adula 0.0.0-stage → 2.0.0

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.
Files changed (210) hide show
  1. package/LICENSE.md +10 -0
  2. package/README.md +40 -2
  3. package/build/agent/AGENTS.template.md +28 -0
  4. package/build/agent/capabilities.md +60 -0
  5. package/build/agent/skills/adula-frontend-design/SKILL.md +59 -0
  6. package/build/agent/skills/idea-review/SKILL.md +31 -0
  7. package/build/agent/skills/module-review/SKILL.md +22 -0
  8. package/build/agent/skills/perf-review/SKILL.md +24 -0
  9. package/build/agent/skills/schema-review/SKILL.md +22 -0
  10. package/build/agent/skills/security-review/SKILL.md +24 -0
  11. package/build/agent/skills/ui-review/SKILL.md +22 -0
  12. package/build/commands/capabilities.d.ts +10 -0
  13. package/build/commands/capabilities.js +40 -0
  14. package/build/commands/doctor.d.ts +9 -0
  15. package/build/commands/doctor.js +72 -0
  16. package/build/commands/gaps.d.ts +12 -0
  17. package/build/commands/gaps.js +62 -0
  18. package/build/commands/install.d.ts +9 -0
  19. package/build/commands/install.js +105 -0
  20. package/build/commands/main.d.ts +8 -0
  21. package/build/commands/main.js +33 -0
  22. package/build/commands/module_add.d.ts +8 -0
  23. package/build/commands/module_add.js +57 -0
  24. package/build/commands/module_remove.d.ts +10 -0
  25. package/build/commands/module_remove.js +94 -0
  26. package/build/commands/resource.d.ts +8 -0
  27. package/build/commands/resource.js +29 -0
  28. package/build/commands/resource_snapshot.d.ts +15 -0
  29. package/build/commands/resource_snapshot.js +61 -0
  30. package/build/commands/storage_migrate.d.ts +12 -0
  31. package/build/commands/storage_migrate.js +39 -0
  32. package/build/commands/ui.d.ts +11 -0
  33. package/build/commands/ui.js +210 -0
  34. package/build/commands/upgrade.d.ts +15 -0
  35. package/build/commands/upgrade.js +34 -0
  36. package/build/configure.d.ts +2 -0
  37. package/build/configure.js +79 -0
  38. package/build/database/migrations/1770000000000_core.d.ts +5 -0
  39. package/build/database/migrations/1770000000000_core.js +10 -0
  40. package/build/database/migrations/1770000000001_attachments.d.ts +5 -0
  41. package/build/database/migrations/1770000000001_attachments.js +10 -0
  42. package/build/database/migrations/1770000000002_saved_views.d.ts +5 -0
  43. package/build/database/migrations/1770000000002_saved_views.js +10 -0
  44. package/build/database/migrations/1770000000003_user_invitations.d.ts +5 -0
  45. package/build/database/migrations/1770000000003_user_invitations.js +18 -0
  46. package/build/database/migrations/1770000000004_collaboration.d.ts +5 -0
  47. package/build/database/migrations/1770000000004_collaboration.js +10 -0
  48. package/build/database/migrations/1770000000005_assignments.d.ts +5 -0
  49. package/build/database/migrations/1770000000005_assignments.js +10 -0
  50. package/build/database/migrations/1770000000006_messaging.d.ts +5 -0
  51. package/build/database/migrations/1770000000006_messaging.js +10 -0
  52. package/build/database/migrations/1770000000007_webhooks.d.ts +5 -0
  53. package/build/database/migrations/1770000000007_webhooks.js +10 -0
  54. package/build/database/migrations/1770000000008_imports.d.ts +5 -0
  55. package/build/database/migrations/1770000000008_imports.js +10 -0
  56. package/build/database/migrations/1770000000010_workflows.d.ts +5 -0
  57. package/build/database/migrations/1770000000010_workflows.js +10 -0
  58. package/build/database/migrations/1770000000011_managed_assignments.d.ts +5 -0
  59. package/build/database/migrations/1770000000011_managed_assignments.js +10 -0
  60. package/build/database/migrations/1770000000012_role_keys.d.ts +5 -0
  61. package/build/database/migrations/1770000000012_role_keys.js +10 -0
  62. package/build/database/migrations/1770000000013_notification_targets.d.ts +5 -0
  63. package/build/database/migrations/1770000000013_notification_targets.js +10 -0
  64. package/build/database/migrations/1770000000014_upload_grants.d.ts +5 -0
  65. package/build/database/migrations/1770000000014_upload_grants.js +10 -0
  66. package/build/database/migrations/1770000000015_inbound_webhooks.d.ts +5 -0
  67. package/build/database/migrations/1770000000015_inbound_webhooks.js +10 -0
  68. package/build/database/migrations/1770000000016_adulajs_names.d.ts +6 -0
  69. package/build/database/migrations/1770000000016_adulajs_names.js +11 -0
  70. package/build/index.d.ts +80 -0
  71. package/build/index.js +49 -0
  72. package/build/providers/adula_provider.d.ts +6 -0
  73. package/build/providers/adula_provider.js +10 -0
  74. package/build/src/admin/contracts.d.ts +19 -0
  75. package/build/src/admin/contracts.js +115 -0
  76. package/build/src/admin/controller.d.ts +32 -0
  77. package/build/src/admin/controller.js +167 -0
  78. package/build/src/admin/errors.d.ts +5 -0
  79. package/build/src/admin/errors.js +9 -0
  80. package/build/src/admin/presentation.d.ts +28 -0
  81. package/build/src/admin/presentation.js +1 -0
  82. package/build/src/admin/record_title.d.ts +14 -0
  83. package/build/src/admin/record_title.js +50 -0
  84. package/build/src/admin/resource_service.d.ts +376 -0
  85. package/build/src/admin/resource_service.js +1448 -0
  86. package/build/src/attachments/attachment_service.d.ts +100 -0
  87. package/build/src/attachments/attachment_service.js +270 -0
  88. package/build/src/attachments/doctor.d.ts +4 -0
  89. package/build/src/attachments/doctor.js +28 -0
  90. package/build/src/attachments/storage_migrate.d.ts +39 -0
  91. package/build/src/attachments/storage_migrate.js +64 -0
  92. package/build/src/attachments/upload_grants.d.ts +44 -0
  93. package/build/src/attachments/upload_grants.js +105 -0
  94. package/build/src/auth/ability.d.ts +24 -0
  95. package/build/src/auth/ability.js +34 -0
  96. package/build/src/auth/actor_store.d.ts +14 -0
  97. package/build/src/auth/actor_store.js +70 -0
  98. package/build/src/auth/conditions.d.ts +26 -0
  99. package/build/src/auth/conditions.js +117 -0
  100. package/build/src/auth/packed_rules.d.ts +4 -0
  101. package/build/src/auth/packed_rules.js +13 -0
  102. package/build/src/auth/sql.d.ts +11 -0
  103. package/build/src/auth/sql.js +118 -0
  104. package/build/src/collaboration/assignments.d.ts +129 -0
  105. package/build/src/collaboration/assignments.js +333 -0
  106. package/build/src/collaboration/record_collaboration.d.ts +86 -0
  107. package/build/src/collaboration/record_collaboration.js +348 -0
  108. package/build/src/commands/agent_assets.d.ts +7 -0
  109. package/build/src/commands/agent_assets.js +66 -0
  110. package/build/src/commands/capabilities.d.ts +19 -0
  111. package/build/src/commands/capabilities.js +179 -0
  112. package/build/src/commands/doctor.d.ts +42 -0
  113. package/build/src/commands/doctor.js +375 -0
  114. package/build/src/commands/gap_report.d.ts +56 -0
  115. package/build/src/commands/gap_report.js +110 -0
  116. package/build/src/commands/generator.d.ts +1 -0
  117. package/build/src/commands/generator.js +70 -0
  118. package/build/src/commands/snapshot.d.ts +28 -0
  119. package/build/src/commands/snapshot.js +48 -0
  120. package/build/src/commands/source_markers.d.ts +11 -0
  121. package/build/src/commands/source_markers.js +41 -0
  122. package/build/src/core/activity.d.ts +43 -0
  123. package/build/src/core/activity.js +77 -0
  124. package/build/src/core/administration_guard.d.ts +3 -0
  125. package/build/src/core/administration_guard.js +39 -0
  126. package/build/src/core/health.d.ts +42 -0
  127. package/build/src/core/health.js +44 -0
  128. package/build/src/core/mail_test.d.ts +18 -0
  129. package/build/src/core/mail_test.js +88 -0
  130. package/build/src/core/message_templates.d.ts +83 -0
  131. package/build/src/core/message_templates.js +293 -0
  132. package/build/src/core/module_seed.d.ts +15 -0
  133. package/build/src/core/module_seed.js +31 -0
  134. package/build/src/core/notifications.d.ts +42 -0
  135. package/build/src/core/notifications.js +91 -0
  136. package/build/src/core/org_units.d.ts +30 -0
  137. package/build/src/core/org_units.js +123 -0
  138. package/build/src/core/roles.d.ts +98 -0
  139. package/build/src/core/roles.js +447 -0
  140. package/build/src/core/saved_views.d.ts +37 -0
  141. package/build/src/core/saved_views.js +164 -0
  142. package/build/src/core/settings.d.ts +29 -0
  143. package/build/src/core/settings.js +113 -0
  144. package/build/src/core/setup.d.ts +14 -0
  145. package/build/src/core/setup.js +89 -0
  146. package/build/src/core/ui_preferences.d.ts +12 -0
  147. package/build/src/core/ui_preferences.js +30 -0
  148. package/build/src/core/user_invitations.d.ts +23 -0
  149. package/build/src/core/user_invitations.js +144 -0
  150. package/build/src/core/users.d.ts +44 -0
  151. package/build/src/core/users.js +182 -0
  152. package/build/src/database/configure.d.ts +3 -0
  153. package/build/src/database/configure.js +41 -0
  154. package/build/src/database/schema.d.ts +52 -0
  155. package/build/src/database/schema.js +538 -0
  156. package/build/src/eslint/index.d.ts +3 -0
  157. package/build/src/eslint/index.js +90 -0
  158. package/build/src/events/adonis_jobs.d.ts +9 -0
  159. package/build/src/events/adonis_jobs.js +13 -0
  160. package/build/src/events/outbox.d.ts +19 -0
  161. package/build/src/events/outbox.js +33 -0
  162. package/build/src/events/record_mutation.d.ts +24 -0
  163. package/build/src/events/record_mutation.js +62 -0
  164. package/build/src/integrations/imports.d.ts +74 -0
  165. package/build/src/integrations/imports.js +333 -0
  166. package/build/src/integrations/inbound_webhooks.d.ts +94 -0
  167. package/build/src/integrations/inbound_webhooks.js +276 -0
  168. package/build/src/integrations/openapi.d.ts +39 -0
  169. package/build/src/integrations/openapi.js +323 -0
  170. package/build/src/integrations/print.d.ts +37 -0
  171. package/build/src/integrations/print.js +124 -0
  172. package/build/src/integrations/webhooks.d.ts +98 -0
  173. package/build/src/integrations/webhooks.js +298 -0
  174. package/build/src/mcp/tools.d.ts +8 -0
  175. package/build/src/mcp/tools.js +156 -0
  176. package/build/src/org/org_service.d.ts +2 -0
  177. package/build/src/org/org_service.js +16 -0
  178. package/build/src/resource/define_resource.d.ts +5 -0
  179. package/build/src/resource/define_resource.js +68 -0
  180. package/build/src/resource/registry.d.ts +12 -0
  181. package/build/src/resource/registry.js +101 -0
  182. package/build/src/resource/types.d.ts +155 -0
  183. package/build/src/resource/types.js +1 -0
  184. package/build/src/resource/values.d.ts +5 -0
  185. package/build/src/resource/values.js +88 -0
  186. package/build/src/services/backup.d.ts +14 -0
  187. package/build/src/services/backup.js +59 -0
  188. package/build/src/services/settings.d.ts +21 -0
  189. package/build/src/services/settings.js +30 -0
  190. package/build/src/upgrade/legacy.d.ts +27 -0
  191. package/build/src/upgrade/legacy.js +58 -0
  192. package/build/src/upgrade/rename.d.ts +17 -0
  193. package/build/src/upgrade/rename.js +94 -0
  194. package/build/src/version.d.ts +1 -0
  195. package/build/src/version.js +2 -0
  196. package/build/src/workflows/define_workflow.d.ts +124 -0
  197. package/build/src/workflows/define_workflow.js +123 -0
  198. package/build/src/workflows/engine.d.ts +141 -0
  199. package/build/src/workflows/engine.js +752 -0
  200. package/build/stubs/README.md +6 -0
  201. package/build/stubs/controller.stub +8 -0
  202. package/build/stubs/main.d.ts +5 -0
  203. package/build/stubs/main.js +5 -0
  204. package/build/stubs/main.ts +5 -0
  205. package/build/stubs/modules.stub +6 -0
  206. package/build/stubs/resource_contract.stub +1 -0
  207. package/build/stubs/resource_contract.txt +452 -0
  208. package/build/stubs/routes.stub +16 -0
  209. package/build/stubs/service.stub +9 -0
  210. package/package.json +95 -3
@@ -0,0 +1,156 @@
1
+ import { Tool } from '@jrmc/adonis-mcp';
2
+ import { AdulaError } from '../admin/errors.js';
3
+ function object(value) {
4
+ if (!value || typeof value !== 'object' || Array.isArray(value))
5
+ throw new AdulaError(422, 'E_INPUT', 'Expected an object');
6
+ return value;
7
+ }
8
+ function recordId(value) {
9
+ if (!Number.isSafeInteger(value) || Number(value) < 1)
10
+ throw new AdulaError(422, 'E_ID', 'Expected a positive integer record ID');
11
+ return Number(value);
12
+ }
13
+ /** Optional MCP adapter. Actor identity comes only from the host's authenticated context. */
14
+ export function createResourceTools(resolveRuntime) {
15
+ async function execute(context, write) {
16
+ try {
17
+ const args = object(context.args);
18
+ const accepted = write
19
+ ? ['resource', 'action', 'id', 'input', 'version']
20
+ : ['resource', 'action', 'id', 'options'];
21
+ if (Object.keys(args).some((key) => !accepted.includes(key)))
22
+ throw new AdulaError(422, 'E_INPUT', 'Unknown tool argument');
23
+ const runtime = await resolveRuntime(context);
24
+ if (typeof args.resource !== 'string' ||
25
+ !runtime.registry.all().some((r) => r.name === args.resource))
26
+ throw new AdulaError(404, 'E_NOT_FOUND', 'الكيان غير موجود');
27
+ const name = args.resource;
28
+ const { resources, actor } = runtime;
29
+ let result;
30
+ if (!write && args.action === 'list') {
31
+ const options = args.options === undefined ? {} : object(args.options);
32
+ if (Object.keys(options).some((key) => !['limit', 'cursor', 'search', 'sort', 'direction', 'filters', 'estimate'].includes(key)))
33
+ throw new AdulaError(422, 'E_INPUT', 'Unknown list option');
34
+ for (const key of ['cursor', 'search', 'sort'])
35
+ if (options[key] !== undefined && typeof options[key] !== 'string')
36
+ throw new AdulaError(422, 'E_INPUT', `Invalid ${key}`);
37
+ if ((options.limit !== undefined && !Number.isSafeInteger(options.limit)) ||
38
+ (options.direction !== undefined &&
39
+ !['asc', 'desc'].includes(String(options.direction))) ||
40
+ (options.estimate !== undefined && typeof options.estimate !== 'boolean'))
41
+ throw new AdulaError(422, 'E_INPUT', 'Invalid list options');
42
+ if (options.filters !== undefined)
43
+ object(options.filters);
44
+ result = await resources.list(name, actor, options);
45
+ }
46
+ else if (!write && args.action === 'show') {
47
+ result = await resources.show(name, recordId(args.id), actor);
48
+ }
49
+ else if (!write && args.action === 'editor') {
50
+ result = await resources.editor(name, actor, args.id === undefined ? undefined : recordId(args.id));
51
+ }
52
+ else if (write && (args.action === 'create' || args.action === 'update')) {
53
+ if (args.action === 'create' && args.id !== undefined)
54
+ throw new AdulaError(422, 'E_INPUT', 'Create cannot specify an ID');
55
+ result = {
56
+ data: await resources.save(name, actor, object(args.input), args.action === 'update' ? recordId(args.id) : undefined),
57
+ };
58
+ }
59
+ else if (write &&
60
+ (args.action === 'delete' || args.action === 'submit' || args.action === 'cancel')) {
61
+ result = {
62
+ data: await resources.transition(name, recordId(args.id), actor, args.action, args.version),
63
+ };
64
+ }
65
+ else
66
+ throw new AdulaError(422, 'E_ACTION', 'Unsupported resource action');
67
+ return context.response.text(JSON.stringify(result));
68
+ }
69
+ catch (error) {
70
+ if (error instanceof AdulaError)
71
+ return context.response.error(JSON.stringify({ status: error.status, code: error.code, message: error.message }));
72
+ if (error?.code === 'E_VALIDATION_ERROR')
73
+ return context.response.error(JSON.stringify({
74
+ status: 422,
75
+ code: 'E_VALIDATION_ERROR',
76
+ messages: error.messages,
77
+ }));
78
+ if (['23505', '23503'].includes(error?.code ?? ''))
79
+ return context.response.error(JSON.stringify({
80
+ status: 422,
81
+ code: 'E_CONSTRAINT',
82
+ message: 'تحقق من القيم والسجلات المرتبطة',
83
+ }));
84
+ // Do not put database statements, credentials or stack traces on the wire.
85
+ return context.response.error(JSON.stringify({ status: 500, code: 'E_INTERNAL', message: 'تعذر إتمام العملية' }));
86
+ }
87
+ }
88
+ class ResourceReadTool extends Tool {
89
+ name = 'adula_resource_read';
90
+ title = 'Read authorized resources';
91
+ description = 'List or show records, or obtain an authorized editor schema. Organizational scope and field permissions always apply.';
92
+ annotations = {
93
+ readOnlyHint: true,
94
+ destructiveHint: false,
95
+ idempotentHint: true,
96
+ openWorldHint: false,
97
+ };
98
+ schema() {
99
+ return {
100
+ type: 'object',
101
+ additionalProperties: false,
102
+ properties: {
103
+ resource: { type: 'string' },
104
+ action: { type: 'string', enum: ['list', 'show', 'editor'] },
105
+ id: { type: 'integer', minimum: 1 },
106
+ options: {
107
+ type: 'object',
108
+ properties: {
109
+ limit: { type: 'integer', minimum: 1, maximum: 100 },
110
+ cursor: { type: 'string' },
111
+ search: { type: 'string' },
112
+ sort: { type: 'string' },
113
+ direction: { type: 'string', enum: ['asc', 'desc'] },
114
+ filters: { type: 'object', properties: {}, additionalProperties: true },
115
+ estimate: { type: 'boolean' },
116
+ },
117
+ additionalProperties: false,
118
+ },
119
+ },
120
+ required: ['resource', 'action'],
121
+ };
122
+ }
123
+ async handle(context) {
124
+ return execute(context, false);
125
+ }
126
+ }
127
+ class ResourceWriteTool extends Tool {
128
+ name = 'adula_resource_write';
129
+ title = 'Change authorized resources';
130
+ description = 'Create, update, soft-delete, submit or cancel a record. Use editor metadata; update input must include the current version. Transition version is a top-level argument. Writes generate activity and outbox events atomically.';
131
+ annotations = {
132
+ readOnlyHint: false,
133
+ destructiveHint: true,
134
+ idempotentHint: false,
135
+ openWorldHint: false,
136
+ };
137
+ schema() {
138
+ return {
139
+ type: 'object',
140
+ additionalProperties: false,
141
+ properties: {
142
+ resource: { type: 'string' },
143
+ action: { type: 'string', enum: ['create', 'update', 'delete', 'submit', 'cancel'] },
144
+ id: { type: 'integer', minimum: 1 },
145
+ input: { type: 'object', properties: {}, additionalProperties: true },
146
+ version: { type: 'integer', minimum: 1 },
147
+ },
148
+ required: ['resource', 'action'],
149
+ };
150
+ }
151
+ async handle(context) {
152
+ return execute(context, true);
153
+ }
154
+ }
155
+ return { ResourceReadTool, ResourceWriteTool };
156
+ }
@@ -0,0 +1,2 @@
1
+ import type { Knex } from 'knex';
2
+ export declare function moveOrgUnit(db: Knex, id: number, parentId: number | null): Promise<void>;
@@ -0,0 +1,16 @@
1
+ import { AdulaError } from '../admin/errors.js';
2
+ export async function moveOrgUnit(db, id, parentId) {
3
+ await db.transaction(async (trx) => {
4
+ // Serialize tree edits; concurrent sibling/ancestor moves cannot corrupt paths.
5
+ await trx.raw('SELECT pg_advisory_xact_lock(717010)');
6
+ const unit = await trx('org_units').where({ id }).forUpdate().first();
7
+ const parent = parentId === null ? null : await trx('org_units').where({ id: parentId }).forUpdate().first();
8
+ if (!unit || (parentId !== null && !parent))
9
+ throw new AdulaError(404, 'E_ORG_NOT_FOUND', 'Organization unit not found');
10
+ if (parent && (parent.path === unit.path || parent.path.startsWith(`${unit.path}.`)))
11
+ throw new AdulaError(422, 'E_ORG_CYCLE', 'A unit cannot move beneath itself');
12
+ const next = parent ? `${parent.path}.${id}` : `${id}`;
13
+ await trx.raw('UPDATE org_units SET path = ?::ltree || subpath(path,nlevel(?::ltree)) WHERE path <@ ?::ltree AND id <> ?', [next, unit.path, unit.path, id]);
14
+ await trx('org_units').where({ id }).update({ parent_id: parentId, path: next });
15
+ });
16
+ }
@@ -0,0 +1,5 @@
1
+ import type { Field, Resource, ResourceInput } from './types.js';
2
+ export declare function identifier(value: string): string;
3
+ /** camelCase field key → snake_case column; validated once and memoized (hot in row mapping). */
4
+ export declare function columnName(name: string): string;
5
+ export declare function defineResource<const F extends Record<string, Field>>(input: ResourceInput<F>): ResourceInput<F> & Resource;
@@ -0,0 +1,68 @@
1
+ import { assertTitle } from '../admin/record_title.js';
2
+ export function identifier(value) {
3
+ if (!/^[a-z][a-z0-9_]*$/.test(value))
4
+ throw new Error(`Unsafe SQL identifier: ${value}`);
5
+ return value;
6
+ }
7
+ const columns = new Map();
8
+ /** camelCase field key → snake_case column; validated once and memoized (hot in row mapping). */
9
+ export function columnName(name) {
10
+ const cached = columns.get(name);
11
+ if (cached !== undefined)
12
+ return cached;
13
+ const column = identifier(name.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`));
14
+ if (columns.size < 10000)
15
+ columns.set(name, column);
16
+ return column;
17
+ }
18
+ export function defineResource(input) {
19
+ identifier(input.name);
20
+ if (typeof input.scoped !== 'boolean')
21
+ throw new Error(`${input.name}: scoped must be explicit`);
22
+ if (!input.label.ar || !input.label.en)
23
+ throw new Error('Bilingual labels are required');
24
+ for (const optional of [input.recordLabel, input.createLabel])
25
+ if (optional && (!optional.ar || !optional.en))
26
+ throw new Error(`${input.name}: recordLabel and createLabel need Arabic and English`);
27
+ for (const [key, field] of Object.entries(input.fields)) {
28
+ columnName(key);
29
+ identifier(field.column ?? columnName(key));
30
+ if ([
31
+ 'id',
32
+ 'orgUnitId',
33
+ 'createdBy',
34
+ 'updatedBy',
35
+ 'createdAt',
36
+ 'updatedAt',
37
+ 'deletedAt',
38
+ 'version',
39
+ 'docStatus',
40
+ 'amendedFromId',
41
+ ].includes(key))
42
+ throw new Error(`Reserved field: ${key}`);
43
+ if (!field.label.ar || !field.label.en)
44
+ throw new Error(`${key}: bilingual labels are required`);
45
+ }
46
+ for (const keys of [
47
+ input.list,
48
+ input.form,
49
+ input.show,
50
+ input.hidden ?? [],
51
+ input.serialize ?? [],
52
+ ]) {
53
+ for (const key of keys)
54
+ if (!(key in input.fields))
55
+ throw new Error(`Unknown field: ${key}`);
56
+ }
57
+ if (input.scope) {
58
+ const parent = input.fields[input.scope.from];
59
+ if (!input.scoped)
60
+ throw new Error(`${input.name}: scope.from requires scoped: true`);
61
+ if (parent?.type !== 'belongsTo' || !parent.required)
62
+ throw new Error(`${input.name}: scope.from must name a required belongsTo field`);
63
+ }
64
+ assertTitle(input);
65
+ if (!input.submittable && input.actions.some((a) => ['submit', 'cancel', 'amend'].includes(a)))
66
+ throw new Error('Document actions require submittable');
67
+ return Object.freeze({ ...input, version: input.version ?? input.submittable ?? false });
68
+ }
@@ -0,0 +1,12 @@
1
+ import type { Module, Resource } from './types.js';
2
+ export declare class ResourceRegistry {
3
+ #private;
4
+ register(modules: readonly Module[]): this;
5
+ get(name: string): Resource;
6
+ has(name: string): boolean;
7
+ all(): Resource[];
8
+ owner(name: string): string;
9
+ modules(): Module[];
10
+ /** Workflow definitions declared by registered modules, validated against their resources. */
11
+ workflows(): import("../workflows/define_workflow.ts").WorkflowDefinition[];
12
+ }
@@ -0,0 +1,101 @@
1
+ import { identifier } from './define_resource.js';
2
+ export class ResourceRegistry {
3
+ #resources = new Map();
4
+ #owners = new Map();
5
+ #modules = new Map();
6
+ register(modules) {
7
+ const next = new ResourceRegistry();
8
+ for (const module of modules) {
9
+ identifier(module.name);
10
+ if (next.#modules.has(module.name))
11
+ throw new Error(`Duplicate module: ${module.name}`);
12
+ for (const dep of module.dependsOn)
13
+ if (!next.#modules.has(dep))
14
+ throw new Error(`Module ${module.name} must follow dependency ${dep}`);
15
+ next.#modules.set(module.name, module);
16
+ for (const resource of module.resources) {
17
+ if (next.#resources.has(resource.name))
18
+ throw new Error(`Duplicate resource: ${resource.name}`);
19
+ next.#resources.set(resource.name, resource);
20
+ next.#owners.set(resource.name, module.name);
21
+ }
22
+ }
23
+ const lookupKeys = new Set();
24
+ const roleKeys = new Set();
25
+ for (const module of next.#modules.values()) {
26
+ for (const [group, rows] of Object.entries(module.lookups ?? {})) {
27
+ identifier(group);
28
+ for (const row of rows) {
29
+ if (typeof row.key !== 'string' || !row.key.trim() || row.key.length > 255)
30
+ throw new Error(`Module ${module.name}: invalid lookup key in ${group}`);
31
+ if (!row.label?.ar || !row.label?.en)
32
+ throw new Error(`Module ${module.name}: lookup ${group}.${row.key} needs bilingual labels`);
33
+ if (lookupKeys.has(`${group}\u0000${row.key}`))
34
+ throw new Error(`Duplicate lookup: ${group}.${row.key}`);
35
+ lookupKeys.add(`${group}\u0000${row.key}`);
36
+ }
37
+ }
38
+ for (const role of module.defaultRoles ?? []) {
39
+ if (!/^[a-z][a-z0-9_]{0,99}$/.test(role.key))
40
+ throw new Error(`Module ${module.name}: invalid role key ${role.key}`);
41
+ if (roleKeys.has(role.key))
42
+ throw new Error(`Duplicate default role: ${role.key}`);
43
+ if (!role.name?.trim())
44
+ throw new Error(`Module ${module.name}: role ${role.key} needs a name`);
45
+ roleKeys.add(role.key);
46
+ }
47
+ }
48
+ for (const resource of next.all()) {
49
+ if (resource.scope) {
50
+ const field = resource.fields[resource.scope.from];
51
+ if (field.type === 'belongsTo' && !next.get(field.resource).scoped)
52
+ throw new Error(`${resource.name}: scope.from must reference a scoped resource`);
53
+ }
54
+ for (const field of Object.values(resource.fields)) {
55
+ if (field.type !== 'belongsTo' && field.type !== 'hasMany')
56
+ continue;
57
+ const target = next.get(field.resource);
58
+ const owner = next.owner(resource.name);
59
+ const targetOwner = next.owner(target.name);
60
+ if (owner !== targetOwner && !next.#modules.get(owner).dependsOn.includes(targetOwner))
61
+ throw new Error(`Undeclared dependency: ${owner} -> ${targetOwner}`);
62
+ if (field.type === 'hasMany' && owner !== targetOwner)
63
+ throw new Error('Inline children must belong to the same module');
64
+ if (field.type === 'hasMany' && !(field.foreignKey in target.fields))
65
+ throw new Error(`Missing child foreign key: ${field.foreignKey}`);
66
+ }
67
+ }
68
+ this.#resources = next.#resources;
69
+ this.#owners = next.#owners;
70
+ this.#modules = next.#modules;
71
+ return this;
72
+ }
73
+ get(name) {
74
+ const resource = this.#resources.get(name);
75
+ if (!resource)
76
+ throw new Error(`Unknown resource: ${name}`);
77
+ return resource;
78
+ }
79
+ has(name) {
80
+ return this.#resources.has(name);
81
+ }
82
+ all() {
83
+ return [...this.#resources.values()];
84
+ }
85
+ owner(name) {
86
+ this.get(name);
87
+ return this.#owners.get(name);
88
+ }
89
+ modules() {
90
+ return [...this.#modules.values()];
91
+ }
92
+ /** Workflow definitions declared by registered modules, validated against their resources. */
93
+ workflows() {
94
+ return this.modules().flatMap((module) => {
95
+ for (const workflow of module.workflows ?? [])
96
+ if (this.owner(workflow.resource) !== module.name)
97
+ throw new Error(`Workflow ${workflow.name} must belong to the module of ${workflow.resource}`);
98
+ return [...(module.workflows ?? [])];
99
+ });
100
+ }
101
+ }
@@ -0,0 +1,155 @@
1
+ import type { Knex } from 'knex';
2
+ import type { LucidModel } from '@adonisjs/lucid/types/model';
3
+ import type { WorkflowDefinition } from '../workflows/define_workflow.js';
4
+ import type { Conditions } from '../auth/conditions.js';
5
+ export type Label = {
6
+ ar: string;
7
+ en: string;
8
+ };
9
+ export type Action = 'view' | 'create' | 'update' | 'delete' | 'submit' | 'cancel' | 'amend';
10
+ export type Scalar = string | number | boolean | null;
11
+ export type RecordData = Record<string, unknown>;
12
+ export type JsonValue = string | number | boolean | null | JsonValue[] | {
13
+ [key: string]: JsonValue;
14
+ };
15
+ export type SerializedRecord = Record<string, JsonValue>;
16
+ export type Field = {
17
+ label: Label;
18
+ column?: string;
19
+ required?: boolean;
20
+ unique?: boolean;
21
+ sortable?: boolean;
22
+ searchable?: boolean;
23
+ filterable?: boolean;
24
+ permissionLevel?: number;
25
+ sequence?: string;
26
+ } & ({
27
+ type: 'string' | 'text' | 'integer' | 'money' | 'boolean' | 'date' | 'datetime' | 'json';
28
+ } | {
29
+ type: 'attachment';
30
+ /**
31
+ * Lower-case file extensions accepted for upload, or 'any'. Defaults to
32
+ * DEFAULT_ATTACHMENT_EXTENSIONS (documents, images and archives).
33
+ */
34
+ accept?: string[] | 'any';
35
+ /** Upload size limit such as '5mb'. Defaults to '20mb'. */
36
+ maxSize?: string;
37
+ } | {
38
+ type: 'belongsTo';
39
+ resource: string;
40
+ }
41
+ /**
42
+ * A user of this deployment (foreign key to users). Choices are active members of
43
+ * the record's organization unit or its ancestors; readers see only the display name.
44
+ */
45
+ | {
46
+ type: 'user';
47
+ } | {
48
+ type: 'hasMany';
49
+ resource: string;
50
+ foreignKey: string;
51
+ inline?: boolean;
52
+ } | {
53
+ type: 'lookup';
54
+ group: string;
55
+ });
56
+ export type Resource = {
57
+ name: string;
58
+ /** The list heading, usually plural (for example «الحسابات»). */
59
+ label: Label;
60
+ /**
61
+ * The singular record noun (for example «حساب»). Generated pages say «إضافة حساب»
62
+ * instead of the generic «إضافة سجل».
63
+ */
64
+ recordLabel?: Label;
65
+ /** Full create-button text when «إضافة <recordLabel>» does not fit (for example «مهمة جديدة»). */
66
+ createLabel?: Label;
67
+ model: LucidModel;
68
+ scoped: boolean;
69
+ /**
70
+ * The organization unit of a scoped record follows a required belongsTo parent, for
71
+ * example a clinic follows its facility. The unit is copied from the parent before
72
+ * authorization, the actor must be able to view the parent, and the form has no unit
73
+ * picker. `ResourceService.rehome` moves the children after the parent moves.
74
+ */
75
+ scope?: {
76
+ from: string;
77
+ };
78
+ submittable?: boolean;
79
+ version?: boolean;
80
+ customFields?: boolean;
81
+ fields: Record<string, Field>;
82
+ list: readonly string[];
83
+ form: readonly string[];
84
+ show: readonly string[];
85
+ serialize?: readonly string[];
86
+ hidden?: readonly string[];
87
+ /**
88
+ * Fields that name a record wherever it is referenced: relation cells and pickers,
89
+ * "My tasks" and the approvals inbox. Joined with « · ». Defaults to the first
90
+ * sequence field and the first text field in `list`.
91
+ */
92
+ title?: readonly string[];
93
+ actions: readonly Action[];
94
+ validator: {
95
+ validate(data: unknown): Promise<RecordData>;
96
+ };
97
+ hooks?: {
98
+ beforeSave?: (record: RecordData, context: HookContext) => Promise<void>;
99
+ afterSave?: (record: RecordData, context: HookContext) => Promise<void>;
100
+ };
101
+ };
102
+ export type HookContext = {
103
+ trx: Knex.Transaction;
104
+ userId: number;
105
+ action: Action;
106
+ };
107
+ /** A changeable list value a module needs before its records can be saved. */
108
+ export type ModuleLookup = {
109
+ key: string;
110
+ label: Label;
111
+ sort?: number;
112
+ };
113
+ /** A role a module ships; its rules go through the same validation as the roles screen. */
114
+ export type ModuleRole = {
115
+ /** Stable key that workflows address ({ role: key }); see roles.key. */
116
+ key: string;
117
+ /** Arabic display name; administrators may rename it later. */
118
+ name: string;
119
+ permissionLevel?: number;
120
+ rules: readonly {
121
+ subject: string;
122
+ action: string;
123
+ inverted?: boolean;
124
+ conditions?: Conditions | null;
125
+ fields?: string[] | null;
126
+ }[];
127
+ };
128
+ export type Module = {
129
+ name: string;
130
+ reference?: boolean;
131
+ label: Label;
132
+ dependsOn: readonly string[];
133
+ resources: readonly Resource[];
134
+ /** Versioned workflows of this module's submittable resources (phase 4). */
135
+ workflows?: readonly WorkflowDefinition[];
136
+ /**
137
+ * Lookup rows by group. adula:install inserts missing rows and never changes or
138
+ * removes existing ones, so administrator edits survive upgrades.
139
+ */
140
+ lookups?: Readonly<Record<string, readonly ModuleLookup[]>>;
141
+ /**
142
+ * Roles created by adula:install when no role has their key yet. An existing role
143
+ * is never modified, so administrators own every role after installation.
144
+ */
145
+ defaultRoles?: readonly ModuleRole[];
146
+ };
147
+ export type ResourceInput<F extends Record<string, Field>> = Omit<Resource, 'fields' | 'list' | 'form' | 'show' | 'hidden' | 'serialize' | 'title'> & {
148
+ fields: F;
149
+ list: readonly (keyof F & string)[];
150
+ form: readonly (keyof F & string)[];
151
+ show: readonly (keyof F & string)[];
152
+ hidden?: readonly (keyof F & string)[];
153
+ serialize?: readonly (keyof F & string)[];
154
+ title?: readonly (keyof F & string)[];
155
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,5 @@
1
+ import type { Field } from './types.js';
2
+ export declare function canonicalDate(value: unknown, type: 'date' | 'datetime'): boolean;
3
+ export declare function canonicalMoney(value: unknown): value is string;
4
+ /** Normalize before CASL evaluates a prospective record, using its stored representation. */
5
+ export declare function fieldValue(field: Field, value: unknown): unknown;
@@ -0,0 +1,88 @@
1
+ export function canonicalDate(value, type) {
2
+ if (typeof value !== 'string')
3
+ return false;
4
+ const normalized = type === 'date' ? `${value}T00:00:00.000Z` : value;
5
+ return (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(normalized) &&
6
+ !normalized.startsWith('0000') &&
7
+ Number.isFinite(Date.parse(normalized)) &&
8
+ new Date(normalized).toISOString() === normalized);
9
+ }
10
+ export function canonicalMoney(value) {
11
+ if (typeof value !== 'string' || !/^(0|-?[1-9]\d*)$/.test(value) || value.length > 20)
12
+ return false;
13
+ const integer = BigInt(value);
14
+ return integer >= -9223372036854775808n && integer <= 9223372036854775807n;
15
+ }
16
+ function isJson(value, ancestors = new Set()) {
17
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
18
+ return true;
19
+ if (typeof value === 'number')
20
+ return Number.isFinite(value);
21
+ if (typeof value !== 'object' || ancestors.has(value))
22
+ return false;
23
+ if (!Array.isArray(value) &&
24
+ Object.getPrototypeOf(value) !== Object.prototype &&
25
+ Object.getPrototypeOf(value) !== null)
26
+ return false;
27
+ // JSON.stringify changes holes into null; never silently alter a submitted value.
28
+ if (Array.isArray(value)) {
29
+ for (let index = 0; index < value.length; index++)
30
+ if (!Object.hasOwn(value, index))
31
+ return false;
32
+ }
33
+ ancestors.add(value);
34
+ const valid = Object.values(value).every((entry) => isJson(entry, ancestors));
35
+ ancestors.delete(value);
36
+ return valid;
37
+ }
38
+ /** Normalize before CASL evaluates a prospective record, using its stored representation. */
39
+ export function fieldValue(field, value) {
40
+ if (value === undefined || value === null)
41
+ return value;
42
+ switch (field.type) {
43
+ case 'money': {
44
+ const amount = typeof value === 'number' && Number.isSafeInteger(value) ? String(value) : value;
45
+ if (!canonicalMoney(amount))
46
+ throw new Error('Money requires canonical integer minor units within PostgreSQL bigint range');
47
+ return amount;
48
+ }
49
+ case 'integer':
50
+ case 'belongsTo':
51
+ case 'user':
52
+ if (!Number.isInteger(value) ||
53
+ Number(value) < (field.type === 'integer' ? -2147483648 : 1) ||
54
+ Number(value) > 2147483647)
55
+ throw new Error('Expected a PostgreSQL integer');
56
+ return value;
57
+ case 'boolean':
58
+ if (typeof value !== 'boolean')
59
+ throw new Error('Expected a boolean');
60
+ return value;
61
+ case 'string':
62
+ case 'text':
63
+ case 'lookup':
64
+ if (typeof value !== 'string')
65
+ throw new Error('Expected a string');
66
+ return value;
67
+ case 'date':
68
+ case 'datetime': {
69
+ const normalized = field.type === 'datetime' && value instanceof Date && Number.isFinite(value.getTime())
70
+ ? value.toISOString()
71
+ : value;
72
+ if (!canonicalDate(normalized, field.type))
73
+ throw new Error('Expected a valid ISO date or canonical UTC timestamp');
74
+ return normalized;
75
+ }
76
+ case 'json':
77
+ if (!isJson(value))
78
+ throw new Error('Expected a JSON value without cycles or non-JSON values');
79
+ return value;
80
+ case 'attachment':
81
+ // Writes carry the id of an owned upload; reads are hydrated into summaries later.
82
+ if (!Number.isSafeInteger(value) || Number(value) < 1 || Number(value) > 2147483647)
83
+ throw new Error('Expected the identifier of an uploaded attachment');
84
+ return value;
85
+ default:
86
+ return value;
87
+ }
88
+ }
@@ -0,0 +1,14 @@
1
+ import type { Knex } from 'knex';
2
+ export type BackupObject = {
3
+ key: string;
4
+ size: number;
5
+ modifiedAt: string;
6
+ };
7
+ export type BackupStatus = {
8
+ healthy: boolean;
9
+ reason: string;
10
+ checkedAt: string;
11
+ };
12
+ /** Check one complete recent snapshot; object existence is not a restore test. */
13
+ export declare function assessBackup(objects: BackupObject[], now?: number, prefix?: string): BackupStatus;
14
+ export declare function verifyBackup(db: Knex, inspect: () => Promise<BackupObject[]>, now?: number, prefix?: string): Promise<BackupStatus>;