@genesislcap/mock-server 15.71.1-alpha-71cb16e4d3.0 → 15.73.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 +58 -5
- package/dist/db/audit.d.ts +12 -0
- package/dist/db/audit.js +98 -0
- package/dist/db/criteriaDialect.js +15 -8
- package/dist/db/criteriaJuxtaposition.d.ts +6 -0
- package/dist/db/criteriaJuxtaposition.js +123 -0
- package/dist/db/groovySyntax.js +4 -1
- package/dist/db/groovyValidator.js +166 -7
- package/dist/db/schema.d.ts +2 -0
- package/dist/db/schema.js +2 -0
- package/dist/db/store.d.ts +14 -2
- package/dist/db/store.js +64 -4
- package/dist/handlers/commitEvent.js +16 -3
- package/dist/handlers/dataLogon.js +8 -4
- package/dist/handlers/jsonSchema.js +1 -1
- package/dist/handlers/meta.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/protocol/fieldTypes.d.ts +5 -1
- package/dist/protocol/fieldTypes.js +9 -2
- package/dist/protocol/msgNack.d.ts +2 -0
- package/dist/protocol/msgNack.js +14 -0
- package/dist/protocol/router.js +12 -1
- package/dist/server.js +21 -2
- package/dist/types.d.ts +6 -0
- package/package.json +1 -1
- package/src/db/audit.ts +127 -0
- package/src/db/criteriaDialect.ts +15 -8
- package/src/db/criteriaJuxtaposition.ts +132 -0
- package/src/db/groovySyntax.ts +6 -1
- package/src/db/groovyValidator.ts +176 -11
- package/src/db/schema.ts +4 -0
- package/src/db/store.ts +70 -4
- package/src/handlers/commitEvent.ts +18 -3
- package/src/handlers/dataLogon.ts +8 -4
- package/src/handlers/jsonSchema.ts +1 -1
- package/src/handlers/meta.ts +1 -1
- package/src/index.ts +1 -0
- package/src/protocol/fieldTypes.ts +13 -2
- package/src/protocol/msgNack.ts +16 -0
- package/src/protocol/router.ts +14 -1
- package/src/server.ts +26 -2
- package/src/types.ts +17 -0
package/dist/protocol/msgNack.js
CHANGED
|
@@ -9,6 +9,7 @@ import { MESSAGE_TYPE } from "./messageTypes.js";
|
|
|
9
9
|
export function serviceMsgNack(errors, warnings = []) {
|
|
10
10
|
return { WARNING: warnings, ERROR: errors, MESSAGE_TYPE: MESSAGE_TYPE.MSG_NACK };
|
|
11
11
|
}
|
|
12
|
+
const HTTP_BAD_REQUEST = 400;
|
|
12
13
|
const HTTP_NOT_FOUND = 404;
|
|
13
14
|
const HTTP_CONFLICT = 409;
|
|
14
15
|
// The real router's rejection frame (genesis-router MsgType.Outbound.Error,
|
|
@@ -26,6 +27,19 @@ function routerNack(code, reason, text) {
|
|
|
26
27
|
DETAILS: { ERROR: text, STATUS_CODE },
|
|
27
28
|
};
|
|
28
29
|
}
|
|
30
|
+
// The router reads SOURCE_REF and MESSAGE_TYPE before anything else and
|
|
31
|
+
// refuses a message missing either, or naming a blank one
|
|
32
|
+
// (RouterMessageDelegator.processMessage @v8.15.29). With no SOURCE_REF to
|
|
33
|
+
// echo, the first is sent on an empty one.
|
|
34
|
+
export function missingSourceRefNack() {
|
|
35
|
+
return {
|
|
36
|
+
...routerNack(HTTP_BAD_REQUEST, 'Bad Request', 'No source ref provided'),
|
|
37
|
+
SOURCE_REF: '',
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
export function missingMessageTypeNack() {
|
|
41
|
+
return routerNack(HTTP_BAD_REQUEST, 'Bad Request', 'No message type provided');
|
|
42
|
+
}
|
|
29
43
|
// The router resolves every message to a resource name first and answers this
|
|
30
44
|
// when no service serves it: DETAILS.DATASOURCE_NAME for DATA_LOGON, the name
|
|
31
45
|
// after REQ_ for request servers, DETAILS.FEATURE for META_REQUEST /
|
package/dist/protocol/router.js
CHANGED
|
@@ -8,7 +8,7 @@ import { handleRequestReply } from "../handlers/requestReply.js";
|
|
|
8
8
|
import { handleResourcesRequest } from "../handlers/resources.js";
|
|
9
9
|
import { isLegacyFidelity } from "./fidelity.js";
|
|
10
10
|
import { MESSAGE_TYPE, ERROR_CODE, isCommitEvent, isRequestReply } from "./messageTypes.js";
|
|
11
|
-
import { websocketForbiddenNack } from "./msgNack.js";
|
|
11
|
+
import { missingMessageTypeNack, missingSourceRefNack, websocketForbiddenNack } from "./msgNack.js";
|
|
12
12
|
// Message types a connection may send before authenticating when the OPT-IN
|
|
13
13
|
// auth gate (config.auth.requireAuth = true) is enabled. Everything else
|
|
14
14
|
// (data subscriptions, request-replies, metadata, commit events) then
|
|
@@ -74,6 +74,8 @@ function replyNotLoggedOn(message, connection) {
|
|
|
74
74
|
}
|
|
75
75
|
connection.reply(message, { MESSAGE_TYPE: type, ERROR });
|
|
76
76
|
}
|
|
77
|
+
// Kotlin's isNullOrBlank on GenesisSet.getString, which reads any value as text.
|
|
78
|
+
const isBlank = (value) => value === undefined || value === null || String(value).trim() === '';
|
|
77
79
|
export function routeMessage(inbound, connection, config, store, ctx, auth = createAuthState()) {
|
|
78
80
|
let message = inbound;
|
|
79
81
|
// A socket opened with a sessionAuthToken cookie (auth.cookieAuthentication)
|
|
@@ -88,6 +90,15 @@ export function routeMessage(inbound, connection, config, store, ctx, auth = cre
|
|
|
88
90
|
}
|
|
89
91
|
message = { ...message, SESSION_AUTH_TOKEN: cookieToken };
|
|
90
92
|
}
|
|
93
|
+
// GSF refuses a message with no SOURCE_REF or MESSAGE_TYPE, a heartbeat
|
|
94
|
+
// included, before its client handler sees it (so LAST_SENT and
|
|
95
|
+
// LAST_RECEIVED stay as they were); the 15.47 mock routed it anyway.
|
|
96
|
+
if (!isLegacyFidelity(config)) {
|
|
97
|
+
if (isBlank(message.SOURCE_REF))
|
|
98
|
+
return connection.send(missingSourceRefNack(), false);
|
|
99
|
+
if (isBlank(message.MESSAGE_TYPE))
|
|
100
|
+
return connection.reply(message, missingMessageTypeNack(), false);
|
|
101
|
+
}
|
|
91
102
|
// Adopt token auth on every message (not just gated ones) so e.g. a
|
|
92
103
|
// HEARTBEAT_PONG's IS_AUTHENTICATED reflects an HTTP-issued token straight
|
|
93
104
|
// away; the gate itself only applies to data traffic.
|
package/dist/server.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import http from 'node:http';
|
|
2
2
|
import { WebSocketServer } from 'ws';
|
|
3
|
+
import { auditTableDef, auditTableName, checkNotDeclared, isAudited, withAuditTables, } from "./db/audit.js";
|
|
3
4
|
import { recordKey } from "./db/identity.js";
|
|
4
5
|
import { compareRecordIds } from "./db/ordering.js";
|
|
5
6
|
import { Store } from "./db/store.js";
|
|
@@ -64,7 +65,13 @@ const HTTP_UNAUTHORIZED = 401;
|
|
|
64
65
|
export function createMockServer(config) {
|
|
65
66
|
// Declared columns are held by type (db/values.ts), except under
|
|
66
67
|
// fidelity: 'legacy', which keeps rows as given.
|
|
67
|
-
const store = new Store({
|
|
68
|
+
const store = new Store({
|
|
69
|
+
normalizeValues: () => !isLegacyFidelity(config),
|
|
70
|
+
holdSharedSequences: () => !isLegacyFidelity(config),
|
|
71
|
+
});
|
|
72
|
+
// An audited table's audit table is a table like any other from here on.
|
|
73
|
+
if (config.tables)
|
|
74
|
+
config.tables = withAuditTables(config.tables);
|
|
68
75
|
for (const [tableName, tableDef] of Object.entries(config.tables ?? {})) {
|
|
69
76
|
store.registerTable(tableName, tableDef);
|
|
70
77
|
}
|
|
@@ -482,8 +489,20 @@ export function createMockServer(config) {
|
|
|
482
489
|
// want to inject a one-off failure/edge case (`extendEventHandler`) without
|
|
483
490
|
// spinning up a second server.
|
|
484
491
|
function setTable(tableName, tableDef) {
|
|
485
|
-
config.tables
|
|
492
|
+
checkNotDeclared(config.tables ?? {}, tableName, tableDef);
|
|
493
|
+
const tables = { ...config.tables, [tableName]: tableDef };
|
|
494
|
+
// Nor may it take over a table declared under its audit table's name.
|
|
495
|
+
if (isAudited(tableDef)) {
|
|
496
|
+
const auditName = auditTableName(tableName);
|
|
497
|
+
checkNotDeclared(tables, auditName, config.tables?.[auditName]);
|
|
498
|
+
}
|
|
499
|
+
config.tables = tables;
|
|
486
500
|
store.registerTable(tableName, tableDef);
|
|
501
|
+
// A new definition makes a new audit table too, empty as the table's
|
|
502
|
+
// own rows are its new ones.
|
|
503
|
+
if (isAudited(tableDef)) {
|
|
504
|
+
setTable(auditTableName(tableName), auditTableDef(tableName, tableDef));
|
|
505
|
+
}
|
|
487
506
|
}
|
|
488
507
|
function setView(viewName, viewDef) {
|
|
489
508
|
config.views = { ...config.views, [viewName]: viewDef };
|
package/dist/types.d.ts
CHANGED
|
@@ -18,6 +18,8 @@ export interface FieldDef {
|
|
|
18
18
|
maxSize?: number;
|
|
19
19
|
scale?: number;
|
|
20
20
|
minLength?: number;
|
|
21
|
+
min?: number;
|
|
22
|
+
max?: number;
|
|
21
23
|
description?: string;
|
|
22
24
|
title?: string;
|
|
23
25
|
optional?: boolean;
|
|
@@ -43,6 +45,10 @@ export interface TableDef {
|
|
|
43
45
|
generated?: GeneratedFieldDef[];
|
|
44
46
|
indexes?: IndexDef[];
|
|
45
47
|
events?: CrudEventVerb[];
|
|
48
|
+
audit?: boolean | AuditDef;
|
|
49
|
+
}
|
|
50
|
+
export interface AuditDef {
|
|
51
|
+
sequencePrefix?: string;
|
|
46
52
|
}
|
|
47
53
|
export type SequenceFormat = 'prefix' | 'genesis';
|
|
48
54
|
export type JoinFieldLink = [string, string];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@genesislcap/mock-server",
|
|
3
|
-
"version": "15.
|
|
3
|
+
"version": "15.73.0",
|
|
4
4
|
"description": "Reusable in-memory Genesis WebSocket protocol mock server for client automation/CI, without a JVM or database.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
package/src/db/audit.ts
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// Audit tables, as GSF builds them for a table declared with
|
|
2
|
+
// `audit = details(id = …, sequence = "XA")` (genesis-dictionary
|
|
3
|
+
// reader/model/Audit.kt and Fields.kt, GSF v8.15.29): <TABLE>_AUDIT holds the
|
|
4
|
+
// table's fields, its own sequence key <TABLE>_AUDIT_ID and four audit
|
|
5
|
+
// fields, with a non-unique <TABLE>_AUDIT_BY_UNDERLYING_ID index over the
|
|
6
|
+
// table's key. Every write an event handler makes to the table adds a row to
|
|
7
|
+
// it (TransactionalEventHandlerContainer writes through entityDb.audited):
|
|
8
|
+
// the record as written (as deleted, for a delete), the event's MESSAGE_TYPE,
|
|
9
|
+
// when, its REASON and the user. A write outside an event is not audited.
|
|
10
|
+
// GSF serves no resource for it; an app reads it through its own
|
|
11
|
+
// requestReply(<TABLE>_AUDIT) { request(<TABLE>_AUDIT.BY_UNDERLYING_ID) }.
|
|
12
|
+
|
|
13
|
+
import type { AuditDef, FieldDef, Row, TableDef } from '../types.ts';
|
|
14
|
+
import { RECORD_ID, TIMESTAMP } from './identity.ts';
|
|
15
|
+
|
|
16
|
+
// What GSF names the audit table's own fields (Fields.kt), and the size of
|
|
17
|
+
// AUDIT_EVENT_TEXT (genesis-dictionary pal DB_MAX_SIZE, Int.MAX_VALUE).
|
|
18
|
+
const AUDIT_EVENT_TYPE = 'AUDIT_EVENT_TYPE';
|
|
19
|
+
const AUDIT_EVENT_DATETIME = 'AUDIT_EVENT_DATETIME';
|
|
20
|
+
const AUDIT_EVENT_TEXT = 'AUDIT_EVENT_TEXT';
|
|
21
|
+
const AUDIT_EVENT_USER = 'AUDIT_EVENT_USER';
|
|
22
|
+
const AUDIT_TYPE_SIZE = 255;
|
|
23
|
+
const DB_MAX_SIZE = 2147483647;
|
|
24
|
+
// The sequence an audit table gets when TableDef.audit names none.
|
|
25
|
+
const DEFAULT_AUDIT_SEQUENCE = 'AU';
|
|
26
|
+
|
|
27
|
+
// The event an audited write belongs to.
|
|
28
|
+
export interface AuditContext {
|
|
29
|
+
eventType: string;
|
|
30
|
+
user: string;
|
|
31
|
+
// The event's REASON, null when it has none.
|
|
32
|
+
text: string | null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const auditTableName = (tableName: string) => `${tableName}_AUDIT`;
|
|
36
|
+
|
|
37
|
+
const auditDefOf = (def: TableDef): AuditDef | undefined =>
|
|
38
|
+
def.audit === true ? {} : def.audit || undefined;
|
|
39
|
+
|
|
40
|
+
const pkFieldList = (def: TableDef) => (Array.isArray(def.pkField) ? def.pkField : [def.pkField]);
|
|
41
|
+
|
|
42
|
+
// The audit tables auditTableDef made, so a config that already holds one
|
|
43
|
+
// (a server created twice from it) gets it made again rather than refused.
|
|
44
|
+
const derived = new WeakSet<TableDef>();
|
|
45
|
+
|
|
46
|
+
// The audit table GSF derives from an audited table.
|
|
47
|
+
export function auditTableDef(tableName: string, def: TableDef): TableDef {
|
|
48
|
+
const audit = auditDefOf(def) ?? {};
|
|
49
|
+
const idField = `${auditTableName(tableName)}_ID`;
|
|
50
|
+
const keyFields = pkFieldList(def);
|
|
51
|
+
const auditFields: FieldDef[] = [
|
|
52
|
+
{ name: idField, type: 'STRING', nullable: false },
|
|
53
|
+
{ name: AUDIT_EVENT_TYPE, type: 'STRING', maxSize: AUDIT_TYPE_SIZE },
|
|
54
|
+
{ name: AUDIT_EVENT_DATETIME, type: 'DATETIME' },
|
|
55
|
+
{ name: AUDIT_EVENT_TEXT, type: 'STRING', maxSize: DB_MAX_SIZE },
|
|
56
|
+
{ name: AUDIT_EVENT_USER, type: 'STRING', maxSize: AUDIT_TYPE_SIZE },
|
|
57
|
+
];
|
|
58
|
+
const table: TableDef = {
|
|
59
|
+
pkField: idField,
|
|
60
|
+
sequencePrefix: audit.sequencePrefix ?? DEFAULT_AUDIT_SEQUENCE,
|
|
61
|
+
...(def.sequenceWidth !== undefined ? { sequenceWidth: def.sequenceWidth } : {}),
|
|
62
|
+
...(def.sequenceFormat !== undefined ? { sequenceFormat: def.sequenceFormat } : {}),
|
|
63
|
+
...(def.fields
|
|
64
|
+
? {
|
|
65
|
+
fields: [
|
|
66
|
+
// The table's key is no key here, but its index keeps it not null.
|
|
67
|
+
...def.fields.map((field) =>
|
|
68
|
+
keyFields.includes(field.name) ? { ...field, nullable: false } : field,
|
|
69
|
+
),
|
|
70
|
+
...auditFields,
|
|
71
|
+
],
|
|
72
|
+
}
|
|
73
|
+
: {}),
|
|
74
|
+
indexes: [
|
|
75
|
+
{ name: `${auditTableName(tableName)}_BY_ID`, fields: [idField], unique: true },
|
|
76
|
+
{ name: `${auditTableName(tableName)}_BY_UNDERLYING_ID`, fields: keyFields },
|
|
77
|
+
],
|
|
78
|
+
};
|
|
79
|
+
derived.add(table);
|
|
80
|
+
return table;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// The tables with each audited one's audit table beside it. A table of that
|
|
84
|
+
// name declared by hand is refused, as GSF's dictionary refuses two tables of
|
|
85
|
+
// one name: the audit table is always the one derived from the table.
|
|
86
|
+
export function withAuditTables(tables: Record<string, TableDef>): Record<string, TableDef> {
|
|
87
|
+
const audits = Object.entries(tables).flatMap(([tableName, def]) => {
|
|
88
|
+
if (!auditDefOf(def)) return [];
|
|
89
|
+
const name = auditTableName(tableName);
|
|
90
|
+
checkNotDeclared(tables, name, tables[name]);
|
|
91
|
+
return [[name, auditTableDef(tableName, def)] as const];
|
|
92
|
+
});
|
|
93
|
+
return audits.length > 0 ? { ...tables, ...Object.fromEntries(audits) } : tables;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Refuses a definition, at start or set later, of a name that is an audited
|
|
97
|
+
// table's audit table, unless auditTableDef made it.
|
|
98
|
+
export function checkNotDeclared(
|
|
99
|
+
tables: Record<string, TableDef>,
|
|
100
|
+
name: string,
|
|
101
|
+
def: TableDef | undefined,
|
|
102
|
+
): void {
|
|
103
|
+
if (!def || derived.has(def)) return;
|
|
104
|
+
const audited = Object.entries(tables).find(
|
|
105
|
+
([tableName, table]) => auditDefOf(table) && auditTableName(tableName) === name,
|
|
106
|
+
);
|
|
107
|
+
if (audited) {
|
|
108
|
+
throw new Error(
|
|
109
|
+
`Table ${name} is ${audited[0]}'s audit table, which TableDef.audit derives: don't declare it`,
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export const isAudited = (def: TableDef) => auditDefOf(def) !== undefined;
|
|
115
|
+
|
|
116
|
+
// The audit row for a record as written: its fields (without the record's
|
|
117
|
+
// own RECORD_ID and TIMESTAMP: the audit row gets its own) and the event's.
|
|
118
|
+
export function auditRecord(record: Row, context: AuditContext, now: number): Row {
|
|
119
|
+
const { [RECORD_ID]: _recordId, [TIMESTAMP]: _timestamp, ...fields } = record;
|
|
120
|
+
return {
|
|
121
|
+
...fields,
|
|
122
|
+
[AUDIT_EVENT_TYPE]: context.eventType,
|
|
123
|
+
[AUDIT_EVENT_DATETIME]: now,
|
|
124
|
+
[AUDIT_EVENT_TEXT]: context.text,
|
|
125
|
+
[AUDIT_EVENT_USER]: context.user,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
// recovery differs case by case.
|
|
27
27
|
|
|
28
28
|
import { compileFailureText, tokenizeCriteria } from './criteria.ts';
|
|
29
|
+
import { juxtaposition } from './criteriaJuxtaposition.ts';
|
|
29
30
|
import { groovyCompileErrorText, groovySyntaxError } from './groovySyntax.ts';
|
|
30
31
|
import { EXPR_METHODS, FIELD_METHODS, groovyValidation, isClassName } from './groovyValidator.ts';
|
|
31
32
|
|
|
@@ -466,22 +467,28 @@ export function dialectRefusal(
|
|
|
466
467
|
return criteriaDialect(criteria, allowed, types)?.text;
|
|
467
468
|
}
|
|
468
469
|
|
|
469
|
-
// What strict criteria refuse: a Groovy syntax error (groovySyntax.ts)
|
|
470
|
-
//
|
|
471
|
-
// undefined.
|
|
470
|
+
// What strict criteria refuse: a Groovy syntax error (groovySyntax.ts), the
|
|
471
|
+
// dialect, or operands side by side (criteriaJuxtaposition.ts), whichever
|
|
472
|
+
// Groovy meets first — the INVALID_CRITERIA TEXT, or undefined.
|
|
472
473
|
export function strictCriteriaRefusal(
|
|
473
474
|
criteria: string,
|
|
474
475
|
allowed?: ReadonlySet<string>,
|
|
475
476
|
types?: ReadonlyMap<string, string>,
|
|
476
477
|
): string | undefined {
|
|
477
478
|
const syntax = groovySyntaxError(criteria);
|
|
478
|
-
// Groovy this grammar doesn't read (a list, arithmetic, a ternary, `new
|
|
479
|
-
// GSF's validator answers it whole.
|
|
479
|
+
// Groovy this grammar doesn't read (a list, arithmetic, a ternary, `new`,
|
|
480
|
+
// a command expression): GSF's validator answers it whole.
|
|
480
481
|
const groovy = syntax ? undefined : groovyValidation(criteria, allowed);
|
|
481
482
|
if (groovy) return groovy.kind === 'refused' ? groovy.text : undefined;
|
|
482
|
-
|
|
483
|
-
|
|
483
|
+
// The syntax check stops at operands side by side, so its error is before them.
|
|
484
|
+
const [first] = [
|
|
485
|
+
criteriaDialect(criteria, allowed, types),
|
|
486
|
+
syntax ? undefined : juxtaposition(criteria),
|
|
487
|
+
]
|
|
488
|
+
.filter((refusal) => refusal !== undefined)
|
|
489
|
+
.sort((a, b) => a.at - b.at);
|
|
490
|
+
if (syntax && (!first || syntax.column - 1 < first.at)) {
|
|
484
491
|
return groovyCompileErrorText(criteria, syntax);
|
|
485
492
|
}
|
|
486
|
-
return
|
|
493
|
+
return first?.text;
|
|
487
494
|
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// What GSF answers a CRITERIA_MATCH with two operands side by side — most
|
|
2
|
+
// often a double quote left unescaped inside a double-quoted value
|
|
3
|
+
// (`NAME.equals("say "hi"")` is `"say "`, `hi`, `""`). Groovy reads operands
|
|
4
|
+
// side by side as a command expression (`a b c d e` is `this.a(b).c(d).e`)
|
|
5
|
+
// where one may start, and as a syntax error everywhere else, so GSF never
|
|
6
|
+
// runs such a criteria. Which of the two, and the text, depend on where the
|
|
7
|
+
// operands stand (Groovy 3.0.25 and genesis-db 8.15.29, captured by running
|
|
8
|
+
// them; test/criteriaJuxtaposition.test.ts pins them):
|
|
9
|
+
// - the only argument of a call, with no binary operator before the call:
|
|
10
|
+
// a command expression, refused by the validator (groovyValidator.ts);
|
|
11
|
+
// - the only argument of a call after a binary operator: a syntax error
|
|
12
|
+
// naming the statement up to the method;
|
|
13
|
+
// - a later argument of a call: a syntax error at the call's '(';
|
|
14
|
+
// - after a binary operator outside a call: a syntax error naming the
|
|
15
|
+
// statement up to the operand before them.
|
|
16
|
+
// A type beside a name is no such pair: a cast `(int) X`, a declaration
|
|
17
|
+
// `String x = ...` or a closure parameter `{ String s -> ... }` Groovy parses,
|
|
18
|
+
// and groovyValidator.ts gives GSF's text for them first. Any other shape is
|
|
19
|
+
// still refused, as GSF refuses it, but with an approximate text: GSF's may
|
|
20
|
+
// be another syntax error (the text follows the whole statement, where this
|
|
21
|
+
// one looks at the first pair only) or a validator error (`TRADER "x"` is the
|
|
22
|
+
// call `this.TRADER(x)`).
|
|
23
|
+
|
|
24
|
+
import { groovyCompileErrorText, groovyTokens, type Token } from './groovySyntax.ts';
|
|
25
|
+
|
|
26
|
+
// Names that are no operand: Groovy's keyword operators, `new`, and this
|
|
27
|
+
// engine's AND / OR / NOT dialect (criteriaDialect.ts answers those), in any
|
|
28
|
+
// case; and Groovy's other keywords, which start or shape a statement
|
|
29
|
+
// (`return QTY > 1` is valid Groovy), as written.
|
|
30
|
+
const NOT_OPERANDS = new Set(['in', 'instanceof', 'as', 'new', 'and', 'or', 'not']);
|
|
31
|
+
const KEYWORDS = new Set(
|
|
32
|
+
(
|
|
33
|
+
'abstract assert boolean break byte case catch char class const continue def default do ' +
|
|
34
|
+
'double else enum extends final finally float for goto if implements import int interface ' +
|
|
35
|
+
'long native non-sealed package permits private protected public record return sealed ' +
|
|
36
|
+
'short static strictfp switch synchronized threadsafe throw throws trait transient try var ' +
|
|
37
|
+
'void volatile while yield'
|
|
38
|
+
).split(' '),
|
|
39
|
+
);
|
|
40
|
+
// Operators that end a postfix chain or start an operand: no binary operator.
|
|
41
|
+
const NOT_BINARY = new Set(['.', '?.', '*.', '.&', '.@', '::', '!', '~', '++', '--', '->']);
|
|
42
|
+
|
|
43
|
+
const startsOperand = (token: Token | undefined) =>
|
|
44
|
+
!!token &&
|
|
45
|
+
(token.kind === 'literal' ||
|
|
46
|
+
(token.kind === 'name' &&
|
|
47
|
+
!NOT_OPERANDS.has(token.text.toLowerCase()) &&
|
|
48
|
+
!KEYWORDS.has(token.text)));
|
|
49
|
+
|
|
50
|
+
const endsOperand = (token: Token | undefined) =>
|
|
51
|
+
!!token && (startsOperand(token) || (token.kind === 'close' && token.text !== '}'));
|
|
52
|
+
|
|
53
|
+
const isBinary = (token: Token) =>
|
|
54
|
+
(token.kind === 'operator' && !NOT_BINARY.has(token.text)) ||
|
|
55
|
+
(token.kind === 'name' && ['in', 'instanceof', 'as'].includes(token.text));
|
|
56
|
+
|
|
57
|
+
// The index of the first operand that directly follows another, or -1.
|
|
58
|
+
export function juxtaposedIndex(tokens: Token[]): number {
|
|
59
|
+
return tokens.findIndex(
|
|
60
|
+
(token, index) => index > 0 && startsOperand(token) && endsOperand(tokens[index - 1]),
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// The INVALID_CRITERIA TEXT GSF sends for a criteria with operands side by
|
|
65
|
+
// side, and where the second one is; undefined when it has none. The
|
|
66
|
+
// command expression groovyValidator.ts refuses gets its exact text there
|
|
67
|
+
// first; here it gets the approximate one only when that parser gives up.
|
|
68
|
+
export function juxtaposition(criteria: string): { text: string; at: number } | undefined {
|
|
69
|
+
const tokens = groovyTokens(criteria);
|
|
70
|
+
if (!tokens) return undefined;
|
|
71
|
+
const second = juxtaposedIndex(tokens);
|
|
72
|
+
if (second < 0) return undefined;
|
|
73
|
+
const at = tokens[second].offset;
|
|
74
|
+
const syntaxError = (input: string, offset: number) => ({
|
|
75
|
+
text: groovyCompileErrorText(criteria, {
|
|
76
|
+
message: `Unexpected input: '${input}'`,
|
|
77
|
+
line: 1,
|
|
78
|
+
column: offset + 1,
|
|
79
|
+
}),
|
|
80
|
+
at,
|
|
81
|
+
});
|
|
82
|
+
const span = (from: Token, to: Token) => criteria.slice(from.offset, to.offset + to.text.length);
|
|
83
|
+
|
|
84
|
+
// The parentheses still open at the second operand, and where its statement starts.
|
|
85
|
+
const open: number[] = [];
|
|
86
|
+
let statement = 0;
|
|
87
|
+
for (let index = 0; index < second; index += 1) {
|
|
88
|
+
const token = tokens[index];
|
|
89
|
+
if (token.kind === 'open') open.push(index);
|
|
90
|
+
else if (token.kind === 'close') open.pop();
|
|
91
|
+
else if (token.kind === 'semicolon' && open.length === 0) statement = index + 1;
|
|
92
|
+
}
|
|
93
|
+
const groupStart = (depth: number) => (depth > 0 ? open[depth - 1] + 1 : statement);
|
|
94
|
+
const binaryIn = (from: number, to: number) => tokens.slice(from, to).some(isBinary);
|
|
95
|
+
|
|
96
|
+
const paren = open.at(-1);
|
|
97
|
+
const callee = paren === undefined ? undefined : tokens[paren - 1];
|
|
98
|
+
const inCall =
|
|
99
|
+
paren !== undefined &&
|
|
100
|
+
tokens[paren].text === '(' &&
|
|
101
|
+
callee?.kind === 'name' &&
|
|
102
|
+
!NOT_OPERANDS.has(callee.text.toLowerCase());
|
|
103
|
+
|
|
104
|
+
if (inCall) {
|
|
105
|
+
// A comma of this call's own list before the operands: a later argument.
|
|
106
|
+
let depth = 0;
|
|
107
|
+
let later = false;
|
|
108
|
+
for (let index = paren + 1; index < second; index += 1) {
|
|
109
|
+
const token = tokens[index];
|
|
110
|
+
if (token.kind === 'open') depth += 1;
|
|
111
|
+
else if (token.kind === 'close') depth -= 1;
|
|
112
|
+
else if (token.kind === 'comma' && depth === 0) later = true;
|
|
113
|
+
}
|
|
114
|
+
if (later) return syntaxError('(', tokens[paren].offset);
|
|
115
|
+
let end = second;
|
|
116
|
+
while (startsOperand(tokens[end + 1])) end += 1;
|
|
117
|
+
const after = tokens[end + 1];
|
|
118
|
+
if (after?.kind === 'close' && after.text === ')') {
|
|
119
|
+
// The call's only argument: after a binary operator, a syntax error
|
|
120
|
+
// naming the statement up to the method.
|
|
121
|
+
const from = groupStart(open.length - 1);
|
|
122
|
+
if (binaryIn(from, paren - 1))
|
|
123
|
+
return syntaxError(span(tokens[from], callee), tokens[from].offset);
|
|
124
|
+
}
|
|
125
|
+
} else {
|
|
126
|
+
const from = groupStart(open.length);
|
|
127
|
+
if (binaryIn(from, second)) {
|
|
128
|
+
return syntaxError(span(tokens[from], tokens[second - 1]), tokens[from].offset);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return syntaxError(tokens[second].text, at);
|
|
132
|
+
}
|
package/src/db/groovySyntax.ts
CHANGED
|
@@ -139,7 +139,12 @@ const DIALECT_BINARY = new Set(['AND', 'OR']);
|
|
|
139
139
|
|
|
140
140
|
const NAME_START = /[A-Za-z_$]/;
|
|
141
141
|
const NAME_PART = /[A-Za-z0-9_$]/;
|
|
142
|
-
|
|
142
|
+
// Groovy's number literals: hex, binary, decimal (octal too), digits split by
|
|
143
|
+
// underscores, a fraction, an exponent and a type suffix.
|
|
144
|
+
const DIGITS = '\\d(?:[\\d_]*\\d)?';
|
|
145
|
+
const NUMBER = new RegExp(
|
|
146
|
+
`^(?:0[xX][\\da-fA-F](?:[\\da-fA-F_]*[\\da-fA-F])?|0[bB][01](?:[01_]*[01])?|${DIGITS}(?:\\.${DIGITS})?(?:[eE][+-]?${DIGITS})?)[GgLlDdFfIi]?`,
|
|
147
|
+
);
|
|
143
148
|
// Characters Groovy can't start any token with.
|
|
144
149
|
const NEVER_TOKENS = new Set(['#', '`']);
|
|
145
150
|
const TRIPLE_QUOTE = 3;
|