@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.
- package/dist/main.js +2 -0
- package/dist/package.js +1 -1
- package/dist/skill/install.js +29 -0
- package/dist/skill/register.js +14 -0
- package/package.json +8 -7
- package/skills/protobase/SKILL.md +89 -0
- package/skills/protobase/references/getting-started.md +78 -0
- package/skills/protobase/references/guides/api-functions.md +240 -0
- package/skills/protobase/references/guides/billing-page.md +288 -0
- package/skills/protobase/references/guides/create-page.md +108 -0
- package/skills/protobase/references/guides/deploy.md +52 -0
- package/skills/protobase/references/guides/export-a-list.md +44 -0
- package/skills/protobase/references/guides/field-type.md +131 -0
- package/skills/protobase/references/guides/first-composed-page.md +230 -0
- package/skills/protobase/references/guides/first-plugin.md +166 -0
- package/skills/protobase/references/guides/import-records.md +43 -0
- package/skills/protobase/references/guides/plugin-build.md +64 -0
- package/skills/protobase/references/guides/record-card.md +70 -0
- package/skills/protobase/references/guides/remote-resources.md +185 -0
- package/skills/protobase/references/guides/table-to-admin.md +205 -0
- package/skills/protobase/references/guides/theme-an-app.md +87 -0
- package/skills/protobase/references/reference/access.md +115 -0
- package/skills/protobase/references/reference/ai.md +106 -0
- package/skills/protobase/references/reference/api.md +231 -0
- package/skills/protobase/references/reference/architecture.md +63 -0
- package/skills/protobase/references/reference/assistant.md +157 -0
- package/skills/protobase/references/reference/auth.md +462 -0
- package/skills/protobase/references/reference/blocks.md +341 -0
- package/skills/protobase/references/reference/bottom-bar.md +44 -0
- package/skills/protobase/references/reference/cli.md +493 -0
- package/skills/protobase/references/reference/client.md +38 -0
- package/skills/protobase/references/reference/comments.md +83 -0
- package/skills/protobase/references/reference/custom-components.md +285 -0
- package/skills/protobase/references/reference/data-config.md +266 -0
- package/skills/protobase/references/reference/email.md +166 -0
- package/skills/protobase/references/reference/events.md +121 -0
- package/skills/protobase/references/reference/files.md +291 -0
- package/skills/protobase/references/reference/forms.md +133 -0
- package/skills/protobase/references/reference/history.md +86 -0
- package/skills/protobase/references/reference/jobs.md +174 -0
- package/skills/protobase/references/reference/layouts.md +126 -0
- package/skills/protobase/references/reference/plugins.md +328 -0
- package/skills/protobase/references/reference/remote-resources.md +198 -0
- package/skills/protobase/references/reference/sidebar.md +51 -0
- package/skills/protobase/references/reference/theme.md +132 -0
- package/skills/protobase/references/reference/ui-config.md +880 -0
- package/skills/protobase/references/reference/user-menu.md +38 -0
- package/skills/protobase/references/reference/versioning.md +91 -0
- package/skills/protobase/references/reference/webhooks.md +136 -0
package/dist/main.js
CHANGED
|
@@ -20,6 +20,7 @@ import { loadWorkerBundle, startWorker } from "./worker/start-worker.js";
|
|
|
20
20
|
import { registerOrganizations } from "./organizations/register.js";
|
|
21
21
|
import { registerFiles } from "./files/register.js";
|
|
22
22
|
import { registerMigration } from "./migration/register.js";
|
|
23
|
+
import { registerSkill } from "./skill/register.js";
|
|
23
24
|
import { registerToken, registerUsers } from "./users/register.js";
|
|
24
25
|
import { statSync } from "node:fs";
|
|
25
26
|
import path from "node:path";
|
|
@@ -128,6 +129,7 @@ registerToken(program);
|
|
|
128
129
|
registerAuth(program);
|
|
129
130
|
registerMigration(program);
|
|
130
131
|
registerFiles(program);
|
|
132
|
+
registerSkill(program);
|
|
131
133
|
const run = (argv) => program.parseAsync(argv).catch((error) => {
|
|
132
134
|
process.stderr.write(`error: ${error.message}\n`);
|
|
133
135
|
process.exitCode = 1;
|
package/dist/package.js
CHANGED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { access, cp, readFile, rm } from "node:fs/promises";
|
|
3
|
+
//#region src/skill/install.ts
|
|
4
|
+
const targetFolders = [".agents/skills/protobase", ".claude/skills/protobase"];
|
|
5
|
+
const exists = (path) => access(path).then(() => true, () => false);
|
|
6
|
+
const isOurs = async (target) => {
|
|
7
|
+
const text = await readFile(join(target, "SKILL.md"), "utf8").catch((error) => {
|
|
8
|
+
if (error.code === "ENOENT") return "";
|
|
9
|
+
throw error;
|
|
10
|
+
});
|
|
11
|
+
return /^---\n(?:[^\n]*\n)*?name: protobase\n/.test(text);
|
|
12
|
+
};
|
|
13
|
+
async function installSkill(source, projectDir) {
|
|
14
|
+
const targets = targetFolders.map((folder) => join(projectDir, folder));
|
|
15
|
+
for (const target of targets) {
|
|
16
|
+
if (!await exists(target)) continue;
|
|
17
|
+
if (!await isOurs(target)) throw new Error(`${target} holds a skill that is not protobase's; move it away to install the protobase skill`);
|
|
18
|
+
}
|
|
19
|
+
for (const target of targets) {
|
|
20
|
+
await rm(target, {
|
|
21
|
+
recursive: true,
|
|
22
|
+
force: true
|
|
23
|
+
});
|
|
24
|
+
await cp(source, target, { recursive: true });
|
|
25
|
+
}
|
|
26
|
+
return targets;
|
|
27
|
+
}
|
|
28
|
+
//#endregion
|
|
29
|
+
export { installSkill };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { protobaseVersion } from "../version/version.js";
|
|
2
|
+
import { installSkill } from "./install.js";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
//#region src/skill/register.ts
|
|
5
|
+
const skillSource = fileURLToPath(new URL("../../skills/protobase", import.meta.url));
|
|
6
|
+
function registerSkill(program) {
|
|
7
|
+
program.command("skill").description("the protobase agent skill").command("install").description("copy the protobase agent skill of this CLI's version into the project's .agents/skills and .claude/skills").action(async () => {
|
|
8
|
+
const projectDir = process.cwd();
|
|
9
|
+
const folders = (await installSkill(skillSource, projectDir)).map((target) => target.slice(projectDir.length + 1));
|
|
10
|
+
process.stdout.write(`protobase skill ${protobaseVersion} → ${folders.join(", ")}\n`);
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
export { registerSkill };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.23.0",
|
|
4
4
|
"description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -22,7 +22,8 @@
|
|
|
22
22
|
},
|
|
23
23
|
"files": [
|
|
24
24
|
"bin/protobase.mjs",
|
|
25
|
-
"dist"
|
|
25
|
+
"dist",
|
|
26
|
+
"skills"
|
|
26
27
|
],
|
|
27
28
|
"scripts": {
|
|
28
29
|
"build": "tsdown",
|
|
@@ -34,11 +35,11 @@
|
|
|
34
35
|
"dependencies": {
|
|
35
36
|
"@hono/node-server": "^2.1.3",
|
|
36
37
|
"@hono/vite-dev-server": "^0.26.1",
|
|
37
|
-
"@protobase/layout": "0.
|
|
38
|
-
"@protobase/query": "0.
|
|
39
|
-
"@protobase/schema": "0.
|
|
40
|
-
"@protobase/server": "0.
|
|
41
|
-
"@protobase/ui": "0.
|
|
38
|
+
"@protobase/layout": "0.23.0",
|
|
39
|
+
"@protobase/query": "0.23.0",
|
|
40
|
+
"@protobase/schema": "0.23.0",
|
|
41
|
+
"@protobase/server": "0.23.0",
|
|
42
|
+
"@protobase/ui": "0.23.0",
|
|
42
43
|
"@react-email/render": "^2.1.0",
|
|
43
44
|
"@scalar/hono-api-reference": "^0.12.10",
|
|
44
45
|
"@tailwindcss/vite": "^4.3.3",
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: protobase
|
|
3
|
+
description: Build, check and ship a Protobase admin app on Postgres (data.ts, ui.ts, the protobase CLI), with the guides and reference for this Protobase version. Use it when working in a Protobase project.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Protobase
|
|
7
|
+
|
|
8
|
+
Protobase is a config-driven admin on an existing Postgres database. `config/index.ts` exports the resources, `config/<resource>/data.ts` describes a table and `ui.ts` its views, `functions/` holds the app's API functions, and `protobase.config.ts` in the project root replaces the conventions when it exists. The app's own React code (components, field types, actions) is a plugin in `protobase.ui.tsx`.
|
|
9
|
+
|
|
10
|
+
Run the CLI as the project does: `npx protobase <command>`, or `bun run protobase <command>`. These pages describe the Protobase version installed in the project.
|
|
11
|
+
|
|
12
|
+
## Everyday workflow
|
|
13
|
+
|
|
14
|
+
1. Run `protobase dev`: one process and one port, the admin app and the API; changes to config, layouts and functions show without a restart.
|
|
15
|
+
2. Change the config (`data.ts`, `ui.ts`, layouts) or the app's code.
|
|
16
|
+
3. Database changes go through the project's migrations, never through startup: `protobase migration` writes the migrations a config feature needs, the project applies them with its own migrate script. See [references/reference/cli.md](references/reference/cli.md#migration).
|
|
17
|
+
|
|
18
|
+
## Before calling a change done
|
|
19
|
+
|
|
20
|
+
1. Typecheck and test the project with its own scripts (`tsc --noEmit` and the tests).
|
|
21
|
+
2. Run `protobase doctor --env DATABASE_URL` after the project's migrations. It checks every resource against the database (tables, columns, types, keys) and every read the API would refuse for lack of an index. Exit code 1 means errors. Fix a refused read with the `create index` it prints, as a migration; never loosen the scan guard. See [references/reference/cli.md](references/reference/cli.md#doctor).
|
|
22
|
+
3. Run `protobase build`: it needs no database and must succeed.
|
|
23
|
+
|
|
24
|
+
## Ship
|
|
25
|
+
|
|
26
|
+
`protobase build` writes the bundle (`dist/`); the host runs the serve runtime around it, after the project's migrations and with no other writes while they run. Check a bundle locally with `protobase serve dist`. Details: [references/guides/deploy.md](references/guides/deploy.md).
|
|
27
|
+
|
|
28
|
+
## Rules of thumb
|
|
29
|
+
|
|
30
|
+
- Records live at the framework's standard addresses and API; give a resource another look through its views, layouts or a plugin, not a page with routes of its own.
|
|
31
|
+
- A `.filterable()` or `.sortable()` field, a search and an owner column need an index; doctor fails without one.
|
|
32
|
+
- Plugins keep working as Protobase moves on; the bundle is built again for a new minor version below 1.0.
|
|
33
|
+
- Check the `@protobase` package versions before trusting an example: below 1.0 a minor version may change the config.
|
|
34
|
+
|
|
35
|
+
## When you need more
|
|
36
|
+
|
|
37
|
+
Guides:
|
|
38
|
+
|
|
39
|
+
- When setting up or running a project for the first time → read [Getting started](references/getting-started.md)
|
|
40
|
+
- When shipping a project as a bundle and running it with the serve runtime → read [Deploy](references/guides/deploy.md)
|
|
41
|
+
- When turning a table into an admin with fields, views and filters → read [From a table to an admin](references/guides/table-to-admin.md)
|
|
42
|
+
- When building a page from layouts and blocks → read [Your first composed page](references/guides/first-composed-page.md)
|
|
43
|
+
- When giving customers a page for their plan, cards and invoices → read [A billing page](references/guides/billing-page.md)
|
|
44
|
+
- When adding endpoints of your own beside the REST API → read [Your own API functions](references/guides/api-functions.md)
|
|
45
|
+
- When writing React code of your own → read [Your first plugin](references/guides/first-plugin.md)
|
|
46
|
+
- When changing colors, corners or font → read [Theming an app](references/guides/theme-an-app.md)
|
|
47
|
+
- When showing or editing a field your own way → read [Adding a field type](references/guides/field-type.md)
|
|
48
|
+
- When drawing the cards of a list yourself → read [A custom record card](references/guides/record-card.md)
|
|
49
|
+
- When a project built its UI into the admin app and must move to the plugin build → read [Moving onto the plugin build](references/guides/plugin-build.md)
|
|
50
|
+
- When showing another Protobase app's records → read [Showing another app's records](references/guides/remote-resources.md)
|
|
51
|
+
- When letting users save a list as Excel or CSV → read [Exporting a list](references/guides/export-a-list.md)
|
|
52
|
+
- When importing records from a spreadsheet → read [Importing records from a spreadsheet](references/guides/import-records.md)
|
|
53
|
+
- When replacing a resource's create form with a page of your own → read [A create page of your own](references/guides/create-page.md)
|
|
54
|
+
|
|
55
|
+
Reference:
|
|
56
|
+
|
|
57
|
+
- When defining resources, fields, keys, relations and validation → read [Data config](references/reference/data-config.md)
|
|
58
|
+
- When defining views, columns, filters, charts, related records and actions → read [UI config](references/reference/ui-config.md)
|
|
59
|
+
- When asking how the packages fit together → read [Architecture](references/reference/architecture.md)
|
|
60
|
+
- When calling or changing the REST API, its filters, writes and errors → read [REST API](references/reference/api.md)
|
|
61
|
+
- When working with file fields and uploads → read [Files](references/reference/files.md)
|
|
62
|
+
- When reacting to changes of records → read [Events](references/reference/events.md)
|
|
63
|
+
- When delivering events to URLs → read [Webhooks](references/reference/webhooks.md)
|
|
64
|
+
- When keeping or showing the changes of records → read [Record history](references/reference/history.md)
|
|
65
|
+
- When adding comments to records → read [Record comments](references/reference/comments.md)
|
|
66
|
+
- When filling fields with a model → read [AI fields and actions](references/reference/ai.md)
|
|
67
|
+
- When letting people without an account create records → read [Public forms](references/reference/forms.md)
|
|
68
|
+
- When running background jobs → read [Jobs](references/reference/jobs.md)
|
|
69
|
+
- When sending email → read [Email](references/reference/email.md)
|
|
70
|
+
- When setting roles, capabilities and row filters → read [Access](references/reference/access.md)
|
|
71
|
+
- When configuring sign-in, tokens and the auth schema → read [Login with Better Auth](references/reference/auth.md)
|
|
72
|
+
- When using the typed client and hooks → read [Client and live UI](references/reference/client.md)
|
|
73
|
+
- When writing composed pages in JSX → read [Layouts](references/reference/layouts.md)
|
|
74
|
+
- When looking for a built-in layout block and its props → read [Blocks](references/reference/blocks.md)
|
|
75
|
+
- When using components and action handlers of your own in layouts → read [Custom components](references/reference/custom-components.md)
|
|
76
|
+
- When building or loading plugins → read [Plugins](references/reference/plugins.md)
|
|
77
|
+
- When using resources another Protobase API serves → read [Remote resources](references/reference/remote-resources.md)
|
|
78
|
+
- When setting the app's tokens, colors and fonts → read [Theme](references/reference/theme.md)
|
|
79
|
+
- When grouping sidebar entries or listing recent records → read [Sidebar](references/reference/sidebar.md)
|
|
80
|
+
- When changing the user menu → read [User menu](references/reference/user-menu.md)
|
|
81
|
+
- When adding tabs along the bottom of a phone → read [Bottom bar](references/reference/bottom-bar.md)
|
|
82
|
+
- When configuring the chat beside the admin → read [Assistant](references/reference/assistant.md)
|
|
83
|
+
- When looking for a command or its options → read [CLI](references/reference/cli.md)
|
|
84
|
+
- When asking how Protobase is versioned and which bundles a runtime runs → read [Versioning](references/reference/versioning.md)
|
|
85
|
+
- When looking for an export of `@protobase/schema` → read the [API reference](https://docs.protobase.net/api/schema/)
|
|
86
|
+
|
|
87
|
+
## Keep this skill current
|
|
88
|
+
|
|
89
|
+
After upgrading the `@protobase` packages, run `protobase skill install` again so the skill matches the installed version.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
<!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/getting-started.md: run `bun run docs:skill`, do not edit. -->
|
|
2
|
+
|
|
3
|
+
# Getting started
|
|
4
|
+
|
|
5
|
+
Install the repository, run the ERP, real estate and property portal examples and learn the development commands.
|
|
6
|
+
|
|
7
|
+
Protobase is a config-driven admin panel framework for existing Postgres databases. Data config lives in `data.ts`, UI config in `ui.ts`; a Hono server serves the API and a React app renders the admin. Coding agents get the guides and reference of the installed version with [`protobase skill install`](reference/cli.md#skill)).
|
|
8
|
+
|
|
9
|
+
An app's own React code, its components, field types and actions, is a [plugin](reference/plugins.md)): built on its own against a plugin API that Protobase's releases keep, and loaded by the admin app when it starts. Protobase maintains the admin app, the API and the server, and a plugin keeps working as the app moves to newer releases, with their fixes and features, without changes of its own. Below 1.0 a new minor version may still change the config, and the bundle is built again for it; the plugins' code stays as it is (see [Who maintains what](reference/plugins.md#who-maintains-what))).
|
|
10
|
+
|
|
11
|
+
## Setup
|
|
12
|
+
|
|
13
|
+
Requires Bun 1.4.2, which installs the repository and runs its scripts and tests, and Node 22.12 or later (`.nvmrc`) for the smoke test on Node.
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
bun install
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Run the ERP example
|
|
20
|
+
|
|
21
|
+
`examples/erp` is a sample ERP on a real Postgres database, seeded with three years of history. It needs Docker for the database: `bun run db:up` starts the Postgres container and gives each example its database and a `.env` from its `.env.example`.
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
bun run db:up && bun run --cwd examples/erp db:migrate && bun run --cwd examples/erp db:seed --scale small # the ERP's tables and Better Auth's
|
|
25
|
+
bun run --cwd examples/erp protobase users create you@example.com --generate-password
|
|
26
|
+
bun run --cwd examples/erp dev # http://localhost:5173
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
`BETTER_AUTH_SECRET` in `examples/erp/.env` signs the session cookies; see [Login with Better Auth](reference/auth.md)). `protobase dev` serves the admin app and the API on one port and reloads both on every change ([CLI](reference/cli.md#dev))).
|
|
30
|
+
|
|
31
|
+
## Run the real estate example
|
|
32
|
+
|
|
33
|
+
`examples/real-estate` is a rental and property management firm: owners, properties and units, leases and tenants, monthly rent, payments and arrears, and maintenance. Its database sits beside the ERP's in the same Postgres container, and it keeps its own `.env`.
|
|
34
|
+
|
|
35
|
+
```sh
|
|
36
|
+
bun run db:up && bun run --cwd examples/real-estate db:migrate && bun run --cwd examples/real-estate db:seed --scale small
|
|
37
|
+
bun run --cwd examples/real-estate protobase users create you@example.com --role admin --generate-password
|
|
38
|
+
bun run --cwd examples/real-estate dev # http://localhost:5173
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Run the property portal example
|
|
42
|
+
|
|
43
|
+
`examples/property-portal` is a public portal of homes for sale and for rent in the Netherlands and Spain, in the style of Funda and Idealista. Visitors browse and filter the listings without signing in, through the [anonymous role](reference/access.md#anonymous-access)); members save searches of the listings that mail them new homes, and keep favorites and notes that only they see. The seed makes two members, `anna@portal.example` and `bram@portal.example`, and an admin, `admin@portal.example`, all with the password `property-portal-demo`.
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
bun run db:up && bun run --cwd examples/property-portal db:migrate && bun run --cwd examples/property-portal db:seed --scale small
|
|
47
|
+
bun run --cwd examples/property-portal dev # http://localhost:5173
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Commands
|
|
51
|
+
|
|
52
|
+
| Command | Purpose |
|
|
53
|
+
| --- | --- |
|
|
54
|
+
| `bun run db:up` / `bun run db:down` | start or stop the Postgres container; `db:up` also creates the examples' databases and `.env` files |
|
|
55
|
+
| `bun run test` | the unit tests and the snapshot tests in `packages/*/tests/` and `tests/` (Vitest projects `unit*` and `snapshot*`): no Postgres server, subprocess or network. A snapshot test replays the SQL recorded for it from Postgres in `<test>.sql.json` |
|
|
56
|
+
| `bun run test:record` | runs the snapshot tests on the Postgres container instead and writes their recordings, after building their templates (`bun run test:db snapshots`); run it when a change makes a snapshot test fail with `stale snapshot` |
|
|
57
|
+
| `bun run test:unit` | only the unit tests, next to the code (Vitest projects `unit`, whose files share their modules, and `unit-isolated`, for those that mock a module or change a global), fully parallel; starting a Postgres client there throws |
|
|
58
|
+
| `bun run test:watch` | `bun run test` in watch mode |
|
|
59
|
+
| `bun run test:integration` | the database, subprocess and build tests (projects `integration*`), against the Postgres container, among them the real-Postgres tests (`*.postgres.test.ts`) |
|
|
60
|
+
| `bun run test:smoke` / `node --run test:smoke` | the CLI on Bun or on Node builds the ERP and serves its bundle, whose `€` must come back intact; part of `test:integration` on Bun |
|
|
61
|
+
| `bun run presets:write <version> <dir>` | writes each preset to `<dir>/<name>`: a standalone copy of its example with the `@protobase` packages in the range of `<version>`'s major (`>=0.y.z <1` below 1.0, `^x.y.z` from 1.0) and its own `bun.lock` at exactly `<version>`, which must be on npm |
|
|
62
|
+
| `bun run images:context` | the build contexts of the `protobase` and `protobase-dev` images in `dist/images`, at the version in `package.json` (see [Deploy](guides/deploy.md#images))) |
|
|
63
|
+
| `bun run test:presets` | writes each preset as `bun run presets:write` does it and installs it with Bun from npm (so at a published version), then migrates, seeds, checks, tests and builds it on a database of its own, as a role without superuser rights; needs the Postgres container |
|
|
64
|
+
| `bun run test:postgres` | the Postgres suite in `tests/postgres/` (Vitest project `postgres`): the ERP's medium seed and the planner's statistics on it, and the jobs and event delivery through PgBouncer; needs the Postgres and PgBouncer containers and `bun run test:db postgres` |
|
|
65
|
+
| `bun run test:db` | builds the template databases the database tests clone for each run (`protobase_test_template`, `real_estate_test_template`, `property_portal_test_template`, all at small scale, and the empty, auth and jobs `snapshot_*_test_template` the real-Postgres and end-to-end tests clone), when missing or older than what they are built from; without them those tests skip. `bun run test:db postgres` builds the Postgres suite's (`protobase_medium_test_template`, the ERP at medium scale), `bun run test:db snapshots` the ones `test:record` records on (`snapshot_*_test_template`). Tests never use the `protobase`, `real_estate` or `property_portal` databases |
|
|
66
|
+
| `bun run typecheck` | `tsc --noEmit` |
|
|
67
|
+
| `bun run check:boundaries` | dependency-cruiser package rules |
|
|
68
|
+
| `bun run check` | typecheck + test + test:integration + check:boundaries |
|
|
69
|
+
| `bun run storybook` | Storybook on port 6006 |
|
|
70
|
+
| `bun run build-storybook` | static Storybook build; its toolbar switches every story between light and dark |
|
|
71
|
+
| `bun run screenshots` / `bun run screenshots:dark` | screenshots of the stories tagged `website`, in light into `screenshots/`, in dark into `screenshots/dark/` |
|
|
72
|
+
| `bun run build:serve` | the serve runtime, `dist/protobase-serve.js` (see [Deploy](guides/deploy.md))) |
|
|
73
|
+
| `bun run docs:dev` | this site on port 4321 |
|
|
74
|
+
| `bun run docs:build` | this site, built into `website/dist/`; fails on broken links |
|
|
75
|
+
| `bun run release --dry-run` | the next version and its changelog, from the commits since the last release (see [Versioning](reference/versioning.md))) |
|
|
76
|
+
| `bun run docs:check` | opens every page of the built site in Chromium and fails on console errors and failed requests; `BASE=https://docs.protobase.net` checks the live site |
|
|
77
|
+
|
|
78
|
+
Each public import is a package in `packages/` (`@protobase/schema`, `layout`, `query`, `client`, `ui`, `server`, and `cli` for the `protobase` command); `packages/presets` writes the projects a new app starts from and is not published. See [Architecture](reference/architecture.md)) for the layout and import rules.
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
<!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/guides/api-functions.mdx: run `bun run docs:skill`, do not edit. -->
|
|
2
|
+
|
|
3
|
+
# Your own API functions
|
|
4
|
+
|
|
5
|
+
Endpoints of your own beside the generated REST API, one file each in functions/, acting as the signed-in caller or open to a webhook.
|
|
6
|
+
|
|
7
|
+
The [REST API](../reference/api.md)) covers reading and writing records. For anything else you write a function: a webhook from a payment provider, a button that makes three writes and then texts the customer, an endpoint for another app. Each function is one file in the project's `functions/` folder, served at `/api/functions/<name>`.
|
|
8
|
+
|
|
9
|
+
If you have used Supabase Edge Functions, this will feel familiar. A function is a Web-standard handler that takes a `Request` and returns a `Response`. Only signed-in callers get in unless the function says otherwise. It has a data client that acts as the caller, and the raw database for privileged work.
|
|
10
|
+
|
|
11
|
+
The examples below come from Pip's bike shop (see [From a table to an admin](table-to-admin.md))). The repository compiles and tests every one of them.
|
|
12
|
+
|
|
13
|
+
## A first function
|
|
14
|
+
|
|
15
|
+
```ts title="functions/hello.ts"
|
|
16
|
+
import { defineFunction } from '@protobase/server'
|
|
17
|
+
|
|
18
|
+
// GET /api/functions/hello: who is calling. Only a signed-in user gets here; anyone else gets a 401 problem.
|
|
19
|
+
export default defineFunction((_request, { session }) =>
|
|
20
|
+
Response.json({ message: `Hello, ${session.user.id}`, roles: session.user.roles }),
|
|
21
|
+
)
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
`protobase dev` serves it at `http://localhost:5173/api/functions/hello`. A change reloads it on the next request, and a new file appears after the next change inside the project. `protobase build` bundles the functions into the deploy bundle, and `protobase serve` serves them the same way. Call it with a token:
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
curl -H "Authorization: Bearer $(protobase token pip@example.com)" http://localhost:5173/api/functions/hello
|
|
28
|
+
# {"message":"Hello, 9f3c…","roles":["admin"]}
|
|
29
|
+
curl -i http://localhost:5173/api/functions/hello
|
|
30
|
+
# HTTP/1.1 401 Unauthorized, an application/problem+json body like every other refusal
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The app's own `authenticate` checks the token, the same one that guards the REST API, so a function needs no auth code of its own. A call without a valid token is the usual `401` problem, and the handler never runs.
|
|
34
|
+
|
|
35
|
+
## Files and names
|
|
36
|
+
|
|
37
|
+
- **One function per file:** `functions/<name>.ts`, or `functions/<name>/index.ts` for a function of several files. The name is the URL segment, so it uses letters, digits, `-` and `_`.
|
|
38
|
+
- **Not functions:** files and folders starting with `_` (shared code, such as `functions/_shared/`), dotfiles, `*.test.ts`, `*.spec.ts` and `*.d.ts`. A folder without an `index.ts` is an error that says so.
|
|
39
|
+
- **The default export** is `defineFunction(...)` from `@protobase/server`, a bare `(request, context)` handler, or a Hono app. The last two need a signed-in caller.
|
|
40
|
+
- **Any method** reaches the function, and so does any path below its name. The request's path is the part after `/api/functions/<name>`: `/` for the function itself, `/42/advance` for `/api/functions/workshop/42/advance`. The query string and the body are passed through unchanged.
|
|
41
|
+
- **In `protobase.config.ts`,** `functions: { name: fn }` replaces the folder, the same way `config` replaces `config/index.ts`. The functions of [extended configs](../reference/cli.md#extending-a-config)) are kept, and a name used by two configs is an error that names both.
|
|
42
|
+
|
|
43
|
+
## The context
|
|
44
|
+
|
|
45
|
+
The second argument of a handler (`c.env` in a [Hono app](#hono-apps)):
|
|
46
|
+
|
|
47
|
+
| | |
|
|
48
|
+
| --- | --- |
|
|
49
|
+
| `session` | The caller: `{ user: { id, roles }, tenant? }`, from the app's `authenticate`. |
|
|
50
|
+
| `records` | The app's resources, acting as the caller: `list`, `get`, `create`, `update`, `delete`. |
|
|
51
|
+
| `db` | The Kysely instance itself. It skips every access rule, row filter and tenant scope. |
|
|
52
|
+
| `caller()` | Resolves to `{ session, records }`. Public functions use it to ask for a caller when they need one. |
|
|
53
|
+
| `name` | The function's name. |
|
|
54
|
+
|
|
55
|
+
A [public function](#public-functions-and-webhooks) has only `db`, `caller()` and `name`.
|
|
56
|
+
|
|
57
|
+
## Reading and writing records as the caller
|
|
58
|
+
|
|
59
|
+
```ts title="functions/ready-for-pickup.ts"
|
|
60
|
+
import { z } from 'zod'
|
|
61
|
+
import { defineFunction, HttpProblem, readJson } from '@protobase/server'
|
|
62
|
+
|
|
63
|
+
const Input = z.object({ repairId: z.number().int().positive() })
|
|
64
|
+
|
|
65
|
+
// POST /api/functions/ready-for-pickup { "repairId": 7 }: the workshop finishes a repair. It reads and writes as the
|
|
66
|
+
// caller, so a mechanic touches only the repairs their access rules allow, and the repair's validation and write hooks
|
|
67
|
+
// run as for any other update.
|
|
68
|
+
export default defineFunction({ roles: ['mechanic', 'desk'] }, async (request, { records }) => {
|
|
69
|
+
const { repairId } = await readJson(request, Input)
|
|
70
|
+
const { record: repair, etag } = await records.get('repairs', repairId)
|
|
71
|
+
if (repair.status !== 'working') {
|
|
72
|
+
throw new HttpProblem(409, 'not-in-progress', 'Conflict', `Repair ${repair.number} is ${repair.status}, not in the workshop`)
|
|
73
|
+
}
|
|
74
|
+
// The ETag makes this fail with 412 when someone changed the repair since it was read.
|
|
75
|
+
const ready = await records.update('repairs', repairId, { status: 'ready' }, { etag })
|
|
76
|
+
const waiting = await records.list('repairs', { filter: `customer_id = ${repair.customer_id} AND status = "ready"`, fields: ['number', 'bike'] })
|
|
77
|
+
return Response.json({ repair: ready.record, readyForCustomer: waiting.items.map(({ number, bike }) => ({ number, bike })) })
|
|
78
|
+
})
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
`records` takes the same path as the REST API. The caller's access rules, row filters, field access and tenant scope apply. So do the resource's validation and the write hooks, and a record the caller may not see is not there:
|
|
82
|
+
|
|
83
|
+
| | |
|
|
84
|
+
| --- | --- |
|
|
85
|
+
| `list(resource, params?)` | A page as `GET /api/v1/{resource}` gives it: `{ items, next_page_token, total_size_estimate }`. `params` are `filter`, `order_by`, `page_size`, `page_token`, `fields` (an array), `count: 'exact'` and `show_deleted`. |
|
|
86
|
+
| `get(resource, key)` | `{ record, etag }`. A composite key is an array of its parts, or `a,b` as in a URL. |
|
|
87
|
+
| `create(resource, data)` | `{ record, etag }` of the new record. |
|
|
88
|
+
| `update(resource, key, data, { etag }?)` | With `etag`, it fails with `412` when the record changed after it was read. |
|
|
89
|
+
| `delete(resource, key, { etag }?)` | `{ record, etag }` of the record as it was. It is a soft delete when the resource has one. |
|
|
90
|
+
|
|
91
|
+
A refusal or a missing record rejects with the problem the REST API would answer, such as `403`, `404` or `412`. Left uncaught, that problem becomes the function's response. Each call is its own transaction. Use the [batch endpoint](../reference/api.md#batch-writes)) when several writes must succeed or fail together.
|
|
92
|
+
|
|
93
|
+
### Checking input
|
|
94
|
+
|
|
95
|
+
`readJson(request, schema)` reads the body and checks it against a schema. It takes any [Standard Schema](https://standardschema.dev), such as zod 4, Valibot or ArkType. The result is typed. A body that is not JSON is a `400 malformed-json` problem. A body the schema refuses is a `400 invalid-body` problem with an `errors` list of `{ field, message }`. Without a schema, `readJson(request)` only parses the JSON.
|
|
96
|
+
|
|
97
|
+
### Roles
|
|
98
|
+
|
|
99
|
+
`defineFunction({ roles: ['mechanic', 'desk'] }, handler)` lets in callers with at least one of those roles. Anyone else gets a `403 function-forbidden` problem before the handler runs. Finer rules belong in the resources' [access rules](../reference/access.md)), which `records` already applies.
|
|
100
|
+
|
|
101
|
+
## Public functions and webhooks
|
|
102
|
+
|
|
103
|
+
```ts title="functions/payment-webhook.ts"
|
|
104
|
+
import { defineFunction, requireEnv, verifySignature } from '@protobase/server'
|
|
105
|
+
|
|
106
|
+
type PaymentEvent = { type: string; data: { reference: string } }
|
|
107
|
+
|
|
108
|
+
// POST /api/functions/payment-webhook: the payment provider says a repair is paid. Nobody signs in to send it, so the
|
|
109
|
+
// function is public and checks the provider's signature instead; with no caller, it writes through the database
|
|
110
|
+
// directly, past every access rule.
|
|
111
|
+
export default defineFunction({ public: true }, async (request, { db }) => {
|
|
112
|
+
const body = await verifySignature(request, { secret: requireEnv('PAYMENTS_WEBHOOK_SECRET'), header: 'x-signature', prefix: 'sha256=' })
|
|
113
|
+
const event = JSON.parse(body) as PaymentEvent
|
|
114
|
+
if (event.type === 'payment.succeeded') {
|
|
115
|
+
await db.updateTable('shop.repairs').set({ paid: true }).where('number', '=', event.data.reference).execute()
|
|
116
|
+
}
|
|
117
|
+
return new Response(null, { status: 204 })
|
|
118
|
+
})
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
`{ public: true }` lets anyone call the function. A sender that signs its requests is checked with one of these helpers. Each returns the body as text once the signature matches, and otherwise throws a `401 invalid-signature` problem:
|
|
122
|
+
|
|
123
|
+
- `verifySignature(request, { secret, header, prefix?, encoding?, hash? })` checks an HMAC of the body (`hex` and `SHA-256` by default), as GitHub, Shopify and many payment providers sign. GitHub's is `{ header: 'x-hub-signature-256', prefix: 'sha256=' }`, and Shopify's is `{ header: 'x-shopify-hmac-sha256', encoding: 'base64' }`.
|
|
124
|
+
- `verifyStandardWebhook(request, { secret })` checks [Standard Webhooks](https://www.standardwebhooks.com) signatures, as Supabase Auth hooks, Svix and Resend send them, including the timestamp (5 minutes of tolerance by default).
|
|
125
|
+
- Stripe ships its own check: `stripe.webhooks.constructEventAsync(await request.text(), request.headers.get('stripe-signature'), secret)`.
|
|
126
|
+
|
|
127
|
+
A public function has no caller, so it has no `records`. Its `db` skips the tenant scope too, so filter by tenant yourself where it matters. When a function should serve anyone but treat a signed-in caller differently, `await context.caller()` resolves the caller from the request, or rejects with the `401` problem.
|
|
128
|
+
|
|
129
|
+
## Secrets and other APIs
|
|
130
|
+
|
|
131
|
+
```ts title="functions/notify-customer.ts"
|
|
132
|
+
import { z } from 'zod'
|
|
133
|
+
import { defineFunction, readJson, requireEnv } from '@protobase/server'
|
|
134
|
+
|
|
135
|
+
const Input = z.object({ repairId: z.number().int().positive() })
|
|
136
|
+
|
|
137
|
+
// POST /api/functions/notify-customer { "repairId": 7 }: texts the customer that their bike is ready, through an SMS
|
|
138
|
+
// provider's API. The key comes from the environment: .env in development, the host's settings in production.
|
|
139
|
+
export default defineFunction({ roles: ['desk'] }, async (request, { records }) => {
|
|
140
|
+
const { repairId } = await readJson(request, Input)
|
|
141
|
+
const { record: repair } = await records.get('repairs', repairId)
|
|
142
|
+
const { record: customer } = await records.get('customers', repair.customer_id as number)
|
|
143
|
+
if (!customer.phone) return Response.json({ sent: false, reason: 'The customer has no phone number' })
|
|
144
|
+
|
|
145
|
+
const sent = await fetch('https://api.sms.example/v1/messages', {
|
|
146
|
+
method: 'POST',
|
|
147
|
+
headers: { authorization: `Bearer ${requireEnv('SMS_API_KEY')}`, 'content-type': 'application/json' },
|
|
148
|
+
body: JSON.stringify({ to: customer.phone, text: `Hi ${customer.name}, your ${repair.bike} is ready for pickup.` }),
|
|
149
|
+
})
|
|
150
|
+
if (!sent.ok) throw new Error(`The SMS provider answered ${sent.status}`)
|
|
151
|
+
return Response.json({ sent: true })
|
|
152
|
+
})
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
`requireEnv(name)` returns an environment variable, or throws when it is not set. The call then fails as a `500` that the app reports, and the request goes nowhere. `protobase dev` and `protobase serve` read the nearest `.env` file. In production the serve runtime takes the host's environment as it is, so set the secret where the host keeps its settings. Keep secrets in functions, never in `protobase.ui.tsx`, which runs in the browser.
|
|
156
|
+
|
|
157
|
+
## Calling a function
|
|
158
|
+
|
|
159
|
+
From the admin UI, an [action handler](../reference/custom-components.md#action-handlers)) gets a `client` that carries the user's token. `client.invoke` calls a function the way `supabase.functions.invoke` does:
|
|
160
|
+
|
|
161
|
+
```tsx
|
|
162
|
+
// protobase.ui.tsx
|
|
163
|
+
import { defineUi } from '@protobase/ui'
|
|
164
|
+
|
|
165
|
+
export default defineUi({
|
|
166
|
+
actions: {
|
|
167
|
+
readyForPickup: async ({ client, record }) => {
|
|
168
|
+
await client.invoke('ready-for-pickup', { body: { repairId: record?.id } })
|
|
169
|
+
},
|
|
170
|
+
},
|
|
171
|
+
})
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
`invoke(name, { method?, body?, path?, query?, headers? })` sends a `GET`, or a `POST` with a JSON `body`. It resolves to the parsed JSON, to text, or to `undefined` for a `204`. A problem rejects with an `ApiError`, as any call of the client does. Outside the admin, `createClient` from `@protobase/client` gives the same `invoke`, or you can call the URL with `fetch` and an `Authorization: Bearer` header.
|
|
175
|
+
|
|
176
|
+
## Hono apps
|
|
177
|
+
|
|
178
|
+
A function of several routes can be a [Hono](https://hono.dev) app. The context is its `c.env`:
|
|
179
|
+
|
|
180
|
+
```ts title="functions/workshop/index.ts"
|
|
181
|
+
import { defineFunction, functionApp } from '@protobase/server'
|
|
182
|
+
import { nextStatus } from './status'
|
|
183
|
+
|
|
184
|
+
// /api/functions/workshop/*: the workshop's tablet app, a Hono app on its own origin. `c.env` is the function's
|
|
185
|
+
// context, so every route acts as the signed-in mechanic.
|
|
186
|
+
const app = functionApp()
|
|
187
|
+
|
|
188
|
+
// GET /api/functions/workshop/queue
|
|
189
|
+
app.get('/queue', async (c) => {
|
|
190
|
+
const page = await c.env.records.list('repairs', { filter: 'status = "waiting" OR status = "working"', order_by: 'booked_on', fields: ['id', 'number', 'bike', 'status'] })
|
|
191
|
+
return c.json(page.items)
|
|
192
|
+
})
|
|
193
|
+
|
|
194
|
+
// POST /api/functions/workshop/7/advance
|
|
195
|
+
app.post('/:id/advance', async (c) => {
|
|
196
|
+
const id = Number(c.req.param('id'))
|
|
197
|
+
const { record, etag } = await c.env.records.get('repairs', id)
|
|
198
|
+
const updated = await c.env.records.update('repairs', id, { status: nextStatus(record.status as string) }, { etag })
|
|
199
|
+
return c.json(updated.record)
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
export default defineFunction({ roles: ['mechanic'], cors: { origin: 'https://workshop.pips-bikes.example' } }, app)
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
`functionApp()` is `new Hono()` with one difference: errors and unknown paths reach the app's own error handling, so problems are rendered as problem+json and anything else is reported. Your own Hono instance works too, typed with `FunctionEnv` (or `PublicFunctionEnv`):
|
|
206
|
+
|
|
207
|
+
```ts
|
|
208
|
+
import { Hono } from 'hono'
|
|
209
|
+
import type { FunctionEnv } from '@protobase/server'
|
|
210
|
+
|
|
211
|
+
const app = new Hono<FunctionEnv>()
|
|
212
|
+
// Without this, Hono answers errors itself: a plain-text 500 that the app never reports.
|
|
213
|
+
app.onError((error) => {
|
|
214
|
+
throw error
|
|
215
|
+
})
|
|
216
|
+
export default app
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
A Hono app's routes start at `/`, because the request path no longer includes `/api/functions/<name>`. The deploy bundle supplies `hono`, `hono/cors`, `hono/http-exception` and `hono/validator` (see [the config module](../reference/cli.md#the-config-module))). Other Hono middleware is bundled with the function, as are its other packages.
|
|
220
|
+
|
|
221
|
+
### CORS
|
|
222
|
+
|
|
223
|
+
A function called from a page on another origin needs CORS. Use the `cors` option, which takes the options of `hono/cors`:
|
|
224
|
+
|
|
225
|
+
```ts
|
|
226
|
+
defineFunction({ cors: { origin: 'https://workshop.pips-bikes.example' } }, app)
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
Preflight requests are answered before authentication, because a browser sends them without a token. Every response, including a `401` problem, carries the CORS headers. In a protected function, the `hono/cors` middleware inside a Hono app would never see the preflight, because authentication runs first.
|
|
230
|
+
|
|
231
|
+
## Errors
|
|
232
|
+
|
|
233
|
+
- **Problems:** throw an `HttpProblem` (or `badRequest`, `unauthorized`, `forbidden`, `notFound` from `@protobase/server`) to answer with an [RFC 9457 problem](../reference/api.md#errors)). Hono's `HTTPException` works too.
|
|
234
|
+
- **Everything else:** any other error, or a handler that returns something other than a `Response`, becomes a `500 internal-error` problem without its message. The error goes to `options.onUnhandledError`, which `protobase dev` and `serve` print.
|
|
235
|
+
|
|
236
|
+
## What functions are not
|
|
237
|
+
|
|
238
|
+
- **Not under `/api/v1`,** which stays resources only. Functions live beside the system endpoints, like `/api/meta`.
|
|
239
|
+
- **Not in the OpenAPI document** or the `/api/docs` reference.
|
|
240
|
+
- **Not scheduled:** a function runs when it is called. A cron job on the host, or an external scheduler, can call one with a token, or call a public one that checks a signature.
|