@altopelago/sansa 0.9.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/CHANGELOG.md +41 -0
- package/CODE_OF_CONDUCT.md +28 -0
- package/CONTRIBUTING.md +52 -0
- package/GOVERNANCE.md +35 -0
- package/LICENSE +21 -0
- package/README.md +146 -0
- package/SECURITY.md +38 -0
- package/docs/api-contract.md +788 -0
- package/docs/capabilities.json +80 -0
- package/docs/query-tool.md +228 -0
- package/docs/releasing.md +37 -0
- package/fixtures/address-v1.json +316 -0
- package/fixtures/query-inventory.aeon +69 -0
- package/fixtures/query-inventory.json +671 -0
- package/fixtures/query-params-single.json +10 -0
- package/package.json +70 -0
- package/scripts/cts-address.mjs +107 -0
- package/scripts/cts-query.mjs +271 -0
- package/scripts/cts-resolve.mjs +151 -0
- package/scripts/cts-value-semantics.mjs +83 -0
- package/scripts/query-web.mjs +145 -0
- package/scripts/query.mjs +579 -0
- package/scripts/stress-addresses.mjs +65 -0
- package/src/index.d.ts +575 -0
- package/src/index.js +3389 -0
- package/stress-tests/README.md +19 -0
- package/stress-tests/address/invalid.sansa-cases +60 -0
- package/stress-tests/address/valid.sansa-cases +76 -0
- package/tools/query-web/app.js +266 -0
- package/tools/query-web/examples.mjs +478 -0
- package/tools/query-web/index.html +117 -0
- package/tools/query-web/runtime.mjs +796 -0
- package/tools/query-web/styles.css +251 -0
package/src/index.js
ADDED
|
@@ -0,0 +1,3389 @@
|
|
|
1
|
+
const IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
2
|
+
const QUALIFIER_ARG_RE = /^[A-Za-z0-9!#$%&*+\-.:;=?@^_|~<>]+$/;
|
|
3
|
+
export const SANSA_MAX_POSITION_INDEX = 999_999;
|
|
4
|
+
export const SANSA_MAX_QUERY_INTEGER = Number.MAX_SAFE_INTEGER;
|
|
5
|
+
|
|
6
|
+
const QUERY_VALUE_METADATA_PROPERTY = '__sansaQueryValueMetadata';
|
|
7
|
+
const QUERY_OBJECT_FIELD_METADATA_PROPERTY = '__sansaObjectFieldMetadata';
|
|
8
|
+
const TRANSFORM_EXTENSION_FUNCTIONS = new Map([
|
|
9
|
+
['objectFrom', 'sansa.transform.objectFrom'],
|
|
10
|
+
['fieldsFrom', 'sansa.transform.fieldsFrom'],
|
|
11
|
+
]);
|
|
12
|
+
|
|
13
|
+
export class SansaParseError extends Error {
|
|
14
|
+
constructor(message, index, code = 'SANSA_PARSE_ERROR') {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = 'SansaParseError';
|
|
17
|
+
this.code = code;
|
|
18
|
+
this.index = index;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function parseAddress(input, options = {}) {
|
|
23
|
+
try {
|
|
24
|
+
const parser = new AddressParser(input, options);
|
|
25
|
+
const address = parser.parse();
|
|
26
|
+
return { ok: true, address, warnings: parser.warnings };
|
|
27
|
+
} catch (error) {
|
|
28
|
+
if (error instanceof SansaParseError) {
|
|
29
|
+
return {
|
|
30
|
+
ok: false,
|
|
31
|
+
errors: [{
|
|
32
|
+
code: error.code,
|
|
33
|
+
message: error.message,
|
|
34
|
+
index: error.index,
|
|
35
|
+
}],
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function parseAddressOrThrow(input, options = {}) {
|
|
43
|
+
const result = parseAddress(input, options);
|
|
44
|
+
if (!result.ok) {
|
|
45
|
+
const first = result.errors[0];
|
|
46
|
+
throw new SansaParseError(first.message, first.index, first.code);
|
|
47
|
+
}
|
|
48
|
+
return result.address;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function parseQuery(input, options = {}) {
|
|
52
|
+
try {
|
|
53
|
+
const parser = new QueryParser(input, options);
|
|
54
|
+
const query = parser.parse();
|
|
55
|
+
return { ok: true, query, warnings: parser.warnings };
|
|
56
|
+
} catch (error) {
|
|
57
|
+
if (error instanceof SansaParseError) {
|
|
58
|
+
return {
|
|
59
|
+
ok: false,
|
|
60
|
+
errors: [{
|
|
61
|
+
code: error.code,
|
|
62
|
+
message: error.message,
|
|
63
|
+
index: error.index,
|
|
64
|
+
}],
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function parseQueryOrThrow(input, options = {}) {
|
|
72
|
+
const result = parseQuery(input, options);
|
|
73
|
+
if (!result.ok) {
|
|
74
|
+
const first = result.errors[0];
|
|
75
|
+
throw new SansaParseError(first.message, first.index, first.code);
|
|
76
|
+
}
|
|
77
|
+
return result.query;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function parseQueryExpression(input, options = {}) {
|
|
81
|
+
try {
|
|
82
|
+
const parser = new QueryExpressionParser(input, options);
|
|
83
|
+
const expression = parser.parse();
|
|
84
|
+
return { ok: true, expression, warnings: parser.warnings };
|
|
85
|
+
} catch (error) {
|
|
86
|
+
if (error instanceof SansaParseError) {
|
|
87
|
+
return {
|
|
88
|
+
ok: false,
|
|
89
|
+
errors: [{
|
|
90
|
+
code: error.code,
|
|
91
|
+
message: error.message,
|
|
92
|
+
index: error.index,
|
|
93
|
+
}],
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function parseQueryExpressionOrThrow(input, options = {}) {
|
|
101
|
+
const result = parseQueryExpression(input, options);
|
|
102
|
+
if (!result.ok) {
|
|
103
|
+
const first = result.errors[0];
|
|
104
|
+
throw new SansaParseError(first.message, first.index, first.code);
|
|
105
|
+
}
|
|
106
|
+
return result.expression;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function evaluateQuery(input, namespace, options = {}) {
|
|
110
|
+
const parsed = typeof input === 'string' ? parseQuery(input, options.parse) : { ok: true, query: input };
|
|
111
|
+
if (!parsed.ok) {
|
|
112
|
+
return {
|
|
113
|
+
ok: false,
|
|
114
|
+
results: [],
|
|
115
|
+
errors: parsed.errors.map((error) => annotateQueryDiagnostic(error, { phase: 'parse' })),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const query = parsed.query;
|
|
120
|
+
const policy = enforceQueryPolicy(query, options);
|
|
121
|
+
if (!policy.ok) {
|
|
122
|
+
return {
|
|
123
|
+
ok: false,
|
|
124
|
+
results: [],
|
|
125
|
+
errors: [annotateQueryDiagnostic(policy.error, { phase: 'policy' })],
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const from = evaluateQueryFromClause(query.from, namespace, options);
|
|
130
|
+
if (!from.ok) {
|
|
131
|
+
return {
|
|
132
|
+
ok: false,
|
|
133
|
+
results: [],
|
|
134
|
+
errors: from.errors.map((error) => annotateQueryDiagnostic(error, { phase: 'from' })),
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
let bindings = from.bindings;
|
|
139
|
+
const fromBudget = checkQueryBudget(options, 'maxFromBindings', bindings.length);
|
|
140
|
+
if (!fromBudget.ok) {
|
|
141
|
+
return {
|
|
142
|
+
ok: false,
|
|
143
|
+
results: [],
|
|
144
|
+
errors: [annotateQueryDiagnostic(fromBudget.error, { phase: 'from' })],
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (query.where) {
|
|
149
|
+
const whereBudget = checkQueryBudget(options, 'maxWhereCandidates', bindings.length);
|
|
150
|
+
if (!whereBudget.ok) {
|
|
151
|
+
return {
|
|
152
|
+
ok: false,
|
|
153
|
+
results: [],
|
|
154
|
+
errors: [annotateQueryDiagnostic(whereBudget.error, { phase: 'where' })],
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
const filtered = [];
|
|
158
|
+
for (const binding of bindings) {
|
|
159
|
+
const evaluated = evaluateQueryExpressionValue(query.where.ast, binding, namespace, options);
|
|
160
|
+
if (!evaluated.ok) {
|
|
161
|
+
return {
|
|
162
|
+
ok: false,
|
|
163
|
+
results: [],
|
|
164
|
+
errors: [annotateQueryDiagnostic(evaluated.error, {
|
|
165
|
+
phase: 'where',
|
|
166
|
+
candidateAddress: getBindingAddress(binding),
|
|
167
|
+
})],
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
const boolean = expectBooleanQueryValue(evaluated.value, namespace);
|
|
171
|
+
if (!boolean.ok) {
|
|
172
|
+
return {
|
|
173
|
+
ok: false,
|
|
174
|
+
results: [],
|
|
175
|
+
errors: [annotateQueryDiagnostic(boolean.error, {
|
|
176
|
+
phase: 'where',
|
|
177
|
+
candidateAddress: getBindingAddress(binding),
|
|
178
|
+
})],
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
if (boolean.value) filtered.push(binding);
|
|
182
|
+
}
|
|
183
|
+
bindings = filtered;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
if (query.orderBy) {
|
|
187
|
+
const orderBudget = checkQueryBudget(options, 'maxOrderCandidates', bindings.length);
|
|
188
|
+
if (!orderBudget.ok) {
|
|
189
|
+
return {
|
|
190
|
+
ok: false,
|
|
191
|
+
results: [],
|
|
192
|
+
errors: [annotateQueryDiagnostic(orderBudget.error, { phase: 'order' })],
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
const ordered = orderQueryBindings(query.orderBy, bindings, namespace, options);
|
|
196
|
+
if (!ordered.ok) {
|
|
197
|
+
return {
|
|
198
|
+
ok: false,
|
|
199
|
+
results: [],
|
|
200
|
+
errors: [annotateQueryDiagnostic(ordered.error, { phase: 'order' })],
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
bindings = ordered.bindings;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (query.offset) bindings = bindings.slice(query.offset.value);
|
|
207
|
+
if (query.limit) bindings = bindings.slice(0, query.limit.value);
|
|
208
|
+
|
|
209
|
+
const resultBudget = checkQueryBudget(options, 'maxResultRecords', bindings.length);
|
|
210
|
+
if (!resultBudget.ok) {
|
|
211
|
+
return {
|
|
212
|
+
ok: false,
|
|
213
|
+
results: [],
|
|
214
|
+
errors: [annotateQueryDiagnostic(resultBudget.error, { phase: 'select' })],
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const results = [];
|
|
219
|
+
for (const binding of bindings) {
|
|
220
|
+
const evaluated = evaluateQueryExpressionValue(query.select.ast, binding, namespace, options);
|
|
221
|
+
if (!evaluated.ok) {
|
|
222
|
+
return {
|
|
223
|
+
ok: false,
|
|
224
|
+
results: [],
|
|
225
|
+
errors: [annotateQueryDiagnostic(evaluated.error, {
|
|
226
|
+
phase: 'select',
|
|
227
|
+
candidateAddress: getBindingAddress(binding),
|
|
228
|
+
})],
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
const candidateAddress = getBindingAddress(binding);
|
|
232
|
+
const valueAddress = queryValueAddress(evaluated.value);
|
|
233
|
+
results.push({
|
|
234
|
+
type: 'queryResult',
|
|
235
|
+
...(candidateAddress === undefined ? {} : { address: candidateAddress, candidateAddress }),
|
|
236
|
+
...(valueAddress === undefined ? {} : { valueAddress }),
|
|
237
|
+
kind: evaluated.value.type === 'bindingSet' ? 'binding' : 'derived',
|
|
238
|
+
binding,
|
|
239
|
+
value: evaluated.value,
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
return { ok: true, results, diagnostics: [] };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function enforceQueryPolicy(query, options) {
|
|
247
|
+
if (!isValidationQueryPolicy(options.policy)) return { ok: true };
|
|
248
|
+
|
|
249
|
+
if (query.orderBy) return queryPolicyViolation('Validation query policy does not allow order by clauses');
|
|
250
|
+
if (query.offset) return queryPolicyViolation('Validation query policy does not allow offset clauses');
|
|
251
|
+
if (query.limit) return queryPolicyViolation('Validation query policy does not allow limit clauses');
|
|
252
|
+
if (query.select.ast.type === 'projectionExpression') {
|
|
253
|
+
return queryPolicyViolation('Validation query policy does not allow object projection expressions');
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const expressions = [
|
|
257
|
+
...(query.from.source === 'expression' ? [query.from.ast] : []),
|
|
258
|
+
...(query.where ? [query.where.ast] : []),
|
|
259
|
+
...(query.orderBy ? query.orderBy.keys.map((key) => key.ast) : []),
|
|
260
|
+
query.select.ast,
|
|
261
|
+
];
|
|
262
|
+
const disallowedFunction = expressions
|
|
263
|
+
.map((expression) => findExpression(expression, (entry) => entry.type === 'functionCallExpression'
|
|
264
|
+
&& TRANSFORM_EXTENSION_FUNCTIONS.has(entry.name)))
|
|
265
|
+
.find(Boolean);
|
|
266
|
+
if (disallowedFunction) {
|
|
267
|
+
return queryPolicyViolation(
|
|
268
|
+
`Validation query policy does not allow transform extension function '${disallowedFunction.name}'`,
|
|
269
|
+
{ extension: TRANSFORM_EXTENSION_FUNCTIONS.get(disallowedFunction.name) },
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
return { ok: true };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function isValidationQueryPolicy(policy) {
|
|
277
|
+
return policy === 'validation'
|
|
278
|
+
|| policy?.mode === 'validation'
|
|
279
|
+
|| policy?.validation === true;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function queryPolicyViolation(message, details = {}) {
|
|
283
|
+
return {
|
|
284
|
+
ok: false,
|
|
285
|
+
error: queryEvaluateError('SANSA_QUERY_POLICY_VIOLATION', message, details),
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function checkQueryBudget(options, budget, observed) {
|
|
290
|
+
const limit = normalizeQueryBudgetLimit(options.budget?.[budget]);
|
|
291
|
+
if (limit === undefined || observed <= limit) return { ok: true };
|
|
292
|
+
return {
|
|
293
|
+
ok: false,
|
|
294
|
+
error: queryEvaluateError(
|
|
295
|
+
'SANSA_QUERY_BUDGET_EXCEEDED',
|
|
296
|
+
`Query budget '${budget}' exceeded: limit ${limit}, observed ${observed}`,
|
|
297
|
+
{ budget, limit, observed },
|
|
298
|
+
),
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function normalizeQueryBudgetLimit(value) {
|
|
303
|
+
return Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function findExpression(expression, predicate) {
|
|
307
|
+
if (predicate(expression)) return expression;
|
|
308
|
+
|
|
309
|
+
switch (expression.type) {
|
|
310
|
+
case 'groupExpression':
|
|
311
|
+
return findExpression(expression.expression, predicate);
|
|
312
|
+
case 'unaryExpression':
|
|
313
|
+
return findExpression(expression.argument, predicate);
|
|
314
|
+
case 'binaryExpression':
|
|
315
|
+
return findExpression(expression.left, predicate)
|
|
316
|
+
?? findExpression(expression.right, predicate);
|
|
317
|
+
case 'functionCallExpression':
|
|
318
|
+
for (const argument of expression.arguments) {
|
|
319
|
+
const found = findExpression(argument, predicate);
|
|
320
|
+
if (found) return found;
|
|
321
|
+
}
|
|
322
|
+
return null;
|
|
323
|
+
case 'existenceExpression':
|
|
324
|
+
case 'cardinalityExpression':
|
|
325
|
+
return findExpression(expression.argument, predicate);
|
|
326
|
+
case 'projectionExpression':
|
|
327
|
+
for (const field of expression.fields) {
|
|
328
|
+
const found = findExpression(field.expression, predicate);
|
|
329
|
+
if (found) return found;
|
|
330
|
+
}
|
|
331
|
+
return null;
|
|
332
|
+
default:
|
|
333
|
+
return null;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
export function resolveAddress(input, namespace, options = {}) {
|
|
338
|
+
const parsed = typeof input === 'string' ? parseAddress(input, options.parse) : { ok: true, address: input };
|
|
339
|
+
if (!parsed.ok) return { ok: false, bindings: [], errors: parsed.errors };
|
|
340
|
+
|
|
341
|
+
const rootResult = resolveRoot(parsed.address.root, namespace, options);
|
|
342
|
+
if (!rootResult.ok) return { ok: false, bindings: [], errors: [rootResult.error] };
|
|
343
|
+
|
|
344
|
+
let current = [rootResult.binding];
|
|
345
|
+
for (let index = 0; index < parsed.address.selectors.length; index += 1) {
|
|
346
|
+
const selector = parsed.address.selectors[index];
|
|
347
|
+
const selected = applyResolveSelector(
|
|
348
|
+
selector,
|
|
349
|
+
current,
|
|
350
|
+
namespace,
|
|
351
|
+
index,
|
|
352
|
+
{
|
|
353
|
+
effectiveRoot: options.allowParentFromEffectiveRoot === true ? undefined : rootResult.binding,
|
|
354
|
+
parentTraversal: options.parentTraversal,
|
|
355
|
+
failOnParentFromEffectiveRoot: options.failOnParentFromEffectiveRoot === true,
|
|
356
|
+
},
|
|
357
|
+
);
|
|
358
|
+
if (!selected.ok) return { ok: false, bindings: [], errors: [selected.error] };
|
|
359
|
+
current = selected.bindings;
|
|
360
|
+
if (current.length === 0) break;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
if (parsed.address.isExact && current.length > 1) {
|
|
364
|
+
return {
|
|
365
|
+
ok: false,
|
|
366
|
+
bindings: [],
|
|
367
|
+
errors: [
|
|
368
|
+
resolveError(
|
|
369
|
+
'SANSA_RESOLVE_EXACT_MULTIPLICITY_VIOLATION',
|
|
370
|
+
'Exact SANSA resolution produced more than one binding',
|
|
371
|
+
),
|
|
372
|
+
],
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
return { ok: true, bindings: current, diagnostics: [] };
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
export function renderAddress(address) {
|
|
380
|
+
let output = address.root.kind === 'absolute' ? '$' : '?';
|
|
381
|
+
|
|
382
|
+
for (const selector of address.selectors) {
|
|
383
|
+
switch (selector.type) {
|
|
384
|
+
case 'member':
|
|
385
|
+
output += IDENTIFIER_RE.test(selector.name)
|
|
386
|
+
? `.${selector.name}`
|
|
387
|
+
: `.[${quotePayload(selector.name)}]`;
|
|
388
|
+
break;
|
|
389
|
+
case 'position':
|
|
390
|
+
output += `[${selector.index}]`;
|
|
391
|
+
break;
|
|
392
|
+
case 'positionRange':
|
|
393
|
+
output += `[${selector.start ?? ''}..${selector.end ?? ''}]`;
|
|
394
|
+
break;
|
|
395
|
+
case 'parent':
|
|
396
|
+
output += '.^';
|
|
397
|
+
break;
|
|
398
|
+
case 'attributeSpace':
|
|
399
|
+
output += '.@';
|
|
400
|
+
break;
|
|
401
|
+
case 'localSpace':
|
|
402
|
+
output += `.<${quotePayload(selector.name)}>`;
|
|
403
|
+
break;
|
|
404
|
+
case 'directExpansion':
|
|
405
|
+
output += '.*';
|
|
406
|
+
break;
|
|
407
|
+
case 'descendantExpansion':
|
|
408
|
+
output += '.**';
|
|
409
|
+
break;
|
|
410
|
+
case 'namePattern':
|
|
411
|
+
output += `.(${quotePayload(selector.pattern)})`;
|
|
412
|
+
break;
|
|
413
|
+
case 'semanticTypeFilter':
|
|
414
|
+
output += `#${selector.name}`;
|
|
415
|
+
break;
|
|
416
|
+
case 'representationKindFilter':
|
|
417
|
+
output += `%${selector.name}`;
|
|
418
|
+
break;
|
|
419
|
+
default:
|
|
420
|
+
throw new Error(`Unknown selector type: ${selector.type}`);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
if (address.qualifierExpression) {
|
|
425
|
+
output += `:${renderQualifierExpression(address.qualifierExpression)}`;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
return output;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
export function renderQuery(query) {
|
|
432
|
+
const lines = [`from ${renderQueryFromClause(query.from)}`];
|
|
433
|
+
if (query.where) lines.push(`where ${renderQueryExpression(query.where.ast)}`);
|
|
434
|
+
if (query.orderBy) {
|
|
435
|
+
lines.push(`order by ${query.orderBy.keys.map((key) => `${renderQueryExpression(key.ast)} ${key.direction}`).join(', ')}`);
|
|
436
|
+
}
|
|
437
|
+
if (query.offset) lines.push(`offset ${query.offset.value}`);
|
|
438
|
+
if (query.limit) lines.push(`limit ${query.limit.value}`);
|
|
439
|
+
lines.push(`select ${renderQueryExpression(query.select.ast)}`);
|
|
440
|
+
return lines.join('\n');
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function renderQueryFromClause(from) {
|
|
444
|
+
return from.source === 'expression'
|
|
445
|
+
? renderQueryExpression(from.ast)
|
|
446
|
+
: renderAddress(from.address);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
export function renderQueryExpression(expression) {
|
|
450
|
+
switch (expression.type) {
|
|
451
|
+
case 'literalExpression':
|
|
452
|
+
return expression.kind === 'string' ? quotePayload(expression.value) : String(expression.value);
|
|
453
|
+
case 'currentBindingExpression':
|
|
454
|
+
return '.';
|
|
455
|
+
case 'resolutionExpression':
|
|
456
|
+
return expression.canonical;
|
|
457
|
+
case 'groupExpression':
|
|
458
|
+
return `(${renderQueryExpression(expression.expression)})`;
|
|
459
|
+
case 'unaryExpression':
|
|
460
|
+
return `${expression.operator} ${renderQueryExpression(expression.argument)}`;
|
|
461
|
+
case 'binaryExpression':
|
|
462
|
+
return `${renderQueryExpression(expression.left)} ${expression.operator} ${renderQueryExpression(expression.right)}`;
|
|
463
|
+
case 'functionCallExpression':
|
|
464
|
+
return `${expression.name}(${expression.arguments.map((argument) => renderQueryExpression(argument)).join(', ')})`;
|
|
465
|
+
case 'existenceExpression':
|
|
466
|
+
return `${expression.operator}(${renderQueryExpression(expression.argument)})`;
|
|
467
|
+
case 'cardinalityExpression':
|
|
468
|
+
return `${expression.operator}(${renderQueryExpression(expression.argument)})`;
|
|
469
|
+
case 'projectionExpression':
|
|
470
|
+
return `{ ${expression.fields.map((field) => `${field.name} = ${renderQueryExpression(field.expression)}`).join(' ')} }`;
|
|
471
|
+
default:
|
|
472
|
+
throw new Error(`Unknown query expression type: ${expression.type}`);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
function resolveRoot(root, namespace, options) {
|
|
477
|
+
if (!namespace || typeof namespace !== 'object') {
|
|
478
|
+
return { ok: false, error: resolveError('SANSA_RESOLVE_EXPECTED_NAMESPACE', 'Expected SANSA resolve namespace') };
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
if (root.kind === 'contextual') {
|
|
482
|
+
const binding = options.contextualRoot ?? namespace.contextualRoot;
|
|
483
|
+
if (isBindingObject(binding)) return { ok: true, binding };
|
|
484
|
+
return {
|
|
485
|
+
ok: false,
|
|
486
|
+
error: resolveError('SANSA_RESOLVE_UNSUPPORTED_CONTEXTUAL_ROOT', 'Contextual root requires a contextualRoot binding'),
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
const rootBinding = typeof namespace.root === 'function' ? namespace.root() : namespace.root;
|
|
491
|
+
if (rootBinding) return { ok: true, binding: rootBinding };
|
|
492
|
+
return { ok: false, error: resolveError('SANSA_RESOLVE_MISSING_ROOT', 'SANSA resolve namespace does not expose a root binding') };
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
function isBindingObject(value) {
|
|
496
|
+
return value !== null && typeof value === 'object';
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function evaluateQueryFromClause(from, namespace, options) {
|
|
500
|
+
if (from.source !== 'expression') {
|
|
501
|
+
return resolveAddress(from.address, namespace, options.resolve);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
const rootResult = resolveRoot({ kind: 'absolute' }, namespace, options.resolve ?? {});
|
|
505
|
+
if (!rootResult.ok) return { ok: false, bindings: [], errors: [rootResult.error] };
|
|
506
|
+
|
|
507
|
+
const evaluated = evaluateQueryExpressionValue(from.ast, rootResult.binding, namespace, options);
|
|
508
|
+
if (!evaluated.ok) return { ok: false, bindings: [], errors: [evaluated.error] };
|
|
509
|
+
if (evaluated.value.type !== 'bindingSet') {
|
|
510
|
+
return {
|
|
511
|
+
ok: false,
|
|
512
|
+
bindings: [],
|
|
513
|
+
errors: [
|
|
514
|
+
queryEvaluateError(
|
|
515
|
+
'SANSA_QUERY_EVALUATE_INVALID_FROM_SOURCE',
|
|
516
|
+
"Dynamic 'from' source expression must evaluate to a Binding Set",
|
|
517
|
+
),
|
|
518
|
+
],
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
return { ok: true, bindings: evaluated.value.bindings, diagnostics: [] };
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function evaluateQueryExpressionValue(expression, currentBinding, namespace, options) {
|
|
525
|
+
switch (expression.type) {
|
|
526
|
+
case 'literalExpression':
|
|
527
|
+
return {
|
|
528
|
+
ok: true,
|
|
529
|
+
value: {
|
|
530
|
+
type: 'scalar',
|
|
531
|
+
value: expression.value,
|
|
532
|
+
},
|
|
533
|
+
};
|
|
534
|
+
case 'currentBindingExpression':
|
|
535
|
+
return {
|
|
536
|
+
ok: true,
|
|
537
|
+
value: {
|
|
538
|
+
type: 'bindingSet',
|
|
539
|
+
bindings: [currentBinding],
|
|
540
|
+
},
|
|
541
|
+
};
|
|
542
|
+
case 'resolutionExpression':
|
|
543
|
+
return evaluateResolutionExpression(expression, currentBinding, namespace, options);
|
|
544
|
+
case 'groupExpression':
|
|
545
|
+
return evaluateQueryExpressionValue(expression.expression, currentBinding, namespace, options);
|
|
546
|
+
case 'unaryExpression':
|
|
547
|
+
return evaluateUnaryExpression(expression, currentBinding, namespace, options);
|
|
548
|
+
case 'binaryExpression':
|
|
549
|
+
return evaluateBinaryExpression(expression, currentBinding, namespace, options);
|
|
550
|
+
case 'projectionExpression':
|
|
551
|
+
return evaluateProjectionExpression(expression, currentBinding, namespace, options);
|
|
552
|
+
case 'functionCallExpression':
|
|
553
|
+
return evaluateFunctionCallExpression(expression, currentBinding, namespace, options);
|
|
554
|
+
case 'existenceExpression':
|
|
555
|
+
return evaluateExistenceExpression(expression, currentBinding, namespace, options);
|
|
556
|
+
case 'cardinalityExpression':
|
|
557
|
+
return evaluateCardinalityExpression(expression, currentBinding, namespace, options);
|
|
558
|
+
default:
|
|
559
|
+
return {
|
|
560
|
+
ok: false,
|
|
561
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_UNSUPPORTED_EXPRESSION', `Unsupported query expression type: ${expression.type}`),
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function evaluateResolutionExpression(expression, currentBinding, namespace, options) {
|
|
567
|
+
const resolveOptions = {
|
|
568
|
+
...(options.resolve ?? {}),
|
|
569
|
+
...(['current', 'contextual'].includes(expression.scope) ? { contextualRoot: currentBinding } : {}),
|
|
570
|
+
...(expression.scope === 'current' ? { allowParentFromEffectiveRoot: true } : {}),
|
|
571
|
+
};
|
|
572
|
+
const resolved = resolveAddress(expression.address, namespace, resolveOptions);
|
|
573
|
+
if (!resolved.ok) return { ok: false, error: resolved.errors[0] };
|
|
574
|
+
return {
|
|
575
|
+
ok: true,
|
|
576
|
+
value: {
|
|
577
|
+
type: 'bindingSet',
|
|
578
|
+
bindings: resolved.bindings,
|
|
579
|
+
},
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
function evaluateUnaryExpression(expression, currentBinding, namespace, options) {
|
|
584
|
+
const evaluated = evaluateQueryExpressionValue(expression.argument, currentBinding, namespace, options);
|
|
585
|
+
if (!evaluated.ok) return evaluated;
|
|
586
|
+
const boolean = expectBooleanQueryValue(evaluated.value, namespace);
|
|
587
|
+
if (!boolean.ok) return boolean;
|
|
588
|
+
return {
|
|
589
|
+
ok: true,
|
|
590
|
+
value: {
|
|
591
|
+
type: 'scalar',
|
|
592
|
+
value: !boolean.value,
|
|
593
|
+
},
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
function evaluateBinaryExpression(expression, currentBinding, namespace, options) {
|
|
598
|
+
if (expression.operator === 'and' || expression.operator === 'or') {
|
|
599
|
+
return evaluateBooleanBinaryExpression(expression, currentBinding, namespace, options);
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
const left = evaluateQueryExpressionValue(expression.left, currentBinding, namespace, options);
|
|
603
|
+
if (!left.ok) return left;
|
|
604
|
+
const right = evaluateQueryExpressionValue(expression.right, currentBinding, namespace, options);
|
|
605
|
+
if (!right.ok) return right;
|
|
606
|
+
|
|
607
|
+
if (expression.operator === 'in') {
|
|
608
|
+
return evaluateMembershipExpression(left.value, right.value, namespace);
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
const leftScalar = expectScalarQueryValue(left.value, namespace);
|
|
612
|
+
if (!leftScalar.ok) return leftScalar;
|
|
613
|
+
const rightScalar = expectScalarQueryValue(right.value, namespace);
|
|
614
|
+
if (!rightScalar.ok) return rightScalar;
|
|
615
|
+
return compareQueryScalars(expression.operator, leftScalar.value, rightScalar.value);
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
function evaluateMembershipExpression(leftValue, rightValue, namespace) {
|
|
619
|
+
const leftScalar = expectScalarQueryValue(leftValue, namespace);
|
|
620
|
+
if (!leftScalar.ok) return leftScalar;
|
|
621
|
+
|
|
622
|
+
if (rightValue.type !== 'bindingSet') {
|
|
623
|
+
return {
|
|
624
|
+
ok: false,
|
|
625
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_COMPARISON', 'Membership right operand must evaluate to a Binding Set'),
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
for (const binding of rightValue.bindings) {
|
|
630
|
+
const rightScalar = getBindingScalarValue(namespace, binding);
|
|
631
|
+
if (!rightScalar.ok) return rightScalar;
|
|
632
|
+
const compared = compareQueryScalars('==', leftScalar.value, rightScalar.value);
|
|
633
|
+
if (!compared.ok) return compared;
|
|
634
|
+
if (compared.value.value) {
|
|
635
|
+
return {
|
|
636
|
+
ok: true,
|
|
637
|
+
value: {
|
|
638
|
+
type: 'scalar',
|
|
639
|
+
value: true,
|
|
640
|
+
},
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
return {
|
|
646
|
+
ok: true,
|
|
647
|
+
value: {
|
|
648
|
+
type: 'scalar',
|
|
649
|
+
value: false,
|
|
650
|
+
},
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
function evaluateBooleanBinaryExpression(expression, currentBinding, namespace, options) {
|
|
655
|
+
const left = evaluateQueryExpressionValue(expression.left, currentBinding, namespace, options);
|
|
656
|
+
if (!left.ok) return left;
|
|
657
|
+
const leftBoolean = expectBooleanQueryValue(left.value, namespace);
|
|
658
|
+
if (!leftBoolean.ok) return leftBoolean;
|
|
659
|
+
|
|
660
|
+
if (expression.operator === 'and' && leftBoolean.value === false) {
|
|
661
|
+
return { ok: true, value: { type: 'scalar', value: false } };
|
|
662
|
+
}
|
|
663
|
+
if (expression.operator === 'or' && leftBoolean.value === true) {
|
|
664
|
+
return { ok: true, value: { type: 'scalar', value: true } };
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
const right = evaluateQueryExpressionValue(expression.right, currentBinding, namespace, options);
|
|
668
|
+
if (!right.ok) return right;
|
|
669
|
+
const rightBoolean = expectBooleanQueryValue(right.value, namespace);
|
|
670
|
+
if (!rightBoolean.ok) return rightBoolean;
|
|
671
|
+
return {
|
|
672
|
+
ok: true,
|
|
673
|
+
value: {
|
|
674
|
+
type: 'scalar',
|
|
675
|
+
value: expression.operator === 'and'
|
|
676
|
+
? leftBoolean.value && rightBoolean.value
|
|
677
|
+
: leftBoolean.value || rightBoolean.value,
|
|
678
|
+
},
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
function evaluateProjectionExpression(expression, currentBinding, namespace, options) {
|
|
683
|
+
const value = {};
|
|
684
|
+
const fieldMetadata = {};
|
|
685
|
+
for (const field of expression.fields) {
|
|
686
|
+
const evaluated = evaluateQueryExpressionValue(field.expression, currentBinding, namespace, options);
|
|
687
|
+
if (!evaluated.ok) return evaluated;
|
|
688
|
+
const metadata = queryValueMetadata(evaluated.value, namespace);
|
|
689
|
+
const unwrapped = unwrapQueryValue(evaluated.value, namespace);
|
|
690
|
+
if (!unwrapped.ok) return unwrapped;
|
|
691
|
+
value[field.name] = unwrapped.value;
|
|
692
|
+
if (metadata) fieldMetadata[field.name] = metadata;
|
|
693
|
+
}
|
|
694
|
+
if (Object.keys(fieldMetadata).length > 0) {
|
|
695
|
+
Object.defineProperty(value, QUERY_OBJECT_FIELD_METADATA_PROPERTY, {
|
|
696
|
+
value: fieldMetadata,
|
|
697
|
+
enumerable: false,
|
|
698
|
+
});
|
|
699
|
+
}
|
|
700
|
+
return {
|
|
701
|
+
ok: true,
|
|
702
|
+
value: {
|
|
703
|
+
type: 'object',
|
|
704
|
+
value,
|
|
705
|
+
},
|
|
706
|
+
};
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
function evaluateFunctionCallExpression(expression, currentBinding, namespace, options) {
|
|
710
|
+
if (isSpecialValuePredicateName(expression.name)) {
|
|
711
|
+
return evaluateSpecialValuePredicate(expression, currentBinding, namespace, options);
|
|
712
|
+
}
|
|
713
|
+
if (expression.name === 'path') {
|
|
714
|
+
return evaluatePathExpression(expression, currentBinding, namespace, options);
|
|
715
|
+
}
|
|
716
|
+
if (expression.name === 'fallback') {
|
|
717
|
+
return evaluateFallbackExpression(expression, currentBinding, namespace, options);
|
|
718
|
+
}
|
|
719
|
+
if (expression.name === 'resolveChild') {
|
|
720
|
+
return evaluateResolveChildExpression(expression, currentBinding, namespace, options);
|
|
721
|
+
}
|
|
722
|
+
if (expression.name === 'objectFrom') {
|
|
723
|
+
const extension = expectEnabledExtension(expression.name, options);
|
|
724
|
+
if (!extension.ok) return extension;
|
|
725
|
+
return evaluateObjectFromExpression(expression, currentBinding, namespace, options);
|
|
726
|
+
}
|
|
727
|
+
if (expression.name === 'fieldsFrom') {
|
|
728
|
+
const extension = expectEnabledExtension(expression.name, options);
|
|
729
|
+
if (!extension.ok) return extension;
|
|
730
|
+
return evaluateFieldsFromExpression(expression, currentBinding, namespace, options);
|
|
731
|
+
}
|
|
732
|
+
if (!isOrdinaryFunctionName(expression.name)) {
|
|
733
|
+
return {
|
|
734
|
+
ok: false,
|
|
735
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_UNSUPPORTED_FUNCTION', `Function '${expression.name}' is not supported by this evaluator slice`),
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
const evaluatedArgs = [];
|
|
740
|
+
for (const argument of expression.arguments) {
|
|
741
|
+
const evaluated = evaluateQueryExpressionValue(argument, currentBinding, namespace, options);
|
|
742
|
+
if (!evaluated.ok) return evaluated;
|
|
743
|
+
const scalar = expectScalarQueryValue(evaluated.value, namespace);
|
|
744
|
+
if (!scalar.ok) return scalar;
|
|
745
|
+
evaluatedArgs.push(scalar.value);
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
return evaluateOrdinaryFunction(expression.name, evaluatedArgs);
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
function expectEnabledExtension(functionName, options) {
|
|
752
|
+
const extensionId = TRANSFORM_EXTENSION_FUNCTIONS.get(functionName);
|
|
753
|
+
if (!extensionId || isExtensionEnabled(extensionId, options)) return { ok: true };
|
|
754
|
+
return {
|
|
755
|
+
ok: false,
|
|
756
|
+
error: queryEvaluateError(
|
|
757
|
+
'SANSA_QUERY_EVALUATE_UNSUPPORTED_EXTENSION',
|
|
758
|
+
`Function '${functionName}' requires disabled extension '${extensionId}'`,
|
|
759
|
+
{ extension: extensionId },
|
|
760
|
+
),
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
function isExtensionEnabled(extensionId, options) {
|
|
765
|
+
const enabledExtensions = options.enabledExtensions;
|
|
766
|
+
if (Array.isArray(enabledExtensions)) return enabledExtensions.includes(extensionId);
|
|
767
|
+
|
|
768
|
+
const extensions = options.extensions;
|
|
769
|
+
if (!extensions || typeof extensions !== 'object') return true;
|
|
770
|
+
if (extensions.transform === false) return false;
|
|
771
|
+
if (extensions.transform === true) return true;
|
|
772
|
+
if (extensionId === 'sansa.transform.objectFrom' && extensions.objectFrom === false) return false;
|
|
773
|
+
if (extensionId === 'sansa.transform.fieldsFrom' && extensions.fieldsFrom === false) return false;
|
|
774
|
+
return true;
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
function isOrdinaryFunctionName(name) {
|
|
778
|
+
return ['contains', 'startsWith', 'endsWith', 'lower', 'upper', 'concat'].includes(name);
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
function evaluateOrdinaryFunction(name, evaluatedArgs) {
|
|
782
|
+
switch (name) {
|
|
783
|
+
case 'contains':
|
|
784
|
+
return evaluateStringFunction(name, evaluatedArgs, 2, ([value, search]) => value.includes(search));
|
|
785
|
+
case 'startsWith':
|
|
786
|
+
return evaluateStringFunction(name, evaluatedArgs, 2, ([value, search]) => value.startsWith(search));
|
|
787
|
+
case 'endsWith':
|
|
788
|
+
return evaluateStringFunction(name, evaluatedArgs, 2, ([value, search]) => value.endsWith(search));
|
|
789
|
+
case 'lower':
|
|
790
|
+
return evaluateStringFunction(name, evaluatedArgs, 1, ([value]) => value.toLowerCase());
|
|
791
|
+
case 'upper':
|
|
792
|
+
return evaluateStringFunction(name, evaluatedArgs, 1, ([value]) => value.toUpperCase());
|
|
793
|
+
case 'concat':
|
|
794
|
+
if (evaluatedArgs.length === 0) {
|
|
795
|
+
return {
|
|
796
|
+
ok: false,
|
|
797
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', "Function 'concat' expects at least one argument"),
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
return evaluateStringFunction(name, evaluatedArgs, evaluatedArgs.length, (args) => args.join(''));
|
|
801
|
+
default:
|
|
802
|
+
return {
|
|
803
|
+
ok: false,
|
|
804
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_UNSUPPORTED_FUNCTION', `Function '${name}' is not supported by this evaluator slice`),
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
function evaluatePathExpression(expression, currentBinding, namespace, options) {
|
|
810
|
+
if (expression.arguments.length !== 1) {
|
|
811
|
+
return {
|
|
812
|
+
ok: false,
|
|
813
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', "Function 'path' expects 1 argument"),
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
const evaluated = evaluateQueryExpressionValue(expression.arguments[0], currentBinding, namespace, options);
|
|
818
|
+
if (!evaluated.ok) return evaluated;
|
|
819
|
+
const scalar = expectScalarQueryValue(evaluated.value, namespace);
|
|
820
|
+
if (!scalar.ok) return scalar;
|
|
821
|
+
|
|
822
|
+
const activated = activateAddressLiteral(scalar.value, options.parse?.address);
|
|
823
|
+
if (!activated.ok) return activated;
|
|
824
|
+
|
|
825
|
+
const resolved = resolveAddress(activated.address, namespace, {
|
|
826
|
+
...(options.resolve ?? {}),
|
|
827
|
+
contextualRoot: currentBinding,
|
|
828
|
+
});
|
|
829
|
+
if (!resolved.ok) return { ok: false, error: resolved.errors[0] };
|
|
830
|
+
return {
|
|
831
|
+
ok: true,
|
|
832
|
+
value: {
|
|
833
|
+
type: 'bindingSet',
|
|
834
|
+
bindings: resolved.bindings,
|
|
835
|
+
},
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
function activateAddressLiteral(value, parseOptions) {
|
|
840
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
841
|
+
return {
|
|
842
|
+
ok: false,
|
|
843
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_PATH_LITERAL', "Function 'path' expects a SANSA Address Literal value"),
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
if (value.type === 'SansaAddress' && value.root && Array.isArray(value.selectors)) {
|
|
848
|
+
return { ok: true, address: value };
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
if (value.type !== 'SansaAddressLiteral') {
|
|
852
|
+
return {
|
|
853
|
+
ok: false,
|
|
854
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_PATH_LITERAL', "Function 'path' expects a SANSA Address Literal value"),
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
if (value.address && typeof value.address === 'object') {
|
|
859
|
+
return { ok: true, address: value.address };
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
const source = typeof value.canonical === 'string'
|
|
863
|
+
? value.canonical
|
|
864
|
+
: typeof value.source === 'string'
|
|
865
|
+
? value.source
|
|
866
|
+
: typeof value.address === 'string'
|
|
867
|
+
? value.address
|
|
868
|
+
: null;
|
|
869
|
+
if (source === null) {
|
|
870
|
+
return {
|
|
871
|
+
ok: false,
|
|
872
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_PATH_LITERAL', "Function 'path' expects a structured address literal"),
|
|
873
|
+
};
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
const parsed = parseAddress(source, parseOptions);
|
|
877
|
+
if (!parsed.ok) {
|
|
878
|
+
return {
|
|
879
|
+
ok: false,
|
|
880
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_PATH_LITERAL', "Function 'path' received an invalid SANSA Address Literal", {
|
|
881
|
+
cause: parsed.errors[0],
|
|
882
|
+
}),
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
return { ok: true, address: parsed.address };
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
function evaluateFallbackExpression(expression, currentBinding, namespace, options) {
|
|
889
|
+
if (expression.arguments.length !== 2) {
|
|
890
|
+
return {
|
|
891
|
+
ok: false,
|
|
892
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', "Function 'fallback' expects 2 arguments"),
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
const primary = evaluateQueryExpressionValue(expression.arguments[0], currentBinding, namespace, options);
|
|
897
|
+
if (!primary.ok) {
|
|
898
|
+
if (primary.error.code === 'SANSA_QUERY_EVALUATE_MISSING_SCALAR') {
|
|
899
|
+
return evaluateFallbackReplacement(expression.arguments[1], currentBinding, namespace, options);
|
|
900
|
+
}
|
|
901
|
+
return primary;
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
const primaryValue = consumeFallbackOperand(primary.value, namespace);
|
|
905
|
+
if (primaryValue.ok) return primaryValue;
|
|
906
|
+
if (primaryValue.missing) {
|
|
907
|
+
return evaluateFallbackReplacement(expression.arguments[1], currentBinding, namespace, options);
|
|
908
|
+
}
|
|
909
|
+
return primaryValue;
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
function evaluateFallbackReplacement(expression, currentBinding, namespace, options) {
|
|
913
|
+
const replacement = evaluateQueryExpressionValue(expression, currentBinding, namespace, options);
|
|
914
|
+
if (!replacement.ok) return replacement;
|
|
915
|
+
const replacementValue = consumeFallbackOperand(replacement.value, namespace);
|
|
916
|
+
if (replacementValue.ok) return replacementValue;
|
|
917
|
+
if (replacementValue.missing) {
|
|
918
|
+
return {
|
|
919
|
+
ok: false,
|
|
920
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_MISSING_SCALAR', "Function 'fallback' replacement resolved no scalar value"),
|
|
921
|
+
};
|
|
922
|
+
}
|
|
923
|
+
return replacementValue;
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
function consumeFallbackOperand(value, namespace) {
|
|
927
|
+
if (value.type !== 'bindingSet') {
|
|
928
|
+
return { ok: true, value };
|
|
929
|
+
}
|
|
930
|
+
if (value.bindings.length === 0) {
|
|
931
|
+
return { ok: false, missing: true };
|
|
932
|
+
}
|
|
933
|
+
if (value.bindings.length > 1) {
|
|
934
|
+
return {
|
|
935
|
+
ok: false,
|
|
936
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_CARDINALITY', "Function 'fallback' expected one binding but resolved multiple bindings"),
|
|
937
|
+
};
|
|
938
|
+
}
|
|
939
|
+
const scalar = getBindingScalarValue(namespace, value.bindings[0]);
|
|
940
|
+
if (!scalar.ok) return scalar;
|
|
941
|
+
return scalarQueryValue(scalar.value, scalar.metadata);
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
function evaluateResolveChildExpression(expression, currentBinding, namespace, options) {
|
|
945
|
+
if (expression.arguments.length !== 2) {
|
|
946
|
+
return {
|
|
947
|
+
ok: false,
|
|
948
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', "Function 'resolveChild' expects 2 arguments"),
|
|
949
|
+
};
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
const baseResolution = unwrapResolutionExpression(expression.arguments[0]);
|
|
953
|
+
if (!baseResolution) {
|
|
954
|
+
return {
|
|
955
|
+
ok: false,
|
|
956
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', "Function 'resolveChild' expects a resolution expression base"),
|
|
957
|
+
};
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
const base = evaluateResolutionExpression(baseResolution, currentBinding, namespace, options);
|
|
961
|
+
if (!base.ok) return base;
|
|
962
|
+
if (base.value.bindings.length === 0) {
|
|
963
|
+
return {
|
|
964
|
+
ok: false,
|
|
965
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_MISSING_SCALAR', "Function 'resolveChild' expected one base binding but resolved none"),
|
|
966
|
+
};
|
|
967
|
+
}
|
|
968
|
+
if (base.value.bindings.length > 1) {
|
|
969
|
+
return {
|
|
970
|
+
ok: false,
|
|
971
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_CARDINALITY', "Function 'resolveChild' expected one base binding but resolved multiple bindings"),
|
|
972
|
+
};
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
const key = evaluateQueryExpressionValue(expression.arguments[1], currentBinding, namespace, options);
|
|
976
|
+
if (!key.ok) return key;
|
|
977
|
+
const keyScalar = expectScalarQueryValue(key.value, namespace);
|
|
978
|
+
if (!keyScalar.ok) return keyScalar;
|
|
979
|
+
|
|
980
|
+
let bindings;
|
|
981
|
+
if (typeof keyScalar.value === 'string') {
|
|
982
|
+
bindings = selectMember(namespace, base.value.bindings[0], keyScalar.value);
|
|
983
|
+
} else if (Number.isInteger(keyScalar.value) && keyScalar.value >= 0) {
|
|
984
|
+
bindings = selectPosition(namespace, base.value.bindings[0], keyScalar.value);
|
|
985
|
+
} else {
|
|
986
|
+
return {
|
|
987
|
+
ok: false,
|
|
988
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', "Function 'resolveChild' expects a string member key or non-negative integer position key"),
|
|
989
|
+
};
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
if (bindings.length > 1) {
|
|
993
|
+
return {
|
|
994
|
+
ok: false,
|
|
995
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_CARDINALITY', "Function 'resolveChild' target resolved multiple bindings"),
|
|
996
|
+
};
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
return {
|
|
1000
|
+
ok: true,
|
|
1001
|
+
value: {
|
|
1002
|
+
type: 'bindingSet',
|
|
1003
|
+
bindings,
|
|
1004
|
+
},
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
function evaluateObjectFromExpression(expression, currentBinding, namespace, options) {
|
|
1009
|
+
if (expression.arguments.length !== 2) {
|
|
1010
|
+
return {
|
|
1011
|
+
ok: false,
|
|
1012
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', "Function 'objectFrom' expects 2 arguments"),
|
|
1013
|
+
};
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
const keyResolution = unwrapResolutionExpression(expression.arguments[0]);
|
|
1017
|
+
const valueResolution = unwrapResolutionExpression(expression.arguments[1]);
|
|
1018
|
+
if (!keyResolution || !valueResolution) {
|
|
1019
|
+
return {
|
|
1020
|
+
ok: false,
|
|
1021
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', "Function 'objectFrom' expects resolution expression arguments"),
|
|
1022
|
+
};
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
const keys = evaluateResolutionExpression(keyResolution, currentBinding, namespace, options);
|
|
1026
|
+
if (!keys.ok) return keys;
|
|
1027
|
+
const values = evaluateResolutionExpression(valueResolution, currentBinding, namespace, options);
|
|
1028
|
+
if (!values.ok) return values;
|
|
1029
|
+
|
|
1030
|
+
return objectFromBindingSets(keys.value.bindings, values.value.bindings, namespace, 'objectFrom');
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
function evaluateFieldsFromExpression(expression, currentBinding, namespace, options) {
|
|
1034
|
+
if (expression.arguments.length < 3) {
|
|
1035
|
+
return {
|
|
1036
|
+
ok: false,
|
|
1037
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', "Function 'fieldsFrom' expects headers, values, and at least one field name"),
|
|
1038
|
+
};
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
const keyResolution = unwrapResolutionExpression(expression.arguments[0]);
|
|
1042
|
+
const valueResolution = unwrapResolutionExpression(expression.arguments[1]);
|
|
1043
|
+
if (!keyResolution || !valueResolution) {
|
|
1044
|
+
return {
|
|
1045
|
+
ok: false,
|
|
1046
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', "Function 'fieldsFrom' expects resolution expression header and value arguments"),
|
|
1047
|
+
};
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
const requested = [];
|
|
1051
|
+
for (const argument of expression.arguments.slice(2)) {
|
|
1052
|
+
const evaluated = evaluateQueryExpressionValue(argument, currentBinding, namespace, options);
|
|
1053
|
+
if (!evaluated.ok) return evaluated;
|
|
1054
|
+
const scalar = expectScalarQueryValue(evaluated.value, namespace);
|
|
1055
|
+
if (!scalar.ok) return scalar;
|
|
1056
|
+
if (typeof scalar.value !== 'string') {
|
|
1057
|
+
return {
|
|
1058
|
+
ok: false,
|
|
1059
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', "Function 'fieldsFrom' expects string field names"),
|
|
1060
|
+
};
|
|
1061
|
+
}
|
|
1062
|
+
if (requested.includes(scalar.value)) {
|
|
1063
|
+
return {
|
|
1064
|
+
ok: false,
|
|
1065
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', `Function 'fieldsFrom' received duplicate requested field '${scalar.value}'`),
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
requested.push(scalar.value);
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
const keys = evaluateResolutionExpression(keyResolution, currentBinding, namespace, options);
|
|
1072
|
+
if (!keys.ok) return keys;
|
|
1073
|
+
const values = evaluateResolutionExpression(valueResolution, currentBinding, namespace, options);
|
|
1074
|
+
if (!values.ok) return values;
|
|
1075
|
+
|
|
1076
|
+
return objectFromBindingSets(keys.value.bindings, values.value.bindings, namespace, 'fieldsFrom', new Set(requested));
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
function objectFromBindingSets(keyBindings, valueBindings, namespace, functionName, requestedFields = null) {
|
|
1080
|
+
if (keyBindings.length !== valueBindings.length) {
|
|
1081
|
+
return {
|
|
1082
|
+
ok: false,
|
|
1083
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_CARDINALITY', `Function '${functionName}' expected key and value binding sets with equal length`),
|
|
1084
|
+
};
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
const output = {};
|
|
1088
|
+
const fieldMetadata = {};
|
|
1089
|
+
const observedRequestedFields = new Set();
|
|
1090
|
+
for (let index = 0; index < keyBindings.length; index += 1) {
|
|
1091
|
+
const keyScalar = getBindingScalarValue(namespace, keyBindings[index]);
|
|
1092
|
+
if (!keyScalar.ok) return keyScalar;
|
|
1093
|
+
if (typeof keyScalar.value !== 'string') {
|
|
1094
|
+
return {
|
|
1095
|
+
ok: false,
|
|
1096
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', `Function '${functionName}' expects string key bindings`),
|
|
1097
|
+
};
|
|
1098
|
+
}
|
|
1099
|
+
if (requestedFields && !requestedFields.has(keyScalar.value)) continue;
|
|
1100
|
+
if (Object.hasOwn(output, keyScalar.value)) {
|
|
1101
|
+
return {
|
|
1102
|
+
ok: false,
|
|
1103
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', `Function '${functionName}' received duplicate key '${keyScalar.value}'`),
|
|
1104
|
+
};
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
const valueScalar = getBindingScalarValue(namespace, valueBindings[index]);
|
|
1108
|
+
if (!valueScalar.ok) return valueScalar;
|
|
1109
|
+
output[keyScalar.value] = valueScalar.value;
|
|
1110
|
+
observedRequestedFields.add(keyScalar.value);
|
|
1111
|
+
if (valueScalar.metadata) fieldMetadata[keyScalar.value] = valueScalar.metadata;
|
|
1112
|
+
}
|
|
1113
|
+
if (requestedFields) {
|
|
1114
|
+
for (const field of requestedFields) {
|
|
1115
|
+
if (!observedRequestedFields.has(field)) {
|
|
1116
|
+
return {
|
|
1117
|
+
ok: false,
|
|
1118
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_MISSING_SCALAR', `Function '${functionName}' could not find requested field '${field}'`),
|
|
1119
|
+
};
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
if (Object.keys(fieldMetadata).length > 0) {
|
|
1125
|
+
Object.defineProperty(output, QUERY_OBJECT_FIELD_METADATA_PROPERTY, {
|
|
1126
|
+
value: fieldMetadata,
|
|
1127
|
+
enumerable: false,
|
|
1128
|
+
});
|
|
1129
|
+
}
|
|
1130
|
+
return {
|
|
1131
|
+
ok: true,
|
|
1132
|
+
value: {
|
|
1133
|
+
type: 'object',
|
|
1134
|
+
value: output,
|
|
1135
|
+
},
|
|
1136
|
+
};
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
function isSpecialValuePredicateName(name) {
|
|
1140
|
+
return ['isValue', 'isNull', 'isNullReason', 'isNaN', 'isInfinity'].includes(name);
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
function evaluateSpecialValuePredicate(expression, currentBinding, namespace, options) {
|
|
1144
|
+
const arity = expression.name === 'isNullReason' ? 2 : 1;
|
|
1145
|
+
if (expression.arguments.length !== arity) {
|
|
1146
|
+
return {
|
|
1147
|
+
ok: false,
|
|
1148
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', `Function '${expression.name}' expects ${arity} argument${arity === 1 ? '' : 's'}`),
|
|
1149
|
+
};
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
if (expression.name === 'isValue') {
|
|
1153
|
+
return evaluateIsValuePredicate(expression.arguments[0], currentBinding, namespace, options);
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
const bindingInfo = evaluateSingleBindingArgument(expression.name, expression.arguments[0], currentBinding, namespace, options);
|
|
1157
|
+
if (!bindingInfo.ok) return bindingInfo;
|
|
1158
|
+
|
|
1159
|
+
switch (expression.name) {
|
|
1160
|
+
case 'isNull':
|
|
1161
|
+
return scalarBoolean(isExplicitNullScalar(bindingInfo));
|
|
1162
|
+
case 'isNullReason': {
|
|
1163
|
+
const reason = evaluateQueryExpressionValue(expression.arguments[1], currentBinding, namespace, options);
|
|
1164
|
+
if (!reason.ok) return reason;
|
|
1165
|
+
const scalarReason = expectScalarQueryValue(reason.value, namespace);
|
|
1166
|
+
if (!scalarReason.ok) return scalarReason;
|
|
1167
|
+
if (typeof scalarReason.value !== 'string') {
|
|
1168
|
+
return {
|
|
1169
|
+
ok: false,
|
|
1170
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', "Function 'isNullReason' expects a string reason"),
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
return scalarBoolean(isExplicitNullScalar(bindingInfo) && bindingInfo.nullReason === scalarReason.value);
|
|
1174
|
+
}
|
|
1175
|
+
case 'isNaN':
|
|
1176
|
+
return scalarBoolean(isNanScalar(bindingInfo));
|
|
1177
|
+
case 'isInfinity':
|
|
1178
|
+
return scalarBoolean(isInfinityScalar(bindingInfo));
|
|
1179
|
+
default:
|
|
1180
|
+
return {
|
|
1181
|
+
ok: false,
|
|
1182
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_UNSUPPORTED_FUNCTION', `Function '${expression.name}' is not supported by this evaluator slice`),
|
|
1183
|
+
};
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
function evaluateIsValuePredicate(argument, currentBinding, namespace, options) {
|
|
1188
|
+
const evaluated = evaluateQueryExpressionValue(argument, currentBinding, namespace, options);
|
|
1189
|
+
if (!evaluated.ok) {
|
|
1190
|
+
if (evaluated.error.code === 'SANSA_QUERY_EVALUATE_MISSING_SCALAR') return scalarBoolean(false);
|
|
1191
|
+
return evaluated;
|
|
1192
|
+
}
|
|
1193
|
+
return evaluateIsValueQueryValue(evaluated.value, namespace);
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
function evaluateIsValueQueryValue(value, namespace) {
|
|
1197
|
+
if (value.type === 'scalar') {
|
|
1198
|
+
return scalarBoolean(isOrdinaryValueScalar({
|
|
1199
|
+
value: value.value,
|
|
1200
|
+
...(value[QUERY_VALUE_METADATA_PROPERTY]?.kind === undefined ? {} : { kind: value[QUERY_VALUE_METADATA_PROPERTY].kind }),
|
|
1201
|
+
}));
|
|
1202
|
+
}
|
|
1203
|
+
if (value.type === 'object') return scalarBoolean(false);
|
|
1204
|
+
if (value.type !== 'bindingSet') {
|
|
1205
|
+
return scalarBoolean(false);
|
|
1206
|
+
}
|
|
1207
|
+
if (value.bindings.length === 0) return scalarBoolean(false);
|
|
1208
|
+
if (value.bindings.length > 1) {
|
|
1209
|
+
return {
|
|
1210
|
+
ok: false,
|
|
1211
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_CARDINALITY', "Function 'isValue' expected one binding but resolved multiple bindings"),
|
|
1212
|
+
};
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
const scalar = getBindingScalarInfo(namespace, value.bindings[0]);
|
|
1216
|
+
if (!scalar.ok) {
|
|
1217
|
+
if (scalar.error.code === 'SANSA_QUERY_EVALUATE_MISSING_SCALAR') return scalarBoolean(false);
|
|
1218
|
+
return scalar;
|
|
1219
|
+
}
|
|
1220
|
+
return scalarBoolean(isOrdinaryValueScalar(scalar));
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
function evaluateSingleBindingArgument(name, argument, currentBinding, namespace, options) {
|
|
1224
|
+
const resolution = unwrapResolutionExpression(argument);
|
|
1225
|
+
if (!resolution) {
|
|
1226
|
+
return {
|
|
1227
|
+
ok: false,
|
|
1228
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', `Function '${name}' expects a resolution expression`),
|
|
1229
|
+
};
|
|
1230
|
+
}
|
|
1231
|
+
const evaluated = evaluateResolutionExpression(resolution, currentBinding, namespace, options);
|
|
1232
|
+
if (!evaluated.ok) return evaluated;
|
|
1233
|
+
if (evaluated.value.bindings.length === 0) {
|
|
1234
|
+
return {
|
|
1235
|
+
ok: false,
|
|
1236
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_MISSING_SCALAR', `Function '${name}' expected one binding but resolved none`),
|
|
1237
|
+
};
|
|
1238
|
+
}
|
|
1239
|
+
if (evaluated.value.bindings.length > 1) {
|
|
1240
|
+
return {
|
|
1241
|
+
ok: false,
|
|
1242
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_CARDINALITY', `Function '${name}' expected one binding but resolved multiple bindings`),
|
|
1243
|
+
};
|
|
1244
|
+
}
|
|
1245
|
+
const scalar = getBindingScalarInfo(namespace, evaluated.value.bindings[0]);
|
|
1246
|
+
if (!scalar.ok) return scalar;
|
|
1247
|
+
return scalar;
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
function isExplicitNullScalar(info) {
|
|
1251
|
+
return info.kind === 'null' || info.value === null;
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
function isNanScalar(info) {
|
|
1255
|
+
return info.kind === 'nan' || (typeof info.value === 'number' && Number.isNaN(info.value));
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
function isInfinityScalar(info) {
|
|
1259
|
+
return info.kind === 'infinity' || info.value === Infinity || info.value === -Infinity;
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
function isOrdinaryValueScalar(info) {
|
|
1263
|
+
return isOrdinaryValueDescriptor(scalarInfoToValueDescriptor(info));
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
function scalarBoolean(value) {
|
|
1267
|
+
return scalarQueryValue(value);
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
function scalarQueryValue(value, metadata) {
|
|
1271
|
+
const output = {
|
|
1272
|
+
type: 'scalar',
|
|
1273
|
+
value,
|
|
1274
|
+
};
|
|
1275
|
+
if (metadata) {
|
|
1276
|
+
Object.defineProperty(output, QUERY_VALUE_METADATA_PROPERTY, {
|
|
1277
|
+
value: metadata,
|
|
1278
|
+
enumerable: false,
|
|
1279
|
+
});
|
|
1280
|
+
}
|
|
1281
|
+
return {
|
|
1282
|
+
ok: true,
|
|
1283
|
+
value: output,
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
function evaluateStringFunction(name, args, arity, operation) {
|
|
1288
|
+
if (args.length !== arity) {
|
|
1289
|
+
return {
|
|
1290
|
+
ok: false,
|
|
1291
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', `Function '${name}' expects ${arity} argument${arity === 1 ? '' : 's'}`),
|
|
1292
|
+
};
|
|
1293
|
+
}
|
|
1294
|
+
if (args.some((arg) => typeof arg !== 'string')) {
|
|
1295
|
+
return {
|
|
1296
|
+
ok: false,
|
|
1297
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_FUNCTION_CALL', `Function '${name}' expects string arguments`),
|
|
1298
|
+
};
|
|
1299
|
+
}
|
|
1300
|
+
return {
|
|
1301
|
+
ok: true,
|
|
1302
|
+
value: {
|
|
1303
|
+
type: 'scalar',
|
|
1304
|
+
value: operation(args),
|
|
1305
|
+
},
|
|
1306
|
+
};
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
function evaluateExistenceExpression(expression, currentBinding, namespace, options) {
|
|
1310
|
+
const resolution = unwrapResolutionExpression(expression.argument);
|
|
1311
|
+
if (!resolution) {
|
|
1312
|
+
return {
|
|
1313
|
+
ok: false,
|
|
1314
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_EXISTENCE_ARGUMENT', 'Existence operators require a resolution expression'),
|
|
1315
|
+
};
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
const resolved = evaluateResolutionExpression(resolution, currentBinding, namespace, options);
|
|
1319
|
+
if (!resolved.ok) return resolved;
|
|
1320
|
+
const hasBindings = resolved.value.bindings.length > 0;
|
|
1321
|
+
return {
|
|
1322
|
+
ok: true,
|
|
1323
|
+
value: {
|
|
1324
|
+
type: 'scalar',
|
|
1325
|
+
value: expression.operator === 'exists' ? hasBindings : !hasBindings,
|
|
1326
|
+
},
|
|
1327
|
+
};
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
function unwrapResolutionExpression(expression) {
|
|
1331
|
+
if (expression.type === 'groupExpression') return unwrapResolutionExpression(expression.expression);
|
|
1332
|
+
return expression.type === 'resolutionExpression' ? expression : null;
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
function evaluateCardinalityExpression(expression, currentBinding, namespace, options) {
|
|
1336
|
+
const booleans = evaluateCardinalityBooleans(expression.argument, currentBinding, namespace, options);
|
|
1337
|
+
if (!booleans.ok) return booleans;
|
|
1338
|
+
const value = (() => {
|
|
1339
|
+
switch (expression.operator) {
|
|
1340
|
+
case 'any': return booleans.values.some(Boolean);
|
|
1341
|
+
case 'all': return booleans.values.every(Boolean);
|
|
1342
|
+
case 'none': return booleans.values.every((entry) => !entry);
|
|
1343
|
+
default: return false;
|
|
1344
|
+
}
|
|
1345
|
+
})();
|
|
1346
|
+
return {
|
|
1347
|
+
ok: true,
|
|
1348
|
+
value: {
|
|
1349
|
+
type: 'scalar',
|
|
1350
|
+
value,
|
|
1351
|
+
},
|
|
1352
|
+
};
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
function evaluateCardinalityBooleans(expression, currentBinding, namespace, options) {
|
|
1356
|
+
if (expression.type === 'groupExpression') {
|
|
1357
|
+
return evaluateCardinalityBooleans(expression.expression, currentBinding, namespace, options);
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
if (expression.type === 'resolutionExpression') {
|
|
1361
|
+
const resolved = evaluateResolutionExpression(expression, currentBinding, namespace, options);
|
|
1362
|
+
if (!resolved.ok) return resolved;
|
|
1363
|
+
const values = [];
|
|
1364
|
+
for (const binding of resolved.value.bindings) {
|
|
1365
|
+
const scalar = getBindingScalarValue(namespace, binding);
|
|
1366
|
+
if (!scalar.ok) return scalar;
|
|
1367
|
+
if (typeof scalar.value !== 'boolean') {
|
|
1368
|
+
return {
|
|
1369
|
+
ok: false,
|
|
1370
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_EXPECTED_BOOLEAN', 'Cardinality resolution operands must expose Boolean scalar values'),
|
|
1371
|
+
};
|
|
1372
|
+
}
|
|
1373
|
+
values.push(scalar.value);
|
|
1374
|
+
}
|
|
1375
|
+
return { ok: true, values };
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
if (expression.type === 'functionCallExpression') {
|
|
1379
|
+
return evaluateCardinalityFunctionBooleans(expression, currentBinding, namespace, options);
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
if (expression.type !== 'binaryExpression' || ['and', 'or'].includes(expression.operator)) {
|
|
1383
|
+
return {
|
|
1384
|
+
ok: false,
|
|
1385
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_CARDINALITY_ARGUMENT', 'Cardinality operators require a resolution predicate in this evaluator slice'),
|
|
1386
|
+
};
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
const left = evaluateQueryExpressionValue(expression.left, currentBinding, namespace, options);
|
|
1390
|
+
if (!left.ok) return left;
|
|
1391
|
+
const right = evaluateQueryExpressionValue(expression.right, currentBinding, namespace, options);
|
|
1392
|
+
if (!right.ok) return right;
|
|
1393
|
+
|
|
1394
|
+
const leftIsSet = left.value.type === 'bindingSet';
|
|
1395
|
+
const rightIsSet = right.value.type === 'bindingSet';
|
|
1396
|
+
|
|
1397
|
+
if (leftIsSet === rightIsSet) {
|
|
1398
|
+
return {
|
|
1399
|
+
ok: false,
|
|
1400
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_CARDINALITY_ARGUMENT', 'Cardinality comparison predicates require exactly one binding-set side'),
|
|
1401
|
+
};
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
const setValue = leftIsSet ? left.value : right.value;
|
|
1405
|
+
const scalarValue = leftIsSet
|
|
1406
|
+
? expectScalarQueryValue(right.value, namespace)
|
|
1407
|
+
: expectScalarQueryValue(left.value, namespace);
|
|
1408
|
+
if (!scalarValue.ok) return scalarValue;
|
|
1409
|
+
|
|
1410
|
+
const values = [];
|
|
1411
|
+
for (const binding of setValue.bindings) {
|
|
1412
|
+
const bindingScalar = getBindingScalarValue(namespace, binding);
|
|
1413
|
+
if (!bindingScalar.ok) return bindingScalar;
|
|
1414
|
+
const compared = leftIsSet
|
|
1415
|
+
? compareQueryScalars(expression.operator, bindingScalar.value, scalarValue.value)
|
|
1416
|
+
: compareQueryScalars(expression.operator, scalarValue.value, bindingScalar.value);
|
|
1417
|
+
if (!compared.ok) return compared;
|
|
1418
|
+
values.push(compared.value.value);
|
|
1419
|
+
}
|
|
1420
|
+
return { ok: true, values };
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
function evaluateCardinalityFunctionBooleans(expression, currentBinding, namespace, options) {
|
|
1424
|
+
if (!isOrdinaryFunctionName(expression.name)) {
|
|
1425
|
+
return {
|
|
1426
|
+
ok: false,
|
|
1427
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_UNSUPPORTED_FUNCTION', `Function '${expression.name}' is not supported by this evaluator slice`),
|
|
1428
|
+
};
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
const evaluatedArgs = [];
|
|
1432
|
+
for (const argument of expression.arguments) {
|
|
1433
|
+
const evaluated = evaluateQueryExpressionValue(argument, currentBinding, namespace, options);
|
|
1434
|
+
if (!evaluated.ok) return evaluated;
|
|
1435
|
+
evaluatedArgs.push(evaluated.value);
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
const bindingSetArgs = evaluatedArgs
|
|
1439
|
+
.map((value, index) => ({ value, index }))
|
|
1440
|
+
.filter((entry) => entry.value.type === 'bindingSet');
|
|
1441
|
+
if (bindingSetArgs.length !== 1) {
|
|
1442
|
+
return {
|
|
1443
|
+
ok: false,
|
|
1444
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_CARDINALITY_ARGUMENT', 'Cardinality function predicates require exactly one binding-set argument'),
|
|
1445
|
+
};
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
const scalarArgs = [];
|
|
1449
|
+
for (let index = 0; index < evaluatedArgs.length; index += 1) {
|
|
1450
|
+
if (index === bindingSetArgs[0].index) {
|
|
1451
|
+
scalarArgs.push(null);
|
|
1452
|
+
continue;
|
|
1453
|
+
}
|
|
1454
|
+
const scalar = expectScalarQueryValue(evaluatedArgs[index], namespace);
|
|
1455
|
+
if (!scalar.ok) return scalar;
|
|
1456
|
+
scalarArgs.push(scalar.value);
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
const values = [];
|
|
1460
|
+
for (const binding of bindingSetArgs[0].value.bindings) {
|
|
1461
|
+
const bindingScalar = getBindingScalarValue(namespace, binding);
|
|
1462
|
+
if (!bindingScalar.ok) return bindingScalar;
|
|
1463
|
+
const args = scalarArgs.slice();
|
|
1464
|
+
args[bindingSetArgs[0].index] = bindingScalar.value;
|
|
1465
|
+
const evaluated = evaluateOrdinaryFunction(expression.name, args);
|
|
1466
|
+
if (!evaluated.ok) return evaluated;
|
|
1467
|
+
if (evaluated.value.type !== 'scalar' || typeof evaluated.value.value !== 'boolean') {
|
|
1468
|
+
return {
|
|
1469
|
+
ok: false,
|
|
1470
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_EXPECTED_BOOLEAN', 'Cardinality function predicates must evaluate to Boolean scalar values'),
|
|
1471
|
+
};
|
|
1472
|
+
}
|
|
1473
|
+
values.push(evaluated.value.value);
|
|
1474
|
+
}
|
|
1475
|
+
return { ok: true, values };
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1478
|
+
function orderQueryBindings(orderBy, bindings, namespace, options) {
|
|
1479
|
+
const keyed = [];
|
|
1480
|
+
for (let index = 0; index < bindings.length; index += 1) {
|
|
1481
|
+
const binding = bindings[index];
|
|
1482
|
+
const keys = [];
|
|
1483
|
+
for (const key of orderBy.keys) {
|
|
1484
|
+
const evaluated = evaluateQueryExpressionValue(key.ast, binding, namespace, options);
|
|
1485
|
+
if (!evaluated.ok) {
|
|
1486
|
+
return {
|
|
1487
|
+
ok: false,
|
|
1488
|
+
error: annotateQueryDiagnostic(evaluated.error, { candidateAddress: getBindingAddress(binding) }),
|
|
1489
|
+
};
|
|
1490
|
+
}
|
|
1491
|
+
const scalar = expectScalarQueryValue(evaluated.value, namespace);
|
|
1492
|
+
if (!scalar.ok) {
|
|
1493
|
+
return {
|
|
1494
|
+
ok: false,
|
|
1495
|
+
error: annotateQueryDiagnostic(scalar.error, { candidateAddress: getBindingAddress(binding) }),
|
|
1496
|
+
};
|
|
1497
|
+
}
|
|
1498
|
+
if (!['number', 'string'].includes(typeof scalar.value)) {
|
|
1499
|
+
return {
|
|
1500
|
+
ok: false,
|
|
1501
|
+
error: queryEvaluateError(
|
|
1502
|
+
'SANSA_QUERY_EVALUATE_INVALID_COMPARISON',
|
|
1503
|
+
'Order keys must evaluate to string or number scalar values',
|
|
1504
|
+
{ candidateAddress: getBindingAddress(binding) },
|
|
1505
|
+
),
|
|
1506
|
+
};
|
|
1507
|
+
}
|
|
1508
|
+
if (typeof scalar.value === 'number' && Number.isNaN(scalar.value)) {
|
|
1509
|
+
return {
|
|
1510
|
+
ok: false,
|
|
1511
|
+
error: queryEvaluateError(
|
|
1512
|
+
'SANSA_QUERY_EVALUATE_INVALID_COMPARISON',
|
|
1513
|
+
'NaN is not a valid order key',
|
|
1514
|
+
{ candidateAddress: getBindingAddress(binding) },
|
|
1515
|
+
),
|
|
1516
|
+
};
|
|
1517
|
+
}
|
|
1518
|
+
keys.push({ value: scalar.value, direction: key.direction });
|
|
1519
|
+
}
|
|
1520
|
+
keyed.push({ binding, keys, index });
|
|
1521
|
+
}
|
|
1522
|
+
|
|
1523
|
+
for (let keyIndex = 0; keyIndex < orderBy.keys.length; keyIndex += 1) {
|
|
1524
|
+
const expectedType = keyed[0] ? typeof keyed[0].keys[keyIndex].value : null;
|
|
1525
|
+
const mismatched = expectedType
|
|
1526
|
+
? keyed.find((entry) => typeof entry.keys[keyIndex].value !== expectedType)
|
|
1527
|
+
: undefined;
|
|
1528
|
+
if (mismatched) {
|
|
1529
|
+
return {
|
|
1530
|
+
ok: false,
|
|
1531
|
+
error: queryEvaluateError(
|
|
1532
|
+
'SANSA_QUERY_EVALUATE_INVALID_COMPARISON',
|
|
1533
|
+
'Order keys must evaluate to one scalar type per key position',
|
|
1534
|
+
{ candidateAddress: getBindingAddress(mismatched.binding) },
|
|
1535
|
+
),
|
|
1536
|
+
};
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
keyed.sort((left, right) => {
|
|
1541
|
+
for (let index = 0; index < left.keys.length; index += 1) {
|
|
1542
|
+
const comparison = compareOrderKeyValues(left.keys[index].value, right.keys[index].value);
|
|
1543
|
+
if (comparison !== 0) {
|
|
1544
|
+
return left.keys[index].direction === 'desc' ? -comparison : comparison;
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
return left.index - right.index;
|
|
1548
|
+
});
|
|
1549
|
+
|
|
1550
|
+
return {
|
|
1551
|
+
ok: true,
|
|
1552
|
+
bindings: keyed.map((entry) => entry.binding),
|
|
1553
|
+
};
|
|
1554
|
+
}
|
|
1555
|
+
|
|
1556
|
+
function compareOrderKeyValues(left, right) {
|
|
1557
|
+
if (typeof left === 'string') return compareStringsByUnicodeScalarValue(left, right);
|
|
1558
|
+
if (left < right) return -1;
|
|
1559
|
+
if (left > right) return 1;
|
|
1560
|
+
return 0;
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
function compareStringsByUnicodeScalarValue(left, right) {
|
|
1564
|
+
const leftScalars = Array.from(left);
|
|
1565
|
+
const rightScalars = Array.from(right);
|
|
1566
|
+
const length = Math.min(leftScalars.length, rightScalars.length);
|
|
1567
|
+
for (let index = 0; index < length; index += 1) {
|
|
1568
|
+
const leftCodePoint = leftScalars[index].codePointAt(0);
|
|
1569
|
+
const rightCodePoint = rightScalars[index].codePointAt(0);
|
|
1570
|
+
if (leftCodePoint < rightCodePoint) return -1;
|
|
1571
|
+
if (leftCodePoint > rightCodePoint) return 1;
|
|
1572
|
+
}
|
|
1573
|
+
if (leftScalars.length < rightScalars.length) return -1;
|
|
1574
|
+
if (leftScalars.length > rightScalars.length) return 1;
|
|
1575
|
+
return 0;
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
export function evaluateValueSemanticsOperation(operation, input = {}) {
|
|
1579
|
+
try {
|
|
1580
|
+
switch (operation) {
|
|
1581
|
+
case 'equal':
|
|
1582
|
+
case 'notEqual':
|
|
1583
|
+
return evaluateValueSemanticsEquality(operation, input.left, input.right);
|
|
1584
|
+
case 'compare':
|
|
1585
|
+
return evaluateValueSemanticsOrdering(input.left, input.right);
|
|
1586
|
+
case 'isValue':
|
|
1587
|
+
return {
|
|
1588
|
+
ok: true,
|
|
1589
|
+
outcome: 'value',
|
|
1590
|
+
value: isOrdinaryValueScalar(valueDescriptorToScalarInfo(input.value)),
|
|
1591
|
+
};
|
|
1592
|
+
default:
|
|
1593
|
+
return valueSemanticsDiagnostic(
|
|
1594
|
+
'unsupported_operation',
|
|
1595
|
+
`Unsupported value-semantics operation '${String(operation)}'`,
|
|
1596
|
+
);
|
|
1597
|
+
}
|
|
1598
|
+
} catch (error) {
|
|
1599
|
+
return valueSemanticsDiagnostic('invalid_value_descriptor', error.message);
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
function evaluateValueSemanticsEquality(operation, leftDescriptor, rightDescriptor) {
|
|
1604
|
+
const left = valueDescriptorToScalarInfo(leftDescriptor);
|
|
1605
|
+
const right = valueDescriptorToScalarInfo(rightDescriptor);
|
|
1606
|
+
if (isNanScalar(left) || isNanScalar(right) || isExplicitNullScalar(left) || isExplicitNullScalar(right) || isExplicitAbsenceScalar(left) || isExplicitAbsenceScalar(right)) {
|
|
1607
|
+
return valueSemanticsDiagnostic('not_equality_comparable', 'Value category is not equality-comparable in the minimum profile');
|
|
1608
|
+
}
|
|
1609
|
+
if (left.category === 'missing' || right.category === 'missing' || left.category === 'container' || right.category === 'container' || left.category === 'bindingSet' || right.category === 'bindingSet') {
|
|
1610
|
+
return valueSemanticsDiagnostic('not_equality_comparable', 'Evaluation state or non-scalar value is not equality-comparable');
|
|
1611
|
+
}
|
|
1612
|
+
if (!sameMinimumEqualityDomain(left, right)) {
|
|
1613
|
+
return valueSemanticsDiagnostic('mixed_categories', 'Mixed categories do not compare by implicit coercion');
|
|
1614
|
+
}
|
|
1615
|
+
const value = compareMinimumEquality(operation, left, right);
|
|
1616
|
+
return {
|
|
1617
|
+
ok: true,
|
|
1618
|
+
outcome: 'value',
|
|
1619
|
+
value,
|
|
1620
|
+
};
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
function evaluateValueSemanticsOrdering(leftDescriptor, rightDescriptor) {
|
|
1624
|
+
const left = valueDescriptorToScalarInfo(leftDescriptor);
|
|
1625
|
+
const right = valueDescriptorToScalarInfo(rightDescriptor);
|
|
1626
|
+
if (isNanScalar(left) || isNanScalar(right) || isExplicitNullScalar(left) || isExplicitNullScalar(right) || isExplicitAbsenceScalar(left) || isExplicitAbsenceScalar(right)) {
|
|
1627
|
+
return valueSemanticsDiagnostic('not_orderable', 'Value category is not orderable in the minimum profile');
|
|
1628
|
+
}
|
|
1629
|
+
if (left.category === 'missing' || right.category === 'missing' || left.category === 'container' || right.category === 'container' || left.category === 'bindingSet' || right.category === 'bindingSet') {
|
|
1630
|
+
return valueSemanticsDiagnostic('not_orderable', 'Evaluation state or non-scalar value is not orderable');
|
|
1631
|
+
}
|
|
1632
|
+
if (typeof left.value === 'boolean' && typeof right.value === 'boolean') {
|
|
1633
|
+
return valueSemanticsDiagnostic('not_orderable', 'Boolean ordering is not part of the minimum profile');
|
|
1634
|
+
}
|
|
1635
|
+
if (!sameMinimumOrderingDomain(left, right)) {
|
|
1636
|
+
return valueSemanticsDiagnostic('mixed_categories', 'Mixed categories do not order by implicit coercion');
|
|
1637
|
+
}
|
|
1638
|
+
const comparison = compareMinimumOrdering(left, right);
|
|
1639
|
+
return {
|
|
1640
|
+
ok: true,
|
|
1641
|
+
outcome: 'value',
|
|
1642
|
+
relation: comparison < 0 ? 'less' : comparison > 0 ? 'greater' : 'equal',
|
|
1643
|
+
};
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
function valueDescriptorToScalarInfo(descriptor) {
|
|
1647
|
+
if (!descriptor || typeof descriptor !== 'object') {
|
|
1648
|
+
throw new Error('Value descriptor must be an object');
|
|
1649
|
+
}
|
|
1650
|
+
switch (descriptor.category) {
|
|
1651
|
+
case 'finiteNumber': {
|
|
1652
|
+
const value = Number(descriptor.value);
|
|
1653
|
+
if (!Number.isFinite(value)) throw new Error('finiteNumber descriptor must contain a finite numeric value');
|
|
1654
|
+
return { category: 'finiteNumber', value };
|
|
1655
|
+
}
|
|
1656
|
+
case 'positiveInfinity':
|
|
1657
|
+
return { category: 'positiveInfinity', value: Infinity, kind: 'infinity' };
|
|
1658
|
+
case 'negativeInfinity':
|
|
1659
|
+
return { category: 'negativeInfinity', value: -Infinity, kind: 'infinity' };
|
|
1660
|
+
case 'nan':
|
|
1661
|
+
return { category: 'nan', value: Number.NaN, kind: 'nan' };
|
|
1662
|
+
case 'string':
|
|
1663
|
+
return { category: 'string', value: String(descriptor.value ?? '') };
|
|
1664
|
+
case 'boolean':
|
|
1665
|
+
return { category: 'boolean', value: Boolean(descriptor.value) };
|
|
1666
|
+
case 'explicitNull':
|
|
1667
|
+
return { category: 'explicitNull', value: null, kind: 'null', nullReason: descriptor.reason };
|
|
1668
|
+
case 'explicitAbsence':
|
|
1669
|
+
return { category: 'explicitAbsence', value: undefined, kind: 'absence', nullReason: descriptor.reason };
|
|
1670
|
+
case 'missing':
|
|
1671
|
+
return { category: 'missing', value: undefined, kind: 'missing' };
|
|
1672
|
+
case 'container':
|
|
1673
|
+
return { category: 'container', value: descriptor, kind: 'container' };
|
|
1674
|
+
case 'bindingSet':
|
|
1675
|
+
return { category: 'bindingSet', value: descriptor, kind: 'bindingSet' };
|
|
1676
|
+
default:
|
|
1677
|
+
throw new Error(`Unsupported value category '${String(descriptor.category)}'`);
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
function scalarInfoToValueDescriptor(info) {
|
|
1682
|
+
if (isExplicitNullScalar(info)) {
|
|
1683
|
+
return { category: 'explicitNull', reason: info.nullReason };
|
|
1684
|
+
}
|
|
1685
|
+
if (isExplicitAbsenceScalar(info)) {
|
|
1686
|
+
return { category: 'explicitAbsence', reason: info.nullReason };
|
|
1687
|
+
}
|
|
1688
|
+
if (isNanScalar(info)) {
|
|
1689
|
+
return { category: 'nan' };
|
|
1690
|
+
}
|
|
1691
|
+
if (isInfinityScalar(info)) {
|
|
1692
|
+
return info.value === -Infinity
|
|
1693
|
+
? { category: 'negativeInfinity' }
|
|
1694
|
+
: { category: 'positiveInfinity' };
|
|
1695
|
+
}
|
|
1696
|
+
if (typeof info.value === 'number') {
|
|
1697
|
+
return Number.isFinite(info.value)
|
|
1698
|
+
? { category: 'finiteNumber', value: String(info.value) }
|
|
1699
|
+
: { category: 'nan' };
|
|
1700
|
+
}
|
|
1701
|
+
if (typeof info.value === 'string') {
|
|
1702
|
+
return { category: 'string', value: info.value };
|
|
1703
|
+
}
|
|
1704
|
+
if (typeof info.value === 'boolean') {
|
|
1705
|
+
return { category: 'boolean', value: info.value };
|
|
1706
|
+
}
|
|
1707
|
+
if (info.kind === 'missing' || info.category === 'missing') {
|
|
1708
|
+
return { category: 'missing' };
|
|
1709
|
+
}
|
|
1710
|
+
if (info.kind === 'bindingSet' || info.category === 'bindingSet') {
|
|
1711
|
+
return { category: 'bindingSet', count: info.count };
|
|
1712
|
+
}
|
|
1713
|
+
return { category: 'container', value: info.value };
|
|
1714
|
+
}
|
|
1715
|
+
|
|
1716
|
+
function sameMinimumEqualityDomain(left, right) {
|
|
1717
|
+
if (isValueSemanticsNumeric(left) && isValueSemanticsNumeric(right)) return true;
|
|
1718
|
+
return left.category === right.category && ['string', 'boolean'].includes(left.category);
|
|
1719
|
+
}
|
|
1720
|
+
|
|
1721
|
+
function sameMinimumOrderingDomain(left, right) {
|
|
1722
|
+
if (isValueSemanticsNumeric(left) && isValueSemanticsNumeric(right)) return true;
|
|
1723
|
+
return left.category === 'string' && right.category === 'string';
|
|
1724
|
+
}
|
|
1725
|
+
|
|
1726
|
+
function isValueSemanticsNumeric(info) {
|
|
1727
|
+
return info.category === 'finiteNumber' || info.category === 'positiveInfinity' || info.category === 'negativeInfinity';
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
function compareMinimumEquality(operation, left, right) {
|
|
1731
|
+
if (isValueSemanticsNumeric(left) && isValueSemanticsNumeric(right)) {
|
|
1732
|
+
return operation === 'equal' ? left.value === right.value : left.value !== right.value;
|
|
1733
|
+
}
|
|
1734
|
+
const equals = Object.is(left.value, right.value);
|
|
1735
|
+
return operation === 'equal' ? equals : !equals;
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
function compareMinimumOrdering(left, right) {
|
|
1739
|
+
return compareOrderKeyValues(left.value, right.value);
|
|
1740
|
+
}
|
|
1741
|
+
|
|
1742
|
+
function isOrdinaryValueDescriptor(descriptor) {
|
|
1743
|
+
const info = valueDescriptorToScalarInfo(descriptor);
|
|
1744
|
+
return info.category === 'finiteNumber' || info.category === 'string' || info.category === 'boolean';
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
function isExplicitAbsenceScalar(info) {
|
|
1748
|
+
return info.kind === 'absence' || info.category === 'explicitAbsence';
|
|
1749
|
+
}
|
|
1750
|
+
|
|
1751
|
+
function valueSemanticsDiagnostic(reason, message) {
|
|
1752
|
+
return {
|
|
1753
|
+
ok: false,
|
|
1754
|
+
outcome: 'diagnostic',
|
|
1755
|
+
reason,
|
|
1756
|
+
error: {
|
|
1757
|
+
code: `AEON_VALUE_SEMANTICS_${reason.toUpperCase()}`,
|
|
1758
|
+
reason,
|
|
1759
|
+
message,
|
|
1760
|
+
},
|
|
1761
|
+
};
|
|
1762
|
+
}
|
|
1763
|
+
|
|
1764
|
+
function compareQueryScalars(operator, left, right) {
|
|
1765
|
+
const leftDescriptor = scalarInfoToValueDescriptor({ value: left });
|
|
1766
|
+
const rightDescriptor = scalarInfoToValueDescriptor({ value: right });
|
|
1767
|
+
const operation = ['==', '!='].includes(operator) ? (operator === '==' ? 'equal' : 'notEqual') : 'compare';
|
|
1768
|
+
const evaluated = evaluateValueSemanticsOperation(operation, {
|
|
1769
|
+
left: leftDescriptor,
|
|
1770
|
+
right: rightDescriptor,
|
|
1771
|
+
});
|
|
1772
|
+
if (!evaluated.ok) {
|
|
1773
|
+
return {
|
|
1774
|
+
ok: false,
|
|
1775
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_INVALID_COMPARISON', queryComparisonMessage(evaluated.reason, operator)),
|
|
1776
|
+
};
|
|
1777
|
+
}
|
|
1778
|
+
const value = (() => {
|
|
1779
|
+
if (operator === '==') return evaluated.value;
|
|
1780
|
+
if (operator === '!=') return evaluated.value;
|
|
1781
|
+
if (operator === '<') return evaluated.relation === 'less';
|
|
1782
|
+
if (operator === '<=') return evaluated.relation === 'less' || evaluated.relation === 'equal';
|
|
1783
|
+
if (operator === '>') return evaluated.relation === 'greater';
|
|
1784
|
+
if (operator === '>=') return evaluated.relation === 'greater' || evaluated.relation === 'equal';
|
|
1785
|
+
return false;
|
|
1786
|
+
})();
|
|
1787
|
+
return { ok: true, value: { type: 'scalar', value } };
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
function queryComparisonMessage(reason, operator) {
|
|
1791
|
+
if (reason === 'mixed_categories') return 'Cross-type comparison is not supported by this evaluator slice';
|
|
1792
|
+
if (reason === 'not_equality_comparable') return 'NaN, null, absence, and non-scalar values are not equality-comparable in this evaluator slice';
|
|
1793
|
+
if (reason === 'not_orderable' && ['<', '<=', '>', '>='].includes(operator)) return 'Ordering comparison is not defined for this value category';
|
|
1794
|
+
return 'Invalid scalar comparison';
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
function expectBooleanQueryValue(value, namespace) {
|
|
1798
|
+
if (value.type === 'scalar' && typeof value.value === 'boolean') {
|
|
1799
|
+
return { ok: true, value: value.value };
|
|
1800
|
+
}
|
|
1801
|
+
if (value.type === 'bindingSet') {
|
|
1802
|
+
const scalar = expectScalarQueryValue(value, namespace);
|
|
1803
|
+
if (!scalar.ok) return scalar;
|
|
1804
|
+
if (typeof scalar.value === 'boolean') return { ok: true, value: scalar.value };
|
|
1805
|
+
}
|
|
1806
|
+
return {
|
|
1807
|
+
ok: false,
|
|
1808
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_EXPECTED_BOOLEAN', 'Expected Boolean query value'),
|
|
1809
|
+
};
|
|
1810
|
+
}
|
|
1811
|
+
|
|
1812
|
+
function expectScalarQueryValue(value, namespace) {
|
|
1813
|
+
if (value.type === 'scalar') return { ok: true, value: value.value };
|
|
1814
|
+
if (value.type === 'bindingSet') {
|
|
1815
|
+
if (value.bindings.length === 0) {
|
|
1816
|
+
return {
|
|
1817
|
+
ok: false,
|
|
1818
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_MISSING_SCALAR', 'Expected one binding but resolved none'),
|
|
1819
|
+
};
|
|
1820
|
+
}
|
|
1821
|
+
if (value.bindings.length > 1) {
|
|
1822
|
+
return {
|
|
1823
|
+
ok: false,
|
|
1824
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_CARDINALITY', 'Expected one binding but resolved multiple bindings'),
|
|
1825
|
+
};
|
|
1826
|
+
}
|
|
1827
|
+
const scalar = getBindingScalarValue(namespace, value.bindings[0]);
|
|
1828
|
+
if (!scalar.ok) return scalar;
|
|
1829
|
+
return { ok: true, value: scalar.value };
|
|
1830
|
+
}
|
|
1831
|
+
return {
|
|
1832
|
+
ok: false,
|
|
1833
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_EXPECTED_SCALAR', 'Expected scalar query value'),
|
|
1834
|
+
};
|
|
1835
|
+
}
|
|
1836
|
+
|
|
1837
|
+
function unwrapQueryValue(value, namespace) {
|
|
1838
|
+
if (value.type === 'scalar') return { ok: true, value: value.value };
|
|
1839
|
+
if (value.type === 'object') return { ok: true, value: value.value };
|
|
1840
|
+
return expectScalarQueryValue(value, namespace);
|
|
1841
|
+
}
|
|
1842
|
+
|
|
1843
|
+
function getBindingScalarValue(namespace, binding) {
|
|
1844
|
+
const info = getBindingScalarInfo(namespace, binding);
|
|
1845
|
+
if (!info.ok) return info;
|
|
1846
|
+
return { ok: true, value: info.value, metadata: scalarMetadataFromInfo(info) };
|
|
1847
|
+
}
|
|
1848
|
+
|
|
1849
|
+
function getBindingScalarInfo(namespace, binding) {
|
|
1850
|
+
const kind = getBindingScalarKind(namespace, binding);
|
|
1851
|
+
const nullReason = getBindingNullReason(namespace, binding);
|
|
1852
|
+
if (typeof namespace.value === 'function') {
|
|
1853
|
+
return { ok: true, value: namespace.value(binding), kind, nullReason };
|
|
1854
|
+
}
|
|
1855
|
+
if (Object.hasOwn(binding, 'value')) return { ok: true, value: binding.value, kind, nullReason };
|
|
1856
|
+
if (Object.hasOwn(binding, 'scalar')) return { ok: true, value: binding.scalar, kind, nullReason };
|
|
1857
|
+
return {
|
|
1858
|
+
ok: false,
|
|
1859
|
+
error: queryEvaluateError('SANSA_QUERY_EVALUATE_MISSING_SCALAR', 'Binding does not expose a scalar value'),
|
|
1860
|
+
};
|
|
1861
|
+
}
|
|
1862
|
+
|
|
1863
|
+
function getBindingScalarKind(namespace, binding) {
|
|
1864
|
+
const actual = typeof namespace.representationKind === 'function'
|
|
1865
|
+
? namespace.representationKind(binding)
|
|
1866
|
+
: binding.scalarKind ?? binding.valueKind ?? binding.literalKind ?? binding.representationKind ?? binding.kind ?? binding.type;
|
|
1867
|
+
if (actual === 'NullLiteral') return 'null';
|
|
1868
|
+
if (actual === 'NaNLiteral') return 'nan';
|
|
1869
|
+
if (actual === 'InfinityLiteral') return 'infinity';
|
|
1870
|
+
return typeof actual === 'string' ? lowerFirst(actual) : undefined;
|
|
1871
|
+
}
|
|
1872
|
+
|
|
1873
|
+
function getBindingNullReason(namespace, binding) {
|
|
1874
|
+
if (typeof namespace.nullReason === 'function') return namespace.nullReason(binding);
|
|
1875
|
+
return binding.nullReason;
|
|
1876
|
+
}
|
|
1877
|
+
|
|
1878
|
+
function queryValueMetadata(value, namespace) {
|
|
1879
|
+
if (value.type === 'scalar') return value[QUERY_VALUE_METADATA_PROPERTY];
|
|
1880
|
+
if (value.type !== 'bindingSet' || value.bindings.length !== 1) return undefined;
|
|
1881
|
+
const info = getBindingScalarInfo(namespace, value.bindings[0]);
|
|
1882
|
+
return info.ok ? scalarMetadataFromInfo(info) : undefined;
|
|
1883
|
+
}
|
|
1884
|
+
|
|
1885
|
+
function queryValueAddress(value) {
|
|
1886
|
+
if (value.type !== 'bindingSet' || value.bindings.length !== 1) return undefined;
|
|
1887
|
+
return getBindingAddress(value.bindings[0]);
|
|
1888
|
+
}
|
|
1889
|
+
|
|
1890
|
+
function scalarMetadataFromInfo(info) {
|
|
1891
|
+
const metadata = {};
|
|
1892
|
+
if (info.kind !== undefined) metadata.kind = info.kind;
|
|
1893
|
+
if (info.nullReason !== undefined) metadata.nullReason = info.nullReason;
|
|
1894
|
+
return Object.keys(metadata).length > 0 ? metadata : undefined;
|
|
1895
|
+
}
|
|
1896
|
+
|
|
1897
|
+
function applyResolveSelector(selector, bindings, namespace, selectorIndex, policy = {}) {
|
|
1898
|
+
switch (selector.type) {
|
|
1899
|
+
case 'member':
|
|
1900
|
+
return { ok: true, bindings: bindings.flatMap((binding) => selectMember(namespace, binding, selector.name)) };
|
|
1901
|
+
case 'position':
|
|
1902
|
+
return { ok: true, bindings: bindings.flatMap((binding) => selectPosition(namespace, binding, selector.index)) };
|
|
1903
|
+
case 'positionRange':
|
|
1904
|
+
return { ok: true, bindings: bindings.flatMap((binding) => selectPositionRange(namespace, binding, selector.start, selector.end)) };
|
|
1905
|
+
case 'parent':
|
|
1906
|
+
return selectParents(namespace, bindings, selectorIndex, policy);
|
|
1907
|
+
case 'directExpansion':
|
|
1908
|
+
return { ok: true, bindings: bindings.flatMap((binding) => getChildren(namespace, binding)) };
|
|
1909
|
+
case 'descendantExpansion':
|
|
1910
|
+
return { ok: true, bindings: bindings.flatMap((binding) => getDescendants(namespace, binding)) };
|
|
1911
|
+
case 'namePattern': {
|
|
1912
|
+
const pattern = globPatternToRegExp(selector.pattern);
|
|
1913
|
+
return {
|
|
1914
|
+
ok: true,
|
|
1915
|
+
bindings: bindings.flatMap((binding) => getChildren(namespace, binding).filter((child) => {
|
|
1916
|
+
const name = getBindingName(namespace, child);
|
|
1917
|
+
return typeof name === 'string' && pattern.test(name);
|
|
1918
|
+
})),
|
|
1919
|
+
};
|
|
1920
|
+
}
|
|
1921
|
+
case 'semanticTypeFilter':
|
|
1922
|
+
return { ok: true, bindings: bindings.filter((binding) => matchesSemanticType(namespace, binding, selector.name)) };
|
|
1923
|
+
case 'representationKindFilter':
|
|
1924
|
+
return { ok: true, bindings: bindings.filter((binding) => matchesRepresentationKind(namespace, binding, selector.name)) };
|
|
1925
|
+
case 'attributeSpace':
|
|
1926
|
+
return selectAttributeSpaces(namespace, bindings, selectorIndex);
|
|
1927
|
+
case 'localSpace':
|
|
1928
|
+
return selectLocalSpaces(namespace, bindings, selector.name, selectorIndex);
|
|
1929
|
+
default:
|
|
1930
|
+
return {
|
|
1931
|
+
ok: false,
|
|
1932
|
+
error: resolveError(
|
|
1933
|
+
'SANSA_RESOLVE_UNSUPPORTED_SELECTOR',
|
|
1934
|
+
`Unsupported SANSA selector type: ${selector.type}`,
|
|
1935
|
+
selectorIndex,
|
|
1936
|
+
),
|
|
1937
|
+
};
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
function selectMember(namespace, binding, name) {
|
|
1942
|
+
if (typeof namespace.member === 'function') {
|
|
1943
|
+
const selected = namespace.member(binding, name);
|
|
1944
|
+
return selected ? [selected] : [];
|
|
1945
|
+
}
|
|
1946
|
+
return getChildren(namespace, binding).filter((child) => getBindingName(namespace, child) === name);
|
|
1947
|
+
}
|
|
1948
|
+
|
|
1949
|
+
function selectPosition(namespace, binding, index) {
|
|
1950
|
+
if (typeof namespace.position === 'function') {
|
|
1951
|
+
const selected = namespace.position(binding, index);
|
|
1952
|
+
return selected ? [selected] : [];
|
|
1953
|
+
}
|
|
1954
|
+
const children = getChildren(namespace, binding);
|
|
1955
|
+
const indexed = children.find((child) => getBindingIndex(namespace, child) === index);
|
|
1956
|
+
if (indexed) return [indexed];
|
|
1957
|
+
return children[index] ? [children[index]] : [];
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1960
|
+
function selectPositionRange(namespace, binding, start, end) {
|
|
1961
|
+
const lower = start ?? 0;
|
|
1962
|
+
const upper = end ?? Number.POSITIVE_INFINITY;
|
|
1963
|
+
if (lower > upper) return [];
|
|
1964
|
+
|
|
1965
|
+
return getChildren(namespace, binding).filter((child, ordinal) => {
|
|
1966
|
+
const explicitIndex = getBindingIndex(namespace, child);
|
|
1967
|
+
const position = Number.isInteger(explicitIndex) ? explicitIndex : ordinal;
|
|
1968
|
+
return position >= lower && position <= upper;
|
|
1969
|
+
});
|
|
1970
|
+
}
|
|
1971
|
+
|
|
1972
|
+
function selectParents(namespace, bindings, selectorIndex, policy) {
|
|
1973
|
+
if (policy.parentTraversal === 'forbid') {
|
|
1974
|
+
return {
|
|
1975
|
+
ok: false,
|
|
1976
|
+
error: resolveError(
|
|
1977
|
+
'SANSA_RESOLVE_PARENT_TRAVERSAL_FORBIDDEN',
|
|
1978
|
+
'Parent traversal is forbidden by resolver policy',
|
|
1979
|
+
selectorIndex,
|
|
1980
|
+
),
|
|
1981
|
+
};
|
|
1982
|
+
}
|
|
1983
|
+
|
|
1984
|
+
const rootBindings = bindings.filter((binding) => binding === policy.effectiveRoot);
|
|
1985
|
+
if (rootBindings.length > 0 && policy.failOnParentFromEffectiveRoot) {
|
|
1986
|
+
return {
|
|
1987
|
+
ok: false,
|
|
1988
|
+
error: resolveError(
|
|
1989
|
+
'SANSA_RESOLVE_BOUNDARY_ESCAPE_FORBIDDEN',
|
|
1990
|
+
'Parent traversal would escape the effective resolution root',
|
|
1991
|
+
selectorIndex,
|
|
1992
|
+
),
|
|
1993
|
+
};
|
|
1994
|
+
}
|
|
1995
|
+
|
|
1996
|
+
const traversable = bindings.filter((binding) => binding !== policy.effectiveRoot);
|
|
1997
|
+
if (traversable.length === 0) return { ok: true, bindings: [] };
|
|
1998
|
+
if (typeof namespace.parent === 'function') {
|
|
1999
|
+
return { ok: true, bindings: traversable.map((binding) => namespace.parent(binding)).filter(Boolean) };
|
|
2000
|
+
}
|
|
2001
|
+
if (traversable.some((binding) => Object.prototype.hasOwnProperty.call(binding, 'parent'))) {
|
|
2002
|
+
return { ok: true, bindings: traversable.map((binding) => binding.parent).filter(Boolean) };
|
|
2003
|
+
}
|
|
2004
|
+
if (traversable.length === 0) return { ok: true, bindings: [] };
|
|
2005
|
+
return {
|
|
2006
|
+
ok: false,
|
|
2007
|
+
error: resolveError(
|
|
2008
|
+
'SANSA_RESOLVE_UNSUPPORTED_PARENT',
|
|
2009
|
+
'The namespace does not expose parent traversal',
|
|
2010
|
+
selectorIndex,
|
|
2011
|
+
),
|
|
2012
|
+
};
|
|
2013
|
+
}
|
|
2014
|
+
|
|
2015
|
+
function selectAttributeSpaces(namespace, bindings, selectorIndex) {
|
|
2016
|
+
if (typeof namespace.attributeSpace !== 'function') {
|
|
2017
|
+
const selected = bindings
|
|
2018
|
+
.map((binding) => binding.attributeSpace ?? binding.attributes)
|
|
2019
|
+
.filter(Boolean);
|
|
2020
|
+
if (selected.length > 0 || bindings.length === 0) return { ok: true, bindings: selected };
|
|
2021
|
+
return {
|
|
2022
|
+
ok: false,
|
|
2023
|
+
error: resolveError(
|
|
2024
|
+
'SANSA_RESOLVE_UNSUPPORTED_ATTRIBUTE_SPACE',
|
|
2025
|
+
'The namespace does not expose attribute address-space traversal',
|
|
2026
|
+
selectorIndex,
|
|
2027
|
+
),
|
|
2028
|
+
};
|
|
2029
|
+
}
|
|
2030
|
+
return {
|
|
2031
|
+
ok: true,
|
|
2032
|
+
bindings: bindings.map((binding) => namespace.attributeSpace(binding)).filter(Boolean),
|
|
2033
|
+
};
|
|
2034
|
+
}
|
|
2035
|
+
|
|
2036
|
+
function selectLocalSpaces(namespace, bindings, name, selectorIndex) {
|
|
2037
|
+
if (typeof namespace.localSpace !== 'function') {
|
|
2038
|
+
return {
|
|
2039
|
+
ok: false,
|
|
2040
|
+
error: resolveError(
|
|
2041
|
+
'SANSA_RESOLVE_UNSUPPORTED_LOCAL_SPACE',
|
|
2042
|
+
`The namespace does not expose local address space '${name}'`,
|
|
2043
|
+
selectorIndex,
|
|
2044
|
+
),
|
|
2045
|
+
};
|
|
2046
|
+
}
|
|
2047
|
+
return {
|
|
2048
|
+
ok: true,
|
|
2049
|
+
bindings: bindings.map((binding) => namespace.localSpace(binding, name)).filter(Boolean),
|
|
2050
|
+
};
|
|
2051
|
+
}
|
|
2052
|
+
|
|
2053
|
+
function getChildren(namespace, binding) {
|
|
2054
|
+
if (typeof namespace.children === 'function') return Array.from(namespace.children(binding) ?? []);
|
|
2055
|
+
if (Array.isArray(binding.children)) return binding.children;
|
|
2056
|
+
return [];
|
|
2057
|
+
}
|
|
2058
|
+
|
|
2059
|
+
function getDescendants(namespace, binding) {
|
|
2060
|
+
const output = [];
|
|
2061
|
+
for (const child of getChildren(namespace, binding)) {
|
|
2062
|
+
output.push(child, ...getDescendants(namespace, child));
|
|
2063
|
+
}
|
|
2064
|
+
return output;
|
|
2065
|
+
}
|
|
2066
|
+
|
|
2067
|
+
function getBindingName(namespace, binding) {
|
|
2068
|
+
if (typeof namespace.name === 'function') return namespace.name(binding);
|
|
2069
|
+
return binding.name ?? binding.key ?? undefined;
|
|
2070
|
+
}
|
|
2071
|
+
|
|
2072
|
+
function getBindingIndex(namespace, binding) {
|
|
2073
|
+
if (typeof namespace.index === 'function') return namespace.index(binding);
|
|
2074
|
+
return Number.isInteger(binding.index) ? binding.index : undefined;
|
|
2075
|
+
}
|
|
2076
|
+
|
|
2077
|
+
function matchesSemanticType(namespace, binding, expected) {
|
|
2078
|
+
if (typeof namespace.semanticTypeMatches === 'function') return namespace.semanticTypeMatches(binding, expected) === true;
|
|
2079
|
+
const actual = typeof namespace.semanticType === 'function'
|
|
2080
|
+
? namespace.semanticType(binding)
|
|
2081
|
+
: binding.semanticType ?? binding.datatype;
|
|
2082
|
+
if (actual === expected) return true;
|
|
2083
|
+
return typeof actual === 'string' && datatypeBaseName(actual) === expected;
|
|
2084
|
+
}
|
|
2085
|
+
|
|
2086
|
+
function matchesRepresentationKind(namespace, binding, expected) {
|
|
2087
|
+
if (typeof namespace.representationKindMatches === 'function') return namespace.representationKindMatches(binding, expected) === true;
|
|
2088
|
+
const actual = typeof namespace.representationKind === 'function'
|
|
2089
|
+
? namespace.representationKind(binding)
|
|
2090
|
+
: binding.representationKind ?? binding.kind ?? binding.type;
|
|
2091
|
+
return typeof actual === 'string' && lowerFirst(actual) === expected;
|
|
2092
|
+
}
|
|
2093
|
+
|
|
2094
|
+
function resolveError(code, message, selectorIndex) {
|
|
2095
|
+
return {
|
|
2096
|
+
code,
|
|
2097
|
+
message,
|
|
2098
|
+
...(selectorIndex === undefined ? {} : { selectorIndex }),
|
|
2099
|
+
};
|
|
2100
|
+
}
|
|
2101
|
+
|
|
2102
|
+
function queryEvaluateError(code, message, details = {}) {
|
|
2103
|
+
return { code, message, ...details };
|
|
2104
|
+
}
|
|
2105
|
+
|
|
2106
|
+
function annotateQueryDiagnostic(error, details) {
|
|
2107
|
+
return {
|
|
2108
|
+
...error,
|
|
2109
|
+
...(details.phase === undefined ? {} : { phase: details.phase }),
|
|
2110
|
+
...(details.candidateAddress === undefined ? {} : { candidateAddress: details.candidateAddress }),
|
|
2111
|
+
};
|
|
2112
|
+
}
|
|
2113
|
+
|
|
2114
|
+
function getBindingAddress(binding) {
|
|
2115
|
+
return typeof binding.address === 'string' ? binding.address : undefined;
|
|
2116
|
+
}
|
|
2117
|
+
|
|
2118
|
+
export function renderQualifierExpression(expression) {
|
|
2119
|
+
return expression.terms.map(renderQualifierTerm).join('|');
|
|
2120
|
+
}
|
|
2121
|
+
|
|
2122
|
+
export function renderQualifierTerm(term) {
|
|
2123
|
+
let output = term.name;
|
|
2124
|
+
const parameterGroups = term.parameterGroups ?? (term.parameters.length > 0 ? [term.parameters] : []);
|
|
2125
|
+
for (const group of parameterGroups) {
|
|
2126
|
+
output += `<${group.map(renderQualifierTerm).join(',')}>`;
|
|
2127
|
+
}
|
|
2128
|
+
for (const argument of term.arguments) {
|
|
2129
|
+
output += `[${renderQualifierArgument(argument)}]`;
|
|
2130
|
+
}
|
|
2131
|
+
return output;
|
|
2132
|
+
}
|
|
2133
|
+
|
|
2134
|
+
function renderQualifierArgument(argument) {
|
|
2135
|
+
if (argument.kind === 'token') return argument.value;
|
|
2136
|
+
return quotePayload(argument.value);
|
|
2137
|
+
}
|
|
2138
|
+
|
|
2139
|
+
class AddressParser {
|
|
2140
|
+
constructor(input, options = {}) {
|
|
2141
|
+
this.input = input;
|
|
2142
|
+
this.options = options;
|
|
2143
|
+
this.index = 0;
|
|
2144
|
+
this.warnings = [];
|
|
2145
|
+
this.maxPositionIndex = normalizeMaxPositionIndex(options.maxPositionIndex);
|
|
2146
|
+
}
|
|
2147
|
+
|
|
2148
|
+
parse() {
|
|
2149
|
+
if (this.input.length === 0) this.fail('Expected SANSA address root', 'SANSA_EMPTY_ADDRESS');
|
|
2150
|
+
const rootChar = this.peek();
|
|
2151
|
+
if (rootChar !== '$' && rootChar !== '?') {
|
|
2152
|
+
this.fail("Expected SANSA address root '$' or '?'", 'SANSA_EXPECTED_ROOT');
|
|
2153
|
+
}
|
|
2154
|
+
this.index += 1;
|
|
2155
|
+
|
|
2156
|
+
const root = { type: 'root', kind: rootChar === '$' ? 'absolute' : 'contextual' };
|
|
2157
|
+
const selectors = [];
|
|
2158
|
+
let qualifierExpression = null;
|
|
2159
|
+
|
|
2160
|
+
while (!this.atEnd()) {
|
|
2161
|
+
const char = this.peek();
|
|
2162
|
+
if (char === ':') {
|
|
2163
|
+
this.index += 1;
|
|
2164
|
+
if (this.atEnd()) this.fail('Expected qualifier expression', 'SANSA_EXPECTED_QUALIFIER');
|
|
2165
|
+
qualifierExpression = this.parseQualifierExpression();
|
|
2166
|
+
break;
|
|
2167
|
+
}
|
|
2168
|
+
if (char === '.') {
|
|
2169
|
+
selectors.push(this.parseDotSelector());
|
|
2170
|
+
continue;
|
|
2171
|
+
}
|
|
2172
|
+
if (char === '[') {
|
|
2173
|
+
selectors.push(this.parsePositionSelector());
|
|
2174
|
+
continue;
|
|
2175
|
+
}
|
|
2176
|
+
if (char === '#') {
|
|
2177
|
+
this.index += 1;
|
|
2178
|
+
selectors.push({ type: 'semanticTypeFilter', name: this.parseIdentifier('semantic type filter') });
|
|
2179
|
+
continue;
|
|
2180
|
+
}
|
|
2181
|
+
if (char === '%') {
|
|
2182
|
+
this.index += 1;
|
|
2183
|
+
selectors.push({ type: 'representationKindFilter', name: this.parseIdentifier('representation kind filter') });
|
|
2184
|
+
continue;
|
|
2185
|
+
}
|
|
2186
|
+
if (isLayout(char)) this.fail('Whitespace is not allowed inside a SANSA address', 'SANSA_UNEXPECTED_WHITESPACE');
|
|
2187
|
+
this.fail(`Unexpected character '${char}'`, 'SANSA_UNEXPECTED_CHARACTER');
|
|
2188
|
+
}
|
|
2189
|
+
|
|
2190
|
+
this.expectEnd();
|
|
2191
|
+
const address = {
|
|
2192
|
+
type: 'SansaAddress',
|
|
2193
|
+
root,
|
|
2194
|
+
selectors,
|
|
2195
|
+
qualifierExpression,
|
|
2196
|
+
isExact: selectors.every(isExactSelector),
|
|
2197
|
+
};
|
|
2198
|
+
address.canonical = renderAddress(address);
|
|
2199
|
+
return address;
|
|
2200
|
+
}
|
|
2201
|
+
|
|
2202
|
+
parseDotSelector() {
|
|
2203
|
+
this.consume('.');
|
|
2204
|
+
if (this.match('@')) return { type: 'attributeSpace' };
|
|
2205
|
+
if (this.match('^')) return { type: 'parent' };
|
|
2206
|
+
if (this.match('*')) {
|
|
2207
|
+
if (this.match('*')) return { type: 'descendantExpansion' };
|
|
2208
|
+
return { type: 'directExpansion' };
|
|
2209
|
+
}
|
|
2210
|
+
if (this.match('[')) {
|
|
2211
|
+
const name = this.parseQuotedPayload();
|
|
2212
|
+
if (name.length === 0) this.fail('Quoted member names must not be empty', 'SANSA_EMPTY_MEMBER_NAME');
|
|
2213
|
+
this.consume(']');
|
|
2214
|
+
return { type: 'member', name, quoted: true };
|
|
2215
|
+
}
|
|
2216
|
+
if (this.match('<')) {
|
|
2217
|
+
const name = this.parseQuotedPayload();
|
|
2218
|
+
if (name.length === 0) this.fail('Local address-space names must not be empty', 'SANSA_EMPTY_LOCAL_SPACE_NAME');
|
|
2219
|
+
this.consume('>');
|
|
2220
|
+
return { type: 'localSpace', name };
|
|
2221
|
+
}
|
|
2222
|
+
if (this.match('(')) {
|
|
2223
|
+
const pattern = this.parseQuotedPayload();
|
|
2224
|
+
this.consume(')');
|
|
2225
|
+
return { type: 'namePattern', pattern };
|
|
2226
|
+
}
|
|
2227
|
+
return { type: 'member', name: this.parseIdentifier('member selector'), quoted: false };
|
|
2228
|
+
}
|
|
2229
|
+
|
|
2230
|
+
parsePositionSelector() {
|
|
2231
|
+
this.consume('[');
|
|
2232
|
+
const selectorStart = this.index;
|
|
2233
|
+
const start = this.parseOptionalPositionIndex();
|
|
2234
|
+
if (this.input.startsWith('..', this.index)) {
|
|
2235
|
+
this.index += 2;
|
|
2236
|
+
const end = this.parseOptionalPositionIndex();
|
|
2237
|
+
if (start === null && end === null) {
|
|
2238
|
+
this.fail('Position ranges must include a start or end index', 'SANSA_EMPTY_POSITION_RANGE', selectorStart);
|
|
2239
|
+
}
|
|
2240
|
+
this.consume(']');
|
|
2241
|
+
return { type: 'positionRange', start, end };
|
|
2242
|
+
}
|
|
2243
|
+
if (start === null) this.fail('Expected positional index', 'SANSA_EXPECTED_INDEX');
|
|
2244
|
+
this.consume(']');
|
|
2245
|
+
return { type: 'position', index: start };
|
|
2246
|
+
}
|
|
2247
|
+
|
|
2248
|
+
parseOptionalPositionIndex() {
|
|
2249
|
+
const start = this.index;
|
|
2250
|
+
while (isDigit(this.peek())) this.index += 1;
|
|
2251
|
+
if (this.index === start) return null;
|
|
2252
|
+
const raw = this.input.slice(start, this.index);
|
|
2253
|
+
if (raw.length > 1 && raw.startsWith('0')) {
|
|
2254
|
+
this.fail('Positional indexes must not contain leading zeroes', 'SANSA_LEADING_ZERO_INDEX', start);
|
|
2255
|
+
}
|
|
2256
|
+
if (exceedsUnsignedDecimal(raw, this.maxPositionIndex)) {
|
|
2257
|
+
this.fail(
|
|
2258
|
+
`Position indexes must be less than or equal to ${this.maxPositionIndex}`,
|
|
2259
|
+
'SANSA_POSITION_INDEX_LIMIT_EXCEEDED',
|
|
2260
|
+
start,
|
|
2261
|
+
);
|
|
2262
|
+
}
|
|
2263
|
+
const value = Number(raw);
|
|
2264
|
+
if (!Number.isSafeInteger(value)) {
|
|
2265
|
+
this.fail(
|
|
2266
|
+
`Position indexes must be less than or equal to ${this.maxPositionIndex}`,
|
|
2267
|
+
'SANSA_POSITION_INDEX_LIMIT_EXCEEDED',
|
|
2268
|
+
start,
|
|
2269
|
+
);
|
|
2270
|
+
}
|
|
2271
|
+
if (value > SANSA_MAX_POSITION_INDEX) {
|
|
2272
|
+
this.warn(
|
|
2273
|
+
`Position index ${value} exceeds the SANSA v1 portable index ceiling ${SANSA_MAX_POSITION_INDEX}`,
|
|
2274
|
+
'SANSA_NON_PORTABLE_POSITION_INDEX',
|
|
2275
|
+
start,
|
|
2276
|
+
{ observed: value, portableFloor: SANSA_MAX_POSITION_INDEX },
|
|
2277
|
+
);
|
|
2278
|
+
}
|
|
2279
|
+
return value;
|
|
2280
|
+
}
|
|
2281
|
+
|
|
2282
|
+
parseQualifierExpression(stopChar = '') {
|
|
2283
|
+
const terms = [this.parseQualifierTerm(stopChar)];
|
|
2284
|
+
while (!this.atEnd() && this.peek() === '|') {
|
|
2285
|
+
this.index += 1;
|
|
2286
|
+
terms.push(this.parseQualifierTerm(stopChar));
|
|
2287
|
+
}
|
|
2288
|
+
return { type: 'QualifierExpression', terms };
|
|
2289
|
+
}
|
|
2290
|
+
|
|
2291
|
+
parseQualifierTerm(stopChar = '') {
|
|
2292
|
+
const name = this.parseIdentifier('qualifier type name');
|
|
2293
|
+
const parameters = [];
|
|
2294
|
+
const parameterGroups = [];
|
|
2295
|
+
const args = [];
|
|
2296
|
+
|
|
2297
|
+
while (this.match('<')) {
|
|
2298
|
+
const group = [];
|
|
2299
|
+
group.push(this.parseQualifierTerm('>'));
|
|
2300
|
+
if (this.peek() === '|') {
|
|
2301
|
+
this.fail('Nested qualifier unions are not supported', 'SANSA_INVALID_QUALIFIER');
|
|
2302
|
+
}
|
|
2303
|
+
while (this.match(',')) {
|
|
2304
|
+
group.push(this.parseQualifierTerm('>'));
|
|
2305
|
+
if (this.peek() === '|') {
|
|
2306
|
+
this.fail('Nested qualifier unions are not supported', 'SANSA_INVALID_QUALIFIER');
|
|
2307
|
+
}
|
|
2308
|
+
}
|
|
2309
|
+
this.consume('>');
|
|
2310
|
+
parameterGroups.push(group);
|
|
2311
|
+
parameters.push(...group);
|
|
2312
|
+
}
|
|
2313
|
+
|
|
2314
|
+
while (this.match('[')) {
|
|
2315
|
+
args.push(this.parseQualifierArgument());
|
|
2316
|
+
this.consume(']');
|
|
2317
|
+
}
|
|
2318
|
+
|
|
2319
|
+
const next = this.peek();
|
|
2320
|
+
if (next && !['|', ',', '>', stopChar].includes(next)) {
|
|
2321
|
+
this.fail(`Unexpected character '${next}' in qualifier expression`, 'SANSA_INVALID_QUALIFIER');
|
|
2322
|
+
}
|
|
2323
|
+
|
|
2324
|
+
return { type: 'QualifierTerm', name, parameters, parameterGroups, arguments: args };
|
|
2325
|
+
}
|
|
2326
|
+
|
|
2327
|
+
parseQualifierArgument() {
|
|
2328
|
+
if (this.peek() === '"') {
|
|
2329
|
+
return { kind: 'quoted', value: this.parseQuotedPayload() };
|
|
2330
|
+
}
|
|
2331
|
+
|
|
2332
|
+
const start = this.index;
|
|
2333
|
+
while (!this.atEnd() && this.peek() !== ']') {
|
|
2334
|
+
const char = this.peek();
|
|
2335
|
+
if (!isQualifierArgumentChar(char)) {
|
|
2336
|
+
this.fail(`Invalid unquoted qualifier argument character '${char}'`, 'SANSA_INVALID_QUALIFIER_ARGUMENT_CHAR');
|
|
2337
|
+
}
|
|
2338
|
+
this.index += 1;
|
|
2339
|
+
}
|
|
2340
|
+
if (this.index === start) this.fail('Expected qualifier argument', 'SANSA_EXPECTED_QUALIFIER_ARGUMENT');
|
|
2341
|
+
const value = this.input.slice(start, this.index);
|
|
2342
|
+
if (!QUALIFIER_ARG_RE.test(value)) this.fail('Invalid qualifier argument', 'SANSA_INVALID_QUALIFIER_ARGUMENT');
|
|
2343
|
+
return { kind: 'token', value };
|
|
2344
|
+
}
|
|
2345
|
+
|
|
2346
|
+
parseIdentifier(context) {
|
|
2347
|
+
const start = this.index;
|
|
2348
|
+
const first = this.peek();
|
|
2349
|
+
if (!isIdentifierStart(first)) this.fail(`Expected ${context}`, 'SANSA_EXPECTED_IDENTIFIER');
|
|
2350
|
+
this.index += 1;
|
|
2351
|
+
while (isIdentifierContinue(this.peek())) this.index += 1;
|
|
2352
|
+
return this.input.slice(start, this.index);
|
|
2353
|
+
}
|
|
2354
|
+
|
|
2355
|
+
parseQuotedPayload() {
|
|
2356
|
+
this.consume('"');
|
|
2357
|
+
let output = '';
|
|
2358
|
+
while (!this.atEnd()) {
|
|
2359
|
+
const char = this.peek();
|
|
2360
|
+
if (char === '"') {
|
|
2361
|
+
this.index += 1;
|
|
2362
|
+
return output;
|
|
2363
|
+
}
|
|
2364
|
+
if (char === '\n' || char === '\r') {
|
|
2365
|
+
this.fail('Quoted payloads must not contain raw newlines', 'SANSA_RAW_NEWLINE_IN_QUOTED_PAYLOAD');
|
|
2366
|
+
}
|
|
2367
|
+
if (char === '\\') {
|
|
2368
|
+
output += this.parseEscape();
|
|
2369
|
+
continue;
|
|
2370
|
+
}
|
|
2371
|
+
output += char;
|
|
2372
|
+
this.index += 1;
|
|
2373
|
+
}
|
|
2374
|
+
this.fail('Unterminated quoted payload', 'SANSA_UNTERMINATED_QUOTED_PAYLOAD');
|
|
2375
|
+
}
|
|
2376
|
+
|
|
2377
|
+
parseEscape() {
|
|
2378
|
+
this.consume('\\');
|
|
2379
|
+
const escape = this.peek();
|
|
2380
|
+
if (!escape) this.fail('Unterminated escape sequence', 'SANSA_UNTERMINATED_ESCAPE');
|
|
2381
|
+
this.index += 1;
|
|
2382
|
+
switch (escape) {
|
|
2383
|
+
case '\\': return '\\';
|
|
2384
|
+
case '"': return '"';
|
|
2385
|
+
case "'": return "'";
|
|
2386
|
+
case '`': return '`';
|
|
2387
|
+
case 'n': return '\n';
|
|
2388
|
+
case 'r': return '\r';
|
|
2389
|
+
case 't': return '\t';
|
|
2390
|
+
case 'b': return '\b';
|
|
2391
|
+
case 'f': return '\f';
|
|
2392
|
+
case 'u':
|
|
2393
|
+
return this.parseUnicodeEscape();
|
|
2394
|
+
default:
|
|
2395
|
+
this.fail(`Invalid escape sequence \\${escape}`, 'SANSA_INVALID_ESCAPE', this.index - 2);
|
|
2396
|
+
}
|
|
2397
|
+
}
|
|
2398
|
+
|
|
2399
|
+
parseUnicodeEscape() {
|
|
2400
|
+
if (this.match('{')) {
|
|
2401
|
+
const start = this.index;
|
|
2402
|
+
while (!this.atEnd() && this.peek() !== '}') this.index += 1;
|
|
2403
|
+
if (this.atEnd()) this.fail('Unterminated Unicode escape', 'SANSA_UNTERMINATED_UNICODE_ESCAPE');
|
|
2404
|
+
const raw = this.input.slice(start, this.index);
|
|
2405
|
+
this.consume('}');
|
|
2406
|
+
if (!/^[0-9A-Fa-f]{1,6}$/.test(raw)) this.fail('Invalid Unicode escape', 'SANSA_INVALID_UNICODE_ESCAPE', start);
|
|
2407
|
+
return codePointToString(Number.parseInt(raw, 16), start);
|
|
2408
|
+
}
|
|
2409
|
+
|
|
2410
|
+
const raw = this.input.slice(this.index, this.index + 4);
|
|
2411
|
+
if (!/^[0-9A-Fa-f]{4}$/.test(raw)) this.fail('Invalid Unicode escape', 'SANSA_INVALID_UNICODE_ESCAPE');
|
|
2412
|
+
this.index += 4;
|
|
2413
|
+
return codePointToString(Number.parseInt(raw, 16), this.index - 4);
|
|
2414
|
+
}
|
|
2415
|
+
|
|
2416
|
+
expectEnd() {
|
|
2417
|
+
if (!this.atEnd()) this.fail(`Unexpected trailing character '${this.peek()}'`, 'SANSA_TRAILING_INPUT');
|
|
2418
|
+
}
|
|
2419
|
+
|
|
2420
|
+
consume(char) {
|
|
2421
|
+
if (this.peek() !== char) this.fail(`Expected '${char}'`, 'SANSA_EXPECTED_TOKEN');
|
|
2422
|
+
this.index += 1;
|
|
2423
|
+
}
|
|
2424
|
+
|
|
2425
|
+
match(char) {
|
|
2426
|
+
if (this.peek() !== char) return false;
|
|
2427
|
+
this.index += 1;
|
|
2428
|
+
return true;
|
|
2429
|
+
}
|
|
2430
|
+
|
|
2431
|
+
peek() {
|
|
2432
|
+
return this.input[this.index] ?? '';
|
|
2433
|
+
}
|
|
2434
|
+
|
|
2435
|
+
atEnd() {
|
|
2436
|
+
return this.index >= this.input.length;
|
|
2437
|
+
}
|
|
2438
|
+
|
|
2439
|
+
fail(message, code, index = this.index) {
|
|
2440
|
+
throw new SansaParseError(message, index, code);
|
|
2441
|
+
}
|
|
2442
|
+
|
|
2443
|
+
warn(message, code, index = this.index, extra = {}) {
|
|
2444
|
+
this.warnings.push({ code, message, index, ...extra });
|
|
2445
|
+
}
|
|
2446
|
+
}
|
|
2447
|
+
|
|
2448
|
+
class QueryParser {
|
|
2449
|
+
constructor(input, options = {}) {
|
|
2450
|
+
this.input = input;
|
|
2451
|
+
this.options = options;
|
|
2452
|
+
this.warnings = [];
|
|
2453
|
+
}
|
|
2454
|
+
|
|
2455
|
+
parse() {
|
|
2456
|
+
const source = stripQueryComments(this.input);
|
|
2457
|
+
if (source.trim().length === 0) {
|
|
2458
|
+
this.fail('Expected SANSA query', 'SANSA_QUERY_EMPTY', 0);
|
|
2459
|
+
}
|
|
2460
|
+
|
|
2461
|
+
const clauses = scanQueryClauses(source);
|
|
2462
|
+
const first = clauses[0];
|
|
2463
|
+
if (!first || first.name !== 'from' || source.slice(0, first.start).trim().length > 0) {
|
|
2464
|
+
this.fail("Expected 'from' clause", 'SANSA_QUERY_EXPECTED_FROM', first?.start ?? 0);
|
|
2465
|
+
}
|
|
2466
|
+
|
|
2467
|
+
let previousOrder = -1;
|
|
2468
|
+
let sawSelect = false;
|
|
2469
|
+
const seen = new Set();
|
|
2470
|
+
const order = new Map([
|
|
2471
|
+
['from', 0],
|
|
2472
|
+
['where', 1],
|
|
2473
|
+
['order', 2],
|
|
2474
|
+
['offset', 3],
|
|
2475
|
+
['limit', 4],
|
|
2476
|
+
['select', 5],
|
|
2477
|
+
]);
|
|
2478
|
+
|
|
2479
|
+
for (const clause of clauses) {
|
|
2480
|
+
if (sawSelect) {
|
|
2481
|
+
this.fail("'select' must be the terminal SANSA query clause", 'SANSA_QUERY_SELECT_MUST_BE_TERMINAL', clause.start);
|
|
2482
|
+
}
|
|
2483
|
+
if (seen.has(clause.name)) {
|
|
2484
|
+
this.fail(`Duplicate SANSA query clause '${clause.label}'`, 'SANSA_QUERY_DUPLICATE_CLAUSE', clause.start);
|
|
2485
|
+
}
|
|
2486
|
+
seen.add(clause.name);
|
|
2487
|
+
const currentOrder = order.get(clause.name);
|
|
2488
|
+
if (currentOrder < previousOrder) {
|
|
2489
|
+
this.fail(`SANSA query clause '${clause.label}' is out of order`, 'SANSA_QUERY_INVALID_CLAUSE_ORDER', clause.start);
|
|
2490
|
+
}
|
|
2491
|
+
previousOrder = currentOrder;
|
|
2492
|
+
if (clause.name === 'select') sawSelect = true;
|
|
2493
|
+
}
|
|
2494
|
+
|
|
2495
|
+
if (!seen.has('select')) {
|
|
2496
|
+
const end = source.length;
|
|
2497
|
+
this.fail("Expected 'select' clause", 'SANSA_QUERY_EXPECTED_SELECT', end);
|
|
2498
|
+
}
|
|
2499
|
+
|
|
2500
|
+
const clauseByName = new Map(clauses.map((clause) => [clause.name, clause]));
|
|
2501
|
+
const from = this.parseFromClause(clauseByName.get('from'));
|
|
2502
|
+
const where = clauseByName.has('where') ? this.parseExpressionClause(clauseByName.get('where'), 'where') : null;
|
|
2503
|
+
const orderBy = clauseByName.has('order') ? this.parseOrderByClause(clauseByName.get('order')) : null;
|
|
2504
|
+
const offset = clauseByName.has('offset') ? this.parseIntegerClause(clauseByName.get('offset'), 'offset') : null;
|
|
2505
|
+
const limit = clauseByName.has('limit') ? this.parseIntegerClause(clauseByName.get('limit'), 'limit') : null;
|
|
2506
|
+
const select = this.parseExpressionClause(clauseByName.get('select'), 'select');
|
|
2507
|
+
|
|
2508
|
+
const query = {
|
|
2509
|
+
type: 'SansaQuery',
|
|
2510
|
+
from,
|
|
2511
|
+
where,
|
|
2512
|
+
orderBy,
|
|
2513
|
+
offset,
|
|
2514
|
+
limit,
|
|
2515
|
+
select,
|
|
2516
|
+
clauses: clauses.map((clause) => clause.name),
|
|
2517
|
+
};
|
|
2518
|
+
query.canonical = renderQuery(query);
|
|
2519
|
+
return query;
|
|
2520
|
+
}
|
|
2521
|
+
|
|
2522
|
+
parseFromClause(clause) {
|
|
2523
|
+
const expression = normalizeQueryExpression(clause.body);
|
|
2524
|
+
if (expression.length === 0) {
|
|
2525
|
+
this.fail("Expected SANSA address after 'from'", 'SANSA_QUERY_EXPECTED_FROM_ADDRESS', clause.bodyStart);
|
|
2526
|
+
}
|
|
2527
|
+
if (expression.startsWith('$') || expression.startsWith('?')) {
|
|
2528
|
+
if (/\s/.test(expression)) {
|
|
2529
|
+
this.fail("Expected a single SANSA address after 'from'", 'SANSA_QUERY_INVALID_FROM_ADDRESS', clause.bodyStart);
|
|
2530
|
+
}
|
|
2531
|
+
const result = parseAddress(expression, this.options.address);
|
|
2532
|
+
if (!result.ok) {
|
|
2533
|
+
const first = result.errors[0];
|
|
2534
|
+
this.fail(first.message, first.code, clause.bodyStart + first.index);
|
|
2535
|
+
}
|
|
2536
|
+
this.warnings.push(...result.warnings);
|
|
2537
|
+
return { type: 'fromClause', source: 'address', address: result.address };
|
|
2538
|
+
}
|
|
2539
|
+
|
|
2540
|
+
const ast = this.parseClauseExpression(expression, clause.bodyStart);
|
|
2541
|
+
if (ast.type !== 'functionCallExpression' || ast.name !== 'path') {
|
|
2542
|
+
this.fail("Expected SANSA address or path(...) after 'from'", 'SANSA_QUERY_INVALID_FROM_SOURCE', clause.bodyStart);
|
|
2543
|
+
}
|
|
2544
|
+
return { type: 'fromClause', source: 'expression', expression: renderQueryExpression(ast), ast };
|
|
2545
|
+
}
|
|
2546
|
+
|
|
2547
|
+
parseExpressionClause(clause, name) {
|
|
2548
|
+
const expression = normalizeQueryExpression(clause.body);
|
|
2549
|
+
if (expression.length === 0) {
|
|
2550
|
+
this.fail(`Expected expression after '${clause.label}'`, `SANSA_QUERY_EXPECTED_${name.toUpperCase()}_EXPRESSION`, clause.bodyStart);
|
|
2551
|
+
}
|
|
2552
|
+
const ast = this.parseClauseExpression(expression, clause.bodyStart);
|
|
2553
|
+
return { type: `${name}Clause`, expression: renderQueryExpression(ast), ast };
|
|
2554
|
+
}
|
|
2555
|
+
|
|
2556
|
+
parseOrderByClause(clause) {
|
|
2557
|
+
const expression = normalizeQueryExpression(clause.body);
|
|
2558
|
+
if (expression.length === 0) {
|
|
2559
|
+
this.fail("Expected expression after 'order by'", 'SANSA_QUERY_EXPECTED_ORDER_EXPRESSION', clause.bodyStart);
|
|
2560
|
+
}
|
|
2561
|
+
const keys = splitTopLevelQueryList(expression).map((part) => {
|
|
2562
|
+
const normalized = normalizeQueryExpression(part);
|
|
2563
|
+
const directionMatch = /^(.*)\s+(asc|desc)$/u.exec(normalized);
|
|
2564
|
+
const keyExpression = directionMatch ? directionMatch[1].trim() : normalized;
|
|
2565
|
+
const direction = directionMatch ? directionMatch[2] : 'asc';
|
|
2566
|
+
if (keyExpression.length === 0) {
|
|
2567
|
+
this.fail("Expected order key expression", 'SANSA_QUERY_EXPECTED_ORDER_EXPRESSION', clause.bodyStart);
|
|
2568
|
+
}
|
|
2569
|
+
const ast = this.parseClauseExpression(keyExpression, clause.bodyStart + part.indexOf(keyExpression));
|
|
2570
|
+
return { type: 'orderKey', expression: renderQueryExpression(ast), ast, direction };
|
|
2571
|
+
});
|
|
2572
|
+
return { type: 'orderByClause', keys };
|
|
2573
|
+
}
|
|
2574
|
+
|
|
2575
|
+
parseIntegerClause(clause, name) {
|
|
2576
|
+
const value = normalizeQueryExpression(clause.body);
|
|
2577
|
+
const code = name === 'limit' ? 'SANSA_QUERY_INVALID_LIMIT' : 'SANSA_QUERY_INVALID_OFFSET';
|
|
2578
|
+
if (!/^(0|[1-9][0-9]*)$/.test(value)) {
|
|
2579
|
+
this.fail(`Expected non-negative integer after '${name}'`, code, clause.bodyStart);
|
|
2580
|
+
}
|
|
2581
|
+
if (exceedsUnsignedDecimal(value, SANSA_MAX_QUERY_INTEGER)) {
|
|
2582
|
+
this.fail(`Query '${name}' must be less than or equal to ${SANSA_MAX_QUERY_INTEGER}`, code, clause.bodyStart);
|
|
2583
|
+
}
|
|
2584
|
+
return { type: `${name}Clause`, value: Number(value) };
|
|
2585
|
+
}
|
|
2586
|
+
|
|
2587
|
+
parseClauseExpression(expression, offset) {
|
|
2588
|
+
const result = parseQueryExpression(expression, this.options.expression);
|
|
2589
|
+
if (!result.ok) {
|
|
2590
|
+
const first = result.errors[0];
|
|
2591
|
+
this.fail(first.message, first.code, offset + first.index);
|
|
2592
|
+
}
|
|
2593
|
+
this.warnings.push(...result.warnings);
|
|
2594
|
+
return result.expression;
|
|
2595
|
+
}
|
|
2596
|
+
|
|
2597
|
+
fail(message, code, index) {
|
|
2598
|
+
throw new SansaParseError(message, index, code);
|
|
2599
|
+
}
|
|
2600
|
+
}
|
|
2601
|
+
|
|
2602
|
+
class QueryExpressionParser {
|
|
2603
|
+
constructor(input, options = {}) {
|
|
2604
|
+
this.input = normalizeQueryExpression(stripQueryComments(String(input)));
|
|
2605
|
+
this.options = options;
|
|
2606
|
+
this.index = 0;
|
|
2607
|
+
this.warnings = [];
|
|
2608
|
+
}
|
|
2609
|
+
|
|
2610
|
+
parse() {
|
|
2611
|
+
if (this.input.length === 0) {
|
|
2612
|
+
this.fail('Expected SANSA query expression', 'SANSA_QUERY_EXPECTED_EXPRESSION');
|
|
2613
|
+
}
|
|
2614
|
+
const expression = this.parseOr();
|
|
2615
|
+
this.skipLayout();
|
|
2616
|
+
if (!this.atEnd()) {
|
|
2617
|
+
this.fail(`Unexpected query expression token '${this.peek()}'`, 'SANSA_QUERY_UNEXPECTED_EXPRESSION_TOKEN');
|
|
2618
|
+
}
|
|
2619
|
+
expression.canonical = renderQueryExpression(expression);
|
|
2620
|
+
return expression;
|
|
2621
|
+
}
|
|
2622
|
+
|
|
2623
|
+
parseOr() {
|
|
2624
|
+
let left = this.parseAnd();
|
|
2625
|
+
while (this.matchKeyword('or')) {
|
|
2626
|
+
const right = this.parseAnd();
|
|
2627
|
+
left = this.binary('or', left, right);
|
|
2628
|
+
}
|
|
2629
|
+
return left;
|
|
2630
|
+
}
|
|
2631
|
+
|
|
2632
|
+
parseAnd() {
|
|
2633
|
+
let left = this.parseNot();
|
|
2634
|
+
while (this.matchKeyword('and')) {
|
|
2635
|
+
const right = this.parseNot();
|
|
2636
|
+
left = this.binary('and', left, right);
|
|
2637
|
+
}
|
|
2638
|
+
return left;
|
|
2639
|
+
}
|
|
2640
|
+
|
|
2641
|
+
parseNot() {
|
|
2642
|
+
if (this.matchKeyword('not')) {
|
|
2643
|
+
const argument = this.parseNot();
|
|
2644
|
+
return {
|
|
2645
|
+
type: 'unaryExpression',
|
|
2646
|
+
operator: 'not',
|
|
2647
|
+
argument,
|
|
2648
|
+
canonical: '',
|
|
2649
|
+
};
|
|
2650
|
+
}
|
|
2651
|
+
return this.parseComparison();
|
|
2652
|
+
}
|
|
2653
|
+
|
|
2654
|
+
parseComparison() {
|
|
2655
|
+
let left = this.parsePrimary();
|
|
2656
|
+
this.skipLayout();
|
|
2657
|
+
const operator = this.matchComparisonOperator();
|
|
2658
|
+
if (!operator) return left;
|
|
2659
|
+
const right = this.parsePrimary();
|
|
2660
|
+
left = this.binary(operator, left, right);
|
|
2661
|
+
this.skipLayout();
|
|
2662
|
+
if (this.matchComparisonOperator()) {
|
|
2663
|
+
this.fail('Chained comparison expressions are not supported', 'SANSA_QUERY_UNEXPECTED_EXPRESSION_TOKEN');
|
|
2664
|
+
}
|
|
2665
|
+
return left;
|
|
2666
|
+
}
|
|
2667
|
+
|
|
2668
|
+
parsePrimary() {
|
|
2669
|
+
this.skipLayout();
|
|
2670
|
+
const char = this.peek();
|
|
2671
|
+
if (!char) this.fail('Expected SANSA query expression', 'SANSA_QUERY_EXPECTED_EXPRESSION');
|
|
2672
|
+
if (char === '"') return this.parseString();
|
|
2673
|
+
if (char === '-' || isDigit(char)) return this.parseNumber();
|
|
2674
|
+
if (char === '$' || char === '?' || char === '.') return this.parseResolution();
|
|
2675
|
+
if (char === '(') return this.parseGroup();
|
|
2676
|
+
if (char === '{') return this.parseProjection();
|
|
2677
|
+
if (isIdentifierStart(char)) return this.parseIdentifierExpression();
|
|
2678
|
+
this.fail(`Unexpected query expression token '${char}'`, 'SANSA_QUERY_UNEXPECTED_EXPRESSION_TOKEN');
|
|
2679
|
+
}
|
|
2680
|
+
|
|
2681
|
+
parseIdentifierExpression() {
|
|
2682
|
+
const name = this.readIdentifier();
|
|
2683
|
+
if (name === 'true' || name === 'false') {
|
|
2684
|
+
return {
|
|
2685
|
+
type: 'literalExpression',
|
|
2686
|
+
kind: 'boolean',
|
|
2687
|
+
value: name === 'true',
|
|
2688
|
+
canonical: name,
|
|
2689
|
+
};
|
|
2690
|
+
}
|
|
2691
|
+
this.skipLayout();
|
|
2692
|
+
if (!this.match('(')) {
|
|
2693
|
+
this.fail(`Unexpected query expression identifier '${name}'`, 'SANSA_QUERY_UNEXPECTED_EXPRESSION_TOKEN');
|
|
2694
|
+
}
|
|
2695
|
+
const argumentSource = this.readBalancedBody('(', ')');
|
|
2696
|
+
const argumentParts = argumentSource.trim().length === 0 ? [] : splitTopLevelQueryList(argumentSource);
|
|
2697
|
+
const args = argumentParts.map((part) => parseQueryExpressionOrThrow(part, this.options));
|
|
2698
|
+
if (['any', 'all', 'none'].includes(name)) {
|
|
2699
|
+
if (args.length !== 1) {
|
|
2700
|
+
this.fail(`Cardinality operator '${name}' expects exactly one expression`, 'SANSA_QUERY_INVALID_FUNCTION_CALL');
|
|
2701
|
+
}
|
|
2702
|
+
return {
|
|
2703
|
+
type: 'cardinalityExpression',
|
|
2704
|
+
operator: name,
|
|
2705
|
+
argument: args[0],
|
|
2706
|
+
canonical: '',
|
|
2707
|
+
};
|
|
2708
|
+
}
|
|
2709
|
+
if (['exists', 'absent'].includes(name)) {
|
|
2710
|
+
if (args.length !== 1) {
|
|
2711
|
+
this.fail(`Existence operator '${name}' expects exactly one resolution expression`, 'SANSA_QUERY_INVALID_FUNCTION_CALL');
|
|
2712
|
+
}
|
|
2713
|
+
if (!unwrapResolutionExpression(args[0])) {
|
|
2714
|
+
this.fail(`Existence operator '${name}' expects a resolution expression`, 'SANSA_QUERY_INVALID_FUNCTION_CALL');
|
|
2715
|
+
}
|
|
2716
|
+
return {
|
|
2717
|
+
type: 'existenceExpression',
|
|
2718
|
+
operator: name,
|
|
2719
|
+
argument: args[0],
|
|
2720
|
+
canonical: '',
|
|
2721
|
+
};
|
|
2722
|
+
}
|
|
2723
|
+
return {
|
|
2724
|
+
type: 'functionCallExpression',
|
|
2725
|
+
name,
|
|
2726
|
+
arguments: args,
|
|
2727
|
+
canonical: '',
|
|
2728
|
+
};
|
|
2729
|
+
}
|
|
2730
|
+
|
|
2731
|
+
parseString() {
|
|
2732
|
+
const value = this.parseQuotedPayload();
|
|
2733
|
+
return {
|
|
2734
|
+
type: 'literalExpression',
|
|
2735
|
+
kind: 'string',
|
|
2736
|
+
value,
|
|
2737
|
+
canonical: quotePayload(value),
|
|
2738
|
+
};
|
|
2739
|
+
}
|
|
2740
|
+
|
|
2741
|
+
parseNumber() {
|
|
2742
|
+
const start = this.index;
|
|
2743
|
+
if (this.peek() === '-') this.index += 1;
|
|
2744
|
+
if (this.peek() === '0') {
|
|
2745
|
+
this.index += 1;
|
|
2746
|
+
if (isDigit(this.peek())) {
|
|
2747
|
+
this.fail('Number literals must not contain leading zeroes', 'SANSA_QUERY_INVALID_NUMBER_LITERAL', start);
|
|
2748
|
+
}
|
|
2749
|
+
} else if (isDigit(this.peek())) {
|
|
2750
|
+
while (isDigit(this.peek())) this.index += 1;
|
|
2751
|
+
} else {
|
|
2752
|
+
this.fail('Expected number literal', 'SANSA_QUERY_INVALID_NUMBER_LITERAL', start);
|
|
2753
|
+
}
|
|
2754
|
+
if (this.peek() === '.') {
|
|
2755
|
+
this.index += 1;
|
|
2756
|
+
if (!isDigit(this.peek())) {
|
|
2757
|
+
this.fail('Expected decimal digits after number literal decimal point', 'SANSA_QUERY_INVALID_NUMBER_LITERAL', start);
|
|
2758
|
+
}
|
|
2759
|
+
while (isDigit(this.peek())) this.index += 1;
|
|
2760
|
+
}
|
|
2761
|
+
const source = this.input.slice(start, this.index);
|
|
2762
|
+
return {
|
|
2763
|
+
type: 'literalExpression',
|
|
2764
|
+
kind: 'number',
|
|
2765
|
+
value: Number(source),
|
|
2766
|
+
canonical: source,
|
|
2767
|
+
};
|
|
2768
|
+
}
|
|
2769
|
+
|
|
2770
|
+
parseResolution() {
|
|
2771
|
+
const start = this.index;
|
|
2772
|
+
const source = this.readResolutionSource();
|
|
2773
|
+
if (source === '.') {
|
|
2774
|
+
return {
|
|
2775
|
+
type: 'currentBindingExpression',
|
|
2776
|
+
canonical: '.',
|
|
2777
|
+
};
|
|
2778
|
+
}
|
|
2779
|
+
const positionalCurrentShorthand = isQueryCurrentPositionalShorthand(source);
|
|
2780
|
+
const parseSource = positionalCurrentShorthand
|
|
2781
|
+
? `?${source.slice(1)}`
|
|
2782
|
+
: source.startsWith('.')
|
|
2783
|
+
? `?${source}`
|
|
2784
|
+
: source;
|
|
2785
|
+
const result = parseAddress(parseSource, this.options.address);
|
|
2786
|
+
if (!result.ok) {
|
|
2787
|
+
const first = result.errors[0];
|
|
2788
|
+
this.fail(first.message, first.code, start + first.index - (source.startsWith('.') ? 1 : 0));
|
|
2789
|
+
}
|
|
2790
|
+
this.warnings.push(...result.warnings);
|
|
2791
|
+
const scope = source.startsWith('.')
|
|
2792
|
+
? 'current'
|
|
2793
|
+
: result.address.root.kind;
|
|
2794
|
+
const canonical = positionalCurrentShorthand
|
|
2795
|
+
? `.${renderAddress(result.address).slice(1)}`
|
|
2796
|
+
: source.startsWith('.')
|
|
2797
|
+
? renderAddress(result.address).slice(1)
|
|
2798
|
+
: renderAddress(result.address);
|
|
2799
|
+
return {
|
|
2800
|
+
type: 'resolutionExpression',
|
|
2801
|
+
scope,
|
|
2802
|
+
address: result.address,
|
|
2803
|
+
canonical,
|
|
2804
|
+
};
|
|
2805
|
+
}
|
|
2806
|
+
|
|
2807
|
+
parseGroup() {
|
|
2808
|
+
this.consume('(');
|
|
2809
|
+
const source = this.readBalancedBody('(', ')');
|
|
2810
|
+
const expression = parseQueryExpressionOrThrow(source, this.options);
|
|
2811
|
+
return {
|
|
2812
|
+
type: 'groupExpression',
|
|
2813
|
+
expression,
|
|
2814
|
+
canonical: '',
|
|
2815
|
+
};
|
|
2816
|
+
}
|
|
2817
|
+
|
|
2818
|
+
parseProjection() {
|
|
2819
|
+
this.consume('{');
|
|
2820
|
+
const source = this.readBalancedBody('{', '}');
|
|
2821
|
+
const fields = splitProjectionFields(source).map((field) => ({
|
|
2822
|
+
type: 'projectionField',
|
|
2823
|
+
name: field.name,
|
|
2824
|
+
expression: parseQueryExpressionOrThrow(field.expression, this.options),
|
|
2825
|
+
}));
|
|
2826
|
+
if (fields.length === 0) {
|
|
2827
|
+
this.fail('Expected at least one projection field', 'SANSA_QUERY_INVALID_PROJECTION');
|
|
2828
|
+
}
|
|
2829
|
+
return {
|
|
2830
|
+
type: 'projectionExpression',
|
|
2831
|
+
fields,
|
|
2832
|
+
canonical: '',
|
|
2833
|
+
};
|
|
2834
|
+
}
|
|
2835
|
+
|
|
2836
|
+
readResolutionSource() {
|
|
2837
|
+
const start = this.index;
|
|
2838
|
+
let quote = null;
|
|
2839
|
+
let parenDepth = 0;
|
|
2840
|
+
let bracketDepth = 0;
|
|
2841
|
+
let angleDepth = 0;
|
|
2842
|
+
let qualifierDepth = 0;
|
|
2843
|
+
let sawColon = false;
|
|
2844
|
+
for (; this.index < this.input.length; this.index += 1) {
|
|
2845
|
+
const char = this.input[this.index];
|
|
2846
|
+
if (quote) {
|
|
2847
|
+
if (char === '\\') this.index += 1;
|
|
2848
|
+
else if (char === quote) quote = null;
|
|
2849
|
+
continue;
|
|
2850
|
+
}
|
|
2851
|
+
if (char === '"') {
|
|
2852
|
+
quote = char;
|
|
2853
|
+
continue;
|
|
2854
|
+
}
|
|
2855
|
+
if (char === ':') sawColon = true;
|
|
2856
|
+
if (char === '(') parenDepth += 1;
|
|
2857
|
+
else if (char === ')' && parenDepth > 0) parenDepth -= 1;
|
|
2858
|
+
else if (char === '[') bracketDepth += 1;
|
|
2859
|
+
else if (char === ']' && bracketDepth > 0) bracketDepth -= 1;
|
|
2860
|
+
else if (char === '<' && (sawColon || this.input[this.index - 1] === '.')) {
|
|
2861
|
+
angleDepth += 1;
|
|
2862
|
+
if (sawColon) qualifierDepth += 1;
|
|
2863
|
+
} else if (char === '>' && angleDepth > 0) {
|
|
2864
|
+
angleDepth -= 1;
|
|
2865
|
+
if (qualifierDepth > 0) qualifierDepth -= 1;
|
|
2866
|
+
} else if (
|
|
2867
|
+
parenDepth === 0
|
|
2868
|
+
&& bracketDepth === 0
|
|
2869
|
+
&& angleDepth === 0
|
|
2870
|
+
&& (isLayout(char) || char === ',' || char === ')' || char === '}' || isComparisonStart(char))
|
|
2871
|
+
) {
|
|
2872
|
+
break;
|
|
2873
|
+
}
|
|
2874
|
+
}
|
|
2875
|
+
const source = this.input.slice(start, this.index);
|
|
2876
|
+
if (source.length === 0) {
|
|
2877
|
+
this.fail('Expected SANSA resolution expression', 'SANSA_QUERY_INVALID_RESOLUTION_EXPRESSION', start);
|
|
2878
|
+
}
|
|
2879
|
+
return source;
|
|
2880
|
+
}
|
|
2881
|
+
|
|
2882
|
+
readBalancedBody(open, close) {
|
|
2883
|
+
const start = this.index;
|
|
2884
|
+
let quote = null;
|
|
2885
|
+
let depth = 1;
|
|
2886
|
+
while (!this.atEnd()) {
|
|
2887
|
+
const char = this.input[this.index];
|
|
2888
|
+
if (quote) {
|
|
2889
|
+
if (char === '\\') this.index += 2;
|
|
2890
|
+
else {
|
|
2891
|
+
if (char === quote) quote = null;
|
|
2892
|
+
this.index += 1;
|
|
2893
|
+
}
|
|
2894
|
+
continue;
|
|
2895
|
+
}
|
|
2896
|
+
if (char === '"') {
|
|
2897
|
+
quote = char;
|
|
2898
|
+
this.index += 1;
|
|
2899
|
+
continue;
|
|
2900
|
+
}
|
|
2901
|
+
if (char === open) depth += 1;
|
|
2902
|
+
else if (char === close) depth -= 1;
|
|
2903
|
+
if (depth === 0) {
|
|
2904
|
+
const body = this.input.slice(start, this.index);
|
|
2905
|
+
this.index += 1;
|
|
2906
|
+
return body;
|
|
2907
|
+
}
|
|
2908
|
+
this.index += 1;
|
|
2909
|
+
}
|
|
2910
|
+
this.fail(`Unterminated '${open}' expression`, 'SANSA_QUERY_UNTERMINATED_EXPRESSION', start - 1);
|
|
2911
|
+
}
|
|
2912
|
+
|
|
2913
|
+
parseQuotedPayload() {
|
|
2914
|
+
const parser = new AddressParser(this.input.slice(this.index), this.options.address);
|
|
2915
|
+
const value = parser.parseQuotedPayload();
|
|
2916
|
+
this.warnings.push(...parser.warnings);
|
|
2917
|
+
this.index += parser.index;
|
|
2918
|
+
return value;
|
|
2919
|
+
}
|
|
2920
|
+
|
|
2921
|
+
binary(operator, left, right) {
|
|
2922
|
+
return {
|
|
2923
|
+
type: 'binaryExpression',
|
|
2924
|
+
operator,
|
|
2925
|
+
left,
|
|
2926
|
+
right,
|
|
2927
|
+
canonical: '',
|
|
2928
|
+
};
|
|
2929
|
+
}
|
|
2930
|
+
|
|
2931
|
+
matchComparisonOperator() {
|
|
2932
|
+
this.skipLayout();
|
|
2933
|
+
if (this.matchKeyword('in')) return 'in';
|
|
2934
|
+
for (const operator of ['==', '!=', '<=', '>=', '<', '>']) {
|
|
2935
|
+
if (this.input.startsWith(operator, this.index)) {
|
|
2936
|
+
this.index += operator.length;
|
|
2937
|
+
return operator;
|
|
2938
|
+
}
|
|
2939
|
+
}
|
|
2940
|
+
return null;
|
|
2941
|
+
}
|
|
2942
|
+
|
|
2943
|
+
matchKeyword(keyword) {
|
|
2944
|
+
this.skipLayout();
|
|
2945
|
+
if (!this.input.startsWith(keyword, this.index)) return false;
|
|
2946
|
+
const before = this.index === 0 ? '' : this.input[this.index - 1];
|
|
2947
|
+
const after = this.input[this.index + keyword.length] ?? '';
|
|
2948
|
+
if (isIdentifierContinue(before) || isIdentifierContinue(after)) return false;
|
|
2949
|
+
this.index += keyword.length;
|
|
2950
|
+
return true;
|
|
2951
|
+
}
|
|
2952
|
+
|
|
2953
|
+
readIdentifier() {
|
|
2954
|
+
const start = this.index;
|
|
2955
|
+
if (!isIdentifierStart(this.peek())) {
|
|
2956
|
+
this.fail('Expected identifier', 'SANSA_QUERY_UNEXPECTED_EXPRESSION_TOKEN');
|
|
2957
|
+
}
|
|
2958
|
+
this.index += 1;
|
|
2959
|
+
while (isIdentifierContinue(this.peek())) this.index += 1;
|
|
2960
|
+
return this.input.slice(start, this.index);
|
|
2961
|
+
}
|
|
2962
|
+
|
|
2963
|
+
skipLayout() {
|
|
2964
|
+
while (isLayout(this.peek())) this.index += 1;
|
|
2965
|
+
}
|
|
2966
|
+
|
|
2967
|
+
consume(char) {
|
|
2968
|
+
if (this.peek() !== char) this.fail(`Expected '${char}'`, 'SANSA_QUERY_UNEXPECTED_EXPRESSION_TOKEN');
|
|
2969
|
+
this.index += 1;
|
|
2970
|
+
}
|
|
2971
|
+
|
|
2972
|
+
match(char) {
|
|
2973
|
+
if (this.peek() !== char) return false;
|
|
2974
|
+
this.index += 1;
|
|
2975
|
+
return true;
|
|
2976
|
+
}
|
|
2977
|
+
|
|
2978
|
+
peek() {
|
|
2979
|
+
return this.input[this.index] ?? '';
|
|
2980
|
+
}
|
|
2981
|
+
|
|
2982
|
+
atEnd() {
|
|
2983
|
+
return this.index >= this.input.length;
|
|
2984
|
+
}
|
|
2985
|
+
|
|
2986
|
+
fail(message, code, index = this.index) {
|
|
2987
|
+
throw new SansaParseError(message, index, code);
|
|
2988
|
+
}
|
|
2989
|
+
}
|
|
2990
|
+
|
|
2991
|
+
function stripQueryComments(input) {
|
|
2992
|
+
let output = '';
|
|
2993
|
+
let quote = null;
|
|
2994
|
+
for (let index = 0; index < input.length; index += 1) {
|
|
2995
|
+
const char = input[index];
|
|
2996
|
+
const next = input[index + 1] ?? '';
|
|
2997
|
+
if (quote) {
|
|
2998
|
+
output += char;
|
|
2999
|
+
if (char === '\\') {
|
|
3000
|
+
index += 1;
|
|
3001
|
+
output += input[index] ?? '';
|
|
3002
|
+
} else if (char === quote) {
|
|
3003
|
+
quote = null;
|
|
3004
|
+
}
|
|
3005
|
+
continue;
|
|
3006
|
+
}
|
|
3007
|
+
if (char === '"' || char === "'") {
|
|
3008
|
+
quote = char;
|
|
3009
|
+
output += char;
|
|
3010
|
+
continue;
|
|
3011
|
+
}
|
|
3012
|
+
if (char === '/' && next === '/') {
|
|
3013
|
+
output += ' ';
|
|
3014
|
+
index += 1;
|
|
3015
|
+
while (index + 1 < input.length && input[index + 1] !== '\n' && input[index + 1] !== '\r') {
|
|
3016
|
+
index += 1;
|
|
3017
|
+
output += ' ';
|
|
3018
|
+
}
|
|
3019
|
+
continue;
|
|
3020
|
+
}
|
|
3021
|
+
if (char === '/' && next === '*') {
|
|
3022
|
+
const start = index;
|
|
3023
|
+
output += ' ';
|
|
3024
|
+
index += 1;
|
|
3025
|
+
let closed = false;
|
|
3026
|
+
while (index + 1 < input.length) {
|
|
3027
|
+
index += 1;
|
|
3028
|
+
const current = input[index];
|
|
3029
|
+
const following = input[index + 1] ?? '';
|
|
3030
|
+
output += current === '\n' || current === '\r' ? current : ' ';
|
|
3031
|
+
if (current === '*' && following === '/') {
|
|
3032
|
+
index += 1;
|
|
3033
|
+
output += ' ';
|
|
3034
|
+
closed = true;
|
|
3035
|
+
break;
|
|
3036
|
+
}
|
|
3037
|
+
}
|
|
3038
|
+
if (!closed) {
|
|
3039
|
+
throw new SansaParseError('Unterminated SANSA query block comment', start, 'SANSA_QUERY_UNTERMINATED_BLOCK_COMMENT');
|
|
3040
|
+
}
|
|
3041
|
+
continue;
|
|
3042
|
+
}
|
|
3043
|
+
output += char;
|
|
3044
|
+
}
|
|
3045
|
+
return output;
|
|
3046
|
+
}
|
|
3047
|
+
|
|
3048
|
+
function scanQueryClauses(source) {
|
|
3049
|
+
const clauses = [];
|
|
3050
|
+
let quote = null;
|
|
3051
|
+
let parenDepth = 0;
|
|
3052
|
+
let bracketDepth = 0;
|
|
3053
|
+
let braceDepth = 0;
|
|
3054
|
+
for (let index = 0; index < source.length; index += 1) {
|
|
3055
|
+
const char = source[index];
|
|
3056
|
+
if (quote) {
|
|
3057
|
+
if (char === '\\') {
|
|
3058
|
+
index += 1;
|
|
3059
|
+
} else if (char === quote) {
|
|
3060
|
+
quote = null;
|
|
3061
|
+
}
|
|
3062
|
+
continue;
|
|
3063
|
+
}
|
|
3064
|
+
if (char === '"' || char === "'") {
|
|
3065
|
+
quote = char;
|
|
3066
|
+
continue;
|
|
3067
|
+
}
|
|
3068
|
+
if (char === '(') parenDepth += 1;
|
|
3069
|
+
else if (char === ')' && parenDepth > 0) parenDepth -= 1;
|
|
3070
|
+
else if (char === '[') bracketDepth += 1;
|
|
3071
|
+
else if (char === ']' && bracketDepth > 0) bracketDepth -= 1;
|
|
3072
|
+
else if (char === '{') braceDepth += 1;
|
|
3073
|
+
else if (char === '}' && braceDepth > 0) braceDepth -= 1;
|
|
3074
|
+
|
|
3075
|
+
if (parenDepth !== 0 || bracketDepth !== 0 || braceDepth !== 0) {
|
|
3076
|
+
continue;
|
|
3077
|
+
}
|
|
3078
|
+
|
|
3079
|
+
const match = matchQueryClauseKeyword(source, index);
|
|
3080
|
+
if (match) {
|
|
3081
|
+
clauses.push({
|
|
3082
|
+
name: match.name,
|
|
3083
|
+
label: match.label,
|
|
3084
|
+
start: index,
|
|
3085
|
+
bodyStart: match.end,
|
|
3086
|
+
body: '',
|
|
3087
|
+
});
|
|
3088
|
+
index = match.end - 1;
|
|
3089
|
+
}
|
|
3090
|
+
}
|
|
3091
|
+
|
|
3092
|
+
for (let index = 0; index < clauses.length; index += 1) {
|
|
3093
|
+
const clause = clauses[index];
|
|
3094
|
+
const next = clauses[index + 1];
|
|
3095
|
+
const bodyEnd = next ? next.start : source.length;
|
|
3096
|
+
clause.body = source.slice(clause.bodyStart, bodyEnd);
|
|
3097
|
+
}
|
|
3098
|
+
return clauses;
|
|
3099
|
+
}
|
|
3100
|
+
|
|
3101
|
+
function matchQueryClauseKeyword(source, index) {
|
|
3102
|
+
if (!isQueryClauseBoundaryBefore(source, index)) return null;
|
|
3103
|
+
if (source.startsWith('order', index) && isQueryClauseBoundaryAfter(source, index + 'order'.length)) {
|
|
3104
|
+
let cursor = index + 'order'.length;
|
|
3105
|
+
const gapStart = cursor;
|
|
3106
|
+
while (isLayout(source[cursor] ?? '')) cursor += 1;
|
|
3107
|
+
if (cursor > gapStart && source.startsWith('by', cursor) && isQueryClauseBoundaryAfter(source, cursor + 2)) {
|
|
3108
|
+
return { name: 'order', label: 'order by', end: cursor + 2 };
|
|
3109
|
+
}
|
|
3110
|
+
}
|
|
3111
|
+
for (const name of ['from', 'where', 'offset', 'limit', 'select']) {
|
|
3112
|
+
if (source.startsWith(name, index) && isQueryClauseBoundaryAfter(source, index + name.length)) {
|
|
3113
|
+
return { name, label: name, end: index + name.length };
|
|
3114
|
+
}
|
|
3115
|
+
}
|
|
3116
|
+
return null;
|
|
3117
|
+
}
|
|
3118
|
+
|
|
3119
|
+
function exceedsUnsignedDecimal(raw, max) {
|
|
3120
|
+
const maxRaw = String(max);
|
|
3121
|
+
return raw.length > maxRaw.length || (raw.length === maxRaw.length && raw > maxRaw);
|
|
3122
|
+
}
|
|
3123
|
+
|
|
3124
|
+
function normalizeMaxPositionIndex(value) {
|
|
3125
|
+
if (value === undefined) return SANSA_MAX_POSITION_INDEX;
|
|
3126
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
|
|
3127
|
+
return SANSA_MAX_POSITION_INDEX;
|
|
3128
|
+
}
|
|
3129
|
+
return value;
|
|
3130
|
+
}
|
|
3131
|
+
|
|
3132
|
+
function isQueryClauseBoundaryBefore(source, index) {
|
|
3133
|
+
if (index === 0) return true;
|
|
3134
|
+
return isLayout(source[index - 1]);
|
|
3135
|
+
}
|
|
3136
|
+
|
|
3137
|
+
function isQueryClauseBoundaryAfter(source, index) {
|
|
3138
|
+
const char = source[index] ?? '';
|
|
3139
|
+
return char === '' || isLayout(char);
|
|
3140
|
+
}
|
|
3141
|
+
|
|
3142
|
+
function normalizeQueryExpression(source) {
|
|
3143
|
+
let output = '';
|
|
3144
|
+
let quote = null;
|
|
3145
|
+
let pendingSpace = false;
|
|
3146
|
+
for (let index = 0; index < source.length; index += 1) {
|
|
3147
|
+
const char = source[index];
|
|
3148
|
+
if (quote) {
|
|
3149
|
+
output += char;
|
|
3150
|
+
if (char === '\\') {
|
|
3151
|
+
index += 1;
|
|
3152
|
+
output += source[index] ?? '';
|
|
3153
|
+
} else if (char === quote) {
|
|
3154
|
+
quote = null;
|
|
3155
|
+
}
|
|
3156
|
+
continue;
|
|
3157
|
+
}
|
|
3158
|
+
if (char === '"' || char === "'") {
|
|
3159
|
+
if (pendingSpace && output.length > 0) output += ' ';
|
|
3160
|
+
pendingSpace = false;
|
|
3161
|
+
quote = char;
|
|
3162
|
+
output += char;
|
|
3163
|
+
continue;
|
|
3164
|
+
}
|
|
3165
|
+
if (isLayout(char)) {
|
|
3166
|
+
pendingSpace = output.length > 0;
|
|
3167
|
+
continue;
|
|
3168
|
+
}
|
|
3169
|
+
if (pendingSpace && output.length > 0) output += ' ';
|
|
3170
|
+
pendingSpace = false;
|
|
3171
|
+
output += char;
|
|
3172
|
+
}
|
|
3173
|
+
return output.trim();
|
|
3174
|
+
}
|
|
3175
|
+
|
|
3176
|
+
function isQueryCurrentPositionalShorthand(source) {
|
|
3177
|
+
return source.startsWith('.[') && source[2] !== '"';
|
|
3178
|
+
}
|
|
3179
|
+
|
|
3180
|
+
function splitTopLevelQueryList(source) {
|
|
3181
|
+
const parts = [];
|
|
3182
|
+
let quote = null;
|
|
3183
|
+
let parenDepth = 0;
|
|
3184
|
+
let bracketDepth = 0;
|
|
3185
|
+
let braceDepth = 0;
|
|
3186
|
+
let start = 0;
|
|
3187
|
+
for (let index = 0; index < source.length; index += 1) {
|
|
3188
|
+
const char = source[index];
|
|
3189
|
+
if (quote) {
|
|
3190
|
+
if (char === '\\') index += 1;
|
|
3191
|
+
else if (char === quote) quote = null;
|
|
3192
|
+
continue;
|
|
3193
|
+
}
|
|
3194
|
+
if (char === '"' || char === "'") {
|
|
3195
|
+
quote = char;
|
|
3196
|
+
continue;
|
|
3197
|
+
}
|
|
3198
|
+
if (char === '(') parenDepth += 1;
|
|
3199
|
+
else if (char === ')' && parenDepth > 0) parenDepth -= 1;
|
|
3200
|
+
else if (char === '[') bracketDepth += 1;
|
|
3201
|
+
else if (char === ']' && bracketDepth > 0) bracketDepth -= 1;
|
|
3202
|
+
else if (char === '{') braceDepth += 1;
|
|
3203
|
+
else if (char === '}' && braceDepth > 0) braceDepth -= 1;
|
|
3204
|
+
else if (char === ',' && parenDepth === 0 && bracketDepth === 0 && braceDepth === 0) {
|
|
3205
|
+
parts.push(source.slice(start, index));
|
|
3206
|
+
start = index + 1;
|
|
3207
|
+
}
|
|
3208
|
+
}
|
|
3209
|
+
parts.push(source.slice(start));
|
|
3210
|
+
return parts;
|
|
3211
|
+
}
|
|
3212
|
+
|
|
3213
|
+
function splitProjectionFields(source) {
|
|
3214
|
+
const fields = [];
|
|
3215
|
+
let cursor = 0;
|
|
3216
|
+
while (cursor < source.length) {
|
|
3217
|
+
while (isLayout(source[cursor] ?? '')) cursor += 1;
|
|
3218
|
+
if (cursor >= source.length) break;
|
|
3219
|
+
const nameStart = cursor;
|
|
3220
|
+
if (!isIdentifierStart(source[cursor] ?? '')) {
|
|
3221
|
+
throw new SansaParseError('Expected projection field name', cursor, 'SANSA_QUERY_INVALID_PROJECTION');
|
|
3222
|
+
}
|
|
3223
|
+
cursor += 1;
|
|
3224
|
+
while (isIdentifierContinue(source[cursor] ?? '')) cursor += 1;
|
|
3225
|
+
const name = source.slice(nameStart, cursor);
|
|
3226
|
+
while (isLayout(source[cursor] ?? '')) cursor += 1;
|
|
3227
|
+
if (source[cursor] !== '=') {
|
|
3228
|
+
throw new SansaParseError("Expected '=' after projection field name", cursor, 'SANSA_QUERY_INVALID_PROJECTION');
|
|
3229
|
+
}
|
|
3230
|
+
cursor += 1;
|
|
3231
|
+
const expressionStart = cursor;
|
|
3232
|
+
const nextField = findNextProjectionField(source, cursor);
|
|
3233
|
+
const expressionEnd = nextField < 0 ? source.length : nextField;
|
|
3234
|
+
const expression = source.slice(expressionStart, expressionEnd).trim();
|
|
3235
|
+
if (expression.length === 0) {
|
|
3236
|
+
throw new SansaParseError('Expected projection field expression', expressionStart, 'SANSA_QUERY_INVALID_PROJECTION');
|
|
3237
|
+
}
|
|
3238
|
+
fields.push({ name, expression });
|
|
3239
|
+
cursor = expressionEnd;
|
|
3240
|
+
}
|
|
3241
|
+
return fields;
|
|
3242
|
+
}
|
|
3243
|
+
|
|
3244
|
+
function findNextProjectionField(source, start) {
|
|
3245
|
+
let quote = null;
|
|
3246
|
+
let parenDepth = 0;
|
|
3247
|
+
let bracketDepth = 0;
|
|
3248
|
+
let braceDepth = 0;
|
|
3249
|
+
for (let index = start; index < source.length; index += 1) {
|
|
3250
|
+
const char = source[index];
|
|
3251
|
+
if (quote) {
|
|
3252
|
+
if (char === '\\') index += 1;
|
|
3253
|
+
else if (char === quote) quote = null;
|
|
3254
|
+
continue;
|
|
3255
|
+
}
|
|
3256
|
+
if (char === '"') {
|
|
3257
|
+
quote = char;
|
|
3258
|
+
continue;
|
|
3259
|
+
}
|
|
3260
|
+
if (char === '(') parenDepth += 1;
|
|
3261
|
+
else if (char === ')' && parenDepth > 0) parenDepth -= 1;
|
|
3262
|
+
else if (char === '[') bracketDepth += 1;
|
|
3263
|
+
else if (char === ']' && bracketDepth > 0) bracketDepth -= 1;
|
|
3264
|
+
else if (char === '{') braceDepth += 1;
|
|
3265
|
+
else if (char === '}' && braceDepth > 0) braceDepth -= 1;
|
|
3266
|
+
|
|
3267
|
+
if (parenDepth !== 0 || bracketDepth !== 0 || braceDepth !== 0 || !isLayout(char)) {
|
|
3268
|
+
continue;
|
|
3269
|
+
}
|
|
3270
|
+
|
|
3271
|
+
let cursor = index;
|
|
3272
|
+
while (isLayout(source[cursor] ?? '')) cursor += 1;
|
|
3273
|
+
if (!isIdentifierStart(source[cursor] ?? '')) continue;
|
|
3274
|
+
cursor += 1;
|
|
3275
|
+
while (isIdentifierContinue(source[cursor] ?? '')) cursor += 1;
|
|
3276
|
+
const afterName = cursor;
|
|
3277
|
+
while (isLayout(source[cursor] ?? '')) cursor += 1;
|
|
3278
|
+
if (source[cursor] === '=' && source[cursor + 1] !== '=') {
|
|
3279
|
+
return index;
|
|
3280
|
+
}
|
|
3281
|
+
index = afterName - 1;
|
|
3282
|
+
}
|
|
3283
|
+
return -1;
|
|
3284
|
+
}
|
|
3285
|
+
|
|
3286
|
+
function isComparisonStart(char) {
|
|
3287
|
+
return char === '=' || char === '!' || char === '<' || char === '>';
|
|
3288
|
+
}
|
|
3289
|
+
|
|
3290
|
+
function isExactSelector(selector) {
|
|
3291
|
+
return ['member', 'position', 'attributeSpace', 'localSpace'].includes(selector.type);
|
|
3292
|
+
}
|
|
3293
|
+
|
|
3294
|
+
function isIdentifierStart(char) {
|
|
3295
|
+
return /^[A-Za-z_]$/.test(char ?? '');
|
|
3296
|
+
}
|
|
3297
|
+
|
|
3298
|
+
function isIdentifierContinue(char) {
|
|
3299
|
+
return /^[A-Za-z0-9_]$/.test(char ?? '');
|
|
3300
|
+
}
|
|
3301
|
+
|
|
3302
|
+
function isDigit(char) {
|
|
3303
|
+
return /^[0-9]$/.test(char ?? '');
|
|
3304
|
+
}
|
|
3305
|
+
|
|
3306
|
+
function isLayout(char) {
|
|
3307
|
+
return char === ' ' || char === '\t' || char === '\n' || char === '\r';
|
|
3308
|
+
}
|
|
3309
|
+
|
|
3310
|
+
function isQualifierArgumentChar(char) {
|
|
3311
|
+
return /^[A-Za-z0-9!#$%&*+\-.:;=?@^_|~<>]$/.test(char ?? '');
|
|
3312
|
+
}
|
|
3313
|
+
|
|
3314
|
+
function datatypeBaseName(datatype) {
|
|
3315
|
+
const genericCut = datatype.indexOf('<');
|
|
3316
|
+
const argumentCut = datatype.indexOf('[');
|
|
3317
|
+
const cut = [genericCut, argumentCut].filter((index) => index >= 0).sort((a, b) => a - b)[0];
|
|
3318
|
+
return (cut === undefined ? datatype : datatype.slice(0, cut)).trim();
|
|
3319
|
+
}
|
|
3320
|
+
|
|
3321
|
+
function lowerFirst(value) {
|
|
3322
|
+
return `${value.charAt(0).toLowerCase()}${value.slice(1)}`;
|
|
3323
|
+
}
|
|
3324
|
+
|
|
3325
|
+
function globPatternToRegExp(pattern) {
|
|
3326
|
+
let source = '^';
|
|
3327
|
+
const chars = Array.from(pattern);
|
|
3328
|
+
for (let index = 0; index < chars.length; index += 1) {
|
|
3329
|
+
const char = chars[index];
|
|
3330
|
+
if (char === '\\' && ['*', '?', '\\'].includes(chars[index + 1])) {
|
|
3331
|
+
source += escapeRegExp(chars[index + 1]);
|
|
3332
|
+
index += 1;
|
|
3333
|
+
continue;
|
|
3334
|
+
}
|
|
3335
|
+
if (char === '*') {
|
|
3336
|
+
source += '.*';
|
|
3337
|
+
} else if (char === '?') {
|
|
3338
|
+
source += '.';
|
|
3339
|
+
} else {
|
|
3340
|
+
source += escapeRegExp(char);
|
|
3341
|
+
}
|
|
3342
|
+
}
|
|
3343
|
+
return new RegExp(`${source}$`, 'u');
|
|
3344
|
+
}
|
|
3345
|
+
|
|
3346
|
+
function escapeRegExp(value) {
|
|
3347
|
+
return value.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&');
|
|
3348
|
+
}
|
|
3349
|
+
|
|
3350
|
+
function codePointToString(codePoint, index) {
|
|
3351
|
+
if (codePoint > 0x10FFFF || (codePoint >= 0xD800 && codePoint <= 0xDFFF)) {
|
|
3352
|
+
throw new SansaParseError('Unicode escape must decode to a scalar value', index, 'SANSA_INVALID_UNICODE_SCALAR');
|
|
3353
|
+
}
|
|
3354
|
+
return String.fromCodePoint(codePoint);
|
|
3355
|
+
}
|
|
3356
|
+
|
|
3357
|
+
function quotePayload(value) {
|
|
3358
|
+
let output = '"';
|
|
3359
|
+
for (const char of value) {
|
|
3360
|
+
switch (char) {
|
|
3361
|
+
case '\\':
|
|
3362
|
+
output += '\\\\';
|
|
3363
|
+
break;
|
|
3364
|
+
case '"':
|
|
3365
|
+
output += '\\"';
|
|
3366
|
+
break;
|
|
3367
|
+
case '\n':
|
|
3368
|
+
output += '\\n';
|
|
3369
|
+
break;
|
|
3370
|
+
case '\r':
|
|
3371
|
+
output += '\\r';
|
|
3372
|
+
break;
|
|
3373
|
+
case '\t':
|
|
3374
|
+
output += '\\t';
|
|
3375
|
+
break;
|
|
3376
|
+
case '\b':
|
|
3377
|
+
output += '\\b';
|
|
3378
|
+
break;
|
|
3379
|
+
case '\f':
|
|
3380
|
+
output += '\\f';
|
|
3381
|
+
break;
|
|
3382
|
+
default:
|
|
3383
|
+
output += char;
|
|
3384
|
+
break;
|
|
3385
|
+
}
|
|
3386
|
+
}
|
|
3387
|
+
output += '"';
|
|
3388
|
+
return output;
|
|
3389
|
+
}
|