@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.
Files changed (49) hide show
  1. package/dist/main.js +2 -0
  2. package/dist/package.js +1 -1
  3. package/dist/skill/install.js +29 -0
  4. package/dist/skill/register.js +14 -0
  5. package/package.json +8 -7
  6. package/skills/protobase/SKILL.md +89 -0
  7. package/skills/protobase/references/getting-started.md +78 -0
  8. package/skills/protobase/references/guides/api-functions.md +240 -0
  9. package/skills/protobase/references/guides/billing-page.md +288 -0
  10. package/skills/protobase/references/guides/create-page.md +108 -0
  11. package/skills/protobase/references/guides/deploy.md +52 -0
  12. package/skills/protobase/references/guides/export-a-list.md +44 -0
  13. package/skills/protobase/references/guides/field-type.md +131 -0
  14. package/skills/protobase/references/guides/first-composed-page.md +230 -0
  15. package/skills/protobase/references/guides/first-plugin.md +166 -0
  16. package/skills/protobase/references/guides/import-records.md +43 -0
  17. package/skills/protobase/references/guides/plugin-build.md +64 -0
  18. package/skills/protobase/references/guides/record-card.md +70 -0
  19. package/skills/protobase/references/guides/remote-resources.md +185 -0
  20. package/skills/protobase/references/guides/table-to-admin.md +205 -0
  21. package/skills/protobase/references/guides/theme-an-app.md +87 -0
  22. package/skills/protobase/references/reference/access.md +115 -0
  23. package/skills/protobase/references/reference/ai.md +106 -0
  24. package/skills/protobase/references/reference/api.md +231 -0
  25. package/skills/protobase/references/reference/architecture.md +63 -0
  26. package/skills/protobase/references/reference/assistant.md +157 -0
  27. package/skills/protobase/references/reference/auth.md +462 -0
  28. package/skills/protobase/references/reference/blocks.md +341 -0
  29. package/skills/protobase/references/reference/bottom-bar.md +44 -0
  30. package/skills/protobase/references/reference/cli.md +493 -0
  31. package/skills/protobase/references/reference/client.md +38 -0
  32. package/skills/protobase/references/reference/comments.md +83 -0
  33. package/skills/protobase/references/reference/custom-components.md +285 -0
  34. package/skills/protobase/references/reference/data-config.md +266 -0
  35. package/skills/protobase/references/reference/email.md +166 -0
  36. package/skills/protobase/references/reference/events.md +121 -0
  37. package/skills/protobase/references/reference/files.md +291 -0
  38. package/skills/protobase/references/reference/forms.md +133 -0
  39. package/skills/protobase/references/reference/history.md +86 -0
  40. package/skills/protobase/references/reference/jobs.md +174 -0
  41. package/skills/protobase/references/reference/layouts.md +126 -0
  42. package/skills/protobase/references/reference/plugins.md +328 -0
  43. package/skills/protobase/references/reference/remote-resources.md +198 -0
  44. package/skills/protobase/references/reference/sidebar.md +51 -0
  45. package/skills/protobase/references/reference/theme.md +132 -0
  46. package/skills/protobase/references/reference/ui-config.md +880 -0
  47. package/skills/protobase/references/reference/user-menu.md +38 -0
  48. package/skills/protobase/references/reference/versioning.md +91 -0
  49. package/skills/protobase/references/reference/webhooks.md +136 -0
@@ -0,0 +1,83 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/comments.mdx: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # Record comments
4
+
5
+ Comments on a resource's records by anyone who may read them, with @mentions that email the people named, shown on the record page and listed for admins.
6
+
7
+ A resource with [`.comments()`](https://docs.protobase.net/api/schema/interfaces/resourcebuilder/#comments)) takes comments on its records: plain text, each with its author and time. Typing `@` in a comment mentions someone, who gets an email with a link to the record. Comments cannot be edited, and there are no replies or reactions.
8
+
9
+ ```ts title="config/tickets.ts"
10
+ import { f, l, resource, view } from '@protobase/schema'
11
+
12
+ // A helpdesk's tickets, which everyone who may read one can comment on, mentioning colleagues who may read it too.
13
+
14
+ /** support.tickets */
15
+ export const tickets = resource('tickets')
16
+ .table('support.tickets')
17
+ .fields({
18
+ id: f.integer().readOnly().filterable().sortable(),
19
+ title: f.text(),
20
+ status: f.enum(['open', 'waiting', 'closed']).default('open'),
21
+ })
22
+ .primaryKey((r) => r.id)
23
+ .comments()
24
+
25
+ export const ticketsView = view<typeof tickets>('tickets')
26
+ .names({ singular: 'Ticket', plural: 'Tickets' })
27
+ .title((r) => r.title)
28
+ .layout((r) => [
29
+ l.section('Ticket', [r.title, r.status]),
30
+ // oldest first, the newest just above the box to write one
31
+ l.comments(),
32
+ ])
33
+ ```
34
+
35
+ ```ts title="protobase.config.ts"
36
+ import { defineConfig } from '@protobase/server'
37
+ import * as config from './tickets'
38
+
39
+ // Mentions are emailed by the app's workers, to the users of its Better Auth (`auth`, left out here).
40
+ export default defineConfig({ config })
41
+ ```
42
+
43
+ ## On the record page
44
+
45
+ [`l.comments(title?, { when })`](https://docs.protobase.net/api/schema/variables/l/#comments)) shows the record's comments oldest first, the newest just above the box to write one; Show earlier comments loads those before. ⌘/Ctrl+Enter or the Comment button posts. A view without a layout shows Comments last by itself. A view that names `l.comments()` for a resource without `.comments()` stops startup. A visitor who is not signed in sees the comments but no box.
46
+
47
+ ## Mentions
48
+
49
+ Typing `@` and part of a name lists up to 8 people to mention: the arrows move, Enter, Tab or a click picks, Escape closes. Only people who may read the record themselves are listed, and the server refuses a mention of anyone else, so a mention email never shows a record to someone who cannot open it. The comment keeps `@Name` as written, and the record page picks it out.
50
+
51
+ Each person mentioned gets one email from the app's own mail: who mentioned them on which record, the comment, and a button that opens the record. The emails are sent by the job `comments.mention`, enqueued with the comment, so mentions need:
52
+
53
+ - the project's [Better Auth](auth.md)), whose users are the people listed; without it, comments work and nobody can be mentioned;
54
+ - [mail](email.md#configuration)); without it, the job sends nothing;
55
+ - the [`jobs` schema](jobs.md#the-jobs-schema)) and the app's workers.
56
+
57
+ A person banned or deleted since the comment gets no email, and neither does anyone when an admin has deleted the comment.
58
+
59
+ ## Who may comment
60
+
61
+ Whoever may read the record may read its comments and add one: the same tenant, row filter and record-level rule as a get. Everyone else gets a `404`, as for the record itself. Writing one, or looking for someone to mention, needs a signed-in user. A soft-deleted record keeps its comments, which can still be read, and takes no new ones.
62
+
63
+ ## The endpoints
64
+
65
+ `GET /api/v1/{resource}/{key}:comments` reads them newest first, `POST` to the same path adds one, and `GET /api/v1/{resource}/{key}:mentionable?q=` lists whom a comment may mention. See [REST API](api.md#record-comments)).
66
+
67
+ ## Moderation
68
+
69
+ Once a resource takes comments, admins get **Comments** (the built-in resource `record_comments`): every comment of every resource, newest first, filterable by resource, record, author and time. Only the `admin` role reads it, whatever the project's roles say; deleting a comment there is how a wrong or abusive one goes. When a resource with comments has a [tenant](data-config.md#resource)), the list is scoped to the caller's tenant.
70
+
71
+ ## The table
72
+
73
+ [`protobase migration`](cli.md#migration)) adds the schema `comments` with the table `comments.comments`; apply it with the project's other migrations. `protobase dev` and `protobase serve` do not start while a resource has comments and the table is missing. A deleted record's comments stay in the table.
74
+
75
+ | Column | |
76
+ | --- | --- |
77
+ | `id` | Grows with every comment. |
78
+ | `resource`, `record_key` | The resource and the record's key as its URL has it. |
79
+ | `tenant_id` | The record's tenant, as text. |
80
+ | `author_id` | The user who wrote it. |
81
+ | `body` | The text, trimmed, at most 10,000 characters. |
82
+ | `mentions` | The ids of the users it mentions, as a JSON array; `[]` for none. |
83
+ | `created_at` | When it was written. |
@@ -0,0 +1,285 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/custom-components.mdx: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # Custom components
4
+
5
+ React components and action handlers of your own in protobase.ui.tsx, used by name from layouts.
6
+
7
+ Layouts are data; a project's React code lives in one module: `protobase.ui.tsx` at the project root, beside `protobase.config.ts`. It exports each custom component under the name its layouts declare, each from a file of its own, and default-exports `defineUi({ actions })` from `@protobase/ui` for the rest, so the project depends on `@protobase/ui`, and on `react` for its JSX. This is the ERP example's:
8
+
9
+ ```tsx title="examples/erp/protobase.ui.tsx"
10
+ import { defineUi, type ActionContext } from '@protobase/ui'
11
+
12
+ // The custom components, each in a file of its own, exported by the name their layouts declare.
13
+ export { OrdersPerDay } from './components/orders-per-day'
14
+
15
+ /** "Send reminder" on an invoice: opens a mail to the customer, and marks a draft invoice as sent. */
16
+ const send = async ({ record, recordKey, etag, client }: ActionContext) => {
17
+ const company = await client.get('companies', String(record!.company_id))
18
+ const subject = encodeURIComponent(`Invoice ${String(record!.number)}`)
19
+ window.location.assign(`mailto:${String(company.record.email ?? '')}?subject=${subject}`)
20
+ if (record!.status === 'draft') await client.update('invoices', recordKey!, { status: 'sent' }, etag ?? '*')
21
+ }
22
+
23
+ export default defineUi({ actions: { send } })
24
+ ```
25
+
26
+ ```tsx title="examples/erp/components/orders-per-day.tsx"
27
+ import { useSeries } from '@protobase/ui'
28
+
29
+ /** Bars for orders per day; the custom component behind `<OrdersPerDay>` in config/overview/page.tsx. */
30
+ export const OrdersPerDay = ({ days }: { days: 7 | 30 | 90 }) => {
31
+ const series = useSeries('orders', { field: 'created_at', range: `${days}d`, granularity: 'day' })
32
+ if (series.isPending) return <p className="text-muted-foreground">Loading</p>
33
+ if (series.error) return <p className="text-danger-text">Could not load the orders</p>
34
+ const points = series.data.points
35
+ const highest = Math.max(1, ...points.map((point) => point.count))
36
+ const total = points.reduce((sum, point) => sum + point.count, 0)
37
+ return (
38
+ <figure>
39
+ <div className="flex h-24 items-end gap-0.5" role="img" aria-label={`${total} orders in ${days} days`}>
40
+ {points.map((point) => (
41
+ <div key={point.bucket} title={`${point.bucket.slice(0, 10)}: ${point.count}`} className="flex-1 rounded-t-sm bg-primary/70" style={{ height: `${(point.count / highest) * 100}%` }} />
42
+ ))}
43
+ </div>
44
+ <figcaption className="mt-2 text-xs text-muted-foreground">{total.toLocaleString('en-IE')} orders</figcaption>
45
+ </figure>
46
+ )
47
+ }
48
+ ```
49
+
50
+ `protobase dev` serves it with hot reload, and `protobase build` builds it as the [plugin](plugins.md)) `app` in the bundle's `public/plugins/app/`, beside the prebuilt admin app, which loads it when someone signs in. It is the only project code that reaches the browser, so keep secrets out of it. `definePlugin` types its default export as well as `defineUi`, which stays as its alias. The same exports can come from other plugins too, which the app loads at runtime and which keep working when the app moves to a newer release.
51
+
52
+ ## Components
53
+
54
+ Declare a component in the layout with `component(name)` from `@protobase/layout`, typing its props:
55
+
56
+ ```tsx
57
+ /** @jsxImportSource @protobase/layout */
58
+ import { Card, component, page, Page } from '@protobase/layout'
59
+
60
+ export const OrdersPerDay = component<{ days: 7 | 30 | 90 }>('OrdersPerDay')
61
+
62
+ export const overview = page('overview', <Page title="Overview"><Card title="Orders per day"><OrdersPerDay days={30} /></Card></Page>)
63
+ ```
64
+
65
+ The element stays data, `{ type: 'OrdersPerDay', props: { days: 30 }, children: [], custom: true }`, so its props follow the same [rules](layouts.md#what-a-layout-may-hold)) as any block's. The name must be PascalCase and not a built-in block's.
66
+
67
+ `protobase.ui.tsx` exports the React component under the same name. It gets the props, and the rendered children when the element has any. Inside it:
68
+
69
+ - the hooks of `@protobase/ui` (`useList`, `useRecord`, `useSeries`, `useFacets`, `useHistogram`, `useClient`, ...) read the API with the user's token, under the same access rules as everything else;
70
+ - `useLayoutRecord()` gives the record around it in a `RecordCard` or `CardRow` (`{ model, record, key, etag, permissions }`), and `undefined` elsewhere.
71
+
72
+ A component that asks for a one-time code uses `OtpInput` from `@protobase/ui`, the field of the app's own code pages: a box per digit drawn over one real input, so pasting a whole code into any box, the system's code autofill from a mail or a text message, and the phone's digit keyboard all work. It takes `value` and `onChange`, `length` (6 by default), `invalid` and `disabled`, and `onComplete` gets the code once its last digit is in, to check it at once. Ask for a code on a step of its own, before anything else.
73
+
74
+ `protobase build` fails when the config declares a component that `protobase.ui.tsx` does not export, naming it; while you work, `protobase dev` draws a warning in its place. A component a plugin provides is declared with the plugin's name, `component('DraftOrders', { plugin: 'sales-tools' })`, and the build does not look for it in `protobase.ui.tsx`. A component that throws while drawing shows a warning in its own place, not a blank app. The object form, `defineUi({ components: { OrdersPerDay } })`, still works, and a name given both ways must be the same component.
75
+
76
+ ### Fields and resources in props
77
+
78
+ A prop that names a field is a field reference, `fieldRef('plan.name')` from `@protobase/layout`, read from the record around the element or the resource its `resource` prop names. The component gets the plain name (`'plan.name'`), and the names are checked when the server starts. A `resource` prop names a resource the way a block's does.
79
+
80
+ ```tsx
81
+ <RecordCard resource="subscriptions">
82
+ <SeatsChart value={fieldRef('seats_used')} max={fieldRef('plan.seats')} />
83
+ </RecordCard>
84
+ ```
85
+
86
+ `/api/meta` leaves a component out for a user who cannot read a field it references or see the resource it names, as it leaves out a `Field`, so a hidden name never reaches their browser. A field written as plain text is not checked or hidden this way.
87
+
88
+ ## List displays
89
+
90
+ A list can show its rows with a component of the project's own, declared in the view with [`d.custom`](ui-config.md#list-displays)). The list page loads the rows, with the filter, search and order of the address, and the component draws them: `useListDisplay()` gives them, `RecordLink` opens one. A board in columns of an enum field, with cards dragged between them, is built in as [`d.board`](ui-config.md#boards)), and a month or week calendar of a date field as [`d.calendar`](ui-config.md#calendars)); the board below draws its own.
91
+
92
+ ```tsx
93
+ // components/repair-board.tsx, exported from protobase.ui.tsx: export { RepairBoard } from './components/repair-board'
94
+ import { RecordLink, useListDisplay } from '@protobase/ui'
95
+
96
+ export const RepairBoard = ({ by }: { by: string }) => {
97
+ const list = useListDisplay()
98
+ const columns = [...new Set(list.rows.map((row) => String(row.record[by])))]
99
+ return (
100
+ <div className="grid grid-flow-col gap-3">
101
+ {columns.map((value) => (
102
+ <section key={value} aria-label={value}>
103
+ {list.rows.filter((row) => String(row.record[by]) === value).map((row) => (
104
+ <RecordLink key={row.key} row={row}>{String(row.record.number)}</RecordLink>
105
+ ))}
106
+ </section>
107
+ ))}
108
+ </div>
109
+ )
110
+ }
111
+ ```
112
+
113
+ | `useListDisplay()` | |
114
+ | --- | --- |
115
+ | `resource` | The list's resource. |
116
+ | `rows` | `{ key, record, labels }` per record: its key, the record as the list API gives it, and the name of the record each relation the display shows points at (`labels.customer_id`). |
117
+ | `total` | How many records match. |
118
+ | `loading`, `error` | While the first rows load, and why they did not. |
119
+ | `more`, `loadMore()` | Whether there are more rows, and loading the next page of them. |
120
+
121
+ A display never fetches its list, changes the address or keeps its own history: that is what keeps it at `/<resource>` with every other display, its filters and its links.
122
+
123
+ ## Record sections
124
+
125
+ A record page can hold a component of the project's own beside its sections, declared in the view with [`l.custom`](ui-config.md#the-record-page)). `useLayoutRecord()` gives it the record the page shows, as inside a `RecordCard`, so one component works in both. It reads more through the hooks (`useList`, `useRecord`), and acts through named actions or the API. Breadcrumbs, the heading, Save, the action rail with Edit and Delete, and the related records stay the page's.
126
+
127
+ ```tsx
128
+ // components/customer-repairs.tsx
129
+ import { RecordLink, useLayoutRecord, useList } from '@protobase/ui'
130
+
131
+ export const CustomerRepairs = ({ limit }: { limit: number }) => {
132
+ const { record } = useLayoutRecord()!
133
+ const earlier = useList('repairs', { filter: `customer_id = ${record.customer_id} AND id != ${record.id}`, orderBy: 'booked_on desc', pageSize: limit })
134
+ return <ul>{earlier.items.map((repair) => <li key={String(repair.id)}><RecordLink recordKey={repair.id as number}>{String(repair.number)}</RecordLink></li>)}</ul>
135
+ }
136
+ ```
137
+
138
+ ## Record cards
139
+
140
+ A cards display can draw each card's content with a component, declared in the view with `d.cards(fields, { card })`. The card stays a link to the record, with the display's frame; the component draws what is inside it from `row`, the record with the fields the display names, so name every field the card shows:
141
+
142
+ ```ts
143
+ // config/repairs/ui.ts
144
+ export const RepairCard = component('RepairCard')
145
+ // in .list((r, d) => ...):
146
+ d.cards({ title: r.bike, subtitle: r.customer_id, badge: r.status, meta: [r.number, r.estimate] }, { card: RepairCard })
147
+ ```
148
+
149
+ ```tsx
150
+ // components/repair-card.tsx, exported from protobase.ui.tsx: export { RepairCard } from './components/repair-card'
151
+ import type { RecordCardProps } from '@protobase/ui'
152
+
153
+ export const RepairCard = ({ row }: RecordCardProps) => (
154
+ <span className="flex flex-col gap-1">
155
+ <span className="font-medium">{String(row.record.bike)}</span>
156
+ <span className="text-muted-foreground">{row.labels.customer_id}</span>
157
+ </span>
158
+ )
159
+ ```
160
+
161
+ `row` is `{ key, record, labels }`, as a [list display's](#list-displays) rows are. A card is inside a link, so it holds no buttons or links of its own. Without the component, from a plugin that is off for instance, and when it throws, each card is the built-in one: the title, subtitle, badge and meta fields. [A custom record card](../guides/record-card.md)) builds one step by step.
162
+
163
+ ## Field types
164
+
165
+ A [field type](plugins.md#field-types)) shows and edits a field everywhere the app shows it: a view picks one with `r.status.widget('steps')`, and `protobase.ui.tsx` registers it under that name in `fields`:
166
+
167
+ ```tsx
168
+ export default definePlugin({ fields: { steps: { of: ['enum'], display: StepsDisplay, editor: StepsEditor } } })
169
+ ```
170
+
171
+ [Plugins](plugins.md#field-types)) describes the contract, and [Adding a field type](../guides/field-type.md)) builds one.
172
+
173
+ ## Addresses
174
+
175
+ Every place in the app has an [address](layouts.md#addresses)), and a component never writes a path or reads the query string itself, so the address can change shape in one place. `useAppAddress()` from `@protobase/ui` gives the current one as values, with the list's defaults filled in, and moves the app:
176
+
177
+ ```tsx
178
+ const { address, set, listTo, go, href } = useAppAddress()
179
+ // address: { kind: 'list', resource: 'repairs', display: 'board', filter: 'status = "ready"', orderBy: 'booked_on desc', filterLayout: 'bar' }
180
+ set({ display: 'cards' }) // changes this list in place
181
+ listTo({ display: 'cards' }) // this list changed, as an AppLink's `to`
182
+ go({ kind: 'record', resource: 'repairs', key: 42 }) // moves to another address
183
+ href({ kind: 'create', resource: 'repairs' }) // for an <a href>, with the base path
184
+ ```
185
+
186
+ `RecordLink` (a record, from a display's `row` or a `recordKey`) and `AppLink` (`to` any address) are links written the same way. Code outside React builds and reads addresses with [`appPath(address, basePath?)`](https://docs.protobase.net/api/schema/functions/apppath/)) and [`readAppPath(path, pages)`](https://docs.protobase.net/api/schema/functions/readapppath/)) from `@protobase/schema`, whose words (`filter`, `order_by`, `display`) are in [`addressWords`](https://docs.protobase.net/api/schema/variables/addresswords/)).
187
+
188
+ ## Create pages
189
+
190
+ A view whose records a page of the app's own creates names it with [`.create({ page })`](ui-config.md#create-pages)), and `/<resource>/new` shows that page. The address keeps its `values`: a component on the page reads them from `useAppAddress()`, and writes its answers back with `go(..., { replace: true })`, so a reload, a link, or a round trip through another site, such as an install page that sends the user back, keeps them:
191
+
192
+ ```tsx
193
+ const { address, go } = useAppAddress()
194
+ const values = address?.kind === 'create' ? (address.values ?? {}) : {}
195
+ const answer = (patch: Record<string, string>) => go({ kind: 'create', resource: 'repairs', values: { ...values, ...patch } }, { replace: true })
196
+ ```
197
+
198
+ The same page at its own address, `/<page>`, starts without values.
199
+
200
+ ## Form parts
201
+
202
+ A component that asks for input looks like the app's own forms when it is built from the parts they use, all from `@protobase/ui`:
203
+
204
+ | | |
205
+ | --- | --- |
206
+ | `Form` | The create form's frame: `submit`, the button's label; `onSubmit`; `saving` and `disabled` for the button; `onCancel`, which adds Cancel; and `error` with `errorTitle`, a failure that belongs to no field, where an `ApiError` shows its messages. With `title` (and `eyebrow`, the line above it) the form is the whole page, its buttons beside the heading, as the create form is. Without, it sits in a composed page under the page's heading, its buttons after the sections. |
207
+ | `Section` | A titled part of a form or page: `title`, `help`, `actions`. Sections in a `Form` have a line between them. |
208
+ | `Field` | A label over its input: `label`, `required`, `help`, `example`, `error`, `name` for the browser's autofill, and `wide` for both columns of a grid of two. An `Input` or `Textarea` inside takes its label, name, help and error from it, and whether it is invalid or required; another control spreads `useFieldControl()` on its element. |
209
+ | `Input`, `Textarea` | A text box, with `leading` and `trailing` content and `invalid`; a box of several lines that grows with its text. |
210
+ | `Choices` | One of a few options, each a card in a row of its own with a `description`: `name`, `label`, `options`, `value`, `onChange`. A `disabled` option shows and cannot be chosen. |
211
+ | `Segmented`, `MenuSelect` | A switch between a few short options in a row (`size`, `iconOnly`), and the same options in a menu. |
212
+ | `Button`, `buttonClass` | A button (`variant` `primary`, `secondary`, `ghost` or `danger`, `size`, `loading`), and its classes for a link that looks like one. |
213
+ | `Dialog`, `ResponsiveDialog` | A modal with a `title`, `description`, `actions` and a body, which Escape and a click outside close with `onClose`; the responsive one becomes a sheet on a phone. |
214
+
215
+ ```tsx
216
+ // components/book-repair.tsx, exported from protobase.ui.tsx
217
+ import { Choices, Field, Form, Input, Section } from '@protobase/ui'
218
+
219
+ export const BookRepair = () => {
220
+ // values and answer as above
221
+ return (
222
+ <Form submit="Book repair" disabled={!values.bike || !values.kind} onSubmit={() => void book(values)}>
223
+ <Section title="The bike">
224
+ <div className="flex flex-col gap-5">
225
+ <Field label="Bike" required>
226
+ <Input value={values.bike ?? ''} onChange={(event) => answer({ bike: event.target.value })} />
227
+ </Field>
228
+ <Field label="What it needs" required>
229
+ <Choices name="kind" label="What it needs" options={kinds} value={values.kind} onChange={(kind) => answer({ kind })} />
230
+ </Field>
231
+ </div>
232
+ </Section>
233
+ </Form>
234
+ )
235
+ }
236
+ ```
237
+
238
+ ## Components in the chat
239
+
240
+ The same components draw the assistant's [widget parts](assistant.md#widget-parts)): a part names a component, and the dock draws it with the part's props, so one component can sit on a page and in the chat. In the chat there is no record around it, so a component that needs `useLayoutRecord()` works only on pages; take ids as props instead. Besides the API hooks, a widget can read the assistant backend with [`useBackendData`](assistant.md#reading-the-backend-from-a-widget)).
241
+
242
+ ## Action handlers
243
+
244
+ A named action declared with `a.action(name, ...)` in a view has no built-in behaviour: its button runs `actions[name]` from `protobase.ui.tsx`. The handler gets:
245
+
246
+ | | |
247
+ | --- | --- |
248
+ | `resource` | The action's resource. |
249
+ | `record`, `recordKey`, `etag` | The record around the button, when there is one. |
250
+ | `client` | The API client (`@protobase/client`) of the API that serves the resource, with the user's token: the app's own, or a source's for a [remote resource](remote-resources.md)), whose functions `invoke` then calls. |
251
+ | `navigate(to)` | Moves the app to an [address](layouts.md#addresses)), such as `{ kind: 'record', resource: 'orders', key: 42 }`. |
252
+ | `values` | The answers to the action's [inputs](ui-config.md#actions-that-ask-for-input)), by input name, when it has some. |
253
+
254
+ When the handler resolves, everything shown of the resource reloads and a toast says it is done; when it throws, the toast shows the error, or for an action with inputs its dialog does, under the inputs an `ActionInputError` names. Without a handler the button is disabled. Actions with built-in behaviour (`a.update`, `a.remove`, `a.link`) do not need one.
255
+
256
+ ## Shell slots
257
+
258
+ `shell` adds components to the shell around every page: `actions` at the end of the top bar, and `rightPanel` beside the page, such as a `SidePanel` from `@protobase/ui` (see [the primitives](assistant.md#in-the-ui))). They take no props and use the same hooks as custom components:
259
+
260
+ ```tsx
261
+ export default defineUi({ shell: { actions: NotesButton, rightPanel: Notes } })
262
+ ```
263
+
264
+ When the app has an [assistant](assistant.md)), its button follows the project's actions and its dock the project's panel.
265
+
266
+ `logo` replaces Protobase's logo at the top of the sidebar with the app's own. It gets `compact`, true when the sidebar shows only icons, so it draws a mark alone, `workspace`, the name of the user's organization that Protobase's logo shows under it, and `appName`, the app's [name](auth.md#configuration)), which Protobase's logo shows beside its mark (`ShellLogoProps`). Its colors follow the [theme](theme.md)), and a `dark:` class gives dark its own. When it throws, Protobase's logo shows instead. The tab's icon is [the favicon](theme.md#logo-and-favicon)).
267
+
268
+ ```tsx
269
+ import { defineUi, type ShellLogoProps } from '@protobase/ui'
270
+
271
+ const Logo = ({ compact }: ShellLogoProps) => (
272
+ <div className="flex items-center gap-2.5">
273
+ <img src="https://cdn.example.com/rijnland-mark.svg" alt="Rijnland Industrial" className="size-7" />
274
+ {!compact && <span className="font-semibold">Rijnland Industrial</span>}
275
+ </div>
276
+ )
277
+
278
+ export default defineUi({ shell: { logo: Logo } })
279
+ ```
280
+
281
+ ## Without protobase dev
282
+
283
+ `<App ui={...} />` from `@protobase/ui` takes the same object, for an app that mounts the admin itself, and so do stories.
284
+
285
+ Below 1.0, a project built before 0.12 had its `protobase.ui.tsx` built into the admin app; [Moving onto the plugin build](../guides/plugin-build.md)) says what changes.
@@ -0,0 +1,266 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/data-config.mdx: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # Data config
4
+
5
+ Resources in data.ts, every field type and option, keys and relations, soft delete, tenants, search, validation and access.
6
+
7
+ A **resource** describes one table of a database you already have: its columns as fields, its key, and the rules around it. It is plain TypeScript in `config/<resource>/data.ts`, exported from `config/index.ts`; [`protobase scaffold`](cli.md#scaffold)) writes a first version from the database. Every example on this page is a file in the repository that CI typechecks and tests.
8
+
9
+ ```ts title="docs-examples/bike-shop/data.ts"
10
+ import { f, resource } from '@protobase/schema'
11
+
12
+ // Pip's bike shop: customers bring bikes in, the workshop repairs them. Two tables of a Postgres database the
13
+ // shop already has, described as they are.
14
+
15
+ /** shop.customers */
16
+ export const customers = resource('customers')
17
+ .table('shop.customers')
18
+ .fields({
19
+ id: f.integer().readOnly().filterable().sortable().dbDefault(),
20
+ name: f.text().min(2).filterable().sortable(),
21
+ phone: f.text().regex(/^\+?[0-9 ]{6,}$/, 'Use digits, spaces and an optional +').optional(),
22
+ email: f.text().optional().filterable(),
23
+ country: f.country().default('NL'),
24
+ created_at: f.timestamp().readOnly().filterable().sortable().dbDefault(),
25
+ })
26
+ .primaryKey((r) => r.id)
27
+ .search((r) => [r.name, r.email])
28
+
29
+ /** shop.repairs */
30
+ export const repairs = resource('repairs')
31
+ .table('shop.repairs')
32
+ .fields({
33
+ id: f.integer().readOnly().filterable().sortable().dbDefault(),
34
+ number: f.text().readOnly().filterable().sortable().dbDefault(),
35
+ customer_id: f.relation('customers').filterable().sortable(),
36
+ bike: f.text(),
37
+ problem: f.text(),
38
+ status: f.enum(['booked', 'waiting', 'working', 'ready', 'collected']).default('booked').filterable().sortable(),
39
+ mechanic: f.text().optional().filterable().sortable(),
40
+ estimate: f.decimal({ precision: 8, scale: 2 }).filterable().sortable(),
41
+ currency: f.currency().default('EUR'),
42
+ paid: f.boolean().default(false).filterable(),
43
+ booked_on: f.date().filterable().sortable(),
44
+ notes: f.text().optional().column('internal_notes'),
45
+ legacy_ref: null,
46
+ updated_at: f.timestamp().readOnly().dbDefault(),
47
+ })
48
+ .primaryKey((r) => r.id)
49
+ .search((r) => [r.number, r.bike, r.problem])
50
+ .validate((repair) => (repair.status === 'collected' && !repair.paid ? [{ field: 'paid', message: 'A bike leaves the shop paid' }] : undefined))
51
+ ```
52
+
53
+ ## resource()
54
+
55
+ | | |
56
+ | --- | --- |
57
+ | [`resource(name)`](https://docs.protobase.net/api/schema/functions/resource/)) | The name is the resource's address (`/api/v1/<name>`, `/<name>` in the admin) and how other config refers to it. It may not contain `/`, `:`, `?` or `#`, and must be unique. |
58
+ | `.table('schema.table')` | The table, with or without its schema. Required. |
59
+ | `.fields({ ... })` | The columns, by field name. `name: null` ignores a column on purpose (scaffold writes it, so it does not offer the column again). Required. |
60
+ | `.primaryKey((r) => r.id)` | The key, one field or a list (`(r) => [r.order_id, r.line_no]`). Required; records are addressed by it. |
61
+ | `.softDelete((r) => r.deleted_at)` | A nullable timestamp or date: deleting sets it, lists leave such rows out, `:undelete` clears it. See [REST API](api.md#routes)). |
62
+ | `.tenant((r) => r.organization_id)` | The column that separates tenants: every query is limited to the caller's tenant, creates set it, and a request body may not. |
63
+ | `.owner((r) => r.owner_id)` | The field holding the owning user's id, which `.own` capabilities filter on (see [Access](#access)). |
64
+ | `.search((r) => [r.number, r.name])` | The fields that `search("...")` and bare words in a filter match, and what the admin's [global search](client.md#global-search)) looks in. Every word of the text must appear in one of them, ignoring case, and part of a word is enough: `port` finds "Portfolio". `r.phone.digitsEnd()` matches only the end of a field's digits instead, ignoring spaces, `+` and dashes, and only words written like phone numbers: `9623`, `47069623` and `+31 6 47069623` find "+31 6 47069623", `4706` and `+316` do not. Each field needs a pg_trgm index (`using gin (name gin_trgm_ops)`), a `digitsEnd` one on `regexp_replace(phone, '[^0-9]', '', 'g')`, or the API refuses the search. |
65
+ | `.position((r) => r.position, { within? })` | The integer field holding the records' order by hand, 1 the first, which a list's **Sort** button changes by dragging; with `within: (r) => r.invoice_id`, a filterable relation, each parent's records have an order of their own, sorted in its related section. The field must be sortable. See [Sorting by hand](ui-config.md#sorting-by-hand)). |
66
+ | `.validate((record) => issues)` | A rule over the whole record, run after the field checks on every create and update. It returns `[{ field, message }]` or `undefined`; issues answer `400` with the field named. |
67
+ | `.access({ ... })` | Rules per operation. See [Access](#access). |
68
+ | `.events((e, r) => [...])` | What changes of its records mean, such as `orders.created`, captured in the database for every write. See [Events](events.md)). |
69
+ | `.history()` | Keeps every change of its records with who made it, shown on the record page and listed for admins as Activity. See [Record history](history.md)). |
70
+ | `.comments()` | Lets whoever may read a record comment on it and @mention others who may, who are emailed; shown on the record page and listed for admins. See [Record comments](comments.md)). |
71
+
72
+ Field and resource names are snake_case by convention, like the columns: they are the names in URLs, the API, filters and sorts as written (`/stock_moves?order_by=moved_at desc`). The column is the snake_case of the name unless `.column()` says otherwise, so a camelCase name such as `movedAt` maps to `moved_at` too.
73
+
74
+ ## Field types
75
+
76
+ | Builder | Column types | API value | Options |
77
+ | --- | --- | --- | --- |
78
+ | `f.text()` | `text`, `varchar`, `bpchar` | string | `.min(n)`, `.max(n)` (length), `.regex(re, message)`; a text of several lines, such as a description, takes the view's [`.multiline()`](ui-config.md#names-and-columns)), and markdown its [`.markdown()`](ui-config.md#names-and-columns)) |
79
+ | `f.integer()` | `int2`, `int4` | number | `.min(n)`, `.max(n)` |
80
+ | `f.bigint()` | `int8` | string (all 64 bits) | |
81
+ | `f.decimal({ precision, scale })` | `numeric` | string (exact) | |
82
+ | `f.boolean()` | `bool` | boolean | |
83
+ | `f.date()` | `date` | `2026-10-08` | a day with no time zone, shown as it is |
84
+ | `f.timestamp()` | `timestamp`, `timestamptz` | ISO 8601 with offset | an instant, shown on the viewer's clock, in their browser's time zone, which hovering over it names |
85
+ | `f.uuid()` | `uuid` | string | |
86
+ | `f.enum(['a', 'b'])` | Postgres enum, or text with a `CHECK (... IN ...)` | one of the values | |
87
+ | `f.json()` | `json`, `jsonb` | any JSON | |
88
+ | `f.relation('resource')` | the key column(s) of another resource | its key | `.columns([...])` |
89
+ | `f.currency()` | `text` | ISO 4217 code (`EUR`) | |
90
+ | `f.country()` | `text` | ISO 3166-1 alpha-2 code (`NL`) | |
91
+ | `f.file()` | `text` | `{ uri, name, type, size, url }`; written with a ticket from `:upload` | `.accept([...])`, `.maxSize(size)`, `.public()`, `.storage(name)`, `.derive({...})`; see [Files](files.md)) |
92
+
93
+ A constraint a type does not support (`f.boolean().min(1)`) throws when the config loads. The builders are the members of [`f`](https://docs.protobase.net/api/schema/variables/f/)).
94
+
95
+ ## Field options
96
+
97
+ Every option returns a new [field](https://docs.protobase.net/api/schema/interfaces/field/)), so they chain in any order.
98
+
99
+ | Option | Effect |
100
+ | --- | --- |
101
+ | `.optional()` | The column is nullable; the value may be `null`. |
102
+ | `.readOnly()` | Never written through the API: ids, computed columns, audit timestamps. |
103
+ | `.default(value)` | The value a create uses when none is given; the admin's create form shows it. |
104
+ | `.dbDefault()` | The database supplies a value when none is given (identity, `now()`, a sequence). |
105
+ | `.filterable()` | May appear in `filter`, in filter widgets and in `Stat`/`Table` filters. It needs an index: the API refuses a filter on a column no index serves (see the [scan guard](api.md#safety))), and [`protobase doctor`](cli.md#doctor)) fails without one. |
106
+ | `.sortable()` | May appear in `order_by` and in sorts. It needs a btree index that serves it alone, as a filterable field does, since a list may be sorted by it. A list's header of a field without it is no button and says "This column can't be sorted" on hover and in its menu. |
107
+ | `.alias(...names)` | Other names filters may use for the field. |
108
+ | `.column('name')` | The column, when it is not the snake_case of the field name (`'EMP_NAME'`). |
109
+ | `.access({ read, create, update })` | Role rules for this column. See [Access](#access). |
110
+ | `.sensitive()` | Hidden like a password: no response carries it, and a caller who may read it reveals one record's value at a time. See [Sensitive fields](#sensitive-fields). |
111
+ | `.ai({ prompt })` | A job fills the field from `prompt`, `{field}` replaced by the record's values, after a create and after an update of a field the prompt reads, as the user who wrote. Text or enum, optional. See [AI fields and actions](ai.md)). |
112
+
113
+ The ERP's products show most of them, together with soft delete and a tenant:
114
+
115
+ ```ts title="examples/erp/config/products/data.ts"
116
+ import { f, resource } from '@protobase/schema'
117
+ import { erpAccess } from '../roles'
118
+
119
+ /** catalog.products. Unique: (organization_id, sku) */
120
+ export const products = resource('products')
121
+ .table('catalog.products')
122
+ .fields({
123
+ id: f.bigint().readOnly().filterable().sortable().dbDefault(),
124
+ organization_id: f.relation('organizations').filterable().sortable(),
125
+ category_id: f.relation('categories').filterable().sortable(),
126
+ sku: f.text().filterable().sortable(),
127
+ name: f.text().filterable(),
128
+ description: f.text().optional(),
129
+ price: f.decimal({ precision: 12, scale: 2 }),
130
+ currency_code: f.relation('currencies'),
131
+ attributes: f.json().dbDefault(),
132
+ active: f.boolean().default(true),
133
+ deleted_at: f.timestamp().optional(),
134
+ created_at: f.timestamp().readOnly().filterable().sortable().dbDefault(),
135
+ updated_at: f.timestamp().readOnly().dbDefault(),
136
+ })
137
+ .primaryKey((r) => r.id)
138
+ .softDelete((r) => r.deleted_at)
139
+ .tenant((r) => r.organization_id)
140
+ .access(erpAccess('products'))
141
+ ```
142
+
143
+ ## Sensitive fields
144
+
145
+ A sensitive field, such as a bank account number, is written like any other field but never read with the record: lists, gets, `:search`, `:seek`, create and update responses and batch results leave it out, and it cannot be filtered, sorted, searched, counted or picked with `fields`. The record page shows it masked, with an eye button. Showing it asks the server for that one value with `POST /{resource}/{key}:reveal` (see [REST API](api.md#sensitive-fields-and-audit))), which needs the same access as reading the record and the field, inside the caller's tenant, and publishes an audit event before it answers.
146
+
147
+ ```ts
148
+ iban: f.text().sensitive().access({ read: roles.can('screening.read') }),
149
+ ```
150
+
151
+ A sensitive field cannot be `.filterable()`, `.sortable()`, aliased, searched, or the key, tenant, owner or soft delete field, and a view may only put it in a record page section: in a list, filter, chart, sidebar, title, recent-record group or action it would always be empty, so the config fails to load.
152
+
153
+ ## Keys and relations
154
+
155
+ A key of several columns is a list, and a record's address joins its parts with a comma (`/stock/CHAIN-11,L`). A relation to such a resource names its columns, in the order of that key:
156
+
157
+ ```ts title="docs-examples/reference/keys.ts"
158
+ import { f, resource } from '@protobase/schema'
159
+
160
+ // Keys of more than one column, and a relation that points at one.
161
+
162
+ /** shop.stock: one row per part and size. */
163
+ export const stock = resource('stock')
164
+ .table('shop.stock')
165
+ .fields({
166
+ part_no: f.text().filterable().sortable(),
167
+ size: f.text().filterable().sortable(),
168
+ on_hand: f.integer().min(0),
169
+ })
170
+ .primaryKey((r) => [r.part_no, r.size])
171
+
172
+ /** shop.part_orders: parts ordered from suppliers. */
173
+ export const partOrders = resource('part_orders')
174
+ .table('shop.part_orders')
175
+ .fields({
176
+ id: f.uuid().readOnly().filterable().dbDefault(),
177
+ // Two columns hold the key of one stock row, in the order of its primary key.
178
+ part: f.relation('stock').columns(['part_no', 'part_size']),
179
+ quantity: f.integer().min(1).max(50),
180
+ // Filters may say `ref` as well as `supplier_reference`.
181
+ supplier_reference: f.text().alias('ref').filterable(),
182
+ ordered_at: f.timestamp().readOnly().filterable().sortable().dbDefault(),
183
+ })
184
+ .primaryKey((r) => r.id)
185
+ ```
186
+
187
+ A relation's value in the API is the other record's key. The admin shows the other record's name instead (its view's `title`, else a field such as `name` or `number`) and links to it. The create form and the record's form pick it from a list, with a link beside it on the record's form; a relation the user may not change, the record's own key and a relation to a record with a key of several columns stay links.
188
+
189
+ ## Access
190
+
191
+ Without rules everyone who can sign in may do everything. Rules come in three kinds, and the [Access](access.md)) reference explains the defaults:
192
+
193
+ - **Per operation** (`list`, `read`, `create`, `update`, `delete`): `.access({ update: rule })`. A rule returns `true`, `false`, or an AIP-160 filter that limits the rows, like row-level security. A rule that reads the record (`record.status`) is checked against the stored row.
194
+ - **Per row**: a filter from a rule, or a `.own` capability with `.owner(...)`.
195
+ - **Per field**: `.access({ read, create, update })` on the field. Field rules see only the user, never a record, so the fields a user can read are the same for every row.
196
+
197
+ [`defineRoles`](https://docs.protobase.net/api/schema/functions/defineroles/)) turns roles into capabilities (`work_orders.update.own`, `money.read`, `*`), and `roles.can(...)` and `roles.is(...)` make rules of them; `.and()` and `.or()` combine rules.
198
+
199
+ ```ts title="docs-examples/reference/access.ts"
200
+ import { defineRoles, f, resource } from '@protobase/schema'
201
+
202
+ // Access for the bike shop's work orders: who may do what, which rows they see, and which fields.
203
+
204
+ /** Roles are bundles of capabilities: `<resource or area>.<action>[.own]`, `*` for everything. */
205
+ export const roles = defineRoles({
206
+ admin: ['*'],
207
+ desk: ['work_orders.read', 'work_orders.create', 'work_orders.update', 'money.read'],
208
+ mechanic: ['work_orders.read.own', 'work_orders.update.own'],
209
+ })
210
+
211
+ /** shop.work_orders */
212
+ export const workOrders = resource('work_orders')
213
+ .table('shop.work_orders')
214
+ .fields({
215
+ id: f.integer().readOnly().filterable().sortable().dbDefault(),
216
+ assignee: f.text().filterable(),
217
+ task: f.text(),
218
+ status: f.enum(['open', 'done']).default('open').filterable(),
219
+ // Only roles holding `money.read` see the price of the labour; only an admin may change it.
220
+ labour: f.decimal({ precision: 8, scale: 2 }).access({ read: roles.can('money.read'), update: roles.is('admin') }),
221
+ })
222
+ .primaryKey((r) => r.id)
223
+ // `.own` capabilities match the rows whose assignee is the signed-in user's id.
224
+ .owner((r) => r.assignee)
225
+ .access({
226
+ read: roles.can('work_orders.read'),
227
+ create: roles.can('work_orders.create'),
228
+ // A finished work order is closed: this rule needs the record, so it is checked against the stored row.
229
+ update: roles.can('work_orders.update').and((_ctx, record) => (record as { status: string }).status !== 'done'),
230
+ delete: roles.is('admin'),
231
+ })
232
+ ```
233
+
234
+ Pass the roles to the server (`options: { roles }` in `protobase.config.ts`) and every operation without a rule needs its capability (`<resource>.<action>`). The ERP's orders use `.owner` and `.search` with the ERP's roles:
235
+
236
+ ```ts title="examples/erp/config/orders/data.ts"
237
+ import { f, resource } from '@protobase/schema'
238
+ import { erpAccess } from '../roles'
239
+
240
+ /** sales.orders. Unique: (organization_id, number) */
241
+ export const orders = resource('orders')
242
+ .table('sales.orders')
243
+ .fields({
244
+ id: f.uuid().readOnly().filterable().sortable().dbDefault(),
245
+ organization_id: f.relation('organizations').filterable().sortable(),
246
+ number: f.text().filterable().sortable(),
247
+ company_id: f.relation('companies').filterable().sortable(),
248
+ person_id: f.relation('people').optional().filterable().sortable(),
249
+ owner_id: f.relation('users').filterable().sortable(),
250
+ status: f.enum(['draft', 'confirmed', 'picking', 'shipped', 'delivered', 'cancelled']).filterable().sortable(),
251
+ currency_code: f.relation('currencies'),
252
+ discount_percent: f.decimal({ precision: 5, scale: 2 }).default('0'),
253
+ total: f.decimal({ precision: 14, scale: 2 }).readOnly().default('0').filterable().sortable(),
254
+ paid: f.boolean().default(false).filterable().sortable(),
255
+ notes: f.text().optional(),
256
+ created_at: f.timestamp().readOnly().filterable().sortable().dbDefault(),
257
+ updated_at: f.timestamp().readOnly().dbDefault(),
258
+ })
259
+ .primaryKey((r) => r.id)
260
+ .tenant((r) => r.organization_id)
261
+ .owner((r) => r.owner_id)
262
+ .search((r) => [r.number])
263
+ .access(erpAccess('orders'))
264
+ ```
265
+
266
+ The UI side of a resource, its names, columns, filters and record page, is in [UI config](ui-config.md)).