@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,37 @@
1
+ import type { Connection } from '../protocol/connection.ts';
2
+ import type { ResourceAuthDef, RequestingUser, Row } from '../types.ts';
3
+
4
+ // The identity a resource-level auth hook (rowFilter/hideFields) sees for the
5
+ // requesting connection. userName is undefined for unauthenticated
6
+ // connections — possible when requireAuth is off, or pre-login.
7
+ export function requestingUser(connection: Connection): RequestingUser {
8
+ return {
9
+ userName: connection.userName,
10
+ profile: connection.profile,
11
+ permission: connection.permission,
12
+ };
13
+ }
14
+
15
+ export function hiddenFields(auth: ResourceAuthDef | undefined, user: RequestingUser): Set<string> {
16
+ const fields = typeof auth?.hideFields === 'function' ? auth.hideFields(user) : auth?.hideFields;
17
+ return new Set(fields ?? []);
18
+ }
19
+
20
+ // Applies a resource's permissioning to a reply/snapshot row set: drops rows
21
+ // the user's rowFilter rejects, then strips hidden fields from what's left.
22
+ // Mirrors dataserver auth maps + hideFields on the real server.
23
+ export function applyResourceAuth(
24
+ rows: Row[],
25
+ auth: ResourceAuthDef | undefined,
26
+ user: RequestingUser,
27
+ ): Row[] {
28
+ if (!auth) return rows;
29
+ let result = auth.rowFilter ? rows.filter((row) => auth.rowFilter!(row, user)) : rows;
30
+ const hidden = hiddenFields(auth, user);
31
+ if (hidden.size > 0) {
32
+ result = result.map((row) =>
33
+ Object.fromEntries(Object.entries(row).filter(([field]) => !hidden.has(field))),
34
+ );
35
+ }
36
+ return result;
37
+ }
@@ -17,7 +17,14 @@ function deriveResources(config: MockServerConfig): ResourceItem[] {
17
17
  for (const name of Object.keys(config.requestReplies ?? {})) {
18
18
  resources.push({ RESOURCE_NAME: name, RESOURCE_TYPE: 'REQUEST_SERVER' });
19
19
  }
20
- for (const name of Object.keys(config.eventHandlers ?? {})) {
20
+ const eventNames = new Set([
21
+ ...Object.keys(config.eventHandlers ?? {}),
22
+ // Events served only by eventSchemas + defaultEventHandler still need to
23
+ // be discoverable, or the client-side resource gate blocks them before
24
+ // the commit is ever sent.
25
+ ...Object.keys(config.eventSchemas ?? {}),
26
+ ]);
27
+ for (const name of eventNames) {
21
28
  resources.push({ RESOURCE_NAME: name, RESOURCE_TYPE: 'EVENT_HANDLER' });
22
29
  }
23
30
  return resources;
package/src/index.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  export { createMockServer, type MockServer } from './server.ts';
2
+ export { launchStack, type LaunchStackOptions, type LaunchedStack } from './launch.ts';
2
3
  export { Store } from './db/store.ts';
3
4
  export { NackError, type NackErrorInput, type NackErrorEntry } from './protocol/errors.ts';
4
5
  export { compileCriteria, filterByCriteria, type Predicate } from './db/criteria.ts';
5
6
  export type {
7
+ AntiJoinDef,
6
8
  AuthConfig,
7
9
  AuthUser,
8
10
  BroadcastFn,
@@ -13,13 +15,20 @@ export type {
13
15
  EventSchemaOverride,
14
16
  FieldMetadata,
15
17
  GenesisMessage,
18
+ HttpRouteDef,
16
19
  JoinDef,
17
20
  MockServerConfig,
21
+ OnMessageCtx,
22
+ OnMessageHook,
18
23
  QueryDef,
24
+ RequestingUser,
19
25
  RequestReplyDef,
26
+ RequestReplyResolverCtx,
27
+ ResourceAuthDef,
20
28
  ResourceItem,
21
29
  Row,
22
30
  SocketLike,
31
+ SsoIdentityProvider,
23
32
  TableDef,
24
33
  ViewDef,
25
34
  } from './types.ts';
package/src/launch.ts ADDED
@@ -0,0 +1,95 @@
1
+ // One-command dev stack: boot a mock server (ephemeral port by default) and
2
+ // spawn the client dev command pointed at it, with tied lifetimes — so
3
+ // several server+client pairs can run on one machine without hand-assigning
4
+ // ports or orphaning processes.
5
+
6
+ import { spawn, type ChildProcess } from 'node:child_process';
7
+ import { createMockServer, type MockServer } from './server.ts';
8
+ import type { MockServerConfig } from './types.ts';
9
+
10
+ export interface LaunchStackOptions {
11
+ config: MockServerConfig;
12
+ // The client dev command, spawned once the server port is known. An array
13
+ // is spawned directly ([command, ...args]); a string runs through the
14
+ // shell. Inherits stdio so the client's output streams to the terminal.
15
+ clientCommand: string | string[];
16
+ // Server port; default 0 lets the OS pick a free one (the parallel case).
17
+ port?: number;
18
+ cwd?: string;
19
+ // Extra env for the client, derived from the bound port. Merged over
20
+ // process.env and the default { API_HOST: `ws://localhost:${port}` }.
21
+ // Use it to also pin per-instance client ports, e.g.
22
+ // (port) => ({ PORT: String(port + 1) }) — or leave the client dev
23
+ // server's own auto-increment (vite's default) to handle collisions.
24
+ clientEnv?: (port: number) => Record<string, string>;
25
+ // Default true: stop the mock server when the client exits, and terminate
26
+ // the client on SIGINT/SIGTERM — one Ctrl+C tears the whole pair down.
27
+ tieLifetimes?: boolean;
28
+ }
29
+
30
+ export interface LaunchedStack {
31
+ server: MockServer;
32
+ port: number;
33
+ client: ChildProcess;
34
+ // Resolves with the client's exit code (null if killed by signal). When
35
+ // tieLifetimes is on, the server has been stopped by the time it resolves.
36
+ clientExited: Promise<number | null>;
37
+ // Terminate the client and stop the server.
38
+ stop(): Promise<void>;
39
+ }
40
+
41
+ export async function launchStack(options: LaunchStackOptions): Promise<LaunchedStack> {
42
+ const { config, clientCommand, port = 0, cwd, clientEnv, tieLifetimes = true } = options;
43
+
44
+ const server = createMockServer(config);
45
+ const boundPort = await server.listen(port);
46
+
47
+ const env = {
48
+ ...process.env,
49
+ API_HOST: `ws://localhost:${boundPort}`,
50
+ ...clientEnv?.(boundPort),
51
+ };
52
+ const client = Array.isArray(clientCommand)
53
+ ? spawn(clientCommand[0], clientCommand.slice(1), { cwd, env, stdio: 'inherit' })
54
+ : spawn(clientCommand, { cwd, env, stdio: 'inherit', shell: true });
55
+
56
+ let stopping = false;
57
+ async function stop(): Promise<void> {
58
+ if (stopping) return;
59
+ stopping = true;
60
+ if (client.exitCode === null && !client.killed) client.kill('SIGINT');
61
+ await server.stop();
62
+ }
63
+
64
+ const clientExited = new Promise<number | null>((resolve) => {
65
+ client.once('exit', (code) => {
66
+ const finish = () => resolve(code);
67
+ if (tieLifetimes) {
68
+ stopping = true;
69
+ server.stop().then(finish, finish);
70
+ } else {
71
+ finish();
72
+ }
73
+ });
74
+ client.once('error', (error) => {
75
+ console.error('[mock-server] Failed to spawn client command:', error);
76
+ const finish = () => resolve(null);
77
+ if (tieLifetimes) {
78
+ stopping = true;
79
+ server.stop().then(finish, finish);
80
+ } else {
81
+ finish();
82
+ }
83
+ });
84
+ });
85
+
86
+ if (tieLifetimes) {
87
+ const onSignal = () => {
88
+ void stop();
89
+ };
90
+ process.once('SIGINT', onSignal);
91
+ process.once('SIGTERM', onSignal);
92
+ }
93
+
94
+ return { server, port: boundPort, client, clientExited, stop };
95
+ }
@@ -6,7 +6,9 @@ const WS_OPEN = 1;
6
6
 
7
7
  export interface Subscription {
8
8
  resourceName: string;
9
- pkField?: string;
9
+ // Computes the DETAILS.ROW_REF value for a pushed row (single pk value, or
10
+ // the joined composite key) — bound to Store.getRowRef at subscribe time.
11
+ getRowRef: (row: Row) => unknown;
10
12
  predicate: Predicate;
11
13
  sequenceId: number;
12
14
  }
@@ -1,4 +1,13 @@
1
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',
2
11
  EVENT_LOGIN_AUTH: 'EVENT_LOGIN_AUTH',
3
12
  EVENT_LOGIN_AUTH_ACK: 'EVENT_LOGIN_AUTH_ACK',
4
13
  EVENT_LOGIN_AUTH_NACK: 'EVENT_LOGIN_AUTH_NACK',
@@ -11,15 +11,21 @@ import type { GenesisMessage, MockServerConfig } from '../types.ts';
11
11
  import type { Connection } from './connection.ts';
12
12
  import { MESSAGE_TYPE, ERROR_CODE, isCommitEvent, isRequestReply } from './messageTypes.ts';
13
13
 
14
- // Message types a connection may send before authenticating. Everything else
15
- // (data subscriptions, request-replies, metadata, commit events) requires the
16
- // connection to have logged in over WS — or to present a SESSION_AUTH_TOKEN
17
- // this server issued (over either transport), which is how a client that
18
- // logged in over HTTP authenticates its WS traffic: foundation-comms stamps
19
- // the stored token onto every outgoing message. RESOURCES_REQUEST is allowed
20
- // pre-auth so resource discovery can't deadlock a client that fetches it
21
- // before (or while) logging in. Set config.auth.requireAuth = false to skip
22
- // the gate entirely.
14
+ // Message types a connection may send before authenticating when the OPT-IN
15
+ // auth gate (config.auth.requireAuth = true) is enabled. Everything else
16
+ // (data subscriptions, request-replies, metadata, commit events) then
17
+ // requires the connection to have logged in over WS — or to present a
18
+ // SESSION_AUTH_TOKEN this server issued (over either transport).
19
+ // RESOURCES_REQUEST is allowed pre-auth so resource discovery can't deadlock
20
+ // a client that fetches it before (or while) logging in.
21
+ //
22
+ // The gate is OFF by default because real clients can't be assumed to
23
+ // satisfy it: browser frame captures show that after logging in over
24
+ // foundation-auth's HTTP transport, the client sends NO SESSION_AUTH_TOKEN
25
+ // on any WebSocket message (session storage's authToken is never populated
26
+ // by that flow, so message.ts's stamp serializes to nothing) — a default-on
27
+ // gate would reject every datasource with NOT_LOGGED_ON. Enable it only for
28
+ // clients that log in over WS (or stamp tokens on WS traffic).
23
29
  const PRE_AUTH_MESSAGE_TYPES = new Set<string>([
24
30
  MESSAGE_TYPE.EVENT_LOGIN_AUTH,
25
31
  MESSAGE_TYPE.EVENT_LOGOUT,
@@ -60,7 +66,8 @@ function replyNotLoggedOn(message: GenesisMessage, connection: Connection): void
60
66
  return;
61
67
  }
62
68
  if (isCommitEvent(type)) {
63
- connection.reply(message, { MESSAGE_TYPE: `${type}_NACK`, ERROR });
69
+ // Generic, not `${type}_NACK` — see the note in messageTypes.ts.
70
+ connection.reply(message, { MESSAGE_TYPE: MESSAGE_TYPE.EVENT_NACK, ERROR });
64
71
  return;
65
72
  }
66
73
  connection.reply(message, { MESSAGE_TYPE: type, ERROR });
@@ -78,7 +85,7 @@ export function routeMessage(
78
85
  // HEARTBEAT_PONG's IS_AUTHENTICATED reflects an HTTP-issued token straight
79
86
  // away; the gate itself only applies to data traffic.
80
87
  ensureAuthenticated(message, connection, tokens);
81
- const requireAuth = config.auth?.requireAuth ?? true;
88
+ const requireAuth = config.auth?.requireAuth ?? false;
82
89
  if (
83
90
  requireAuth &&
84
91
  !PRE_AUTH_MESSAGE_TYPES.has(message.MESSAGE_TYPE) &&
@@ -93,7 +100,7 @@ export function routeMessage(
93
100
  case MESSAGE_TYPE.EVENT_LOGOUT:
94
101
  return handleLogout(message, connection);
95
102
  case MESSAGE_TYPE.HEARTBEAT_PING:
96
- return handleHeartbeat(message, connection);
103
+ return handleHeartbeat(message, connection, config);
97
104
  case MESSAGE_TYPE.DATA_LOGON:
98
105
  return handleDataLogon(message, connection, config, store);
99
106
  case MESSAGE_TYPE.DATA_LOGOFF:
@@ -7,8 +7,9 @@ export type RowOperation = 'INSERT' | 'MODIFY' | 'DELETE';
7
7
  // (both for the initial snapshot and later unsolicited pushes on the same
8
8
  // SOURCE_REF — the envelope is otherwise identical). OPERATION must be exactly
9
9
  // 'INSERT' | 'MODIFY' | 'DELETE'; anything else is silently dropped client-side.
10
- export function stampRow(row: Row, pkField: string | undefined, operation: RowOperation): Row {
11
- const rowRef = pkField ? row[pkField] : undefined;
10
+ // rowRef comes from Store.getRowRef — a single pk value, or the joined
11
+ // composite key for multi-field pks.
12
+ export function stampRow(row: Row, rowRef: unknown, operation: RowOperation): Row {
12
13
  return {
13
14
  ...row,
14
15
  ROW_REF: rowRef,
@@ -18,8 +19,8 @@ export function stampRow(row: Row, pkField: string | undefined, operation: RowOp
18
19
 
19
20
  export function stampRows(
20
21
  rows: Row[],
21
- pkField: string | undefined,
22
+ getRowRef: (row: Row) => unknown,
22
23
  operation: RowOperation,
23
24
  ): Row[] {
24
- return rows.map((row) => stampRow(row, pkField, operation));
25
+ return rows.map((row) => stampRow(row, getRowRef(row), operation));
25
26
  }
package/src/server.ts CHANGED
@@ -2,6 +2,7 @@ import http from 'node:http';
2
2
  import { WebSocketServer, type WebSocket } from 'ws';
3
3
  import { Store } from './db/store.ts';
4
4
  import { createHttpRequestListener } from './handlers/http.ts';
5
+ import { applyResourceAuth, requestingUser } from './handlers/resourceAuth.ts';
5
6
  import { Connection, type Subscription } from './protocol/connection.ts';
6
7
  import { routeMessage } from './protocol/router.ts';
7
8
  import { stampRow } from './protocol/rowUpdate.ts';
@@ -19,6 +20,11 @@ import type {
19
20
 
20
21
  export interface MockServer {
21
22
  start(port: number): WebSocketServer;
23
+ // Like start(), but resolves with the ACTUAL bound port once listening —
24
+ // pass 0 (the default) to let the OS pick a free one. This is the way to
25
+ // run several servers in parallel (per test worker/shard) without
26
+ // hand-assigning ports.
27
+ listen(port?: number): Promise<number>;
22
28
  stop(): Promise<void>;
23
29
  store: Store;
24
30
  broadcast: BroadcastFn;
@@ -80,15 +86,30 @@ export function createMockServer(config: MockServerConfig): MockServer {
80
86
  }
81
87
 
82
88
  const broadcast: BroadcastFn = (resourceName, operation, row) => {
89
+ const query = config.queries?.[resourceName];
90
+ // The query's own filter (where-clause equivalent) applies to live pushes
91
+ // too — a row the snapshot would exclude must not leak in via broadcast.
92
+ // DELETEs always go through: dropping an unknown ROW_REF is a no-op
93
+ // client-side, while a swallowed DELETE leaves a ghost row.
94
+ if (operation !== 'DELETE' && query?.filter && !query.filter(row)) return;
83
95
  for (const connection of connections) {
84
96
  for (const [sourceRef, subscription] of connection.subscriptions) {
85
97
  if (subscription.resourceName !== resourceName) continue;
86
98
  if (!subscriptionAccepts(subscription, sourceRef, operation, row)) continue;
99
+ // Per-user permissioning (auth maps / hideFields equivalent): the
100
+ // ROW_REF is computed from the unstripped row, since pk fields may
101
+ // themselves be hidden from this user.
102
+ let outRow = row;
103
+ if (operation !== 'DELETE' && query?.auth) {
104
+ const [permitted] = applyResourceAuth([row], query.auth, requestingUser(connection));
105
+ if (!permitted) continue;
106
+ outRow = permitted;
107
+ }
87
108
  subscription.sequenceId += 1;
88
109
  connection.send({
89
110
  MESSAGE_TYPE: 'QUERY_UPDATE',
90
111
  SOURCE_REF: sourceRef,
91
- ROW: [stampRow(row, subscription.pkField, operation)],
112
+ ROW: [stampRow(outRow, subscription.getRowRef(row), operation)],
92
113
  ROWS_COUNT: 1,
93
114
  SEQUENCE_ID: subscription.sequenceId,
94
115
  });
@@ -99,7 +120,9 @@ export function createMockServer(config: MockServerConfig): MockServer {
99
120
  // Event handlers mutate one table (e.g. TRADE) but grids may be subscribed to
100
121
  // a view built on top of it (e.g. ALL_TRADES -> TRADE_VIEW). This finds every
101
122
  // query resource backed by that table — directly or via a view — and pushes
102
- // the (re-joined, for views) row to each one's subscribers.
123
+ // the (re-joined, for views) row to each one's subscribers. `pk` is the
124
+ // store key: the single pk field's value, or store.rowKey(...) for
125
+ // composite-keyed tables.
103
126
  const broadcastTableChange: BroadcastTableChangeFn = (tableName, operation, pk) => {
104
127
  for (const [queryName, query] of Object.entries(config.queries ?? {})) {
105
128
  const isDirect = query.source === tableName;
@@ -107,14 +130,16 @@ export function createMockServer(config: MockServerConfig): MockServer {
107
130
  const isViewOnTable = view?.base === tableName;
108
131
  if (!isDirect && !isViewOnTable) continue;
109
132
 
110
- const pkField = store.getPkField(query.source);
111
133
  let row: Row | undefined;
112
134
  if (operation === 'DELETE') {
113
- row = pkField ? { [pkField]: pk } : undefined;
135
+ const stub = store.rowStubFromKey(query.source, pk);
136
+ row = Object.keys(stub).length > 0 ? stub : undefined;
114
137
  } else if (isDirect) {
115
138
  row = store.getRow(tableName, pk);
116
139
  } else {
117
- row = store.getViewRows(query.source).find((r) => r[pkField!] === pk);
140
+ row = store
141
+ .getViewRows(query.source)
142
+ .find((r) => String(store.getRowRef(query.source, r)) === String(pk));
118
143
  }
119
144
  if (row) broadcast(queryName, operation, row);
120
145
  }
@@ -222,6 +247,19 @@ export function createMockServer(config: MockServerConfig): MockServer {
222
247
  return;
223
248
  }
224
249
  try {
250
+ // Inbound hook: lets a project rewrite messages before routing
251
+ // (e.g. normalize a CRITERIA_MATCH dialect) or handle them fully
252
+ // itself (return false) — instead of monkey-patching ws.on.
253
+ if (config.onMessage) {
254
+ const hooked = config.onMessage(message, {
255
+ connection,
256
+ store,
257
+ broadcast,
258
+ broadcastTableChange,
259
+ });
260
+ if (hooked === false) return;
261
+ if (hooked) message = hooked;
262
+ }
225
263
  routeMessage(
226
264
  message,
227
265
  connection,
@@ -241,12 +279,38 @@ export function createMockServer(config: MockServerConfig): MockServer {
241
279
  });
242
280
 
243
281
  httpServer.listen(port);
244
- console.log(
245
- `[mock-server] Listening on ws://localhost:${port} (HTTP login endpoints on the same port)`,
246
- );
282
+ // Log the ACTUAL bound port once listening — with port 0 (ephemeral, the
283
+ // parallel-servers pattern) the requested port would read "0".
284
+ httpServer.once('listening', () => {
285
+ console.log(
286
+ `[mock-server] Listening on ws://localhost:${boundPort()} (HTTP login endpoints on the same port)`,
287
+ );
288
+ });
247
289
  return wss;
248
290
  }
249
291
 
292
+ function boundPort(): number | undefined {
293
+ const address = httpServer?.address();
294
+ return typeof address === 'object' && address ? address.port : undefined;
295
+ }
296
+
297
+ // start() + resolve with the OS-assigned port once actually listening.
298
+ // Pass no argument (port 0) to run any number of servers side by side —
299
+ // each instance's store/connections/sessions are fully isolated already,
300
+ // so parallel test workers just call listen() and hand the returned port
301
+ // to their own client (API_HOST=ws://localhost:<port>).
302
+ function listen(port = 0): Promise<number> {
303
+ return new Promise((resolve, reject) => {
304
+ if (httpServer?.listening) {
305
+ resolve(boundPort()!);
306
+ return;
307
+ }
308
+ if (!httpServer) start(port);
309
+ httpServer!.once('error', reject);
310
+ httpServer!.once('listening', () => resolve(boundPort()!));
311
+ });
312
+ }
313
+
250
314
  function stop(): Promise<void> {
251
315
  return new Promise((resolve) => {
252
316
  if (!wss || !httpServer) {
@@ -269,6 +333,7 @@ export function createMockServer(config: MockServerConfig): MockServer {
269
333
 
270
334
  return {
271
335
  start,
336
+ listen,
272
337
  stop,
273
338
  store,
274
339
  broadcast,
package/src/types.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // a real Genesis payload's shape is "whatever the project defines" (row data,
3
3
  // event DETAILS) — Record<string, any> there is the honest type, not a cop-out.
4
4
 
5
+ import type { IncomingMessage, ServerResponse } from 'node:http';
5
6
  import type { Store } from './db/store.ts';
6
7
 
7
8
  export type Row = Record<string, any>;
@@ -14,7 +15,12 @@ export interface GenesisMessage {
14
15
  }
15
16
 
16
17
  export interface TableDef {
17
- pkField: string;
18
+ // A single field, or several for composite-keyed tables (e.g. PRICE keyed
19
+ // by [RFQ_ID, SIDE]). Composite rows are identified by the fields' values
20
+ // joined with '|' (see Store.rowKey) — no synthetic key column needed, and
21
+ // nothing extra shows up in grids. Field values therefore must not contain
22
+ // '|' themselves. Sequence generation requires a single pkField.
23
+ pkField: string | string[];
18
24
  sequencePrefix?: string;
19
25
  sequenceWidth?: number;
20
26
  rows?: Row[];
@@ -24,24 +30,86 @@ export interface JoinDef {
24
30
  table: string;
25
31
  on: [string, string];
26
32
  select?: Record<string, string>;
33
+ // Extra join predicate beyond the `on` equality — receives the candidate
34
+ // join row and the base row, e.g. side-specific joins like
35
+ // (price, rfq) => price.SIDE === 'SALES'. When present, matching scans the
36
+ // join table per base row instead of using a prebuilt index (fine at mock
37
+ // scale).
38
+ where?: (joinRow: Row, baseRow: Row) => boolean;
39
+ }
40
+
41
+ // Keeps only base rows with NO match in `table` (e.g. USER_WITHOUT_DETAIL:
42
+ // users lacking a USER_DETAIL row). `where` narrows what counts as a match,
43
+ // same contract as JoinDef.where.
44
+ export interface AntiJoinDef {
45
+ table: string;
46
+ on: [string, string];
47
+ where?: (joinRow: Row, baseRow: Row) => boolean;
27
48
  }
28
49
 
29
50
  export interface ViewDef {
30
51
  base: string;
31
- pkField?: string;
52
+ pkField?: string | string[];
32
53
  joins?: JoinDef[];
54
+ antiJoins?: AntiJoinDef[];
33
55
  derived?: Record<string, (row: Row) => any>;
34
56
  }
35
57
 
58
+ // The authenticated identity a resource-level auth hook sees. userName is
59
+ // undefined for unauthenticated connections (possible when requireAuth is
60
+ // off, or pre-login).
61
+ export interface RequestingUser {
62
+ userName?: string;
63
+ profile: string[];
64
+ permission: string[];
65
+ }
66
+
67
+ // Per-resource permissioning, mirroring what dataserver auth maps and
68
+ // hideFields do on the real server: rowFilter drops rows the user must not
69
+ // see (applied to snapshots, live pushes, and REQ_ replies); hideFields
70
+ // strips columns from rows AND from META_REQUEST field metadata, so e.g.
71
+ // sales users never see the trader side of mirrored columns.
72
+ export interface ResourceAuthDef {
73
+ rowFilter?: (row: Row, user: RequestingUser) => boolean;
74
+ hideFields?: string[] | ((user: RequestingUser) => string[]);
75
+ }
76
+
36
77
  export interface QueryDef {
37
78
  source: string;
38
79
  fieldTypes?: Record<string, string>;
80
+ // Server-side where-clause equivalent, applied before any client
81
+ // CRITERIA_MATCH — to both the DATA_LOGON snapshot and live pushes. Use it
82
+ // for things the real query's filter/where clause does (e.g. keep template
83
+ // rows out of ALL_QTE_MAIN_ENTRIES, CANCELLED out of the blotter).
84
+ filter?: (row: Row) => boolean;
85
+ auth?: ResourceAuthDef;
86
+ }
87
+
88
+ // Details a request-reply resolver receives: the keyed REQUEST fields, the
89
+ // full message, the requesting user, and the live store.
90
+ export interface RequestReplyResolverCtx {
91
+ request: Row;
92
+ message: GenesisMessage;
93
+ user: RequestingUser;
94
+ store: Store;
39
95
  }
40
96
 
41
97
  export interface RequestReplyDef {
42
- source: string;
98
+ // Either serve rows from a table/view (`source`, optionally narrowed by
99
+ // `filter`/REQUEST fields/CRITERIA_MATCH), or compute the reply yourself
100
+ // (`resolver`) — for request servers that calculate rather than read (date
101
+ // calculations, holiday validate/roll, premium schedules, composite
102
+ // lookups). A resolver receives the REQUEST fields and returns the REPLY
103
+ // rows verbatim; throw NackError for a protocol-correct error reply. When
104
+ // both are set, resolver wins. With resolver only, set `metadataRows` (a
105
+ // representative sample reply) or `fieldTypes` so META_REQUEST can still
106
+ // derive REPLY_FIELD metadata.
107
+ source?: string;
108
+ resolver?: (ctx: RequestReplyResolverCtx) => Row[];
109
+ metadataRows?: Row[];
43
110
  fieldTypes?: Record<string, string>;
44
111
  filter?: (row: Row) => boolean;
112
+ auth?: ResourceAuthDef;
45
113
  }
46
114
 
47
115
  export interface EventSchemaOverride {
@@ -63,17 +131,37 @@ export interface AuthUser {
63
131
  user?: Row;
64
132
  }
65
133
 
134
+ // Entry served from GET gwf/sso/list, matching foundation-auth's
135
+ // IDENTITY_PROVIDER DTO (services/idp.ts): { ID, DESCRIPTION, TYPE }.
136
+ export interface SsoIdentityProvider {
137
+ ID: string;
138
+ DESCRIPTION?: string;
139
+ TYPE?: string;
140
+ [key: string]: any;
141
+ }
142
+
66
143
  export interface AuthConfig {
67
144
  users?: AuthUser[];
145
+ // Served from GET gwf/sso/list as { IDPS: [...] }. foundation-auth's login
146
+ // screen fetches this whenever sso.toggled is on, shows a red "Failed to
147
+ // fetch identity providers" AND hides the credentials form if the fetch
148
+ // fails, and rejects an empty list too ("Identity provider list empty") —
149
+ // so when unset, the mock serves one non-functional placeholder provider
150
+ // to keep the login screen rendering. Clicking it navigates to the real
151
+ // SSO login URL template, which the mock does not implement.
152
+ ssoIdentityProviders?: SsoIdentityProvider[];
68
153
  heartbeatIntervalSecs?: number;
69
154
  // A username to always ack gwf/event-login-details as (skips the login
70
155
  // screen entirely), or `true` to use the first configured user.
71
156
  httpAutoLogin?: string | true;
72
- // Default true: WS data traffic (DATA_LOGON, REQ_*, META/JSON_SCHEMA,
73
- // commit events) is rejected with a NOT_LOGGED_ON error until the
74
- // connection logs in — or presents a SESSION_AUTH_TOKEN this server issued
75
- // over either transport (which is how an HTTP login authenticates WS
76
- // traffic). Set false to accept everything unauthenticated.
157
+ // OPT-IN (default false): when true, WS data traffic (DATA_LOGON, REQ_*,
158
+ // META/JSON_SCHEMA, commit events) is rejected with a NOT_LOGGED_ON error
159
+ // until the connection logs in — or presents a SESSION_AUTH_TOKEN this
160
+ // server issued over either transport. Off by default because clients
161
+ // using foundation-auth's HTTP login send no SESSION_AUTH_TOKEN on WS
162
+ // messages at all (verified from browser frame captures), so a default-on
163
+ // gate rejects their every datasource. Enable only for clients that log in
164
+ // over WS.
77
165
  requireAuth?: boolean;
78
166
  }
79
167
 
@@ -97,15 +185,51 @@ export type EventHandlerResult = { generated?: Row[] } | void;
97
185
 
98
186
  export type EventHandler = (details: Row, ctx: EventHandlerCtx) => EventHandlerResult;
99
187
 
188
+ // Extra HTTP route served by the engine's shared http.Server — for project
189
+ // endpoints the protocol doesn't cover (e.g. GET pbi/configs). Routes are
190
+ // tried FIRST, before the built-in login/SSO handlers, so they can also
191
+ // override those. A string path matches pathname.endsWith(path) (same
192
+ // convention as the built-ins, which tolerates any gateway prefix); a RegExp
193
+ // is tested against the full pathname.
194
+ export interface HttpRouteDef {
195
+ method?: string;
196
+ path: string | RegExp;
197
+ handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
198
+ }
199
+
200
+ export interface OnMessageCtx {
201
+ connection: import('./protocol/connection.ts').Connection;
202
+ store: Store;
203
+ broadcast: BroadcastFn;
204
+ broadcastTableChange: BroadcastTableChangeFn;
205
+ }
206
+
207
+ // Inbound-message hook, called for every parsed WS message BEFORE routing.
208
+ // Return a message (possibly rewritten — e.g. normalizing a CRITERIA_MATCH
209
+ // dialect) to continue routing with it, `false` if the hook fully handled
210
+ // the message itself (reply via ctx.connection.reply), or nothing to route
211
+ // the original unchanged.
212
+ export type OnMessageHook = (
213
+ message: GenesisMessage,
214
+ ctx: OnMessageCtx,
215
+ ) => GenesisMessage | false | void;
216
+
100
217
  export interface MockServerConfig {
101
218
  tables?: Record<string, TableDef>;
102
219
  views?: Record<string, ViewDef>;
103
220
  queries?: Record<string, QueryDef>;
104
221
  requestReplies?: Record<string, RequestReplyDef>;
105
222
  eventHandlers?: Record<string, EventHandler>;
223
+ // Fallback for commit events with no registered handler — lets a project
224
+ // with many events adopt incrementally (e.g. `() => ({})` acks everything
225
+ // unhandled) instead of enumerating ack-only handlers. Unregistered events
226
+ // NACK with UNKNOWN_RESOURCE when this is unset.
227
+ defaultEventHandler?: EventHandler;
106
228
  eventSchemas?: Record<string, EventSchemaOverride>;
107
229
  auth?: AuthConfig;
108
230
  resources?: ResourceItem[];
231
+ httpRoutes?: HttpRouteDef[];
232
+ onMessage?: OnMessageHook;
109
233
  productName?: string;
110
234
  }
111
235