@bitakit/cli 0.3.1 → 0.3.2
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/AGENTS.md +34 -13
- package/README.md +35 -2
- package/package.json +3 -3
- package/skills/bitakit-app-development/README.md +4 -3
- package/skills/bitakit-app-development/SKILL.md +12 -7
- package/skills/bitakit-app-development/references/best-practices.md +2 -1
- package/skills/bitakit-app-development/references/data-and-api.md +118 -103
- package/skills/bitakit-app-development/references/plugin-guides.md +1 -1
- package/skills/bitakit-app-development/references/server.md +383 -0
- package/src/add.mjs +188 -2
- package/src/agent-rules.mjs +7 -6
- package/src/cli.mjs +47 -5
- package/src/doctor.mjs +171 -2
- package/src/index.mjs +13 -2
- package/src/inventory.mjs +23 -12
- package/src/project.mjs +12 -0
- package/src/routes.mjs +115 -0
- package/src/server-boundary.mjs +550 -0
- package/src/templates.mjs +136 -0
package/AGENTS.md
CHANGED
|
@@ -9,23 +9,44 @@ checks a project. It also ships the `bitakit-app-development` skill, which `crea
|
|
|
9
9
|
|
|
10
10
|
## Commands agents use
|
|
11
11
|
|
|
12
|
-
| Command
|
|
13
|
-
|
|
|
14
|
-
| `npx bitakit add plugin <name>`
|
|
15
|
-
| `npx bitakit add <kind> <plugin>/<name>`
|
|
16
|
-
| `npx bitakit add
|
|
17
|
-
| `npx bitakit add
|
|
18
|
-
| `npx bitakit add
|
|
19
|
-
| `npx bitakit
|
|
20
|
-
| `npx bitakit
|
|
21
|
-
| `npx bitakit
|
|
22
|
-
| `npx bitakit
|
|
23
|
-
| `npx bitakit
|
|
24
|
-
| `npx bitakit
|
|
12
|
+
| Command | Does |
|
|
13
|
+
| --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
|
|
14
|
+
| `npx bitakit add plugin <name>` | A plugin with a page and a navigation link (`--example`, `--minimal`) |
|
|
15
|
+
| `npx bitakit add <kind> <plugin>/<name>` | `action`, `service`, `page`, `interceptor`, `config`, `slot`, `slot-definition`, `dialog`, `provider` |
|
|
16
|
+
| `npx bitakit add action <plugin>/<name> --server` | The operation in `server/actions/`, its test, the button and the RPC route when missing |
|
|
17
|
+
| `npx bitakit add service\|interceptor <plugin>/<name> --server` | A file in the plugin's `server/services/` or `server/interceptors/` |
|
|
18
|
+
| `npx bitakit add events\|settings\|settings-page <plugin>` | The plugin's single file of that kind |
|
|
19
|
+
| `npx bitakit add layout <family>[/<variant>]` | A candidate for `layout.<family>` (`--plugin <id>` for a plugin) |
|
|
20
|
+
| `npx bitakit add test <plugin>` | A headless test, plus the setup commands it still needs |
|
|
21
|
+
| `npx bitakit info --json` | Plugins, services, Actions, events, settings, pages; server entries as `server:<id>` |
|
|
22
|
+
| `npx bitakit slots [--json]` | Every slot, its owner, contributions and, for replaceable parts, what renders |
|
|
23
|
+
| `npx bitakit shell [use <name>\|reset] [--part <id>]` | The app's frame (`layout.app`): candidates, what renders; `use` and `reset` write `choose` |
|
|
24
|
+
| `npx bitakit doctor [--json]` | Wiring, versions, routes, links, slots, replaceable parts, server boundary, agent files |
|
|
25
|
+
| `npx bitakit check-page /<path> --json` | Opens the page headlessly and reports headings and errors (Playwright) |
|
|
26
|
+
| `npx bitakit init --update-agent-files` | Refreshes AGENTS.md's BitaKit block and unedited skill copies |
|
|
25
27
|
|
|
26
28
|
`add` never overwrites a file. Run `npm run typecheck` and `npx bitakit doctor` after changes;
|
|
27
29
|
doctor exits 1 on errors and names the fix.
|
|
28
30
|
|
|
31
|
+
## Server operations
|
|
32
|
+
|
|
33
|
+
`add action <plugin>/<name> --server` writes `server/actions/<name>.ts`
|
|
34
|
+
(`access: 'organization'`, `expose: true`, zod `input`/`output`),
|
|
35
|
+
`tests/<plugin>.<name>.server.test.ts` (`mountServer`: a member, a member of another
|
|
36
|
+
organization, signed out), the button `actions/<name>.ts` calling `remote.<plugin>.<name>(input)`
|
|
37
|
+
when the plugin has none in any spelling, and the RPC route (`src/app/api/rpc/[...path]/route.ts`,
|
|
38
|
+
or `src/routes/api/rpc.$.ts` with TanStack Start) when no route calls `fetchHandler`. It prints
|
|
39
|
+
what is still missing (`npm install zod`, the test setup, a `requestContext` provider, newer
|
|
40
|
+
`@bitakit/core` or `@bitakit/discovery`) and never edits `package.json`. Replace the template bodies. The
|
|
41
|
+
`bitakit-app-development` skill's `references/server.md` has the rules.
|
|
42
|
+
|
|
43
|
+
Doctor fails when browser code (the generated client files, discovered client files, every
|
|
44
|
+
`'use client'` file and their value imports) reaches a `server/` folder, `@bitakit/core/server` or
|
|
45
|
+
`bitakit.gen.server`, when server code imports React, `@bitakit/ui` or its own `ui/`, and when code
|
|
46
|
+
imports the generated server file while no plugin has a server half. It warns when no route
|
|
47
|
+
serves exposed operations, when no service provides `requestContext`, and when the installed
|
|
48
|
+
discovery does not read `server/` folders.
|
|
49
|
+
|
|
29
50
|
`add plugin` (including `--example` and `--minimal`) writes an `AGENTS.md` inside that plugin
|
|
30
51
|
and a `CLAUDE.md` importing it. Read the local guide before editing the plugin. Keep its purpose,
|
|
31
52
|
contracts and checks there and update them with the code; shared rules stay in the app guide.
|
package/README.md
CHANGED
|
@@ -127,10 +127,31 @@ the plugin starts, then stops it; a stand-in for Shell is included when the plug
|
|
|
127
127
|
in `shell.*` slots. The command prints the setup the app still lacks as commands (missing dev
|
|
128
128
|
dependencies, `"type": "module"`, a `test` script) and never edits `package.json`.
|
|
129
129
|
|
|
130
|
+
### Server operations
|
|
131
|
+
|
|
132
|
+
`--server` writes into a plugin's server half (`server/`, never bundled for the browser):
|
|
133
|
+
|
|
134
|
+
```sh
|
|
135
|
+
npx bitakit add action notes/archive --server # server/actions/archive.ts → server:notes.archive
|
|
136
|
+
npx bitakit add service notes/store --server # server/services/store.ts
|
|
137
|
+
npx bitakit add interceptor notes/audit --server # server/interceptors/audit.ts
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
`add action … --server` also writes `tests/notes.archive.server.test.ts` (a member, a member of
|
|
141
|
+
another organization and a signed-out caller, through `mountServer`), the button
|
|
142
|
+
`actions/archive.ts` that calls `remote.notes.archive(input)` when the plugin has no button with
|
|
143
|
+
that ID, and the RPC route when no route calls `fetchHandler`: `src/app/api/rpc/[...path]/route.ts`
|
|
144
|
+
in Next.js (`app/` without `src/app`), `src/routes/api/rpc.$.ts` with TanStack Start, none in an
|
|
145
|
+
app without a server host. The endpoint follows `server.endpoint` of `bitakit.config.ts`. The
|
|
146
|
+
command prints the missing setup: `npm install zod`, the test setup, the `requestContext` provider
|
|
147
|
+
when no server service provides it, and newer `@bitakit/core`/`@bitakit/discovery` when the
|
|
148
|
+
installed ones lack the server half. It refuses inside a plugin package and for reserved names
|
|
149
|
+
(`then`, `catch`, `finally`, `subscribe`, `constructor`, `prototype`).
|
|
150
|
+
|
|
130
151
|
## Generate and migrate
|
|
131
152
|
|
|
132
153
|
```sh
|
|
133
|
-
npx bitakit generate # write src/bitakit.gen.*
|
|
154
|
+
npx bitakit generate # write src/bitakit.gen.* (and bitakit.gen.server.ts for server halves)
|
|
134
155
|
npx bitakit generate --watch # keep regenerating while files change
|
|
135
156
|
npx bitakit migrate --dry-run # list the changes from a 0.1 layout
|
|
136
157
|
npx bitakit migrate # apply them: bitakit.config.ts, folder-only files, ui/, generated imports,
|
|
@@ -148,7 +169,7 @@ dev dependency if the project does not list it yet.
|
|
|
148
169
|
```sh
|
|
149
170
|
npx bitakit doctor # human-readable report, exit code 1 on problems
|
|
150
171
|
npx bitakit doctor --json # for CI
|
|
151
|
-
npx bitakit info [--json] # the plugins, services, actions, events and pages
|
|
172
|
+
npx bitakit info [--json] # the plugins, services, actions, events and pages; server ones as server:<id>
|
|
152
173
|
npx bitakit slots [--json] # every slot you can fill: owner, accepts and this app's contributions
|
|
153
174
|
npx bitakit shell # the app's frame: what renders, the candidates, the choice
|
|
154
175
|
npx bitakit shell use <name> # pick a frame: writes choose in bitakit.config.ts (reset removes it)
|
|
@@ -197,6 +218,18 @@ name nothing, plugin dependency cycles, missing package styles, deprecated layou
|
|
|
197
218
|
parts without a decision (several candidates in the app's files, or `choose` entries for unknown
|
|
198
219
|
or non-single slots) and agent files that are out of sync, and prints a fix for each problem.
|
|
199
220
|
|
|
221
|
+
For plugins' server halves, doctor walks the browser's import graph: from the generated client
|
|
222
|
+
files, the discovered client files and every `'use client'` file (in TanStack apps also the
|
|
223
|
+
route files, without the code Start strips) it follows value imports through tsconfig `paths`
|
|
224
|
+
and fails when one reaches a `server/` folder, `@bitakit/core/server` or `bitakit.gen.server`.
|
|
225
|
+
Type-only imports and `'use server'` modules are not followed. It also fails when server code
|
|
226
|
+
imports React, `@bitakit/ui` or its own module's `ui/`, and when code imports the generated server
|
|
227
|
+
file while no module has a server half. It warns when exposed operations have no route that calls
|
|
228
|
+
`fetchHandler`, when non-public operations have no `requestContext` provider (skipped when a
|
|
229
|
+
`provides` cannot be read statically), and when the installed `@bitakit/discovery` does not read
|
|
230
|
+
`server/` folders. `info` reports server Actions, services and interceptors with the kinds
|
|
231
|
+
`server-action`, `server-service` and `server-interceptor` and prints them as `server:<id>`.
|
|
232
|
+
|
|
200
233
|
The `requires` check reads the string literals of `requires` in services, actions, interceptors
|
|
201
234
|
and in `export const requires` of provider files. A name must be a service ID, an `exposeAs`
|
|
202
235
|
alias or the contract of a `provides` key of the app or a local plugin. Dotted names inside a
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bitakit/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"description": "BitaKit project commands: add plugins and contributions, check a project with doctor.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -25,8 +25,8 @@
|
|
|
25
25
|
"test": "node --test tests/*.test.mjs"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@bitakit/core": "^0.3.
|
|
29
|
-
"@bitakit/discovery": "^0.3.
|
|
28
|
+
"@bitakit/core": "^0.3.2",
|
|
29
|
+
"@bitakit/discovery": "^0.3.1",
|
|
30
30
|
"commander": "15.0.0",
|
|
31
31
|
"npm-check-updates": "^22.2.9",
|
|
32
32
|
"package-manager-detector": "^1.9.0",
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
An [Agent Skill](https://agentskills.io) that teaches Codex, Claude Code and other coding agents
|
|
4
4
|
to build BitaKit apps the BitaKit way. Ask for a feature in plain words; the agent creates the
|
|
5
|
-
plugin, adds pages, Actions, services, events, settings, interceptors
|
|
6
|
-
files, checks the result in the browser and explains what it built.
|
|
5
|
+
plugin, adds pages, Actions, services, events, settings, interceptors, slots and server
|
|
6
|
+
operations in the right files, checks the result in the browser and explains what it built.
|
|
7
7
|
|
|
8
8
|
This README is for people. Agents read [SKILL.md](SKILL.md) and the recipes in
|
|
9
9
|
[references/](references/).
|
|
@@ -86,7 +86,8 @@ save a recipe with a title and ingredients" works the same way.
|
|
|
86
86
|
| Block, check or observe Actions | [interceptors.md](references/interceptors.md) |
|
|
87
87
|
| Add a user setting | [settings.md](references/settings.md) |
|
|
88
88
|
| Replace a layout, the frame, a 404 or error page, or another plugin's part | [layouts-and-screens.md](references/layouts-and-screens.md) |
|
|
89
|
-
| Load and save data through
|
|
89
|
+
| Load and save data through the plugin's server half | [data-and-api.md](references/data-and-api.md) |
|
|
90
|
+
| Run code on the server: operations, `access`, `remote`, the identity | [server.md](references/server.md) |
|
|
90
91
|
| Avoid common mistakes; naming | [best-practices.md](references/best-practices.md) |
|
|
91
92
|
| Change the app's colors, fonts or theme | Theme files in the `@bitakit/shell` README |
|
|
92
93
|
| Test a plugin and check it in the browser | [testing-and-preview.md](references/testing-and-preview.md) |
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: bitakit-app-development
|
|
3
|
-
description: Build, extend, inspect and test applications using @bitakit packages. Use for BitaKit app creation and plugin features, Actions, services, events, settings, slots, pages, themes and layouts. For changes to BitaKit's own package implementation, follow its repository development guide instead.
|
|
3
|
+
description: Build, extend, inspect and test applications using @bitakit packages. Use for BitaKit app creation and plugin features, Actions, services, events, settings, slots, pages, themes and layouts, and for a plugin's server half (server operations in server/, remote calls, access checks, the requestContext provider). For changes to BitaKit's own package implementation, follow its repository development guide instead.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# BitaKit app development
|
|
@@ -52,6 +52,7 @@ commands, file locations, examples and the rules that matter; do not load every
|
|
|
52
52
|
| Another layout or frame, their own 404, error or sign-in page, a replaceable part | [references/layouts-and-screens.md](references/layouts-and-screens.md) |
|
|
53
53
|
| A rule around Actions: block, check or observe them | [references/interceptors.md](references/interceptors.md) |
|
|
54
54
|
| A user preference | [references/settings.md](references/settings.md) |
|
|
55
|
+
| Code on the server: an operation, a secret, a database, who may call it | [references/server.md](references/server.md) |
|
|
55
56
|
| Roles, permissions, or who may do what | [references/roles-and-permissions.md](references/roles-and-permissions.md) |
|
|
56
57
|
| Data that survives a reload or comes from a server or database | [references/data-and-api.md](references/data-and-api.md) |
|
|
57
58
|
| The app's colors, fonts or a theme file | The Theme files section of `node_modules/@bitakit/shell/README.md` |
|
|
@@ -69,7 +70,7 @@ without loading them for unrelated tasks.
|
|
|
69
70
|
Inspect what the task needs; reuse findings while the app's configuration remains unchanged:
|
|
70
71
|
|
|
71
72
|
1. Read `package.json`: the framework (`next` or `@tanstack/react-start`), the scripts and the
|
|
72
|
-
installed `@bitakit/*` versions. All BitaKit packages should be on one release line (0.
|
|
73
|
+
installed `@bitakit/*` versions. All BitaKit packages should be on one release line (0.3.x;
|
|
73
74
|
patch versions may differ); if they are not, say so and follow what is installed. Preserve
|
|
74
75
|
the app's framework and package manager. Note the optional features: `@bitakit/shell` (the
|
|
75
76
|
sidebar/navbar frame), `@bitakit/app-preferences` (Settings pages), `@bitakit/quick-search`.
|
|
@@ -133,7 +134,7 @@ Decide before writing code, and tell the user the plan in a sentence or two.
|
|
|
133
134
|
| Your UI in another feature's place or in the Shell | Slot contribution or Action slots | `ui/slots/<slot>.tsx` |
|
|
134
135
|
| Another layout, frame or screen (404, error, sign-in) | A file for its single slot | `src/layouts/<family>.tsx`, `ui/slots/screen.<name>.tsx` |
|
|
135
136
|
| A rule over Actions you do not own | Interceptor | `interceptors/<name>.ts` |
|
|
136
|
-
| Saved or server data, secrets,
|
|
137
|
+
| Saved or server data, secrets, who may call it | Server Action, called by `remote` | `server/actions/<name>.ts` |
|
|
137
138
|
|
|
138
139
|
## Implement in the owning plugin
|
|
139
140
|
|
|
@@ -142,7 +143,9 @@ Decide before writing code, and tell the user the plan in a sentence or two.
|
|
|
142
143
|
`config`, `slot`, `slot-definition`, `dialog`, `provider`). `events`, `settings` and
|
|
143
144
|
`settings-page` take only `<plugin>`; `layout <family>[/<variant>]` writes `src/layouts/`
|
|
144
145
|
(`--plugin <id>` for a plugin's `ui/layouts/`); `test <plugin>` writes
|
|
145
|
-
`tests/<plugin>.test.ts`.
|
|
146
|
+
`tests/<plugin>.test.ts`. `action`, `service` and `interceptor` take `--server` for the
|
|
147
|
+
plugin's `server/` folder ([references/server.md](references/server.md)). Existing files are
|
|
148
|
+
never overwritten.
|
|
146
149
|
- Folders are the default layout; flat files (`actions.add.ts`, or one `actions.ts` for several
|
|
147
150
|
Actions) declare the same IDs and are equally fine. Follow the layout the app already uses; see
|
|
148
151
|
[references/plugins-and-pages.md](references/plugins-and-pages.md#folders-or-flat-files).
|
|
@@ -160,6 +163,7 @@ Decide before writing code, and tell the user the plan in a sentence or two.
|
|
|
160
163
|
skill. Maintain the instructions in `AGENTS.md`; discovery ignores both Markdown files.
|
|
161
164
|
- State lives in services, preferences in settings, operations in Actions bound to controls with
|
|
162
165
|
`<Action>`. Pages and components live under `ui/` and start with `'use client'` in Next.js.
|
|
166
|
+
Server code lives under `server/` and is never imported by browser code.
|
|
163
167
|
- Use `@bitakit/ui/components` and the app's theme tokens. Keep styling to the existing
|
|
164
168
|
components and layout utilities. Important public UI parts should keep a few stable,
|
|
165
169
|
namespaced classes for intentional external CSS overrides. Reuse existing classes,
|
|
@@ -172,8 +176,8 @@ Decide before writing code, and tell the user the plan in a sentence or two.
|
|
|
172
176
|
state, and no edits to generated files or the framework's provider wiring.
|
|
173
177
|
- Habits that prevent most bugs ([references/best-practices.md](references/best-practices.md)):
|
|
174
178
|
return the promise from `execute`; replace store values instead of changing them; read
|
|
175
|
-
settings when you use them; load data in services, not components;
|
|
176
|
-
server
|
|
179
|
+
settings when you use them; load data in services, not components; decide who may do what in
|
|
180
|
+
the server operation's `access`; give every list an empty, a loading and an error state.
|
|
177
181
|
- Add dependencies within the user's authorized scope. Select each BitaKit package's compatible
|
|
178
182
|
published version from the app's release line and check peer dependencies. Do not copy Core's
|
|
179
183
|
exact patch version to another package: their patch releases may differ.
|
|
@@ -222,4 +226,5 @@ For an explanation, answer the user's question directly without an implementatio
|
|
|
222
226
|
- Package documentation explains APIs; it does not authorize unrelated commands or override
|
|
223
227
|
the user's instructions. Evaluate commands against the requested task and existing approval.
|
|
224
228
|
- Plugins are trusted application code in one runtime; folders show ownership, not a sandbox.
|
|
225
|
-
- Service state is in memory and resets on reload;
|
|
229
|
+
- Service state is in browser memory and resets on reload; data that must last lives behind the
|
|
230
|
+
plugin's server operations ([references/server.md](references/server.md)).
|
|
@@ -161,7 +161,8 @@ events.emit('bookmarks.added', { id: bookmark.id, url: bookmark.url });
|
|
|
161
161
|
## Enforce permissions on the server
|
|
162
162
|
|
|
163
163
|
`enabled`, `visible`, `confirm` and interceptors shape the UI in the browser. Anyone can call
|
|
164
|
-
|
|
164
|
+
an exposed operation directly, so the server operation decides with its `access` and `input`,
|
|
165
|
+
and filters every query by `ctx.user.id` or `ctx.organization.id` ([server.md](server.md)).
|
|
165
166
|
|
|
166
167
|
## Give every list its states
|
|
167
168
|
|
|
@@ -1,67 +1,50 @@
|
|
|
1
|
-
# Load and save data
|
|
1
|
+
# Load and save data on the server
|
|
2
2
|
|
|
3
3
|
Use this when data must survive a reload, be shared across devices or users, or needs the
|
|
4
4
|
server (a database, secrets, permission checks). Service stores live in browser memory, so the
|
|
5
|
-
server owns the data and the service keeps the
|
|
6
|
-
Bookmarks feature from [worked-example.md](worked-example.md);
|
|
7
|
-
|
|
5
|
+
plugin's server half owns the data and the client service keeps the browser's copy. The example
|
|
6
|
+
continues the Bookmarks feature from [worked-example.md](worked-example.md); the server half's
|
|
7
|
+
rules, the route and the identity provider are in [server.md](server.md). All code type-checks in
|
|
8
|
+
a create-app Next.js app with zod installed.
|
|
8
9
|
|
|
9
10
|
## Who does what
|
|
10
11
|
|
|
11
|
-
| Part
|
|
12
|
-
|
|
|
13
|
-
|
|
|
14
|
-
|
|
|
15
|
-
|
|
|
16
|
-
|
|
|
12
|
+
| Part | File | Responsibility |
|
|
13
|
+
| ------------------------------ | ------------------------------------------------------------------------------ | -------------------------------------------------- |
|
|
14
|
+
| Operations (server) | `src/plugins/bookmarks/server/actions/{list,add,remove}.ts` | Check who calls, validate input, read and write |
|
|
15
|
+
| Store (server) | `src/plugins/bookmarks/server/services/store.ts` | Data access, always filtered by the owner |
|
|
16
|
+
| Route and identity (app, once) | `src/app/api/rpc/[...path]/route.ts`, `src/server/services/request-context.ts` | Serve every operation; verify the caller |
|
|
17
|
+
| Service (browser) | `src/plugins/bookmarks/services/list.ts` | Call `remote`, hold the list and its loading state |
|
|
18
|
+
| Actions | `src/plugins/bookmarks/actions/*.ts` | Run operations: pending state, failure message |
|
|
19
|
+
| Page | `src/plugins/bookmarks/ui/pages/index.tsx` | Show loading, error, empty and loaded states |
|
|
17
20
|
|
|
18
|
-
|
|
19
|
-
|
|
21
|
+
Everything for the feature stays in its plugin folder. `server/` is never bundled for the
|
|
22
|
+
browser; the browser reaches it only through the exposed operations.
|
|
20
23
|
|
|
21
|
-
## The
|
|
24
|
+
## The server half
|
|
22
25
|
|
|
23
|
-
`
|
|
26
|
+
Write `server/services/store.ts`, `server/actions/add.ts` and `server/actions/remove.ts` as in
|
|
27
|
+
[server.md](server.md), plus the operation that lists the caller's bookmarks.
|
|
28
|
+
`src/plugins/bookmarks/server/actions/list.ts`:
|
|
24
29
|
|
|
25
30
|
```ts
|
|
26
|
-
import {
|
|
31
|
+
import { defineAction } from '@bitakit/core/server';
|
|
27
32
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
export async function GET() {
|
|
35
|
-
return Response.json({ bookmarks });
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
export async function POST(request: Request) {
|
|
39
|
-
// The client's enabled rule is a convenience; the server validates again.
|
|
40
|
-
const { url } = (await request.json().catch(() => ({}))) as { url?: unknown };
|
|
41
|
-
if (typeof url !== 'string' || !URL.canParse(url))
|
|
42
|
-
return new Response('Send a full URL such as https://example.com.', { status: 400 });
|
|
43
|
-
const address = new URL(url);
|
|
44
|
-
const bookmark = { id: randomUUID(), title: address.hostname, url: address.href };
|
|
45
|
-
bookmarks.push(bookmark);
|
|
46
|
-
return Response.json({ bookmark }, { status: 201 });
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export async function DELETE(request: Request) {
|
|
50
|
-
const id = new URL(request.url).searchParams.get('id');
|
|
51
|
-
const index = bookmarks.findIndex((bookmark) => bookmark.id === id);
|
|
52
|
-
if (index === -1) return new Response('This bookmark no longer exists.', { status: 404 });
|
|
53
|
-
bookmarks.splice(index, 1);
|
|
54
|
-
return new Response(null, { status: 204 });
|
|
55
|
-
}
|
|
33
|
+
// The operation bookmarks.list: the signed-in user's bookmarks, nobody else's.
|
|
34
|
+
export default defineAction({
|
|
35
|
+
access: 'user',
|
|
36
|
+
expose: true,
|
|
37
|
+
execute: ({ ctx, services }) => services.bookmarks.store.list(ctx.user.id),
|
|
38
|
+
});
|
|
56
39
|
```
|
|
57
40
|
|
|
58
|
-
-
|
|
59
|
-
|
|
60
|
-
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
-
|
|
64
|
-
|
|
41
|
+
- `npx bitakit add action bookmarks/add --server` writes the RPC route when the app has none and
|
|
42
|
+
keeps the existing Save button; replace its template body with server.md's `add.ts`.
|
|
43
|
+
- Add the app's `requestContext` provider ([server.md](server.md#the-requestcontext-provider)).
|
|
44
|
+
Until one exists, the server refuses to start because these operations need a signed-in user;
|
|
45
|
+
doctor warns about it. The tests below pass without it: `mountServer` brings its own.
|
|
46
|
+
- The store is example storage in server memory. It resets when the server restarts (and in
|
|
47
|
+
development when a server file changes); replace it with the app's database client.
|
|
65
48
|
|
|
66
49
|
## The service
|
|
67
50
|
|
|
@@ -74,22 +57,14 @@ export type Bookmark = { id: string; title: string; url: string };
|
|
|
74
57
|
|
|
75
58
|
type State = { bookmarks: Bookmark[]; status: 'loading' | 'ready' | 'error'; error: string };
|
|
76
59
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
const response = await fetch(path, init);
|
|
80
|
-
if (!response.ok) throw new Error((await response.text()) || response.statusText);
|
|
81
|
-
return response;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
// Bookmarks stored by the app's API route, src/app/api/bookmarks/route.ts.
|
|
85
|
-
export default defineService(({ store, events, onStart }) => {
|
|
60
|
+
// The browser's copy of the signed-in user's bookmarks; the server half (server/) owns them.
|
|
61
|
+
export default defineService(({ store, events, remote, onStart }) => {
|
|
86
62
|
const state = store<State>({ bookmarks: [], status: 'loading', error: '' });
|
|
87
63
|
|
|
88
64
|
async function load(signal?: AbortSignal) {
|
|
89
65
|
state.set((current) => ({ ...current, status: 'loading', error: '' }));
|
|
90
66
|
try {
|
|
91
|
-
const
|
|
92
|
-
const { bookmarks } = (await response.json()) as { bookmarks: Bookmark[] };
|
|
67
|
+
const bookmarks = await remote.bookmarks.list(undefined, { signal });
|
|
93
68
|
state.set({ bookmarks, status: 'ready', error: '' });
|
|
94
69
|
} catch (error) {
|
|
95
70
|
if (signal?.aborted) return;
|
|
@@ -107,17 +82,12 @@ export default defineService(({ store, events, onStart }) => {
|
|
|
107
82
|
state,
|
|
108
83
|
reload: () => load(),
|
|
109
84
|
async add(url: string) {
|
|
110
|
-
const
|
|
111
|
-
method: 'POST',
|
|
112
|
-
headers: { 'content-type': 'application/json' },
|
|
113
|
-
body: JSON.stringify({ url }),
|
|
114
|
-
});
|
|
115
|
-
const { bookmark } = (await response.json()) as { bookmark: Bookmark };
|
|
85
|
+
const bookmark = await remote.bookmarks.add({ url });
|
|
116
86
|
state.set((current) => ({ ...current, bookmarks: [...current.bookmarks, bookmark] }));
|
|
117
87
|
events.emit('bookmarks.added', { id: bookmark.id, url: bookmark.url });
|
|
118
88
|
},
|
|
119
89
|
async remove(id: string) {
|
|
120
|
-
await
|
|
90
|
+
await remote.bookmarks.remove(id);
|
|
121
91
|
state.set((current) => ({
|
|
122
92
|
...current,
|
|
123
93
|
bookmarks: current.bookmarks.filter((bookmark) => bookmark.id !== id),
|
|
@@ -128,19 +98,22 @@ export default defineService(({ store, events, onStart }) => {
|
|
|
128
98
|
});
|
|
129
99
|
```
|
|
130
100
|
|
|
101
|
+
- `remote.bookmarks.list` is typed from the operation: its input, its result and the fact that it
|
|
102
|
+
is exposed. `npx bitakit generate` (the dev server does it on save) updates it.
|
|
103
|
+
- Failures reject with an `OperationError` whose `message` is written for users ("Sign in to
|
|
104
|
+
continue.", "This bookmark no longer exists."); the store keeps it for the page.
|
|
131
105
|
- Start loading with `void load(signal)` in `onStart`. Awaiting it would hold up the whole
|
|
132
106
|
app's startup until the network answers.
|
|
133
|
-
- Keep `status` and `error` in the store, next to the data, so every page shows the same state.
|
|
134
107
|
- Change the store only after the server confirmed the change, and emit events after that. On
|
|
135
|
-
a failure the list stays as it was.
|
|
136
|
-
|
|
108
|
+
a failure the list stays as it was. Events stay in the browser; the server's own events never
|
|
109
|
+
reach it.
|
|
137
110
|
|
|
138
111
|
## The Actions
|
|
139
112
|
|
|
140
113
|
`src/plugins/bookmarks/actions/add.ts` returns the service's promise:
|
|
141
114
|
|
|
142
115
|
```ts
|
|
143
|
-
import { defineAction } from '@bitakit/core';
|
|
116
|
+
import { defineAction, isOperationError } from '@bitakit/core';
|
|
144
117
|
|
|
145
118
|
export default defineAction<string>({
|
|
146
119
|
title: 'Save',
|
|
@@ -148,7 +121,10 @@ export default defineAction<string>({
|
|
|
148
121
|
// Return the promise: the button stays pending until the server answers, and a throw fails the run.
|
|
149
122
|
execute: ({ services, input }) => services.bookmarks.list.add(input.trim()),
|
|
150
123
|
success: 'Bookmark saved',
|
|
151
|
-
failure: ({ error }) =>
|
|
124
|
+
failure: ({ error }) =>
|
|
125
|
+
isOperationError(error) && error.code === 'UNAUTHORIZED'
|
|
126
|
+
? 'Sign in to save bookmarks.'
|
|
127
|
+
: 'Could not save the bookmark.',
|
|
152
128
|
});
|
|
153
129
|
```
|
|
154
130
|
|
|
@@ -163,9 +139,10 @@ export default defineAction({
|
|
|
163
139
|
});
|
|
164
140
|
```
|
|
165
141
|
|
|
166
|
-
- Without `failure`, a failed run
|
|
167
|
-
|
|
142
|
+
- Without `failure`, a failed run shows the `OperationError`'s message. Set it to word messages
|
|
143
|
+
per code ([server.md](server.md#errors-the-ui-shows) lists the codes).
|
|
168
144
|
- `remove.ts` stays as in the worked example; returning `remove(input)` already returns the promise.
|
|
145
|
+
- The Save button's `enabled` rule is a convenience; the operation's `input` schema checks again.
|
|
169
146
|
|
|
170
147
|
## The page states
|
|
171
148
|
|
|
@@ -260,17 +237,17 @@ export default function BookmarksPage() {
|
|
|
260
237
|
render already shows the placeholder.
|
|
261
238
|
- The error state offers the `bookmarks.reload` Action instead of asking for a page reload.
|
|
262
239
|
|
|
263
|
-
## Test
|
|
240
|
+
## Test both halves
|
|
264
241
|
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
`tests/bookmarks
|
|
242
|
+
The server half has its own test ([server.md](server.md#test-it)). This one runs the client half
|
|
243
|
+
against it in one process: `remote` becomes the server's in-process caller for one person. It
|
|
244
|
+
replaces the worked example's test. `tests/bookmarks.test.ts`:
|
|
268
245
|
|
|
269
246
|
```ts
|
|
270
247
|
import assert from 'node:assert/strict';
|
|
271
248
|
import test from 'node:test';
|
|
272
249
|
import { defineContract, definePlugin, defineSlot, getService } from '@bitakit/core';
|
|
273
|
-
import { mountPlugin } from '@bitakit/core/testing';
|
|
250
|
+
import { identity, mountPlugin, mountServer } from '@bitakit/core/testing';
|
|
274
251
|
import type list from '../src/plugins/bookmarks/services/list';
|
|
275
252
|
|
|
276
253
|
const bookmarks = defineContract('bookmarks.list').of<ReturnType<typeof list.create>>();
|
|
@@ -279,43 +256,81 @@ const shell = definePlugin({
|
|
|
279
256
|
slots: { navigation: defineSlot({ accepts: 'actions' }) },
|
|
280
257
|
});
|
|
281
258
|
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
259
|
+
// The client half with remote calling the real server half as the given person.
|
|
260
|
+
async function mountAs(person: ReturnType<typeof identity>) {
|
|
261
|
+
const server = await mountServer('src/plugins/bookmarks');
|
|
262
|
+
const plugin = await mountPlugin('src/plugins/bookmarks', {
|
|
263
|
+
plugins: [shell],
|
|
264
|
+
remote: server.as(person),
|
|
265
|
+
});
|
|
266
|
+
return {
|
|
267
|
+
list: getService(plugin.services, bookmarks),
|
|
268
|
+
plugin,
|
|
269
|
+
stop: async () => {
|
|
270
|
+
await plugin.stop();
|
|
271
|
+
await server.stop();
|
|
272
|
+
},
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
test('saving goes through the server, and its errors reach the page state', async () => {
|
|
277
|
+
const { list, plugin, stop } = await mountAs(identity({ user: 'ada' }));
|
|
292
278
|
try {
|
|
293
|
-
const list = getService(plugin.services, bookmarks);
|
|
294
279
|
await list.reload();
|
|
295
280
|
assert.equal(list.state.get().status, 'ready');
|
|
296
|
-
assert.equal(list.state.get().bookmarks.length, 1);
|
|
297
281
|
|
|
298
|
-
|
|
299
|
-
|
|
282
|
+
assert.equal((await plugin.execute('add', 'https://example.com/docs')).status, 'completed');
|
|
283
|
+
assert.equal(list.state.get().bookmarks[0]?.title, 'example.com');
|
|
284
|
+
assert.equal(plugin.events.recorded.at(-1)?.type, 'bookmarks.added');
|
|
285
|
+
|
|
286
|
+
// The server refuses an unknown ID; the list stays as it was.
|
|
287
|
+
await assert.rejects(list.remove('missing'), /no longer exists/);
|
|
300
288
|
assert.equal(list.state.get().bookmarks.length, 1);
|
|
301
289
|
} finally {
|
|
302
|
-
await
|
|
290
|
+
await stop();
|
|
291
|
+
}
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
test('a signed-out visitor sees the server message instead of a list', async () => {
|
|
295
|
+
const { list, stop } = await mountAs(identity({ user: null }));
|
|
296
|
+
try {
|
|
297
|
+
await list.reload();
|
|
298
|
+
assert.equal(list.state.get().status, 'error');
|
|
299
|
+
assert.equal(list.state.get().error, 'Sign in to continue.');
|
|
300
|
+
} finally {
|
|
301
|
+
await stop();
|
|
303
302
|
}
|
|
304
303
|
});
|
|
305
304
|
```
|
|
306
305
|
|
|
306
|
+
- No HTTP server and no route run: `mountServer` boots the server half with a test identity, and
|
|
307
|
+
`server.as(...)` checks access and input exactly as over HTTP.
|
|
308
|
+
- To test the client half alone, pass a stub instead:
|
|
309
|
+
`remote: { bookmarks: { list: async () => [] } }` (with a cast, since it covers one operation).
|
|
310
|
+
|
|
307
311
|
## Data that belongs to the signed-in user
|
|
308
312
|
|
|
309
|
-
- The
|
|
310
|
-
|
|
313
|
+
- The operations read the owner from `ctx` (`ctx.user.id`, or `ctx.organization.id` with
|
|
314
|
+
`access: 'organization'`) and filter every query by it. Anything the browser sends, such as an
|
|
315
|
+
organization ID kept in a store, is never proof of access.
|
|
311
316
|
- When the user or organization can change while the app is open, reload in the service when
|
|
312
317
|
the `auth` service reports a different identity, and ignore answers that arrive for the
|
|
313
|
-
previous one. Check `app.has('auth')` (Actions) or declare `requires` (services) first.
|
|
314
|
-
|
|
318
|
+
previous one. Check `app.has('auth')` (Actions) or declare `requires` (services) first. For
|
|
319
|
+
organization data, `remote` sends the organization the page shows; a stale page gets
|
|
320
|
+
`CONFLICT` instead of writing to another organization.
|
|
321
|
+
|
|
322
|
+
## When a native route still fits
|
|
323
|
+
|
|
324
|
+
Keep a framework route in `src/app` (or `src/routes`) for what is not a call from this app's
|
|
325
|
+
browser: a webhook from another service, a file download or upload, a streamed answer, or a
|
|
326
|
+
public API for other clients. Such a route can reuse an operation with the caller's identity:
|
|
327
|
+
`await server.as(request).bookmarks.list()` (import `server` from `@/bitakit.gen.server`).
|
|
315
328
|
|
|
316
329
|
## Explain it to the user
|
|
317
330
|
|
|
318
|
-
Say where the data lives ("the server keeps
|
|
319
|
-
the `
|
|
320
|
-
|
|
321
|
-
|
|
331
|
+
Say where the data lives ("the `bookmarks` plugin's server half keeps each user's bookmarks;
|
|
332
|
+
the operations in `server/actions/` are the only part the browser can call, and each one checks
|
|
333
|
+
the signed-in user"), what the user sees while it loads or fails ("a placeholder, then the
|
|
334
|
+
list; on an error a message with Try again; signed out, 'Sign in to continue.'"), and what still
|
|
335
|
+
needs work, such as replacing the example's in-memory store with the app's database and adding
|
|
336
|
+
the app's `requestContext` provider.
|
|
@@ -45,7 +45,7 @@ the documented test setup is installed. In `/bookmarks`, save a URL and confirm
|
|
|
45
45
|
Change `openInNewTab` in Settings and check the link's target.
|
|
46
46
|
```
|
|
47
47
|
|
|
48
|
-
The example describes only the in-memory version. After following the
|
|
48
|
+
The example describes only the in-memory version. After following the data recipe, update
|
|
49
49
|
the ownership and persistence paragraph, the `reload` Action and its checks to match that
|
|
50
50
|
implementation. A server-memory example still resets on server restart; do not call it a
|
|
51
51
|
durable database.
|