@genesislcap/mock-server 15.7.3-alpha-277c463.0 → 15.7.3-alpha-e7d4aa5.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 (71) hide show
  1. package/README.md +237 -52
  2. package/dist/db/criteria.d.ts +5 -0
  3. package/dist/db/criteria.js +304 -0
  4. package/dist/db/metadata.d.ts +3 -0
  5. package/dist/db/metadata.js +35 -0
  6. package/dist/db/store.d.ts +27 -0
  7. package/dist/db/store.js +226 -0
  8. package/dist/handlers/auth.d.ts +9 -0
  9. package/dist/handlers/auth.js +99 -0
  10. package/dist/handlers/commitEvent.d.ts +8 -0
  11. package/dist/handlers/commitEvent.js +40 -0
  12. package/dist/handlers/dataLogon.d.ts +5 -0
  13. package/dist/handlers/dataLogon.js +46 -0
  14. package/dist/handlers/heartbeat.d.ts +3 -0
  15. package/dist/handlers/heartbeat.js +16 -0
  16. package/dist/handlers/http.d.ts +4 -0
  17. package/dist/handlers/http.js +165 -0
  18. package/dist/handlers/jsonSchema.d.ts +5 -0
  19. package/dist/handlers/jsonSchema.js +77 -0
  20. package/dist/handlers/meta.d.ts +4 -0
  21. package/dist/handlers/meta.js +42 -0
  22. package/dist/handlers/requestReply.d.ts +4 -0
  23. package/dist/handlers/requestReply.js +68 -0
  24. package/dist/handlers/resourceAuth.d.ts +5 -0
  25. package/dist/handlers/resourceAuth.js +27 -0
  26. package/dist/handlers/resources.d.ts +3 -0
  27. package/dist/handlers/resources.js +34 -0
  28. package/dist/index.d.ts +6 -0
  29. package/dist/index.js +5 -0
  30. package/dist/launch.d.ts +19 -0
  31. package/dist/launch.js +59 -0
  32. package/dist/protocol/connection.d.ts +24 -0
  33. package/dist/protocol/connection.js +35 -0
  34. package/dist/protocol/errors.d.ts +17 -0
  35. package/dist/protocol/errors.js +16 -0
  36. package/dist/protocol/messageTypes.d.ts +28 -0
  37. package/dist/protocol/messageTypes.js +42 -0
  38. package/dist/protocol/router.d.ts +6 -0
  39. package/dist/protocol/router.js +101 -0
  40. package/dist/protocol/rowUpdate.d.ts +4 -0
  41. package/dist/protocol/rowUpdate.js +17 -0
  42. package/dist/server.d.ts +23 -0
  43. package/dist/server.js +274 -0
  44. package/dist/types.d.ts +142 -0
  45. package/dist/types.js +4 -0
  46. package/package.json +16 -6
  47. package/src/db/criteria.ts +53 -21
  48. package/src/db/store.ts +100 -27
  49. package/src/handlers/commitEvent.ts +13 -5
  50. package/src/handlers/dataLogon.ts +11 -4
  51. package/src/handlers/heartbeat.ts +16 -3
  52. package/src/handlers/http.ts +27 -0
  53. package/src/handlers/jsonSchema.ts +3 -3
  54. package/src/handlers/meta.ts +11 -3
  55. package/src/handlers/requestReply.ts +22 -8
  56. package/src/handlers/resourceAuth.ts +37 -0
  57. package/src/handlers/resources.ts +8 -1
  58. package/src/index.ts +9 -0
  59. package/src/launch.ts +95 -0
  60. package/src/protocol/connection.ts +3 -1
  61. package/src/protocol/messageTypes.ts +9 -0
  62. package/src/protocol/router.ts +19 -12
  63. package/src/protocol/rowUpdate.ts +5 -4
  64. package/src/server.ts +73 -8
  65. package/src/types.ts +132 -8
  66. package/test/criteria.test.ts +0 -174
  67. package/test/jsonSchema.test.ts +0 -38
  68. package/test/metadata.test.ts +0 -49
  69. package/test/server.test.ts +0 -289
  70. package/test/store.test.ts +0 -181
  71. package/tsconfig.json +0 -18
@@ -0,0 +1,35 @@
1
+ // Derives META_REQUEST/JSON_SCHEMA_REQUEST field metadata from seed data itself,
2
+ // so every table/view/query gets working metadata without hand-authoring it —
3
+ // datasource init won't complete without a non-empty FIELD array (see README).
4
+ // Numeric fields scan EVERY row, not just the first non-null value: a column
5
+ // like PRICE is DOUBLE if any row holds a fractional value, even when row one
6
+ // happens to land on a whole number. A column whose values are all whole
7
+ // numbers still infers as LONG — if it's semantically a DOUBLE, say so via
8
+ // the fieldTypes override (see README).
9
+ function inferFieldType(name, rows, sample) {
10
+ if (typeof sample === 'number') {
11
+ const anyFractional = rows.some((row) => typeof row[name] === 'number' && !Number.isInteger(row[name]));
12
+ return anyFractional ? 'DOUBLE' : 'LONG';
13
+ }
14
+ if (typeof sample === 'boolean')
15
+ return 'BOOLEAN';
16
+ return 'STRING';
17
+ }
18
+ /** rows: array of plain row objects. Returns a FIELD array covering every key seen. */
19
+ export function deriveFields(rows, overrides = {}) {
20
+ const fieldNames = [];
21
+ const seen = new Set();
22
+ for (const row of rows) {
23
+ for (const key of Object.keys(row)) {
24
+ if (!seen.has(key)) {
25
+ seen.add(key);
26
+ fieldNames.push(key);
27
+ }
28
+ }
29
+ }
30
+ return fieldNames.map((name) => {
31
+ const sampleRow = rows.find((row) => row[name] !== undefined && row[name] !== null);
32
+ const type = overrides[name] ?? (sampleRow ? inferFieldType(name, rows, sampleRow[name]) : 'STRING');
33
+ return { NAME: name, TYPE: type };
34
+ });
35
+ }
@@ -0,0 +1,27 @@
1
+ import type { Row, TableDef, ViewDef } from '../types.ts';
2
+ type Pk = string;
3
+ export declare class Store {
4
+ private tables;
5
+ private tableConfig;
6
+ private sequenceCounters;
7
+ private seedRows;
8
+ readonly views: Map<string, ViewDef>;
9
+ registerTable(tableName: string, { pkField, sequencePrefix, sequenceWidth, rows }: TableDef): this;
10
+ registerView(viewName: string, definition: ViewDef): this;
11
+ nextSequenceValue(sequencePrefix: string, width: number): string;
12
+ getAllRows(tableName: string): Row[];
13
+ getRow(tableName: string, pk: Pk): Row | undefined;
14
+ rowKey(tableName: string, row: Row): Pk;
15
+ findRow(tableName: string, criteria: Row): Row | undefined;
16
+ insertRow(tableName: string, record: Row): Row;
17
+ updateRow(tableName: string, pk: Pk, patch: Row): Row | undefined;
18
+ deleteRow(tableName: string, pk: Pk): boolean;
19
+ getViewRows(viewName: string): Row[];
20
+ private materializeView;
21
+ getResourceRows(resourceName: string): Row[];
22
+ getMetadataRows(resourceName: string): Row[];
23
+ getPkFields(resourceName: string): string[];
24
+ getRowRef(resourceName: string, row: Row): unknown;
25
+ rowStubFromKey(resourceName: string, key: Pk): Row;
26
+ }
27
+ export {};
@@ -0,0 +1,226 @@
1
+ // In-memory tables + views + sequence generation. No persistence, no external deps.
2
+ // This is the "database" — disposable and rebuilt from seed data on every server start.
3
+ // Composite keys join the pk fields' values with '|' (so values must not
4
+ // contain '|'). Single-field keys stay the raw value, preserving
5
+ // getRow('TABLE', 'TR001')-style lookups.
6
+ const COMPOSITE_KEY_SEPARATOR = '|';
7
+ function normalizePkFields(pkField) {
8
+ return Array.isArray(pkField) ? pkField : [pkField];
9
+ }
10
+ function keyFor(pkFields, row) {
11
+ if (pkFields.length === 1)
12
+ return row[pkFields[0]];
13
+ return pkFields.map((field) => String(row[field])).join(COMPOSITE_KEY_SEPARATOR);
14
+ }
15
+ export class Store {
16
+ tables = new Map();
17
+ tableConfig = new Map();
18
+ sequenceCounters = new Map();
19
+ // Immutable snapshot of each table's rows as registered, used only for field
20
+ // metadata derivation (see getMetadataRows) so deleting every live row can't
21
+ // collapse a resource's schema to zero fields.
22
+ seedRows = new Map();
23
+ views = new Map();
24
+ registerTable(tableName, { pkField, sequencePrefix, sequenceWidth = 3, rows = [] }) {
25
+ const pkFields = normalizePkFields(pkField);
26
+ const table = new Map();
27
+ for (const row of rows) {
28
+ table.set(keyFor(pkFields, row), { ...row });
29
+ }
30
+ this.tables.set(tableName, table);
31
+ this.tableConfig.set(tableName, { pkFields, sequencePrefix, sequenceWidth });
32
+ this.seedRows.set(tableName, rows.map((row) => ({ ...row })));
33
+ // Sequence generation only makes sense for a single-field pk.
34
+ if (sequencePrefix && pkFields.length === 1) {
35
+ let maxN = 0;
36
+ for (const row of rows) {
37
+ const pk = String(row[pkFields[0]] ?? '');
38
+ if (pk.startsWith(sequencePrefix)) {
39
+ const n = parseInt(pk.slice(sequencePrefix.length), 10);
40
+ if (Number.isFinite(n))
41
+ maxN = Math.max(maxN, n);
42
+ }
43
+ }
44
+ this.sequenceCounters.set(sequencePrefix, maxN + 1);
45
+ }
46
+ return this;
47
+ }
48
+ registerView(viewName, definition) {
49
+ this.views.set(viewName, definition);
50
+ return this;
51
+ }
52
+ nextSequenceValue(sequencePrefix, width) {
53
+ const n = this.sequenceCounters.get(sequencePrefix) ?? 1;
54
+ this.sequenceCounters.set(sequencePrefix, n + 1);
55
+ return `${sequencePrefix}${String(n).padStart(width, '0')}`;
56
+ }
57
+ getAllRows(tableName) {
58
+ const table = this.tables.get(tableName);
59
+ if (!table)
60
+ return [];
61
+ return Array.from(table.values());
62
+ }
63
+ getRow(tableName, pk) {
64
+ return this.tables.get(tableName)?.get(pk);
65
+ }
66
+ // The storage/broadcast key for a row: the pk field's value, or for
67
+ // composite-keyed tables the pk fields' values joined with '|'. Event
68
+ // handlers on composite tables pass this to broadcastTableChange.
69
+ rowKey(tableName, row) {
70
+ const config = this.tableConfig.get(tableName);
71
+ if (!config)
72
+ throw new Error(`Unknown table: ${tableName}`);
73
+ return keyFor(config.pkFields, row);
74
+ }
75
+ // Fallback matching for tables where the caller doesn't have the full key:
76
+ // try the pk field(s) first, then any single field that uniquely identifies
77
+ // one row, then the full combination of provided fields.
78
+ findRow(tableName, criteria) {
79
+ const table = this.tables.get(tableName);
80
+ if (!table)
81
+ return undefined;
82
+ const { pkFields } = this.tableConfig.get(tableName) ?? { pkFields: [] };
83
+ if (pkFields.length > 0 && pkFields.every((field) => criteria[field] !== undefined)) {
84
+ const byKey = table.get(keyFor(pkFields, criteria));
85
+ if (byKey)
86
+ return byKey;
87
+ }
88
+ const rows = Array.from(table.values());
89
+ const matchesAllCriteria = (row) => Object.entries(criteria).every(([field, value]) => row[field] === value);
90
+ for (const [field, value] of Object.entries(criteria)) {
91
+ const matches = rows.filter((row) => row[field] === value);
92
+ if (matches.length === 1 && matchesAllCriteria(matches[0]))
93
+ return matches[0];
94
+ }
95
+ return rows.find(matchesAllCriteria);
96
+ }
97
+ insertRow(tableName, record) {
98
+ const table = this.tables.get(tableName);
99
+ const config = this.tableConfig.get(tableName);
100
+ if (!table || !config)
101
+ throw new Error(`Unknown table: ${tableName}`);
102
+ const row = { ...record };
103
+ if (config.pkFields.length === 1 &&
104
+ row[config.pkFields[0]] === undefined &&
105
+ config.sequencePrefix) {
106
+ row[config.pkFields[0]] = this.nextSequenceValue(config.sequencePrefix, config.sequenceWidth);
107
+ }
108
+ const missing = config.pkFields.filter((field) => row[field] === undefined);
109
+ if (missing.length > 0) {
110
+ throw new Error(`Primary key field(s) '${missing.join("', '")}' are required for inserting into table '${tableName}'`);
111
+ }
112
+ table.set(keyFor(config.pkFields, row), row);
113
+ return row;
114
+ }
115
+ updateRow(tableName, pk, patch) {
116
+ const table = this.tables.get(tableName);
117
+ if (!table || !table.has(pk))
118
+ return undefined;
119
+ const updated = { ...table.get(pk), ...patch };
120
+ table.set(pk, updated);
121
+ return updated;
122
+ }
123
+ deleteRow(tableName, pk) {
124
+ const table = this.tables.get(tableName);
125
+ if (!table)
126
+ return false;
127
+ return table.delete(pk);
128
+ }
129
+ // Materializes a view: base table left-joined to related tables (optionally
130
+ // narrowed by per-join `where` predicates), minus anti-joined rows, plus
131
+ // derived fields.
132
+ getViewRows(viewName) {
133
+ const view = this.views.get(viewName);
134
+ if (!view)
135
+ throw new Error(`Unknown view: ${viewName}`);
136
+ return this.materializeView(view, (tableName) => this.getAllRows(tableName));
137
+ }
138
+ materializeView(view, getRows) {
139
+ let rows = getRows(view.base).map((row) => ({ ...row }));
140
+ for (const antiJoin of view.antiJoins ?? []) {
141
+ const joinRows = getRows(antiJoin.table);
142
+ rows = rows.filter((row) => !joinRows.some((joinRow) => joinRow[antiJoin.on[1]] === row[antiJoin.on[0]] &&
143
+ (antiJoin.where?.(joinRow, row) ?? true)));
144
+ }
145
+ for (const join of view.joins ?? []) {
146
+ const joinRows = getRows(join.table);
147
+ // A `where` predicate sees the base row, so an index keyed on the `on`
148
+ // field alone can't answer it — scan per base row instead.
149
+ const joinIndex = join.where ? undefined : new Map();
150
+ if (joinIndex) {
151
+ for (const row of joinRows) {
152
+ joinIndex.set(row[join.on[1]], row);
153
+ }
154
+ }
155
+ rows = rows.map((row) => {
156
+ const match = joinIndex
157
+ ? joinIndex.get(row[join.on[0]])
158
+ : joinRows.find((joinRow) => joinRow[join.on[1]] === row[join.on[0]] && join.where(joinRow, row));
159
+ const merged = { ...row };
160
+ for (const [alias, sourceField] of Object.entries(join.select ?? {})) {
161
+ merged[alias] = match?.[sourceField];
162
+ }
163
+ return merged;
164
+ });
165
+ }
166
+ if (view.derived) {
167
+ rows = rows.map((row) => {
168
+ const merged = { ...row };
169
+ for (const [field, compute] of Object.entries(view.derived)) {
170
+ merged[field] = compute(row);
171
+ }
172
+ return merged;
173
+ });
174
+ }
175
+ return rows;
176
+ }
177
+ // Resolves a queryable resource (table or view) by name to its current rows.
178
+ getResourceRows(resourceName) {
179
+ if (this.views.has(resourceName))
180
+ return this.getViewRows(resourceName);
181
+ return this.getAllRows(resourceName);
182
+ }
183
+ // Rows to derive META_REQUEST/JSON_SCHEMA_REQUEST field metadata from:
184
+ // current rows when there are any, else the registration-time seed rows
185
+ // (re-joined through the view definition for views). Without this fallback,
186
+ // deleting a table's last row would make the next metadata reply say the
187
+ // resource has zero fields — which entity-management renders as a form with
188
+ // no inputs and a delete button that can't build a payload, silently.
189
+ getMetadataRows(resourceName) {
190
+ const live = this.getResourceRows(resourceName);
191
+ if (live.length > 0)
192
+ return live;
193
+ const view = this.views.get(resourceName);
194
+ if (view)
195
+ return this.materializeView(view, (tableName) => this.seedRows.get(tableName) ?? []);
196
+ return this.seedRows.get(resourceName) ?? [];
197
+ }
198
+ // Row-identity fields for a table or view; empty when unknown.
199
+ getPkFields(resourceName) {
200
+ const view = this.views.get(resourceName);
201
+ if (view) {
202
+ if (view.pkField)
203
+ return normalizePkFields(view.pkField);
204
+ return this.tableConfig.get(view.base)?.pkFields ?? [];
205
+ }
206
+ return this.tableConfig.get(resourceName)?.pkFields ?? [];
207
+ }
208
+ // The DETAILS.ROW_REF value stamped on QUERY_UPDATE rows (see
209
+ // protocol/rowUpdate.ts): the pk field's value, or the composite key. The
210
+ // client's dataServerResultFilter keys inserts/amends/deletes off this.
211
+ getRowRef(resourceName, row) {
212
+ const pkFields = this.getPkFields(resourceName);
213
+ if (pkFields.length === 0)
214
+ return undefined;
215
+ return keyFor(pkFields, row);
216
+ }
217
+ // Rebuilds a DELETE stub row carrying the pk field(s) from a stored key, so
218
+ // subscribers can be told which row to drop after it's already gone.
219
+ rowStubFromKey(resourceName, key) {
220
+ const pkFields = this.getPkFields(resourceName);
221
+ if (pkFields.length <= 1)
222
+ return pkFields.length ? { [pkFields[0]]: key } : {};
223
+ const parts = String(key).split(COMPOSITE_KEY_SEPARATOR);
224
+ return Object.fromEntries(pkFields.map((field, i) => [field, parts[i]]));
225
+ }
226
+ }
@@ -0,0 +1,9 @@
1
+ import type { Connection } from '../protocol/connection.ts';
2
+ import type { AuthUser, GenesisMessage, MockServerConfig, Row } from '../types.ts';
3
+ export type TokenRegistry = Map<string, string>;
4
+ export declare function capRegistry(registry: Map<string, string>): void;
5
+ export declare function registerAckTokens(ack: Row, username: string, tokens: TokenRegistry): void;
6
+ export declare function buildLoginAckBody(user: AuthUser, config: MockServerConfig, messageType?: string): Row;
7
+ export declare function findUser(config: MockServerConfig, username?: string, password?: string): AuthUser | undefined;
8
+ export declare function handleLogin(message: GenesisMessage, connection: Connection, config: MockServerConfig, tokens: TokenRegistry): void;
9
+ export declare function handleLogout(message: GenesisMessage, connection: Connection): void;
@@ -0,0 +1,99 @@
1
+ import crypto from 'node:crypto';
2
+ import { MESSAGE_TYPE, ERROR_CODE } from "../protocol/messageTypes.js";
3
+ const DEFAULT_HEARTBEAT_INTERVAL_SECS = 30;
4
+ // Both transports mint tokens on every login/silent-login, so a long-lived
5
+ // dev/CI server would otherwise grow these maps one entry per page load.
6
+ // Maps iterate in insertion order, so dropping from the front evicts the
7
+ // oldest sessions/tokens first.
8
+ const MAX_REGISTRY_ENTRIES = 1000;
9
+ export function capRegistry(registry) {
10
+ while (registry.size > MAX_REGISTRY_ENTRIES) {
11
+ const oldest = registry.keys().next().value;
12
+ if (oldest === undefined)
13
+ return;
14
+ registry.delete(oldest);
15
+ }
16
+ }
17
+ export function registerAckTokens(ack, username, tokens) {
18
+ tokens.set(ack.SESSION_AUTH_TOKEN, username);
19
+ tokens.set(ack.REFRESH_AUTH_TOKEN, username);
20
+ capRegistry(tokens);
21
+ }
22
+ // Shared by the WS EVENT_LOGIN_AUTH handler and the HTTP login handlers
23
+ // (handlers/http.ts) — EVENT_LOGIN_DETAILS_ACK is byte-for-byte the same shape
24
+ // as EVENT_LOGIN_AUTH_ACK, just under a different MESSAGE_TYPE (see
25
+ // foundation-auth's EVENT_LOGIN_DETAILS_ACK.ts, which literally extends it).
26
+ export function buildLoginAckBody(user, config, messageType = MESSAGE_TYPE.EVENT_LOGIN_AUTH_ACK) {
27
+ return {
28
+ MESSAGE_TYPE: messageType,
29
+ SESSION_AUTH_TOKEN: crypto.randomUUID(),
30
+ REFRESH_AUTH_TOKEN: crypto.randomUUID(),
31
+ SESSION_ID: crypto.randomUUID(),
32
+ USER_NAME: user.username,
33
+ UPDATE_QUEUE: 'MOCK',
34
+ ZERO_MQ_PROXY_MODE_ENABLED: false,
35
+ ZERO_MQ_PROXY_INBOUND_PORT: 0,
36
+ ZERO_MQ_PROXY_OUTBOUND_PORT: 0,
37
+ USER: user.user ?? {},
38
+ DETAILS: {
39
+ SYSTEM: { DATE: new Date().toISOString() },
40
+ HEARTBEAT_INTERVAL_SECS: config.auth?.heartbeatIntervalSecs ?? DEFAULT_HEARTBEAT_INTERVAL_SECS,
41
+ FAILED_LOGIN_ATTEMPTS: 0,
42
+ REJECTED_LOGIN_ATTEMPTS: 0,
43
+ LAST_LOGIN_DATETIME: 0,
44
+ DAYS_TO_PASSWORD_EXPIRY: -1,
45
+ PRODUCT: [{ NAME: config.productName ?? 'mock-server', VERSION: '0.1.0' }],
46
+ },
47
+ PERMISSION: user.permission ?? [],
48
+ PROFILE: user.profile ?? [],
49
+ };
50
+ }
51
+ export function findUser(config, username, password) {
52
+ const users = config.auth?.users ?? [];
53
+ if (password === undefined)
54
+ return users.find((u) => u.username === username);
55
+ return users.find((u) => u.username === username && u.password === password);
56
+ }
57
+ export function handleLogin(message, connection, config, tokens) {
58
+ const details = message.DETAILS ?? {};
59
+ // Two login shapes share EVENT_LOGIN_AUTH: credentials ({USER_NAME,
60
+ // PASSWORD}) and token refresh — foundation-comms' createRefreshTokenMessage
61
+ // sends only DETAILS.REFRESH_AUTH_TOKEN (plus the stored SESSION_AUTH_TOKEN
62
+ // at the top level), no username at all.
63
+ const tokenUsername = details.USER_NAME === undefined
64
+ ? (tokens.get(details.REFRESH_AUTH_TOKEN) ??
65
+ tokens.get(details.SESSION_AUTH_TOKEN) ??
66
+ tokens.get(message.SESSION_AUTH_TOKEN))
67
+ : undefined;
68
+ const user = details.USER_NAME !== undefined
69
+ ? findUser(config, details.USER_NAME, details.PASSWORD)
70
+ : findUser(config, tokenUsername);
71
+ if (!user) {
72
+ connection.reply(message, {
73
+ MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
74
+ ERROR: [
75
+ {
76
+ CODE: ERROR_CODE.INCORRECT_CREDENTIALS,
77
+ STATUS_CODE: '401',
78
+ TEXT: 'Incorrect username or password',
79
+ },
80
+ ],
81
+ WARNING: [],
82
+ });
83
+ return;
84
+ }
85
+ const ack = buildLoginAckBody(user, config);
86
+ registerAckTokens(ack, user.username, tokens);
87
+ connection.authenticated = true;
88
+ connection.userName = user.username;
89
+ connection.profile = user.profile ?? [];
90
+ connection.permission = user.permission ?? [];
91
+ connection.sessionAuthToken = ack.SESSION_AUTH_TOKEN;
92
+ connection.sessionId = ack.SESSION_ID;
93
+ connection.reply(message, ack);
94
+ }
95
+ export function handleLogout(message, connection) {
96
+ connection.authenticated = false;
97
+ connection.subscriptions.clear();
98
+ connection.reply(message, { MESSAGE_TYPE: MESSAGE_TYPE.LOGOUT_ACK });
99
+ }
@@ -0,0 +1,8 @@
1
+ import type { Store } from '../db/store.ts';
2
+ import type { Connection } from '../protocol/connection.ts';
3
+ import type { BroadcastFn, BroadcastTableChangeFn, GenesisMessage, MockServerConfig } from '../types.ts';
4
+ export interface CommitEventCtx {
5
+ broadcast: BroadcastFn;
6
+ broadcastTableChange: BroadcastTableChangeFn;
7
+ }
8
+ export declare function handleCommitEvent(message: GenesisMessage, connection: Connection, config: MockServerConfig, store: Store, ctx: CommitEventCtx): void;
@@ -0,0 +1,40 @@
1
+ import { NackError } from "../protocol/errors.js";
2
+ import { ERROR_CODE, MESSAGE_TYPE } from "../protocol/messageTypes.js";
3
+ // Commit events (EVENT_<ENTITY>_INSERT/_AMEND/_DELETE, or whatever suffix
4
+ // convention your project uses) are looked up by exact MESSAGE_TYPE against
5
+ // config.eventHandlers. A handler receives (details, ctx) and either returns
6
+ // { generated?: [...] } on success, or throws NackError(errors) on failure.
7
+ export function handleCommitEvent(message, connection, config, store, ctx) {
8
+ const eventName = message.MESSAGE_TYPE;
9
+ // defaultEventHandler catches anything unregistered — lets projects with
10
+ // dozens of commit events adopt incrementally (e.g. `() => ({})` to ack
11
+ // everything unhandled) instead of enumerating ack-only handlers.
12
+ const handler = config.eventHandlers?.[eventName] ?? config.defaultEventHandler;
13
+ // Replies use the GENERIC EVENT_ACK/EVENT_NACK — correlation is purely via
14
+ // SOURCE_REF. See the note on MESSAGE_TYPE in protocol/messageTypes.ts:
15
+ // real consumers (foundation-comms' kv.service, entity-management) match
16
+ // these names exactly, so a name-suffixed <EVENT>_ACK reads as failure and
17
+ // a <EVENT>_NACK passes as silent success.
18
+ if (!handler) {
19
+ connection.reply(message, {
20
+ MESSAGE_TYPE: MESSAGE_TYPE.EVENT_NACK,
21
+ ERROR: [
22
+ { CODE: ERROR_CODE.UNKNOWN_RESOURCE, TEXT: `No event handler registered for ${eventName}` },
23
+ ],
24
+ });
25
+ return;
26
+ }
27
+ try {
28
+ const result = handler(message.DETAILS ?? {}, { connection, store, message, ...ctx }) ?? {};
29
+ connection.reply(message, {
30
+ MESSAGE_TYPE: MESSAGE_TYPE.EVENT_ACK,
31
+ GENERATED: result.generated ?? [],
32
+ });
33
+ }
34
+ catch (error) {
35
+ const errors = error instanceof NackError
36
+ ? error.errors
37
+ : [{ CODE: ERROR_CODE.VALIDATION_ERROR, TEXT: error.message }];
38
+ connection.reply(message, { MESSAGE_TYPE: MESSAGE_TYPE.EVENT_NACK, ERROR: errors });
39
+ }
40
+ }
@@ -0,0 +1,5 @@
1
+ import type { Store } from '../db/store.ts';
2
+ import type { Connection } from '../protocol/connection.ts';
3
+ import type { GenesisMessage, MockServerConfig } from '../types.ts';
4
+ export declare function handleDataLogon(message: GenesisMessage, connection: Connection, config: MockServerConfig, store: Store): void;
5
+ export declare function handleDataLogoff(message: GenesisMessage, connection: Connection): void;
@@ -0,0 +1,46 @@
1
+ import { compileCriteria, filterByCriteria } from "../db/criteria.js";
2
+ import { MESSAGE_TYPE, ERROR_CODE } from "../protocol/messageTypes.js";
3
+ import { stampRows } from "../protocol/rowUpdate.js";
4
+ import { applyResourceAuth, requestingUser } from "./resourceAuth.js";
5
+ // DATA_LOGON opens a persistent subscription keyed by SOURCE_REF: reply with an
6
+ // initial snapshot, then keep the SOURCE_REF registered so later inserts/amends/
7
+ // deletes on this resource can be pushed on the same channel (see server.ts
8
+ // broadcast()) until the client sends DATA_LOGOFF.
9
+ export function handleDataLogon(message, connection, config, store) {
10
+ const details = message.DETAILS ?? {};
11
+ const resourceName = details.DATASOURCE_NAME;
12
+ const query = config.queries?.[resourceName];
13
+ if (!query) {
14
+ connection.reply(message, {
15
+ MESSAGE_TYPE: MESSAGE_TYPE.QUERY_UPDATE,
16
+ ERROR: [{ CODE: ERROR_CODE.UNKNOWN_RESOURCE, TEXT: `Unknown datasource: ${resourceName}` }],
17
+ });
18
+ return;
19
+ }
20
+ const criteria = details.CRITERIA_MATCH;
21
+ const user = requestingUser(connection);
22
+ // Order matters: the query's own filter (the where-clause equivalent) and
23
+ // the user's row permissioning narrow the set BEFORE the client's
24
+ // CRITERIA_MATCH; hidden fields are stripped last, off the final rows.
25
+ let rows = store.getResourceRows(query.source);
26
+ if (query.filter)
27
+ rows = rows.filter(query.filter);
28
+ rows = filterByCriteria(rows, criteria);
29
+ rows = applyResourceAuth(rows, query.auth, user);
30
+ connection.subscribe(message.SOURCE_REF, {
31
+ resourceName,
32
+ getRowRef: (row) => store.getRowRef(query.source, row),
33
+ predicate: compileCriteria(criteria),
34
+ sequenceId: 1,
35
+ });
36
+ connection.reply(message, {
37
+ MESSAGE_TYPE: MESSAGE_TYPE.QUERY_UPDATE,
38
+ ROW: stampRows(rows, (row) => store.getRowRef(query.source, row), 'INSERT'),
39
+ ROWS_COUNT: rows.length,
40
+ SEQUENCE_ID: 1,
41
+ MORE_ROWS: false,
42
+ });
43
+ }
44
+ export function handleDataLogoff(message, connection) {
45
+ connection.unsubscribe(message.SOURCE_REF);
46
+ }
@@ -0,0 +1,3 @@
1
+ import type { Connection } from '../protocol/connection.ts';
2
+ import type { GenesisMessage, MockServerConfig } from '../types.ts';
3
+ export declare function handleHeartbeat(message: GenesisMessage, connection: Connection, config: MockServerConfig): void;
@@ -0,0 +1,16 @@
1
+ import { MESSAGE_TYPE } from "../protocol/messageTypes.js";
2
+ export function handleHeartbeat(message, connection, config) {
3
+ // With the auth gate off (the default), this server accepts every data
4
+ // message — so the pong must report IS_AUTHENTICATED: true even though the
5
+ // WS connection itself never "logged in". HTTP-login clients (httpAutoLogin
6
+ // included) send no SESSION_AUTH_TOKEN on WS messages, so
7
+ // connection.authenticated stays false forever on their connections; report
8
+ // that raw flag and the client treats the session as dead and tears it
9
+ // down, defeating httpAutoLogin entirely. Only when a project opts into
10
+ // auth.requireAuth does the flag reflect real connection auth state.
11
+ const requireAuth = config.auth?.requireAuth ?? false;
12
+ connection.reply(message, {
13
+ MESSAGE_TYPE: MESSAGE_TYPE.HEARTBEAT_PONG,
14
+ IS_AUTHENTICATED: connection.authenticated || !requireAuth,
15
+ });
16
+ }
@@ -0,0 +1,4 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { MockServerConfig } from '../types.ts';
3
+ import { type TokenRegistry } from './auth.ts';
4
+ export declare function createHttpRequestListener(config: MockServerConfig, sessions: Map<string, string>, tokens?: TokenRegistry): (req: IncomingMessage, res: ServerResponse) => Promise<void>;