@dokebi/module 0.4.2 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,18 +1,8 @@
1
1
  import { stat } from 'node:fs/promises';
2
2
  import { fileURLToPath } from 'node:url';
3
3
  import { types } from 'node:util';
4
- import { DokebiError, definePlugin, definePoint, dependencyOf, providerDependency, } from '@dokebi/core';
5
- import { createActionApi, } from './action-api.js';
6
- import { CONTRACT_KEYS, ContractIssue, describeContract, readContract, readPresets, readTemplate, } from './contract.js';
7
- import { createDataApi } from './data-api.js';
4
+ import { DokebiError, definePlugin, dependencyOf, providerDependency, } from '@dokebi/core';
8
5
  import { options } from './options.js';
9
- export { ACTION_LIMITS, checkInput, inputSchema, TEXT_FORMATS, } from './action.js';
10
- export { ActionValidationError, actionConflict, actionError, actionInvalid, actorOf, runAction, } from './action-api.js';
11
- export { CONTRACT_LIMITS, islandName, } from './contract.js';
12
- export { dataError, } from './data-api.js';
13
- export { CHOICE_TONES, checkQuery, DATA_LIMITS, decodeCursor, encodeCursor, FIELD_TYPES, readSql, } from './data-source.js';
14
- export { checkParts, PART_KINDS, PARTS_LIMITS, PartsIssue, readParts, } from './parts.js';
15
- export { checkPresetApp, isSiteFile, PRESET_APP_KEYS, PRESET_KINDS, PRESET_LIMITS, } from './preset.js';
16
6
  const FIX = {
17
7
  INVALID_DEFINITION: 'Pass defineModule a lower-case name (a-z, 0-9, ., _, -) and only the documented fields: requires and controllers arrays, views as a file: URL, hooks as functions.',
18
8
  INVALID_REQUIREMENT: 'List plugin instances or dependency descriptors ({ name, version }) in requires, each name once.',
@@ -23,8 +13,6 @@ const FIX = {
23
13
  VIEWS_MISSING: 'Create the views/default/ folder of the module (the cause names the file system error), or remove views.',
24
14
  INVALID_CONTRIBUTION: 'List in contributes the points made by definePoint that the module contributes to, each once and at most 64 (import them from the plugin that owns them, as mcpTools from @dokebi/mcp).',
25
15
  UNDECLARED_POINT: 'Add the point to contributes of defineModule and call module.contribute(point, value) in the setup of the module. Modules only contribute: a plugin collects.',
26
- INVALID_CONTRACT: 'Correct the contract fields of defineModule as the message says (AI.md of @dokebi/module, section 2a): titles, permission keys <module>.<action>, data source, action (input fields, permission, danger with preview), widget and menu names, file: URLs for db, locales and widget templates (.html, at most 64 KB).',
27
- MODULE_MISSING: 'Add the module the message names to the project (npx dokebi module add <name>, or its package), or remove it from modules of the module that needs it.',
28
16
  };
29
17
  function moduleError(code, message, cause, fix = FIX[code]) {
30
18
  return new DokebiError(code, message, {
@@ -35,13 +23,6 @@ function moduleError(code, message, cause, fix = FIX[code]) {
35
23
  }
36
24
  export const MODULE_MOUNT = Symbol.for('dokebi.module.mount');
37
25
  const NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
38
- /** Module plugins are `dokebi-module.<name>` (D-0032). */
39
- const MODULE_PREFIX = 'dokebi-module.';
40
- /**
41
- * The `core:describe` point of @dokebi/core 0.4.2, declared here by name (its identity) so this
42
- * package keeps working with older cores, which never describe.
43
- */
44
- const describePoint = definePoint('core:describe');
45
26
  /** core's point name (`<owner plugin>:<name>`) and its limit per plugin (D-0063). */
46
27
  const POINT_NAME = /^[a-z0-9][a-z0-9._/-]{0,95}:[a-z0-9][a-z0-9._-]{0,63}$/;
47
28
  const POINT_LIMIT = 64;
@@ -58,7 +39,6 @@ const DEFINITION_KEYS = new Set([
58
39
  'setup',
59
40
  'start',
60
41
  'drain',
61
- ...CONTRACT_KEYS,
62
42
  ]);
63
43
  const ejs = providerDependency({
64
44
  name: 'dokebi-template-ejs',
@@ -95,12 +75,11 @@ function contributedPoints(value, module) {
95
75
  }
96
76
  return Object.freeze([...names]);
97
77
  }
98
- function moduleContext(context, name, declared, controllers, points, contract) {
78
+ function moduleContext(context, name, declared, controllers, points) {
99
79
  // core accepts only the descriptor object this module declared; look it up by name.
100
80
  const own = (dependency) => declared.get(dependency?.name) ?? dependency;
101
81
  return Object.freeze({
102
82
  module: name,
103
- contract,
104
83
  get app() {
105
84
  return context.app;
106
85
  },
@@ -160,21 +139,9 @@ export function defineModule(definition) {
160
139
  ['routes', 'sockets', 'events', 'setup', 'start', 'drain'].some((hook) => definition[hook] !== undefined && typeof definition[hook] !== 'function'))
161
140
  throw moduleError('INVALID_DEFINITION', 'Invalid module definition');
162
141
  const { name, views } = definition;
163
- let contract;
164
- try {
165
- contract = readContract(name, definition);
166
- }
167
- catch (error) {
168
- if (error instanceof ContractIssue)
169
- throw moduleError('INVALID_CONTRACT', error.message);
170
- throw error;
171
- }
172
142
  const points = contributedPoints(definition.contributes, name);
173
143
  const pointSet = new Set(points);
174
144
  const dependencies = (definition.requires ?? []).map(requirement);
175
- // D-0197: the modules it needs by name and range; core refuses the start without them.
176
- for (const [other, range] of Object.entries(contract.modules))
177
- dependencies.push(Object.freeze({ name: MODULE_PREFIX + other, version: range }));
178
145
  if (new Set(dependencies.map((dependency) => dependency.name)).size !== dependencies.length)
179
146
  throw moduleError('INVALID_REQUIREMENT', 'Duplicate module requirement');
180
147
  if (views && !dependencies.some((dependency) => dependency.name === ejs.name))
@@ -188,7 +155,7 @@ export function defineModule(definition) {
188
155
  const prefix = `module.${name}`;
189
156
  const hook = (key) => async (context) => {
190
157
  const begin = performance.now();
191
- await definition[key]?.(current ?? moduleContext(context, name, declared, () => controllers, pointSet, contract));
158
+ await definition[key]?.(current ?? moduleContext(context, name, declared, () => controllers, pointSet));
192
159
  context.logger.log('debug', `Module ${key} finished`, {
193
160
  module: name,
194
161
  ms: Math.round(performance.now() - begin),
@@ -196,7 +163,7 @@ export function defineModule(definition) {
196
163
  };
197
164
  const plugin = {
198
165
  metadata: Object.freeze({
199
- name: MODULE_PREFIX + name,
166
+ name: 'dokebi-module.' + name,
200
167
  version,
201
168
  core: '^0.4.0',
202
169
  dependencies: Object.freeze(dependencies),
@@ -207,7 +174,7 @@ export function defineModule(definition) {
207
174
  if (started)
208
175
  throw moduleError('ALREADY_SET_UP', 'Create one module instance per Application');
209
176
  started = true;
210
- current = moduleContext(context, name, declared, () => controllers, pointSet, contract);
177
+ current = moduleContext(context, name, declared, () => controllers, pointSet);
211
178
  const begin = performance.now();
212
179
  if (definition.controllers?.length) {
213
180
  const { createControllers } = await import('@dokebi/controller');
@@ -225,26 +192,6 @@ export function defineModule(definition) {
225
192
  throw moduleError('VIEWS_MISSING', `Module ${name} has no views/default/ folder`, failure);
226
193
  await context.getDependency(templates ?? ejs).addDirectory(views, prefix);
227
194
  }
228
- // D-0197: a widget's first HTML must be readable and its settings valid before anything runs.
229
- for (const [widget, item] of Object.entries(contract.widgets)) {
230
- try {
231
- await readTemplate(item.template);
232
- }
233
- catch (cause) {
234
- throw moduleError('INVALID_CONTRACT', `The template of widget ${widget} of module ${name} cannot be read as UTF-8 HTML of at most 64 KB`, cause);
235
- }
236
- }
237
- // dokebi-platform DEC-16: a preset folder must have the shape of an app folder before anything runs.
238
- try {
239
- await readPresets(name, contract.presets);
240
- }
241
- catch (error) {
242
- if (error instanceof ContractIssue)
243
- throw moduleError('INVALID_CONTRACT', error.message);
244
- throw error;
245
- }
246
- // Throws INVALID_PLUGIN_OPTIONS (paths, never values) for settings that do not fit.
247
- contract.settings?.read(context.app.config);
248
195
  const api = (await definition.setup?.(current));
249
196
  context.logger.log('debug', 'Module set up', {
250
197
  module: name,
@@ -256,13 +203,6 @@ export function defineModule(definition) {
256
203
  routes: Boolean(definition.routes),
257
204
  sockets: Boolean(definition.sockets),
258
205
  events: Boolean(definition.events),
259
- modules: contract.modules,
260
- permissions: Object.keys(contract.permissions).length,
261
- dataSources: Object.keys(contract.dataSources),
262
- actions: Object.keys(contract.actions),
263
- widgets: Object.keys(contract.widgets),
264
- menu: contract.menu.length,
265
- settings: contract.settings?.section ?? false,
266
206
  ms: Math.round(performance.now() - begin),
267
207
  });
268
208
  return api;
@@ -281,27 +221,6 @@ export function defineModule(definition) {
281
221
  throw moduleError('NOT_SET_UP', `Module ${name} is not set up yet`);
282
222
  return current;
283
223
  },
284
- contract,
285
- describe: () => describeContract({
286
- name,
287
- version,
288
- requires: dependencies
289
- .map((dependency) => dependency.name)
290
- .filter((dependency) => !dependency.startsWith(MODULE_PREFIX)),
291
- contributes: points,
292
- views: views ? prefix : undefined,
293
- hooks: {
294
- routes: Boolean(definition.routes),
295
- sockets: Boolean(definition.sockets),
296
- events: Boolean(definition.events),
297
- },
298
- contract,
299
- }).catch((error) => {
300
- // A parts file that breaks its rules (D-0203) is found here, when it is read.
301
- if (error instanceof ContractIssue)
302
- throw moduleError('INVALID_CONTRACT', error.message);
303
- throw error;
304
- }),
305
224
  });
306
225
  Object.defineProperty(plugin, MODULE_MOUNT, { value: mount });
307
226
  return Object.freeze(plugin);
@@ -339,94 +258,27 @@ function parseEntry(input) {
339
258
  if (!Array.isArray(modules) || modules.length > LIMIT)
340
259
  throw moduleError('INVALID_ENTRY', 'Expected a modules array');
341
260
  const names = modules.map((module) => module?.metadata?.name);
342
- if (names.some((name) => typeof name !== 'string' || !name.startsWith(MODULE_PREFIX)) ||
261
+ if (names.some((name) => typeof name !== 'string' || !name.startsWith('dokebi-module.')) ||
343
262
  new Set(names).size !== names.length)
344
263
  throw moduleError('INVALID_ENTRY', 'Expected distinct module plugins');
345
- // D-0197: a module that needs another one which is not in the project says so by name, before
346
- // core's MISSING_DEPENDENCY (whose message only names the plugin).
347
- const present = new Set(names);
348
- for (const module of modules) {
349
- const mount = moduleMount(module);
350
- for (const [other, range] of Object.entries(mount?.contract?.modules ?? {}))
351
- if (!present.has(MODULE_PREFIX + other))
352
- throw moduleError('MODULE_MISSING', `Module ${mount?.name} needs module ${other} (${range}), which is not in the project`, undefined, `Add module ${other} to the project (npx dokebi module add ${other}, or install the package that provides it), or remove ${other} from modules of module ${mount?.name}.`);
353
- }
354
264
  return [...modules];
355
265
  }
356
266
  class ModuleGroupRuntime {
357
267
  names;
358
- modules;
359
- constructor(names, modules) {
268
+ constructor(names) {
360
269
  this.names = names;
361
- this.modules = modules;
362
270
  }
363
271
  setup(context) {
364
272
  context.logger.log('debug', 'Modules registered', { modules: this.names });
365
- // D-0197: only `dokebi describe` (runtime.describing) asks; a normal start adds nothing.
366
- if (context.runtime.describing) {
367
- const mounts = this.modules
368
- .map((module) => moduleMount(module))
369
- .filter((mount) => mount !== undefined);
370
- context.contribute(describePoint, {
371
- section: 'modules',
372
- describe: async () => {
373
- const described = [];
374
- for (const mount of mounts)
375
- described.push(await mount.describe());
376
- return described;
377
- },
378
- });
379
- }
380
- const byName = new Map();
381
- for (const module of this.modules) {
382
- const mount = moduleMount(module);
383
- if (mount)
384
- byName.set(mount.name, mount);
385
- }
386
- const sources = new Map();
387
- for (const mount of byName.values())
388
- for (const [name, declaration] of Object.entries(mount.contract?.dataSources ?? {}))
389
- sources.set(`${mount.name}.${name}`, {
390
- module: mount.name,
391
- declaration,
392
- context: () => mount.context(),
393
- });
394
- const data = createDataApi(sources, context.logger);
395
- context.logger.log('debug', 'Data sources registered', { sources: data.ids });
396
- const actions = new Map();
397
- for (const mount of byName.values())
398
- for (const [name, declaration] of Object.entries(mount.contract?.actions ?? {}))
399
- actions.set(`${mount.name}.${name}`, {
400
- id: `${mount.name}.${name}`,
401
- module: mount.name,
402
- declaration,
403
- context: () => mount.context(),
404
- });
405
- // D-0202: a row action naming another module's action names one that module declares.
406
- for (const mount of byName.values())
407
- for (const [source, item] of Object.entries(mount.contract?.dataSources ?? {}))
408
- for (const [name, rowAction] of Object.entries(item.actions ?? {})) {
409
- const target = rowAction.action;
410
- if (target?.includes('.') && !actions.has(target))
411
- throw moduleError('INVALID_CONTRACT', `dataSources.${source}.actions.${name}.action of module ${mount.name} names ${target}, which no module of the project declares`);
412
- }
413
- const write = createActionApi(actions, context.logger);
414
- context.logger.log('debug', 'Actions registered', { actions: write.ids });
415
- return Object.freeze({
416
- names: this.names,
417
- module: (name) => byName.get(name),
418
- data,
419
- actions: write,
420
- });
273
+ return Object.freeze({ names: this.names });
421
274
  }
422
275
  }
423
276
  export const createPlugin = definePlugin({
424
277
  name: 'dokebi-module',
425
- version: '0.4.2',
278
+ version: '0.4.3',
426
279
  core: '^0.4.0',
427
280
  options,
428
- contributes: [describePoint],
429
281
  entry: parseEntry,
430
282
  dependencies: ({ entry }) => (entry ?? []).map((module) => dependencyOf(module)),
431
- instance: ({ dependencies, entry }) => new ModuleGroupRuntime(Object.freeze(dependencies.map((dependency) => dependency.name)), Object.freeze([...(entry ?? [])])),
283
+ instance: ({ dependencies }) => new ModuleGroupRuntime(Object.freeze(dependencies.map((dependency) => dependency.name))),
432
284
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/module",
3
- "version": "0.4.2",
3
+ "version": "0.4.3",
4
4
  "description": "Feature modules for Dokebi apps: controllers, models, views and routes in one folder mounted under a prefix.",
5
5
  "keywords": [
6
6
  "dokebi",
@@ -18,10 +18,6 @@
18
18
  ".": {
19
19
  "types": "./dist/index.d.ts",
20
20
  "import": "./dist/index.js"
21
- },
22
- "./dependency": {
23
- "types": "./dist/dependency.d.ts",
24
- "import": "./dist/dependency.js"
25
21
  }
26
22
  },
27
23
  "files": [
@@ -40,9 +36,6 @@
40
36
  "typecheck": "tsc -p tsconfig.test.json --noEmit",
41
37
  "test": "node -e \"require('node:fs').rmSync('.tmp/tests',{recursive:true,force:true})\" && tsc -p tsconfig.test.json && node --test .tmp/tests/tests/*.test.js"
42
38
  },
43
- "dependencies": {
44
- "yaml": "2.9.1"
45
- },
46
39
  "peerDependencies": {
47
40
  "@dokebi/controller": "^0.4.0",
48
41
  "@dokebi/core": "^0.4.0",
@@ -59,9 +52,6 @@
59
52
  "hosts": [
60
53
  "modules"
61
54
  ],
62
- "contributes": [
63
- "core:describe"
64
- ],
65
55
  "install": {
66
56
  "directories": [
67
57
  "src/shared/modules"
@@ -1,73 +0,0 @@
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;
@@ -1,249 +0,0 @@
1
- // The general write of actions (D-0202): one runner for every caller of every module's actions —
2
- // the route `POST <path>/:module/:action`, the group API and the MCP tools of @dokebi/module/mcp.
3
- // It checks the caller's permission and scope, the input against the declaration (unknown fields
4
- // 400, wrong values 422), runs a dangerous action only with the token of its preview, and checks
5
- // that the result is JSON.
6
- import { DokebiError } from '@dokebi/core';
7
- import { ACTION_LIMITS, checkInput, confirmToken, } from './action.js';
8
- const STATUS = {
9
- ACTION_NOT_FOUND: 404,
10
- FORBIDDEN: 403,
11
- INVALID_INPUT: 400,
12
- VALIDATION_FAILED: 422,
13
- ACTION_CONFLICT: 409,
14
- CONFIRM_REQUIRED: 428,
15
- CONFIRM_STALE: 409,
16
- ACTION_FAILED: 500,
17
- };
18
- const FIX = {
19
- ACTION_NOT_FOUND: 'Run an action that npx dokebi describe --json lists under app.modules[].actions, as <module>.<name>.',
20
- FORBIDDEN: 'Sign in with an account that holds the action permission (its scope must not be empty), or leave the action out.',
21
- INVALID_INPUT: 'Send { input: { <declared field>: value } } and, for a dangerous action, confirm: <the token of its preview>; nothing else. data.reason and data.name say what was refused.',
22
- VALIDATION_FAILED: 'Correct the fields named in fields (a fixed message each; data.rules names the broken rule) and send the input again.',
23
- ACTION_CONFLICT: 'Read the row again (its new version) and send the change again on top of it.',
24
- CONFIRM_REQUIRED: 'Show data.preview to the user; when they agree, send the same input with confirm: data.confirm.',
25
- CONFIRM_STALE: 'The row changed after the preview: show the new data.preview and send confirm: data.confirm when the user agrees.',
26
- ACTION_FAILED: 'Correct the action as the message says: its scope function answers one of its scopes, its preview and result are JSON of at most the documented size.',
27
- };
28
- const HINT = {
29
- ACTION_NOT_FOUND: 'This action does not exist.',
30
- FORBIDDEN: 'You are not allowed to do this.',
31
- VALIDATION_FAILED: 'Check the highlighted fields.',
32
- ACTION_CONFLICT: 'Someone changed this in the meantime. Load it again.',
33
- CONFIRM_REQUIRED: 'Confirm to continue.',
34
- CONFIRM_STALE: 'It changed in the meantime. Check again and confirm.',
35
- };
36
- export function actionError(code, message, data, cause) {
37
- return new DokebiError(code, message, {
38
- plugin: 'dokebi-module',
39
- status: STATUS[code],
40
- fix: FIX[code],
41
- ...(HINT[code] === undefined ? {} : { hint: HINT[code] }),
42
- ...(data === undefined ? {} : { data }),
43
- ...(cause === undefined ? {} : { cause }),
44
- });
45
- }
46
- /**
47
- * 422 with the refused fields, in the shape @dokebi/web answers (`fields`, `errors`) and
48
- * template-inertia turns into a validation redirect. `data.rules` names the rule per field.
49
- */
50
- export class ActionValidationError extends DokebiError {
51
- fields;
52
- errors;
53
- constructor(problems, action) {
54
- const rules = {};
55
- for (const problem of problems)
56
- if (!Object.hasOwn(rules, problem.field))
57
- rules[problem.field] = problem.rule;
58
- super('VALIDATION_FAILED', `Invalid fields: ${[...new Set(problems.map((problem) => problem.field))].join(', ')}`, {
59
- plugin: 'dokebi-module',
60
- status: 422,
61
- fix: FIX.VALIDATION_FAILED,
62
- hint: HINT.VALIDATION_FAILED,
63
- data: { action, rules },
64
- });
65
- this.fields = Object.freeze(problems.map(({ field, message }) => Object.freeze({ field, message })));
66
- const errors = {};
67
- for (const { field, message } of this.fields)
68
- if (!Object.hasOwn(errors, field))
69
- errors[field] = message;
70
- this.errors = Object.freeze(errors);
71
- }
72
- }
73
- /**
74
- * What a run throws when the row changed since the caller read it (the `version` it sent is not the
75
- * stored one): 409 ACTION_CONFLICT. `data` may carry the stored version (`{ version }`).
76
- */
77
- export function actionConflict(message = 'The row changed since it was read', data) {
78
- return actionError('ACTION_CONFLICT', message, data);
79
- }
80
- /**
81
- * What a run throws for a field the services refuse after the input check (a username that is
82
- * taken): 422 VALIDATION_FAILED like the input check, `{ field: message }`.
83
- */
84
- export function actionInvalid(fields, action = '') {
85
- return new ActionValidationError(Object.entries(fields).map(([field, message]) => ({ field, message, rule: 'service' })), action);
86
- }
87
- /** Who asks: the AI client of an OAuth grant (@dokebi/oauth), else the signed-in user. */
88
- export function actorOf(request) {
89
- const asked = (request ?? {});
90
- const grant = asked.oauth?.grant;
91
- if (grant && typeof grant === 'object') {
92
- const client = typeof grant.clientName === 'string' && grant.clientName ? grant.clientName : grant.clientId;
93
- return Object.freeze({
94
- type: 'ai',
95
- ...(typeof grant.userId === 'string' ? { id: grant.userId } : {}),
96
- ...(typeof client === 'string' ? { client: client.slice(0, 128) } : {}),
97
- });
98
- }
99
- const id = asked.auth?.id;
100
- return Object.freeze({ type: 'user', ...(typeof id === 'string' ? { id } : {}) });
101
- }
102
- /** JSON of at most `bytes`, or undefined. */
103
- function json(value, bytes) {
104
- let text;
105
- try {
106
- text = JSON.stringify(value === undefined ? null : value);
107
- }
108
- catch (error) {
109
- throw actionError('ACTION_FAILED', 'The value is not JSON', undefined, error);
110
- }
111
- if (text === undefined || Buffer.byteLength(text) > bytes)
112
- return undefined;
113
- return JSON.parse(text);
114
- }
115
- /** Runs one action: the steps every caller shares (route, group API, MCP tool). */
116
- export async function runAction(entry, request, body, logger) {
117
- const begin = performance.now();
118
- const { id, declaration } = entry;
119
- const actor = actorOf(request);
120
- const done = (outcome, extra = {}) => {
121
- if (logger.isEnabled('debug'))
122
- logger.log('debug', 'Action answered', {
123
- action: id,
124
- outcome,
125
- actor: actor.type,
126
- ...(actor.id === undefined ? {} : { user: actor.id }),
127
- ...(actor.client === undefined ? {} : { client: actor.client }),
128
- ms: Math.round((performance.now() - begin) * 10) / 10,
129
- ...extra,
130
- });
131
- };
132
- try {
133
- const asked = request;
134
- const allowed = asked?.auth ? await asked.auth.can(declaration.permission) : false;
135
- if (!allowed)
136
- throw actionError('FORBIDDEN', `Running ${id} needs ${declaration.permission}`, {
137
- action: id,
138
- });
139
- if (body === null || typeof body !== 'object' || Array.isArray(body))
140
- throw actionError('INVALID_INPUT', 'The body must be { input, confirm? }', {
141
- action: id,
142
- reason: 'body',
143
- });
144
- const extra = Object.keys(body).find((key) => key !== 'input' && key !== 'confirm');
145
- if (extra !== undefined)
146
- throw actionError('INVALID_INPUT', `The body field ${extra.slice(0, 64)} is not known`, {
147
- action: id,
148
- reason: 'body',
149
- name: extra.slice(0, 64),
150
- });
151
- const { input, confirm } = body;
152
- if (confirm !== undefined &&
153
- (!declaration.danger || typeof confirm !== 'string' || confirm.length > 64))
154
- throw actionError('INVALID_INPUT', declaration.danger ? 'confirm must be the token of the preview' : `${id} takes no confirm`, { action: id, reason: 'confirm' });
155
- const checked = checkInput(declaration.input ?? {}, input ?? {});
156
- if (!checked.ok) {
157
- if (checked.reason === 'fields')
158
- throw new ActionValidationError(checked.problems, id);
159
- throw actionError('INVALID_INPUT', checked.message, {
160
- action: id,
161
- reason: checked.reason,
162
- ...(checked.name === undefined ? {} : { name: checked.name }),
163
- });
164
- }
165
- const module = entry.context();
166
- let scope = null;
167
- if (declaration.scope) {
168
- const answer = await declaration.scope({ request, module });
169
- if (answer === null || answer === undefined)
170
- throw actionError('FORBIDDEN', `The caller has no scope on ${id}`, { action: id });
171
- if (typeof answer !== 'string' || !declaration.scopes?.includes(answer))
172
- throw actionError('ACTION_FAILED', `The scope function of ${id} answered something other than one of its scopes (${declaration.scopes?.join(', ')})`, { action: id });
173
- scope = answer;
174
- }
175
- const run = Object.freeze({
176
- action: id,
177
- input: checked.input,
178
- scope,
179
- actor,
180
- request,
181
- module,
182
- });
183
- if (declaration.preview) {
184
- const preview = json(await declaration.preview(run), ACTION_LIMITS.previewBytes);
185
- if (preview === undefined)
186
- throw actionError('ACTION_FAILED', `The preview of ${id} is larger than ${ACTION_LIMITS.previewBytes} bytes of JSON`, { action: id });
187
- const token = confirmToken(id, actor, checked.input, preview);
188
- if (confirm === undefined)
189
- throw actionError('CONFIRM_REQUIRED', `${id} needs a confirm after its preview`, {
190
- action: id,
191
- preview,
192
- confirm: token,
193
- });
194
- if (confirm !== token)
195
- throw actionError('CONFIRM_STALE', `What ${id} would change is not what was previewed`, {
196
- action: id,
197
- preview,
198
- confirm: token,
199
- });
200
- }
201
- const value = await declaration.run(run);
202
- const result = json(value, ACTION_LIMITS.resultBytes);
203
- if (result === undefined)
204
- throw actionError('ACTION_FAILED', `The result of ${id} is larger than ${ACTION_LIMITS.resultBytes} bytes of JSON`, { action: id });
205
- done('ok');
206
- return Object.freeze({ action: id, result });
207
- }
208
- catch (error) {
209
- const code = error?.code;
210
- if (code === 'ACTION_FAILED')
211
- logger.log('error', 'Action broke the rules', { code: 'ACTION_FAILED', action: id, error });
212
- done('refused', { code: typeof code === 'string' ? code : 'ERROR' });
213
- throw error;
214
- }
215
- }
216
- const PATH = /^(?:\/[a-z0-9][a-z0-9._-]{0,63}){1,4}$/;
217
- export function createActionApi(actions, logger) {
218
- const ids = Object.freeze([...actions.keys()]);
219
- const run = async (request, id, body) => {
220
- const entry = typeof id === 'string' ? actions.get(id) : undefined;
221
- if (!entry) {
222
- const error = actionError('ACTION_NOT_FOUND', `There is no action ${String(id).slice(0, 140)}`, {
223
- action: String(id).slice(0, 140),
224
- });
225
- logger.log('debug', 'Action answered', {
226
- action: String(id).slice(0, 140),
227
- outcome: 'refused',
228
- code: error.code,
229
- });
230
- throw error;
231
- }
232
- return runAction(entry, request, body, logger);
233
- };
234
- return Object.freeze({
235
- ids,
236
- run,
237
- routes(route, options = {}) {
238
- const path = options.path ?? '/actions';
239
- if (!PATH.test(path))
240
- throw actionError('ACTION_FAILED', `The action route path ${path} must be /a/lower-case/path`);
241
- const handler = (async (request) => {
242
- const asked = request;
243
- const params = asked.params ?? {};
244
- return run(request, `${String(params.module)}.${String(params.action)}`, (asked.body ?? {}));
245
- });
246
- route.post(`${path}/:module/:action`, handler, { config: { id: 'module.action' } });
247
- },
248
- });
249
- }