trilean 1.7.12 → 1.8.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.
Files changed (50) hide show
  1. package/README.md +33 -13
  2. package/dist/builtin-functions.cjs +129 -0
  3. package/dist/builtin-functions.d.cts +13 -0
  4. package/dist/builtin-functions.d.ts +13 -0
  5. package/dist/builtin-functions.js +128 -0
  6. package/dist/complex-division.cjs +48 -0
  7. package/dist/complex-division.d.cts +25 -0
  8. package/dist/complex-division.d.ts +25 -0
  9. package/dist/complex-division.js +47 -0
  10. package/dist/duration-order.cjs +84 -0
  11. package/dist/duration-order.d.cts +22 -0
  12. package/dist/duration-order.d.ts +22 -0
  13. package/dist/duration-order.js +82 -0
  14. package/dist/evaluate-document.cjs +87 -0
  15. package/dist/evaluate-document.d.cts +40 -0
  16. package/dist/evaluate-document.d.ts +40 -0
  17. package/dist/evaluate-document.js +86 -0
  18. package/dist/evaluator-collection.d.cts +1 -1
  19. package/dist/evaluator-collection.d.ts +1 -1
  20. package/dist/evaluator-factory.d.cts +1 -1
  21. package/dist/evaluator-factory.d.ts +1 -1
  22. package/dist/evaluator-indeterminacy-helpers.d.cts +1 -1
  23. package/dist/evaluator-indeterminacy-helpers.d.ts +1 -1
  24. package/dist/evaluator-operations.cjs +75 -24
  25. package/dist/evaluator-operations.d.cts +3 -3
  26. package/dist/evaluator-operations.d.ts +3 -3
  27. package/dist/evaluator-operations.js +74 -23
  28. package/dist/evaluator.d.cts +1 -1
  29. package/dist/evaluator.d.ts +1 -1
  30. package/dist/functions.d.cts +8 -4
  31. package/dist/functions.d.ts +8 -4
  32. package/dist/index.cjs +8 -1
  33. package/dist/index.d.cts +5 -2
  34. package/dist/index.d.ts +5 -2
  35. package/dist/index.js +5 -2
  36. package/dist/input-resolvers.cjs +63 -0
  37. package/dist/input-resolvers.d.cts +19 -0
  38. package/dist/input-resolvers.d.ts +19 -0
  39. package/dist/input-resolvers.js +61 -0
  40. package/dist/integer-power.cjs +20 -0
  41. package/dist/integer-power.d.cts +13 -0
  42. package/dist/integer-power.d.ts +13 -0
  43. package/dist/integer-power.js +19 -0
  44. package/dist/plain-record.cjs +8 -0
  45. package/dist/plain-record.d.cts +4 -0
  46. package/dist/plain-record.d.ts +4 -0
  47. package/dist/plain-record.js +7 -0
  48. package/dist-cli/trilean.mjs +1745 -0
  49. package/package.json +5 -1
  50. package/schemas/trilean.schema.json +1 -1
@@ -0,0 +1,1745 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { parseArgs } from "node:util";
4
+ import { z } from "zod";
5
+ import { RegexParseError, compilePattern } from "trilean-regex";
6
+ //#region package.json
7
+ var version = "1.8.0";
8
+ //#endregion
9
+ //#region src/computed-value.ts
10
+ /** Dimension symbol -\> exponent, e.g. `{ m: 1, s: -1 }` for metres per second. A bare symbol like `"kg"` is shorthand for `{ kg: 1 }`. */
11
+ const UnitSchema = z.record(z.string(), z.number());
12
+ const DurationUnitSchema = z.enum([
13
+ "ms",
14
+ "s",
15
+ "min",
16
+ "h",
17
+ "d"
18
+ ]);
19
+ const ComputedValueSchema = z.discriminatedUnion("kind", [
20
+ z.object({
21
+ kind: z.literal("number"),
22
+ value: z.number(),
23
+ unit: UnitSchema.optional()
24
+ }),
25
+ z.object({
26
+ kind: z.literal("text"),
27
+ value: z.string()
28
+ }),
29
+ z.object({
30
+ kind: z.literal("boolean"),
31
+ value: z.boolean()
32
+ }),
33
+ z.object({
34
+ kind: z.literal("instant"),
35
+ value: z.string()
36
+ }),
37
+ z.object({
38
+ kind: z.literal("duration"),
39
+ value: z.number(),
40
+ unit: DurationUnitSchema
41
+ }),
42
+ z.object({
43
+ kind: z.literal("complex"),
44
+ re: z.number(),
45
+ im: z.number(),
46
+ unit: UnitSchema.optional()
47
+ })
48
+ ]);
49
+ /** Drops zero-exponent dimensions so that, e.g., dividing a unit by itself normalises to the same dimensionless `{}` as an absent unit -- without this, `{ m: 0 }` and `{}` would compare unequal despite representing the same dimension. */
50
+ function normalizeUnit(unit) {
51
+ if (unit === void 0) return {};
52
+ const normalized = {};
53
+ for (const [dimension, exponent] of Object.entries(unit)) if (exponent !== 0) normalized[dimension] = exponent;
54
+ return normalized;
55
+ }
56
+ /** An operand with no `unit` is dimensionless (an empty map) for comparison purposes. */
57
+ function unitsEqual(a, b) {
58
+ const normalizedA = normalizeUnit(a);
59
+ const normalizedB = normalizeUnit(b);
60
+ const dimensionsA = Object.keys(normalizedA);
61
+ const dimensionsB = Object.keys(normalizedB);
62
+ if (dimensionsA.length !== dimensionsB.length) return false;
63
+ return dimensionsA.every((dimension) => normalizedA[dimension] === normalizedB[dimension]);
64
+ }
65
+ /** Multiplying two unit-tagged numbers adds exponents per dimension. An operand with no `unit` is treated as dimensionless (an empty map). */
66
+ function combineUnitsForMultiply(a, b) {
67
+ const normalizedA = normalizeUnit(a);
68
+ const normalizedB = normalizeUnit(b);
69
+ const combined = { ...normalizedA };
70
+ for (const [dimension, exponent] of Object.entries(normalizedB)) combined[dimension] = (combined[dimension] ?? 0) + exponent;
71
+ return normalizeUnit(combined);
72
+ }
73
+ /** Dividing two unit-tagged numbers subtracts exponents per dimension. An operand with no `unit` is treated as dimensionless (an empty map). */
74
+ function combineUnitsForDivide(a, b) {
75
+ const normalizedA = normalizeUnit(a);
76
+ const normalizedB = normalizeUnit(b);
77
+ const combined = { ...normalizedA };
78
+ for (const [dimension, exponent] of Object.entries(normalizedB)) combined[dimension] = (combined[dimension] ?? 0) - exponent;
79
+ return normalizeUnit(combined);
80
+ }
81
+ z.object({
82
+ /** Which of the three reason categories applies. */
83
+ code: z.enum([
84
+ "not-found",
85
+ "wrong-type",
86
+ "domain-error"
87
+ ]),
88
+ /** A human-readable explanation, for logging and debugging. */
89
+ message: z.string()
90
+ });
91
+ function definite(value) {
92
+ return {
93
+ status: "definite",
94
+ value
95
+ };
96
+ }
97
+ function indeterminate(code, message) {
98
+ return {
99
+ status: "indeterminate",
100
+ reason: {
101
+ code,
102
+ message
103
+ }
104
+ };
105
+ }
106
+ /**
107
+ * Implements the tie-break rule from "The evaluation model": when several sub-evaluations could each independently be indeterminate for a different reason, take the first indeterminate reason encountered in the node's own declared operand order. Entries that are `undefined` (an operand not yet evaluated, or not applicable to this node kind) are skipped rather than treated as indeterminate.
108
+ */
109
+ function firstIndeterminate(...results) {
110
+ for (const result of results) if (result?.status === "indeterminate") return result.reason;
111
+ }
112
+ //#endregion
113
+ //#region src/evaluator-budget.ts
114
+ /** Default cap on the total number of predicate/expression nodes a single `evaluatePredicate`/`evaluateValue` call may visit -- see `createEvaluator`'s `maxNodes` option, threaded through to `createEvaluationBudget` below. Chosen generously above any realistic hand-authored business-rule, eligibility, or formula tree (see README.md's own consumer use cases), while still bounding an untrusted, adversarially-authored tree's total evaluation cost to a fixed, small amount of work regardless of how it is shaped. */
115
+ const DEFAULT_MAX_EVALUATION_NODES = 1e4;
116
+ /** Constructs a fresh `EvaluationBudget` for one top-level `evaluatePredicate`/`evaluateValue` call -- see `createEvaluator`'s `maxNodes`/`maxNestingDepth` options, which supply `maxNodes`/`maxNestingDepth` here. A fresh closure per call is what keeps `nodesVisited` from leaking between unrelated evaluations. */
117
+ function createEvaluationBudget(maxNodes, maxNestingDepth) {
118
+ /** Total predicate/expression nodes visited so far across the whole call -- shared by every branch of an `and`/`or`/`allOf`/`anyOf`/fold/quantifier through the closure below, so it accumulates across the whole traversal rather than resetting per branch. */
119
+ let nodesVisited = 0;
120
+ return { checkNode(nestingDepth) {
121
+ nodesVisited += 1;
122
+ if (nodesVisited > maxNodes) return indeterminate("domain-error", `evaluation exceeded the maximum of ${maxNodes.toString()} nodes visited in a single call (resource exhausted)`);
123
+ if (nestingDepth >= maxNestingDepth) return indeterminate("domain-error", `evaluation nesting depth exceeds the maximum of ${maxNestingDepth.toString()} (resource exhausted)`);
124
+ } };
125
+ }
126
+ //#endregion
127
+ //#region src/complex.ts
128
+ const complexFromPolar = (magnitude, phase, unit) => ({
129
+ kind: "complex",
130
+ re: magnitude * Math.cos(phase),
131
+ im: magnitude * Math.sin(phase),
132
+ unit
133
+ });
134
+ //#endregion
135
+ //#region src/evaluator-effect.ts
136
+ /**
137
+ * Suspends until `value` is available. The driver resumes the task with exactly that value (awaited, in the async driver), and the generator's own "next" type is `T`, so the result is typed without an assertion.
138
+ */
139
+ function* wait(value) {
140
+ return yield {
141
+ kind: "wait",
142
+ value
143
+ };
144
+ }
145
+ /**
146
+ * Suspends until every task has finished and returns their results in order. The tasks are independent of one another by construction, so a driver may interleave them (async) or run them in sequence (sync).
147
+ */
148
+ function* all(tasks) {
149
+ return yield {
150
+ kind: "all",
151
+ tasks
152
+ };
153
+ }
154
+ function isThenable(value) {
155
+ return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
156
+ }
157
+ /** Runs a task to completion, awaiting each suspension and running an `all` group's tasks concurrently. */
158
+ async function runAsync(task) {
159
+ let step = task.next();
160
+ while (step.done !== true) {
161
+ const suspension = step.value;
162
+ const result = suspension.kind === "wait" ? await suspension.value : await Promise.all(suspension.tasks.map(runAsync));
163
+ step = task.next(result);
164
+ }
165
+ return step.value;
166
+ }
167
+ /**
168
+ * Runs a task to completion without awaiting anything: an `all` group's tasks run one after another, and a `wait` on a promise throws, since a synchronous evaluator has nothing to do with one.
169
+ */
170
+ function runSync(task) {
171
+ let step = task.next();
172
+ while (step.done !== true) {
173
+ const suspension = step.value;
174
+ let result;
175
+ if (suspension.kind === "wait") {
176
+ if (isThenable(suspension.value)) throw new TypeError("a resolver supplied to a synchronous evaluator returned a promise; use the asynchronous evaluator for asynchronous resolvers");
177
+ result = suspension.value;
178
+ } else result = suspension.tasks.map(runSync);
179
+ step = task.next(result);
180
+ }
181
+ return step.value;
182
+ }
183
+ //#endregion
184
+ //#region src/evaluator-collection.ts
185
+ /**
186
+ * Collection resolution shared by the quantifiers (`some`/`every`) and by `fold` in evaluator.ts: resolves the opaque `collection` reference to its concrete candidate list via `resolvers.resolveCollection`, then evaluates each candidate's optional `filter` (via the injected `evaluatePredicate`, see `EvaluatePredicate`'s own doc comment) with that candidate as its own evaluation context and the accumulator reset to `undefined` -- see the README's "Evaluation context" and "Pre-filtering which items participate" sections. Deliberately stops short of deciding how an indeterminate filter combines with the rest of the surrounding node: `some`/`every` fold a filter-indeterminate item in as its own vote via the surrounding OR/AND absorption, while `fold` has no absorbing value at all and goes indeterminate outright on the same condition -- the two callers need genuinely different combination logic over these same per-item outcomes, so this helper only produces the outcomes and leaves combining them to the caller.
187
+ */
188
+ function* resolveParticipatingItems(evaluatePredicate, collection, filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth) {
189
+ return yield* all((yield* wait(resolvers.resolveCollection(collection, context))).map(function* (item) {
190
+ if (filter === void 0) return {
191
+ item,
192
+ filterOutcome: "include"
193
+ };
194
+ const filterResult = yield* evaluatePredicate(filter, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
195
+ if (filterResult.status === "indeterminate") return {
196
+ item,
197
+ filterOutcome: filterResult
198
+ };
199
+ return {
200
+ item,
201
+ filterOutcome: filterResult.value ? "include" : "exclude"
202
+ };
203
+ }));
204
+ }
205
+ /** The first participating item (in declared collection order) whose `filter` evaluation was itself indeterminate, or `undefined` if every participating item's filter resolved definitely -- a filter-excluded item's own `"exclude"` outcome never counts here. Used only by `fold`, which -- unlike `some`/`every`'s OR/AND absorption -- has no absorbing value at all: any participating item's indeterminate filter makes the whole fold indeterminate outright, with no other item's outcome able to override it. */
206
+ function firstFilterIndeterminate(participating) {
207
+ for (const { filterOutcome } of participating) {
208
+ if (filterOutcome === "include" || filterOutcome === "exclude") continue;
209
+ if (filterOutcome.status === "indeterminate") return filterOutcome.reason;
210
+ }
211
+ }
212
+ //#endregion
213
+ //#region src/complex-division.ts
214
+ /**
215
+ * `value * 2 ** exponent`, applied in two halves because `2 ** exponent` is infinite beyond 1023 and a quotient can need a shift of about twice that. A power of two multiplies a double exactly while the result stays normal, so when the result can be non-zero and finite (a shift between about -1077 and 1024 for a scaled quotient of order one) each half is at most about 540 in magnitude, the first multiplication is exact, and the second rounds only where the result is subnormal. Outside that range the result overflows or is below the smallest subnormal: a non-zero value gives an infinity or zero, which is correct, and a zero value with a shift of 2047 or more gives NaN (zero times an infinite half), which the caller's finite check treats as it does an infinity.
216
+ */
217
+ function scaleByPowerOfTwo(value, exponent) {
218
+ const firstHalf = Math.trunc(exponent / 2);
219
+ return value * 2 ** firstHalf * 2 ** (exponent - firstHalf);
220
+ }
221
+ /** The exponent of the power of two that brings a magnitude to between a quarter and a half, which this file calls about a quarter. `Math.log2` is rounded, so for a magnitude just under a power of two it can return that power itself and the result lands just under a quarter instead. The magnitude must be non-zero. */
222
+ function scaleToAboutAQuarter(larger) {
223
+ return -Math.floor(Math.log2(larger)) - 2;
224
+ }
225
+ /**
226
+ * The components of `dividend / divisor` for a non-zero divisor.
227
+ *
228
+ * The textbook route multiplies both sides by the divisor's conjugate and divides by `re^2 + im^2`, which overflows for a divisor near the top of the range and underflows for one near the bottom, even when the quotient is an ordinary number. Smith's algorithm avoids that for ordinary operands but still overflows its denominator or numerator above about 9e307 and loses accuracy for subnormal divisors, giving a wrong finite answer (zero for a quotient of about 0.07) rather than an error.
229
+ *
230
+ * Here the divisor is multiplied by a power of two that brings its larger component to about a quarter, and the dividend by its own power of two that does the same for its larger component. The conjugate formula then runs on those two scaled values. Its largest product is of order one (the two larger components multiplied), so nothing in it overflows, and a product that underflows belongs to a smaller component and is negligible beside the larger terms.
231
+ *
232
+ * The scaled quotient is the true quotient multiplied by `2 ** (dividendScale - divisorScale)`: for a dividend of 8 (scale -5, scaled to 0.25) and a divisor of 1 (scale -2, scaled to 0.25) the scaled quotient is 1, and the true quotient 8 is 1 times `2 ** 3`. The result is therefore the scaled quotient multiplied by `2 ** (divisorScale - dividendScale)`, applied once at the end. For a quotient in the subnormal range that multiplication is the only rounding of the larger components beyond the formula's own few.
233
+ *
234
+ * Accuracy: where the quotient is a normal number the error over the pair is a few units of 2^-53 (the measured worst case over a large exact-rational check is under 4), and a component much smaller than the other is accurate relative to the larger one, not to itself. Where the quotient lies in the subnormal range, results are within a few spacings of the true value (the measured worst case is under 5), not correctly rounded. A quotient too large for a double comes out with a non-finite component (an infinity, or NaN when the other component is zero), left to the caller's finite check; one below about half the smallest subnormal comes out as zero. Both thresholds are fuzzy by that error near the edge: measured, a true quotient up to about 2 ulps above the largest double came back finite, and a representable one a little over 1 ulp below it was reported as an overflow.
235
+ *
236
+ * A zero dividend gives zero in both components without regard to the signs of its zeros, so `-0` is not preserved; that is visible only through `Object.is` on this function's result, not through JSON, `compare` or `memberOf`.
237
+ */
238
+ function divideComplexComponents(dividend, divisor) {
239
+ const largerDividend = Math.max(Math.abs(dividend.re), Math.abs(dividend.im));
240
+ if (largerDividend === 0) return {
241
+ re: 0,
242
+ im: 0
243
+ };
244
+ const largerDivisor = Math.max(Math.abs(divisor.re), Math.abs(divisor.im));
245
+ const dividendScale = scaleToAboutAQuarter(largerDividend);
246
+ const divisorScale = scaleToAboutAQuarter(largerDivisor);
247
+ const a = scaleByPowerOfTwo(dividend.re, dividendScale);
248
+ const b = scaleByPowerOfTwo(dividend.im, dividendScale);
249
+ const c = scaleByPowerOfTwo(divisor.re, divisorScale);
250
+ const d = scaleByPowerOfTwo(divisor.im, divisorScale);
251
+ const denominator = c * c + d * d;
252
+ const shift = divisorScale - dividendScale;
253
+ return {
254
+ re: scaleByPowerOfTwo((a * c + b * d) / denominator, shift),
255
+ im: scaleByPowerOfTwo((b * c - a * d) / denominator, shift)
256
+ };
257
+ }
258
+ //#endregion
259
+ //#region src/duration-order.ts
260
+ /** How many milliseconds one of each duration unit is. Every unit is a whole multiple of every finer one, which is what lets a value be divided down into a coarser unit by an exact integer. */
261
+ const millisecondsPerDurationUnit = {
262
+ ms: 1,
263
+ s: 1e3,
264
+ min: 6e4,
265
+ h: 36e5,
266
+ d: 864e5
267
+ };
268
+ const ONE = 1n;
269
+ const FRACTION_BITS = 52n;
270
+ const FRACTION_MASK = (ONE << FRACTION_BITS) - ONE;
271
+ const IMPLICIT_LEADING_BIT = ONE << FRACTION_BITS;
272
+ const EXPONENT_FIELD_MASK = 2047n;
273
+ const EXPONENT_BIAS_WITH_FRACTION = 1075;
274
+ const SUBNORMAL_EXPONENT = -1074;
275
+ const scratchValue = /* @__PURE__ */ new Float64Array(1);
276
+ const scratchBits = new BigUint64Array(scratchValue.buffer);
277
+ /** A finite double as `significand * 2 ** exponent` with an integer significand, exactly, read from its bit pattern. Zero has a zero significand. */
278
+ function exactParts(magnitude) {
279
+ scratchValue[0] = magnitude;
280
+ const bits = scratchBits[0];
281
+ if (bits === void 0) throw new Error("a one-element array always has an element zero");
282
+ const exponentField = Number(bits >> FRACTION_BITS & EXPONENT_FIELD_MASK);
283
+ const fraction = bits & FRACTION_MASK;
284
+ if (exponentField === 0) return {
285
+ significand: fraction,
286
+ exponent: SUBNORMAL_EXPONENT
287
+ };
288
+ return {
289
+ significand: fraction | IMPLICIT_LEADING_BIT,
290
+ exponent: exponentField - EXPONENT_BIAS_WITH_FRACTION
291
+ };
292
+ }
293
+ function orderOf(left, right) {
294
+ if (left < right) return -1;
295
+ return left > right ? 1 : 0;
296
+ }
297
+ /** The exact order of `left * leftSize` and `right * rightSize` for finite doubles and positive integer sizes, by comparing the products as integers once both are written over a common power of two. */
298
+ function exactOrder(left, right) {
299
+ const leftSign = Math.sign(left.value);
300
+ const rightSign = Math.sign(right.value);
301
+ if (leftSign !== rightSign) return leftSign < rightSign ? -1 : 1;
302
+ if (leftSign === 0) return 0;
303
+ const leftParts = exactParts(Math.abs(left.value));
304
+ const rightParts = exactParts(Math.abs(right.value));
305
+ let leftProduct = leftParts.significand * BigInt(left.size);
306
+ let rightProduct = rightParts.significand * BigInt(right.size);
307
+ const shift = leftParts.exponent - rightParts.exponent;
308
+ if (shift > 0) leftProduct <<= BigInt(shift);
309
+ else rightProduct <<= BigInt(-shift);
310
+ return leftSign < 0 ? orderOf(rightProduct, leftProduct) : orderOf(leftProduct, rightProduct);
311
+ }
312
+ /**
313
+ * The order of two durations: -1, 0 or 1, or `undefined` when a NaN makes them unordered.
314
+ *
315
+ * A value that is not finite is handled first, as numbers are: a NaN is unordered against everything (so every comparison with it is false, and `neq` true), and an infinity is equal to the same infinity and greater or less than anything finite whatever the units, since a unit only scales by a positive amount. The bit-pattern comparison below reads a finite double's exact value and has no meaning for these.
316
+ *
317
+ * Two finite durations are ordered exactly, with no overflow and no underflow. Both are divided into the coarser of the two units. A division by an exact integer is correctly rounded and rounding is monotone, so it can collapse a difference into equality but never reverse an order: when the two rounded values differ their order is the true order, and that settles almost every comparison without leaving floating point. Dividing can lose the difference, though: two close values round to the same double, and a subnormal rounds to zero. Only when the rounded values are equal is the answer settled exactly, from the doubles' binary expansions, by comparing each value times its unit's size in milliseconds as integers.
318
+ *
319
+ * Converting both to milliseconds by multiplying instead overflows for spans of days beyond roughly 1e300, which is why it is not done here.
320
+ */
321
+ function compareDurations(left, right) {
322
+ if (Number.isNaN(left.value) || Number.isNaN(right.value)) return void 0;
323
+ if (!Number.isFinite(left.value) || !Number.isFinite(right.value)) return orderOf(left.value, right.value);
324
+ const leftSize = millisecondsPerDurationUnit[left.unit];
325
+ const rightSize = millisecondsPerDurationUnit[right.unit];
326
+ const sharedSize = Math.max(leftSize, rightSize);
327
+ const leftInShared = left.value / (sharedSize / leftSize);
328
+ const rightInShared = right.value / (sharedSize / rightSize);
329
+ if (leftInShared < rightInShared) return -1;
330
+ if (leftInShared > rightInShared) return 1;
331
+ return exactOrder({
332
+ value: left.value,
333
+ size: leftSize
334
+ }, {
335
+ value: right.value,
336
+ size: rightSize
337
+ });
338
+ }
339
+ //#endregion
340
+ //#region src/integer-power.ts
341
+ /**
342
+ * `base` raised to a non-negative integer `exponent` by exponentiation by squaring: one squaring and at most one product per bit of the exponent, so the number of `multiply` calls grows with the logarithm of the exponent where repeated multiplication grows with the exponent itself (an exponent of 1e9 is a few dozen products rather than a billion). `identity` is the value of exponent zero and the start of the product; `multiply` must be associative, which squaring relies on. With a rounding `multiply` the grouping matters: squaring compounds a rounding error through each successive square, so its error grows in proportion to the exponent, and for large exponents the result is many times less accurate than a plain loop's, in exchange for work that does not grow with the exponent.
343
+ *
344
+ * The exponent is halved with `Math.floor(remaining / 2)` and tested for oddness with `% 2`, both exact for any finite double, including those past the largest safe integer, whose low bits are all zero. The last squaring is skipped, so no unused product is formed and a base too large to square is not squared once more than the result needs.
345
+ */
346
+ function powerByRepeatedSquaring({ base, exponent, identity, multiply }) {
347
+ let result = identity;
348
+ let factor = base;
349
+ let remaining = exponent;
350
+ while (remaining > 0) {
351
+ if (remaining % 2 === 1) result = multiply(result, factor);
352
+ remaining = Math.floor(remaining / 2);
353
+ if (remaining > 0) factor = multiply(factor, factor);
354
+ }
355
+ return result;
356
+ }
357
+ //#endregion
358
+ //#region src/evaluator-operations.ts
359
+ /** The three-valued AND table: `false` is absorbing regardless of the other operand's indeterminacy; otherwise both-definite folds to a boolean AND; otherwise indeterminate, with the tie-break rule (declared operand order, left before right) applied via `firstIndeterminate`. */
360
+ function combineAnd(left, right) {
361
+ if (left.status === "definite" && !left.value) return definite(false);
362
+ if (right.status === "definite" && !right.value) return definite(false);
363
+ const reason = firstIndeterminate(left, right);
364
+ if (reason !== void 0) return {
365
+ status: "indeterminate",
366
+ reason
367
+ };
368
+ return definite(true);
369
+ }
370
+ /** The three-valued OR table: mirror image of `combineAnd`, with `true` absorbing. */
371
+ function combineOr(left, right) {
372
+ if (left.status === "definite" && left.value) return definite(true);
373
+ if (right.status === "definite" && right.value) return definite(true);
374
+ const reason = firstIndeterminate(left, right);
375
+ if (reason !== void 0) return {
376
+ status: "indeterminate",
377
+ reason
378
+ };
379
+ return definite(false);
380
+ }
381
+ function applyComparisonOperator(op, left, right) {
382
+ switch (op) {
383
+ case "gt": return left > right;
384
+ case "gte": return left >= right;
385
+ case "lt": return left < right;
386
+ case "lte": return left <= right;
387
+ case "eq": return left === right;
388
+ case "neq": return left !== right;
389
+ default: throw new Error("unreachable comparison operator");
390
+ }
391
+ }
392
+ /** Converts a `duration`'s magnitude to milliseconds by multiplying, the base unit the temporal arithmetic below combines durations of different `DurationUnit`s in and shifts an `instant` by. Comparing two durations does not use it: `compareDurations` does that without converting, because this multiplication overflows for very large spans. */
393
+ function toMilliseconds(value, unit) {
394
+ return value * millisecondsPerDurationUnit[unit];
395
+ }
396
+ /** `Date.parse` reports an unparseable timestamp as `NaN`, and every downstream use of that `NaN` then fails silently rather than loudly: every comparison against it is `false` (so `neq` between two unparseable instants would come back definitely `true`), a subtraction yields a `NaN`-magnitude duration, and `new Date(NaN).toISOString()` throws a `RangeError` outright -- a thrown exception for a data-quality problem, which this design never does (see `Evaluation<T>`'s own doc comment in evaluation.ts). An `instant` whose string will not parse is a value the operation cannot use, so every caller below reports it as `wrong-type`, exactly like any other unusable operand. */
397
+ function toEpochMilliseconds(value) {
398
+ const epochMilliseconds = Date.parse(value);
399
+ return Number.isNaN(epochMilliseconds) ? void 0 : epochMilliseconds;
400
+ }
401
+ function unparseableInstant(value) {
402
+ return indeterminate("wrong-type", `'${value}' is not a parseable ISO-8601 timestamp`);
403
+ }
404
+ /** The representable timestamp range is finite, so a valid instant shifted by a large enough duration lands outside it, where `new Date(...).toISOString()` throws a `RangeError`. Checking the shifted date against the platform's own notion of a valid time value keeps that inside the three-outcome model as a `domain-error` -- an operation pushed outside its valid domain, the same category as division by zero -- and avoids hardcoding the range bound. */
405
+ function instantFromEpochMilliseconds(epochMilliseconds) {
406
+ const shifted = new Date(epochMilliseconds);
407
+ if (Number.isNaN(shifted.getTime())) return indeterminate("domain-error", "the resulting instant falls outside the representable timestamp range");
408
+ return definite({
409
+ kind: "instant",
410
+ value: shifted.toISOString()
411
+ });
412
+ }
413
+ /** `compare`'s two operands: valid kinds are `number` (matching units required), `instant` (ordered by parsed epoch millisecond), or `duration` (ordered by `compareDurations`, in whatever unit each carries, with a NaN unordered) -- `text` is never valid here (see `textCompare`), and a kind mismatch between the two operands is `wrong-type`. Narrowing `right` against a literal `left.kind` case (rather than asserting it) is what lets both sides stay properly typed with no `as`. */
414
+ function compareValues(op, left, right) {
415
+ switch (left.kind) {
416
+ case "number":
417
+ if (right.kind !== "number") return indeterminate("wrong-type", `cannot compare a 'number' value with a '${right.kind}' value`);
418
+ if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot compare numbers with incompatible units");
419
+ return definite(applyComparisonOperator(op, left.value, right.value));
420
+ case "text": return indeterminate("wrong-type", "text values are not comparable via 'compare'; use 'textCompare'");
421
+ case "boolean":
422
+ if (right.kind !== "boolean") return indeterminate("wrong-type", `cannot compare a 'boolean' value with a '${right.kind}' value`);
423
+ if (op !== "eq" && op !== "neq") return indeterminate("wrong-type", `booleans have no natural ordering; '${op}' is only defined for 'eq'/'neq'`);
424
+ return definite(op === "eq" ? left.value === right.value : left.value !== right.value);
425
+ case "instant": {
426
+ if (right.kind !== "instant") return indeterminate("wrong-type", `cannot compare an 'instant' value with a '${right.kind}' value`);
427
+ const leftEpoch = toEpochMilliseconds(left.value);
428
+ if (leftEpoch === void 0) return unparseableInstant(left.value);
429
+ const rightEpoch = toEpochMilliseconds(right.value);
430
+ if (rightEpoch === void 0) return unparseableInstant(right.value);
431
+ return definite(applyComparisonOperator(op, leftEpoch, rightEpoch));
432
+ }
433
+ case "duration":
434
+ if (right.kind !== "duration") return indeterminate("wrong-type", `cannot compare a 'duration' value with a '${right.kind}' value`);
435
+ return definite(applyComparisonOperator(op, compareDurations(left, right) ?? NaN, 0));
436
+ case "complex":
437
+ if (op !== "eq" && op !== "neq") return indeterminate("wrong-type", `ordering operator '${op}' is not defined for complex values; the complex plane has no total order`);
438
+ if (right.kind !== "complex") return indeterminate("wrong-type", `cannot compare a 'complex' value with a '${right.kind}' value`);
439
+ if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot compare complex values with incompatible units");
440
+ return definite(op === "eq" ? left.re === right.re && left.im === right.im : left.re !== right.re || left.im !== right.im);
441
+ default: throw new Error("unreachable computed-value kind");
442
+ }
443
+ }
444
+ /** `textCompare`'s two operands must both resolve to the `text` computed-value kind -- any other kind, on either operand, is `wrong-type` (see the `textCompare` section of README.md). `equals`/`notEquals` are exact string equality; `matches`/`notMatches` interpret `right`'s text as an ECMAScript regular expression tested against `left`'s text; `portableMatches`/`portableNotMatches` interpret it as a pattern in `trilean-regex`'s own restricted grammar instead, matched by that package's finite-automaton reference matcher rather than the host's native `RegExp` engine -- see the `textCompare` section of README.md for when to reach for the portable pair instead of the plain one. An invalid pattern is `wrong-type` rather than a thrown exception either way -- every data-quality problem stays inside the `Evaluation` result, per `Evaluation<T>`'s own doc comment in evaluation.ts. */
445
+ function compareText(op, left, right) {
446
+ if (left.kind !== "text") return indeterminate("wrong-type", `'textCompare' requires 'text' operands; the left operand is '${left.kind}'`);
447
+ if (right.kind !== "text") return indeterminate("wrong-type", `'textCompare' requires 'text' operands; the right operand is '${right.kind}'`);
448
+ switch (op) {
449
+ case "equals": return definite(left.value === right.value);
450
+ case "notEquals": return definite(left.value !== right.value);
451
+ case "matches":
452
+ case "notMatches": {
453
+ let pattern;
454
+ try {
455
+ pattern = new RegExp(right.value);
456
+ } catch {
457
+ return indeterminate("wrong-type", `'${right.value}' is not a valid regular expression pattern`);
458
+ }
459
+ const isMatch = pattern.test(left.value);
460
+ return definite(op === "matches" ? isMatch : !isMatch);
461
+ }
462
+ case "portableMatches":
463
+ case "portableNotMatches": {
464
+ let compiled;
465
+ try {
466
+ compiled = compilePattern(right.value);
467
+ } catch (error) {
468
+ const reason = error instanceof RegexParseError ? error.message : String(error);
469
+ return indeterminate("wrong-type", `'${right.value}' is not a valid trilean-regex pattern: ${reason}`);
470
+ }
471
+ const isMatch = compiled.test(left.value);
472
+ return definite(op === "portableMatches" ? isMatch : !isMatch);
473
+ }
474
+ default: throw new Error("unreachable text comparison operator");
475
+ }
476
+ }
477
+ /** `memberOf`'s own value-equality test between two computed values -- kind-agnostic across `number`/`text`/`instant`/`duration` (see the `memberOf` section of README.md, and its "Derived aggregates" note that this equality is kind-agnostic across every computed-value kind), unlike `compare`'s own `eq`, which rejects a `text` operand outright and directs callers to `textCompare` instead. A kind mismatch, or a `number` pair with an incompatible unit, is `wrong-type` -- never simply "not equal". Narrowing `candidate` against a literal `operand.kind` case (rather than asserting it) is the same technique `compareValues` uses above. */
478
+ function computeMembershipMatch(operand, candidate) {
479
+ switch (operand.kind) {
480
+ case "number":
481
+ if (candidate.kind !== "number") return indeterminate("wrong-type", `cannot compare a 'number' value with a '${candidate.kind}' value for membership`);
482
+ if (!unitsEqual(operand.unit, candidate.unit)) return indeterminate("wrong-type", "cannot compare numbers with incompatible units for membership");
483
+ return definite(operand.value === candidate.value);
484
+ case "text":
485
+ if (candidate.kind !== "text") return indeterminate("wrong-type", `cannot compare a 'text' value with a '${candidate.kind}' value for membership`);
486
+ return definite(operand.value === candidate.value);
487
+ case "boolean":
488
+ if (candidate.kind !== "boolean") return indeterminate("wrong-type", `cannot compare a 'boolean' value with a '${candidate.kind}' value for membership`);
489
+ return definite(operand.value === candidate.value);
490
+ case "instant": {
491
+ if (candidate.kind !== "instant") return indeterminate("wrong-type", `cannot compare an 'instant' value with a '${candidate.kind}' value for membership`);
492
+ const operandEpoch = toEpochMilliseconds(operand.value);
493
+ if (operandEpoch === void 0) return unparseableInstant(operand.value);
494
+ const candidateEpoch = toEpochMilliseconds(candidate.value);
495
+ if (candidateEpoch === void 0) return unparseableInstant(candidate.value);
496
+ return definite(operandEpoch === candidateEpoch);
497
+ }
498
+ case "duration":
499
+ if (candidate.kind !== "duration") return indeterminate("wrong-type", `cannot compare a 'duration' value with a '${candidate.kind}' value for membership`);
500
+ return definite(compareDurations(operand, candidate) === 0);
501
+ case "complex":
502
+ if (candidate.kind !== "complex") return indeterminate("wrong-type", `cannot compare a 'complex' value with a '${candidate.kind}' value for membership`);
503
+ if (!unitsEqual(operand.unit, candidate.unit)) return indeterminate("wrong-type", "cannot compare complex values with incompatible units for membership");
504
+ return definite(operand.re === candidate.re && operand.im === candidate.im);
505
+ default: throw new Error("unreachable computed-value kind");
506
+ }
507
+ }
508
+ /** `power`/`modulo` have no defined unit-combination rule in this design (unlike `add`/`subtract`'s "identical units" requirement or `multiply`/`divide`'s dimensional-exponent combination) -- scoping them to dimensionless operands avoids inventing an unspecified unit-scaling semantics for a fractional or runtime-determined exponent. */
509
+ function isDimensionless$1(unit) {
510
+ return unitsEqual(unit, void 0);
511
+ }
512
+ /** `negate` is never sugar for "zero minus the value" (see the `arithmetic`/`negate` section of README.md) -- a `duration`'s magnitude is negated directly, in its own original unit, with no subtraction or millisecond normalisation involved. */
513
+ function applyNegate(operand) {
514
+ switch (operand.kind) {
515
+ case "number": return definite({
516
+ kind: "number",
517
+ value: -operand.value,
518
+ unit: operand.unit
519
+ });
520
+ case "duration": return definite({
521
+ kind: "duration",
522
+ value: -operand.value,
523
+ unit: operand.unit
524
+ });
525
+ case "complex": return definite({
526
+ kind: "complex",
527
+ re: -operand.re,
528
+ im: -operand.im,
529
+ unit: operand.unit
530
+ });
531
+ case "text":
532
+ case "instant":
533
+ case "boolean": return indeterminate("wrong-type", `cannot negate a '${operand.kind}' value`);
534
+ default: throw new Error("unreachable computed-value kind");
535
+ }
536
+ }
537
+ function applyArithmeticOnNumbers(op, left, right) {
538
+ switch (op) {
539
+ case "add":
540
+ if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot add numbers with incompatible units");
541
+ return definite({
542
+ kind: "number",
543
+ value: left.value + right.value,
544
+ unit: left.unit
545
+ });
546
+ case "subtract":
547
+ if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot subtract numbers with incompatible units");
548
+ return definite({
549
+ kind: "number",
550
+ value: left.value - right.value,
551
+ unit: left.unit
552
+ });
553
+ case "multiply": return definite({
554
+ kind: "number",
555
+ value: left.value * right.value,
556
+ unit: combineUnitsForMultiply(left.unit, right.unit)
557
+ });
558
+ case "divide":
559
+ if (right.value === 0) return indeterminate("domain-error", "division by zero");
560
+ return definite({
561
+ kind: "number",
562
+ value: left.value / right.value,
563
+ unit: combineUnitsForDivide(left.unit, right.unit)
564
+ });
565
+ case "power":
566
+ if (!isDimensionless$1(left.unit) || !isDimensionless$1(right.unit)) return indeterminate("wrong-type", "'power' requires dimensionless operands");
567
+ if (left.value < 0 && !Number.isInteger(right.value)) return indeterminate("domain-error", "a negative base raised to a non-integer power is not a real number");
568
+ if (left.value === 0 && right.value < 0) return indeterminate("domain-error", "zero raised to a negative power is a division by zero");
569
+ return definite({
570
+ kind: "number",
571
+ value: left.value ** right.value
572
+ });
573
+ case "modulo":
574
+ if (!isDimensionless$1(left.unit) || !isDimensionless$1(right.unit)) return indeterminate("wrong-type", "'modulo' requires dimensionless operands");
575
+ if (right.value === 0) return indeterminate("domain-error", "modulo by zero");
576
+ return definite({
577
+ kind: "number",
578
+ value: left.value % right.value
579
+ });
580
+ default: throw new Error("unreachable arithmetic operator");
581
+ }
582
+ }
583
+ /** The only same-kind, non-`number` arithmetic this design defines: two `duration`s combine by normalising both to milliseconds first (see `toMilliseconds`), reporting the result in milliseconds -- `multiply`/`divide`/`power`/`modulo` have no representable result unit for a `duration` squared or a dimensionless ratio, so they are `wrong-type` rather than invented. */
584
+ function applyArithmeticOnDurations(op, left, right) {
585
+ switch (op) {
586
+ case "add": return definite({
587
+ kind: "duration",
588
+ value: toMilliseconds(left.value, left.unit) + toMilliseconds(right.value, right.unit),
589
+ unit: "ms"
590
+ });
591
+ case "subtract": return definite({
592
+ kind: "duration",
593
+ value: toMilliseconds(left.value, left.unit) - toMilliseconds(right.value, right.unit),
594
+ unit: "ms"
595
+ });
596
+ case "multiply":
597
+ case "divide":
598
+ case "power":
599
+ case "modulo": return indeterminate("wrong-type", `arithmetic operator '${op}' is not defined between two 'duration' values`);
600
+ default: throw new Error("unreachable arithmetic operator");
601
+ }
602
+ }
603
+ /** Every real number is a complex number with a zero imaginary part, so promoting one is exact and total -- unlike the temporal cross-kind combinations above, which each had to be enumerated because no such embedding exists between an `instant` and a `duration`. This is what lets a tree mix real and complex terms freely instead of forcing every real literal to be written as a complex one. */
604
+ function toComplexValue(value) {
605
+ if (value.kind === "complex") return value;
606
+ return {
607
+ kind: "complex",
608
+ re: value.value,
609
+ im: 0,
610
+ unit: value.unit
611
+ };
612
+ }
613
+ /** The complex product, as its own component-level helper rather than only a branch of the operator switch below, because `power`'s exponentiation by squaring needs exactly this and must not re-derive it. */
614
+ function multiplyComplexValues(left, right) {
615
+ return {
616
+ kind: "complex",
617
+ re: left.re * right.re - left.im * right.im,
618
+ im: left.re * right.im + left.im * right.re,
619
+ unit: combineUnitsForMultiply(left.unit, right.unit)
620
+ };
621
+ }
622
+ /** Complex arithmetic, over the one canonical rectangular representation the `complex` kind stores (see the "Complex values" section of README.md). `add`/`subtract` are component-wise and carry the same identical-units requirement real numbers already have. `power` is deliberately excluded from this operator set rather than handled and rejected here: its exponent must stay an un-promoted real number, so the dispatcher routes it to `applyComplexPower` first, and excluding it from the type is what makes the compiler enforce that routing instead of leaving a dead branch behind. */
623
+ function applyArithmeticOnComplex(op, left, right) {
624
+ switch (op) {
625
+ case "add":
626
+ if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot add complex values with incompatible units");
627
+ return definite({
628
+ kind: "complex",
629
+ re: left.re + right.re,
630
+ im: left.im + right.im,
631
+ unit: left.unit
632
+ });
633
+ case "subtract":
634
+ if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot subtract complex values with incompatible units");
635
+ return definite({
636
+ kind: "complex",
637
+ re: left.re - right.re,
638
+ im: left.im - right.im,
639
+ unit: left.unit
640
+ });
641
+ case "multiply": return definite(multiplyComplexValues(left, right));
642
+ case "divide": {
643
+ if (right.re === 0 && right.im === 0) return indeterminate("domain-error", "division by zero");
644
+ const quotient = divideComplexComponents(left, right);
645
+ return definite({
646
+ kind: "complex",
647
+ re: quotient.re,
648
+ im: quotient.im,
649
+ unit: combineUnitsForDivide(left.unit, right.unit)
650
+ });
651
+ }
652
+ case "modulo": return indeterminate("domain-error", "'modulo' is undefined for complex values");
653
+ default: throw new Error("unreachable arithmetic operator");
654
+ }
655
+ }
656
+ /** `1 / value` for a non-zero complex value, carrying the inverse unit. */
657
+ function reciprocalOf(value) {
658
+ return {
659
+ kind: "complex",
660
+ ...divideComplexComponents({
661
+ re: 1,
662
+ im: 0
663
+ }, value),
664
+ unit: combineUnitsForDivide({}, value.unit)
665
+ };
666
+ }
667
+ /** Whether a complex value is finite and not zero, which is what dividing by it needs. A positive power that has overflowed or underflowed to zero is neither, and cannot be inverted. */
668
+ function isFiniteAndNonZero(value) {
669
+ const larger = Math.max(Math.abs(value.re), Math.abs(value.im));
670
+ return Number.isFinite(larger) && larger > 0;
671
+ }
672
+ /** `power` with a complex operand on either side, defined for exactly one case: a real integer exponent, evaluated as the repeated multiplication that integer exponentiation *is*, grouped by squaring so the work grows with the logarithm of the exponent rather than the exponent itself. The price is accuracy: the error of squaring grows in proportion to the exponent, so for large exponents the result is many times less accurate than a plain multiplication loop's (the "Complex values" section of README.md has the measurement, and explains why an arbitrary complex exponent stays out of scope). */
673
+ function applyComplexPower(base, exponent) {
674
+ if (exponent.kind !== "number" || !Number.isInteger(exponent.value)) return indeterminate("wrong-type", "'power' with a complex operand requires a real integer exponent");
675
+ if (!isDimensionless$1(base.unit) || !isDimensionless$1(exponent.unit)) return indeterminate("wrong-type", "'power' requires dimensionless operands");
676
+ const complexUnit = {
677
+ kind: "complex",
678
+ re: 1,
679
+ im: 0,
680
+ unit: {}
681
+ };
682
+ const complexBase = toComplexValue(base);
683
+ if (exponent.value >= 0) return definite(powerByRepeatedSquaring({
684
+ base: complexBase,
685
+ exponent: exponent.value,
686
+ identity: complexUnit,
687
+ multiply: multiplyComplexValues
688
+ }));
689
+ if (complexBase.re === 0 && complexBase.im === 0) return indeterminate("domain-error", "division by zero");
690
+ const positivePower = powerByRepeatedSquaring({
691
+ base: complexBase,
692
+ exponent: -exponent.value,
693
+ identity: complexUnit,
694
+ multiply: multiplyComplexValues
695
+ });
696
+ if (isFiniteAndNonZero(positivePower)) return definite(reciprocalOf(positivePower));
697
+ return definite(powerByRepeatedSquaring({
698
+ base: reciprocalOf(complexBase),
699
+ exponent: -exponent.value,
700
+ identity: complexUnit,
701
+ multiply: multiplyComplexValues
702
+ }));
703
+ }
704
+ /**
705
+ * Dispatches `arithmetic` by operand kind. The three cross-kind temporal combinations this design defines (`instant - instant`, `instant + duration`, `duration + instant`) are checked explicitly first, in that order, against the exact operator each requires; any other combination touching an `instant` is `wrong-type` (see "Temporal values" in README.md -- e.g. adding two instants, or subtracting a `duration` from an `instant`, are deliberately *not* defined). Same-kind `duration`/`duration` combinations are delegated to `applyArithmeticOnDurations`; a `duration` paired with anything other than an `instant` or another `duration` is `wrong-type`. Everything remaining requires two `number` operands.
706
+ */
707
+ function applyArithmeticByKind(op, left, right) {
708
+ if (left.kind === "instant" && right.kind === "instant" && op === "subtract") {
709
+ const leftEpoch = toEpochMilliseconds(left.value);
710
+ if (leftEpoch === void 0) return unparseableInstant(left.value);
711
+ const rightEpoch = toEpochMilliseconds(right.value);
712
+ if (rightEpoch === void 0) return unparseableInstant(right.value);
713
+ return definite({
714
+ kind: "duration",
715
+ value: leftEpoch - rightEpoch,
716
+ unit: "ms"
717
+ });
718
+ }
719
+ if (left.kind === "instant" && right.kind === "duration" && op === "add") {
720
+ const leftEpoch = toEpochMilliseconds(left.value);
721
+ if (leftEpoch === void 0) return unparseableInstant(left.value);
722
+ return instantFromEpochMilliseconds(leftEpoch + toMilliseconds(right.value, right.unit));
723
+ }
724
+ if (left.kind === "duration" && right.kind === "instant" && op === "add") {
725
+ const rightEpoch = toEpochMilliseconds(right.value);
726
+ if (rightEpoch === void 0) return unparseableInstant(right.value);
727
+ return instantFromEpochMilliseconds(rightEpoch + toMilliseconds(left.value, left.unit));
728
+ }
729
+ if (left.kind === "instant" || right.kind === "instant") return indeterminate("wrong-type", `arithmetic operator '${op}' is not defined between a '${left.kind}' and a '${right.kind}' value`);
730
+ if (left.kind === "duration" && right.kind === "duration") return applyArithmeticOnDurations(op, left, right);
731
+ if (left.kind === "duration" || right.kind === "duration") return indeterminate("wrong-type", `arithmetic operator '${op}' is not defined between a '${left.kind}' and a '${right.kind}' value`);
732
+ if (left.kind !== "number" && left.kind !== "complex") return indeterminate("wrong-type", `arithmetic requires numeric operands; got a '${left.kind}' value`);
733
+ if (right.kind !== "number" && right.kind !== "complex") return indeterminate("wrong-type", `arithmetic requires numeric operands; got a '${right.kind}' value`);
734
+ if (left.kind === "complex" || right.kind === "complex") {
735
+ if (op === "power") return applyComplexPower(left, right);
736
+ return applyArithmeticOnComplex(op, toComplexValue(left), toComplexValue(right));
737
+ }
738
+ return applyArithmeticOnNumbers(op, left, right);
739
+ }
740
+ /** Whether a computed value's numeric components are all finite. Only the kinds an arithmetic operator can produce carry one; any other kind has nothing to overflow. */
741
+ function hasFiniteMagnitude(value) {
742
+ switch (value.kind) {
743
+ case "number":
744
+ case "duration": return Number.isFinite(value.value);
745
+ case "complex": return Number.isFinite(value.re) && Number.isFinite(value.im);
746
+ case "text":
747
+ case "boolean":
748
+ case "instant": return true;
749
+ default: throw new Error("unreachable computed-value kind");
750
+ }
751
+ }
752
+ /**
753
+ * `arithmetic`'s entry point: the result of `applyArithmeticByKind`, except that a definite result whose magnitude overflowed to `Infinity` (or became `NaN`) is a `domain-error` instead. A value of that kind is outside what `ComputedValue` can serialise (JSON writes it as `null`), and an operation pushed outside its valid domain is exactly the category division by zero already uses. Checking once here, after every operator and operand kind has produced its result, is what keeps each of them honest without repeating the check per operator.
754
+ */
755
+ function applyArithmetic(op, left, right) {
756
+ const result = applyArithmeticByKind(op, left, right);
757
+ if (result.status === "definite" && !hasFiniteMagnitude(result.value)) return indeterminate("domain-error", "result is not a finite number");
758
+ return result;
759
+ }
760
+ /** `reference`'s optional expected-unit check: when `expectedUnit` is declared (from `node.unit`), the resolved value must be numeric (`number` or `complex`) and its own unit must match. Returns the `wrong-type` `Evaluation` to return immediately if the check fails, or `undefined` if the reference may resolve as-is. */
761
+ function checkReferenceUnit(expectedUnit, resolvedValue) {
762
+ if (expectedUnit === void 0) return void 0;
763
+ if (resolvedValue.kind !== "number" && resolvedValue.kind !== "complex") return indeterminate("wrong-type", "a unit was expected on a reference that resolved to a non-numeric value");
764
+ if (!unitsEqual(expectedUnit, resolvedValue.unit)) return indeterminate("wrong-type", "the resolved value's unit does not match the reference's expected unit");
765
+ }
766
+ /** `call`'s own function-registry dispatch, given the `fn` name off the tree and its already-evaluated `args`. `node.fn` comes off the serialised tree, which this design treats as data that may have been authored anywhere (see README.md's opening section), while `FunctionRegistry` is an ordinary object with `Object.prototype` on its chain. A bare index lookup would therefore resolve `toString`, `valueOf`, `constructor` and friends as though a consumer had registered them; only the registry's own keys count as registered function names. */
767
+ function invokeRegisteredFunction(functions, fnName, args) {
768
+ const fn = Object.hasOwn(functions, fnName) ? functions[fnName] : void 0;
769
+ if (fn === void 0) return indeterminate("wrong-type", `no function registered under the name '${fnName}'`);
770
+ const outcome = fn(args);
771
+ if ("domainError" in outcome) return indeterminate("domain-error", outcome.domainError);
772
+ if ("wrongType" in outcome) return indeterminate("wrong-type", outcome.wrongType);
773
+ return definite(outcome);
774
+ }
775
+ //#endregion
776
+ //#region src/json-value.ts
777
+ const JsonValueSchema = z.lazy(() => z.union([
778
+ z.string(),
779
+ z.number(),
780
+ z.boolean(),
781
+ z.null(),
782
+ z.array(JsonValueSchema),
783
+ z.record(z.string(), JsonValueSchema)
784
+ ]));
785
+ //#endregion
786
+ //#region src/tree.ts
787
+ const ComparisonOperatorSchema = z.enum([
788
+ "gt",
789
+ "gte",
790
+ "lt",
791
+ "lte",
792
+ "eq",
793
+ "neq"
794
+ ]);
795
+ const TextComparisonOperatorSchema = z.enum([
796
+ "equals",
797
+ "notEquals",
798
+ "matches",
799
+ "notMatches",
800
+ "portableMatches",
801
+ "portableNotMatches"
802
+ ]);
803
+ const MembershipOperatorSchema = z.enum(["in", "notIn"]);
804
+ const ArithmeticOperatorSchema = z.enum([
805
+ "add",
806
+ "subtract",
807
+ "multiply",
808
+ "divide",
809
+ "power",
810
+ "modulo"
811
+ ]);
812
+ const HitPolicySchema = z.enum(["first", "unique"]);
813
+ const NotNodeSchema = z.object({
814
+ kind: z.literal("not"),
815
+ get operand() {
816
+ return PredicateNodeSchema;
817
+ }
818
+ });
819
+ const AndNodeSchema = z.object({
820
+ kind: z.literal("and"),
821
+ get left() {
822
+ return PredicateNodeSchema;
823
+ },
824
+ get right() {
825
+ return PredicateNodeSchema;
826
+ }
827
+ });
828
+ const OrNodeSchema = z.object({
829
+ kind: z.literal("or"),
830
+ get left() {
831
+ return PredicateNodeSchema;
832
+ },
833
+ get right() {
834
+ return PredicateNodeSchema;
835
+ }
836
+ });
837
+ const AllOfNodeSchema = z.object({
838
+ kind: z.literal("allOf"),
839
+ get operands() {
840
+ return z.array(PredicateNodeSchema);
841
+ }
842
+ });
843
+ const AnyOfNodeSchema = z.object({
844
+ kind: z.literal("anyOf"),
845
+ get operands() {
846
+ return z.array(PredicateNodeSchema);
847
+ }
848
+ });
849
+ const CompareNodeSchema = z.object({
850
+ kind: z.literal("compare"),
851
+ op: ComparisonOperatorSchema,
852
+ get left() {
853
+ return ExpressionNodeSchema;
854
+ },
855
+ get right() {
856
+ return ExpressionNodeSchema;
857
+ }
858
+ });
859
+ const TextCompareNodeSchema = z.object({
860
+ kind: z.literal("textCompare"),
861
+ op: TextComparisonOperatorSchema,
862
+ get left() {
863
+ return ExpressionNodeSchema;
864
+ },
865
+ get right() {
866
+ return ExpressionNodeSchema;
867
+ }
868
+ });
869
+ const MemberOfNodeSchema = z.object({
870
+ kind: z.literal("memberOf"),
871
+ op: MembershipOperatorSchema,
872
+ get operand() {
873
+ return ExpressionNodeSchema;
874
+ },
875
+ get candidates() {
876
+ return z.array(ExpressionNodeSchema);
877
+ }
878
+ });
879
+ const ExistsNodeSchema = z.object({
880
+ kind: z.literal("exists"),
881
+ get operand() {
882
+ return ExpressionNodeSchema;
883
+ }
884
+ });
885
+ const SomeNodeSchema = z.object({
886
+ kind: z.literal("some"),
887
+ collection: JsonValueSchema,
888
+ get item() {
889
+ return PredicateNodeSchema;
890
+ },
891
+ get filter() {
892
+ return PredicateNodeSchema.optional();
893
+ }
894
+ });
895
+ const EveryNodeSchema = z.object({
896
+ kind: z.literal("every"),
897
+ collection: JsonValueSchema,
898
+ get item() {
899
+ return PredicateNodeSchema;
900
+ },
901
+ get filter() {
902
+ return PredicateNodeSchema.optional();
903
+ }
904
+ });
905
+ /** Shared by both trees -- the only node kind valid in both PredicateNodeSchema's and ExpressionNodeSchema's own discriminated unions, appended as the last member of each below. Declared once, here, ahead of the predicate union that needs it first; the expression union further down references this exact same schema object again rather than declaring its own copy. See the `treeReference` section of README.md. */
906
+ const TreeReferenceNodeSchema = z.object({
907
+ kind: z.literal("treeReference"),
908
+ key: JsonValueSchema
909
+ });
910
+ const PredicateNodeSchema = z.discriminatedUnion("kind", [
911
+ NotNodeSchema,
912
+ AndNodeSchema,
913
+ OrNodeSchema,
914
+ AllOfNodeSchema,
915
+ AnyOfNodeSchema,
916
+ CompareNodeSchema,
917
+ TextCompareNodeSchema,
918
+ MemberOfNodeSchema,
919
+ ExistsNodeSchema,
920
+ SomeNodeSchema,
921
+ EveryNodeSchema,
922
+ TreeReferenceNodeSchema
923
+ ]);
924
+ const NumberLiteralNodeSchema = z.object({
925
+ kind: z.literal("numberLiteral"),
926
+ value: z.number(),
927
+ unit: UnitSchema.optional()
928
+ });
929
+ const TextLiteralNodeSchema = z.object({
930
+ kind: z.literal("textLiteral"),
931
+ value: z.string()
932
+ });
933
+ const BooleanLiteralNodeSchema = z.object({
934
+ kind: z.literal("booleanLiteral"),
935
+ value: z.boolean()
936
+ });
937
+ const InstantLiteralNodeSchema = z.object({
938
+ kind: z.literal("instantLiteral"),
939
+ /** ISO-8601 timestamp. */
940
+ value: z.string()
941
+ });
942
+ const DurationLiteralNodeSchema = z.object({
943
+ kind: z.literal("durationLiteral"),
944
+ value: z.number(),
945
+ unit: DurationUnitSchema
946
+ });
947
+ /**
948
+ * The wire-format literal accepts either of the two authoring forms real-world complex data arrives in, discriminated structurally rather than by a `form` tag: rectangular (`re`/`im`), matching the `complex` computed-value kind's own single canonical representation exactly (see the "Complex values" section of README.md), or polar (`magnitude`/`phase`, in radians), for the domains that reason that way natively and would otherwise have to hand-compute the conversion before ever constructing the tree. `strictObject` on both members is what makes the two forms mutually exclusive on the wire -- a plain `object` would silently strip an unrecognised field rather than reject a payload that mixes both.
949
+ *
950
+ * The evaluator normalises whichever form was authored into the single rectangular `ComputedValue` immediately on evaluation (see the `complexLiteral` case in evaluator.ts), so nothing downstream of that -- arithmetic, `compare`, `memberOf`, `negate` -- ever sees a polar value; they keep consuming the one canonical `complex` shape unchanged.
951
+ */
952
+ const ComplexRectangularLiteralNodeSchema = z.strictObject({
953
+ kind: z.literal("complexLiteral"),
954
+ re: z.number(),
955
+ im: z.number(),
956
+ unit: UnitSchema.optional()
957
+ });
958
+ const ComplexPolarLiteralNodeSchema = z.strictObject({
959
+ kind: z.literal("complexLiteral"),
960
+ magnitude: z.number(),
961
+ phase: z.number(),
962
+ unit: UnitSchema.optional()
963
+ });
964
+ /** Both literal forms share the one literal `kind: "complexLiteral"` value, which is exactly why this is a plain `z.union` rather than a `z.discriminatedUnion` -- `z.discriminatedUnion` requires a unique discriminant literal per member and throws ("Duplicate discriminator value") the moment two members share one. `ExpressionNodeSchema` below folds this plain union in alongside its own discriminated union of every other kind, rather than trying to host it as a normal member. */
965
+ const ComplexLiteralNodeSchema = z.union([ComplexRectangularLiteralNodeSchema, ComplexPolarLiteralNodeSchema]);
966
+ const ReferenceNodeSchema = z.object({
967
+ kind: z.literal("reference"),
968
+ key: JsonValueSchema,
969
+ unit: UnitSchema.optional()
970
+ });
971
+ const ArithmeticNodeSchema = z.object({
972
+ kind: z.literal("arithmetic"),
973
+ op: ArithmeticOperatorSchema,
974
+ get left() {
975
+ return ExpressionNodeSchema;
976
+ },
977
+ get right() {
978
+ return ExpressionNodeSchema;
979
+ }
980
+ });
981
+ const NegateNodeSchema = z.object({
982
+ kind: z.literal("negate"),
983
+ get operand() {
984
+ return ExpressionNodeSchema;
985
+ }
986
+ });
987
+ const CallNodeSchema = z.object({
988
+ kind: z.literal("call"),
989
+ fn: z.string(),
990
+ get args() {
991
+ return z.array(ExpressionNodeSchema);
992
+ }
993
+ });
994
+ const LookupNodeSchema = z.object({
995
+ kind: z.literal("lookup"),
996
+ table: JsonValueSchema,
997
+ get keys() {
998
+ return z.array(ExpressionNodeSchema);
999
+ }
1000
+ });
1001
+ const ConditionalCaseSchema = z.object({
1002
+ get when() {
1003
+ return PredicateNodeSchema;
1004
+ },
1005
+ get then() {
1006
+ return ExpressionNodeSchema;
1007
+ }
1008
+ });
1009
+ const ConditionalNodeSchema = z.object({
1010
+ kind: z.literal("conditional"),
1011
+ /** Absent means `"first"` -- the exact, unchanged behaviour of every tree serialised before this field existed. A deliberate, meaningful default, not a masked-bug fallback; see the `conditional` section of README.md for `"unique"`'s own absorption rules. */
1012
+ hitPolicy: HitPolicySchema.optional(),
1013
+ get cases() {
1014
+ return z.array(ConditionalCaseSchema);
1015
+ },
1016
+ get fallback() {
1017
+ return ExpressionNodeSchema;
1018
+ }
1019
+ });
1020
+ const FoldCombinerSchema = z.discriminatedUnion("mode", [
1021
+ z.object({
1022
+ mode: z.literal("max"),
1023
+ get item() {
1024
+ return ExpressionNodeSchema;
1025
+ }
1026
+ }),
1027
+ z.object({
1028
+ mode: z.literal("min"),
1029
+ get item() {
1030
+ return ExpressionNodeSchema;
1031
+ }
1032
+ }),
1033
+ z.object({
1034
+ mode: z.literal("reduce"),
1035
+ get initial() {
1036
+ return ExpressionNodeSchema;
1037
+ },
1038
+ get combine() {
1039
+ return ExpressionNodeSchema;
1040
+ }
1041
+ })
1042
+ ]);
1043
+ const FoldNodeSchema = z.object({
1044
+ kind: z.literal("fold"),
1045
+ collection: JsonValueSchema,
1046
+ get filter() {
1047
+ return PredicateNodeSchema.optional();
1048
+ },
1049
+ combiner: FoldCombinerSchema
1050
+ });
1051
+ const AccumulatorNodeSchema = z.object({ kind: z.literal("accumulator") });
1052
+ const DelegateNodeSchema = z.object({
1053
+ kind: z.literal("delegate"),
1054
+ system: z.string(),
1055
+ payload: JsonValueSchema
1056
+ });
1057
+ /** Every expression node kind except `complexLiteral`, which cannot be a member of this same discriminated union alongside its own two forms (see `ComplexLiteralNodeSchema` above) -- folded back in below via a plain `z.union` rather than `z.discriminatedUnion`. */
1058
+ const CoreExpressionNodeSchema = z.discriminatedUnion("kind", [
1059
+ NumberLiteralNodeSchema,
1060
+ TextLiteralNodeSchema,
1061
+ BooleanLiteralNodeSchema,
1062
+ InstantLiteralNodeSchema,
1063
+ DurationLiteralNodeSchema,
1064
+ ReferenceNodeSchema,
1065
+ ArithmeticNodeSchema,
1066
+ NegateNodeSchema,
1067
+ CallNodeSchema,
1068
+ LookupNodeSchema,
1069
+ ConditionalNodeSchema,
1070
+ FoldNodeSchema,
1071
+ AccumulatorNodeSchema,
1072
+ DelegateNodeSchema,
1073
+ TreeReferenceNodeSchema
1074
+ ]);
1075
+ const ExpressionNodeSchema = z.union([CoreExpressionNodeSchema, ComplexLiteralNodeSchema]);
1076
+ //#endregion
1077
+ //#region src/evaluator.ts
1078
+ /**
1079
+ * `evaluatePredicateInternal` and `evaluateValueInternal` below are co-located in this one file, rather than split across `predicate-evaluator.ts`/`value-evaluator.ts`, because they are mutually recursive: a predicate leaf (`compare`, `textCompare`, `memberOf`, `exists`) holds `ExpressionNode` operands, and an expression node (`conditional`'s `when`, a fold's `filter`) holds `PredicateNode` operands. Splitting them across modules would make each half import the other, and whichever module finished loading second would see the other's export as `undefined` at its own module-evaluation time -- a genuine circular-import TDZ hazard, not merely a style preference. `resolveParticipatingItems` (in `evaluator-collection.ts`) would share that same hazard if it imported `evaluatePredicateInternal` directly, since it calls back into it to evaluate each candidate's filter -- so it instead takes the evaluator as an injected `EvaluatePredicate` parameter (see that type's own doc comment), which is what lets it live in its own file with no circular dependency on this one. The pure, non-recursive value-combination logic (`combineAnd`/`compareValues`/`applyArithmetic` and their siblings) carries no such constraint either and lives in `evaluator-operations.ts`; the resource-limit infrastructure (`EvaluationBudget` and its constants), likewise self-contained, lives in `evaluator-budget.ts`.
1080
+ */
1081
+ function* evaluatePredicateInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth) {
1082
+ const budgetExceeded = budget.checkNode(nestingDepth);
1083
+ if (budgetExceeded !== void 0) return budgetExceeded;
1084
+ switch (node.kind) {
1085
+ case "not": {
1086
+ const operand = yield* evaluatePredicateInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
1087
+ if (operand.status === "indeterminate") return operand;
1088
+ return definite(!operand.value);
1089
+ }
1090
+ case "and": {
1091
+ const [left, right] = yield* all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)]);
1092
+ return combineAnd(left, right);
1093
+ }
1094
+ case "or": {
1095
+ const [left, right] = yield* all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)]);
1096
+ return combineOr(left, right);
1097
+ }
1098
+ case "allOf": return (yield* all(node.operands.map((operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)))).reduce(combineAnd, definite(true));
1099
+ case "anyOf": return (yield* all(node.operands.map((operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)))).reduce(combineOr, definite(false));
1100
+ case "compare": {
1101
+ const [left, right] = yield* all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)]);
1102
+ if (left.status === "indeterminate") return left;
1103
+ if (right.status === "indeterminate") return right;
1104
+ return compareValues(node.op, left.value, right.value);
1105
+ }
1106
+ case "textCompare": {
1107
+ const [left, right] = yield* all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)]);
1108
+ if (left.status === "indeterminate") return left;
1109
+ if (right.status === "indeterminate") return right;
1110
+ return compareText(node.op, left.value, right.value);
1111
+ }
1112
+ case "memberOf": {
1113
+ const operandResult = yield* evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
1114
+ if (operandResult.status === "indeterminate") return operandResult;
1115
+ const candidateOutcomes = yield* all(node.candidates.map(function* (candidate) {
1116
+ const candidateResult = yield* evaluateValueInternal(candidate, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
1117
+ if (candidateResult.status === "indeterminate") return candidateResult;
1118
+ return computeMembershipMatch(operandResult.value, candidateResult.value);
1119
+ }));
1120
+ for (const outcome of candidateOutcomes) if (outcome.status === "definite" && outcome.value) return definite(node.op === "in");
1121
+ const reason = firstIndeterminate(...candidateOutcomes);
1122
+ if (reason !== void 0) return {
1123
+ status: "indeterminate",
1124
+ reason
1125
+ };
1126
+ return definite(node.op === "notIn");
1127
+ }
1128
+ case "exists": {
1129
+ const operandResult = yield* evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
1130
+ if (operandResult.status === "indeterminate" && operandResult.reason.code === "not-found") return definite(false);
1131
+ return definite(true);
1132
+ }
1133
+ case "some":
1134
+ case "every": {
1135
+ const votes = (yield* all((yield* resolveParticipatingItems(evaluatePredicateInternal, node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)).map(function* ({ item, filterOutcome }) {
1136
+ if (filterOutcome === "exclude") return void 0;
1137
+ if (filterOutcome !== "include") return filterOutcome;
1138
+ return yield* evaluatePredicateInternal(node.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
1139
+ }))).filter((vote) => vote !== void 0);
1140
+ const combine = node.kind === "some" ? combineOr : combineAnd;
1141
+ const identity = node.kind === "some" ? definite(false) : definite(true);
1142
+ return votes.reduce(combine, identity);
1143
+ }
1144
+ case "treeReference": {
1145
+ if (resolvers.resolveTree === void 0) return indeterminate("wrong-type", "no tree resolver registered for treeReference nodes");
1146
+ const keyString = JSON.stringify(node.key);
1147
+ if (visitedTreeKeys.has(keyString)) return indeterminate("domain-error", "circular treeReference detected");
1148
+ if (treeReferenceDepth >= 100) return indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${100 .toString()}`);
1149
+ const resolution = yield* wait(resolvers.resolveTree(node.key, context));
1150
+ if (!resolution.found) return indeterminate("not-found", "treeReference key did not resolve to a tree");
1151
+ const parsed = PredicateNodeSchema.safeParse(resolution.node);
1152
+ if (!parsed.success) return indeterminate("wrong-type", "the referenced tree is not a valid PredicateNode");
1153
+ return yield* evaluatePredicateInternal(parsed.data, context, resolvers, accumulator, functions, /* @__PURE__ */ new Set([...visitedTreeKeys, keyString]), treeReferenceDepth + 1, budget, nestingDepth + 1);
1154
+ }
1155
+ default: throw new Error("unreachable predicate node kind");
1156
+ }
1157
+ }
1158
+ function* evaluateValueInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth) {
1159
+ const budgetExceeded = budget.checkNode(nestingDepth);
1160
+ if (budgetExceeded !== void 0) return budgetExceeded;
1161
+ switch (node.kind) {
1162
+ case "reference": {
1163
+ const resolution = yield* wait(resolvers.resolveValue(node.key, context));
1164
+ if (!resolution.found) return indeterminate("not-found", `no value found for reference key ${JSON.stringify(node.key)}`);
1165
+ const unitError = checkReferenceUnit(node.unit, resolution.value);
1166
+ if (unitError !== void 0) return unitError;
1167
+ return definite(resolution.value);
1168
+ }
1169
+ case "accumulator":
1170
+ if (accumulator === void 0) return indeterminate("wrong-type", "accumulator used outside a reduce fold's combine expression");
1171
+ return definite(accumulator);
1172
+ case "call": {
1173
+ const argResults = yield* all(node.args.map((arg) => evaluateValueInternal(arg, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)));
1174
+ const args = [];
1175
+ for (const result of argResults) {
1176
+ if (result.status === "indeterminate") return result;
1177
+ args.push(result.value);
1178
+ }
1179
+ return invokeRegisteredFunction(functions, node.fn, args);
1180
+ }
1181
+ case "numberLiteral": return definite({
1182
+ kind: "number",
1183
+ value: node.value,
1184
+ unit: node.unit
1185
+ });
1186
+ case "textLiteral": return definite({
1187
+ kind: "text",
1188
+ value: node.value
1189
+ });
1190
+ case "booleanLiteral": return definite({
1191
+ kind: "boolean",
1192
+ value: node.value
1193
+ });
1194
+ case "instantLiteral": return definite({
1195
+ kind: "instant",
1196
+ value: node.value
1197
+ });
1198
+ case "durationLiteral": return definite({
1199
+ kind: "duration",
1200
+ value: node.value,
1201
+ unit: node.unit
1202
+ });
1203
+ case "complexLiteral":
1204
+ if ("re" in node) return definite({
1205
+ kind: "complex",
1206
+ re: node.re,
1207
+ im: node.im,
1208
+ unit: node.unit
1209
+ });
1210
+ return definite(complexFromPolar(node.magnitude, node.phase, node.unit));
1211
+ case "arithmetic": {
1212
+ const [left, right] = yield* all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)]);
1213
+ if (left.status === "indeterminate") return left;
1214
+ if (right.status === "indeterminate") return right;
1215
+ return applyArithmetic(node.op, left.value, right.value);
1216
+ }
1217
+ case "negate": {
1218
+ const operand = yield* evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
1219
+ if (operand.status === "indeterminate") return operand;
1220
+ return applyNegate(operand.value);
1221
+ }
1222
+ case "lookup": {
1223
+ const keyResults = yield* all(node.keys.map((key) => evaluateValueInternal(key, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)));
1224
+ const keyValues = [];
1225
+ for (const result of keyResults) {
1226
+ if (result.status === "indeterminate") return result;
1227
+ keyValues.push(result.value);
1228
+ }
1229
+ const resolution = yield* wait(resolvers.resolveLookup(node.table, keyValues, context));
1230
+ if (!resolution.found) return indeterminate("not-found", `no match found in lookup table ${JSON.stringify(node.table)}`);
1231
+ return definite(resolution.value);
1232
+ }
1233
+ case "conditional": {
1234
+ if ((node.hitPolicy ?? "first") === "first") {
1235
+ for (const { when, then } of node.cases) {
1236
+ const whenResult = yield* evaluatePredicateInternal(when, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
1237
+ if (whenResult.status === "indeterminate") return whenResult;
1238
+ if (whenResult.value) return yield* evaluateValueInternal(then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
1239
+ }
1240
+ return yield* evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
1241
+ }
1242
+ const evaluatedCases = yield* all(node.cases.map(function* ({ when, then }) {
1243
+ return {
1244
+ then,
1245
+ whenResult: yield* evaluatePredicateInternal(when, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1)
1246
+ };
1247
+ }));
1248
+ const matches = evaluatedCases.filter(({ whenResult }) => whenResult.status === "definite" && whenResult.value);
1249
+ if (matches.length >= 2) return indeterminate("domain-error", "more than one case matched under the 'unique' hit policy");
1250
+ const reason = firstIndeterminate(...evaluatedCases.map(({ whenResult }) => whenResult));
1251
+ if (reason !== void 0) return {
1252
+ status: "indeterminate",
1253
+ reason
1254
+ };
1255
+ const [match] = matches;
1256
+ if (match === void 0) return yield* evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
1257
+ return yield* evaluateValueInternal(match.then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
1258
+ }
1259
+ case "fold": {
1260
+ const participating = yield* resolveParticipatingItems(evaluatePredicateInternal, node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
1261
+ const filterIndeterminateReason = firstFilterIndeterminate(participating);
1262
+ if (filterIndeterminateReason !== void 0) return {
1263
+ status: "indeterminate",
1264
+ reason: filterIndeterminateReason
1265
+ };
1266
+ const includedItems = participating.filter(({ filterOutcome }) => filterOutcome === "include").map(({ item }) => item);
1267
+ if (node.combiner.mode === "reduce") {
1268
+ const initialResult = yield* evaluateValueInternal(node.combiner.initial, context, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
1269
+ if (initialResult.status === "indeterminate") return initialResult;
1270
+ let runningAccumulator = initialResult.value;
1271
+ for (const item of includedItems) {
1272
+ const stepResult = yield* evaluateValueInternal(node.combiner.combine, item, resolvers, runningAccumulator, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
1273
+ if (stepResult.status === "indeterminate") return stepResult;
1274
+ runningAccumulator = stepResult.value;
1275
+ }
1276
+ return definite(runningAccumulator);
1277
+ }
1278
+ if (includedItems.length === 0) return indeterminate("domain-error", `'${node.combiner.mode}' has no participating items to seed a running result from`);
1279
+ const dominatesOp = node.combiner.mode === "max" ? "gt" : "lt";
1280
+ let runningExtremum;
1281
+ for (const item of includedItems) {
1282
+ const itemResult = yield* evaluateValueInternal(node.combiner.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth, budget, nestingDepth + 1);
1283
+ if (itemResult.status === "indeterminate") return itemResult;
1284
+ if (runningExtremum === void 0) {
1285
+ runningExtremum = itemResult.value;
1286
+ continue;
1287
+ }
1288
+ const comparison = compareValues(dominatesOp, itemResult.value, runningExtremum);
1289
+ if (comparison.status === "indeterminate") return comparison;
1290
+ if (comparison.value) runningExtremum = itemResult.value;
1291
+ }
1292
+ if (runningExtremum === void 0) throw new Error("unreachable: max/min over a non-empty participating list produced no running result");
1293
+ return definite(runningExtremum);
1294
+ }
1295
+ case "delegate": {
1296
+ if (resolvers.resolveDelegate === void 0) return indeterminate("wrong-type", `no delegate handler registered for external system '${node.system}'`);
1297
+ const resolution = yield* wait(resolvers.resolveDelegate(node.system, node.payload, context));
1298
+ if (!resolution.found) return indeterminate("not-found", `delegate handler for external system '${node.system}' reported no value`);
1299
+ return definite(resolution.value);
1300
+ }
1301
+ case "treeReference": {
1302
+ if (resolvers.resolveTree === void 0) return indeterminate("wrong-type", "no tree resolver registered for treeReference nodes");
1303
+ const keyString = JSON.stringify(node.key);
1304
+ if (visitedTreeKeys.has(keyString)) return indeterminate("domain-error", "circular treeReference detected");
1305
+ if (treeReferenceDepth >= 100) return indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${100 .toString()}`);
1306
+ const resolution = yield* wait(resolvers.resolveTree(node.key, context));
1307
+ if (!resolution.found) return indeterminate("not-found", "treeReference key did not resolve to a tree");
1308
+ const parsed = ExpressionNodeSchema.safeParse(resolution.node);
1309
+ if (!parsed.success) return indeterminate("wrong-type", "the referenced tree is not a valid ExpressionNode");
1310
+ return yield* evaluateValueInternal(parsed.data, context, resolvers, accumulator, functions, /* @__PURE__ */ new Set([...visitedTreeKeys, keyString]), treeReferenceDepth + 1, budget, nestingDepth + 1);
1311
+ }
1312
+ default: throw new Error("unreachable expression node kind");
1313
+ }
1314
+ }
1315
+ //#endregion
1316
+ //#region src/functions.ts
1317
+ const emptyFunctionRegistry = {};
1318
+ //#endregion
1319
+ //#region src/evaluator-factory.ts
1320
+ /**
1321
+ * Builds a bound `{ evaluatePredicate, evaluateValue }` pair over a caller-supplied function registry for `call` nodes -- the registry is bound once, at construction time, unlike `resolvers`, which are supplied fresh to every call. `maxNodes` and `maxNestingDepth` configure that same pair's own `EvaluationBudget` (see its doc comment in evaluator-budget.ts), created fresh for every top-level `evaluatePredicate`/`evaluateValue` invocation so budgets never leak between unrelated calls. The bare module-level `evaluatePredicate`/`evaluateValue` exports below are `createEvaluator({})`'s output, so both caps default to `DEFAULT_MAX_EVALUATION_NODES`/`DEFAULT_MAX_NESTING_DEPTH` for every caller that does not explicitly configure them.
1322
+ */
1323
+ function createEvaluator({ functions = emptyFunctionRegistry, maxNodes = DEFAULT_MAX_EVALUATION_NODES, maxNestingDepth = 500 }) {
1324
+ return {
1325
+ evaluatePredicate: async (node, context, resolvers) => runAsync(evaluatePredicateInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0, createEvaluationBudget(maxNodes, maxNestingDepth), 0)),
1326
+ evaluateValue: async (node, context, resolvers) => runAsync(evaluateValueInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0, createEvaluationBudget(maxNodes, maxNestingDepth), 0))
1327
+ };
1328
+ }
1329
+ /**
1330
+ * The synchronous counterpart of `createEvaluator`: the same node rules, options and `Evaluation` results, over `SyncResolvers`, returning the result directly instead of a promise. It runs the same implementation as the asynchronous evaluator, so the two cannot disagree about a node. One difference follows from having nothing to wait on: independent operands (both sides of an `and`, the candidates of a `memberOf`, the items of a collection) are evaluated one after another rather than concurrently, so when a `maxNodes` or `maxNestingDepth` budget is exhausted partway through a tree, which operand meets the limit first can differ from the asynchronous evaluator.
1331
+ */
1332
+ function createSyncEvaluator({ functions = emptyFunctionRegistry, maxNodes = DEFAULT_MAX_EVALUATION_NODES, maxNestingDepth = 500 }) {
1333
+ return {
1334
+ evaluatePredicate: (node, context, resolvers) => runSync(evaluatePredicateInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0, createEvaluationBudget(maxNodes, maxNestingDepth), 0)),
1335
+ evaluateValue: (node, context, resolvers) => runSync(evaluateValueInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0, createEvaluationBudget(maxNodes, maxNestingDepth), 0))
1336
+ };
1337
+ }
1338
+ const { evaluatePredicate, evaluateValue } = createEvaluator({});
1339
+ //#endregion
1340
+ //#region src/builtin-functions.ts
1341
+ const DECIMAL_BASE = 10;
1342
+ const BINARY_BASE = 2;
1343
+ /** Beyond this many decimal places a double either has no digit left to round (positive places) or rounds to zero (negative places): the decimal exponent range of a finite double, from the largest value's order of magnitude down to the smallest subnormal's. Clamping to it keeps the exponent written into a number string well formed whatever count a caller passes. */
1344
+ const DECIMAL_PLACES_LIMIT = Math.ceil(Math.log10(Number.MAX_VALUE) - Math.log10(Number.MIN_VALUE));
1345
+ function isNumberValue(value) {
1346
+ return value?.kind === "number";
1347
+ }
1348
+ function isDimensionless(value) {
1349
+ return unitsEqual(value.unit, void 0);
1350
+ }
1351
+ /** The magnitude of a number that carries no unit, or `undefined` for any other value. */
1352
+ function dimensionlessNumber(value) {
1353
+ return isNumberValue(value) && isDimensionless(value) ? value.value : void 0;
1354
+ }
1355
+ function withUnit(value, unit) {
1356
+ return unit === void 0 ? {
1357
+ kind: "number",
1358
+ value
1359
+ } : {
1360
+ kind: "number",
1361
+ value,
1362
+ unit
1363
+ };
1364
+ }
1365
+ /** The one exit for every numeric result: a value that left the finite range (an overflow or a limit) would otherwise surface as `Infinity` or `NaN` inside a definite value, which JSON writes as `null`. */
1366
+ function finiteNumber(name, value, unit) {
1367
+ return Number.isFinite(value) ? withUnit(value, unit) : { domainError: `${name} produced a result that is not a finite number` };
1368
+ }
1369
+ function singleNumber(name, args) {
1370
+ const [arg] = args;
1371
+ if (args.length !== 1 || !isNumberValue(arg)) return { wrongType: `${name} requires exactly one number argument` };
1372
+ return arg;
1373
+ }
1374
+ /** Halves every dimension's exponent, or `false` when one is odd and the root would need a fractional exponent. */
1375
+ function halveUnit(unit) {
1376
+ if (unit === void 0) return void 0;
1377
+ const halved = {};
1378
+ for (const [dimension, exponent] of Object.entries(unit)) {
1379
+ if (exponent === 0) continue;
1380
+ if (exponent % 2 !== 0) return false;
1381
+ halved[dimension] = exponent / 2;
1382
+ }
1383
+ return halved;
1384
+ }
1385
+ function extremum(name, args, prefer) {
1386
+ const [first, ...rest] = args;
1387
+ if (!isNumberValue(first)) return { wrongType: `${name} requires at least one number argument` };
1388
+ let best = first;
1389
+ for (const arg of rest) {
1390
+ if (!isNumberValue(arg)) return { wrongType: `${name} requires number arguments only` };
1391
+ if (!unitsEqual(arg.unit, first.unit)) return { wrongType: `${name} requires arguments in the same unit` };
1392
+ if (prefer(arg.value, best.value)) best = arg;
1393
+ }
1394
+ return finiteNumber(name, best.value, best.unit);
1395
+ }
1396
+ /** Moves the decimal point of a number by editing the exponent of its shortest decimal form, so `1.005` shifted by 2 places is parsed from the text `1.005e2` (exactly 100.5) rather than computed as `1.005 * 100` (100.49999999999999). `String` writes a large or small value in exponent form already (`1.5e-7`), so the existing exponent is read and added to rather than appended to. */
1397
+ function shiftDecimalPoint(value, places) {
1398
+ const text = String(value);
1399
+ const marker = text.indexOf("e");
1400
+ const mantissa = marker === -1 ? text : text.slice(0, marker);
1401
+ const exponent = marker === -1 ? 0 : Number(text.slice(marker + 1));
1402
+ return Number(`${mantissa}e${String(exponent + places)}`);
1403
+ }
1404
+ /** Rounds to `places` decimal places, halves away from zero, working on the decimal number the value is written as. A value whose shifted magnitude reaches the largest safe integer has no fractional digit at that precision (or shifts out of the finite range altogether), so it is returned as it is. */
1405
+ function roundHalfAwayFromZero(value, places) {
1406
+ const clamped = Math.max(-DECIMAL_PLACES_LIMIT, Math.min(DECIMAL_PLACES_LIMIT, places));
1407
+ const shifted = shiftDecimalPoint(Math.abs(value), clamped);
1408
+ if (!(shifted < Number.MAX_SAFE_INTEGER)) return value;
1409
+ const rounded = shiftDecimalPoint(Math.round(shifted), -clamped);
1410
+ return rounded === 0 ? 0 : Math.sign(value) * rounded;
1411
+ }
1412
+ /**
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`, and `logarithm` (natural, or to an optional base). They take real numbers only: a complex value is refused by every one of them, `absoluteValue` included.
1414
+ *
1415
+ * 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
+ *
1417
+ * Units follow the evaluator's rule that dimensions are never silently converted. `minimum`, `maximum`, `absoluteValue` and `round` keep the argument's unit (and the first two require all arguments to share one); `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
+ *
1419
+ * Frozen, so mutating the export cannot change what `evaluateDocument` resolves.
1420
+ */
1421
+ const builtinFunctions = Object.freeze({
1422
+ minimum: (args) => extremum("minimum", args, (candidate, best) => candidate < best),
1423
+ maximum: (args) => extremum("maximum", args, (candidate, best) => candidate > best),
1424
+ absoluteValue: (args) => {
1425
+ const arg = singleNumber("absoluteValue", args);
1426
+ if ("wrongType" in arg) return arg;
1427
+ return finiteNumber("absoluteValue", Math.abs(arg.value), arg.unit);
1428
+ },
1429
+ round: (args) => {
1430
+ const [value, places, ...extra] = args;
1431
+ if (!isNumberValue(value) || extra.length > 0) return { wrongType: "round requires a number and an optional count of decimal places" };
1432
+ if (places === void 0) return finiteNumber("round", roundHalfAwayFromZero(value.value, 0), value.unit);
1433
+ if (!isNumberValue(places) || !isDimensionless(places)) return { wrongType: "round requires its decimal places to be a dimensionless number" };
1434
+ if (!Number.isInteger(places.value)) return { domainError: "round requires its decimal places to be an integer" };
1435
+ return finiteNumber("round", roundHalfAwayFromZero(value.value, places.value), value.unit);
1436
+ },
1437
+ squareRoot: (args) => {
1438
+ const arg = singleNumber("squareRoot", args);
1439
+ if ("wrongType" in arg) return arg;
1440
+ const unit = halveUnit(arg.unit);
1441
+ if (unit === false) return { wrongType: "squareRoot requires every unit exponent to be even" };
1442
+ if (arg.value < 0) return { domainError: "squareRoot of a negative number is not a real number" };
1443
+ return finiteNumber("squareRoot", Math.sqrt(arg.value), unit);
1444
+ },
1445
+ exponential: (args) => {
1446
+ const arg = singleNumber("exponential", args);
1447
+ if ("wrongType" in arg) return arg;
1448
+ if (!isDimensionless(arg)) return { wrongType: "exponential requires a dimensionless number" };
1449
+ return finiteNumber("exponential", Math.exp(arg.value));
1450
+ },
1451
+ logarithm: (args) => {
1452
+ const [value, base, ...extra] = args;
1453
+ if (!isNumberValue(value) || extra.length > 0) return { wrongType: "logarithm requires a number and an optional base" };
1454
+ if (!isDimensionless(value)) return { wrongType: "logarithm requires a dimensionless number" };
1455
+ const baseNumber = base === void 0 ? void 0 : dimensionlessNumber(base);
1456
+ if (base !== void 0 && baseNumber === void 0) return { wrongType: "logarithm requires its base to be a dimensionless number" };
1457
+ if (value.value <= 0) return { domainError: "logarithm requires a number above zero" };
1458
+ if (baseNumber === void 0) return finiteNumber("logarithm", Math.log(value.value));
1459
+ if (baseNumber <= 0 || baseNumber === 1) return { domainError: "logarithm requires its base to be above zero and not one" };
1460
+ if (baseNumber === DECIMAL_BASE) return finiteNumber("logarithm", Math.log10(value.value));
1461
+ if (baseNumber === BINARY_BASE) return finiteNumber("logarithm", Math.log2(value.value));
1462
+ return finiteNumber("logarithm", Math.log(value.value) / Math.log(baseNumber));
1463
+ }
1464
+ });
1465
+ //#endregion
1466
+ //#region src/plain-record.ts
1467
+ /** Narrows `unknown` to a plain JSON-style object: not `null`, not an array. The guard parsed JSON is checked with before its fields are read, in place of an `as Record<string, unknown>` assertion. */
1468
+ function isPlainRecord(value) {
1469
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1470
+ }
1471
+ //#endregion
1472
+ //#region src/input-resolvers.ts
1473
+ /** A plain JSON number, string or boolean is the unit-less value of that kind; anything else must already be a complete `ComputedValue` (the only way to supply units, durations, instants or complex values). Both routes end in `ComputedValueSchema`, so a number that is not finite (`1e999` parses to `Infinity`) is refused whichever way it was written, and a field the schema does not define is dropped rather than carried along. */
1474
+ function toComputedValue(raw) {
1475
+ const candidate = typeof raw === "number" ? {
1476
+ kind: "number",
1477
+ value: raw
1478
+ } : typeof raw === "string" ? {
1479
+ kind: "text",
1480
+ value: raw
1481
+ } : typeof raw === "boolean" ? {
1482
+ kind: "boolean",
1483
+ value: raw
1484
+ } : raw;
1485
+ const parsed = ComputedValueSchema.safeParse(candidate);
1486
+ return parsed.success ? parsed.data : void 0;
1487
+ }
1488
+ /**
1489
+ * Validates a plain object of named inputs, one `ComputedValue` per name (see `toComputedValue` for the accepted shapes). Every entry is checked up front, so a malformed input is reported as one by name rather than surfacing later as a `not-found` reference.
1490
+ */
1491
+ function parseInputs(raw) {
1492
+ if (!isPlainRecord(raw)) return {
1493
+ ok: false,
1494
+ issues: ["inputs must be a JSON object of named values"]
1495
+ };
1496
+ const inputs = /* @__PURE__ */ new Map();
1497
+ const issues = [];
1498
+ for (const [name, value] of Object.entries(raw)) {
1499
+ const computed = toComputedValue(value);
1500
+ if (computed === void 0) issues.push(`inputs.${name}: expected a finite number, text, boolean or a complete computed value`);
1501
+ else inputs.set(name, computed);
1502
+ }
1503
+ return issues.length === 0 ? {
1504
+ ok: true,
1505
+ inputs
1506
+ } : {
1507
+ ok: false,
1508
+ issues
1509
+ };
1510
+ }
1511
+ /**
1512
+ * Synchronous resolvers over a fixed set of named inputs: a `reference` whose key is a string naming an input resolves to it, and every other key, and every `lookup`, is `not-found`. `resolveCollection` throws, because a fixed map of scalars has no collection to hand back and an empty list would silently change what a `fold`, `some` or `every` means; `delegate` and `treeReference` nodes are left unresolved, so they are `wrong-type` like any node whose optional resolver is absent.
1513
+ */
1514
+ function createInputResolvers(inputs) {
1515
+ return {
1516
+ resolveValue: (key) => {
1517
+ const value = typeof key === "string" ? inputs.get(key) : void 0;
1518
+ return value === void 0 ? { found: false } : {
1519
+ found: true,
1520
+ value
1521
+ };
1522
+ },
1523
+ resolveLookup: () => ({ found: false }),
1524
+ resolveCollection: (collection) => {
1525
+ throw new Error(`collection ${JSON.stringify(collection)} cannot be resolved: named inputs hold scalar values only`);
1526
+ }
1527
+ };
1528
+ }
1529
+ //#endregion
1530
+ //#region src/evaluate-document.ts
1531
+ const predicateKinds = new Set(PredicateNodeSchema.options.map((option) => option.shape.kind.value));
1532
+ /** 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
+ const NOT_REPRESENTABLE = "(result): the value is not a finite number";
1534
+ 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 evaluator = createSyncEvaluator({ functions: builtinFunctions });
1536
+ /** 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
+ function describeIssues(issues, parentPath = []) {
1538
+ return issues.flatMap((issue) => {
1539
+ const path = [...parentPath, ...issue.path];
1540
+ if (issue.code === "invalid_union" && issue.errors.length > 0) return describeIssues(issue.errors.reduce((best, branch) => maxPathLength(branch) > maxPathLength(best) ? branch : best), path);
1541
+ return [`${path.length === 0 ? "(root)" : path.join(".")}: ${issue.message}`];
1542
+ });
1543
+ }
1544
+ function maxPathLength(issues) {
1545
+ return Math.max(0, ...issues.map((issue) => issue.path.length));
1546
+ }
1547
+ function resolveTreeKind(tree, requested) {
1548
+ if (requested !== void 0) return requested;
1549
+ const kind = isPlainRecord(tree) ? tree.kind : void 0;
1550
+ if (kind === "treeReference") return "ambiguous";
1551
+ return typeof kind === "string" && predicateKinds.has(kind) ? "predicate" : "expression";
1552
+ }
1553
+ /**
1554
+ * Validates a tree and its named inputs and evaluates it with the built-in function registry (`builtinFunctions`), the evaluation the `trilean evaluate` command performs. The tree kind is read from the root node's `kind` unless `as` names it. There are three outcomes:
1555
+ *
1556
+ * - `evaluated`: an `Evaluation`, definite or indeterminate.
1557
+ * - `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
+ * - `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
+ *
1560
+ * Resolution is limited to what `createInputResolvers` provides, and its collection error propagates for a tree that folds or quantifies over one.
1561
+ */
1562
+ function evaluateDocument({ tree, inputs, as }) {
1563
+ const parsedInputs = parseInputs(inputs ?? {});
1564
+ if (!parsedInputs.ok) return {
1565
+ outcome: "rejected",
1566
+ reason: "invalid",
1567
+ issues: parsedInputs.issues
1568
+ };
1569
+ const resolvers = createInputResolvers(parsedInputs.inputs);
1570
+ const treeKind = resolveTreeKind(tree, as);
1571
+ if (treeKind === "ambiguous") return {
1572
+ outcome: "rejected",
1573
+ reason: "ambiguous-tree-kind",
1574
+ issues: [AMBIGUOUS_TREE_KIND$1]
1575
+ };
1576
+ if (treeKind === "predicate") {
1577
+ const parsed = PredicateNodeSchema.safeParse(tree);
1578
+ if (!parsed.success) return {
1579
+ outcome: "rejected",
1580
+ reason: "invalid",
1581
+ issues: describeIssues(parsed.error.issues)
1582
+ };
1583
+ const node = parsed.data;
1584
+ return {
1585
+ outcome: "evaluated",
1586
+ treeKind,
1587
+ evaluation: evaluator.evaluatePredicate(node, void 0, resolvers)
1588
+ };
1589
+ }
1590
+ const parsed = ExpressionNodeSchema.safeParse(tree);
1591
+ if (!parsed.success) return {
1592
+ outcome: "rejected",
1593
+ reason: "invalid",
1594
+ issues: describeIssues(parsed.error.issues)
1595
+ };
1596
+ const node = parsed.data;
1597
+ const evaluation = evaluator.evaluateValue(node, void 0, resolvers);
1598
+ if (evaluation.status === "definite" && !ComputedValueSchema.safeParse(evaluation.value).success) return {
1599
+ outcome: "unrepresentable",
1600
+ issues: [NOT_REPRESENTABLE]
1601
+ };
1602
+ return {
1603
+ outcome: "evaluated",
1604
+ treeKind,
1605
+ evaluation
1606
+ };
1607
+ }
1608
+ //#endregion
1609
+ //#region cli/run.ts
1610
+ /** The command's wording for a root `treeReference` given without `--as`, in the same `path: message` form as the library's own issues. */
1611
+ const AMBIGUOUS_TREE_KIND = "(root): a treeReference is valid as a predicate and as an expression; pass --as predicate or --as expression";
1612
+ /** The path that stands for standard input. */
1613
+ const STDIN = "-";
1614
+ const usage = `Usage: trilean evaluate <tree.json> [--inputs <inputs.json>] [--as predicate|expression]
1615
+
1616
+ Evaluates a trilean predicate or expression tree and prints the result as JSON.
1617
+
1618
+ <tree.json> the tree, or - to read it from standard input
1619
+ --inputs <file> a JSON object of named values for \`reference\` nodes: a plain
1620
+ number, string or boolean, or a complete computed value such
1621
+ as {"kind":"number","value":2,"unit":{"m":1}}
1622
+ --as <kind> predicate or expression; needed only when the root is a
1623
+ treeReference, otherwise read from the root's kind
1624
+
1625
+ Exit status: 0 for a definite result, 1 for an indeterminate one, 2 when no
1626
+ result was printed: bad usage, an unreadable or invalid file, a tree that folds
1627
+ or quantifies over a collection (the command has none to supply), or a result
1628
+ JSON cannot carry. A lookup, delegate or treeReference it cannot resolve is an
1629
+ indeterminate result (1).
1630
+ `;
1631
+ function isTreeKind(value) {
1632
+ return value === "predicate" || value === "expression";
1633
+ }
1634
+ function readJson(io, path) {
1635
+ const name = path === STDIN ? "standard input" : path;
1636
+ let text;
1637
+ try {
1638
+ text = io.readText(path);
1639
+ } catch (error) {
1640
+ return {
1641
+ ok: false,
1642
+ message: `cannot read ${name}: ${error instanceof Error ? error.message : String(error)}`
1643
+ };
1644
+ }
1645
+ try {
1646
+ return {
1647
+ ok: true,
1648
+ value: JSON.parse(text)
1649
+ };
1650
+ } catch (error) {
1651
+ return {
1652
+ ok: false,
1653
+ message: `${name} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`
1654
+ };
1655
+ }
1656
+ }
1657
+ function reject(io, lines) {
1658
+ io.writeStderr(`${lines.join("\n").trimEnd()}\n`);
1659
+ return 2;
1660
+ }
1661
+ /** Runs the command and returns its exit status; it never throws and never exits the process itself. */
1662
+ function run(args, io) {
1663
+ let parsed;
1664
+ try {
1665
+ parsed = parseCommandLine(args);
1666
+ } catch (error) {
1667
+ return reject(io, [
1668
+ error instanceof Error ? error.message : String(error),
1669
+ "",
1670
+ usage
1671
+ ]);
1672
+ }
1673
+ if (parsed.values.version === true) {
1674
+ io.writeStdout(`${io.version}\n`);
1675
+ return 0;
1676
+ }
1677
+ if (parsed.values.help === true) {
1678
+ io.writeStdout(usage);
1679
+ return 0;
1680
+ }
1681
+ if (parsed.positionals.length === 0) return reject(io, [usage]);
1682
+ const [command, treePath, ...extra] = parsed.positionals;
1683
+ if (command !== "evaluate" || treePath === void 0 || extra.length > 0) return reject(io, [
1684
+ "expected: trilean evaluate <tree.json>",
1685
+ "",
1686
+ usage
1687
+ ]);
1688
+ const as = parsed.values.as;
1689
+ if (as !== void 0 && !isTreeKind(as)) return reject(io, [`--as must be predicate or expression, not ${as}`]);
1690
+ const inputsPath = parsed.values.inputs;
1691
+ if (treePath === STDIN && inputsPath === STDIN) return reject(io, ["the tree and --inputs cannot both be read from standard input"]);
1692
+ const tree = readJson(io, treePath);
1693
+ if (!tree.ok) return reject(io, [tree.message]);
1694
+ const inputs = inputsPath === void 0 ? void 0 : readJson(io, inputsPath);
1695
+ if (inputs !== void 0 && !inputs.ok) return reject(io, [inputs.message]);
1696
+ let result;
1697
+ try {
1698
+ result = evaluateDocument({
1699
+ tree: tree.value,
1700
+ inputs: inputs?.value,
1701
+ as
1702
+ });
1703
+ } catch (error) {
1704
+ return reject(io, [`evaluation could not run: ${error instanceof Error ? error.message : String(error)}`]);
1705
+ }
1706
+ if (result.outcome === "rejected") return reject(io, result.reason === "ambiguous-tree-kind" ? [AMBIGUOUS_TREE_KIND] : result.issues);
1707
+ if (result.outcome === "unrepresentable") return reject(io, result.issues);
1708
+ io.writeStdout(`${JSON.stringify(result.evaluation, void 0, 2)}\n`);
1709
+ return result.evaluation.status === "definite" ? 0 : 1;
1710
+ }
1711
+ function parseCommandLine(args) {
1712
+ return parseArgs({
1713
+ args: [...args],
1714
+ allowPositionals: true,
1715
+ options: {
1716
+ as: { type: "string" },
1717
+ inputs: { type: "string" },
1718
+ help: {
1719
+ type: "boolean",
1720
+ short: "h"
1721
+ },
1722
+ version: {
1723
+ type: "boolean",
1724
+ short: "v"
1725
+ }
1726
+ }
1727
+ });
1728
+ }
1729
+ //#endregion
1730
+ //#region cli/trilean.ts
1731
+ process.stdout.on("error", (error) => {
1732
+ if (error.code !== "EPIPE") throw error;
1733
+ });
1734
+ process.exitCode = run(process.argv.slice(2), {
1735
+ readText: (path) => readFileSync(path === "-" ? 0 : path, "utf8"),
1736
+ writeStdout: (text) => {
1737
+ process.stdout.write(text);
1738
+ },
1739
+ writeStderr: (text) => {
1740
+ process.stderr.write(text);
1741
+ },
1742
+ version
1743
+ });
1744
+ //#endregion
1745
+ export {};