adula 2.1.0 → 2.2.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 (214) hide show
  1. package/README.md +149 -18
  2. package/build/agent/AGENTS.template.md +4 -4
  3. package/build/agent/capabilities.md +22 -11
  4. package/build/agent/skills/adula-frontend-design/SKILL.md +1 -1
  5. package/build/agent/skills/idea-review/SKILL.md +2 -2
  6. package/build/commands/adula_outbox.d.ts +10 -0
  7. package/build/commands/adula_outbox.js +11 -0
  8. package/build/commands/adula_restore_reconcile.d.ts +10 -0
  9. package/build/commands/adula_restore_reconcile.js +34 -0
  10. package/build/commands/adula_runtime_health.d.ts +10 -0
  11. package/build/commands/adula_runtime_health.js +27 -0
  12. package/build/commands/adula_uploads_prune.d.ts +10 -0
  13. package/build/commands/adula_uploads_prune.js +16 -0
  14. package/build/commands/app.d.ts +10 -0
  15. package/build/commands/app.js +64 -0
  16. package/build/commands/backup_create.d.ts +11 -0
  17. package/build/commands/backup_create.js +99 -0
  18. package/build/commands/backup_restore_files.d.ts +11 -0
  19. package/build/commands/backup_restore_files.js +44 -0
  20. package/build/commands/backup_restore_test.d.ts +12 -0
  21. package/build/commands/backup_restore_test.js +185 -0
  22. package/build/commands/backup_services.d.ts +31 -0
  23. package/build/commands/backup_services.js +6 -0
  24. package/build/commands/backup_verify.d.ts +9 -0
  25. package/build/commands/backup_verify.js +59 -0
  26. package/build/commands/backup_verify_snapshot.d.ts +10 -0
  27. package/build/commands/backup_verify_snapshot.js +37 -0
  28. package/build/commands/client.d.ts +16 -0
  29. package/build/commands/client.js +71 -0
  30. package/build/commands/doctor.js +4 -1
  31. package/build/commands/install.d.ts +8 -0
  32. package/build/commands/install.js +63 -45
  33. package/build/commands/main.d.ts +3 -2
  34. package/build/commands/main.js +26 -0
  35. package/build/commands/module_add.js +4 -20
  36. package/build/commands/resource.d.ts +2 -0
  37. package/build/commands/resource.js +12 -3
  38. package/build/commands/resource_migration.d.ts +15 -0
  39. package/build/commands/resource_migration.js +72 -0
  40. package/build/commands/resource_snapshot.d.ts +2 -0
  41. package/build/commands/resource_snapshot.js +3 -0
  42. package/build/commands/sla_evaluate.d.ts +14 -0
  43. package/build/commands/sla_evaluate.js +16 -0
  44. package/build/commands/ui.js +4 -2
  45. package/build/commands/ui_css.d.ts +9 -0
  46. package/build/commands/ui_css.js +19 -0
  47. package/build/commands/upgrade.d.ts +1 -1
  48. package/build/commands/upgrade.js +1 -1
  49. package/build/configure.js +1 -1
  50. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  51. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  52. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  53. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  54. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  55. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  56. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  57. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  58. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  59. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  60. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  61. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  62. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  63. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  64. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  65. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  66. package/build/index.d.ts +56 -10
  67. package/build/index.js +34 -6
  68. package/build/providers/adula_provider.d.ts +2 -0
  69. package/build/providers/adula_provider.js +7 -0
  70. package/build/src/admin/contracts.js +1 -1
  71. package/build/src/admin/controller.d.ts +14 -1
  72. package/build/src/admin/controller.js +77 -13
  73. package/build/src/admin/errors.d.ts +32 -0
  74. package/build/src/admin/errors.js +63 -1
  75. package/build/src/admin/presentation.d.ts +21 -2
  76. package/build/src/admin/resource/editor.d.ts +59 -0
  77. package/build/src/admin/resource/editor.js +323 -0
  78. package/build/src/admin/resource/export.d.ts +37 -0
  79. package/build/src/admin/resource/export.js +181 -0
  80. package/build/src/admin/resource/lifecycle.d.ts +21 -0
  81. package/build/src/admin/resource/lifecycle.js +91 -0
  82. package/build/src/admin/resource/query.d.ts +100 -0
  83. package/build/src/admin/resource/query.js +508 -0
  84. package/build/src/admin/resource/read.d.ts +106 -0
  85. package/build/src/admin/resource/read.js +327 -0
  86. package/build/src/admin/resource/shared.d.ts +77 -0
  87. package/build/src/admin/resource/shared.js +222 -0
  88. package/build/src/admin/resource/trash.d.ts +10 -0
  89. package/build/src/admin/resource/trash.js +56 -0
  90. package/build/src/admin/resource/write.d.ts +57 -0
  91. package/build/src/admin/resource/write.js +574 -0
  92. package/build/src/admin/resource_service.d.ts +66 -193
  93. package/build/src/admin/resource_service.js +69 -1345
  94. package/build/src/attachments/attachment_service.d.ts +46 -2
  95. package/build/src/attachments/attachment_service.js +96 -4
  96. package/build/src/auth/conditions.d.ts +5 -0
  97. package/build/src/auth/conditions.js +26 -3
  98. package/build/src/auth/sql.js +17 -5
  99. package/build/src/auth/two_factor.d.ts +96 -0
  100. package/build/src/auth/two_factor.js +259 -0
  101. package/build/src/collaboration/assignments.d.ts +36 -1
  102. package/build/src/collaboration/assignments.js +132 -66
  103. package/build/src/collaboration/record_collaboration.d.ts +2 -3
  104. package/build/src/collaboration/record_collaboration.js +19 -16
  105. package/build/src/collaboration/shared.d.ts +16 -0
  106. package/build/src/collaboration/shared.js +21 -0
  107. package/build/src/commands/app_scaffold.d.ts +72 -0
  108. package/build/src/commands/app_scaffold.js +285 -0
  109. package/build/src/commands/capabilities.js +34 -8
  110. package/build/src/commands/doctor.d.ts +14 -2
  111. package/build/src/commands/doctor.js +50 -5
  112. package/build/src/commands/gap_report.d.ts +1 -1
  113. package/build/src/commands/gap_report.js +2 -2
  114. package/build/src/commands/generator.d.ts +37 -1
  115. package/build/src/commands/generator.js +61 -18
  116. package/build/src/commands/snapshot.d.ts +10 -13
  117. package/build/src/commands/snapshot.js +31 -14
  118. package/build/src/commands/source_markers.d.ts +10 -0
  119. package/build/src/commands/source_markers.js +29 -0
  120. package/build/src/core/activity.d.ts +2 -0
  121. package/build/src/core/activity.js +7 -1
  122. package/build/src/core/administrators.d.ts +38 -0
  123. package/build/src/core/administrators.js +129 -0
  124. package/build/src/core/html_sanitizer.d.ts +20 -0
  125. package/build/src/core/html_sanitizer.js +261 -0
  126. package/build/src/core/like.d.ts +5 -0
  127. package/build/src/core/like.js +5 -0
  128. package/build/src/core/lookups.d.ts +80 -0
  129. package/build/src/core/lookups.js +319 -0
  130. package/build/src/core/message_templates.d.ts +7 -2
  131. package/build/src/core/message_templates.js +72 -11
  132. package/build/src/core/module_seed.js +2 -1
  133. package/build/src/core/notification_channels.d.ts +235 -0
  134. package/build/src/core/notification_channels.js +660 -0
  135. package/build/src/core/roles.js +2 -2
  136. package/build/src/core/saved_views.d.ts +8 -1
  137. package/build/src/core/saved_views.js +36 -2
  138. package/build/src/core/sequences.d.ts +32 -0
  139. package/build/src/core/sequences.js +97 -0
  140. package/build/src/core/settings.d.ts +5 -0
  141. package/build/src/core/settings.js +19 -2
  142. package/build/src/core/template_language.d.ts +61 -0
  143. package/build/src/core/template_language.js +141 -0
  144. package/build/src/core/ui_preferences.d.ts +4 -0
  145. package/build/src/core/ui_preferences.js +4 -1
  146. package/build/src/core/user_invitations.d.ts +5 -1
  147. package/build/src/core/user_invitations.js +7 -1
  148. package/build/src/core/users.js +1 -1
  149. package/build/src/database/calendar_days.d.ts +19 -0
  150. package/build/src/database/calendar_days.js +36 -0
  151. package/build/src/database/schema.d.ts +155 -2
  152. package/build/src/database/schema.js +531 -59
  153. package/build/src/database/schema_diff.d.ts +56 -0
  154. package/build/src/database/schema_diff.js +157 -0
  155. package/build/src/events/record_mutation.d.ts +2 -1
  156. package/build/src/events/record_mutation.js +1 -0
  157. package/build/src/integrations/api_client.d.ts +37 -0
  158. package/build/src/integrations/api_client.js +552 -0
  159. package/build/src/integrations/import_adapters.d.ts +37 -0
  160. package/build/src/integrations/import_adapters.js +35 -0
  161. package/build/src/integrations/imports.d.ts +118 -16
  162. package/build/src/integrations/imports.js +406 -73
  163. package/build/src/integrations/openapi.d.ts +3 -1
  164. package/build/src/integrations/openapi.js +454 -31
  165. package/build/src/integrations/outbound.d.ts +51 -0
  166. package/build/src/integrations/outbound.js +195 -0
  167. package/build/src/integrations/print.d.ts +21 -1
  168. package/build/src/integrations/print.js +63 -21
  169. package/build/src/integrations/print_templates.d.ts +216 -0
  170. package/build/src/integrations/print_templates.js +1015 -0
  171. package/build/src/integrations/sync_jobs.d.ts +139 -0
  172. package/build/src/integrations/sync_jobs.js +416 -0
  173. package/build/src/integrations/webhooks.d.ts +12 -12
  174. package/build/src/integrations/webhooks.js +34 -43
  175. package/build/src/languages/ar.d.ts +11 -0
  176. package/build/src/languages/ar.js +336 -0
  177. package/build/src/languages/ar_ui.d.ts +332 -0
  178. package/build/src/languages/ar_ui.js +333 -0
  179. package/build/src/languages/catalog.d.ts +66 -0
  180. package/build/src/languages/catalog.js +152 -0
  181. package/build/src/languages/en.d.ts +7 -0
  182. package/build/src/languages/en.js +330 -0
  183. package/build/src/languages/en_ui.d.ts +3 -0
  184. package/build/src/languages/en_ui.js +328 -0
  185. package/build/src/languages/validation.d.ts +26 -0
  186. package/build/src/languages/validation.js +60 -0
  187. package/build/src/lists/bulk_actions.d.ts +89 -0
  188. package/build/src/lists/bulk_actions.js +268 -0
  189. package/build/src/lists/dashboards.d.ts +96 -0
  190. package/build/src/lists/dashboards.js +241 -0
  191. package/build/src/mcp/tools.js +1 -1
  192. package/build/src/resource/define_resource.d.ts +18 -1
  193. package/build/src/resource/define_resource.js +205 -18
  194. package/build/src/resource/definition.d.ts +44 -0
  195. package/build/src/resource/definition.js +171 -0
  196. package/build/src/resource/registry.js +15 -4
  197. package/build/src/resource/types.d.ts +304 -16
  198. package/build/src/resource/values.d.ts +56 -1
  199. package/build/src/resource/values.js +237 -5
  200. package/build/src/services/settings.d.ts +2 -0
  201. package/build/src/services/settings.js +5 -1
  202. package/build/src/upgrade/legacy.js +2 -2
  203. package/build/src/workflows/calendar.d.ts +9 -0
  204. package/build/src/workflows/calendar.js +44 -0
  205. package/build/src/workflows/define_workflow.d.ts +48 -3
  206. package/build/src/workflows/define_workflow.js +57 -13
  207. package/build/src/workflows/delegations.d.ts +93 -0
  208. package/build/src/workflows/delegations.js +287 -0
  209. package/build/src/workflows/engine.d.ts +69 -4
  210. package/build/src/workflows/engine.js +441 -83
  211. package/build/src/workflows/sla.d.ts +15 -0
  212. package/build/src/workflows/sla.js +8 -0
  213. package/build/stubs/resource_contract.txt +12 -1
  214. package/package.json +5 -2
@@ -0,0 +1,100 @@
1
+ import type { Field, JsonValue } from '../../resource/types.js';
2
+ import { type Actor } from '../../auth/ability.js';
3
+ import { type Conditions } from '../../auth/conditions.js';
4
+ import { type ResourceContext } from './shared.js';
5
+ export type AggregateOptions = {
6
+ /** Up to three queryable fields (docStatus and orgUnitId are also accepted). */
7
+ groupBy?: string[];
8
+ /** Count rows per group (default true). */
9
+ count?: boolean;
10
+ /** Integer, money, decimal or percent fields to total per group; totals are decimal strings. */
11
+ sum?: string[];
12
+ /** Equality filters, as in list(). */
13
+ filters?: Record<string, unknown>;
14
+ /** Role-rule style conditions ($eq, $ne, $in, $lt, $gt, $like, "$actor.id"). */
15
+ where?: Conditions;
16
+ search?: string;
17
+ };
18
+ export type AggregateRow = {
19
+ group: Record<string, JsonValue>;
20
+ count?: number;
21
+ sum?: Record<string, string | null>;
22
+ };
23
+ export type ListOptions = {
24
+ limit?: number;
25
+ cursor?: string;
26
+ search?: string;
27
+ sort?: string;
28
+ direction?: 'asc' | 'desc';
29
+ filters?: Record<string, unknown>;
30
+ /** Only records carrying this tag (see RecordCollaboration.setTags). */
31
+ tag?: string;
32
+ estimate?: boolean;
33
+ /**
34
+ * Only soft-deleted records («المحذوفات»), for actors who may delete records of the
35
+ * resource (403 otherwise). Rows are those the actor's delete rules reach, and each
36
+ * row's permissions carry `restore` (ADR 046).
37
+ */
38
+ trashed?: boolean;
39
+ };
40
+ /** A scalar filter operand: equality, or one value of an operator. */
41
+ export type ListFilterScalar = string | number | boolean | null;
42
+ /**
43
+ * A list or aggregate filter value (ADR 046): a scalar (equality, null = IS NULL) or one
44
+ * operator object. `in` takes 1–50 values (an array or a comma-separated string);
45
+ * `gte`/`lte` are an inclusive range and may be combined; `empty` matches NULL (and the
46
+ * empty string on text fields) when true and the opposite when false.
47
+ */
48
+ export type ListFilterValue = ListFilterScalar | {
49
+ in: ListFilterScalar[] | string;
50
+ } | {
51
+ gte?: ListFilterScalar;
52
+ lte?: ListFilterScalar;
53
+ } | {
54
+ empty: boolean | 'true' | 'false';
55
+ };
56
+ /** Most values an `in` filter accepts. */
57
+ export declare const FILTER_IN_LIMIT = 50;
58
+ /** A typed filter condition, after validation and coercion of every operand. */
59
+ export type FilterCondition = {
60
+ kind: 'eq';
61
+ value: unknown;
62
+ } | {
63
+ kind: 'in';
64
+ values: unknown[];
65
+ } | {
66
+ kind: 'range';
67
+ gte?: unknown;
68
+ lte?: unknown;
69
+ } | {
70
+ kind: 'empty';
71
+ empty: boolean;
72
+ };
73
+ /**
74
+ * Validates one filter value against its field and coerces every operand to the field's
75
+ * stored representation. Throws 422 E_FILTER for an unknown operator, an operator the
76
+ * field type does not support, or an operand that does not fit the field.
77
+ */
78
+ export declare function filterCondition(key: string, field: Field, value: unknown): FilterCondition;
79
+ /**
80
+ * How many records list() would return for these options, counting at most `max` + 1,
81
+ * so callers can refuse an oversized request with one bounded query.
82
+ */
83
+ export declare function countUpTo(ctx: ResourceContext, name: string, actor: Actor, options: ListOptions, max: number): Promise<number>;
84
+ export declare function list(ctx: ResourceContext, name: string, actor: Actor, options?: ListOptions): Promise<{
85
+ data: import("../../resource/types.js").SerializedRecord[];
86
+ permissions: {
87
+ [k: string]: Partial<Record<import("../../resource/types.js").Action | "restore", boolean>>;
88
+ };
89
+ meta: {
90
+ limit: number;
91
+ estimatedTotal: number | undefined;
92
+ nextCursor: string | null;
93
+ };
94
+ related: Record<string, import("../../resource/types.js").SerializedRecord[]>;
95
+ }>;
96
+ /** Counts and totals over viewable records; see ResourceService.aggregate. */
97
+ export declare function aggregate(ctx: ResourceContext, name: string, actor: Actor, options?: AggregateOptions): Promise<{
98
+ rows: AggregateRow[];
99
+ truncated: boolean;
100
+ }>;
@@ -0,0 +1,508 @@
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 } 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
+ * Coerces a query-string or API filter/cursor value to the field's stored representation,
17
+ * so a mismatch is rejected before PostgreSQL raises an invalid-input error.
18
+ */
19
+ function queryValue(field, value) {
20
+ if (value === null)
21
+ return null;
22
+ let candidate = value;
23
+ switch (field.type) {
24
+ case 'integer':
25
+ case 'belongsTo':
26
+ case 'user':
27
+ case 'attachment':
28
+ if (typeof value === 'string' && /^-?\d{1,10}$/.test(value))
29
+ candidate = Number(value);
30
+ break;
31
+ // A multiSelect filter is one option it contains; a manyToMany filter one linked id.
32
+ case 'multiSelect':
33
+ return fieldValue({ ...field, min: undefined, max: undefined }, [String(value)])[0];
34
+ case 'manyToMany':
35
+ return fieldValue(field, [
36
+ typeof value === 'string' && /^\d{1,10}$/.test(value) ? Number(value) : value,
37
+ ])[0];
38
+ case 'decimal':
39
+ case 'percent':
40
+ case 'enum':
41
+ case 'email':
42
+ case 'phone':
43
+ case 'url':
44
+ if (typeof value === 'number')
45
+ candidate = String(value);
46
+ break;
47
+ case 'boolean':
48
+ if (value === 'true')
49
+ candidate = true;
50
+ else if (value === 'false')
51
+ candidate = false;
52
+ break;
53
+ case 'string':
54
+ case 'text':
55
+ case 'lookup':
56
+ if (typeof value === 'number' || typeof value === 'boolean')
57
+ candidate = String(value);
58
+ break;
59
+ case 'money':
60
+ case 'date':
61
+ case 'datetime':
62
+ break;
63
+ default:
64
+ throw new Error('Field cannot be compared');
65
+ }
66
+ // Length, pattern and range limits describe stored values, not the probes compared with them.
67
+ return fieldValue({ ...field, min: undefined, max: undefined, pattern: undefined }, candidate);
68
+ }
69
+ /** Most values an `in` filter accepts. */
70
+ export const FILTER_IN_LIMIT = 50;
71
+ const IN_TYPES = new Set([
72
+ 'string',
73
+ 'text',
74
+ 'email',
75
+ 'phone',
76
+ 'url',
77
+ 'enum',
78
+ 'lookup',
79
+ 'integer',
80
+ 'belongsTo',
81
+ 'user',
82
+ ]);
83
+ const RANGE_TYPES = new Set(['integer', 'money', 'decimal', 'percent', 'date', 'datetime']);
84
+ const TEXT_TYPES = new Set(['string', 'text', 'email', 'phone', 'url', 'enum', 'lookup']);
85
+ const COLLECTION_TYPES = new Set(['multiSelect', 'manyToMany']);
86
+ function isScalar(value) {
87
+ return value === null || ['string', 'number', 'boolean'].includes(typeof value);
88
+ }
89
+ /** Query strings parse long `in[]` lists as objects with index keys; read them as arrays. */
90
+ function asList(value) {
91
+ if (Array.isArray(value))
92
+ return value;
93
+ if (typeof value === 'string')
94
+ return value.split(',').map((entry) => entry.trim());
95
+ if (value && typeof value === 'object') {
96
+ const keys = Object.keys(value);
97
+ if (keys.length && keys.every((key) => /^\d{1,3}$/.test(key)))
98
+ return keys
99
+ .sort((a, b) => Number(a) - Number(b))
100
+ .map((key) => value[key]);
101
+ }
102
+ return null;
103
+ }
104
+ /**
105
+ * Validates one filter value against its field and coerces every operand to the field's
106
+ * stored representation. Throws 422 E_FILTER for an unknown operator, an operator the
107
+ * field type does not support, or an operand that does not fit the field.
108
+ */
109
+ export function filterCondition(key, field, value) {
110
+ const coerce = (operand) => {
111
+ try {
112
+ return queryValue(field, operand);
113
+ }
114
+ catch {
115
+ throw invalidFilter(`Invalid filter value: ${key}`);
116
+ }
117
+ };
118
+ if (isScalar(value))
119
+ return { kind: 'eq', value: coerce(value) };
120
+ if (!value || typeof value !== 'object' || Array.isArray(value))
121
+ throw invalidFilter('Invalid filter value');
122
+ const operators = Object.keys(value);
123
+ const entry = value;
124
+ if (operators.length === 1 && operators[0] === 'in') {
125
+ if (!IN_TYPES.has(field.type))
126
+ throw invalidFilter(`Unsupported filter operator: ${key}`);
127
+ const operands = asList(entry.in);
128
+ if (!operands || !operands.length || operands.length > FILTER_IN_LIMIT)
129
+ throw invalidFilter(`Invalid filter value: ${key}`);
130
+ const values = operands.map((operand) => {
131
+ if (operand === null || operand === '' || !isScalar(operand))
132
+ throw invalidFilter(`Invalid filter value: ${key}`);
133
+ return coerce(operand);
134
+ });
135
+ return { kind: 'in', values: [...new Set(values)] };
136
+ }
137
+ if (operators.length === 1 && operators[0] === 'empty') {
138
+ const empty = entry.empty;
139
+ if (empty === true || empty === 'true')
140
+ return { kind: 'empty', empty: true };
141
+ if (empty === false || empty === 'false')
142
+ return { kind: 'empty', empty: false };
143
+ throw invalidFilter(`Invalid filter value: ${key}`);
144
+ }
145
+ if (operators.length && operators.every((operator) => operator === 'gte' || operator === 'lte')) {
146
+ if (!RANGE_TYPES.has(field.type))
147
+ throw invalidFilter(`Unsupported filter operator: ${key}`);
148
+ const bound = (operand) => {
149
+ if (operand === null || operand === '' || !isScalar(operand))
150
+ throw invalidFilter(`Invalid filter value: ${key}`);
151
+ return coerce(operand);
152
+ };
153
+ return {
154
+ kind: 'range',
155
+ ...('gte' in entry ? { gte: bound(entry.gte) } : {}),
156
+ ...('lte' in entry ? { lte: bound(entry.lte) } : {}),
157
+ };
158
+ }
159
+ throw invalidFilter(`Unsupported filter operator: ${key}`);
160
+ }
161
+ /**
162
+ * Filters shared by list() and aggregate(): each key must be a filterable field the
163
+ * caller allows querying, and each value a scalar or operator object whose operands
164
+ * coerce to the field's type (see ListFilterValue).
165
+ */
166
+ function applyFilters(query, resource, filters, queryable) {
167
+ if (!filters || typeof filters !== 'object' || Array.isArray(filters))
168
+ throw invalidFilter('Invalid filter value');
169
+ for (const [key, value] of Object.entries(filters)) {
170
+ if (!Object.hasOwn(resource.fields, key) ||
171
+ !resource.fields[key]?.filterable ||
172
+ !queryable(key))
173
+ throw invalidFilter('Unsupported filter');
174
+ const field = resource.fields[key];
175
+ const condition = filterCondition(key, field, value);
176
+ const column = `r.${field.column ?? columnName(key)}`;
177
+ // multiSelect and manyToMany match one member, or none at all for an empty filter.
178
+ if (COLLECTION_TYPES.has(field.type)) {
179
+ if (condition.kind === 'eq')
180
+ collectionFilter(query, resource, key, condition.value);
181
+ else if (condition.kind === 'empty' && condition.empty)
182
+ collectionFilter(query, resource, key, null);
183
+ else if (condition.kind === 'empty')
184
+ query.whereNot((present) => {
185
+ collectionFilter(present, resource, key, null);
186
+ });
187
+ else
188
+ throw invalidFilter(`Unsupported filter operator: ${key}`);
189
+ continue;
190
+ }
191
+ // Several files filter only by having files or none (ADR 047).
192
+ if (isMultipleAttachment(field)) {
193
+ if (condition.kind !== 'empty')
194
+ throw invalidFilter(`Unsupported filter operator: ${key}`);
195
+ if (condition.empty)
196
+ query.where((empty) => {
197
+ empty.whereNull(column).orWhereRaw(`?? = '[]'::jsonb`, [column]);
198
+ });
199
+ else
200
+ query.whereNotNull(column).whereRaw(`?? <> '[]'::jsonb`, [column]);
201
+ continue;
202
+ }
203
+ switch (condition.kind) {
204
+ case 'eq':
205
+ if (condition.value === null)
206
+ query.whereNull(column);
207
+ else
208
+ query.where(column, condition.value);
209
+ break;
210
+ case 'in':
211
+ query.whereIn(column, condition.values);
212
+ break;
213
+ case 'range':
214
+ if (condition.gte !== undefined)
215
+ query.where(column, '>=', condition.gte);
216
+ if (condition.lte !== undefined)
217
+ query.where(column, '<=', condition.lte);
218
+ break;
219
+ case 'empty': {
220
+ const text = TEXT_TYPES.has(field.type);
221
+ if (condition.empty)
222
+ query.where((empty) => {
223
+ empty.whereNull(column);
224
+ if (text)
225
+ empty.orWhere(column, '');
226
+ });
227
+ else {
228
+ query.whereNotNull(column);
229
+ if (text)
230
+ query.whereNot(column, '');
231
+ }
232
+ break;
233
+ }
234
+ }
235
+ }
236
+ }
237
+ /** Full-text search, allowed only when the caller may query every searchable field. */
238
+ function applySearch(query, resource, search, queryable) {
239
+ const searchable = Object.entries(resource.fields).filter(([, f]) => f.searchable);
240
+ if (!searchable.length || searchable.some(([key]) => !queryable(key)))
241
+ throw searchUnavailable();
242
+ query.whereRaw("r.search_vector @@ plainto_tsquery('simple', ?)", [search]);
243
+ }
244
+ /**
245
+ * The authorized, filtered list query of list() before keyset paging and ordering, with
246
+ * what paging needs. Shared with countUpTo() so a count uses exactly the list's rules.
247
+ */
248
+ function listQuery(ctx, name, actor, options) {
249
+ const resource = ctx.registry.get(name);
250
+ const ability = authorizeAction(ctx, resource, actor, 'view');
251
+ const trashed = options.trashed === true;
252
+ // The trash is reached through the delete permission: restore reuses the delete rule.
253
+ if (trashed)
254
+ authorizeAction(ctx, resource, actor, 'delete');
255
+ const queryable = (key) => canQueryField(resource, actor, ability, key);
256
+ const limit = Math.max(1, Math.min(100, Math.floor(Number(options.limit) || 25)));
257
+ const sort = options.sort ?? 'id';
258
+ const direction = options.direction === 'desc' ? 'desc' : 'asc';
259
+ if (sort !== 'id' && !resource.fields[sort]?.sortable)
260
+ throw new AdulaError(422, 'E_SORT', 'Unsupported sort field');
261
+ // Sorting/filtering private fields would otherwise reveal their values indirectly.
262
+ if (sort !== 'id' && !queryable(sort))
263
+ throw forbiddenField('Forbidden sort field');
264
+ const sortColumn = `r.${resource.fields[sort]?.column ?? columnName(sort)}`;
265
+ const base = ctx.db(`${name} as r`);
266
+ if (trashed) {
267
+ base.whereNotNull('r.deleted_at');
268
+ // Deleted rows are listed when both the view and the delete rules reach them.
269
+ const viewable = authorizationSql(ability, 'view', resource);
270
+ base.whereRaw(viewable.text, viewable.bindings);
271
+ }
272
+ else
273
+ base.whereNull('r.deleted_at');
274
+ const query = accessibleBy(base, ability, actor, trashed ? 'delete' : 'view', resource);
275
+ query.select(columns(resource, ability, false, [sort]));
276
+ if (resource.scoped)
277
+ query.select('ou.path as org_path');
278
+ if (options.search)
279
+ applySearch(query, resource, options.search, queryable);
280
+ applyFilters(query, resource, options.filters ?? {}, queryable);
281
+ if (options.tag !== undefined && options.tag !== null && options.tag !== '') {
282
+ if (typeof options.tag !== 'string' || options.tag.length > 60)
283
+ throw invalidFilter('Invalid tag filter');
284
+ query.whereExists((exists) => exists
285
+ .from('taggables as tg')
286
+ .join('tags as tn', 'tn.id', 'tg.tag_id')
287
+ .where('tg.resource', name)
288
+ .whereRaw('tg.record_id = r.id')
289
+ .where('tn.name', options.tag));
290
+ }
291
+ return { resource, ability, trashed, limit, sort, direction, sortColumn, query };
292
+ }
293
+ /**
294
+ * How many records list() would return for these options, counting at most `max` + 1,
295
+ * so callers can refuse an oversized request with one bounded query.
296
+ */
297
+ export async function countUpTo(ctx, name, actor, options, max) {
298
+ const { query } = listQuery(ctx, name, actor, options);
299
+ const bounded = query
300
+ .clearSelect()
301
+ .select('r.id')
302
+ .limit(max + 1);
303
+ const [row] = await ctx.db.from(bounded.as('bounded')).count('* as count');
304
+ return Number(row.count);
305
+ }
306
+ export async function list(ctx, name, actor, options = {}) {
307
+ const { resource, ability, trashed, limit, sort, direction, sortColumn, query } = listQuery(ctx, name, actor, options);
308
+ // Estimate the authorized, filtered query, never the deployment-wide table cardinality.
309
+ // Only the first page pays for the extra planner round trip; later pages keep its figure.
310
+ let estimatedTotal;
311
+ if (options.estimate !== false && !options.cursor) {
312
+ estimatedTotal = await estimate(ctx.db, query);
313
+ }
314
+ if (options.cursor) {
315
+ const cursor = decodeCursor(resource, options.cursor, sort, direction);
316
+ query.where((q) => {
317
+ if (cursor.value === null)
318
+ q.whereNull(sortColumn).andWhere('r.id', direction === 'asc' ? '>' : '<', cursor.id);
319
+ else
320
+ q.where(sortColumn, direction === 'asc' ? '>' : '<', cursor.value)
321
+ .orWhere((same) => same
322
+ .where(sortColumn, cursor.value)
323
+ .andWhere('r.id', direction === 'asc' ? '>' : '<', cursor.id))
324
+ .orWhereNull(sortColumn);
325
+ });
326
+ }
327
+ query.orderBy(sortColumn, direction, 'last');
328
+ if (sort !== 'id')
329
+ query.orderBy('r.id', direction);
330
+ const rows = await query.limit(limit + 1);
331
+ const records = rows
332
+ .slice(0, limit)
333
+ .map((row) => fromRow(row, resource));
334
+ await withLinks(ctx.db, resource, records);
335
+ const last = records.at(-1);
336
+ if (estimatedTotal !== undefined) {
337
+ estimatedTotal =
338
+ !options.cursor && rows.length <= limit ? rows.length : Math.max(estimatedTotal, rows.length);
339
+ }
340
+ const hydrated = await hydrate(ctx.db, resource, records, ctx.attachments);
341
+ return {
342
+ data: hydrated.map((record) => serialize(resource, record, ability, actor)),
343
+ permissions: Object.fromEntries(records.map((record) => [
344
+ String(record.id),
345
+ trashed
346
+ ? trashedPermissions(resource, record, actor, ability)
347
+ : permissions(resource, record, actor, ability),
348
+ ])),
349
+ meta: {
350
+ limit,
351
+ estimatedTotal,
352
+ nextCursor: rows.length > limit && last
353
+ ? Buffer.from(JSON.stringify({ id: last.id, value: last[sort] ?? null, sort, direction })).toString('base64url')
354
+ : null,
355
+ },
356
+ related: await preload(ctx, resource, records, actor),
357
+ };
358
+ }
359
+ /** A deleted record can only be viewed or restored; restore follows the delete rule. */
360
+ function trashedPermissions(resource, record, actor, ability) {
361
+ return {
362
+ ...Object.fromEntries(resource.actions.map((action) => [action, false])),
363
+ view: canRecord(ability, actor, resource, 'view', record),
364
+ restore: canRecord(ability, actor, resource, 'delete', record),
365
+ };
366
+ }
367
+ /** The planner's row estimate of a list query, reused briefly for the identical query. */
368
+ async function estimate(db, query) {
369
+ const compiled = query.clone().clearSelect().select('r.id').toSQL();
370
+ // The planner estimate is approximate by nature; reuse it briefly for the same
371
+ // authorized, filtered query instead of planning it on every first page.
372
+ const key = `${compiled.sql}\u0000${JSON.stringify(compiled.bindings)}`;
373
+ const cached = estimates.get(key);
374
+ if (cached && cached.at > Date.now() - ESTIMATE_TTL_MS)
375
+ return cached.rows;
376
+ const plan = await db.raw(`EXPLAIN (FORMAT JSON) ${compiled.sql}`, [...compiled.bindings]);
377
+ const rows = Number(plan.rows[0]['QUERY PLAN'][0].Plan['Plan Rows']);
378
+ if (estimates.size >= ESTIMATE_CACHE_LIMIT)
379
+ estimates.delete(estimates.keys().next().value);
380
+ estimates.set(key, { rows, at: Date.now() });
381
+ return rows;
382
+ }
383
+ /** A keyset cursor of list(), checked against the current sort and the sort field's type. */
384
+ function decodeCursor(resource, encoded, sort, direction) {
385
+ let cursor;
386
+ try {
387
+ if (typeof encoded !== 'string')
388
+ throw new Error('Cursor must be a string');
389
+ cursor = JSON.parse(Buffer.from(encoded, 'base64url').toString());
390
+ }
391
+ catch {
392
+ throw invalidCursor();
393
+ }
394
+ if (!cursor ||
395
+ typeof cursor !== 'object' ||
396
+ Array.isArray(cursor) ||
397
+ cursor.sort !== sort ||
398
+ cursor.direction !== direction ||
399
+ !Number.isSafeInteger(cursor.id) ||
400
+ cursor.id < 1 ||
401
+ cursor.id > 2147483647 ||
402
+ cursor.value === undefined ||
403
+ (cursor.value !== null && !['number', 'string', 'boolean'].includes(typeof cursor.value)))
404
+ throw invalidCursor();
405
+ // The sort key must have the sort field's type, or PostgreSQL rejects the comparison.
406
+ try {
407
+ if (sort === 'id') {
408
+ if (cursor.value !== cursor.id)
409
+ throw new Error('Cursor id mismatch');
410
+ }
411
+ else
412
+ cursor.value = fieldValue(resource.fields[sort], cursor.value);
413
+ }
414
+ catch {
415
+ throw invalidCursor();
416
+ }
417
+ return cursor;
418
+ }
419
+ /** Counts and totals over viewable records; see ResourceService.aggregate. */
420
+ export async function aggregate(ctx, name, actor, options = {}) {
421
+ const resource = ctx.registry.get(name);
422
+ const ability = authorizeAction(ctx, resource, actor, 'view');
423
+ const standard = new Set([
424
+ ...(resource.submittable ? ['docStatus'] : []),
425
+ ...(resource.scoped ? ['orgUnitId'] : []),
426
+ ]);
427
+ const column = (key) => `r.${resource.fields[key]?.column ?? columnName(key)}`;
428
+ const queryable = (key, kinds) => {
429
+ if (typeof key !== 'string')
430
+ return false;
431
+ if (standard.has(key))
432
+ return !kinds;
433
+ // Own keys only: names such as "constructor" are not fields.
434
+ if (!Object.hasOwn(resource.fields, key))
435
+ return false;
436
+ const field = resource.fields[key];
437
+ return (Boolean(field) &&
438
+ !['hasMany', 'manyToMany', 'json', 'attachment'].includes(field.type) &&
439
+ (!kinds || kinds.includes(field.type)) &&
440
+ canQueryField(resource, actor, ability, key));
441
+ };
442
+ const groupBy = options.groupBy ?? [];
443
+ const sums = options.sum ?? [];
444
+ if (!Array.isArray(groupBy) || groupBy.length > 3 || !Array.isArray(sums) || sums.length > 5)
445
+ throw new AdulaError(422, 'E_AGGREGATE', 'Group by up to three fields and total up to five');
446
+ for (const key of groupBy)
447
+ if (!queryable(key))
448
+ throw forbiddenField(`Field cannot be grouped: ${String(key)}`);
449
+ for (const key of sums)
450
+ if (!queryable(key, ['integer', 'money', 'decimal', 'percent']))
451
+ throw forbiddenField(`Field cannot be totalled: ${String(key)}`);
452
+ const query = accessibleBy(ctx.db(`${name} as r`).whereNull('r.deleted_at'), ability, actor, 'view', resource);
453
+ // A manyToMany field cannot be grouped or totalled, but filters by one linked id or none.
454
+ applyFilters(query, resource, options.filters ?? {}, (key) => queryable(key) ||
455
+ (Object.hasOwn(resource.fields, key) &&
456
+ resource.fields[key].type === 'manyToMany' &&
457
+ canQueryField(resource, actor, ability, key)));
458
+ if (options.where !== undefined && options.where !== null) {
459
+ if (typeof options.where !== 'object' || Array.isArray(options.where))
460
+ throw invalidFilter('Conditions must be an object');
461
+ for (const key of Object.keys(options.where))
462
+ if (!queryable(key))
463
+ throw forbiddenField(`Field cannot be filtered: ${key}`);
464
+ let where;
465
+ try {
466
+ where = conditionSql(resolveActorConditions(options.where, actor.id), resource);
467
+ }
468
+ catch (error) {
469
+ throw invalidFilter(error.message);
470
+ }
471
+ query.whereRaw(where.text, where.bindings);
472
+ }
473
+ if (options.search)
474
+ applySearch(query, resource, options.search, (key) => queryable(key));
475
+ const selects = groupBy.map((key, index) => `${key === 'docStatus' ? 'r.doc_status' : column(key)} as g${index}`);
476
+ if (options.count !== false)
477
+ selects.push(ctx.db.raw('count(*)::int as count'));
478
+ sums.forEach((key, index) => selects.push(ctx.db.raw(`sum(??)::text as s${index}`, [column(key)])));
479
+ query.select(selects);
480
+ groupBy.forEach((_, index) => query.groupByRaw(`${index + 1}`));
481
+ groupBy.forEach((_, index) => query.orderByRaw(`${index + 1} ASC NULLS LAST`));
482
+ const rows = await query.limit(AGGREGATE_GROUP_LIMIT + 1);
483
+ return {
484
+ truncated: rows.length > AGGREGATE_GROUP_LIMIT,
485
+ rows: rows.slice(0, AGGREGATE_GROUP_LIMIT).map((row) => {
486
+ const group = fromRow(Object.fromEntries(groupBy.map((key, index) => [
487
+ key === 'docStatus'
488
+ ? 'doc_status'
489
+ : key === 'orgUnitId'
490
+ ? 'org_unit_id'
491
+ : (resource.fields[key].column ?? columnName(key)),
492
+ row[`g${index}`],
493
+ ])), resource);
494
+ return {
495
+ group: Object.fromEntries(groupBy.map((key) => [key, jsonValue(group[key])])),
496
+ ...(options.count !== false ? { count: Number(row.count) } : {}),
497
+ ...(sums.length
498
+ ? {
499
+ sum: Object.fromEntries(sums.map((key, index) => [
500
+ key,
501
+ row[`s${index}`] === null ? null : String(row[`s${index}`]),
502
+ ])),
503
+ }
504
+ : {}),
505
+ };
506
+ }),
507
+ };
508
+ }