lambdajson-js 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -25,6 +25,18 @@ lint({ $str: ['\\ needless escape'] }); // => [{ severity: 'warning', code: 'nee
25
25
  Problems found while a program runs throw a `LambdaJSONRuntimeError` (also with `code` and `path`).
26
26
  See the language documentation for the full reference and the migration notes.
27
27
 
28
+ ## Type inference
29
+
30
+ `infer(program, { input, vars, primitives })` returns `{ type, problems }`: the JSON Schema type of the result
31
+ and the errors and warnings (impossible paths, possibly missing operands, mismatched arguments, impossible
32
+ comparisons, unbound variables) found from the type of the input, without running the program.
33
+ See the language documentation.
34
+
35
+ ## Changes in 3.1
36
+
37
+ * `infer(program, { input, vars, primitives })`: type inference with errors and warnings before a program runs.
38
+ * `typed(primitive, signature, infer?)` accepts JSON Schema types as well as notation.
39
+
28
40
  ## Changes in 3.0
29
41
 
30
42
  * **Breaking:** arithmetic (`$sum`, `$subtract`, `$multiply`, `$divide`) and ordering (`$lt`, `$lte`, `$gt`, `$gte`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lambdajson-js",
3
- "version": "3.0.0",
3
+ "version": "3.1.0",
4
4
  "description": "LambdaJSON to JavaScript function compiler",
5
5
  "type": "module",
6
6
  "main": "./src/js-compiler.js",
package/src/infer.js ADDED
@@ -0,0 +1,420 @@
1
+ import { isArray, isEqual, isPlainObject, isString, mapValues, toPath } from 'lodash-es';
2
+ import { primitives as builtins } from './primitives.js';
3
+ import { lint } from './js-compiler.js';
4
+ import {
5
+ ANY, ARRAY, BOOLEAN, FUNCTION, NULL, NUMBER, OBJECT, STRING,
6
+ arrayOf, describe, disjoint, isAny, isNullable, itemOf, literalType, members, nonNull, normalize,
7
+ nullable, objectOf, orAny, toType, tuple, union, valueOf, walkPath
8
+ } from './types.js';
9
+
10
+ const LET = '$let';
11
+ const pointer = (path, ...keys) => keys.reduce((p, key) => `${p}/${String(key).replace(/~/g, '~0').replace(/\//g, '~1')}`, path);
12
+ const NUMBER_OR_STRING = union(NUMBER, STRING);
13
+ const isTuple = t => t.type === 'array' && t.items === false && t.prefixItems !== undefined;
14
+
15
+ /**
16
+ * Infers the type of the result of a program from the type of its input, and reports the
17
+ * problems that are certain (errors) or possible (warnings) before it runs.
18
+ * @param {any} program
19
+ * @param {{ input?: object, vars?: object, primitives?: object }} options types as JSON Schema
20
+ * @returns {{ type: object, problems: { severity: 'error' | 'warning', code: string, path: string, message: string }[] }}
21
+ */
22
+ export function infer(program, { input = {}, vars = {}, primitives: extended = {} } = {}) {
23
+ const problems = lint(program, extended);
24
+ if (problems.some(p => p.severity === 'error')) return { type: ANY, problems };
25
+ const seen = new Set(problems.map(p => JSON.stringify(p)));
26
+ const report = (severity, code, path, message) => {
27
+ const problem = { severity, code, path, message };
28
+ const key = JSON.stringify(problem);
29
+ if (!seen.has(key)) {
30
+ seen.add(key);
31
+ problems.push(problem);
32
+ }
33
+ };
34
+ const engine = createEngine({ ...builtins, ...extended }, report);
35
+ const env = { input: toType(input), vars: mapValues(vars, toType), funcs: new Map() };
36
+ return { type: engine.tree(env, program, ''), problems };
37
+ }
38
+
39
+ function createEngine(prims, report) {
40
+ const active = new Set();
41
+
42
+ const error = (code, path, message) => report('error', code, path, message);
43
+ const warning = (code, path, message) => report('warning', code, path, message);
44
+
45
+ function tree(env, node, path) {
46
+ if (isString(node)) return string(env, node, path);
47
+ if (isArray(node)) return tuple(node.map((n, i) => tree(env, n, pointer(path, i))));
48
+ if (isPlainObject(node)) {
49
+ return Object.keys(node).some(k => k.startsWith('$')) ? call(env, node, path) : object(env, node, path);
50
+ }
51
+ return literalType(node);
52
+ }
53
+
54
+ function object(env, node, path) {
55
+ const properties = {};
56
+ for (const key of Object.keys(node)) {
57
+ properties[key.startsWith('\\') ? key.slice(1) : key] = tree(env, node[key], pointer(path, key));
58
+ }
59
+ return { type: 'object', properties, required: Object.keys(properties), additionalProperties: false };
60
+ }
61
+
62
+ function string(env, node, path) {
63
+ if (node.startsWith('\\')) return literalType(node.slice(1));
64
+ if (node === '#') return env.input;
65
+ const fail = message => error('unknown-path', path, message);
66
+ if (node.startsWith('#')) {
67
+ let p = node.slice(1);
68
+ p = /^\d/.test(p) ? `[${p[0]}]` + p.slice(1) : p;
69
+ p = p.startsWith('.') ? p.slice(1) : p;
70
+ return walkPath(env.input, toPath(p), fail);
71
+ }
72
+ if (node.startsWith('@')) {
73
+ const [name, ...rest] = toPath(node.slice(1));
74
+ if (name === undefined || !Object.prototype.hasOwnProperty.call(env.vars, name)) {
75
+ error('unknown-variable', path, `'${name ?? ''}' is not bound by an enclosing '${LET}' or 'as'`);
76
+ return ANY;
77
+ }
78
+ return walkPath(env.vars[name], rest, fail);
79
+ }
80
+ return literalType(node);
81
+ }
82
+
83
+ function call(env, node, path) {
84
+ const keys = Object.keys(node);
85
+ const key = keys.find(k => k !== LET);
86
+ if (!keys.includes(LET)) return head(env, key, node[key], path);
87
+
88
+ const letPath = pointer(path, LET);
89
+ const declarations = node[LET];
90
+ const funcs = new Map(env.funcs);
91
+ const inner = { ...env, funcs, vars: { ...env.vars } };
92
+ for (const name of Object.keys(declarations)) {
93
+ if (name.startsWith('$')) funcs.set(name, { tree: declarations[name], path: pointer(letPath, name), funcs });
94
+ }
95
+ for (const name of Object.keys(declarations)) {
96
+ if (!name.startsWith('$')) inner.vars[name] = tree(inner, declarations[name], pointer(letPath, name));
97
+ }
98
+ return head(inner, key, node[key], path);
99
+ }
100
+
101
+ function head(env, key, value, path) {
102
+ const argPath = pointer(path, key);
103
+ const prim = prims[key];
104
+ return prim !== undefined ? primitive(env, key, prim, value, argPath) : functionCall(env, key, value, argPath);
105
+ }
106
+
107
+ function functionCall(env, key, value, path) {
108
+ const arg = tree(env, value, path);
109
+ const decl = env.funcs.get(key);
110
+ if (!decl || active.has(decl)) return ANY;
111
+ active.add(decl);
112
+ try {
113
+ const fn = isPlainObject(decl.tree) && Object.keys(decl.tree).length === 1 ? decl.tree.$fn : undefined;
114
+ if (fn === undefined) return tree({ input: arg, vars: env.vars, funcs: decl.funcs }, decl.tree, decl.path);
115
+ const vars = { ...env.vars, ...bindParameters(fn.as, arg, path) };
116
+ return tree({ input: env.input, vars, funcs: decl.funcs }, fn.body, pointer(decl.path, '$fn', 'body'));
117
+ } finally {
118
+ active.delete(decl);
119
+ }
120
+ }
121
+
122
+ function bindParameters(as, arg, path) {
123
+ if (!isArray(as)) return { [as]: arg };
124
+ if (disjoint(arg, ARRAY)) {
125
+ error('type-mismatch', path, `the function takes ${as.length} arguments as an array, got ${describe(arg)}`);
126
+ return Object.fromEntries(as.map(name => [name, ANY]));
127
+ }
128
+ const argument = nonNull(arg);
129
+ if (isTuple(argument)) {
130
+ if (argument.prefixItems.length !== as.length) {
131
+ error('wrong-argument-count', path, `the function takes ${as.length} arguments, got ${argument.prefixItems.length}`);
132
+ return Object.fromEntries(as.map(name => [name, ANY]));
133
+ }
134
+ return Object.fromEntries(as.map((name, i) => [name, argument.prefixItems[i]]));
135
+ }
136
+ const item = itemOf(argument);
137
+ return Object.fromEntries(as.map(name => [name, item]));
138
+ }
139
+
140
+ function primitive(env, key, prim, value, path) {
141
+ const builtin = prim === builtins[key];
142
+ if (builtin && FORMS[key]) return FORMS[key](env, value, path);
143
+ if (prim.params) return named(env, key, prim, value, path, builtin);
144
+ if (typeof prim !== 'function') return returnsOf(prim.signature, ANY);
145
+ return positional(env, key, prim, value, path, builtin);
146
+ }
147
+
148
+ const returnsOf = (signature, argument) => {
149
+ if (signature === undefined) return ANY;
150
+ if (signature.infer) return normalize(signature.infer(argument, {}));
151
+ return signature.returns === undefined ? ANY : toType(signature.returns);
152
+ };
153
+
154
+ function positional(env, key, prim, value, path, builtin) {
155
+ const arg = tree(env, value, path);
156
+ const signature = prim.signature;
157
+ if (signature?.takes !== undefined) checkTakes(toType(signature.takes), arg, value, path);
158
+ if (builtin && RESULTS[key]) return RESULTS[key](arg, path);
159
+ return returnsOf(signature, arg);
160
+ }
161
+
162
+ /** The operands of an argument that is an array: [{ type, path }]. */
163
+ function operands(value, arg, path) {
164
+ const array = nonNull(arg);
165
+ if (array.prefixItems) {
166
+ const list = array.prefixItems.map((type, i) => ({ type, path: isArray(value) ? pointer(path, i) : path }));
167
+ return array.items === false ? list : [...list, { type: array.items ?? ANY, path }];
168
+ }
169
+ return [{ type: itemOf(array), path }];
170
+ }
171
+
172
+ function check(expected, actual, path, what) {
173
+ if (disjoint(actual, expected)) {
174
+ error('type-mismatch', path, `${what} is ${describe(actual)}, expected ${describe(expected)}`);
175
+ }
176
+ }
177
+
178
+ function checkTakes(expected, arg, value, path) {
179
+ if (expected.type === 'array' && expected.items && expected.items !== false) {
180
+ check(ARRAY, arg, path, 'the argument');
181
+ if (disjoint(arg, ARRAY)) return;
182
+ for (const operand of operands(value, arg, path)) check(expected.items, operand.type, operand.path, 'an item');
183
+ } else {
184
+ check(expected, arg, path, 'the argument');
185
+ }
186
+ }
187
+
188
+ function named(env, key, prim, value, path, builtin) {
189
+ const signature = prim.signature;
190
+ const takes = isPlainObject(signature?.takes) ? signature.takes : {};
191
+ const rule = builtin ? NAMED[key] : undefined;
192
+ const types = {};
193
+ const lambdas = {};
194
+ for (const [k, v] of Object.entries(value)) {
195
+ const argPath = pointer(path, k);
196
+ if (k === 'as') continue;
197
+ if (takes[k] === 'function') {
198
+ lambdas[k] = [v, argPath];
199
+ continue;
200
+ }
201
+ types[k] = tree(env, v, argPath);
202
+ if (takes[k] !== undefined) check(toType(takes[k]), types[k], argPath, `'${k}'`);
203
+ }
204
+ for (const spec of prim.params) {
205
+ const name = spec.replace(/(=#|\?)$/, '');
206
+ if (spec.endsWith('=#') && !(name in types) && !(name in lambdas)) {
207
+ types[name] = env.input;
208
+ if (takes[name] !== undefined) check(toType(takes[name]), env.input, path, `the input`);
209
+ }
210
+ }
211
+ const as = value.as === undefined ? undefined : isArray(value.as) ? value.as : [value.as];
212
+ const bodies = {};
213
+ for (const k of Object.keys(lambdas)) {
214
+ const run = (args, input) => lambda(env, lambdas[k], as, args, input);
215
+ bodies[k] = rule?.fns?.[k] ? rule.fns[k](types, run) : run([], ANY);
216
+ }
217
+ if (rule?.result) return rule.result(types, bodies, path);
218
+ return returnsOf(signature, types);
219
+ }
220
+
221
+ function lambda(env, [node, path], as, args, input = args[0] ?? ANY) {
222
+ const scope = as === undefined
223
+ ? { ...env, input }
224
+ : { ...env, vars: { ...env.vars, ...Object.fromEntries(as.map((name, i) => [name, args[i] ?? ANY])) } };
225
+ return tree(scope, node, path);
226
+ }
227
+
228
+ /** Arithmetic and ordering fail at run time on a missing operand. */
229
+ const strict = accepted => (env, value, path) => {
230
+ const arg = tree(env, value, path);
231
+ if (disjoint(arg, ARRAY)) {
232
+ error('type-mismatch', path, `the argument is ${describe(arg)}, expected an array of operands`);
233
+ } else {
234
+ if (isNullable(arg)) warning('possibly-missing-operand', path, 'the operands may be missing');
235
+ for (const operand of operands(value, arg, path)) {
236
+ if (disjoint(operand.type, accepted)) {
237
+ error('type-mismatch', operand.path, `an operand is ${describe(operand.type)}, expected ${describe(accepted)}`);
238
+ } else if (isNullable(operand.type)) {
239
+ warning('possibly-missing-operand', operand.path, `an operand may be missing: ${describe(operand.type)}`);
240
+ }
241
+ }
242
+ }
243
+ };
244
+ const arithmetic = strict(NUMBER);
245
+ const ordering = strict(NUMBER_OR_STRING);
246
+
247
+ const truthyConst = t => 'const' in t && !!t.const;
248
+ const args = (env, value, path) => value.map((v, i) => tree(env, v, pointer(path, i)));
249
+
250
+ const FORMS = {
251
+ $literal: (env, value) => literalType(value),
252
+ $: (env, value, path) => {
253
+ tree({ ...env, input: ANY }, value, path);
254
+ return FUNCTION;
255
+ },
256
+ $if: (env, value, path) => {
257
+ const [, then, otherwise] = args(env, value, path);
258
+ return otherwise ? union(then, otherwise) : nullable(then);
259
+ },
260
+ $cond: (env, value, path) => {
261
+ const results = value.map((clause, i) => [tree(env, clause[0], pointer(path, i, 0)), tree(env, clause[1], pointer(path, i, 1))]);
262
+ const last = results[results.length - 1];
263
+ const total = last && !isAny(last[0]) && members(last[0]).every(truthyConst);
264
+ return orAny(union(...results.map(r => r[1]), ...(total ? [] : [NULL])));
265
+ },
266
+ $and: (env, value, path) => logic(env, value, path, true),
267
+ $or: (env, value, path) => logic(env, value, path, false),
268
+ };
269
+ for (const key of ['$sum', '$subtract', '$multiply', '$divide']) {
270
+ FORMS[key] = (env, value, path) => { arithmetic(env, value, path); return NUMBER; };
271
+ }
272
+ for (const key of ['$lt', '$lte', '$gt', '$gte']) {
273
+ FORMS[key] = (env, value, path) => { ordering(env, value, path); return BOOLEAN; };
274
+ }
275
+
276
+ function logic(env, value, path, empty) {
277
+ const types = isArray(value) ? args(env, value, path) : [itemOf(tree(env, value, path))];
278
+ return orAny(union(...types, ...(types.length === 0 ? [literalType(empty)] : [])));
279
+ }
280
+
281
+ const mergeObjects = types => {
282
+ const objects = types.map(nonNull);
283
+ if (!objects.every(t => t.type === 'object')) return OBJECT;
284
+ const properties = {};
285
+ const required = new Set();
286
+ let closed = true;
287
+ for (const t of objects) {
288
+ for (const [k, p] of Object.entries(t.properties ?? {})) {
289
+ const previous = properties[k];
290
+ properties[k] = previous && nonNull(previous).type === 'object' && nonNull(p).type === 'object' ? mergeObjects([previous, p]) : p;
291
+ }
292
+ (t.required ?? []).forEach(k => required.add(k));
293
+ closed = closed && t.additionalProperties === false;
294
+ }
295
+ return { type: 'object', properties, required: [...required], ...(closed ? { additionalProperties: false } : {}) };
296
+ };
297
+
298
+ const literalKeys = t => {
299
+ const list = nonNull(t);
300
+ return isTuple(list) && list.prefixItems.every(m => typeof m.const === 'string') ? list.prefixItems.map(m => m.const) : null;
301
+ };
302
+
303
+ const restrict = (object, keep) => {
304
+ const o = nonNull(object);
305
+ if (o.type !== 'object') return OBJECT;
306
+ const result = { ...o };
307
+ if (o.properties) result.properties = Object.fromEntries(Object.entries(o.properties).filter(([k]) => keep(k)));
308
+ if (o.required) result.required = o.required.filter(keep);
309
+ return result;
310
+ };
311
+
312
+ const RESULTS = {
313
+ $in: a => a,
314
+ $return: a => a,
315
+ $eq: (a, path) => compared(a, path),
316
+ $neq: (a, path) => compared(a, path),
317
+ $head: a => {
318
+ const list = nonNull(a);
319
+ if (list.prefixItems?.length > 0) return list.prefixItems[0];
320
+ return isTuple(list) ? NULL : nullable(itemOf(list));
321
+ },
322
+ $tail: a => arrayOf(itemOf(a)),
323
+ $unique: a => arrayOf(itemOf(a)),
324
+ $concat: a => arrayOf(orAny(union(...operands(undefined, a, '').map(o => itemOf(o.type))))),
325
+ $keys: a => {
326
+ const o = nonNull(a);
327
+ const keys = o.type === 'object' && o.additionalProperties === false ? Object.keys(o.properties ?? {}) : null;
328
+ return arrayOf(keys && keys.length > 0 ? { type: 'string', enum: keys } : STRING);
329
+ },
330
+ $values: a => arrayOf(valueOf(a)),
331
+ $merge: a => mergeObjects(operands(undefined, a, '').map(o => o.type)),
332
+ $coalesce: a => {
333
+ const list = nonNull(a);
334
+ if (!isTuple(list)) return nullable(itemOf(list));
335
+ const result = [];
336
+ for (const type of list.prefixItems) {
337
+ result.push(nonNull(type));
338
+ if (!isNullable(type)) return orAny(union(...result));
339
+ }
340
+ return orAny(union(...result, NULL));
341
+ },
342
+ $match: () => nullable(arrayOf(STRING)),
343
+ $parseInt: () => nullable(NUMBER),
344
+ $parseFloat: () => nullable(NUMBER),
345
+ };
346
+
347
+ function compared(a, path) {
348
+ const list = nonNull(a);
349
+ if (list.prefixItems?.length >= 2 && disjoint(list.prefixItems[0], list.prefixItems[1])) {
350
+ warning('impossible-comparison', path, `${describe(list.prefixItems[0])} and ${describe(list.prefixItems[1])} are never equal`);
351
+ }
352
+ return BOOLEAN;
353
+ }
354
+
355
+ const over = (collection, fn, result, argsOf = item => [item, NUMBER]) => ({
356
+ fns: { [fn]: (t, run) => run(argsOf(itemOf(t[collection]))) },
357
+ result: (t, b) => result(b, itemOf(t[collection])),
358
+ });
359
+ const sequenceItems = sequences => {
360
+ const list = nonNull(sequences);
361
+ return isTuple(list) && list.prefixItems.length === 2
362
+ ? list.prefixItems.map(itemOf)
363
+ : [itemOf(itemOf(list)), itemOf(itemOf(list))];
364
+ };
365
+
366
+ const NAMED = {
367
+ $map: over('over', 'fn', b => arrayOf(b.fn)),
368
+ $filter: over('collection', 'predicate', (b, item) => arrayOf(item)),
369
+ $any: over('collection', 'predicate', () => BOOLEAN),
370
+ $all: over('collection', 'predicate', () => BOOLEAN),
371
+ $find: over('collection', 'predicate', (b, item) => nullable(item)),
372
+ $count: over('collection', 'predicate', () => NUMBER),
373
+ $group: over('collection', 'by', (b, item) => objectOf(arrayOf(item)), item => [item]),
374
+ $toDictionary: over('collection', 'by', (b, item) => objectOf(item), item => [item]),
375
+ $ascending: over('collection', 'by', (b, item) => arrayOf(item), item => [item]),
376
+ $descending: over('collection', 'by', (b, item) => arrayOf(item), item => [item]),
377
+ $take: over('from', 'while', (b, item) => arrayOf(item), item => [item]),
378
+ $mapValues: {
379
+ fns: { fn: (t, run) => run([valueOf(t.of), STRING]) },
380
+ result: (t, b) => objectOf(b.fn),
381
+ },
382
+ $apply: {
383
+ fns: { fn: (t, run) => run([t.to]) },
384
+ result: (t, b) => b.fn,
385
+ },
386
+ $zip: {
387
+ fns: { with: (t, run) => { const pair = sequenceItems(t.sequences); return run(pair, tuple(pair)); } },
388
+ result: (t, b) => arrayOf('with' in b ? b.with : tuple(sequenceItems(t.sequences))),
389
+ },
390
+ $fold: {
391
+ fns: {
392
+ with: (t, run) => {
393
+ const item = itemOf(t.collection);
394
+ let accumulator = t.init ?? item;
395
+ for (let pass = 0; pass < 2; pass++) {
396
+ const next = union(accumulator, run([accumulator, item], tuple([accumulator, item])));
397
+ if (isEqual(next, accumulator)) break;
398
+ accumulator = next;
399
+ }
400
+ return accumulator;
401
+ }
402
+ },
403
+ result: (t, b) => b.with,
404
+ },
405
+ $get: {
406
+ result: (t, b, path) => {
407
+ const literal = t.path && 'const' in t.path && typeof t.path.const === 'string';
408
+ return literal ? walkPath(t.object, toPath(t.path.const), message => error('unknown-path', pointer(path, 'path'), message)) : ANY;
409
+ },
410
+ },
411
+ $pick: {
412
+ result: t => { const keys = literalKeys(t.keys); return keys ? restrict(t.object, k => keys.includes(k)) : OBJECT; },
413
+ },
414
+ $omit: {
415
+ result: t => { const keys = literalKeys(t.keys); return keys ? restrict(t.object, k => !keys.includes(k)) : nonNull(t.object).type === 'object' ? nonNull(t.object) : OBJECT; },
416
+ },
417
+ };
418
+
419
+ return { tree };
420
+ }
@@ -8,6 +8,7 @@ export {
8
8
  LambdaJSONError
9
9
  }
10
10
  export { primitives, named, special, call, typed, LambdaJSONRuntimeError } from './primitives.js';
11
+ export { infer } from './infer.js';
11
12
 
12
13
  /**
13
14
  * A problem in the structure of a program, found while compiling it.
package/src/primitives.js CHANGED
@@ -188,11 +188,14 @@ const primitiveTable = {
188
188
  * `takes` is the type of the expression argument, or an object of parameter types for
189
189
  * named parameters; `returns` the type of the result. Types: `any`, `number`, `string`,
190
190
  * `boolean`, `object`, `function` (a lambda), `names` (the `as` parameter), `array` or `array<T>`.
191
- * A custom primitive declares its own with `typed`.
191
+ * A type (JSON Schema) is accepted wherever a notation is. A custom primitive declares its own with
192
+ * `typed(primitive, signature, infer?)`; `infer(argumentTypes, context)` computes the result type from the
193
+ * type of the argument (an object of parameter types for named parameters).
192
194
  */
193
- export const typed = (primitive, signature) => typeof primitive === 'function'
194
- ? Object.assign(primitive, { signature })
195
- : { ...primitive, signature };
195
+ export const typed = (primitive, signature, infer) => {
196
+ const declared = infer ? { ...signature, infer } : signature;
197
+ return typeof primitive === 'function' ? Object.assign(primitive, { signature: declared }) : { ...primitive, signature: declared };
198
+ };
196
199
 
197
200
  const sig = (takes, returns) => ({ takes, returns });
198
201
  const over = (fn, collection, returns, extra = {}) => sig({ [fn]: 'function', [collection]: collection === 'of' ? 'object' : 'array', ...extra, as: 'names' }, returns);
package/src/types.js ADDED
@@ -0,0 +1,293 @@
1
+ import { isArray, isEqual, isPlainObject, isString, mapValues } from 'lodash-es';
2
+
3
+ /**
4
+ * Types are JSON Schema objects restricted to: `type`, `const`, `enum`, `items`, `prefixItems`,
5
+ * `properties`, `required`, `additionalProperties` and `anyOf`, plus the non-standard
6
+ * `{ type: 'function' }`. `{}` is any value; a missing value is `{ type: 'null' }`.
7
+ */
8
+ export const ANY = {};
9
+ export const NULL = { type: 'null' };
10
+ export const NUMBER = { type: 'number' };
11
+ export const STRING = { type: 'string' };
12
+ export const BOOLEAN = { type: 'boolean' };
13
+ export const FUNCTION = { type: 'function' };
14
+ export const ARRAY = { type: 'array' };
15
+ export const OBJECT = { type: 'object' };
16
+ export const NEVER = { enum: [] };
17
+
18
+ export const arrayOf = items => ({ type: 'array', items });
19
+ export const objectOf = additionalProperties => ({ type: 'object', additionalProperties });
20
+ export const tuple = prefixItems => ({ type: 'array', prefixItems, items: false });
21
+
22
+ export const isAny = t => Object.keys(t).length === 0;
23
+ export const members = t => t.anyOf ?? [t];
24
+ const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
25
+
26
+ /**
27
+ * Reduces a JSON Schema (or a signature notation, see `toType`) to the supported subset.
28
+ */
29
+ export function normalize(t) {
30
+ if (t === false) return NEVER;
31
+ if (!isPlainObject(t)) return ANY;
32
+ if (isArray(t.anyOf)) return union(...t.anyOf.map(normalize));
33
+ if (isArray(t.type)) return union(...t.type.map(type => normalize({ ...t, type })));
34
+ const out = {};
35
+ if (isString(t.type)) out.type = t.type === 'integer' ? 'number' : t.type;
36
+ if ('const' in t) out.const = t.const;
37
+ if (isArray(t.enum)) out.enum = t.enum;
38
+ if (t.items !== undefined) out.items = t.items === false ? false : normalize(t.items);
39
+ if (isArray(t.prefixItems)) out.prefixItems = t.prefixItems.map(normalize);
40
+ if (isPlainObject(t.properties)) out.properties = mapValues(t.properties, normalize);
41
+ if (isArray(t.required)) out.required = t.required;
42
+ if (t.additionalProperties === false) out.additionalProperties = false;
43
+ else if (isPlainObject(t.additionalProperties)) out.additionalProperties = normalize(t.additionalProperties);
44
+ return out;
45
+ }
46
+
47
+ /**
48
+ * Notation of a signature: `any`, `number`, `string`, `boolean`, `object`, `array`, `array<T>`,
49
+ * `function`; anything else that is an object is a type.
50
+ */
51
+ export function toType(notation) {
52
+ if (isString(notation)) {
53
+ const generic = /^array<(.+)>$/.exec(notation);
54
+ if (generic) return arrayOf(toType(generic[1]));
55
+ return { number: NUMBER, string: STRING, boolean: BOOLEAN, object: OBJECT, array: ARRAY, function: FUNCTION }[notation] ?? ANY;
56
+ }
57
+ return normalize(notation);
58
+ }
59
+
60
+ export function literalType(value) {
61
+ if (value === null) return { type: 'null', const: null };
62
+ if (isArray(value)) return tuple(value.map(literalType));
63
+ if (isPlainObject(value)) {
64
+ return { type: 'object', properties: mapValues(value, literalType), required: Object.keys(value), additionalProperties: false };
65
+ }
66
+ return { type: typeof value, const: value };
67
+ }
68
+
69
+ const valuesOf = m => 'const' in m ? [m.const] : m.enum ?? null;
70
+
71
+ const kindOfValue = v => v === null ? 'null' : isArray(v) ? 'array' : typeof v;
72
+
73
+ function kindsOf(m) {
74
+ if (m.type !== undefined) return [m.type];
75
+ const values = valuesOf(m);
76
+ return values === null ? null : [...new Set(values.map(kindOfValue))];
77
+ }
78
+
79
+ export function valueMatches(v, t) {
80
+ return members(t).some(m => matchOne(v, m));
81
+ }
82
+
83
+ function matchOne(v, m) {
84
+ if (isAny(m)) return true;
85
+ if (m.type !== undefined && m.type !== kindOfValue(v)) return false;
86
+ const values = valuesOf(m);
87
+ if (values && !values.some(x => isEqual(x, v))) return false;
88
+ if (isArray(v)) {
89
+ return v.every((item, i) => {
90
+ const target = m.prefixItems?.[i] ?? (m.items === false ? null : m.items);
91
+ return target === null ? false : target === undefined || valueMatches(item, target);
92
+ });
93
+ }
94
+ if (isPlainObject(v)) {
95
+ if ((m.required ?? []).some(k => !own(v, k))) return false;
96
+ return Object.entries(v).every(([k, item]) => {
97
+ const target = own(m.properties ?? {}, k) ? m.properties[k] : m.additionalProperties;
98
+ return target === false ? false : target === undefined || valueMatches(item, target);
99
+ });
100
+ }
101
+ return true;
102
+ }
103
+
104
+ /** Every value of `s` is a value of `t`; conservative: false when it can't be shown. */
105
+ export function assignable(s, t) {
106
+ return members(s).every(a => members(t).some(b => assignableOne(a, b)));
107
+ }
108
+
109
+ function assignableOne(a, b) {
110
+ if (isAny(b)) return true;
111
+ if (isAny(a)) return false;
112
+ const values = valuesOf(a);
113
+ if (values) return values.every(v => matchOne(v, b));
114
+ if (a.type === undefined || a.type !== b.type || valuesOf(b)) return false;
115
+ if (a.type === 'array') return arrayAssignable(a, b);
116
+ if (a.type === 'object') return objectAssignable(a, b);
117
+ return true;
118
+ }
119
+
120
+ function arrayAssignable(a, b) {
121
+ const aPrefix = a.prefixItems ?? [];
122
+ const bPrefix = b.prefixItems ?? [];
123
+ for (let i = 0; i < aPrefix.length; i++) {
124
+ const target = bPrefix[i] ?? (b.items === false ? null : b.items ?? ANY);
125
+ if (!target || !assignable(aPrefix[i], target)) return false;
126
+ }
127
+ if (a.items === false) return true;
128
+ if (b.items === false) return false;
129
+ const rest = a.items ?? ANY;
130
+ return assignable(rest, b.items ?? ANY) && bPrefix.slice(aPrefix.length).every(t => assignable(rest, t));
131
+ }
132
+
133
+ function objectAssignable(a, b) {
134
+ const aProps = a.properties ?? {};
135
+ const bProps = b.properties ?? {};
136
+ const aRequired = a.required ?? [];
137
+ for (const [k, target] of Object.entries(bProps)) {
138
+ if (own(aProps, k)) {
139
+ if (!assignable(aProps[k], target)) return false;
140
+ } else if ((b.required ?? []).includes(k) || (a.additionalProperties !== false && !assignable(a.additionalProperties ?? ANY, target))) {
141
+ return false;
142
+ }
143
+ }
144
+ if ((b.required ?? []).some(k => !aRequired.includes(k))) return false;
145
+ const extra = Object.keys(aProps).filter(k => !own(bProps, k));
146
+ if (b.additionalProperties === false) return a.additionalProperties === false && extra.length === 0;
147
+ if (b.additionalProperties !== undefined) {
148
+ return (a.additionalProperties === false || assignable(a.additionalProperties ?? ANY, b.additionalProperties))
149
+ && extra.every(k => assignable(aProps[k], b.additionalProperties));
150
+ }
151
+ return true;
152
+ }
153
+
154
+ /** No value is both `s` and `t`. */
155
+ export function disjoint(s, t) {
156
+ return members(s).every(a => members(t).every(b => disjointOne(a, b)));
157
+ }
158
+
159
+ function disjointOne(a, b) {
160
+ if (isAny(a) || isAny(b)) return false;
161
+ const ka = kindsOf(a);
162
+ const kb = kindsOf(b);
163
+ if (ka && kb && !ka.some(k => kb.includes(k))) return true;
164
+ const va = valuesOf(a);
165
+ const vb = valuesOf(b);
166
+ if (va && vb) return !va.some(x => vb.some(y => isEqual(x, y)));
167
+ if (va) return !va.some(v => matchOne(v, b));
168
+ if (vb) return !vb.some(v => matchOne(v, a));
169
+ return false;
170
+ }
171
+
172
+ /** The union of types, normalized: flat, without duplicates or members assignable to another. */
173
+ export function union(...types) {
174
+ const result = [];
175
+ for (const t of types) {
176
+ if (isAny(t)) return ANY;
177
+ for (const m of members(t)) {
178
+ if (result.some(r => assignableOne(m, r))) continue;
179
+ for (let i = result.length - 1; i >= 0; i--) {
180
+ if (assignableOne(result[i], m)) result.splice(i, 1);
181
+ }
182
+ result.push(m);
183
+ }
184
+ }
185
+ if (result.length === 0) return NEVER;
186
+ return result.length === 1 ? result[0] : { anyOf: result };
187
+ }
188
+
189
+ export const orAny = t => isEqual(t, NEVER) ? ANY : t;
190
+
191
+ export function isNullable(t) {
192
+ return !isAny(t) && members(t).some(m => kindsOf(m)?.includes('null'));
193
+ }
194
+
195
+ export function nonNull(t) {
196
+ return union(...members(t).map(m => {
197
+ if (m.enum) return { enum: m.enum.filter(v => v !== null) };
198
+ return kindsOf(m)?.length === 1 && kindsOf(m)[0] === 'null' ? NEVER : m;
199
+ }));
200
+ }
201
+
202
+ export const nullable = t => union(t, NULL);
203
+
204
+ /** The type of an element of an array type. */
205
+ export function itemOf(t) {
206
+ const items = members(nonNull(t)).map(m => {
207
+ if (m.type !== 'array') return ANY;
208
+ if (m.prefixItems === undefined && m.items === undefined) return ANY;
209
+ return union(...(m.prefixItems ?? []), ...(m.items === false ? [] : [m.items ?? ANY]));
210
+ });
211
+ return orAny(union(...items));
212
+ }
213
+
214
+ /** The type of a value of an object type. */
215
+ export function valueOf(t) {
216
+ const values = members(nonNull(t)).map(m => {
217
+ if (m.type !== 'object') return ANY;
218
+ const add = m.additionalProperties;
219
+ return union(...Object.values(m.properties ?? {}), ...(add === false ? [] : [add ?? ANY]));
220
+ });
221
+ return orAny(union(...values));
222
+ }
223
+
224
+ const expand = m => {
225
+ if (m.type !== undefined) return [m];
226
+ if ('const' in m) return [literalType(m.const)];
227
+ return m.enum ? m.enum.map(literalType) : [m];
228
+ };
229
+
230
+ const describeKeys = props => Object.keys(props).join(', ') || 'none';
231
+
232
+ function walkMember(m, k) {
233
+ if (isAny(m)) return { type: ANY };
234
+ const numeric = /^\d+$/.test(k);
235
+ switch (m.type) {
236
+ case 'object': {
237
+ const props = m.properties ?? {};
238
+ if (own(props, k)) return { type: (m.required ?? []).includes(k) ? props[k] : nullable(props[k]) };
239
+ if (m.additionalProperties === false) {
240
+ return { error: `'${k}' is not a property of the object (declared: ${describeKeys(props)})` };
241
+ }
242
+ return { type: nullable(m.additionalProperties ?? ANY) };
243
+ }
244
+ case 'array': {
245
+ if (numeric) {
246
+ const prefix = m.prefixItems ?? [];
247
+ if (Number(k) < prefix.length) return { type: prefix[Number(k)] };
248
+ if (m.items === false) return { error: `index ${k} is beyond the tuple of ${prefix.length}` };
249
+ return { type: nullable(m.items ?? ANY) };
250
+ }
251
+ return k === 'length' ? { type: NUMBER } : { error: `an array has no '${k}'` };
252
+ }
253
+ case 'string':
254
+ if (k === 'length') return { type: NUMBER };
255
+ return numeric ? { type: nullable(STRING) } : { error: `a string has no '${k}'` };
256
+ default:
257
+ return { error: `a ${m.type} has no '${k}'` };
258
+ }
259
+ }
260
+
261
+ /** Walks one segment: `{ type }`, or `{ error }` when the segment can't exist. */
262
+ export function walkSegment(t, k) {
263
+ const results = members(t).flatMap(expand).map(m => kindsOf(m)?.[0] === 'null' && kindsOf(m).length === 1
264
+ ? { type: NULL, isNull: true }
265
+ : walkMember(m, k));
266
+ const real = results.filter(r => !r.isNull);
267
+ if (real.length > 0 && real.every(r => r.error)) return { error: real[0].error };
268
+ return { type: union(...results.filter(r => !r.error).map(r => r.type)) };
269
+ }
270
+
271
+ /** Walks a path; calls `fail(message)` at the first impossible segment and continues with null. */
272
+ export function walkPath(t, segments, fail) {
273
+ let current = t;
274
+ for (const segment of segments) {
275
+ const step = walkSegment(current, segment);
276
+ if (step.error) {
277
+ fail(step.error);
278
+ return NULL;
279
+ }
280
+ current = step.type;
281
+ }
282
+ return current;
283
+ }
284
+
285
+ export function describe(t) {
286
+ if (isAny(t)) return 'any';
287
+ return members(t).map(m => {
288
+ if ('const' in m) return JSON.stringify(m.const);
289
+ if (m.enum) return m.enum.map(v => JSON.stringify(v)).join(' | ') || 'never';
290
+ if (m.type === 'array' && m.items && m.items !== false) return `array<${describe(m.items)}>`;
291
+ return m.type ?? 'any';
292
+ }).join(' | ');
293
+ }