lambdajson-js 2.0.0 → 3.0.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
@@ -22,4 +22,15 @@ lint({ $str: ['\\ needless escape'] }); // => [{ severity: 'warning', code: 'nee
22
22
  ```
23
23
 
24
24
  `compile` throws a `LambdaJSONError` (with `code` and a JSON Pointer `path`) for a malformed program.
25
- See the language documentation for the full reference and the migration notes from 1.x.
25
+ Problems found while a program runs throw a `LambdaJSONRuntimeError` (also with `code` and `path`).
26
+ See the language documentation for the full reference and the migration notes.
27
+
28
+ ## Changes in 3.0
29
+
30
+ * **Breaking:** arithmetic (`$sum`, `$subtract`, `$multiply`, `$divide`) and ordering (`$lt`, `$lte`, `$gt`, `$gte`)
31
+ throw `LambdaJSONRuntimeError` (`missing-operand`) on a `null` or `undefined` operand instead of passing it on.
32
+ * **Breaking:** `$eq` and `$neq` compare deeply, by value.
33
+ * Functions with named parameters: `{ "$let": { "$f": { "$fn": { "as": ["a", "b"], "body": … } } }, "$f": [1, 2] }`;
34
+ `#` in the body stays the caller's input.
35
+ * New primitives: `$round`, `$min`, `$max`, `$count`, `$find`, `$unique`, `$pick`, `$omit`, `$lower`, `$upper`, `$trim`, `$isNil`.
36
+ * `signatureOf(name)` returns the declared types of a primitive; `typed(primitive, { takes, returns })` declares them for custom ones.
package/package.json CHANGED
@@ -1,13 +1,12 @@
1
1
  {
2
2
  "name": "lambdajson-js",
3
- "version": "2.0.0",
3
+ "version": "3.0.0",
4
4
  "description": "LambdaJSON to JavaScript function compiler",
5
5
  "type": "module",
6
6
  "main": "./src/js-compiler.js",
7
7
  "module": "./src/js-compiler.js",
8
8
  "files": [
9
9
  "src",
10
- "src/README.md",
11
10
  "LICENSE"
12
11
  ],
13
12
  "exports": {
@@ -34,7 +33,8 @@
34
33
  "license": "MIT",
35
34
  "author": "Benjamin Batistic",
36
35
  "scripts": {
37
- "test": "mocha"
36
+ "test": "mocha",
37
+ "prepublishOnly": "npm test"
38
38
  },
39
39
  "dependencies": {
40
40
  "fast-printf": "^1.6.10",
@@ -46,5 +46,11 @@
46
46
  "esbuild": "^0.27.0",
47
47
  "globals": "^16.5.0",
48
48
  "mocha": "^11.7.5"
49
+ },
50
+ "engines": {
51
+ "node": ">=18"
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
49
55
  }
50
56
  }
@@ -1,12 +1,13 @@
1
- import { get, isArray, isPlainObject, isString, map, mapValues } from 'lodash-es'
2
- import { primitives } from './primitives.js';
1
+ import { get, isArray, isPlainObject, isString, map, mapValues, zipObject } from 'lodash-es'
2
+ import { primitives, LambdaJSONRuntimeError } from './primitives.js';
3
3
 
4
4
  export {
5
5
  compile,
6
6
  lint,
7
+ signatureOf,
7
8
  LambdaJSONError
8
9
  }
9
- export { primitives, named, special, call } from './primitives.js';
10
+ export { primitives, named, special, call, typed, LambdaJSONRuntimeError } from './primitives.js';
10
11
 
11
12
  /**
12
13
  * A problem in the structure of a program, found while compiling it.
@@ -22,6 +23,7 @@ class LambdaJSONError extends Error {
22
23
  }
23
24
 
24
25
  const LET = '$let';
26
+ const FN = '$fn';
25
27
  const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_-]*$/;
26
28
 
27
29
  /**
@@ -55,6 +57,15 @@ function lint(program, extendedPrimitives = {}) {
55
57
  return problems;
56
58
  }
57
59
 
60
+ /**
61
+ * The declared types of a primitive: `{ takes, returns }`, or undefined when it declares none.
62
+ * @param {string} name
63
+ * @param {object} extendedPrimitives
64
+ */
65
+ function signatureOf(name, extendedPrimitives = {}) {
66
+ return ({ ...primitives, ...extendedPrimitives })[name]?.signature;
67
+ }
68
+
58
69
  function compileProgram(program, extendedPrimitives, warn) {
59
70
  const scope = {
60
71
  primitives: { ...primitives, ...extendedPrimitives },
@@ -204,7 +215,7 @@ function parseAs(value, path) {
204
215
 
205
216
  function compileFunctionCall(scope, key, value, path) {
206
217
  const arg = compileTree(scope, value, path);
207
- return ({ vars, input }) => vars[key]({ vars, input: arg({ vars, input }) });
218
+ return ({ vars, input }) => vars[key]({ vars, input: arg({ vars, input }), outer: input });
208
219
  }
209
220
 
210
221
  function compileArray(scope, tree, path) {
@@ -212,8 +223,34 @@ function compileArray(scope, tree, path) {
212
223
  return x => map(funks, f => f(x));
213
224
  }
214
225
 
226
+ /**
227
+ * `{ "$fn": { "as": names, "body": expression } }` declares a function with named parameters.
228
+ * The call's argument is bound to the name, or its items to the names of an array; `#` in the
229
+ * body stays the input of the caller.
230
+ */
231
+ function compileFunction(scope, tree, path) {
232
+ const fnPath = pointer(path, FN);
233
+ const spec = tree[FN];
234
+ if (!isPlainObject(spec) || Object.keys(spec).some(k => k !== 'as' && k !== 'body') || !('as' in spec) || !('body' in spec)) {
235
+ fail('invalid-function', fnPath, `'${FN}' is an object { as, body }`);
236
+ }
237
+ const names = parseAs(spec.as, pointer(fnPath, 'as'));
238
+ const body = compileTree(scope, spec.body, pointer(fnPath, 'body'));
239
+ return ({ vars, input, outer }) => {
240
+ const args = isArray(spec.as) ? input : [input];
241
+ if (args.length !== names.length) {
242
+ throw new LambdaJSONRuntimeError('wrong-argument-count', fnPath, `the function takes ${names.length} argument(s), got ${args.length}`);
243
+ }
244
+ return body({ vars: { ...vars, ...zipObject(names, args) }, input: outer });
245
+ };
246
+ }
247
+
248
+ const isFunctionDeclaration = tree => isPlainObject(tree) && Object.keys(tree).length === 1 && FN in tree;
249
+
215
250
  function compileVars(scope, obj, path) {
216
- const funks = mapValues(obj, (n, k) => compileTree(scope, n, pointer(path, k)));
251
+ const funks = mapValues(obj, (n, k) => k.startsWith('$') && isFunctionDeclaration(n)
252
+ ? compileFunction(scope, n, pointer(path, k))
253
+ : compileTree(scope, n, pointer(path, k)));
217
254
  return ({ vars, input }) => {
218
255
  const localVars = {};
219
256
  const extendedVars = { ...vars };
package/src/primitives.js CHANGED
@@ -1,6 +1,19 @@
1
1
  import { printf } from 'fast-printf';
2
- import { concat, divide, eq, every, filter, first, get, groupBy, gt, gte, includes, isArray, join, keyBy, keys, lt, lte, map, mapValues, merge, multiply,
3
- orderBy, reduce, some, split, subtract, sum, tail, take, takeWhile, values, zipObject, zipWith } from 'lodash-es'
2
+ import { concat, divide, every, filter, find, first, get, groupBy, gt, gte, includes, isArray, isEqual, isNil, join, keyBy, keys, lt, lte, map, mapValues, max, merge, min, multiply,
3
+ omit, orderBy, pick, reduce, round, some, split, subtract, sum, tail, take, takeWhile, uniqWith, values, zipObject, zipWith } from 'lodash-es'
4
+
5
+ /**
6
+ * A problem found while a program runs, e.g. an operand that is missing.
7
+ * `path` is a JSON Pointer to the offending node of the program, `code` a stable identifier.
8
+ */
9
+ export class LambdaJSONRuntimeError extends Error {
10
+ constructor(code, path, message) {
11
+ super(`${message} (at ${path || '/'})`);
12
+ this.name = 'LambdaJSONRuntimeError';
13
+ this.code = code;
14
+ this.path = path;
15
+ }
16
+ }
4
17
 
5
18
  /**
6
19
  * Primitives come in three shapes:
@@ -44,10 +57,27 @@ const variadic = (name, empty, decides) => special((args, { compile }) => {
44
57
  };
45
58
  }, { description: `${name}: [a, b, …], short-circuits` });
46
59
 
60
+ /**
61
+ * Arithmetic and ordering need values: an operand that is null or undefined (typically a path
62
+ * missing in the input) fails with the path of the call instead of flowing on silently.
63
+ */
64
+ const strict = (name, impl) => special((args, { compile, path }) => {
65
+ const f = compile(args);
66
+ return x => {
67
+ const operands = f(x);
68
+ const missing = isArray(operands) ? operands.findIndex(isNil) : isNil(operands) ? 0 : -1;
69
+ if (missing >= 0) {
70
+ throw new LambdaJSONRuntimeError('missing-operand', path,
71
+ `${name} got ${operands?.[missing] === null ? 'null' : 'undefined'} as ${isArray(operands) ? `operand ${missing}` : 'its operand'}; a path in the input is probably missing`);
72
+ }
73
+ return impl(operands);
74
+ };
75
+ });
76
+
47
77
  const sort = direction => named(['by?', 'collection=#', 'as?'], ({ by, collection, as }) => x =>
48
78
  orderBy(collection(x), by ? [v => call(by, as, x, [v])] : undefined, [direction]));
49
79
 
50
- export const primitives = {
80
+ const primitiveTable = {
51
81
  $let: true,
52
82
  $literal: special(value => () => value),
53
83
  $: f => x => v => f({ ...x, input: v }),
@@ -78,17 +108,17 @@ export const primitives = {
78
108
  $not: f => x => !f(x),
79
109
  $negate: f => x => !f(x),
80
110
 
81
- $eq: f => x => eq(...f(x)),
82
- $neq: f => x => !eq(...f(x)),
83
- $lt: f => x => lt(...f(x)),
84
- $lte: f => x => lte(...f(x)),
85
- $gt: f => x => gt(...f(x)),
86
- $gte: f => x => gte(...f(x)),
111
+ $eq: f => x => isEqual(...f(x)),
112
+ $neq: f => x => !isEqual(...f(x)),
113
+ $lt: strict('$lt', v => lt(...v)),
114
+ $lte: strict('$lte', v => lte(...v)),
115
+ $gt: strict('$gt', v => gt(...v)),
116
+ $gte: strict('$gte', v => gte(...v)),
87
117
 
88
- $sum: f => x => sum(f(x)),
89
- $subtract: f => x => subtract(...f(x)),
90
- $multiply: f => x => multiply(...f(x)),
91
- $divide: f => x => divide(...f(x)),
118
+ $sum: strict('$sum', v => sum(v)),
119
+ $subtract: strict('$subtract', v => subtract(...v)),
120
+ $multiply: strict('$multiply', v => multiply(...v)),
121
+ $divide: strict('$divide', v => divide(...v)),
92
122
 
93
123
  $map: named(['fn', 'over=#', 'as?'], ({ fn, over, as }) => x => map(over(x), lambda(fn, as, x))),
94
124
  $mapValues: named(['fn', 'of=#', 'as?'], ({ fn, of, as }) => x => mapValues(of(x), lambda(fn, as, x))),
@@ -136,6 +166,82 @@ export const primitives = {
136
166
  return string(x).replace(p, substitute(x));
137
167
  }),
138
168
  $printf: named(['template', 'args=#'], ({ template, args }) => x => printf(template(x), ...args(x))),
169
+ $round: named(['value=#', 'digits?'], ({ value, digits }) => x => round(value(x), digits?.(x))),
170
+ $min: f => x => min(f(x)),
171
+ $max: f => x => max(f(x)),
172
+ $count: named(['predicate?', 'collection=#', 'as?'], ({ predicate, collection, as }) => x =>
173
+ predicate ? filter(collection(x), lambda(predicate, as, x)).length : collection(x).length),
174
+ $find: named(['predicate', 'collection=#', 'as?'], ({ predicate, collection, as }) => x => find(collection(x), lambda(predicate, as, x))),
175
+ $unique: f => x => uniqWith(f(x), isEqual),
176
+ $pick: named(['keys', 'object=#'], ({ keys, object }) => x => pick(object(x), keys(x))),
177
+ $omit: named(['keys', 'object=#'], ({ keys, object }) => x => omit(object(x), keys(x))),
178
+ $lower: f => x => toStr(f(x)).toLowerCase(),
179
+ $upper: f => x => toStr(f(x)).toUpperCase(),
180
+ $trim: f => x => toStr(f(x)).trim(),
181
+ $isNil: f => x => isNil(f(x)),
139
182
  $parseInt: f => x => { const n = parseInt(f(x), 10); return isNaN(n) ? undefined : n; },
140
183
  $parseFloat: f => x => { const n = parseFloat(f(x)); return isNaN(n) ? undefined : n; },
141
184
  }
185
+
186
+ /**
187
+ * Types of the primitives, so that tools can infer what a program takes and returns.
188
+ * `takes` is the type of the expression argument, or an object of parameter types for
189
+ * named parameters; `returns` the type of the result. Types: `any`, `number`, `string`,
190
+ * `boolean`, `object`, `function` (a lambda), `names` (the `as` parameter), `array` or `array<T>`.
191
+ * A custom primitive declares its own with `typed`.
192
+ */
193
+ export const typed = (primitive, signature) => typeof primitive === 'function'
194
+ ? Object.assign(primitive, { signature })
195
+ : { ...primitive, signature };
196
+
197
+ const sig = (takes, returns) => ({ takes, returns });
198
+ const over = (fn, collection, returns, extra = {}) => sig({ [fn]: 'function', [collection]: collection === 'of' ? 'object' : 'array', ...extra, as: 'names' }, returns);
199
+ const numbers = 'array<number>';
200
+
201
+ const signatures = {
202
+ $literal: sig('any', 'any'), $: sig('any', 'function'), $in: sig('any', 'any'), $return: sig('any', 'any'),
203
+ $apply: sig({ fn: 'function', to: 'any', as: 'names' }, 'any'),
204
+ $pipeline: sig('array<function>', 'any'),
205
+ $if: sig('array', 'any'), $cond: sig('array', 'any'), $and: sig('array', 'any'), $or: sig('array', 'any'),
206
+ $not: sig('any', 'boolean'), $negate: sig('any', 'boolean'),
207
+ $eq: sig('array', 'boolean'), $neq: sig('array', 'boolean'),
208
+ $lt: sig(numbers, 'boolean'), $lte: sig(numbers, 'boolean'), $gt: sig(numbers, 'boolean'), $gte: sig(numbers, 'boolean'),
209
+ $sum: sig(numbers, 'number'), $subtract: sig(numbers, 'number'), $multiply: sig(numbers, 'number'), $divide: sig(numbers, 'number'),
210
+ $map: over('fn', 'over', 'array'),
211
+ $mapValues: over('fn', 'of', 'object'),
212
+ $filter: over('predicate', 'collection', 'array'),
213
+ $any: over('predicate', 'collection', 'boolean'),
214
+ $all: over('predicate', 'collection', 'boolean'),
215
+ $group: over('by', 'collection', 'object'),
216
+ $toDictionary: over('by', 'collection', 'object'),
217
+ $ascending: over('by', 'collection', 'array'),
218
+ $descending: over('by', 'collection', 'array'),
219
+ $take: sig({ while: 'function', count: 'number', from: 'array', as: 'names' }, 'array'),
220
+ $zip: sig({ with: 'function', sequences: 'array<array>', as: 'names' }, 'array'),
221
+ $fold: sig({ with: 'function', init: 'any', collection: 'array', as: 'names' }, 'any'),
222
+ $head: sig('array', 'any'), $tail: sig('array', 'array'), $concat: sig('array<array>', 'array'),
223
+ $keys: sig('object', 'array<string>'), $values: sig('object', 'array'), $merge: sig('array<object>', 'object'),
224
+ $coalesce: sig('array', 'any'),
225
+ $get: sig({ object: 'object', path: 'string' }, 'any'),
226
+ $includes: sig({ collection: 'array', value: 'any' }, 'boolean'),
227
+ $str: sig('any', 'string'),
228
+ $join: sig({ separator: 'string', strings: 'array' }, 'string'),
229
+ $split: sig({ separator: 'string', string: 'string' }, 'array<string>'),
230
+ $match: sig({ pattern: 'string', string: 'string' }, 'array'),
231
+ $isMatch: sig({ pattern: 'string', string: 'string' }, 'boolean'),
232
+ $replace: sig({ regex: 'string', substitute: 'string', string: 'string', global: 'boolean' }, 'string'),
233
+ $printf: sig({ template: 'string', args: 'array' }, 'string'),
234
+ $round: sig({ value: 'number', digits: 'number' }, 'number'),
235
+ $min: sig(numbers, 'number'), $max: sig(numbers, 'number'),
236
+ $count: over('predicate', 'collection', 'number'),
237
+ $find: over('predicate', 'collection', 'any'),
238
+ $unique: sig('array', 'array'),
239
+ $pick: sig({ keys: 'array<string>', object: 'object' }, 'object'),
240
+ $omit: sig({ keys: 'array<string>', object: 'object' }, 'object'),
241
+ $lower: sig('string', 'string'), $upper: sig('string', 'string'), $trim: sig('string', 'string'),
242
+ $isNil: sig('any', 'boolean'),
243
+ $parseInt: sig('string', 'number'), $parseFloat: sig('string', 'number'),
244
+ };
245
+
246
+ export const primitives = Object.fromEntries(Object.entries(primitiveTable).map(([name, primitive]) =>
247
+ [name, signatures[name] ? typed(primitive, signatures[name]) : primitive]));