@genesislcap/mock-server 15.74.0 → 15.76.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 (100) hide show
  1. package/README.md +296 -58
  2. package/dist/db/schema.d.ts +9 -1
  3. package/dist/db/schema.js +40 -11
  4. package/dist/db/store.d.ts +1 -0
  5. package/dist/db/store.js +4 -0
  6. package/dist/handlers/auth.d.ts +15 -6
  7. package/dist/handlers/auth.js +152 -33
  8. package/dist/handlers/commitEvent.js +43 -20
  9. package/dist/handlers/crudEvents.d.ts +3 -1
  10. package/dist/handlers/crudEvents.js +3 -2
  11. package/dist/handlers/eventValidation.js +6 -3
  12. package/dist/handlers/http.d.ts +2 -2
  13. package/dist/handlers/http.js +66 -43
  14. package/dist/handlers/jsonSchema.d.ts +1 -0
  15. package/dist/handlers/jsonSchema.js +72 -21
  16. package/dist/handlers/meta.d.ts +1 -1
  17. package/dist/handlers/meta.js +59 -10
  18. package/dist/handlers/requestReply.js +36 -9
  19. package/dist/index.d.ts +1 -1
  20. package/dist/presets/auth.d.ts +25 -0
  21. package/dist/presets/auth.js +855 -0
  22. package/dist/presets/cronExpression.d.ts +1 -0
  23. package/dist/presets/cronExpression.js +429 -0
  24. package/dist/presets/fileServer.d.ts +13 -0
  25. package/dist/presets/fileServer.js +399 -0
  26. package/dist/presets/gsf.d.ts +24 -0
  27. package/dist/presets/gsf.js +450 -0
  28. package/dist/presets/index.d.ts +1 -0
  29. package/dist/presets/index.js +1 -0
  30. package/dist/presets/javaTime.d.ts +7 -0
  31. package/dist/presets/javaTime.js +322 -0
  32. package/dist/presets/multipart.d.ts +14 -0
  33. package/dist/presets/multipart.js +91 -0
  34. package/dist/presets/notify.d.ts +27 -0
  35. package/dist/presets/notify.js +250 -0
  36. package/dist/presets/notifyDispatch.d.ts +28 -0
  37. package/dist/presets/notifyDispatch.js +570 -0
  38. package/dist/presets/notifyRules.d.ts +9 -0
  39. package/dist/presets/notifyRules.js +754 -0
  40. package/dist/presets/platform/backing.json +8058 -217
  41. package/dist/presets/platform/criteria-model.json +362 -0
  42. package/dist/presets/platform/time-zones.json +608 -0
  43. package/dist/presets/platform.d.ts +7 -0
  44. package/dist/presets/platform.js +145 -103
  45. package/dist/presets/products.d.ts +9 -7
  46. package/dist/presets/products.js +89 -21
  47. package/dist/presets/reconciliation.d.ts +18 -0
  48. package/dist/presets/reconciliation.js +721 -0
  49. package/dist/presets/reporting.d.ts +14 -0
  50. package/dist/presets/reporting.js +862 -0
  51. package/dist/protocol/connection.d.ts +2 -0
  52. package/dist/protocol/connection.js +4 -0
  53. package/dist/protocol/dtoTypes.d.ts +30 -0
  54. package/dist/protocol/dtoTypes.js +250 -0
  55. package/dist/protocol/errors.d.ts +3 -1
  56. package/dist/protocol/errors.js +2 -0
  57. package/dist/protocol/fieldTypes.js +5 -0
  58. package/dist/protocol/router.d.ts +1 -0
  59. package/dist/protocol/router.js +3 -3
  60. package/dist/protocol/schemaValidation.d.ts +1 -1
  61. package/dist/protocol/schemaValidation.js +53 -8
  62. package/dist/server.js +34 -2
  63. package/dist/types.d.ts +50 -2
  64. package/package.json +1 -1
  65. package/src/db/schema.ts +56 -13
  66. package/src/db/store.ts +5 -0
  67. package/src/handlers/auth.ts +211 -37
  68. package/src/handlers/commitEvent.ts +44 -19
  69. package/src/handlers/crudEvents.ts +9 -2
  70. package/src/handlers/eventValidation.ts +6 -3
  71. package/src/handlers/http.ts +83 -42
  72. package/src/handlers/jsonSchema.ts +86 -23
  73. package/src/handlers/meta.ts +77 -9
  74. package/src/handlers/requestReply.ts +42 -6
  75. package/src/index.ts +7 -0
  76. package/src/presets/auth.ts +961 -0
  77. package/src/presets/cronExpression.ts +445 -0
  78. package/src/presets/fileServer.ts +475 -0
  79. package/src/presets/gsf.ts +475 -0
  80. package/src/presets/index.ts +5 -0
  81. package/src/presets/javaTime.ts +354 -0
  82. package/src/presets/multipart.ts +110 -0
  83. package/src/presets/notify.ts +312 -0
  84. package/src/presets/notifyDispatch.ts +685 -0
  85. package/src/presets/notifyRules.ts +866 -0
  86. package/src/presets/platform/backing.json +8058 -217
  87. package/src/presets/platform/criteria-model.json +362 -0
  88. package/src/presets/platform/time-zones.json +608 -0
  89. package/src/presets/platform.ts +204 -115
  90. package/src/presets/products.ts +125 -19
  91. package/src/presets/reconciliation.ts +824 -0
  92. package/src/presets/reporting.ts +953 -0
  93. package/src/protocol/connection.ts +4 -0
  94. package/src/protocol/dtoTypes.ts +310 -0
  95. package/src/protocol/errors.ts +13 -1
  96. package/src/protocol/fieldTypes.ts +5 -0
  97. package/src/protocol/router.ts +3 -3
  98. package/src/protocol/schemaValidation.ts +61 -8
  99. package/src/server.ts +38 -2
  100. package/src/types.ts +147 -3
@@ -0,0 +1,866 @@
1
+ // genesis-notify's notification rules and rule templates: their ten events
2
+ // (genesis-notify-rules-eventhandler.kts below as RULES-EH), the request
3
+ // servers that read them back (genesis-notify-rules-reqrep.kts, RULES-RR),
4
+ // and the rule and template reads with the filters the generated backing
5
+ // leaves out (genesis-notify-rules-dataserver.kts), genesis-notify v8.15.16.
6
+ //
7
+ // A rule is stored in DYNAMIC_RULE as Groovy strings, written from the model
8
+ // the rule dialog sends as GSF's EvaluatorExpressionWriter writes them. GSF
9
+ // reads them back for the dialog with a Groovy-based parser; this answers
10
+ // from the model it was sent instead, which differs only where parsing the
11
+ // written string wouldn't give that model back (a BigDecimal's formatting,
12
+ // say). Rules never fire here: GSF's DynamicRulesEngine, which raises an
13
+ // EVENT_NOTIFY_INSERT when a matching record changes, isn't modelled.
14
+ import type { Store } from '../db/store.ts';
15
+ import { NackError } from '../protocol/errors.ts';
16
+ import { schemaFieldErrors, validateSchema } from '../protocol/schemaValidation.ts';
17
+ import type {
18
+ EventHandler,
19
+ EventHandlerCtx,
20
+ EventSchemaOverride,
21
+ FieldDef,
22
+ QueryDef,
23
+ RequestingUser,
24
+ RequestReplyDef,
25
+ Row,
26
+ } from '../types.ts';
27
+ import { dto, ENUMS, nullable, type NotifyUsers } from './notify.ts';
28
+ import criteriaModel from './platform/criteria-model.json' with { type: 'json' };
29
+
30
+ const ADMIN_RIGHT = 'NotificationAdminAction';
31
+ const ON_BEHALF_RIGHT = 'SendNotificationOnBehalfOfOthers';
32
+
33
+ // --- the expression model, written as GSF does ---------------------------------
34
+
35
+ // global.genesis.criteria.model.Operation, MethodCall (genesis-criteria, GSF
36
+ // v8.15.29 Expressions.kt).
37
+ const OPERATIONS: Record<string, string> = {
38
+ GREATER_THAN: '>',
39
+ LESS_THAN: '<',
40
+ GREATER_THAN_OR_EQUAL: '>=',
41
+ LESS_THAN_OR_EQUAL: '<=',
42
+ EQUALS: '==',
43
+ NOT_EQUALS: '!=',
44
+ AND: '&&',
45
+ OR: '||',
46
+ PLUS: '+',
47
+ MINUS: '-',
48
+ MULTIPLY: '*',
49
+ DIVIDE: '/',
50
+ BITWISE_AND: '&',
51
+ BITWISE_OR: '|',
52
+ ASSIGNMENT: '=',
53
+ };
54
+ const METHODS: Record<string, string> = {
55
+ CONTAINS_IGNORE_CASE: 'Expr.containsIgnoreCase',
56
+ CONTAINS_WORDS_STARTING_WITH_IGNORE_CASE: 'Expr.containsWordsStartingWithIgnoreCase',
57
+ IS_NULL_OR_BLANK: 'Expr.isNullOrBlank',
58
+ NOT_NULL_OR_BLANK: 'Expr.notNullOrBlank',
59
+ LONG_TO_DATE: 'Expr.longLocalDate',
60
+ LONG_TO_DATE_TIME: 'Expr.longDateTime',
61
+ DATE_TIME_IS_IN_RANGE: 'Expr.dateTimeIsInRange',
62
+ };
63
+ const operation = (name: unknown) => OPERATIONS[String(name)] ?? String(name);
64
+
65
+ // EvaluatorExpressionWriter.writeExpression (genesis-criteria util).
66
+ function writeExpression(expression: Row): string {
67
+ switch (expression?.TYPE) {
68
+ case 'FIELD':
69
+ return String(expression.NAME);
70
+ case 'NUMBER':
71
+ return String(expression.VALUE);
72
+ case 'PLACEHOLDER':
73
+ return `{{${expression.KEY}}}`;
74
+ case 'STRING':
75
+ return `"${expression.VALUE}"`;
76
+ case 'BOOLEAN':
77
+ return String(expression.VALUE);
78
+ case 'NULL':
79
+ return 'null';
80
+ case 'BINARY_EXPRESSION':
81
+ return `(${writeExpression(expression.LEFT)} ${operation(expression.OPERATION)} ${writeExpression(expression.RIGHT)})`;
82
+ case 'METHOD_EXPRESSION':
83
+ return `${METHODS[expression.METHOD] ?? expression.METHOD}(${(expression.PARAMETERS ?? []).map(writeExpression).join(', ')})`;
84
+ case 'PREDICATE_EXPRESSION':
85
+ return `(${(expression.EXPRESSIONS ?? [])
86
+ .map(writeExpression)
87
+ .join(` ${operation(expression.OPERATION ?? 'AND')} `)})`;
88
+ default:
89
+ throw NackError.standard('INTERNAL_ERROR');
90
+ }
91
+ }
92
+
93
+ const writeRule = (rule: Row) =>
94
+ `(${(rule.CONDITIONS ?? [])
95
+ .map(
96
+ (condition: Row) =>
97
+ `(${writeExpression(condition.LEFT)} ${operation(condition.OPERATION)} ${writeExpression(condition.RIGHT)})`,
98
+ )
99
+ .join(' && ')})`;
100
+
101
+ const writeResult = (assignments: Row[]) =>
102
+ `(${assignments
103
+ .map(
104
+ (assignment) =>
105
+ `(${writeExpression(assignment.FIELD)} = ${writeExpression(assignment.VALUE)})`,
106
+ )
107
+ .join(' && ')})`;
108
+
109
+ // RULE_EXPRESSION and RESULT_EXPRESSION as GSF's inbound schema describes
110
+ // them (platform/criteria-model.json: EventMeta's schema of
111
+ // NotificationRuleInsert on genesis-criteria 8.15.29, its Expression tree in
112
+ // $defs). GSF's decoder checks them before the handler, VALIDATE too: an
113
+ // operation, method or value off the tree (a NUMBER's VALUE is a decimal
114
+ // string) is a VALIDATION_ERROR, with every oneOf branch's complaint.
115
+ const EXPRESSIONS_SCHEMA = {
116
+ properties: {
117
+ DETAILS: {
118
+ properties: {
119
+ RULE_EXPRESSION: criteriaModel.RULE_EXPRESSION,
120
+ RESULT_EXPRESSION: criteriaModel.RESULT_EXPRESSION,
121
+ },
122
+ },
123
+ },
124
+ $defs: criteriaModel.$defs,
125
+ };
126
+ function checkExpressions(details: Row): void {
127
+ const sent = Object.fromEntries(
128
+ ['RULE_EXPRESSION', 'RESULT_EXPRESSION']
129
+ .filter((name) => Object.hasOwn(details, name))
130
+ .map((name) => [name, details[name]]),
131
+ );
132
+ const errors = schemaFieldErrors(validateSchema(EXPRESSIONS_SCHEMA, { DETAILS: sent }));
133
+ if (errors.length > 0) throw new NackError(errors);
134
+ }
135
+
136
+ const field = (NAME: string) => ({ TYPE: 'FIELD', NAME });
137
+ const assign = (name: string, VALUE: Row) => ({ FIELD: field(name), VALUE });
138
+
139
+ // The model a rule was sent, kept by its DYNAMIC_RULE ID for the details
140
+ // request servers: RULE_EXPRESSION (or null, with the raw string),
141
+ // RESULT_EXPRESSION with the assignments the handler adds.
142
+ interface RuleModel {
143
+ rule: Row | null;
144
+ raw: string | null;
145
+ result: Row | null;
146
+ }
147
+
148
+ // --- schemas ---------------------------------------------------------------------
149
+
150
+ const MESSAGE_CLASS = 'global.genesis.notify.message.event';
151
+ const TABLE_OPERATIONS = ['INSERT', 'MODIFY', 'DELETE'];
152
+ // RuleExpression and ResultExpression hold a sealed Expression tree, which
153
+ // FieldDef can't describe: declared as objects, and checked against GSF's own
154
+ // schema of them before the handler (checkExpressions).
155
+ const RULE_FIELDS: FieldDef[] = [
156
+ dto('RULE_NAME', 'STRING'),
157
+ dto('RULE_DESCRIPTION', 'STRING', { optional: true }),
158
+ dto('RULE_TABLE', 'STRING'),
159
+ dto('RULE_EXPRESSION', 'MAP', nullable),
160
+ dto('RAW_RULE_EXPRESSION', 'STRING', nullable),
161
+ dto('RESULT_EXPRESSION', 'MAP'),
162
+ dto('TABLE_OPERATIONS', 'ARRAY', {
163
+ items: {
164
+ type: 'ENUM',
165
+ values: TABLE_OPERATIONS,
166
+ enumClass: 'global.genesis.db.updatequeue.UpdateType',
167
+ },
168
+ unique: true,
169
+ optional: true,
170
+ }),
171
+ dto('ALERT_SOUND_FILE_NAME', 'STRING', nullable),
172
+ dto('ALERT_SOUND_MIME_TYPE', 'STRING', nullable),
173
+ dto('ALERT_SOUND_DATA', 'STRING', nullable),
174
+ ];
175
+ // NotificationRuleTemplateParameters.
176
+ const TEMPLATE_PARAMETERS: FieldDef = dto('PARAMETER_DETAILS', 'MAP', {
177
+ items: {
178
+ type: 'OBJECT',
179
+ className: 'global.genesis.notify.message.event.NotificationRuleTemplateParameters',
180
+ nullable: false,
181
+ fields: [
182
+ dto('PARAM_SOURCE', 'STRING'),
183
+ dto('PARAM_SOURCE_TYPE', 'ENUM', {
184
+ values: ['USER_TEXT', 'DEFINED_GROUP', 'REQ_REP'],
185
+ enumClass: `${ENUMS}.ParamSourceType`,
186
+ }),
187
+ dto('PARAM_TYPE', 'ENUM', {
188
+ values: ['FIELD', 'STRING', 'BOOLEAN', 'NUMBER'],
189
+ enumClass: `${ENUMS}.ParamType`,
190
+ }),
191
+ dto('PARAM_LABEL', 'STRING'),
192
+ dto('PARAM_OPERATOR', 'STRING'),
193
+ ],
194
+ },
195
+ });
196
+ const RULE_ID = dto('DYNAMIC_RULE_ID', 'STRING');
197
+ const CLEAR_ALERT_SOUND = dto('CLEAR_ALERT_SOUND', 'BOOLEAN', { optional: true });
198
+ const BY_ID: EventSchemaOverride = {
199
+ table: 'DYNAMIC_RULE',
200
+ pkOnly: true,
201
+ className: 'global.genesis.gen.dao.DynamicRule.ById',
202
+ };
203
+
204
+ const SCHEMAS: Record<string, EventSchemaOverride> = {
205
+ EVENT_NOTIFICATION_RULE_TEMPLATE_CREATE: {
206
+ table: 'DYNAMIC_RULE_TEMPLATE_PARAMS',
207
+ className: `${MESSAGE_CLASS}.NotificationRuleTemplateInsert`,
208
+ fields: [...RULE_FIELDS, TEMPLATE_PARAMETERS],
209
+ },
210
+ EVENT_NOTIFICATION_RULE_TEMPLATE_UPDATE: {
211
+ table: 'DYNAMIC_RULE_TEMPLATE_PARAMS',
212
+ className: `${MESSAGE_CLASS}.NotificationRuleTemplateUpdate`,
213
+ fields: [RULE_ID, ...RULE_FIELDS, TEMPLATE_PARAMETERS, CLEAR_ALERT_SOUND],
214
+ },
215
+ EVENT_NOTIFICATION_RULE_TEMPLATE_DELETE: BY_ID,
216
+ EVENT_NOTIFICATION_RULE_CREATE: {
217
+ className: `${MESSAGE_CLASS}.NotificationRuleInsert`,
218
+ fields: RULE_FIELDS,
219
+ },
220
+ EVENT_NOTIFICATION_RULE_UPDATE: {
221
+ className: `${MESSAGE_CLASS}.NotificationRuleUpdate`,
222
+ fields: [RULE_ID, ...RULE_FIELDS, CLEAR_ALERT_SOUND],
223
+ },
224
+ EVENT_NOTIFICATION_RULE_DELETE: BY_ID,
225
+ EVENT_NOTIFICATION_RULE_SUBSCRIBE: {
226
+ className: `${MESSAGE_CLASS}.NotificationRuleSubscribe`,
227
+ fields: [RULE_ID, dto('PARAMETER_DETAILS', 'MAP', { items: { type: 'STRING' } })],
228
+ },
229
+ EVENT_NOTIFICATION_RULE_UNSUBSCRIBE: BY_ID,
230
+ EVENT_NOTIFICATION_RULE_DISABLE: BY_ID,
231
+ EVENT_NOTIFICATION_RULE_ENABLE: BY_ID,
232
+ };
233
+
234
+ // --- alert sounds (RULES-EH :23-117) ------------------------------------------------
235
+
236
+ // 1536 * 1024, and the base64 length that holds it: ((bytes + 2) / 3) * 4.
237
+ const MAX_ALERT_SOUND_BYTES = 1_572_864;
238
+ const MAX_ALERT_SOUND_BASE64_CHARS = 2_097_152;
239
+ // What java.util.Base64's decoder takes: whole 4-character units, the last of
240
+ // which may be 2 or 3 characters, padded or not.
241
+ const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}(?:==)?|[A-Za-z0-9+/]{3}=?)?$/;
242
+ const TOO_BIG = 'Alert sound exceeds maximum size of 1.5MB';
243
+ const isBlank = (value: unknown) =>
244
+ value === undefined || value === null || String(value).trim() === '';
245
+
246
+ // decodeAlertSoundData: the bytes, as canonical base64 (the RAW column's
247
+ // form here), or null for none.
248
+ function decodeAlertSound(data: unknown): string | null {
249
+ if (isBlank(data)) return null;
250
+ const text = String(data)
251
+ .replace(/^data:[^;,]*;base64,/, '')
252
+ .replace(/\s/g, '');
253
+ if (text.length > MAX_ALERT_SOUND_BASE64_CHARS) throw new NackError(TOO_BIG);
254
+ if (!BASE64.test(text)) {
255
+ throw new NackError('Alert sound data is not valid Base64');
256
+ }
257
+ const bytes = Buffer.from(text, 'base64');
258
+ if (bytes.length > MAX_ALERT_SOUND_BYTES) throw new NackError(TOO_BIG);
259
+ return bytes.toString('base64');
260
+ }
261
+
262
+ function validateAlertSound(details: Row): void {
263
+ if (isBlank(details.ALERT_SOUND_DATA)) return;
264
+ if (isBlank(details.ALERT_SOUND_MIME_TYPE)) {
265
+ throw new NackError('MIME type is required when an alert sound is provided');
266
+ }
267
+ if (isBlank(details.ALERT_SOUND_FILE_NAME)) {
268
+ throw new NackError('File name is required when an alert sound is provided');
269
+ }
270
+ decodeAlertSound(details.ALERT_SOUND_DATA);
271
+ }
272
+
273
+ function validateAlertSoundUpdate(details: Row): void {
274
+ if (details.CLEAR_ALERT_SOUND === true && !isBlank(details.ALERT_SOUND_DATA)) {
275
+ throw new NackError('clearAlertSound cannot be combined with alertSoundData');
276
+ }
277
+ validateAlertSound(details);
278
+ }
279
+
280
+ // --- the backing -------------------------------------------------------------------
281
+
282
+ const PARAMS = 'DYNAMIC_RULE_TEMPLATE_PARAMS';
283
+
284
+ // A template's params as GSF reads them, through the DYNAMIC_RULE_ID index:
285
+ // in primary-key order, so by PARAM_NAME.
286
+ const paramsOf = (store: EventHandlerCtx['store'], ruleId: string) =>
287
+ store
288
+ .getAllRows(PARAMS)
289
+ .filter((row) => row.DYNAMIC_RULE_ID === ruleId)
290
+ .sort((a, b) => (a.PARAM_NAME < b.PARAM_NAME ? -1 : a.PARAM_NAME > b.PARAM_NAME ? 1 : 0));
291
+
292
+ // The rules' and the templates' `where` / `filter`: IS_TEMPLATE is false
293
+ // unless set (its dictionary default).
294
+ const where = (template: boolean) => (row: Row) =>
295
+ (row.IS_TEMPLATE ?? false) === template && row.RULE_TYPE === 'NOTIFY';
296
+
297
+ export interface RuleBacking {
298
+ eventHandlers: Record<string, EventHandler>;
299
+ eventSchemas: Record<string, EventSchemaOverride>;
300
+ requestReplies: Record<string, RequestReplyDef>;
301
+ queries: Record<string, QueryDef>;
302
+ }
303
+
304
+ // The events whose DTO holds the expressions.
305
+ const WITH_EXPRESSIONS = new Set([
306
+ 'EVENT_NOTIFICATION_RULE_TEMPLATE_CREATE',
307
+ 'EVENT_NOTIFICATION_RULE_TEMPLATE_UPDATE',
308
+ 'EVENT_NOTIFICATION_RULE_CREATE',
309
+ 'EVENT_NOTIFICATION_RULE_UPDATE',
310
+ ]);
311
+
312
+ export function ruleBacking(users: NotifyUsers): RuleBacking {
313
+ // Each rule's model, per server, with the strings it was stored as: a rule
314
+ // whose strings have changed since, or one the mock didn't write, has none.
315
+ // Kept and dropped once the event commits.
316
+ const models = new WeakMap<Store, Map<string, { model: RuleModel; stored: unknown[] }>>();
317
+ const modelsOf = (store: Store) => {
318
+ let kept = models.get(store);
319
+ if (!kept) {
320
+ kept = new Map();
321
+ models.set(store, kept);
322
+ }
323
+ return kept;
324
+ };
325
+ const keep = (ctx: EventHandlerCtx, id: string, row: Row, model: RuleModel) =>
326
+ ctx.afterCommit(() =>
327
+ modelsOf(ctx.store).set(id, { model, stored: [row.RULE_EXPRESSION, row.RESULT_EXPRESSION] }),
328
+ );
329
+ const forget = (ctx: EventHandlerCtx, id: string) =>
330
+ ctx.afterCommit(() => modelsOf(ctx.store).delete(id));
331
+ const keptFor = (store: Store, row: Row): RuleModel | undefined => {
332
+ const kept = modelsOf(store).get(row.ID);
333
+ const [rule, result] = kept?.stored ?? [];
334
+ return rule === row.RULE_EXPRESSION && result === row.RESULT_EXPRESSION
335
+ ? kept?.model
336
+ : undefined;
337
+ };
338
+ const isAdmin = (store: Store, user: string) => users.hasRight(store, user, ADMIN_RIGHT);
339
+
340
+ // Writes a row and pushes it live.
341
+ function write(
342
+ ctx: EventHandlerCtx,
343
+ table: string,
344
+ op: 'INSERT' | 'MODIFY',
345
+ row: Row,
346
+ key?: string,
347
+ ) {
348
+ const { store } = ctx;
349
+ const written =
350
+ op === 'INSERT' ? store.insertRow(table, row) : store.updateRow(table, key!, row)!;
351
+ ctx.broadcastTableChange(table, op, store.rowKey(table, written));
352
+ return written;
353
+ }
354
+ function remove(ctx: EventHandlerCtx, table: string, key: string) {
355
+ if (ctx.store.deleteRow(table, key)) ctx.broadcastTableChange(table, 'DELETE', key);
356
+ }
357
+ const rowsWhere = (ctx: EventHandlerCtx, table: string, test: (row: Row) => boolean) =>
358
+ ctx.store.getAllRows(table).filter(test);
359
+
360
+ // The rule's own record, or the 2.2 checks' NACK: it must exist, and be
361
+ // the event user's or the user an admin.
362
+ function ownedRule(ctx: EventHandlerCtx, id: string, user: string, missing: string): Row {
363
+ const rule = ctx.store.getRow('DYNAMIC_RULE', id);
364
+ if (!rule) throw new NackError(missing);
365
+ if (rule.USER_NAME !== user && !isAdmin(ctx.store, user)) {
366
+ throw new NackError(`User ${user} lacks sufficient permissions`);
367
+ }
368
+ return rule;
369
+ }
370
+
371
+ // The result assignments a rule is stored with (RULES-EH :128-174): the sent
372
+ // ones, then TABLE_NAME, TABLE_ENTITY_ID (a table with a single-field key
373
+ // only; what GSF does for a view isn't known, so none) and SENDER.
374
+ function resultAssignments(ctx: EventHandlerCtx, details: Row, sender: Row): Row[] {
375
+ const table = String(details.RULE_TABLE);
376
+ const key = ctx.store.hasTable(table) ? ctx.store.getPkFields(table) : [];
377
+ return [
378
+ ...((details.RESULT_EXPRESSION?.ASSIGNMENTS as Row[] | undefined) ?? []),
379
+ assign('TABLE_NAME', { TYPE: 'STRING', VALUE: table }),
380
+ ...(key.length === 1 ? [assign('TABLE_ENTITY_ID', field(key[0]))] : []),
381
+ assign('SENDER', sender),
382
+ ];
383
+ }
384
+
385
+ // The DYNAMIC_RULE row 2.1 / 2.4 build, and the model it was built from.
386
+ function ruleRow(ctx: EventHandlerCtx, details: Row, user: string, template: boolean) {
387
+ const rule: Row | null = details.RULE_EXPRESSION ?? null;
388
+ const raw: string | null = rule ? null : (details.RAW_RULE_EXPRESSION ?? null);
389
+ // ruleExpressionString: the model written, else the raw string (both
390
+ // null is a NullPointerException).
391
+ if (!rule && raw === null) throw NackError.standard('INTERNAL_ERROR');
392
+ const sender = template
393
+ ? { TYPE: 'PLACEHOLDER', KEY: 'USER' }
394
+ : { TYPE: 'STRING', VALUE: user };
395
+ const assignments = resultAssignments(ctx, details, sender);
396
+ const operations = (details.TABLE_OPERATIONS as string[] | undefined) ?? ['INSERT'];
397
+ return {
398
+ row: {
399
+ USER_NAME: user,
400
+ NAME: details.RULE_NAME,
401
+ DESCRIPTION: details.RULE_DESCRIPTION ?? '',
402
+ RULE_TABLE: details.RULE_TABLE,
403
+ RULE_EXECUTION_STRATEGY: 'UNLIMITED',
404
+ RULE_EXPRESSION: rule ? writeRule(rule) : raw,
405
+ RESULT_EXPRESSION: writeResult(assignments),
406
+ RULE_STATUS: 'ENABLED',
407
+ MESSAGE_TYPE: 'EVENT_NOTIFY_INSERT',
408
+ IS_TEMPLATE: template,
409
+ RULE_TYPE: 'NOTIFY',
410
+ TABLE_OPERATION: [...new Set(operations)].join('|'),
411
+ PROCESS_NAME: null,
412
+ },
413
+ model: { rule, raw, result: { ASSIGNMENTS: assignments } },
414
+ };
415
+ }
416
+
417
+ // upsertAlertSound (:77-103): one sound per rule, kept by its id.
418
+ function upsertSound(ctx: EventHandlerCtx, ruleId: string, details: Row, data: string) {
419
+ const existing = rowsWhere(
420
+ ctx,
421
+ 'NOTIFY_ALERT_SOUND',
422
+ (row) => row.DYNAMIC_RULE_ID === ruleId,
423
+ )[0];
424
+ const row = {
425
+ DYNAMIC_RULE_ID: ruleId,
426
+ ALERT_SOUND_FILE_NAME: details.ALERT_SOUND_FILE_NAME,
427
+ ALERT_SOUND_MIME_TYPE: details.ALERT_SOUND_MIME_TYPE,
428
+ ALERT_SOUND_DATA: data,
429
+ };
430
+ if (existing) write(ctx, 'NOTIFY_ALERT_SOUND', 'MODIFY', row, existing.ALERT_SOUND_ID);
431
+ else write(ctx, 'NOTIFY_ALERT_SOUND', 'INSERT', row);
432
+ }
433
+ function deleteSound(ctx: EventHandlerCtx, ruleId: string) {
434
+ for (const row of rowsWhere(
435
+ ctx,
436
+ 'NOTIFY_ALERT_SOUND',
437
+ (each) => each.DYNAMIC_RULE_ID === ruleId,
438
+ )) {
439
+ remove(ctx, 'NOTIFY_ALERT_SOUND', row.ALERT_SOUND_ID);
440
+ }
441
+ }
442
+ const soundOf = (ctx: EventHandlerCtx, ruleId: string) =>
443
+ rowsWhere(ctx, 'NOTIFY_ALERT_SOUND', (row) => row.DYNAMIC_RULE_ID === ruleId)[0];
444
+
445
+ const reservedUser = (details: Row) => {
446
+ if (Object.hasOwn(details.PARAMETER_DETAILS ?? {}, 'USER')) {
447
+ throw new NackError(
448
+ 'USER is a reserved keyword for rule creation, please choose another key for your parameter',
449
+ );
450
+ }
451
+ };
452
+
453
+ // The template's parameters as DYNAMIC_RULE_TEMPLATE_PARAMS rows.
454
+ const paramRows = (ruleId: string, details: Row): Row[] =>
455
+ Object.entries((details.PARAMETER_DETAILS ?? {}) as Record<string, Row>).map(
456
+ ([name, param]) => ({
457
+ DYNAMIC_RULE_ID: ruleId,
458
+ PARAM_NAME: name,
459
+ PARAM_SOURCE: param.PARAM_SOURCE,
460
+ PARAM_SOURCE_TYPE: param.PARAM_SOURCE_TYPE,
461
+ PARAM_TYPE: param.PARAM_TYPE,
462
+ PARAM_LABEL: param.PARAM_LABEL,
463
+ PARAM_OPERATOR: param.PARAM_OPERATOR,
464
+ }),
465
+ );
466
+
467
+ // DELETE, UNSUBSCRIBE (:510-531, :583-603): the sound, the template link,
468
+ // the rule.
469
+ const deleteRule =
470
+ (missing: (id: string) => string): EventHandler =>
471
+ (details, ctx) => {
472
+ const user = users.userOf(ctx);
473
+ const id = details.ID;
474
+ ownedRule(ctx, id, user, missing(id));
475
+ if (ctx.validate) return {};
476
+ deleteSound(ctx, id);
477
+ remove(ctx, 'NOTIFY_RULE_TEMPLATE_LINK', id);
478
+ remove(ctx, 'DYNAMIC_RULE', id);
479
+ forget(ctx, id);
480
+ return {};
481
+ };
482
+
483
+ // DISABLE, ENABLE (:606-651).
484
+ const setStatus =
485
+ (status: string): EventHandler =>
486
+ (details, ctx) => {
487
+ const user = users.userOf(ctx);
488
+ const rule = ctx.store.getRow('DYNAMIC_RULE', details.ID);
489
+ if (rule?.USER_NAME !== user && !isAdmin(ctx.store, user)) {
490
+ throw new NackError(`User ${user} lacks sufficient permissions`);
491
+ }
492
+ if (ctx.validate) return {};
493
+ if (!rule) throw NackError.nack(`Cannot find Dynamic Rule for ID: ${details.ID}`);
494
+ write(ctx, 'DYNAMIC_RULE', 'MODIFY', { RULE_STATUS: status }, details.ID);
495
+ return {};
496
+ };
497
+
498
+ const notFound = (id: string) => `Dynamic Rule of ID ${id} doesn't exist!`;
499
+
500
+ const eventHandlers: Record<string, EventHandler> = {
501
+ // :177-246
502
+ EVENT_NOTIFICATION_RULE_TEMPLATE_CREATE: (details, ctx) => {
503
+ reservedUser(details);
504
+ validateAlertSound(details);
505
+ if (ctx.validate) return {};
506
+ const user = users.userOf(ctx);
507
+ const { row, model } = ruleRow(ctx, details, user, true);
508
+ const id = write(ctx, 'DYNAMIC_RULE', 'INSERT', row).ID;
509
+ for (const param of paramRows(id, details)) {
510
+ write(ctx, PARAMS, 'INSERT', param);
511
+ }
512
+ const sound = decodeAlertSound(details.ALERT_SOUND_DATA);
513
+ if (sound) upsertSound(ctx, id, details, sound);
514
+ keep(ctx, id, row, model);
515
+ return {};
516
+ },
517
+ // :249-356: the whole row rebuilt, the editor its owner; the sent params
518
+ // upserted and the others deleted; a sound change reaches every rule
519
+ // subscribed to the template.
520
+ EVENT_NOTIFICATION_RULE_TEMPLATE_UPDATE: (details, ctx) => {
521
+ const user = users.userOf(ctx);
522
+ const id = details.DYNAMIC_RULE_ID;
523
+ ownedRule(ctx, id, user, notFound(id));
524
+ reservedUser(details);
525
+ validateAlertSoundUpdate(details);
526
+ if (ctx.validate) return {};
527
+ const { row, model } = ruleRow(ctx, details, user, true);
528
+ write(ctx, 'DYNAMIC_RULE', 'MODIFY', row, id);
529
+ const sent = paramRows(id, details);
530
+ for (const old of paramsOf(ctx.store, id)) {
531
+ if (!sent.some((param) => param.PARAM_NAME === old.PARAM_NAME)) {
532
+ remove(ctx, PARAMS, ctx.store.rowKey(PARAMS, old));
533
+ }
534
+ }
535
+ for (const param of sent) {
536
+ const key = ctx.store.rowKey(PARAMS, param);
537
+ if (ctx.store.getRow(PARAMS, key)) write(ctx, PARAMS, 'MODIFY', param, key);
538
+ else write(ctx, PARAMS, 'INSERT', param);
539
+ }
540
+ const linked = rowsWhere(
541
+ ctx,
542
+ 'NOTIFY_RULE_TEMPLATE_LINK',
543
+ (link) => link.TEMPLATE_DYNAMIC_RULE_ID === id,
544
+ ).map((link) => link.DYNAMIC_RULE_ID as string);
545
+ if (details.CLEAR_ALERT_SOUND === true) {
546
+ for (const ruleId of [id, ...linked]) deleteSound(ctx, ruleId);
547
+ } else {
548
+ const sound = decodeAlertSound(details.ALERT_SOUND_DATA);
549
+ if (sound) for (const ruleId of [id, ...linked]) upsertSound(ctx, ruleId, details, sound);
550
+ }
551
+ keep(ctx, id, row, model);
552
+ return {};
553
+ },
554
+ // :359-383: the sound, the links (the subscribed rules stay), the
555
+ // template, its params.
556
+ EVENT_NOTIFICATION_RULE_TEMPLATE_DELETE: (details, ctx) => {
557
+ const user = users.userOf(ctx);
558
+ const id = details.ID;
559
+ ownedRule(ctx, id, user, notFound(id));
560
+ if (ctx.validate) return {};
561
+ deleteSound(ctx, id);
562
+ for (const link of rowsWhere(
563
+ ctx,
564
+ 'NOTIFY_RULE_TEMPLATE_LINK',
565
+ (each) => each.TEMPLATE_DYNAMIC_RULE_ID === id,
566
+ )) {
567
+ remove(ctx, 'NOTIFY_RULE_TEMPLATE_LINK', link.DYNAMIC_RULE_ID);
568
+ }
569
+ remove(ctx, 'DYNAMIC_RULE', id);
570
+ for (const param of paramsOf(ctx.store, id))
571
+ remove(ctx, PARAMS, ctx.store.rowKey(PARAMS, param));
572
+ forget(ctx, id);
573
+ return {};
574
+ },
575
+ // :386-439
576
+ EVENT_NOTIFICATION_RULE_CREATE: (details, ctx) => {
577
+ validateAlertSound(details);
578
+ if (ctx.validate) return {};
579
+ const user = users.userOf(ctx);
580
+ const { row, model } = ruleRow(ctx, details, user, false);
581
+ const id = write(ctx, 'DYNAMIC_RULE', 'INSERT', row).ID;
582
+ const sound = decodeAlertSound(details.ALERT_SOUND_DATA);
583
+ if (sound) upsertSound(ctx, id, details, sound);
584
+ keep(ctx, id, row, model);
585
+ return {};
586
+ },
587
+ // :442-507: rebuilt as a rule (IS_TEMPLATE false), the editor its owner.
588
+ EVENT_NOTIFICATION_RULE_UPDATE: (details, ctx) => {
589
+ const user = users.userOf(ctx);
590
+ const id = details.DYNAMIC_RULE_ID;
591
+ ownedRule(ctx, id, user, notFound(id));
592
+ validateAlertSoundUpdate(details);
593
+ if (ctx.validate) return {};
594
+ const { row, model } = ruleRow(ctx, details, user, false);
595
+ write(ctx, 'DYNAMIC_RULE', 'MODIFY', row, id);
596
+ if (details.CLEAR_ALERT_SOUND === true) deleteSound(ctx, id);
597
+ else {
598
+ const sound = decodeAlertSound(details.ALERT_SOUND_DATA);
599
+ if (sound) upsertSound(ctx, id, details, sound);
600
+ }
601
+ keep(ctx, id, row, model);
602
+ return {};
603
+ },
604
+ EVENT_NOTIFICATION_RULE_DELETE: deleteRule(notFound),
605
+ // :533-580: a rule from the template, its expressions' placeholders
606
+ // filled as Mustache fills them (DynamicRuleFactory.kt:50-96).
607
+ EVENT_NOTIFICATION_RULE_SUBSCRIBE: (details, ctx) => {
608
+ const id = details.DYNAMIC_RULE_ID;
609
+ const template = ctx.store.getRow('DYNAMIC_RULE', id);
610
+ if (!template) throw NackError.nack(`Unable to find dynamic rule template with id ${id}`);
611
+ const params = paramsOf(ctx.store, id);
612
+ const required = params.map((param) => param.PARAM_NAME as string);
613
+ const provided = Object.keys(details.PARAMETER_DETAILS ?? {});
614
+ if (required.includes('USER') || provided.includes('USER')) {
615
+ throw new NackError('USER is a reserved keyword and cannot be used as a parameter key');
616
+ }
617
+ if (
618
+ required.length !== provided.length ||
619
+ required.some((name) => !provided.includes(name))
620
+ ) {
621
+ throw new NackError(
622
+ `The required parameters ([${required.join(', ')}]) did not match the provided parameters ([${provided.join(', ')}]) for template ${id}`,
623
+ );
624
+ }
625
+ if (ctx.validate) return {};
626
+ const user = users.userOf(ctx);
627
+ // transformInputs: the sent values, a STRING parameter's quoted, and
628
+ // USER the quoted subscriber. Mustache HTML-escapes each value it puts
629
+ // in (mustache.java 0.9.14), an unknown key gives "" (GSF looks it up
630
+ // in the system definition first, which the mock doesn't model), and
631
+ // then every &quot; in the result goes back to ".
632
+ const values = new Map<string, string>(Object.entries(details.PARAMETER_DETAILS ?? {}));
633
+ values.set('USER', user);
634
+ const typeOf = (key: string) =>
635
+ key === 'USER' ? 'STRING' : params.find((param) => param.PARAM_NAME === key)?.PARAM_TYPE;
636
+ const shown = (key: string) => escapeHtml(values.get(key) ?? '').replace(/&quot;/g, '"');
637
+ const fill = (text: string | null) =>
638
+ (text ?? '')
639
+ .replace(/\{\{([^}]*)\}\}/g, (_match, tag: string) => {
640
+ const key = tag.trim();
641
+ if (!values.has(key)) return '';
642
+ return typeOf(key) === 'STRING' ? `"${shown(key)}"` : shown(key);
643
+ })
644
+ .replace(/&quot;/g, '"');
645
+ const created = write(ctx, 'DYNAMIC_RULE', 'INSERT', {
646
+ NAME: template.NAME,
647
+ DESCRIPTION: template.DESCRIPTION,
648
+ RULE_TABLE: template.RULE_TABLE,
649
+ RULE_STATUS: template.RULE_STATUS,
650
+ RULE_EXECUTION_STRATEGY: template.RULE_EXECUTION_STRATEGY,
651
+ PROCESS_NAME: template.PROCESS_NAME,
652
+ MESSAGE_TYPE: template.MESSAGE_TYPE,
653
+ TABLE_OPERATION: template.TABLE_OPERATION,
654
+ USER_NAME: user,
655
+ IS_TEMPLATE: false,
656
+ RULE_TYPE: 'NOTIFY',
657
+ RULE_EXPRESSION: fill(template.RULE_EXPRESSION),
658
+ RESULT_EXPRESSION: fill(template.RESULT_EXPRESSION),
659
+ });
660
+ write(ctx, 'NOTIFY_RULE_TEMPLATE_LINK', 'INSERT', {
661
+ DYNAMIC_RULE_ID: created.ID,
662
+ TEMPLATE_DYNAMIC_RULE_ID: id,
663
+ });
664
+ const sound = soundOf(ctx, id);
665
+ if (sound) upsertSound(ctx, created.ID, sound, sound.ALERT_SOUND_DATA);
666
+ // The instance's model: the template's, each placeholder the value the
667
+ // stored string got, as GSF would read it back.
668
+ const templateModel = keptFor(ctx.store, template);
669
+ if (templateModel) {
670
+ const placeholder = (key: string): Row => {
671
+ const value = shown(key);
672
+ switch (typeOf(key)) {
673
+ case 'STRING':
674
+ return { TYPE: 'STRING', VALUE: value };
675
+ // NumericValue's VALUE is a BigDecimal, a string on the wire.
676
+ case 'NUMBER':
677
+ return { TYPE: 'NUMBER', VALUE: value };
678
+ case 'BOOLEAN':
679
+ return { TYPE: 'BOOLEAN', VALUE: value === 'true' };
680
+ default:
681
+ return { TYPE: 'FIELD', NAME: value };
682
+ }
683
+ };
684
+ const filled = (expression: Row | null) => expression && fillModel(expression, placeholder);
685
+ keep(ctx, created.ID, created, {
686
+ rule: filled(templateModel.rule),
687
+ raw: templateModel.raw === null ? null : fill(templateModel.raw),
688
+ result: filled(templateModel.result),
689
+ });
690
+ }
691
+ return {};
692
+ },
693
+ EVENT_NOTIFICATION_RULE_UNSUBSCRIBE: deleteRule(
694
+ (id) => `No record found for Dynamic Rule ID: ${id}`,
695
+ ),
696
+ EVENT_NOTIFICATION_RULE_DISABLE: setStatus('DISABLED'),
697
+ EVENT_NOTIFICATION_RULE_ENABLE: setStatus('ENABLED'),
698
+ };
699
+
700
+ // NOTIFICATION_RULE_DETAILS (:101) and _TEMPLATE_DETAILS (:56): the rule
701
+ // as the dialog sent it. A rule the mock didn't write (a seeded one), or
702
+ // whose strings have changed since, answers its stored string as the raw
703
+ // expression, as GSF does for one too complex for the dialog's model, and
704
+ // no result expression.
705
+ const details = (template: boolean): RequestReplyDef => ({
706
+ requestFields: ['ID'],
707
+ resolver: ({ request, store }) => {
708
+ const rule = store.getRow('DYNAMIC_RULE', request.ID);
709
+ // A failed `require`: GENERIC_ERROR with its text; the request is a
710
+ // data class, so it prints as ById(id=…).
711
+ if (!rule)
712
+ throw new Error(`Could not find dynamic rule record for id: ById(id=${request.ID})`);
713
+ const model = keptFor(store, rule) ?? {
714
+ rule: null,
715
+ raw: rule.RULE_EXPRESSION ?? null,
716
+ result: null,
717
+ };
718
+ return [
719
+ {
720
+ DYNAMIC_RULE_ID: rule.ID,
721
+ RULE_NAME: rule.NAME,
722
+ RULE_DESCRIPTION: rule.DESCRIPTION ?? null,
723
+ RULE_TABLE: rule.RULE_TABLE ?? '',
724
+ RULE_EXECUTION_STRATEGY: rule.RULE_EXECUTION_STRATEGY,
725
+ RULE_EXPRESSION: model.rule,
726
+ RAW_RULE_EXPRESSION: model.raw,
727
+ RESULT_EXPRESSION: model.result,
728
+ ...(template
729
+ ? {
730
+ PARAMETERS: Object.fromEntries(
731
+ paramsOf(store, rule.ID).map((param) => [param.PARAM_NAME, param]),
732
+ ),
733
+ }
734
+ : {}),
735
+ TABLE_OPERATIONS: tableOperations(rule),
736
+ },
737
+ ];
738
+ },
739
+ metadataRows: [
740
+ {
741
+ DYNAMIC_RULE_ID: '',
742
+ RULE_NAME: '',
743
+ RULE_DESCRIPTION: '',
744
+ RULE_TABLE: '',
745
+ RULE_EXECUTION_STRATEGY: 'UNLIMITED',
746
+ },
747
+ ],
748
+ });
749
+
750
+ // NOTIFY_ALERT_SOUND (:172-203): the rule's sound, to whoever may hear it.
751
+ const alertSound: RequestReplyDef = {
752
+ requestFields: ['DYNAMIC_RULE_ID'],
753
+ resolver: ({ request, store, user }) => {
754
+ const sound = store
755
+ .getAllRows('NOTIFY_ALERT_SOUND')
756
+ .find((row) => row.DYNAMIC_RULE_ID === request.DYNAMIC_RULE_ID);
757
+ const rule = sound && store.getRow('DYNAMIC_RULE', sound.DYNAMIC_RULE_ID);
758
+ if (!sound || !rule || !mayHear(store, rule, user)) return [];
759
+ return [
760
+ {
761
+ ALERT_SOUND_ID: sound.ALERT_SOUND_ID,
762
+ DYNAMIC_RULE_ID: sound.DYNAMIC_RULE_ID,
763
+ ALERT_SOUND_FILE_NAME: sound.ALERT_SOUND_FILE_NAME,
764
+ ALERT_SOUND_MIME_TYPE: sound.ALERT_SOUND_MIME_TYPE,
765
+ SOUND_DATA: sound.ALERT_SOUND_DATA,
766
+ },
767
+ ];
768
+ },
769
+ metadataRows: [
770
+ {
771
+ ALERT_SOUND_ID: '',
772
+ DYNAMIC_RULE_ID: '',
773
+ ALERT_SOUND_FILE_NAME: '',
774
+ ALERT_SOUND_MIME_TYPE: '',
775
+ SOUND_DATA: '',
776
+ },
777
+ ],
778
+ };
779
+ const mayHear = (store: Store, rule: Row, requester: RequestingUser) => {
780
+ const name = requester.userName ?? users.fallback;
781
+ return (
782
+ rule.IS_TEMPLATE === true ||
783
+ rule.USER_NAME === name ||
784
+ users.hasRight(store, name, ADMIN_RIGHT) ||
785
+ rule.USER_NAME === 'SYSTEM' ||
786
+ users.hasRight(store, rule.USER_NAME, ON_BEHALF_RIGHT)
787
+ );
788
+ };
789
+
790
+ return {
791
+ eventHandlers: Object.fromEntries(
792
+ Object.entries(eventHandlers).map(([name, handler]): [string, EventHandler] => [
793
+ name,
794
+ WITH_EXPRESSIONS.has(name)
795
+ ? (details, ctx) => {
796
+ checkExpressions(details);
797
+ return handler(details, ctx);
798
+ }
799
+ : handler,
800
+ ]),
801
+ ),
802
+ eventSchemas: SCHEMAS,
803
+ requestReplies: {
804
+ NOTIFICATION_RULE_DETAILS: details(false),
805
+ NOTIFICATION_RULE_TEMPLATE_DETAILS: details(true),
806
+ NOTIFY_ALERT_SOUND: alertSound,
807
+ // The `filter` and the user filter the generated backing leaves out.
808
+ NOTIFICATION_RULE: {
809
+ source: 'DYNAMIC_RULE_VIEW',
810
+ requestFields: ['ID'],
811
+ filter: where(false),
812
+ auth: { rowFilter: (row, user) => row.USER_NAME === (user.userName ?? users.fallback) },
813
+ },
814
+ NOTIFICATION_RULE_TEMPLATE: {
815
+ source: 'DYNAMIC_RULE_VIEW',
816
+ requestFields: ['ID'],
817
+ filter: where(true),
818
+ },
819
+ },
820
+ queries: {
821
+ ALL_DYNAMIC_NOTIFY_RULES: { source: 'DYNAMIC_RULE', filter: where(false) },
822
+ ALL_RULE_TEMPLATES: { source: 'DYNAMIC_RULE', filter: where(true) },
823
+ },
824
+ };
825
+ }
826
+
827
+ // RULES-RR :80/:121: TABLE_OPERATION split on '|', each UpdateType.valueOf,
828
+ // whose failure (an empty or unknown one) fails the request.
829
+ function tableOperations(rule: Row): string[] {
830
+ return String(rule.TABLE_OPERATION ?? '')
831
+ .split('|')
832
+ .map((name) => {
833
+ if (!TABLE_OPERATIONS.includes(name)) {
834
+ throw new Error(`No enum constant global.genesis.db.updatequeue.UpdateType.${name}`);
835
+ }
836
+ return name;
837
+ });
838
+ }
839
+
840
+ // Mustache.java's HTML escaping of a value.
841
+ function escapeHtml(text: string): string {
842
+ return (
843
+ text
844
+ .replace(/&/g, '&amp;')
845
+ .replace(/</g, '&lt;')
846
+ .replace(/>/g, '&gt;')
847
+ .replace(/"/g, '&quot;')
848
+ .replace(/'/g, '&#39;')
849
+ .replace(/`/g, '&#96;')
850
+ .replace(/=/g, '&#61;')
851
+ // HtmlEscaper (compiler 0.9.14) writes characters 0-13 as references.
852
+ // eslint-disable-next-line no-control-regex
853
+ .replace(/[\u0000-\u000d]/g, (char) => `&#${char.charCodeAt(0)};`)
854
+ );
855
+ }
856
+
857
+ // A model with each PLACEHOLDER replaced.
858
+ function fillModel(expression: unknown, placeholder: (key: string) => Row): Row {
859
+ if (Array.isArray(expression)) return expression.map((item) => fillModel(item, placeholder));
860
+ if (typeof expression !== 'object' || expression === null) return expression as Row;
861
+ const node = expression as Row;
862
+ if (node.TYPE === 'PLACEHOLDER') return placeholder(String(node.KEY));
863
+ return Object.fromEntries(
864
+ Object.entries(node).map(([key, value]) => [key, fillModel(value, placeholder)]),
865
+ );
866
+ }