@protobase/cli 0.22.13 → 0.23.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.
- package/dist/main.js +2 -0
- package/dist/package.js +1 -1
- package/dist/skill/install.js +29 -0
- package/dist/skill/register.js +14 -0
- package/package.json +8 -7
- package/skills/protobase/SKILL.md +89 -0
- package/skills/protobase/references/getting-started.md +78 -0
- package/skills/protobase/references/guides/api-functions.md +240 -0
- package/skills/protobase/references/guides/billing-page.md +288 -0
- package/skills/protobase/references/guides/create-page.md +108 -0
- package/skills/protobase/references/guides/deploy.md +52 -0
- package/skills/protobase/references/guides/export-a-list.md +44 -0
- package/skills/protobase/references/guides/field-type.md +131 -0
- package/skills/protobase/references/guides/first-composed-page.md +230 -0
- package/skills/protobase/references/guides/first-plugin.md +166 -0
- package/skills/protobase/references/guides/import-records.md +43 -0
- package/skills/protobase/references/guides/plugin-build.md +64 -0
- package/skills/protobase/references/guides/record-card.md +70 -0
- package/skills/protobase/references/guides/remote-resources.md +185 -0
- package/skills/protobase/references/guides/table-to-admin.md +205 -0
- package/skills/protobase/references/guides/theme-an-app.md +87 -0
- package/skills/protobase/references/reference/access.md +115 -0
- package/skills/protobase/references/reference/ai.md +106 -0
- package/skills/protobase/references/reference/api.md +231 -0
- package/skills/protobase/references/reference/architecture.md +63 -0
- package/skills/protobase/references/reference/assistant.md +157 -0
- package/skills/protobase/references/reference/auth.md +462 -0
- package/skills/protobase/references/reference/blocks.md +341 -0
- package/skills/protobase/references/reference/bottom-bar.md +44 -0
- package/skills/protobase/references/reference/cli.md +493 -0
- package/skills/protobase/references/reference/client.md +38 -0
- package/skills/protobase/references/reference/comments.md +83 -0
- package/skills/protobase/references/reference/custom-components.md +285 -0
- package/skills/protobase/references/reference/data-config.md +266 -0
- package/skills/protobase/references/reference/email.md +166 -0
- package/skills/protobase/references/reference/events.md +121 -0
- package/skills/protobase/references/reference/files.md +291 -0
- package/skills/protobase/references/reference/forms.md +133 -0
- package/skills/protobase/references/reference/history.md +86 -0
- package/skills/protobase/references/reference/jobs.md +174 -0
- package/skills/protobase/references/reference/layouts.md +126 -0
- package/skills/protobase/references/reference/plugins.md +328 -0
- package/skills/protobase/references/reference/remote-resources.md +198 -0
- package/skills/protobase/references/reference/sidebar.md +51 -0
- package/skills/protobase/references/reference/theme.md +132 -0
- package/skills/protobase/references/reference/ui-config.md +880 -0
- package/skills/protobase/references/reference/user-menu.md +38 -0
- package/skills/protobase/references/reference/versioning.md +91 -0
- package/skills/protobase/references/reference/webhooks.md +136 -0
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
<!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/cli.md: run `bun run docs:skill`, do not edit. -->
|
|
2
|
+
|
|
3
|
+
# CLI
|
|
4
|
+
|
|
5
|
+
Every protobase command, from scaffold, doctor, dev, build, build-plugin, build-serve and serve to users, organizations, token and skill.
|
|
6
|
+
|
|
7
|
+
The `protobase` command comes with `@protobase/cli`. Install it in a project next to the packages its config imports:
|
|
8
|
+
|
|
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 examples/erp protobase <command> # in this repository, for an example
|
|
13
|
+
```
|
|
14
|
+
|
|
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.
|
|
16
|
+
|
|
17
|
+
## How it runs
|
|
18
|
+
|
|
19
|
+
The published `@protobase` packages are JavaScript: each is built with [tsdown](https://tsdown.dev) to ES modules and type declarations in `dist`, one file per source module, and packing them points their `exports`, `types` and `bin` at it (`publishConfig`). The installed `protobase` command (`bin/protobase.mjs`) runs `dist` on Node 22.12 or later, or on Bun. The project's own TypeScript is loaded with Vite on both: `users` and `doctor` import it through Vite's module runner, `dev` serves it and `build` bundles it.
|
|
20
|
+
|
|
21
|
+
In this repository nothing needs a build: the packages' `exports` point at `src`, and the workspace's `protobase` is `bin/protobase-source.mjs`, which imports `src/index.ts`: Bun loads it itself, Node through [tsx](https://tsx.is). `bun run build` builds every package to `dist`.
|
|
22
|
+
|
|
23
|
+
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)).
|
|
24
|
+
|
|
25
|
+
The CLI reads the database with `default_transaction_read_only = on`, so it can never write.
|
|
26
|
+
|
|
27
|
+
## `scaffold`
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
protobase scaffold <connection string | --env DATABASE_URL> [target] [options]
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
`target` is `all` (default), `schema`, `schema.table` or `schema.table.column`. Tables are introspected from `pg_catalog`; `config/<resource>/data.ts` is created or extended.
|
|
34
|
+
|
|
35
|
+
| Option | Effect |
|
|
36
|
+
| --- | --- |
|
|
37
|
+
| `--config <dir>` | config folder, default `config` |
|
|
38
|
+
| `--yes` | accept every proposal, no prompts (required without a TTY) |
|
|
39
|
+
| `--dry-run` | print a diff, write nothing |
|
|
40
|
+
| `--ui` | also write `ui.ts` (`.names()` and `.list()`) |
|
|
41
|
+
| `--ui-list`, `--ui-section <names\|list>` | write only those `ui.ts` sections |
|
|
42
|
+
| `--exclude <schema[.table]>` | skip tables, repeatable |
|
|
43
|
+
|
|
44
|
+
Interactively, each new column shows its proposal: accept, edit (name, type) or ignore (writes `field: null`; key columns cannot be ignored).
|
|
45
|
+
|
|
46
|
+
### Inference
|
|
47
|
+
|
|
48
|
+
| Database | Field |
|
|
49
|
+
| --- | --- |
|
|
50
|
+
| `int2`, `int4` / `int8` | `f.integer()` / `f.bigint()` |
|
|
51
|
+
| `numeric(p,s)` | `f.decimal({ precision, scale })` (unconstrained: 38, 9) |
|
|
52
|
+
| `text`, `varchar`, `bpchar` | `f.text()` |
|
|
53
|
+
| `bool`, `date`, `timestamp(tz)`, `uuid`, `json(b)` | `f.boolean()`, `f.date()`, `f.timestamp()`, `f.uuid()`, `f.json()` |
|
|
54
|
+
| Postgres enum, or a `CHECK (col IN (...))` on text | `f.enum([...])` |
|
|
55
|
+
| foreign key | `f.relation('<resource>')`, `.columns([...])` for a composite key (on its first column) |
|
|
56
|
+
| anything else (`ltree`, arrays, ...) | `f.text().readOnly()` |
|
|
57
|
+
|
|
58
|
+
- `NOT NULL` absent: `.optional()`. Literal default: `.default(v)`.
|
|
59
|
+
- Computed defaults (function, sequence, expression, `GENERATED BY DEFAULT` identity): `.dbDefault()`. It also gets `.readOnly()` when the column is an identity column, a primary-key column, or an audit timestamp (`created_at`, `inserted_at`, `updated_at`, `modified_at`); other computed defaults, such as `order_date DEFAULT current_date`, stay editable. `GENERATED ALWAYS` identity and generated columns are only `.readOnly()`.
|
|
60
|
+
- Leading column of a non-partial index: `.filterable()`; of a btree: also `.sortable()`. Not applied to json.
|
|
61
|
+
- The text field that names a record (`name`, `title`, `number`, `sku`, `email`, `code` or `description`, else the first text field) becomes the resource's `.search(...)` when a non-partial pg_trgm index (`gin_trgm_ops` or `gist_trgm_ops`) serves it, so the [global search](client.md#global-search)) finds its records by name. Without one the API would refuse the search, so it is left out; add the index and run `infer` on a new resource, or add `.search` by hand.
|
|
62
|
+
- Key: primary key (composite supported), else the first unique index with only `NOT NULL` columns, else the table is skipped with a warning.
|
|
63
|
+
- `deleted_at`, `removed_at`, `archived_at` (nullable timestamp/date) become `.softDelete`; `organization_id` and `tenant_id` become `.tenant`.
|
|
64
|
+
- Unique indexes are listed in the doc comment above the resource.
|
|
65
|
+
- Field names are the column names in snake_case; `.column()` is written only when the schema builder's default mapping would not give the column back (always for `hr."EMP_MASTER"`).
|
|
66
|
+
- Resource names are the table name in snake_case, prefixed with the schema on collisions, and exported under their camelCase name (`export const orderLines = resource('order_lines')`). Names already in `config/` win.
|
|
67
|
+
|
|
68
|
+
### Re-running
|
|
69
|
+
|
|
70
|
+
Existing `data.ts` files are edited with ts-morph: only columns that are neither declared nor `null` are added, at the end of `.fields({...})`. Nothing else is rewritten, and key, soft delete and tenant calls are only written when a resource is created. `ui.ts` gets only missing sections. `config/index.ts` gets exports for resources created in the run (all resources when it does not exist yet); existing lines are never touched. A run with nothing new changes nothing. `schema.table.column` on an unscaffolded table scaffolds the whole table.
|
|
71
|
+
|
|
72
|
+
### Drift report
|
|
73
|
+
|
|
74
|
+
After each run, declared fields are compared with the database: a column that no longer exists, a type that no longer fits (a relation fits `integer`/`bigint`/`uuid`/`text`, `currency` and `country` fit `text`), or different enum values. Each entry carries a suggested replacement. Drift is reported, never applied.
|
|
75
|
+
|
|
76
|
+
## `doctor`
|
|
77
|
+
|
|
78
|
+
```sh
|
|
79
|
+
protobase doctor <connection string | --env VAR> [--config <dir>]
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Imports `config/index.ts` and the views of `config/*/ui.ts`, as the config module has them by convention, and checks every exported resource against the database:
|
|
83
|
+
|
|
84
|
+
- error: missing table or column, field type that does not fit the column (a file field needs a text column), table without a usable key, configured key not backed by a unique index
|
|
85
|
+
- error: a read the [scan guard](api.md#safety)) refuses, because no index serves a column it filters, sorts, searches or counts by. Doctor reads each table's indexes from the catalog, as the server does, and judges with the scan guard's own rule every read the API takes and the app makes: a filter on each `.filterable()` field, a sort by each `.sortable()` one, `search()` over the search fields, a role's own records (`.owner()`) and the names a relation shows; each view's list in its order, its filter widgets and their counts, its map and card photos, its related sections, its recent records and a saved search's new records; and each block of a [composed page](layouts.md)) that lists records. Each error is an index to add, with every request that needs it and where it comes from:
|
|
86
|
+
|
|
87
|
+
```
|
|
88
|
+
error agencies: no index serves the column "name", so the API refuses:
|
|
89
|
+
GET /agencies?order_by=name asc ("name" is sortable; the agencies list's order)
|
|
90
|
+
fix: create index on "market"."agencies" ("name");
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Reads are judged as the scan guard's default `reject` mode judges them, for a role that reads every row, such as admin; other access rules are code doctor does not run. A resource on a plain view or a foreign table is not judged, as the scan guard does not judge it.
|
|
94
|
+
- warning: enum values differ
|
|
95
|
+
|
|
96
|
+
Exit code is 1 when there are errors. Run it after the project's migrations and before a new version serves, as a platform's deploy does: a read it fails is one the API would refuse once the version runs. `protobase build` needs no database, so the indexes are doctor's to check.
|
|
97
|
+
|
|
98
|
+
## `dev`
|
|
99
|
+
|
|
100
|
+
```sh
|
|
101
|
+
protobase dev [--port 5173] [--env DATABASE_URL] [--cache-dir <dir>] [--allowed-hosts <hosts>] [--extend <dir>] # run inside a project, e.g. bun run --cwd examples/erp dev
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
One process, one port: 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 `@hono/vite-dev-server` mounts the Hono app from `createAdmin` under `/api`. Open `http://localhost:<port>`; the API reference is at `/api/docs`.
|
|
105
|
+
|
|
106
|
+
- **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 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`.
|
|
107
|
+
- **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).
|
|
108
|
+
- **Login:** real sign-in only, with the `authenticate` and `auth` exported by `protobase.config.ts` (see [Login with Better Auth](auth.md))). A project without an authenticator fails at startup with a message pointing there, one whose auth schema is behind with the tables and columns it lacks (see [`auth migration`](#auth-migration)), and one with a resource whose [events](events.md)) or [history](history.md)) lack their triggers, or whose [comments](comments.md)) lack their table, 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. Create the first admin with `protobase users create`.
|
|
109
|
+
- **Jobs:** with [jobs](jobs.md)) in the config it runs them in its process, once the jobs schema checks out (see [`migration`](#migration)); an edited job runs its new code from the next job on.
|
|
110
|
+
- **Tunnels and other hosts:** Vite only answers `localhost` by default. `--allowed-hosts .trycloudflare.com,app.example.com` adds Host headers (a leading dot matches all subdomains). Hot reload needs no extra setting: the Vite client takes protocol, host and port from the page, so behind an HTTPS tunnel it connects over `wss` on 443 as long as the tunnel forwards WebSockets.
|
|
111
|
+
- **Project discovery**, by convention: `config/index.ts` exports the resources (and views), and every `config/*/ui.ts` export that is not already exported by the index is added as a view. Each `functions/<name>.ts` (or `functions/<name>/index.ts`) is an [API function](../guides/api-functions.md)) at `/api/functions/<name>`. A `protobase.config.ts` in the project root replaces the convention; its default export may contain any of:
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
import * as config from './config'
|
|
115
|
+
export default {
|
|
116
|
+
config, // module whose exports are resources and views
|
|
117
|
+
db, // Kysely instance, instead of DATABASE_URL
|
|
118
|
+
authenticate, // Authenticator, required
|
|
119
|
+
auth, // Better Auth (AdminAuth); its routes are mounted under /api/auth
|
|
120
|
+
functions, // API functions by name, instead of ./functions
|
|
121
|
+
jobs, // module whose exports are jobs (defineJob), see Jobs
|
|
122
|
+
options, // AdminOptions (scan guard, write hooks, ...)
|
|
123
|
+
}
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
`defineConfig` from `@protobase/server` types it, and its `extends` merges other configs in (see [Extending a config](#extending-a-config)).
|
|
127
|
+
- **Project UI:** the app imports `protobase.ui.tsx` from the project root, with hot reload, when it exists (see [Custom components](custom-components.md))): the same contract as the plugin `protobase build` makes of it, built into the dev page instead. Layout files are checked as they load, as `protobase build` checks them.
|
|
128
|
+
- **Theme:** the page links `/protobase.theme.css`, which the dev server answers from the project's [theme](theme.md)), checked as the build checks it, on every request, so an edit shows on the next reload. It links `/protobase.favicon.svg` too, the project's [favicon](theme.md#logo-and-favicon)) or Protobase's.
|
|
129
|
+
- **Extensions:** `--extend <dir>` merges an extension in, its UI built into the dev page beside the project's, to try one out; its files reload like the project's.
|
|
130
|
+
- **Hot reload:** server code, data configs, `ui.ts` views, layouts and `protobase.config.ts` are loaded through Vite's SSR module graph. A change inside the project (or, in this repository, in `packages/server`, `packages/query`, `packages/schema`) rebuilds the API on the next request without a restart; `/meta` and `X-Meta-Version` change, so open tabs refetch. The database pool survives reloads. Newly added `ui.ts` files appear after the next change inside the project.
|
|
131
|
+
|
|
132
|
+
### Extending a config
|
|
133
|
+
|
|
134
|
+
A config can extend others by importing them, like Vite's `defineConfig`. `extends` lists configs merged in order, each after the ones it extends itself, and the extending config last:
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
// protobase.config.ts
|
|
138
|
+
import { defineConfig } from '@protobase/server'
|
|
139
|
+
import tasks from 'some-extension/protobase.config'
|
|
140
|
+
|
|
141
|
+
export default defineConfig({ extends: [tasks], config, auth, authenticate, options: { roles } })
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
```tsx
|
|
145
|
+
// protobase.ui.tsx
|
|
146
|
+
import { defineUi } from '@protobase/ui'
|
|
147
|
+
import * as tasksUi from 'some-extension/protobase.ui'
|
|
148
|
+
|
|
149
|
+
export { UsageChart } from './components/usage-chart'
|
|
150
|
+
export default defineUi({ extends: [tasksUi] })
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
| What | How it merges | The same name twice |
|
|
154
|
+
| --- | --- | --- |
|
|
155
|
+
| `config` exports: resources, views, pages | all kept | an error naming both configs |
|
|
156
|
+
| user menu | at most one among all configs | an error |
|
|
157
|
+
| `options.assistant.tools` | the extended configs' first, in order, then the app's | an error naming the tool and both configs |
|
|
158
|
+
| `jobs` | all kept, by job name | an error naming the job and both configs |
|
|
159
|
+
| `options.writeHooks` | all run, in the same order | |
|
|
160
|
+
| every other value (`db`, `auth`, `authenticate`, `roles`, `assistant.url`, ...) | the app's own; otherwise the last config that sets it | |
|
|
161
|
+
| UI components (exported by name or in `components`), `actions` | all kept | an error naming the name and both configs |
|
|
162
|
+
| UI `shell.actions`, `shell.rightPanel` | all drawn, the extended configs' first | |
|
|
163
|
+
| UI `shell.logo` | the app's own; otherwise the last config that sets it | |
|
|
164
|
+
|
|
165
|
+
A config's `name` names it in these errors; an extension should set one. Nothing is namespaced, so a collision is always an error, never a silent override. Names starting with `Protobase` (components) and `protobase_` (tools) belong to Protobase's own extensions, such as `ProtobaseCloudTask` and `protobase_cloud_create_proposal`; give yours other names. `mergeConfig(...configs)` from `@protobase/server` and `mergeUi(...configs)` from `@protobase/ui` merge the same way in code.
|
|
166
|
+
|
|
167
|
+
## `build`
|
|
168
|
+
|
|
169
|
+
```sh
|
|
170
|
+
protobase build [--out dist] [--bun] [--extend <dir>] # run inside a project, e.g. bun run --cwd examples/erp protobase build
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
Writes the project's deploy bundle, the folder a deployment ships:
|
|
174
|
+
|
|
175
|
+
```
|
|
176
|
+
dist/
|
|
177
|
+
protobase.config.js the config module for serve
|
|
178
|
+
node_modules/ the packages it loads from disk, only when it imports native add-ons
|
|
179
|
+
public/
|
|
180
|
+
index.html, assets/ the admin app: the shell, the same for every project
|
|
181
|
+
plugins/app/ the project's protobase.ui.tsx, built as a plugin
|
|
182
|
+
plugins/<extension>/ each --extend folder's protobase.ui.tsx, built as a plugin
|
|
183
|
+
protobase.theme.css the project's theme, checked and minified; empty without one
|
|
184
|
+
protobase.favicon.svg the project's favicon; Protobase's without one
|
|
185
|
+
protobase.bundle.json the manifest
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
The output folder is not emptied; `public/` and `node_modules/` are replaced on every build. `node_modules/` is deleted only when the previous build's manifest names it, so a build into a folder with a project's own `node_modules` fails instead. Of the project's server config only the config folder runs at build time, `config/index.ts` and `config/*/ui.ts` with what they import, never `protobase.config.ts`, so the build needs no secrets and no database. It is loaded once in Node to check each view against its resource: a filter widget or the chart on a field that is not `.filterable()`, a list sorted by one that is not `.sortable()`, or a list search on a field outside the resource's `.search(...)` fails the build, naming the view and the field, since the API would refuse it once a page asked. Whether an index serves those reads needs the database, which [`doctor`](#doctor) checks. Its browser code is loaded once in Node too: to check its component names (see [The UI](#the-ui)) and to read the field types each plugin registers.
|
|
189
|
+
|
|
190
|
+
A token the [theme](theme.md)) sets that the app does not read prints a `warning:` line, a likely typo; the build still succeeds.
|
|
191
|
+
|
|
192
|
+
By default the bundle runs on Node and on Bun. `--bun` makes it a bundle for Bun only, as the Protobase images and the cloud serve it: Bun's bundler writes the config module (see [the config module](#the-config-module)), so the build needs `bun` on `PATH` and fails without it.
|
|
193
|
+
|
|
194
|
+
### Extensions
|
|
195
|
+
|
|
196
|
+
`--extend <dir>` (repeatable) adds an extension to the bundle without touching the project's files: a folder with a `protobase.config.ts`, a `protobase.ui.tsx` or both. Its `protobase.config.ts` is merged into the config module before the project's own, as if the project [extended](#extending-a-config) it, in the order given. Its `protobase.ui.tsx` becomes one more [plugin](plugins.md)) of the bundle, in `public/plugins/<name>/`, named by its `package.json`'s `name`, else its folder's. A host adds its own assistant tools and widgets to every app it builds this way; to add React code to apps without building them, serve a plugin instead.
|
|
197
|
+
|
|
198
|
+
- The extension's imports of `@protobase/*` resolve from the project, so it runs on the app's own versions; `react`, `react-dom` and `@protobase/ui` are the app's at runtime, as for every plugin. Everything else it imports resolves from its own folder and is built into its plugin, with a stylesheet of the classes its files use.
|
|
199
|
+
- A component, action handler or field type that the extension and the project both define fails the build, naming both. To find them, the build loads the merged UI configs once in Node: only browser code, which needs no secrets. The server config still does not run at build time, so a tool both define fails when the bundle is served, naming both.
|
|
200
|
+
- An error names a config by its `name`, otherwise by its file. Two extensions whose plugins would have one name fail the build.
|
|
201
|
+
|
|
202
|
+
### The manifest
|
|
203
|
+
|
|
204
|
+
`protobase.bundle.json` is the contract between a bundle and the host that serves it:
|
|
205
|
+
|
|
206
|
+
```json
|
|
207
|
+
{
|
|
208
|
+
"version": 3,
|
|
209
|
+
"protobase": "0.12.0",
|
|
210
|
+
"server": "protobase.config.js",
|
|
211
|
+
"public": "public",
|
|
212
|
+
"spa": "index.html",
|
|
213
|
+
"api": ["/api"],
|
|
214
|
+
"theme": "protobase.theme.css",
|
|
215
|
+
"plugins": [
|
|
216
|
+
{ "name": "app", "path": "plugins/app/plugin.json", "api": 1, "protobase": ">=0.12.0", "fields": { "steps": ["enum"] } }
|
|
217
|
+
],
|
|
218
|
+
"shell": { "protobase": "0.12.0", "pluginApi": 1, "paths": ["/index.html", "/assets"] },
|
|
219
|
+
"nodeModules": "node_modules"
|
|
220
|
+
}
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
- `protobase` is the Protobase version that built the bundle. The serve runtime serves only bundles of a compatible version: below 1.0 the same minor, from 1.0 the same major and the runtime's minor or an older one (see [Versioning](versioning.md#bundles-and-runtimes))).
|
|
224
|
+
- `server`, `public` and `nodeModules` are relative to the bundle folder; `spa`, `theme` and each plugin's `path` to `public`.
|
|
225
|
+
- `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.
|
|
226
|
+
- `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, of a release every plugin of the bundle loads in, may serve its own for those paths instead (see [The UI](#the-ui)), so the app gets that release's fixes without a rebuild.
|
|
227
|
+
- `theme` is the project's [theme](theme.md)), which the app links at `/protobase.theme.css`. It is always there, empty when the project has none.
|
|
228
|
+
- `nodeModules` is present only when the config module imports [native packages](#native-packages). It is always the `node_modules` folder beside `server`, where Bun and Node resolve the module's imports from, and holds plain packages: JavaScript, `package.json` files and native binaries for linux x64 and arm64 (glibc), which the runtime loads with `dlopen`. A host keeps it next to the server module and must not mount it `noexec` (an add-on there then fails with `failed to map segment from shared object`). Its binaries link nothing but glibc, `libstdc++.so.6`, `libgcc_s.so.1` and libraries in the bundle itself, so the run image must have those three. Without `nodeModules`, the server module is the only file the runtime reads.
|
|
229
|
+
- `api` lists the path prefixes the server answers. A path is under a prefix when it equals it or continues it with `/` (`/api` covers `/api/meta` and `/api/v1:batchWrite`, not `/apiary`). It is always `["/api"]`: a bundle assumes the API lives under `/api`, with the resources at the default `basePath` `/api/v1`, `/api/meta`, the docs, the API functions and the built-in assistant beside them and Better Auth at `/api/auth`. The serve runtime refuses a config that sets another `options.basePath`.
|
|
230
|
+
- Every other path is the UI's. A `GET` or `HEAD` for a file in `public` gets that file; a folder gets its `index.html`. Otherwise a request whose `Accept` header contains `text/html` (a navigation) gets `spa` with status 200, so deep links such as `/orders/42` load the app; anything else gets 404. Other methods get 405.
|
|
231
|
+
- Files under an `assets/` folder, `public/assets/` and each plugin's, are named by their content hash and never change: serve them with `Cache-Control: public, max-age=31536000, immutable`, and everything else, `index.html`, each `plugin.json` and the theme, with `no-cache`.
|
|
232
|
+
- `version` is the format of the manifest, not a Protobase version. A host that does not know it must refuse the bundle. Version 3 replaced version 2 when the project's UI became a plugin beside a prebuilt app, and gained `plugins`, `theme` and `shell`; version 2 replaced version 1 when the config module started to import [every module the runtime supplies](#the-config-module), and gained `nodeModules`. `protobase serve` refuses an older bundle; rebuild it with `protobase build`.
|
|
233
|
+
|
|
234
|
+
### The UI
|
|
235
|
+
|
|
236
|
+
`public/` holds two parts that are built apart.
|
|
237
|
+
|
|
238
|
+
- **The shell**, `index.html` and `assets/`: 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, and its tab icon from `/protobase.favicon.svg`.
|
|
239
|
+
- **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))).
|
|
240
|
+
|
|
241
|
+
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.
|
|
242
|
+
|
|
243
|
+
### The config module
|
|
244
|
+
|
|
245
|
+
`protobase.config.js` is one ES module. The entry is found as `protobase dev` finds it: the default export of `protobase.config.ts`, with `config` taken from the convention (`config/index.ts` plus `config/*/ui.ts`) and `functions` from `functions/` when it exports none.
|
|
246
|
+
|
|
247
|
+
- Vite bundles the config into plain ES modules in UTF-8, which Node and Bun both load as they are.
|
|
248
|
+
- With `--bun`, Vite writes to a scratch folder and `bun build --target bun` writes the final module. Bun's output starts with `// @bun`, which tells Bun the file is already plain JavaScript: Bun neither transpiles it nor writes its transpiler cache. Bun reads such a file as Latin-1, so only Bun's own output can carry that line: its bundler writes non-ASCII text as escapes (`€` as `\u20AC`). Raw UTF-8 with that line would load as `â¬`.
|
|
249
|
+
- The `@protobase` packages and every package in their `dependencies` belong to the serve runtime: their imports stay `import` statements and the runtime supplies them, so the bundle carries no copy and shares the runtime's. It supplies these modules:
|
|
250
|
+
|
|
251
|
+
| Modules | |
|
|
252
|
+
| --- | --- |
|
|
253
|
+
| `@protobase/schema`, `@protobase/layout`, `@protobase/layout/jsx-runtime`, `@protobase/query`, `@protobase/server` | the server entry points of the `@protobase` packages, and what [layout files](layouts.md)) compile to |
|
|
254
|
+
| `kysely`, `kysely/helpers/postgres`, `pg`, `postgres` | the database |
|
|
255
|
+
| `better-auth`, `hono`, `jose`, `zod`, `aip-parsers`, `@hono/node-server`, `@scalar/hono-api-reference` | the main entry of each other dependency the `@protobase` packages run on the server |
|
|
256
|
+
| `hono/cors`, `hono/http-exception`, `hono/validator` | Hono middleware for [API functions](../guides/api-functions.md)) |
|
|
257
|
+
| `react`, `react/jsx-runtime`, `@react-email/render` | what [email templates](email.md#in-a-bundle)) render with, so a template's component and the renderer share one React |
|
|
258
|
+
|
|
259
|
+
`react-email` is a dependency of `@protobase/server` that the runtime does not supply: the server loads it only to send an auth email, so a config that imports it inlines its own copy, like any other package.
|
|
260
|
+
|
|
261
|
+
Importing any other `@protobase` package or dependency of one (`@protobase/ui`, `react-dom`, `better-auth/plugins`, `zod/v4`, ...) fails the build with this list, also from inside an inlined package, when the finished bundle still imports it: an inlined package may re-export a module that imports one, as `react-email` does with `tailwindcss`, as long as the project leaves that export unused. So does a copy the project installs in another version than the `@protobase` packages use (another major, or another minor below 1.0), which the runtime's would replace. The list is `packages/cli/src/serve/host-module-ids.ts`; the set of packages comes from the `package.json` of `@protobase/cli` and of every `@protobase` package it depends on.
|
|
262
|
+
- Packages with a native add-on stay imports too, and the bundle carries them in `node_modules/` (see [Native packages](#native-packages)). Node's built-in modules stay imports.
|
|
263
|
+
- Everything else (the project's files and its other packages) is inlined. Nothing is minified.
|
|
264
|
+
- Layout files (`@jsxImportSource @protobase/layout`) compile to calls of `@protobase/layout/jsx-runtime`, for production whatever `NODE_ENV` says. The build refuses one with a function, class, `new` value or hook in its JSX, naming the file, line and column ([what a layout may hold](layouts.md#what-a-layout-may-hold))).
|
|
265
|
+
- The default export is the project config merged with the configs it [extends](#extending-a-config), with `config` always set:
|
|
266
|
+
|
|
267
|
+
```ts
|
|
268
|
+
export default { config, authenticate, auth?, functions?, options?, db? } // as protobase.config.ts exports it
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
The serve runtime reads the environment when it imports the module, on the host.
|
|
272
|
+
|
|
273
|
+
### Native packages
|
|
274
|
+
|
|
275
|
+
A package with a native add-on cannot be inlined: it loads a compiled `.node` file from its own folder at runtime. The build recognises one by a `.node` file or a `binding.gyp` in it, or by optional dependencies that carry the add-on per platform and name a linux one (`@node-rs/argon2-linux-x64-gnu`, sharp's `@img/sharp-linux-x64`). For each such package the config module imports, directly or through an inlined package:
|
|
276
|
+
|
|
277
|
+
- The import stays an import, which resolves at runtime to `node_modules/<package>` beside the config module.
|
|
278
|
+
- The package and everything it needs at runtime (its dependencies and the optional ones that are installed, recursively) are copied to `node_modules/` as one tree: each package at the top, a second version of one under the package that needs it. Files of a package are copied as they are, except native binaries.
|
|
279
|
+
- Every native binary in them (ELF, Mach-O or PE, told by its headers, not its name) is copied only when it is for linux x64 or linux arm64 with glibc: the run image is Bun's distroless image (Debian) for amd64 and arm64, and a bundle may run on either. Binaries for macOS, Windows, musl or other architectures stay behind, as do platform packages for them (by their `os`, `cpu` and `libc` fields).
|
|
280
|
+
- Every add-on needs a `.node` binary for both, in its package or in its platform packages. Otherwise the build fails and names each package, the platforms it misses and the ones it has. It never ships a binary built for the wrong platform.
|
|
281
|
+
- Every binary it copies may link only glibc's libraries, the C++ runtime (`libstdc++.so.6`, `libgcc_s.so.1`) and libraries the bundle carries itself (sharp's libvips); otherwise the build fails and names the binary and the library. Every add-on in common use links `libgcc_s` and, when written in C++, `libstdc++`. Bun's distroless image has glibc only, so the run image adds those two (Debian's `libgcc-s1` and `libstdc++6`); without them an add-on fails to load (`libstdc++.so.6: cannot open shared object file`).
|
|
282
|
+
|
|
283
|
+
What that means for a package:
|
|
284
|
+
|
|
285
|
+
- **Prebuilt binaries for every platform inside the npm package** (prebuildify and node-gyp-build: `argon2`, `bcrypt` 6, `bufferutil`): builds anywhere, macOS included.
|
|
286
|
+
- **Per-platform optional packages** (napi-rs, such as `@node-rs/argon2`, and sharp): a package manager installs only the build machine's, so the build fails until the linux ones are installed as well. With Bun, `bun install --os='*' --cpu='*'` installs every platform's. With pnpm, in `pnpm-workspace.yaml`:
|
|
287
|
+
|
|
288
|
+
```yaml
|
|
289
|
+
supportedArchitectures:
|
|
290
|
+
os: [current, linux]
|
|
291
|
+
cpu: [current, x64, arm64]
|
|
292
|
+
libc: [current, glibc]
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
- **Built or downloaded on install** (node-gyp from source, prebuild-install such as `better-sqlite3`, node-pre-gyp): only the build machine's binary exists, so the build fails, on a linux machine too, which has one architecture.
|
|
296
|
+
|
|
297
|
+
The bundle then runs on linux only: `protobase serve` of it on macOS cannot load the add-ons. Check it in a linux container of a run image with the C++ runtime, built from this `Dockerfile` (`docker build -t protobase-run .`, with `--platform linux/amd64` for the other architecture):
|
|
298
|
+
|
|
299
|
+
```dockerfile
|
|
300
|
+
FROM debian:trixie-slim AS libs
|
|
301
|
+
RUN d=/usr/lib/$(uname -m)-linux-gnu && mkdir -p /out$d && cp -a $d/libstdc++.so.6* $d/libgcc_s.so.1 /out$d/
|
|
302
|
+
FROM oven/bun:1.4.2-distroless
|
|
303
|
+
COPY --from=libs /out/ /
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
```sh
|
|
307
|
+
docker run --rm -p 8787:8787 -e DATABASE_URL -e BETTER_AUTH_SECRET \
|
|
308
|
+
-v "$PWD/dist:/app:ro" -v "$PWD/protobase-serve.js:/opt/protobase/protobase-serve.js:ro" \
|
|
309
|
+
protobase-run --no-install /opt/protobase/protobase-serve.js /app/protobase.config.js
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
## `build-plugin`
|
|
313
|
+
|
|
314
|
+
```sh
|
|
315
|
+
protobase build-plugin [dir] [--out <dir>] [--name <name>]
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
Builds the [plugin](plugins.md)) in `dir` (default: the current folder), whose entry is its `protobase.ui.tsx`, into `--out` (default: `dir/dist`):
|
|
319
|
+
|
|
320
|
+
```
|
|
321
|
+
dist/
|
|
322
|
+
plugin.json what the app reads first
|
|
323
|
+
assets/index-<hash>.js the plugin's module, and its chunks beside it
|
|
324
|
+
assets/styles-<hash>.css the utilities its files use
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
- The output folder is emptied first, so it must not be the plugin's folder or hold it.
|
|
328
|
+
- 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.
|
|
329
|
+
- 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)`).
|
|
330
|
+
- `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))).
|
|
331
|
+
|
|
332
|
+
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 `options.plugins` (see [loading](plugins.md#loading))).
|
|
333
|
+
|
|
334
|
+
## `build-serve`
|
|
335
|
+
|
|
336
|
+
```sh
|
|
337
|
+
protobase build-serve [--out dist/protobase-serve.js] [--bun] # or, in this repository: bun run build:serve
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
Bundles the serve runtime (`@protobase/cli`'s `src/serve/main.ts`) and all its dependencies into one file, about 3 MB. A host needs Bun and this file, nothing else. `--bun` has Bun's bundler write the file, as for [`build`](#build), and needs `bun` on `PATH`; the `protobase` image is built from such a file. The file carries the Protobase version it was built from, which decides [the bundles it serves](versioning.md#bundles-and-runtimes)).
|
|
341
|
+
|
|
342
|
+
## `serve`
|
|
343
|
+
|
|
344
|
+
```sh
|
|
345
|
+
bun --no-install protobase-serve.js <bundle>/protobase.config.js # production, under Bun: the API
|
|
346
|
+
protobase serve <bundle>/protobase.config.js # the same, with the CLI on Node or Bun
|
|
347
|
+
protobase serve <bundle> # the whole bundle as a host serves it, e.g. bun run --cwd examples/erp serve
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
Serves the API of a bundle from `protobase build` and owns the process around it. Given the bundle folder, `protobase serve` also serves its UI by [the manifest's rules](#the-manifest), so a bundle can be checked locally exactly as the host will serve it.
|
|
351
|
+
|
|
352
|
+
**Its own shell.** Given the bundle folder, `protobase serve` serves the manifest's `shell.paths`, the root and navigations from a shell of its own when it has one: the folder `PROTOBASE_SHELL` names, else the prebuilt shell of the installed `@protobase/ui` (none when the CLI runs from this repository's sources). It does so only when every plugin of the bundle loads in that shell's release; otherwise it serves the bundle's copy. Its startup output says which (`app the app of Protobase 0.12.3 from ...`). The plugins, the theme and the API always come from the bundle.
|
|
353
|
+
|
|
354
|
+
| Variable | |
|
|
355
|
+
| --- | --- |
|
|
356
|
+
| `DATABASE_URL` | the API's pool (Kysely over `pg`, 10 connections); not needed when the config exports `db` |
|
|
357
|
+
| `PROTOBASE_DB_CONNECTIONS` | the connections that pool opens, such as the database's limit for the app; default 10. [API functions](../guides/api-functions.md)) and [jobs](jobs.md)) hold at most one less, so a long import leaves a connection to page and API requests |
|
|
358
|
+
| `PORT` | default 8787 |
|
|
359
|
+
| `REQUEST_LOG` | `true` logs every request; default `false` |
|
|
360
|
+
| `PROTOBASE_SMTP_URL` | the SMTP server for password-reset mail, emailed sign-in and two-factor codes and the app's own [email](email.md)), credential included: `smtp://user:password@host:587` (STARTTLS when offered) or `smtps://...:465`; without it they are off ([Password reset](auth.md#password-reset)), [Emailed sign-in codes](auth.md#emailed-sign-in-codes))) |
|
|
361
|
+
| `PROTOBASE_MAIL_FROM` | the sender of that mail, a plain address such as `noreply@admin.example.com`; set with `PROTOBASE_SMTP_URL` or not at all |
|
|
362
|
+
| `PROTOBASE_APP_NAME` | the app's name, such as `Property Finder`: what its auth emails, its sidebar and its browser tabs call it, and the sender's display name of its mail ([`appName`](auth.md#configuration))) |
|
|
363
|
+
| `PROTOBASE_SIGN_IN_ISSUER`, `PROTOBASE_SIGN_IN_CLIENT_ID`, `PROTOBASE_SIGN_IN_CLIENT_SECRET` | an OpenID Connect provider people who have an account can sign in with; all three or none. `PROTOBASE_SIGN_IN_PROVIDER` and `PROTOBASE_SIGN_IN_NAME` are optional ([Platform sign-in provider](auth.md#platform-sign-in-provider))) |
|
|
364
|
+
| `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))) |
|
|
365
|
+
| `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))) |
|
|
366
|
+
| `PROTOBASE_CORS_ORIGINS` | other websites whose browser code may call the API, `*` or comma separated origins ([CORS](api.md#cors))) |
|
|
367
|
+
| `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 |
|
|
368
|
+
| `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 |
|
|
369
|
+
| `PROTOBASE_SENTRY_DSN` | the DSN of a Sentry-compatible error tracker the app's server and admin app send their errors to, after `options.errorReporting` ([Error reporting](api.md#error-reporting))); without it nothing is sent |
|
|
370
|
+
| `PROTOBASE_MAP_STYLE_URL` | the URL of the MapLibre style the record page's [maps](ui-config.md#maps)) are drawn with, after `options.maps`; without it there are no maps |
|
|
371
|
+
| `PROTOBASE_SOURCES` | other Protobase APIs whose resources the app draws as its own, a JSON list of `{ "url", "label", "resources", "roles"? }` after `options.sources` ([Remote resources](remote-resources.md#declaring-a-source))) |
|
|
372
|
+
| `PROTOBASE_FILES_<NAME>`, `PROTOBASE_FILES_RETENTION`, `PROTOBASE_FILES_SECRET` | [file providers](files.md#providers)) and their settings, over `files` in the config; a bucket's credentials in `PROTOBASE_FILES_<NAME>_ACCESS_KEY_ID` and `_SECRET_ACCESS_KEY` |
|
|
373
|
+
| `PROTOBASE_FILES_CLEANUP_MINUTES` | minutes between runs of the [scheduled file deletes](files.md#deleting-files)), default 60; 0 leaves them to `protobase files cleanup` or the platform |
|
|
374
|
+
| `PROTOBASE_JOBS` | `false` runs none of the app's [jobs](jobs.md)) in this process, which still enqueues them; default `true` |
|
|
375
|
+
| `PROTOBASE_STARTUP_CHECKS` | `false` skips the startup reads of the auth, changes, webhooks and jobs schemas, which make a start slower; default `true`. Set it only to restart a bundle that already started on this database, such as when a platform wakes a sleeping app, never for a new bundle or after its migrations ran |
|
|
376
|
+
| `PROTOBASE_SHELL` | `protobase serve <bundle>` only: a shell folder, such as the `/opt/protobase/shell` of a protobase image or `@protobase/ui`'s `dist/shell`, to serve the bundle's app from (see [its own shell](#serve)) |
|
|
377
|
+
| `PROTOBASE_JOBS_DRAIN_TOKEN` | the operator's bearer token for `POST /api/jobs/drain`, which [runs the due jobs](jobs.md#hosts-that-sleep)) of a host that lets the app sleep; without it there is no such endpoint |
|
|
378
|
+
|
|
379
|
+
Better Auth and other settings are the project's own variables (`BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, ...), read by its config. `protobase serve` also loads the nearest `.env`, like `dev`; the runtime takes the environment as it is.
|
|
380
|
+
|
|
381
|
+
- **Routes:** `createAdmin` (`/api/v1`, `/api/meta`, `/api/functions/*`, `/api/auth/*`, ...) and `GET /health`, which answers `{"status":"ok"}` without a token and without touching the database. The runtime never serves the UI; `protobase serve <bundle>` serves `public/` for every path outside the manifest's `api` and `/.well-known/webauthn`, after `/health`.
|
|
382
|
+
- **Plugins:** the runtime reads the manifest's `plugins`: `/api/meta` names them, and a view that shows a field with one of their [field types](plugins.md#field-types)) that does not show the field's storage type stops startup, naming the view, the field and what the field type shows.
|
|
383
|
+
- **Version:** before loading the config module, the runtime reads `protobase.bundle.json` beside it and refuses a bundle built by a Protobase version it does not serve, or one without a version, with an error naming both versions (see [Versioning](versioning.md#bundles-and-runtimes))). A config module needs its manifest beside it.
|
|
384
|
+
- **Startup:** a bundle without a default export, `config` or `authenticate`, or with an `options.basePath` other than `/api/v1`, stops startup with a one-line error and exit code 1, as does a missing `DATABASE_URL`, an auth schema that lacks a table or column (see [`auth migration`](#auth-migration)), a resource whose [events](events.md)) or [history](history.md)) lack their triggers or have out-of-date ones, or a missing history or [comments](comments.md#the-table)) table, a jobs schema that is missing or behind for a config with [jobs](jobs.md#the-jobs-schema)) (see [`migration`](#migration)), an [AI field or action](ai.md#the-model)) without a model key, or a taken port; `PROTOBASE_STARTUP_CHECKS=false` skips the checks of those schemas and the key. `protobase serve listening on port <port>` means it is ready.
|
|
385
|
+
- **Jobs:** with [jobs](jobs.md)) in the config it runs them beside the API, unless `PROTOBASE_JOBS=false`, and with `PROTOBASE_JOBS_DRAIN_TOKEN` it answers `POST /api/jobs/drain` for the operator.
|
|
386
|
+
- **Shutdown:** the first SIGTERM or SIGINT stops accepting connections, waits for open requests, gives running jobs 30 seconds to finish, drains the pool `serve` created (a `db` the config exports is the project's to close) and exits with 0.
|
|
387
|
+
- **Host modules:** under Bun, the runtime registers [the modules it supplies](#the-config-module) as virtual modules, so the bundle needs no `node_modules` for them. `protobase serve`, on Node or Bun, resolves them from the `node_modules` next to the bundle, so keep the bundle inside the project. Native packages load from the bundle's own `node_modules/` under both.
|
|
388
|
+
- **Read-only hosts:** nothing is written: no install (`--no-install`), and for a bundle built with `--bun` no transpiling and so no transpiler cache. A bundle with `node_modules/` needs its folder mounted without `noexec`, since its add-ons are mapped as executable code.
|
|
389
|
+
|
|
390
|
+
## `worker`
|
|
391
|
+
|
|
392
|
+
```sh
|
|
393
|
+
protobase worker <bundle> # a bundle from `protobase build`: its folder or its protobase.config.js
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
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` unless the config exports `db`. Run it beside a `serve` with `PROTOBASE_JOBS=false`, from the same bundle. `protobase worker running <n> jobs` means it is ready.
|
|
397
|
+
|
|
398
|
+
## `files cleanup`
|
|
399
|
+
|
|
400
|
+
```sh
|
|
401
|
+
protobase files cleanup # the project in the current directory
|
|
402
|
+
protobase files cleanup <bundle> # a bundle from `protobase build`: its folder or its protobase.config.js
|
|
403
|
+
```
|
|
404
|
+
|
|
405
|
+
Runs the [scheduled file deletes](files.md#deleting-files)) that are due: replaced and cleared files past their retention, and uploads nobody saved. A file a row references again is kept. It prints each file it deleted or kept. It reads the `.env` nearest the current directory and needs `DATABASE_URL` unless the config exports `db`. `protobase serve` runs the same every hour; this is for cron, or a host that turns that off.
|
|
406
|
+
|
|
407
|
+
## `users`
|
|
408
|
+
|
|
409
|
+
```sh
|
|
410
|
+
protobase users create <email> [--name <name>] [--role <role>] [--password-stdin | --generate-password] [--github-id <id>]
|
|
411
|
+
[--organization <slug> [--org-role <role>] [--app-roles <a,b>]]
|
|
412
|
+
protobase users list
|
|
413
|
+
protobase users roles
|
|
414
|
+
protobase users set-role <email> <role>
|
|
415
|
+
protobase users disable <email> # and: enable <email>
|
|
416
|
+
protobase users delete <email> [--yes]
|
|
417
|
+
```
|
|
418
|
+
|
|
419
|
+
Run inside a project whose `protobase.config.ts` exports `auth` (Better Auth). 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 (`createAuth({ roles, defaultRole })`). `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.
|
|
420
|
+
|
|
421
|
+
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. 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.
|
|
422
|
+
|
|
423
|
+
`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 within their lifetime (15 minutes by default), and `protobase token` refuses disabled users. `enable` lifts the ban. `protobase dev` prints "No users yet. Create the first admin with: protobase users create you@example.com" at startup while the user table is empty.
|
|
424
|
+
|
|
425
|
+
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.
|
|
426
|
+
|
|
427
|
+
## `organizations`
|
|
428
|
+
|
|
429
|
+
```sh
|
|
430
|
+
protobase organizations list
|
|
431
|
+
protobase organizations create <name> --owner <email> [--slug <slug>] [--id <id>] [--members all]
|
|
432
|
+
protobase organizations add-member <organization> <email> [--org-role <role>] [--app-roles <a,b>]
|
|
433
|
+
protobase organizations set-roles <organization> <email> [--org-role <role>] [--app-roles <a,b>]
|
|
434
|
+
protobase organizations remove-member <organization> <email>
|
|
435
|
+
protobase organizations add-app-role <role> --to owners
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
For a project with [organizations](auth.md#organizations)); `<organization>` is a slug or an id. The host acts as a superuser, so it may give any role. `create` makes `--owner` the owner with every app role; `--id` keeps an existing tenant value, and `--members all` adds every other user, superusers as owners and everyone else as a member with their global roles moved onto the membership, for an app that ran as one organization. `remove-member` and `set-roles` refuse to leave an organization without an owner. `add-app-role` gives a role the project added later to every owner.
|
|
439
|
+
|
|
440
|
+
## `migration`
|
|
441
|
+
|
|
442
|
+
```sh
|
|
443
|
+
protobase migration [--dir db/migrations] [--extend <dir>]
|
|
444
|
+
```
|
|
445
|
+
|
|
446
|
+
Writes what the database still needs for every feature the config enables, as the project's next migrations in `--dir`, one file per feature: the auth schema when `protobase.config.ts` exports `auth` (`NNN_auth.sql`, as [`auth migration`](#auth-migration) writes it), the [jobs schema](jobs.md#the-jobs-schema)) when the config has jobs or a resource has events, history, comments or an [AI field](ai.md)) (`NNN_jobs.sql`), the [capture of events](events.md#migrations-and-startup)) and the [history table](history.md#the-table)) (`NNN_changes.sql`), the [comments table](comments.md#the-table)) (`NNN_comments.sql`), and the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app)) of `webhooks()` (`NNN_webhooks.sql`). It compares the database, with the project's migrations applied, with the config, merged with the configs it extends and those of `--extend` as `dev` merges them, and writes nothing when the database is current. Apply the files with the project's other migrations. It reads the `.env` nearest the current directory and needs `DATABASE_URL` unless the config exports `db`.
|
|
447
|
+
|
|
448
|
+
```sh
|
|
449
|
+
bun run db:migrate # the database at the project's current schema
|
|
450
|
+
bun run protobase migration # writes db/migrations/NNN_auth.sql, NNN_jobs.sql, NNN_changes.sql, ... for what the config enables
|
|
451
|
+
bun run db:migrate # applies them
|
|
452
|
+
```
|
|
453
|
+
|
|
454
|
+
## `auth migration`
|
|
455
|
+
|
|
456
|
+
```sh
|
|
457
|
+
protobase auth migration [--dir db/migrations] [--name auth]
|
|
458
|
+
```
|
|
459
|
+
|
|
460
|
+
Run inside a project whose `protobase.config.ts` exports `auth`, against its database with the project's migrations applied. It compares the database with the tables, columns and indexes Better Auth needs (with Protobase's plugins and the project's own) and writes what is missing as the next migration in `--dir`: `009_auth.sql` after `008_...`. Nothing is written when the schema is current. The file only adds, never drops; apply it with the project's other migrations. For a store with the camelCase names of Protobase 0.6 it writes their rename to snake_case instead, and the startup check asks for that. See [migrations](auth.md#migrations)).
|
|
461
|
+
|
|
462
|
+
## `token`
|
|
463
|
+
|
|
464
|
+
```sh
|
|
465
|
+
protobase token <email> [--ttl 15m]
|
|
466
|
+
```
|
|
467
|
+
|
|
468
|
+
Prints a bearer token (JWT, signed with the project's Better Auth keys, same claims as a browser token) for an existing user. The lifetime is `30s`, `15m`, `24h`, ... up to 24 hours, default 15 minutes. Only the token goes to stdout and errors go to stderr, so it composes in scripts:
|
|
469
|
+
|
|
470
|
+
```sh
|
|
471
|
+
curl -H "Authorization: Bearer $(protobase token me@x)" http://localhost:5173/api/v1/orders?page_size=1
|
|
472
|
+
```
|
|
473
|
+
|
|
474
|
+
## `skill`
|
|
475
|
+
|
|
476
|
+
```sh
|
|
477
|
+
protobase skill install
|
|
478
|
+
```
|
|
479
|
+
|
|
480
|
+
Copies the protobase agent skill of this CLI's version into the current project, to `.agents/skills/protobase/` (read by Codex, Cursor, OpenCode and Amp) and `.claude/skills/protobase/` (read by Claude Code): a short `SKILL.md` with the everyday workflow and the checks before calling a change done, and the guides and reference of this version as files it points to. It replaces an earlier copy, and refuses to touch a folder of that name that holds another skill. Commit the folders, and run the command again after upgrading the `@protobase` packages. The skill also ships in `node_modules/@protobase/cli/skills`, where the `skills` CLI's `experimental_sync` finds it.
|
|
481
|
+
|
|
482
|
+
## ERP example
|
|
483
|
+
|
|
484
|
+
```sh
|
|
485
|
+
bun run db:up && bun run --cwd examples/erp db:migrate && bun run --cwd examples/erp db:seed --scale small
|
|
486
|
+
bun run --cwd examples/erp protobase scaffold postgres://protobase:protobase@localhost:55432/protobase \
|
|
487
|
+
--yes --ui --exclude auth --exclude public.schema_migrations --exclude public.seed_info
|
|
488
|
+
bun run --cwd examples/erp protobase doctor postgres://protobase:protobase@localhost:55432/protobase
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
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.
|
|
492
|
+
|
|
493
|
+
The integration test (`packages/cli/tests/scaffold/scaffold.integration.test.ts`) scaffolds into a temp folder and is skipped when the database is unreachable.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
<!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/client.md: run `bun run docs:skill`, do not edit. -->
|
|
2
|
+
|
|
3
|
+
# Client and live UI
|
|
4
|
+
|
|
5
|
+
The typed fetch client, the TanStack Query hooks and the admin app that runs on them.
|
|
6
|
+
|
|
7
|
+
`@protobase/client` is a typed fetch client for `/api/v1`; `@protobase/ui` wraps it in TanStack Query hooks (`src/data`) and runs the admin on both (`src/app`). Everything runs in the browser (or anywhere with `fetch`) and imports only `@protobase/schema` and `@protobase/layout`'s types.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { createClient } from '@protobase/client'
|
|
11
|
+
import { where } from '@protobase/schema'
|
|
12
|
+
|
|
13
|
+
const api = createClient({ baseUrl: '/api/v1', onMetaVersion: (version) => { /* refetch meta when it changes */ } })
|
|
14
|
+
|
|
15
|
+
const page = await api.list(orders, { filter: where.eq('status', 'draft'), orderBy: 'created_at desc', pageSize: 50, fields: ['id', 'number'] })
|
|
16
|
+
const { record, etag } = await api.get(orders, id)
|
|
17
|
+
await api.update(orders, id, { status: 'shipped' }, etag) // 412 rejects with PreconditionFailedError
|
|
18
|
+
```
|
|
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).
|
|
21
|
+
|
|
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
|
+
|
|
24
|
+
## The admin app
|
|
25
|
+
|
|
26
|
+
`<App baseUrl="/api/v1" />` renders the shell from `/api/meta` (beside the API, so `createClient` derives it from `baseUrl`) and routes `/:page` ([composed pages](layouts.md))), `/:resource` (list) and `/:resource/:key` (record); it opens on the first page, or the first resource. Its own pages sit under `/-/`, which no page or resource name takes: `/-/account` (the user's passkeys and two-factor authentication) 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 above the shell. `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: `?filter=` (AIP-160), `?order_by=`, `?layout=panel`, `?calendar=month,2026-10-01`, the month or week a [calendar](ui-config.md#calendars)) shows, and `?saved_search=`, the [saved search](ui-config.md#saved-searches)) the list was opened from. Views come from `examples/*/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)).
|
|
27
|
+
|
|
28
|
+
## Global search
|
|
29
|
+
|
|
30
|
+
The search box in the top bar looks in every resource the user can read that has search fields (`.search(...)` in its [data config](data-config.md#resource))) and a view in the sidebar or the user menu. Its placeholder names them, such as "Search organizations, services and more"; an app with no page or resource has no box.
|
|
31
|
+
|
|
32
|
+
From two characters on, it asks each of those resources' list API for `search("<text>")` (every word, even part of one, in one of the search fields; the end of a [`digitsEnd`](data-config.md#resource)) field) with the user's token, five records each, so row filters and hidden fields apply exactly as on the lists and it never offers a record the user could not open. Before the records, under **Go to**, are the sidebar's pages and lists whose names hold the text ("stock" finds Stock levels), and under **Create** a **New ...** for each resource the user may create whose name holds it, with or without "new" before it ("order" or "new ord" finds New order), five of each. The records are grouped by resource, two lines each: a bold title, the view's [`searchResult`](ui-config.md#names-and-columns)) title fields joined by spaces (default: the record's title), and a subtitle, the view's `searchResult` subtitle (default: the first search field not in the title). When the text matched a search field that neither line shows, such as a phone number, that field is the subtitle instead.
|
|
33
|
+
|
|
34
|
+
Each result is a link: a click or Enter opens it and closes the list, Enter the first result when none is highlighted, and Cmd or Ctrl click, a middle click or the browser's menu open it in a new tab. The text stays, so focusing the box again shows the same results without asking the server; only changed text searches again. While the box has text, a clear button replaces the ⌘K hint. ⌘K (Ctrl+K) focuses the box, or opens it on a phone; the arrow keys move through the results, and Escape clears the box, then leaves it. A resource whose search fails says so in its group.
|
|
35
|
+
|
|
36
|
+
## Live stories
|
|
37
|
+
|
|
38
|
+
`bun run db:up && bun run --cwd examples/erp serve`, then `bun run storybook`. Storybook proxies `/api` to `PROTOBASE_API` (default `http://localhost:8787`); pick another API in the toolbar. Without a server the stories say so. `bun run screenshots:live` writes `screenshots/live/`.
|