@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,28 @@
1
+ export declare const MESSAGE_TYPE: {
2
+ readonly EVENT_ACK: "EVENT_ACK";
3
+ readonly EVENT_NACK: "EVENT_NACK";
4
+ readonly EVENT_LOGIN_AUTH: "EVENT_LOGIN_AUTH";
5
+ readonly EVENT_LOGIN_AUTH_ACK: "EVENT_LOGIN_AUTH_ACK";
6
+ readonly EVENT_LOGIN_AUTH_NACK: "EVENT_LOGIN_AUTH_NACK";
7
+ readonly EVENT_LOGOUT: "EVENT_LOGOUT";
8
+ readonly LOGOUT_ACK: "LOGOUT_ACK";
9
+ readonly EVENT_LOGOUT_NACK: "EVENT_LOGOUT_NACK";
10
+ readonly HEARTBEAT_PING: "HEARTBEAT_PING";
11
+ readonly HEARTBEAT_PONG: "HEARTBEAT_PONG";
12
+ readonly DATA_LOGON: "DATA_LOGON";
13
+ readonly DATA_LOGOFF: "DATA_LOGOFF";
14
+ readonly QUERY_UPDATE: "QUERY_UPDATE";
15
+ readonly META_REQUEST: "META_REQUEST";
16
+ readonly JSON_SCHEMA_REQUEST: "JSON_SCHEMA_REQUEST";
17
+ readonly RESOURCES_REQUEST: "RESOURCES_REQUEST";
18
+ readonly RESOURCES_REQUEST_ACK: "RESOURCES_REQUEST_ACK";
19
+ readonly RESOURCES_REQUEST_NACK: "RESOURCES_REQUEST_NACK";
20
+ };
21
+ export declare const ERROR_CODE: {
22
+ readonly INCORRECT_CREDENTIALS: "INCORRECT_CREDENTIALS";
23
+ readonly VALIDATION_ERROR: "VALIDATION_ERROR";
24
+ readonly UNKNOWN_RESOURCE: "UNKNOWN_RESOURCE";
25
+ readonly NOT_LOGGED_ON: "NOT_LOGGED_ON";
26
+ };
27
+ export declare function isCommitEvent(messageType: unknown): messageType is string;
28
+ export declare function isRequestReply(messageType: unknown): messageType is string;
@@ -0,0 +1,42 @@
1
+ export const MESSAGE_TYPE = {
2
+ // Commit events are acked with the GENERIC pair below — the reply is
3
+ // correlated by SOURCE_REF, not by name. Real Genesis never replies
4
+ // <EVENT_NAME>_ACK/_NACK: foundation-comms' kv.service checks
5
+ // MESSAGE_TYPE === 'EVENT_ACK' exactly, and entity-management (and the
6
+ // showcase's customEvents.ts) check MESSAGE_TYPE === 'EVENT_NACK' exactly.
7
+ // Reply with the name-suffixed form and every successful commit renders as
8
+ // a failure toast while every NACK passes silently.
9
+ EVENT_ACK: 'EVENT_ACK',
10
+ EVENT_NACK: 'EVENT_NACK',
11
+ EVENT_LOGIN_AUTH: 'EVENT_LOGIN_AUTH',
12
+ EVENT_LOGIN_AUTH_ACK: 'EVENT_LOGIN_AUTH_ACK',
13
+ EVENT_LOGIN_AUTH_NACK: 'EVENT_LOGIN_AUTH_NACK',
14
+ EVENT_LOGOUT: 'EVENT_LOGOUT',
15
+ LOGOUT_ACK: 'LOGOUT_ACK',
16
+ EVENT_LOGOUT_NACK: 'EVENT_LOGOUT_NACK',
17
+ HEARTBEAT_PING: 'HEARTBEAT_PING',
18
+ HEARTBEAT_PONG: 'HEARTBEAT_PONG',
19
+ DATA_LOGON: 'DATA_LOGON',
20
+ DATA_LOGOFF: 'DATA_LOGOFF',
21
+ QUERY_UPDATE: 'QUERY_UPDATE',
22
+ META_REQUEST: 'META_REQUEST',
23
+ JSON_SCHEMA_REQUEST: 'JSON_SCHEMA_REQUEST',
24
+ RESOURCES_REQUEST: 'RESOURCES_REQUEST',
25
+ RESOURCES_REQUEST_ACK: 'RESOURCES_REQUEST_ACK',
26
+ RESOURCES_REQUEST_NACK: 'RESOURCES_REQUEST_NACK',
27
+ };
28
+ export const ERROR_CODE = {
29
+ INCORRECT_CREDENTIALS: 'INCORRECT_CREDENTIALS',
30
+ VALIDATION_ERROR: 'VALIDATION_ERROR',
31
+ UNKNOWN_RESOURCE: 'UNKNOWN_RESOURCE',
32
+ NOT_LOGGED_ON: 'NOT_LOGGED_ON',
33
+ };
34
+ export function isCommitEvent(messageType) {
35
+ return (typeof messageType === 'string' &&
36
+ messageType.startsWith('EVENT_') &&
37
+ messageType !== MESSAGE_TYPE.EVENT_LOGIN_AUTH &&
38
+ messageType !== MESSAGE_TYPE.EVENT_LOGOUT);
39
+ }
40
+ export function isRequestReply(messageType) {
41
+ return typeof messageType === 'string' && messageType.startsWith('REQ_');
42
+ }
@@ -0,0 +1,6 @@
1
+ import type { Store } from '../db/store.ts';
2
+ import { type TokenRegistry } from '../handlers/auth.ts';
3
+ import { type CommitEventCtx } from '../handlers/commitEvent.ts';
4
+ import type { GenesisMessage, MockServerConfig } from '../types.ts';
5
+ import type { Connection } from './connection.ts';
6
+ export declare function routeMessage(message: GenesisMessage, connection: Connection, config: MockServerConfig, store: Store, ctx: CommitEventCtx, tokens?: TokenRegistry): void;
@@ -0,0 +1,101 @@
1
+ import { handleLogin, handleLogout } from "../handlers/auth.js";
2
+ import { handleCommitEvent } from "../handlers/commitEvent.js";
3
+ import { handleDataLogon, handleDataLogoff } from "../handlers/dataLogon.js";
4
+ import { handleHeartbeat } from "../handlers/heartbeat.js";
5
+ import { handleJsonSchemaRequest } from "../handlers/jsonSchema.js";
6
+ import { handleMetaRequest } from "../handlers/meta.js";
7
+ import { handleRequestReply } from "../handlers/requestReply.js";
8
+ import { handleResourcesRequest } from "../handlers/resources.js";
9
+ import { MESSAGE_TYPE, ERROR_CODE, isCommitEvent, isRequestReply } from "./messageTypes.js";
10
+ // Message types a connection may send before authenticating when the OPT-IN
11
+ // auth gate (config.auth.requireAuth = true) is enabled. Everything else
12
+ // (data subscriptions, request-replies, metadata, commit events) then
13
+ // requires the connection to have logged in over WS — or to present a
14
+ // SESSION_AUTH_TOKEN this server issued (over either transport).
15
+ // RESOURCES_REQUEST is allowed pre-auth so resource discovery can't deadlock
16
+ // a client that fetches it before (or while) logging in.
17
+ //
18
+ // The gate is OFF by default because real clients can't be assumed to
19
+ // satisfy it: browser frame captures show that after logging in over
20
+ // foundation-auth's HTTP transport, the client sends NO SESSION_AUTH_TOKEN
21
+ // on any WebSocket message (session storage's authToken is never populated
22
+ // by that flow, so message.ts's stamp serializes to nothing) — a default-on
23
+ // gate would reject every datasource with NOT_LOGGED_ON. Enable it only for
24
+ // clients that log in over WS (or stamp tokens on WS traffic).
25
+ const PRE_AUTH_MESSAGE_TYPES = new Set([
26
+ MESSAGE_TYPE.EVENT_LOGIN_AUTH,
27
+ MESSAGE_TYPE.EVENT_LOGOUT,
28
+ MESSAGE_TYPE.HEARTBEAT_PING,
29
+ MESSAGE_TYPE.DATA_LOGOFF,
30
+ MESSAGE_TYPE.RESOURCES_REQUEST,
31
+ ]);
32
+ function ensureAuthenticated(message, connection, tokens) {
33
+ if (connection.authenticated)
34
+ return true;
35
+ const token = message.SESSION_AUTH_TOKEN;
36
+ const username = typeof token === 'string' ? tokens.get(token) : undefined;
37
+ if (username !== undefined) {
38
+ connection.authenticated = true;
39
+ connection.userName = username;
40
+ connection.sessionAuthToken = token;
41
+ return true;
42
+ }
43
+ return false;
44
+ }
45
+ // Error reply for unauthenticated traffic, shaped per message family the same
46
+ // way each handler's own error paths are (REP_* for REQ_*, *_NACK for events,
47
+ // QUERY_UPDATE for DATA_LOGON, echoed MESSAGE_TYPE for META/JSON_SCHEMA).
48
+ function replyNotLoggedOn(message, connection) {
49
+ const type = message.MESSAGE_TYPE;
50
+ const ERROR = [{ CODE: ERROR_CODE.NOT_LOGGED_ON, TEXT: 'Not logged on' }];
51
+ if (isRequestReply(type)) {
52
+ connection.reply(message, { MESSAGE_TYPE: `REP_${type.replace(/^REQ_/, '')}`, ERROR });
53
+ return;
54
+ }
55
+ if (type === MESSAGE_TYPE.DATA_LOGON) {
56
+ connection.reply(message, { MESSAGE_TYPE: MESSAGE_TYPE.QUERY_UPDATE, ERROR });
57
+ return;
58
+ }
59
+ if (isCommitEvent(type)) {
60
+ // Generic, not `${type}_NACK` — see the note in messageTypes.ts.
61
+ connection.reply(message, { MESSAGE_TYPE: MESSAGE_TYPE.EVENT_NACK, ERROR });
62
+ return;
63
+ }
64
+ connection.reply(message, { MESSAGE_TYPE: type, ERROR });
65
+ }
66
+ export function routeMessage(message, connection, config, store, ctx, tokens = new Map()) {
67
+ // Adopt token auth on every message (not just gated ones) so e.g. a
68
+ // HEARTBEAT_PONG's IS_AUTHENTICATED reflects an HTTP-issued token straight
69
+ // away; the gate itself only applies to data traffic.
70
+ ensureAuthenticated(message, connection, tokens);
71
+ const requireAuth = config.auth?.requireAuth ?? false;
72
+ if (requireAuth &&
73
+ !PRE_AUTH_MESSAGE_TYPES.has(message.MESSAGE_TYPE) &&
74
+ !connection.authenticated) {
75
+ return replyNotLoggedOn(message, connection);
76
+ }
77
+ switch (message.MESSAGE_TYPE) {
78
+ case MESSAGE_TYPE.EVENT_LOGIN_AUTH:
79
+ return handleLogin(message, connection, config, tokens);
80
+ case MESSAGE_TYPE.EVENT_LOGOUT:
81
+ return handleLogout(message, connection);
82
+ case MESSAGE_TYPE.HEARTBEAT_PING:
83
+ return handleHeartbeat(message, connection, config);
84
+ case MESSAGE_TYPE.DATA_LOGON:
85
+ return handleDataLogon(message, connection, config, store);
86
+ case MESSAGE_TYPE.DATA_LOGOFF:
87
+ return handleDataLogoff(message, connection);
88
+ case MESSAGE_TYPE.META_REQUEST:
89
+ return handleMetaRequest(message, connection, config, store);
90
+ case MESSAGE_TYPE.JSON_SCHEMA_REQUEST:
91
+ return handleJsonSchemaRequest(message, connection, config, store);
92
+ case MESSAGE_TYPE.RESOURCES_REQUEST:
93
+ return handleResourcesRequest(message, connection, config);
94
+ default:
95
+ if (isRequestReply(message.MESSAGE_TYPE))
96
+ return handleRequestReply(message, connection, config, store);
97
+ if (isCommitEvent(message.MESSAGE_TYPE))
98
+ return handleCommitEvent(message, connection, config, store, ctx);
99
+ console.warn(`[mock-server] Unhandled MESSAGE_TYPE: ${message.MESSAGE_TYPE}`);
100
+ }
101
+ }
@@ -0,0 +1,4 @@
1
+ import type { Row } from '../types.ts';
2
+ export type RowOperation = 'INSERT' | 'MODIFY' | 'DELETE';
3
+ export declare function stampRow(row: Row, rowRef: unknown, operation: RowOperation): Row;
4
+ export declare function stampRows(rows: Row[], getRowRef: (row: Row) => unknown, operation: RowOperation): Row[];
@@ -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 {};