@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
package/dist/launch.js ADDED
@@ -0,0 +1,164 @@
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
+ import { spawn } from 'node:child_process';
6
+ import { createMockServer } from "./server.js";
7
+ // How long a client gets to exit on SIGINT before it is killed outright. A dev
8
+ // server that ignores the signal must not keep its port (or hang stop()).
9
+ const CLIENT_EXIT_GRACE_MS = 5000;
10
+ // How often the watchdog checks whether the launcher is still alive.
11
+ const WATCHDOG_POLL_MS = 500;
12
+ // Signals the client tree, not just the direct child. The client command is
13
+ // normally a launcher itself (genx -> vite -> esbuild), so signalling only the
14
+ // immediate pid can leave grandchildren holding the port. `detached: true`
15
+ // makes the child a process-group leader, and a negative pid addresses that
16
+ // whole group.
17
+ function killClientTree(client, signal) {
18
+ if (client.pid === undefined || client.exitCode !== null || client.signalCode !== null)
19
+ return;
20
+ try {
21
+ process.kill(-client.pid, signal);
22
+ }
23
+ catch {
24
+ // No process group (Windows, or the group is already gone) — fall back to
25
+ // the single child.
26
+ try {
27
+ client.kill(signal);
28
+ }
29
+ catch {
30
+ // Already exited between the check and the signal; nothing to do.
31
+ }
32
+ }
33
+ }
34
+ // Nothing in THIS process runs when it is SIGKILLed or dies with the terminal,
35
+ // so parent-death cleanup cannot live here: the client would be reparented to
36
+ // init and keep serving its port forever (verified — a hard-killed launcher
37
+ // leaves vite listening). This tiny detached watcher polls for the launcher
38
+ // and takes the client's process group down with it. It also exits as soon as
39
+ // the client is gone, so it can never outlive the pair it is watching.
40
+ const WATCHDOG_SOURCE = `
41
+ const [launcher, target] = process.argv.slice(1).map(Number);
42
+ const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
43
+ const stop = (sig) => { try { process.kill(-target, sig); } catch { try { process.kill(target, sig); } catch {} } };
44
+ const timer = setInterval(() => {
45
+ if (!alive(target)) { clearInterval(timer); process.exit(0); }
46
+ if (alive(launcher)) return;
47
+ clearInterval(timer);
48
+ stop('SIGTERM');
49
+ setTimeout(() => { stop('SIGKILL'); process.exit(0); }, ${CLIENT_EXIT_GRACE_MS});
50
+ }, ${WATCHDOG_POLL_MS});
51
+ `;
52
+ function startWatchdog(clientPid) {
53
+ try {
54
+ const watchdog = spawn(process.execPath, ['-e', WATCHDOG_SOURCE, String(process.pid), String(clientPid)], { detached: true, stdio: 'ignore' });
55
+ // Detached + unref'd so it survives a hard kill of this process and never
56
+ // holds this process's event loop open.
57
+ watchdog.unref();
58
+ return watchdog;
59
+ }
60
+ catch (error) {
61
+ console.warn('[mock-server] Could not start the client watchdog:', error);
62
+ return undefined;
63
+ }
64
+ }
65
+ export async function launchStack(options) {
66
+ const { config, clientCommand, port = 0, cwd, clientEnv, tieLifetimes = true, clientExitGraceMs = CLIENT_EXIT_GRACE_MS, } = options;
67
+ const server = createMockServer(config);
68
+ const boundPort = await server.listen(port);
69
+ const env = {
70
+ ...process.env,
71
+ API_HOST: `ws://localhost:${boundPort}`,
72
+ ...clientEnv?.(boundPort),
73
+ };
74
+ // detached: the client leads its own process group so the whole tree can be
75
+ // signalled at once. It also means a terminal Ctrl+C no longer reaches the
76
+ // client directly — it reaches this process, whose SIGINT handler below
77
+ // tears the group down, so shutdown always takes one controlled path.
78
+ const client = Array.isArray(clientCommand)
79
+ ? spawn(clientCommand[0], clientCommand.slice(1), {
80
+ cwd,
81
+ env,
82
+ stdio: 'inherit',
83
+ detached: true,
84
+ })
85
+ : spawn(clientCommand, { cwd, env, stdio: 'inherit', shell: true, detached: true });
86
+ const watchdog = tieLifetimes && client.pid !== undefined ? startWatchdog(client.pid) : undefined;
87
+ function cleanupWatchdog() {
88
+ if (watchdog?.pid === undefined)
89
+ return;
90
+ try {
91
+ process.kill(watchdog.pid, 'SIGKILL');
92
+ }
93
+ catch {
94
+ // Already exited on noticing the client was gone.
95
+ }
96
+ }
97
+ // Resolves once the client tree is actually down, so stop() means everything
98
+ // is stopped rather than merely signalled.
99
+ function stopClient() {
100
+ if (client.pid === undefined || client.exitCode !== null || client.signalCode !== null) {
101
+ return Promise.resolve();
102
+ }
103
+ return new Promise((resolve) => {
104
+ const escalate = setTimeout(() => killClientTree(client, 'SIGKILL'), clientExitGraceMs);
105
+ client.once('exit', () => {
106
+ clearTimeout(escalate);
107
+ resolve();
108
+ });
109
+ killClientTree(client, 'SIGINT');
110
+ });
111
+ }
112
+ let stopping = false;
113
+ async function stop() {
114
+ if (stopping)
115
+ return;
116
+ stopping = true;
117
+ removeSignalHandlers();
118
+ cleanupWatchdog();
119
+ await Promise.all([stopClient(), server.stop()]);
120
+ }
121
+ const clientExited = new Promise((resolve) => {
122
+ const settle = (code) => {
123
+ if (!tieLifetimes) {
124
+ resolve(code);
125
+ return;
126
+ }
127
+ stopping = true;
128
+ removeSignalHandlers();
129
+ cleanupWatchdog();
130
+ const finish = () => resolve(code);
131
+ server.stop().then(finish, finish);
132
+ };
133
+ client.once('exit', (code) => settle(code));
134
+ client.once('error', (error) => {
135
+ console.error('[mock-server] Failed to spawn client command:', error);
136
+ settle(null);
137
+ });
138
+ });
139
+ // Every path this process can still observe tears the client group down.
140
+ // SIGHUP matters for a closing terminal; 'exit' catches a plain return or an
141
+ // uncaught throw. (A SIGKILL of this process runs none of them — that is
142
+ // what the watchdog above is for.)
143
+ const onSignal = () => {
144
+ void stop();
145
+ };
146
+ const onExit = () => {
147
+ // Synchronous only: no async work runs during 'exit'.
148
+ cleanupWatchdog();
149
+ killClientTree(client, 'SIGKILL');
150
+ };
151
+ function removeSignalHandlers() {
152
+ process.off('SIGINT', onSignal);
153
+ process.off('SIGTERM', onSignal);
154
+ process.off('SIGHUP', onSignal);
155
+ process.off('exit', onExit);
156
+ }
157
+ if (tieLifetimes) {
158
+ process.on('SIGINT', onSignal);
159
+ process.on('SIGTERM', onSignal);
160
+ process.on('SIGHUP', onSignal);
161
+ process.on('exit', onExit);
162
+ }
163
+ return { server, port: boundPort, client, clientExited, stop };
164
+ }
@@ -0,0 +1,25 @@
1
+ import type { Predicate } from '../db/criteria.ts';
2
+ import type { GenesisMessage, Row, SocketLike } from '../types.ts';
3
+ export interface Subscription {
4
+ resourceName: string;
5
+ getRowRef: (row: Row) => unknown;
6
+ predicate: Predicate;
7
+ sequenceId: number;
8
+ }
9
+ export declare class Connection {
10
+ readonly ws: SocketLike;
11
+ readonly id: `${string}-${string}-${string}-${string}-${string}`;
12
+ authenticated: boolean;
13
+ sessionAuthToken: string | undefined;
14
+ refreshAuthToken: string | undefined;
15
+ sessionId: string | undefined;
16
+ userName: string | undefined;
17
+ profile: string[];
18
+ permission: string[];
19
+ readonly subscriptions: Map<string, Subscription>;
20
+ constructor(ws: SocketLike);
21
+ send(payload: Row): void;
22
+ reply(requestMessage: GenesisMessage, payload: Row): void;
23
+ subscribe(sourceRef: string, subscription: Subscription): void;
24
+ unsubscribe(sourceRef: string): void;
25
+ }
@@ -0,0 +1,36 @@
1
+ import crypto from 'node:crypto';
2
+ const WS_OPEN = 1;
3
+ // Wraps one WebSocket client connection: auth state and its live DATA_LOGON
4
+ // subscriptions (keyed by SOURCE_REF, since that's the client's sole correlation
5
+ // key — see README pitfall #1).
6
+ export class Connection {
7
+ ws;
8
+ id = crypto.randomUUID();
9
+ authenticated = false;
10
+ sessionAuthToken;
11
+ refreshAuthToken;
12
+ sessionId;
13
+ userName;
14
+ profile = [];
15
+ permission = [];
16
+ subscriptions = new Map();
17
+ constructor(ws) {
18
+ this.ws = ws;
19
+ }
20
+ // Every response must echo the request's SOURCE_REF verbatim, or the client's
21
+ // pending promise for that call never resolves (silent hang, no error).
22
+ send(payload) {
23
+ if (this.ws.readyState !== WS_OPEN)
24
+ return;
25
+ this.ws.send(JSON.stringify(payload));
26
+ }
27
+ reply(requestMessage, payload) {
28
+ this.send({ ...payload, SOURCE_REF: requestMessage.SOURCE_REF });
29
+ }
30
+ subscribe(sourceRef, subscription) {
31
+ this.subscriptions.set(sourceRef, subscription);
32
+ }
33
+ unsubscribe(sourceRef) {
34
+ this.subscriptions.delete(sourceRef);
35
+ }
36
+ }
@@ -0,0 +1,17 @@
1
+ export interface NackErrorInput {
2
+ CODE?: string;
3
+ code?: string;
4
+ TEXT?: string;
5
+ text?: string;
6
+ FIELD?: string;
7
+ field?: string;
8
+ }
9
+ export interface NackErrorEntry {
10
+ CODE: string;
11
+ TEXT: string;
12
+ FIELD?: string;
13
+ }
14
+ export declare class NackError extends Error {
15
+ readonly errors: NackErrorEntry[];
16
+ constructor(errors: NackErrorInput | NackErrorInput[]);
17
+ }
@@ -0,0 +1,16 @@
1
+ // Throw this from an event handler / request-reply resolver to produce a
2
+ // protocol-correct *_NACK with ERROR as an array of {CODE, TEXT, FIELD?} —
3
+ // never {error, details} (lowercase, non-array), which crashes real clients
4
+ // calling .forEach on the wrong shape.
5
+ export class NackError extends Error {
6
+ errors;
7
+ constructor(errors) {
8
+ const list = Array.isArray(errors) ? errors : [errors];
9
+ super(list.map((e) => e.TEXT ?? e.text ?? 'Unknown error').join(', '));
10
+ this.errors = list.map((e) => ({
11
+ CODE: e.CODE ?? e.code ?? 'VALIDATION_ERROR',
12
+ TEXT: e.TEXT ?? e.text ?? 'Unknown error',
13
+ ...(e.FIELD || e.field ? { FIELD: e.FIELD ?? e.field } : {}),
14
+ }));
15
+ }
16
+ }
@@ -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, tokens);
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;