@bitakit/cli 0.3.0 → 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.
@@ -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 API recipe, update
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.
@@ -0,0 +1,383 @@
1
+ # Server operations: a plugin's server half
2
+
3
+ Use this when code must run on the server: a database, a secret, a check of who may do
4
+ something, or data shared between users. The plugin keeps it in its own `server/` folder, which
5
+ is never bundled for the browser. The browser calls an exposed operation through the generated
6
+ `remote` client; there is no hand-written route or `fetch` per feature.
7
+ [data-and-api.md](data-and-api.md) builds the complete Bookmarks feature on these files.
8
+
9
+ ## The button and the operation
10
+
11
+ A server feature has two files with one name:
12
+
13
+ | File | It is | Edit it to change |
14
+ | ---------------------------------------- | ---------------------------------------------------- | ------------------------------------------------------ |
15
+ | `actions/add.ts` | The button (client Action `bookmarks.add`) | Label, `enabled`, `confirm`, messages, client state |
16
+ | `server/actions/add.ts` | The operation (server Action `server:bookmarks.add`) | Input, who may call it, what it reads and changes |
17
+ | `server/services/<name>.ts` | Server logic and data access the operations share | Queries, clients, caches |
18
+ | `src/server/services/request-context.ts` | The app's `requestContext` provider (once per app) | How a request becomes a verified user and organization |
19
+
20
+ - Both Actions are called `bookmarks.add`, in separate maps: `ActionMap` (client) and
21
+ `ServerActionMap` (server). Tools print the operation as `server:bookmarks.add`.
22
+ - The button's `enabled`, `visible` and `confirm` only shape the UI. Who may run the operation
23
+ is decided by its `access`, on the server, for every call.
24
+ - Server Actions are the only thing the browser can call. Server services are never reachable
25
+ over HTTP; operations call them.
26
+ - A plugin with only server work is just a `server/` folder. Every other file under `server/`
27
+ (helpers, a database module) is the plugin's own code and is not discovered.
28
+
29
+ ## Create the files
30
+
31
+ ```sh
32
+ npx bitakit add action bookmarks/add --server
33
+ ```
34
+
35
+ It writes `server/actions/add.ts` (`access: 'organization'`, `expose: true`, zod `input` and
36
+ `output`), `tests/bookmarks.add.server.test.ts`, the button `actions/add.ts` when the plugin has
37
+ none, and the RPC route when no route answers the endpoint yet. It prints what is still missing:
38
+ `npm install zod`, the test setup and, when no service provides `requestContext`, the provider.
39
+ `npx bitakit add service bookmarks/store --server` and `add interceptor bookmarks/audit --server`
40
+ write `server/services/store.ts` and `server/interceptors/audit.ts`. Replace the template bodies.
41
+
42
+ ## The operation
43
+
44
+ ```ts
45
+ // src/plugins/bookmarks/server/actions/add.ts
46
+ import { randomUUID } from 'node:crypto';
47
+ import { defineAction } from '@bitakit/core/server';
48
+ import { z } from 'zod';
49
+
50
+ // The operation behind the Save button (actions/add.ts).
51
+ export default defineAction({
52
+ access: 'user',
53
+ expose: true,
54
+ input: z.object({ url: z.url() }),
55
+ execute: ({ input, ctx, services }) => {
56
+ const address = new URL(input.url);
57
+ const bookmark = { id: randomUUID(), title: address.hostname, url: address.href };
58
+ services.bookmarks.store.add(ctx.user.id, bookmark);
59
+ return bookmark;
60
+ },
61
+ });
62
+ ```
63
+
64
+ - Import `defineAction`, `defineService` and `defineInterceptor` from `@bitakit/core/server` in
65
+ server files: the same functions as `@bitakit/core`, typed with the server fields. Client-only
66
+ fields (`enabled`, `confirm`, `slots`, `success`, ...) are type errors and startup errors there,
67
+ and `access`, `expose` or `output` in a client Action fail with "This file is the button".
68
+ - `execute` receives `{ id, input, ctx, services, config, events, settings, signal }`. `input` is
69
+ validated once; without an `input` schema the operation takes no input and a body is refused.
70
+ - `output` (a schema) checks the result and returns the validator's value: zod and valibot
71
+ objects drop extra keys, which keeps a database row's other columns from leaking. Without it the
72
+ caller receives exactly what `execute` returns, so select fields yourself.
73
+ - `requires: ['billing.invoices']` lists server services of other plugins, as on the client.
74
+
75
+ ## `access` and `expose`
76
+
77
+ | `access` | Who may call it | `ctx` has |
78
+ | --------------------------------------- | ----------------------------------------------------- | ----------------------------------------- |
79
+ | `'public'` | Anyone, also signed out | `requestId`, `signal` |
80
+ | `'user'` | A signed-in user | plus `user` (`id`, `name?`, `email?`) |
81
+ | `'organization'` | A member of the active organization | plus `organization.id`, `member`, `can()` |
82
+ | `{ permission: { todos: ['delete'] } }` | A member whose provider grants every listed operation | as `'organization'` |
83
+
84
+ - `access` is required; there is no default. A typo or an unknown permission is a startup error.
85
+ - `expose: true` publishes the operation over HTTP and in `remote`. Without it the operation is
86
+ private: other server code calls it in-process (`server.as(request)`), the browser cannot.
87
+ - Permissions come from the plugins' `permissions.ts` ([roles-and-permissions.md](roles-and-permissions.md)).
88
+ The provider's `can()` decides; only an answer of exactly `true` grants.
89
+
90
+ ## `ctx` and tenant filters
91
+
92
+ `ctx` is the verified identity of this call, frozen and passed explicitly. BitaKit never filters
93
+ your data for you: every query of user or organization data names its owner.
94
+
95
+ ```ts
96
+ // src/plugins/bookmarks/server/services/store.ts
97
+ import { defineService } from '@bitakit/core/server';
98
+
99
+ export type Bookmark = { id: string; title: string; url: string };
100
+
101
+ // Example storage: each user's bookmarks in server memory, lost when the server restarts.
102
+ // Replace the map with the app's database client; keep every query filtered by the owner.
103
+ export default defineService(() => {
104
+ const byUser = new Map<string, Bookmark[]>();
105
+ return {
106
+ list: (userId: string) => byUser.get(userId) ?? [],
107
+ add(userId: string, bookmark: Bookmark) {
108
+ byUser.set(userId, [...(byUser.get(userId) ?? []), bookmark]);
109
+ },
110
+ remove(userId: string, id: string) {
111
+ const bookmarks = byUser.get(userId) ?? [];
112
+ byUser.set(
113
+ userId,
114
+ bookmarks.filter((bookmark) => bookmark.id !== id),
115
+ );
116
+ return bookmarks.some((bookmark) => bookmark.id === id);
117
+ },
118
+ };
119
+ });
120
+ ```
121
+
122
+ - A server service is one instance for the whole process and every user. Take the owner as a
123
+ method argument (`ctx.user.id`, `ctx.organization.id`); never keep "the current user" in a field.
124
+ - For organization data use `access: 'organization'` and filter by `ctx.organization.id`. An
125
+ organization ID sent by the browser is never proof of membership; only `ctx` is.
126
+ - Never return authentication records (users, sessions, memberships) from your own tables; read
127
+ them through the auth provider.
128
+
129
+ ## The button calls `remote`
130
+
131
+ ```ts
132
+ // src/plugins/bookmarks/actions/add.ts (a button that calls the operation directly)
133
+ import { defineAction } from '@bitakit/core';
134
+
135
+ export default defineAction<string>({
136
+ title: 'Save',
137
+ enabled: ({ input }) => URL.canParse(input?.trim() ?? ''),
138
+ execute: ({ input, remote }) => remote.bookmarks.add({ url: input.trim() }),
139
+ });
140
+ ```
141
+
142
+ - `remote` is in every client Action's and service's context: one typed function per exposed
143
+ operation, `remote.<plugin>.<name>(input, { signal?, organizationId? })`. A private operation
144
+ is a type error there. When a service holds the client's copy of the data, the button calls the
145
+ service and the service calls `remote` ([data-and-api.md](data-and-api.md)).
146
+ - `npx bitakit generate` (the dev server does it on save) adds a new operation to `remote`.
147
+ - Signed in, `remote` sends the organization the page shows (the `auth` snapshot's
148
+ `organizationId`, or the `organizationId` option). When the session has moved to another
149
+ organization meanwhile, the server answers `CONFLICT` instead of writing to the wrong one.
150
+
151
+ ## Errors the UI shows
152
+
153
+ Throw `OperationError` for expected failures; anything else becomes a 500 with a reference, and
154
+ the original stays in the server log.
155
+
156
+ ```ts
157
+ // src/plugins/bookmarks/server/actions/remove.ts
158
+ import { defineAction, OperationError } from '@bitakit/core/server';
159
+ import { z } from 'zod';
160
+
161
+ export default defineAction({
162
+ access: 'user',
163
+ expose: true,
164
+ input: z.string().min(1),
165
+ execute: ({ input, ctx, services }) => {
166
+ if (!services.bookmarks.store.remove(ctx.user.id, input))
167
+ throw new OperationError('NOT_FOUND', 'This bookmark no longer exists.');
168
+ },
169
+ });
170
+ ```
171
+
172
+ | Code | Status | Means |
173
+ | ----------------------- | ------ | ------------------------------------------------------------------------------- |
174
+ | `BAD_REQUEST` | 400 | Invalid input; `issues: [{ path, message }]` name the fields |
175
+ | `UNAUTHORIZED` | 401 | Not signed in |
176
+ | `FORBIDDEN` | 403 | `reason`: `NO_ACTIVE_ORGANIZATION`, `NOT_A_MEMBER`, `PERMISSION`, `INTERCEPTED` |
177
+ | `NOT_FOUND` | 404 | Unknown or private operation, or your own "no such thing" |
178
+ | `CONFLICT` | 409 | `reason: 'ORGANIZATION_CHANGED'`, or your own conflict |
179
+ | `TOO_MANY_REQUESTS` | 429 | Yours to throw (no built-in rate limit) |
180
+ | `INTERNAL_SERVER_ERROR` | 500 | An unexpected error; `requestId` matches the server log |
181
+ | `SERVICE_UNAVAILABLE` | 503 | Server unreachable, failed to start, or no operations configured |
182
+
183
+ `METHOD_NOT_SUPPORTED` (405), `PAYLOAD_TOO_LARGE` (413) and `UNSUPPORTED_MEDIA_TYPE` (415) come
184
+ from the HTTP handler. `remote` rejects with the same `OperationError`, and an Action's default
185
+ failure message shows its `safeMessage`. Word it per code with `failure`:
186
+
187
+ ```ts
188
+ import { isOperationError } from '@bitakit/core';
189
+
190
+ // In a client Action: failure receives the rejected error.
191
+ const failure = ({ error }: { error: unknown }) =>
192
+ isOperationError(error) && error.code === 'UNAUTHORIZED'
193
+ ? 'Sign in to save bookmarks.'
194
+ : isOperationError(error)
195
+ ? error.safeMessage
196
+ : 'Could not save the bookmark.';
197
+ ```
198
+
199
+ Only `code`, `message`, `issues`, `reason` and `requestId` leave the server; never put internal
200
+ details into a `safeMessage`.
201
+
202
+ ## The route
203
+
204
+ One route serves every operation: `POST /api/rpc/<operation id>` with a JSON body.
205
+ `add action … --server` writes it when missing. Next.js, `src/app/api/rpc/[...path]/route.ts`:
206
+
207
+ ```ts
208
+ import { fetchHandler } from '@bitakit/core/server';
209
+ import { server } from '@/bitakit.gen.server';
210
+
211
+ // Every BitaKit server operation the browser calls: POST /api/rpc/<operation id>.
212
+ export const POST = fetchHandler(server);
213
+ ```
214
+
215
+ - TanStack Start: `src/routes/api/rpc.$.ts` with
216
+ `createFileRoute('/api/rpc/$')({ server: { handlers: { POST: ({ request }) => handle(request) } } })`
217
+ and `const handle = fetchHandler(server)`. A plain Vite app has no server to host it.
218
+ - `src/bitakit.gen.server.ts` is generated when a module has server content; never import it from
219
+ browser code. Another path: `server: { endpoint: '/api/bitakit' }` in `bitakit.config.ts`
220
+ (route and `remote` follow it).
221
+ - `fetchHandler(server, { trustedOrigins, origin, maxBodyBytes })`: browser calls must come from
222
+ the app's origin (the browser's same-origin signal, the request URL or the `Host` it sent;
223
+ `origin` names it behind a proxy) or an exact trusted origin; bodies are
224
+ limited to 1 MiB. Cross-origin browser calls are not supported yet (no CORS preflight).
225
+ - Server code reuses an operation in-process with the request's identity:
226
+ `await server.as(request).bookmarks.list()`. It runs the same checks and also reaches private
227
+ operations.
228
+
229
+ ## The `requestContext` provider
230
+
231
+ The app has one server service with `provides: requestContext`. It turns a request into a
232
+ verified identity. While a non-`public` operation exists and no provider does, the server refuses
233
+ to start and names the fix. With Better Auth and its organization plugin:
234
+
235
+ ```ts
236
+ // src/server/services/request-context.ts
237
+ import { defineService, requestContext, type RequestIdentity } from '@bitakit/core/server';
238
+ import { auth } from '@/lib/auth'; // the app's Better Auth server instance
239
+
240
+ export default defineService(
241
+ () => ({
242
+ async resolve(request: Request): Promise<RequestIdentity> {
243
+ const { headers } = request;
244
+ const session = await auth.api.getSession({ headers });
245
+ if (!session) return { user: null };
246
+ const { id, name, email } = session.user;
247
+ const user = { id, name, email };
248
+ const organizationId = session.session.activeOrganizationId;
249
+ if (!organizationId) return { user, organization: null };
250
+ // Only an active, enabled membership of this user in this organization counts.
251
+ const member = await auth.api.getActiveMember({ headers }).catch(() => null);
252
+ if (
253
+ !member ||
254
+ member.organizationId !== organizationId ||
255
+ member.userId !== id ||
256
+ member.disabled === true
257
+ )
258
+ return { user, organization: null, reason: 'NOT_A_MEMBER' };
259
+ return {
260
+ user,
261
+ organization: { id: organizationId },
262
+ member: { id: member.id, role: member.role },
263
+ can: async (permission) => {
264
+ const permissions = Object.fromEntries(
265
+ Object.entries(permission).map(([resource, operations]) => [resource, [...operations]]),
266
+ );
267
+ const result = await auth.api.hasPermission({ headers, body: { permissions } });
268
+ return result.success === true;
269
+ },
270
+ };
271
+ },
272
+ }),
273
+ { provides: requestContext },
274
+ );
275
+ ```
276
+
277
+ - `member.disabled` exists only when the Better Auth member schema declares it
278
+ (`additionalFields: { disabled: { type: 'boolean', required: false, input: false } }`); drop that
279
+ line otherwise.
280
+ - Any other auth works the same way: read the request (a cookie, a bearer token, a gateway
281
+ header), verify it with the library you use and answer `{ user, organization?, member?, can? }`:
282
+
283
+ ```ts
284
+ // src/server/services/request-context.ts (without Better Auth)
285
+ import { defineService, requestContext, type RequestIdentity } from '@bitakit/core/server';
286
+ import { verifySession } from '@/server/session'; // the app's own check of the session cookie
287
+
288
+ export default defineService(
289
+ () => ({
290
+ async resolve(request: Request): Promise<RequestIdentity> {
291
+ const session = await verifySession(request.headers.get('cookie'));
292
+ if (!session) return { user: null };
293
+ return {
294
+ user: { id: session.userId },
295
+ organization: session.organizationId ? { id: session.organizationId } : null,
296
+ };
297
+ },
298
+ }),
299
+ { provides: requestContext },
300
+ );
301
+ ```
302
+
303
+ - Return an `organization` only for a verified, active membership, never for an organization ID
304
+ the client merely sent. Without `can`, permission rules deny.
305
+ - A throwing `resolve` answers 500 and grants nothing. The provider runs only for non-public
306
+ operations, once per call.
307
+
308
+ ## Test it
309
+
310
+ The test `add action … --server` writes calls the operation as three people. The same pattern:
311
+
312
+ ```ts
313
+ // tests/bookmarks.server.test.ts
314
+ import assert from 'node:assert/strict';
315
+ import { after, test } from 'node:test';
316
+ import { identity, mountServer } from '@bitakit/core/testing';
317
+
318
+ // The server half of bookmarks, booted once; as() calls it as different people.
319
+ const server = await mountServer('src/plugins/bookmarks');
320
+ after(() => server.stop());
321
+
322
+ test('each user sees only their own bookmarks', async () => {
323
+ const ada = server.as(identity({ user: 'ada' }));
324
+ const bob = server.as(identity({ user: 'bob' }));
325
+ await ada.bookmarks.add({ url: 'https://example.com/' });
326
+ assert.equal((await ada.bookmarks.list()).length, 1);
327
+ assert.deepEqual(await bob.bookmarks.list(), []);
328
+ });
329
+
330
+ test('a signed-out caller and invalid input are refused', async () => {
331
+ const anonymous = server.as(identity({ user: null }));
332
+ await assert.rejects(anonymous.bookmarks.list(), { code: 'UNAUTHORIZED' });
333
+ const ada = server.as(identity({ user: 'ada' }));
334
+ await assert.rejects(ada.bookmarks.add({ url: 'not a link' }), { code: 'BAD_REQUEST' });
335
+ await assert.rejects(ada.bookmarks.remove('missing'), { code: 'NOT_FOUND' });
336
+ });
337
+ ```
338
+
339
+ - `mountServer(folder)` loads the folder's `events.ts`, `settings.ts`, `permissions.ts`,
340
+ `configs/` and `server/` services, Actions and interceptors (tsconfig `paths` such as `@/` work)
341
+ and boots them. A test provider answers every `as()` caller; it replaces the app's own.
342
+ - `identity({ user, organization, member, permissions, reason })`: `user: null` is signed out;
343
+ `organization: 'org-1'` makes a member; `permissions: { todos: ['delete'] }` (or `'*'`) is
344
+ exactly what `can()` grants.
345
+ - For organization data, test a member, a member of another organization and a signed-out
346
+ caller, and pass `{ organizationId: 'org-1' }` as a stale page to see `CONFLICT`.
347
+ - `mountServer('src')` mounts the app module (unprefixed IDs); `mounted.import('src/server/db.ts')`
348
+ returns the same module instance the operations use, to seed or inspect data.
349
+ - The client half calls its real server half in-process:
350
+ `mountPlugin('src/plugins/bookmarks', { plugins: [shell], remote: server.as(identity()) })`.
351
+
352
+ ## Same names, different rules on the server
353
+
354
+ | On the client | On the server |
355
+ | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
356
+ | `settings.<plugin>.<name>.get()` | `await settings.<plugin>.<name>.load()` in an operation, `load(ctx)` elsewhere; `get()` throws. Needs a `settings.storage` provider; `device` settings stay in the browser |
357
+ | `store()` holds one user's UI state | `store()` is process-wide, shared by every request: a cache, never user data |
358
+ | An interceptor's `before` returning `false` skips | It rejects the call with `FORBIDDEN` (`INTERCEPTED`); `before` sees validated input and `ctx` |
359
+ | Events reach every listener in the browser | Events stay in the server process (listeners get `{ signal, ctx }`); none reaches the browser |
360
+ | Client interceptors match client Actions | Client interceptors never match server Actions; use `server/interceptors/<name>.ts` |
361
+ | `contributions/<dir>/` for a kind's files | Server-only kinds live in `server/contributions/<dir>/`; doctor and generation name a misplaced file |
362
+
363
+ - A server service has no `remote`; it calls other server services directly.
364
+ - Server Action IDs may not use the segments `then`, `catch`, `finally`, `subscribe`, `toJSON`,
365
+ `valueOf`, `toString`, `constructor` or `prototype`.
366
+
367
+ ## Checks
368
+
369
+ - `npm run typecheck` (generates `src/bitakit.gen.server.ts` and types `remote`), then
370
+ `npx bitakit doctor`: it fails when browser code imports a `server/` file,
371
+ `@bitakit/core/server` or `bitakit.gen.server`, or server code imports React or its `ui/`, and
372
+ warns when no route answers the endpoint or no service provides `requestContext`.
373
+ `npx bitakit info` lists operations as `server:<id>`.
374
+ - Run the server tests, then use the feature in the running app signed in, signed out and, for
375
+ organization data, after switching organizations.
376
+
377
+ ## Explain it to the user
378
+
379
+ Name both halves and the rule: "Save is the button `bookmarks.add` in `actions/add.ts`; the
380
+ operation `server:bookmarks.add` in `server/actions/add.ts` stores the link for the signed-in
381
+ user only (`access: 'user'`) and is the only part the browser can call. Signed-out visitors get
382
+ 'Sign in to continue.'" Say what is not done, such as replacing the in-memory map with the
383
+ app's database.
package/src/add.mjs CHANGED
@@ -1,9 +1,16 @@
1
1
  import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import ts from 'typescript';
4
- import { contributionSegments, describeBitaKit, describeModule } from '@bitakit/discovery';
4
+ import {
5
+ contributionSegments,
6
+ describeBitaKit,
7
+ describeDefinitions,
8
+ describeModule,
9
+ } from '@bitakit/discovery';
5
10
  import { exists, findProject } from './project.mjs';
6
11
  import { appPluginAgentRules, claudeFileFor } from './agent-rules.mjs';
12
+ import { providedKeys } from './doctor.mjs';
13
+ import { serverHostNote, serverRoute, serverRouteFor } from './routes.mjs';
7
14
  import {
8
15
  actionFile,
9
16
  configFile,
@@ -18,6 +25,11 @@ import {
18
25
  dialogFile,
19
26
  providerFile,
20
27
  pluginFiles,
28
+ remoteActionFile,
29
+ serverActionFile,
30
+ serverInterceptorFile,
31
+ serverServiceFile,
32
+ serverTestFile,
21
33
  serviceFile,
22
34
  starterFiles,
23
35
  testFile,
@@ -107,16 +119,31 @@ const singleFile = {
107
119
  'settings-page': 'ui/settings/page.tsx',
108
120
  };
109
121
 
122
+ /** The kinds `--server` writes into a plugin's `server/` folder. */
123
+ export const serverKinds = ['action', 'service', 'interceptor'];
124
+
110
125
  /**
111
126
  * `bitakit add <kind> <plugin>/<name>` in an app, or `<name>` in a plugin package. Nested names
112
127
  * such as `notes/team/invite` create `actions/team/invite.ts` with the ID `notes.team.invite`.
113
128
  * `events` takes only the plugin: a plugin declares its events once in `events.ts`. `test` also
114
129
  * takes only an existing plugin of an app and writes `tests/<plugin>.test.ts` at the app root.
130
+ * `server: true` writes an action, service or interceptor into the plugin's `server/` folder
131
+ * instead (see `addServer`).
115
132
  */
116
- export async function addContribution(kind, target, { cwd, plugin: layoutPlugin } = {}) {
133
+ export async function addContribution(
134
+ kind,
135
+ target,
136
+ { cwd, plugin: layoutPlugin, server = false } = {},
137
+ ) {
117
138
  if (!contributionKinds.includes(kind))
118
139
  throw new Error(`Unknown kind "${kind}". Use ${contributionKinds.join(', ')}.`);
140
+ if (server && !serverKinds.includes(kind))
141
+ throw new Error(`--server applies to ${serverKinds.join(', ')}, not to ${kind}.`);
119
142
  const project = await configuredProject(cwd);
143
+ if (server && project.kind !== 'app')
144
+ throw new Error(
145
+ 'Plugin packages have no server half yet. Run "bitakit add <kind> <plugin>/<name> --server" inside an app.',
146
+ );
120
147
  if (kind === 'test') return addTest(project, target);
121
148
  if (kind === 'layout') return addLayout(project, target, layoutPlugin);
122
149
  const single = Object.hasOwn(singleFile, kind);
@@ -159,6 +186,8 @@ export async function addContribution(kind, target, { cwd, plugin: layoutPlugin
159
186
  }
160
187
  const segments = name ? name.split('/') : [];
161
188
  const dotted = segments.join('.');
189
+ if (server)
190
+ return addServer(kind, project, { plugin, name, segments, moduleRoot, createdPlugin });
162
191
  // ui/pages/team/index.tsx serves /<plugin>/team, exactly as discovery derives it.
163
192
  const pageSegments = segments.at(-1) === 'index' ? segments.slice(0, -1) : segments;
164
193
  const pagePath = `/${plugin}${pageSegments.map((segment) => `/${segment}`).join('')}`;
@@ -190,6 +219,163 @@ export async function addContribution(kind, target, { cwd, plugin: layoutPlugin
190
219
  };
191
220
  }
192
221
 
222
+ /**
223
+ * Name segments no server operation may use: as properties of `remote` they would make it
224
+ * thenable, observable or converting. The lowercase ones of Core's list; the others are not
225
+ * valid file names here anyway.
226
+ */
227
+ const reservedSegments = new Set([
228
+ 'then',
229
+ 'catch',
230
+ 'finally',
231
+ 'subscribe',
232
+ 'constructor',
233
+ 'prototype',
234
+ ]);
235
+
236
+ /** The file of the plugin's client Action `id` (its button) in any spelling, if it has one. */
237
+ async function buttonOf(moduleRoot, id, plugin) {
238
+ if (!(await exists(moduleRoot))) return undefined;
239
+ const { directory, actions } = await describeModule(moduleRoot);
240
+ const { definitions, unresolved } = await describeDefinitions(actions, {
241
+ helper: 'defineAction',
242
+ moduleId: plugin,
243
+ });
244
+ // A file that cannot be read statically may declare it; its path decides then.
245
+ const file =
246
+ definitions.find((definition) => definition.id === id)?.file ??
247
+ actions.find((entry) => unresolved.includes(entry.file) && `${plugin}.${entry.path}` === id)
248
+ ?.file;
249
+ // Discovery reports real paths; name the file as the caller knows the folder.
250
+ return file && path.join(moduleRoot, path.relative(directory, file));
251
+ }
252
+
253
+ /** Whether `@bitakit/core` as installed has the `./server` entry server files import. */
254
+ async function coreHasServer(root) {
255
+ for (let folder = root; ; folder = path.dirname(folder)) {
256
+ const manifest = await readFile(
257
+ path.join(folder, 'node_modules/@bitakit/core/package.json'),
258
+ 'utf8',
259
+ )
260
+ .then(JSON.parse)
261
+ .catch(() => undefined);
262
+ if (manifest) return Boolean(manifest.exports?.['./server']);
263
+ if (path.dirname(folder) === folder) return true;
264
+ }
265
+ }
266
+
267
+ /** Whether the CLI's `@bitakit/discovery` reads `server/` folders (0.3.1 and newer). */
268
+ async function discoveryHasServer(project, moduleRoot) {
269
+ for (const directory of [moduleRoot, project.appDirectory])
270
+ if (await exists(directory)) return (await describeModule(directory)).server !== undefined;
271
+ return true;
272
+ }
273
+
274
+ /**
275
+ * Whether no server service of the app or an enabled plugin provides `requestContext`, read
276
+ * statically. Without a provider the server refuses to start once a non-public operation exists;
277
+ * a key whose name cannot be read counts as a provider.
278
+ */
279
+ async function needsRequestContext(project) {
280
+ // Only a hint: a project discovery cannot describe gets none (generate reports the problem).
281
+ const description = await describeBitaKit(project.root).catch(() => undefined);
282
+ if (!description) return false;
283
+ const entries = [description.app, ...description.plugins.filter((item) => item.enabled)].flatMap(
284
+ (module) => module.server?.services ?? [],
285
+ );
286
+ const { names, unresolved } = await providedKeys(description.root, entries);
287
+ return !unresolved && !names.includes('requestContext');
288
+ }
289
+
290
+ /**
291
+ * `bitakit add <action|service|interceptor> <plugin>/<name> --server`: the file in the plugin's
292
+ * `server/` folder. An action also gets its test (`tests/<id>.server.test.ts`, which mounts the
293
+ * server half), the button that calls it through `remote` when the plugin has none with that ID,
294
+ * and the RPC route when no app route hands `<endpoint>/x` to BitaKit yet and the framework has
295
+ * a server host for it (`noHost` otherwise). `needsProvider` tells that no server service
296
+ * provides `requestContext` yet. Nothing is written when any of these files exists; nothing is
297
+ * ever overwritten.
298
+ */
299
+ async function addServer(kind, project, { plugin, name, segments, moduleRoot, createdPlugin }) {
300
+ const id = `${plugin}.${segments.join('.')}`;
301
+ const folder = path.relative(project.root, moduleRoot).split(path.sep).join('/');
302
+ const files = {};
303
+ const kept = [];
304
+ let route;
305
+ let noHost;
306
+ let needsProvider = false;
307
+ let setup = [];
308
+ let run;
309
+ if (kind === 'service')
310
+ files[`${folder}/server/services/${name}.ts`] = serverServiceFile(name, plugin);
311
+ else if (kind === 'interceptor')
312
+ files[`${folder}/server/interceptors/${name}.ts`] = serverInterceptorFile(plugin, name);
313
+ else {
314
+ const reserved = id.split('.').find((segment) => reservedSegments.has(segment));
315
+ if (reserved)
316
+ throw new Error(
317
+ `"${reserved}" cannot name a server operation: remote.${id} would make remote thenable or observable. Choose another name.`,
318
+ );
319
+ const button = await buttonOf(moduleRoot, id, plugin);
320
+ files[`${folder}/server/actions/${name}.ts`] = serverActionFile(name, plugin, {
321
+ button: button && path.relative(moduleRoot, button).split(path.sep).join('/'),
322
+ });
323
+ if (button) kept.push(button);
324
+ else files[`${folder}/actions/${name}.ts`] = remoteActionFile(name, plugin);
325
+ const test = `tests/${id}.server.test.ts`;
326
+ files[test] = serverTestFile(name, plugin, {
327
+ directory: folder,
328
+ // Under plugins/, mountServer reads the same ID from plugin.config.ts or the folder name.
329
+ id: path.basename(project.pluginsDirectory) === 'plugins' ? undefined : plugin,
330
+ });
331
+ const caught = await serverRouteFor(project, project.serverEndpoint);
332
+ const written = caught
333
+ ? undefined
334
+ : await serverRoute(project, { endpoint: project.serverEndpoint });
335
+ if (caught) route = { file: caught.file, created: false };
336
+ else if (written) {
337
+ files[written.file] = written.content;
338
+ route = { file: written.file, created: true };
339
+ } else
340
+ noHost = serverHostNote(
341
+ project.serverEndpoint,
342
+ path
343
+ .relative(project.root, path.join(project.appDirectory, 'bitakit.gen.server.ts'))
344
+ .split(path.sep)
345
+ .join('/'),
346
+ );
347
+ needsProvider = await needsRequestContext(project);
348
+ ({ setup, run } = testSetup(project.manifest, test));
349
+ const installed = { ...project.manifest.dependencies, ...project.manifest.devDependencies };
350
+ // Server files need Core's /server entry, and discovery 0.3.1 to generate and test them.
351
+ const core = await coreHasServer(project.root);
352
+ const discovery = await discoveryHasServer(project, moduleRoot);
353
+ setup = [
354
+ ...(installed.zod ? [] : ['npm install zod']),
355
+ ...(core && discovery
356
+ ? []
357
+ : [`npm install ${core ? '' : '@bitakit/core@latest '}@bitakit/discovery@latest`]),
358
+ ...setup,
359
+ ];
360
+ }
361
+ const created = await writeNewFiles(project.root, files);
362
+ return {
363
+ project,
364
+ created,
365
+ createdPlugin,
366
+ id,
367
+ plugin,
368
+ server: true,
369
+ kept,
370
+ route,
371
+ noHost,
372
+ needsProvider,
373
+ remote: kind === 'action' ? `remote.${id}` : undefined,
374
+ setup,
375
+ run,
376
+ };
377
+ }
378
+
193
379
  /**
194
380
  * `bitakit add layout <family>[/<variant>]`: a candidate for the `layout.<family>` slot, in the
195
381
  * app's `src/layouts`, an app plugin's `ui/layouts` (`--plugin`) or a plugin package's `ui/layouts`.
@@ -115,6 +115,7 @@ the file path is the ID. Discovery generates \`src/bitakit.gen.*\`; there is no
115
115
  | A page | \`ui/pages/<path>.tsx\`, served at \`/<name>/<path>\` |
116
116
  | A button, link or menu entry | \`actions/<file>.ts\`: \`defineAction({ title, execute })\`, ID \`<name>.<file>\` |
117
117
  | Shared state or logic | \`services/<file>.ts\`: \`defineService(({ store }) => ({ ... }))\`, \`services.<name>.<file>\` |
118
+ | Server data or secrets | \`server/actions/<file>.ts\` (\`access\`, \`expose: true\`); buttons call \`remote.<name>.<file>()\` |
118
119
  | A user setting | \`settings.ts\`: \`defineSettings({ size: setting({ default: 20 }) })\`, \`settings.<name>.size\` |
119
120
  | Tell other features something happened | \`events.ts\`: \`defineEvents({ changed: event<T>() })\`, \`<name>.changed\` |
120
121
  | Let other features add UI here | \`slots/<file>.ts\`: \`defineSlot(...)\`; others fill it from \`ui/slots/<slot>.tsx\` |
@@ -128,14 +129,14 @@ the file path is the ID. Discovery generates \`src/bitakit.gen.*\`; there is no
128
129
  - In React: \`useServiceState('<name>.<file>', (state) => ...)\`, \`useSetting('<name>.<key>')\`, \`useEvent('<name>.changed', fn)\`.
129
130
  React only under \`ui/\`. Use \`@bitakit/ui/components\` and the app theme; do not restyle locally or
130
131
  import package CSS from JavaScript (discovery writes \`src/bitakit.gen.css\`).
131
- - Do not rebuild what BitaKit provides: no own registries, event buses, settings stores or button state.
132
- ${shell ? "- Shell: place an Action with `slots: ['shell.navigation']` or `['shell.toolbar']`; header content goes in `ui/slots/shell.header.end.tsx`.\n" : ''}- App-owned routes stay native framework routes in \`${routes}\`; layouts live in \`src/layouts/<family>.tsx\` (pages pick one with \`export const layout\`).
133
- - Each installed \`@bitakit/*\` package explains itself in \`node_modules/@bitakit/<name>/AGENTS.md\`; read it before using the package.
134
- - Create files with \`npx bitakit add plugin <name>\` and \`npx bitakit add <kind> <name>/<file>\` (\`events\` and
135
- \`settings\` take only \`<name>\`); list IDs with \`npx bitakit info --json\` and slots with \`npx bitakit slots\`; check with \`npx bitakit doctor\` and \`npm run typecheck\`.
132
+ - Do not rebuild BitaKit: no own registries, event buses, settings stores or button state.
133
+ ${shell ? "- Shell: place an Action with `slots: ['shell.navigation']` or `['shell.toolbar']`; header content in `ui/slots/shell.header.end.tsx`.\n" : ''}- App-owned routes stay native framework routes in \`${routes}\`; layouts live in \`src/layouts/<family>.tsx\` (pages pick one with \`export const layout\`).
134
+ - Each \`@bitakit/*\` package explains itself in \`node_modules/@bitakit/<name>/AGENTS.md\`; read it first.
135
+ - Create files with \`npx bitakit add plugin <name>\` and \`npx bitakit add <kind> <name>/<file>\` (\`--server\` for
136
+ \`server/\`; \`events\` and \`settings\` take only \`<name>\`); list IDs with \`npx bitakit info --json\` and slots with \`npx bitakit slots\`; check with \`npx bitakit doctor\` and \`npm run typecheck\`.
136
137
  - For feature work, use the project-local \`bitakit-app-development\` skill (\`$bitakit-app-development\` in Codex,
137
138
  \`/bitakit-app-development\` in Claude Code, otherwise read \`.agents/skills/bitakit-app-development/SKILL.md\`):
138
- recipes for each task above, slot and layout choice, and checking the result in the browser.
139
+ recipes for each task above and checks in the browser.
139
140
  - Advanced, only when needed: interceptors, configs, providers, dialogs, \`setup.ts\`, \`plugin.config.ts\`.
140
141
  - Never edit generated files: \`src/bitakit.gen.*\`.
141
142