@genesislcap/mock-server 15.74.0 → 15.75.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
@@ -88,6 +88,10 @@ export class Connection {
88
88
  // The sessionAuthToken cookie the socket was opened with, under
89
89
  // auth.cookieAuthentication; it authenticates every message (router.ts).
90
90
  cookieSessionAuthToken: string | undefined;
91
+ // The upgrade request's HOSTNAME header and the client's address, which
92
+ // GSF's router gives a login as DETAILS.HOSTNAME (auth.ts routerHostname).
93
+ hostnameHeader: string | undefined;
94
+ remoteAddress: string | undefined;
91
95
  // A verbose HEARTBEAT_PONG's CREATED_AT, LAST_RECEIVED and LAST_SENT, as
92
96
  // genesis-router's ClientHandler keeps them (ClientHandler.kt:66-68,
93
97
  // 100-113 @v8.15.29): 0 until a message other than a heartbeat goes either
@@ -0,0 +1,310 @@
1
+ // DTO fields that hold more than one value: a Kotlin List or Set (ARRAY), a
2
+ // Map (MAP), a nested class (OBJECT) or Any (ANY), as GSF 8.15.29 describes
3
+ // and checks them (genesis-process metadata/pal: PALMetadataUtils.kt
4
+ // mapPropertyType, common/MetaFieldType.kt, jsonschema/JsonSchema.kt):
5
+ // - META: the type sits in the field's FIELD entry (MetaField's
6
+ // @JsonUnwrapped type), an ARRAY's items and a MAP's values as VALUE_TYPE,
7
+ // a nested class as a REFERENCE to its DEFINITIONS entry, keyed by its
8
+ // class name;
9
+ // - JSON schema: a DETAILS property through toJsonSchemaType, a nested
10
+ // class in $defs through mapJsonSchemaProperty, which orders keys
11
+ // differently, puts null first in a nullable's oneOf and puts an array's
12
+ // uniqueItems inside its items.
13
+ // A DESCRIPTION / description is the property's class: kotlin.collections.Set
14
+ // / List / Map, kotlin.Any, or the nested class's name.
15
+
16
+ import type { FieldDef, FieldTypeDef, Row } from '../types.ts';
17
+ import { eventMetaTypeOf, jsonTypeOf, jvmClassOf } from './fieldTypes.ts';
18
+
19
+ export const isNestedType = (type: string) =>
20
+ type === 'ARRAY' || type === 'MAP' || type === 'OBJECT' || type === 'ANY';
21
+
22
+ // A type as declared (FieldTypeDef) or resolved (schema.ts ResolvedField).
23
+ export interface TypeShape {
24
+ type: string;
25
+ nullable?: boolean;
26
+ values?: string[];
27
+ maxSize?: number;
28
+ minLength?: number;
29
+ description?: string;
30
+ items?: FieldTypeDef;
31
+ unique?: boolean;
32
+ className?: string;
33
+ fields?: FieldDef[];
34
+ enumClass?: string;
35
+ }
36
+
37
+ const ANY: TypeShape = { type: 'ANY' };
38
+
39
+ // A nested class: its name and its fields.
40
+ export interface NestedClass {
41
+ className: string;
42
+ fields: FieldDef[];
43
+ }
44
+
45
+ // The class a nested field's DESCRIPTION names.
46
+ export function nestedClassOf(def: TypeShape): string {
47
+ if (def.type === 'ARRAY')
48
+ return def.unique ? 'kotlin.collections.Set' : 'kotlin.collections.List';
49
+ if (def.type === 'MAP') return 'kotlin.collections.Map';
50
+ if (def.type === 'OBJECT') return def.className ?? 'kotlin.Any';
51
+ return 'kotlin.Any';
52
+ }
53
+
54
+ // Every nested class the fields reach, the first time each is met, as GSF
55
+ // adds them to the definitions while it walks the class (depth first).
56
+ export function nestedClasses(defs: TypeShape[], found = new Map<string, NestedClass>()) {
57
+ for (const def of defs) {
58
+ if (def.type === 'OBJECT' && def.className && !found.has(def.className)) {
59
+ found.set(def.className, { className: def.className, fields: def.fields ?? [] });
60
+ nestedClasses(def.fields ?? [], found);
61
+ }
62
+ if (def.items) nestedClasses([def.items], found);
63
+ }
64
+ return found;
65
+ }
66
+
67
+ const simpleName = (className: string) => className.slice(className.lastIndexOf('.') + 1);
68
+
69
+ // 'NotifyRoute' -> 'NOTIFY_ROUTE' (toUpperUnderscoreWithAcronyms).
70
+ export function upperUnderscore(name: string): string {
71
+ return name
72
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
73
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
74
+ .toUpperCase();
75
+ }
76
+
77
+ // --- META ----------------------------------------------------------------------
78
+
79
+ // A type as META writes it unwrapped: NULLABLE, the type's own fields, TYPE
80
+ // and JSON_TYPE. Any is always nullable.
81
+ export function metaType(def: TypeShape): Row {
82
+ const NULLABLE = def.type === 'ANY' ? true : (def.nullable ?? false);
83
+ switch (def.type) {
84
+ case 'ARRAY':
85
+ return {
86
+ NULLABLE,
87
+ VALUE_TYPE: metaType(def.items ?? ANY),
88
+ UNIQUE: def.unique ?? false,
89
+ TYPE: 'ARRAY',
90
+ JSON_TYPE: 'array',
91
+ };
92
+ case 'MAP':
93
+ return {
94
+ NULLABLE,
95
+ KEY_TYPE: { NULLABLE: false, TYPE: 'STRING', JSON_TYPE: 'string' },
96
+ VALUE_TYPE: metaType(def.items ?? ANY),
97
+ TYPE: 'MAP',
98
+ JSON_TYPE: 'object',
99
+ };
100
+ case 'OBJECT':
101
+ if (!def.className) return metaType(ANY);
102
+ return { NULLABLE, REFERENCE: def.className, TYPE: 'OBJECT', JSON_TYPE: 'object' };
103
+ // MetaFieldType.AnyType, an object with no constructor: Jackson writes its
104
+ // properties in declaration order, its null default included (as a
105
+ // recorded SYSTEM_ENTITY_FIELDS META shows).
106
+ case 'ANY':
107
+ return { TYPE: 'ANY', JSON_TYPE: jsonTypeOf('ANY'), NULLABLE, DEFAULT_VALUE: null };
108
+ case 'ENUM':
109
+ return {
110
+ NULLABLE,
111
+ ...(def.values?.length ? { VALID_VALUES: def.values, DEFAULT_VALUE: def.values[0] } : {}),
112
+ ENUM_CLASS: def.enumClass ?? 'kotlin.Enum',
113
+ TYPE: 'ENUM',
114
+ JSON_TYPE: 'string',
115
+ };
116
+ default:
117
+ return { NULLABLE, TYPE: eventMetaTypeOf(def.type), JSON_TYPE: jsonTypeOf(def.type) };
118
+ }
119
+ }
120
+
121
+ // DEFINITIONS: each nested class as {NAME, DESCRIPTION, PROPERTIES}, its
122
+ // properties written as the event's own FIELD entries are.
123
+ export function metaDefinitions(
124
+ classes: Map<string, NestedClass>,
125
+ properties: (nested: NestedClass) => Row[],
126
+ ): Row {
127
+ return Object.fromEntries(
128
+ [...classes.values()].map((nested) => [
129
+ nested.className,
130
+ {
131
+ NAME: upperUnderscore(simpleName(nested.className)),
132
+ DESCRIPTION: nested.className,
133
+ PROPERTIES: properties(nested),
134
+ },
135
+ ]),
136
+ );
137
+ }
138
+
139
+ // --- JSON schema: DETAILS properties (toJsonSchemaType) -----------------------
140
+
141
+ const ref = (className: string) => ({ $ref: `#/$defs/${className}` });
142
+ const orNull = (schema: Row, nullable: boolean | undefined) =>
143
+ nullable ? { oneOf: [schema, { type: 'null' }] } : schema;
144
+
145
+ // The bare type: an array's items or a map's values, with no annotations.
146
+ function itemSchema(def: TypeShape): Row {
147
+ switch (def.type) {
148
+ case 'ARRAY':
149
+ return orNull(
150
+ { items: itemSchema(def.items ?? ANY), uniqueItems: def.unique ?? false, type: 'array' },
151
+ def.nullable,
152
+ );
153
+ case 'MAP':
154
+ return orNull({ additionalProperties: true, type: 'object' }, def.nullable);
155
+ case 'OBJECT':
156
+ return def.className ? orNull(ref(def.className), def.nullable) : itemSchema(ANY);
157
+ case 'ANY':
158
+ return anySchema({});
159
+ case 'ENUM':
160
+ return orNull(
161
+ { ...(def.values?.length ? { enum: def.values } : {}), type: 'string' },
162
+ def.nullable,
163
+ );
164
+ case 'BIGDECIMAL':
165
+ return orNull({ pattern: '[0-9]+(\\.[0-9]+)?', type: 'string' }, def.nullable);
166
+ default:
167
+ return orNull({ type: jsonTypeOf(def.type) }, def.nullable);
168
+ }
169
+ }
170
+
171
+ // Any: an object, string, number or boolean, and null.
172
+ function anySchema(annotations: Row): Row {
173
+ return {
174
+ oneOf: [
175
+ {
176
+ oneOf: ['object', 'string', 'number', 'boolean'].map((type) => ({ ...annotations, type })),
177
+ },
178
+ { type: 'null' },
179
+ ],
180
+ };
181
+ }
182
+
183
+ // A DETAILS property whose type is nested.
184
+ export function nestedProperty(def: TypeShape): Row {
185
+ const description = nestedClassOf(def);
186
+ switch (def.type) {
187
+ case 'ARRAY':
188
+ return orNull(
189
+ {
190
+ items: itemSchema(def.items ?? ANY),
191
+ uniqueItems: def.unique ?? false,
192
+ readOnly: false,
193
+ description,
194
+ type: 'array',
195
+ },
196
+ def.nullable,
197
+ );
198
+ case 'MAP':
199
+ return orNull({ additionalProperties: true, type: 'object' }, def.nullable);
200
+ case 'OBJECT':
201
+ return def.className ? orNull(ref(def.className), def.nullable) : nestedProperty(ANY);
202
+ default:
203
+ return anySchema({ readOnly: false, description });
204
+ }
205
+ }
206
+
207
+ // --- decoding ----------------------------------------------------------------------
208
+
209
+ const isRecord = (value: unknown): value is Row =>
210
+ typeof value === 'object' && value !== null && !Array.isArray(value);
211
+
212
+ // A nested value as Jackson decodes it into its class: the keys a nested
213
+ // class doesn't declare dropped (GSF's mapper doesn't fail on unknown
214
+ // properties, GenesisJacksonMapper.kt:260 @v8.15.29), in its lists and maps
215
+ // too. The value itself when nothing is dropped.
216
+ export function decodedValue(def: TypeShape, value: unknown): unknown {
217
+ if (def.type === 'OBJECT' && def.className && isRecord(value)) {
218
+ const fields = new Map((def.fields ?? []).map((field) => [field.name, field]));
219
+ let changed = false;
220
+ const decoded: Row = {};
221
+ for (const [key, item] of Object.entries(value)) {
222
+ const field = fields.get(key);
223
+ if (!field) {
224
+ changed = true;
225
+ continue;
226
+ }
227
+ decoded[key] = decodedValue(field, item);
228
+ changed ||= decoded[key] !== item;
229
+ }
230
+ return changed ? decoded : value;
231
+ }
232
+ const items = def.items;
233
+ if (def.type === 'ARRAY' && items && Array.isArray(value)) {
234
+ const decoded = value.map((item) => decodedValue(items, item));
235
+ return decoded.some((item, index) => item !== value[index]) ? decoded : value;
236
+ }
237
+ if (def.type === 'MAP' && items && isRecord(value)) {
238
+ const decoded = Object.fromEntries(
239
+ Object.entries(value).map(([key, item]) => [key, decodedValue(items, item)]),
240
+ );
241
+ return Object.keys(value).some((key) => decoded[key] !== value[key]) ? decoded : value;
242
+ }
243
+ return value;
244
+ }
245
+
246
+ // --- JSON schema: $defs (mapJsonSchemaProperty) --------------------------------
247
+
248
+ function defsType(def: TypeShape, nullable: boolean): Row {
249
+ if (nullable) return { oneOf: [{ type: 'null' }, defsType(def, false)] };
250
+ const type = def.type;
251
+ const schema: Row = { type: jsonTypeOf(type) };
252
+ if (type === 'STRING') {
253
+ if (def.maxSize !== undefined) schema.maxLength = def.maxSize;
254
+ if (def.minLength !== undefined) schema.minLength = def.minLength;
255
+ }
256
+ if (type === 'OBJECT') {
257
+ if (def.className) schema.$ref = `#/$defs/${def.className}`;
258
+ else schema.additionalProperties = true;
259
+ }
260
+ if (type === 'MAP' && def.items && def.items.type !== 'ANY') {
261
+ schema.additionalProperties = defsType(def.items, typeNullable(def.items));
262
+ }
263
+ if (type === 'ENUM' && def.values?.length) schema.enum = def.values;
264
+ if (type === 'ARRAY') {
265
+ const items = def.items ?? ANY;
266
+ schema.items = {
267
+ ...defsType(items, typeNullable(items)),
268
+ ...(def.unique ? { uniqueItems: true } : {}),
269
+ };
270
+ }
271
+ return schema;
272
+ }
273
+
274
+ const typeNullable = (def: TypeShape) => (def.type === 'ANY' ? true : (def.nullable ?? false));
275
+
276
+ // $defs: each nested class as an object schema of its properties, closed to
277
+ // any other (no class here carries @AdditionalProperties), requiring the
278
+ // ones that aren't optional.
279
+ export function jsonDefs(
280
+ classes: Map<string, NestedClass>,
281
+ resolve: (nested: NestedClass) => Array<TypeShape & { name: string; optional?: boolean }>,
282
+ ): Row {
283
+ return Object.fromEntries(
284
+ [...classes.values()].map((nested) => {
285
+ const properties = resolve(nested);
286
+ const required = properties.filter((field) => !field.optional).map((field) => field.name);
287
+ return [
288
+ nested.className,
289
+ {
290
+ type: 'object',
291
+ description: nested.className,
292
+ properties: Object.fromEntries(
293
+ properties.map((field) => [
294
+ field.name,
295
+ {
296
+ ...defsType(field, typeNullable(field)),
297
+ description: isNestedType(field.type)
298
+ ? nestedClassOf(field)
299
+ : (field.description ??
300
+ jvmClassOf(field.type, () => field.enumClass ?? 'kotlin.Enum')),
301
+ },
302
+ ]),
303
+ ),
304
+ additionalProperties: false,
305
+ ...(required.length > 0 ? { required } : {}),
306
+ },
307
+ ];
308
+ }),
309
+ );
310
+ }
@@ -141,7 +141,14 @@ export function defaultTextFor(code: string): string | undefined {
141
141
  return knownCode(code)?.[0];
142
142
  }
143
143
 
144
- export type GenesisErrorType = 'StandardError' | 'FieldError' | 'TableStandardError' | 'LoginError';
144
+ // PasswordValidationError: auth's password checks (PasswordService), which a
145
+ // change of password NACKs with as they are.
146
+ export type GenesisErrorType =
147
+ | 'StandardError'
148
+ | 'FieldError'
149
+ | 'TableStandardError'
150
+ | 'LoginError'
151
+ | 'PasswordValidationError';
145
152
 
146
153
  // What a handler throws (inside a NackError) or returns as a warning. Keys
147
154
  // are accepted in either case. Without '@type', the class is inferred: TABLE
@@ -249,6 +256,9 @@ export interface NackErrorOptions {
249
256
  // event, IGNORE_WARNINGS or not: return warnings from the handler instead
250
257
  // ({ warnings }) for ones that should give way to it.
251
258
  warnings?: NackErrorInput | NackErrorInput[];
259
+ // The NACK's MESSAGE_TYPE when it isn't EVENT_NACK: a typed handler's own
260
+ // (auth's CREATE_MFA_SECRET_NACK).
261
+ messageType?: string;
252
262
  }
253
263
 
254
264
  // Throw this from an event handler or request-reply resolver for a
@@ -263,6 +273,7 @@ export class NackError extends Error {
263
273
  readonly warnings: NackErrorEntry[];
264
274
  readonly inputs: readonly NackErrorInput[];
265
275
  readonly warningInputs: readonly NackErrorInput[];
276
+ readonly messageType: string | undefined;
266
277
 
267
278
  constructor(errors: string | NackErrorInput | NackErrorInput[], options: NackErrorOptions = {}) {
268
279
  const inputs = asList(errors);
@@ -275,6 +286,7 @@ export class NackError extends Error {
275
286
  this.warningInputs = warningInputs;
276
287
  this.errors = entries;
277
288
  this.warnings = warnings;
289
+ this.messageType = options.messageType;
278
290
  }
279
291
 
280
292
  // A FieldError: VALIDATION_ERROR (400) naming the field. PATH is the JSON
@@ -20,6 +20,11 @@ const JSON_TYPES: Record<string, string> = {
20
20
  DATETIME: 'integer',
21
21
  NANO_TIMESTAMP: 'integer',
22
22
  RAW: 'string',
23
+ // A DTO's nested types (dtoTypes.ts): GSF's MetaFieldType jsonType.
24
+ ARRAY: 'array',
25
+ MAP: 'object',
26
+ OBJECT: 'object',
27
+ ANY: '{}',
23
28
  };
24
29
 
25
30
  // The JVM class of the generated DAO property, which the real server puts in
@@ -71,7 +71,7 @@ function ensureAuthenticated(
71
71
  // Error reply for unauthenticated traffic, shaped per message family the same
72
72
  // way each handler's own error paths are (REP_* for REQ_*, *_NACK for events,
73
73
  // QUERY_UPDATE for DATA_LOGON, echoed MESSAGE_TYPE for META/JSON_SCHEMA).
74
- function replyNotLoggedOn(message: GenesisMessage, connection: Connection): void {
74
+ export function replyNotLoggedOn(message: GenesisMessage, connection: Connection): void {
75
75
  const type = message.MESSAGE_TYPE;
76
76
  const ERROR = [{ CODE: ERROR_CODE.NOT_LOGGED_ON, TEXT: 'Not logged on' }];
77
77
  if (isRequestReply(type)) {
@@ -137,9 +137,9 @@ export function routeMessage(
137
137
 
138
138
  switch (message.MESSAGE_TYPE) {
139
139
  case MESSAGE_TYPE.EVENT_LOGIN_AUTH:
140
- return handleLogin(message, connection, config, auth);
140
+ return handleLogin(message, connection, config, auth, store, ctx.broadcastTableChange);
141
141
  case MESSAGE_TYPE.EVENT_LOGOUT:
142
- return handleLogout(message, connection, config, auth);
142
+ return handleLogout(message, connection, config, auth, store, ctx.broadcastTableChange);
143
143
  case MESSAGE_TYPE.HEARTBEAT_PING:
144
144
  return handleHeartbeat(message, connection, config, auth);
145
145
  case MESSAGE_TYPE.DATA_LOGON:
@@ -6,7 +6,9 @@
6
6
  // GenesisJsonSchemaFactory (draft 2019-09, PathType.LEGACY,
7
7
  // losslessNarrowing). This is the subset of that validator the engine's own
8
8
  // event schemas need: type, const, enum, oneOf, properties, required,
9
- // additionalProperties, minLength / maxLength, minimum / maximum and pattern.
9
+ // additionalProperties, minLength / maxLength, minimum / maximum, pattern, and
10
+ // for a DTO's lists, sets and nested classes items, uniqueItems and $ref (into
11
+ // the schema's own $defs).
10
12
  // Texts, locations and their order follow networknt's output, checked by
11
13
  // running the real validator on the recorded showcase schemas
12
14
  // (test/schemaValidation.test.ts pins the cases).
@@ -63,6 +65,20 @@ function deepEqual(a: unknown, b: unknown): boolean {
63
65
  return false;
64
66
  }
65
67
 
68
+ // A JSON value written with its object keys sorted: the same text for two
69
+ // values deepEqual calls equal, so a long array's repeats are found in one
70
+ // pass.
71
+ function canonical(value: unknown): string {
72
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
73
+ if (isObject(value)) {
74
+ const entries = Object.keys(value)
75
+ .sort()
76
+ .map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`);
77
+ return `{${entries.join(',')}}`;
78
+ }
79
+ return JSON.stringify(value) ?? 'undefined';
80
+ }
81
+
66
82
  // networknt evaluates these before a schema's other keywords, whatever their
67
83
  // position; the rest go in key order.
68
84
  const FIRST_KEYWORDS = ['type', 'properties'];
@@ -73,12 +89,16 @@ const codePoints = (text: string) => [...text].length;
73
89
  interface KeywordCheck {
74
90
  arg: any;
75
91
  schema: Schema;
92
+ // The schema validation started from, which $ref points into.
93
+ root: Schema;
76
94
  value: unknown;
77
95
  location: string;
78
96
  errors: SchemaError[];
79
97
  fail(message: string, property?: string): void;
80
98
  }
81
99
 
100
+ const DEFS = '#/$defs/';
101
+
82
102
  const NOT_DEFINED =
83
103
  'is not defined in the schema and the schema does not allow additional properties';
84
104
 
@@ -121,9 +141,9 @@ const KEYWORDS: Record<string, (check: KeywordCheck) => void> = {
121
141
  fail(`does not match the regex pattern ${arg}`);
122
142
  }
123
143
  },
124
- oneOf({ arg, value, location, errors, fail }) {
144
+ oneOf({ arg, root, value, location, errors, fail }) {
125
145
  if (!Array.isArray(arg)) return;
126
- const results = arg.map((branch: Schema) => validateSchema(branch, value, location));
146
+ const results = arg.map((branch: Schema) => validateSchema(branch, value, location, root));
127
147
  const valid = results.flatMap((result, index) => (result.length === 0 ? [index] : []));
128
148
  if (valid.length === 1) return;
129
149
  if (valid.length > 1) {
@@ -135,11 +155,13 @@ const KEYWORDS: Record<string, (check: KeywordCheck) => void> = {
135
155
  fail('must be valid to one and only one schema, but 0 are valid');
136
156
  errors.push(...results.flat());
137
157
  },
138
- properties({ arg, value, location, errors }) {
158
+ properties({ arg, root, value, location, errors }) {
139
159
  if (!isObject(value) || !isObject(arg)) return;
140
160
  for (const [name, propertySchema] of Object.entries(arg)) {
141
161
  if (!Object.hasOwn(value, name)) continue;
142
- errors.push(...validateSchema(propertySchema as Schema, value[name], `${location}.${name}`));
162
+ errors.push(
163
+ ...validateSchema(propertySchema as Schema, value[name], `${location}.${name}`, root),
164
+ );
143
165
  }
144
166
  },
145
167
  required({ arg, value, fail }) {
@@ -148,21 +170,51 @@ const KEYWORDS: Record<string, (check: KeywordCheck) => void> = {
148
170
  if (!Object.hasOwn(value, name)) fail(`required property '${name}' not found`, name);
149
171
  }
150
172
  },
151
- additionalProperties({ arg, schema, value, location, errors, fail }) {
173
+ additionalProperties({ arg, schema, root, value, location, errors, fail }) {
152
174
  if (!isObject(value) || (arg !== false && !isObject(arg))) return;
153
175
  const known = isObject(schema.properties) ? schema.properties : {};
154
176
  for (const name of Object.keys(value)) {
155
177
  if (Object.hasOwn(known, name)) continue;
156
178
  if (arg === false) fail(`property '${name}' ${NOT_DEFINED}`, name);
157
- else errors.push(...validateSchema(arg, value[name], `${location}.${name}`));
179
+ else errors.push(...validateSchema(arg, value[name], `${location}.${name}`, root));
158
180
  }
159
181
  },
182
+ items({ arg, root, value, location, errors }) {
183
+ if (!Array.isArray(value) || !isObject(arg)) return;
184
+ value.forEach((item, index) => {
185
+ errors.push(...validateSchema(arg, item, `${location}[${index}]`, root));
186
+ });
187
+ },
188
+ uniqueItems({ arg, value, fail }) {
189
+ if (arg !== true || !Array.isArray(value)) return;
190
+ const seen = new Set<string>();
191
+ for (const item of value) {
192
+ const key = canonical(item);
193
+ if (seen.has(key)) {
194
+ fail('must have only unique items in the array');
195
+ return;
196
+ }
197
+ seen.add(key);
198
+ }
199
+ },
200
+ // Only the schema's own definitions: '#/$defs/<name>'.
201
+ $ref({ arg, root, value, location, errors }) {
202
+ const name =
203
+ typeof arg === 'string' && arg.startsWith(DEFS) ? arg.slice(DEFS.length) : undefined;
204
+ const target = name !== undefined && isObject(root.$defs) ? root.$defs[name] : undefined;
205
+ if (isObject(target)) errors.push(...validateSchema(target, value, location, root));
206
+ },
160
207
  // Anything else is an annotation (description, title, default, readOnly,
161
208
  // genesisType, $schema, $defs, ...) and validates nothing; networknt
162
209
  // doesn't enforce readOnly unless asked to.
163
210
  };
164
211
 
165
- export function validateSchema(schema: Schema, value: unknown, location = '$'): SchemaError[] {
212
+ export function validateSchema(
213
+ schema: Schema,
214
+ value: unknown,
215
+ location = '$',
216
+ root: Schema = schema,
217
+ ): SchemaError[] {
166
218
  const errors: SchemaError[] = [];
167
219
  if (!isObject(schema)) return errors;
168
220
  const keywords = Object.keys(schema);
@@ -175,6 +227,7 @@ export function validateSchema(schema: Schema, value: unknown, location = '$'):
175
227
  KEYWORDS[keyword]({
176
228
  arg: schema[keyword],
177
229
  schema,
230
+ root,
178
231
  value,
179
232
  location,
180
233
  errors,
package/src/server.ts CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  type ViewEntry,
19
19
  } from './db/views.ts';
20
20
  import { createAuthState } from './handlers/auth.ts';
21
+ import { handleCommitEvent } from './handlers/commitEvent.ts';
21
22
  import { crudEventHandler } from './handlers/crudEvents.ts';
22
23
  import { pendingKey, viewRow, waitForPage } from './handlers/dataLogon.ts';
23
24
  import {
@@ -29,12 +30,13 @@ import {
29
30
  import { permittedQueryRow, requestingUser } from './handlers/resourceAuth.ts';
30
31
  import { Connection, type Subscription, type ViewRow } from './protocol/connection.ts';
31
32
  import { isLegacyFidelity, liveModifyMode } from './protocol/fidelity.ts';
32
- import { routeMessage } from './protocol/router.ts';
33
+ import { replyNotLoggedOn, routeMessage } from './protocol/router.ts';
33
34
  import { dataserverRow, stampRow, type RowOperation } from './protocol/rowUpdate.ts';
34
35
  import type {
35
36
  BroadcastFn,
36
37
  BroadcastTableChangeFn,
37
38
  EventHandler,
39
+ GenesisMessage,
38
40
  MockServerConfig,
39
41
  QueryDef,
40
42
  RequestReplyDef,
@@ -43,6 +45,9 @@ import type {
43
45
  ViewDef,
44
46
  } from './types.ts';
45
47
 
48
+ // WebSocket.OPEN: what a socket of the engine's own reports.
49
+ const WS_OPEN = 1;
50
+
46
51
  // One view row a live change pushes, and how.
47
52
  type ViewChange = [RowOperation, Row];
48
53
 
@@ -674,6 +679,27 @@ export function createMockServer(config: MockServerConfig): MockServer {
674
679
  setEventHandler(eventName, augment(getEventHandler(eventName)));
675
680
  }
676
681
 
682
+ // An event POSTed over HTTP (HttpRouteCtx.commitEvent): run through the
683
+ // socket's commit path on a connection of its own, whose one reply is the
684
+ // answer.
685
+ function commitEventOverHttp(message: GenesisMessage, userName: string | undefined): Row {
686
+ let reply: Row = {};
687
+ const connection = new Connection({
688
+ readyState: WS_OPEN,
689
+ send: (data) => {
690
+ reply = JSON.parse(data);
691
+ },
692
+ });
693
+ connection.authenticated = userName !== undefined;
694
+ connection.userName = userName;
695
+ if (config.auth?.requireAuth && !connection.authenticated) {
696
+ replyNotLoggedOn(message, connection);
697
+ } else {
698
+ handleCommitEvent(message, connection, config, store, { broadcast, broadcastTableChange });
699
+ }
700
+ return reply;
701
+ }
702
+
677
703
  let wss: WebSocketServer | undefined;
678
704
  let httpServer: http.Server | undefined;
679
705
 
@@ -684,7 +710,14 @@ export function createMockServer(config: MockServerConfig): MockServer {
684
710
  // node:http + the `ws` package rather than a runtime-specific API (e.g.
685
711
  // Bun.serve) so this runs unmodified under both Node (>=22.6, via
686
712
  // `node --experimental-strip-types`) and Bun.
687
- httpServer = http.createServer(createHttpRequestListener(config, legacyHttpSessions, auth));
713
+ httpServer = http.createServer(
714
+ createHttpRequestListener(config, legacyHttpSessions, auth, {
715
+ store,
716
+ broadcast,
717
+ broadcastTableChange,
718
+ commitEvent: commitEventOverHttp,
719
+ }),
720
+ );
688
721
  // A cookie-authenticated router answers an upgrade without a live
689
722
  // sessionAuthToken cookie with HTTP 401 (PreHttpHandlerProvider.kt:61-95
690
723
  // @v8.15.29). Read per upgrade, like every config field.
@@ -702,6 +735,9 @@ export function createMockServer(config: MockServerConfig): MockServer {
702
735
  wss.on('connection', (ws: WebSocket, req: http.IncomingMessage) => {
703
736
  const connection = new Connection(ws);
704
737
  if (cookieAuthentication(config)) connection.cookieSessionAuthToken = cookieToken(req);
738
+ const hostname = req.headers.hostname;
739
+ connection.hostnameHeader = typeof hostname === 'string' ? hostname : undefined;
740
+ connection.remoteAddress = req.socket.remoteAddress;
705
741
  connections.add(connection);
706
742
 
707
743
  ws.on('message', (data) => {