@protobase/cli 0.22.12 → 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,185 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/guides/remote-resources.mdx: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # Showing another app's records
4
+
5
+ Two Protobase apps, where the shop's admin app shows the service desk's tickets with its own pages, sidebar and links.
6
+
7
+ Sam runs a web shop, and its customers' questions land in the company's service desk, a Protobase app of its own. When a customer calls about an order, Sam's people look the order up in the shop's admin app, then open the desk in another tab to find the customer's ticket. They want the tickets in the shop's admin app, next to the orders: a list, each ticket's page, the open ones in the sidebar, and a status they can change. The desk's agents keep working in the desk.
8
+
9
+ This guide makes the desk's tickets a [remote resource](../reference/remote-resources.md)) of the shop: the shop draws them with its own pages, while the desk keeps the data, the rules and the views. Nothing is copied and nothing is proxied: the shop's admin app reads the desk's API with the shop's own sign-in.
10
+
11
+ ## 1. Two apps
12
+
13
+ You need two Protobase projects, each with its own database, its own [admin store](../reference/auth.md#admin-store)) and a user: the from-scratch preset (`examples/scratch` in the repository) is enough for both. Each runs on its own origin; this guide runs them side by side on one machine:
14
+
15
+ | | `BETTER_AUTH_URL` in its `.env` | Started with |
16
+ | --- | --- | --- |
17
+ | The service desk | `http://localhost:4720` | `protobase dev --port 4720` |
18
+ | The shop | `http://localhost:4710` | `protobase dev --port 4710` |
19
+
20
+ `BETTER_AUTH_URL` matters here: it is the issuer of each app's tokens, and the desk will recognise the shop's tokens by it.
21
+
22
+ The shop has its orders. The desk has tickets and their notes:
23
+
24
+ ```ts
25
+ // desk: config/tickets/data.ts
26
+ import { f, resource } from '@protobase/schema'
27
+
28
+ type Caller = { user: { roles: string[] } }
29
+ const deskOnly = (ctx: unknown) => (ctx as Caller).user.roles.includes('admin')
30
+
31
+ export const tickets = resource('tickets')
32
+ .table('tickets')
33
+ .fields({
34
+ id: f.integer().readOnly().filterable().sortable(),
35
+ title: f.text().filterable().sortable(),
36
+ customer_email: f.text().filterable(),
37
+ status: f.enum(['open', 'waiting', 'closed']).filterable().sortable(),
38
+ updated_at: f.timestamp().readOnly().filterable().sortable(),
39
+ })
40
+ .primaryKey((r) => r.id)
41
+ .search((r) => [r.title, r.customer_email])
42
+ .access({ delete: deskOnly })
43
+
44
+ export const ticketNotes = resource('ticket_notes')
45
+ .table('ticket_notes')
46
+ .fields({
47
+ id: f.integer().readOnly().filterable().sortable(),
48
+ ticket_id: f.relation('tickets').filterable(),
49
+ body: f.text(),
50
+ created_at: f.timestamp().readOnly().sortable(),
51
+ })
52
+ .primaryKey((r) => r.id)
53
+ .access({ delete: deskOnly })
54
+ ```
55
+
56
+ Only the desk's own admins delete: the [access rule](../reference/access.md)) holds for everyone who reaches the desk's API, the shop's people included.
57
+
58
+ ```ts
59
+ // desk: config/tickets/ui.ts
60
+ import { l, view } from '@protobase/schema'
61
+ import type { ticketNotes, tickets } from './data'
62
+
63
+ const recent = { status: 'status', tones: { open: 'warning', waiting: 'neutral', closed: 'success' }, orderBy: 'updated_at desc' } as const
64
+
65
+ export const ticketsView = view<typeof tickets>('tickets')
66
+ .title((r) => r.title)
67
+ .names({ singular: 'Ticket', plural: 'Tickets' })
68
+ .nav({ group: 'Support', recent })
69
+ .fields((r) => ({ customer_email: r.customer_email.label('Customer'), status: r.status.format('badge'), updated_at: r.updated_at.label('Changed').format('relative') }))
70
+ .list((r) => ({ columns: [r.title, r.customer_email, r.status, r.updated_at], sort: [[r.updated_at, 'desc']] }))
71
+ .filters((r, w) => [w.facets(r.status)])
72
+ .layout((r) => [
73
+ l.section('Ticket', [r.title, r.customer_email, r.status]),
74
+ l.related('Notes', { resource: 'ticket_notes', field: 'ticket_id', sort: 'created_at desc', columns: ['body', 'created_at'], empty: 'No notes yet.' }),
75
+ ])
76
+
77
+ export const ticketNotesView = view<typeof ticketNotes>('ticket_notes').nav({ hidden: true })
78
+ ```
79
+
80
+ That is the desk's admin app as its agents use it. Nothing in it knows about the shop yet.
81
+
82
+ ## 2. The desk lets the shop's people in
83
+
84
+ The shop's admin app will call the desk's API from the browser, with the token the shop gave the signed-in person. The desk needs to accept two things: that token, and calls from the shop's origin.
85
+
86
+ The token: list the shop as a trusted app in the desk's authenticator, and say what the shop's roles are at the desk:
87
+
88
+ ```ts
89
+ // desk: auth/auth.ts
90
+ export const authenticate = betterAuthAuthenticator({
91
+ auth,
92
+ tenant: 1,
93
+ // The shop's admins sign in at the shop; the desk takes the shop's tokens and calls them `shop` here.
94
+ apps: [{ issuer: 'http://localhost:4710', roles: { admin: 'shop' }, tenant: 1 }],
95
+ })
96
+ ```
97
+
98
+ The desk now checks a token from the shop against the shop's keys, at `http://localhost:4710/api/auth/jwks`. Its holder is `shop` at the desk, never the desk's `admin`, so the `deskOnly` rule keeps tickets from being deleted from the shop; a shop user with any other role is refused. The [reference](../reference/remote-resources.md#signing-in-at-the-source)) has the details, such as the ids those users get.
99
+
100
+ The origin: the shop's admin app runs on `http://localhost:4710`, so the desk answers [CORS](../reference/api.md#cors)) for it:
101
+
102
+ ```ts
103
+ // desk: protobase.config.ts
104
+ import * as config from './config'
105
+ import { auth, authenticate } from './auth/auth'
106
+
107
+ // The shop's admin app, on its own origin, calls this API from the browser.
108
+ export default { config, auth, authenticate, options: { cors: ['http://localhost:4710'] } }
109
+ ```
110
+
111
+ `protobase dev` reloads the desk.
112
+
113
+ ## 3. The shop draws the tickets
114
+
115
+ The shop lists the desk as a source, with the resources it draws from it:
116
+
117
+ ```ts
118
+ // shop: protobase.config.ts
119
+ import * as config from './config'
120
+ import { auth, authenticate } from './auth/auth'
121
+
122
+ export default {
123
+ config,
124
+ auth,
125
+ authenticate,
126
+ options: {
127
+ sources: [{ url: 'http://localhost:4720/api/v1', label: 'Service desk', resources: ['tickets', 'ticket_notes'] }],
128
+ },
129
+ }
130
+ ```
131
+
132
+ `url` is the desk's resources API, and `label` its name when the shop's people cannot reach it. The notes are there because a ticket's page lists them: what the shop does not draw, it does not show. A platform that runs the shop can set the same list in `PROTOBASE_SOURCES`, without touching the shop's code:
133
+
134
+ ```sh
135
+ PROTOBASE_SOURCES='[{"url":"http://localhost:4720/api/v1","label":"Service desk","resources":["tickets","ticket_notes"]}]'
136
+ ```
137
+
138
+ Had the shop a resource or page called `tickets` of its own, it would now refuse to start, naming both: `/tickets` can only be one thing.
139
+
140
+ ## 4. The tickets in the shop
141
+
142
+ Sign in to the shop. The sidebar has a Support group with Tickets and the desk's recent tickets under it, each with its status; `/tickets` is the desk's list, with its columns, its status filter and its search, and the breadcrumbs read "Support › Tickets":
143
+
144
+ A ticket opens at `/tickets/1`, with its notes from the desk, and the trail back to the list. Change the status and Save: the shop's admin app writes it to the desk with the ticket's ETag, under the desk's rules, and the ticket moves in the sidebar. The global search in the top bar finds tickets too.
145
+
146
+ (The stories run on made-up data, with a summary section the next section describes.)
147
+
148
+ Behind it, the shop's admin app read the desk's `/api/meta` with the shop's token, kept the tickets and notes, and placed them as the desk's view says. Every list and save went straight from the browser to the desk.
149
+
150
+ ## 5. A view for the shop's people
151
+
152
+ "Support" is how the desk's agents think of tickets. In the shop they are about customers, and only the open ones matter in the sidebar. The desk decides what the shop's people see, so it gives the role it gave them, `shop`, a [view of its own](../reference/ui-config.md#actions-and-views-per-role)):
153
+
154
+ ```ts
155
+ // desk: config/tickets/ui.ts
156
+ // What the shop's people see: the tickets of their customers, next to the shop's orders, and the open ones first.
157
+ export const shopTicketsView = ticketsView
158
+ .forRoles(['shop'])
159
+ .names({ singular: 'Customer ticket', plural: 'Customer tickets' })
160
+ .nav({ group: 'Sales', recent: { ...recent, filter: 'status != "closed"' } })
161
+ ```
162
+
163
+ After a reload, "Customer tickets" sits in the shop's own Sales group, under Orders, and its recent tickets are the ones still open. The desk's agents still see Support › Tickets.
164
+
165
+ ## 6. When the desk is down
166
+
167
+ Stop the desk and reload the shop. The orders work as before. The tickets stay in the sidebar, under "Service desk" and marked, and `/tickets` says what is wrong, with a way to try again:
168
+
169
+ Start the desk again and press **Try again**: the tickets are back. The same happens when the desk answers but does not accept the shop's sign-in, for instance when its `apps` does not list the shop, with the desk's own reason.
170
+
171
+ ## Custom sections
172
+
173
+ The desk's views can name [custom components](../reference/custom-components.md)), such as a timeline of the ticket with `l.custom(TicketTimeline)`. The shop draws them by name from its [plugins](../reference/plugins.md)), so the desk ships them as a plugin, built with `protobase build-plugin` and served wherever the shop's browser can load it, and the shop lists it with the source, for instance:
174
+
175
+ ```sh
176
+ PROTOBASE_PLUGINS='http://localhost:4720/plugins/desk/plugin.json'
177
+ ```
178
+
179
+ Inside, the component reads the ticket with `useLayoutRecord()`, and `useList` and `useRecord` read the desk for the desk's resources. Without the plugin, the shop draws the component's fallback in its place and everything else of the ticket.
180
+
181
+ ## Where to go from here
182
+
183
+ - [Remote resources](../reference/remote-resources.md)): how it works, the contract between an app and its sources, and the API.
184
+ - [Your first plugin](first-plugin.md)): build the plugin a source's views need.
185
+ - [Access](../reference/access.md)): what the role you give another app's users may do.
@@ -0,0 +1,205 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/guides/table-to-admin.mdx: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # From a table to an admin
4
+
5
+ Pip's bike shop goes from a repairs table to an admin the front desk and the workshop both like, in five steps.
6
+
7
+ Pip runs a bike repair shop. The repairs live in a Postgres table that a booking site writes to and a spreadsheet export reads from, and the front desk keeps a paper card per bike because nothing else shows what they need. Pip wants an admin on top of that table, without moving the data or writing an app.
8
+
9
+ This guide follows that admin from nothing to something the front desk and the workshop both like. Each step is a small change to two config files, and each has a live story you can click through: the same admin, on fourteen repairs of a made-up week.
10
+
11
+ ## 1. The table, as it is
12
+
13
+ Everything starts with the data config: what the tables are, as they are. `protobase scaffold` writes it from the database, and Pip tidies it up:
14
+
15
+ ```ts title="config/data.ts"
16
+ import { f, resource } from '@protobase/schema'
17
+
18
+ // Pip's bike shop: customers bring bikes in, the workshop repairs them. Two tables of a Postgres database the
19
+ // shop already has, described as they are.
20
+
21
+ /** shop.customers */
22
+ export const customers = resource('customers')
23
+ .table('shop.customers')
24
+ .fields({
25
+ id: f.integer().readOnly().filterable().sortable().dbDefault(),
26
+ name: f.text().min(2).filterable().sortable(),
27
+ phone: f.text().regex(/^\+?[0-9 ]{6,}$/, 'Use digits, spaces and an optional +').optional(),
28
+ email: f.text().optional().filterable(),
29
+ country: f.country().default('NL'),
30
+ created_at: f.timestamp().readOnly().filterable().sortable().dbDefault(),
31
+ })
32
+ .primaryKey((r) => r.id)
33
+ .search((r) => [r.name, r.email])
34
+
35
+ /** shop.repairs */
36
+ export const repairs = resource('repairs')
37
+ .table('shop.repairs')
38
+ .fields({
39
+ id: f.integer().readOnly().filterable().sortable().dbDefault(),
40
+ number: f.text().readOnly().filterable().sortable().dbDefault(),
41
+ customer_id: f.relation('customers').filterable().sortable(),
42
+ bike: f.text(),
43
+ problem: f.text(),
44
+ status: f.enum(['booked', 'waiting', 'working', 'ready', 'collected']).default('booked').filterable().sortable(),
45
+ mechanic: f.text().optional().filterable().sortable(),
46
+ estimate: f.decimal({ precision: 8, scale: 2 }).filterable().sortable(),
47
+ currency: f.currency().default('EUR'),
48
+ paid: f.boolean().default(false).filterable(),
49
+ booked_on: f.date().filterable().sortable(),
50
+ notes: f.text().optional().column('internal_notes'),
51
+ legacy_ref: null,
52
+ updated_at: f.timestamp().readOnly().dbDefault(),
53
+ })
54
+ .primaryKey((r) => r.id)
55
+ .search((r) => [r.number, r.bike, r.problem])
56
+ .validate((repair) => (repair.status === 'collected' && !repair.paid ? [{ field: 'paid', message: 'A bike leaves the shop paid' }] : undefined))
57
+ ```
58
+
59
+ The fields follow the columns, with what the database does not say added: which fields can be filtered and sorted, which ones the database fills in (`dbDefault`), which are read-only. `notes` lives in a column called `internal_notes`, and `legacy_ref: null` keeps an old column out for good. The `validate` rule holds the shop's one firm rule: a bike does not leave unpaid.
60
+
61
+ For the admin to list repairs, a view is enough, even an empty one:
62
+
63
+ ```ts title="config/ui.ts"
64
+ import { view } from '@protobase/schema'
65
+ import type { customers, repairs } from './data'
66
+
67
+ // Step 1: an entry in the sidebar for each table, and nothing else. Lists and record pages work from the data config.
68
+
69
+ export const customersView = view<typeof customers>('customers')
70
+
71
+ export const repairsView = view<typeof repairs>('repairs')
72
+ ```
73
+
74
+ That is already a working admin: every column, sorting, paging, a record page and a "New" button.
75
+
76
+ ## 2. Names and columns
77
+
78
+ The list shows everything, including the problem descriptions nobody reads in a list. The front desk wants the repair number, whose bike, what state it is in, and who is on it, newest first.
79
+
80
+ ```ts title="config/ui.ts"
81
+ import { view } from '@protobase/schema'
82
+ import type { customers, repairs } from './data'
83
+
84
+ // Step 2: names, what a record is called, the columns the workshop reads, and how values look.
85
+
86
+ export const customersView = view<typeof customers>('customers')
87
+ .names({ singular: 'Customer', plural: 'Customers' })
88
+ .title((r) => r.name)
89
+ .list((r) => ({ columns: [r.name, r.phone, r.email], sort: [[r.name, 'asc']] }))
90
+
91
+ export const repairsView = view<typeof repairs>('repairs')
92
+ .names({ singular: 'Repair', plural: 'Repairs' })
93
+ .title((r) => r.number)
94
+ .fields((r) => ({
95
+ number: r.number.format('code'),
96
+ customer_id: r.customer_id.label('Customer'),
97
+ status: r.status.format('badge'),
98
+ estimate: r.estimate.prefix('€').decimals(2),
99
+ booked_on: r.booked_on.label('Booked on'),
100
+ }))
101
+ .list((r) => ({
102
+ columns: [r.number, r.customer_id, r.bike, r.status, r.mechanic, r.estimate, r.booked_on],
103
+ sort: [[r.booked_on, 'desc']],
104
+ search: [r.number, r.bike],
105
+ }))
106
+ ```
107
+
108
+ `title` makes "R-303" the name of a repair everywhere: breadcrumbs, links, the record page. `fields` adjusts how values look: statuses become badges, the estimate gets a euro sign and two decimals, and `customer_id` shows as "Customer" (with the customer's name, since it is a relation). `list` picks the columns, the starting order, and what the search box looks in.
109
+
110
+ ## 3. Filters
111
+
112
+ On Saturdays the desk asks the same questions over and over: what is ready, what is Sem working on, what came in this week, what is not paid. Filters answer them in one click.
113
+
114
+ ```ts title="config/ui.ts"
115
+ import { customersView, repairsView as named } from './step-2'
116
+
117
+ // Step 3: the filters the front desk reaches for, and a chart of bookings above the list.
118
+
119
+ export { customersView }
120
+
121
+ export const repairsView = named
122
+ .filters((r, w) => [
123
+ w.facets(r.status),
124
+ w.facets(r.mechanic, { search: true }),
125
+ w.dateRange(r.booked_on, { presets: ['7d', '30d', 'month'] }),
126
+ w.range(r.estimate, { histogram: true }),
127
+ w.toggle(r.paid),
128
+ ])
129
+ .chart((r) => ({ field: r.booked_on, range: '30d', granularity: 'day' }))
130
+ ```
131
+
132
+ From here on each step starts from the view of the step before (`named` is step 2's), so the file shows only what changes; in a project it is one view in one `ui.ts`. Each widget writes into the list's `?filter=`, so "ready and unpaid" is a link someone can send. The chart above the list, a daily graph, counts repairs per day, following the same filters; [UI config](../reference/ui-config.md#charts-graphs-records-per-day-week-or-month-or-per-value-above-a-list)) has its ranges and granularities. In the story, switch on "Paid" and watch the list drop to six.
133
+
134
+ ## 4. The repair card
135
+
136
+ The record page still lists every field in one long column. The paper card the desk uses has three parts: the bike and its problem, the workshop's side, and the money. The layout copies it.
137
+
138
+ ```ts title="config/ui.ts"
139
+ import { l } from '@protobase/schema'
140
+ import { customersView, repairsView as filtered } from './step-3'
141
+
142
+ // Step 4: a record page that reads like the paper repair card: what is wrong, who works on it, what it costs.
143
+
144
+ export { customersView }
145
+
146
+ export const repairsView = filtered
147
+ .fields((r) => ({
148
+ problem: r.problem.help('In the customer’s words; the mechanic adds findings to the notes.'),
149
+ notes: r.notes.label('Workshop notes').help('Only the workshop reads these.'),
150
+ paid: r.paid.help('Set when the customer pays at the desk.'),
151
+ }))
152
+ .layout((r) => [
153
+ l.section('The bike', [r.customer_id, r.bike, r.problem]),
154
+ l.section('In the workshop', [r.status, r.mechanic, r.notes], { help: 'Pick up a repair by putting your name on it.' }),
155
+ l.section('Money', [r.estimate, r.currency, r.paid]),
156
+ l.sidebar([r.status, r.estimate, r.booked_on]),
157
+ ])
158
+ .saveFeedback('button')
159
+ ```
160
+
161
+ Sections group fields under a title, with help where the shop has a habit to explain. The sidebar repeats what matters at a glance and stays read-only. `saveFeedback('button')` makes Save say when it is done, since the desk prefers that to a toast.
162
+
163
+ The form and the [read view](../reference/ui-config.md#form-and-read-view)), which a user who may change nothing gets, share the layout. An item or field meant for one of them says so with `when`: `'editing'` keeps it to the form, `'reading'` to the read view. A table of the parts used, for whoever fills in the repair:
164
+
165
+ ```ts
166
+ l.related('Parts used', { resource: 'repair_parts', field: 'repair_id', when: 'editing' })
167
+ ```
168
+
169
+ ## 5. Daily moves, and the workshop's own view
170
+
171
+ Two things happen to every repair: it becomes ready, and it gets collected (and paid). Typing a status into a dropdown is how mistakes happen, so they become buttons. And the mechanics would rather not see prices at all.
172
+
173
+ ```ts title="config/ui.ts"
174
+ import { l } from '@protobase/schema'
175
+ import { customersView, repairsView as laidOut } from './step-4'
176
+
177
+ // Step 5: buttons for the moves the shop makes all day, and a quieter view for the mechanics.
178
+
179
+ export { customersView }
180
+
181
+ export const repairsView = laidOut.actions((a) => [
182
+ a.update('ready', { label: 'Ready for pickup', icon: 'send', set: { status: 'ready' } }),
183
+ a.update('collect', { label: 'Collected and paid', icon: 'wallet', set: { status: 'collected', paid: true }, confirm: 'Has the customer paid and taken the bike?' }),
184
+ a.link('customerRepairs', { label: 'Other repairs of this customer', icon: 'file-text', to: { kind: 'list', resource: 'repairs', filter: 'customer_id = {customer_id}' } }),
185
+ ])
186
+
187
+ /** What mechanics get instead: no money, and their own move. */
188
+ export const workshopRepairsView = laidOut
189
+ .forRoles(['mechanic'])
190
+ .list((r) => ({ columns: [r.number, r.bike, r.problem, r.status, r.mechanic], sort: [[r.booked_on, 'asc']], search: [r.number, r.bike] }))
191
+ .filters((r, w) => [w.facets(r.status), w.facets(r.mechanic, { search: true }), w.dateRange(r.booked_on, { presets: ['7d', '30d', 'month'] })])
192
+ .layout((r) => [l.section('The bike', [r.bike, r.problem]), l.section('In the workshop', [r.status, r.mechanic, r.notes]), l.sidebar([r.status, r.booked_on])])
193
+ .actions((a) => [a.update('ready', { label: 'Ready for pickup', icon: 'send', set: { status: 'ready' } })])
194
+ ```
195
+
196
+ `a.update` sets fields when its button is pressed, through the same API as Save, so the access rules and the `validate` rule apply. "Collected and paid" asks first. `a.link` goes `to` the list of this customer's repairs, an address with the customer filled in from the record. Try the three buttons in the story, on R-303:
197
+
198
+ `forRoles(['mechanic'])` gives users with the `mechanic` role their own view: oldest first, no money columns, no money filter, a card without the money section, and only the "Ready for pickup" button. It is built from the step 4 view, so everything else stays the same. A view only decides what is shown; to make the prices truly unreadable for mechanics, give the field an access rule as well (see [Data config](../reference/data-config.md#access))).
199
+
200
+ ## Where Pip is now
201
+
202
+ Two short files describe a table and how the shop wants to see it, and the admin follows: lists, filters, a record page, buttons and a view per role. Next steps:
203
+
204
+ - [Data config](../reference/data-config.md)) and [UI config](../reference/ui-config.md)) list every option used here, and the ones that were not.
205
+ - [Your first composed page](first-composed-page.md)) puts what needs attention on one page.
@@ -0,0 +1,87 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/guides/theme-an-app.md: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # Theming an app
4
+
5
+ Give an app its own colors, corners and font with protobase.theme.css, in light and dark, and keep them through every release.
6
+
7
+ Rijnland Industrial Supply wants its admin in its own colors: teal instead of blue, rounder corners and its own font. That is one file of values, `protobase.theme.css`, which the app reads on every page, the sign-in page included. This guide writes it for the ERP example (`examples/erp`); any project works the same. [Theme](../reference/theme.md)) has every token.
8
+
9
+ ## 1. The light values
10
+
11
+ Create `protobase.theme.css` at the project root, beside `protobase.config.ts`, and set the tokens you want to change under `:root`:
12
+
13
+ ```css
14
+ /* protobase.theme.css */
15
+ :root {
16
+ --primary: #0d9488;
17
+ --primary-hover: #0f766e;
18
+ --primary-soft: #f0fdfa;
19
+ --primary-border: #99f6e4;
20
+ --primary-text: #0f766e;
21
+ --sidebar: #f5faf9;
22
+ }
23
+ ```
24
+
25
+ The primary group goes together: the color of buttons and the selected item, its hover, a soft background for selected rows, a border for those, and the color of text and links. Start `bun run protobase dev` and sign in: the buttons, links, the sidebar's selected item and the chart are teal. Every other token keeps the app's value.
26
+
27
+ Only values are allowed. A selector such as `.sidebar`, or a property such as `color`, fails the build, naming the line it is on, and `protobase dev` answers the theme with that error and draws the app without it; the [file's rules](../reference/theme.md#the-file)) say why. To change how one part looks beyond its tokens, replace it with a plugin, such as a [record card](record-card.md)).
28
+
29
+ ## 2. Corners and font
30
+
31
+ ```css
32
+ :root {
33
+ /* ... */
34
+ --radius: 10px;
35
+ --font: Georgia, "Times New Roman", serif;
36
+ }
37
+ ```
38
+
39
+ `--radius` sets every rounded corner: buttons, inputs and menus take it, cards two pixels more. `--font` is the app's text, and `--font-code` the font of identifiers and code. Reload: the app is rounder and set in Georgia.
40
+
41
+ A font the browser does not have comes with an `@font-face` rule in the same file, its files served by the app, a CDN or a font service:
42
+
43
+ ```css
44
+ @font-face {
45
+ font-family: Inter;
46
+ src: url(https://fonts.example.com/inter-var.woff2) format("woff2");
47
+ font-weight: 100 900;
48
+ }
49
+
50
+ :root {
51
+ --font: Inter, ui-sans-serif, system-ui, sans-serif;
52
+ }
53
+ ```
54
+
55
+ ## 3. Dark
56
+
57
+ The app draws in light or dark as each user chooses in the profile menu, and follows their system until they choose ([Light, dark or the system](../reference/theme.md#light-dark-or-the-system))). Values under `:root` hold for both, so teal on white is also teal on near-black. Give dark its own where it needs them, under `[data-theme="dark"]`:
58
+
59
+ ```css
60
+ [data-theme="dark"] {
61
+ --primary: #2dd4bf;
62
+ --primary-hover: #5eead4;
63
+ --primary-foreground: #042f2e;
64
+ --primary-soft: #11302c;
65
+ --primary-text: #5eead4;
66
+ }
67
+ ```
68
+
69
+ A light teal needs dark text on it, so the button's text, `--primary-foreground`, turns near-black here. A soft background from `:root` would glare on the dark page, so `--primary-soft` gets a dark one too. Pick "Dark" in the profile menu to check each screen, the sign-in page included.
70
+
71
+ ## 4. Build and ship
72
+
73
+ ```sh
74
+ bun run protobase build
75
+ ```
76
+
77
+ The build checks the theme as `protobase dev` does, minifies it, and writes it to `dist/public/protobase.theme.css`, which the app links after its own stylesheets. A token the app does not read is printed as a warning, since it is most likely a typo:
78
+
79
+ ```
80
+ warning: protobase.theme.css:1: --primry is not a token the app reads; check its name
81
+ ```
82
+
83
+ Ship the bundle as before. The theme is a file of the bundle like the others, so a static host serves it, with `no-cache` so a change shows on the next load.
84
+
85
+ ## When the app moves on
86
+
87
+ The theme holds no selectors into the app, only the values of tokens, and releases only ever add tokens. So it applies the same way after every update, and a token that is added later keeps the app's value until the theme sets it. Plugins follow it too: their `bg-primary` and `rounded-md` read the same tokens, so the sales team's [plugins](../reference/plugins.md)) are teal and round in this app, and blue and square in another.
@@ -0,0 +1,115 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/access.mdx: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # Access
4
+
5
+ Roles, capabilities with field lists and row filters, field rules, anonymous access, and what they default to.
6
+
7
+ Roles are defined in code ([`defineRoles`](https://docs.protobase.net/api/schema/functions/defineroles/))) and assigned through the auth user's `roles`; with [organizations](auth.md#organizations)), also per membership, and `ctx.user.roles` holds both, while `ctx.organization.id` is the organization the request works in. Rules decide per operation (`list`, `read`, `create`, `update`, `delete`), per field (role-based, never per record) and per row (filters, like RLS).
8
+
9
+ ## Defaults
10
+
11
+ - A project that passes `roles` to `resolveAccess` is **default deny**: an operation without a rule needs the capability `<resource>.<action>` (`list` uses `read`), so admin's `*` still passes. A field without a rule follows its resource.
12
+ - A project without roles (the single-admin case) is **default allow**.
13
+ - `defaultAccess: 'allow'` together with `roles` is an explicit opt-in. Print `accessWarnings(options)` at startup.
14
+ - Every request needs a token, unless the roles define [`anonymous`](#anonymous-access).
15
+
16
+ ## Capabilities
17
+
18
+ A role is a list of capabilities, `<resource|area>.<action>[.<scope>]`: `orders.read`, `orders.update.own`, `costs.read` (an area, for field rules), `*.read` or `*`. An entry may also be an object that limits capabilities to fields, rows or both:
19
+
20
+ ```ts
21
+ defineRoles<'orders' | 'products'>({
22
+ sales: ['orders.read.own', 'orders.create', 'products.read'],
23
+ erp_sync: [{ 'products.read': ['sku', 'price', 'stock'] }, { 'products.update': ['stock'] }],
24
+ reseller: [{ 'products.read': { fields: ['sku', 'name', 'price'], filter: 'published = true' } }],
25
+ })
26
+ ```
27
+
28
+ - **Fields** (`['sku', 'price']`, or `fields` in an object) are an allowlist: for `<resource>.read`, `.create` or `.update`, the role reads or writes only the fields listed, so a column added later stays hidden from it until someone lists it. Key columns are always there, because records are addressed by them. A plain capability (`'products.read'`) still means every field.
29
+ - **Filter** is AIP-160 text, like a filter an access rule returns. It narrows the rows of the capability, together with `.own` or `.team` when the capability has one.
30
+ - A limit names one resource, never `*`, and fields go with `read`, `create` or `update` only; `defineRoles` refuses anything else. At startup the server refuses a field the resource does not have, a filter that does not fit it, and a limit on a name that is not a resource.
31
+
32
+ A field is readable when the role's list allows it and the field's own [rule](#field-rules-or-field-lists) passes. Field lists take effect through the roles the server gets (`options: { roles }` in `protobase.config.ts`, `resolveAccess(source, ctx, { roles })`), for every resource whatever its rules. A filter is the capability's row filter, so like `.own` it applies where the capability decides: an operation without a rule, or a rule built with `roles.can(...)`.
33
+
34
+ **Several roles add up.** A user gets every field one of their roles lists (all of them when a role holds the plain capability) and the rows any of their roles allows. Fields and rows add up separately: someone holding both `erp_sync` and `reseller` above reads `name` on unpublished products too. With Better Auth a session acts with one [active role](auth.md#active-role)) at a time, so this only comes up with an authenticator that hands out several.
35
+
36
+ ## Anonymous access
37
+
38
+ The role `anonymous` is what a request without a token acts as. A project without it answers such requests `401`, as always.
39
+
40
+ ```ts
41
+ anonymous: [{ 'products.read': { fields: ['name', 'slug', 'price', 'image'], filter: 'published = true' } }],
42
+ ```
43
+
44
+ - **It reads listed fields, and creates them through a public form only.** Each entry names one resource, `read` or `create` without a scope, and its fields; `defineRoles` refuses other capabilities, wildcards, `.own` and `.team`, and a capability without a field list, so nothing becomes public by accident, a new column included. A `create` is used by the resource's [public forms](forms.md)) alone, behind their rate limit and bot check: everywhere else it does not exist.
45
+ - **No token, not a bad one.** A request without an `Authorization` header is served as a caller holding only this role, in no organization. A header with anything but a valid, unexpired token is still a `401`. `jwtAuthenticator` and `betterAuthAuthenticator` tell the two apart; an authenticator of your own throws `MissingCredentials` (from `@protobase/server`) for a request without a credential to do the same.
46
+ - **Only its capabilities open anything.** The capability is ANDed into a resource's access rule, so a rule that allows everyone (`read: () => true`) or `defaultAccess: 'allow'` never lets an anonymous caller in on its own.
47
+ - **The resources API and `/api/meta` only.** Lists, records, `:search`, `:seek` and the aggregates of what the role reads, with filters, sorts and `fields` checked as for everyone: an unlisted field is refused like an unknown one. A resource it cannot read is a `404`; a write, or another operation it may not do on a resource it reads, is a `401` that asks for a token, a `create` it holds for a form included. `/api/meta` describes what it reads, for the [admin app](#browsing-the-admin-app). `/api/openapi.json`, `/api/docs`, batch writes, [API functions](../guides/api-functions.md)), the assistant and the file cleanup still need a token. A [file field](files.md#downloads)) it reads comes with its link, as for anyone.
48
+ - A tenant-scoped resource (`.tenant`) cannot be in it, since an anonymous caller works in no organization; the server refuses to start.
49
+ - Reading has no rate limit of its own: put a proxy or CDN in front of a public API to limit and cache requests. [Public forms](forms.md#rate-limit)) limit their submissions.
50
+
51
+ ### Browsing the admin app
52
+
53
+ With an anonymous role that reads a resource, `GET /api/auth/status` says `"anonymous": true`, and the admin app opens for someone who is not signed in instead of the sign-in page: the sidebar, lists, displays, filters and record pages of what the role reads, read-only, with the views and pages of the role `anonymous` (a view `.forRoles(['anonymous'])` is theirs alone). The sidebar has a **Sign in** button where the profile menu would be. It opens the sign-in route, `/-/sign-in`, a page of its own: the browser's Back, or **Continue without signing in**, returns to browsing, and signing in comes back to the page it was opened from. Signing out returns to browsing. A link for the sign-in steps, such as a password reset, still opens its page. An anonymous role that only creates, for public forms, leaves the app behind sign-in.
54
+
55
+ ## Use cases
56
+
57
+ One shop's catalog, read by its staff, by the warehouse system and by web store visitors. CI typechecks and tests the file:
58
+
59
+ ```ts title="docs-examples/reference/catalog.ts"
60
+ import { defineRoles, f, resource } from '@protobase/schema'
61
+
62
+ // A shop's catalog, read by its staff, by the warehouse system and by visitors of the web store, who sign in to nothing.
63
+
64
+ export const roles = defineRoles<'products' | 'costs'>({
65
+ admin: ['*'],
66
+ editor: ['products.read', 'products.create', 'products.update'],
67
+ buyer: ['products.read', 'costs.read'],
68
+ // The warehouse system reads three columns and changes one. A column added later stays hidden from it.
69
+ erp_sync: [{ 'products.read': ['sku', 'price', 'stock'] }, { 'products.update': ['stock'] }],
70
+ // Requests without a token: what the web store shows, of published products only.
71
+ anonymous: [{ 'products.read': { fields: ['name', 'slug', 'price', 'image'], filter: 'published = true' } }],
72
+ })
73
+
74
+ /** shop.products */
75
+ export const products = resource('products')
76
+ .table('shop.products')
77
+ .fields({
78
+ id: f.integer().readOnly().filterable().sortable().dbDefault(),
79
+ sku: f.text().filterable().sortable(),
80
+ name: f.text().filterable().sortable(),
81
+ slug: f.text().filterable(),
82
+ price: f.decimal({ precision: 10, scale: 2 }).filterable().sortable(),
83
+ // Whoever reads products, only roles holding `costs.read` see what one costs the shop.
84
+ cost_price: f.decimal({ precision: 10, scale: 2 }).access({ read: roles.can('costs.read') }),
85
+ stock: f.integer().filterable(),
86
+ image: f.file().accept(['image/*']).public().optional(),
87
+ published: f.boolean().default(false).filterable(),
88
+ })
89
+ .primaryKey((r) => r.id)
90
+ .search((r) => [r.name, r.sku])
91
+ ```
92
+
93
+ ### A public storefront catalog
94
+
95
+ The web store lists products without signing in:
96
+
97
+ ```sh
98
+ curl 'https://shop.example.com/api/v1/products?order_by=name&page_size=20'
99
+ ```
100
+
101
+ Each item has `id`, `name`, `slug`, `price` and `image`, of published products only: a draft's URL is a `404`. `filter=cost_price < 10` or `order_by=stock` is a `400`, worded as an unknown field, and a `PATCH` without a token is a `401`. The staff sign in as before and see what their roles allow. A column added to `shop.products` later, such as a supplier, stays off the store until it is added to the list.
102
+
103
+ ### An integration limited to some columns
104
+
105
+ `erp_sync` is a role for a system: a user with that role, and a token for it ([`issueToken`](auth.md#tokens-for-scripts-and-curl))). It reads `sku`, `price` and `stock` of every product and writes only `stock`; a `PATCH` with `price` is a `400`, as for a field it cannot see, and `cost_price` is not in its responses. A role that only uses the API needs no view: views shape the admin app, while what a caller may see and do is decided here.
106
+
107
+ ### Field rules or field lists
108
+
109
+ A field rule goes from the field to the roles: `cost_price` above is hidden from every role that reads products but those holding `costs.read`. Use it for the few sensitive columns of a resource that many roles read, such as a screening result (`f.text().access({ read: roles.can('screening.read') })`). A field list goes from the role to the fields: use it for a role that should see only some columns, such as an integration or anonymous visitors, so a new column stays hidden from it. When both apply, a field needs both.
110
+
111
+ ## Restricted model and row filters
112
+
113
+ [`resolveAccess`](https://docs.protobase.net/api/schema/functions/resolveaccess/)) returns everything a request may do. Use [`restrictModel(model, access)`](https://docs.protobase.net/api/schema/functions/restrictmodel/)) for everything user-facing (checking filters and sorts, queries, OpenAPI, `/meta`): hidden fields are gone, so they cannot be referenced, searched, sorted or leaked. Key columns always stay, because records are addressed by them.
114
+
115
+ Row filters (`access.rowFilter`) are a separate thing. They come from the access rules (`.own`, `.team`, filters of capabilities, returned filters), are checked against the **full** model because they may use hidden or non-filterable columns, and are ANDed into queries by the server.