@dokebi/module 0.4.0 → 0.4.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/AI.md CHANGED
@@ -1,6 +1,6 @@
1
- # AI guide — @dokebi/module 0.4.0
1
+ # AI guide — @dokebi/module
2
2
 
3
- A module is **one feature as a unit of business code** (D-0032). It keeps controllers, models, views, routes and sockets in one folder, and apps mount it under a prefix. Business code without a web side (job handlers, event subscriptions, shared APIs) is a module too. Node >=24.0.0, core ^0.4.0. Details are in the [README](README.md).
3
+ A module is **one feature as a unit of business code** (D-0032). It keeps controllers, services, models, views, routes and sockets in one folder, and apps mount it under a prefix. It also declares what it is made of — the modules it needs, tables and migrations, permissions, data sources, widgets, menu items, settings and translations — and `dokebi describe` lists that contract (§2a, D-0197). Business code without a web side (job handlers, event subscriptions, shared APIs) is a module too. Node >=24.0.0, core ^0.4.0. Details are in the [README](README.md).
4
4
 
5
5
  ## 1. Creating modules
6
6
 
@@ -20,7 +20,7 @@ A hand-made module folder is not registered. The generated registration code pas
20
20
  src/shared/modules/<module>/
21
21
  module.ts export default defineModule({ ... })
22
22
  routes.ts routes registered when an app mounts the module
23
- controllers/ models/ views/default/ (modules with pages) sockets/ (when needed)
23
+ controllers/ services/ models/ views/default/ (modules with pages) sockets/ (when needed)
24
24
  ```
25
25
 
26
26
  Do not scatter controllers, models and views into layer folders (`src/shared/controllers` and so on).
@@ -30,12 +30,14 @@ Do not scatter controllers, models and views into layer folders (`src/shared/con
30
30
  ```ts snippet
31
31
  import { defineModule } from '@dokebi/module';
32
32
  import { dependency as db } from '@dokebi/db';
33
+ import { mcpTools } from '@dokebi/mcp';
33
34
  import { postsController } from './controllers/posts.ts';
34
35
 
35
36
  export default defineModule({
36
37
  name: 'board', // the folder name; the plugin id is dokebi-module.board
37
38
  requires: [db], // instances, descriptors, other modules
38
39
  controllers: [postsController],
40
+ contributes: [mcpTools], // points of plugins this module contributes to (§3a)
39
41
  views: new URL('./views/', import.meta.url), // default/ is required (adds a template-ejs dependency)
40
42
  routes(route, module) { // registered for every app that mounts it, on that app's domains and prefix
41
43
  route.get('/', async (request, reply, page) =>
@@ -57,6 +59,227 @@ export default defineModule({
57
59
  - `controllers`: uses @dokebi/controller (optional peer). Calling `module.controller()` without controllers is `NO_CONTROLLERS` (`declares no controllers`).
58
60
  - `module.runtime` is core's runtime role (`solo`, `primary`, `worker`; D-0063 §4). Do not read `node:cluster` yourself.
59
61
  - Route options are `WebRoute` options without `handler` and `constraints` (`ModuleRouteOptions`, so `seal` works).
62
+ - `contributes`: the points of other plugins this module contributes to (§3a). Without it `module.contribute` is `UNDECLARED_POINT`.
63
+
64
+ ## 2a. The module contract (0.4.2)
65
+
66
+ A module also declares **what it is made of**, in the same `defineModule` call, so the framework, an editor and an AI read it without running it ([D-0197](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0197-module-contract.md)). Every field is optional; `examples/81-module-contract` uses them all.
67
+
68
+ ```ts snippet
69
+ import { defineOptions, option as o } from '@dokebi/core';
70
+ import { defineModule } from '@dokebi/module';
71
+ import memberSettings from '../../settings/members.ts'; // defineSettings({ section: 'members', options })
72
+
73
+ const here = (path: string) => new URL(path, import.meta.url);
74
+
75
+ export default defineModule({
76
+ name: 'members',
77
+ version: '0.1.0',
78
+ title: { en: 'Members', ko: '...' }, // a text, or a text per locale
79
+ description: 'Member accounts and their lists',
80
+ modules: { auth: '^0.1.0' }, // other modules by name and version range
81
+ db: here('./db/'), // db/migrations/<connection>/, db/seeds/<connection>/
82
+ tables: ['members'],
83
+ permissions: { 'members.read': { title: 'Read members' }, 'members.write': { title: 'Change members' } },
84
+ dataSources: { list: { title: 'Member list' } }, // id members.list
85
+ widgets: {
86
+ detail: {
87
+ title: 'Member detail',
88
+ settings: defineOptions({ showJoined: o.boolean({ default: true }) }), // the editor's fields
89
+ template: here('./widgets/detail.html'), // the first HTML, at most 64 KB of UTF-8
90
+ },
91
+ },
92
+ menu: [
93
+ { id: 'members', title: 'Members', path: '', icon: 'users', permission: 'members.read' },
94
+ { id: 'new', title: 'New member', path: '/new', parent: 'members', permission: 'members.write' },
95
+ ],
96
+ settings: memberSettings, // options.members of dokebi.yaml, checked at start
97
+ locales: here('./locales/'), // locales/<language>/<namespace>.json
98
+ });
99
+ ```
100
+
101
+ | Field | Rule |
102
+ |---|---|
103
+ | `title`, `description` | 1–200 characters, or `{ <locale>: text }` (at most 32 locales such as `en`, `ko`, `pt-BR`) |
104
+ | `modules` | `{ <module name>: <version range> }`, at most 64, never the module itself. Each becomes the plugin dependency `dokebi-module.<name>` with that range: core orders the modules and refuses the start without it (`MISSING_DEPENDENCY`) or with another version (`INCOMPATIBLE_VERSION`). The group plugin refuses earlier, naming both modules: `MODULE_MISSING` (the cause of `INVALID_PLUGIN_INPUT` at registration). The group looks only in its own entry, so a module named in `modules` must be in the same group; a module registered alone with `app.register` is not seen there (name it with `requires`, importing it, or put both in the group). Use `requires` for plugins and module instances you import; `modules` names a module without importing it |
105
+ | `db`, `tables` | `db` is the folder URL (ending in `/`) with `migrations/<connection>/` and `seeds/<connection>/`, named as `dokebi-migrate make` names them. **dokebi-migrate runs them**: its option `directories` (default `src/shared/modules/*/db`) adds every module's `db/` to the project's folder, in one name order ([@dokebi/migrate AI.md](https://git.nyx-zone.com/dokebi/framework/-/blob/main/plugins/dokebi-migrate/AI.md)). Create one with `npx dokebi-migrate make <name> --connection main --directory src/shared/modules/<module>/db`. `tables`: the tables or collections the module owns, at most 64 |
106
+ | `permissions` | `{ '<module>.<action>': { title, description? } }`, at most 256; keys start with the module name (`members.read`) |
107
+ | `dataSources` | `{ <name>: { title, description?, fields, sorts, search?, filters?, actions?, permission \| public, scopes?, scope?, limit?, read } }`, at most 64, lower-case names; the id is `<module>.<name>`. §2b. A data source with only `title` and `description` is named but not readable yet (`readable: false` in describe) |
108
+ | `actions` | `{ <name>: { title, description?, input?, key?, version?, permission, scopes?, scope?, danger?, preview?, run } }`, at most 64, lower-case names; the id is `<module>.<name>`. The writes of the module, §2c ([D-0202](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0202-actions.md)). A data source row action that names one of this module's actions (`update` or `<module>.update`) must name a declared one (`INVALID_CONTRACT` at definition); another module's action is checked when the group sets up |
109
+ | `widgets` | `{ <name>: { title, description?, settings?, template, load?, island? } }`, at most 64. `settings` is a `defineOptions` declaration: the editor draws a widget's fields from its schema and checks entered values with `contract.widgets.<name>.settings.check(values)`. `template` is the file URL of a `.html` file: the start fails (`INVALID_CONTRACT`, the file error as cause) when it is missing, larger than 64 KB or not UTF-8. `load({ settings, request, module, modules, app, form? })` (D-0198; `app`: the title and the visitor's menu of the app that draws it, `ModuleMenuEntry[]`; `form`: only for the widget an app names to draw `<x-form>` — the x-form's class and its `<x-field>` children and the HTML between them, @dokebi/pages D-0204) gives the data the template draws next to its settings, on the server for every placed widget (@dokebi/pages `<x-widget module name>`); `modules` is the module group (D-0200: `data.read` of a data source with the visitor's request); describe never shows it. `island` (D-0200) is the file URL of `islands/<Name>.vue` of the module (PascalCase): the page runs that Vue component in the browser in place of the drawn template, with `{ settings, data }` as props (`{ settings, data, form }` for a form widget); describe gives it as `<module>/<Name>` |
110
+ | `menu` | At most 64 items `{ id, title, path, icon?, permission?, parent?, order? }`: `id` unique in the module; `path` is `''` or `/a/path` below the prefix the app mounts the module at; `permission` a key (one of this module's own keys must be declared in `permissions`); `parent` another item's id (no cycle); `order` −1000 to 1000 (default 0). The app decides where the items go |
111
+ | `settings` | A `defineSettings` result of @dokebi/core. The module checks `options.<section>` at start (`INVALID_PLUGIN_OPTIONS`, paths only); read it with `memberSettings.read(module.app.config)`. Keep the file in `src/shared/settings/` so `npx dokebi settings add`, `config set` and doctor know the section |
112
+ | `locales` | The folder URL of `locales/<language>/<namespace>.json`; @dokebi/i18n reads a module's `locales/` itself (its layers) |
113
+ | `presets` | `{ <name>: { title, kind, folder } }`, at most 16, lower-case names; the id is `<module>.<name>` (dokebi-platform DEC-12, DEC-16). A preset is what an editor copies into a new app: `kind` is `admin` or `front` (the app kinds it is for), `folder` the folder URL (ending in `/`) of a folder shaped like an app's definition folder — `app.yaml`, `theme.css`, `layouts/<name>.html`, `components/<name>.html`, `pages/<path>.html` (D-0198, D-0205); hidden files such as `.DS_Store` are left out. Its `app.yaml` holds only what the preset fills: `layout`, `modules` and `menu` (`{ title, path, icon?, permission?, children? }`); the new-app window gives the rest. **The start refuses** a folder that is missing, holds another file, a file larger than 200 KB, more than 200 files, or an `app.yaml` that is not YAML, has another key or an alias, or breaks @dokebi/pages' app.yaml rules (a layout name of 40 characters at most, menu paths of `[A-Za-z0-9/_.-]`, permissions of 128 characters at most) (`INVALID_CONTRACT`, the file named; [D-0206](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0206-module-presets.md)). What the files hold is @dokebi/pages' check (`checkSiteFiles` of `@dokebi/pages/html`); `isSiteFile` and `checkPresetApp` are exported |
114
+
115
+ - A field that breaks a rule throws `INVALID_CONTRACT` from `defineModule`, naming the field, never a value.
116
+ - The module context (`ModuleContext`) has `contract`: the checked contract of the module (what `@dokebi/mcp/actions` reads its actions from).
117
+ - The group API (`ModuleGroupApi`) has `module(name)`: the mount of a module of the group by its name, or undefined (D-0198; what @dokebi/pages reads to draw widgets).
118
+ - `moduleMount(plugin).contract` is the checked contract (frozen; widget `settings` keep their declaration); `moduleMount(plugin).describe()` returns the JSON `dokebi describe` shows (`DescribedModule`).
119
+ - **`npx dokebi describe --json` lists the modules as `app.modules`**: per module `name`, `version`, `title`, `description`, `requires` (plugins), `modules`, `tables`, `db` (`folder`, `migrations` and `seeds` file names per connection), `permissions[{ key, title, description? }]`, `dataSources[{ id, name, title, description?, readable, fields, sorts, search, filters, actions, permission, scopes, limit }]` (no functions, no hidden fields), `actions[{ id, name, title, description?, input, schema, key?, version?, permission, scopes?, danger }]` (`input` the fields with their rules, `schema` the same as a JSON Schema; no functions), `widgets[{ id, name, title, description?, settings (JSON Schema or null), template (the HTML) }]`, `menu`, `settings` (`{ section, schema }` or null, never a value), `locales` (`folder`, `languages: { <language>: [namespaces] }`), `presets[{ id, name, title, kind, folder, files }]` (`folder` relative to the project, `files` the sorted paths inside it), `contributes`, `views`, `routes`, `sockets`, `events`. The group plugin `dokebi-module` contributes this section only in describe mode; a module registered alone with `app.register` is not listed.
120
+
121
+ ## 2b. Data sources and the general read (0.4.2)
122
+
123
+ A data source is a window on the module's data that every caller pages through one general read: a data grid, a screen, another program, an AI ([D-0199](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0199-data-sources.md)). Callers only pick from what the module declared; the module's reader turns a checked request into one SQL page. `examples/83-data-sources` measures every declared combination on PostgreSQL.
124
+
125
+ ```ts snippet
126
+ import { type DataSourceRead, defineModule, readSql } from '@dokebi/module';
127
+
128
+ export default defineModule({
129
+ name: 'members',
130
+ permissions: { 'members.read': { title: 'Read members' } },
131
+ dataSources: {
132
+ list: {
133
+ title: { en: 'Member list' },
134
+ fields: {
135
+ id: { type: 'id', label: 'No.' }, // an id is unique
136
+ username: { type: 'text', label: 'Username', unique: true },
137
+ status: { type: 'status', label: 'Status', display: 'badge',
138
+ choices: { active: { label: 'Active' }, blocked: { label: 'Blocked' } } },
139
+ joined: { type: 'datetime', label: 'Joined' },
140
+ path: { type: 'text', label: 'Place', hidden: true, unique: true }, // pages, never returned
141
+ },
142
+ sorts: { // each one index's order
143
+ newest: { label: 'Newest', by: [['joined', 'desc'], ['id', 'desc']], scopes: ['all', 'direct', 'own'] },
144
+ tree: { label: 'Tree', by: [['path', 'asc']] },
145
+ },
146
+ search: { label: 'Username starts with', fields: ['username'], sorts: ['username'], scopes: ['all'] },
147
+ filters: { status: { label: 'Status', field: 'status', kind: 'choice', sorts: ['newest'], scopes: ['all'] } },
148
+ actions: { open: { label: 'Open', href: '/members/{id}' } },
149
+ permission: 'members.read',
150
+ scopes: ['all', 'subtree', 'direct', 'own'],
151
+ scope: ({ request }) => scopeOfCaller(request), // one of scopes, or null (403)
152
+ limit: { default: 20, max: 100 },
153
+ read: (read: DataSourceRead) => members.page(read), // at most read.limit rows
154
+ },
155
+ },
156
+ });
157
+ declare function scopeOfCaller(request: unknown): string | null;
158
+ declare const members: { page(read: DataSourceRead): Promise<object[]> };
159
+ ```
160
+
161
+ | Field | Rule |
162
+ |---|---|
163
+ | `fields` | 1–64 `{ type, label, display?, choices?, hidden?, unique? }`. `type`: `id` (unique), `text`, `number`, `money` (a decimal text), `date` (`YYYY-MM-DD`), `datetime`, `status`, `boolean`, `person`, `image`, `file`, `richtext` (a list returns text, an excerpt), `category`, `choice`: one list for data sources, data grids, forms and MCP tools. `boolean`, `image`, `file` and `richtext` cannot be sorted by; `image`, `file` and `richtext` cannot be filtered. `choices` `{ <value>: { label, tone? } }` (at most 64) is what a choice filter offers; `tone` (one of `CHOICE_TONES`: `primary`, `secondary`, `success`, `warning`, `info`, `destructive`) is the colour a grid's dot or badge draws the value in, another word is `INVALID_CONTRACT`; a `status`, `choice` or `category` field with choices takes only those values. `hidden` fields page or filter but are never chosen nor returned |
164
+ | `sorts` | 1–16 `{ label, by, scopes? }`. `by` is 1–4 `[field, 'asc' \| 'desc']` pairs: **the columns of one index, in its order, ending with a unique field** (the cursor's tiebreaker). The first sort a scope may use is its default |
165
+ | `search` | `{ label, fields, minLength? (1), maxLength? (100), sorts?, scopes? }`: what the reader searches; `sorts` are the sorts a search may use (the order its index gives) |
166
+ | `filters` | 0–32 `{ label, field, kind, multiple?, sorts?, scopes? }`. `kind`: `choice` (values among the field's choices; one value unless `multiple: true`, because several values' rows must all be read and sorted), `equal` (one value of the field's kind), `range` (`from` and/or `to` of a number, money, date or datetime field). `sorts`: the sorts it goes with (the index that starts with its field) |
167
+ | `actions` | 0–16 `{ label, href \| action, permission? }`: a link with `{field}` places (declared, not hidden), or a module action by name — `update` or `<module>.<name>` (`members.update`); only the name is checked here, the action contract checks the rest. The caller shows it |
168
+ | `permission` | A key `request.auth.can` must grant (a key of this module must be in `permissions`). A data source with a reader declares `permission` or `public: true`, one of them (`INVALID_CONTRACT` otherwise): none is open by a forgotten line |
169
+ | `public` | `true`: anyone may read, signed in or not (instead of `permission`) |
170
+ | `scopes`, `scope` | Together: the scope names the reader knows, and `scope({ request, module })` giving the caller's (`@dokebi/permissions` `scopeOf` in an app with member types), or null for 403. `sorts`, `search` and `filters` name the scopes they are offered to (default every scope): **offer a scope only what its index pages** — a subtree is one range of an ordered path, so it pages by that path; a parent's members page by `(parent_id, created_at, id)` |
171
+ | `limit` | `{ default?, max? }`: page size, 1 ≤ default ≤ max ≤ 500 (default 20 and 100) |
172
+ | `read` | `read(read: DataSourceRead)` → the rows of one page: at most `read.limit` (page size + 1), in `read.sort` order, after `read.after`, inside `read.scope`, each with every field of `read.select` (the chosen fields and the sort fields). Values are text, number, boolean or null: **dates as text with full precision** (`to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`), never a `Date` |
173
+
174
+ **The general read.** The group API (`ModuleGroupApi.data`) reads any data source of its modules; an app mounts the route in its `routes`:
175
+
176
+ ```ts snippet
177
+ import { dependency as modules } from '@dokebi/module/dependency';
178
+ import type { AppContext, AppRouter } from '@dokebi/app';
179
+
180
+ export async function routes(route: AppRouter, app: AppContext): Promise<void> {
181
+ app.getDependency(modules).data.routes(route); // GET /data/:module/:source (route id module.data)
182
+ }
183
+ ```
184
+
185
+ `GET /data/members/list?fields=id,username&sort=newest&filter.status=blocked&q=m0&limit=20&cursor=…` answers `{ source, sort, rows, next }`: only the chosen fields, the next page's cursor or null, never a total count. In code: `data.read(request, 'members.list', query)`; `data.ids` lists the readable ones. Parameters: `fields` (required, comma-separated), `sort`, `limit`, `cursor`, `q`, `filter.<name>` (a choice: comma-separated when `multiple`), `filter.<name>.from` and `.to`. In the browser call it with `sealedFetch` (POL-02 of a project: data inside a page by REST, only the fields it shows).
186
+
187
+ - **Refusals**, never ignored: anything not declared, hidden, not offered to the caller's scope or not combinable with the sort is `INVALID_QUERY` (400, `data.reason`: `fields`, `field`, `sort`, `limit`, `parameter`, `search`, `filter`, `value`, `combination`; `data.name` names it). A parameter given twice is `parameter`. A cursor of another sort, filter, search or scope, or one nobody gave, is `INVALID_CURSOR` (400: start again). No permission, no auth or a null scope is `FORBIDDEN` (403). An unknown or name-only data source is `DATA_SOURCE_NOT_FOUND` (404).
188
+ - **The cursor** is base64url JSON of the sort name, a fingerprint of the sort, filters, search and scope, and the sort fields' values of the page's last row; it is checked against the field kinds (`2026-02-30` is no date). It is opaque to callers but not secret: the scope still bounds every page.
189
+ - **A reader that breaks the rules** — more rows than `read.limit`, a missing or mistyped sort field, a `Date` — is `DATA_SOURCE_FAILED` (500, logged at error with the whole error). A reader's own errors (a database down: `DB_UNAVAILABLE` 503) pass through unchanged.
190
+ - **`readSql(read, { columns, dialect, start? })`** builds the filter, cursor and order parts for a SQL table (`columns`: field → column): `{ conditions, params, orderBy, limit, next }`. The cursor is a row comparison on PostgreSQL when every sort column goes one way, and the expanded `a < ? OR (a = ? AND b < ?)` otherwise and always on MySQL and MariaDB (@dokebi/db AI.md §7.4). Add the scope and search conditions yourself (parameters from `next`), then `SELECT <read.select> … WHERE … ORDER BY <orderBy> LIMIT <limit>`. Name the columns with their table (`{ id: 'members.id' }`) when the SELECT gives a field a computed value under the field's name (`id::text AS "id"`): PostgreSQL reads a bare `ORDER BY id` as that output column, so the index order is lost and every page is sorted. A filter `parent = $1` on a parent that holds a large share of the rows can make the planner walk a newest-first index from the cursor and discard the other parents' rows: write that equality as `parent_id = ANY($1::uuid[])` and keep `parent_id` first in the ORDER BY (against the sort's way), so only the `(parent_id, sort…)` index gives the order, and measure the deep page of that parent.
191
+ - **Measure every declared combination** (@dokebi/db AI.md §6.1, §7): each sort, each filter at its rarest, each scope for its busiest owner, the first and a deep page. `assertRowBudget(measure, { maxExamined: 2 * (page + 1), noFullScan: true, noSortOfAll: true })` must hold; when it fails, change the index or stop offering that combination to that scope.
192
+ - Debug logs: `Data sources registered` (ids), `Data source page read` (source, sort, scope, filter names, search, cursor, rows, more, ms).
193
+
194
+ ## 2c. Actions and the general write (0.4.2)
195
+
196
+ An action is the write side of a data source ([D-0202](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0202-actions.md)): the module declares what it takes and who may run it, and one general write runs it for every caller — a form, a data grid row button, another program, an AI through MCP. Keep the input rules in the module's `validation/` and the work in its services; `run` only calls the service.
197
+
198
+ ```ts snippet
199
+ import { defineModule } from '@dokebi/module';
200
+ import { MemberActions } from './services/member-actions.ts';
201
+ import { memberScope } from './services/member-scope.ts';
202
+
203
+ // validation/update.ts — the input rules, in one place.
204
+ export const updateInput = {
205
+ id: { type: 'id', label: 'No.', required: true },
206
+ version: { type: 'number', label: 'Version', required: true, integer: true, min: 1 },
207
+ name: { type: 'text', label: 'Name', minLength: 1, maxLength: 60, nullable: false },
208
+ status: {
209
+ type: 'status',
210
+ label: 'Status',
211
+ nullable: false,
212
+ choices: { active: { label: 'Active' }, blocked: { label: 'Blocked' } },
213
+ },
214
+ } as const;
215
+
216
+ const service = new MemberActions();
217
+ export default defineModule({
218
+ name: 'members',
219
+ permissions: {
220
+ 'members.write': { title: 'Change members' },
221
+ 'members.leave': { title: 'Mark members as left' },
222
+ },
223
+ actions: {
224
+ update: {
225
+ title: 'Change a member',
226
+ input: updateInput,
227
+ key: 'id', // the row it changes: a form reads the row by it
228
+ version: 'version', // the version the caller read; the service compares it
229
+ permission: 'members.write', // every action has one (writes are never public)
230
+ scopes: ['all', 'subtree', 'direct', 'own'],
231
+ scope: ({ request }) => memberScope(request),
232
+ run: (run) => service.update(run), // one transaction: lock in reach, compare, change, audit row
233
+ },
234
+ leave: {
235
+ title: 'Mark a member as left',
236
+ input: { id: { type: 'id', label: 'No.', required: true } },
237
+ key: 'id',
238
+ permission: 'members.leave',
239
+ danger: true, // two steps: the preview first, then the same input with confirm
240
+ preview: (run) => service.leavePreview(run), // JSON of what would change (16 KB at most)
241
+ run: (run) => service.leave(run),
242
+ },
243
+ },
244
+ });
245
+ ```
246
+
247
+ | Field | Rule |
248
+ |---|---|
249
+ | `input` | 0–64 fields `{ type, label, required?, nullable?, … }` of the shared kinds (`FIELD_TYPES`, §2b; DEC-06: data sources, grids, forms and MCP tools use one list), names `a-z0-9_` (`confirm` is kept by the general write). Per kind: `text` `minLength`, `maxLength` (default 1000, at most 100,000, code points), `format: 'email'`; `number` `min`, `max`, `integer`; `money` a decimal text (`'12.50'`) with `scale` (0–4, default 2), `min`, `max`; `date` `YYYY-MM-DD` (a real date); `datetime` ISO 8601 with `Z` or an offset; `boolean`; `status` and `choice` with `choices` (required; `choice` may be `multiple`: a list of distinct values); `category` (`choices` optional); `id`, `person`, `image`, `file` an id (text up to 128 characters without spaces at the ends or control characters, or a positive whole number); `richtext` a JSON object of at most `maxBytes` (default 64 KB; check its nodes in the service with @dokebi/rich-text). Another rule of another kind is `INVALID_CONTRACT` |
250
+ | `required`, `nullable` | `required`: must be given and not empty (null, `''`, `[]`). Otherwise a field may be left out (**not changed**: the run's `input` has only the given fields) or null (**cleared**); `nullable: false` refuses the clearing (a name that must stay) |
251
+ | `key` | An input field of type `id`: the row the action changes |
252
+ | `version` | A required `number` or `text` input field: the version of the row the caller read. The run compares it with the stored one and throws `actionConflict(message?, { version })` (409 `ACTION_CONFLICT`) when they differ |
253
+ | `permission` | Required: a key `request.auth.can` must grant (a key of this module must be in `permissions`) |
254
+ | `scopes`, `scope` | As for data sources: the caller's scope (`run.scope`), null for 403. **The run checks the reach** (the row is in the scope: lock it with the scope's condition) |
255
+ | `danger`, `preview` | Together. The first call answers 428 `CONFIRM_REQUIRED` with `data: { preview, confirm }` and changes nothing; the same input with `confirm` runs it. The confirm call runs `preview` again: a different preview (the row changed) answers 409 `CONFIRM_STALE` with the new preview and token. The token is a hash of the action, the actor, the input and the preview (no secret, works across workers): it proves the caller was shown this preview, not who the caller is — the permission does that |
256
+ | `run` | `run({ action, input, scope, actor, request, module })` → its result, JSON of at most 64 KB (ids, counts; null when it returns nothing). `actor` is `{ type: 'user' \| 'ai', id?, client? }`: the AI client of an @dokebi/oauth grant (`request.oauth.grant`, its name), else the signed-in user — write it to the audit row (@dokebi/audit `record` in the run's transaction; its `actor(request, name)` gives the same) |
257
+
258
+ **The general write.** The group API (`ModuleGroupApi.actions`) runs any action of its modules; an app mounts the route next to the general read:
259
+
260
+ ```ts snippet
261
+ app.getDependency(modules).actions.routes(route); // POST /actions/:module/:action (route id module.action)
262
+ ```
263
+
264
+ `POST /actions/members/update` with `{ "input": { "id": "…", "version": 3, "name": "Kim" } }` answers `{ action, result }`. In code: `actions.run(request, 'members.update', { input, confirm? })`; `actions.ids` lists them. A browser page sends it with `sealedFetch` (CSRF and seal included).
265
+
266
+ - **Refusals**: no permission, no auth or a null scope 403 `FORBIDDEN`; an unknown action 404 `ACTION_NOT_FOUND`; a body other than `{ input, confirm? }`, an input field the action does not declare (also `constructor`), or `confirm` on an action that is not dangerous 400 `INVALID_INPUT` (`data.reason`: `body`, `field`, `confirm`; `data.name`). Wrong values are **422 `VALIDATION_FAILED` with `fields` and `errors`** (the shape @dokebi/web answers and template-inertia turns into form errors; one fixed English message per field, `data.rules` names the broken rule: `required`, `type`, `minLength`, `maxLength`, `format`, `min`, `max`, `integer`, `choice`, `size`). Nothing runs before every check passed.
267
+ - **What the service refuses later** (a username taken, a row out of reach): `throw actionInvalid({ field: 'message' }, run.action)`, the same 422. A changed row: `throw actionConflict(undefined, { version })`. Other errors of the run pass through unchanged (`DB_UNAVAILABLE` 503).
268
+ - **`ACTION_FAILED`** (500, logged at error with the whole error): a scope function that answers a name it did not declare, a preview or result that is not JSON or too large.
269
+ - **MCP**: `actionTools(module, { scope?, only? })` of `@dokebi/mcp/actions` makes one tool per action (`members.update`) that runs this same runner; §3a.
270
+ - Debug logs: `Actions registered` (ids), `Action answered` (action, outcome, code, actor type, user, client, ms; never input values).
271
+
272
+ ## 2d. UI parts (0.4.2, D-0203)
273
+
274
+ A module that offers UI parts — Vue components, directives, CSS classes for page HTML, and its widgets — lists them in one JSON file the contract points at, so an editor and an AI connected over MCP can find them, their props and their live samples:
275
+
276
+ ```ts snippet
277
+ defineModule({ name: 'ui', parts: new URL('./parts.json', import.meta.url), widgets: { 'admin-header': { /* … */ } } });
278
+ ```
279
+
280
+ - The file is `{ parts: [...] }`. A part: `name` (`UiButton`, `v-truncate-tooltip`, `.btn`, or a widget name), `kind` (`component` · `directive` · `class` · `widget`), `title` (one line), `description?`, `use?` (when to use it) — each a text or `{ <locale>: text }` — `file?` (inside the module folder), `props?` (`{ name, type, required, default?, description? }`), `slots?` (`{ name, props? }`), `events?` (`{ name, payload? }`), `variants?` (`{ name, description? }`, classes or prop values), `examples?` (markup to start from), `sample?` (an address of the app, `/ui#buttons`). A `widget` part names a widget of the same module (`widget: 'admin-header'`).
281
+ - Generate it from the `.vue` files (props from `defineProps`, slots from the template) rather than writing props by hand, and keep a test that fails when the file is stale or a component is missing. `readParts(url, widgets)` / `checkParts(value, widgets)` check a file with the same rules.
282
+ - `dokebi describe --json` reads and checks it (2 MB at most) and gives `app.modules[].parts` = `{ file, parts }` (null without one). A file that breaks a rule makes the module's description `INVALID_CONTRACT` naming the field (listed under `unavailable`); a running app never reads it. Limits: `PARTS_LIMITS` (512 parts, 128 props/slots/events/variants each, 16 examples).
60
283
 
61
284
  ## 3. Mounting on apps and shared APIs
62
285
 
@@ -65,6 +288,57 @@ export default defineModule({
65
288
  - APIs that must answer on every domain (such as `/api/*`) are not `routes`; register them in `setup` directly with `@dokebi/router` (`mount`) or web.
66
289
  - For another module or plugin to use this module's API, put this module into its `requires` and `get(module)`; it receives what `setup` returned.
67
290
 
291
+ ## 3a. Contributing to plugin points (MCP tools and others)
292
+
293
+ A module offers values to a plugin that collects a point ([D-0130](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0130-module-contributions.md); the points are core's, D-0063): MCP tools, prompts and resources of @dokebi/mcp (`mcpTools`, `mcpPrompts`, `mcpResources`), mail template folders, error translators. It is the same mechanism for every point; nothing is special to MCP.
294
+
295
+ ```ts snippet
296
+ import { dependency as db } from '@dokebi/db';
297
+ import { mcpTools } from '@dokebi/mcp';
298
+ import { defineModule } from '@dokebi/module';
299
+ import { DocumentService } from './services/documents.ts';
300
+ import { ListDocuments } from './tools/list-documents.ts';
301
+
302
+ export default defineModule({
303
+ name: 'workspace',
304
+ requires: [db],
305
+ contributes: [mcpTools], // declared when the module is defined
306
+ setup(module) {
307
+ const documents = new DocumentService(module.getDependency(db));
308
+ module.contribute(mcpTools, new ListDocuments(documents)); // the module's own service
309
+ return { documents }; // the module API: the same object
310
+ },
311
+ });
312
+ ```
313
+
314
+ - **Declared, not dynamic**: `contributes` becomes the module plugin's `metadata.contributes` when `defineModule` runs, before the app registers anything, so core checks every `module.contribute` against it and `npx dokebi describe` lists it (each plugin's `contributes` and `collects`, and a summary line per module point with its collector). Points made by `definePoint`, each once, at most 64 (`INVALID_CONTRIBUTION`).
315
+ - **Order**: core's rule for every contributor: the module sets up (and builds its services) before every plugin that collects the point, and drains after it; registration order does not matter. Contribute in `setup` only (in `start`, `drain` or a route it is core's `CONTRIBUTIONS_CLOSED`).
316
+ - **The module boundary holds**: the contributed objects get the services the module built; nothing builds them again. Another module that contributes tools for this one lists it in `requires` and reads `module.get(workspace).documents`. Never write a separate `definePlugin` that builds the services a second time, and never register an app plugin by hand in `src/main.ts` or `src/infra/runtime/application.ts` for this: `npx dokebi describe` and the tests build the app from the generated registration and do not see it, and doctor and check do not read it.
317
+ - **A module never collects**: `module.collect` is `UNDECLARED_POINT` (collecting is a plugin's role).
318
+ - **No collector**: when no registered plugin collects a point (its plugin is not installed, or a test app leaves it out), the start goes on, the values are dropped and the module hears warn `POINT_NOT_COLLECTED` once per point (`point`, `count`, `fix`). Module tests without the MCP stack keep working; `npx dokebi check` makes the missing plugin an error (`module-point-not-installed`).
319
+ - A module that `requires` the collector of a point it contributes to is a `DEPENDENCY_CYCLE` (the contributor must set up first). Values with rules of their own are checked by the collector (two tools with one name: @dokebi/mcp's `INVALID_TOOL`, naming both modules).
320
+
321
+ **Actions as MCP tools (D-0202).** A module offers its actions (§2c) to AI clients with `actionTools` of `@dokebi/mcp/actions`: one tool per action, named `<module>.<action>`, whose input schema is the action's (`describe` `schema`) and whose handler runs the general write's runner — the same permission, scope, checks, preview and confirm and result.
322
+
323
+ ```ts snippet
324
+ import { mcpTools } from '@dokebi/mcp';
325
+ import { actionTools } from '@dokebi/mcp/actions';
326
+ import { defineModule } from '@dokebi/module';
327
+ import { updateAction } from './actions/update.ts';
328
+
329
+ export default defineModule({
330
+ name: 'members',
331
+ permissions: { 'members.write': { title: 'Change members' } },
332
+ actions: { update: updateAction },
333
+ contributes: [mcpTools],
334
+ setup(module) {
335
+ for (const tool of actionTools(module)) module.contribute(mcpTools, tool);
336
+ },
337
+ });
338
+ ```
339
+
340
+ The OAuth scope of each tool is the action's permission key by default (`scope` changes it): an OAuth token carries its scopes as abilities, and `request.auth.can(permission)` needs the permission among them, so list the permission keys (or `<module>.*`) in `dokebi-oauth.resources.<id>.scopes`. The run sees `actor: { type: 'ai', id, client }`.
341
+
68
342
  ## 4. View lookup order (how an app changes a module page)
69
343
 
70
344
  1. `<app>/<template>/<module>/…`
@@ -78,22 +352,33 @@ To change a module page, an app never edits the module file; it puts a file with
78
352
 
79
353
  ## 5. Group plugin and lifecycle
80
354
 
81
- - `createPlugin({ app, entry: { modules } })`: groups several modules into a dependency graph. The API is `{ names }` (`ModuleGroupApi`). It accepts only what `defineModule` made; duplicates are `INVALID_PLUGIN_INPUT`. A single module may also be registered directly with `app.register`.
355
+ - `createPlugin({ app, entry: { modules } })`: groups several modules into a dependency graph. The API is `{ names, module, data, actions }` (`ModuleGroupApi`; `data` §2b, `actions` §2c). It accepts only what `defineModule` made; duplicates are `INVALID_PLUGIN_INPUT`. A single module may also be registered directly with `app.register`.
82
356
  - Hooks: setup (register routes, return the API) → start → drain (stop new input, wait for work in progress) → deferred cleanup. Drain runs in reverse dependency order (modules that depend on this one first); unrelated modules drain at the same time.
83
357
  - A module instance is used by one Application only. There is no automatic discovery, dynamic import or hot reload while running.
84
358
  - Options of the group plugin are an empty object.
85
- - Debug logs (D-0047): `Modules registered` (the group), `Module set up` (requires, number of controllers, views prefix, whether routes, sockets and events exist, ms), `Module start finished`, `Module drain finished`. A missing or unreadable `views/default/` fails the start, with the original file error kept as `cause`.
359
+ - Debug logs (D-0047): `Modules registered` (the group), `Module set up` (requires, number of controllers, contributes, views prefix, whether routes, sockets and events exist, ms), `Module start finished`, `Module drain finished`. A missing or unreadable `views/default/` fails the start, with the original file error kept as `cause`.
86
360
 
87
361
  ## 6. Errors
88
362
 
89
363
  <!-- docs-check: complete-error-codes ModuleErrorCode -->
90
- `DokebiError` (`plugin: 'dokebi-module'`, a `fix` that says how to repair it): `INVALID_DEFINITION` (arguments of `defineModule`), `INVALID_REQUIREMENT` (shape of requires, duplicate names), `INVALID_ENTRY` (the group entry file; at registration the cause of `INVALID_PLUGIN_INPUT`), `ALREADY_SET_UP` (one instance in two apps), `NOT_SET_UP` (context used before setup), `NO_CONTROLLERS`, `VIEWS_MISSING` (no `views/default/`; the file error is the `cause`). Options of the group plugin other than an empty object are `INVALID_PLUGIN_OPTIONS` (cause `INVALID_OPTIONS`). The `defineOptions` declaration in `src/options.ts` is the parser, and the build writes `options.schema.json` from it (D-0063 §3; never edit it by hand). Before 0.4.0 the codes had a `MODULE_` prefix (D-0071).
364
+ `DokebiError` (`plugin: 'dokebi-module'`, a `fix` that says how to repair it): `INVALID_DEFINITION` (arguments of `defineModule`), `INVALID_REQUIREMENT` (shape of requires, duplicate names), `INVALID_ENTRY` (the group entry file; at registration the cause of `INVALID_PLUGIN_INPUT`), `ALREADY_SET_UP` (one instance in two apps), `NOT_SET_UP` (context used before setup), `NO_CONTROLLERS`, `VIEWS_MISSING` (no `views/default/`; the file error is the `cause`), `INVALID_CONTRIBUTION` (`contributes` is not a list of distinct points made by `definePoint`, or has more than 64), `UNDECLARED_POINT` (`module.contribute` to a point missing from `contributes`, or `module.collect`; the `fix` names the module), `INVALID_CONTRACT` (a contract field of §2a that breaks its rule, or a widget template that cannot be read at start), `MODULE_MISSING` (the group entry has a module whose `modules` names one that is not in the entry; at registration the cause of `INVALID_PLUGIN_INPUT`). The general read (§2b) answers with a status: `DATA_SOURCE_NOT_FOUND` (404), `FORBIDDEN` (403), `INVALID_QUERY` and `INVALID_CURSOR` (400, `data.reason` and `data.name`), `DATA_SOURCE_FAILED` (500: the reader or the scope function broke the rules, logged at error). The general write (§2c) too: `ACTION_NOT_FOUND` (404), `FORBIDDEN` (403), `INVALID_INPUT` (400, `data.reason` and `data.name`), `VALIDATION_FAILED` (422, `fields`, `errors`, `data.rules`), `ACTION_CONFLICT` (409, thrown by a run through `actionConflict`), `CONFIRM_REQUIRED` (428, `data.preview` and `data.confirm`), `CONFIRM_STALE` (409, a new preview and token), `ACTION_FAILED` (500, logged at error). Warn log `POINT_NOT_COLLECTED` (core): values no registered plugin collects were dropped. Options of the group plugin other than an empty object are `INVALID_PLUGIN_OPTIONS` (cause `INVALID_OPTIONS`). The `defineOptions` declaration in `src/options.ts` is the parser, and the build writes `options.schema.json` from it (D-0063 §3; never edit it by hand). Before 0.4.0 the codes had a `MODULE_` prefix (D-0071).
91
365
 
92
366
  ## 7. Cautions
93
367
 
94
368
  - A module does not depend on apps (never branch on an app name). Handle per-app differences with `page.app` and the app's view overrides.
95
369
  - `moduleMount` and `MODULE_MOUNT` are the internal link @dokebi/app uses. App code does not use them.
96
- - Socket and SSE route types (`ModuleSocketRoute`, `ModuleEventRoute`) are defined by shape only, so projects that do not use them need neither @dokebi/websocket nor @dokebi/sse. When used, add that package (otherwise the app start fails: `has sockets; add @dokebi/websocket`, `has event streams; add @dokebi/sse`).
370
+ - Socket and SSE route types (`ModuleSocketRoute`, `ModuleEventRoute`) are defined by shape only, so projects that do not use them need neither @dokebi/websocket nor @dokebi/sse. When used, add that package (otherwise the app start fails: `has sockets; add @dokebi/websocket`, `has event streams; add @dokebi/sse`). Both take `config: { id }`, the route id (D-0140), like the module's routes: it must be unique among the routes, sockets and streams of each app that mounts the module (`DUPLICATE_ROUTE_ID` at start otherwise).
97
371
  - Do not treat the end of a response or a dropped connection as the work being done. Work detached from the request is awaited in the module's `drain`.
98
372
 
99
373
  References: `examples/26-scaffold` (repeated generation, mounting and overriding), `examples/25-playground` (eight feature modules; the sse module mounts `/api/sse/events` on every app through `events`), `examples/22-web/main.ts` (assembled in code), D-0022, D-0032.
374
+
375
+ ## Service composition
376
+
377
+ Use Controller -> Service -> Model for application data. Controllers handle HTTP input/output;
378
+ services provide data and coordinate workflows through models; models own persistence.
379
+ Generated app/module starters include this chain. Keep services free of request/reply and
380
+ rendering objects, and reuse them from jobs. Compose dependencies once during setup.
381
+ App-specific services belong in `src/apps/<app>/services`, cross-app services in
382
+ `src/shared/services`, and module services in `src/shared/modules/<module>/services`.
383
+ Shared services must not import app-specific code. These are ordinary application classes,
384
+ not a new framework plugin or service registry. Existing projects are not moved automatically.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
- # @dokebi/module 0.4.0
1
+ # @dokebi/module 0.4.2
2
2
 
3
- An optional package for Node >=24.0.0 and core ^0.4.0 (public on npm). A module is **one feature as an MVC unit of business code** ([D-0022](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0022-plugin-boundaries-and-db.md), [D-0032](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0032-feature-modules.md)). It keeps controllers, models, views, routes and sockets in one folder, and apps mount it under a prefix. It is not an HTTP-only bundle, so business code without a web side (job processing, event subscriptions) is a module too.
3
+ An optional package for Node >=24.0.0 and core ^0.4.0 (public on npm). A module is **one feature as an MVC unit of business code** ([D-0022](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0022-plugin-boundaries-and-db.md), [D-0032](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0032-feature-modules.md)). It keeps controllers, services, models, views, routes and sockets in one folder, and apps mount it under a prefix. It is not an HTTP-only bundle, so business code without a web side (job processing, event subscriptions) is a module too.
4
4
 
5
5
  ## Folder
6
6
 
@@ -23,6 +23,7 @@ export default defineModule({
23
23
  name: 'board', // the folder name; the ID is dokebi-module.board
24
24
  requires: [db, other], // plugin instances, descriptors, other modules
25
25
  controllers: [postsController], // created once with the module context
26
+ contributes: [mcpTools], // points of plugins it contributes to; module.contribute in setup
26
27
  views: new URL('./views/', import.meta.url), // default/ required; template names get the prefix module.board
27
28
  routes(route, module) { // registered per app (when mounted). page = { app, module, base, view, inertia }
28
29
  route.get('/', (request, reply, page) =>
@@ -42,6 +43,7 @@ export default defineModule({
42
43
  - **`views`:** adds a template-ejs dependency automatically. Without `views/default/` the start fails.
43
44
  - **`controllers`:** uses @dokebi/controller (optional peer). Calling `module.controller()` without controllers fails with `declares no controllers`.
44
45
  - **`setup`:** optional. The older `setup(context)` form still works.
46
+ - **`contributes`** ([D-0130](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0130-module-contributions.md)): the points of other plugins this module contributes to (for example `mcpTools` of @dokebi/mcp). `setup` calls `module.contribute(point, value)` with objects that use the module's own services; core sets the module up before every collector of the point. A point that nothing collects drops its values with warn `POINT_NOT_COLLECTED`; an undeclared point is `UNDECLARED_POINT`; modules never collect. See AI.md §3a.
45
47
  - **Shared APIs:** APIs that must answer on every domain are registered directly with router or web in setup, for example the playground's `/api/*`.
46
48
  - **Mounting on apps:** `defineApp({ modules: { '/board': board } })`. Routes and sockets answer only on that app's domains and prefix. A mounted module's API is readable with `app.get(board)` without listing it in the app's `requires`. Details are in [@dokebi/app](https://git.nyx-zone.com/dokebi/framework/-/blob/main/plugins/dokebi-app/README.md).
47
49
  - **View lookup order:**
@@ -57,6 +59,10 @@ export default defineModule({
57
59
  - **Sockets and SSE:** the return types of `sockets` and `events` (0.1.3) are defined by shape only (`ModuleSocketRoute`, `ModuleEventRoute`), so projects that do not use them need neither @dokebi/websocket nor @dokebi/sse. The mounting app registers them under its namespace rules ([D-0061](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0061-realtime-namespaces.md)): the tenant is `<namespace>:<authenticated tenant>`, and an authenticated `namespace` must be in that app's list.
58
60
  - **`moduleMount(plugin)` and `MODULE_MOUNT`:** how the app plugin reads the mounting information. App code never needs them.
59
61
 
62
+ ## The module contract (0.4.2)
63
+
64
+ A module also declares what it is made of — the modules it needs (`modules: { auth: '^0.1.0' }`), its `db/` folder of migrations and seeds and its `tables`, permission keys, data sources, widgets (a settings schema and a first HTML file), menu items, settings (`defineSettings`) and translations — so the framework, an editor and an AI read it without running it ([D-0197](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0197-module-contract.md)). `npx dokebi describe --json` lists it as `app.modules`; an app without a module another one needs refuses to start (`MODULE_MISSING`, then core's `MISSING_DEPENDENCY` or `INCOMPATIBLE_VERSION`); dokebi-migrate runs the module's migrations with the project's own. The rules of each field are in [AI.md](AI.md) §2a, and `examples/81-module-contract` uses them all.
65
+
60
66
  ## Group plugin
61
67
 
62
68
  `createPlugin({ app: app.view, entry: { modules: [...] } })` groups several modules into a dependency graph and exposes the frozen `names` (plugin contract v2, [D-0028](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0028-plugin-contract-v2.md)).
@@ -76,3 +82,14 @@ Examples:
76
82
  - `examples/22-web/main.ts`: assembled in code
77
83
 
78
84
  See the [AI guide](AI.md) for errors and cautions.
85
+
86
+ ## Service composition
87
+
88
+ Use Controller -> Service -> Model for application data. Controllers handle HTTP input/output;
89
+ services provide data and coordinate workflows through models; models own persistence.
90
+ Generated app/module starters include this chain. Keep services free of request/reply and
91
+ rendering objects, and reuse them from jobs. Compose dependencies once during setup.
92
+ App-specific services belong in `src/apps/<app>/services`, cross-app services in
93
+ `src/shared/services`, and module services in `src/shared/modules/<module>/services`.
94
+ Shared services must not import app-specific code. These are ordinary application classes,
95
+ not a new framework plugin or service registry. Existing projects are not moved automatically.
@@ -0,0 +1,73 @@
1
+ import { DokebiError, type Logger } from '@dokebi/core';
2
+ import { type ActionActor, type ActionFieldProblem, type ModuleAction } from './action.js';
3
+ /** Codes of the general write (`DokebiError`, `plugin: 'dokebi-module'`). */
4
+ export type ActionErrorCode = 'ACTION_NOT_FOUND' | 'FORBIDDEN' | 'INVALID_INPUT' | 'VALIDATION_FAILED' | 'ACTION_CONFLICT' | 'CONFIRM_REQUIRED' | 'CONFIRM_STALE' | 'ACTION_FAILED';
5
+ export declare function actionError(code: ActionErrorCode, message: string, data?: Readonly<Record<string, unknown>>, cause?: unknown): DokebiError<ActionErrorCode>;
6
+ /**
7
+ * 422 with the refused fields, in the shape @dokebi/web answers (`fields`, `errors`) and
8
+ * template-inertia turns into a validation redirect. `data.rules` names the rule per field.
9
+ */
10
+ export declare class ActionValidationError extends DokebiError<ActionErrorCode> {
11
+ readonly fields: readonly {
12
+ readonly field: string;
13
+ readonly message: string;
14
+ }[];
15
+ readonly errors: Readonly<Record<string, string>>;
16
+ constructor(problems: readonly ActionFieldProblem[], action: string);
17
+ }
18
+ /**
19
+ * What a run throws when the row changed since the caller read it (the `version` it sent is not the
20
+ * stored one): 409 ACTION_CONFLICT. `data` may carry the stored version (`{ version }`).
21
+ */
22
+ export declare function actionConflict(message?: string, data?: Readonly<Record<string, unknown>>): DokebiError<ActionErrorCode>;
23
+ /**
24
+ * What a run throws for a field the services refuse after the input check (a username that is
25
+ * taken): 422 VALIDATION_FAILED like the input check, `{ field: message }`.
26
+ */
27
+ export declare function actionInvalid(fields: Readonly<Record<string, string>>, action?: string): ActionValidationError;
28
+ /** What one action answers. */
29
+ export interface ActionResult {
30
+ /** `<module>.<name>`. */
31
+ readonly action: string;
32
+ /** What the run returned (JSON: ids, counts), null when it returned nothing. */
33
+ readonly result: unknown;
34
+ }
35
+ /** The body the general write takes. */
36
+ export interface ActionBody {
37
+ readonly input?: Readonly<Record<string, unknown>>;
38
+ /** The confirm token of the preview of a dangerous action. */
39
+ readonly confirm?: string;
40
+ }
41
+ /** The app router as @dokebi/app hands it to `routes(route, app)` (typed by shape). */
42
+ export interface ActionRouter {
43
+ post(url: string, handler: ActionHandler, options?: {
44
+ readonly config?: Readonly<Record<string, unknown>>;
45
+ }): void;
46
+ }
47
+ /** A route handler (Fastify request and reply), method-typed so any app router accepts it. */
48
+ export type ActionHandler = {
49
+ handle(request: unknown, reply: unknown, page: unknown): unknown;
50
+ }['handle'];
51
+ /** The actions of the module group (`ModuleGroupApi.actions`, D-0202). */
52
+ export interface ActionApi {
53
+ /** The ids of the actions (`members.update`). */
54
+ readonly ids: readonly string[];
55
+ /** Runs action `id` for `request` (its `auth` decides the permission) with `body`. */
56
+ run(request: unknown, id: string, body: ActionBody): Promise<ActionResult>;
57
+ /** Adds `POST <path>/:module/:action` (route id `module.action`) answering `run` as JSON. */
58
+ routes(route: ActionRouter, options?: {
59
+ readonly path?: string;
60
+ }): void;
61
+ }
62
+ /** One action as the runner knows it. */
63
+ export interface ActionEntry {
64
+ readonly id: string;
65
+ readonly module: string;
66
+ readonly declaration: ModuleAction;
67
+ context(): unknown;
68
+ }
69
+ /** Who asks: the AI client of an OAuth grant (@dokebi/oauth), else the signed-in user. */
70
+ export declare function actorOf(request: unknown): ActionActor;
71
+ /** Runs one action: the steps every caller shares (route, group API, MCP tool). */
72
+ export declare function runAction(entry: ActionEntry, request: unknown, body: unknown, logger: Logger): Promise<ActionResult>;
73
+ export declare function createActionApi(actions: ReadonlyMap<string, ActionEntry>, logger: Logger): ActionApi;