@genesislcap/mock-server 15.7.3-alpha-94532c4.0 → 15.7.3-alpha-e7d4aa5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +212 -37
- package/dist/db/criteria.d.ts +5 -0
- package/dist/db/criteria.js +304 -0
- package/dist/db/metadata.d.ts +3 -0
- package/dist/db/metadata.js +35 -0
- package/dist/db/store.d.ts +27 -0
- package/dist/db/store.js +226 -0
- package/dist/handlers/auth.d.ts +9 -0
- package/dist/handlers/auth.js +99 -0
- package/dist/handlers/commitEvent.d.ts +8 -0
- package/dist/handlers/commitEvent.js +40 -0
- package/dist/handlers/dataLogon.d.ts +5 -0
- package/dist/handlers/dataLogon.js +46 -0
- package/dist/handlers/heartbeat.d.ts +3 -0
- package/dist/handlers/heartbeat.js +16 -0
- package/dist/handlers/http.d.ts +4 -0
- package/dist/handlers/http.js +165 -0
- package/dist/handlers/jsonSchema.d.ts +5 -0
- package/dist/handlers/jsonSchema.js +77 -0
- package/dist/handlers/meta.d.ts +4 -0
- package/dist/handlers/meta.js +42 -0
- package/dist/handlers/requestReply.d.ts +4 -0
- package/dist/handlers/requestReply.js +68 -0
- package/dist/handlers/resourceAuth.d.ts +5 -0
- package/dist/handlers/resourceAuth.js +27 -0
- package/dist/handlers/resources.d.ts +3 -0
- package/dist/handlers/resources.js +34 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/launch.d.ts +19 -0
- package/dist/launch.js +59 -0
- package/dist/protocol/connection.d.ts +24 -0
- package/dist/protocol/connection.js +35 -0
- package/dist/protocol/errors.d.ts +17 -0
- package/dist/protocol/errors.js +16 -0
- package/dist/protocol/messageTypes.d.ts +28 -0
- package/dist/protocol/messageTypes.js +42 -0
- package/dist/protocol/router.d.ts +6 -0
- package/dist/protocol/router.js +101 -0
- package/dist/protocol/rowUpdate.d.ts +4 -0
- package/dist/protocol/rowUpdate.js +17 -0
- package/dist/server.d.ts +23 -0
- package/dist/server.js +274 -0
- package/dist/types.d.ts +142 -0
- package/dist/types.js +4 -0
- package/package.json +16 -6
- package/src/db/criteria.ts +53 -21
- package/src/db/store.ts +100 -27
- package/src/handlers/commitEvent.ts +4 -1
- package/src/handlers/dataLogon.ts +11 -4
- package/src/handlers/heartbeat.ts +16 -3
- package/src/handlers/http.ts +27 -0
- package/src/handlers/jsonSchema.ts +3 -3
- package/src/handlers/meta.ts +11 -3
- package/src/handlers/requestReply.ts +22 -8
- package/src/handlers/resourceAuth.ts +37 -0
- package/src/handlers/resources.ts +8 -1
- package/src/index.ts +9 -0
- package/src/launch.ts +95 -0
- package/src/protocol/connection.ts +3 -1
- package/src/protocol/router.ts +1 -1
- package/src/protocol/rowUpdate.ts +5 -4
- package/src/server.ts +73 -8
- package/src/types.ts +124 -3
- package/test/criteria.test.ts +0 -174
- package/test/jsonSchema.test.ts +0 -38
- package/test/metadata.test.ts +0 -49
- package/test/server.test.ts +0 -308
- package/test/store.test.ts +0 -181
- package/tsconfig.json +0 -18
package/src/db/store.ts
CHANGED
|
@@ -6,11 +6,25 @@ import type { Row, TableDef, ViewDef } from '../types.ts';
|
|
|
6
6
|
type Pk = string;
|
|
7
7
|
|
|
8
8
|
interface TableConfig {
|
|
9
|
-
|
|
9
|
+
pkFields: string[];
|
|
10
10
|
sequencePrefix?: string;
|
|
11
11
|
sequenceWidth: number;
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
+
// Composite keys join the pk fields' values with '|' (so values must not
|
|
15
|
+
// contain '|'). Single-field keys stay the raw value, preserving
|
|
16
|
+
// getRow('TABLE', 'TR001')-style lookups.
|
|
17
|
+
const COMPOSITE_KEY_SEPARATOR = '|';
|
|
18
|
+
|
|
19
|
+
function normalizePkFields(pkField: string | string[]): string[] {
|
|
20
|
+
return Array.isArray(pkField) ? pkField : [pkField];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function keyFor(pkFields: string[], row: Row): Pk {
|
|
24
|
+
if (pkFields.length === 1) return row[pkFields[0]];
|
|
25
|
+
return pkFields.map((field) => String(row[field])).join(COMPOSITE_KEY_SEPARATOR);
|
|
26
|
+
}
|
|
27
|
+
|
|
14
28
|
export class Store {
|
|
15
29
|
private tables = new Map<string, Map<Pk, Row>>();
|
|
16
30
|
private tableConfig = new Map<string, TableConfig>();
|
|
@@ -25,21 +39,23 @@ export class Store {
|
|
|
25
39
|
tableName: string,
|
|
26
40
|
{ pkField, sequencePrefix, sequenceWidth = 3, rows = [] }: TableDef,
|
|
27
41
|
): this {
|
|
42
|
+
const pkFields = normalizePkFields(pkField);
|
|
28
43
|
const table = new Map<Pk, Row>();
|
|
29
44
|
for (const row of rows) {
|
|
30
|
-
table.set(row
|
|
45
|
+
table.set(keyFor(pkFields, row), { ...row });
|
|
31
46
|
}
|
|
32
47
|
this.tables.set(tableName, table);
|
|
33
|
-
this.tableConfig.set(tableName, {
|
|
48
|
+
this.tableConfig.set(tableName, { pkFields, sequencePrefix, sequenceWidth });
|
|
34
49
|
this.seedRows.set(
|
|
35
50
|
tableName,
|
|
36
51
|
rows.map((row) => ({ ...row })),
|
|
37
52
|
);
|
|
38
53
|
|
|
39
|
-
|
|
54
|
+
// Sequence generation only makes sense for a single-field pk.
|
|
55
|
+
if (sequencePrefix && pkFields.length === 1) {
|
|
40
56
|
let maxN = 0;
|
|
41
57
|
for (const row of rows) {
|
|
42
|
-
const pk = String(row[
|
|
58
|
+
const pk = String(row[pkFields[0]] ?? '');
|
|
43
59
|
if (pk.startsWith(sequencePrefix)) {
|
|
44
60
|
const n = parseInt(pk.slice(sequencePrefix.length), 10);
|
|
45
61
|
if (Number.isFinite(n)) maxN = Math.max(maxN, n);
|
|
@@ -71,16 +87,26 @@ export class Store {
|
|
|
71
87
|
return this.tables.get(tableName)?.get(pk);
|
|
72
88
|
}
|
|
73
89
|
|
|
74
|
-
//
|
|
75
|
-
//
|
|
76
|
-
//
|
|
90
|
+
// The storage/broadcast key for a row: the pk field's value, or for
|
|
91
|
+
// composite-keyed tables the pk fields' values joined with '|'. Event
|
|
92
|
+
// handlers on composite tables pass this to broadcastTableChange.
|
|
93
|
+
rowKey(tableName: string, row: Row): Pk {
|
|
94
|
+
const config = this.tableConfig.get(tableName);
|
|
95
|
+
if (!config) throw new Error(`Unknown table: ${tableName}`);
|
|
96
|
+
return keyFor(config.pkFields, row);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Fallback matching for tables where the caller doesn't have the full key:
|
|
100
|
+
// try the pk field(s) first, then any single field that uniquely identifies
|
|
101
|
+
// one row, then the full combination of provided fields.
|
|
77
102
|
findRow(tableName: string, criteria: Row): Row | undefined {
|
|
78
103
|
const table = this.tables.get(tableName);
|
|
79
104
|
if (!table) return undefined;
|
|
80
|
-
const {
|
|
105
|
+
const { pkFields } = this.tableConfig.get(tableName) ?? { pkFields: [] };
|
|
81
106
|
|
|
82
|
-
if (
|
|
83
|
-
|
|
107
|
+
if (pkFields.length > 0 && pkFields.every((field) => criteria[field] !== undefined)) {
|
|
108
|
+
const byKey = table.get(keyFor(pkFields, criteria));
|
|
109
|
+
if (byKey) return byKey;
|
|
84
110
|
}
|
|
85
111
|
|
|
86
112
|
const rows = Array.from(table.values());
|
|
@@ -100,15 +126,20 @@ export class Store {
|
|
|
100
126
|
if (!table || !config) throw new Error(`Unknown table: ${tableName}`);
|
|
101
127
|
|
|
102
128
|
const row = { ...record };
|
|
103
|
-
if (
|
|
104
|
-
|
|
129
|
+
if (
|
|
130
|
+
config.pkFields.length === 1 &&
|
|
131
|
+
row[config.pkFields[0]] === undefined &&
|
|
132
|
+
config.sequencePrefix
|
|
133
|
+
) {
|
|
134
|
+
row[config.pkFields[0]] = this.nextSequenceValue(config.sequencePrefix, config.sequenceWidth);
|
|
105
135
|
}
|
|
106
|
-
|
|
136
|
+
const missing = config.pkFields.filter((field) => row[field] === undefined);
|
|
137
|
+
if (missing.length > 0) {
|
|
107
138
|
throw new Error(
|
|
108
|
-
`Primary key '${
|
|
139
|
+
`Primary key field(s) '${missing.join("', '")}' are required for inserting into table '${tableName}'`,
|
|
109
140
|
);
|
|
110
141
|
}
|
|
111
|
-
table.set(
|
|
142
|
+
table.set(keyFor(config.pkFields, row), row);
|
|
112
143
|
return row;
|
|
113
144
|
}
|
|
114
145
|
|
|
@@ -126,7 +157,9 @@ export class Store {
|
|
|
126
157
|
return table.delete(pk);
|
|
127
158
|
}
|
|
128
159
|
|
|
129
|
-
// Materializes a view: base table left-joined to related tables
|
|
160
|
+
// Materializes a view: base table left-joined to related tables (optionally
|
|
161
|
+
// narrowed by per-join `where` predicates), minus anti-joined rows, plus
|
|
162
|
+
// derived fields.
|
|
130
163
|
getViewRows(viewName: string): Row[] {
|
|
131
164
|
const view = this.views.get(viewName);
|
|
132
165
|
if (!view) throw new Error(`Unknown view: ${viewName}`);
|
|
@@ -136,13 +169,34 @@ export class Store {
|
|
|
136
169
|
private materializeView(view: ViewDef, getRows: (tableName: string) => Row[]): Row[] {
|
|
137
170
|
let rows = getRows(view.base).map((row) => ({ ...row }));
|
|
138
171
|
|
|
172
|
+
for (const antiJoin of view.antiJoins ?? []) {
|
|
173
|
+
const joinRows = getRows(antiJoin.table);
|
|
174
|
+
rows = rows.filter(
|
|
175
|
+
(row) =>
|
|
176
|
+
!joinRows.some(
|
|
177
|
+
(joinRow) =>
|
|
178
|
+
joinRow[antiJoin.on[1]] === row[antiJoin.on[0]] &&
|
|
179
|
+
(antiJoin.where?.(joinRow, row) ?? true),
|
|
180
|
+
),
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
|
|
139
184
|
for (const join of view.joins ?? []) {
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
185
|
+
const joinRows = getRows(join.table);
|
|
186
|
+
// A `where` predicate sees the base row, so an index keyed on the `on`
|
|
187
|
+
// field alone can't answer it — scan per base row instead.
|
|
188
|
+
const joinIndex = join.where ? undefined : new Map<unknown, Row>();
|
|
189
|
+
if (joinIndex) {
|
|
190
|
+
for (const row of joinRows) {
|
|
191
|
+
joinIndex.set(row[join.on[1]], row);
|
|
192
|
+
}
|
|
143
193
|
}
|
|
144
194
|
rows = rows.map((row) => {
|
|
145
|
-
const match = joinIndex
|
|
195
|
+
const match = joinIndex
|
|
196
|
+
? joinIndex.get(row[join.on[0]])
|
|
197
|
+
: joinRows.find(
|
|
198
|
+
(joinRow) => joinRow[join.on[1]] === row[join.on[0]] && join.where!(joinRow, row),
|
|
199
|
+
);
|
|
146
200
|
const merged = { ...row };
|
|
147
201
|
for (const [alias, sourceField] of Object.entries(join.select ?? {})) {
|
|
148
202
|
merged[alias] = match?.[sourceField];
|
|
@@ -184,12 +238,31 @@ export class Store {
|
|
|
184
238
|
return this.seedRows.get(resourceName) ?? [];
|
|
185
239
|
}
|
|
186
240
|
|
|
187
|
-
// Row-identity
|
|
188
|
-
|
|
189
|
-
// client-side, which keys inserts/amends/deletes off this field).
|
|
190
|
-
getPkField(resourceName: string): string | undefined {
|
|
241
|
+
// Row-identity fields for a table or view; empty when unknown.
|
|
242
|
+
getPkFields(resourceName: string): string[] {
|
|
191
243
|
const view = this.views.get(resourceName);
|
|
192
|
-
if (view)
|
|
193
|
-
|
|
244
|
+
if (view) {
|
|
245
|
+
if (view.pkField) return normalizePkFields(view.pkField);
|
|
246
|
+
return this.tableConfig.get(view.base)?.pkFields ?? [];
|
|
247
|
+
}
|
|
248
|
+
return this.tableConfig.get(resourceName)?.pkFields ?? [];
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// The DETAILS.ROW_REF value stamped on QUERY_UPDATE rows (see
|
|
252
|
+
// protocol/rowUpdate.ts): the pk field's value, or the composite key. The
|
|
253
|
+
// client's dataServerResultFilter keys inserts/amends/deletes off this.
|
|
254
|
+
getRowRef(resourceName: string, row: Row): unknown {
|
|
255
|
+
const pkFields = this.getPkFields(resourceName);
|
|
256
|
+
if (pkFields.length === 0) return undefined;
|
|
257
|
+
return keyFor(pkFields, row);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// Rebuilds a DELETE stub row carrying the pk field(s) from a stored key, so
|
|
261
|
+
// subscribers can be told which row to drop after it's already gone.
|
|
262
|
+
rowStubFromKey(resourceName: string, key: Pk): Row {
|
|
263
|
+
const pkFields = this.getPkFields(resourceName);
|
|
264
|
+
if (pkFields.length <= 1) return pkFields.length ? { [pkFields[0]]: key } : {};
|
|
265
|
+
const parts = String(key).split(COMPOSITE_KEY_SEPARATOR);
|
|
266
|
+
return Object.fromEntries(pkFields.map((field, i) => [field, parts[i]]));
|
|
194
267
|
}
|
|
195
268
|
}
|
|
@@ -26,7 +26,10 @@ export function handleCommitEvent(
|
|
|
26
26
|
ctx: CommitEventCtx,
|
|
27
27
|
): void {
|
|
28
28
|
const eventName = message.MESSAGE_TYPE;
|
|
29
|
-
|
|
29
|
+
// defaultEventHandler catches anything unregistered — lets projects with
|
|
30
|
+
// dozens of commit events adopt incrementally (e.g. `() => ({})` to ack
|
|
31
|
+
// everything unhandled) instead of enumerating ack-only handlers.
|
|
32
|
+
const handler = config.eventHandlers?.[eventName] ?? config.defaultEventHandler;
|
|
30
33
|
|
|
31
34
|
// Replies use the GENERIC EVENT_ACK/EVENT_NACK — correlation is purely via
|
|
32
35
|
// SOURCE_REF. See the note on MESSAGE_TYPE in protocol/messageTypes.ts:
|
|
@@ -4,6 +4,7 @@ import type { Connection } from '../protocol/connection.ts';
|
|
|
4
4
|
import { MESSAGE_TYPE, ERROR_CODE } from '../protocol/messageTypes.ts';
|
|
5
5
|
import { stampRows } from '../protocol/rowUpdate.ts';
|
|
6
6
|
import type { GenesisMessage, MockServerConfig } from '../types.ts';
|
|
7
|
+
import { applyResourceAuth, requestingUser } from './resourceAuth.ts';
|
|
7
8
|
|
|
8
9
|
// DATA_LOGON opens a persistent subscription keyed by SOURCE_REF: reply with an
|
|
9
10
|
// initial snapshot, then keep the SOURCE_REF registered so later inserts/amends/
|
|
@@ -28,19 +29,25 @@ export function handleDataLogon(
|
|
|
28
29
|
}
|
|
29
30
|
|
|
30
31
|
const criteria = details.CRITERIA_MATCH;
|
|
31
|
-
const
|
|
32
|
-
|
|
32
|
+
const user = requestingUser(connection);
|
|
33
|
+
// Order matters: the query's own filter (the where-clause equivalent) and
|
|
34
|
+
// the user's row permissioning narrow the set BEFORE the client's
|
|
35
|
+
// CRITERIA_MATCH; hidden fields are stripped last, off the final rows.
|
|
36
|
+
let rows = store.getResourceRows(query.source);
|
|
37
|
+
if (query.filter) rows = rows.filter(query.filter);
|
|
38
|
+
rows = filterByCriteria(rows, criteria);
|
|
39
|
+
rows = applyResourceAuth(rows, query.auth, user);
|
|
33
40
|
|
|
34
41
|
connection.subscribe(message.SOURCE_REF!, {
|
|
35
42
|
resourceName,
|
|
36
|
-
|
|
43
|
+
getRowRef: (row) => store.getRowRef(query.source, row),
|
|
37
44
|
predicate: compileCriteria(criteria),
|
|
38
45
|
sequenceId: 1,
|
|
39
46
|
});
|
|
40
47
|
|
|
41
48
|
connection.reply(message, {
|
|
42
49
|
MESSAGE_TYPE: MESSAGE_TYPE.QUERY_UPDATE,
|
|
43
|
-
ROW: stampRows(rows,
|
|
50
|
+
ROW: stampRows(rows, (row) => store.getRowRef(query.source, row), 'INSERT'),
|
|
44
51
|
ROWS_COUNT: rows.length,
|
|
45
52
|
SEQUENCE_ID: 1,
|
|
46
53
|
MORE_ROWS: false,
|
|
@@ -1,10 +1,23 @@
|
|
|
1
1
|
import type { Connection } from '../protocol/connection.ts';
|
|
2
2
|
import { MESSAGE_TYPE } from '../protocol/messageTypes.ts';
|
|
3
|
-
import type { GenesisMessage } from '../types.ts';
|
|
3
|
+
import type { GenesisMessage, MockServerConfig } from '../types.ts';
|
|
4
4
|
|
|
5
|
-
export function handleHeartbeat(
|
|
5
|
+
export function handleHeartbeat(
|
|
6
|
+
message: GenesisMessage,
|
|
7
|
+
connection: Connection,
|
|
8
|
+
config: MockServerConfig,
|
|
9
|
+
): void {
|
|
10
|
+
// With the auth gate off (the default), this server accepts every data
|
|
11
|
+
// message — so the pong must report IS_AUTHENTICATED: true even though the
|
|
12
|
+
// WS connection itself never "logged in". HTTP-login clients (httpAutoLogin
|
|
13
|
+
// included) send no SESSION_AUTH_TOKEN on WS messages, so
|
|
14
|
+
// connection.authenticated stays false forever on their connections; report
|
|
15
|
+
// that raw flag and the client treats the session as dead and tears it
|
|
16
|
+
// down, defeating httpAutoLogin entirely. Only when a project opts into
|
|
17
|
+
// auth.requireAuth does the flag reflect real connection auth state.
|
|
18
|
+
const requireAuth = config.auth?.requireAuth ?? false;
|
|
6
19
|
connection.reply(message, {
|
|
7
20
|
MESSAGE_TYPE: MESSAGE_TYPE.HEARTBEAT_PONG,
|
|
8
|
-
IS_AUTHENTICATED: connection.authenticated,
|
|
21
|
+
IS_AUTHENTICATED: connection.authenticated || !requireAuth,
|
|
9
22
|
});
|
|
10
23
|
}
|
package/src/handlers/http.ts
CHANGED
|
@@ -88,6 +88,33 @@ export function createHttpRequestListener(
|
|
|
88
88
|
const pathname = (req.url ?? '').split('?')[0];
|
|
89
89
|
|
|
90
90
|
try {
|
|
91
|
+
// Project-defined routes run first (see HttpRouteDef) — endpoints the
|
|
92
|
+
// protocol doesn't cover (e.g. GET pbi/configs), or overrides of the
|
|
93
|
+
// built-ins below.
|
|
94
|
+
const route = (config.httpRoutes ?? []).find(
|
|
95
|
+
(candidate) =>
|
|
96
|
+
(!candidate.method || candidate.method.toUpperCase() === req.method) &&
|
|
97
|
+
(typeof candidate.path === 'string'
|
|
98
|
+
? pathname.endsWith(candidate.path)
|
|
99
|
+
: candidate.path.test(pathname)),
|
|
100
|
+
);
|
|
101
|
+
if (route) {
|
|
102
|
+
await route.handler(req, res);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// foundation-auth's login screen fetches this whenever SSO is toggled
|
|
107
|
+
// on, and treats both a failed fetch and an empty IDPS list as fatal
|
|
108
|
+
// (red error, credentials form hidden). Serve the configured providers,
|
|
109
|
+
// or one non-functional placeholder so the screen still renders.
|
|
110
|
+
if (req.method === 'GET' && pathname.endsWith('sso/list')) {
|
|
111
|
+
const idps = config.auth?.ssoIdentityProviders ?? [
|
|
112
|
+
{ ID: 'mock-sso', DESCRIPTION: 'Mock SSO (placeholder, not functional)', TYPE: 'saml' },
|
|
113
|
+
];
|
|
114
|
+
sendJson(res, HTTP_STATUS.OK, { IDPS: idps });
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
|
|
91
118
|
// Cookie-based silent login on app load — auto-authenticates as the
|
|
92
119
|
// configured user when config.auth.httpAutoLogin is set, so the login
|
|
93
120
|
// screen never appears (matches how a real session cookie would behave
|
|
@@ -82,11 +82,11 @@ export function handleJsonSchemaRequest(
|
|
|
82
82
|
}
|
|
83
83
|
|
|
84
84
|
const pkOnly = override?.pkOnly ?? DELETE_EVENT_RE.test(eventName!);
|
|
85
|
-
const
|
|
85
|
+
const pkFields = store.getPkFields(table);
|
|
86
86
|
let fields = deriveFields(store.getMetadataRows(table), override?.fieldTypes);
|
|
87
|
-
if (pkOnly) fields = fields.filter((field) => field.NAME
|
|
87
|
+
if (pkOnly) fields = fields.filter((field) => pkFields.includes(field.NAME));
|
|
88
88
|
|
|
89
|
-
const schema = buildSchema(fields, pkOnly
|
|
89
|
+
const schema = buildSchema(fields, pkOnly ? pkFields : []);
|
|
90
90
|
|
|
91
91
|
connection.reply(message, {
|
|
92
92
|
MESSAGE_TYPE: message.MESSAGE_TYPE,
|
package/src/handlers/meta.ts
CHANGED
|
@@ -2,7 +2,8 @@ import { deriveFields } from '../db/metadata.ts';
|
|
|
2
2
|
import type { Store } from '../db/store.ts';
|
|
3
3
|
import type { Connection } from '../protocol/connection.ts';
|
|
4
4
|
import { ERROR_CODE } from '../protocol/messageTypes.ts';
|
|
5
|
-
import type { GenesisMessage, MockServerConfig } from '../types.ts';
|
|
5
|
+
import type { GenesisMessage, MockServerConfig, Row } from '../types.ts';
|
|
6
|
+
import { hiddenFields, requestingUser } from './resourceAuth.ts';
|
|
6
7
|
|
|
7
8
|
// createMetaRequestMessage (foundation-comms/src/connect/message.ts) puts the
|
|
8
9
|
// resource name in DETAILS.FEATURE — not DATASOURCE_NAME/RESOURCE_NAME despite
|
|
@@ -37,8 +38,15 @@ export function handleMetaRequest(
|
|
|
37
38
|
}
|
|
38
39
|
|
|
39
40
|
const resolved = (query ?? requestReply)!;
|
|
40
|
-
|
|
41
|
-
|
|
41
|
+
// Resolver-only request-replies have no backing table/view — their field
|
|
42
|
+
// metadata comes from the def's own metadataRows sample (plus fieldTypes).
|
|
43
|
+
const rows: Row[] = resolved.source
|
|
44
|
+
? store.getMetadataRows(resolved.source)
|
|
45
|
+
: (requestReply?.metadataRows ?? []);
|
|
46
|
+
// Hidden fields disappear from the metadata too — a column the user can't
|
|
47
|
+
// see must not be offered to the grid at all.
|
|
48
|
+
const hidden = hiddenFields(resolved.auth, requestingUser(connection));
|
|
49
|
+
const fields = deriveFields(rows, resolved.fieldTypes).filter((field) => !hidden.has(field.NAME));
|
|
42
50
|
|
|
43
51
|
connection.reply(message, {
|
|
44
52
|
MESSAGE_TYPE: message.MESSAGE_TYPE,
|
|
@@ -4,6 +4,7 @@ import type { Connection } from '../protocol/connection.ts';
|
|
|
4
4
|
import { NackError } from '../protocol/errors.ts';
|
|
5
5
|
import { ERROR_CODE } from '../protocol/messageTypes.ts';
|
|
6
6
|
import type { GenesisMessage, MockServerConfig, Row } from '../types.ts';
|
|
7
|
+
import { applyResourceAuth, requestingUser } from './resourceAuth.ts';
|
|
7
8
|
|
|
8
9
|
// Keyed lookups: foundation-comms' createRequestMessage spreads RequestParams
|
|
9
10
|
// onto the message, so REQUEST is a *top-level* field ({FIELD: value} pairs
|
|
@@ -27,7 +28,7 @@ export function handleRequestReply(
|
|
|
27
28
|
const resourceName = message.MESSAGE_TYPE.replace(/^REQ_/, '');
|
|
28
29
|
const requestReply = config.requestReplies?.[resourceName];
|
|
29
30
|
|
|
30
|
-
if (!requestReply) {
|
|
31
|
+
if (!requestReply || (!requestReply.resolver && !requestReply.source)) {
|
|
31
32
|
connection.reply(message, {
|
|
32
33
|
MESSAGE_TYPE: `REP_${resourceName}`,
|
|
33
34
|
ERROR: [
|
|
@@ -40,15 +41,28 @@ export function handleRequestReply(
|
|
|
40
41
|
return;
|
|
41
42
|
}
|
|
42
43
|
|
|
44
|
+
const user = requestingUser(connection);
|
|
45
|
+
const request: Row =
|
|
46
|
+
(typeof message.REQUEST === 'object' && message.REQUEST) || message.DETAILS?.REQUEST || {};
|
|
47
|
+
|
|
43
48
|
try {
|
|
44
|
-
let rows
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
49
|
+
let rows: Row[];
|
|
50
|
+
if (requestReply.resolver) {
|
|
51
|
+
// Computed reply (date calcs, holiday roll, composite lookups...): the
|
|
52
|
+
// resolver owns REQUEST interpretation entirely — no generic REQUEST/
|
|
53
|
+
// CRITERIA filtering is applied on top, since a computed reply's rows
|
|
54
|
+
// needn't echo the request's fields at all.
|
|
55
|
+
rows = requestReply.resolver({ request, message, user, store });
|
|
56
|
+
} else {
|
|
57
|
+
rows = store.getResourceRows(requestReply.source!);
|
|
58
|
+
if (Object.keys(request).length > 0) {
|
|
59
|
+
rows = rows.filter((row) => matchesRequestFields(row, request));
|
|
60
|
+
}
|
|
61
|
+
const criteria = message.DETAILS?.CRITERIA_MATCH ?? message.CRITERIA_MATCH;
|
|
62
|
+
if (criteria) rows = filterByCriteria(rows, criteria);
|
|
63
|
+
if (requestReply.filter) rows = rows.filter(requestReply.filter);
|
|
48
64
|
}
|
|
49
|
-
|
|
50
|
-
if (criteria) rows = filterByCriteria(rows, criteria);
|
|
51
|
-
if (requestReply.filter) rows = rows.filter(requestReply.filter);
|
|
65
|
+
rows = applyResourceAuth(rows, requestReply.auth, user);
|
|
52
66
|
|
|
53
67
|
connection.reply(message, {
|
|
54
68
|
MESSAGE_TYPE: `REP_${resourceName}`,
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
}
|
package/src/protocol/router.ts
CHANGED
|
@@ -100,7 +100,7 @@ export function routeMessage(
|
|
|
100
100
|
case MESSAGE_TYPE.EVENT_LOGOUT:
|
|
101
101
|
return handleLogout(message, connection);
|
|
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
|
-
|
|
11
|
-
|
|
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
|
-
|
|
22
|
+
getRowRef: (row: Row) => unknown,
|
|
22
23
|
operation: RowOperation,
|
|
23
24
|
): Row[] {
|
|
24
|
-
return rows.map((row) => stampRow(row,
|
|
25
|
+
return rows.map((row) => stampRow(row, getRowRef(row), operation));
|
|
25
26
|
}
|