@protobase/cli 0.47.1 → 0.49.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 (101) hide show
  1. package/dist/build/config-bundle.js +6 -1
  2. package/dist/build/entry-code.js +30 -17
  3. package/dist/cli/package.js +1 -1
  4. package/dist/config/build-project.js +70 -0
  5. package/dist/config/called-config.js +11 -0
  6. package/dist/config/config-defaults.js +30 -0
  7. package/dist/config/env-values.js +20 -0
  8. package/dist/config/lazy-imports.js +18 -0
  9. package/dist/config/merge-config.js +72 -0
  10. package/dist/config/project-files.js +48 -0
  11. package/dist/config/project-parts.js +201 -0
  12. package/dist/config/read-config.js +31 -0
  13. package/dist/config/source-config.js +37 -0
  14. package/dist/dev/api-child.js +2 -1
  15. package/dist/dev/api-process.d.ts +1 -0
  16. package/dist/dev/api-process.js +5 -2
  17. package/dist/dev/auth-drift-lines.js +8 -0
  18. package/dist/dev/create-db.js +2 -2
  19. package/dist/dev/entry.d.ts +5 -0
  20. package/dist/dev/entry.js +17 -12
  21. package/dist/dev/project.js +23 -47
  22. package/dist/dev/run.js +3 -2
  23. package/dist/main.js +3 -3
  24. package/dist/migration/load-project.js +34 -34
  25. package/dist/migration/parts.js +2 -2
  26. package/dist/migration/summary.js +2 -2
  27. package/dist/mobile/api-origin.js +4 -4
  28. package/dist/mobile/load-project.js +13 -12
  29. package/dist/mobile/register.js +1 -1
  30. package/dist/mobile/run.js +1 -1
  31. package/dist/organizations/register.js +1 -1
  32. package/dist/project/error-reporter.js +3 -3
  33. package/dist/project/import-project-file.js +4 -2
  34. package/dist/project/load-bundle-project.js +16 -25
  35. package/dist/project/load-data-config.js +2 -2
  36. package/dist/project/pg-db.js +10 -4
  37. package/dist/project/placeholder-secret.js +2 -2
  38. package/dist/project/project-admin.js +12 -11
  39. package/dist/scaffold/plan.js +7 -3
  40. package/dist/scaffold/protobase-tables.js +8 -13
  41. package/dist/scaffold/run.js +1 -1
  42. package/dist/serve/create-admin.js +9 -4
  43. package/dist/serve/host-module-ids.js +1 -0
  44. package/dist/serve/host-modules.js +3 -1
  45. package/dist/serve/lifecycle.js +19 -14
  46. package/dist/serve/load-bundle.js +41 -11
  47. package/dist/serve/mobile-release.js +1 -1
  48. package/dist/serve/serve-bundle.js +3 -3
  49. package/dist/supabase/auth-config.js +33 -28
  50. package/dist/supabase/config-jobs.js +28 -27
  51. package/dist/supabase/config-object.js +25 -0
  52. package/dist/supabase/cron-job-file.js +13 -14
  53. package/dist/supabase/cron-jobs-write.js +6 -12
  54. package/dist/supabase/cron-plan.js +3 -51
  55. package/dist/supabase/project-files.js +4 -9
  56. package/dist/supabase/report.js +3 -3
  57. package/dist/users/load-auth.js +16 -15
  58. package/dist/worker/start-worker.js +18 -15
  59. package/package.json +8 -6
  60. package/skills/protobase/SKILL.md +2 -1
  61. package/skills/protobase/references/features/notifications.md +1 -1
  62. package/skills/protobase/references/features/sign-in-and-accounts.md +1 -0
  63. package/skills/protobase/references/features/start-a-project.md +3 -0
  64. package/skills/protobase/references/getting-started.md +2 -2
  65. package/skills/protobase/references/guides/api-functions.md +4 -4
  66. package/skills/protobase/references/guides/deploy.md +8 -8
  67. package/skills/protobase/references/guides/existing-database.md +11 -31
  68. package/skills/protobase/references/guides/first-plugin.md +1 -1
  69. package/skills/protobase/references/guides/mobile-app.md +5 -3
  70. package/skills/protobase/references/guides/plugin-build.md +1 -1
  71. package/skills/protobase/references/guides/push-notifications.md +6 -7
  72. package/skills/protobase/references/guides/remote-resources.md +22 -31
  73. package/skills/protobase/references/reference/access.md +3 -3
  74. package/skills/protobase/references/reference/ai.md +1 -9
  75. package/skills/protobase/references/reference/api.md +15 -15
  76. package/skills/protobase/references/reference/app-identity.md +9 -10
  77. package/skills/protobase/references/reference/assistant.md +6 -6
  78. package/skills/protobase/references/reference/auth.md +126 -96
  79. package/skills/protobase/references/reference/bottom-bar.md +1 -1
  80. package/skills/protobase/references/reference/cli.md +36 -86
  81. package/skills/protobase/references/reference/comments.md +0 -8
  82. package/skills/protobase/references/reference/config.md +152 -0
  83. package/skills/protobase/references/reference/data-config.md +2 -2
  84. package/skills/protobase/references/reference/email.md +36 -37
  85. package/skills/protobase/references/reference/events.md +1 -1
  86. package/skills/protobase/references/reference/files.md +18 -23
  87. package/skills/protobase/references/reference/forms.md +5 -17
  88. package/skills/protobase/references/reference/history.md +2 -3
  89. package/skills/protobase/references/reference/installable-app.md +1 -1
  90. package/skills/protobase/references/reference/jobs.md +53 -56
  91. package/skills/protobase/references/reference/languages.md +4 -2
  92. package/skills/protobase/references/reference/mcp.md +11 -11
  93. package/skills/protobase/references/reference/notifications.md +26 -24
  94. package/skills/protobase/references/reference/plugins.md +11 -14
  95. package/skills/protobase/references/reference/remote-resources.md +18 -24
  96. package/skills/protobase/references/reference/supabase-realtime.md +1 -1
  97. package/skills/protobase/references/reference/supabase-rest.md +1 -1
  98. package/skills/protobase/references/reference/supabase-storage.md +1 -1
  99. package/skills/protobase/references/reference/ui-config.md +15 -17
  100. package/skills/protobase/references/reference/versioning.md +1 -1
  101. package/skills/protobase/references/reference/webhooks.md +6 -7
@@ -275,7 +275,7 @@ No other field of the resource may be over the column, as its own or as a relati
275
275
 
276
276
  ### The key
277
277
 
278
- The app's key is `PROTOBASE_ENCRYPTION_KEY`: 32 random bytes in base64, such as the output of `openssl rand -base64 32`. It is its own: never `BETTER_AUTH_SECRET` or an API key, nor derived from one, so rotating those loses nothing. Keep it apart from the database's backups, since whoever holds both reads every value. The server does not start with an encrypted field and no key, or a key that is not 32 bytes in base64.
278
+ The app's key is `PROTOBASE_ENCRYPTION_KEY`: 32 random bytes in base64, such as the output of `openssl rand -base64 32`. It is its own: never the app's `secret` (`PROTOBASE_SECRET`) or an API key, nor derived from one, so rotating those loses nothing. Keep it apart from the database's backups, since whoever holds both reads every value. The server does not start with an encrypted field and no key, or a key that is not 32 bytes in base64.
279
279
 
280
280
  To rotate it on several instances:
281
281
 
@@ -396,7 +396,7 @@ export const workOrders = resource('work_orders')
396
396
  })
397
397
  ```
398
398
 
399
- 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:
399
+ Export the roles as `roles` from `config/roles.ts`, where the server finds them, and every operation without a rule needs its capability (`<resource>.<action>`). The ERP's orders use `.owner` and `.search` with the ERP's roles:
400
400
 
401
401
  ```ts title="examples/erp/config/orders/data.ts"
402
402
  import { f, resource } from '@protobase/schema'
@@ -12,7 +12,7 @@ An app sends mail through one SMTP server: Protobase's own mail ([password reset
12
12
  | --- | --- |
13
13
  | `PROTOBASE_SMTP_URL` | The SMTP server, credential included: `smtp://user:password@host:587` (STARTTLS when the server offers it) or `smtps://user:password@host:465` (TLS from the start). |
14
14
  | `PROTOBASE_MAIL_FROM` | The sender, a plain address such as `noreply@shop.example.com`. The client greets the server with its domain; a `?name=` on the URL overrides that. |
15
- | `PROTOBASE_APP_NAME` | Optional: the app's name, such as `Shop`, which mail clients show as the sender's name (`Shop <noreply@shop.example.com>`). It overrides [`createAuth`'s `appName`](auth.md#configuration). Without either the sender has no name. |
15
+ | `PROTOBASE_APP_NAME` | Optional: the app's name, such as `Shop`, which mail clients show as the sender's name (`Shop <noreply@shop.example.com>`). It overrides the config's [`name`](config.md#keys). Without either the sender has no name. |
16
16
 
17
17
  Set both or neither. One without the other, a URL that is not `smtp://` or `smtps://`, or a sender that is not a plain address stops the app at startup. Without them mail is off: password reset and emailed codes are not offered, a job's `mail` is `undefined`, and sending an app's email rejects.
18
18
 
@@ -26,7 +26,7 @@ PROTOBASE_SMTP_URL=smtp://localhost:1025
26
26
  PROTOBASE_MAIL_FROM=noreply@shop.example.com
27
27
  ```
28
28
 
29
- A project that delivers mail another way passes a `mailer`, `{ send({ to, subject, text, html, headers }) }`, to [`createAuth`](auth.md#password-reset) and `startJobs`, or `mailer: false` to turn mail off whatever the environment says. A template's `send` takes one too, see [Templates](#templates).
29
+ A project that delivers sign-in's mail another way exports a mailer, `{ send({ to, subject, text, html, headers }) }`, as the default of `auth/mailer.ts`; `auth: { mailer: false }` turns that mail off whatever the environment says. A host that runs jobs itself passes a mailer to `startJobs`. A template's `send` takes one too, see [Templates](#templates).
30
30
 
31
31
  ## Protobase's own mail
32
32
 
@@ -130,49 +130,48 @@ They are apart from `@protobase/server` itself, so an app that imports none neve
130
130
 
131
131
  A **job** is the usual place: it runs after the write that asked for it has committed, and a message the server refuses fails the try, which is retried. Pass the job's `mail`, so a job runtime started with a mailer of its own sends through it:
132
132
 
133
- ```ts title="config/jobs.ts"
134
- import { defineJob, FatalJobError } from '@protobase/server'
135
- import { z } from 'zod'
136
- import { repairReady } from './repair-ready'
137
-
138
- // Enqueued by the write hook of a repair that became ready (see protobase.config.ts), so the email goes out only once
139
- // the write has committed, and a refused message is retried.
140
- export const emailRepairReady = defineJob({
141
- name: 'email-repair-ready',
142
- payload: z.object({ repairId: z.number() }),
143
- run: async ({ repairId }, { db, mail }) => {
144
- if (!mail) throw new FatalJobError('Mail is off: set PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM')
145
- const repair = await db
146
- .selectFrom('repairs')
147
- .innerJoin('customers', 'customers.id', 'repairs.customer_id')
148
- .select(['repairs.number', 'repairs.bike', 'customers.name', 'customers.email'])
149
- .where('repairs.id', '=', repairId)
150
- .executeTakeFirst()
151
- if (!repair?.email) return
152
- const url = `https://bikeshop.example.com/repairs/${repair.number}`
153
- await repairReady.send(repair.email, { customer: repair.name, bike: repair.bike, number: repair.number, url }, mail)
154
- },
155
- })
133
+ ```ts title="jobs/email-repair-ready.ts"
134
+ import { FatalJobError, type JobRun } from '@protobase/server'
135
+ import { repairReady } from '../repair-ready'
136
+
137
+ // Enqueued by the write hook of a repair that became ready (hooks/email-ready-repair.ts), so the email goes out only
138
+ // once the write has committed, and a refused message is retried.
139
+ export default (async ({ repairId }, { db, mail }) => {
140
+ if (!mail) throw new FatalJobError('Mail is off: set PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM')
141
+ const repair = await db
142
+ .selectFrom('repairs')
143
+ .innerJoin('customers', 'customers.id', 'repairs.customer_id')
144
+ .select(['repairs.number', 'repairs.bike', 'customers.name', 'customers.email'])
145
+ .where('repairs.id', '=', repairId)
146
+ .executeTakeFirst()
147
+ if (!repair?.email) return
148
+ const url = `https://bikeshop.example.com/repairs/${repair.number}`
149
+ await repairReady.send(repair.email, { customer: repair.name, bike: repair.bike, number: repair.number, url }, mail)
150
+ }) satisfies JobRun<{ repairId: number }>
156
151
  ```
157
152
 
158
153
  A **write hook** runs in the write's transaction, which may still roll back. It enqueues the job rather than sending, so the email goes out only for a write that committed:
159
154
 
155
+ ```ts title="hooks/email-ready-repair.ts"
156
+ import { enqueueJob, type PipelineHook } from '@protobase/server'
157
+
158
+ // The job commits with the write, or not at all: no email about a change that was rolled back.
159
+ export default (async (event, trx) => {
160
+ if (event.resource.name !== 'repairs' || event.after?.status !== 'ready' || event.before?.status === 'ready') return
161
+ await enqueueJob(trx, 'email-repair-ready', { repairId: Number(event.after.id) })
162
+ }) satisfies PipelineHook
163
+ ```
164
+
160
165
  ```ts title="protobase.config.ts"
161
- import { defineConfig } from '@protobase/server'
162
- import * as jobs from './jobs'
166
+ import { defineConfig } from '@protobase/config'
163
167
 
164
168
  export default defineConfig({
165
- config: {},
166
- jobs,
167
- options: {
168
- writeHooks: [
169
- // The job commits with the write, or not at all: no email about a change that was rolled back.
170
- async (event, trx) => {
171
- if (event.resource.name !== 'repairs' || event.after?.status !== 'ready' || event.before?.status === 'ready') return
172
- await jobs.emailRepairReady.enqueue(trx, { repairId: Number(event.after.id) })
173
- },
174
- ],
169
+ jobs: {
170
+ // jobs/email-repair-ready.ts
171
+ 'email-repair-ready': { description: 'Emails a customer that their repair is ready for pickup.', arguments: { repairId: 'integer' } },
175
172
  },
173
+ // hooks/email-ready-repair.ts
174
+ writeHooks: ['email-ready-repair'],
176
175
  })
177
176
  ```
178
177
 
@@ -97,7 +97,7 @@ Two transaction settings steer the capture:
97
97
  For a database that already has a schema named `changes`, pick another name in `protobase.config.ts`; the settings take the same prefix:
98
98
 
99
99
  ```ts
100
- export default defineConfig({ config, auth, authenticate, events: { schema: 'row_changes' } })
100
+ export default defineConfig({ events: { schema: 'row_changes' } })
101
101
  ```
102
102
 
103
103
  ## Migrations and startup
@@ -81,30 +81,28 @@ An image with variants also has `variants`, each `{ url, type, width, height }`
81
81
  ## Providers
82
82
 
83
83
  ```ts title="protobase.config.ts"
84
- import sharp from 'sharp'
85
- import { defineConfig, localFiles } from '@protobase/server'
86
- import * as config from './config'
84
+ import { defineConfig } from '@protobase/config'
87
85
 
88
86
  export default defineConfig({
89
- config,
90
87
  files: {
91
88
  providers: {
92
- private: localFiles({ dir: './data/files/private' }),
93
- public: localFiles({ dir: './data/files/public', public: true }),
94
- archive: localFiles({ dir: '/mnt/archive', retention: '30 days' }),
89
+ private: { kind: 'local', dir: './data/files/private' },
90
+ public: { kind: 'local', dir: './data/files/public', public: true },
91
+ archive: { kind: 'local', dir: '/mnt/archive', retention: '30 days' },
95
92
  },
96
93
  retention: '1 day',
97
94
  // Makes the image variants and placeholders
98
- sharp,
95
+ images: 'sharp',
99
96
  },
100
97
  })
101
98
  ```
102
99
 
103
- - `localFiles({ dir, public?, publicUrl?, retention? })` keeps files in a folder on local disk. Writes go to a temporary file first and are renamed into place, so nobody reads half a file. A full disk or quota answers `507`.
104
- - `s3Files({ bucket, prefix?, endpoint?, region?, public?, publicUrl?, retention? })` keeps them in an S3-compatible bucket, see [S3-compatible buckets](#s3-compatible-buckets).
100
+ - `{ kind: 'local', dir, public?, publicUrl?, retention? }` keeps files in a folder on local disk. Writes go to a temporary file first and are renamed into place, so nobody reads half a file. A full disk or quota answers `507`.
101
+ - `{ kind: 's3', bucket, prefix?, endpoint?, region?, public?, publicUrl?, retention? }` keeps them in an S3-compatible bucket, see [S3-compatible buckets](#s3-compatible-buckets).
102
+ - `{ kind: 'custom' }` is a `FileProvider` of the project's own, the default export of `files/<name>.ts`.
105
103
  - Without config, `private` and `public` are the folders `data/files/private` and `data/files/public`, created when needed. Any other provider a field names must be configured.
106
104
  - `PROTOBASE_FILES_<NAME>` configures a provider from the environment and wins over the config for that name: `PROTOBASE_FILES_PRIVATE=file:///data/files/private`, or `file:///data/files/public?public=1&public_url=https://cdn.example.com/app&retention=0`, or an `s3://` URL. `PROTOBASE_FILES_RETENTION` overrides `files.retention`.
107
- - Uploads and download links are signed with `files.secret`, else `PROTOBASE_FILES_SECRET`, else `BETTER_AUTH_SECRET`. The server does not start with file fields and none of them set.
105
+ - Uploads and download links are signed with `files.secret`, else `PROTOBASE_FILES_SECRET`, else the app's `secret` (`PROTOBASE_SECRET`). The server does not start with file fields and none of them set.
108
106
 
109
107
  ### Limits
110
108
 
@@ -114,7 +112,7 @@ A bucket has no quota of its own, so the provider counts what it holds with `lis
114
112
 
115
113
  ### Writing files from a seed
116
114
 
117
- A seed, an import or another script that writes files outside a request uses `storeFile` from `@protobase/server`, so the same script fills the folder locally and the bucket where the app has one. It finds the provider as the server does, from `env` and the config's `files`, when that declares providers:
115
+ A seed, an import or another script that writes files outside a request uses `storeFile` from `@protobase/server`, so the same script fills the folder locally and the bucket where the app has one. It finds the provider as the server does, from `env`, and from `files` with its providers made when the script passes it:
118
116
 
119
117
  ```ts
120
118
  import { storeFile } from '@protobase/server'
@@ -131,14 +129,14 @@ await storeFile({ provider: 'public', path: 'images/test.png', body: bytes, env:
131
129
  <gap>S3-compatible buckets work only when the app runs on Bun, as Node has no S3 client built in.</gap> On Node the first file operation fails.
132
130
  :::
133
131
 
134
- `s3Files` stores files in any bucket with the S3 API, such as Cloudflare R2, Scaleway Object Storage or AWS S3, under `prefix` when given, so one bucket can hold several providers or apps:
132
+ An `s3` provider stores files in any bucket with the S3 API, such as Cloudflare R2, Scaleway Object Storage or AWS S3, under `prefix` when given, so one bucket can hold several providers or apps:
135
133
 
136
134
  ```ts
137
135
  // Cloudflare R2, in the EU jurisdiction
138
- private: s3Files({ bucket: 'acme-files', prefix: 'private', endpoint: 'https://<account id>.eu.r2.cloudflarestorage.com', region: 'auto' }),
139
- public: s3Files({ bucket: 'acme-files', prefix: 'public', endpoint: 'https://<account id>.eu.r2.cloudflarestorage.com', region: 'auto', publicUrl: 'https://files.acme.com' }),
136
+ private: { kind: 's3', bucket: 'acme-files', prefix: 'private', endpoint: 'https://<account id>.eu.r2.cloudflarestorage.com', region: 'auto' },
137
+ public: { kind: 's3', bucket: 'acme-files', prefix: 'public', endpoint: 'https://<account id>.eu.r2.cloudflarestorage.com', region: 'auto', publicUrl: 'https://files.acme.com' },
140
138
  // Scaleway, in Paris
141
- archive: s3Files({ bucket: 'acme-archive', endpoint: 'https://s3.fr-par.scw.cloud', region: 'fr-par', retention: '30 days' }),
139
+ archive: { kind: 's3', bucket: 'acme-archive', endpoint: 'https://s3.fr-par.scw.cloud', region: 'fr-par', retention: '30 days' },
142
140
  ```
143
141
 
144
142
  Or from the environment, the same providers:
@@ -222,16 +220,14 @@ photo_placeholder: f.text().readOnly().optional(),
222
220
 
223
221
  Variants and placeholders turn the image upright first, following its EXIF orientation, and carry no metadata. JPEG, PNG, WebP, AVIF, GIF and TIFF images are processed; any other file, HEIC and SVG included, is stored as it is, without variants, and its placeholder is `null`. <gap>Files uploaded before a field declared variants keep none, as variants are not made for existing files.</gap>
224
222
 
225
- sharp is a native package, so the config passes it in, and a [built bundle](cli.md#native-packages) carries it with its add-on for linux:
223
+ sharp is a native package, so the config names it, the app loads it from the project's dependencies when it serves, and a [built bundle](cli.md#native-packages) carries it with its add-on for linux:
226
224
 
227
225
  ```ts
228
226
  // protobase.config.ts
229
- import sharp from 'sharp'
230
-
231
- export default defineConfig({ config, files: { sharp } })
227
+ export default defineConfig({ files: { images: 'sharp' } })
232
228
  ```
233
229
 
234
- The server does not start with a field that declares variants or a placeholder and no `files.sharp`. In code, `fileUrl(file, 'card')` from `@protobase/client` links a variant by name, or the file itself when it has none.
230
+ The server does not start with a field that declares variants or a placeholder and no `files.images`. In code, `fileUrl(file, 'card')` from `@protobase/client` links a variant by name, or the file itself when it has none.
235
231
 
236
232
  ## External URLs
237
233
 
@@ -268,7 +264,6 @@ The admin app draws every image of a file field with `referrerPolicy="no-referre
268
264
 
269
265
  ```ts
270
266
  export default defineConfig({
271
- config,
272
267
  files: { trustedHosts: ['images.example.com'] },
273
268
  })
274
269
  ```
@@ -279,7 +274,7 @@ A trusted host is matched exactly: `images.example.com` does not trust `cdn.imag
279
274
 
280
275
  Files are deleted by schedule, never in the write itself, so a restore of the database to an earlier moment still finds its files:
281
276
 
282
- - A write that **replaces or clears** a file, or **deletes a row** (not a soft delete), schedules the delete of each file it took out of its row, with its variants, once it commits, so its transaction never waits on the storage. It is due after the provider's retention: `files.retention`, 1 day by default, or 0 for a public provider. When the storage refuses the entry, the write still stands, the file stays in storage, and the error goes to `options.onUnhandledError`.
277
+ - A write that **replaces or clears** a file, or **deletes a row** (not a soft delete), schedules the delete of each file it took out of its row, with its variants, once it commits, so its transaction never waits on the storage. It is due after the provider's retention: `files.retention`, 1 day by default, or 0 for a public provider. When the storage refuses the entry, the write still stands, the file stays in storage, and the error goes to the default export of `hooks/error.ts`.
283
278
  - Every **upload** schedules one too, due an hour after its ticket expires, so a file nobody saved, or whose write rolled back, goes as well.
284
279
  - Each scheduled delete is a small JSON object in the provider's own storage, in a `.cleanup/` folder, named after its due time and saying what to delete: `.cleanup/2026-10-12T03-00-00Z-<uuid>.json` holding `{ "provider": "private", "path": "1/2992db9c-….jpg", "due": "…" }`.
285
280
  - A **cleanup run** handles the entries that are due. Right before deleting, it checks every file column of every resource for the file: one that a row holds again (a rolled-back write, a restore, a copied value) is kept, and its entry dropped. Two runs at once do no harm.
@@ -88,26 +88,14 @@ A submission is a create like any other, made by the anonymous role and limited
88
88
  There is no mail built into forms: the record's `created` event enqueues a [job](jobs.md), and the job [sends the mail](jobs.md#mail).
89
89
 
90
90
  ```ts title="config/notify.ts"
91
- import { defineJob, FatalJobError, subscription } from '@protobase/server'
92
- import { z } from 'zod'
93
-
94
- // Email me on a new submission: the record's event enqueues a job, and the job sends the mail.
95
-
96
- export const emailContactRequest = defineJob({
97
- name: 'email-contact-request',
98
- payload: z.object({ id: z.number() }),
99
- run: async ({ id }, { db, mail }) => {
100
- if (!mail) throw new FatalJobError('Mail is off: set PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM')
101
- const request = await db.selectFrom('contact_requests').select(['name', 'email', 'message']).where('id', '=', id).executeTakeFirst()
102
- if (!request) return
103
- await mail.send({ to: 'shop@example.com', subject: `Contact request from ${request.name}`, text: `${request.email} wrote:\n\n${request.message}` })
104
- },
105
- })
91
+ import { enqueueJob, subscription } from '@protobase/server'
106
92
 
93
+ // Email me on a new submission: the record's event enqueues a job (jobs/email-contact-request.ts), and the job sends
94
+ // the mail.
107
95
  export const newContactRequests = subscription('newContactRequests', {
108
96
  events: ['contact_requests.created'],
109
97
  run: async (event, { db }) => {
110
- await emailContactRequest.enqueue(db, { id: Number(event.data.key) }, { key: `contact-request:${event.data.key}` })
98
+ await enqueueJob(db, 'email-contact-request', { id: Number(event.data.key) }, { key: `contact-request:${event.data.key}` })
111
99
  },
112
100
  })
113
101
  ```
@@ -120,7 +108,7 @@ Each client may send a form `perMinute` times a minute, 5 by default, as many as
120
108
 
121
109
  Every submission carries a solved proof-of-work challenge ([ALTCHA](https://altcha.org)): the browser fetches a fresh one when the visitor presses **Send** and counts SHA-256 hashes until it finds the one the challenge asks for, about a second on a current laptop. There is no third-party service, cookie or visible puzzle, and it works offline. Sending many forms costs a bot that second each time, on top of the rate limit.
122
110
 
123
- A challenge is made for one form, expires after 5 minutes and verifies once. The server signs challenges with `PROTOBASE_FORMS_SECRET`, or `BETTER_AUTH_SECRET` when it is not set, and does not start with a form and neither variable, so give every instance of an app the same one. The browser solves the check with Web Crypto, which needs `https` or `localhost`.
111
+ A challenge is made for one form, expires after 5 minutes and verifies once. The server signs challenges with `PROTOBASE_FORMS_SECRET`, else the app's `secret` (`PROTOBASE_SECRET`), and does not start with a form and none of them, so give every instance of an app the same one. The browser solves the check with Web Crypto, which needs `https` or `localhost`.
124
112
 
125
113
  ## Routes
126
114
 
@@ -34,11 +34,10 @@ export const ordersView = view<typeof orders>('orders')
34
34
  ```
35
35
 
36
36
  ```ts title="protobase.config.ts"
37
- import { defineConfig } from '@protobase/server'
38
- import * as config from './orders'
37
+ import { defineConfig } from '@protobase/config'
39
38
 
40
39
  // Changes older than 90 days are deleted every night.
41
- export default defineConfig({ config, history: { days: 90 } })
40
+ export default defineConfig({ history: { days: 90 } })
42
41
  ```
43
42
 
44
43
  ## What a change holds
@@ -6,7 +6,7 @@ The admin app installs as an app of its own on phones and computers, named for t
6
6
 
7
7
  Every app built with `protobase build` can be installed from the browser, as a Progressive Web App: Chrome and Edge offer **Install** in the address bar, Android's browsers **Add to home screen**, and Safari on iPhone and iPad **Share > Add to Home Screen**. The installed app opens in a window of its own, without the browser's toolbars, at the app's home page.
8
8
 
9
- There is nothing to set up. The app installs under its name, `PROTOBASE_APP_NAME` or `appName`, with its favicon, `protobase.favicon.svg`, as its icon, and the colours of `app` in `protobase.config.ts` (see [App identity](app-identity.md)). Safari takes no SVG icon: give the project a `protobase.apple-touch-icon.png`, or it shows a picture of the page on the home screen instead.
9
+ There is nothing to set up. The app installs under its name, `PROTOBASE_APP_NAME` or `name` in `protobase.config.ts`, with its favicon, `protobase.favicon.svg`, as its icon, and the colours `themeColor` and `backgroundColor` of the config (see [App identity](app-identity.md)). Safari takes no SVG icon: give the project a `protobase.apple-touch-icon.png`, or it shows a picture of the page on the home screen instead.
10
10
 
11
11
  ## The manifest
12
12
 
@@ -6,86 +6,83 @@ Background jobs in the app's own database, enqueued with its writes, retried wit
6
6
 
7
7
  A job is work the app does after a request, or that a request should not wait for: mail an invoice, push a change to another system, recompute a report. Jobs live in the app's own Postgres database, in a schema named `jobs`, so a job can commit in the same transaction as the write that asks for it. The queue underneath is [pg-boss](https://github.com/timgit/pg-boss), pinned to one version; Protobase's own API in front of it is what the app uses.
8
8
 
9
- ```ts title="config/jobs.ts"
10
- import { defineJob, FatalJobError } from '@protobase/server'
11
- import { z } from 'zod'
12
-
13
- export const sendInvoice = defineJob({
14
- name: 'send-invoice',
15
- payload: z.object({ invoiceId: z.number() }),
16
- maxAttempts: 10, // then kept as failed, with its last error
17
- retryDelay: '30 seconds', // doubling with each retry, up to maxRetryDelay
18
- run: async ({ invoiceId }, { db }) => {
19
- const invoice = await db.selectFrom('sales.invoices').select(['id', 'status']).where('id', '=', invoiceId).executeTakeFirst()
20
- // Retrying will not bring it back: fail for good.
21
- if (!invoice) throw new FatalJobError(`Invoice ${invoiceId} is gone`)
22
- // ... render the PDF and mail it
23
- },
24
- })
9
+ A job is declared in `protobase.config.ts`, by its name, under `jobs`: what it does, its arguments and when it runs. What it does is the default export of `jobs/<name>.ts`, which Protobase finds by that path and loads the first time the job runs.
25
10
 
26
- // One at a time per customer, in the order the changes were made.
27
- export const syncCustomer = defineJob({
28
- name: 'sync-customer',
29
- ordered: true,
30
- payload: z.object({ customerId: z.number(), fields: z.array(z.string()) }),
31
- run: async ({ customerId, fields }) => {
32
- // ... push the changed fields to the CRM
33
- },
34
- })
11
+ ```ts title="protobase.config.ts"
12
+ import { defineConfig } from '@protobase/config'
35
13
 
36
- // Every morning at 7 in Amsterdam: one run per time, however many workers run.
37
- export const remindOverdue = defineJob({
38
- name: 'remind-overdue',
39
- schedule: '0 7 * * *',
40
- timezone: 'Europe/Amsterdam',
41
- run: async (_, { db }) => {
42
- // ... mail a reminder for every invoice past its due date
14
+ export default defineConfig({
15
+ // Each job's run is jobs/<name>.ts; the worker in `protobase dev` and `protobase serve` runs them.
16
+ jobs: {
17
+ 'send-invoice': {
18
+ description: 'Renders an invoice as a PDF and mails it to the customer.',
19
+ arguments: { invoiceId: 'integer' },
20
+ maxAttempts: 10, // then kept as failed, with its last error
21
+ retryDelay: '30 seconds', // doubling with each retry, up to maxRetryDelay
22
+ },
23
+ 'sync-customer': {
24
+ description: 'Pushes the changed fields of a customer to the CRM.',
25
+ arguments: { customerId: 'integer', fields: 'json' },
26
+ ordered: true, // one at a time per customer, in the order the changes were made
27
+ },
28
+ 'remind-overdue': {
29
+ description: 'Mails a reminder for every invoice past its due date.',
30
+ schedule: '0 7 * * *', // every morning at 7: one run per time, however many workers run
31
+ timezone: 'Europe/Amsterdam',
32
+ },
43
33
  },
34
+ // hooks/queue-sent-invoice.ts
35
+ writeHooks: ['queue-sent-invoice'],
44
36
  })
45
37
  ```
46
38
 
47
- ```ts title="protobase.config.ts"
48
- import { defineConfig } from '@protobase/server'
49
- import * as jobs from './jobs'
39
+ ```ts title="jobs/send-invoice.ts"
40
+ import { FatalJobError, type JobRun } from '@protobase/server'
50
41
 
51
- export default defineConfig({
52
- config: {},
53
- jobs, // run by the worker in `protobase dev` and `protobase serve`
54
- options: {
55
- writeHooks: [
56
- // In the write's own transaction: the invoice and its job commit together or not at all.
57
- async (event, trx) => {
58
- if (event.resource.name !== 'invoices' || event.after?.status !== 'sent' || event.before?.status === 'sent') return
59
- const invoiceId = Number(event.after.id)
60
- await jobs.sendInvoice.enqueue(trx, { invoiceId }, { key: `invoice:${invoiceId}` })
61
- },
62
- ],
63
- },
64
- })
42
+ export default (async ({ invoiceId }, { db }) => {
43
+ const invoice = await db.selectFrom('sales.invoices').select(['id', 'status']).where('id', '=', invoiceId).executeTakeFirst()
44
+ // Retrying will not bring it back: fail for good.
45
+ if (!invoice) throw new FatalJobError(`Invoice ${invoiceId} is gone`)
46
+ // ... render the PDF and mail it
47
+ }) satisfies JobRun<{ invoiceId: number }>
65
48
  ```
66
49
 
67
- | `defineJob` option | |
50
+ | Key of a job | |
68
51
  | --- | --- |
69
- | `name` | Letters, digits, `_`, `-`, `.` and `/`. Two jobs may not share a name. |
70
- | `payload` | A [Standard Schema](https://standardschema.dev) such as a zod schema, checked when the job is enqueued and again before it runs. A payload it refuses at run time fails the job for good. |
71
- | `run(payload, { db, job, signal, mail, sendNotification })` | The work. `db` is the app's pool: the enqueuer's transaction has committed by then. `job` holds its `id`, `name`, `attempt`, `maxAttempts` and `startedOn`, when this try took it. `signal` aborts when the try times out or the worker shuts down. `mail` sends mail, see [Mail](#mail). `sendNotification` sends a notification, see [Sending](notifications.md#sending); inside a transaction of `db`, a try that throws in it queues nothing. |
52
+ | its name | Letters, digits, `_`, `-`, `.` and `/`; the file `jobs/<name>.ts` holds what it does. |
53
+ | `description` | What the job does, for the people who read the config. |
54
+ | `arguments` | Its arguments by name, each a [field type](data-config.md#field-types) such as `'integer'` or `'bigint'`, or the type with options: `{ type: 'enum', values: ['day', 'week'] }`, `{ type: 'text', min: 1 }`, `{ type: 'integer', optional: true }`, `{ type: 'decimal', precision: 8, scale: 2 }`. Each value is checked as a field of that type checks it, when the job is enqueued and again before it runs, and no other argument is taken. A payload refused at run time fails the job for good. The same is JSON in a `protobase.config.json`. |
55
+ | the default export of `jobs/<name>.ts` | `(payload, { db, job, signal, mail, sendNotification })`, typed with `JobRun<Payload>` from `@protobase/server`: the work. `db` is the app's pool: the enqueuer's transaction has committed by then. `job` holds its `id`, `name`, `attempt`, `maxAttempts` and `startedOn`, when this try took it. `signal` aborts when the try times out or the worker shuts down. `mail` sends mail, see [Mail](#mail). `sendNotification` sends a notification, see [Sending](notifications.md#sending); inside a transaction of `db`, a try that throws in it queues nothing. |
72
56
  | `maxAttempts` | Tries before the job is kept as failed; default 10. |
73
57
  | `retryDelay`, `maxRetryDelay` | The wait before the first retry, doubling with each one (with some jitter), and its ceiling; default `2s` and `1 hour`. Milliseconds or text such as `30 seconds`. |
74
58
  | `timeout` | How long one try may run before it counts as failed; default `15 minutes`. |
75
59
  | `concurrency` | Jobs of this name running at once in each worker process; default 1. |
76
60
  | `longQueries` | Its queries through `db` may run up to 30 seconds instead of the database's own limit, for imports, backfills and large deletes; see [Long queries](../guides/api-functions.md#long-queries). A query stopped at its limit fails the try with an error that names the job. |
77
61
  | `ordered` | Jobs run one at a time per group, in the order they were enqueued; see [Ordered groups](#ordered-groups). |
78
- | `schedule`, `timezone` | Runs the job on a cron schedule, in a time zone (default `UTC`); see [Recurring jobs](#recurring-jobs). |
62
+ | `schedule`, `timezone` | Runs the job on a cron schedule, in a time zone (default the config's `timezone`, else `UTC`); see [Recurring jobs](#recurring-jobs). |
79
63
 
80
64
  A job runs **at least once**: a worker that dies mid-job, or a try cut off by a shutdown, means it runs again. Write `run` so that running twice does no harm, for example by checking the state it is about to change.
81
65
 
82
66
  ## Enqueueing
83
67
 
84
68
  ```ts
85
- await sendInvoice.enqueue(db, { invoiceId: 7 }, { delay: '5 minutes', key: 'invoice:7', priority: 10 })
69
+ import { enqueueJob } from '@protobase/server'
70
+
71
+ await enqueueJob(db, 'send-invoice', { invoiceId: 7 }, { delay: '5 minutes', key: 'invoice:7', priority: 10 })
86
72
  ```
87
73
 
88
- `db` is the app's database, or the transaction of a write hook or an [API function](../guides/api-functions.md): there, the job commits with the caller's writes, or not at all. It returns the job's id.
74
+ `db` is the app's database, or the transaction of a write hook or an [API function](../guides/api-functions.md): there, the job commits with the caller's writes, or not at all. It returns the job's id. A write hook is named in the config's `writeHooks` and is the default export of `hooks/<name>.ts`:
75
+
76
+ ```ts title="hooks/queue-sent-invoice.ts"
77
+ import { enqueueJob, type PipelineHook } from '@protobase/server'
78
+
79
+ // In the write's own transaction: the invoice and its job commit together or not at all.
80
+ export default (async (event, trx) => {
81
+ if (event.resource.name !== 'invoices' || event.after?.status !== 'sent' || event.before?.status === 'sent') return
82
+ const invoiceId = Number(event.after.id)
83
+ await enqueueJob(trx, 'send-invoice', { invoiceId }, { key: `invoice:${invoiceId}` })
84
+ }) satisfies PipelineHook
85
+ ```
89
86
 
90
87
  | Option | |
91
88
  | --- | --- |
@@ -8,10 +8,12 @@ The admin app's own texts and its numbers and dates come in English and Dutch. T
8
8
 
9
9
  ## Choosing the language
10
10
 
11
- Without a setting, each user sees the app in their browser's language when it is Dutch or English, and in English otherwise. `options.locale` in `protobase.config.ts` puts the app in one language for everyone:
11
+ Without a setting, each user sees the app in their browser's language when it is Dutch or English, and in English otherwise. `locale` in `protobase.config.ts` puts the app in one language for everyone:
12
12
 
13
13
  ```ts title="protobase.config.ts"
14
- export default { config, auth, authenticate, options: { locale: 'nl' } }
14
+ import { defineConfig } from '@protobase/config'
15
+
16
+ export default defineConfig({ locale: 'nl' })
15
17
  ```
16
18
 
17
19
  The value is `'en'` or `'nl'`, and the server refuses to start with any other value. `/meta` names the language as `locale`, and so does the sign-in status (`GET /api/auth/status`), which the sign-in screens and public forms read before `/meta`, so they are in the same language.
@@ -8,13 +8,13 @@ An app can serve an MCP endpoint: a person adds its address to an AI client that
8
8
 
9
9
  ## Turning it on
10
10
 
11
- One option of `createAuth` turns it on:
11
+ `auth.mcp` in `protobase.config.ts` turns it on:
12
12
 
13
13
  ```ts
14
- createAuth({ ..., mcp: true })
14
+ export default defineConfig({ auth: { mcp: true } })
15
15
  ```
16
16
 
17
- Run `protobase auth migration` after turning it on, for the OAuth tables. The endpoint is `https://<app>/api/mcp`, or the path `mcp.path` names. How clients register, how people sign in and allow them, and how they disconnect them is in [OAuth for MCP clients](auth.md#oauth-for-mcp-clients).
17
+ Every auth store has the OAuth tables, so turning it on needs no migration. The endpoint is `https://<app>/api/mcp`, or the path `mcp.path` names. How clients register, how people sign in and allow them, and how they disconnect them is in [OAuth for MCP clients](auth.md#oauth-for-mcp-clients).
18
18
 
19
19
  ## Connecting a client
20
20
 
@@ -45,20 +45,20 @@ A refusal, such as a resource the person may not read or a bad filter, comes bac
45
45
 
46
46
  ### SQL for admins
47
47
 
48
- `createAdmin`'s `options.mcp.sql` also offers `run_read_only_query`, as in the [assistant](assistant.md#the-built-in-backend), to people with the `admin` or `ai` role:
48
+ `mcpEndpoint.sql` also offers `run_read_only_query`, as in the [assistant](assistant.md#the-built-in-backend), to people with the `admin` or `ai` role:
49
49
 
50
50
  ```ts
51
- createAdmin({ ..., auth, options: { mcp: { sql: true } } })
51
+ export default defineConfig({ auth: { mcp: true }, mcpEndpoint: { sql: true } })
52
52
  ```
53
53
 
54
54
  It runs one `SELECT` in a read-only transaction, as the app's database role, **outside the access rules and tenant scoping**: whoever has one of those roles reads the whole database through it. Give those roles only to people who may see all of the data.
55
55
 
56
56
  ### Writes
57
57
 
58
- `createAdmin`'s `options.mcp.writes` also offers three tools that change records, to everyone signed in:
58
+ `mcpEndpoint.writes` also offers three tools that change records, to everyone signed in:
59
59
 
60
60
  ```ts
61
- createAdmin({ ..., auth, options: { mcp: { writes: true } } })
61
+ export default defineConfig({ auth: { mcp: true }, mcpEndpoint: { writes: true } })
62
62
  ```
63
63
 
64
64
  | Tool | What it does |
@@ -77,17 +77,17 @@ Before each write the client asks the person to approve it, showing the resource
77
77
  To offer the writes on some resources only, list them:
78
78
 
79
79
  ```ts
80
- createAdmin({ ..., auth, options: { mcp: { writes: { resources: ['tasks'] } } } })
80
+ mcpEndpoint: { writes: { resources: ['tasks'] } }
81
81
  ```
82
82
 
83
83
  The write tools then name those resources in their descriptions, and refuse a write to any other before asking, with `{ "error": "forbidden", "message": ... }` saying which resources they write; nothing is written. A name the app has no resource for stops the server at startup. The list only narrows the writes: the person's access rules still apply on the listed resources.
84
84
 
85
85
  #### Writes without approval
86
86
 
87
- An app that runs service accounts over MCP, such as a backend job or an agent with no person present, names their roles in `options.mcp.writes`:
87
+ An app that runs service accounts over MCP, such as a backend job or an agent with no person present, names their roles in `mcpEndpoint.writes`:
88
88
 
89
89
  ```ts
90
- createAdmin({ ..., auth, options: { mcp: { writes: { resources: ['tasks'], rolesWithoutApproval: ['service'] } } } })
90
+ mcpEndpoint: { writes: { resources: ['tasks'], rolesWithoutApproval: ['service'] } }
91
91
  ```
92
92
 
93
93
  A user with one of those roles creates, updates and deletes records over MCP without the approval step: the client is never asked, so a client that cannot ask writes too. Their role's access rules and the listed resources still limit every write as before, so a job with no person present can keep the app's data over MCP and do nothing there it could not do through the REST API. Everyone else is still asked before each write. Taking the role away, banning or deleting the account stops its tokens at their next request, not when they expire.
@@ -132,7 +132,7 @@ The endpoint serves each request on its own, without an MCP session: a `GET` or
132
132
  - `mcpGate({ authenticate, resource, scope })`: the token check alone, answering 401 or 403 with a challenge that names the resource's metadata.
133
133
  - `mcpToolContext(...)`, `mcpRoutes(app, { path, handler })` and `sessionOf(authInfo)`: the tools' context as the app builds it, the routes with open CORS, and the session a request was admitted with.
134
134
 
135
- To serve your own endpoint at `mcp.path` instead, pass `createAdmin` `options: { mcp: false }` and mount yours in front of `createAdmin`'s app. The OAuth provider and its discovery stay, `createAdmin` answers 404 at the path and under it, and its `authenticate` needs no `forAudience`.
135
+ To serve your own endpoint at `mcp.path` instead, set `mcpEndpoint: false` (`createAdmin`'s `options.mcp`) and mount yours in front of `createAdmin`'s app. The OAuth provider and its discovery stay, `createAdmin` answers 404 at the path and under it, and its `authenticate` needs no `forAudience`.
136
136
 
137
137
  A tool of your own goes on the server `server` returns, with the context its tools get:
138
138