trilean 1.8.0 → 1.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/README.md +8 -6
- package/dist/builtin-functions.cjs +19 -2
- package/dist/builtin-functions.d.cts +2 -2
- package/dist/builtin-functions.d.ts +2 -2
- package/dist/builtin-functions.js +19 -2
- package/dist/complex.cjs +4 -2
- package/dist/complex.d.cts +4 -2
- package/dist/complex.d.ts +4 -2
- package/dist/complex.js +4 -2
- package/dist/evaluate-document.cjs +10 -4
- package/dist/evaluate-document.d.cts +7 -3
- package/dist/evaluate-document.d.ts +7 -3
- package/dist/evaluate-document.js +10 -4
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/input-resolvers.cjs +55 -8
- package/dist/input-resolvers.d.cts +8 -3
- package/dist/input-resolvers.d.ts +8 -3
- package/dist/input-resolvers.js +55 -8
- package/dist-cli/trilean.mjs +126 -23
- package/package.json +1 -1
- package/schemas/trilean.schema.json +1 -1
package/README.md
CHANGED
|
@@ -175,15 +175,17 @@ The package ships a `trilean` command that evaluates a tree stored as JSON, for
|
|
|
175
175
|
npx trilean evaluate formula.json --inputs inputs.json
|
|
176
176
|
```
|
|
177
177
|
|
|
178
|
-
`formula.json` is a predicate tree or an expression tree (`-` reads it from standard input; the tree and `--inputs` cannot both be `-`). The root's `kind` says which; only a root `treeReference`, valid in both, needs `--as predicate` or `--as expression`. `inputs.json` is an object of named values, one per `reference` key: a plain number, string or boolean, or a complete computed value when the input needs a unit, for example `{ "kind": "number", "value": 2, "unit": { "m": 1 } }`. Units are dimensional-exponent maps and are never converted, exactly as in the library. Numbers must be finite (`1e999` parses to infinity and is refused), a field a computed value does not define is dropped, and a repeated key in the JSON, like a repeated `--inputs` flag, takes the last value.
|
|
178
|
+
`formula.json` is a predicate tree or an expression tree (`-` reads it from standard input; the tree and `--inputs` cannot both be `-`). The root's `kind` says which; only a root `treeReference`, valid in both, needs `--as predicate` or `--as expression`. `inputs.json` is an object of named values, one per `reference` key: a plain number, string or boolean, or a complete computed value when the input needs a unit or is not a real number, for example `{ "kind": "number", "value": 2, "unit": { "m": 1 } }` or the complex value `{ "kind": "complex", "re": 1, "im": 2 }`. An entry that is an array is a list of items instead: each element is an object of named values (each by the same rules), and a `fold`, `some` or `every` whose `collection` is that entry's name takes its items from it, for example `{ "intervals": [{ "theta_h": 98, "hours": 24 }, { "theta_h": 110, "hours": 2 }] }`. Inside such a node a `reference` resolves against the current item alone, as it does in the library, so a value an item needs is written into the item rather than read from the top-level inputs, while a collection name is not scoped to an item (a `fold` nested inside another fold's item still finds the top-level lists); an empty list folds to its `initial` value. Units are dimensional-exponent maps and are never converted, exactly as in the library. Numbers must be finite (`1e999` parses to infinity and is refused), a field a computed value does not define is dropped, and a repeated key in the JSON, like a repeated `--inputs` flag, takes the last value.
|
|
179
179
|
|
|
180
|
-
The
|
|
180
|
+
The inputs are validated in full before anything is evaluated, every element of every list included, so a very long list is read and held in memory whatever else happens. Evaluation is bounded as well, by default: one evaluation visits at most a fixed number of nodes (the evaluator's default `maxNodes`), and a `fold` visits its combine expression once for every item, so a long list can exhaust it. When it does the result is indeterminate (`evaluation exceeded the maximum of N nodes`) and the exit status is `1`. `--max-nodes <n>` sets the limit instead, as a positive safe integer; any other value is rejected with exit `2`. A day of loss-of-life intervals at one-minute resolution is 1440 items and needs it raised. Raising the limit raises the worst-case work with it, and nested folds multiply that work (it can grow exponentially with the nesting), so the limit is also the guard against a hostile tree.
|
|
181
181
|
|
|
182
|
-
|
|
182
|
+
The result is printed as JSON in the `Evaluation` shape, a `definite` value or an `indeterminate` reason (see [The evaluation model](#the-evaluation-model)). The exit status separates the three outcomes a script cares about: `0` for a definite result, `1` for an indeterminate one, `2` when no result was printed (bad usage, an unreadable file, JSON that is malformed, a tree or an input that fails validation, a tree that folds or quantifies over a list the inputs do not hold, or a result JSON cannot carry, which the built-in registry never produces). Everything that is not a result goes to standard error, the usage text included unless `--help` asked for it, and problems with the tree or an input are one `path: message` line each. A reader of standard output that closes early (`| true`) does not change the exit status or print an error.
|
|
183
183
|
|
|
184
|
-
|
|
184
|
+
`call` nodes resolve against `builtinFunctions`, which the library also exports (frozen, so changing the export cannot change what the command resolves): `minimum` and `maximum` (one or more numbers sharing a unit), `absoluteValue`, `round` (halves away from zero, working on the decimal number as written, so `round(1.005, 2)` is `1.01`, with an optional count of decimal places, and a value too large to have a digit at that precision returned unchanged), `squareRoot`, `exponential`, and `logarithm` (natural, or to an optional base, exact for powers of 10 and 2), and the two projections of a complex value onto the reals: `magnitude` (the absolute value of a real number or the modulus of a complex one) and `phase` (the angle of a complex number in radians, in the range [-pi, pi]: a negative real number is +pi whatever the sign of its zero imaginary part, so a signed zero never gives -pi, though a tiny negative imaginary part can round to exactly -pi; zero is 0; a component that is not finite is a `domain-error`). Every function but those two takes real numbers only and refuses a complex value, `absoluteValue` included; `magnitude` takes a real or a complex number and `phase` a complex one. They follow the unit rules above: `minimum`, `maximum`, `absoluteValue`, `round` and `magnitude` keep the argument's unit, `phase` is dimensionless, `squareRoot` halves each dimension's exponent and refuses an odd one, and `exponential` and `logarithm` accept dimensionless numbers only. An argument a function cannot accept (the wrong kind or count, or mismatched units, as in `minimum(1 m, 2)`) is `wrong-type`; an argument of the right kind outside the function's domain, or a result that is not a finite number, is `domain-error`; and any other name is `wrong-type`.
|
|
185
185
|
|
|
186
|
-
The
|
|
186
|
+
The command has no table, delegate or tree store to hand a `lookup`, `delegate` or `treeReference` node. A `lookup` is `not-found` and a `delegate` or `treeReference` is `wrong-type`. A tree that folds or quantifies over a list the inputs do not hold exits `2` rather than treating the missing list as empty. That holds even when another operand would settle the answer: `and(false, some(...))` still exits `2`, because the synchronous evaluator asks for the collection before it combines the two. For trees that need a table, a delegate or a tree store, embed the library and supply the [resolvers](#resolvers) yourself.
|
|
187
|
+
|
|
188
|
+
The same evaluation is available in code as `evaluateDocument`, which takes the node budget as its `maxNodes` option (a positive integer the caller supplies; nothing checks it), with `parseInputs` and `createInputResolvers` for the named-value and list resolvers it uses. `createInputResolvers` takes the lists of items as its `collections` argument, and only items served by its own `resolveCollection` are scoped to an item: an embedder that composes resolvers, overriding `resolveCollection` to serve its own items while keeping its `resolveValue`, gets references inside a fold read from the top-level inputs, and scoping those items is the embedder's responsibility.
|
|
187
189
|
|
|
188
190
|
## Build, test, and lint
|
|
189
191
|
|
|
@@ -551,7 +553,7 @@ The magnitude-and-phase view stays reachable through four exported conversion he
|
|
|
551
553
|
|
|
552
554
|
**Comparison is kind-strict, deliberately unlike arithmetic.** `gt`/`gte`/`lt`/`lte` are `wrong-type` for a `complex` operand — the complex plane carries no total order — exactly as they already are for `text`. `eq`/`neq` work normally, as exact equality across both components under the same unit-compatibility rule numbers already have, and `memberOf` matches the same way. But a `complex` compared against a `number` is `wrong-type`, with no promotion: arithmetic *produces* a value, so promoting a real operand loses nothing, whereas a comparison *consumes* two, and this design already treats a kind difference between them as a modelling error worth surfacing — the same reason an `instant` is never compared against a plain `number` despite being a count of milliseconds underneath.
|
|
553
555
|
|
|
554
|
-
Ordering a complex quantity therefore goes through whichever real projection the formula actually means
|
|
556
|
+
Ordering a complex quantity therefore goes through whichever real projection the formula actually means, most often its magnitude. The evaluator ships no function set of its own (see [`call`](#call); the command line's `builtinFunctions` includes `magnitude` and `phase`), so an embedder's bridge is an ordinary registry entry, one line over the exported helper:
|
|
555
557
|
|
|
556
558
|
```ts
|
|
557
559
|
const functions: FunctionRegistry = {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_computed_value = require("./computed-value.cjs");
|
|
3
|
+
const require_complex = require("./complex.cjs");
|
|
3
4
|
//#region src/builtin-functions.ts
|
|
4
5
|
const DECIMAL_BASE = 10;
|
|
5
6
|
const BINARY_BASE = 2;
|
|
@@ -73,11 +74,11 @@ function roundHalfAwayFromZero(value, places) {
|
|
|
73
74
|
return rounded === 0 ? 0 : Math.sign(value) * rounded;
|
|
74
75
|
}
|
|
75
76
|
/**
|
|
76
|
-
* The numeric functions a `call` node can name when an embedder has no registry of its own: `minimum` and `maximum` (one or more numbers in a shared unit), `absoluteValue`, `round` (half away from zero, with an optional count of decimal places), `squareRoot`, `exponential`,
|
|
77
|
+
* The numeric functions a `call` node can name when an embedder has no registry of its own: `minimum` and `maximum` (one or more numbers in a shared unit), `absoluteValue`, `round` (half away from zero, with an optional count of decimal places), `squareRoot`, `exponential`, `logarithm` (natural, or to an optional base), and the two projections of a complex value onto the reals, `magnitude` and `phase`. Every function but those two takes real numbers only, and refuses a complex value; `magnitude` takes a real or a complex number, and `phase` a complex one.
|
|
77
78
|
*
|
|
78
79
|
* Failures split as the evaluator's own operators split. An argument a function cannot accept at all (the wrong kind, the wrong count, or units that do not fit) is a `wrongType`; an argument of the right kind outside the function's domain (a negative `squareRoot`, a `logarithm` of zero, a base of one, a fractional count of decimal places) or a result that is not a finite number is a `domainError`.
|
|
79
80
|
*
|
|
80
|
-
* Units follow the evaluator's rule that dimensions are never silently converted. `minimum`, `maximum`, `absoluteValue` and `
|
|
81
|
+
* Units follow the evaluator's rule that dimensions are never silently converted. `minimum`, `maximum`, `absoluteValue`, `round` and `magnitude` keep the argument's unit (and the first two require all arguments to share one); `phase` returns a dimensionless angle in radians in the range [-pi, pi], whatever unit its argument carries, with a negative real number +pi whatever the sign of its zero imaginary part (a signed zero never gives -pi, though a tiny negative imaginary part can round to it) and zero 0 (a component that is not finite is a `domainError`); `squareRoot` halves each dimension's exponent and refuses a unit whose exponents are not all even; `exponential` and `logarithm` accept only dimensionless numbers and return one.
|
|
81
82
|
*
|
|
82
83
|
* Frozen, so mutating the export cannot change what `evaluateDocument` resolves.
|
|
83
84
|
*/
|
|
@@ -123,6 +124,22 @@ const builtinFunctions = Object.freeze({
|
|
|
123
124
|
if (baseNumber === DECIMAL_BASE) return finiteNumber("logarithm", Math.log10(value.value));
|
|
124
125
|
if (baseNumber === BINARY_BASE) return finiteNumber("logarithm", Math.log2(value.value));
|
|
125
126
|
return finiteNumber("logarithm", Math.log(value.value) / Math.log(baseNumber));
|
|
127
|
+
},
|
|
128
|
+
magnitude: (args) => {
|
|
129
|
+
const [arg] = args;
|
|
130
|
+
if (args.length !== 1) return { wrongType: "magnitude requires exactly one argument" };
|
|
131
|
+
if (arg?.kind === "complex") {
|
|
132
|
+
const { value, unit } = require_complex.complexMagnitude(arg);
|
|
133
|
+
return finiteNumber("magnitude", value, unit);
|
|
134
|
+
}
|
|
135
|
+
if (arg?.kind !== "number") return { wrongType: "magnitude requires a number or a complex number" };
|
|
136
|
+
return finiteNumber("magnitude", Math.abs(arg.value), arg.unit);
|
|
137
|
+
},
|
|
138
|
+
phase: (args) => {
|
|
139
|
+
const [arg] = args;
|
|
140
|
+
if (args.length !== 1 || arg?.kind !== "complex") return { wrongType: "phase requires exactly one complex argument" };
|
|
141
|
+
if (!Number.isFinite(arg.re) || !Number.isFinite(arg.im)) return { domainError: "phase requires finite components" };
|
|
142
|
+
return require_complex.complexPhase(arg);
|
|
126
143
|
}
|
|
127
144
|
});
|
|
128
145
|
//#endregion
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { FunctionRegistry } from "./functions.cjs";
|
|
2
2
|
//#region src/builtin-functions.d.ts
|
|
3
3
|
/**
|
|
4
|
-
* The numeric functions a `call` node can name when an embedder has no registry of its own: `minimum` and `maximum` (one or more numbers in a shared unit), `absoluteValue`, `round` (half away from zero, with an optional count of decimal places), `squareRoot`, `exponential`,
|
|
4
|
+
* The numeric functions a `call` node can name when an embedder has no registry of its own: `minimum` and `maximum` (one or more numbers in a shared unit), `absoluteValue`, `round` (half away from zero, with an optional count of decimal places), `squareRoot`, `exponential`, `logarithm` (natural, or to an optional base), and the two projections of a complex value onto the reals, `magnitude` and `phase`. Every function but those two takes real numbers only, and refuses a complex value; `magnitude` takes a real or a complex number, and `phase` a complex one.
|
|
5
5
|
*
|
|
6
6
|
* Failures split as the evaluator's own operators split. An argument a function cannot accept at all (the wrong kind, the wrong count, or units that do not fit) is a `wrongType`; an argument of the right kind outside the function's domain (a negative `squareRoot`, a `logarithm` of zero, a base of one, a fractional count of decimal places) or a result that is not a finite number is a `domainError`.
|
|
7
7
|
*
|
|
8
|
-
* Units follow the evaluator's rule that dimensions are never silently converted. `minimum`, `maximum`, `absoluteValue` and `
|
|
8
|
+
* Units follow the evaluator's rule that dimensions are never silently converted. `minimum`, `maximum`, `absoluteValue`, `round` and `magnitude` keep the argument's unit (and the first two require all arguments to share one); `phase` returns a dimensionless angle in radians in the range [-pi, pi], whatever unit its argument carries, with a negative real number +pi whatever the sign of its zero imaginary part (a signed zero never gives -pi, though a tiny negative imaginary part can round to it) and zero 0 (a component that is not finite is a `domainError`); `squareRoot` halves each dimension's exponent and refuses a unit whose exponents are not all even; `exponential` and `logarithm` accept only dimensionless numbers and return one.
|
|
9
9
|
*
|
|
10
10
|
* Frozen, so mutating the export cannot change what `evaluateDocument` resolves.
|
|
11
11
|
*/
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { FunctionRegistry } from "./functions.js";
|
|
2
2
|
//#region src/builtin-functions.d.ts
|
|
3
3
|
/**
|
|
4
|
-
* The numeric functions a `call` node can name when an embedder has no registry of its own: `minimum` and `maximum` (one or more numbers in a shared unit), `absoluteValue`, `round` (half away from zero, with an optional count of decimal places), `squareRoot`, `exponential`,
|
|
4
|
+
* The numeric functions a `call` node can name when an embedder has no registry of its own: `minimum` and `maximum` (one or more numbers in a shared unit), `absoluteValue`, `round` (half away from zero, with an optional count of decimal places), `squareRoot`, `exponential`, `logarithm` (natural, or to an optional base), and the two projections of a complex value onto the reals, `magnitude` and `phase`. Every function but those two takes real numbers only, and refuses a complex value; `magnitude` takes a real or a complex number, and `phase` a complex one.
|
|
5
5
|
*
|
|
6
6
|
* Failures split as the evaluator's own operators split. An argument a function cannot accept at all (the wrong kind, the wrong count, or units that do not fit) is a `wrongType`; an argument of the right kind outside the function's domain (a negative `squareRoot`, a `logarithm` of zero, a base of one, a fractional count of decimal places) or a result that is not a finite number is a `domainError`.
|
|
7
7
|
*
|
|
8
|
-
* Units follow the evaluator's rule that dimensions are never silently converted. `minimum`, `maximum`, `absoluteValue` and `
|
|
8
|
+
* Units follow the evaluator's rule that dimensions are never silently converted. `minimum`, `maximum`, `absoluteValue`, `round` and `magnitude` keep the argument's unit (and the first two require all arguments to share one); `phase` returns a dimensionless angle in radians in the range [-pi, pi], whatever unit its argument carries, with a negative real number +pi whatever the sign of its zero imaginary part (a signed zero never gives -pi, though a tiny negative imaginary part can round to it) and zero 0 (a component that is not finite is a `domainError`); `squareRoot` halves each dimension's exponent and refuses a unit whose exponents are not all even; `exponential` and `logarithm` accept only dimensionless numbers and return one.
|
|
9
9
|
*
|
|
10
10
|
* Frozen, so mutating the export cannot change what `evaluateDocument` resolves.
|
|
11
11
|
*/
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { unitsEqual } from "./computed-value.js";
|
|
2
|
+
import { complexMagnitude, complexPhase } from "./complex.js";
|
|
2
3
|
//#region src/builtin-functions.ts
|
|
3
4
|
const DECIMAL_BASE = 10;
|
|
4
5
|
const BINARY_BASE = 2;
|
|
@@ -72,11 +73,11 @@ function roundHalfAwayFromZero(value, places) {
|
|
|
72
73
|
return rounded === 0 ? 0 : Math.sign(value) * rounded;
|
|
73
74
|
}
|
|
74
75
|
/**
|
|
75
|
-
* The numeric functions a `call` node can name when an embedder has no registry of its own: `minimum` and `maximum` (one or more numbers in a shared unit), `absoluteValue`, `round` (half away from zero, with an optional count of decimal places), `squareRoot`, `exponential`,
|
|
76
|
+
* The numeric functions a `call` node can name when an embedder has no registry of its own: `minimum` and `maximum` (one or more numbers in a shared unit), `absoluteValue`, `round` (half away from zero, with an optional count of decimal places), `squareRoot`, `exponential`, `logarithm` (natural, or to an optional base), and the two projections of a complex value onto the reals, `magnitude` and `phase`. Every function but those two takes real numbers only, and refuses a complex value; `magnitude` takes a real or a complex number, and `phase` a complex one.
|
|
76
77
|
*
|
|
77
78
|
* Failures split as the evaluator's own operators split. An argument a function cannot accept at all (the wrong kind, the wrong count, or units that do not fit) is a `wrongType`; an argument of the right kind outside the function's domain (a negative `squareRoot`, a `logarithm` of zero, a base of one, a fractional count of decimal places) or a result that is not a finite number is a `domainError`.
|
|
78
79
|
*
|
|
79
|
-
* Units follow the evaluator's rule that dimensions are never silently converted. `minimum`, `maximum`, `absoluteValue` and `
|
|
80
|
+
* Units follow the evaluator's rule that dimensions are never silently converted. `minimum`, `maximum`, `absoluteValue`, `round` and `magnitude` keep the argument's unit (and the first two require all arguments to share one); `phase` returns a dimensionless angle in radians in the range [-pi, pi], whatever unit its argument carries, with a negative real number +pi whatever the sign of its zero imaginary part (a signed zero never gives -pi, though a tiny negative imaginary part can round to it) and zero 0 (a component that is not finite is a `domainError`); `squareRoot` halves each dimension's exponent and refuses a unit whose exponents are not all even; `exponential` and `logarithm` accept only dimensionless numbers and return one.
|
|
80
81
|
*
|
|
81
82
|
* Frozen, so mutating the export cannot change what `evaluateDocument` resolves.
|
|
82
83
|
*/
|
|
@@ -122,6 +123,22 @@ const builtinFunctions = Object.freeze({
|
|
|
122
123
|
if (baseNumber === DECIMAL_BASE) return finiteNumber("logarithm", Math.log10(value.value));
|
|
123
124
|
if (baseNumber === BINARY_BASE) return finiteNumber("logarithm", Math.log2(value.value));
|
|
124
125
|
return finiteNumber("logarithm", Math.log(value.value) / Math.log(baseNumber));
|
|
126
|
+
},
|
|
127
|
+
magnitude: (args) => {
|
|
128
|
+
const [arg] = args;
|
|
129
|
+
if (args.length !== 1) return { wrongType: "magnitude requires exactly one argument" };
|
|
130
|
+
if (arg?.kind === "complex") {
|
|
131
|
+
const { value, unit } = complexMagnitude(arg);
|
|
132
|
+
return finiteNumber("magnitude", value, unit);
|
|
133
|
+
}
|
|
134
|
+
if (arg?.kind !== "number") return { wrongType: "magnitude requires a number or a complex number" };
|
|
135
|
+
return finiteNumber("magnitude", Math.abs(arg.value), arg.unit);
|
|
136
|
+
},
|
|
137
|
+
phase: (args) => {
|
|
138
|
+
const [arg] = args;
|
|
139
|
+
if (args.length !== 1 || arg?.kind !== "complex") return { wrongType: "phase requires exactly one complex argument" };
|
|
140
|
+
if (!Number.isFinite(arg.re) || !Number.isFinite(arg.im)) return { domainError: "phase requires finite components" };
|
|
141
|
+
return complexPhase(arg);
|
|
125
142
|
}
|
|
126
143
|
});
|
|
127
144
|
//#endregion
|
package/dist/complex.cjs
CHANGED
|
@@ -22,10 +22,12 @@ const complexMagnitude = (value) => ({
|
|
|
22
22
|
value: Math.hypot(value.re, value.im),
|
|
23
23
|
unit: value.unit
|
|
24
24
|
});
|
|
25
|
-
/**
|
|
25
|
+
/**
|
|
26
|
+
* arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. The range is [-pi, pi]: `Math.atan2` returns -pi for a negative real number whose imaginary part is `-0` and +pi when it is `+0`, although the two are the same number and JSON writes both zeros as `0`, and the closed range is what the result can be because a tiny negative imaginary part also rounds to exactly -pi (`phase(-1 - 1e-17i)` is -pi, the true angle being a hair inside). Adding `+0` turns `-0` into `+0` without changing any other value, so a signed zero never gives -pi: a negative real number is +pi whatever the sign of its zero, and zero is 0.
|
|
27
|
+
*/
|
|
26
28
|
const complexPhase = (value) => ({
|
|
27
29
|
kind: "number",
|
|
28
|
-
value: Math.atan2(value.im, value.re)
|
|
30
|
+
value: Math.atan2(value.im + 0, value.re + 0)
|
|
29
31
|
});
|
|
30
32
|
//#endregion
|
|
31
33
|
exports.complexFromPolar = complexFromPolar;
|
package/dist/complex.d.cts
CHANGED
|
@@ -4,7 +4,7 @@ import { ComplexLiteralNode } from "./tree.cjs";
|
|
|
4
4
|
/**
|
|
5
5
|
* The `complex` computed-value kind stores one canonical representation, rectangular (`re` + `im`i), with no `form` discriminant offering a polar alternative alongside it -- see the "Complex values" section of README.md for the reasoning. These four helpers are what keep the magnitude-and-phase view reachable for the domains that reason that way, as conversions at the edges rather than a second encoding of the same value that every operator would then have to branch on.
|
|
6
6
|
*
|
|
7
|
-
* Phase is in radians throughout, measured from the positive real axis,
|
|
7
|
+
* Phase is in radians throughout, measured from the positive real axis, in the range [-pi, pi] that `complexPhase` below states, which differs from `Math.atan2`'s only for a zero imaginary part of either sign.
|
|
8
8
|
*/
|
|
9
9
|
type ComplexValue = Extract<ComputedValue, {
|
|
10
10
|
kind: "complex";
|
|
@@ -17,6 +17,8 @@ export declare const complexFromPolar: (magnitude: number, phase: number, unit?:
|
|
|
17
17
|
export declare const complexLiteralFromPolar: (magnitude: number, phase: number, unit?: Unit) => ComplexLiteralNode;
|
|
18
18
|
/** |z|, as a real number in the same unit the complex value itself carries -- the magnitude of an impedance in ohms is a real quantity in ohms. */
|
|
19
19
|
export declare const complexMagnitude: (value: ComplexValue) => NumberValue;
|
|
20
|
-
/**
|
|
20
|
+
/**
|
|
21
|
+
* arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. The range is [-pi, pi]: `Math.atan2` returns -pi for a negative real number whose imaginary part is `-0` and +pi when it is `+0`, although the two are the same number and JSON writes both zeros as `0`, and the closed range is what the result can be because a tiny negative imaginary part also rounds to exactly -pi (`phase(-1 - 1e-17i)` is -pi, the true angle being a hair inside). Adding `+0` turns `-0` into `+0` without changing any other value, so a signed zero never gives -pi: a negative real number is +pi whatever the sign of its zero, and zero is 0.
|
|
22
|
+
*/
|
|
21
23
|
export declare const complexPhase: (value: ComplexValue) => NumberValue;
|
|
22
24
|
//#endregion
|
package/dist/complex.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { ComplexLiteralNode } from "./tree.js";
|
|
|
4
4
|
/**
|
|
5
5
|
* The `complex` computed-value kind stores one canonical representation, rectangular (`re` + `im`i), with no `form` discriminant offering a polar alternative alongside it -- see the "Complex values" section of README.md for the reasoning. These four helpers are what keep the magnitude-and-phase view reachable for the domains that reason that way, as conversions at the edges rather than a second encoding of the same value that every operator would then have to branch on.
|
|
6
6
|
*
|
|
7
|
-
* Phase is in radians throughout, measured from the positive real axis,
|
|
7
|
+
* Phase is in radians throughout, measured from the positive real axis, in the range [-pi, pi] that `complexPhase` below states, which differs from `Math.atan2`'s only for a zero imaginary part of either sign.
|
|
8
8
|
*/
|
|
9
9
|
type ComplexValue = Extract<ComputedValue, {
|
|
10
10
|
kind: "complex";
|
|
@@ -17,6 +17,8 @@ export declare const complexFromPolar: (magnitude: number, phase: number, unit?:
|
|
|
17
17
|
export declare const complexLiteralFromPolar: (magnitude: number, phase: number, unit?: Unit) => ComplexLiteralNode;
|
|
18
18
|
/** |z|, as a real number in the same unit the complex value itself carries -- the magnitude of an impedance in ohms is a real quantity in ohms. */
|
|
19
19
|
export declare const complexMagnitude: (value: ComplexValue) => NumberValue;
|
|
20
|
-
/**
|
|
20
|
+
/**
|
|
21
|
+
* arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. The range is [-pi, pi]: `Math.atan2` returns -pi for a negative real number whose imaginary part is `-0` and +pi when it is `+0`, although the two are the same number and JSON writes both zeros as `0`, and the closed range is what the result can be because a tiny negative imaginary part also rounds to exactly -pi (`phase(-1 - 1e-17i)` is -pi, the true angle being a hair inside). Adding `+0` turns `-0` into `+0` without changing any other value, so a signed zero never gives -pi: a negative real number is +pi whatever the sign of its zero, and zero is 0.
|
|
22
|
+
*/
|
|
21
23
|
export declare const complexPhase: (value: ComplexValue) => NumberValue;
|
|
22
24
|
//#endregion
|
package/dist/complex.js
CHANGED
|
@@ -21,10 +21,12 @@ const complexMagnitude = (value) => ({
|
|
|
21
21
|
value: Math.hypot(value.re, value.im),
|
|
22
22
|
unit: value.unit
|
|
23
23
|
});
|
|
24
|
-
/**
|
|
24
|
+
/**
|
|
25
|
+
* arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. The range is [-pi, pi]: `Math.atan2` returns -pi for a negative real number whose imaginary part is `-0` and +pi when it is `+0`, although the two are the same number and JSON writes both zeros as `0`, and the closed range is what the result can be because a tiny negative imaginary part also rounds to exactly -pi (`phase(-1 - 1e-17i)` is -pi, the true angle being a hair inside). Adding `+0` turns `-0` into `+0` without changing any other value, so a signed zero never gives -pi: a negative real number is +pi whatever the sign of its zero, and zero is 0.
|
|
26
|
+
*/
|
|
25
27
|
const complexPhase = (value) => ({
|
|
26
28
|
kind: "number",
|
|
27
|
-
value: Math.atan2(value.im, value.re)
|
|
29
|
+
value: Math.atan2(value.im + 0, value.re + 0)
|
|
28
30
|
});
|
|
29
31
|
//#endregion
|
|
30
32
|
export { complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase };
|
|
@@ -10,7 +10,7 @@ const predicateKinds = new Set(require_tree.PredicateNodeSchema.options.map((opt
|
|
|
10
10
|
/** What a definite expression result that `ComputedValueSchema` refuses is reported as: the only way a result fails it is a non-finite number, which JSON would write as `null`. The evaluator's arithmetic and the built-in functions already keep one from forming, so this is the last check before a value leaves the document boundary, and it fails loudly rather than print a different value from the one computed. */
|
|
11
11
|
const NOT_REPRESENTABLE = "(result): the value is not a finite number";
|
|
12
12
|
const AMBIGUOUS_TREE_KIND = "(root): a treeReference is valid as a predicate and as an expression; set `as` to \"predicate\" or \"expression\"";
|
|
13
|
-
const
|
|
13
|
+
const defaultEvaluator = require_evaluator_factory.createSyncEvaluator({ functions: require_builtin_functions.builtinFunctions });
|
|
14
14
|
/** Turns zod's issues into `path: message` lines. A failed union wraps one list of issues per branch, each path relative to the union; the branch the input got furthest into (the deepest path) is the one it was meant to match, so only that branch's issues are reported, under the union's own path. */
|
|
15
15
|
function describeIssues(issues, parentPath = []) {
|
|
16
16
|
return issues.flatMap((issue) => {
|
|
@@ -35,16 +35,22 @@ function resolveTreeKind(tree, requested) {
|
|
|
35
35
|
* - `rejected`: nothing was evaluated, because a tree or an input failed validation (`invalid`) or a root `treeReference` was given without `as` (`ambiguous-tree-kind`). `issues` has one `path: message` line per problem.
|
|
36
36
|
* - `unrepresentable`: the tree was evaluated and the result is a number JSON cannot carry (`Infinity` or `NaN`), which would otherwise be printed as `null`. The built-in registry never produces one, and the evaluator's arithmetic turns an overflow into a `domain-error`, so this is a guard on the document boundary against a change that stops doing so.
|
|
37
37
|
*
|
|
38
|
-
*
|
|
38
|
+
* The inputs are validated in full before anything is evaluated, every element of every list included, so a very long list is parsed and held in memory whatever the node budget (`maxNodes`) is.
|
|
39
|
+
*
|
|
40
|
+
* Resolution is limited to what `createInputResolvers` provides: named values, and lists of items for a `fold`, `some` or `every`. A tree that names a collection the inputs do not hold throws that resolver's error, which propagates.
|
|
39
41
|
*/
|
|
40
|
-
function evaluateDocument({ tree, inputs, as }) {
|
|
42
|
+
function evaluateDocument({ tree, inputs, as, maxNodes }) {
|
|
43
|
+
const evaluator = maxNodes === void 0 ? defaultEvaluator : require_evaluator_factory.createSyncEvaluator({
|
|
44
|
+
functions: require_builtin_functions.builtinFunctions,
|
|
45
|
+
maxNodes
|
|
46
|
+
});
|
|
41
47
|
const parsedInputs = require_input_resolvers.parseInputs(inputs ?? {});
|
|
42
48
|
if (!parsedInputs.ok) return {
|
|
43
49
|
outcome: "rejected",
|
|
44
50
|
reason: "invalid",
|
|
45
51
|
issues: parsedInputs.issues
|
|
46
52
|
};
|
|
47
|
-
const resolvers = require_input_resolvers.createInputResolvers(parsedInputs.inputs);
|
|
53
|
+
const resolvers = require_input_resolvers.createInputResolvers(parsedInputs.inputs, parsedInputs.collections);
|
|
48
54
|
const treeKind = resolveTreeKind(tree, as);
|
|
49
55
|
if (treeKind === "ambiguous") return {
|
|
50
56
|
outcome: "rejected",
|
|
@@ -5,10 +5,12 @@ export type TreeKind = "predicate" | "expression";
|
|
|
5
5
|
export interface EvaluateDocumentOptions {
|
|
6
6
|
/** The tree as parsed from JSON, not yet validated. */
|
|
7
7
|
tree: unknown;
|
|
8
|
-
/** Named
|
|
8
|
+
/** Named values and lists of items as parsed from JSON (see `parseInputs`); absent means none. */
|
|
9
9
|
inputs?: unknown;
|
|
10
10
|
/** Which tree `tree` is. Needed only when its root is a `treeReference`, the one node kind valid in both. */
|
|
11
11
|
as?: TreeKind;
|
|
12
|
+
/** The most nodes one evaluation may visit before it ends as an indeterminate result (see `createSyncEvaluator`); absent means the evaluator's default. A fold visits its combine expression once per item, so a long list needs a larger budget. The caller supplies a positive integer. */
|
|
13
|
+
maxNodes?: number;
|
|
12
14
|
}
|
|
13
15
|
export type DocumentEvaluation = {
|
|
14
16
|
outcome: "evaluated";
|
|
@@ -34,7 +36,9 @@ export type DocumentEvaluation = {
|
|
|
34
36
|
* - `rejected`: nothing was evaluated, because a tree or an input failed validation (`invalid`) or a root `treeReference` was given without `as` (`ambiguous-tree-kind`). `issues` has one `path: message` line per problem.
|
|
35
37
|
* - `unrepresentable`: the tree was evaluated and the result is a number JSON cannot carry (`Infinity` or `NaN`), which would otherwise be printed as `null`. The built-in registry never produces one, and the evaluator's arithmetic turns an overflow into a `domain-error`, so this is a guard on the document boundary against a change that stops doing so.
|
|
36
38
|
*
|
|
37
|
-
*
|
|
39
|
+
* The inputs are validated in full before anything is evaluated, every element of every list included, so a very long list is parsed and held in memory whatever the node budget (`maxNodes`) is.
|
|
40
|
+
*
|
|
41
|
+
* Resolution is limited to what `createInputResolvers` provides: named values, and lists of items for a `fold`, `some` or `every`. A tree that names a collection the inputs do not hold throws that resolver's error, which propagates.
|
|
38
42
|
*/
|
|
39
|
-
export declare function evaluateDocument({ tree, inputs, as }: EvaluateDocumentOptions): DocumentEvaluation;
|
|
43
|
+
export declare function evaluateDocument({ tree, inputs, as, maxNodes }: EvaluateDocumentOptions): DocumentEvaluation;
|
|
40
44
|
//#endregion
|
|
@@ -5,10 +5,12 @@ export type TreeKind = "predicate" | "expression";
|
|
|
5
5
|
export interface EvaluateDocumentOptions {
|
|
6
6
|
/** The tree as parsed from JSON, not yet validated. */
|
|
7
7
|
tree: unknown;
|
|
8
|
-
/** Named
|
|
8
|
+
/** Named values and lists of items as parsed from JSON (see `parseInputs`); absent means none. */
|
|
9
9
|
inputs?: unknown;
|
|
10
10
|
/** Which tree `tree` is. Needed only when its root is a `treeReference`, the one node kind valid in both. */
|
|
11
11
|
as?: TreeKind;
|
|
12
|
+
/** The most nodes one evaluation may visit before it ends as an indeterminate result (see `createSyncEvaluator`); absent means the evaluator's default. A fold visits its combine expression once per item, so a long list needs a larger budget. The caller supplies a positive integer. */
|
|
13
|
+
maxNodes?: number;
|
|
12
14
|
}
|
|
13
15
|
export type DocumentEvaluation = {
|
|
14
16
|
outcome: "evaluated";
|
|
@@ -34,7 +36,9 @@ export type DocumentEvaluation = {
|
|
|
34
36
|
* - `rejected`: nothing was evaluated, because a tree or an input failed validation (`invalid`) or a root `treeReference` was given without `as` (`ambiguous-tree-kind`). `issues` has one `path: message` line per problem.
|
|
35
37
|
* - `unrepresentable`: the tree was evaluated and the result is a number JSON cannot carry (`Infinity` or `NaN`), which would otherwise be printed as `null`. The built-in registry never produces one, and the evaluator's arithmetic turns an overflow into a `domain-error`, so this is a guard on the document boundary against a change that stops doing so.
|
|
36
38
|
*
|
|
37
|
-
*
|
|
39
|
+
* The inputs are validated in full before anything is evaluated, every element of every list included, so a very long list is parsed and held in memory whatever the node budget (`maxNodes`) is.
|
|
40
|
+
*
|
|
41
|
+
* Resolution is limited to what `createInputResolvers` provides: named values, and lists of items for a `fold`, `some` or `every`. A tree that names a collection the inputs do not hold throws that resolver's error, which propagates.
|
|
38
42
|
*/
|
|
39
|
-
export declare function evaluateDocument({ tree, inputs, as }: EvaluateDocumentOptions): DocumentEvaluation;
|
|
43
|
+
export declare function evaluateDocument({ tree, inputs, as, maxNodes }: EvaluateDocumentOptions): DocumentEvaluation;
|
|
40
44
|
//#endregion
|
|
@@ -9,7 +9,7 @@ const predicateKinds = new Set(PredicateNodeSchema.options.map((option) => optio
|
|
|
9
9
|
/** What a definite expression result that `ComputedValueSchema` refuses is reported as: the only way a result fails it is a non-finite number, which JSON would write as `null`. The evaluator's arithmetic and the built-in functions already keep one from forming, so this is the last check before a value leaves the document boundary, and it fails loudly rather than print a different value from the one computed. */
|
|
10
10
|
const NOT_REPRESENTABLE = "(result): the value is not a finite number";
|
|
11
11
|
const AMBIGUOUS_TREE_KIND = "(root): a treeReference is valid as a predicate and as an expression; set `as` to \"predicate\" or \"expression\"";
|
|
12
|
-
const
|
|
12
|
+
const defaultEvaluator = createSyncEvaluator({ functions: builtinFunctions });
|
|
13
13
|
/** Turns zod's issues into `path: message` lines. A failed union wraps one list of issues per branch, each path relative to the union; the branch the input got furthest into (the deepest path) is the one it was meant to match, so only that branch's issues are reported, under the union's own path. */
|
|
14
14
|
function describeIssues(issues, parentPath = []) {
|
|
15
15
|
return issues.flatMap((issue) => {
|
|
@@ -34,16 +34,22 @@ function resolveTreeKind(tree, requested) {
|
|
|
34
34
|
* - `rejected`: nothing was evaluated, because a tree or an input failed validation (`invalid`) or a root `treeReference` was given without `as` (`ambiguous-tree-kind`). `issues` has one `path: message` line per problem.
|
|
35
35
|
* - `unrepresentable`: the tree was evaluated and the result is a number JSON cannot carry (`Infinity` or `NaN`), which would otherwise be printed as `null`. The built-in registry never produces one, and the evaluator's arithmetic turns an overflow into a `domain-error`, so this is a guard on the document boundary against a change that stops doing so.
|
|
36
36
|
*
|
|
37
|
-
*
|
|
37
|
+
* The inputs are validated in full before anything is evaluated, every element of every list included, so a very long list is parsed and held in memory whatever the node budget (`maxNodes`) is.
|
|
38
|
+
*
|
|
39
|
+
* Resolution is limited to what `createInputResolvers` provides: named values, and lists of items for a `fold`, `some` or `every`. A tree that names a collection the inputs do not hold throws that resolver's error, which propagates.
|
|
38
40
|
*/
|
|
39
|
-
function evaluateDocument({ tree, inputs, as }) {
|
|
41
|
+
function evaluateDocument({ tree, inputs, as, maxNodes }) {
|
|
42
|
+
const evaluator = maxNodes === void 0 ? defaultEvaluator : createSyncEvaluator({
|
|
43
|
+
functions: builtinFunctions,
|
|
44
|
+
maxNodes
|
|
45
|
+
});
|
|
40
46
|
const parsedInputs = parseInputs(inputs ?? {});
|
|
41
47
|
if (!parsedInputs.ok) return {
|
|
42
48
|
outcome: "rejected",
|
|
43
49
|
reason: "invalid",
|
|
44
50
|
issues: parsedInputs.issues
|
|
45
51
|
};
|
|
46
|
-
const resolvers = createInputResolvers(parsedInputs.inputs);
|
|
52
|
+
const resolvers = createInputResolvers(parsedInputs.inputs, parsedInputs.collections);
|
|
47
53
|
const treeKind = resolveTreeKind(tree, as);
|
|
48
54
|
if (treeKind === "ambiguous") return {
|
|
49
55
|
outcome: "rejected",
|
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_computed_value = require("./computed-value.cjs");
|
|
3
|
-
const require_builtin_functions = require("./builtin-functions.cjs");
|
|
4
3
|
const require_complex = require("./complex.cjs");
|
|
4
|
+
const require_builtin_functions = require("./builtin-functions.cjs");
|
|
5
5
|
const require_derived_aggregates = require("./derived-aggregates.cjs");
|
|
6
6
|
const require_derived_connectives = require("./derived-connectives.cjs");
|
|
7
7
|
const require_derived_patterns = require("./derived-patterns.cjs");
|
package/dist/index.d.cts
CHANGED
|
@@ -12,5 +12,5 @@ import { Evaluation, IndeterminateReason, IndeterminateReasonSchema, definite, f
|
|
|
12
12
|
import { DocumentEvaluation, EvaluateDocumentOptions, TreeKind, evaluateDocument } from "./evaluate-document.cjs";
|
|
13
13
|
import { EvaluationContext, Resolution, Resolvers, SyncResolvers, TreeResolution } from "./resolvers.cjs";
|
|
14
14
|
import { EvaluatorOptions, createEvaluator, createSyncEvaluator, evaluatePredicate, evaluateValue } from "./evaluator-factory.cjs";
|
|
15
|
-
import { InputsParseResult, createInputResolvers, parseInputs } from "./input-resolvers.cjs";
|
|
16
|
-
export { type AccumulatorNode, AccumulatorNodeSchema, type AllOfNode, AllOfNodeSchema, type AndNode, AndNodeSchema, type AnyOfNode, AnyOfNodeSchema, type ArithmeticNode, ArithmeticNodeSchema, type ArithmeticOperator, ArithmeticOperatorSchema, type BooleanLiteralNode, BooleanLiteralNodeSchema, type CallNode, CallNodeSchema, type CompareNode, CompareNodeSchema, type ComparisonOperator, ComparisonOperatorSchema, type ComplexLiteralNode, ComplexLiteralNodeSchema, type ComplexPolarLiteralNode, ComplexPolarLiteralNodeSchema, type ComplexRectangularLiteralNode, ComplexRectangularLiteralNodeSchema, type ComputedValue, ComputedValueSchema, type ConditionalCase, ConditionalCaseSchema, type ConditionalNode, ConditionalNodeSchema, type DelegateNode, DelegateNodeSchema, type DocumentEvaluation, type DurationLiteralNode, DurationLiteralNodeSchema, type DurationUnit, DurationUnitSchema, type EvaluateDocumentOptions, type Evaluation, type EvaluationContext, type EvaluatorOptions, type EveryNode, EveryNodeSchema, type ExistsNode, ExistsNodeSchema, type ExpressionNode, ExpressionNodeSchema, type FoldCombiner, FoldCombinerSchema, type FoldNode, FoldNodeSchema, type FunctionFailure, type FunctionRegistry, type HitPolicy, HitPolicySchema, type IndeterminateReason, IndeterminateReasonSchema, type InputsParseResult, type InstantLiteralNode, InstantLiteralNodeSchema, type JsonValue, JsonValueSchema, type LookupNode, LookupNodeSchema, type MemberOfNode, MemberOfNodeSchema, type MembershipOperator, MembershipOperatorSchema, type NegateNode, NegateNodeSchema, type NotNode, NotNodeSchema, type NumberLiteralNode, NumberLiteralNodeSchema, type OrNode, OrNodeSchema, type PredicateNode, PredicateNodeSchema, type ReferenceNode, ReferenceNodeSchema, type Resolution, type Resolvers, type SomeNode, SomeNodeSchema, type SyncResolvers, type TextCompareNode, TextCompareNodeSchema, type TextComparisonOperator, TextComparisonOperatorSchema, type TextLiteralNode, TextLiteralNodeSchema, type TreeKind, type TreeReferenceNode, TreeReferenceNodeSchema, type TreeResolution, type Unit, UnitSchema, and, average, builtinFunctions, coalesce, combineUnitsForDivide, combineUnitsForMultiply, complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase, count, createEvaluator, createInputResolvers, createSyncEvaluator, definite, emptyFunctionRegistry, evaluateDocument, evaluatePredicate, evaluateValue, firstIndeterminate, hierarchicalGlobPattern, iff, implies, indeterminate, nand, none, nor, not, or, parseInputs, prefixPattern, presenceOf, sum, unitsEqual, wildcardPattern, xor };
|
|
15
|
+
import { InputItem, InputsParseResult, createInputResolvers, parseInputs } from "./input-resolvers.cjs";
|
|
16
|
+
export { type AccumulatorNode, AccumulatorNodeSchema, type AllOfNode, AllOfNodeSchema, type AndNode, AndNodeSchema, type AnyOfNode, AnyOfNodeSchema, type ArithmeticNode, ArithmeticNodeSchema, type ArithmeticOperator, ArithmeticOperatorSchema, type BooleanLiteralNode, BooleanLiteralNodeSchema, type CallNode, CallNodeSchema, type CompareNode, CompareNodeSchema, type ComparisonOperator, ComparisonOperatorSchema, type ComplexLiteralNode, ComplexLiteralNodeSchema, type ComplexPolarLiteralNode, ComplexPolarLiteralNodeSchema, type ComplexRectangularLiteralNode, ComplexRectangularLiteralNodeSchema, type ComputedValue, ComputedValueSchema, type ConditionalCase, ConditionalCaseSchema, type ConditionalNode, ConditionalNodeSchema, type DelegateNode, DelegateNodeSchema, type DocumentEvaluation, type DurationLiteralNode, DurationLiteralNodeSchema, type DurationUnit, DurationUnitSchema, type EvaluateDocumentOptions, type Evaluation, type EvaluationContext, type EvaluatorOptions, type EveryNode, EveryNodeSchema, type ExistsNode, ExistsNodeSchema, type ExpressionNode, ExpressionNodeSchema, type FoldCombiner, FoldCombinerSchema, type FoldNode, FoldNodeSchema, type FunctionFailure, type FunctionRegistry, type HitPolicy, HitPolicySchema, type IndeterminateReason, IndeterminateReasonSchema, type InputItem, type InputsParseResult, type InstantLiteralNode, InstantLiteralNodeSchema, type JsonValue, JsonValueSchema, type LookupNode, LookupNodeSchema, type MemberOfNode, MemberOfNodeSchema, type MembershipOperator, MembershipOperatorSchema, type NegateNode, NegateNodeSchema, type NotNode, NotNodeSchema, type NumberLiteralNode, NumberLiteralNodeSchema, type OrNode, OrNodeSchema, type PredicateNode, PredicateNodeSchema, type ReferenceNode, ReferenceNodeSchema, type Resolution, type Resolvers, type SomeNode, SomeNodeSchema, type SyncResolvers, type TextCompareNode, TextCompareNodeSchema, type TextComparisonOperator, TextComparisonOperatorSchema, type TextLiteralNode, TextLiteralNodeSchema, type TreeKind, type TreeReferenceNode, TreeReferenceNodeSchema, type TreeResolution, type Unit, UnitSchema, and, average, builtinFunctions, coalesce, combineUnitsForDivide, combineUnitsForMultiply, complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase, count, createEvaluator, createInputResolvers, createSyncEvaluator, definite, emptyFunctionRegistry, evaluateDocument, evaluatePredicate, evaluateValue, firstIndeterminate, hierarchicalGlobPattern, iff, implies, indeterminate, nand, none, nor, not, or, parseInputs, prefixPattern, presenceOf, sum, unitsEqual, wildcardPattern, xor };
|
package/dist/index.d.ts
CHANGED
|
@@ -12,5 +12,5 @@ import { Evaluation, IndeterminateReason, IndeterminateReasonSchema, definite, f
|
|
|
12
12
|
import { DocumentEvaluation, EvaluateDocumentOptions, TreeKind, evaluateDocument } from "./evaluate-document.js";
|
|
13
13
|
import { EvaluationContext, Resolution, Resolvers, SyncResolvers, TreeResolution } from "./resolvers.js";
|
|
14
14
|
import { EvaluatorOptions, createEvaluator, createSyncEvaluator, evaluatePredicate, evaluateValue } from "./evaluator-factory.js";
|
|
15
|
-
import { InputsParseResult, createInputResolvers, parseInputs } from "./input-resolvers.js";
|
|
16
|
-
export { type AccumulatorNode, AccumulatorNodeSchema, type AllOfNode, AllOfNodeSchema, type AndNode, AndNodeSchema, type AnyOfNode, AnyOfNodeSchema, type ArithmeticNode, ArithmeticNodeSchema, type ArithmeticOperator, ArithmeticOperatorSchema, type BooleanLiteralNode, BooleanLiteralNodeSchema, type CallNode, CallNodeSchema, type CompareNode, CompareNodeSchema, type ComparisonOperator, ComparisonOperatorSchema, type ComplexLiteralNode, ComplexLiteralNodeSchema, type ComplexPolarLiteralNode, ComplexPolarLiteralNodeSchema, type ComplexRectangularLiteralNode, ComplexRectangularLiteralNodeSchema, type ComputedValue, ComputedValueSchema, type ConditionalCase, ConditionalCaseSchema, type ConditionalNode, ConditionalNodeSchema, type DelegateNode, DelegateNodeSchema, type DocumentEvaluation, type DurationLiteralNode, DurationLiteralNodeSchema, type DurationUnit, DurationUnitSchema, type EvaluateDocumentOptions, type Evaluation, type EvaluationContext, type EvaluatorOptions, type EveryNode, EveryNodeSchema, type ExistsNode, ExistsNodeSchema, type ExpressionNode, ExpressionNodeSchema, type FoldCombiner, FoldCombinerSchema, type FoldNode, FoldNodeSchema, type FunctionFailure, type FunctionRegistry, type HitPolicy, HitPolicySchema, type IndeterminateReason, IndeterminateReasonSchema, type InputsParseResult, type InstantLiteralNode, InstantLiteralNodeSchema, type JsonValue, JsonValueSchema, type LookupNode, LookupNodeSchema, type MemberOfNode, MemberOfNodeSchema, type MembershipOperator, MembershipOperatorSchema, type NegateNode, NegateNodeSchema, type NotNode, NotNodeSchema, type NumberLiteralNode, NumberLiteralNodeSchema, type OrNode, OrNodeSchema, type PredicateNode, PredicateNodeSchema, type ReferenceNode, ReferenceNodeSchema, type Resolution, type Resolvers, type SomeNode, SomeNodeSchema, type SyncResolvers, type TextCompareNode, TextCompareNodeSchema, type TextComparisonOperator, TextComparisonOperatorSchema, type TextLiteralNode, TextLiteralNodeSchema, type TreeKind, type TreeReferenceNode, TreeReferenceNodeSchema, type TreeResolution, type Unit, UnitSchema, and, average, builtinFunctions, coalesce, combineUnitsForDivide, combineUnitsForMultiply, complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase, count, createEvaluator, createInputResolvers, createSyncEvaluator, definite, emptyFunctionRegistry, evaluateDocument, evaluatePredicate, evaluateValue, firstIndeterminate, hierarchicalGlobPattern, iff, implies, indeterminate, nand, none, nor, not, or, parseInputs, prefixPattern, presenceOf, sum, unitsEqual, wildcardPattern, xor };
|
|
15
|
+
import { InputItem, InputsParseResult, createInputResolvers, parseInputs } from "./input-resolvers.js";
|
|
16
|
+
export { type AccumulatorNode, AccumulatorNodeSchema, type AllOfNode, AllOfNodeSchema, type AndNode, AndNodeSchema, type AnyOfNode, AnyOfNodeSchema, type ArithmeticNode, ArithmeticNodeSchema, type ArithmeticOperator, ArithmeticOperatorSchema, type BooleanLiteralNode, BooleanLiteralNodeSchema, type CallNode, CallNodeSchema, type CompareNode, CompareNodeSchema, type ComparisonOperator, ComparisonOperatorSchema, type ComplexLiteralNode, ComplexLiteralNodeSchema, type ComplexPolarLiteralNode, ComplexPolarLiteralNodeSchema, type ComplexRectangularLiteralNode, ComplexRectangularLiteralNodeSchema, type ComputedValue, ComputedValueSchema, type ConditionalCase, ConditionalCaseSchema, type ConditionalNode, ConditionalNodeSchema, type DelegateNode, DelegateNodeSchema, type DocumentEvaluation, type DurationLiteralNode, DurationLiteralNodeSchema, type DurationUnit, DurationUnitSchema, type EvaluateDocumentOptions, type Evaluation, type EvaluationContext, type EvaluatorOptions, type EveryNode, EveryNodeSchema, type ExistsNode, ExistsNodeSchema, type ExpressionNode, ExpressionNodeSchema, type FoldCombiner, FoldCombinerSchema, type FoldNode, FoldNodeSchema, type FunctionFailure, type FunctionRegistry, type HitPolicy, HitPolicySchema, type IndeterminateReason, IndeterminateReasonSchema, type InputItem, type InputsParseResult, type InstantLiteralNode, InstantLiteralNodeSchema, type JsonValue, JsonValueSchema, type LookupNode, LookupNodeSchema, type MemberOfNode, MemberOfNodeSchema, type MembershipOperator, MembershipOperatorSchema, type NegateNode, NegateNodeSchema, type NotNode, NotNodeSchema, type NumberLiteralNode, NumberLiteralNodeSchema, type OrNode, OrNodeSchema, type PredicateNode, PredicateNodeSchema, type ReferenceNode, ReferenceNodeSchema, type Resolution, type Resolvers, type SomeNode, SomeNodeSchema, type SyncResolvers, type TextCompareNode, TextCompareNodeSchema, type TextComparisonOperator, TextComparisonOperatorSchema, type TextLiteralNode, TextLiteralNodeSchema, type TreeKind, type TreeReferenceNode, TreeReferenceNodeSchema, type TreeResolution, type Unit, UnitSchema, and, average, builtinFunctions, coalesce, combineUnitsForDivide, combineUnitsForMultiply, complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase, count, createEvaluator, createInputResolvers, createSyncEvaluator, definite, emptyFunctionRegistry, evaluateDocument, evaluatePredicate, evaluateValue, firstIndeterminate, hierarchicalGlobPattern, iff, implies, indeterminate, nand, none, nor, not, or, parseInputs, prefixPattern, presenceOf, sum, unitsEqual, wildcardPattern, xor };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ComputedValueSchema, DurationUnitSchema, UnitSchema, combineUnitsForDivide, combineUnitsForMultiply, unitsEqual } from "./computed-value.js";
|
|
2
|
-
import { builtinFunctions } from "./builtin-functions.js";
|
|
3
2
|
import { complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase } from "./complex.js";
|
|
3
|
+
import { builtinFunctions } from "./builtin-functions.js";
|
|
4
4
|
import { average, count, presenceOf, sum } from "./derived-aggregates.js";
|
|
5
5
|
import { and, iff, implies, nand, none, nor, not, or, xor } from "./derived-connectives.js";
|
|
6
6
|
import { hierarchicalGlobPattern, prefixPattern, wildcardPattern } from "./derived-patterns.js";
|
package/dist/input-resolvers.cjs
CHANGED
|
@@ -17,8 +17,40 @@ function toComputedValue(raw) {
|
|
|
17
17
|
const parsed = require_computed_value.ComputedValueSchema.safeParse(candidate);
|
|
18
18
|
return parsed.success ? parsed.data : void 0;
|
|
19
19
|
}
|
|
20
|
+
const NOT_A_VALUE = "expected a finite number, text, boolean or a complete computed value";
|
|
20
21
|
/**
|
|
21
|
-
*
|
|
22
|
+
* The evaluation context while a `fold`, `some` or `every` is evaluating one item. `resolveCollection` wraps each element in one of these, and `resolveValue` reads names from an item only when its context is one, so scope follows what the resolver itself handed out and not the identity or shape of anything else. The class is not exported, so no value passed as a context can be mistaken for an item. The guarantee is about this resolver's own `resolveCollection`: a list served by it is scoped, and the supported way to give it lists is the `collections` argument of `createInputResolvers`. An embedder that composes resolvers, spreading these and overriding `resolveCollection` to serve its own items while keeping this `resolveValue`, serves items that are not wrappers, and a fold over them reads names from the top-level inputs; scoping those items is the embedder's responsibility.
|
|
23
|
+
*/
|
|
24
|
+
var ScopedItem = class {
|
|
25
|
+
values;
|
|
26
|
+
constructor(values) {
|
|
27
|
+
this.values = values;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
/** Validates one element of a list input: a plain object whose every entry is a value, each by the same rules as a top-level input. */
|
|
31
|
+
function parseItem(label, raw) {
|
|
32
|
+
if (!require_plain_record.isPlainRecord(raw)) return {
|
|
33
|
+
item: void 0,
|
|
34
|
+
issues: [`${label}: expected an object of named values`]
|
|
35
|
+
};
|
|
36
|
+
const item = /* @__PURE__ */ new Map();
|
|
37
|
+
const issues = [];
|
|
38
|
+
for (const [name, value] of Object.entries(raw)) {
|
|
39
|
+
const computed = toComputedValue(value);
|
|
40
|
+
if (computed === void 0) issues.push(`${label}.${name}: ${NOT_A_VALUE}`);
|
|
41
|
+
else item.set(name, computed);
|
|
42
|
+
}
|
|
43
|
+
if (issues.length > 0) return {
|
|
44
|
+
item: void 0,
|
|
45
|
+
issues
|
|
46
|
+
};
|
|
47
|
+
return {
|
|
48
|
+
item,
|
|
49
|
+
issues
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Validates a plain object of inputs and splits it into named values and lists of items. An entry that is an array is a list: every element must be an object of named values (see `toComputedValue` for the accepted shapes of each value), and the list is what a `fold`, `some` or `every` resolves its `collection` to. Any other entry is one named value. Every entry is checked up front, so a malformed input is reported as one by name and position rather than surfacing later as a `not-found` reference.
|
|
22
54
|
*/
|
|
23
55
|
function parseInputs(raw) {
|
|
24
56
|
if (!require_plain_record.isPlainRecord(raw)) return {
|
|
@@ -26,27 +58,40 @@ function parseInputs(raw) {
|
|
|
26
58
|
issues: ["inputs must be a JSON object of named values"]
|
|
27
59
|
};
|
|
28
60
|
const inputs = /* @__PURE__ */ new Map();
|
|
61
|
+
const collections = /* @__PURE__ */ new Map();
|
|
29
62
|
const issues = [];
|
|
30
63
|
for (const [name, value] of Object.entries(raw)) {
|
|
64
|
+
if (Array.isArray(value)) {
|
|
65
|
+
const items = [];
|
|
66
|
+
value.forEach((element, index) => {
|
|
67
|
+
const parsedItem = parseItem(`inputs.${name}[${String(index)}]`, element);
|
|
68
|
+
issues.push(...parsedItem.issues);
|
|
69
|
+
if (parsedItem.item !== void 0) items.push(parsedItem.item);
|
|
70
|
+
});
|
|
71
|
+
collections.set(name, items);
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
31
74
|
const computed = toComputedValue(value);
|
|
32
|
-
if (computed === void 0) issues.push(`inputs.${name}:
|
|
75
|
+
if (computed === void 0) issues.push(`inputs.${name}: ${NOT_A_VALUE}`);
|
|
33
76
|
else inputs.set(name, computed);
|
|
34
77
|
}
|
|
35
78
|
return issues.length === 0 ? {
|
|
36
79
|
ok: true,
|
|
37
|
-
inputs
|
|
80
|
+
inputs,
|
|
81
|
+
collections
|
|
38
82
|
} : {
|
|
39
83
|
ok: false,
|
|
40
84
|
issues
|
|
41
85
|
};
|
|
42
86
|
}
|
|
43
87
|
/**
|
|
44
|
-
* Synchronous resolvers over
|
|
88
|
+
* Synchronous resolvers over named inputs and lists of items. A `reference` whose key is a string resolves to the value of that name: against the top-level inputs outside a `fold`, `some` or `every`, and against the current item alone inside one, since descending into a collection replaces the evaluation context with the item (an item does not see the top-level inputs, so a value an item needs is written into the item). Every other key, and every `lookup`, is `not-found`. `resolveCollection` returns the items the inputs hold under the collection's name, each wrapped so that only the wrapper this module created is read as an item (a list built by the embedder works the same as a parsed one), and throws for a collection the inputs do not hold: an empty list would silently change what a `fold`, `some` or `every` means, and a missing list is a mistake in the tree or the inputs, not an empty collection. `delegate` and `treeReference` nodes are left unresolved, so they are `wrong-type` like any node whose optional resolver is absent.
|
|
45
89
|
*/
|
|
46
|
-
function createInputResolvers(inputs) {
|
|
90
|
+
function createInputResolvers(inputs, collections = /* @__PURE__ */ new Map()) {
|
|
47
91
|
return {
|
|
48
|
-
resolveValue: (key) => {
|
|
49
|
-
const
|
|
92
|
+
resolveValue: (key, context) => {
|
|
93
|
+
const scope = context instanceof ScopedItem ? context.values : inputs;
|
|
94
|
+
const value = typeof key === "string" ? scope.get(key) : void 0;
|
|
50
95
|
return value === void 0 ? { found: false } : {
|
|
51
96
|
found: true,
|
|
52
97
|
value
|
|
@@ -54,7 +99,9 @@ function createInputResolvers(inputs) {
|
|
|
54
99
|
},
|
|
55
100
|
resolveLookup: () => ({ found: false }),
|
|
56
101
|
resolveCollection: (collection) => {
|
|
57
|
-
|
|
102
|
+
const items = typeof collection === "string" ? collections.get(collection) : void 0;
|
|
103
|
+
if (items === void 0) throw new Error(`collection ${JSON.stringify(collection)} cannot be resolved: the inputs hold no list of items under that name`);
|
|
104
|
+
return items.map((values) => new ScopedItem(values));
|
|
58
105
|
}
|
|
59
106
|
};
|
|
60
107
|
}
|
|
@@ -1,19 +1,24 @@
|
|
|
1
1
|
import { t as ComputedValue } from "./computed-value-CbRF0Izc.cjs";
|
|
2
2
|
import { SyncResolvers } from "./resolvers.cjs";
|
|
3
3
|
//#region src/input-resolvers.d.ts
|
|
4
|
+
/** One element of a list input: the named values a `reference` resolves against while a `fold`, `some` or `every` is evaluating that element. */
|
|
5
|
+
export type InputItem = ReadonlyMap<string, ComputedValue>;
|
|
4
6
|
export type InputsParseResult = {
|
|
5
7
|
ok: true;
|
|
8
|
+
/** The named values: every entry that is not an array. */
|
|
6
9
|
inputs: ReadonlyMap<string, ComputedValue>;
|
|
10
|
+
/** The lists of items: every entry that is an array, which a `fold`, `some` or `every` names as its `collection`. */
|
|
11
|
+
collections: ReadonlyMap<string, readonly InputItem[]>;
|
|
7
12
|
} | {
|
|
8
13
|
ok: false;
|
|
9
14
|
issues: readonly string[];
|
|
10
15
|
};
|
|
11
16
|
/**
|
|
12
|
-
* Validates a plain object of named
|
|
17
|
+
* Validates a plain object of inputs and splits it into named values and lists of items. An entry that is an array is a list: every element must be an object of named values (see `toComputedValue` for the accepted shapes of each value), and the list is what a `fold`, `some` or `every` resolves its `collection` to. Any other entry is one named value. Every entry is checked up front, so a malformed input is reported as one by name and position rather than surfacing later as a `not-found` reference.
|
|
13
18
|
*/
|
|
14
19
|
export declare function parseInputs(raw: unknown): InputsParseResult;
|
|
15
20
|
/**
|
|
16
|
-
* Synchronous resolvers over
|
|
21
|
+
* Synchronous resolvers over named inputs and lists of items. A `reference` whose key is a string resolves to the value of that name: against the top-level inputs outside a `fold`, `some` or `every`, and against the current item alone inside one, since descending into a collection replaces the evaluation context with the item (an item does not see the top-level inputs, so a value an item needs is written into the item). Every other key, and every `lookup`, is `not-found`. `resolveCollection` returns the items the inputs hold under the collection's name, each wrapped so that only the wrapper this module created is read as an item (a list built by the embedder works the same as a parsed one), and throws for a collection the inputs do not hold: an empty list would silently change what a `fold`, `some` or `every` means, and a missing list is a mistake in the tree or the inputs, not an empty collection. `delegate` and `treeReference` nodes are left unresolved, so they are `wrong-type` like any node whose optional resolver is absent.
|
|
17
22
|
*/
|
|
18
|
-
export declare function createInputResolvers(inputs: ReadonlyMap<string, ComputedValue>): SyncResolvers;
|
|
23
|
+
export declare function createInputResolvers(inputs: ReadonlyMap<string, ComputedValue>, collections?: ReadonlyMap<string, readonly InputItem[]>): SyncResolvers;
|
|
19
24
|
//#endregion
|
|
@@ -1,19 +1,24 @@
|
|
|
1
1
|
import { t as ComputedValue } from "./computed-value-CbRF0Izc.js";
|
|
2
2
|
import { SyncResolvers } from "./resolvers.js";
|
|
3
3
|
//#region src/input-resolvers.d.ts
|
|
4
|
+
/** One element of a list input: the named values a `reference` resolves against while a `fold`, `some` or `every` is evaluating that element. */
|
|
5
|
+
export type InputItem = ReadonlyMap<string, ComputedValue>;
|
|
4
6
|
export type InputsParseResult = {
|
|
5
7
|
ok: true;
|
|
8
|
+
/** The named values: every entry that is not an array. */
|
|
6
9
|
inputs: ReadonlyMap<string, ComputedValue>;
|
|
10
|
+
/** The lists of items: every entry that is an array, which a `fold`, `some` or `every` names as its `collection`. */
|
|
11
|
+
collections: ReadonlyMap<string, readonly InputItem[]>;
|
|
7
12
|
} | {
|
|
8
13
|
ok: false;
|
|
9
14
|
issues: readonly string[];
|
|
10
15
|
};
|
|
11
16
|
/**
|
|
12
|
-
* Validates a plain object of named
|
|
17
|
+
* Validates a plain object of inputs and splits it into named values and lists of items. An entry that is an array is a list: every element must be an object of named values (see `toComputedValue` for the accepted shapes of each value), and the list is what a `fold`, `some` or `every` resolves its `collection` to. Any other entry is one named value. Every entry is checked up front, so a malformed input is reported as one by name and position rather than surfacing later as a `not-found` reference.
|
|
13
18
|
*/
|
|
14
19
|
export declare function parseInputs(raw: unknown): InputsParseResult;
|
|
15
20
|
/**
|
|
16
|
-
* Synchronous resolvers over
|
|
21
|
+
* Synchronous resolvers over named inputs and lists of items. A `reference` whose key is a string resolves to the value of that name: against the top-level inputs outside a `fold`, `some` or `every`, and against the current item alone inside one, since descending into a collection replaces the evaluation context with the item (an item does not see the top-level inputs, so a value an item needs is written into the item). Every other key, and every `lookup`, is `not-found`. `resolveCollection` returns the items the inputs hold under the collection's name, each wrapped so that only the wrapper this module created is read as an item (a list built by the embedder works the same as a parsed one), and throws for a collection the inputs do not hold: an empty list would silently change what a `fold`, `some` or `every` means, and a missing list is a mistake in the tree or the inputs, not an empty collection. `delegate` and `treeReference` nodes are left unresolved, so they are `wrong-type` like any node whose optional resolver is absent.
|
|
17
22
|
*/
|
|
18
|
-
export declare function createInputResolvers(inputs: ReadonlyMap<string, ComputedValue>): SyncResolvers;
|
|
23
|
+
export declare function createInputResolvers(inputs: ReadonlyMap<string, ComputedValue>, collections?: ReadonlyMap<string, readonly InputItem[]>): SyncResolvers;
|
|
19
24
|
//#endregion
|
package/dist/input-resolvers.js
CHANGED
|
@@ -16,8 +16,40 @@ function toComputedValue(raw) {
|
|
|
16
16
|
const parsed = ComputedValueSchema.safeParse(candidate);
|
|
17
17
|
return parsed.success ? parsed.data : void 0;
|
|
18
18
|
}
|
|
19
|
+
const NOT_A_VALUE = "expected a finite number, text, boolean or a complete computed value";
|
|
19
20
|
/**
|
|
20
|
-
*
|
|
21
|
+
* The evaluation context while a `fold`, `some` or `every` is evaluating one item. `resolveCollection` wraps each element in one of these, and `resolveValue` reads names from an item only when its context is one, so scope follows what the resolver itself handed out and not the identity or shape of anything else. The class is not exported, so no value passed as a context can be mistaken for an item. The guarantee is about this resolver's own `resolveCollection`: a list served by it is scoped, and the supported way to give it lists is the `collections` argument of `createInputResolvers`. An embedder that composes resolvers, spreading these and overriding `resolveCollection` to serve its own items while keeping this `resolveValue`, serves items that are not wrappers, and a fold over them reads names from the top-level inputs; scoping those items is the embedder's responsibility.
|
|
22
|
+
*/
|
|
23
|
+
var ScopedItem = class {
|
|
24
|
+
values;
|
|
25
|
+
constructor(values) {
|
|
26
|
+
this.values = values;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
/** Validates one element of a list input: a plain object whose every entry is a value, each by the same rules as a top-level input. */
|
|
30
|
+
function parseItem(label, raw) {
|
|
31
|
+
if (!isPlainRecord(raw)) return {
|
|
32
|
+
item: void 0,
|
|
33
|
+
issues: [`${label}: expected an object of named values`]
|
|
34
|
+
};
|
|
35
|
+
const item = /* @__PURE__ */ new Map();
|
|
36
|
+
const issues = [];
|
|
37
|
+
for (const [name, value] of Object.entries(raw)) {
|
|
38
|
+
const computed = toComputedValue(value);
|
|
39
|
+
if (computed === void 0) issues.push(`${label}.${name}: ${NOT_A_VALUE}`);
|
|
40
|
+
else item.set(name, computed);
|
|
41
|
+
}
|
|
42
|
+
if (issues.length > 0) return {
|
|
43
|
+
item: void 0,
|
|
44
|
+
issues
|
|
45
|
+
};
|
|
46
|
+
return {
|
|
47
|
+
item,
|
|
48
|
+
issues
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Validates a plain object of inputs and splits it into named values and lists of items. An entry that is an array is a list: every element must be an object of named values (see `toComputedValue` for the accepted shapes of each value), and the list is what a `fold`, `some` or `every` resolves its `collection` to. Any other entry is one named value. Every entry is checked up front, so a malformed input is reported as one by name and position rather than surfacing later as a `not-found` reference.
|
|
21
53
|
*/
|
|
22
54
|
function parseInputs(raw) {
|
|
23
55
|
if (!isPlainRecord(raw)) return {
|
|
@@ -25,27 +57,40 @@ function parseInputs(raw) {
|
|
|
25
57
|
issues: ["inputs must be a JSON object of named values"]
|
|
26
58
|
};
|
|
27
59
|
const inputs = /* @__PURE__ */ new Map();
|
|
60
|
+
const collections = /* @__PURE__ */ new Map();
|
|
28
61
|
const issues = [];
|
|
29
62
|
for (const [name, value] of Object.entries(raw)) {
|
|
63
|
+
if (Array.isArray(value)) {
|
|
64
|
+
const items = [];
|
|
65
|
+
value.forEach((element, index) => {
|
|
66
|
+
const parsedItem = parseItem(`inputs.${name}[${String(index)}]`, element);
|
|
67
|
+
issues.push(...parsedItem.issues);
|
|
68
|
+
if (parsedItem.item !== void 0) items.push(parsedItem.item);
|
|
69
|
+
});
|
|
70
|
+
collections.set(name, items);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
30
73
|
const computed = toComputedValue(value);
|
|
31
|
-
if (computed === void 0) issues.push(`inputs.${name}:
|
|
74
|
+
if (computed === void 0) issues.push(`inputs.${name}: ${NOT_A_VALUE}`);
|
|
32
75
|
else inputs.set(name, computed);
|
|
33
76
|
}
|
|
34
77
|
return issues.length === 0 ? {
|
|
35
78
|
ok: true,
|
|
36
|
-
inputs
|
|
79
|
+
inputs,
|
|
80
|
+
collections
|
|
37
81
|
} : {
|
|
38
82
|
ok: false,
|
|
39
83
|
issues
|
|
40
84
|
};
|
|
41
85
|
}
|
|
42
86
|
/**
|
|
43
|
-
* Synchronous resolvers over
|
|
87
|
+
* Synchronous resolvers over named inputs and lists of items. A `reference` whose key is a string resolves to the value of that name: against the top-level inputs outside a `fold`, `some` or `every`, and against the current item alone inside one, since descending into a collection replaces the evaluation context with the item (an item does not see the top-level inputs, so a value an item needs is written into the item). Every other key, and every `lookup`, is `not-found`. `resolveCollection` returns the items the inputs hold under the collection's name, each wrapped so that only the wrapper this module created is read as an item (a list built by the embedder works the same as a parsed one), and throws for a collection the inputs do not hold: an empty list would silently change what a `fold`, `some` or `every` means, and a missing list is a mistake in the tree or the inputs, not an empty collection. `delegate` and `treeReference` nodes are left unresolved, so they are `wrong-type` like any node whose optional resolver is absent.
|
|
44
88
|
*/
|
|
45
|
-
function createInputResolvers(inputs) {
|
|
89
|
+
function createInputResolvers(inputs, collections = /* @__PURE__ */ new Map()) {
|
|
46
90
|
return {
|
|
47
|
-
resolveValue: (key) => {
|
|
48
|
-
const
|
|
91
|
+
resolveValue: (key, context) => {
|
|
92
|
+
const scope = context instanceof ScopedItem ? context.values : inputs;
|
|
93
|
+
const value = typeof key === "string" ? scope.get(key) : void 0;
|
|
49
94
|
return value === void 0 ? { found: false } : {
|
|
50
95
|
found: true,
|
|
51
96
|
value
|
|
@@ -53,7 +98,9 @@ function createInputResolvers(inputs) {
|
|
|
53
98
|
},
|
|
54
99
|
resolveLookup: () => ({ found: false }),
|
|
55
100
|
resolveCollection: (collection) => {
|
|
56
|
-
|
|
101
|
+
const items = typeof collection === "string" ? collections.get(collection) : void 0;
|
|
102
|
+
if (items === void 0) throw new Error(`collection ${JSON.stringify(collection)} cannot be resolved: the inputs hold no list of items under that name`);
|
|
103
|
+
return items.map((values) => new ScopedItem(values));
|
|
57
104
|
}
|
|
58
105
|
};
|
|
59
106
|
}
|
package/dist-cli/trilean.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { parseArgs } from "node:util";
|
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
import { RegexParseError, compilePattern } from "trilean-regex";
|
|
6
6
|
//#region package.json
|
|
7
|
-
var version = "1.
|
|
7
|
+
var version = "1.9.0";
|
|
8
8
|
//#endregion
|
|
9
9
|
//#region src/computed-value.ts
|
|
10
10
|
/** Dimension symbol -\> exponent, e.g. `{ m: 1, s: -1 }` for metres per second. A bare symbol like `"kg"` is shorthand for `{ kg: 1 }`. */
|
|
@@ -131,6 +131,19 @@ const complexFromPolar = (magnitude, phase, unit) => ({
|
|
|
131
131
|
im: magnitude * Math.sin(phase),
|
|
132
132
|
unit
|
|
133
133
|
});
|
|
134
|
+
/** |z|, as a real number in the same unit the complex value itself carries -- the magnitude of an impedance in ohms is a real quantity in ohms. */
|
|
135
|
+
const complexMagnitude = (value) => ({
|
|
136
|
+
kind: "number",
|
|
137
|
+
value: Math.hypot(value.re, value.im),
|
|
138
|
+
unit: value.unit
|
|
139
|
+
});
|
|
140
|
+
/**
|
|
141
|
+
* arg(z), as a dimensionless real number of radians: an angle is a ratio of two lengths, so it carries no unit of its own regardless of what the value it was read from carried. The range is [-pi, pi]: `Math.atan2` returns -pi for a negative real number whose imaginary part is `-0` and +pi when it is `+0`, although the two are the same number and JSON writes both zeros as `0`, and the closed range is what the result can be because a tiny negative imaginary part also rounds to exactly -pi (`phase(-1 - 1e-17i)` is -pi, the true angle being a hair inside). Adding `+0` turns `-0` into `+0` without changing any other value, so a signed zero never gives -pi: a negative real number is +pi whatever the sign of its zero, and zero is 0.
|
|
142
|
+
*/
|
|
143
|
+
const complexPhase = (value) => ({
|
|
144
|
+
kind: "number",
|
|
145
|
+
value: Math.atan2(value.im + 0, value.re + 0)
|
|
146
|
+
});
|
|
134
147
|
//#endregion
|
|
135
148
|
//#region src/evaluator-effect.ts
|
|
136
149
|
/**
|
|
@@ -1410,11 +1423,11 @@ function roundHalfAwayFromZero(value, places) {
|
|
|
1410
1423
|
return rounded === 0 ? 0 : Math.sign(value) * rounded;
|
|
1411
1424
|
}
|
|
1412
1425
|
/**
|
|
1413
|
-
* The numeric functions a `call` node can name when an embedder has no registry of its own: `minimum` and `maximum` (one or more numbers in a shared unit), `absoluteValue`, `round` (half away from zero, with an optional count of decimal places), `squareRoot`, `exponential`,
|
|
1426
|
+
* The numeric functions a `call` node can name when an embedder has no registry of its own: `minimum` and `maximum` (one or more numbers in a shared unit), `absoluteValue`, `round` (half away from zero, with an optional count of decimal places), `squareRoot`, `exponential`, `logarithm` (natural, or to an optional base), and the two projections of a complex value onto the reals, `magnitude` and `phase`. Every function but those two takes real numbers only, and refuses a complex value; `magnitude` takes a real or a complex number, and `phase` a complex one.
|
|
1414
1427
|
*
|
|
1415
1428
|
* Failures split as the evaluator's own operators split. An argument a function cannot accept at all (the wrong kind, the wrong count, or units that do not fit) is a `wrongType`; an argument of the right kind outside the function's domain (a negative `squareRoot`, a `logarithm` of zero, a base of one, a fractional count of decimal places) or a result that is not a finite number is a `domainError`.
|
|
1416
1429
|
*
|
|
1417
|
-
* Units follow the evaluator's rule that dimensions are never silently converted. `minimum`, `maximum`, `absoluteValue` and `
|
|
1430
|
+
* Units follow the evaluator's rule that dimensions are never silently converted. `minimum`, `maximum`, `absoluteValue`, `round` and `magnitude` keep the argument's unit (and the first two require all arguments to share one); `phase` returns a dimensionless angle in radians in the range [-pi, pi], whatever unit its argument carries, with a negative real number +pi whatever the sign of its zero imaginary part (a signed zero never gives -pi, though a tiny negative imaginary part can round to it) and zero 0 (a component that is not finite is a `domainError`); `squareRoot` halves each dimension's exponent and refuses a unit whose exponents are not all even; `exponential` and `logarithm` accept only dimensionless numbers and return one.
|
|
1418
1431
|
*
|
|
1419
1432
|
* Frozen, so mutating the export cannot change what `evaluateDocument` resolves.
|
|
1420
1433
|
*/
|
|
@@ -1460,6 +1473,22 @@ const builtinFunctions = Object.freeze({
|
|
|
1460
1473
|
if (baseNumber === DECIMAL_BASE) return finiteNumber("logarithm", Math.log10(value.value));
|
|
1461
1474
|
if (baseNumber === BINARY_BASE) return finiteNumber("logarithm", Math.log2(value.value));
|
|
1462
1475
|
return finiteNumber("logarithm", Math.log(value.value) / Math.log(baseNumber));
|
|
1476
|
+
},
|
|
1477
|
+
magnitude: (args) => {
|
|
1478
|
+
const [arg] = args;
|
|
1479
|
+
if (args.length !== 1) return { wrongType: "magnitude requires exactly one argument" };
|
|
1480
|
+
if (arg?.kind === "complex") {
|
|
1481
|
+
const { value, unit } = complexMagnitude(arg);
|
|
1482
|
+
return finiteNumber("magnitude", value, unit);
|
|
1483
|
+
}
|
|
1484
|
+
if (arg?.kind !== "number") return { wrongType: "magnitude requires a number or a complex number" };
|
|
1485
|
+
return finiteNumber("magnitude", Math.abs(arg.value), arg.unit);
|
|
1486
|
+
},
|
|
1487
|
+
phase: (args) => {
|
|
1488
|
+
const [arg] = args;
|
|
1489
|
+
if (args.length !== 1 || arg?.kind !== "complex") return { wrongType: "phase requires exactly one complex argument" };
|
|
1490
|
+
if (!Number.isFinite(arg.re) || !Number.isFinite(arg.im)) return { domainError: "phase requires finite components" };
|
|
1491
|
+
return complexPhase(arg);
|
|
1463
1492
|
}
|
|
1464
1493
|
});
|
|
1465
1494
|
//#endregion
|
|
@@ -1485,8 +1514,40 @@ function toComputedValue(raw) {
|
|
|
1485
1514
|
const parsed = ComputedValueSchema.safeParse(candidate);
|
|
1486
1515
|
return parsed.success ? parsed.data : void 0;
|
|
1487
1516
|
}
|
|
1517
|
+
const NOT_A_VALUE = "expected a finite number, text, boolean or a complete computed value";
|
|
1518
|
+
/**
|
|
1519
|
+
* The evaluation context while a `fold`, `some` or `every` is evaluating one item. `resolveCollection` wraps each element in one of these, and `resolveValue` reads names from an item only when its context is one, so scope follows what the resolver itself handed out and not the identity or shape of anything else. The class is not exported, so no value passed as a context can be mistaken for an item. The guarantee is about this resolver's own `resolveCollection`: a list served by it is scoped, and the supported way to give it lists is the `collections` argument of `createInputResolvers`. An embedder that composes resolvers, spreading these and overriding `resolveCollection` to serve its own items while keeping this `resolveValue`, serves items that are not wrappers, and a fold over them reads names from the top-level inputs; scoping those items is the embedder's responsibility.
|
|
1520
|
+
*/
|
|
1521
|
+
var ScopedItem = class {
|
|
1522
|
+
values;
|
|
1523
|
+
constructor(values) {
|
|
1524
|
+
this.values = values;
|
|
1525
|
+
}
|
|
1526
|
+
};
|
|
1527
|
+
/** Validates one element of a list input: a plain object whose every entry is a value, each by the same rules as a top-level input. */
|
|
1528
|
+
function parseItem(label, raw) {
|
|
1529
|
+
if (!isPlainRecord(raw)) return {
|
|
1530
|
+
item: void 0,
|
|
1531
|
+
issues: [`${label}: expected an object of named values`]
|
|
1532
|
+
};
|
|
1533
|
+
const item = /* @__PURE__ */ new Map();
|
|
1534
|
+
const issues = [];
|
|
1535
|
+
for (const [name, value] of Object.entries(raw)) {
|
|
1536
|
+
const computed = toComputedValue(value);
|
|
1537
|
+
if (computed === void 0) issues.push(`${label}.${name}: ${NOT_A_VALUE}`);
|
|
1538
|
+
else item.set(name, computed);
|
|
1539
|
+
}
|
|
1540
|
+
if (issues.length > 0) return {
|
|
1541
|
+
item: void 0,
|
|
1542
|
+
issues
|
|
1543
|
+
};
|
|
1544
|
+
return {
|
|
1545
|
+
item,
|
|
1546
|
+
issues
|
|
1547
|
+
};
|
|
1548
|
+
}
|
|
1488
1549
|
/**
|
|
1489
|
-
* Validates a plain object of named
|
|
1550
|
+
* Validates a plain object of inputs and splits it into named values and lists of items. An entry that is an array is a list: every element must be an object of named values (see `toComputedValue` for the accepted shapes of each value), and the list is what a `fold`, `some` or `every` resolves its `collection` to. Any other entry is one named value. Every entry is checked up front, so a malformed input is reported as one by name and position rather than surfacing later as a `not-found` reference.
|
|
1490
1551
|
*/
|
|
1491
1552
|
function parseInputs(raw) {
|
|
1492
1553
|
if (!isPlainRecord(raw)) return {
|
|
@@ -1494,27 +1555,40 @@ function parseInputs(raw) {
|
|
|
1494
1555
|
issues: ["inputs must be a JSON object of named values"]
|
|
1495
1556
|
};
|
|
1496
1557
|
const inputs = /* @__PURE__ */ new Map();
|
|
1558
|
+
const collections = /* @__PURE__ */ new Map();
|
|
1497
1559
|
const issues = [];
|
|
1498
1560
|
for (const [name, value] of Object.entries(raw)) {
|
|
1561
|
+
if (Array.isArray(value)) {
|
|
1562
|
+
const items = [];
|
|
1563
|
+
value.forEach((element, index) => {
|
|
1564
|
+
const parsedItem = parseItem(`inputs.${name}[${String(index)}]`, element);
|
|
1565
|
+
issues.push(...parsedItem.issues);
|
|
1566
|
+
if (parsedItem.item !== void 0) items.push(parsedItem.item);
|
|
1567
|
+
});
|
|
1568
|
+
collections.set(name, items);
|
|
1569
|
+
continue;
|
|
1570
|
+
}
|
|
1499
1571
|
const computed = toComputedValue(value);
|
|
1500
|
-
if (computed === void 0) issues.push(`inputs.${name}:
|
|
1572
|
+
if (computed === void 0) issues.push(`inputs.${name}: ${NOT_A_VALUE}`);
|
|
1501
1573
|
else inputs.set(name, computed);
|
|
1502
1574
|
}
|
|
1503
1575
|
return issues.length === 0 ? {
|
|
1504
1576
|
ok: true,
|
|
1505
|
-
inputs
|
|
1577
|
+
inputs,
|
|
1578
|
+
collections
|
|
1506
1579
|
} : {
|
|
1507
1580
|
ok: false,
|
|
1508
1581
|
issues
|
|
1509
1582
|
};
|
|
1510
1583
|
}
|
|
1511
1584
|
/**
|
|
1512
|
-
* Synchronous resolvers over
|
|
1585
|
+
* Synchronous resolvers over named inputs and lists of items. A `reference` whose key is a string resolves to the value of that name: against the top-level inputs outside a `fold`, `some` or `every`, and against the current item alone inside one, since descending into a collection replaces the evaluation context with the item (an item does not see the top-level inputs, so a value an item needs is written into the item). Every other key, and every `lookup`, is `not-found`. `resolveCollection` returns the items the inputs hold under the collection's name, each wrapped so that only the wrapper this module created is read as an item (a list built by the embedder works the same as a parsed one), and throws for a collection the inputs do not hold: an empty list would silently change what a `fold`, `some` or `every` means, and a missing list is a mistake in the tree or the inputs, not an empty collection. `delegate` and `treeReference` nodes are left unresolved, so they are `wrong-type` like any node whose optional resolver is absent.
|
|
1513
1586
|
*/
|
|
1514
|
-
function createInputResolvers(inputs) {
|
|
1587
|
+
function createInputResolvers(inputs, collections = /* @__PURE__ */ new Map()) {
|
|
1515
1588
|
return {
|
|
1516
|
-
resolveValue: (key) => {
|
|
1517
|
-
const
|
|
1589
|
+
resolveValue: (key, context) => {
|
|
1590
|
+
const scope = context instanceof ScopedItem ? context.values : inputs;
|
|
1591
|
+
const value = typeof key === "string" ? scope.get(key) : void 0;
|
|
1518
1592
|
return value === void 0 ? { found: false } : {
|
|
1519
1593
|
found: true,
|
|
1520
1594
|
value
|
|
@@ -1522,7 +1596,9 @@ function createInputResolvers(inputs) {
|
|
|
1522
1596
|
},
|
|
1523
1597
|
resolveLookup: () => ({ found: false }),
|
|
1524
1598
|
resolveCollection: (collection) => {
|
|
1525
|
-
|
|
1599
|
+
const items = typeof collection === "string" ? collections.get(collection) : void 0;
|
|
1600
|
+
if (items === void 0) throw new Error(`collection ${JSON.stringify(collection)} cannot be resolved: the inputs hold no list of items under that name`);
|
|
1601
|
+
return items.map((values) => new ScopedItem(values));
|
|
1526
1602
|
}
|
|
1527
1603
|
};
|
|
1528
1604
|
}
|
|
@@ -1532,7 +1608,7 @@ const predicateKinds = new Set(PredicateNodeSchema.options.map((option) => optio
|
|
|
1532
1608
|
/** What a definite expression result that `ComputedValueSchema` refuses is reported as: the only way a result fails it is a non-finite number, which JSON would write as `null`. The evaluator's arithmetic and the built-in functions already keep one from forming, so this is the last check before a value leaves the document boundary, and it fails loudly rather than print a different value from the one computed. */
|
|
1533
1609
|
const NOT_REPRESENTABLE = "(result): the value is not a finite number";
|
|
1534
1610
|
const AMBIGUOUS_TREE_KIND$1 = "(root): a treeReference is valid as a predicate and as an expression; set `as` to \"predicate\" or \"expression\"";
|
|
1535
|
-
const
|
|
1611
|
+
const defaultEvaluator = createSyncEvaluator({ functions: builtinFunctions });
|
|
1536
1612
|
/** Turns zod's issues into `path: message` lines. A failed union wraps one list of issues per branch, each path relative to the union; the branch the input got furthest into (the deepest path) is the one it was meant to match, so only that branch's issues are reported, under the union's own path. */
|
|
1537
1613
|
function describeIssues(issues, parentPath = []) {
|
|
1538
1614
|
return issues.flatMap((issue) => {
|
|
@@ -1557,16 +1633,22 @@ function resolveTreeKind(tree, requested) {
|
|
|
1557
1633
|
* - `rejected`: nothing was evaluated, because a tree or an input failed validation (`invalid`) or a root `treeReference` was given without `as` (`ambiguous-tree-kind`). `issues` has one `path: message` line per problem.
|
|
1558
1634
|
* - `unrepresentable`: the tree was evaluated and the result is a number JSON cannot carry (`Infinity` or `NaN`), which would otherwise be printed as `null`. The built-in registry never produces one, and the evaluator's arithmetic turns an overflow into a `domain-error`, so this is a guard on the document boundary against a change that stops doing so.
|
|
1559
1635
|
*
|
|
1560
|
-
*
|
|
1636
|
+
* The inputs are validated in full before anything is evaluated, every element of every list included, so a very long list is parsed and held in memory whatever the node budget (`maxNodes`) is.
|
|
1637
|
+
*
|
|
1638
|
+
* Resolution is limited to what `createInputResolvers` provides: named values, and lists of items for a `fold`, `some` or `every`. A tree that names a collection the inputs do not hold throws that resolver's error, which propagates.
|
|
1561
1639
|
*/
|
|
1562
|
-
function evaluateDocument({ tree, inputs, as }) {
|
|
1640
|
+
function evaluateDocument({ tree, inputs, as, maxNodes }) {
|
|
1641
|
+
const evaluator = maxNodes === void 0 ? defaultEvaluator : createSyncEvaluator({
|
|
1642
|
+
functions: builtinFunctions,
|
|
1643
|
+
maxNodes
|
|
1644
|
+
});
|
|
1563
1645
|
const parsedInputs = parseInputs(inputs ?? {});
|
|
1564
1646
|
if (!parsedInputs.ok) return {
|
|
1565
1647
|
outcome: "rejected",
|
|
1566
1648
|
reason: "invalid",
|
|
1567
1649
|
issues: parsedInputs.issues
|
|
1568
1650
|
};
|
|
1569
|
-
const resolvers = createInputResolvers(parsedInputs.inputs);
|
|
1651
|
+
const resolvers = createInputResolvers(parsedInputs.inputs, parsedInputs.collections);
|
|
1570
1652
|
const treeKind = resolveTreeKind(tree, as);
|
|
1571
1653
|
if (treeKind === "ambiguous") return {
|
|
1572
1654
|
outcome: "rejected",
|
|
@@ -1611,23 +1693,39 @@ function evaluateDocument({ tree, inputs, as }) {
|
|
|
1611
1693
|
const AMBIGUOUS_TREE_KIND = "(root): a treeReference is valid as a predicate and as an expression; pass --as predicate or --as expression";
|
|
1612
1694
|
/** The path that stands for standard input. */
|
|
1613
1695
|
const STDIN = "-";
|
|
1614
|
-
const usage = `Usage: trilean evaluate <tree.json> [--inputs <inputs.json>]
|
|
1696
|
+
const usage = `Usage: trilean evaluate <tree.json> [--inputs <inputs.json>]
|
|
1697
|
+
[--as predicate|expression] [--max-nodes <n>]
|
|
1615
1698
|
|
|
1616
1699
|
Evaluates a trilean predicate or expression tree and prints the result as JSON.
|
|
1617
1700
|
|
|
1618
1701
|
<tree.json> the tree, or - to read it from standard input
|
|
1619
1702
|
--inputs <file> a JSON object of named values for \`reference\` nodes: a plain
|
|
1620
1703
|
number, string or boolean, or a complete computed value such
|
|
1621
|
-
as {"kind":"number","value":2,"unit":{"m":1}}
|
|
1704
|
+
as {"kind":"number","value":2,"unit":{"m":1}} or a complex
|
|
1705
|
+
one, {"kind":"complex","re":1,"im":2}. An array of objects of
|
|
1706
|
+
such values is a list of items for a fold, some or every.
|
|
1707
|
+
The inputs are validated in full before evaluation starts
|
|
1622
1708
|
--as <kind> predicate or expression; needed only when the root is a
|
|
1623
1709
|
treeReference, otherwise read from the root's kind
|
|
1710
|
+
--max-nodes <n> the most nodes one evaluation may visit, a positive safe
|
|
1711
|
+
integer; the default is the evaluator's own. A fold visits
|
|
1712
|
+
its combine expression once per item, so a long list can
|
|
1713
|
+
need more. Past the limit the result is indeterminate.
|
|
1714
|
+
Raising it raises the worst-case work, which nested folds
|
|
1715
|
+
multiply, and the limit is the guard against a hostile tree
|
|
1624
1716
|
|
|
1625
|
-
Exit status: 0 for a definite result, 1 for an indeterminate one
|
|
1626
|
-
result was printed: bad usage, an
|
|
1627
|
-
or
|
|
1628
|
-
JSON cannot carry. A lookup, delegate or
|
|
1629
|
-
indeterminate result (1).
|
|
1717
|
+
Exit status: 0 for a definite result, 1 for an indeterminate one (running past
|
|
1718
|
+
the node limit included), 2 when no result was printed: bad usage, an
|
|
1719
|
+
unreadable or invalid file, a tree that folds or quantifies over a list the
|
|
1720
|
+
inputs do not hold, or a result JSON cannot carry. A lookup, delegate or
|
|
1721
|
+
treeReference it cannot resolve is an indeterminate result (1).
|
|
1630
1722
|
`;
|
|
1723
|
+
/** `--max-nodes` takes a positive integer written in plain digits, small enough to be exact. */
|
|
1724
|
+
function parseMaxNodes(text) {
|
|
1725
|
+
if (!/^[1-9]\d*$/.test(text)) return void 0;
|
|
1726
|
+
const value = Number(text);
|
|
1727
|
+
return Number.isSafeInteger(value) ? value : void 0;
|
|
1728
|
+
}
|
|
1631
1729
|
function isTreeKind(value) {
|
|
1632
1730
|
return value === "predicate" || value === "expression";
|
|
1633
1731
|
}
|
|
@@ -1687,6 +1785,9 @@ function run(args, io) {
|
|
|
1687
1785
|
]);
|
|
1688
1786
|
const as = parsed.values.as;
|
|
1689
1787
|
if (as !== void 0 && !isTreeKind(as)) return reject(io, [`--as must be predicate or expression, not ${as}`]);
|
|
1788
|
+
const maxNodesText = parsed.values["max-nodes"];
|
|
1789
|
+
const maxNodes = maxNodesText === void 0 ? void 0 : parseMaxNodes(maxNodesText);
|
|
1790
|
+
if (maxNodesText !== void 0 && maxNodes === void 0) return reject(io, [`--max-nodes must be a positive safe integer, not ${JSON.stringify(maxNodesText)}`]);
|
|
1690
1791
|
const inputsPath = parsed.values.inputs;
|
|
1691
1792
|
if (treePath === STDIN && inputsPath === STDIN) return reject(io, ["the tree and --inputs cannot both be read from standard input"]);
|
|
1692
1793
|
const tree = readJson(io, treePath);
|
|
@@ -1698,7 +1799,8 @@ function run(args, io) {
|
|
|
1698
1799
|
result = evaluateDocument({
|
|
1699
1800
|
tree: tree.value,
|
|
1700
1801
|
inputs: inputs?.value,
|
|
1701
|
-
as
|
|
1802
|
+
as,
|
|
1803
|
+
maxNodes
|
|
1702
1804
|
});
|
|
1703
1805
|
} catch (error) {
|
|
1704
1806
|
return reject(io, [`evaluation could not run: ${error instanceof Error ? error.message : String(error)}`]);
|
|
@@ -1715,6 +1817,7 @@ function parseCommandLine(args) {
|
|
|
1715
1817
|
options: {
|
|
1716
1818
|
as: { type: "string" },
|
|
1717
1819
|
inputs: { type: "string" },
|
|
1820
|
+
"max-nodes": { type: "string" },
|
|
1718
1821
|
help: {
|
|
1719
1822
|
type: "boolean",
|
|
1720
1823
|
short: "h"
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "trilean",
|
|
3
3
|
"description": "Three-valued predicate and expression evaluation trees, stored as JSON and evaluated against injected resolvers, for domain logic — business rules, eligibility checks, formulas, search filters, and more — that needs to be data instead of code.",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.9.0",
|
|
5
5
|
"bin": {
|
|
6
6
|
"trilean": "./dist-cli/trilean.mjs"
|
|
7
7
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"$defs":{"ExpressionNode":{"anyOf":[{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"numberLiteral","type":"string"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"},"value":{"type":"number"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"textLiteral","type":"string"},"value":{"type":"string"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"booleanLiteral","type":"string"},"value":{"type":"boolean"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"instantLiteral","type":"string"},"value":{"type":"string"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"durationLiteral","type":"string"},"unit":{"enum":["ms","s","min","h","d"],"type":"string"},"value":{"type":"number"}},"required":["kind","value","unit"],"type":"object"},{"additionalProperties":false,"properties":{"key":{"$ref":"#/$defs/schema0"},"kind":{"const":"reference","type":"string"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"}},"required":["kind","key"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"arithmetic","type":"string"},"left":{"$ref":"#/$defs/ExpressionNode"},"op":{"enum":["add","subtract","multiply","divide","power","modulo"],"type":"string"},"right":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"negate","type":"string"},"operand":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","operand"],"type":"object"},{"additionalProperties":false,"properties":{"args":{"items":{"$ref":"#/$defs/ExpressionNode"},"type":"array"},"fn":{"type":"string"},"kind":{"const":"call","type":"string"}},"required":["kind","fn","args"],"type":"object"},{"additionalProperties":false,"properties":{"keys":{"items":{"$ref":"#/$defs/ExpressionNode"},"type":"array"},"kind":{"const":"lookup","type":"string"},"table":{"$ref":"#/$defs/schema0"}},"required":["kind","table","keys"],"type":"object"},{"additionalProperties":false,"properties":{"cases":{"items":{"additionalProperties":false,"properties":{"then":{"$ref":"#/$defs/ExpressionNode"},"when":{"$ref":"#/$defs/PredicateNode"}},"required":["when","then"],"type":"object"},"type":"array"},"fallback":{"$ref":"#/$defs/ExpressionNode"},"hitPolicy":{"enum":["first","unique"],"type":"string"},"kind":{"const":"conditional","type":"string"}},"required":["kind","cases","fallback"],"type":"object"},{"additionalProperties":false,"properties":{"collection":{"$ref":"#/$defs/schema0"},"combiner":{"oneOf":[{"additionalProperties":false,"properties":{"item":{"$ref":"#/$defs/ExpressionNode"},"mode":{"const":"max","type":"string"}},"required":["mode","item"],"type":"object"},{"additionalProperties":false,"properties":{"item":{"$ref":"#/$defs/ExpressionNode"},"mode":{"const":"min","type":"string"}},"required":["mode","item"],"type":"object"},{"additionalProperties":false,"properties":{"combine":{"$ref":"#/$defs/ExpressionNode"},"initial":{"$ref":"#/$defs/ExpressionNode"},"mode":{"const":"reduce","type":"string"}},"required":["mode","initial","combine"],"type":"object"}]},"filter":{"$ref":"#/$defs/PredicateNode"},"kind":{"const":"fold","type":"string"}},"required":["kind","collection","combiner"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"accumulator","type":"string"}},"required":["kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"delegate","type":"string"},"payload":{"$ref":"#/$defs/schema0"},"system":{"type":"string"}},"required":["kind","system","payload"],"type":"object"},{"additionalProperties":false,"properties":{"key":{"$ref":"#/$defs/schema0"},"kind":{"const":"treeReference","type":"string"}},"required":["kind","key"],"type":"object"}]},{"anyOf":[{"additionalProperties":false,"properties":{"im":{"type":"number"},"kind":{"const":"complexLiteral","type":"string"},"re":{"type":"number"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"}},"required":["kind","re","im"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"complexLiteral","type":"string"},"magnitude":{"type":"number"},"phase":{"type":"number"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"}},"required":["kind","magnitude","phase"],"type":"object"}]}]},"PredicateNode":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"not","type":"string"},"operand":{"$ref":"#/$defs/PredicateNode"}},"required":["kind","operand"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"and","type":"string"},"left":{"$ref":"#/$defs/PredicateNode"},"right":{"$ref":"#/$defs/PredicateNode"}},"required":["kind","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"or","type":"string"},"left":{"$ref":"#/$defs/PredicateNode"},"right":{"$ref":"#/$defs/PredicateNode"}},"required":["kind","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"allOf","type":"string"},"operands":{"items":{"$ref":"#/$defs/PredicateNode"},"type":"array"}},"required":["kind","operands"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"anyOf","type":"string"},"operands":{"items":{"$ref":"#/$defs/PredicateNode"},"type":"array"}},"required":["kind","operands"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"compare","type":"string"},"left":{"$ref":"#/$defs/ExpressionNode"},"op":{"enum":["gt","gte","lt","lte","eq","neq"],"type":"string"},"right":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"textCompare","type":"string"},"left":{"$ref":"#/$defs/ExpressionNode"},"op":{"enum":["equals","notEquals","matches","notMatches","portableMatches","portableNotMatches"],"type":"string"},"right":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"candidates":{"items":{"$ref":"#/$defs/ExpressionNode"},"type":"array"},"kind":{"const":"memberOf","type":"string"},"op":{"enum":["in","notIn"],"type":"string"},"operand":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","operand","candidates"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"exists","type":"string"},"operand":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","operand"],"type":"object"},{"additionalProperties":false,"properties":{"collection":{"$ref":"#/$defs/schema0"},"filter":{"$ref":"#/$defs/PredicateNode"},"item":{"$ref":"#/$defs/PredicateNode"},"kind":{"const":"some","type":"string"}},"required":["kind","collection","item"],"type":"object"},{"additionalProperties":false,"properties":{"collection":{"$ref":"#/$defs/schema0"},"filter":{"$ref":"#/$defs/PredicateNode"},"item":{"$ref":"#/$defs/PredicateNode"},"kind":{"const":"every","type":"string"}},"required":["kind","collection","item"],"type":"object"},{"additionalProperties":false,"properties":{"key":{"$ref":"#/$defs/schema0"},"kind":{"const":"treeReference","type":"string"}},"required":["kind","key"],"type":"object"}]},"schema0":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"},{"items":{"$ref":"#/$defs/schema0"},"type":"array"},{"additionalProperties":{"$ref":"#/$defs/schema0"},"propertyNames":{"type":"string"},"type":"object"}]}},"$id":"https://cdn.jsdelivr.net/npm/trilean@1.
|
|
1
|
+
{"$defs":{"ExpressionNode":{"anyOf":[{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"numberLiteral","type":"string"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"},"value":{"type":"number"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"textLiteral","type":"string"},"value":{"type":"string"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"booleanLiteral","type":"string"},"value":{"type":"boolean"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"instantLiteral","type":"string"},"value":{"type":"string"}},"required":["kind","value"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"durationLiteral","type":"string"},"unit":{"enum":["ms","s","min","h","d"],"type":"string"},"value":{"type":"number"}},"required":["kind","value","unit"],"type":"object"},{"additionalProperties":false,"properties":{"key":{"$ref":"#/$defs/schema0"},"kind":{"const":"reference","type":"string"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"}},"required":["kind","key"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"arithmetic","type":"string"},"left":{"$ref":"#/$defs/ExpressionNode"},"op":{"enum":["add","subtract","multiply","divide","power","modulo"],"type":"string"},"right":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"negate","type":"string"},"operand":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","operand"],"type":"object"},{"additionalProperties":false,"properties":{"args":{"items":{"$ref":"#/$defs/ExpressionNode"},"type":"array"},"fn":{"type":"string"},"kind":{"const":"call","type":"string"}},"required":["kind","fn","args"],"type":"object"},{"additionalProperties":false,"properties":{"keys":{"items":{"$ref":"#/$defs/ExpressionNode"},"type":"array"},"kind":{"const":"lookup","type":"string"},"table":{"$ref":"#/$defs/schema0"}},"required":["kind","table","keys"],"type":"object"},{"additionalProperties":false,"properties":{"cases":{"items":{"additionalProperties":false,"properties":{"then":{"$ref":"#/$defs/ExpressionNode"},"when":{"$ref":"#/$defs/PredicateNode"}},"required":["when","then"],"type":"object"},"type":"array"},"fallback":{"$ref":"#/$defs/ExpressionNode"},"hitPolicy":{"enum":["first","unique"],"type":"string"},"kind":{"const":"conditional","type":"string"}},"required":["kind","cases","fallback"],"type":"object"},{"additionalProperties":false,"properties":{"collection":{"$ref":"#/$defs/schema0"},"combiner":{"oneOf":[{"additionalProperties":false,"properties":{"item":{"$ref":"#/$defs/ExpressionNode"},"mode":{"const":"max","type":"string"}},"required":["mode","item"],"type":"object"},{"additionalProperties":false,"properties":{"item":{"$ref":"#/$defs/ExpressionNode"},"mode":{"const":"min","type":"string"}},"required":["mode","item"],"type":"object"},{"additionalProperties":false,"properties":{"combine":{"$ref":"#/$defs/ExpressionNode"},"initial":{"$ref":"#/$defs/ExpressionNode"},"mode":{"const":"reduce","type":"string"}},"required":["mode","initial","combine"],"type":"object"}]},"filter":{"$ref":"#/$defs/PredicateNode"},"kind":{"const":"fold","type":"string"}},"required":["kind","collection","combiner"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"accumulator","type":"string"}},"required":["kind"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"delegate","type":"string"},"payload":{"$ref":"#/$defs/schema0"},"system":{"type":"string"}},"required":["kind","system","payload"],"type":"object"},{"additionalProperties":false,"properties":{"key":{"$ref":"#/$defs/schema0"},"kind":{"const":"treeReference","type":"string"}},"required":["kind","key"],"type":"object"}]},{"anyOf":[{"additionalProperties":false,"properties":{"im":{"type":"number"},"kind":{"const":"complexLiteral","type":"string"},"re":{"type":"number"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"}},"required":["kind","re","im"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"complexLiteral","type":"string"},"magnitude":{"type":"number"},"phase":{"type":"number"},"unit":{"additionalProperties":{"type":"number"},"propertyNames":{"type":"string"},"type":"object"}},"required":["kind","magnitude","phase"],"type":"object"}]}]},"PredicateNode":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"not","type":"string"},"operand":{"$ref":"#/$defs/PredicateNode"}},"required":["kind","operand"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"and","type":"string"},"left":{"$ref":"#/$defs/PredicateNode"},"right":{"$ref":"#/$defs/PredicateNode"}},"required":["kind","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"or","type":"string"},"left":{"$ref":"#/$defs/PredicateNode"},"right":{"$ref":"#/$defs/PredicateNode"}},"required":["kind","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"allOf","type":"string"},"operands":{"items":{"$ref":"#/$defs/PredicateNode"},"type":"array"}},"required":["kind","operands"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"anyOf","type":"string"},"operands":{"items":{"$ref":"#/$defs/PredicateNode"},"type":"array"}},"required":["kind","operands"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"compare","type":"string"},"left":{"$ref":"#/$defs/ExpressionNode"},"op":{"enum":["gt","gte","lt","lte","eq","neq"],"type":"string"},"right":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"textCompare","type":"string"},"left":{"$ref":"#/$defs/ExpressionNode"},"op":{"enum":["equals","notEquals","matches","notMatches","portableMatches","portableNotMatches"],"type":"string"},"right":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","left","right"],"type":"object"},{"additionalProperties":false,"properties":{"candidates":{"items":{"$ref":"#/$defs/ExpressionNode"},"type":"array"},"kind":{"const":"memberOf","type":"string"},"op":{"enum":["in","notIn"],"type":"string"},"operand":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","op","operand","candidates"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"exists","type":"string"},"operand":{"$ref":"#/$defs/ExpressionNode"}},"required":["kind","operand"],"type":"object"},{"additionalProperties":false,"properties":{"collection":{"$ref":"#/$defs/schema0"},"filter":{"$ref":"#/$defs/PredicateNode"},"item":{"$ref":"#/$defs/PredicateNode"},"kind":{"const":"some","type":"string"}},"required":["kind","collection","item"],"type":"object"},{"additionalProperties":false,"properties":{"collection":{"$ref":"#/$defs/schema0"},"filter":{"$ref":"#/$defs/PredicateNode"},"item":{"$ref":"#/$defs/PredicateNode"},"kind":{"const":"every","type":"string"}},"required":["kind","collection","item"],"type":"object"},{"additionalProperties":false,"properties":{"key":{"$ref":"#/$defs/schema0"},"kind":{"const":"treeReference","type":"string"}},"required":["kind","key"],"type":"object"}]},"schema0":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"},{"items":{"$ref":"#/$defs/schema0"},"type":"array"},{"additionalProperties":{"$ref":"#/$defs/schema0"},"propertyNames":{"type":"string"},"type":"object"}]}},"$id":"https://cdn.jsdelivr.net/npm/trilean@1.9.0/schemas/trilean.schema.json","$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"$ref":"#/$defs/PredicateNode"},{"$ref":"#/$defs/ExpressionNode"}]}
|