@genesislcap/mock-server 15.7.3-alpha-94532c4.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 (70) hide show
  1. package/README.md +212 -37
  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 +4 -1
  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/router.ts +1 -1
  62. package/src/protocol/rowUpdate.ts +5 -4
  63. package/src/server.ts +73 -8
  64. package/src/types.ts +124 -3
  65. package/test/criteria.test.ts +0 -174
  66. package/test/jsonSchema.test.ts +0 -38
  67. package/test/metadata.test.ts +0 -49
  68. package/test/server.test.ts +0 -308
  69. package/test/store.test.ts +0 -181
  70. package/tsconfig.json +0 -18
@@ -0,0 +1,17 @@
1
+ // Stamps each row with DETAILS.OPERATION/ROW_REF, the only fields the client's
2
+ // dataServerResultFilter uses to distinguish INSERT/MODIFY/DELETE on a QUERY_UPDATE
3
+ // (both for the initial snapshot and later unsolicited pushes on the same
4
+ // SOURCE_REF — the envelope is otherwise identical). OPERATION must be exactly
5
+ // 'INSERT' | 'MODIFY' | 'DELETE'; anything else is silently dropped client-side.
6
+ // rowRef comes from Store.getRowRef — a single pk value, or the joined
7
+ // composite key for multi-field pks.
8
+ export function stampRow(row, rowRef, operation) {
9
+ return {
10
+ ...row,
11
+ ROW_REF: rowRef,
12
+ DETAILS: { OPERATION: operation, ROW_REF: rowRef },
13
+ };
14
+ }
15
+ export function stampRows(rows, getRowRef, operation) {
16
+ return rows.map((row) => stampRow(row, getRowRef(row), operation));
17
+ }
@@ -0,0 +1,23 @@
1
+ import { WebSocketServer } from 'ws';
2
+ import { Store } from './db/store.ts';
3
+ import type { BroadcastFn, BroadcastTableChangeFn, EventHandler, MockServerConfig, QueryDef, RequestReplyDef, TableDef, ViewDef } from './types.ts';
4
+ export interface MockServer {
5
+ start(port: number): WebSocketServer;
6
+ listen(port?: number): Promise<number>;
7
+ stop(): Promise<void>;
8
+ store: Store;
9
+ broadcast: BroadcastFn;
10
+ broadcastTableChange: BroadcastTableChangeFn;
11
+ setTable(tableName: string, tableDef: TableDef): void;
12
+ setView(viewName: string, viewDef: ViewDef): void;
13
+ setQuery(resourceName: string, queryDef: QueryDef): void;
14
+ setRequestReply(resourceName: string, requestReplyDef: RequestReplyDef): void;
15
+ setEventHandler(eventName: string, handler: EventHandler): void;
16
+ getQuery(resourceName: string): QueryDef | undefined;
17
+ getRequestReply(resourceName: string): RequestReplyDef | undefined;
18
+ getEventHandler(eventName: string): EventHandler | undefined;
19
+ extendQuery(resourceName: string, augment: (current: QueryDef | undefined) => QueryDef): void;
20
+ extendRequestReply(resourceName: string, augment: (current: RequestReplyDef | undefined) => RequestReplyDef): void;
21
+ extendEventHandler(eventName: string, augment: (current: EventHandler | undefined) => EventHandler): void;
22
+ }
23
+ export declare function createMockServer(config: MockServerConfig): MockServer;
package/dist/server.js ADDED
@@ -0,0 +1,274 @@
1
+ import http from 'node:http';
2
+ import { WebSocketServer } from 'ws';
3
+ import { Store } from "./db/store.js";
4
+ import { createHttpRequestListener } from "./handlers/http.js";
5
+ import { applyResourceAuth, requestingUser } from "./handlers/resourceAuth.js";
6
+ import { Connection } from "./protocol/connection.js";
7
+ import { routeMessage } from "./protocol/router.js";
8
+ import { stampRow } from "./protocol/rowUpdate.js";
9
+ export function createMockServer(config) {
10
+ const store = new Store();
11
+ for (const [tableName, tableDef] of Object.entries(config.tables ?? {})) {
12
+ store.registerTable(tableName, tableDef);
13
+ }
14
+ for (const [viewName, viewDef] of Object.entries(config.views ?? {})) {
15
+ store.registerView(viewName, viewDef);
16
+ }
17
+ const connections = new Set();
18
+ // Pushes an unsolicited row update to every currently-subscribed connection
19
+ // whose DATA_LOGON resource matches, filtered by that subscription's own
20
+ // CRITERIA_MATCH. Event handlers call this after mutating the store so open
21
+ // grids reflect inserts/amends/deletes without the client re-querying.
22
+ // DELETE rows are PK-only stubs (see broadcastTableChange), so a criteria
23
+ // predicate would evaluate against missing fields and drop the push —
24
+ // leaving the client holding a ghost row. Deliver every DELETE instead: a
25
+ // client that never held that ROW_REF ignores it.
26
+ function subscriptionAccepts(subscription, sourceRef, operation, row) {
27
+ if (operation === 'DELETE')
28
+ return true;
29
+ try {
30
+ return subscription.predicate(row);
31
+ }
32
+ catch (error) {
33
+ console.error(`[mock-server] Error evaluating predicate for subscription ${sourceRef}:`, error);
34
+ return false;
35
+ }
36
+ }
37
+ const broadcast = (resourceName, operation, row) => {
38
+ const query = config.queries?.[resourceName];
39
+ // The query's own filter (where-clause equivalent) applies to live pushes
40
+ // too — a row the snapshot would exclude must not leak in via broadcast.
41
+ // DELETEs always go through: dropping an unknown ROW_REF is a no-op
42
+ // client-side, while a swallowed DELETE leaves a ghost row.
43
+ if (operation !== 'DELETE' && query?.filter && !query.filter(row))
44
+ return;
45
+ for (const connection of connections) {
46
+ for (const [sourceRef, subscription] of connection.subscriptions) {
47
+ if (subscription.resourceName !== resourceName)
48
+ continue;
49
+ if (!subscriptionAccepts(subscription, sourceRef, operation, row))
50
+ continue;
51
+ // Per-user permissioning (auth maps / hideFields equivalent): the
52
+ // ROW_REF is computed from the unstripped row, since pk fields may
53
+ // themselves be hidden from this user.
54
+ let outRow = row;
55
+ if (operation !== 'DELETE' && query?.auth) {
56
+ const [permitted] = applyResourceAuth([row], query.auth, requestingUser(connection));
57
+ if (!permitted)
58
+ continue;
59
+ outRow = permitted;
60
+ }
61
+ subscription.sequenceId += 1;
62
+ connection.send({
63
+ MESSAGE_TYPE: 'QUERY_UPDATE',
64
+ SOURCE_REF: sourceRef,
65
+ ROW: [stampRow(outRow, subscription.getRowRef(row), operation)],
66
+ ROWS_COUNT: 1,
67
+ SEQUENCE_ID: subscription.sequenceId,
68
+ });
69
+ }
70
+ }
71
+ };
72
+ // Event handlers mutate one table (e.g. TRADE) but grids may be subscribed to
73
+ // a view built on top of it (e.g. ALL_TRADES -> TRADE_VIEW). This finds every
74
+ // query resource backed by that table — directly or via a view — and pushes
75
+ // the (re-joined, for views) row to each one's subscribers. `pk` is the
76
+ // store key: the single pk field's value, or store.rowKey(...) for
77
+ // composite-keyed tables.
78
+ const broadcastTableChange = (tableName, operation, pk) => {
79
+ for (const [queryName, query] of Object.entries(config.queries ?? {})) {
80
+ const isDirect = query.source === tableName;
81
+ const view = store.views.get(query.source);
82
+ const isViewOnTable = view?.base === tableName;
83
+ if (!isDirect && !isViewOnTable)
84
+ continue;
85
+ let row;
86
+ if (operation === 'DELETE') {
87
+ const stub = store.rowStubFromKey(query.source, pk);
88
+ row = Object.keys(stub).length > 0 ? stub : undefined;
89
+ }
90
+ else if (isDirect) {
91
+ row = store.getRow(tableName, pk);
92
+ }
93
+ else {
94
+ row = store
95
+ .getViewRows(query.source)
96
+ .find((r) => String(store.getRowRef(query.source, r)) === String(pk));
97
+ }
98
+ if (row)
99
+ broadcast(queryName, operation, row);
100
+ }
101
+ };
102
+ const httpSessions = new Map(); // sessionId -> username, for the HTTP login transport (see handlers/http.ts)
103
+ // Every SESSION_AUTH_TOKEN/REFRESH_AUTH_TOKEN this server has issued (over
104
+ // either transport) -> username. Lets a WS connection authenticate with a
105
+ // token from an earlier HTTP login (foundation-comms sends the stored
106
+ // SESSION_AUTH_TOKEN on every message, and its token-refresh path sends
107
+ // EVENT_LOGIN_AUTH with only DETAILS.REFRESH_AUTH_TOKEN — no credentials).
108
+ const issuedTokens = new Map();
109
+ // Runtime override/extend API. Every handler reads off this same `config`
110
+ // object at call time (both the WS path in routeMessage below and the HTTP
111
+ // login transport, whose handler was created once in start() and holds a
112
+ // reference to this exact object) — so these mutate config's own
113
+ // properties in place rather than rebinding the `config` variable, which
114
+ // would only be visible to callers still reading the original reference.
115
+ // Useful both for composing a project's config from a shared base
116
+ // (`setEventHandler`/`setQuery` after createMockServer) and for tests that
117
+ // want to inject a one-off failure/edge case (`extendEventHandler`) without
118
+ // spinning up a second server.
119
+ function setTable(tableName, tableDef) {
120
+ config.tables = { ...config.tables, [tableName]: tableDef };
121
+ store.registerTable(tableName, tableDef);
122
+ }
123
+ function setView(viewName, viewDef) {
124
+ config.views = { ...config.views, [viewName]: viewDef };
125
+ store.registerView(viewName, viewDef);
126
+ }
127
+ function setQuery(resourceName, queryDef) {
128
+ config.queries = { ...config.queries, [resourceName]: queryDef };
129
+ }
130
+ function setRequestReply(resourceName, requestReplyDef) {
131
+ config.requestReplies = { ...config.requestReplies, [resourceName]: requestReplyDef };
132
+ }
133
+ function setEventHandler(eventName, handler) {
134
+ config.eventHandlers = { ...config.eventHandlers, [eventName]: handler };
135
+ }
136
+ function getQuery(resourceName) {
137
+ return config.queries?.[resourceName];
138
+ }
139
+ function getRequestReply(resourceName) {
140
+ return config.requestReplies?.[resourceName];
141
+ }
142
+ function getEventHandler(eventName) {
143
+ return config.eventHandlers?.[eventName];
144
+ }
145
+ // augment(current) => replacement. `current` is undefined if nothing was
146
+ // registered under that name yet, so augment can also be used to define a
147
+ // brand new query/handler in terms of "there was nothing before".
148
+ function extendQuery(resourceName, augment) {
149
+ setQuery(resourceName, augment(getQuery(resourceName)));
150
+ }
151
+ function extendRequestReply(resourceName, augment) {
152
+ setRequestReply(resourceName, augment(getRequestReply(resourceName)));
153
+ }
154
+ function extendEventHandler(eventName, augment) {
155
+ setEventHandler(eventName, augment(getEventHandler(eventName)));
156
+ }
157
+ let wss;
158
+ let httpServer;
159
+ function start(port) {
160
+ // WS (datasource/commit protocol) and HTTP (foundation-auth's login
161
+ // transport) share one http.Server, matching how the real Genesis gateway
162
+ // and the vite dev proxy present a single origin to the client. Built on
163
+ // node:http + the `ws` package rather than a runtime-specific API (e.g.
164
+ // Bun.serve) so this runs unmodified under both Node (>=22.6, via
165
+ // `node --experimental-strip-types`) and Bun.
166
+ httpServer = http.createServer(createHttpRequestListener(config, httpSessions, issuedTokens));
167
+ wss = new WebSocketServer({ server: httpServer });
168
+ wss.on('connection', (ws) => {
169
+ const connection = new Connection(ws);
170
+ connections.add(connection);
171
+ ws.on('message', (data) => {
172
+ let message;
173
+ try {
174
+ message = JSON.parse(data.toString());
175
+ }
176
+ catch {
177
+ console.warn('[mock-server] Ignoring non-JSON message');
178
+ return;
179
+ }
180
+ try {
181
+ // Inbound hook: lets a project rewrite messages before routing
182
+ // (e.g. normalize a CRITERIA_MATCH dialect) or handle them fully
183
+ // itself (return false) — instead of monkey-patching ws.on.
184
+ if (config.onMessage) {
185
+ const hooked = config.onMessage(message, {
186
+ connection,
187
+ store,
188
+ broadcast,
189
+ broadcastTableChange,
190
+ });
191
+ if (hooked === false)
192
+ return;
193
+ if (hooked)
194
+ message = hooked;
195
+ }
196
+ routeMessage(message, connection, config, store, { broadcast, broadcastTableChange }, issuedTokens);
197
+ }
198
+ catch (error) {
199
+ console.error(`[mock-server] Error handling ${message.MESSAGE_TYPE}:`, error);
200
+ }
201
+ });
202
+ ws.on('close', () => {
203
+ connections.delete(connection);
204
+ });
205
+ });
206
+ httpServer.listen(port);
207
+ // Log the ACTUAL bound port once listening — with port 0 (ephemeral, the
208
+ // parallel-servers pattern) the requested port would read "0".
209
+ httpServer.once('listening', () => {
210
+ console.log(`[mock-server] Listening on ws://localhost:${boundPort()} (HTTP login endpoints on the same port)`);
211
+ });
212
+ return wss;
213
+ }
214
+ function boundPort() {
215
+ const address = httpServer?.address();
216
+ return typeof address === 'object' && address ? address.port : undefined;
217
+ }
218
+ // start() + resolve with the OS-assigned port once actually listening.
219
+ // Pass no argument (port 0) to run any number of servers side by side —
220
+ // each instance's store/connections/sessions are fully isolated already,
221
+ // so parallel test workers just call listen() and hand the returned port
222
+ // to their own client (API_HOST=ws://localhost:<port>).
223
+ function listen(port = 0) {
224
+ return new Promise((resolve, reject) => {
225
+ if (httpServer?.listening) {
226
+ resolve(boundPort());
227
+ return;
228
+ }
229
+ if (!httpServer)
230
+ start(port);
231
+ httpServer.once('error', reject);
232
+ httpServer.once('listening', () => resolve(boundPort()));
233
+ });
234
+ }
235
+ function stop() {
236
+ return new Promise((resolve) => {
237
+ if (!wss || !httpServer) {
238
+ resolve();
239
+ return;
240
+ }
241
+ // wss.close() on a {server}-attached WebSocketServer does NOT close live
242
+ // client sockets, and httpServer.close() waits for every open connection
243
+ // — so with a browser still attached, a plain close chain never resolves
244
+ // (and the showcase's SIGINT handler would hang forever). Terminate WS
245
+ // clients and drop idle keep-alive HTTP sockets explicitly first.
246
+ for (const client of wss.clients)
247
+ client.terminate();
248
+ wss.close(() => {
249
+ httpServer.close(() => resolve());
250
+ // Node >=18.2; optional-called because Bun's node:http may lack it.
251
+ httpServer.closeAllConnections?.();
252
+ });
253
+ });
254
+ }
255
+ return {
256
+ start,
257
+ listen,
258
+ stop,
259
+ store,
260
+ broadcast,
261
+ broadcastTableChange,
262
+ setTable,
263
+ setView,
264
+ setQuery,
265
+ setRequestReply,
266
+ setEventHandler,
267
+ getQuery,
268
+ getRequestReply,
269
+ getEventHandler,
270
+ extendQuery,
271
+ extendRequestReply,
272
+ extendEventHandler,
273
+ };
274
+ }
@@ -0,0 +1,142 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { Store } from './db/store.ts';
3
+ export type Row = Record<string, any>;
4
+ export interface GenesisMessage {
5
+ MESSAGE_TYPE: string;
6
+ SOURCE_REF?: string;
7
+ DETAILS?: Row;
8
+ [key: string]: any;
9
+ }
10
+ export interface TableDef {
11
+ pkField: string | string[];
12
+ sequencePrefix?: string;
13
+ sequenceWidth?: number;
14
+ rows?: Row[];
15
+ }
16
+ export interface JoinDef {
17
+ table: string;
18
+ on: [string, string];
19
+ select?: Record<string, string>;
20
+ where?: (joinRow: Row, baseRow: Row) => boolean;
21
+ }
22
+ export interface AntiJoinDef {
23
+ table: string;
24
+ on: [string, string];
25
+ where?: (joinRow: Row, baseRow: Row) => boolean;
26
+ }
27
+ export interface ViewDef {
28
+ base: string;
29
+ pkField?: string | string[];
30
+ joins?: JoinDef[];
31
+ antiJoins?: AntiJoinDef[];
32
+ derived?: Record<string, (row: Row) => any>;
33
+ }
34
+ export interface RequestingUser {
35
+ userName?: string;
36
+ profile: string[];
37
+ permission: string[];
38
+ }
39
+ export interface ResourceAuthDef {
40
+ rowFilter?: (row: Row, user: RequestingUser) => boolean;
41
+ hideFields?: string[] | ((user: RequestingUser) => string[]);
42
+ }
43
+ export interface QueryDef {
44
+ source: string;
45
+ fieldTypes?: Record<string, string>;
46
+ filter?: (row: Row) => boolean;
47
+ auth?: ResourceAuthDef;
48
+ }
49
+ export interface RequestReplyResolverCtx {
50
+ request: Row;
51
+ message: GenesisMessage;
52
+ user: RequestingUser;
53
+ store: Store;
54
+ }
55
+ export interface RequestReplyDef {
56
+ source?: string;
57
+ resolver?: (ctx: RequestReplyResolverCtx) => Row[];
58
+ metadataRows?: Row[];
59
+ fieldTypes?: Record<string, string>;
60
+ filter?: (row: Row) => boolean;
61
+ auth?: ResourceAuthDef;
62
+ }
63
+ export interface EventSchemaOverride {
64
+ table?: string;
65
+ pkOnly?: boolean;
66
+ fieldTypes?: Record<string, string>;
67
+ }
68
+ export interface ResourceItem {
69
+ RESOURCE_NAME: string;
70
+ RESOURCE_TYPE: 'DATASERVER' | 'REQUEST_SERVER' | 'EVENT_HANDLER';
71
+ }
72
+ export interface AuthUser {
73
+ username: string;
74
+ password?: string;
75
+ profile?: string[];
76
+ permission?: string[];
77
+ user?: Row;
78
+ }
79
+ export interface SsoIdentityProvider {
80
+ ID: string;
81
+ DESCRIPTION?: string;
82
+ TYPE?: string;
83
+ [key: string]: any;
84
+ }
85
+ export interface AuthConfig {
86
+ users?: AuthUser[];
87
+ ssoIdentityProviders?: SsoIdentityProvider[];
88
+ heartbeatIntervalSecs?: number;
89
+ httpAutoLogin?: string | true;
90
+ requireAuth?: boolean;
91
+ }
92
+ export interface BroadcastFn {
93
+ (resourceName: string, operation: 'INSERT' | 'MODIFY' | 'DELETE', row: Row): void;
94
+ }
95
+ export interface BroadcastTableChangeFn {
96
+ (tableName: string, operation: 'INSERT' | 'MODIFY' | 'DELETE', pk: string): void;
97
+ }
98
+ export interface EventHandlerCtx {
99
+ connection: import('./protocol/connection.ts').Connection;
100
+ store: Store;
101
+ message: GenesisMessage;
102
+ broadcast: BroadcastFn;
103
+ broadcastTableChange: BroadcastTableChangeFn;
104
+ }
105
+ export type EventHandlerResult = {
106
+ generated?: Row[];
107
+ } | void;
108
+ export type EventHandler = (details: Row, ctx: EventHandlerCtx) => EventHandlerResult;
109
+ export interface HttpRouteDef {
110
+ method?: string;
111
+ path: string | RegExp;
112
+ handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
113
+ }
114
+ export interface OnMessageCtx {
115
+ connection: import('./protocol/connection.ts').Connection;
116
+ store: Store;
117
+ broadcast: BroadcastFn;
118
+ broadcastTableChange: BroadcastTableChangeFn;
119
+ }
120
+ export type OnMessageHook = (message: GenesisMessage, ctx: OnMessageCtx) => GenesisMessage | false | void;
121
+ export interface MockServerConfig {
122
+ tables?: Record<string, TableDef>;
123
+ views?: Record<string, ViewDef>;
124
+ queries?: Record<string, QueryDef>;
125
+ requestReplies?: Record<string, RequestReplyDef>;
126
+ eventHandlers?: Record<string, EventHandler>;
127
+ defaultEventHandler?: EventHandler;
128
+ eventSchemas?: Record<string, EventSchemaOverride>;
129
+ auth?: AuthConfig;
130
+ resources?: ResourceItem[];
131
+ httpRoutes?: HttpRouteDef[];
132
+ onMessage?: OnMessageHook;
133
+ productName?: string;
134
+ }
135
+ export interface FieldMetadata {
136
+ NAME: string;
137
+ TYPE: string;
138
+ }
139
+ export interface SocketLike {
140
+ readyState: number;
141
+ send(data: string): void;
142
+ }
package/dist/types.js ADDED
@@ -0,0 +1,4 @@
1
+ // Shared types for the mock-server protocol engine. Deliberately loose where
2
+ // a real Genesis payload's shape is "whatever the project defines" (row data,
3
+ // event DETAILS) — Record<string, any> there is the honest type, not a cop-out.
4
+ export {};
package/package.json CHANGED
@@ -1,15 +1,25 @@
1
1
  {
2
2
  "name": "@genesislcap/mock-server",
3
- "version": "15.7.3-alpha-94532c4.0",
3
+ "version": "15.7.3-alpha-e7d4aa5.0",
4
4
  "description": "Reusable in-memory Genesis WebSocket protocol mock server for client automation/CI, without a JVM or database.",
5
5
  "type": "module",
6
- "main": "src/index.ts",
7
- "types": "src/index.ts",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
8
  "exports": {
9
- ".": "./src/index.ts"
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "bun": "./src/index.ts",
12
+ "default": "./dist/index.js"
13
+ }
10
14
  },
15
+ "files": [
16
+ "dist",
17
+ "src",
18
+ "README.md"
19
+ ],
11
20
  "scripts": {
12
- "build": "echo \"@genesislcap/mock-server: no build step — runs src/*.ts directly under Node or Bun\"",
21
+ "build": "tsc -p tsconfig.build.json",
22
+ "build:watch": "tsc -p tsconfig.build.json --watch",
13
23
  "lint": "echo \"@genesislcap/mock-server: no lint step\"",
14
24
  "typecheck": "tsc --noEmit",
15
25
  "test": "node --experimental-strip-types --test"
@@ -33,5 +43,5 @@
33
43
  "publishConfig": {
34
44
  "access": "public"
35
45
  },
36
- "gitHead": "85a871e7a46382dbfc7cc262a508e0cc95d3b3e3"
46
+ "gitHead": "47329b0160faf49d52b2964ea22ed9362f275130"
37
47
  }
@@ -3,10 +3,15 @@
3
3
  // NOT (SIDE == 'SELL') OR PRICE >= 100.5
4
4
  // Expr.dateTimeIsGreaterEqual(TRADE_DATE, '20240101-00:00:00') && COUNTERPARTY_ID == 'CPTY001'
5
5
  //
6
- // Supports: == = != <> > >= < <=, AND OR NOT (also && ||), parentheses,
7
- // string/number/boolean literals, bare field identifiers, and the
8
- // `Expr.<fn>(field, value)` function-call criteria that foundation-criteria's
9
- // serialisers.ts emits for grid date/text filters (see EXPR_FUNCTIONS below).
6
+ // Supports: == = != <> > >= < <=, AND OR NOT (also && || !), parentheses,
7
+ // string/number/boolean literals, bare field identifiers, and two
8
+ // function-call dialects real clients emit:
9
+ // - `Expr.<fn>(field, value)` — foundation-criteria's serialisers.ts
10
+ // (grid date/text filters);
11
+ // - `<FIELD>.<fn>(value)` method-call form — e.g.
12
+ // `DEAL_CURRENCIES.containsIgnoreCase('USD')`, as emitted by
13
+ // project-level filter builders. Same EXPR_FUNCTIONS, with the receiver
14
+ // field as the implicit first argument.
10
15
  // Deliberately NOT eval()/new Function() — this parses a small typed grammar
11
16
  // so a malformed or hostile criteria string can only fail to parse, never
12
17
  // execute arbitrary JS.
@@ -16,7 +21,7 @@ import type { Row } from '../types.ts';
16
21
  export type Predicate = (record: Row) => boolean;
17
22
 
18
23
  const TOKEN_RE =
19
- /\s*(&&|\|\||<=|>=|!=|<>|==|=|<|>|\(|\)|,|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|[A-Za-z_][A-Za-z0-9_.]*)/g;
24
+ /\s*(&&|\|\||<=|>=|!=|<>|==|=|<|>|!|\(|\)|,|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?|[A-Za-z_][A-Za-z0-9_.]*)/g;
20
25
 
21
26
  function tokenize(input: string): string[] {
22
27
  const tokens: string[] = [];
@@ -47,16 +52,28 @@ function parseLiteral(token: string): unknown {
47
52
 
48
53
  const COMPARATORS = new Set(['==', '=', '!=', '<>', '<', '<=', '>', '>=']);
49
54
 
50
- // Genesis date/datetime values serialize as 'YYYYMMDD-HH:MM[:SS]' (see
51
- // foundation-criteria's serialisers.ts formatDate); row values may already be
52
- // epoch millis (number) or an ISO string. Returns null if unparseable.
55
+ // Genesis date/datetime values serialize as 'YYYYMMDD-HH:MM[:SS[.mmm]]' —
56
+ // foundation-criteria's serialisers.ts formatDate stops at seconds, but
57
+ // getGroovyDateFormat() emits milliseconds too, and a parser that rejects
58
+ // them makes every Expr.dateTimeIs* comparison silently false (date-filtered
59
+ // grids render zero rows with no warning). Row values may already be epoch
60
+ // millis (number) or an ISO string. Returns null if unparseable.
53
61
  function parseGenesisDateTime(value: unknown): number | null {
54
62
  if (typeof value === 'number') return value;
55
63
  if (typeof value !== 'string') return null;
56
- const match = value.match(/^(\d{4})(\d{2})(\d{2})-(\d{2}):(\d{2})(?::(\d{2}))?$/);
64
+ const match = value.match(/^(\d{4})(\d{2})(\d{2})-(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?$/);
57
65
  if (match) {
58
- const [, y, mo, d, h, mi, s] = match;
59
- return Date.UTC(Number(y), Number(mo) - 1, Number(d), Number(h), Number(mi), Number(s ?? '0'));
66
+ const MS_DIGITS = 3; // '.5' means 500ms, not 5ms — right-pad to full precision
67
+ const [, y, mo, d, h, mi, s, ms] = match;
68
+ return Date.UTC(
69
+ Number(y),
70
+ Number(mo) - 1,
71
+ Number(d),
72
+ Number(h),
73
+ Number(mi),
74
+ Number(s ?? '0'),
75
+ Number((ms ?? '0').padEnd(MS_DIGITS, '0')),
76
+ );
60
77
  }
61
78
  const parsed = Date.parse(value);
62
79
  return Number.isNaN(parsed) ? null : parsed;
@@ -85,19 +102,24 @@ const EXPR_FUNCTIONS: Record<
85
102
  string,
86
103
  (record: Row, args: string[], resolve: ExprResolver) => boolean
87
104
  > = {
105
+ // Multi-value fields (e.g. DEAL_CURRENCIES) may hold an array — treat
106
+ // "contains" as membership there, substring match on strings.
88
107
  contains: (record, args, resolve) => {
89
108
  const value = resolve(args[0], record);
90
109
  const needle = resolve(args[1], record);
91
- return typeof value === 'string' && typeof needle === 'string' && value.includes(needle);
110
+ if (typeof needle !== 'string') return false;
111
+ if (Array.isArray(value)) return value.some((v) => typeof v === 'string' && v === needle);
112
+ return typeof value === 'string' && value.includes(needle);
92
113
  },
93
114
  containsIgnoreCase: (record, args, resolve) => {
94
115
  const value = resolve(args[0], record);
95
116
  const needle = resolve(args[1], record);
96
- return (
97
- typeof value === 'string' &&
98
- typeof needle === 'string' &&
99
- value.toLowerCase().includes(needle.toLowerCase())
100
- );
117
+ if (typeof needle !== 'string') return false;
118
+ const lowered = needle.toLowerCase();
119
+ if (Array.isArray(value)) {
120
+ return value.some((v) => typeof v === 'string' && v.toLowerCase() === lowered);
121
+ }
122
+ return typeof value === 'string' && value.toLowerCase().includes(lowered);
101
123
  },
102
124
  dateIsToday: (record, args, resolve) => {
103
125
  const day = toEpochDay(resolve(args[0], record));
@@ -190,7 +212,8 @@ class Parser {
190
212
  }
191
213
 
192
214
  parseNot(): Predicate {
193
- if (this.peek()?.toUpperCase() === 'NOT') {
215
+ const next = this.peek();
216
+ if (next === '!' || next?.toUpperCase() === 'NOT') {
194
217
  this.next();
195
218
  const operand = this.parseNot();
196
219
  return (record) => !operand(record);
@@ -211,7 +234,10 @@ class Parser {
211
234
  throw new Error('Expected operand on the left side of comparison');
212
235
  }
213
236
 
214
- if (/^Expr\.[A-Za-z_][A-Za-z0-9_]*$/.test(leftToken) && this.peek() === '(') {
237
+ // Both function-call dialects arrive as one dotted token followed by '(':
238
+ // 'Expr.containsIgnoreCase' (foundation-criteria) or
239
+ // 'DEAL_CURRENCIES.containsIgnoreCase' (field method-call form).
240
+ if (leftToken.includes('.') && this.peek() === '(') {
215
241
  return this.parseFunctionCall(leftToken);
216
242
  }
217
243
 
@@ -274,12 +300,18 @@ class Parser {
274
300
  }
275
301
  if (this.next() !== ')') throw new Error(`Missing closing parenthesis in ${name}(...)`);
276
302
 
277
- const fnName = name.slice('Expr.'.length);
303
+ // 'Expr.<fn>(field, value)' passes args through as-is; the method-call
304
+ // form '<FIELD>.<fn>(value)' makes the receiver field the implicit first
305
+ // argument, so both dialects share EXPR_FUNCTIONS.
306
+ const dotIndex = name.lastIndexOf('.');
307
+ const receiver = name.slice(0, dotIndex);
308
+ const fnName = name.slice(dotIndex + 1);
278
309
  const handler = EXPR_FUNCTIONS[fnName];
279
310
  if (!handler) throw new Error(`Unsupported criteria function: ${name}`);
311
+ const allArgs = receiver === 'Expr' ? args : [receiver, ...args];
280
312
 
281
313
  const resolve: ExprResolver = (token, record) => this.resolveValue(token, record);
282
- return (record: Row) => handler(record, args, resolve);
314
+ return (record: Row) => handler(record, allArgs, resolve);
283
315
  }
284
316
  }
285
317