adula 2.1.0 → 2.3.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 (269) hide show
  1. package/README.md +149 -18
  2. package/build/agent/AGENTS.template.md +4 -4
  3. package/build/agent/capabilities.md +22 -12
  4. package/build/agent/skills/adula-frontend-design/SKILL.md +6 -4
  5. package/build/agent/skills/idea-review/SKILL.md +2 -2
  6. package/build/commands/adula_assistant_prune.d.ts +10 -0
  7. package/build/commands/adula_assistant_prune.js +12 -0
  8. package/build/commands/adula_outbox.d.ts +10 -0
  9. package/build/commands/adula_outbox.js +11 -0
  10. package/build/commands/adula_restore_reconcile.d.ts +10 -0
  11. package/build/commands/adula_restore_reconcile.js +34 -0
  12. package/build/commands/adula_runtime_health.d.ts +10 -0
  13. package/build/commands/adula_runtime_health.js +27 -0
  14. package/build/commands/adula_uploads_prune.d.ts +10 -0
  15. package/build/commands/adula_uploads_prune.js +16 -0
  16. package/build/commands/app.d.ts +10 -0
  17. package/build/commands/app.js +64 -0
  18. package/build/commands/backup_create.d.ts +11 -0
  19. package/build/commands/backup_create.js +99 -0
  20. package/build/commands/backup_open.d.ts +16 -0
  21. package/build/commands/backup_open.js +48 -0
  22. package/build/commands/backup_restore_files.d.ts +11 -0
  23. package/build/commands/backup_restore_files.js +44 -0
  24. package/build/commands/backup_restore_test.d.ts +12 -0
  25. package/build/commands/backup_restore_test.js +188 -0
  26. package/build/commands/backup_seal.d.ts +12 -0
  27. package/build/commands/backup_seal.js +36 -0
  28. package/build/commands/backup_services.d.ts +33 -0
  29. package/build/commands/backup_services.js +6 -0
  30. package/build/commands/backup_verify.d.ts +9 -0
  31. package/build/commands/backup_verify.js +59 -0
  32. package/build/commands/backup_verify_snapshot.d.ts +10 -0
  33. package/build/commands/backup_verify_snapshot.js +37 -0
  34. package/build/commands/client.d.ts +16 -0
  35. package/build/commands/client.js +71 -0
  36. package/build/commands/doctor.js +21 -1
  37. package/build/commands/install.d.ts +8 -0
  38. package/build/commands/install.js +69 -45
  39. package/build/commands/main.d.ts +3 -2
  40. package/build/commands/main.js +32 -0
  41. package/build/commands/module_add.js +4 -20
  42. package/build/commands/resource.d.ts +2 -0
  43. package/build/commands/resource.js +12 -3
  44. package/build/commands/resource_migration.d.ts +15 -0
  45. package/build/commands/resource_migration.js +81 -0
  46. package/build/commands/resource_snapshot.d.ts +2 -0
  47. package/build/commands/resource_snapshot.js +21 -4
  48. package/build/commands/sla_evaluate.d.ts +14 -0
  49. package/build/commands/sla_evaluate.js +16 -0
  50. package/build/commands/ui.js +4 -2
  51. package/build/commands/ui_css.d.ts +9 -0
  52. package/build/commands/ui_css.js +19 -0
  53. package/build/commands/upgrade.d.ts +1 -1
  54. package/build/commands/upgrade.js +1 -1
  55. package/build/configure.js +1 -1
  56. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  57. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  58. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  59. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  60. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  61. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  62. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  63. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  64. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  65. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  66. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  67. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  68. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  69. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  70. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  71. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  72. package/build/database/migrations/1770000000051_comment_notifications.d.ts +5 -0
  73. package/build/database/migrations/1770000000051_comment_notifications.js +10 -0
  74. package/build/database/migrations/1770000000054_cloud_backups.d.ts +5 -0
  75. package/build/database/migrations/1770000000054_cloud_backups.js +10 -0
  76. package/build/database/migrations/1770000000055_ai_assistant.d.ts +5 -0
  77. package/build/database/migrations/1770000000055_ai_assistant.js +10 -0
  78. package/build/database/migrations/1770000000056_appearance.d.ts +5 -0
  79. package/build/database/migrations/1770000000056_appearance.js +10 -0
  80. package/build/index.d.ts +87 -11
  81. package/build/index.js +50 -7
  82. package/build/providers/adula_provider.d.ts +2 -0
  83. package/build/providers/adula_provider.js +7 -0
  84. package/build/src/admin/contracts.js +1 -1
  85. package/build/src/admin/controller.d.ts +14 -1
  86. package/build/src/admin/controller.js +91 -13
  87. package/build/src/admin/errors.d.ts +32 -0
  88. package/build/src/admin/errors.js +63 -1
  89. package/build/src/admin/presentation.d.ts +21 -2
  90. package/build/src/admin/resource/editor.d.ts +60 -0
  91. package/build/src/admin/resource/editor.js +345 -0
  92. package/build/src/admin/resource/export.d.ts +54 -0
  93. package/build/src/admin/resource/export.js +262 -0
  94. package/build/src/admin/resource/lifecycle.d.ts +23 -0
  95. package/build/src/admin/resource/lifecycle.js +91 -0
  96. package/build/src/admin/resource/query.d.ts +111 -0
  97. package/build/src/admin/resource/query.js +595 -0
  98. package/build/src/admin/resource/read.d.ts +109 -0
  99. package/build/src/admin/resource/read.js +388 -0
  100. package/build/src/admin/resource/shared.d.ts +93 -0
  101. package/build/src/admin/resource/shared.js +265 -0
  102. package/build/src/admin/resource/trash.d.ts +10 -0
  103. package/build/src/admin/resource/trash.js +56 -0
  104. package/build/src/admin/resource/write.d.ts +57 -0
  105. package/build/src/admin/resource/write.js +603 -0
  106. package/build/src/admin/resource_service.d.ts +80 -193
  107. package/build/src/admin/resource_service.js +81 -1343
  108. package/build/src/admin/resource_tools.d.ts +111 -0
  109. package/build/src/admin/resource_tools.js +139 -0
  110. package/build/src/ai/assistant.d.ts +100 -0
  111. package/build/src/ai/assistant.js +487 -0
  112. package/build/src/ai/client.d.ts +49 -0
  113. package/build/src/ai/client.js +85 -0
  114. package/build/src/ai/prompt.d.ts +23 -0
  115. package/build/src/ai/prompt.js +83 -0
  116. package/build/src/ai/settings.d.ts +56 -0
  117. package/build/src/ai/settings.js +214 -0
  118. package/build/src/ai/usage.d.ts +16 -0
  119. package/build/src/ai/usage.js +33 -0
  120. package/build/src/appearance/appearance.d.ts +134 -0
  121. package/build/src/appearance/appearance.js +461 -0
  122. package/build/src/appearance/colors.d.ts +43 -0
  123. package/build/src/appearance/colors.js +99 -0
  124. package/build/src/appearance/logo.d.ts +32 -0
  125. package/build/src/appearance/logo.js +112 -0
  126. package/build/src/attachments/attachment_service.d.ts +46 -2
  127. package/build/src/attachments/attachment_service.js +96 -4
  128. package/build/src/auth/actor_store.d.ts +5 -1
  129. package/build/src/auth/actor_store.js +8 -4
  130. package/build/src/auth/conditions.d.ts +5 -0
  131. package/build/src/auth/conditions.js +26 -3
  132. package/build/src/auth/sql.js +17 -5
  133. package/build/src/auth/two_factor.d.ts +96 -0
  134. package/build/src/auth/two_factor.js +259 -0
  135. package/build/src/backups/archive.d.ts +52 -0
  136. package/build/src/backups/archive.js +362 -0
  137. package/build/src/backups/cloud_backups.d.ts +133 -0
  138. package/build/src/backups/cloud_backups.js +650 -0
  139. package/build/src/backups/doctor.d.ts +7 -0
  140. package/build/src/backups/doctor.js +55 -0
  141. package/build/src/backups/providers.d.ts +81 -0
  142. package/build/src/backups/providers.js +470 -0
  143. package/build/src/collaboration/assignments.d.ts +59 -2
  144. package/build/src/collaboration/assignments.js +196 -74
  145. package/build/src/collaboration/record_collaboration.d.ts +21 -4
  146. package/build/src/collaboration/record_collaboration.js +126 -51
  147. package/build/src/collaboration/shared.d.ts +24 -0
  148. package/build/src/collaboration/shared.js +34 -0
  149. package/build/src/commands/app_scaffold.d.ts +72 -0
  150. package/build/src/commands/app_scaffold.js +285 -0
  151. package/build/src/commands/capabilities.js +35 -9
  152. package/build/src/commands/doctor.d.ts +24 -2
  153. package/build/src/commands/doctor.js +81 -6
  154. package/build/src/commands/gap_report.d.ts +1 -1
  155. package/build/src/commands/gap_report.js +2 -2
  156. package/build/src/commands/generator.d.ts +37 -1
  157. package/build/src/commands/generator.js +61 -18
  158. package/build/src/commands/snapshot.d.ts +24 -13
  159. package/build/src/commands/snapshot.js +54 -14
  160. package/build/src/commands/source_markers.d.ts +10 -0
  161. package/build/src/commands/source_markers.js +29 -0
  162. package/build/src/core/activity.d.ts +2 -0
  163. package/build/src/core/activity.js +7 -1
  164. package/build/src/core/administrators.d.ts +38 -0
  165. package/build/src/core/administrators.js +145 -0
  166. package/build/src/core/avatar_image.d.ts +33 -0
  167. package/build/src/core/avatar_image.js +278 -0
  168. package/build/src/core/html_sanitizer.d.ts +20 -0
  169. package/build/src/core/html_sanitizer.js +261 -0
  170. package/build/src/core/like.d.ts +5 -0
  171. package/build/src/core/like.js +5 -0
  172. package/build/src/core/lookups.d.ts +80 -0
  173. package/build/src/core/lookups.js +319 -0
  174. package/build/src/core/mail_settings.d.ts +83 -0
  175. package/build/src/core/mail_settings.js +274 -0
  176. package/build/src/core/mail_test.d.ts +16 -0
  177. package/build/src/core/mail_test.js +81 -6
  178. package/build/src/core/message_templates.d.ts +15 -2
  179. package/build/src/core/message_templates.js +81 -11
  180. package/build/src/core/module_seed.js +2 -1
  181. package/build/src/core/notification_channels.d.ts +235 -0
  182. package/build/src/core/notification_channels.js +660 -0
  183. package/build/src/core/roles.js +26 -9
  184. package/build/src/core/saved_views.d.ts +8 -1
  185. package/build/src/core/saved_views.js +91 -26
  186. package/build/src/core/sequences.d.ts +32 -0
  187. package/build/src/core/sequences.js +97 -0
  188. package/build/src/core/settings.d.ts +5 -0
  189. package/build/src/core/settings.js +31 -3
  190. package/build/src/core/template_language.d.ts +61 -0
  191. package/build/src/core/template_language.js +141 -0
  192. package/build/src/core/ui_preferences.d.ts +10 -0
  193. package/build/src/core/ui_preferences.js +15 -1
  194. package/build/src/core/user_avatars.d.ts +79 -0
  195. package/build/src/core/user_avatars.js +186 -0
  196. package/build/src/core/user_invitations.d.ts +5 -1
  197. package/build/src/core/user_invitations.js +7 -1
  198. package/build/src/core/user_preferences.d.ts +36 -0
  199. package/build/src/core/user_preferences.js +125 -0
  200. package/build/src/core/users.d.ts +2 -0
  201. package/build/src/core/users.js +5 -3
  202. package/build/src/database/calendar_days.d.ts +19 -0
  203. package/build/src/database/calendar_days.js +36 -0
  204. package/build/src/database/schema.d.ts +201 -2
  205. package/build/src/database/schema.js +713 -59
  206. package/build/src/database/schema_diff.d.ts +70 -0
  207. package/build/src/database/schema_diff.js +190 -0
  208. package/build/src/events/record_mutation.d.ts +2 -1
  209. package/build/src/events/record_mutation.js +1 -0
  210. package/build/src/integrations/api_client.d.ts +37 -0
  211. package/build/src/integrations/api_client.js +567 -0
  212. package/build/src/integrations/import_adapters.d.ts +37 -0
  213. package/build/src/integrations/import_adapters.js +35 -0
  214. package/build/src/integrations/imports.d.ts +130 -16
  215. package/build/src/integrations/imports.js +434 -73
  216. package/build/src/integrations/openapi.d.ts +3 -1
  217. package/build/src/integrations/openapi.js +465 -31
  218. package/build/src/integrations/outbound.d.ts +94 -0
  219. package/build/src/integrations/outbound.js +276 -0
  220. package/build/src/integrations/print.d.ts +22 -1
  221. package/build/src/integrations/print.js +68 -22
  222. package/build/src/integrations/print_templates.d.ts +216 -0
  223. package/build/src/integrations/print_templates.js +1017 -0
  224. package/build/src/integrations/sync_jobs.d.ts +139 -0
  225. package/build/src/integrations/sync_jobs.js +416 -0
  226. package/build/src/integrations/webhooks.d.ts +12 -12
  227. package/build/src/integrations/webhooks.js +34 -43
  228. package/build/src/integrations/xlsx.d.ts +41 -0
  229. package/build/src/integrations/xlsx.js +519 -0
  230. package/build/src/languages/ar.d.ts +11 -0
  231. package/build/src/languages/ar.js +358 -0
  232. package/build/src/languages/ar_ui.d.ts +461 -0
  233. package/build/src/languages/ar_ui.js +464 -0
  234. package/build/src/languages/catalog.d.ts +66 -0
  235. package/build/src/languages/catalog.js +152 -0
  236. package/build/src/languages/en.d.ts +7 -0
  237. package/build/src/languages/en.js +352 -0
  238. package/build/src/languages/en_ui.d.ts +3 -0
  239. package/build/src/languages/en_ui.js +458 -0
  240. package/build/src/languages/validation.d.ts +26 -0
  241. package/build/src/languages/validation.js +60 -0
  242. package/build/src/lists/bulk_actions.d.ts +89 -0
  243. package/build/src/lists/bulk_actions.js +268 -0
  244. package/build/src/lists/dashboards.d.ts +138 -0
  245. package/build/src/lists/dashboards.js +290 -0
  246. package/build/src/mcp/tools.js +9 -104
  247. package/build/src/resource/define_resource.d.ts +18 -1
  248. package/build/src/resource/define_resource.js +212 -18
  249. package/build/src/resource/definition.d.ts +44 -0
  250. package/build/src/resource/definition.js +171 -0
  251. package/build/src/resource/registry.js +15 -4
  252. package/build/src/resource/types.d.ts +313 -16
  253. package/build/src/resource/values.d.ts +56 -1
  254. package/build/src/resource/values.js +237 -5
  255. package/build/src/services/settings.d.ts +2 -0
  256. package/build/src/services/settings.js +5 -1
  257. package/build/src/upgrade/legacy.js +2 -2
  258. package/build/src/workflows/calendar.d.ts +9 -0
  259. package/build/src/workflows/calendar.js +44 -0
  260. package/build/src/workflows/define_workflow.d.ts +48 -3
  261. package/build/src/workflows/define_workflow.js +57 -13
  262. package/build/src/workflows/delegations.d.ts +107 -0
  263. package/build/src/workflows/delegations.js +326 -0
  264. package/build/src/workflows/engine.d.ts +80 -4
  265. package/build/src/workflows/engine.js +466 -86
  266. package/build/src/workflows/sla.d.ts +15 -0
  267. package/build/src/workflows/sla.js +8 -0
  268. package/build/stubs/resource_contract.txt +12 -1
  269. package/package.json +9 -2
@@ -1,16 +1,33 @@
1
1
  import { mkdir, readFile, writeFile, access, glob } from 'node:fs/promises';
2
2
  import { dirname, join, resolve } from 'node:path';
3
3
  import { identifier } from '../resource/define_resource.js';
4
- import { appendMarkedItem, moduleSource } from './source_markers.js';
5
- export async function generateResource(root, name, module) {
4
+ import { appendMarkedItem, moduleRegistered, moduleSource, registerModuleSource, } from './source_markers.js';
5
+ /** A single-quoted TypeScript string literal. */
6
+ export function quoted(value) {
7
+ return `'${value.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'`;
8
+ }
9
+ /**
10
+ * Plans a scoped resource with its migration, model, validator, factory and security
11
+ * contract, without writing. `moduleSource` replaces the module definition read from disk
12
+ * (adula:app passes the module it is about to create); `label` sets the resource labels.
13
+ */
14
+ export async function planResource(root, name, module, options = {}) {
6
15
  identifier(name);
7
16
  identifier(module);
8
17
  for await (const existing of glob(`app/modules/*/resources/${name}.ts`, { cwd: root }))
9
18
  throw new Error(`Refusing to overwrite resource registered at ${existing}`);
10
19
  const base = resolve(root, 'app/modules', module);
11
20
  const title = name.replace(/_/g, ' ');
21
+ const ar = quoted(options.label?.ar ?? title);
22
+ const en = quoted(options.label?.en ?? title);
12
23
  const relative = `app/modules/${module}`;
13
- const resourceSource = `import { defineResource } from 'adula'\nimport Model from '#modules/${module}/models/${name}'\nimport { validator } from '#modules/${module}/validators/${name}'\n\nexport default defineResource({\n name: '${name}', label: { ar: '${title}', en: '${title}' },\n recordLabel: { ar: '${title}', en: '${title}' }, model: Model, scoped: true,\n fields: { title: { type: 'string', label: { ar: 'العنوان', en: 'Title' }, required: true, searchable: true } },\n list: ['title'], form: ['title'], show: ['title'],\n actions: ['view', 'create', 'update', 'delete'], validator,\n})\n`;
24
+ const imports = [
25
+ ...(options.model ? [`import Model from '#modules/${module}/models/${name}'`] : []),
26
+ ...(options.validator
27
+ ? [`import { validator } from '#modules/${module}/validators/${name}'`]
28
+ : []),
29
+ ];
30
+ const resourceSource = `import { defineResource } from 'adula'\n${imports.map((line) => `${line}\n`).join('')}\n// The fields are the source of truth: validation, columns and forms derive from them.\nexport default defineResource({\n name: '${name}', label: { ar: ${ar}, en: ${en} },\n recordLabel: { ar: ${ar}, en: ${en} },${options.model ? ' model: Model,' : ''} scoped: true,\n fields: { title: { type: 'string', label: { ar: 'العنوان', en: 'Title' }, required: true, searchable: true } },\n list: ['title'], form: ['title'], show: ['title'],\n actions: ['view', 'create', 'update', 'delete'],${options.validator ? ' validator,' : ''}\n})\n`;
14
31
  const migration = {
15
32
  name,
16
33
  scoped: true,
@@ -31,16 +48,24 @@ export async function generateResource(root, name, module) {
31
48
  [`${relative}/factories/${name}.ts`]: `import factory from '@adonisjs/lucid/factories'\nimport Model from '#modules/${module}/models/${name}'\nexport default factory.define(Model, ({ faker }) => ({ title: faker.lorem.words(3) })).build()\n`,
32
49
  [`tests/functional/${name}.spec.ts`]: `import { resourceContract } from '#tests/helpers/resource_contract'\n\n// Extend this fixture whenever the resource form or its validator changes.\nresourceContract('${name}', ({ unique }) => ({\n input: { title: 'سجل ' + unique },\n expected: { title: 'سجل ' + unique },\n update: { title: 'سجل محدث ' + unique },\n updated: { title: 'سجل محدث ' + unique },\n}))\n`,
33
50
  };
34
- const modulePath = join(base, 'module.ts');
35
- let current;
36
- try {
37
- current = await readFile(modulePath, 'utf8');
38
- }
39
- catch (error) {
40
- if (error.code !== 'ENOENT')
41
- throw error;
42
- current = moduleSource(module);
51
+ // Opt-in only: the definition derives the validator, and persistence never reads a model.
52
+ if (!options.model) {
53
+ delete files[`${relative}/models/${name}.ts`];
54
+ delete files[`${relative}/factories/${name}.ts`];
43
55
  }
56
+ if (!options.validator)
57
+ delete files[`${relative}/validators/${name}.ts`];
58
+ const modulePath = join(base, 'module.ts');
59
+ let current = options.moduleSource;
60
+ if (current === undefined)
61
+ try {
62
+ current = await readFile(modulePath, 'utf8');
63
+ }
64
+ catch (error) {
65
+ if (error.code !== 'ENOENT')
66
+ throw error;
67
+ current = moduleSource(module);
68
+ }
44
69
  if (!current.includes('// adula:imports') || !current.includes('/* adula:resources */'))
45
70
  throw new Error('Module registration markers are missing; no files were changed');
46
71
  const modulesPath = join(root, 'start/modules.ts');
@@ -57,14 +82,32 @@ export async function generateResource(root, name, module) {
57
82
  throw error;
58
83
  }
59
84
  }
60
- for (const [file, content] of Object.entries(files)) {
85
+ return {
86
+ files,
87
+ module: {
88
+ path: modulePath,
89
+ source: appendMarkedItem(current.replace('// adula:imports', `import resource_${name} from './resources/${name}.js'
90
+ // adula:imports`), '/* adula:resources */', `resource_${name}`),
91
+ },
92
+ modules: moduleRegistered(modules, module)
93
+ ? null
94
+ : { path: modulesPath, source: registerModuleSource(modules, module) },
95
+ };
96
+ }
97
+ /** Writes a plan: new files first (never overwriting), then the module and the index. */
98
+ export async function writeResourcePlan(root, plan) {
99
+ for (const [file, content] of Object.entries(plan.files)) {
61
100
  const path = join(root, file);
62
101
  await mkdir(dirname(path), { recursive: true });
63
102
  await writeFile(path, content, { flag: 'wx' });
64
103
  }
65
- await mkdir(base, { recursive: true });
66
- await writeFile(modulePath, appendMarkedItem(current.replace('// adula:imports', `import resource_${name} from './resources/${name}.js'\n// adula:imports`), '/* adula:resources */', `resource_${name}`));
67
- if (!modules.includes(`'#modules/${module}/module'`))
68
- await writeFile(modulesPath, appendMarkedItem(modules.replace('// adula:imports', `import module_${module} from '#modules/${module}/module'\n// adula:imports`), '/* adula:modules */', `module_${module}`));
69
- return Object.keys(files);
104
+ await mkdir(dirname(plan.module.path), { recursive: true });
105
+ await writeFile(plan.module.path, plan.module.source);
106
+ if (plan.modules)
107
+ await writeFile(plan.modules.path, plan.modules.source);
108
+ }
109
+ export async function generateResource(root, name, module, options = {}) {
110
+ const plan = await planResource(root, name, module, options);
111
+ await writeResourcePlan(root, plan);
112
+ return Object.keys(plan.files);
70
113
  }
@@ -1,27 +1,38 @@
1
- import type { Resource } from '../resource/types.js';
1
+ import type { Field, Resource } from '../resource/types.js';
2
+ /**
3
+ * The parts of one field that decide its table shape (and keep the snapshot a valid
4
+ * Field): type and label, relation target and join table, column, constraints that
5
+ * become indexes or NOT NULL, numeric shape, the column default and enum options.
6
+ */
7
+ export declare function fieldSnapshot(field: Field): Field;
2
8
  /**
3
9
  * The part of a resource definition createResourceTable reads, as a generated
4
10
  * create-migration embeds it. Labels are kept so the migration stays readable.
5
11
  */
6
- export declare function resourceSnapshot(resource: Pick<Resource, 'name' | 'scoped' | 'version' | 'submittable' | 'customFields' | 'fields'>): {
12
+ export declare function resourceSnapshot(resource: Pick<Resource, 'name' | 'scoped' | 'version' | 'submittable' | 'fields' | 'unique'>): {
7
13
  fields: {
8
- [k: string]: {
9
- sequence?: string | undefined;
10
- searchable?: boolean | undefined;
11
- unique?: boolean | undefined;
12
- required?: boolean | undefined;
13
- column?: string | undefined;
14
- resource?: string | undefined;
15
- type: "string" | "boolean" | "text" | "integer" | "money" | "date" | "datetime" | "json" | "attachment" | "belongsTo" | "user" | "hasMany" | "lookup";
16
- label: import("../resource/types.js").Label;
17
- };
14
+ [k: string]: Field;
18
15
  };
19
- customFields?: boolean | undefined;
16
+ unique?: string[][] | undefined;
20
17
  submittable?: boolean | undefined;
21
18
  version?: boolean | undefined;
22
19
  name: string;
23
20
  scoped: boolean;
24
21
  };
22
+ /**
23
+ * The relations of a snapshot whose target table is created by a generated
24
+ * create-migration that runs after `file` (the migration runner's order): their foreign
25
+ * keys would fail on a fresh database (#99). Targets without a generated create-migration
26
+ * (core tables, hand-written ones), earlier ones and self-references are fine.
27
+ */
28
+ export declare function laterRelationTargets(snapshot: ReturnType<typeof resourceSnapshot>, file: string, migrations: readonly {
29
+ name: string;
30
+ resource?: string;
31
+ }[]): {
32
+ field: string;
33
+ target: string;
34
+ migration: string;
35
+ }[];
25
36
  /** The resource name embedded in a generated create-migration, if the source is one. */
26
37
  export declare function embeddedResource(source: string): string | undefined;
27
38
  /** Replaces the embedded definition of a generated create-migration (#20). */
@@ -1,4 +1,35 @@
1
+ import { decimalShape } from '../resource/values.js';
1
2
  const EMBEDDED = /(createResourceTable\([^,]+,\s*)(\{[\s\S]*\})(\s*\)\s*\})/;
3
+ /**
4
+ * The parts of one field that decide its table shape (and keep the snapshot a valid
5
+ * Field): type and label, relation target and join table, column, constraints that
6
+ * become indexes or NOT NULL, numeric shape, the column default and enum options.
7
+ */
8
+ export function fieldSnapshot(field) {
9
+ return {
10
+ type: field.type,
11
+ label: field.label,
12
+ ...('resource' in field && field.type !== 'hasMany' ? { resource: field.resource } : {}),
13
+ // Required by the lookup Field type: without it the generated migration fails tsc (#98).
14
+ ...(field.type === 'lookup' ? { group: field.group } : {}),
15
+ ...(field.type === 'manyToMany' && field.table ? { table: field.table } : {}),
16
+ ...(field.column ? { column: field.column } : {}),
17
+ ...(field.required ? { required: true } : {}),
18
+ ...(field.unique ? { unique: true } : {}),
19
+ ...(field.searchable ? { searchable: true } : {}),
20
+ ...(field.sequence ? { sequence: field.sequence } : {}),
21
+ // The resolved numeric shape: replay never depends on the package's defaults.
22
+ ...(field.type === 'decimal' || field.type === 'percent' ? decimalShape(field) : {}),
23
+ // Decides nullability: a required field that visibleWhen may hide is a nullable column.
24
+ ...(field.visibleWhen !== undefined ? { visibleWhen: field.visibleWhen } : {}),
25
+ ...(field.default !== undefined && !Array.isArray(field.default)
26
+ ? { default: field.default }
27
+ : {}),
28
+ ...('options' in field ? { options: field.options } : {}),
29
+ // A multiple attachment field is a jsonb column instead of a foreign key.
30
+ ...(field.type === 'attachment' && field.multiple ? { multiple: true } : {}),
31
+ };
32
+ }
2
33
  /**
3
34
  * The part of a resource definition createResourceTable reads, as a generated
4
35
  * create-migration embeds it. Labels are kept so the migration stays readable.
@@ -9,24 +40,33 @@ export function resourceSnapshot(resource) {
9
40
  scoped: resource.scoped,
10
41
  ...(resource.version ? { version: true } : {}),
11
42
  ...(resource.submittable ? { submittable: true } : {}),
12
- ...(resource.customFields ? { customFields: true } : {}),
43
+ ...(resource.unique?.length ? { unique: resource.unique.map((keys) => [...keys]) } : {}),
13
44
  fields: Object.fromEntries(Object.entries(resource.fields)
14
45
  .filter(([, field]) => field.type !== 'hasMany')
15
- .map(([key, field]) => [
16
- key,
17
- {
18
- type: field.type,
19
- label: field.label,
20
- ...(field.type === 'belongsTo' ? { resource: field.resource } : {}),
21
- ...(field.column ? { column: field.column } : {}),
22
- ...(field.required ? { required: true } : {}),
23
- ...(field.unique ? { unique: true } : {}),
24
- ...(field.searchable ? { searchable: true } : {}),
25
- ...(field.sequence ? { sequence: field.sequence } : {}),
26
- },
27
- ])),
46
+ .map(([key, field]) => [key, fieldSnapshot(field)])),
28
47
  };
29
48
  }
49
+ /**
50
+ * The relations of a snapshot whose target table is created by a generated
51
+ * create-migration that runs after `file` (the migration runner's order): their foreign
52
+ * keys would fail on a fresh database (#99). Targets without a generated create-migration
53
+ * (core tables, hand-written ones), earlier ones and self-references are fine.
54
+ */
55
+ export function laterRelationTargets(snapshot, file, migrations) {
56
+ const position = migrations.findIndex((migration) => migration.name === file);
57
+ const later = [];
58
+ for (const [key, field] of Object.entries(snapshot.fields)) {
59
+ if ((field.type !== 'belongsTo' && field.type !== 'manyToMany') || !('resource' in field))
60
+ continue;
61
+ const target = field.resource;
62
+ if (target === snapshot.name)
63
+ continue;
64
+ const index = migrations.findIndex((migration) => migration.resource === target);
65
+ if (index > position)
66
+ later.push({ field: key, target, migration: migrations[index].name });
67
+ }
68
+ return later;
69
+ }
30
70
  /** The resource name embedded in a generated create-migration, if the source is one. */
31
71
  export function embeddedResource(source) {
32
72
  const embedded = EMBEDDED.exec(source)?.[2];
@@ -9,3 +9,13 @@ export declare function moduleSource(name: string, options?: {
9
9
  reference?: boolean;
10
10
  typed?: boolean;
11
11
  }): string;
12
+ /**
13
+ * Registers a module in the application's start/modules.ts source: one import before
14
+ * `// adula:imports` and one item in the `/* adula:modules *\/` list. Shared by
15
+ * adula:module:add, adula:resource and adula:app so the three stay identical.
16
+ */
17
+ export declare function registerModuleSource(source: string, name: string): string;
18
+ /** True when start/modules.ts already imports the module. */
19
+ export declare function moduleRegistered(source: string, name: string): boolean;
20
+ /** The folders every application-owned module starts with. */
21
+ export declare const MODULE_DIRECTORIES: readonly ["models", "resources", "validators", "migrations", "factories", "listeners", "jobs", "workflows", "reports", "pages", "tests"];
@@ -39,3 +39,32 @@ export function moduleSource(name, options = {}) {
39
39
  '',
40
40
  ].join('\n');
41
41
  }
42
+ /**
43
+ * Registers a module in the application's start/modules.ts source: one import before
44
+ * `// adula:imports` and one item in the `/* adula:modules *\/` list. Shared by
45
+ * adula:module:add, adula:resource and adula:app so the three stay identical.
46
+ */
47
+ export function registerModuleSource(source, name) {
48
+ if (!source.includes('// adula:imports') || !source.includes('/* adula:modules */'))
49
+ throw new Error('Module index registration markers are missing');
50
+ const alias = `module_${name}`;
51
+ return appendMarkedItem(source.replace('// adula:imports', `import ${alias} from '#modules/${name}/module'\n// adula:imports`), '/* adula:modules */', alias);
52
+ }
53
+ /** True when start/modules.ts already imports the module. */
54
+ export function moduleRegistered(source, name) {
55
+ return source.includes(`'#modules/${name}/module'`);
56
+ }
57
+ /** The folders every application-owned module starts with. */
58
+ export const MODULE_DIRECTORIES = [
59
+ 'models',
60
+ 'resources',
61
+ 'validators',
62
+ 'migrations',
63
+ 'factories',
64
+ 'listeners',
65
+ 'jobs',
66
+ 'workflows',
67
+ 'reports',
68
+ 'pages',
69
+ 'tests',
70
+ ];
@@ -6,6 +6,8 @@ export type ActivityEntry = {
6
6
  actorId: number;
7
7
  action: string;
8
8
  changes?: Record<string, unknown>;
9
+ /** The administrator acting as actorId through impersonation; stored as impersonatedBy. */
10
+ impersonatorId?: number | null;
9
11
  };
10
12
  export type ActivityFilters = {
11
13
  resource?: string;
@@ -6,12 +6,18 @@ export function pageLimit(limit, fallback = 50) {
6
6
  return Math.min(value, 100);
7
7
  }
8
8
  export async function logActivity(db, entry) {
9
+ // Only the trusted impersonatorId may mark an entry as impersonated.
10
+ const changes = { ...entry.changes };
11
+ delete changes.impersonatedBy;
9
12
  await db('activities').insert({
10
13
  resource: entry.resource,
11
14
  record_id: entry.recordId,
12
15
  actor_id: entry.actorId,
13
16
  action: entry.action,
14
- changes: JSON.stringify(entry.changes ?? {}),
17
+ changes: JSON.stringify({
18
+ ...changes,
19
+ ...(entry.impersonatorId ? { impersonatedBy: entry.impersonatorId } : {}),
20
+ }),
15
21
  });
16
22
  }
17
23
  function boundary(value, end) {
@@ -0,0 +1,38 @@
1
+ import type { Knex } from 'knex';
2
+ /**
3
+ * Whether any user holds an unconditional `manage all` grant, which is what the
4
+ * administration area requires. Disabled holders still count: disabling the last
5
+ * administrator must not reopen bootstrap paths such as self-signup.
6
+ */
7
+ export declare function administratorExists(knex: Knex | Knex.Transaction): Promise<boolean>;
8
+ /** What installation did to secure a pre-existing account before promoting it. */
9
+ export type InstallAccountRotation = {
10
+ sessions: number;
11
+ tokens: number;
12
+ resetTokens: number;
13
+ invitations: number;
14
+ };
15
+ /**
16
+ * Resolves the installation administrator by e-mail. A missing account is created
17
+ * through `create` only while the application has no administrator yet, so a
18
+ * mistyped address on an existing installation never mints a new privileged user.
19
+ *
20
+ * An account that already exists while no administrator does may have been
21
+ * self-registered by anyone who guessed the address (pre-registration takeover).
22
+ * When `rotatePassword` is given it replaces the password, every session and API
23
+ * token of that account ends, and the event is recorded before it is promoted.
24
+ * Callers that just created the account themselves omit it (`--keep-password`).
25
+ */
26
+ export declare function resolveInstallAdministrator(knex: Knex, email: string, create: () => Promise<number>, options?: {
27
+ rotatePassword?: (userId: number) => Promise<void>;
28
+ }): Promise<{
29
+ id: number;
30
+ created: boolean;
31
+ rotated?: InstallAccountRotation;
32
+ }>;
33
+ /**
34
+ * Idempotently installs the root unit, the bootstrap `administrator` role with its
35
+ * `manage all` grant, and assigns it to the user. A transaction-scoped advisory
36
+ * lock makes repeated and concurrent installation safe.
37
+ */
38
+ export declare function grantInstallAdministrator(knex: Knex, userId: number, version: string): Promise<void>;
@@ -0,0 +1,145 @@
1
+ import { Settings } from '../services/settings.js';
2
+ import { logActivity } from './activity.js';
3
+ /**
4
+ * Whether any user holds an unconditional `manage all` grant, which is what the
5
+ * administration area requires. Disabled holders still count: disabling the last
6
+ * administrator must not reopen bootstrap paths such as self-signup.
7
+ */
8
+ export async function administratorExists(knex) {
9
+ const row = await knex('user_roles')
10
+ .join('role_rules', 'role_rules.role_id', 'user_roles.role_id')
11
+ .where({ 'role_rules.subject': 'all', 'role_rules.action': 'manage' })
12
+ .where('role_rules.inverted', false)
13
+ .whereNull('role_rules.conditions')
14
+ .whereNull('role_rules.fields')
15
+ .first('user_roles.user_id');
16
+ return Boolean(row);
17
+ }
18
+ /**
19
+ * Ends every way into an account: browser sessions (the `user_sessions` index and
20
+ * the database session store), personal API tokens, outstanding recovery links and
21
+ * pending invitations for the address. Tables are application-owned, so each is used
22
+ * only when it exists.
23
+ */
24
+ async function endAccountAccess(knex, userId, email) {
25
+ let sessions = 0;
26
+ let tokens = 0;
27
+ let resetTokens = 0;
28
+ let invitations = 0;
29
+ if (await knex.schema.hasTable('user_sessions')) {
30
+ const rows = await knex('user_sessions')
31
+ .where({ user_id: userId })
32
+ .select('id');
33
+ if (rows.length && (await knex.schema.hasTable('sessions')))
34
+ await knex('sessions')
35
+ .whereIn('id', rows.map((row) => row.id))
36
+ .delete();
37
+ sessions = Number(await knex('user_sessions').where({ user_id: userId }).delete());
38
+ }
39
+ if (await knex.schema.hasTable('auth_access_tokens'))
40
+ tokens = Number(await knex('auth_access_tokens').where({ tokenable_id: userId }).delete());
41
+ // A recovery link requested while signup was open would otherwise outlive the rotation.
42
+ if (await knex.schema.hasTable('password_reset_tokens'))
43
+ resetTokens = Number(await knex('password_reset_tokens').where({ user_id: userId }).whereNull('used_at').delete());
44
+ if (await knex.schema.hasTable('user_invitations'))
45
+ invitations = Number(await knex('user_invitations')
46
+ .whereRaw('lower(email) = lower(?)', [email])
47
+ .whereNull('accepted_at')
48
+ .delete());
49
+ return { sessions, tokens, resetTokens, invitations };
50
+ }
51
+ /**
52
+ * Resolves the installation administrator by e-mail. A missing account is created
53
+ * through `create` only while the application has no administrator yet, so a
54
+ * mistyped address on an existing installation never mints a new privileged user.
55
+ *
56
+ * An account that already exists while no administrator does may have been
57
+ * self-registered by anyone who guessed the address (pre-registration takeover).
58
+ * When `rotatePassword` is given it replaces the password, every session and API
59
+ * token of that account ends, and the event is recorded before it is promoted.
60
+ * Callers that just created the account themselves omit it (`--keep-password`).
61
+ */
62
+ export async function resolveInstallAdministrator(knex, email, create, options = {}) {
63
+ const existing = await knex('users').whereRaw('lower(email) = lower(?)', [email]).first('id');
64
+ const bootstrap = !(await administratorExists(knex));
65
+ if (existing) {
66
+ const id = Number(existing.id);
67
+ if (!bootstrap || !options.rotatePassword)
68
+ return { id, created: false };
69
+ await options.rotatePassword(id);
70
+ const rotated = await endAccountAccess(knex, id, email);
71
+ await logActivity(knex, {
72
+ resource: 'core.users',
73
+ recordId: id,
74
+ actorId: id,
75
+ action: 'install_rotate_credentials',
76
+ changes: rotated,
77
+ });
78
+ return { id, created: false, rotated };
79
+ }
80
+ if (!bootstrap)
81
+ throw new Error('Administrator user does not exist. An administrator already exists, so adula:install only creates the first one; check the e-mail address.');
82
+ return { id: await create(), created: true };
83
+ }
84
+ /** The name a new installation gives the bootstrap role; its key stays `administrator`. */
85
+ const BOOTSTRAP_ROLE_NAME = 'مدير النظام';
86
+ /**
87
+ * Idempotently installs the root unit, the bootstrap `administrator` role with its
88
+ * `manage all` grant, and assigns it to the user. A transaction-scoped advisory
89
+ * lock makes repeated and concurrent installation safe.
90
+ */
91
+ export async function grantInstallAdministrator(knex, userId, version) {
92
+ await knex.transaction(async (trx) => {
93
+ await trx.raw('SELECT pg_advisory_xact_lock(717011)');
94
+ let root = await trx('org_units').whereNull('parent_id').first();
95
+ if (!root) {
96
+ const [created] = await trx('org_units')
97
+ .insert({ name: 'الجهة', type: 'root', path: 'root' })
98
+ .returning('*');
99
+ await trx('org_units')
100
+ .where('id', created.id)
101
+ .update({ path: String(created.id) });
102
+ root = created;
103
+ }
104
+ // The bootstrap role is found by its fixed key, so administrators may rename it; a role
105
+ // installed before keys existed is found by its original name and keyed once.
106
+ let role = (await trx('roles').where('key', 'administrator').first()) ??
107
+ (await trx('roles').where('name', 'administrator').whereNull('key').first());
108
+ if (!role) {
109
+ // Role names are unique: a project role already named either way keeps its name.
110
+ const taken = new Set(await trx('roles').whereIn('name', [BOOTSTRAP_ROLE_NAME, 'administrator']).pluck('name'));
111
+ const name = [
112
+ BOOTSTRAP_ROLE_NAME,
113
+ 'administrator',
114
+ `${BOOTSTRAP_ROLE_NAME} (administrator)`,
115
+ ].find((candidate) => !taken.has(candidate));
116
+ const [created] = await trx('roles')
117
+ .insert({
118
+ name,
119
+ key: 'administrator',
120
+ permission_level: 1,
121
+ })
122
+ .returning('*');
123
+ role = created;
124
+ }
125
+ else if (!role.key)
126
+ await trx('roles').where('id', role.id).update({ key: 'administrator' });
127
+ // Repair a missing bootstrap grant even when the role already exists.
128
+ if (!(await trx('role_rules')
129
+ .where({ role_id: role.id, subject: 'all', action: 'manage', inverted: false })
130
+ .whereNull('conditions')
131
+ .whereNull('fields')
132
+ .first()))
133
+ await trx('role_rules').insert({ role_id: role.id, subject: 'all', action: 'manage' });
134
+ if (!(await trx('user_roles')
135
+ .where({ user_id: userId, role_id: role.id })
136
+ .whereNull('org_unit_id')
137
+ .first()))
138
+ await trx('user_roles').insert({ user_id: userId, role_id: role.id });
139
+ await trx('user_org_units')
140
+ .insert({ user_id: userId, org_unit_id: root.id })
141
+ .onConflict(['user_id', 'org_unit_id'])
142
+ .ignore();
143
+ await new Settings(trx).set('adula.version', version);
144
+ });
145
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Profile pictures (ADR 050) are untrusted bytes. The browser crops and re-encodes every
3
+ * picture to at most 512 px, so the server accepts only what that produces: PNG or still
4
+ * WebP within these bounds. Nothing here decodes pixel data; the container is checked and
5
+ * rewritten so that only the chunks a browser needs to draw the picture remain.
6
+ */
7
+ export declare const AVATAR_LIMITS: Readonly<{
8
+ maxBytes: number;
9
+ minSide: 32;
10
+ maxSide: 512;
11
+ }>;
12
+ export type AvatarImage = {
13
+ type: 'png' | 'webp';
14
+ mimeType: 'image/png' | 'image/webp';
15
+ extname: 'png' | 'webp';
16
+ width: number;
17
+ height: number;
18
+ bytes: Buffer;
19
+ };
20
+ /**
21
+ * Checks an uploaded profile picture by its first bytes (never its name or declared type),
22
+ * bounds its size and dimensions from the header, and returns a copy without metadata or
23
+ * trailing bytes. Anything else, including SVG, GIF, JPEG, HTML and animations, is refused.
24
+ */
25
+ export declare function sanitizeAvatarImage(input: Uint8Array): AvatarImage;
26
+ /**
27
+ * Prepares an uploaded profile picture for storage (ADR 050). `sanitizeAvatarImage` first
28
+ * checks the bytes without decoding them (type, size, header, dimensions, animation), so
29
+ * nothing unexpected reaches the decoder. libvips then decodes the single still frame
30
+ * within a pixel budget and re-encodes it, which drops every metadata chunk and any payload
31
+ * hidden inside the compressed pixel data. The result is checked again before it is stored.
32
+ */
33
+ export declare function prepareAvatarImage(input: Uint8Array): Promise<AvatarImage>;