@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.
@@ -0,0 +1,524 @@
1
+ // The module contract (D-0197): what a module declares about itself so the framework, an editor and
2
+ // an AI can read it without running it — tables and migrations, permission keys, data sources,
3
+ // widgets (screen pieces with a settings schema and a first HTML), menu items, settings,
4
+ // translations and the other modules it relies on. `defineModule` checks the declaration;
5
+ // `dokebi describe --json` gives it as `app.modules`. The UI parts the module offers (D-0203) are
6
+ // a JSON file it points at (`parts`), read and checked when it is described (parts.ts).
7
+ import { readdir, readFile, stat } from 'node:fs/promises';
8
+ import { join, relative } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { types } from 'node:util';
11
+ import { ActionIssue, inputSchema, readAction } from './action.js';
12
+ import { DataSourceIssue, readDataSource, } from './data-source.js';
13
+ import { PartsIssue, readParts } from './parts.js';
14
+ import { PRESET_KINDS, PresetIssue, readPreset } from './preset.js';
15
+ export const CONTRACT_KEYS = [
16
+ 'title',
17
+ 'description',
18
+ 'modules',
19
+ 'db',
20
+ 'tables',
21
+ 'permissions',
22
+ 'dataSources',
23
+ 'actions',
24
+ 'widgets',
25
+ 'menu',
26
+ 'settings',
27
+ 'locales',
28
+ 'parts',
29
+ 'presets',
30
+ ];
31
+ /** Limits of one contract (D-0197). */
32
+ export const CONTRACT_LIMITS = Object.freeze({
33
+ modules: 64,
34
+ tables: 64,
35
+ permissions: 256,
36
+ dataSources: 64,
37
+ actions: 64,
38
+ widgets: 64,
39
+ menu: 64,
40
+ presets: 16,
41
+ textChars: 200,
42
+ locales: 32,
43
+ /** Bytes of one widget template file. */
44
+ templateBytes: 65536,
45
+ /** Files listed per folder when the module is described. */
46
+ describedFiles: 1000,
47
+ });
48
+ const LOCAL_NAME = /^[a-z][a-z0-9-]{0,63}$/;
49
+ const MODULE_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
50
+ const TABLE = /^[A-Za-z_][A-Za-z0-9_.]{0,127}$/;
51
+ const PERMISSION = /^[a-z0-9][a-z0-9_-]*(?:\.[a-z0-9][a-z0-9_-]*)+$/;
52
+ const LOCALE = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/;
53
+ const ICON = /^[a-z0-9][a-z0-9-]{0,63}$/;
54
+ // '' or /segment[/segment…]; no '..', no query or fragment.
55
+ const MENU_PATH = /^(?:\/[A-Za-z0-9._~:@!$&'()*+,;=-]+)*\/?$/;
56
+ const RANGE = /^[0-9A-Za-z.^~<>=|*x+ -]{1,64}$/;
57
+ /** An island component: `<module folder>/islands/<Name>.vue`. */
58
+ const ISLAND_FILE = /\/islands\/[A-Z][A-Za-z0-9]{0,63}\.vue$/;
59
+ /** The island name the page registry and @dokebi/pages use: `<module>/<Name>`. */
60
+ export const islandName = (module, island) => `${module}/${(island.pathname.split('/').at(-1) ?? '').replace(/\.vue$/, '')}`;
61
+ /** Thrown for a contract that breaks a rule; index.ts turns it into INVALID_CONTRACT. */
62
+ export class ContractIssue extends Error {
63
+ }
64
+ const plain = (value) => value !== null &&
65
+ typeof value === 'object' &&
66
+ !Array.isArray(value) &&
67
+ !types.isProxy(value) &&
68
+ [Object.prototype, null].includes(Object.getPrototypeOf(value));
69
+ function text(value, where, required) {
70
+ if (value === undefined && !required)
71
+ return undefined;
72
+ const fits = (item) => typeof item === 'string' && item.trim().length > 0 && item.length <= CONTRACT_LIMITS.textChars;
73
+ if (fits(value))
74
+ return value;
75
+ if (plain(value)) {
76
+ const entries = Object.entries(value);
77
+ if (entries.length > 0 &&
78
+ entries.length <= CONTRACT_LIMITS.locales &&
79
+ entries.every(([locale, item]) => LOCALE.test(locale) && fits(item)))
80
+ return Object.freeze(Object.fromEntries(entries));
81
+ }
82
+ throw new ContractIssue(`${where} must be a text of 1 to ${CONTRACT_LIMITS.textChars} characters or { <locale>: text }`);
83
+ }
84
+ function record(value, where, limit, key, item) {
85
+ if (value === undefined)
86
+ return Object.freeze({});
87
+ if (!plain(value))
88
+ throw new ContractIssue(`${where} must be an object`);
89
+ const names = Object.keys(value);
90
+ if (names.length > limit)
91
+ throw new ContractIssue(`${where} has more than ${limit} entries`);
92
+ const result = {};
93
+ for (const name of names) {
94
+ if (!key.test(name))
95
+ throw new ContractIssue(`${where} has an invalid name: ${name}`);
96
+ const input = value[name];
97
+ if (!plain(input))
98
+ throw new ContractIssue(`${where}.${name} must be an object`);
99
+ result[name] = item(input, name);
100
+ }
101
+ return Object.freeze(result);
102
+ }
103
+ function only(input, keys, where) {
104
+ const extra = Object.keys(input).find((name) => !keys.includes(name));
105
+ if (extra)
106
+ throw new ContractIssue(`${where} has an unknown field: ${extra}`);
107
+ }
108
+ function fileUrl(value, where, folder) {
109
+ if (value === undefined)
110
+ return undefined;
111
+ if (!(value instanceof URL) || value.protocol !== 'file:')
112
+ throw new ContractIssue(`${where} must be a file: URL (new URL(…, import.meta.url))`);
113
+ if (folder && !value.pathname.endsWith('/'))
114
+ throw new ContractIssue(`${where} must be a folder URL ending in /`);
115
+ return value;
116
+ }
117
+ const isDeclaration = (value) => value !== null &&
118
+ typeof value === 'object' &&
119
+ typeof value.check === 'function' &&
120
+ typeof value.schema === 'object';
121
+ /** Checks the contract fields of a module definition (names only in messages, never values). */
122
+ export function readContract(module, input) {
123
+ const where = (field) => `${field} of module ${module}`;
124
+ const modules = record(input.modules === undefined
125
+ ? undefined
126
+ : plain(input.modules)
127
+ ? Object.fromEntries(Object.entries(input.modules).map(([name, range]) => [name, { range }]))
128
+ : input.modules, where('modules'), CONTRACT_LIMITS.modules, MODULE_NAME, (item, name) => {
129
+ if (name === module)
130
+ throw new ContractIssue(`${where('modules')} lists the module itself`);
131
+ if (typeof item.range !== 'string' || !RANGE.test(item.range))
132
+ throw new ContractIssue(`${where('modules')}.${name} must be a version range such as ^0.1.0`);
133
+ return item.range;
134
+ });
135
+ let tables = [];
136
+ if (input.tables !== undefined) {
137
+ if (!Array.isArray(input.tables) ||
138
+ types.isProxy(input.tables) ||
139
+ input.tables.length > CONTRACT_LIMITS.tables ||
140
+ input.tables.some((name) => typeof name !== 'string' || !TABLE.test(name)) ||
141
+ new Set(input.tables).size !== input.tables.length)
142
+ throw new ContractIssue(`${where('tables')} must be distinct table names, at most ${CONTRACT_LIMITS.tables}`);
143
+ tables = Object.freeze([...input.tables]);
144
+ }
145
+ const permissions = record(input.permissions, where('permissions'), CONTRACT_LIMITS.permissions, PERMISSION, (item, key) => {
146
+ if (!key.startsWith(`${module}.`))
147
+ throw new ContractIssue(`${where('permissions')}: ${key} must start with ${module}.`);
148
+ only(item, ['title', 'description'], `${where('permissions')}.${key}`);
149
+ return Object.freeze({
150
+ title: text(item.title, `${where('permissions')}.${key}.title`, true),
151
+ ...(item.description === undefined
152
+ ? {}
153
+ : {
154
+ description: text(item.description, `${where('permissions')}.${key}.description`, false),
155
+ }),
156
+ });
157
+ });
158
+ const dataSources = record(input.dataSources, where('dataSources'), CONTRACT_LIMITS.dataSources, LOCAL_NAME, (item, name) => {
159
+ const at = `${where('dataSources')}.${name}`;
160
+ // D-0199: fields, sorts, search, filters, actions, permission, scopes and the reader.
161
+ let rest;
162
+ try {
163
+ rest = readDataSource(item, at, (value, place) => text(value, place, true), (key, place) => {
164
+ if (key.startsWith(`${module}.`) && !Object.hasOwn(permissions, key))
165
+ throw new ContractIssue(`${place} ${key} is not in permissions of module ${module}`);
166
+ });
167
+ }
168
+ catch (error) {
169
+ if (error instanceof DataSourceIssue)
170
+ throw new ContractIssue(error.message);
171
+ throw error;
172
+ }
173
+ return Object.freeze({
174
+ title: text(item.title, `${at}.title`, true),
175
+ ...(item.description === undefined
176
+ ? {}
177
+ : { description: text(item.description, `${at}.description`, false) }),
178
+ ...rest,
179
+ });
180
+ });
181
+ const actions = record(input.actions, where('actions'), CONTRACT_LIMITS.actions, LOCAL_NAME, (item, name) => {
182
+ const at = `${where('actions')}.${name}`;
183
+ // D-0202: input fields, key, version, permission, scopes, danger with preview, and the run.
184
+ let rest;
185
+ try {
186
+ rest = readAction(item, at, (value, place) => text(value, place, true), (key, place) => {
187
+ if (key.startsWith(`${module}.`) && !Object.hasOwn(permissions, key))
188
+ throw new ContractIssue(`${place} ${key} is not in permissions of module ${module}`);
189
+ });
190
+ }
191
+ catch (error) {
192
+ if (error instanceof ActionIssue)
193
+ throw new ContractIssue(error.message);
194
+ throw error;
195
+ }
196
+ return Object.freeze({
197
+ title: text(item.title, `${at}.title`, true),
198
+ ...(item.description === undefined
199
+ ? {}
200
+ : { description: text(item.description, `${at}.description`, false) }),
201
+ ...rest,
202
+ });
203
+ });
204
+ // A row action that names an action of this module (`update` or `<module>.update`) names one it
205
+ // declares; another module's action is checked when the group sets up (D-0202).
206
+ for (const [source, item] of Object.entries(dataSources))
207
+ for (const [name, rowAction] of Object.entries(item.actions ?? {})) {
208
+ const target = rowAction.action;
209
+ if (target === undefined)
210
+ continue;
211
+ const local = target.includes('.')
212
+ ? target.startsWith(`${module}.`)
213
+ ? target.slice(module.length + 1)
214
+ : undefined
215
+ : target;
216
+ if (local !== undefined && !Object.hasOwn(actions, local))
217
+ throw new ContractIssue(`${where('dataSources')}.${source}.actions.${name}.action ${target} is not in actions of module ${module}`);
218
+ }
219
+ const widgets = record(input.widgets, where('widgets'), CONTRACT_LIMITS.widgets, LOCAL_NAME, (item, name) => {
220
+ const at = `${where('widgets')}.${name}`;
221
+ only(item, ['title', 'description', 'settings', 'template', 'load', 'island'], at);
222
+ const island = fileUrl(item.island, `${at}.island`, false);
223
+ if (island && !ISLAND_FILE.test(island.pathname))
224
+ throw new ContractIssue(`${at}.island must be the file: URL of islands/<Name>.vue in the module (PascalCase)`);
225
+ if (item.load !== undefined && typeof item.load !== 'function')
226
+ throw new ContractIssue(`${at}.load must be a function`);
227
+ const template = fileUrl(item.template, `${at}.template`, false);
228
+ if (!template?.pathname.endsWith('.html'))
229
+ throw new ContractIssue(`${at}.template must be the file: URL of a .html file`);
230
+ if (item.settings !== undefined && !isDeclaration(item.settings))
231
+ throw new ContractIssue(`${at}.settings must be a defineOptions declaration`);
232
+ return Object.freeze({
233
+ title: text(item.title, `${at}.title`, true),
234
+ ...(item.description === undefined
235
+ ? {}
236
+ : { description: text(item.description, `${at}.description`, false) }),
237
+ ...(item.settings === undefined
238
+ ? {}
239
+ : { settings: item.settings }),
240
+ template,
241
+ ...(item.load === undefined
242
+ ? {}
243
+ : { load: item.load }),
244
+ ...(island === undefined ? {} : { island }),
245
+ });
246
+ });
247
+ let menu = [];
248
+ if (input.menu !== undefined) {
249
+ if (!Array.isArray(input.menu) || types.isProxy(input.menu))
250
+ throw new ContractIssue(`${where('menu')} must be an array`);
251
+ if (input.menu.length > CONTRACT_LIMITS.menu)
252
+ throw new ContractIssue(`${where('menu')} has more than ${CONTRACT_LIMITS.menu} items`);
253
+ const ids = new Set();
254
+ const items = input.menu.map((value, index) => {
255
+ const at = `${where('menu')}[${index}]`;
256
+ if (!plain(value))
257
+ throw new ContractIssue(`${at} must be an object`);
258
+ only(value, ['id', 'title', 'path', 'icon', 'permission', 'parent', 'order'], at);
259
+ if (typeof value.id !== 'string' || !LOCAL_NAME.test(value.id))
260
+ throw new ContractIssue(`${at}.id must be a lower-case name`);
261
+ if (ids.has(value.id))
262
+ throw new ContractIssue(`${where('menu')} has the id ${value.id} twice`);
263
+ ids.add(value.id);
264
+ if (typeof value.path !== 'string' ||
265
+ value.path.length > 256 ||
266
+ !MENU_PATH.test(value.path) ||
267
+ value.path.split('/').includes('..'))
268
+ throw new ContractIssue(`${at}.path must be '' or /a/path below the mount prefix`);
269
+ if (value.icon !== undefined && (typeof value.icon !== 'string' || !ICON.test(value.icon)))
270
+ throw new ContractIssue(`${at}.icon must be a lower-case icon name`);
271
+ if (value.permission !== undefined) {
272
+ if (typeof value.permission !== 'string' || !PERMISSION.test(value.permission))
273
+ throw new ContractIssue(`${at}.permission must be a permission key`);
274
+ if (value.permission.startsWith(`${module}.`) &&
275
+ !Object.hasOwn(permissions, value.permission))
276
+ throw new ContractIssue(`${at}.permission ${value.permission} is not in permissions of module ${module}`);
277
+ }
278
+ if (value.order !== undefined &&
279
+ (!Number.isInteger(value.order) || Math.abs(value.order) > 1000))
280
+ throw new ContractIssue(`${at}.order must be a whole number from -1000 to 1000`);
281
+ return value;
282
+ });
283
+ menu = Object.freeze(items.map((value, index) => {
284
+ if (value.parent !== undefined &&
285
+ (typeof value.parent !== 'string' || !ids.has(value.parent) || value.parent === value.id))
286
+ throw new ContractIssue(`${where('menu')}[${index}].parent must be the id of another item of the module`);
287
+ return Object.freeze({
288
+ id: value.id,
289
+ title: text(value.title, `${where('menu')}[${index}].title`, true),
290
+ path: value.path,
291
+ ...(value.icon === undefined ? {} : { icon: value.icon }),
292
+ ...(value.permission === undefined ? {} : { permission: value.permission }),
293
+ ...(value.parent === undefined ? {} : { parent: value.parent }),
294
+ order: value.order ?? 0,
295
+ });
296
+ }));
297
+ // A parent chain must end: no item may be its own ancestor.
298
+ const parents = new Map(menu.map((item) => [item.id, item.parent]));
299
+ for (const item of menu) {
300
+ const seen = new Set();
301
+ for (let at = item.id; at !== undefined; at = parents.get(at)) {
302
+ if (seen.has(at))
303
+ throw new ContractIssue(`${where('menu')} nests ${item.id} under itself`);
304
+ seen.add(at);
305
+ }
306
+ }
307
+ }
308
+ const presets = record(input.presets, where('presets'), CONTRACT_LIMITS.presets, LOCAL_NAME, (item, name) => {
309
+ const at = `${where('presets')}.${name}`;
310
+ only(item, ['title', 'kind', 'folder'], at);
311
+ if (typeof item.kind !== 'string' || !PRESET_KINDS.includes(item.kind))
312
+ throw new ContractIssue(`${at}.kind must be ${PRESET_KINDS.join(' or ')}`);
313
+ const folder = fileUrl(item.folder, `${at}.folder`, true);
314
+ if (!folder)
315
+ throw new ContractIssue(`${at}.folder must be a folder URL ending in /`);
316
+ return Object.freeze({
317
+ title: text(item.title, `${at}.title`, true),
318
+ kind: item.kind,
319
+ folder,
320
+ });
321
+ });
322
+ const settings = input.settings;
323
+ if (settings !== undefined &&
324
+ (settings === null ||
325
+ typeof settings !== 'object' ||
326
+ typeof settings.section !== 'string' ||
327
+ typeof settings.read !== 'function' ||
328
+ !isDeclaration(settings.options)))
329
+ throw new ContractIssue(`${where('settings')} must be a defineSettings result of @dokebi/core`);
330
+ return Object.freeze({
331
+ title: text(input.title, where('title'), false),
332
+ description: text(input.description, where('description'), false),
333
+ modules,
334
+ db: fileUrl(input.db, where('db'), true),
335
+ tables,
336
+ permissions,
337
+ dataSources,
338
+ actions,
339
+ widgets,
340
+ menu,
341
+ settings,
342
+ locales: fileUrl(input.locales, where('locales'), true),
343
+ parts: partsFile(input.parts, where('parts')),
344
+ presets,
345
+ });
346
+ }
347
+ /** Checks the folder of every preset (preset.ts) and gives its files, by preset name. */
348
+ export async function readPresets(module, presets) {
349
+ const files = {};
350
+ for (const [name, item] of Object.entries(presets)) {
351
+ try {
352
+ files[name] = await readPreset(item.folder, `preset ${name} of module ${module}`);
353
+ }
354
+ catch (error) {
355
+ if (error instanceof PresetIssue)
356
+ throw new ContractIssue(error.message);
357
+ throw error;
358
+ }
359
+ }
360
+ return files;
361
+ }
362
+ function partsFile(value, where) {
363
+ const file = fileUrl(value, where, false);
364
+ if (file && !file.pathname.endsWith('.json'))
365
+ throw new ContractIssue(`${where} must be the file: URL of a .json file`);
366
+ return file;
367
+ }
368
+ /** The first HTML of a widget: a UTF-8 file of at most CONTRACT_LIMITS.templateBytes. */
369
+ export async function readTemplate(template) {
370
+ const path = fileURLToPath(template);
371
+ const info = await stat(path);
372
+ if (!info.isFile())
373
+ throw new ContractIssue(`${path} is not a file`);
374
+ if (info.size > CONTRACT_LIMITS.templateBytes)
375
+ throw new ContractIssue(`${path} is larger than ${CONTRACT_LIMITS.templateBytes} bytes`);
376
+ const bytes = await readFile(path);
377
+ const html = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
378
+ return html;
379
+ }
380
+ /** File names (without extension) per sub-folder: `{ main: ['20261101000000_members'] }`. */
381
+ async function namesPerFolder(folder, file) {
382
+ const result = {};
383
+ let folders;
384
+ try {
385
+ folders = (await readdir(folder, { withFileTypes: true }))
386
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
387
+ .map((entry) => entry.name)
388
+ .sort();
389
+ }
390
+ catch (error) {
391
+ if (error.code === 'ENOENT')
392
+ return result;
393
+ throw error;
394
+ }
395
+ for (const name of folders) {
396
+ const files = (await readdir(join(folder, name), { withFileTypes: true }))
397
+ .filter((entry) => entry.isFile() && file.test(entry.name))
398
+ .map((entry) => entry.name.replace(file, '$1'))
399
+ .sort()
400
+ .slice(0, CONTRACT_LIMITS.describedFiles);
401
+ result[name] = files;
402
+ }
403
+ return result;
404
+ }
405
+ const json = (value) => JSON.parse(JSON.stringify(value));
406
+ function describeAction(module, name, item) {
407
+ return {
408
+ id: `${module}.${name}`,
409
+ name,
410
+ title: item.title,
411
+ ...(item.description === undefined ? {} : { description: item.description }),
412
+ input: json(item.input ?? {}),
413
+ schema: inputSchema(item),
414
+ ...(item.key === undefined ? {} : { key: item.key }),
415
+ ...(item.version === undefined ? {} : { version: item.version }),
416
+ permission: item.permission,
417
+ ...(item.scopes === undefined ? {} : { scopes: [...item.scopes] }),
418
+ danger: item.danger === true,
419
+ };
420
+ }
421
+ function describeDataSource(module, name, item) {
422
+ const base = {
423
+ id: `${module}.${name}`,
424
+ name,
425
+ title: item.title,
426
+ ...(item.description === undefined ? {} : { description: item.description }),
427
+ };
428
+ if (!item.read)
429
+ return { ...base, readable: false };
430
+ const fields = Object.fromEntries(Object.entries(item.fields ?? {})
431
+ .filter(([, field]) => !field.hidden)
432
+ .map(([field, value]) => [field, json(value)]));
433
+ return {
434
+ ...base,
435
+ readable: true,
436
+ fields,
437
+ sorts: json(item.sorts),
438
+ ...(item.search === undefined ? {} : { search: json(item.search) }),
439
+ filters: json(item.filters),
440
+ actions: json(item.actions),
441
+ ...(item.permission === undefined ? {} : { permission: item.permission }),
442
+ ...(item.public === true ? { public: true } : {}),
443
+ ...(item.scopes === undefined ? {} : { scopes: [...item.scopes] }),
444
+ limit: json(item.limit),
445
+ };
446
+ }
447
+ const where = (url) => relative(process.cwd(), fileURLToPath(url)).split('\\').join('/') || '.';
448
+ export async function describeContract(input) {
449
+ const { name, contract } = input;
450
+ const db = contract.db
451
+ ? {
452
+ folder: where(contract.db),
453
+ migrations: await namesPerFolder(fileURLToPath(new URL('migrations/', contract.db)), /^(\d{14}_[a-z0-9]+(?:_[a-z0-9]+)*)\.(?:ts|mts|js|mjs)$/),
454
+ seeds: await namesPerFolder(fileURLToPath(new URL('seeds/', contract.db)), /^([a-z0-9]+(?:[_-][a-z0-9]+)*)\.(?:ts|mts|js|mjs)$/),
455
+ }
456
+ : null;
457
+ const locales = contract.locales
458
+ ? {
459
+ folder: where(contract.locales),
460
+ languages: await namesPerFolder(fileURLToPath(contract.locales), /^([a-z][a-z0-9-]{0,63})\.json$/),
461
+ }
462
+ : null;
463
+ const widgets = [];
464
+ for (const [widget, item] of Object.entries(contract.widgets))
465
+ widgets.push({
466
+ id: `${name}.${widget}`,
467
+ name: widget,
468
+ title: item.title,
469
+ ...(item.description === undefined ? {} : { description: item.description }),
470
+ settings: item.settings ? json(item.settings.schema) : null,
471
+ template: await readTemplate(item.template),
472
+ island: item.island ? islandName(name, item.island) : null,
473
+ });
474
+ let parts = null;
475
+ if (contract.parts) {
476
+ try {
477
+ parts = {
478
+ file: where(contract.parts),
479
+ parts: (await readParts(contract.parts, Object.keys(contract.widgets))).parts,
480
+ };
481
+ }
482
+ catch (error) {
483
+ // A broken parts file is a broken contract (INVALID_CONTRACT), with the file's own message.
484
+ if (error instanceof PartsIssue)
485
+ throw new ContractIssue(`parts of module ${name}: ${error.message}`);
486
+ throw error;
487
+ }
488
+ }
489
+ const presetFiles = await readPresets(name, contract.presets);
490
+ const presets = Object.entries(contract.presets).map(([preset, item]) => ({
491
+ id: `${name}.${preset}`,
492
+ name: preset,
493
+ title: item.title,
494
+ kind: item.kind,
495
+ folder: where(item.folder),
496
+ files: [...(presetFiles[preset] ?? [])],
497
+ }));
498
+ return {
499
+ name,
500
+ version: input.version,
501
+ title: contract.title ?? null,
502
+ description: contract.description ?? null,
503
+ requires: [...input.requires],
504
+ modules: { ...contract.modules },
505
+ tables: [...contract.tables],
506
+ db,
507
+ permissions: Object.entries(contract.permissions).map(([key, item]) => ({ key, ...item })),
508
+ dataSources: Object.entries(contract.dataSources).map(([source, item]) => describeDataSource(name, source, item)),
509
+ actions: Object.entries(contract.actions).map(([action, item]) => describeAction(name, action, item)),
510
+ widgets,
511
+ menu: json(contract.menu),
512
+ settings: contract.settings
513
+ ? { section: contract.settings.section, schema: json(contract.settings.options.schema) }
514
+ : null,
515
+ locales,
516
+ parts,
517
+ presets,
518
+ contributes: [...input.contributes],
519
+ views: input.views ?? null,
520
+ routes: input.hooks.routes,
521
+ sockets: input.hooks.sockets,
522
+ events: input.hooks.events,
523
+ };
524
+ }
@@ -0,0 +1,49 @@
1
+ import { DokebiError, type Logger } from '@dokebi/core';
2
+ import { type DataField, type DataRow, type ModuleDataSource } from './data-source.js';
3
+ /** Codes of the data source read (`DokebiError`, `plugin: 'dokebi-module'`). */
4
+ export type DataErrorCode = 'DATA_SOURCE_NOT_FOUND' | 'FORBIDDEN' | 'INVALID_QUERY' | 'INVALID_CURSOR' | 'DATA_SOURCE_FAILED';
5
+ export declare function dataError(code: DataErrorCode, message: string, data?: Readonly<Record<string, unknown>>, cause?: unknown): DokebiError<DataErrorCode>;
6
+ /** One page of a data source. */
7
+ export interface DataPage {
8
+ /** `<module>.<name>`. */
9
+ readonly source: string;
10
+ /** The sort used (the scope's default when none was asked for). */
11
+ readonly sort: string;
12
+ /** The chosen fields of each row, in the sort order (a missing value is null). */
13
+ readonly rows: readonly DataRow[];
14
+ /** The cursor of the next page, or null on the last one. There is no total count. */
15
+ readonly next: string | null;
16
+ }
17
+ /** The app router as @dokebi/app hands it to `routes(route, app)` (typed by shape). */
18
+ export interface DataRouter {
19
+ get(url: string, handler: DataHandler, options?: {
20
+ readonly config?: Readonly<Record<string, unknown>>;
21
+ }): void;
22
+ }
23
+ /** A route handler (Fastify request and reply), method-typed so any app router accepts it. */
24
+ export type DataHandler = {
25
+ handle(request: unknown, reply: unknown, page: unknown): unknown;
26
+ }['handle'];
27
+ /** The data sources of the module group (`ModuleGroupApi.data`, D-0199). */
28
+ export interface DataApi {
29
+ /** The ids of the data sources that can be read (`members.list`). */
30
+ readonly ids: readonly string[];
31
+ /**
32
+ * Reads one page of data source `id` for `request` (its `auth` decides the permission; the
33
+ * data source's `scope` the scope) with `query` as a query string gives it: `fields`, `sort`,
34
+ * `limit`, `cursor`, `q`, `filter.<name>`, `filter.<name>.from`, `filter.<name>.to`.
35
+ */
36
+ read(request: unknown, id: string, query: Readonly<Record<string, unknown>>): Promise<DataPage>;
37
+ /** Adds `GET <path>/:module/:source` (route id `module.data`) answering `read` as JSON. */
38
+ routes(route: DataRouter, options?: {
39
+ readonly path?: string;
40
+ }): void;
41
+ }
42
+ interface Source {
43
+ readonly module: string;
44
+ readonly declaration: ModuleDataSource;
45
+ context(): unknown;
46
+ }
47
+ export declare function createDataApi(sources: ReadonlyMap<string, Source>, logger: Logger): DataApi;
48
+ /** For tests: the field kinds a cursor value is checked against. */
49
+ export type { DataField };