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
@@ -0,0 +1,595 @@
1
+ import { columnName } from '../../resource/define_resource.js';
2
+ import { accessibleBy, authorizationSql, conditionSql } from '../../auth/sql.js';
3
+ import { canRecord } from '../../auth/ability.js';
4
+ import { fromRow, jsonValue, serialize } from '../contracts.js';
5
+ import { resolveActorConditions } from '../../auth/conditions.js';
6
+ import { AdulaError, forbiddenField, invalidCursor, invalidFilter, searchUnavailable, } from '../errors.js';
7
+ import { fieldValue, isMultipleAttachment } from '../../resource/values.js';
8
+ import { authorizeAction, canQueryField, columns, hydrate, permissions, collectionFilter, withLinks, } from './shared.js';
9
+ import { preload, titler } from './read.js';
10
+ /** Per-process cache of planner row estimates for identical list queries. */
11
+ const estimates = new Map();
12
+ const ESTIMATE_TTL_MS = 30_000;
13
+ const ESTIMATE_CACHE_LIMIT = 500;
14
+ const AGGREGATE_GROUP_LIMIT = 1000;
15
+ /**
16
+ * The default order's key: the creation time, newest first. Not a field, so a request cannot
17
+ * name it; a cursor carries it.
18
+ */
19
+ const NEWEST = '_created';
20
+ /** The column alias of the creation time's exact text in a list query. */
21
+ const NEWEST_VALUE = '_created_at';
22
+ /**
23
+ * Coerces a query-string or API filter/cursor value to the field's stored representation,
24
+ * so a mismatch is rejected before PostgreSQL raises an invalid-input error.
25
+ */
26
+ function queryValue(field, value) {
27
+ if (value === null)
28
+ return null;
29
+ let candidate = value;
30
+ switch (field.type) {
31
+ case 'integer':
32
+ case 'belongsTo':
33
+ case 'user':
34
+ case 'attachment':
35
+ if (typeof value === 'string' && /^-?\d{1,10}$/.test(value))
36
+ candidate = Number(value);
37
+ break;
38
+ // A multiSelect filter is one option it contains; a manyToMany filter one linked id.
39
+ case 'multiSelect':
40
+ return fieldValue({ ...field, min: undefined, max: undefined }, [String(value)])[0];
41
+ case 'manyToMany':
42
+ return fieldValue(field, [
43
+ typeof value === 'string' && /^\d{1,10}$/.test(value) ? Number(value) : value,
44
+ ])[0];
45
+ case 'decimal':
46
+ case 'percent':
47
+ case 'enum':
48
+ case 'email':
49
+ case 'phone':
50
+ case 'url':
51
+ if (typeof value === 'number')
52
+ candidate = String(value);
53
+ break;
54
+ case 'boolean':
55
+ if (value === 'true')
56
+ candidate = true;
57
+ else if (value === 'false')
58
+ candidate = false;
59
+ break;
60
+ case 'string':
61
+ case 'text':
62
+ case 'lookup':
63
+ if (typeof value === 'number' || typeof value === 'boolean')
64
+ candidate = String(value);
65
+ break;
66
+ case 'money':
67
+ case 'date':
68
+ case 'datetime':
69
+ break;
70
+ default:
71
+ throw new Error('Field cannot be compared');
72
+ }
73
+ // Length, pattern and range limits describe stored values, not the probes compared with them.
74
+ return fieldValue({ ...field, min: undefined, max: undefined, pattern: undefined }, candidate);
75
+ }
76
+ /** Most values an `in` filter accepts. */
77
+ export const FILTER_IN_LIMIT = 50;
78
+ const IN_TYPES = new Set([
79
+ 'string',
80
+ 'text',
81
+ 'email',
82
+ 'phone',
83
+ 'url',
84
+ 'enum',
85
+ 'lookup',
86
+ 'integer',
87
+ 'belongsTo',
88
+ 'user',
89
+ ]);
90
+ const RANGE_TYPES = new Set(['integer', 'money', 'decimal', 'percent', 'date', 'datetime']);
91
+ const TEXT_TYPES = new Set(['string', 'text', 'email', 'phone', 'url', 'enum', 'lookup']);
92
+ const COLLECTION_TYPES = new Set(['multiSelect', 'manyToMany']);
93
+ function isScalar(value) {
94
+ return value === null || ['string', 'number', 'boolean'].includes(typeof value);
95
+ }
96
+ /** Query strings parse long `in[]` lists as objects with index keys; read them as arrays. */
97
+ function asList(value) {
98
+ if (Array.isArray(value))
99
+ return value;
100
+ if (typeof value === 'string')
101
+ return value.split(',').map((entry) => entry.trim());
102
+ if (value && typeof value === 'object') {
103
+ const keys = Object.keys(value);
104
+ if (keys.length && keys.every((key) => /^\d{1,3}$/.test(key)))
105
+ return keys
106
+ .sort((a, b) => Number(a) - Number(b))
107
+ .map((key) => value[key]);
108
+ }
109
+ return null;
110
+ }
111
+ /**
112
+ * Validates one filter value against its field and coerces every operand to the field's
113
+ * stored representation. Throws 422 E_FILTER for an unknown operator, an operator the
114
+ * field type does not support, or an operand that does not fit the field.
115
+ */
116
+ export function filterCondition(key, field, value) {
117
+ const coerce = (operand) => {
118
+ try {
119
+ return queryValue(field, operand);
120
+ }
121
+ catch {
122
+ throw invalidFilter(`Invalid filter value: ${key}`);
123
+ }
124
+ };
125
+ if (isScalar(value))
126
+ return { kind: 'eq', value: coerce(value) };
127
+ if (!value || typeof value !== 'object' || Array.isArray(value))
128
+ throw invalidFilter('Invalid filter value');
129
+ const operators = Object.keys(value);
130
+ const entry = value;
131
+ if (operators.length === 1 && operators[0] === 'in') {
132
+ if (!IN_TYPES.has(field.type))
133
+ throw invalidFilter(`Unsupported filter operator: ${key}`);
134
+ const operands = asList(entry.in);
135
+ if (!operands || !operands.length || operands.length > FILTER_IN_LIMIT)
136
+ throw invalidFilter(`Invalid filter value: ${key}`);
137
+ const values = operands.map((operand) => {
138
+ if (operand === null || operand === '' || !isScalar(operand))
139
+ throw invalidFilter(`Invalid filter value: ${key}`);
140
+ return coerce(operand);
141
+ });
142
+ return { kind: 'in', values: [...new Set(values)] };
143
+ }
144
+ if (operators.length === 1 && operators[0] === 'empty') {
145
+ const empty = entry.empty;
146
+ if (empty === true || empty === 'true')
147
+ return { kind: 'empty', empty: true };
148
+ if (empty === false || empty === 'false')
149
+ return { kind: 'empty', empty: false };
150
+ throw invalidFilter(`Invalid filter value: ${key}`);
151
+ }
152
+ if (operators.length && operators.every((operator) => operator === 'gte' || operator === 'lte')) {
153
+ if (!RANGE_TYPES.has(field.type))
154
+ throw invalidFilter(`Unsupported filter operator: ${key}`);
155
+ const bound = (operand) => {
156
+ if (operand === null || operand === '' || !isScalar(operand))
157
+ throw invalidFilter(`Invalid filter value: ${key}`);
158
+ return coerce(operand);
159
+ };
160
+ return {
161
+ kind: 'range',
162
+ ...('gte' in entry ? { gte: bound(entry.gte) } : {}),
163
+ ...('lte' in entry ? { lte: bound(entry.lte) } : {}),
164
+ };
165
+ }
166
+ throw invalidFilter(`Unsupported filter operator: ${key}`);
167
+ }
168
+ /**
169
+ * Filters shared by list() and aggregate(): each key must be a filterable field the
170
+ * caller allows querying, and each value a scalar or operator object whose operands
171
+ * coerce to the field's type (see ListFilterValue).
172
+ */
173
+ function applyFilters(query, resource, filters, queryable) {
174
+ if (!filters || typeof filters !== 'object' || Array.isArray(filters))
175
+ throw invalidFilter('Invalid filter value');
176
+ for (const [key, value] of Object.entries(filters)) {
177
+ if (!Object.hasOwn(resource.fields, key) ||
178
+ !resource.fields[key]?.filterable ||
179
+ !queryable(key))
180
+ throw invalidFilter('Unsupported filter');
181
+ const field = resource.fields[key];
182
+ const condition = filterCondition(key, field, value);
183
+ const column = `r.${field.column ?? columnName(key)}`;
184
+ // multiSelect and manyToMany match one member, or none at all for an empty filter.
185
+ if (COLLECTION_TYPES.has(field.type)) {
186
+ if (condition.kind === 'eq')
187
+ collectionFilter(query, resource, key, condition.value);
188
+ else if (condition.kind === 'empty' && condition.empty)
189
+ collectionFilter(query, resource, key, null);
190
+ else if (condition.kind === 'empty')
191
+ query.whereNot((present) => {
192
+ collectionFilter(present, resource, key, null);
193
+ });
194
+ else
195
+ throw invalidFilter(`Unsupported filter operator: ${key}`);
196
+ continue;
197
+ }
198
+ // Several files filter only by having files or none (ADR 047).
199
+ if (isMultipleAttachment(field)) {
200
+ if (condition.kind !== 'empty')
201
+ throw invalidFilter(`Unsupported filter operator: ${key}`);
202
+ if (condition.empty)
203
+ query.where((empty) => {
204
+ empty.whereNull(column).orWhereRaw(`?? = '[]'::jsonb`, [column]);
205
+ });
206
+ else
207
+ query.whereNotNull(column).whereRaw(`?? <> '[]'::jsonb`, [column]);
208
+ continue;
209
+ }
210
+ switch (condition.kind) {
211
+ case 'eq':
212
+ if (condition.value === null)
213
+ query.whereNull(column);
214
+ else
215
+ query.where(column, condition.value);
216
+ break;
217
+ case 'in':
218
+ query.whereIn(column, condition.values);
219
+ break;
220
+ case 'range':
221
+ if (condition.gte !== undefined)
222
+ query.where(column, '>=', condition.gte);
223
+ if (condition.lte !== undefined)
224
+ query.where(column, '<=', condition.lte);
225
+ break;
226
+ case 'empty': {
227
+ const text = TEXT_TYPES.has(field.type);
228
+ if (condition.empty)
229
+ query.where((empty) => {
230
+ empty.whereNull(column);
231
+ if (text)
232
+ empty.orWhere(column, '');
233
+ });
234
+ else {
235
+ query.whereNotNull(column);
236
+ if (text)
237
+ query.whereNot(column, '');
238
+ }
239
+ break;
240
+ }
241
+ }
242
+ }
243
+ }
244
+ /** Full-text search, allowed only when the caller may query every searchable field. */
245
+ function applySearch(query, resource, search, queryable) {
246
+ const searchable = Object.entries(resource.fields).filter(([, f]) => f.searchable);
247
+ if (!searchable.length || searchable.some(([key]) => !queryable(key)))
248
+ throw searchUnavailable();
249
+ query.whereRaw("r.search_vector @@ plainto_tsquery('simple', ?)", [search]);
250
+ }
251
+ /**
252
+ * The authorized, filtered list query of list() before keyset paging and ordering, with
253
+ * what paging needs. Shared with countUpTo() so a count uses exactly the list's rules.
254
+ */
255
+ function listQuery(ctx, name, actor, options) {
256
+ const resource = ctx.registry.get(name);
257
+ const ability = authorizeAction(ctx, resource, actor, 'view');
258
+ const trashed = options.trashed === true;
259
+ // The trash is reached through the delete permission: restore reuses the delete rule.
260
+ if (trashed)
261
+ authorizeAction(ctx, resource, actor, 'delete');
262
+ const queryable = (key) => canQueryField(resource, actor, ability, key);
263
+ const limit = Math.max(1, Math.min(100, Math.floor(Number(options.limit) || 25)));
264
+ // The user's sort, else the resource's declared one, else newest first (owner, 2.3.0).
265
+ const chosen = options.sort ?? resource.defaultSort?.field;
266
+ const sort = chosen ?? NEWEST;
267
+ const direction = options.direction === 'desc' || options.direction === 'asc'
268
+ ? options.direction
269
+ : options.sort
270
+ ? 'asc'
271
+ : chosen
272
+ ? (resource.defaultSort?.direction ?? 'asc')
273
+ : 'desc';
274
+ if (sort !== 'id' && sort !== NEWEST && !resource.fields[sort]?.sortable)
275
+ throw new AdulaError(422, 'E_SORT', 'Unsupported sort field');
276
+ // The creation time orders the list only by default; it is not a field a request names.
277
+ if (options.sort === NEWEST)
278
+ throw new AdulaError(422, 'E_SORT', 'Unsupported sort field');
279
+ // Sorting/filtering private fields would otherwise reveal their values indirectly.
280
+ if (sort !== 'id' && sort !== NEWEST && !queryable(sort))
281
+ throw forbiddenField('Forbidden sort field');
282
+ const sortColumn = sort === NEWEST ? 'r.created_at' : `r.${resource.fields[sort]?.column ?? columnName(sort)}`;
283
+ const base = ctx.db(`${name} as r`);
284
+ if (trashed) {
285
+ base.whereNotNull('r.deleted_at');
286
+ // Deleted rows are listed when both the view and the delete rules reach them.
287
+ const viewable = authorizationSql(ability, 'view', resource);
288
+ base.whereRaw(viewable.text, viewable.bindings);
289
+ }
290
+ else
291
+ base.whereNull('r.deleted_at');
292
+ if (options.ids) {
293
+ const ids = options.ids.filter((id) => Number.isSafeInteger(id) && id > 0);
294
+ if (ids.length === 0)
295
+ base.whereRaw('false');
296
+ else
297
+ base.whereIn('r.id', ids);
298
+ }
299
+ const query = accessibleBy(base, ability, actor, trashed ? 'delete' : 'view', resource);
300
+ query.select(columns(resource, ability, false, sort === NEWEST ? [] : [sort]));
301
+ // The creation time as PostgreSQL prints it, microseconds included: a page's cursor must
302
+ // compare exactly, which a JavaScript Date (milliseconds) would not.
303
+ if (sort === NEWEST)
304
+ query.select(ctx.db.raw('r.created_at::text as ??', [NEWEST_VALUE]));
305
+ if (resource.scoped)
306
+ query.select('ou.path as org_path');
307
+ if (options.search)
308
+ applySearch(query, resource, options.search, queryable);
309
+ applyFilters(query, resource, options.filters ?? {}, queryable);
310
+ if (options.tag !== undefined && options.tag !== null && options.tag !== '') {
311
+ if (typeof options.tag !== 'string' || options.tag.length > 60)
312
+ throw invalidFilter('Invalid tag filter');
313
+ query.whereExists((exists) => exists
314
+ .from('taggables as tg')
315
+ .join('tags as tn', 'tn.id', 'tg.tag_id')
316
+ .where('tg.resource', name)
317
+ .whereRaw('tg.record_id = r.id')
318
+ .where('tn.name', options.tag));
319
+ }
320
+ return { resource, ability, trashed, limit, sort, direction, sortColumn, query };
321
+ }
322
+ /**
323
+ * How many records list() would return for these options, counting at most `max` + 1,
324
+ * so callers can refuse an oversized request with one bounded query.
325
+ */
326
+ export async function countUpTo(ctx, name, actor, options, max) {
327
+ const { query } = listQuery(ctx, name, actor, options);
328
+ const bounded = query
329
+ .clearSelect()
330
+ .select('r.id')
331
+ .limit(max + 1);
332
+ const [row] = await ctx.db.from(bounded.as('bounded')).count('* as count');
333
+ return Number(row.count);
334
+ }
335
+ /**
336
+ * Distinct tag names on records list() would return to the actor, for tag suggestions
337
+ * (RecordCollaboration.tagOptions): the same rules, organization scope and soft-delete
338
+ * filter apply, so a suggestion never names a tag found only on records the actor cannot see.
339
+ */
340
+ export async function tagNames(ctx, name, actor, limit) {
341
+ const { query } = listQuery(ctx, name, actor, {});
342
+ const ids = query.clearSelect().select('r.id');
343
+ const names = await ctx
344
+ .db('taggables as t')
345
+ .join('tags', 'tags.id', 't.tag_id')
346
+ .where('t.resource', name)
347
+ .whereIn('t.record_id', ids)
348
+ .distinct('tags.name')
349
+ .orderBy('tags.name')
350
+ .limit(limit)
351
+ .pluck('tags.name');
352
+ return names.map(String);
353
+ }
354
+ export async function list(ctx, name, actor, options = {}) {
355
+ const { resource, ability, trashed, limit, sort, direction, sortColumn, query } = listQuery(ctx, name, actor, options);
356
+ // Estimate the authorized, filtered query, never the deployment-wide table cardinality.
357
+ // Only the first page pays for the extra planner round trip; later pages keep its figure.
358
+ let estimatedTotal;
359
+ // The authorized, filtered query before the cursor and the page limit narrow it.
360
+ const counted = query.clone();
361
+ if (options.estimate !== false && !options.cursor) {
362
+ estimatedTotal = await estimate(ctx.db, query);
363
+ }
364
+ if (options.cursor) {
365
+ const cursor = decodeCursor(resource, options.cursor, sort, direction);
366
+ query.where((q) => {
367
+ if (cursor.value === null)
368
+ q.whereNull(sortColumn).andWhere('r.id', direction === 'asc' ? '>' : '<', cursor.id);
369
+ else
370
+ q.where(sortColumn, direction === 'asc' ? '>' : '<', cursor.value)
371
+ .orWhere((same) => same
372
+ .where(sortColumn, cursor.value)
373
+ .andWhere('r.id', direction === 'asc' ? '>' : '<', cursor.id))
374
+ .orWhereNull(sortColumn);
375
+ });
376
+ }
377
+ query.orderBy(sortColumn, direction, 'last');
378
+ if (sort !== 'id')
379
+ query.orderBy('r.id', direction);
380
+ const rows = await query.limit(limit + 1);
381
+ const records = rows
382
+ .slice(0, limit)
383
+ .map((row) => fromRow(row, resource));
384
+ await withLinks(ctx.db, resource, records);
385
+ const last = records.at(-1);
386
+ const lastRow = rows[Math.min(rows.length, limit) - 1];
387
+ if (estimatedTotal !== undefined) {
388
+ estimatedTotal =
389
+ !options.cursor && rows.length <= limit
390
+ ? rows.length
391
+ : estimatedTotal < EXACT_COUNT_LIMIT
392
+ ? await exactCount(ctx.db, counted, Math.max(estimatedTotal, rows.length))
393
+ : Math.max(estimatedTotal, rows.length);
394
+ }
395
+ const hydrated = await hydrate(ctx.db, resource, records, ctx.attachments);
396
+ const title = await titler(ctx, resource);
397
+ return {
398
+ data: hydrated.map((record) => {
399
+ const row = serialize(resource, record, ability, actor);
400
+ // Like related rows, list rows carry the title formatted from the visible values (#110).
401
+ return { ...row, _title: title(row) };
402
+ }),
403
+ permissions: Object.fromEntries(records.map((record) => [
404
+ String(record.id),
405
+ trashed
406
+ ? trashedPermissions(resource, record, actor, ability)
407
+ : permissions(resource, record, actor, ability),
408
+ ])),
409
+ meta: {
410
+ limit,
411
+ estimatedTotal,
412
+ nextCursor: rows.length > limit && last
413
+ ? Buffer.from(JSON.stringify({
414
+ id: last.id,
415
+ value: sort === NEWEST ? lastRow?.[NEWEST_VALUE] : (last[sort] ?? null),
416
+ sort,
417
+ direction,
418
+ })).toString('base64url')
419
+ : null,
420
+ },
421
+ related: await preload(ctx, resource, records, actor),
422
+ };
423
+ }
424
+ /** A deleted record can only be viewed or restored; restore follows the delete rule. */
425
+ function trashedPermissions(resource, record, actor, ability) {
426
+ return {
427
+ ...Object.fromEntries(resource.actions.map((action) => [action, false])),
428
+ view: canRecord(ability, actor, resource, 'view', record),
429
+ restore: canRecord(ability, actor, resource, 'delete', record),
430
+ };
431
+ }
432
+ /**
433
+ * Planner estimates are coarse for small tables and scoped filters (#111): below this figure the
434
+ * list counts exactly, so a figure under it is the real count of the authorized, filtered rows.
435
+ */
436
+ const EXACT_COUNT_LIMIT = 1000;
437
+ /** The exact row count up to EXACT_COUNT_LIMIT; above it, an estimate known to exceed the limit. */
438
+ async function exactCount(db, query, estimated) {
439
+ const bounded = query
440
+ .clearSelect()
441
+ .clearOrder()
442
+ .select('r.id')
443
+ .limit(EXACT_COUNT_LIMIT + 1);
444
+ const [row] = await db.from(bounded.as('bounded')).count('* as count');
445
+ const count = Number(row.count);
446
+ return count > EXACT_COUNT_LIMIT ? Math.max(estimated, EXACT_COUNT_LIMIT + 1) : count;
447
+ }
448
+ /** The planner's row estimate of a list query, reused briefly for the identical query. */
449
+ async function estimate(db, query) {
450
+ const compiled = query.clone().clearSelect().select('r.id').toSQL();
451
+ // The planner estimate is approximate by nature; reuse it briefly for the same
452
+ // authorized, filtered query instead of planning it on every first page.
453
+ const key = `${compiled.sql}\u0000${JSON.stringify(compiled.bindings)}`;
454
+ const cached = estimates.get(key);
455
+ if (cached && cached.at > Date.now() - ESTIMATE_TTL_MS)
456
+ return cached.rows;
457
+ const plan = await db.raw(`EXPLAIN (FORMAT JSON) ${compiled.sql}`, [...compiled.bindings]);
458
+ const rows = Number(plan.rows[0]['QUERY PLAN'][0].Plan['Plan Rows']);
459
+ if (estimates.size >= ESTIMATE_CACHE_LIMIT)
460
+ estimates.delete(estimates.keys().next().value);
461
+ estimates.set(key, { rows, at: Date.now() });
462
+ return rows;
463
+ }
464
+ /** A keyset cursor of list(), checked against the current sort and the sort field's type. */
465
+ function decodeCursor(resource, encoded, sort, direction) {
466
+ let cursor;
467
+ try {
468
+ if (typeof encoded !== 'string')
469
+ throw new Error('Cursor must be a string');
470
+ cursor = JSON.parse(Buffer.from(encoded, 'base64url').toString());
471
+ }
472
+ catch {
473
+ throw invalidCursor();
474
+ }
475
+ if (!cursor ||
476
+ typeof cursor !== 'object' ||
477
+ Array.isArray(cursor) ||
478
+ cursor.sort !== sort ||
479
+ cursor.direction !== direction ||
480
+ !Number.isSafeInteger(cursor.id) ||
481
+ cursor.id < 1 ||
482
+ cursor.id > 2147483647 ||
483
+ cursor.value === undefined ||
484
+ (cursor.value !== null && !['number', 'string', 'boolean'].includes(typeof cursor.value)))
485
+ throw invalidCursor();
486
+ // The sort key must have the sort field's type, or PostgreSQL rejects the comparison.
487
+ try {
488
+ if (sort === NEWEST) {
489
+ // PostgreSQL's own text form of a timestamp with time zone, as the list printed it.
490
+ if (typeof cursor.value !== 'string' ||
491
+ !/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(\.\d{1,6})?[+-]\d{2}(:\d{2})?$/.test(cursor.value))
492
+ throw new Error('Cursor time mismatch');
493
+ }
494
+ else if (sort === 'id') {
495
+ if (cursor.value !== cursor.id)
496
+ throw new Error('Cursor id mismatch');
497
+ }
498
+ else
499
+ cursor.value = fieldValue(resource.fields[sort], cursor.value);
500
+ }
501
+ catch {
502
+ throw invalidCursor();
503
+ }
504
+ return cursor;
505
+ }
506
+ /** Counts and totals over viewable records; see ResourceService.aggregate. */
507
+ export async function aggregate(ctx, name, actor, options = {}) {
508
+ const resource = ctx.registry.get(name);
509
+ const ability = authorizeAction(ctx, resource, actor, 'view');
510
+ const standard = new Set([
511
+ ...(resource.submittable ? ['docStatus'] : []),
512
+ ...(resource.scoped ? ['orgUnitId'] : []),
513
+ ]);
514
+ const column = (key) => `r.${resource.fields[key]?.column ?? columnName(key)}`;
515
+ const queryable = (key, kinds) => {
516
+ if (typeof key !== 'string')
517
+ return false;
518
+ if (standard.has(key))
519
+ return !kinds;
520
+ // Own keys only: names such as "constructor" are not fields.
521
+ if (!Object.hasOwn(resource.fields, key))
522
+ return false;
523
+ const field = resource.fields[key];
524
+ return (Boolean(field) &&
525
+ !['hasMany', 'manyToMany', 'json', 'attachment'].includes(field.type) &&
526
+ (!kinds || kinds.includes(field.type)) &&
527
+ canQueryField(resource, actor, ability, key));
528
+ };
529
+ const groupBy = options.groupBy ?? [];
530
+ const sums = options.sum ?? [];
531
+ if (!Array.isArray(groupBy) || groupBy.length > 3 || !Array.isArray(sums) || sums.length > 5)
532
+ throw new AdulaError(422, 'E_AGGREGATE', 'Group by up to three fields and total up to five');
533
+ for (const key of groupBy)
534
+ if (!queryable(key))
535
+ throw forbiddenField(`Field cannot be grouped: ${String(key)}`);
536
+ for (const key of sums)
537
+ if (!queryable(key, ['integer', 'money', 'decimal', 'percent']))
538
+ throw forbiddenField(`Field cannot be totalled: ${String(key)}`);
539
+ const query = accessibleBy(ctx.db(`${name} as r`).whereNull('r.deleted_at'), ability, actor, 'view', resource);
540
+ // A manyToMany field cannot be grouped or totalled, but filters by one linked id or none.
541
+ applyFilters(query, resource, options.filters ?? {}, (key) => queryable(key) ||
542
+ (Object.hasOwn(resource.fields, key) &&
543
+ resource.fields[key].type === 'manyToMany' &&
544
+ canQueryField(resource, actor, ability, key)));
545
+ if (options.where !== undefined && options.where !== null) {
546
+ if (typeof options.where !== 'object' || Array.isArray(options.where))
547
+ throw invalidFilter('Conditions must be an object');
548
+ for (const key of Object.keys(options.where))
549
+ if (!queryable(key))
550
+ throw forbiddenField(`Field cannot be filtered: ${key}`);
551
+ let where;
552
+ try {
553
+ where = conditionSql(resolveActorConditions(options.where, actor.id), resource);
554
+ }
555
+ catch (error) {
556
+ throw invalidFilter(error.message);
557
+ }
558
+ query.whereRaw(where.text, where.bindings);
559
+ }
560
+ if (options.search)
561
+ applySearch(query, resource, options.search, (key) => queryable(key));
562
+ const selects = groupBy.map((key, index) => `${key === 'docStatus' ? 'r.doc_status' : column(key)} as g${index}`);
563
+ if (options.count !== false)
564
+ selects.push(ctx.db.raw('count(*)::int as count'));
565
+ sums.forEach((key, index) => selects.push(ctx.db.raw(`sum(??)::text as s${index}`, [column(key)])));
566
+ query.select(selects);
567
+ groupBy.forEach((_, index) => query.groupByRaw(`${index + 1}`));
568
+ groupBy.forEach((_, index) => query.orderByRaw(`${index + 1} ASC NULLS LAST`));
569
+ const rows = await query.limit(AGGREGATE_GROUP_LIMIT + 1);
570
+ return {
571
+ truncated: rows.length > AGGREGATE_GROUP_LIMIT,
572
+ rows: rows.slice(0, AGGREGATE_GROUP_LIMIT).map((row) => {
573
+ const group = fromRow(Object.fromEntries(groupBy.map((key, index) => [
574
+ key === 'docStatus'
575
+ ? 'doc_status'
576
+ : key === 'orgUnitId'
577
+ ? 'org_unit_id'
578
+ : (resource.fields[key].column ?? columnName(key)),
579
+ row[`g${index}`],
580
+ ])), resource);
581
+ return {
582
+ group: Object.fromEntries(groupBy.map((key) => [key, jsonValue(group[key])])),
583
+ ...(options.count !== false ? { count: Number(row.count) } : {}),
584
+ ...(sums.length
585
+ ? {
586
+ sum: Object.fromEntries(sums.map((key, index) => [
587
+ key,
588
+ row[`s${index}`] === null ? null : String(row[`s${index}`]),
589
+ ])),
590
+ }
591
+ : {}),
592
+ };
593
+ }),
594
+ };
595
+ }