@protobase/cli 0.49.2 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/bin/protobase.mjs +3 -2
  2. package/dist/build/config-bundle.js +1 -1
  3. package/dist/build/deploy-bundle.js +3 -4
  4. package/dist/build/plugin-build.js +16 -8
  5. package/dist/build/plugin-fields.js +5 -2
  6. package/dist/build/ui-check.js +5 -0
  7. package/dist/build/view-check.js +1 -1
  8. package/dist/cli/package.js +1 -1
  9. package/dist/config/project-files.js +4 -1
  10. package/dist/config/source-config.js +1 -1
  11. package/dist/dev/api-process.js +1 -1
  12. package/dist/dev/app-server.js +43 -35
  13. package/dist/dev/create-db.js +2 -2
  14. package/dist/dev/project.js +3 -2
  15. package/dist/dev/server-package.js +9 -21
  16. package/dist/doctor/run.js +1 -1
  17. package/dist/hand-over.d.ts +15 -0
  18. package/dist/hand-over.js +32 -0
  19. package/dist/main.js +22 -5
  20. package/dist/project/bundled-imports.js +41 -0
  21. package/dist/project/import-project-file.js +28 -8
  22. package/dist/project/load-data-config.js +4 -3
  23. package/dist/project/project-types.js +66 -0
  24. package/dist/run/preload.d.ts +1 -0
  25. package/dist/run/preload.js +20 -0
  26. package/dist/run/run-script.js +36 -0
  27. package/dist/supabase/load-phase.js +5 -4
  28. package/dist/version/project-packages.js +39 -0
  29. package/dist/version/project-version.js +33 -12
  30. package/package.json +9 -8
  31. package/skills/protobase/SKILL.md +1 -1
  32. package/skills/protobase/references/features/build-and-run.md +3 -0
  33. package/skills/protobase/references/features/releases.md +2 -1
  34. package/skills/protobase/references/getting-started.md +18 -5
  35. package/skills/protobase/references/guides/api-functions.md +1 -1
  36. package/skills/protobase/references/guides/billing-page.md +4 -4
  37. package/skills/protobase/references/guides/create-page.md +2 -2
  38. package/skills/protobase/references/guides/deploy.md +24 -8
  39. package/skills/protobase/references/guides/field-type.md +1 -1
  40. package/skills/protobase/references/guides/first-plugin.md +1 -1
  41. package/skills/protobase/references/guides/plugin-build.md +1 -1
  42. package/skills/protobase/references/guides/remote-resources.md +1 -1
  43. package/skills/protobase/references/guides/table-to-admin.md +8 -8
  44. package/skills/protobase/references/reference/ai.md +1 -1
  45. package/skills/protobase/references/reference/api.md +4 -4
  46. package/skills/protobase/references/reference/architecture.md +11 -6
  47. package/skills/protobase/references/reference/assistant.md +1 -1
  48. package/skills/protobase/references/reference/auth.md +17 -4
  49. package/skills/protobase/references/reference/blocks.md +1 -1
  50. package/skills/protobase/references/reference/bottom-bar.md +2 -2
  51. package/skills/protobase/references/reference/cli.md +50 -21
  52. package/skills/protobase/references/reference/client.md +3 -1
  53. package/skills/protobase/references/reference/config/api.md +2 -2
  54. package/skills/protobase/references/reference/config/app.md +2 -2
  55. package/skills/protobase/references/reference/config/sign-in.md +2 -3
  56. package/skills/protobase/references/reference/config.md +11 -9
  57. package/skills/protobase/references/reference/custom-components.md +3 -2
  58. package/skills/protobase/references/reference/email.md +4 -4
  59. package/skills/protobase/references/reference/events.md +1 -1
  60. package/skills/protobase/references/reference/jobs.md +6 -5
  61. package/skills/protobase/references/reference/layouts.md +2 -2
  62. package/skills/protobase/references/reference/mcp.md +9 -8
  63. package/skills/protobase/references/reference/notifications.md +10 -8
  64. package/skills/protobase/references/reference/plugins.md +3 -3
  65. package/skills/protobase/references/reference/ui-config.md +1 -1
  66. package/skills/protobase/references/reference/user-menu.md +3 -3
  67. package/skills/protobase/references/reference/versioning.md +21 -4
  68. package/skills/protobase/references/reference/webhooks.md +5 -5
@@ -8,7 +8,7 @@ Until 0.12, `protobase build` built the whole admin app into each bundle, with t
8
8
 
9
9
  ## 1. Update and rebuild
10
10
 
11
- Move the project's `@protobase` packages to 0.12 or newer, as for any release, and build:
11
+ Move the project's `@protobase` packages to 0.12, as for any release, and build; `^0.12` takes 0.12's patches only, since below 1.0 a new minor is a release of its own, moved to the same way once the project builds on 0.12:
12
12
 
13
13
  ```sh
14
14
  bun add @protobase/cli@^0.12 @protobase/server@^0.12 @protobase/schema@^0.12 @protobase/layout@^0.12 @protobase/ui@^0.12
@@ -53,7 +53,7 @@ export const ticketNotes = resource('ticket_notes')
53
53
  .access({ delete: deskOnly })
54
54
  ```
55
55
 
56
- Only the desk's own admins delete: the [access rule](../reference/access.md) holds for everyone who reaches the desk's API, the shop's people included.
56
+ The tables come first, as a migration of the desk's (a new file in `db/migrations/`, applied with `bun run db:migrate`), and the resources are exported from the desk's `config/index.ts`, where Protobase finds them: `export * from './tickets/data'`. Only the desk's own admins delete: the [access rule](../reference/access.md) holds for everyone who reaches the desk's API, the shop's people included.
57
57
 
58
58
  ```ts
59
59
  // desk: config/tickets/ui.ts
@@ -12,7 +12,7 @@ This guide follows that admin from nothing to something the front desk and the w
12
12
 
13
13
  Everything starts with the data config: what the tables are, as they are. `protobase scaffold` writes it from the database, and Pip tidies it up:
14
14
 
15
- ```ts title="config/data.ts"
15
+ ```ts title="config/bike-shop/data.ts"
16
16
  import { f, resource } from '@protobase/schema'
17
17
 
18
18
  // Pip's bike shop: customers bring bikes in, the workshop repairs them. Two tables of a Postgres database the
@@ -56,11 +56,11 @@ export const repairs = resource('repairs')
56
56
  .validate((repair) => (repair.status === 'collected' && !repair.paid ? [{ field: 'paid', message: 'A bike leaves the shop paid' }] : undefined))
57
57
  ```
58
58
 
59
- The fields follow the columns, with what the database does not say added: which fields can be filtered and sorted, which ones the database fills in (`dbDefault`), which are read-only. `notes` lives in a column called `internal_notes`, and `legacy_ref: null` keeps an old column out for good. The `validate` rule holds the shop's one firm rule: a bike does not leave unpaid.
59
+ `scaffold` writes a file per table, `config/repairs/data.ts` and `config/customers/data.ts`, and exports each from `config/index.ts`, where Protobase finds the resources; Pip keeps both in one file, exported the same way: `export * from './bike-shop/data'`. The fields follow the columns, with what the database does not say added: which fields can be filtered and sorted, which ones the database fills in (`dbDefault`), which are read-only. `notes` lives in a column called `internal_notes`, and `legacy_ref: null` keeps an old column out for good. The `validate` rule holds the shop's one firm rule: a bike does not leave unpaid.
60
60
 
61
- For the admin to list repairs, a view is enough, even an empty one:
61
+ For the admin to list repairs, a view is enough, even an empty one. A `ui.ts` in a folder of `config/` is found by its path, without an export:
62
62
 
63
- ```ts title="config/ui.ts"
63
+ ```ts title="config/bike-shop/ui.ts"
64
64
  import { view } from '@protobase/schema'
65
65
  import type { customers, repairs } from './data'
66
66
 
@@ -77,7 +77,7 @@ That is already a working admin: every column, sorting, paging, a record page an
77
77
 
78
78
  The list shows everything, including the problem descriptions nobody reads in a list. The front desk wants the repair number, whose bike, what state it is in, and who is on it, newest first.
79
79
 
80
- ```ts title="config/ui.ts"
80
+ ```ts title="config/bike-shop/ui.ts"
81
81
  import { view } from '@protobase/schema'
82
82
  import type { customers, repairs } from './data'
83
83
 
@@ -111,7 +111,7 @@ export const repairsView = view<typeof repairs>('repairs')
111
111
 
112
112
  On Saturdays the desk asks the same questions over and over: what is ready, what is Sem working on, what came in this week, what is not paid. Filters answer them in one click.
113
113
 
114
- ```ts title="config/ui.ts"
114
+ ```ts title="config/bike-shop/ui.ts"
115
115
  import { customersView, repairsView as named } from './step-2'
116
116
 
117
117
  // Step 3: the filters the front desk reaches for, and a chart of bookings above the list.
@@ -135,7 +135,7 @@ From here on each step starts from the view of the step before (`named` is step
135
135
 
136
136
  The record page still lists every field in one long column. The paper card the desk uses has three parts: the bike and its problem, the workshop's side, and the money. The layout copies it.
137
137
 
138
- ```ts title="config/ui.ts"
138
+ ```ts title="config/bike-shop/ui.ts"
139
139
  import { l } from '@protobase/schema'
140
140
  import { customersView, repairsView as filtered } from './step-3'
141
141
 
@@ -170,7 +170,7 @@ l.related('Parts used', { resource: 'repair_parts', field: 'repair_id', when: 'e
170
170
 
171
171
  Two things happen to every repair: it becomes ready, and it gets collected (and paid). Typing a status into a dropdown is how mistakes happen, so they become buttons. And the mechanics would rather not see prices at all.
172
172
 
173
- ```ts title="config/ui.ts"
173
+ ```ts title="config/bike-shop/ui.ts"
174
174
  import { l } from '@protobase/schema'
175
175
  import { customersView, repairsView as laidOut } from './step-4'
176
176
 
@@ -80,7 +80,7 @@ The action runs at `POST /api/v1/{resource}/{key}:generate` with `{ "action": "<
80
80
  | `404` | `not-found` | The caller's view has no AI action of that name, or there is no such record. |
81
81
  | `403` | `ai-forbidden` | The caller may not read a field the prompt reads, or update the field it writes. |
82
82
  | `422` | `ai-no-value` | Every field the prompt reads is empty, or the model answered nothing. |
83
- | `502` | `ai-unavailable` | The model failed or took more than 60 seconds. The user sees only that; the endpoint's message goes to the app's error reporting (`onUnhandledError`). |
83
+ | `502` | `ai-unavailable` | The model failed or took more than 60 seconds. The user sees only that; the endpoint's message goes to the app's error reporting (its [`hooks/error.ts`](config/api.md#code-of-the-api)). |
84
84
  | `503` | `ai-not-configured` | No model is set; startup normally catches this first. |
85
85
 
86
86
  Every check is made before the model is asked.
@@ -4,7 +4,7 @@
4
4
 
5
5
  The REST API that @protobase/server generates, with its routes, access, filters, writes, batches and errors.
6
6
 
7
- `@protobase/server` turns resource definitions into a Hono app that follows Google's API design conventions ([AIP-131 to 136](https://google.aip.dev/131), [158](https://google.aip.dev/158), [160](https://google.aip.dev/160)). It uses Web APIs only and runs on Node and Workers; the Node adapter lives in the example.
7
+ `@protobase/server` turns resource definitions into a Hono app that follows Google's API design conventions ([AIP-131 to 136](https://google.aip.dev/131), [158](https://google.aip.dev/158), [160](https://google.aip.dev/160)). It uses Web APIs only and runs on Node, Bun and Workers; `protobase dev` and `serve` serve it on Node or Bun.
8
8
 
9
9
  `protobase dev` and `serve` build it from the project: the resources of `config/`, the functions of `functions/`, sign-in from `auth`, and the API's settings from the top-level keys of [`protobase.config.ts`](config.md), such as `statementTimeoutMs` and `scanGuard`. In code of its own, an app builds it with `createAdmin`, whose `options` take the same settings:
10
10
 
@@ -23,7 +23,7 @@ const admin = createAdmin({
23
23
  })
24
24
  ```
25
25
 
26
- Run the ERP example with `bun run --cwd tests/apps/erp serve` (port 8787, Better Auth login, organization 1 as tenant; `REQUEST_LOG=true` logs requests). Interactive reference: `/api/docs`; like `/api/openapi.json` it needs a bearer token, because the document lists what the caller may see and do. Every route answers `401` without a valid token; get one with `protobase token you@example.com`. A project whose roles define [`anonymous`](access.md#anonymous-access) serves the resources API to requests without a token as that role.
26
+ Run the ERP example with `bun run --cwd tests/apps/erp serve` (port 8787, Better Auth login, the user's active [organization](auth.md#organizations) as tenant; `REQUEST_LOG=true` logs requests). Interactive reference: `/api/docs`; like `/api/openapi.json` it needs a bearer token, because the document lists what the caller may see and do. Every route answers `401` without a valid token; get one with `protobase token you@example.com`. A project whose roles define [`anonymous`](access.md#anonymous-access) serves the resources API to requests without a token as that role.
27
27
 
28
28
  ## Routes
29
29
 
@@ -196,7 +196,7 @@ The API sends no CORS headers until it has something to allow: other websites in
196
196
 
197
197
  ## Safety
198
198
 
199
- - Every request runs in a transaction with `SET LOCAL statement_timeout` (`statementTimeoutMs`, default 1 s), so a slow query fails where it runs instead of holding a connection that other requests wait for. List, search, get, histogram, series, map and seek transactions are read-only. A query that runs longer is stopped: a `504` `statement-timeout` that names the request, its limit and the ways out, such as `GET /api/v1/orders ran a query longer than 1 s, so the database stopped it. Make the query faster, such as with an index or a narrower filter, or move the work into a function or job with longQueries: true, whose queries may run up to 30 s.` It goes to `options.onUnhandledError` and the [error tracker](#error-reporting) like a `500`. A read that needs longer has no way to opt out: give it an index, or move it into a [function](../guides/api-functions.md#long-queries) or [job](jobs.md) with `longQueries`.
199
+ - Every request runs in a transaction with `SET LOCAL statement_timeout` (`statementTimeoutMs`, default 1 s), so a slow query fails where it runs instead of holding a connection that other requests wait for. List, search, get, histogram, series, map and seek transactions are read-only. A query that runs longer is stopped: a `504` `statement-timeout` that names the request, its limit and the ways out, such as `GET /api/v1/orders ran a query longer than 1 s, so the database stopped it. Make the query faster, such as with an index or a narrower filter, or move the work into a function or job with longQueries: true, whose queries may run up to 30 s.` It goes to the app's error hook (`hooks/error.ts`, `createAdmin`'s `options.onUnhandledError`) and the [error tracker](#error-reporting) like a `500`. A read that needs longer has no way to opt out: give it an index, or move it into a [function](../guides/api-functions.md#long-queries) or [job](jobs.md) with `longQueries`.
200
200
  - Under `protobase dev` and `serve`, a request waits at most 2 seconds for a free database connection. When every connection stays busy that long, it is a `503` `connections-busy` with `Retry-After: 1` that names the request, reported the same way, rather than a request that hangs behind slow ones.
201
201
  - **Scan guard**: a list, `:search`, `:seek`, `:map` page, card photos, `:facets` and `:aggregate` read only columns an index serves, so they stay cheap however many rows match. The server reads each table's valid indexes from the catalog once, then checks every column the caller's filter, the role's row filter, the sort's first field and a facet's or an aggregate's grouped field read:
202
202
  - Comparisons, `in`, null checks, sorts and facets need a btree index with the column as a key, every key before it pinned by the query: by `=` or `in` in the filter (outside `OR` and `NOT`), by the tenant or by soft delete. `(for_sale, status, published_at desc)` serves `for_sale = true AND status = "available"` sorted by `published_at desc`, but not `status` alone. `=` on text may use a pg_trgm index instead.
@@ -207,7 +207,7 @@ The API sends no CORS headers until it has something to allow: other websites in
207
207
 
208
208
  ## Errors
209
209
 
210
- Every error is `application/problem+json` (RFC 9457) with `type` (`urn:protobase:problem:<slug>`), `title`, `status`, `detail`, `instance`. Filter and `order_by` errors add `parameter` and `errors: [{ code, message, hint, span: { start, end } }]`; invalid parameters add `errors: [{ parameter, message }]`. A create or update whose body fails the checks is `invalid-record` with `errors: [{ field, code, message, params }]`, `code` one of `required`, `invalid-value`, `read-only`, `unknown-field` and `invalid-record` (a `.validate()` rule); `params` is the limit an invalid value broke, such as `{ min }`, `{ max }` or a decimal's `{ precision, scale }`. Database constraint failures map to `409` or `400` without the raw message. A create or update that writes the position of a resource with `after` so a record ranks at or above one it depends on is a `409` `ranks-above-dependency`, as in a [`reorder`](#batch-writes). A delete that other records still point at is a `409` `conflict` with `blockedBy: { resource, field? }`: their resource, when the caller may list it, and its relation field pointing at the record, when they may filter by it, so a client can open those records; the admin app's toast names them, such as "Orders still point at this company.", with a link to that list. Postgres names one table of them only, so `blockedBy` holds one resource; anything unexpected is a `500` with a fixed detail, reported to `options.onUnhandledError` and, when it is set, the [error tracker](#error-reporting).
210
+ Every error is `application/problem+json` (RFC 9457) with `type` (`urn:protobase:problem:<slug>`), `title`, `status`, `detail`, `instance`. Filter and `order_by` errors add `parameter` and `errors: [{ code, message, hint, span: { start, end } }]`; invalid parameters add `errors: [{ parameter, message }]`. A create or update whose body fails the checks is `invalid-record` with `errors: [{ field, code, message, params }]`, `code` one of `required`, `invalid-value`, `read-only`, `unknown-field` and `invalid-record` (a `.validate()` rule); `params` is the limit an invalid value broke, such as `{ min }`, `{ max }` or a decimal's `{ precision, scale }`. Database constraint failures map to `409` or `400` without the raw message. A create or update that writes the position of a resource with `after` so a record ranks at or above one it depends on is a `409` `ranks-above-dependency`, as in a [`reorder`](#batch-writes). A delete that other records still point at is a `409` `conflict` with `blockedBy: { resource, field? }`: their resource, when the caller may list it, and its relation field pointing at the record, when they may filter by it, so a client can open those records; the admin app's toast names them, such as "Orders still point at this company.", with a link to that list. Postgres names one table of them only, so `blockedBy` holds one resource; anything unexpected is a `500` with a fixed detail, reported to the app's error hook (`hooks/error.ts`, `createAdmin`'s `options.onUnhandledError`) and, when it is set, the [error tracker](#error-reporting).
211
211
 
212
212
  | Status | Slugs |
213
213
  | --- | --- |
@@ -10,26 +10,31 @@ A Bun workspace of npm packages under the `@protobase` scope, in `packages/<name
10
10
 
11
11
  | Package | Folder | Entry points | Runs in | Depends on |
12
12
  | --- | --- | --- | --- | --- |
13
- | `@protobase/schema` | `packages/schema` | `@protobase/schema` | anywhere | no other `@protobase` package |
13
+ | `@protobase/schema` | `packages/schema` | `@protobase/schema`, `@protobase/schema/png-icons`; `@protobase/schema/internal` for the other packages only | anywhere | no other `@protobase` package |
14
14
  | `@protobase/layout` | `packages/layout` | `@protobase/layout`, `@protobase/layout/jsx-runtime`, `@protobase/layout/jsx-dev-runtime` | anywhere | `schema` |
15
15
  | `@protobase/query` | `packages/query` | `@protobase/query` | server | `schema` |
16
16
  | `@protobase/client` | `packages/client` | `@protobase/client` | anywhere with `fetch` | `schema`, `layout` |
17
- | `@protobase/ui` | `packages/ui` | `@protobase/ui`; the admin app in `src/app` | browser | `schema`, `layout`, `client` |
18
- | `@protobase/server` | `packages/server` | `@protobase/server` | server | `schema`, `layout`, `query` |
19
- | `@protobase/cli` | `packages/cli` | the `protobase` command (`bin/protobase.mjs`) | Node and Bun | `schema`, `layout`, `query`, `server`, `ui` |
17
+ | `@protobase/ui` | `packages/ui` | `@protobase/ui`, `@protobase/ui/theme.css`, `@protobase/ui/styles.css`; the admin app in `src/app` | browser | `schema`, `layout`, `client` |
18
+ | `@protobase/server` | `packages/server` | `@protobase/server`, `@protobase/server/auth-store`, `@protobase/server/config-exports`, `@protobase/server/email`, `@protobase/server/vapid`; `@protobase/server/internal` for the other packages only | server | `schema`, `layout`, `query` |
19
+ | `@protobase/config` | `packages/config` | `@protobase/config`, `@protobase/config/schema.json` | anywhere | types of `server` only: it runs nothing besides `defineConfig` |
20
+ | `@protobase/cli` | `packages/cli` | the `protobase` command (`bin/protobase.mjs`), `@protobase/cli/auth`, `@protobase/cli/runner` | Node and Bun | `config`, `schema`, `layout`, `query`, `server`, `ui` |
21
+ | `@protobase/mobile` | `packages/mobile` | none: the Capacitor packages and native plugins `protobase mobile` installs on first use | the app's iOS and Android projects | none |
22
+ | `create-protobase` | `packages/create-protobase` | the `create-protobase` command, for `npm create protobase` | Node | none |
20
23
  | `@protobase/presets` | `packages/presets` | none: private, `bun run presets:write` writes a project per preset | Bun | none; each preset depends on the `@protobase` packages of the major it is written at, locked at that version |
21
24
  | `tests/apps/*` | | none | any | `@protobase/*` entry points only |
22
25
 
23
- The presets are written from `tests/apps/erp`, `tests/apps/real-estate` and `tests/apps/scratch` (from scratch) by `bun run presets:write <version> <dir>`, run from a clone of this repository; `npm create protobase` (`packages/create-protobase`) writes them too, without a lockfile. Each is a standalone copy with the `@protobase` packages in the caret range of `<version>`, `^x.y.z`, so an app takes the updates semver calls compatible: within that major from 1.0 on, and within that minor below 1.0, where a minor may break, and its own `bun.lock` at exactly `<version>`. The three declare the same dependencies, so one `node_modules` fits them all, and their `db:migrate` (the auth schema's migrations included), `typecheck` and `test` scripts take their settings from the environment, or a `.env` beside them, and reach nothing outside the project.
26
+ The presets are written from `tests/apps/erp`, `tests/apps/real-estate` and `tests/apps/scratch` (from scratch) by `bun run presets:write <version> <dir>`, run from a clone of this repository; `npm create protobase` (`packages/create-protobase`) writes them too, without a lockfile. Each is a standalone copy with the `@protobase` packages in `devDependencies`, so an app made from it is [bundled](versioning.md#bundles-and-runtimes) and runs on the CLI's own copies, in the caret range of `<version>`, `^x.y.z`, so an app takes the updates semver calls compatible: within that major from 1.0 on, and within that minor below 1.0, where a minor may break, and its own `bun.lock` at exactly `<version>`. Its `tsconfig.json` extends `.protobase/tsconfig.json`, which [`protobase types`](cli.md#types) writes, as `dev`, `build` and its `typecheck` and `test` scripts do first, and its database scripts run with [`protobase run`](cli.md#run). The examples in this repository list the packages in `dependencies`, locked to the workspace's, and their `tsconfig.json` extends nothing: Vite reads it when it transforms their files, and would fail before the file it extends is written. The three declare the same dependencies, so one `node_modules` fits them all, and their `db:migrate` (the auth schema's migrations included), `typecheck` and `test` scripts take their settings from the environment, or a `.env` beside them, and reach nothing outside the project.
24
27
 
25
28
  The JSX runtime belongs to `@protobase/layout` because a layout file names one package in `@jsxImportSource @protobase/layout`, and TypeScript and Vite look up `jsx-runtime` and `jsx-dev-runtime` under it. Each field type is split along the same lines: its Zod builder is `packages/schema/src/fields/<type>.ts` and its SQL parameter conversion `packages/query/src/fields/<type>.ts`.
26
29
 
27
30
  Every package lists the packages it imports in its `package.json` (`workspace:*` for its `@protobase` dependencies), so it installs and works on its own. Rules, enforced by `bun run check:boundaries` (`.dependency-cruiser.cjs`):
28
31
 
29
32
  - A package imports only the `@protobase` packages in the table above, so `@protobase/ui` never reaches `query`, `server` or `cli`, and `@protobase/layout` only `schema`: layouts are built in the config, checked on the server and rendered in the browser.
33
+ - `@protobase/config` imports types only, so reading a config loads nothing but it and the config.
30
34
  - A package imports another by its name and entry point, never by a path into its source.
31
35
  - A package's code (not its tests and stories) imports only what its `package.json` lists in `dependencies`.
32
36
  - Examples, their tests and `test-support/` import the packages by name, never by path.
37
+ - Only an encrypted field's reveal and the `encryption` commands decrypt its values.
33
38
  - No circular dependencies.
34
39
 
35
40
  In this repository, entry points export TypeScript source directly and the CLI runs its source on Bun, or on Node through [tsx](https://tsx.is), so nothing needs a build. The published packages are built to JavaScript in `dist` by `bun run build` and `bun pm pack` (`scripts/publish.mjs`) (see [CLI](cli.md#how-it-runs)). The other builds are for deployment: the serve runtime, `packages/cli/src/serve/main.ts` bundled with its dependencies into `dist/protobase-serve.js` by `protobase build-serve`, the shell, a production build of the admin app (`packages/ui/src/app`) shipped in `@protobase/ui`'s `dist/shell` and the protobase image, and a project's bundle, its config module plus a copy of the shell and the project's `protobase.ui.tsx` built as a [plugin](plugins.md), by `protobase build` (see [CLI](cli.md#build)).
@@ -58,6 +63,6 @@ Filters are Google AIP-160 text. Parsing, printing, `order_by` and the generic c
58
63
 
59
64
  ## Documentation
60
65
 
61
- `website/` is this site. `bun run docs:dev` serves it on port 4321; `bun run docs:build` writes `website/dist/` and fails on a broken internal link or anchor, so CI runs it on every pull request, followed by `bun run docs:check`, which opens every page in Chromium and fails on a console error or a failed request. Pages are Markdown or MDX in `website/src/content/docs/`, and the sidebar is listed in `website/astro.config.mjs`.
66
+ `website/` is this site. `bun run docs:dev` serves it on port 4321; `bun run docs:build` writes `website/dist/` and fails on a broken internal link or anchor, so CI runs it on every pull request, followed by `bun run docs:check`, which opens every page in Chromium and fails on a console error or a failed request. Pages are Markdown or MDX in `website/src/content/docs/`, and the sidebar is listed in `website/sidebar.mjs`.
62
67
 
63
68
  Every push to `main` builds the site and deploys it, and so does running the workflow by hand (`gh workflow run docs.yml`); either way it deploys to the Cloudflare Pages project `protobase-docs`, served at `docs.protobase.net` (`.github/workflows/docs.yml`). The workflow reads the Cloudflare account id from the repository variable `CLOUDFLARE_ACCOUNT_ID` and a token with Cloudflare Pages edit permission from the repository secret `CLOUDFLARE_API_TOKEN`.
@@ -68,7 +68,7 @@ Making the query role needs `CREATEROLE` once, for the role that applies the mig
68
68
 
69
69
  `assistant/tools.ts` adds tools of the app's own, which the built-in backend offers after its two: its default export is an array of tools, found by that path when the app starts. A tool is `defineTool({ name, description, parameters, run })` from `@protobase/server`: `parameters` is the JSON Schema of its arguments, and `run(args, context)` returns the text the model reads. A name must be 1 to 64 letters, digits, `_` or `-`, and a name taken twice stops the server at startup. A backend elsewhere has its own tools, so the file does nothing there, nor with `assistant: false`. A tool's `annotations` are MCP's tool hints (`readOnlyHint`, `destructiveHint`, ...), which the dock ignores; the same tools can be offered over the app's [MCP endpoint](mcp.md#building-on-it).
70
70
 
71
- `context` holds the user's `session`, `show(part)` to add a part to the answer, `approve(request)` for an approval card, `conversation` (the dock's, absent over MCP), `resources()` (the resources the user may read, restricted to their fields, with their views), and `records`: `list(resource, params)` with the REST API's list parameters, `get(resource, key)`, `create(resource, data)`, `update(resource, key, data, { etag? })` (without an ETag it updates any version), `delete(resource, key, { etag? })` (soft on a resource with `.softDelete()`) and `softDeleteField(resource)` (the field a delete sets, or `undefined` when a delete removes the record) on the app's resources **as the user**, through their access rules, tenant scope, validation and write hooks, as in the REST API. Each answers `{ record, etag }`. `batch(operations)` runs the operations of a REST [batch write](api.md#batch-writes) in one transaction and answers its `results`; a refusal or a missing record rejects with an `HttpProblem`, whose `detail` a tool can return to the model as text.
71
+ `context` holds the user's `session`, `show(part)` to add a part to the answer, `approve(request)` for an approval card, `conversation` (the dock's, absent over MCP), `resources()` (the resources the user may read, restricted to their fields, with their views), and `records`: `list(resource, params)` with the REST API's list parameters, `get(resource, key)`, `create(resource, data)`, `update(resource, key, data, { etag? })` (without an ETag it updates any version), `delete(resource, key, { etag? })` (soft on a resource with `.softDelete()`) and `softDeleteField(resource)` (the field a delete sets, or `undefined` when a delete removes the record) on the app's resources **as the user**, through their access rules, tenant scope, validation and write hooks, as in the REST API. `get`, `create`, `update` and `delete` each answer `{ record, etag }`, and `list` a page of records. `batch(operations)` runs the operations of a REST [batch write](api.md#batch-writes) in one transaction and answers its `results`; a refusal or a missing record rejects with an `HttpProblem`, whose `detail` a tool can return to the model as text.
72
72
 
73
73
  A tool with a [widget](#widget-parts) creates or finds what it is about, shows a widget with its id, and returns the id and the state at that moment:
74
74
 
@@ -38,7 +38,7 @@ Each version's statements are followed by its row in `auth_migrations`. The file
38
38
 
39
39
  Every store has the tables of every feature, whether the app turns the feature on or not: [passkeys](#passkeys), [two-factor authentication](#two-factor-authentication), [organizations](#organizations) and the [OAuth provider for MCP](#oauth-for-mcp-clients). Turning a feature on or off needs no migration and drops nothing; the columns a feature adds to the user and session tables are empty until it is on. SAML providers and open sign-up keep nothing in the store.
40
40
 
41
- The store's tables and columns are snake_case, like the app's (`sign_in_policy.platform_sign_in`, `session.user_id`); the code and the API keep Better Auth's camelCase names. The names the app configures, the store's schema (`schemaName`), the [user table](#an-existing-users-table) and its columns, and uuid ids (`generateUserId: 'uuid'`), are the ones in effect when the file is written. Changing one later is a migration of the project's own, such as a rename.
41
+ The store's tables and columns are snake_case, like the app's (`sign_in_policy.platform_sign_in`, `session.user_id`); the code and the API keep Better Auth's camelCase names. The names the app configures, the store's schema ([`auth.schema`](config/sign-in.md#authschema)), the [user table](#an-existing-users-table) and its columns, and uuid ids (`generateUserId: 'uuid'`), are the ones in effect when the file is written. Changing one later is a migration of the project's own, such as a rename.
42
42
 
43
43
  The server never changes the schema, and never compares it with what Better Auth needs. `protobase serve` and `protobase dev` read `auth_migrations` at startup and refuse to start while a version of this Protobase is not applied, naming it and `protobase auth migration`, or while the store has a version newer than this Protobase knows. The examples' `db:migrate` applies all pending files in one transaction, so a migration that fails leaves the database as the running version expects it. The host must guarantee the rest: nothing but the migrations writes while they run, and the new version serves only after they succeeded. Only [`protobase dev`](cli.md#dev), on the developer's machine, compares the store's tables with what the app's Better Auth needs, and warns at startup about each table, column or index that drifted, such as one changed by hand.
44
44
 
@@ -72,7 +72,7 @@ The store's migrations make the user table only when it is missing, and add each
72
72
  | `PROTOBASE_SECRET` | the app's secret, the default of `secret`: signs cookies and encrypts the token keys; `openssl rand -base64 32`; never committed (`.env.example` has a placeholder) |
73
73
  | `PROTOBASE_PREVIOUS_SECRETS` | the app's secrets before `PROTOBASE_SECRET`, newest first, comma separated, the default of `previousSecrets`; see [Changing the secret](#changing-the-secret) |
74
74
  | `PROTOBASE_URL` | the app's public URL, the default of `url` (in `protobase dev`, the dev server's own); issuer and audience of the tokens; when tunnelling, the https tunnel URL |
75
- | `PROTOBASE_TRUSTED_ORIGINS` | extra comma separated origins, the default of `auth.trustedOrigins`; a dev tunnel needs its exact host here, such as `https://my-tunnel.trycloudflare.com`, since no wildcard is trusted |
75
+ | `PROTOBASE_TRUSTED_ORIGINS` | extra comma separated origins, the default of `auth.trustedOrigins`; a dev tunnel needs its exact host here, such as `https://my-tunnel.trycloudflare.com`, since none is trusted by default; an entry with `*` trusts every host it matches |
76
76
  | `PROTOBASE_ORIGINS` | the other origins the app is served on, comma separated, passed by the platform; see [Several origins](#several-origins) |
77
77
  | `PROTOBASE_PASSKEY_DOMAIN` | the host new [passkeys](#passkeys) are made for, passed by the platform; default the host of the app's `url` |
78
78
  | `PROTOBASE_CORS_ORIGINS` | other websites whose browser code may call the API, `*` or comma separated http and https origins, passed by the platform; see [CORS](api.md#cors) |
@@ -128,14 +128,14 @@ Accounts are never created over the web while the store is empty: there is no se
128
128
 
129
129
  ```ts
130
130
  import { loadProjectAuth } from '@protobase/cli/auth'
131
- import { createUser, hasUsers, listUsers } from '@protobase/server'
131
+ import { createUser, deleteUser, hasUsers, listUsers, setUserBanned, setUserRole } from '@protobase/server'
132
132
 
133
133
  const auth = await loadProjectAuth(process.cwd()) // the project's folder; its .env is loaded too
134
134
 
135
135
  await createUser(auth, { email, password?, name?, role? }) // the first user is always an admin; later ones default to `user`
136
136
  await hasUsers(auth) // boolean
137
137
  await listUsers(auth) // [{ id, email, role, banned, createdAt }], never passwords
138
- await setUserRole(auth, { email, role }) // 'admin' | 'user'
138
+ await setUserRole(auth, { email, role }) // a role of auth.roles, or several comma separated
139
139
  await setUserBanned(auth, { email, banned }) // banning ends the user's sessions and blocks sign-in
140
140
  await deleteUser(auth, email) // with sessions and accounts
141
141
  ```
@@ -587,6 +587,19 @@ It is Better Auth's organization plugin, with its tables named in snake_case (`o
587
587
 
588
588
  **Ids.** The `generateOrganizationId` [hook](#hooks) makes a new organization's id, by default a UUID; `.tenant` columns hold it, so `text` or `uuid`. An app whose tenant columns are integers takes the next value of its own organizations sequence instead, and adds its own row in `onOrganizationCreated`, as the ERP example does (`tests/apps/erp/auth/hooks.ts`). An app that ran as one organization keeps its tenant value: `protobase organizations create "Acme" --owner you@example.com --id 1 --members all` makes that organization, with every user in it: superusers as owners, everyone else as a member, their global roles moved onto the membership.
589
589
 
590
+ **On the host.** The [`protobase organizations`](cli.md#organizations) commands call these functions of `@protobase/server`, which a script of the project's own, such as a seed, calls with the sign-in of [`loadProjectAuth`](#first-run). The host acts as a superuser, so it may give any role; `organization` is a slug or an id:
591
+
592
+ ```ts
593
+ import { addAppRoleToOwners, addMember, createOrganization, listOrganizations, removeMember, setMemberRoles } from '@protobase/server'
594
+
595
+ await createOrganization(auth, { name, slug, owner: email, id? }) // the owner holds every app role
596
+ await addMember(auth, { organization, email, role?, appRoles? }) // role: owner, admin or member (default)
597
+ await setMemberRoles(auth, { organization, email, role?, appRoles? })
598
+ await removeMember(auth, { organization, email }) // refuses the last owner
599
+ await listOrganizations(auth) // oldest first, with members' emails and roles
600
+ await addAppRoleToOwners(auth, appRole) // a role the project added later, to every owner
601
+ ```
602
+
590
603
  The app's own pages are under the profile menu: the switcher, "Manage organizations" (theirs, a new one, and for global roles any one), "Organization" (details, leaving, handing over, deleting), and for owners and admins "Members" and "Invitations". The client has them as `session.organizations` (`list`, `current`, `switchTo`, `members`, `invite`, ...).
591
604
 
592
605
  ## Tokens and roles
@@ -4,7 +4,7 @@
4
4
 
5
5
  Every built-in layout block, its props and what it does, with examples from the ERP's sales overview.
6
6
 
7
- Blocks are imported from `@protobase/layout`. "Record" below means the record of the `RecordCard` or `CardRow` card around a block (see [Data](layouts.md#data)); `filter` is AIP-160 and `sort` AIP-132, as in the list API. Every block below but `RecordRow`, which the property portal's home uses, `RecordCards`, `Tabs` and `Tab`, `Settings`, and `Users`, which the [Users page](auth.md#users-page) uses, appears in the ERP example's sales overview:
7
+ Blocks are imported from `@protobase/layout`. "Record" below means the record of the `RecordCard` or `CardRow` card around a block (see [Data](layouts.md#data)); `filter` is AIP-160 and `sort` AIP-132, as in the list API. The ERP example's sales overview uses `Page`, `Grid`, `Card`, `Stat`, `Table`, `RecordCard`, `CardRow`, `Field`, `Chart`, `Action`, `ModalForm` and `Show`; of the others, the property portal's home uses `RecordRow`, and the [Users page](auth.md#users-page) `Users`:
8
8
 
9
9
  ```tsx title="tests/apps/erp/config/overview/page.tsx"
10
10
  /** @jsxImportSource @protobase/layout */
@@ -6,7 +6,7 @@ Tabs along the bottom of a phone, as on iOS, for the roles that work from one.
6
6
 
7
7
  On phones the sidebar is a drawer behind the top bar's menu button. For people who work from a phone, such as on a warehouse floor, a bottom bar puts their few screens one tap away: up to four tabs, each an icon above its label, the current one highlighted, and "More" last, which opens the drawer with the rest. The bar keeps clear of the iPhone home indicator. From the `md` breakpoint (768px) up there is no bar; the sidebar shows instead.
8
8
 
9
- Export a [`bottomBar(...)`](https://docs.protobase.net/api/schema/functions/bottombar/) from the config module for each group of roles that gets one:
9
+ Export a [`bottomBar(...)`](https://docs.protobase.net/api/schema/functions/bottombar/) from `config/index.ts` for each group of roles that gets one:
10
10
 
11
11
  ```ts
12
12
  // tests/apps/erp/config/bottom-bar.ts, re-exported from config/index.ts
@@ -36,7 +36,7 @@ Each bar names its roles, and a role belongs to one bar. A caller gets the bar t
36
36
 
37
37
  `createAdmin` refuses to start when a bar names a resource or page that does not exist, has no roles, no items or more than four, names a role the app does not have (the roles of [`auth.roles`](auth.md#roles) and [`defineRoles`](access.md); without either, any role is accepted), shares a role with another bar, or has the label of another bar. The checks are [`bottomBarErrors`](https://docs.protobase.net/api/schema/functions/bottombarerrors/) from `@protobase/schema`, a pure function of the bars and the app's names.
38
38
 
39
- `protobase dev`, `protobase build` and `protobase serve` pick the bars up from the config module. With `createAdmin` directly, pass them as `bottomBars`:
39
+ `protobase dev`, `protobase build` and `protobase serve` pick the bars up from `config/index.ts`. With `createAdmin` directly, pass them as `bottomBars`:
40
40
 
41
41
  ```ts
42
42
  const { resources, views, bottomBars } = configExports(config)
@@ -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 @protobase/schema @protobase/layout @protobase/server @protobase/ui
11
- bun run protobase <command> # from the project, config folder defaults to ./config
12
- bun run --cwd tests/apps/erp protobase <command> # in this repository, for an example
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
- Any package manager installs the packages, 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 project in the current directory, by the `@protobase` packages installed there, is of its own major version, and stops with an error naming both versions when it is not: within a major a CLI runs every project, whatever its minor. That is the CLI's one version check. Outside a project, or before its install, there is nothing to check.
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
- The CLI reads the database with `default_transaction_read_only = on`, so it can never write.
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` when its `package.json` lists it, in any of its dependency fields; a project that lists it without installing it fails as with any missing package. Without a `package.json`, or with one that does not list it, it uses the copy the CLI ships, with the CLI's `@protobase/schema`, `@protobase/query` and `@protobase/layout`.
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 project needs `pg` installed, because the API connects with Kysely over the project's own `pg`.
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 project is pinned to: the `@protobase/cli` its lockfile installed, whichever CLI of its major built the bundle. A host serves the bundle on the runtime of that version (see [Versioning](versioning.md#bundles-and-runtimes)). The build fails in a project without its `@protobase` packages installed.
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 the 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)).
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, which the build needs: `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)).
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 or --password-stdin
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, so a project's own `db` with a pool of one is enough.
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 <slug> [--org-role <role>] [--app-roles <a,b>]]
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
 
@@ -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 auth --exclude public.schema_migrations --exclude public.seed_info
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
- Always pass `--exclude auth`: the ERP keeps Better Auth's users, sessions and signing keys in the `auth` schema of the same database, and scaffolding them would expose credentials through the admin API.
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 `update_record` 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).
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'] } } })