@protobase/cli 0.49.2 → 0.50.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/protobase.mjs +3 -2
- package/dist/build/config-bundle.js +1 -1
- package/dist/build/deploy-bundle.js +3 -4
- package/dist/build/plugin-build.js +16 -8
- package/dist/build/plugin-fields.js +5 -2
- package/dist/build/ui-check.js +5 -0
- package/dist/build/view-check.js +1 -1
- package/dist/cli/package.js +1 -1
- package/dist/config/project-files.js +4 -1
- package/dist/config/source-config.js +1 -1
- package/dist/dev/api-process.js +1 -1
- package/dist/dev/app-server.js +43 -35
- package/dist/dev/create-db.js +2 -2
- package/dist/dev/project.js +3 -2
- package/dist/dev/server-package.js +9 -21
- package/dist/doctor/run.js +1 -1
- package/dist/hand-over.d.ts +15 -0
- package/dist/hand-over.js +32 -0
- package/dist/main.js +22 -5
- package/dist/project/bundled-imports.js +41 -0
- package/dist/project/import-project-file.js +28 -8
- package/dist/project/load-data-config.js +4 -3
- package/dist/project/project-types.js +66 -0
- package/dist/run/preload.d.ts +1 -0
- package/dist/run/preload.js +20 -0
- package/dist/run/run-script.js +36 -0
- package/dist/supabase/dump-phase.js +9 -4
- package/dist/supabase/load-phase.js +5 -4
- package/dist/supabase/realtime-policies.js +60 -0
- package/dist/version/project-packages.js +39 -0
- package/dist/version/project-version.js +33 -12
- package/package.json +9 -8
- package/skills/protobase/SKILL.md +1 -1
- package/skills/protobase/references/features/build-and-run.md +3 -0
- package/skills/protobase/references/features/compatibility.md +1 -1
- package/skills/protobase/references/features/releases.md +2 -1
- package/skills/protobase/references/getting-started.md +18 -5
- package/skills/protobase/references/guides/api-functions.md +1 -1
- package/skills/protobase/references/guides/billing-page.md +4 -4
- package/skills/protobase/references/guides/create-page.md +2 -2
- package/skills/protobase/references/guides/deploy.md +24 -8
- package/skills/protobase/references/guides/field-type.md +1 -1
- package/skills/protobase/references/guides/first-plugin.md +1 -1
- package/skills/protobase/references/guides/plugin-build.md +1 -1
- package/skills/protobase/references/guides/remote-resources.md +1 -1
- package/skills/protobase/references/guides/table-to-admin.md +8 -8
- package/skills/protobase/references/reference/ai.md +1 -1
- package/skills/protobase/references/reference/api.md +4 -4
- package/skills/protobase/references/reference/architecture.md +11 -6
- package/skills/protobase/references/reference/assistant.md +1 -1
- package/skills/protobase/references/reference/auth.md +17 -4
- package/skills/protobase/references/reference/blocks.md +1 -1
- package/skills/protobase/references/reference/bottom-bar.md +2 -2
- package/skills/protobase/references/reference/cli.md +51 -22
- package/skills/protobase/references/reference/client.md +3 -1
- package/skills/protobase/references/reference/config/api.md +2 -2
- package/skills/protobase/references/reference/config/app.md +2 -2
- package/skills/protobase/references/reference/config/sign-in.md +2 -3
- package/skills/protobase/references/reference/config.md +11 -9
- package/skills/protobase/references/reference/custom-components.md +3 -2
- package/skills/protobase/references/reference/email.md +4 -4
- package/skills/protobase/references/reference/events.md +1 -1
- package/skills/protobase/references/reference/jobs.md +6 -5
- package/skills/protobase/references/reference/layouts.md +2 -2
- package/skills/protobase/references/reference/mcp.md +9 -8
- package/skills/protobase/references/reference/notifications.md +10 -8
- package/skills/protobase/references/reference/plugins.md +3 -3
- package/skills/protobase/references/reference/supabase-realtime.md +36 -2
- package/skills/protobase/references/reference/ui-config.md +1 -1
- package/skills/protobase/references/reference/user-menu.md +3 -3
- package/skills/protobase/references/reference/versioning.md +21 -4
- package/skills/protobase/references/reference/webhooks.md +5 -5
|
@@ -4,15 +4,18 @@
|
|
|
4
4
|
|
|
5
5
|
Every protobase command, from scaffold, doctor, dev, build, build-plugin, build-serve and serve to users, organizations, token and skill.
|
|
6
6
|
|
|
7
|
-
The `protobase` command comes with `@protobase/cli`. Install it in a project next to the packages its config imports:
|
|
7
|
+
The `protobase` command comes with `@protobase/cli`. Install it globally, or in a project next to the packages its config imports:
|
|
8
8
|
|
|
9
9
|
```sh
|
|
10
|
-
bun add @protobase/cli
|
|
11
|
-
bun
|
|
12
|
-
bun run
|
|
10
|
+
bun add --global @protobase/cli # the protobase command for every bundled project
|
|
11
|
+
bun add --dev @protobase/cli @protobase/config @protobase/schema @protobase/layout @protobase/server @protobase/ui
|
|
12
|
+
bun run protobase <command> # from the project, config folder defaults to ./config
|
|
13
|
+
bun run --cwd tests/apps/erp protobase <command> # in this repository, for an example
|
|
13
14
|
```
|
|
14
15
|
|
|
15
|
-
|
|
16
|
+
Listed in `devDependencies`, as the presets list them, or not at all, the packages make the project bundled: whichever CLI runs supplies them, so a global CLI runs a project with nothing installed. Listed in `dependencies`, they lock it to the installed copies. See [Bundled and locked projects](versioning.md#bundled-and-locked-projects).
|
|
17
|
+
|
|
18
|
+
Any package manager installs it, and the command runs on Node or on Bun: `npm install` and `npx protobase <command>` work the same. The bin starts with `#!/usr/bin/env node`, so where Node is installed `bun run protobase` starts it on Node, unless the project's `bunfig.toml` sets `[run] bun = true`, as the presets' does. `protobase --version` (or `-v`) prints the Protobase version. Before any command runs, the CLI checks that the version specifier the current directory's `package.json` lists the `@protobase` packages at holds its own version, and stops with an error naming both when it does not (see [Versioning](versioning.md#bundles-and-runtimes)). That is the CLI's one version check. Outside a project, or in one that lists no `@protobase` package, there is nothing to check. In a locked project that has its own `@protobase/cli` installed, a CLI installed elsewhere, globally, in CI or in an image, hands the command over to that one before anything else, with a line on stderr naming its version, so the project runs on the version it is locked to.
|
|
16
19
|
|
|
17
20
|
## How it runs
|
|
18
21
|
|
|
@@ -38,7 +41,7 @@ const { exitCode, stdout, stderr } = await runCommand(['doctor', '--env', 'DATAB
|
|
|
38
41
|
|
|
39
42
|
The serve runtime is bundled by `protobase build-serve` into one JavaScript file for Bun, so production needs neither `node_modules` nor the CLI (see [serve](#serve)).
|
|
40
43
|
|
|
41
|
-
|
|
44
|
+
`scaffold` and `doctor` read the database with `default_transaction_read_only = on`, so they can never write, and so does `dev`'s check of the connection. The commands that manage the app's data do write: `users`, `organizations`, `encryption apply`, `files cleanup` and `import supabase`.
|
|
42
45
|
|
|
43
46
|
## `scaffold`
|
|
44
47
|
|
|
@@ -52,6 +55,7 @@ Protobase's own tables are left out, since they hold password hashes, OAuth toke
|
|
|
52
55
|
|
|
53
56
|
| Option | Effect |
|
|
54
57
|
| --- | --- |
|
|
58
|
+
| `--env <variable>` | read the connection string from this variable instead of `DATABASE_URL` |
|
|
55
59
|
| `--config <dir>` | config folder, default `config` |
|
|
56
60
|
| `--yes` | accept every proposal, no prompts (required without a TTY) |
|
|
57
61
|
| `--dry-run` | print a diff, write nothing |
|
|
@@ -125,10 +129,10 @@ protobase dev [--port 5173] [--env DATABASE_URL] [--cache-dir <dir>] [--allowed-
|
|
|
125
129
|
|
|
126
130
|
One port, two processes: Vite serves the admin app from `@protobase/ui`'s `src/app/` (`dist/app/` when installed; `index.html` and `main.tsx`, or `main.js`; the command fails with a clear message when they are missing) and hands `/api`, supabase-js's `/api/sb` included, to the Hono app from `createAdmin`, which runs in a process of its own; the CLI's process never loads `@protobase/server`. Open `http://localhost:<port>`; the API reference is at `/api/docs`.
|
|
127
131
|
|
|
128
|
-
- **Server package:** the API's process loads `@protobase/server` from the project's `node_modules
|
|
132
|
+
- **Server package:** in a locked project, whose `package.json` lists the `@protobase` packages in `dependencies`, the API's process loads `@protobase/server` from the project's `node_modules`; one that is not installed fails as with any missing package. A bundled project, which lists them in `devDependencies`, lists none or has no `package.json`, gets the CLI's own copies of every package the serve runtime supplies, the `@protobase` packages, `kysely`, `pg`, `react` and the rest of [the list](#the-config-module), for its files too, whatever it installed; its page code's imports of the `@protobase` packages, React and React DOM get the admin app's own copies.
|
|
129
133
|
|
|
130
134
|
- **Secret:** a `PROTOBASE_SECRET` still set to the placeholder of `.env.example` (`change-me-...`) prints a warning once the server is ready, as `serve` does at start: anyone who knows it can sign session cookies.
|
|
131
|
-
- **Database:** the URL comes from the variable named by `--env`, read from the environment or the nearest `.env` at or above the project. The connection is checked before anything starts; if it fails, the command names host, port and reason (and, when nothing listens there, points to its `db:up` script when it has one). The
|
|
135
|
+
- **Database:** the URL comes from the variable named by `--env`, read from the environment or the nearest `.env` at or above the project. The connection is checked before anything starts; if it fails, the command names host, port and reason (and, when nothing listens there, points to its `db:up` script when it has one). The API connects with Kysely over the `pg` the config gets: the project's own when it is locked, the CLI's when bundled.
|
|
132
136
|
- **Port:** the app listens on `--port` at both `127.0.0.1` and `::1`, since `localhost` is either one depending on the runtime and the browser. When another process holds the port on either address the command stops before it starts and names that address; stop the other server or pass another `--port`.
|
|
133
137
|
- **Cache:** Vite's dependency cache is `node_modules/.vite`; two dev servers sharing it can disturb each other's optimisation, so pass `--cache-dir` for a second one (the integration test does).
|
|
134
138
|
- **Login:** real sign-in only, with the config's `auth`, on by default, or its `authenticate` for tokens of an auth server elsewhere (see [protobase.config.ts](config.md) and [Login with Better Auth](auth.md)). A project with sign-in off and no authenticator fails at startup with a message pointing there, as does one with sign-in on and no `PROTOBASE_SECRET`, one whose auth store has not applied every migration of this version, naming them (see [`auth migration`](#auth-migration)), one with a resource over a table of the auth store, and one with a resource whose [events](events.md) or [history](history.md) lack their triggers, or whose [comments](comments.md) lack their table, or whose [rollup and formula fields](data-config.md#rollups-and-formulas) lack their columns or triggers, which it checks again on every reload (see [`migration`](#migration)), and one with an [AI field or action](ai.md#the-model) and no model key; there is no development login. The `login` line of the startup message says how to sign in: while the auth store has no users, it prints the exact command that creates the first admin, such as `bun run protobase users create you@example.com --generate-password` (the package manager that started `dev`, `npx` otherwise). Against a database that has users already, such as an app's hosted one, sign in as one of them or add one with a new email; its own password is set there. A `warning` line follows for each way the auth store's tables differ from what the app's sign-in needs, such as a column dropped by hand: the one place Protobase compares them, since `serve` reads the store's record of [migrations](auth.md#migrations) alone.
|
|
@@ -210,7 +214,7 @@ By default the bundle runs on Node and on Bun. `--bun` makes it a bundle for Bun
|
|
|
210
214
|
}
|
|
211
215
|
```
|
|
212
216
|
|
|
213
|
-
- `protobase` is the Protobase version the
|
|
217
|
+
- `protobase` is the Protobase version of the copies the build used: the building CLI's own in a bundled project, and in a locked one the `@protobase` packages its lockfile installed, whichever CLI built the bundle. A host serves the bundle on the runtime of that version (see [Versioning](versioning.md#bundles-and-runtimes)). A bundled project needs nothing installed; a locked one fails without its `@protobase` packages installed.
|
|
214
218
|
- `server`, `public`, `nodeModules` and `migrations` are relative to the bundle folder; `spa`, `theme` and each plugin's `path` to `public`.
|
|
215
219
|
- `plugins` are the bundle's own plugins, in the order the app merges them: the extensions', then the project's (`app`). Each names its `plugin.json`, the plugin API and Protobase versions it is built for, and the [field types](plugins.md#field-types) it registers with the storage types each shows, which the serve runtime checks the views against at startup. `/api/meta` names them to everyone, before any other plugin.
|
|
216
220
|
- `shell` is the admin app `public/` holds a copy of: its Protobase version and plugin API, and its files as URL paths. A host with a shell of its own may serve its own for those paths instead (see [The UI](#the-ui)), so the app gets that release's fixes without a rebuild.
|
|
@@ -228,7 +232,7 @@ By default the bundle runs on Node and on Bun. `--bun` makes it a bundle for Bun
|
|
|
228
232
|
`public/` holds two parts that are built apart.
|
|
229
233
|
|
|
230
234
|
- **The shell**, `index.html`, `assets/` and `protobase.sw.js`: the admin app, a production build of `@protobase/ui`'s `src/app` with no project code in it, the same for every project on a release. `@protobase/ui`'s package ships it prebuilt in `dist/shell/` and the [protobase image](../guides/deploy.md#images) at `/opt/protobase/shell/`; the build copies it. It calls the API on its own origin under `/api`, so the same bundle works under any hostname, and reads everything else at runtime: the resources, views, pages and roles from `/api/meta`, sign-in from `/api/auth`, the project's UI from its plugins and its look from `/protobase.theme.css`, which it links after its own stylesheets, its tab icon from `/protobase.favicon.svg`, and its [web app manifest](installable-app.md) from `/api/manifest.webmanifest`.
|
|
231
|
-
- **The plugins**, `plugins/<name>/`: the project's `protobase.ui.tsx` as the plugin `app`, and each [extension](#extensions)'s, each built as [`build-plugin`](#build-plugin) builds one, against the `@protobase/ui` installed in
|
|
235
|
+
- **The plugins**, `plugins/<name>/`: the project's `protobase.ui.tsx` as the plugin `app`, and each [extension](#extensions)'s, each built as [`build-plugin`](#build-plugin) builds one, against the CLI's own `@protobase/ui` in a bundled project and the one installed in a locked project. `/api/meta` names them, and the shell loads them as it loads any [plugin](plugins.md). A component or field type the config declares but no `protobase.ui.tsx` exports fails the build (see [Components](custom-components.md#components)).
|
|
232
236
|
|
|
233
237
|
The modules the app shares with plugins, `react`, `react/jsx-runtime`, `react-dom` and `@protobase/ui`, are entries of their own, `/assets/shared-<name>-<hash>.js`, each exporting every name of its module. `index.html` maps the four names to them with an import map, ahead of every script, so a plugin's imports of them run on the app's copies.
|
|
234
238
|
|
|
@@ -298,6 +302,24 @@ docker run --rm -p 127.0.0.1:8787:8787 -e DATABASE_URL -e PROTOBASE_URL -e PROTO
|
|
|
298
302
|
protobase-run --no-install /opt/protobase/protobase-serve.js /app/protobase.config.js
|
|
299
303
|
```
|
|
300
304
|
|
|
305
|
+
## `types`
|
|
306
|
+
|
|
307
|
+
```sh
|
|
308
|
+
protobase types # writes .protobase/tsconfig.json; dev and build write it too
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
Writes `.protobase/tsconfig.json`, which the project's `tsconfig.json` extends (`"extends": "./.protobase/tsconfig.json"`). In a bundled project its `paths` point each `@protobase` package and each package the serve runtime supplies, by name and by each of its exports (`@protobase/layout/jsx-runtime`, `kysely`, `zod`, ...), at the declarations of the CLI that builds the app, so the editor and `tsc` see the version that runs with nothing installed. There is no catch-all, so a package the project imports and lacks still fails as missing. React carries no types of its own, so the project keeps `@types/react`, as it keeps `@types/node`. A locked project's installed packages type themselves, so its file holds no `paths`. A `paths` of the project's own `tsconfig.json` replaces the generated one, as `extends` does with any option.
|
|
312
|
+
|
|
313
|
+
`.protobase/` ignores itself in git: the paths are this machine's. Write the file again after installing another CLI; `dev` and `build` do it on every run.
|
|
314
|
+
|
|
315
|
+
## `run`
|
|
316
|
+
|
|
317
|
+
```sh
|
|
318
|
+
protobase run <file> [args...] # e.g. "db:seed": "protobase run seed/cli.ts"
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
Runs one of the project's scripts, such as a seed or a migration, under Bun in a process of its own, in the current directory, with the arguments after the file, options included, passed to the script and its exit code passed back. In a bundled project the script's imports of the `@protobase` packages and of every package the serve runtime supplies (`kysely`, `pg`, `postgres`, `zod`, ...) get the CLI's own copies, as a bundle gets the runtime's, with nothing installed: a preload registers them as Bun's virtual modules. A locked project's script imports its installed packages. Bun never installs a missing package for it (`--no-install`), so a script that imports a package the project lacks fails as missing. It needs `bun` on `PATH`.
|
|
322
|
+
|
|
301
323
|
## `build-plugin`
|
|
302
324
|
|
|
303
325
|
```sh
|
|
@@ -316,7 +338,7 @@ dist/
|
|
|
316
338
|
- The output folder is emptied first, so it must not be the plugin's folder or hold it.
|
|
317
339
|
- The module is `protobase.ui.tsx` with everything it imports bundled, except the four modules the app shares (`react`, `react/jsx-runtime`, `react-dom`, `@protobase/ui`), which stay imports by those names. Any other module of those packages, such as `react-dom/client`, fails the build. React's production build and JSX runtime are used, whatever `NODE_ENV` says, and every export of `protobase.ui.tsx` is kept.
|
|
318
340
|
- The stylesheet is Tailwind's utilities for the classes in the plugin's folder: no reset, no theme values. Each utility reads the theme of the app that loads it, with Tailwind's default as the fallback (`text-sm` is `font-size: var(--text-sm, 0.875rem)`).
|
|
319
|
-
- `plugin.json` names the plugin (`--name`, else its `package.json`'s `name`, else its folder's), its own `version`, the plugin API (`api`) and the Protobase versions (`protobase`) it is built for, the module (`entry`) and stylesheet (`css`), relative to it, and the [field types](plugins.md#field-types) it registers (`fields`), each with the storage types it shows. Both versions come from the `@protobase/ui` installed for the plugin,
|
|
341
|
+
- `plugin.json` names the plugin (`--name`, else its `package.json`'s `name`, else its folder's), its own `version`, the plugin API (`api`) and the Protobase versions (`protobase`) it is built for, the module (`entry`) and stylesheet (`css`), relative to it, and the [field types](plugins.md#field-types) it registers (`fields`), each with the storage types it shows. Both versions come from the `@protobase/ui` installed for the plugin, else for the project it extends, else the CLI's own: `api` is its plugin API, and `protobase` is `>=` its version unless the plugin's `package.json` names a range in `engines.protobase` (see [Plugins](plugins.md#versions)).
|
|
320
342
|
- `--source-maps` ends each script with a `//# debugId=<uuid>` comment, naming no map, and writes its source map, `<script>.js.map` carrying the same `debugId`, beside it, for an error tracker to read the browser's stack frames with.
|
|
321
343
|
|
|
322
344
|
To read its field types, the build loads the plugin's module once in Node, with everything bundled; nothing is rendered, but code at the top level of its modules runs, so keep browser-only work (`window`, `document`) inside components and handlers. The app loads it from wherever `plugin.json` is served, listed in `PROTOBASE_PLUGINS` or the config's `plugins` (see [loading](plugins.md#loading)).
|
|
@@ -332,10 +354,10 @@ Bundles the serve runtime (`@protobase/cli`'s `src/serve/main.ts`) and all its d
|
|
|
332
354
|
```sh
|
|
333
355
|
bun --no-install protobase-serve.js [serve] <bundle> # the folder: the app and the API; the config module: the API
|
|
334
356
|
bun --no-install protobase-serve.js migrate <bundle> # apply the bundle's migrations to DATABASE_URL
|
|
335
|
-
bun --no-install protobase-serve.js create-admin <bundle> <email> # --generate-password
|
|
357
|
+
bun --no-install protobase-serve.js create-admin <bundle> <email> # [--name <name>] [--generate-password | --password-stdin]
|
|
336
358
|
```
|
|
337
359
|
|
|
338
|
-
`migrate` runs none of the app's code and needs only `DATABASE_URL`; `create-admin` loads the app with its settings and refuses an auth schema that is behind. Given the folder, the runtime serves the bundle's own copy of the app. [Deploy](../guides/deploy.md#a-self-hosted-image) puts the three in a self-hosted image.
|
|
360
|
+
`migrate` runs none of the app's code and needs only `DATABASE_URL`; `create-admin` loads the app with its settings and refuses an auth schema that is behind; without `--generate-password` or `--password-stdin` it asks for the password at a hidden prompt. Given the folder, the runtime serves the bundle's own copy of the app. [Deploy](../guides/deploy.md#a-self-hosted-image) puts the three in a self-hosted image.
|
|
339
361
|
|
|
340
362
|
## `serve`
|
|
341
363
|
|
|
@@ -362,7 +384,14 @@ Serves the API of a bundle from `protobase build` and owns the process around it
|
|
|
362
384
|
| `PROTOBASE_OPERATOR_ISSUER`, `PROTOBASE_OPERATOR_CLIENT_ID`, `PROTOBASE_OPERATOR_CLIENT_SECRET` | the OpenID Connect provider of the operator's staff, for [staff sign-in](auth.md#staff-sign-in) as people of the app; all three or none. `PROTOBASE_OPERATOR_NAME` and `PROTOBASE_OPERATOR_GROUP` are optional ([Operator provider](auth.md#operator-provider)) |
|
|
363
385
|
| `PROTOBASE_ORIGINS`, `PROTOBASE_PASSKEY_DOMAIN` | the other origins the app is served on, comma separated, and the host new passkeys are made for ([Several origins](auth.md#several-origins)) |
|
|
364
386
|
| `PROTOBASE_CORS_ORIGINS` | other websites whose browser code may call the API, `*` or comma separated http and https origins ([CORS](api.md#cors)) |
|
|
387
|
+
| `PROTOBASE_PREVIOUS_SECRETS` | the app's secrets before `PROTOBASE_SECRET`, newest first, comma separated, which still decrypt what they encrypted, unless the config sets [`previousSecrets`](config/app.md#previoussecrets) |
|
|
388
|
+
| `PROTOBASE_TRUSTED_ORIGINS` | extra origins that may call the auth endpoints, comma separated, unless the config sets [`auth.trustedOrigins`](config/sign-in.md#authtrustedorigins) |
|
|
389
|
+
| `PROTOBASE_PUBLISHABLE_KEY`, `PROTOBASE_SECRET_KEY` | the app's [API keys](config/api.md#apikeys), unless the config sets `apiKeys` |
|
|
390
|
+
| `PROTOBASE_PLUGINS`, `PROTOBASE_PLUGINS_BEFORE_SIGN_IN` | [plugins](plugins.md#loading) a hosting platform adds to the app, their `plugin.json` URLs comma separated; the second also load before sign-in |
|
|
391
|
+
| `PROTOBASE_FORMS_SECRET` | the secret [public forms](forms.md#bot-check) sign their bot checks with, over the app's secret |
|
|
392
|
+
| `PROTOBASE_VAPID_PUBLIC_KEY`, `PROTOBASE_VAPID_PRIVATE_KEY`, `PROTOBASE_VAPID_SUBJECT` | the key pair and contact of [Web Push](notifications.md#web-push), from [`notifications vapid-keys`](#notifications-vapid-keys) |
|
|
365
393
|
| `PROTOBASE_ASSISTANT_URL`, `PROTOBASE_ASSISTANT_API_KEY`, `PROTOBASE_ASSISTANT_MODEL`, `PROTOBASE_ASSISTANT_BASE_URL` | the [assistant](assistant.md#which-backend): a backend elsewhere, or the built-in one on OpenRouter or another OpenAI-compatible endpoint; without them there is none |
|
|
394
|
+
| `PROTOBASE_ASSISTANT_CHATS` | the folder the built-in assistant keeps its conversations in; default `.protobase/chats` |
|
|
366
395
|
| `PROTOBASE_RUNTIME_URL` | the endpoint behind the top bar's [runtime update button](versioning.md#runtime-updates), such as a hosting platform's; without it there is no button |
|
|
367
396
|
| `PROTOBASE_SENTRY_DSN` | the DSN of a Sentry-compatible error tracker the app's server and admin app send their errors to, after the config's `errorReporting` ([Error reporting](api.md#error-reporting)); without it nothing is sent |
|
|
368
397
|
| `PROTOBASE_MAP_STYLE_URL` | the URL of the MapLibre style the record page's [maps](ui-config.md#maps) are drawn with, after the config's `maps`; without it there are no maps |
|
|
@@ -401,7 +430,7 @@ With a `mobile` section, the server serves the [mobile app](../guides/mobile-app
|
|
|
401
430
|
protobase worker <bundle> # a bundle from `protobase build`: its folder or its protobase.config.js
|
|
402
431
|
```
|
|
403
432
|
|
|
404
|
-
Runs the bundle's [jobs](jobs.md), and the delivery of its [events](webhooks.md#delivery-and-retries), and nothing else, until SIGTERM or SIGINT, which let running jobs finish for 30 seconds as `serve` does. It checks the bundle's version and the jobs schema at start like `serve`, reads the `.env` nearest the current directory and needs `DATABASE_URL`. Run it beside a `serve` with `PROTOBASE_JOBS=false`, from the same bundle. `protobase worker running <n> jobs` means it is ready.
|
|
433
|
+
Runs the bundle's [jobs](jobs.md), and the delivery of its [events](webhooks.md#delivery-and-retries), and nothing else, until SIGTERM or SIGINT, which let running jobs finish for 30 seconds as `serve` does. It checks the bundle's version and the jobs schema at start like `serve`, reads the `.env` nearest the current directory and needs `DATABASE_URL`. Run it beside a `serve` with `PROTOBASE_JOBS=false`, from the same bundle. It refuses a bundle with nothing to run: no jobs, and no resource with events, history, comments or an AI field, whose jobs are Protobase's own. Like `serve`, it reports a crash to the app's [error tracker](api.md#error-reporting). `protobase worker running <n> jobs` means it is ready.
|
|
405
434
|
|
|
406
435
|
## `files cleanup`
|
|
407
436
|
|
|
@@ -433,7 +462,7 @@ Encrypts every plaintext value of the encrypted fields with the current key, enc
|
|
|
433
462
|
|
|
434
463
|
`--rebind <resource>[.<field>]` with `--from-table <table>` (as `.table()` wrote it) or `--from-column <column>` also takes values sealed where the field was before a rename, and seals them where it is now; running it again rebinds nothing more. It refuses a former place another resource still encrypts.
|
|
435
464
|
|
|
436
|
-
Run it at update time, after the migrations and before the new version serves, and again once an old version that wrote plaintext has stopped. It works over one database connection
|
|
465
|
+
Run it at update time, after the migrations and before the new version serves, and again once an old version that wrote plaintext has stopped. It works over one database connection.
|
|
437
466
|
|
|
438
467
|
## `notifications vapid-keys`
|
|
439
468
|
|
|
@@ -447,7 +476,7 @@ Prints a fresh key pair for [Web Push](notifications.md#web-push) as `PROTOBASE_
|
|
|
447
476
|
|
|
448
477
|
```sh
|
|
449
478
|
protobase users create <email> [--name <name>] [--role <role>] [--password-stdin | --generate-password | --no-password] [--github-id <id>]
|
|
450
|
-
[--organization <
|
|
479
|
+
[--organization <organization> [--org-role <role>] [--app-roles <a,b>]]
|
|
451
480
|
protobase users list
|
|
452
481
|
protobase users roles
|
|
453
482
|
protobase users set-role <email> <role>
|
|
@@ -455,13 +484,13 @@ protobase users disable <email> # and: enable <email>
|
|
|
455
484
|
protobase users delete <email> [--yes]
|
|
456
485
|
```
|
|
457
486
|
|
|
458
|
-
Run inside a project with sign-in on (its config's `auth`, on unless `false`). There is no web setup page, and [open sign-up](auth.md#open-sign-up), when a project turns it on, waits for the first admin: the first admin is created here. The first user is always an admin, whatever `--role` says; later users get `--role`, or the project's default role (`auth: { roles, defaultRole }` in its config). `protobase users roles` lists the roles of the project; anything else is refused with that list. `set-role` also takes comma separated roles (`sales,accountant`). `--github-id` links the new user to a GitHub user id (the number, not the login), so signing in with GitHub, the app's own provider or the [platform's](auth.md#platform-sign-in-provider), finds them whatever address GitHub reports; an id that signs in another user already is refused. `createUser(auth, { ..., accounts: [{ providerId, accountId }] })` does the same from code.
|
|
487
|
+
Run inside a project with sign-in on (its config's `auth`, on unless `false`, or unless the config leaves `auth` out and sets `authenticate.jwksUrl`). Like `organizations`, `token` and `auth migration`, it reads the `.env` nearest the project and needs `DATABASE_URL`. There is no web setup page, and [open sign-up](auth.md#open-sign-up), when a project turns it on, waits for the first admin: the first admin is created here. The first user is always an admin, whatever `--role` says; later users get `--role`, or the project's default role (`auth: { roles, defaultRole }` in its config). `protobase users roles` lists the roles of the project; anything else is refused with that list. `set-role` also takes comma separated roles (`sales,accountant`). `--github-id` links the new user to a GitHub user id (the number, not the login), so signing in with GitHub, the app's own provider or the [platform's](auth.md#platform-sign-in-provider), finds them whatever address GitHub reports; an id that signs in another user already is refused. `createUser(auth, { ..., accounts: [{ providerId, accountId }] })` does the same from code.
|
|
459
488
|
|
|
460
489
|
The password is typed at a hidden prompt with confirmation, read from stdin with `--password-stdin` (for scripts, e.g. `pass show erp | protobase users create me@example.com --password-stdin`), or generated with `--generate-password` and printed once; it must be 12 to 128 characters, the length the app requires of every new password. `--no-password` makes an account without one, which signs in by [emailed code](auth.md#emailed-sign-in-codes), passkey or a sign-in provider, as with an app whose [sign-in policy](auth.md#sign-in-policy) turns passwords off. A password is never accepted as an argument, since it would end up in shell history. `users list` prints email, role and creation date (and `disabled` for banned users), never credentials.
|
|
461
490
|
|
|
462
491
|
`delete` asks you to type the email back (or pass `--yes`), and needs a terminal otherwise. `delete`, `set-role` and `disable` refuse to touch the last admin, so the project cannot lock itself out. `disable` bans the user and revokes their sessions; tokens already issued stop working on their next request, and `protobase token` refuses disabled users. With [MCP](auth.md#oauth-for-mcp-clients) on, it also disconnects their MCP clients. `enable` lifts the ban; the clients have to be allowed again. `protobase dev` prints the command that creates the first admin at startup while the user table is empty (see [`dev`](#dev)).
|
|
463
492
|
|
|
464
|
-
With [organizations](auth.md#organizations), `--role` is the user's global role (none by default) and `--organization` adds the new user to an organization, with `--org-role` (`owner`, `admin`, or `member`, the default) and `--app-roles` there.
|
|
493
|
+
With [organizations](auth.md#organizations), `--role` is the user's global role (none by default) and `--organization` adds the new user to an organization, by its slug or id, with `--org-role` (`owner`, `admin`, or `member`, the default) and `--app-roles` there.
|
|
465
494
|
|
|
466
495
|
## `organizations`
|
|
467
496
|
|
|
@@ -507,7 +536,7 @@ protobase import supabase [<connection> | --source-env <variable>] [--env DATABA
|
|
|
507
536
|
|
|
508
537
|
Turns a Supabase project's database into the project in the current directory, in two runs with the project's migrations between them. It needs PostgreSQL's `pg_dump` and `psql` on `PATH`, of the Supabase database's major version or newer, and reads the `.env` nearest the current directory for the project's database (`--env`).
|
|
509
538
|
|
|
510
|
-
1. **The first run** takes the Supabase database's connection string, for its `postgres` role (the session pooler's or the direct one; the transaction pooler cannot hold the snapshot the dumps share). It fails unless the database has Supabase's `auth` and `storage` schemas and its `supabase_admin` role, and while `auth.users` has single sign-on (SAML) users, which Supabase opens only through their identity provider and Better Auth would find by email: merge or delete them in Supabase first. It notes the Supabase CLI's `supabase/config.toml`, `supabase/migrations/` and `supabase/functions/` when the checkout has them. It converts `supabase/functions` into the project's `functions/` (see [functions moved from Supabase](../guides/api-functions.md#functions-moved-from-supabase)): `Deno.serve(handler)` and std's `serve(handler)` become `export default defineFunction({ supabase: true }, { fetch: handler })`, an existing default export is wrapped the same way, so each function also answers at `/api/sb/functions/v1/<name>`, `npm:`, `jsr:` and esm.sh imports become bare imports of packages it adds to `package.json`, `Deno.env.get(name)` becomes `process.env[name]`, `EdgeRuntime.waitUntil` becomes `waitUntil` of `@protobase/server`, a function with `verify_jwt = false` in `config.toml` becomes public (`{ public: true, supabase: true }`), and `_shared` and the like are converted beside them. It stops before anything else when `functions/` already has one of their names. It dumps `auth`, `storage` and every schema the app made, schema and data apart, as of one snapshot, leaving out the platform's own migration tables, and writes the schemas as the project's next migration, `NNN_supabase_schema.sql`. It asks the project's database which of the app's extensions its role may create, by trying each in a transaction it rolls back: Postgres alone allows the trusted ones, Supabase's Postgres image all it allowlists, such as pg_net, pgmq and Vault. The migration creates those first, then, where pg_net is among them and the app has Database Webhooks, the `supabase_functions.http_request` function their triggers call, over pg_net; then the dump without what fails there, as comments: grants and default privileges for `dashboard_user`, `supabase_*`, `authenticator` and `postgres`, statements about the `public` schema, Realtime's publication, pgsodium's security labels, the views that decrypt with it and the triggers that encrypt with it, database webhooks without pg_net, functions in plv8, plls or plcoffee where the database has no such language, and a timescaledb hypertable's insert-blocking trigger. It then writes `NNN_supabase_users.sql`, the nullable columns Better Auth needs on `auth.users` (`name`, `email_verified`, `image`, `app_role`, `banned`, `ban_reason`, `ban_expires`) and GoTrue's `'authenticated'` as the default of `role` and `aud`. It points the app at `auth.users`: the `auth` of `protobase.config.ts` gets `users: { table: 'users', columns: { role: 'app_role' }, metadata: 'raw_user_meta_data' }`, `passwordHashes: ['bcrypt']` and `generateUserId: 'uuid'`, or the config gets an `auth` of them when it has none (see [an existing users table](auth.md#an-existing-users-table)). It removes the migrations `protobase auth migration` or `protobase migration` wrote for Protobase's own user table, since `auth.users` replaces it, and stops before writing anything when the project has no `protobase.config.ts`, or one whose `auth` is not an object it can see, or when the project's database has a schema the dump creates already, such as the `auth` schema those migrations made. The project's database needs the roles `anon`, `authenticated` and `service_role` that the dump's grants and policies name; the command makes them when its role may, and otherwise stops, naming them. The data dump goes to `supabase-import/`, which it adds to `.gitignore`, since it holds every row and the users' password hashes. Where the project's database can create Vault, pgmq and pg_cron, `supabase-import/replay.sql` holds what a dump cannot carry: Vault's secrets with their values, read decrypted since only Supabase's key opens their ciphertext, pgmq's queues with their messages, since pgmq owns their tables, and pg_cron's jobs, which live in its own schema.
|
|
539
|
+
1. **The first run** takes the Supabase database's connection string, for its `postgres` role (the session pooler's or the direct one; the transaction pooler cannot hold the snapshot the dumps share). It fails unless the database has Supabase's `auth` and `storage` schemas and its `supabase_admin` role, and while `auth.users` has single sign-on (SAML) users, which Supabase opens only through their identity provider and Better Auth would find by email: merge or delete them in Supabase first. It notes the Supabase CLI's `supabase/config.toml`, `supabase/migrations/` and `supabase/functions/` when the checkout has them. It converts `supabase/functions` into the project's `functions/` (see [functions moved from Supabase](../guides/api-functions.md#functions-moved-from-supabase)): `Deno.serve(handler)` and std's `serve(handler)` become `export default defineFunction({ supabase: true }, { fetch: handler })`, an existing default export is wrapped the same way, so each function also answers at `/api/sb/functions/v1/<name>`, `npm:`, `jsr:` and esm.sh imports become bare imports of packages it adds to `package.json`, `Deno.env.get(name)` becomes `process.env[name]`, `EdgeRuntime.waitUntil` becomes `waitUntil` of `@protobase/server`, a function with `verify_jwt = false` in `config.toml` becomes public (`{ public: true, supabase: true }`), and `_shared` and the like are converted beside them. It stops before anything else when `functions/` already has one of their names. It dumps `auth`, `storage` and every schema the app made, schema and data apart, as of one snapshot, leaving out the platform's own migration tables, and writes the schemas as the project's next migration, `NNN_supabase_schema.sql`. It asks the project's database which of the app's extensions its role may create, by trying each in a transaction it rolls back: Postgres alone allows the trusted ones, Supabase's Postgres image all it allowlists, such as pg_net, pgmq and Vault. The migration creates those first, then, where pg_net is among them and the app has Database Webhooks, the `supabase_functions.http_request` function their triggers call, over pg_net; then the dump without what fails there, as comments: grants and default privileges for `dashboard_user`, `supabase_*`, `authenticator` and `postgres`, statements about the `public` schema, Realtime's publication, pgsodium's security labels, the views that decrypt with it and the triggers that encrypt with it, database webhooks without pg_net, functions in plv8, plls or plcoffee where the database has no such language, and a timescaledb hypertable's insert-blocking trigger. It then writes `NNN_supabase_users.sql`, the nullable columns Better Auth needs on `auth.users` (`name`, `email_verified`, `image`, `app_role`, `banned`, `ban_reason`, `ban_expires`) and GoTrue's `'authenticated'` as the default of `role` and `aud`. When the source has row security policies on `realtime.messages`, it writes `NNN_supabase_realtime.sql`, which makes `realtime.messages` and `realtime.topic()` with those policies, so the app's [private channels](supabase-realtime.md#private-channels) keep their access; a policy that names only Supabase's own roles is left out as a comment. It points the app at `auth.users`: the `auth` of `protobase.config.ts` gets `users: { table: 'users', columns: { role: 'app_role' }, metadata: 'raw_user_meta_data' }`, `passwordHashes: ['bcrypt']` and `generateUserId: 'uuid'`, or the config gets an `auth` of them when it has none (see [an existing users table](auth.md#an-existing-users-table)). It removes the migrations `protobase auth migration` or `protobase migration` wrote for Protobase's own user table, since `auth.users` replaces it, and stops before writing anything when the project has no `protobase.config.ts`, or one whose `auth` is not an object it can see, or when the project's database has a schema the dump creates already, such as the `auth` schema those migrations made. The project's database needs the roles `anon`, `authenticated` and `service_role` that the dump's grants and policies name; the command makes them when its role may, and otherwise stops, naming them. The data dump goes to `supabase-import/`, which it adds to `.gitignore`, since it holds every row and the users' password hashes. Where the project's database can create Vault, pgmq and pg_cron, `supabase-import/replay.sql` holds what a dump cannot carry: Vault's secrets with their values, read decrypted since only Supabase's key opens their ciphertext, pgmq's queues with their messages, since pgmq owns their tables, and pg_cron's jobs, which live in its own schema.
|
|
511
540
|
2. **Apply the migration** with the project's other migrations, such as `bun run db:migrate`.
|
|
512
541
|
3. **The second run**, without a connection string, loads the data in one transaction, with the app's triggers off so a sign-up trigger on `auth.users` does not run again for users who already have their rows, and fails the transaction unless every table holds the source's number of rows. In the same transaction it makes Vault's secrets and pgmq's queues again through `vault.create_secret`, `pgmq.create` and `pgmq.send`, each message with its headers and the time it becomes visible. Where the project's database has pg_cron, as Supabase's Postgres image does when it serves that database, it schedules pg_cron's jobs again there with `cron.schedule`, run by the importing role, an inactive one inactive. Elsewhere it writes each job of plain SQL as a [recurring job](jobs.md#recurring-jobs) of its own in `jobs/`, of the same name, schedule and `cron.timezone`, that runs its SQL as the app's database role, tried once each time as pg_cron did, and declares it in the `jobs` of `protobase.config.ts` (or writes one); they run once [`migration`](#migration) has added the jobs schema. Recurring jobs wake an app that sleeps, so they run where a host stops an idle app too. A job that calls what the database lacks, such as pg_net's `net.http_*`, `cron` or Vault, an inactive one and a schedule recurring jobs do not take, such as `30 seconds` or `$`, stay in the report, as does a job of another database. It loads only into empty tables, deletes the data dump and the replay, runs [`scaffold`](#scaffold) on the imported tables of the app's schemas (not `auth` or `storage`), giving the tables of the `supabase_realtime` publication [`.live()`](live.md) so [`/api/sb/realtime/v1`](supabase-realtime.md) keeps sending their `postgres_changes` once [`migration`](#migration) has written their capture triggers, writes Better Auth's other tables next to `auth.users` as [`auth migration`](#auth-migration) does (`NNN_auth.sql`), then `NNN_supabase_accounts.sql`, and writes `supabase-import/report.md`: the rows loaded, the imported tables' size against the Starter plan's 500 MB, each sign-in provider's identities, what it made again, the tables it made live, and what needs a person: the pg_cron jobs it could not carry over, each with why, Realtime tables it made no resource of, Vault secrets by name and pgmq queues where the database has no such extension (and partitioned queues), the columns pgsodium encrypts, still holding Supabase's ciphertext, whose values to export decrypted in Supabase before declaring them [`.encrypted()`](data-config.md#encrypted-fields) and running [`encryption apply`](#encryption-apply), the extensions it cannot create, hypertables and plv8, plls or plcoffee functions to convert, triggers that call out over HTTP without pg_net, the converted Edge Functions with the packages to install and the code the conversion left (`deno.land/x` imports, Deno's file, KV and WebSocket APIs, `Supabase.ai`), and the indexes [`doctor`](#doctor) finds missing. `NNN_supabase_accounts.sql` fills the user columns from what Supabase Auth recorded and leaves them empty where it recorded nothing: the name from `raw_user_meta_data`'s `full_name` or `name`, the picture from its `avatar_url` or `picture`, `email_verified` from `email_confirmed_at`, and a ban from `banned_until`, which Better Auth lifts once it has passed. It gives each password of a confirmed address, as Supabase hashed it, a `credential` account (a user who never confirmed theirs signs in by code or resets the password, since GoTrue refused their password sign-in too), and each identity of a social provider an account under Better Auth's name for it (`azure` is `microsoft`, keyed on the `oid` claim; `linkedin_oidc` is `linkedin`, `slack_oidc` is `slack`, `x` is `twitter`), unless its user has an address they never confirmed, since GoTrue refused that sign-in too. Email, phone, anonymous and single sign-on identities and sessions do not carry over. <gap>The import cannot carry over MFA factors because that is not implemented.</gap> <gap>The import cannot carry over passkeys because that is not implemented.</gap>
|
|
513
542
|
4. **Apply the migrations** again. Supabase's users then sign in with their own passwords, and with a social provider once it is in the `socialProviders` of the config's `auth`; new users get a UUID in `auth.users`, so the app's triggers there run for them.
|
|
@@ -527,7 +556,7 @@ protobase mobile build <ios|android> --app-version <x.y.z> --build-number <n> [-
|
|
|
527
556
|
[--team <id> [--certificate <name> --profile <name>]]
|
|
528
557
|
```
|
|
529
558
|
|
|
530
|
-
Builds the project in the current directory as an iOS or Android app with Capacitor, from the `mobile` section of its `protobase.config.ts`; without one it stops and says what to add. See [A mobile app](../guides/mobile-app.md).
|
|
559
|
+
Builds the project in the current directory as an iOS or Android app with Capacitor, from the `mobile` section of its `protobase.config.ts`; without one it stops and says what to add. `--extend <dir>` (repeatable) merges an [extension](config.md#extensions)'s `protobase.config.ts` and `protobase.ui.tsx` before the project's, as `build` does. See [A mobile app](../guides/mobile-app.md).
|
|
531
560
|
|
|
532
561
|
- It installs `@protobase/mobile`, of the CLI's version, which pins Capacitor and its plugins, with the section's `plugins` into `.protobase/mobile/` with npm, when that changed, and on every run for a package from a local folder, given as `file:` or a path such as `../my-plugin`, which npm copies. When such a folder's dependencies are not the versions installed, it removes the workspace's `node_modules` and `package-lock.json` so npm resolves them again, and stops when a pin is still not met, as when two packages pin one dependency at different versions. It builds the app's files as [`build`](#build) does and keeps only `public/`, its `index.html` naming the API origin; writes `capacitor.config.json`, compiling in only the section's plugins; and generates the platform's native project again, replacing the last one.
|
|
533
562
|
- `--api` is the server the app calls, the app's `url` by default: an http or https origin, plain http only to `localhost`, `127.0.0.1` and, on iOS, `[::1]`, or on Android `10.0.2.2`. An Android app calling `localhost` gets the port forwarded.
|
|
@@ -563,10 +592,10 @@ Copies the agent skills of this CLI's version into the current project, or only
|
|
|
563
592
|
```sh
|
|
564
593
|
bun run db:up && bun run --cwd tests/apps/erp db:migrate && bun run --cwd tests/apps/erp db:seed --scale small
|
|
565
594
|
bun run --cwd tests/apps/erp protobase scaffold postgres://protobase:protobase@localhost:55432/protobase \
|
|
566
|
-
--yes --ui --exclude
|
|
595
|
+
--yes --ui --exclude public.schema_migrations --exclude public.seed_info
|
|
567
596
|
bun run --cwd tests/apps/erp protobase doctor postgres://protobase:protobase@localhost:55432/protobase
|
|
568
597
|
```
|
|
569
598
|
|
|
570
|
-
|
|
599
|
+
The ERP keeps Better Auth's users, sessions and signing keys in the `auth` schema of the same database; scaffold leaves that store out on its own, so they are never exposed through the admin API. `--exclude` leaves out the migrations' and the seed's own bookkeeping tables.
|
|
571
600
|
|
|
572
601
|
The integration test (`packages/cli/tests/scaffold/scaffold.integration.test.ts`) scaffolds into a temp folder and is skipped when the database is unreachable.
|
|
@@ -17,10 +17,12 @@ const { record, etag } = await api.get(orders, id)
|
|
|
17
17
|
await api.update(orders, id, { status: 'shipped' }, etag) // 412 rejects with PreconditionFailedError
|
|
18
18
|
```
|
|
19
19
|
|
|
20
|
-
Pass a resource builder to get its record type ([`InferRecord`](https://docs.protobase.net/api/schema/type-aliases/inferrecord/)), or a name for loose records. Filters are AIP-160 text or [`where`](https://docs.protobase.net/api/schema/variables/where/) results (printed with [`printFilter`](https://docs.protobase.net/api/schema/functions/printfilter/)). Errors are `ApiError` (`status`, `slug`, `errors`, `filterErrors` with spans, `blockedBy` for a delete other records point at). Also: `search`, `create`, `remove`, `facets`, `series`, `histogram`, `map(resource, { latitude, longitude, zoom, filter?, orderBy?, fields? })` (the records in a map's view, or buckets of them, see [`:map`](api.md#maps)), `seek`, `reveal(resource, key, field)` (a [sensitive field](data-config.md#sensitive-fields)'s value), `generate(resource, key, action)` (runs an [AI action](ai.md#ai-actions) and resolves to the record as written), `meta(etag?, { signal? })`, `invoke(name, { body?, method?, path?, query? })` (one of the app's [API functions](../guides/api-functions.md#calling-a-function)), `upload(resource, field, file, { onProgress?, signal? })` (a file for a [file field](files.md#uploading); its `value` goes in the next write, and `onProgress` uses XMLHttpRequest, since fetch reports no upload progress), `live({ onChanges, onResync, onRetry? })` (hears which records of the [live](live.md) resources change until the function it returns is called, connecting again by itself).
|
|
20
|
+
Pass a resource builder to get its record type ([`InferRecord`](https://docs.protobase.net/api/schema/type-aliases/inferrecord/)), or a name for loose records. Filters are AIP-160 text or [`where`](https://docs.protobase.net/api/schema/variables/where/) results (printed with [`printFilter`](https://docs.protobase.net/api/schema/functions/printfilter/)). Errors are `ApiError` (`status`, `slug`, `errors`, `filterErrors` with spans, `blockedBy` for a delete other records point at), which `isApiError(error)` tells apart. Also: `search`, `create`, `remove`, `facets`, `series`, `histogram`, `map(resource, { latitude, longitude, zoom, filter?, orderBy?, fields? })` (the records in a map's view, or buckets of them, see [`:map`](api.md#maps)), `seek`, `reveal(resource, key, field)` (a [sensitive field](data-config.md#sensitive-fields)'s value), `generate(resource, key, action)` (runs an [AI action](ai.md#ai-actions) and resolves to the record as written), `meta(etag?, { signal? })`, `invoke(name, { body?, method?, path?, query? })` (one of the app's [API functions](../guides/api-functions.md#calling-a-function)), `upload(resource, field, file, { onProgress?, signal? })` (a file for a [file field](files.md#uploading); its `value` goes in the next write, and `onProgress` uses XMLHttpRequest, since fetch reports no upload progress), `live({ onChanges, onResync, onRetry? })` (hears which records of the [live](live.md) resources change until the function it returns is called, connecting again by itself).
|
|
21
21
|
|
|
22
22
|
With an absolute `baseUrl`, such as another app's `https://desk.example.com/api/v1`, the `url` of each [file](files.md) in a record the client answers is absolute too, on that API's origin, where the API answers a path on its own origin. `routedClient(own, sourceOf)` is one client over several APIs: each call about a resource goes to the client `sourceOf(resource)` gives, else to `own`, as the admin app does for [remote resources](remote-resources.md), and `sourceMeta(meta, source)` keeps the part of another API's `/meta` an app draws.
|
|
23
23
|
|
|
24
|
+
`createStaticSession(token)` is a session already signed in with a token you hold, such as one from [`protobase token`](cli.md#token), for stories and scripts: it never refreshes, so the token must outlive the run, and it cannot change the account. `tokenExpiry(token)` reads a JWT's expiry, in milliseconds.
|
|
25
|
+
|
|
24
26
|
## The admin app
|
|
25
27
|
|
|
26
28
|
`<App baseUrl="/api/v1" />` renders the shell from `/api/meta` (beside the API, so `createClient` derives it from `baseUrl`) and routes `/:page` and `/:page/:tab` ([composed pages](layouts.md) and their [tabs](blocks.md#tabs-and-tab)), `/:resource` (list) and `/:resource/:key` (record); it opens on the first entry of the [sidebar](sidebar.md) the user sees, or, with none, the first page or resource. Its own pages sit under `/-/`, which no page or resource name takes: `/-/account` and its tabs (the user's [account page](auth.md#account-page), from `/meta`'s `account`) and `/-/sign-in-policy` (admins: the policy, and the log of staff sign-ins). Before the shell, it signs in on its sign-in route, `/-/sign-in`, with the methods the server offers and asks for what the [sign-in policy](auth.md#sign-in-policy) requires. Someone signed out goes there from any page, with that page in `?next=`, and signing in comes back to it; each step (a forgotten password, an emailed code, making an account) adds `?step=`, so the browser's Back returns to the step before; `?staff-sign-in` opens the [staff sign-in](auth.md#staff-sign-in) page instead, and a staff session gets a banner below the top bar. `createAuthSession` from `@protobase/client` is that session (`signIn`, `signInWithCode`, `signInWithPasskey`, `verifyTwoFactor`, `account`, `signInPolicy`, `staff`). `ui` takes the project's [custom components and action handlers](custom-components.md). The list state lives in the URL: `?list=`, a [named list](ui-config.md#more-than-one-list), `?filter=` (AIP-160), `?order_by=`, `?display=`, the [display](ui-config.md#list-displays) it shows, `?layout=panel`, the filters in a panel beside the table on a desktop instead of a bar above it, `?map=52.37,4.89,12`, where a [map](ui-config.md#maps) looks, `?calendar=month,2026-10-01`, the month or week a [calendar](ui-config.md#calendars) shows, `?timeline=quarter,2026-10-01`, the week, month or quarter a [timeline](ui-config.md#timelines) shows, and `?saved_search=`, the [saved search](ui-config.md#saved-searches) the list was opened from. Views come from `tests/apps/*/config/*/ui.ts`. The sidebar's recent-record groups and the user menu are configured there too: see [Sidebar](sidebar.md), [User menu](user-menu.md) and [Bottom bar](bottom-bar.md).
|
|
@@ -11,7 +11,7 @@ The keys of the API, at the top level of [`protobase.config.ts`](../config.md).
|
|
|
11
11
|
- **Type:** `string`
|
|
12
12
|
- **Default:** `/api/v1`
|
|
13
13
|
|
|
14
|
-
The path of the REST API on the app's origin.
|
|
14
|
+
The path of the REST API on the app's origin. A bundle serves only `/api/v1`: `protobase serve`, the serve runtime and `protobase worker` refuse a config with another path, so another one works in `protobase dev` and in a server of the app's own around `createAdmin`.
|
|
15
15
|
|
|
16
16
|
```ts
|
|
17
17
|
export default defineConfig({ apiPath: '/api/v2' })
|
|
@@ -117,7 +117,7 @@ export default defineConfig({ writeHooks: ['queue-sent-invoice'] })
|
|
|
117
117
|
- **Type:** `{ sql?: boolean; writes?: boolean | { resources?: string[]; rolesWithoutApproval?: string[] } } | false`
|
|
118
118
|
- **Default:** the read tools only: `list_resources`, `list_records` and `get_record`
|
|
119
119
|
|
|
120
|
-
The MCP endpoint's tools; [`auth.mcp`](sign-in.md#authmcp) turns the endpoint on. `sql: true` also offers admins and the `ai` role `run_read_only_query`, which reads the whole database outside the access rules. `writes: true` offers `create_record` and `
|
|
120
|
+
The MCP endpoint's tools; [`auth.mcp`](sign-in.md#authmcp) turns the endpoint on. `sql: true` also offers admins and the `ai` role `run_read_only_query`, which reads the whole database outside the access rules. `writes: true` offers `create_record`, `update_record`, `delete_record` and `batch_write` through the REST API's rules, each approved by the person in their client; `writes.resources` limits them to the resources named, and `writes.rolesWithoutApproval` lets holders of those roles, such as a service account, write without the approval. `false` is for a host that serves its own MCP endpoint at `auth.mcp.path`, in front of this app. See [MCP](../mcp.md#the-tools).
|
|
121
121
|
|
|
122
122
|
```ts
|
|
123
123
|
export default defineConfig({ auth: { mcp: true }, mcpEndpoint: { writes: { resources: ['tasks'] } } })
|
|
@@ -12,7 +12,7 @@ The keys of the app itself, at the top level of [`protobase.config.ts`](../confi
|
|
|
12
12
|
- **Default:** `Protobase`
|
|
13
13
|
- **Environment variable:** `PROTOBASE_APP_NAME`, which overrides it
|
|
14
14
|
|
|
15
|
-
The app's name: sign-in prompts and passkeys show it, the mail it sends names the app with it and is sent as it, and the sidebar, the browser tabs and the [installed app](../installable-app.md) are called by it. A deployment renames the app with `PROTOBASE_APP_NAME`, which wins over the config. See [App identity](../app-identity.md#the-name).
|
|
15
|
+
The app's name: sign-in prompts and passkeys show it, the mail it sends names the app with it and is sent as it, and the sidebar, the browser tabs and the [installed app](../installable-app.md) are called by it. A deployment renames the app with `PROTOBASE_APP_NAME`, which wins over the config. The name reaches the app through its sign-in, so with sign-in off (`auth: false`, or an `authenticate.jwksUrl` without `auth`) the app shows `PROTOBASE_APP_NAME`, else `Protobase`, and only [`protobase mobile`](../cli.md#mobile) reads `name` itself. See [App identity](../app-identity.md#the-name).
|
|
16
16
|
|
|
17
17
|
```ts
|
|
18
18
|
export default defineConfig({ name: 'Property Finder' })
|
|
@@ -36,7 +36,7 @@ export default defineConfig({ url: 'https://admin.example.com' })
|
|
|
36
36
|
- **Default:** `PROTOBASE_SECRET`
|
|
37
37
|
- **Environment variable:** `PROTOBASE_SECRET`
|
|
38
38
|
|
|
39
|
-
The app's secret, made with `openssl rand -base64 32`: it signs session cookies, upload tickets, download links and public forms' bot checks, and encrypts the token signing keys. Sign-in needs it, and file fields too unless [`files.secret`](files.md#filessecret) names another. Keep it out of the config's source and read it from the environment, which the default does.
|
|
39
|
+
The app's secret, made with `openssl rand -base64 32`: it signs session cookies, upload tickets, download links and public forms' bot checks, and encrypts the token signing keys. Sign-in needs it, and file fields too unless [`files.secret`](files.md#filessecret) names another; public forms sign their bot checks with `PROTOBASE_FORMS_SECRET` instead when it is set. Keep it out of the config's source and read it from the environment, which the default does.
|
|
40
40
|
|
|
41
41
|
```ts
|
|
42
42
|
export default defineConfig(({ env }) => ({ secret: env.ADMIN_SECRET }))
|
|
@@ -21,7 +21,6 @@ Sign-in runs the project's own code from these files, each loaded when Protobase
|
|
|
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
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
|
-
- `emails/`: the templates of sign-in's mail. See [Templates](../email.md#templates).
|
|
25
24
|
|
|
26
25
|
With [extensions](../config.md#extensions), the hooks and the mailer are those of the last folder whose config sets `auth`.
|
|
27
26
|
|
|
@@ -264,7 +263,7 @@ export default defineConfig({ auth: { origins: ['https://admin.shop.com'], passk
|
|
|
264
263
|
- **Default:** `PROTOBASE_TRUSTED_ORIGINS`, comma separated
|
|
265
264
|
- **Environment variable:** `PROTOBASE_TRUSTED_ORIGINS`
|
|
266
265
|
|
|
267
|
-
Extra origins that may call the auth endpoints, such as the exact host of a dev tunnel;
|
|
266
|
+
Extra origins that may call the auth endpoints, such as the exact host of a dev tunnel; none is trusted by default. An entry with `*`, such as `https://*.example.com`, trusts every host it matches, so list only hosts you control. `url` and `origins` always are. Set in the config, it replaces the variable's list.
|
|
268
267
|
|
|
269
268
|
```ts
|
|
270
269
|
export default defineConfig(({ env }) => ({
|
|
@@ -354,7 +353,7 @@ export default defineConfig({ authenticate: { jwksUrl: 'https://auth.example.com
|
|
|
354
353
|
- **Type:** `{ refreshMs?: number; minReloadMs?: number }`
|
|
355
354
|
- **Default:** `{ refreshMs: 600000, minReloadMs: 30000 }`
|
|
356
355
|
|
|
357
|
-
How long the key set is kept
|
|
356
|
+
How long the app's own key set is kept, when the tokens are those of `auth`: reloaded whole every `refreshMs`, so removed keys stop working, and when a token names an unknown key, at most every `minReloadMs`. A key set at `jwksUrl` is cached by its own rules, and `cache` does not change them.
|
|
358
357
|
|
|
359
358
|
```ts
|
|
360
359
|
export default defineConfig({ authenticate: { cache: { refreshMs: 60_000 } } })
|
|
@@ -57,7 +57,7 @@ export default defineConfig(({ command, env }) => ({
|
|
|
57
57
|
|
|
58
58
|
| | |
|
|
59
59
|
| --- | --- |
|
|
60
|
-
| `command` | `dev`, `build`, `serve` (also `protobase worker` and the serve runtime's `migrate`
|
|
60
|
+
| `command` | `dev`, `build`, `serve` (also `protobase worker` and the serve runtime's `create-admin`; the runtime's `migrate` never reads the config), or `tool`, any other command over the project, such as `migration`, `users` or `doctor` |
|
|
61
61
|
| `env` | `process.env`, with the project's `.env` loaded |
|
|
62
62
|
| `root` | the project's folder |
|
|
63
63
|
|
|
@@ -87,7 +87,7 @@ export default defineConfig(({ env }) => ({
|
|
|
87
87
|
}))
|
|
88
88
|
```
|
|
89
89
|
|
|
90
|
-
A JSON config reads one with an `$env` value: `{ "$env": "NAME" }`, with `"default"` for when the variable is unset or empty, and `"split": ","` for a list of its non-empty parts, each trimmed. A value whose variable is unset and has no default is left out, as if the key were not written. A TypeScript config may write `$env` values too, but its types do not know them; `env` is the typed way.
|
|
90
|
+
A JSON config reads one with an `$env` value: `{ "$env": "NAME" }`, with `"default"` for when the variable is unset or empty, and `"split": ","` for a list of its non-empty parts, each trimmed. A value whose variable is unset and has no default is left out, as if the key were not written (an item of a list stays, as `undefined`). An `$env` value is always text, the variable's or the `default` as written: `"30"` is not the number 30, and `"false"` is not `false`, so a key that takes a number or a boolean takes it written in the config, or from a TypeScript config that converts it. A TypeScript config may write `$env` values too, but its types do not know them; `env` is the typed way.
|
|
91
91
|
|
|
92
92
|
The app's database is `DATABASE_URL`'s, with the pool size of `PROTOBASE_DB_CONNECTIONS`; neither is a key of the config.
|
|
93
93
|
|
|
@@ -118,21 +118,21 @@ Every command reads the config, in a few milliseconds: reading it runs the confi
|
|
|
118
118
|
|
|
119
119
|
## Where the code is
|
|
120
120
|
|
|
121
|
-
Protobase loads each file below only when the app needs it, never while the config is read.
|
|
121
|
+
Protobase loads each file below only when the app needs it, never while the config is read. Sign-in's hooks in `auth/hooks.ts` get the app's database, `{ db }` (Kysely, as jobs get it), as their last argument; a write hook gets the write's transaction. A job named in the config without its `jobs/<name>.ts`, or a write hook without its `hooks/<name>.ts`, stops the app at start with an error that names the file.
|
|
122
122
|
|
|
123
123
|
The resources and roles have no key of their own:
|
|
124
124
|
|
|
125
125
|
| File | What it holds | See |
|
|
126
126
|
| --- | --- | --- |
|
|
127
|
-
| `config/index.ts`, `config/<dir>/ui.ts` | the resources, views and pages, as exports | [Data config](data-config.md) |
|
|
128
|
-
| `config/roles.ts` | the `roles` export, made with `defineRoles` | [Access](access.md) |
|
|
129
|
-
| `functions/<name>.ts` | an API function, as its default export | [API functions](../guides/api-functions.md) |
|
|
127
|
+
| `config/index.ts`, `config/<dir>/ui.ts` | the resources, views and pages, and the [webhook subscriptions](webhooks.md), as exports | [Data config](data-config.md) |
|
|
128
|
+
| `config/roles.ts` | the `roles` export (or the default export), made with `defineRoles` | [Access](access.md) |
|
|
129
|
+
| `functions/<name>.ts`, or `functions/<name>/index.ts` for a function of several files | an API function, as its default export; a file or folder whose name starts with `_` or `.`, a test and a `.d.ts` are not functions | [API functions](../guides/api-functions.md) |
|
|
130
130
|
|
|
131
131
|
The other files belong to an option, and are described with it:
|
|
132
132
|
|
|
133
133
|
| File | Option |
|
|
134
134
|
| --- | --- |
|
|
135
|
-
| `auth/hooks.ts`, `auth/mailer.ts
|
|
135
|
+
| `auth/hooks.ts`, `auth/mailer.ts` | [`auth`](config/sign-in.md#auth) |
|
|
136
136
|
| `auth/authenticate.ts` | [`authenticate`](config/sign-in.md#authenticate) |
|
|
137
137
|
| `hooks/<name>.ts` | [`writeHooks`](config/api.md#writehooks) |
|
|
138
138
|
| `hooks/error.ts`, `audit/queue.ts` | [Code of the API](config/api.md#code-of-the-api) |
|
|
@@ -144,7 +144,7 @@ The other files belong to an option, and are described with it:
|
|
|
144
144
|
|
|
145
145
|
## Extensions
|
|
146
146
|
|
|
147
|
-
`protobase dev --extend <dir>` and `protobase build --extend <dir>` merge an extension's folder into the app, before the project. The extension's folder has a config and code of its own, found by the same paths in that folder.
|
|
147
|
+
`protobase dev --extend <dir>` and `protobase build --extend <dir>` merge an extension's folder into the app, before the project, and so do `protobase migration` and `protobase mobile` with the same option. The extension's folder has a config and code of its own, found by the same paths in that folder; its config is a `protobase.config.ts`, since an extension's `protobase.config.json` is not read.
|
|
148
148
|
|
|
149
149
|
```tsx
|
|
150
150
|
// protobase.ui.tsx
|
|
@@ -159,7 +159,9 @@ export default defineUi({ extends: [tasksUi] })
|
|
|
159
159
|
| resources, views and pages of `config/` | all kept | an error naming both folders |
|
|
160
160
|
| user menu | at most one among all folders | an error |
|
|
161
161
|
| assistant tools of `assistant/tools.ts` | the extensions' first, in order, then the app's | an error naming the tool and both folders |
|
|
162
|
-
| `jobs`, functions, file providers | all kept, by name | an error naming the name and both folders |
|
|
162
|
+
| `jobs`, functions, file providers (`files.providers`) | all kept, by name | an error naming the name and both folders |
|
|
163
|
+
| `files.trustedHosts` | all kept | |
|
|
164
|
+
| the other keys of `files` | each the app's own; otherwise the last config that sets it | |
|
|
163
165
|
| `writeHooks` | all run, in the same order | |
|
|
164
166
|
| `config/roles.ts`, `auth/authenticate.ts`, `audit/queue.ts`, `hooks/error.ts`, `webhooks/owner-roles.ts`, `notifications/*.ts` | the app's own; otherwise the last extension's | |
|
|
165
167
|
| `auth/hooks.ts`, `auth/mailer.ts` | those of the last folder whose config sets `auth`; otherwise the app's | |
|
|
@@ -67,6 +67,7 @@ The element stays data, `{ type: 'OrdersPerDay', props: { days: 30 }, children:
|
|
|
67
67
|
`protobase.ui.tsx` exports the React component under the same name. It gets the props, and the rendered children when the element has any. Inside it:
|
|
68
68
|
|
|
69
69
|
- the hooks of `@protobase/ui` (`useList`, `useRecord`, `useSeries`, `useFacets`, `useHistogram`, `useClient`, ...) read the API with the user's token, under the same access rules as everything else;
|
|
70
|
+
- `useUpdateRecord` rejects with an error that `isConflict(error)` recognises when someone changed the record since it was read (a `412`), so the component can load it again;
|
|
70
71
|
- `useLayoutRecord()` gives the record around it in a `RecordCard` or `CardRow` (`{ model, record, key, etag, permissions }`), and `undefined` elsewhere.
|
|
71
72
|
|
|
72
73
|
A component that asks for a one-time code uses `OtpInput` from `@protobase/ui`, the field of the app's own code pages: a box per digit drawn over one real input, so pasting a whole code into any box, the system's code autofill from a mail or a text message, and the phone's digit keyboard all work. It takes `value` and `onChange`, `length` (6 by default), `invalid` and `disabled`, and `onComplete` gets the code once its last digit is in, to check it at once. Ask for a code on a step of its own, before anything else.
|
|
@@ -298,7 +299,7 @@ When the app has an [assistant](assistant.md), its button follows the project's
|
|
|
298
299
|
|
|
299
300
|
`bell` replaces the [notification bell](notifications.md#the-bell) of the top bar with your own, drawn where it would be, and takes no props either; [the bell's slot](notifications.md#the-bells-slot) lists the hooks it reads the user's notifications with. With a bell from a plugin and one from the project, the project's shows.
|
|
300
301
|
|
|
301
|
-
`logo` replaces Protobase's logo at the top of the sidebar with the app's own. It gets `compact`, true when the sidebar shows only icons, so it draws a mark alone, `workspace`, the name of the user's organization that Protobase's logo shows under it, `appName`, the app's [name](
|
|
302
|
+
`logo` replaces Protobase's logo at the top of the sidebar with the app's own. It gets `compact`, true when the sidebar shows only icons, so it draws a mark alone, `workspace`, the name of the user's organization that Protobase's logo shows under it, `appName`, the app's [name](config/app.md#name), which Protobase's logo shows beside its mark, and `appIcon`, the path of the project's own [icon](app-identity.md#the-icons) when it has one (`ShellLogoProps`). Its colors follow the [theme](theme.md), and a `dark:` class gives dark its own. When it throws, Protobase's logo shows instead. The tab's icon is [the favicon](theme.md#logo-and-favicon).
|
|
302
303
|
|
|
303
304
|
```tsx
|
|
304
305
|
import { defineUi, type ShellLogoProps } from '@protobase/ui'
|
|
@@ -315,6 +316,6 @@ export default defineUi({ shell: { logo: Logo } })
|
|
|
315
316
|
|
|
316
317
|
## Without protobase dev
|
|
317
318
|
|
|
318
|
-
`<App ui={...} />` from `@protobase/ui` takes the same object, for an app that mounts the admin itself, and so do stories.
|
|
319
|
+
`<App ui={...} />` from `@protobase/ui` takes the same object, for an app that mounts the admin itself, and so do stories. Outside `<App>`, `<ApiProvider baseUrl="/api/v1" token={...}>` gives components the API client and the query cache the hooks read through, as `<App>` does.
|
|
319
320
|
|
|
320
321
|
Below 1.0, a project built before 0.12 had its `protobase.ui.tsx` built into the admin app; [Moving onto the plugin build](../guides/plugin-build.md) says what changes.
|
|
@@ -32,7 +32,7 @@ A project that delivers its mail another way exports a mailer, `{ send({ to, sub
|
|
|
32
32
|
|
|
33
33
|
The auth emails (sign-in, two-factor and sign-up codes, the note to an address that asked to sign up while it has an account, password reset, invitations and staff sign-in notices) and the email to someone a [comment mentions](comments.md#mentions) are built with React Email's components: a heading, the message, one code or button, and a footer naming the app.
|
|
34
34
|
|
|
35
|
-
- They name the app by [`
|
|
35
|
+
- They name the app by its [`name`](config/app.md#name), and link it on the origin the request came to: the footer links its home page, and the note to an address that has an account links its sign-in page.
|
|
36
36
|
- The plain-text part has each code on a line of its own and each link in full.
|
|
37
37
|
- React Email and the templates are loaded when the first auth email is sent, so an app that sends none never loads them and the server starts as fast without them.
|
|
38
38
|
|
|
@@ -45,7 +45,7 @@ bun add react-email react
|
|
|
45
45
|
bun add -d @types/react
|
|
46
46
|
```
|
|
47
47
|
|
|
48
|
-
```tsx title="
|
|
48
|
+
```tsx title="emails/repair-ready.tsx"
|
|
49
49
|
import { defineEmail } from '@protobase/server'
|
|
50
50
|
import { Body, Button, Container, Head, Heading, Html, Preview, Text } from 'react-email'
|
|
51
51
|
|
|
@@ -132,7 +132,7 @@ A **job** is the usual place: it runs after the write that asked for it has comm
|
|
|
132
132
|
|
|
133
133
|
```ts title="jobs/email-repair-ready.ts"
|
|
134
134
|
import { FatalJobError, type JobRun } from '@protobase/server'
|
|
135
|
-
import { repairReady } from '../repair-ready'
|
|
135
|
+
import { repairReady } from '../emails/repair-ready'
|
|
136
136
|
|
|
137
137
|
// Enqueued by the write hook of a repair that became ready (hooks/email-ready-repair.ts), so the email goes out only
|
|
138
138
|
// once the write has committed, and a refused message is retried.
|
|
@@ -180,7 +180,7 @@ An **[API function](../guides/api-functions.md)** may send directly, as the answ
|
|
|
180
180
|
```ts title="functions/resend-repair-ready.ts"
|
|
181
181
|
import { z } from 'zod'
|
|
182
182
|
import { defineFunction, readJson } from '@protobase/server'
|
|
183
|
-
import { repairReady } from '
|
|
183
|
+
import { repairReady } from '../emails/repair-ready'
|
|
184
184
|
|
|
185
185
|
const Input = z.object({ repairId: z.number().int().positive() })
|
|
186
186
|
|
|
@@ -83,7 +83,7 @@ Filters use the language of [access rules](access.md) and views, on any field, f
|
|
|
83
83
|
|
|
84
84
|
- **`changes.outbox`**, one row per changed row, written in the writer's transaction, so it commits or rolls back with the change. A dispatch job reads the committed rows and deletes them once their events are delivered or queued.
|
|
85
85
|
- **`changes.capture()`**, the trigger function. It runs as its owner, with a fixed search path, so a role that writes the table needs no rights on `changes`: another service writing as its own role keeps working once a resource has events.
|
|
86
|
-
- **Two triggers per resource with events or
|
|
86
|
+
- **Two triggers per resource with events, history or [live updates](live.md)**, on its table: `<table>_changes` for inserts and deletes, and `<table>_changes_update` for updates that change the row.
|
|
87
87
|
|
|
88
88
|
The first row a transaction captures also enqueues a `changes.dispatch` job with `jobs.enqueue()`, in the same transaction, so a resource with events needs the [`jobs` schema](jobs.md#the-jobs-schema) too. Dispatch jobs run one at a time, in the app's workers. After a write through the API commits, or an API function returns, the server has its own worker look for that job at once, so its events usually go out within milliseconds; a write from elsewhere waits for the next poll, two seconds at most.
|
|
89
89
|
|
|
@@ -53,7 +53,7 @@ export default (async ({ invoiceId }, { db }) => {
|
|
|
53
53
|
| its name | Letters, digits, `_`, `-`, `.` and `/`; the file `jobs/<name>.ts` holds what it does. |
|
|
54
54
|
| `description` | What the job does, for the people who read the config. |
|
|
55
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`. |
|
|
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
|
+
| 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. It is `undefined` in an app without [`notifications`](config/jobs-and-events.md#notifications). |
|
|
57
57
|
| `maxAttempts` | Tries before the job is kept as failed; default 10. |
|
|
58
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`. |
|
|
59
59
|
| `timeout` | How long one try may run before it counts as failed; default `15 minutes`. |
|
|
@@ -62,7 +62,7 @@ export default (async ({ invoiceId }, { db }) => {
|
|
|
62
62
|
| `ordered` | Jobs run one at a time per group, in the order they were enqueued; see [Ordered groups](#ordered-groups). |
|
|
63
63
|
| `schedule`, `timezone` | Runs the job on a cron schedule, in a time zone (default the config's `timezone`, else `UTC`); see [Recurring jobs](#recurring-jobs). |
|
|
64
64
|
|
|
65
|
-
A job runs **at least once**: a worker that dies mid-job, or a try cut off by a shutdown, means it runs again. Write
|
|
65
|
+
A job runs **at least once**: a worker that dies mid-job, or a try cut off by a shutdown, means it runs again. Write the job so that running twice does no harm, for example by checking the state it is about to change.
|
|
66
66
|
|
|
67
67
|
## Enqueueing
|
|
68
68
|
|
|
@@ -121,10 +121,11 @@ select jobs.enqueue('sync-customer', '{"customerId": 3, "fields": ["email"]}', g
|
|
|
121
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.
|
|
122
122
|
|
|
123
123
|
```ts
|
|
124
|
-
|
|
124
|
+
// jobs/send-invoice.ts
|
|
125
|
+
export default (async ({ invoiceId }, { mail }) => {
|
|
125
126
|
if (!mail) throw new FatalJobError('Mail is off: set PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM')
|
|
126
127
|
await mail.send({ to: 'customer@example.com', subject: `Invoice ${invoiceId}`, text: 'Your invoice is attached in the portal.' })
|
|
127
|
-
}
|
|
128
|
+
}) satisfies JobRun<JobPayload<typeof config, 'send-invoice'>>
|
|
128
129
|
```
|
|
129
130
|
|
|
130
131
|
A message is sent once per try, so a try that sends and then fails sends again: record what was sent in the same run, and check it first.
|
|
@@ -135,7 +136,7 @@ A try that throws is retried after its backoff, until `maxAttempts`. Then the jo
|
|
|
135
136
|
|
|
136
137
|
A job that has waited 14 days past its start time without running is deleted.
|
|
137
138
|
|
|
138
|
-
While the database is read-only, as during a deploy's write freeze, a write in
|
|
139
|
+
While the database is read-only, as during a deploy's write freeze, a write in the job fails with SQLSTATE `25006`: the try waits 5 seconds and runs the job again, without using an attempt, until the database takes writes or the try times out.
|
|
139
140
|
|
|
140
141
|
## Ordered groups
|
|
141
142
|
|
|
@@ -17,7 +17,7 @@ import { Page, Stat, page } from '@protobase/layout'
|
|
|
17
17
|
export const overview = page('overview', <Page title="Overview"><Stat label="Orders" resource="orders" /></Page>, { nav: { group: 'Sales', order: 0 } })
|
|
18
18
|
```
|
|
19
19
|
|
|
20
|
-
The comment makes `@protobase/layout/jsx-runtime` compile the file instead of React's runtime, and it is how the build recognises a layout file, so every layout file needs it. Export the page from
|
|
20
|
+
The comment makes `@protobase/layout/jsx-runtime` compile the file instead of React's runtime, and it is how the build recognises a layout file, so every layout file needs it. Export the page from `config/index.ts` like a resource or view, for example `export { overview } from './overview/page'` in `config/index.ts`; `configExports` tells pages from views.
|
|
21
21
|
|
|
22
22
|
`page(name, tree, options?)`:
|
|
23
23
|
|
|
@@ -29,7 +29,7 @@ The comment makes `@protobase/layout/jsx-runtime` compile the file instead of Re
|
|
|
29
29
|
| `options.icon` | One of the [user menu icons](user-menu.md), or `layout-dashboard` (the default). |
|
|
30
30
|
| `options.roles` | Only users with one of these roles get the page. Without it, everyone who can sign in does. |
|
|
31
31
|
|
|
32
|
-
A page can also sit in the [user menu](user-menu.md) with `m.page(name)`; it then leaves the sidebar. The admin opens on the first entry of the sidebar as the user sees it, so on the first page there in `nav.order`, not the first page the config exports:
|
|
32
|
+
A page can also sit in the [user menu](user-menu.md) with `m.page(name)`; it then leaves the sidebar. The admin opens on the first entry of the sidebar as the user sees it, so on the first page there in `nav.order`, not the first page the config exports: `config/index.ts`'s exports are in alphabetical order.
|
|
33
33
|
|
|
34
34
|
## The element tree
|
|
35
35
|
|