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.
- package/README.md +149 -18
- package/build/agent/AGENTS.template.md +4 -4
- package/build/agent/capabilities.md +22 -12
- package/build/agent/skills/adula-frontend-design/SKILL.md +6 -4
- package/build/agent/skills/idea-review/SKILL.md +2 -2
- package/build/commands/adula_assistant_prune.d.ts +10 -0
- package/build/commands/adula_assistant_prune.js +12 -0
- package/build/commands/adula_outbox.d.ts +10 -0
- package/build/commands/adula_outbox.js +11 -0
- package/build/commands/adula_restore_reconcile.d.ts +10 -0
- package/build/commands/adula_restore_reconcile.js +34 -0
- package/build/commands/adula_runtime_health.d.ts +10 -0
- package/build/commands/adula_runtime_health.js +27 -0
- package/build/commands/adula_uploads_prune.d.ts +10 -0
- package/build/commands/adula_uploads_prune.js +16 -0
- package/build/commands/app.d.ts +10 -0
- package/build/commands/app.js +64 -0
- package/build/commands/backup_create.d.ts +11 -0
- package/build/commands/backup_create.js +99 -0
- package/build/commands/backup_open.d.ts +16 -0
- package/build/commands/backup_open.js +48 -0
- package/build/commands/backup_restore_files.d.ts +11 -0
- package/build/commands/backup_restore_files.js +44 -0
- package/build/commands/backup_restore_test.d.ts +12 -0
- package/build/commands/backup_restore_test.js +188 -0
- package/build/commands/backup_seal.d.ts +12 -0
- package/build/commands/backup_seal.js +36 -0
- package/build/commands/backup_services.d.ts +33 -0
- package/build/commands/backup_services.js +6 -0
- package/build/commands/backup_verify.d.ts +9 -0
- package/build/commands/backup_verify.js +59 -0
- package/build/commands/backup_verify_snapshot.d.ts +10 -0
- package/build/commands/backup_verify_snapshot.js +37 -0
- package/build/commands/client.d.ts +16 -0
- package/build/commands/client.js +71 -0
- package/build/commands/doctor.js +21 -1
- package/build/commands/install.d.ts +8 -0
- package/build/commands/install.js +69 -45
- package/build/commands/main.d.ts +3 -2
- package/build/commands/main.js +32 -0
- package/build/commands/module_add.js +4 -20
- package/build/commands/resource.d.ts +2 -0
- package/build/commands/resource.js +12 -3
- package/build/commands/resource_migration.d.ts +15 -0
- package/build/commands/resource_migration.js +81 -0
- package/build/commands/resource_snapshot.d.ts +2 -0
- package/build/commands/resource_snapshot.js +21 -4
- package/build/commands/sla_evaluate.d.ts +14 -0
- package/build/commands/sla_evaluate.js +16 -0
- package/build/commands/ui.js +4 -2
- package/build/commands/ui_css.d.ts +9 -0
- package/build/commands/ui_css.js +19 -0
- package/build/commands/upgrade.d.ts +1 -1
- package/build/commands/upgrade.js +1 -1
- package/build/configure.js +1 -1
- package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
- package/build/database/migrations/1770000000020_two_factor.js +10 -0
- package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
- package/build/database/migrations/1770000000041_import_modes.js +10 -0
- package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
- package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
- package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
- package/build/database/migrations/1770000000043_notification_channels.js +10 -0
- package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
- package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
- package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
- package/build/database/migrations/1770000000045_import_leases.js +10 -0
- package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
- package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
- package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
- package/build/database/migrations/1770000000049_print_templates.js +10 -0
- package/build/database/migrations/1770000000051_comment_notifications.d.ts +5 -0
- package/build/database/migrations/1770000000051_comment_notifications.js +10 -0
- package/build/database/migrations/1770000000054_cloud_backups.d.ts +5 -0
- package/build/database/migrations/1770000000054_cloud_backups.js +10 -0
- package/build/database/migrations/1770000000055_ai_assistant.d.ts +5 -0
- package/build/database/migrations/1770000000055_ai_assistant.js +10 -0
- package/build/database/migrations/1770000000056_appearance.d.ts +5 -0
- package/build/database/migrations/1770000000056_appearance.js +10 -0
- package/build/index.d.ts +87 -11
- package/build/index.js +50 -7
- package/build/providers/adula_provider.d.ts +2 -0
- package/build/providers/adula_provider.js +7 -0
- package/build/src/admin/contracts.js +1 -1
- package/build/src/admin/controller.d.ts +14 -1
- package/build/src/admin/controller.js +91 -13
- package/build/src/admin/errors.d.ts +32 -0
- package/build/src/admin/errors.js +63 -1
- package/build/src/admin/presentation.d.ts +21 -2
- package/build/src/admin/resource/editor.d.ts +60 -0
- package/build/src/admin/resource/editor.js +345 -0
- package/build/src/admin/resource/export.d.ts +54 -0
- package/build/src/admin/resource/export.js +262 -0
- package/build/src/admin/resource/lifecycle.d.ts +23 -0
- package/build/src/admin/resource/lifecycle.js +91 -0
- package/build/src/admin/resource/query.d.ts +111 -0
- package/build/src/admin/resource/query.js +595 -0
- package/build/src/admin/resource/read.d.ts +109 -0
- package/build/src/admin/resource/read.js +388 -0
- package/build/src/admin/resource/shared.d.ts +93 -0
- package/build/src/admin/resource/shared.js +265 -0
- package/build/src/admin/resource/trash.d.ts +10 -0
- package/build/src/admin/resource/trash.js +56 -0
- package/build/src/admin/resource/write.d.ts +57 -0
- package/build/src/admin/resource/write.js +603 -0
- package/build/src/admin/resource_service.d.ts +80 -193
- package/build/src/admin/resource_service.js +81 -1343
- package/build/src/admin/resource_tools.d.ts +111 -0
- package/build/src/admin/resource_tools.js +139 -0
- package/build/src/ai/assistant.d.ts +100 -0
- package/build/src/ai/assistant.js +487 -0
- package/build/src/ai/client.d.ts +49 -0
- package/build/src/ai/client.js +85 -0
- package/build/src/ai/prompt.d.ts +23 -0
- package/build/src/ai/prompt.js +83 -0
- package/build/src/ai/settings.d.ts +56 -0
- package/build/src/ai/settings.js +214 -0
- package/build/src/ai/usage.d.ts +16 -0
- package/build/src/ai/usage.js +33 -0
- package/build/src/appearance/appearance.d.ts +134 -0
- package/build/src/appearance/appearance.js +461 -0
- package/build/src/appearance/colors.d.ts +43 -0
- package/build/src/appearance/colors.js +99 -0
- package/build/src/appearance/logo.d.ts +32 -0
- package/build/src/appearance/logo.js +112 -0
- package/build/src/attachments/attachment_service.d.ts +46 -2
- package/build/src/attachments/attachment_service.js +96 -4
- package/build/src/auth/actor_store.d.ts +5 -1
- package/build/src/auth/actor_store.js +8 -4
- package/build/src/auth/conditions.d.ts +5 -0
- package/build/src/auth/conditions.js +26 -3
- package/build/src/auth/sql.js +17 -5
- package/build/src/auth/two_factor.d.ts +96 -0
- package/build/src/auth/two_factor.js +259 -0
- package/build/src/backups/archive.d.ts +52 -0
- package/build/src/backups/archive.js +362 -0
- package/build/src/backups/cloud_backups.d.ts +133 -0
- package/build/src/backups/cloud_backups.js +650 -0
- package/build/src/backups/doctor.d.ts +7 -0
- package/build/src/backups/doctor.js +55 -0
- package/build/src/backups/providers.d.ts +81 -0
- package/build/src/backups/providers.js +470 -0
- package/build/src/collaboration/assignments.d.ts +59 -2
- package/build/src/collaboration/assignments.js +196 -74
- package/build/src/collaboration/record_collaboration.d.ts +21 -4
- package/build/src/collaboration/record_collaboration.js +126 -51
- package/build/src/collaboration/shared.d.ts +24 -0
- package/build/src/collaboration/shared.js +34 -0
- package/build/src/commands/app_scaffold.d.ts +72 -0
- package/build/src/commands/app_scaffold.js +285 -0
- package/build/src/commands/capabilities.js +35 -9
- package/build/src/commands/doctor.d.ts +24 -2
- package/build/src/commands/doctor.js +81 -6
- package/build/src/commands/gap_report.d.ts +1 -1
- package/build/src/commands/gap_report.js +2 -2
- package/build/src/commands/generator.d.ts +37 -1
- package/build/src/commands/generator.js +61 -18
- package/build/src/commands/snapshot.d.ts +24 -13
- package/build/src/commands/snapshot.js +54 -14
- package/build/src/commands/source_markers.d.ts +10 -0
- package/build/src/commands/source_markers.js +29 -0
- package/build/src/core/activity.d.ts +2 -0
- package/build/src/core/activity.js +7 -1
- package/build/src/core/administrators.d.ts +38 -0
- package/build/src/core/administrators.js +145 -0
- package/build/src/core/avatar_image.d.ts +33 -0
- package/build/src/core/avatar_image.js +278 -0
- package/build/src/core/html_sanitizer.d.ts +20 -0
- package/build/src/core/html_sanitizer.js +261 -0
- package/build/src/core/like.d.ts +5 -0
- package/build/src/core/like.js +5 -0
- package/build/src/core/lookups.d.ts +80 -0
- package/build/src/core/lookups.js +319 -0
- package/build/src/core/mail_settings.d.ts +83 -0
- package/build/src/core/mail_settings.js +274 -0
- package/build/src/core/mail_test.d.ts +16 -0
- package/build/src/core/mail_test.js +81 -6
- package/build/src/core/message_templates.d.ts +15 -2
- package/build/src/core/message_templates.js +81 -11
- package/build/src/core/module_seed.js +2 -1
- package/build/src/core/notification_channels.d.ts +235 -0
- package/build/src/core/notification_channels.js +660 -0
- package/build/src/core/roles.js +26 -9
- package/build/src/core/saved_views.d.ts +8 -1
- package/build/src/core/saved_views.js +91 -26
- package/build/src/core/sequences.d.ts +32 -0
- package/build/src/core/sequences.js +97 -0
- package/build/src/core/settings.d.ts +5 -0
- package/build/src/core/settings.js +31 -3
- package/build/src/core/template_language.d.ts +61 -0
- package/build/src/core/template_language.js +141 -0
- package/build/src/core/ui_preferences.d.ts +10 -0
- package/build/src/core/ui_preferences.js +15 -1
- package/build/src/core/user_avatars.d.ts +79 -0
- package/build/src/core/user_avatars.js +186 -0
- package/build/src/core/user_invitations.d.ts +5 -1
- package/build/src/core/user_invitations.js +7 -1
- package/build/src/core/user_preferences.d.ts +36 -0
- package/build/src/core/user_preferences.js +125 -0
- package/build/src/core/users.d.ts +2 -0
- package/build/src/core/users.js +5 -3
- package/build/src/database/calendar_days.d.ts +19 -0
- package/build/src/database/calendar_days.js +36 -0
- package/build/src/database/schema.d.ts +201 -2
- package/build/src/database/schema.js +713 -59
- package/build/src/database/schema_diff.d.ts +70 -0
- package/build/src/database/schema_diff.js +190 -0
- package/build/src/events/record_mutation.d.ts +2 -1
- package/build/src/events/record_mutation.js +1 -0
- package/build/src/integrations/api_client.d.ts +37 -0
- package/build/src/integrations/api_client.js +567 -0
- package/build/src/integrations/import_adapters.d.ts +37 -0
- package/build/src/integrations/import_adapters.js +35 -0
- package/build/src/integrations/imports.d.ts +130 -16
- package/build/src/integrations/imports.js +434 -73
- package/build/src/integrations/openapi.d.ts +3 -1
- package/build/src/integrations/openapi.js +465 -31
- package/build/src/integrations/outbound.d.ts +94 -0
- package/build/src/integrations/outbound.js +276 -0
- package/build/src/integrations/print.d.ts +22 -1
- package/build/src/integrations/print.js +68 -22
- package/build/src/integrations/print_templates.d.ts +216 -0
- package/build/src/integrations/print_templates.js +1017 -0
- package/build/src/integrations/sync_jobs.d.ts +139 -0
- package/build/src/integrations/sync_jobs.js +416 -0
- package/build/src/integrations/webhooks.d.ts +12 -12
- package/build/src/integrations/webhooks.js +34 -43
- package/build/src/integrations/xlsx.d.ts +41 -0
- package/build/src/integrations/xlsx.js +519 -0
- package/build/src/languages/ar.d.ts +11 -0
- package/build/src/languages/ar.js +358 -0
- package/build/src/languages/ar_ui.d.ts +461 -0
- package/build/src/languages/ar_ui.js +464 -0
- package/build/src/languages/catalog.d.ts +66 -0
- package/build/src/languages/catalog.js +152 -0
- package/build/src/languages/en.d.ts +7 -0
- package/build/src/languages/en.js +352 -0
- package/build/src/languages/en_ui.d.ts +3 -0
- package/build/src/languages/en_ui.js +458 -0
- package/build/src/languages/validation.d.ts +26 -0
- package/build/src/languages/validation.js +60 -0
- package/build/src/lists/bulk_actions.d.ts +89 -0
- package/build/src/lists/bulk_actions.js +268 -0
- package/build/src/lists/dashboards.d.ts +138 -0
- package/build/src/lists/dashboards.js +290 -0
- package/build/src/mcp/tools.js +9 -104
- package/build/src/resource/define_resource.d.ts +18 -1
- package/build/src/resource/define_resource.js +212 -18
- package/build/src/resource/definition.d.ts +44 -0
- package/build/src/resource/definition.js +171 -0
- package/build/src/resource/registry.js +15 -4
- package/build/src/resource/types.d.ts +313 -16
- package/build/src/resource/values.d.ts +56 -1
- package/build/src/resource/values.js +237 -5
- package/build/src/services/settings.d.ts +2 -0
- package/build/src/services/settings.js +5 -1
- package/build/src/upgrade/legacy.js +2 -2
- package/build/src/workflows/calendar.d.ts +9 -0
- package/build/src/workflows/calendar.js +44 -0
- package/build/src/workflows/define_workflow.d.ts +48 -3
- package/build/src/workflows/define_workflow.js +57 -13
- package/build/src/workflows/delegations.d.ts +107 -0
- package/build/src/workflows/delegations.js +326 -0
- package/build/src/workflows/engine.d.ts +80 -4
- package/build/src/workflows/engine.js +466 -86
- package/build/src/workflows/sla.d.ts +15 -0
- package/build/src/workflows/sla.js +8 -0
- package/build/stubs/resource_contract.txt +12 -1
- package/package.json +9 -2
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { AdulaError } from '../admin/errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* The `{{name}}` placeholder of message templates (core/message_templates.ts). Print
|
|
4
|
+
* templates use the same delimiters with a small block grammar on top (see parseTemplate).
|
|
5
|
+
*/
|
|
6
|
+
export const PLACEHOLDER = /\{\{\s*([a-zA-Z][a-zA-Z0-9_]*)\s*\}\}/g;
|
|
7
|
+
const NAME = '[a-zA-Z][a-zA-Z0-9_]*';
|
|
8
|
+
const SCOPED = new RegExp(`^(field|row)\\.(${NAME})$`);
|
|
9
|
+
const LINES = new RegExp(`^lines\\.(${NAME})(?:\\.(${NAME}))?$`);
|
|
10
|
+
const META = new RegExp(`^(${NAME})$`);
|
|
11
|
+
const STRING = /^"([^"\\{}<>]{1,100})"$/;
|
|
12
|
+
const HELPER = new RegExp(`^(${NAME})\\s+(\\S.*)$`);
|
|
13
|
+
/** Longest template accepted, in characters. */
|
|
14
|
+
export const TEMPLATE_SOURCE_LIMIT = 20000;
|
|
15
|
+
const TAG_LIMIT = 2000;
|
|
16
|
+
export function templateError(message) {
|
|
17
|
+
throw new AdulaError(422, 'E_PRINT_TEMPLATE', message);
|
|
18
|
+
}
|
|
19
|
+
function reference(source, tag) {
|
|
20
|
+
const scoped = SCOPED.exec(source);
|
|
21
|
+
if (scoped)
|
|
22
|
+
return { kind: scoped[1], key: scoped[2] };
|
|
23
|
+
const lines = LINES.exec(source);
|
|
24
|
+
if (lines)
|
|
25
|
+
return { kind: 'lines', key: lines[1], ...(lines[2] ? { column: lines[2] } : {}) };
|
|
26
|
+
const string = STRING.exec(source);
|
|
27
|
+
if (string)
|
|
28
|
+
return { kind: 'string', value: string[1] };
|
|
29
|
+
if (META.test(source))
|
|
30
|
+
return { kind: 'meta', key: source };
|
|
31
|
+
return templateError(`تعبير غير مسموح في القالب: {{${tag}}}`);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Parses the template language shared by print templates:
|
|
35
|
+
*
|
|
36
|
+
* - `{{field.key}}`, `{{row.key}}` (inside each), `{{name}}` (document values such as id)
|
|
37
|
+
* - `{{helper arg}}` where arg is one of the above, `lines.group.column` or `"text"`
|
|
38
|
+
* - `{{#if ref}}…{{else}}…{{/if}}` and `{{#each lines.group}}…{{/each}}` (not nested)
|
|
39
|
+
*
|
|
40
|
+
* There are no expressions, no property paths beyond these and no raw output: `{{{`
|
|
41
|
+
* is refused. Which names exist is checked by the caller against its own schema.
|
|
42
|
+
*/
|
|
43
|
+
export function parseTemplate(source) {
|
|
44
|
+
if (source.length > TEMPLATE_SOURCE_LIMIT)
|
|
45
|
+
templateError(`القالب أطول من ${TEMPLATE_SOURCE_LIMIT} حرف`);
|
|
46
|
+
if (source.includes('{{{') || source.includes('}}}'))
|
|
47
|
+
templateError('الصيغة {{{ }}} غير مسموحة؛ تُعرض كل القيم بعد تهريبها');
|
|
48
|
+
const root = [];
|
|
49
|
+
const stack = [];
|
|
50
|
+
const target = () => {
|
|
51
|
+
const top = stack.at(-1);
|
|
52
|
+
if (!top)
|
|
53
|
+
return root;
|
|
54
|
+
if (top.node.type === 'each')
|
|
55
|
+
return top.node.body;
|
|
56
|
+
return top.inElse ? top.node.else : top.node.then;
|
|
57
|
+
};
|
|
58
|
+
let index = 0;
|
|
59
|
+
while (index < source.length) {
|
|
60
|
+
const open = source.indexOf('{{', index);
|
|
61
|
+
if (open === -1) {
|
|
62
|
+
target().push({ type: 'text', value: source.slice(index) });
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
if (open > index)
|
|
66
|
+
target().push({ type: 'text', value: source.slice(index, open) });
|
|
67
|
+
const close = source.indexOf('}}', open + 2);
|
|
68
|
+
if (close === -1)
|
|
69
|
+
templateError('وسم غير مكتمل في القالب: {{ بلا }}');
|
|
70
|
+
const raw = source.slice(open + 2, close);
|
|
71
|
+
if (raw.length > TAG_LIMIT || raw.includes('{{'))
|
|
72
|
+
templateError('وسم غير صالح في القالب');
|
|
73
|
+
const tag = raw.trim().replace(/\s+/g, ' ');
|
|
74
|
+
index = close + 2;
|
|
75
|
+
if (tag.startsWith('#if ')) {
|
|
76
|
+
const node = {
|
|
77
|
+
type: 'if',
|
|
78
|
+
test: reference(tag.slice(4).trim(), tag),
|
|
79
|
+
then: [],
|
|
80
|
+
else: [],
|
|
81
|
+
source: tag,
|
|
82
|
+
};
|
|
83
|
+
target().push(node);
|
|
84
|
+
stack.push({ node, inElse: false });
|
|
85
|
+
}
|
|
86
|
+
else if (tag.startsWith('#each ')) {
|
|
87
|
+
if (stack.some((entry) => entry.node.type === 'each'))
|
|
88
|
+
templateError('لا يمكن تداخل {{#each}} داخل {{#each}}');
|
|
89
|
+
const group = reference(tag.slice(6).trim(), tag);
|
|
90
|
+
if (group.kind !== 'lines' || group.column)
|
|
91
|
+
templateError(`{{#each}} يقبل مجموعة بنود فقط مثل lines.items: {{${tag}}}`);
|
|
92
|
+
const node = { type: 'each', group: group.key, body: [], source: tag };
|
|
93
|
+
target().push(node);
|
|
94
|
+
stack.push({ node, inElse: false });
|
|
95
|
+
}
|
|
96
|
+
else if (tag === 'else') {
|
|
97
|
+
const top = stack.at(-1);
|
|
98
|
+
if (!top || top.node.type !== 'if' || top.inElse)
|
|
99
|
+
templateError('{{else}} بلا {{#if}}');
|
|
100
|
+
top.inElse = true;
|
|
101
|
+
}
|
|
102
|
+
else if (tag === '/if' || tag === '/each') {
|
|
103
|
+
const top = stack.pop();
|
|
104
|
+
if (!top || `/${top.node.type}` !== tag)
|
|
105
|
+
templateError(`{{${tag}}} بلا بداية مطابقة`);
|
|
106
|
+
}
|
|
107
|
+
else if (tag.startsWith('#') || tag.startsWith('/') || tag.startsWith('>')) {
|
|
108
|
+
templateError(`وسم غير مسموح في القالب: {{${tag}}}`);
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
const helper = HELPER.exec(tag);
|
|
112
|
+
if (helper)
|
|
113
|
+
target().push({
|
|
114
|
+
type: 'output',
|
|
115
|
+
helper: helper[1],
|
|
116
|
+
arg: reference(helper[2].trim(), tag),
|
|
117
|
+
source: tag,
|
|
118
|
+
});
|
|
119
|
+
else
|
|
120
|
+
target().push({ type: 'output', helper: null, arg: reference(tag, tag), source: tag });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const open = stack.at(-1);
|
|
124
|
+
if (open)
|
|
125
|
+
templateError(`{{#${open.node.type}}} بلا {{/${open.node.type}}}`);
|
|
126
|
+
return root;
|
|
127
|
+
}
|
|
128
|
+
/** Visits every tag of a parsed template, with the line group of the enclosing each. */
|
|
129
|
+
export function walkTemplate(nodes, visit, group = null) {
|
|
130
|
+
for (const node of nodes) {
|
|
131
|
+
if (node.type === 'text')
|
|
132
|
+
continue;
|
|
133
|
+
visit(node, group);
|
|
134
|
+
if (node.type === 'if') {
|
|
135
|
+
walkTemplate(node.then, visit, group);
|
|
136
|
+
walkTemplate(node.else, visit, group);
|
|
137
|
+
}
|
|
138
|
+
else if (node.type === 'each')
|
|
139
|
+
walkTemplate(node.body, visit, node.group);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -1,10 +1,20 @@
|
|
|
1
1
|
import type { Knex } from 'knex';
|
|
2
2
|
export type CalendarSystem = 'gregory' | 'islamic-umalqura';
|
|
3
3
|
export type CalendarPreference = CalendarSystem | 'both';
|
|
4
|
+
/** Latin (0-9) or Arabic-Indic (٠-٩) digits in printed documents. */
|
|
5
|
+
export type DigitsPreference = 'latn' | 'arab';
|
|
6
|
+
/** Where the workspace navigation sits: a side panel or a bar of tabs above the page. */
|
|
7
|
+
export type NavigationLayout = 'sidebar' | 'top';
|
|
4
8
|
export type UiPreferences = {
|
|
5
9
|
calendar: CalendarPreference;
|
|
6
10
|
confirmDialogClose: boolean;
|
|
7
11
|
pageTransitions: boolean;
|
|
12
|
+
/** Optional for values stored before it existed; absent means 'latn'. */
|
|
13
|
+
digits?: DigitsPreference;
|
|
14
|
+
/** The system's navigation layout; absent means 'sidebar'. */
|
|
15
|
+
layout?: NavigationLayout;
|
|
16
|
+
/** Lets each user choose their own layout from the account menu; absent means false. */
|
|
17
|
+
layoutUserChoice?: boolean;
|
|
8
18
|
};
|
|
9
19
|
export declare const UI_PREFERENCES_KEY = "ui.preferences";
|
|
10
20
|
export declare const DEFAULT_UI_PREFERENCES: UiPreferences;
|
|
@@ -6,6 +6,14 @@ export const DEFAULT_UI_PREFERENCES = {
|
|
|
6
6
|
confirmDialogClose: true,
|
|
7
7
|
pageTransitions: true,
|
|
8
8
|
};
|
|
9
|
+
const PREFERENCE_KEYS = [
|
|
10
|
+
'calendar',
|
|
11
|
+
'confirmDialogClose',
|
|
12
|
+
'pageTransitions',
|
|
13
|
+
'digits',
|
|
14
|
+
'layout',
|
|
15
|
+
'layoutUserChoice',
|
|
16
|
+
];
|
|
9
17
|
export function validateUiPreferences(value) {
|
|
10
18
|
const input = value;
|
|
11
19
|
if (!input ||
|
|
@@ -14,12 +22,18 @@ export function validateUiPreferences(value) {
|
|
|
14
22
|
!['gregory', 'islamic-umalqura', 'both'].includes(input.calendar) ||
|
|
15
23
|
typeof input.confirmDialogClose !== 'boolean' ||
|
|
16
24
|
typeof input.pageTransitions !== 'boolean' ||
|
|
17
|
-
|
|
25
|
+
(input.digits !== undefined && !['latn', 'arab'].includes(input.digits)) ||
|
|
26
|
+
(input.layout !== undefined && !['sidebar', 'top'].includes(input.layout)) ||
|
|
27
|
+
(input.layoutUserChoice !== undefined && typeof input.layoutUserChoice !== 'boolean') ||
|
|
28
|
+
Object.keys(input).some((key) => !PREFERENCE_KEYS.includes(key)))
|
|
18
29
|
throw new AdulaError(422, 'E_UI_PREFERENCES', 'اختر تقويمًا صالحًا وحدد خيارات تأكيد الإغلاق والانتقالات');
|
|
19
30
|
return {
|
|
20
31
|
calendar: input.calendar,
|
|
21
32
|
confirmDialogClose: input.confirmDialogClose,
|
|
22
33
|
pageTransitions: input.pageTransitions,
|
|
34
|
+
...(input.digits === undefined ? {} : { digits: input.digits }),
|
|
35
|
+
...(input.layout === undefined ? {} : { layout: input.layout }),
|
|
36
|
+
...(input.layoutUserChoice === undefined ? {} : { layoutUserChoice: input.layoutUserChoice }),
|
|
23
37
|
};
|
|
24
38
|
}
|
|
25
39
|
export async function uiPreferences(db) {
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { Knex } from 'knex';
|
|
2
|
+
import type { AvatarImage } from './avatar_image.js';
|
|
3
|
+
/**
|
|
4
|
+
* A profile picture is one `attachments` row bound to this owner (ADR 050). The name is not
|
|
5
|
+
* a registered resource, so `/attachments/:id` never serves it, pruning never removes it,
|
|
6
|
+
* and backups and `adula:storage:migrate` carry it like every other bound file.
|
|
7
|
+
*/
|
|
8
|
+
export declare const AVATAR_OWNER: Readonly<{
|
|
9
|
+
resource: "core_users";
|
|
10
|
+
field: "avatar";
|
|
11
|
+
}>;
|
|
12
|
+
export type AvatarRecord = {
|
|
13
|
+
userId: number;
|
|
14
|
+
/** The attachment row id; it changes with every upload and is never reused. */
|
|
15
|
+
version: number;
|
|
16
|
+
disk: string;
|
|
17
|
+
path: string;
|
|
18
|
+
size: number;
|
|
19
|
+
mimeType: string;
|
|
20
|
+
width: number;
|
|
21
|
+
height: number;
|
|
22
|
+
};
|
|
23
|
+
/** A file the host deletes from its disk after the transaction committed. */
|
|
24
|
+
export type RemovedAvatarFile = {
|
|
25
|
+
disk: string;
|
|
26
|
+
path: string;
|
|
27
|
+
};
|
|
28
|
+
type Change = {
|
|
29
|
+
userId: number;
|
|
30
|
+
actorId: number;
|
|
31
|
+
impersonatorId?: number | null;
|
|
32
|
+
/** True on the administration page: the actor manages another user's picture. */
|
|
33
|
+
administered?: boolean;
|
|
34
|
+
};
|
|
35
|
+
/** The URL of a user's picture; with a version, the response may be cached for good. */
|
|
36
|
+
export declare function avatarUrl(userId: number, version?: number | null): string;
|
|
37
|
+
/**
|
|
38
|
+
* A select column with the current picture version of the user in `userColumn`, as `alias`.
|
|
39
|
+
* It belongs in the query that already resolves the person's name, so a list of people costs
|
|
40
|
+
* no query per row (the `attachments (resource, record_id, field)` index serves it).
|
|
41
|
+
*/
|
|
42
|
+
export declare function avatarVersionColumn(db: Knex, userColumn: string, alias?: string): Knex.Raw<any>;
|
|
43
|
+
/**
|
|
44
|
+
* The versioned picture URL of a user, or null when they have none: the page then shows the
|
|
45
|
+
* initials and requests nothing, so a user without a picture costs no 404.
|
|
46
|
+
*/
|
|
47
|
+
export declare function avatarUrlFor(userId: unknown, version: unknown): string | null;
|
|
48
|
+
/**
|
|
49
|
+
* Response headers of a profile picture: the stored, allow-listed type only, no sniffing and
|
|
50
|
+
* no script. A versioned URL never changes its bytes, so it is cached privately for a year;
|
|
51
|
+
* the plain URL is revalidated after five minutes with the version as its ETag.
|
|
52
|
+
*/
|
|
53
|
+
export declare function avatarHeaders(avatar: AvatarRecord, options?: {
|
|
54
|
+
immutable?: boolean;
|
|
55
|
+
}): Record<string, string>;
|
|
56
|
+
export declare class UserAvatars {
|
|
57
|
+
#private;
|
|
58
|
+
private db;
|
|
59
|
+
constructor(db: Knex);
|
|
60
|
+
find(userId: number): Promise<AvatarRecord | null>;
|
|
61
|
+
/** The current picture version of each user that has one, in one query. */
|
|
62
|
+
versions(userIds: readonly number[]): Promise<Map<number, number>>;
|
|
63
|
+
/**
|
|
64
|
+
* Records a stored, sanitized picture as the user's avatar and retires the previous one in
|
|
65
|
+
* the same transaction. The host has already written `path` to `disk`; it deletes the
|
|
66
|
+
* returned files after the commit.
|
|
67
|
+
*/
|
|
68
|
+
replace(change: Change & {
|
|
69
|
+
disk: string;
|
|
70
|
+
path: string;
|
|
71
|
+
image: AvatarImage;
|
|
72
|
+
}): Promise<{
|
|
73
|
+
avatar: AvatarRecord;
|
|
74
|
+
removed: RemovedAvatarFile[];
|
|
75
|
+
}>;
|
|
76
|
+
/** Removes the user's picture; nothing happens when there is none. */
|
|
77
|
+
remove(change: Change): Promise<RemovedAvatarFile[]>;
|
|
78
|
+
}
|
|
79
|
+
export {};
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { AdulaError } from '../admin/errors.js';
|
|
2
|
+
import { logActivity } from './activity.js';
|
|
3
|
+
import { registerUpload, isAttachmentId } from '../attachments/attachment_service.js';
|
|
4
|
+
/**
|
|
5
|
+
* A profile picture is one `attachments` row bound to this owner (ADR 050). The name is not
|
|
6
|
+
* a registered resource, so `/attachments/:id` never serves it, pruning never removes it,
|
|
7
|
+
* and backups and `adula:storage:migrate` carry it like every other bound file.
|
|
8
|
+
*/
|
|
9
|
+
export const AVATAR_OWNER = Object.freeze({ resource: 'core_users', field: 'avatar' });
|
|
10
|
+
/**
|
|
11
|
+
* What happens to the previous picture when a user replaces or removes it. 'delete' removes
|
|
12
|
+
* the row and the file (a personal photo does not outlive its removal); 'keep' soft-deletes
|
|
13
|
+
* the row and keeps the file, as field attachments do (ADR 047).
|
|
14
|
+
*/
|
|
15
|
+
const REMOVED_PICTURES = 'delete';
|
|
16
|
+
/** The URL of a user's picture; with a version, the response may be cached for good. */
|
|
17
|
+
export function avatarUrl(userId, version) {
|
|
18
|
+
return version ? `/users/${userId}/avatar?v=${version}` : `/users/${userId}/avatar`;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* A select column with the current picture version of the user in `userColumn`, as `alias`.
|
|
22
|
+
* It belongs in the query that already resolves the person's name, so a list of people costs
|
|
23
|
+
* no query per row (the `attachments (resource, record_id, field)` index serves it).
|
|
24
|
+
*/
|
|
25
|
+
export function avatarVersionColumn(db, userColumn, alias = 'avatar_version') {
|
|
26
|
+
return db.raw(`(select max(av.id) from attachments av where av.resource = ? and av.field = ? and av.deleted_at is null and av.record_id = ??) as ??`, [AVATAR_OWNER.resource, AVATAR_OWNER.field, userColumn, alias]);
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The versioned picture URL of a user, or null when they have none: the page then shows the
|
|
30
|
+
* initials and requests nothing, so a user without a picture costs no 404.
|
|
31
|
+
*/
|
|
32
|
+
export function avatarUrlFor(userId, version) {
|
|
33
|
+
const id = Number(userId);
|
|
34
|
+
const current = Number(version);
|
|
35
|
+
return Number.isSafeInteger(id) && id > 0 && Number.isSafeInteger(current) && current > 0
|
|
36
|
+
? avatarUrl(id, current)
|
|
37
|
+
: null;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Response headers of a profile picture: the stored, allow-listed type only, no sniffing and
|
|
41
|
+
* no script. A versioned URL never changes its bytes, so it is cached privately for a year;
|
|
42
|
+
* the plain URL is revalidated after five minutes with the version as its ETag.
|
|
43
|
+
*/
|
|
44
|
+
export function avatarHeaders(avatar, options = {}) {
|
|
45
|
+
return {
|
|
46
|
+
'Content-Type': avatar.mimeType === 'image/webp' ? 'image/webp' : 'image/png',
|
|
47
|
+
'Content-Length': String(avatar.size),
|
|
48
|
+
'Content-Disposition': 'inline',
|
|
49
|
+
'X-Content-Type-Options': 'nosniff',
|
|
50
|
+
'Content-Security-Policy': "default-src 'none'; sandbox",
|
|
51
|
+
'Cross-Origin-Resource-Policy': 'same-origin',
|
|
52
|
+
'ETag': `"avatar-${avatar.version}"`,
|
|
53
|
+
'Cache-Control': options.immutable
|
|
54
|
+
? 'private, max-age=31536000, immutable'
|
|
55
|
+
: 'private, max-age=300',
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
const live = (db) => db('attachments')
|
|
59
|
+
.where('resource', AVATAR_OWNER.resource)
|
|
60
|
+
.where('field', AVATAR_OWNER.field)
|
|
61
|
+
.whereNull('deleted_at');
|
|
62
|
+
function fromRow(row) {
|
|
63
|
+
const data = (row.data ?? {});
|
|
64
|
+
return {
|
|
65
|
+
userId: Number(row.record_id),
|
|
66
|
+
version: Number(row.id),
|
|
67
|
+
disk: String(row.disk),
|
|
68
|
+
path: String(row.path),
|
|
69
|
+
size: Number(row.size),
|
|
70
|
+
mimeType: String(row.mime_type),
|
|
71
|
+
width: Number(data.width ?? 0),
|
|
72
|
+
height: Number(data.height ?? 0),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
export class UserAvatars {
|
|
76
|
+
db;
|
|
77
|
+
constructor(db) {
|
|
78
|
+
this.db = db;
|
|
79
|
+
}
|
|
80
|
+
async find(userId) {
|
|
81
|
+
if (!isAttachmentId(userId))
|
|
82
|
+
return null;
|
|
83
|
+
const row = await live(this.db).where('record_id', userId).orderBy('id', 'desc').first();
|
|
84
|
+
return row ? fromRow(row) : null;
|
|
85
|
+
}
|
|
86
|
+
/** The current picture version of each user that has one, in one query. */
|
|
87
|
+
async versions(userIds) {
|
|
88
|
+
const ids = [...new Set(userIds.filter(isAttachmentId))];
|
|
89
|
+
const versions = new Map();
|
|
90
|
+
if (!ids.length)
|
|
91
|
+
return versions;
|
|
92
|
+
const rows = await live(this.db)
|
|
93
|
+
.whereIn('record_id', ids)
|
|
94
|
+
.groupBy('record_id')
|
|
95
|
+
.select('record_id')
|
|
96
|
+
.max('id as max');
|
|
97
|
+
for (const row of rows)
|
|
98
|
+
versions.set(Number(row.record_id), Number(row.max));
|
|
99
|
+
return versions;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Records a stored, sanitized picture as the user's avatar and retires the previous one in
|
|
103
|
+
* the same transaction. The host has already written `path` to `disk`; it deletes the
|
|
104
|
+
* returned files after the commit.
|
|
105
|
+
*/
|
|
106
|
+
async replace(change) {
|
|
107
|
+
return this.db.transaction(async (trx) => {
|
|
108
|
+
await this.#lock(trx, change);
|
|
109
|
+
const row = await registerUpload(trx, {
|
|
110
|
+
disk: change.disk,
|
|
111
|
+
path: change.path,
|
|
112
|
+
name: change.path.split('/').at(-1) ?? '',
|
|
113
|
+
originalName: `avatar.${change.image.extname}`,
|
|
114
|
+
size: change.image.bytes.length,
|
|
115
|
+
mimeType: change.image.mimeType,
|
|
116
|
+
extname: change.image.extname,
|
|
117
|
+
data: { width: change.image.width, height: change.image.height },
|
|
118
|
+
uploadedBy: change.actorId,
|
|
119
|
+
impersonatorId: change.impersonatorId,
|
|
120
|
+
resource: AVATAR_OWNER.resource,
|
|
121
|
+
field: AVATAR_OWNER.field,
|
|
122
|
+
});
|
|
123
|
+
const [bound] = await trx('attachments')
|
|
124
|
+
.where('id', row.id)
|
|
125
|
+
.update({ record_id: change.userId })
|
|
126
|
+
.returning('*');
|
|
127
|
+
const { removed } = await this.#retire(trx, change.userId, row.id);
|
|
128
|
+
await this.#log(trx, change, 'avatar_updated', {
|
|
129
|
+
version: row.id,
|
|
130
|
+
width: change.image.width,
|
|
131
|
+
height: change.image.height,
|
|
132
|
+
});
|
|
133
|
+
return { avatar: fromRow(bound), removed };
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
/** Removes the user's picture; nothing happens when there is none. */
|
|
137
|
+
async remove(change) {
|
|
138
|
+
return this.db.transaction(async (trx) => {
|
|
139
|
+
await this.#lock(trx, change);
|
|
140
|
+
const { count, removed } = await this.#retire(trx, change.userId);
|
|
141
|
+
if (count)
|
|
142
|
+
await this.#log(trx, change, 'avatar_removed', {});
|
|
143
|
+
return removed;
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
/** One change per user at a time; the row lock also proves the user exists. */
|
|
147
|
+
async #lock(trx, change) {
|
|
148
|
+
if (!isAttachmentId(change.userId) || !isAttachmentId(change.actorId))
|
|
149
|
+
throw new AdulaError(404, 'E_USER_NOT_FOUND', 'المستخدم غير موجود');
|
|
150
|
+
if (!change.administered && change.actorId !== change.userId)
|
|
151
|
+
throw new AdulaError(403, 'E_FORBIDDEN', 'ليس لديك صلاحية لهذا الإجراء');
|
|
152
|
+
const user = await trx('users').where('id', change.userId).forUpdate().first('id');
|
|
153
|
+
if (!user)
|
|
154
|
+
throw new AdulaError(404, 'E_USER_NOT_FOUND', 'المستخدم غير موجود');
|
|
155
|
+
}
|
|
156
|
+
async #retire(trx, userId, exceptId) {
|
|
157
|
+
const previous = live(trx).where('record_id', userId);
|
|
158
|
+
if (exceptId)
|
|
159
|
+
previous.whereNot('id', exceptId);
|
|
160
|
+
const rows = await previous.select('id', 'disk', 'path');
|
|
161
|
+
const count = rows.length;
|
|
162
|
+
if (!count)
|
|
163
|
+
return { count, removed: [] };
|
|
164
|
+
const ids = rows.map((row) => Number(row.id));
|
|
165
|
+
if (REMOVED_PICTURES === 'keep') {
|
|
166
|
+
await trx('attachments').whereIn('id', ids).update({ deleted_at: trx.fn.now() });
|
|
167
|
+
return { count, removed: [] };
|
|
168
|
+
}
|
|
169
|
+
await trx('attachments').whereIn('id', ids).delete();
|
|
170
|
+
return {
|
|
171
|
+
count,
|
|
172
|
+
removed: rows.map((row) => ({ disk: String(row.disk), path: String(row.path) })),
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
#log(trx, change, action, changes) {
|
|
176
|
+
return logActivity(trx, {
|
|
177
|
+
// The user's own changes sit with their account activity, like profile_updated.
|
|
178
|
+
resource: change.administered ? 'core.users' : 'users',
|
|
179
|
+
recordId: change.userId,
|
|
180
|
+
actorId: change.actorId,
|
|
181
|
+
impersonatorId: change.impersonatorId,
|
|
182
|
+
action,
|
|
183
|
+
changes,
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
}
|
|
@@ -12,7 +12,11 @@ export declare class UserInvitations {
|
|
|
12
12
|
invite(actorId: number, input: {
|
|
13
13
|
email: string;
|
|
14
14
|
fullName: string;
|
|
15
|
-
}, send: (invitation: InvitationDelivery) => Promise<void
|
|
15
|
+
}, send: (invitation: InvitationDelivery) => Promise<void>,
|
|
16
|
+
/** The administrator impersonating actorId; recorded in each activity entry. */
|
|
17
|
+
context?: {
|
|
18
|
+
impersonatorId?: number | null;
|
|
19
|
+
}): Promise<{
|
|
16
20
|
id: number;
|
|
17
21
|
email: string;
|
|
18
22
|
}>;
|
|
@@ -22,7 +22,10 @@ export class UserInvitations {
|
|
|
22
22
|
const actor = await new ActorStore(this.db, new ResourceRegistry()).load(actorId);
|
|
23
23
|
return buildAbility(actor.rules).can('invite', subject(RESOURCE, {}));
|
|
24
24
|
}
|
|
25
|
-
async invite(actorId, input, send
|
|
25
|
+
async invite(actorId, input, send,
|
|
26
|
+
/** The administrator impersonating actorId; recorded in each activity entry. */
|
|
27
|
+
context = {}) {
|
|
28
|
+
const impersonatorId = context.impersonatorId ?? null;
|
|
26
29
|
const email = typeof input.email === 'string' ? input.email.trim().toLowerCase() : '';
|
|
27
30
|
const fullName = typeof input.fullName === 'string' ? input.fullName.trim() : '';
|
|
28
31
|
if (!email ||
|
|
@@ -60,6 +63,7 @@ export class UserInvitations {
|
|
|
60
63
|
resource: INVITATIONS,
|
|
61
64
|
recordId: row.id,
|
|
62
65
|
actorId,
|
|
66
|
+
impersonatorId,
|
|
63
67
|
action: 'invitation_created',
|
|
64
68
|
changes: { email },
|
|
65
69
|
});
|
|
@@ -78,6 +82,7 @@ export class UserInvitations {
|
|
|
78
82
|
resource: INVITATIONS,
|
|
79
83
|
recordId: id,
|
|
80
84
|
actorId,
|
|
85
|
+
impersonatorId,
|
|
81
86
|
action: 'invitation_delivery_failed',
|
|
82
87
|
changes: { email },
|
|
83
88
|
});
|
|
@@ -87,6 +92,7 @@ export class UserInvitations {
|
|
|
87
92
|
resource: INVITATIONS,
|
|
88
93
|
recordId: id,
|
|
89
94
|
actorId,
|
|
95
|
+
impersonatorId,
|
|
90
96
|
action: 'invitation_sent',
|
|
91
97
|
changes: { email },
|
|
92
98
|
});
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { Knex } from 'knex';
|
|
2
|
+
import type { JsonValue } from '../resource/types.js';
|
|
3
|
+
/**
|
|
4
|
+
* One per-user interface preference (ADR 049): the sidebar state, the navigation layout, the
|
|
5
|
+
* theme, an arrangement. The application declares its keys once; each key validates its own
|
|
6
|
+
* value, so a stored value is always one the interface understands.
|
|
7
|
+
*/
|
|
8
|
+
export type PreferenceDefinition<T extends JsonValue = JsonValue> = {
|
|
9
|
+
/** Lower camel segments joined by dots: `shell.sidebar`, `overview.layout`. */
|
|
10
|
+
key: string;
|
|
11
|
+
default: T;
|
|
12
|
+
/** Returns the normalized value, or throws `AdulaError(422, 'E_PREFERENCE_VALUE', …)`. */
|
|
13
|
+
validate: (value: unknown) => T;
|
|
14
|
+
};
|
|
15
|
+
/** Preferences live in `settings` with scope `user`; this prefix keeps them apart. */
|
|
16
|
+
export declare const PREFERENCE_PREFIX = "preference.";
|
|
17
|
+
/** Upper bound for one stored value, in UTF-8 bytes. */
|
|
18
|
+
export declare const PREFERENCE_MAX_BYTES = 4096;
|
|
19
|
+
export declare function definePreference<T extends JsonValue>(definition: PreferenceDefinition<T>): PreferenceDefinition<T>;
|
|
20
|
+
/** True for a settings key that stores a user's own preference. */
|
|
21
|
+
export declare function isPreferenceSetting(key: string): boolean;
|
|
22
|
+
export declare class UserPreferences {
|
|
23
|
+
#private;
|
|
24
|
+
private db;
|
|
25
|
+
private report;
|
|
26
|
+
constructor(db: Knex, definitions: PreferenceDefinition[], report?: (key: string, error: unknown) => void);
|
|
27
|
+
/** Boot check: keys are well formed and unique, and every default passes its validator. */
|
|
28
|
+
static validate(definitions: PreferenceDefinition[]): void;
|
|
29
|
+
keys(): string[];
|
|
30
|
+
/** Every registered preference of the user, defaults filled in. */
|
|
31
|
+
all(userId: number): Promise<Record<string, JsonValue>>;
|
|
32
|
+
get<T extends JsonValue = JsonValue>(userId: number, key: string): Promise<T>;
|
|
33
|
+
set<T extends JsonValue = JsonValue>(userId: number, key: string, value: unknown): Promise<T>;
|
|
34
|
+
/** Removes the stored value; the user sees the default again. */
|
|
35
|
+
reset<T extends JsonValue = JsonValue>(userId: number, key: string): Promise<T>;
|
|
36
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { AdulaError } from '../admin/errors.js';
|
|
2
|
+
/** Preferences live in `settings` with scope `user`; this prefix keeps them apart. */
|
|
3
|
+
export const PREFERENCE_PREFIX = 'preference.';
|
|
4
|
+
/** Upper bound for one stored value, in UTF-8 bytes. */
|
|
5
|
+
export const PREFERENCE_MAX_BYTES = 4096;
|
|
6
|
+
const KEY = /^[a-z][a-zA-Z0-9]*(\.[a-z][a-zA-Z0-9]*)+$/;
|
|
7
|
+
// The settings key column accepts at most 100 characters, prefix included.
|
|
8
|
+
const MAX_KEY_LENGTH = 100 - PREFERENCE_PREFIX.length;
|
|
9
|
+
export function definePreference(definition) {
|
|
10
|
+
if (!KEY.test(definition.key) || definition.key.length > MAX_KEY_LENGTH)
|
|
11
|
+
throw new Error(`Invalid preference key "${definition.key}"`);
|
|
12
|
+
return definition;
|
|
13
|
+
}
|
|
14
|
+
/** True for a settings key that stores a user's own preference. */
|
|
15
|
+
export function isPreferenceSetting(key) {
|
|
16
|
+
return key.startsWith(PREFERENCE_PREFIX);
|
|
17
|
+
}
|
|
18
|
+
function invalid() {
|
|
19
|
+
throw new AdulaError(422, 'E_PREFERENCE_VALUE', 'قيمة التفضيل غير صالحة');
|
|
20
|
+
}
|
|
21
|
+
function sized(value) {
|
|
22
|
+
const text = JSON.stringify(value);
|
|
23
|
+
if (text === undefined)
|
|
24
|
+
invalid();
|
|
25
|
+
if (Buffer.byteLength(text, 'utf8') > PREFERENCE_MAX_BYTES)
|
|
26
|
+
throw new AdulaError(422, 'E_PREFERENCE_TOO_LARGE', 'قيمة التفضيل أكبر من المسموح');
|
|
27
|
+
return text;
|
|
28
|
+
}
|
|
29
|
+
function userScope(userId) {
|
|
30
|
+
if (!Number.isSafeInteger(userId) || userId <= 0)
|
|
31
|
+
throw new Error('Invalid user id');
|
|
32
|
+
return String(userId);
|
|
33
|
+
}
|
|
34
|
+
export class UserPreferences {
|
|
35
|
+
db;
|
|
36
|
+
report;
|
|
37
|
+
#definitions = new Map();
|
|
38
|
+
constructor(db, definitions, report = () => { }) {
|
|
39
|
+
this.db = db;
|
|
40
|
+
this.report = report;
|
|
41
|
+
UserPreferences.validate(definitions);
|
|
42
|
+
for (const definition of definitions)
|
|
43
|
+
this.#definitions.set(definition.key, definition);
|
|
44
|
+
}
|
|
45
|
+
/** Boot check: keys are well formed and unique, and every default passes its validator. */
|
|
46
|
+
static validate(definitions) {
|
|
47
|
+
const seen = new Set();
|
|
48
|
+
for (const definition of definitions) {
|
|
49
|
+
definePreference(definition);
|
|
50
|
+
if (seen.has(definition.key))
|
|
51
|
+
throw new Error(`Duplicate preference "${definition.key}"`);
|
|
52
|
+
seen.add(definition.key);
|
|
53
|
+
sized(definition.default);
|
|
54
|
+
const normalized = definition.validate(definition.default);
|
|
55
|
+
if (JSON.stringify(normalized) !== JSON.stringify(definition.default))
|
|
56
|
+
throw new Error(`The default of preference "${definition.key}" does not validate`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
keys() {
|
|
60
|
+
return [...this.#definitions.keys()];
|
|
61
|
+
}
|
|
62
|
+
/** Every registered preference of the user, defaults filled in. */
|
|
63
|
+
async all(userId) {
|
|
64
|
+
const keys = this.keys();
|
|
65
|
+
const rows = keys.length
|
|
66
|
+
? await this.db('settings')
|
|
67
|
+
.where({ scope: 'user', scope_id: userScope(userId) })
|
|
68
|
+
.whereIn('key', keys.map((key) => PREFERENCE_PREFIX + key))
|
|
69
|
+
.select('key', 'value')
|
|
70
|
+
: [];
|
|
71
|
+
const stored = new Map(rows.map((row) => [String(row.key), row.value]));
|
|
72
|
+
const result = {};
|
|
73
|
+
for (const [key, definition] of this.#definitions)
|
|
74
|
+
result[key] = this.#read(definition, stored.get(PREFERENCE_PREFIX + key));
|
|
75
|
+
return result;
|
|
76
|
+
}
|
|
77
|
+
async get(userId, key) {
|
|
78
|
+
const definition = this.#definition(key);
|
|
79
|
+
const row = await this.db('settings')
|
|
80
|
+
.where({ key: PREFERENCE_PREFIX + key, scope: 'user', scope_id: userScope(userId) })
|
|
81
|
+
.first('value');
|
|
82
|
+
return this.#read(definition, row?.value);
|
|
83
|
+
}
|
|
84
|
+
async set(userId, key, value) {
|
|
85
|
+
const definition = this.#definition(key);
|
|
86
|
+
sized(value);
|
|
87
|
+
const normalized = definition.validate(value);
|
|
88
|
+
await this.db('settings')
|
|
89
|
+
.insert({
|
|
90
|
+
key: PREFERENCE_PREFIX + key,
|
|
91
|
+
scope: 'user',
|
|
92
|
+
scope_id: userScope(userId),
|
|
93
|
+
value: sized(normalized),
|
|
94
|
+
})
|
|
95
|
+
.onConflict(['key', 'scope', 'scope_id'])
|
|
96
|
+
.merge(['value']);
|
|
97
|
+
return normalized;
|
|
98
|
+
}
|
|
99
|
+
/** Removes the stored value; the user sees the default again. */
|
|
100
|
+
async reset(userId, key) {
|
|
101
|
+
const definition = this.#definition(key);
|
|
102
|
+
await this.db('settings')
|
|
103
|
+
.where({ key: PREFERENCE_PREFIX + key, scope: 'user', scope_id: userScope(userId) })
|
|
104
|
+
.delete();
|
|
105
|
+
return definition.default;
|
|
106
|
+
}
|
|
107
|
+
#definition(key) {
|
|
108
|
+
const definition = this.#definitions.get(key);
|
|
109
|
+
if (!definition)
|
|
110
|
+
throw new AdulaError(404, 'E_PREFERENCE_UNKNOWN', 'التفضيل غير معروف');
|
|
111
|
+
return definition;
|
|
112
|
+
}
|
|
113
|
+
// A value stored by an older release that no longer validates falls back to the default.
|
|
114
|
+
#read(definition, value) {
|
|
115
|
+
if (value === undefined || value === null)
|
|
116
|
+
return definition.default;
|
|
117
|
+
try {
|
|
118
|
+
return definition.validate(value);
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
this.report(definition.key, error);
|
|
122
|
+
return definition.default;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|