@genesislcap/mock-server 15.7.3-alpha-94532c4.0 → 15.31.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 (72) hide show
  1. package/README.md +246 -40
  2. package/dist/db/criteria.d.ts +5 -0
  3. package/dist/db/criteria.js +327 -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 +28 -0
  7. package/dist/db/store.js +254 -0
  8. package/dist/handlers/auth.d.ts +10 -0
  9. package/dist/handlers/auth.js +121 -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 +56 -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 +179 -0
  18. package/dist/handlers/jsonSchema.d.ts +5 -0
  19. package/dist/handlers/jsonSchema.js +94 -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 +20 -0
  31. package/dist/launch.js +164 -0
  32. package/dist/protocol/connection.d.ts +25 -0
  33. package/dist/protocol/connection.js +36 -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 +328 -0
  44. package/dist/types.d.ts +142 -0
  45. package/dist/types.js +4 -0
  46. package/package.json +16 -7
  47. package/src/db/criteria.ts +75 -21
  48. package/src/db/store.ts +126 -29
  49. package/src/handlers/auth.ts +32 -6
  50. package/src/handlers/commitEvent.ts +4 -1
  51. package/src/handlers/dataLogon.ts +23 -7
  52. package/src/handlers/heartbeat.ts +16 -3
  53. package/src/handlers/http.ts +43 -2
  54. package/src/handlers/jsonSchema.ts +21 -5
  55. package/src/handlers/meta.ts +11 -3
  56. package/src/handlers/requestReply.ts +22 -8
  57. package/src/handlers/resourceAuth.ts +37 -0
  58. package/src/handlers/resources.ts +8 -1
  59. package/src/index.ts +9 -0
  60. package/src/launch.ts +220 -0
  61. package/src/protocol/connection.ts +4 -1
  62. package/src/protocol/router.ts +2 -2
  63. package/src/protocol/rowUpdate.ts +5 -4
  64. package/src/server.ts +150 -22
  65. package/src/types.ts +124 -3
  66. package/license.txt +0 -46
  67. package/test/criteria.test.ts +0 -174
  68. package/test/jsonSchema.test.ts +0 -38
  69. package/test/metadata.test.ts +0 -49
  70. package/test/server.test.ts +0 -308
  71. package/test/store.test.ts +0 -181
  72. package/tsconfig.json +0 -18
@@ -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,220 @@
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
+ // How long the client tree gets to exit on SIGINT before it is SIGKILLed.
29
+ // Defaults to CLIENT_EXIT_GRACE_MS; lower it in tests, or raise it for a
30
+ // client that needs longer to flush.
31
+ clientExitGraceMs?: number;
32
+ }
33
+
34
+ export interface LaunchedStack {
35
+ server: MockServer;
36
+ port: number;
37
+ client: ChildProcess;
38
+ // Resolves with the client's exit code (null if killed by signal). When
39
+ // tieLifetimes is on, the server has been stopped by the time it resolves.
40
+ clientExited: Promise<number | null>;
41
+ // Terminate the client and stop the server.
42
+ stop(): Promise<void>;
43
+ }
44
+
45
+ // How long a client gets to exit on SIGINT before it is killed outright. A dev
46
+ // server that ignores the signal must not keep its port (or hang stop()).
47
+ const CLIENT_EXIT_GRACE_MS = 5000;
48
+ // How often the watchdog checks whether the launcher is still alive.
49
+ const WATCHDOG_POLL_MS = 500;
50
+
51
+ // Signals the client tree, not just the direct child. The client command is
52
+ // normally a launcher itself (genx -> vite -> esbuild), so signalling only the
53
+ // immediate pid can leave grandchildren holding the port. `detached: true`
54
+ // makes the child a process-group leader, and a negative pid addresses that
55
+ // whole group.
56
+ function killClientTree(client: ChildProcess, signal: NodeJS.Signals): void {
57
+ if (client.pid === undefined || client.exitCode !== null || client.signalCode !== null) return;
58
+ try {
59
+ process.kill(-client.pid, signal);
60
+ } catch {
61
+ // No process group (Windows, or the group is already gone) — fall back to
62
+ // the single child.
63
+ try {
64
+ client.kill(signal);
65
+ } catch {
66
+ // Already exited between the check and the signal; nothing to do.
67
+ }
68
+ }
69
+ }
70
+
71
+ // Nothing in THIS process runs when it is SIGKILLed or dies with the terminal,
72
+ // so parent-death cleanup cannot live here: the client would be reparented to
73
+ // init and keep serving its port forever (verified — a hard-killed launcher
74
+ // leaves vite listening). This tiny detached watcher polls for the launcher
75
+ // and takes the client's process group down with it. It also exits as soon as
76
+ // the client is gone, so it can never outlive the pair it is watching.
77
+ const WATCHDOG_SOURCE = `
78
+ const [launcher, target] = process.argv.slice(1).map(Number);
79
+ const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
80
+ const stop = (sig) => { try { process.kill(-target, sig); } catch { try { process.kill(target, sig); } catch {} } };
81
+ const timer = setInterval(() => {
82
+ if (!alive(target)) { clearInterval(timer); process.exit(0); }
83
+ if (alive(launcher)) return;
84
+ clearInterval(timer);
85
+ stop('SIGTERM');
86
+ setTimeout(() => { stop('SIGKILL'); process.exit(0); }, ${CLIENT_EXIT_GRACE_MS});
87
+ }, ${WATCHDOG_POLL_MS});
88
+ `;
89
+
90
+ function startWatchdog(clientPid: number): ChildProcess | undefined {
91
+ try {
92
+ const watchdog = spawn(
93
+ process.execPath,
94
+ ['-e', WATCHDOG_SOURCE, String(process.pid), String(clientPid)],
95
+ { detached: true, stdio: 'ignore' },
96
+ );
97
+ // Detached + unref'd so it survives a hard kill of this process and never
98
+ // holds this process's event loop open.
99
+ watchdog.unref();
100
+ return watchdog;
101
+ } catch (error) {
102
+ console.warn('[mock-server] Could not start the client watchdog:', error);
103
+ return undefined;
104
+ }
105
+ }
106
+
107
+ export async function launchStack(options: LaunchStackOptions): Promise<LaunchedStack> {
108
+ const {
109
+ config,
110
+ clientCommand,
111
+ port = 0,
112
+ cwd,
113
+ clientEnv,
114
+ tieLifetimes = true,
115
+ clientExitGraceMs = CLIENT_EXIT_GRACE_MS,
116
+ } = options;
117
+
118
+ const server = createMockServer(config);
119
+ const boundPort = await server.listen(port);
120
+
121
+ const env = {
122
+ ...process.env,
123
+ API_HOST: `ws://localhost:${boundPort}`,
124
+ ...clientEnv?.(boundPort),
125
+ };
126
+ // detached: the client leads its own process group so the whole tree can be
127
+ // signalled at once. It also means a terminal Ctrl+C no longer reaches the
128
+ // client directly — it reaches this process, whose SIGINT handler below
129
+ // tears the group down, so shutdown always takes one controlled path.
130
+ const client = Array.isArray(clientCommand)
131
+ ? spawn(clientCommand[0], clientCommand.slice(1), {
132
+ cwd,
133
+ env,
134
+ stdio: 'inherit',
135
+ detached: true,
136
+ })
137
+ : spawn(clientCommand, { cwd, env, stdio: 'inherit', shell: true, detached: true });
138
+
139
+ const watchdog = tieLifetimes && client.pid !== undefined ? startWatchdog(client.pid) : undefined;
140
+
141
+ function cleanupWatchdog(): void {
142
+ if (watchdog?.pid === undefined) return;
143
+ try {
144
+ process.kill(watchdog.pid, 'SIGKILL');
145
+ } catch {
146
+ // Already exited on noticing the client was gone.
147
+ }
148
+ }
149
+
150
+ // Resolves once the client tree is actually down, so stop() means everything
151
+ // is stopped rather than merely signalled.
152
+ function stopClient(): Promise<void> {
153
+ if (client.pid === undefined || client.exitCode !== null || client.signalCode !== null) {
154
+ return Promise.resolve();
155
+ }
156
+ return new Promise((resolve) => {
157
+ const escalate = setTimeout(() => killClientTree(client, 'SIGKILL'), clientExitGraceMs);
158
+ client.once('exit', () => {
159
+ clearTimeout(escalate);
160
+ resolve();
161
+ });
162
+ killClientTree(client, 'SIGINT');
163
+ });
164
+ }
165
+
166
+ let stopping = false;
167
+ async function stop(): Promise<void> {
168
+ if (stopping) return;
169
+ stopping = true;
170
+ removeSignalHandlers();
171
+ cleanupWatchdog();
172
+ await Promise.all([stopClient(), server.stop()]);
173
+ }
174
+
175
+ const clientExited = new Promise<number | null>((resolve) => {
176
+ const settle = (code: number | null) => {
177
+ if (!tieLifetimes) {
178
+ resolve(code);
179
+ return;
180
+ }
181
+ stopping = true;
182
+ removeSignalHandlers();
183
+ cleanupWatchdog();
184
+ const finish = () => resolve(code);
185
+ server.stop().then(finish, finish);
186
+ };
187
+ client.once('exit', (code) => settle(code));
188
+ client.once('error', (error) => {
189
+ console.error('[mock-server] Failed to spawn client command:', error);
190
+ settle(null);
191
+ });
192
+ });
193
+
194
+ // Every path this process can still observe tears the client group down.
195
+ // SIGHUP matters for a closing terminal; 'exit' catches a plain return or an
196
+ // uncaught throw. (A SIGKILL of this process runs none of them — that is
197
+ // what the watchdog above is for.)
198
+ const onSignal = () => {
199
+ void stop();
200
+ };
201
+ const onExit = () => {
202
+ // Synchronous only: no async work runs during 'exit'.
203
+ cleanupWatchdog();
204
+ killClientTree(client, 'SIGKILL');
205
+ };
206
+ function removeSignalHandlers(): void {
207
+ process.off('SIGINT', onSignal);
208
+ process.off('SIGTERM', onSignal);
209
+ process.off('SIGHUP', onSignal);
210
+ process.off('exit', onExit);
211
+ }
212
+ if (tieLifetimes) {
213
+ process.on('SIGINT', onSignal);
214
+ process.on('SIGTERM', onSignal);
215
+ process.on('SIGHUP', onSignal);
216
+ process.on('exit', onExit);
217
+ }
218
+
219
+ return { server, port: boundPort, client, clientExited, stop };
220
+ }
@@ -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
  }
@@ -19,6 +21,7 @@ export class Connection {
19
21
  readonly id = crypto.randomUUID();
20
22
  authenticated = false;
21
23
  sessionAuthToken: string | undefined;
24
+ refreshAuthToken: string | undefined;
22
25
  sessionId: string | undefined;
23
26
  userName: string | undefined;
24
27
  profile: string[] = [];
@@ -98,9 +98,9 @@ export function routeMessage(
98
98
  case MESSAGE_TYPE.EVENT_LOGIN_AUTH:
99
99
  return handleLogin(message, connection, config, tokens);
100
100
  case MESSAGE_TYPE.EVENT_LOGOUT:
101
- return handleLogout(message, connection);
101
+ return handleLogout(message, connection, tokens);
102
102
  case MESSAGE_TYPE.HEARTBEAT_PING:
103
- return handleHeartbeat(message, connection);
103
+ return handleHeartbeat(message, connection, config);
104
104
  case MESSAGE_TYPE.DATA_LOGON:
105
105
  return handleDataLogon(message, connection, config, store);
106
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,9 +2,10 @@ 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
- import { stampRow } from './protocol/rowUpdate.ts';
8
+ import { stampRow, type RowOperation } from './protocol/rowUpdate.ts';
8
9
  import type {
9
10
  BroadcastFn,
10
11
  BroadcastTableChangeFn,
@@ -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;
@@ -61,34 +67,86 @@ export function createMockServer(config: MockServerConfig): MockServer {
61
67
  // predicate would evaluate against missing fields and drop the push —
62
68
  // leaving the client holding a ghost row. Deliver every DELETE instead: a
63
69
  // client that never held that ROW_REF ignores it.
64
- function subscriptionAccepts(
70
+ // 'error' is kept distinct from 'no-match' because only a clean no-match may
71
+ // be turned into a DELETE below; a broken predicate must not evict rows.
72
+ function evaluateSubscription(
65
73
  subscription: Subscription,
66
74
  sourceRef: string,
67
- operation: 'INSERT' | 'MODIFY' | 'DELETE',
68
75
  row: Row,
69
- ): boolean {
70
- if (operation === 'DELETE') return true;
76
+ ): 'match' | 'no-match' | 'error' {
71
77
  try {
72
- return subscription.predicate(row);
78
+ return subscription.predicate(row) ? 'match' : 'no-match';
73
79
  } catch (error) {
74
80
  console.error(
75
81
  `[mock-server] Error evaluating predicate for subscription ${sourceRef}:`,
76
82
  error,
77
83
  );
78
- return false;
84
+ return 'error';
79
85
  }
80
86
  }
81
87
 
88
+ // The operation to push to one subscription, or null to skip it entirely.
89
+ // A MODIFY that moved the row out of this subscription's CRITERIA_MATCH
90
+ // becomes a DELETE so the client drops it rather than keeping a stale ghost
91
+ // row; a predicate that threw skips instead, since a broken filter must
92
+ // never evict rows.
93
+ function resolveSubscriptionOperation(
94
+ subscription: Subscription,
95
+ sourceRef: string,
96
+ operation: RowOperation,
97
+ row: Row,
98
+ ): RowOperation | null {
99
+ if (operation === 'DELETE') return 'DELETE';
100
+ const verdict = evaluateSubscription(subscription, sourceRef, row);
101
+ if (verdict === 'match') return operation;
102
+ if (verdict === 'error') return null;
103
+ return operation === 'MODIFY' ? 'DELETE' : null;
104
+ }
105
+
82
106
  const broadcast: BroadcastFn = (resourceName, operation, row) => {
107
+ const query = config.queries?.[resourceName];
108
+ // The query's own filter (where-clause equivalent) applies to live pushes
109
+ // too — a row the snapshot would exclude must not leak in via broadcast.
110
+ // A MODIFY that moves a row OUT of the filter is converted to a DELETE
111
+ // rather than dropped: a swallowed removal leaves the client rendering the
112
+ // row with its stale pre-modify values until a full reload. An INSERT
113
+ // outside the filter is simply dropped (the client never held it).
114
+ // DELETEs always go through: dropping an unknown ROW_REF is a no-op.
115
+ let effectiveOperation = operation;
116
+ if (operation !== 'DELETE' && query?.filter && !query.filter(row)) {
117
+ if (operation !== 'MODIFY') return;
118
+ effectiveOperation = 'DELETE';
119
+ }
83
120
  for (const connection of connections) {
84
121
  for (const [sourceRef, subscription] of connection.subscriptions) {
85
122
  if (subscription.resourceName !== resourceName) continue;
86
- if (!subscriptionAccepts(subscription, sourceRef, operation, row)) continue;
123
+ const rowOperation = resolveSubscriptionOperation(
124
+ subscription,
125
+ sourceRef,
126
+ effectiveOperation,
127
+ row,
128
+ );
129
+ if (rowOperation === null) continue;
130
+ // Per-user permissioning (auth maps / hideFields equivalent): the
131
+ // ROW_REF is computed from the unstripped row, since pk fields may
132
+ // themselves be hidden from this user.
133
+ const rowRef = subscription.getRowRef(row);
134
+ let outRow = row;
135
+ if (rowOperation !== operation) {
136
+ // Converted to a DELETE: send the row identity only — it is all the
137
+ // client needs to drop the row, and the full row may carry columns
138
+ // this user's hideFields strips.
139
+ outRow = query ? store.rowStubFromKey(query.source, rowRef as string) : row;
140
+ } else if (rowOperation !== 'DELETE' && query?.auth) {
141
+ const [permitted] = applyResourceAuth([row], query.auth, requestingUser(connection));
142
+ if (!permitted) continue;
143
+ outRow = permitted;
144
+ }
87
145
  subscription.sequenceId += 1;
88
146
  connection.send({
89
147
  MESSAGE_TYPE: 'QUERY_UPDATE',
90
148
  SOURCE_REF: sourceRef,
91
- ROW: [stampRow(row, subscription.pkField, operation)],
149
+ ROW: [stampRow(outRow, rowRef, rowOperation)],
92
150
  ROWS_COUNT: 1,
93
151
  SEQUENCE_ID: subscription.sequenceId,
94
152
  });
@@ -99,22 +157,44 @@ export function createMockServer(config: MockServerConfig): MockServer {
99
157
  // Event handlers mutate one table (e.g. TRADE) but grids may be subscribed to
100
158
  // a view built on top of it (e.g. ALL_TRADES -> TRADE_VIEW). This finds every
101
159
  // 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.
160
+ // the (re-joined, for views) row to each one's subscribers. `pk` is the
161
+ // store key: the single pk field's value, or store.rowKey(...) for
162
+ // composite-keyed tables.
103
163
  const broadcastTableChange: BroadcastTableChangeFn = (tableName, operation, pk) => {
104
164
  for (const [queryName, query] of Object.entries(config.queries ?? {})) {
105
165
  const isDirect = query.source === tableName;
106
166
  const view = store.views.get(query.source);
107
167
  const isViewOnTable = view?.base === tableName;
108
- if (!isDirect && !isViewOnTable) continue;
168
+ // A view that JOINS (or anti-joins) the mutated table denormalizes its
169
+ // columns into every matching base row, so one change can affect any
170
+ // number of view rows — none of them keyed by `pk`. Re-materialize and
171
+ // push the refreshed view instead of dropping the change, or e.g.
172
+ // renaming a COUNTERPARTY never updates COUNTERPARTY_NAME in an open
173
+ // ALL_TRADES grid.
174
+ const isViewJoiningTable =
175
+ !isDirect &&
176
+ !isViewOnTable &&
177
+ ((view?.joins ?? []).some((join) => join.table === tableName) ||
178
+ (view?.antiJoins ?? []).some((antiJoin) => antiJoin.table === tableName));
179
+ if (!isDirect && !isViewOnTable && !isViewJoiningTable) continue;
180
+
181
+ if (isViewJoiningTable) {
182
+ for (const viewRow of store.getViewRows(query.source)) {
183
+ broadcast(queryName, 'MODIFY', viewRow);
184
+ }
185
+ continue;
186
+ }
109
187
 
110
- const pkField = store.getPkField(query.source);
111
188
  let row: Row | undefined;
112
189
  if (operation === 'DELETE') {
113
- row = pkField ? { [pkField]: pk } : undefined;
190
+ const stub = store.rowStubFromKey(query.source, pk);
191
+ row = Object.keys(stub).length > 0 ? stub : undefined;
114
192
  } else if (isDirect) {
115
193
  row = store.getRow(tableName, pk);
116
194
  } else {
117
- row = store.getViewRows(query.source).find((r) => r[pkField!] === pk);
195
+ row = store
196
+ .getViewRows(query.source)
197
+ .find((r) => String(store.getRowRef(query.source, r)) === String(pk));
118
198
  }
119
199
  if (row) broadcast(queryName, operation, row);
120
200
  }
@@ -222,6 +302,19 @@ export function createMockServer(config: MockServerConfig): MockServer {
222
302
  return;
223
303
  }
224
304
  try {
305
+ // Inbound hook: lets a project rewrite messages before routing
306
+ // (e.g. normalize a CRITERIA_MATCH dialect) or handle them fully
307
+ // itself (return false) — instead of monkey-patching ws.on.
308
+ if (config.onMessage) {
309
+ const hooked = config.onMessage(message, {
310
+ connection,
311
+ store,
312
+ broadcast,
313
+ broadcastTableChange,
314
+ });
315
+ if (hooked === false) return;
316
+ if (hooked) message = hooked;
317
+ }
225
318
  routeMessage(
226
319
  message,
227
320
  connection,
@@ -241,15 +334,49 @@ export function createMockServer(config: MockServerConfig): MockServer {
241
334
  });
242
335
 
243
336
  httpServer.listen(port);
244
- console.log(
245
- `[mock-server] Listening on ws://localhost:${port} (HTTP login endpoints on the same port)`,
246
- );
337
+ // Log the ACTUAL bound port once listening — with port 0 (ephemeral, the
338
+ // parallel-servers pattern) the requested port would read "0".
339
+ httpServer.once('listening', () => {
340
+ console.log(
341
+ `[mock-server] Listening on ws://localhost:${boundPort()} (HTTP login endpoints on the same port)`,
342
+ );
343
+ });
247
344
  return wss;
248
345
  }
249
346
 
347
+ function boundPort(): number | undefined {
348
+ const address = httpServer?.address();
349
+ return typeof address === 'object' && address ? address.port : undefined;
350
+ }
351
+
352
+ // start() + resolve with the OS-assigned port once actually listening.
353
+ // Pass no argument (port 0) to run any number of servers side by side —
354
+ // each instance's store/connections/sessions are fully isolated already,
355
+ // so parallel test workers just call listen() and hand the returned port
356
+ // to their own client (API_HOST=ws://localhost:<port>).
357
+ function listen(port = 0): Promise<number> {
358
+ return new Promise((resolve, reject) => {
359
+ if (httpServer?.listening) {
360
+ resolve(boundPort()!);
361
+ return;
362
+ }
363
+ if (!httpServer) start(port);
364
+ httpServer!.once('error', reject);
365
+ httpServer!.once('listening', () => resolve(boundPort()!));
366
+ });
367
+ }
368
+
250
369
  function stop(): Promise<void> {
251
370
  return new Promise((resolve) => {
252
- if (!wss || !httpServer) {
371
+ // Release the handles up front: a closed http.Server can never emit
372
+ // 'listening' again, so leaving them set makes a later listen() wait
373
+ // forever instead of starting a fresh server (restart-between-tests
374
+ // harnesses deadlock with no error).
375
+ const socketServer = wss;
376
+ const server = httpServer;
377
+ wss = undefined;
378
+ httpServer = undefined;
379
+ if (!socketServer || !server) {
253
380
  resolve();
254
381
  return;
255
382
  }
@@ -258,17 +385,18 @@ export function createMockServer(config: MockServerConfig): MockServer {
258
385
  // — so with a browser still attached, a plain close chain never resolves
259
386
  // (and the showcase's SIGINT handler would hang forever). Terminate WS
260
387
  // clients and drop idle keep-alive HTTP sockets explicitly first.
261
- for (const client of wss.clients) client.terminate();
262
- wss.close(() => {
263
- httpServer!.close(() => resolve());
388
+ for (const client of socketServer.clients) client.terminate();
389
+ socketServer.close(() => {
390
+ server.close(() => resolve());
264
391
  // Node >=18.2; optional-called because Bun's node:http may lack it.
265
- httpServer!.closeAllConnections?.();
392
+ server.closeAllConnections?.();
266
393
  });
267
394
  });
268
395
  }
269
396
 
270
397
  return {
271
398
  start,
399
+ listen,
272
400
  stop,
273
401
  store,
274
402
  broadcast,