trilean 1.0.13 → 1.2.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.
@@ -19,6 +19,10 @@ const ComputedValueSchema = z.discriminatedUnion("kind", [
19
19
  kind: z.literal("text"),
20
20
  value: z.string()
21
21
  }),
22
+ z.object({
23
+ kind: z.literal("boolean"),
24
+ value: z.boolean()
25
+ }),
22
26
  z.object({
23
27
  kind: z.literal("instant"),
24
28
  value: z.string()
@@ -27,6 +31,12 @@ const ComputedValueSchema = z.discriminatedUnion("kind", [
27
31
  kind: z.literal("duration"),
28
32
  value: z.number(),
29
33
  unit: DurationUnitSchema
34
+ }),
35
+ z.object({
36
+ kind: z.literal("complex"),
37
+ re: z.number(),
38
+ im: z.number(),
39
+ unit: UnitSchema.optional()
30
40
  })
31
41
  ]);
32
42
  /** 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. */
@@ -0,0 +1,24 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/derived-values.ts
3
+ /**
4
+ * `coalesce` is never its own evaluated node kind -- it assembles an ordinary `conditional` whose single case's `when` is an `exists` probe of the current candidate, the same "derived = composition, not new logic" treatment derived-connectives.ts and derived-aggregates.ts already give `xor`/`sum`/`average` (see the "Derived values" section of README.md). Falling through to the next candidate happens only on `exists`'s own `false` -- a genuinely absent value (`not-found`) -- never on a candidate that resolved to something unusable (`wrong-type`/`domain-error`): `exists` already draws exactly that line (see the `exists` section of README.md), and `coalesce` inherits it unmodified rather than re-deciding it.
5
+ *
6
+ * Built right-to-left over the full `[first, second, ...rest]` candidate list via `reduceRight`, which needs no seed value here -- `first`/`second` being required arguments (rather than accepting a single `ExpressionNode[]`) guarantees the list always has at least two elements, so the no-initial-value overload of `reduceRight` never hits an empty array.
7
+ */
8
+ const coalesce = (first, second, ...rest) => [
9
+ first,
10
+ second,
11
+ ...rest
12
+ ].reduceRight((fallback, candidate) => ({
13
+ kind: "conditional",
14
+ cases: [{
15
+ when: {
16
+ kind: "exists",
17
+ operand: candidate
18
+ },
19
+ then: candidate
20
+ }],
21
+ fallback
22
+ }));
23
+ //#endregion
24
+ exports.coalesce = coalesce;
@@ -0,0 +1,10 @@
1
+ import { ExpressionNode } from "./tree.cjs";
2
+ //#region src/derived-values.d.ts
3
+ /**
4
+ * `coalesce` is never its own evaluated node kind -- it assembles an ordinary `conditional` whose single case's `when` is an `exists` probe of the current candidate, the same "derived = composition, not new logic" treatment derived-connectives.ts and derived-aggregates.ts already give `xor`/`sum`/`average` (see the "Derived values" section of README.md). Falling through to the next candidate happens only on `exists`'s own `false` -- a genuinely absent value (`not-found`) -- never on a candidate that resolved to something unusable (`wrong-type`/`domain-error`): `exists` already draws exactly that line (see the `exists` section of README.md), and `coalesce` inherits it unmodified rather than re-deciding it.
5
+ *
6
+ * Built right-to-left over the full `[first, second, ...rest]` candidate list via `reduceRight`, which needs no seed value here -- `first`/`second` being required arguments (rather than accepting a single `ExpressionNode[]`) guarantees the list always has at least two elements, so the no-initial-value overload of `reduceRight` never hits an empty array.
7
+ */
8
+ declare const coalesce: (first: ExpressionNode, second: ExpressionNode, ...rest: readonly ExpressionNode[]) => ExpressionNode;
9
+ //#endregion
10
+ export { coalesce };
@@ -0,0 +1,10 @@
1
+ import { ExpressionNode } from "./tree.js";
2
+ //#region src/derived-values.d.ts
3
+ /**
4
+ * `coalesce` is never its own evaluated node kind -- it assembles an ordinary `conditional` whose single case's `when` is an `exists` probe of the current candidate, the same "derived = composition, not new logic" treatment derived-connectives.ts and derived-aggregates.ts already give `xor`/`sum`/`average` (see the "Derived values" section of README.md). Falling through to the next candidate happens only on `exists`'s own `false` -- a genuinely absent value (`not-found`) -- never on a candidate that resolved to something unusable (`wrong-type`/`domain-error`): `exists` already draws exactly that line (see the `exists` section of README.md), and `coalesce` inherits it unmodified rather than re-deciding it.
5
+ *
6
+ * Built right-to-left over the full `[first, second, ...rest]` candidate list via `reduceRight`, which needs no seed value here -- `first`/`second` being required arguments (rather than accepting a single `ExpressionNode[]`) guarantees the list always has at least two elements, so the no-initial-value overload of `reduceRight` never hits an empty array.
7
+ */
8
+ declare const coalesce: (first: ExpressionNode, second: ExpressionNode, ...rest: readonly ExpressionNode[]) => ExpressionNode;
9
+ //#endregion
10
+ export { coalesce };
@@ -0,0 +1,23 @@
1
+ //#region src/derived-values.ts
2
+ /**
3
+ * `coalesce` is never its own evaluated node kind -- it assembles an ordinary `conditional` whose single case's `when` is an `exists` probe of the current candidate, the same "derived = composition, not new logic" treatment derived-connectives.ts and derived-aggregates.ts already give `xor`/`sum`/`average` (see the "Derived values" section of README.md). Falling through to the next candidate happens only on `exists`'s own `false` -- a genuinely absent value (`not-found`) -- never on a candidate that resolved to something unusable (`wrong-type`/`domain-error`): `exists` already draws exactly that line (see the `exists` section of README.md), and `coalesce` inherits it unmodified rather than re-deciding it.
4
+ *
5
+ * Built right-to-left over the full `[first, second, ...rest]` candidate list via `reduceRight`, which needs no seed value here -- `first`/`second` being required arguments (rather than accepting a single `ExpressionNode[]`) guarantees the list always has at least two elements, so the no-initial-value overload of `reduceRight` never hits an empty array.
6
+ */
7
+ const coalesce = (first, second, ...rest) => [
8
+ first,
9
+ second,
10
+ ...rest
11
+ ].reduceRight((fallback, candidate) => ({
12
+ kind: "conditional",
13
+ cases: [{
14
+ when: {
15
+ kind: "exists",
16
+ operand: candidate
17
+ },
18
+ then: candidate
19
+ }],
20
+ fallback
21
+ }));
22
+ //#endregion
23
+ export { coalesce };
@@ -1,7 +1,9 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_complex = require("./complex.cjs");
2
3
  const require_computed_value = require("./computed-value.cjs");
3
4
  const require_evaluation = require("./evaluation.cjs");
4
5
  const require_functions = require("./functions.cjs");
6
+ const require_tree = require("./tree.cjs");
5
7
  //#region src/evaluator.ts
6
8
  /**
7
9
  * `evaluatePredicateInternal` and `evaluateValueInternal` 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.
@@ -75,6 +77,10 @@ function compareValues(op, left, right) {
75
77
  if (!require_computed_value.unitsEqual(left.unit, right.unit)) return require_evaluation.indeterminate("wrong-type", "cannot compare numbers with incompatible units");
76
78
  return require_evaluation.definite(applyComparisonOperator(op, left.value, right.value));
77
79
  case "text": return require_evaluation.indeterminate("wrong-type", "text values are not comparable via 'compare'; use 'textCompare'");
80
+ case "boolean":
81
+ if (right.kind !== "boolean") return require_evaluation.indeterminate("wrong-type", `cannot compare a 'boolean' value with a '${right.kind}' value`);
82
+ if (op !== "eq" && op !== "neq") return require_evaluation.indeterminate("wrong-type", `booleans have no natural ordering; '${op}' is only defined for 'eq'/'neq'`);
83
+ return require_evaluation.definite(op === "eq" ? left.value === right.value : left.value !== right.value);
78
84
  case "instant": {
79
85
  if (right.kind !== "instant") return require_evaluation.indeterminate("wrong-type", `cannot compare an 'instant' value with a '${right.kind}' value`);
80
86
  const leftEpoch = toEpochMilliseconds(left.value);
@@ -86,6 +92,11 @@ function compareValues(op, left, right) {
86
92
  case "duration":
87
93
  if (right.kind !== "duration") return require_evaluation.indeterminate("wrong-type", `cannot compare a 'duration' value with a '${right.kind}' value`);
88
94
  return require_evaluation.definite(applyComparisonOperator(op, toMilliseconds(left.value, left.unit), toMilliseconds(right.value, right.unit)));
95
+ case "complex":
96
+ if (op !== "eq" && op !== "neq") return require_evaluation.indeterminate("wrong-type", `ordering operator '${op}' is not defined for complex values; the complex plane has no total order`);
97
+ if (right.kind !== "complex") return require_evaluation.indeterminate("wrong-type", `cannot compare a 'complex' value with a '${right.kind}' value`);
98
+ if (!require_computed_value.unitsEqual(left.unit, right.unit)) return require_evaluation.indeterminate("wrong-type", "cannot compare complex values with incompatible units");
99
+ return require_evaluation.definite(op === "eq" ? left.re === right.re && left.im === right.im : left.re !== right.re || left.im !== right.im);
89
100
  default: throw new Error("unreachable computed-value kind");
90
101
  }
91
102
  }
@@ -120,6 +131,9 @@ function computeMembershipMatch(operand, candidate) {
120
131
  case "text":
121
132
  if (candidate.kind !== "text") return require_evaluation.indeterminate("wrong-type", `cannot compare a 'text' value with a '${candidate.kind}' value for membership`);
122
133
  return require_evaluation.definite(operand.value === candidate.value);
134
+ case "boolean":
135
+ if (candidate.kind !== "boolean") return require_evaluation.indeterminate("wrong-type", `cannot compare a 'boolean' value with a '${candidate.kind}' value for membership`);
136
+ return require_evaluation.definite(operand.value === candidate.value);
123
137
  case "instant": {
124
138
  if (candidate.kind !== "instant") return require_evaluation.indeterminate("wrong-type", `cannot compare an 'instant' value with a '${candidate.kind}' value for membership`);
125
139
  const operandEpoch = toEpochMilliseconds(operand.value);
@@ -131,6 +145,10 @@ function computeMembershipMatch(operand, candidate) {
131
145
  case "duration":
132
146
  if (candidate.kind !== "duration") return require_evaluation.indeterminate("wrong-type", `cannot compare a 'duration' value with a '${candidate.kind}' value for membership`);
133
147
  return require_evaluation.definite(toMilliseconds(operand.value, operand.unit) === toMilliseconds(candidate.value, candidate.unit));
148
+ case "complex":
149
+ if (candidate.kind !== "complex") return require_evaluation.indeterminate("wrong-type", `cannot compare a 'complex' value with a '${candidate.kind}' value for membership`);
150
+ if (!require_computed_value.unitsEqual(operand.unit, candidate.unit)) return require_evaluation.indeterminate("wrong-type", "cannot compare complex values with incompatible units for membership");
151
+ return require_evaluation.definite(operand.re === candidate.re && operand.im === candidate.im);
134
152
  default: throw new Error("unreachable computed-value kind");
135
153
  }
136
154
  }
@@ -151,8 +169,15 @@ function applyNegate(operand) {
151
169
  value: -operand.value,
152
170
  unit: operand.unit
153
171
  });
172
+ case "complex": return require_evaluation.definite({
173
+ kind: "complex",
174
+ re: -operand.re,
175
+ im: -operand.im,
176
+ unit: operand.unit
177
+ });
154
178
  case "text":
155
- case "instant": return require_evaluation.indeterminate("wrong-type", `cannot negate a '${operand.kind}' value`);
179
+ case "instant":
180
+ case "boolean": return require_evaluation.indeterminate("wrong-type", `cannot negate a '${operand.kind}' value`);
156
181
  default: throw new Error("unreachable computed-value kind");
157
182
  }
158
183
  }
@@ -222,6 +247,75 @@ function applyArithmeticOnDurations(op, left, right) {
222
247
  default: throw new Error("unreachable arithmetic operator");
223
248
  }
224
249
  }
250
+ /** 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. */
251
+ function toComplexValue(value) {
252
+ if (value.kind === "complex") return value;
253
+ return {
254
+ kind: "complex",
255
+ re: value.value,
256
+ im: 0,
257
+ unit: value.unit
258
+ };
259
+ }
260
+ /** The complex product, as its own component-level helper rather than only a branch of the operator switch below, because `power`'s repeated multiplication needs exactly this and must not re-derive it. */
261
+ function multiplyComplexValues(left, right) {
262
+ return {
263
+ kind: "complex",
264
+ re: left.re * right.re - left.im * right.im,
265
+ im: left.re * right.im + left.im * right.re,
266
+ unit: require_computed_value.combineUnitsForMultiply(left.unit, right.unit)
267
+ };
268
+ }
269
+ /** 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. */
270
+ function applyArithmeticOnComplex(op, left, right) {
271
+ switch (op) {
272
+ case "add":
273
+ if (!require_computed_value.unitsEqual(left.unit, right.unit)) return require_evaluation.indeterminate("wrong-type", "cannot add complex values with incompatible units");
274
+ return require_evaluation.definite({
275
+ kind: "complex",
276
+ re: left.re + right.re,
277
+ im: left.im + right.im,
278
+ unit: left.unit
279
+ });
280
+ case "subtract":
281
+ if (!require_computed_value.unitsEqual(left.unit, right.unit)) return require_evaluation.indeterminate("wrong-type", "cannot subtract complex values with incompatible units");
282
+ return require_evaluation.definite({
283
+ kind: "complex",
284
+ re: left.re - right.re,
285
+ im: left.im - right.im,
286
+ unit: left.unit
287
+ });
288
+ case "multiply": return require_evaluation.definite(multiplyComplexValues(left, right));
289
+ case "divide": {
290
+ const divisorSquaredMagnitude = right.re * right.re + right.im * right.im;
291
+ if (divisorSquaredMagnitude === 0) return require_evaluation.indeterminate("domain-error", "division by zero");
292
+ return require_evaluation.definite({
293
+ kind: "complex",
294
+ re: (left.re * right.re + left.im * right.im) / divisorSquaredMagnitude,
295
+ im: (left.im * right.re - left.re * right.im) / divisorSquaredMagnitude,
296
+ unit: require_computed_value.combineUnitsForDivide(left.unit, right.unit)
297
+ });
298
+ }
299
+ case "modulo": return require_evaluation.indeterminate("domain-error", "'modulo' is undefined for complex values");
300
+ default: throw new Error("unreachable arithmetic operator");
301
+ }
302
+ }
303
+ /** `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* (see the "Complex values" section of README.md for why an arbitrary complex exponent stays out of scope). */
304
+ function applyComplexPower(base, exponent) {
305
+ if (exponent.kind !== "number" || !Number.isInteger(exponent.value)) return require_evaluation.indeterminate("wrong-type", "'power' with a complex operand requires a real integer exponent");
306
+ if (!isDimensionless(base.unit) || !isDimensionless(exponent.unit)) return require_evaluation.indeterminate("wrong-type", "'power' requires dimensionless operands");
307
+ const complexUnit = {
308
+ kind: "complex",
309
+ re: 1,
310
+ im: 0,
311
+ unit: {}
312
+ };
313
+ const complexBase = toComplexValue(base);
314
+ let repeatedProduct = complexUnit;
315
+ for (let applied = 0; applied < Math.abs(exponent.value); applied += 1) repeatedProduct = multiplyComplexValues(repeatedProduct, complexBase);
316
+ if (exponent.value >= 0) return require_evaluation.definite(repeatedProduct);
317
+ return applyArithmeticOnComplex("divide", complexUnit, repeatedProduct);
318
+ }
225
319
  /**
226
320
  * 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.
227
321
  */
@@ -250,21 +344,27 @@ function applyArithmetic(op, left, right) {
250
344
  if (left.kind === "instant" || right.kind === "instant") return require_evaluation.indeterminate("wrong-type", `arithmetic operator '${op}' is not defined between a '${left.kind}' and a '${right.kind}' value`);
251
345
  if (left.kind === "duration" && right.kind === "duration") return applyArithmeticOnDurations(op, left, right);
252
346
  if (left.kind === "duration" || right.kind === "duration") return require_evaluation.indeterminate("wrong-type", `arithmetic operator '${op}' is not defined between a '${left.kind}' and a '${right.kind}' value`);
253
- if (left.kind !== "number") return require_evaluation.indeterminate("wrong-type", `arithmetic requires numeric operands; got a '${left.kind}' value`);
254
- if (right.kind !== "number") return require_evaluation.indeterminate("wrong-type", `arithmetic requires numeric operands; got a '${right.kind}' value`);
347
+ if (left.kind !== "number" && left.kind !== "complex") return require_evaluation.indeterminate("wrong-type", `arithmetic requires numeric operands; got a '${left.kind}' value`);
348
+ if (right.kind !== "number" && right.kind !== "complex") return require_evaluation.indeterminate("wrong-type", `arithmetic requires numeric operands; got a '${right.kind}' value`);
349
+ if (left.kind === "complex" || right.kind === "complex") {
350
+ if (op === "power") return applyComplexPower(left, right);
351
+ return applyArithmeticOnComplex(op, toComplexValue(left), toComplexValue(right));
352
+ }
255
353
  return applyArithmeticOnNumbers(op, left, right);
256
354
  }
355
+ /** A defense-in-depth guard against a long acyclic `treeReference` chain exhausting the call stack -- distinct from, and layered on top of, the cycle detector below (`visitedTreeKeys`), which catches an actual repeat immediately and more precisely. */
356
+ const MAX_TREE_REFERENCE_DEPTH = 100;
257
357
  /**
258
358
  * Collection resolution shared by the quantifiers (`some`/`every`, below) and by `fold` (a later phase): resolves the opaque `collection` reference to its concrete candidate list via `resolvers.resolveCollection`, then evaluates each candidate's optional `filter` 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.
259
359
  */
260
- async function resolveParticipatingItems(collection, filter, context, resolvers, functions) {
360
+ async function resolveParticipatingItems(collection, filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth) {
261
361
  const candidates = await resolvers.resolveCollection(collection, context);
262
362
  return Promise.all(candidates.map(async (item) => {
263
363
  if (filter === void 0) return {
264
364
  item,
265
365
  filterOutcome: "include"
266
366
  };
267
- const filterResult = await evaluatePredicateInternal(filter, item, resolvers, void 0, functions);
367
+ const filterResult = await evaluatePredicateInternal(filter, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
268
368
  if (filterResult.status === "indeterminate") return {
269
369
  item,
270
370
  filterOutcome: filterResult
@@ -282,40 +382,40 @@ function firstFilterIndeterminate(participating) {
282
382
  if (filterOutcome.status === "indeterminate") return filterOutcome.reason;
283
383
  }
284
384
  }
285
- async function evaluatePredicateInternal(node, context, resolvers, accumulator, functions) {
385
+ async function evaluatePredicateInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth) {
286
386
  switch (node.kind) {
287
387
  case "not": {
288
- const operand = await evaluatePredicateInternal(node.operand, context, resolvers, accumulator, functions);
388
+ const operand = await evaluatePredicateInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
289
389
  if (operand.status === "indeterminate") return operand;
290
390
  return require_evaluation.definite(!operand.value);
291
391
  }
292
392
  case "and": {
293
- const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions)]);
393
+ const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
294
394
  return combineAnd(left, right);
295
395
  }
296
396
  case "or": {
297
- const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions)]);
397
+ const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
298
398
  return combineOr(left, right);
299
399
  }
300
- case "allOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions)))).reduce(combineAnd, require_evaluation.definite(true));
301
- case "anyOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions)))).reduce(combineOr, require_evaluation.definite(false));
400
+ case "allOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)))).reduce(combineAnd, require_evaluation.definite(true));
401
+ case "anyOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)))).reduce(combineOr, require_evaluation.definite(false));
302
402
  case "compare": {
303
- const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions), evaluateValueInternal(node.right, context, resolvers, accumulator, functions)]);
403
+ const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
304
404
  if (left.status === "indeterminate") return left;
305
405
  if (right.status === "indeterminate") return right;
306
406
  return compareValues(node.op, left.value, right.value);
307
407
  }
308
408
  case "textCompare": {
309
- const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions), evaluateValueInternal(node.right, context, resolvers, accumulator, functions)]);
409
+ const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
310
410
  if (left.status === "indeterminate") return left;
311
411
  if (right.status === "indeterminate") return right;
312
412
  return compareText(node.op, left.value, right.value);
313
413
  }
314
414
  case "memberOf": {
315
- const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions);
415
+ const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
316
416
  if (operandResult.status === "indeterminate") return operandResult;
317
417
  const candidateOutcomes = await Promise.all(node.candidates.map(async (candidate) => {
318
- const candidateResult = await evaluateValueInternal(candidate, context, resolvers, accumulator, functions);
418
+ const candidateResult = await evaluateValueInternal(candidate, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
319
419
  if (candidateResult.status === "indeterminate") return candidateResult;
320
420
  return computeMembershipMatch(operandResult.value, candidateResult.value);
321
421
  }));
@@ -328,32 +428,43 @@ async function evaluatePredicateInternal(node, context, resolvers, accumulator,
328
428
  return require_evaluation.definite(node.op === "notIn");
329
429
  }
330
430
  case "exists": {
331
- const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions);
431
+ const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
332
432
  if (operandResult.status === "indeterminate" && operandResult.reason.code === "not-found") return require_evaluation.definite(false);
333
433
  return require_evaluation.definite(true);
334
434
  }
335
435
  case "some":
336
436
  case "every": {
337
- const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions);
437
+ const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth);
338
438
  const votes = (await Promise.all(participating.map(async ({ item, filterOutcome }) => {
339
439
  if (filterOutcome === "exclude") return void 0;
340
440
  if (filterOutcome !== "include") return filterOutcome;
341
- return evaluatePredicateInternal(node.item, item, resolvers, void 0, functions);
441
+ return evaluatePredicateInternal(node.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
342
442
  }))).filter((vote) => vote !== void 0);
343
443
  const combine = node.kind === "some" ? combineOr : combineAnd;
344
444
  const identity = node.kind === "some" ? require_evaluation.definite(false) : require_evaluation.definite(true);
345
445
  return votes.reduce(combine, identity);
346
446
  }
447
+ case "treeReference": {
448
+ if (resolvers.resolveTree === void 0) return require_evaluation.indeterminate("wrong-type", "no tree resolver registered for treeReference nodes");
449
+ const keyString = JSON.stringify(node.key);
450
+ if (visitedTreeKeys.has(keyString)) return require_evaluation.indeterminate("domain-error", "circular treeReference detected");
451
+ if (treeReferenceDepth >= MAX_TREE_REFERENCE_DEPTH) return require_evaluation.indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${MAX_TREE_REFERENCE_DEPTH.toString()}`);
452
+ const resolution = await resolvers.resolveTree(node.key, context);
453
+ if (!resolution.found) return require_evaluation.indeterminate("not-found", "treeReference key did not resolve to a tree");
454
+ const parsed = require_tree.PredicateNodeSchema.safeParse(resolution.node);
455
+ if (!parsed.success) return require_evaluation.indeterminate("wrong-type", "the referenced tree is not a valid PredicateNode");
456
+ return evaluatePredicateInternal(parsed.data, context, resolvers, accumulator, functions, /* @__PURE__ */ new Set([...visitedTreeKeys, keyString]), treeReferenceDepth + 1);
457
+ }
347
458
  default: throw new Error("unreachable predicate node kind");
348
459
  }
349
460
  }
350
- async function evaluateValueInternal(node, context, resolvers, accumulator, functions) {
461
+ async function evaluateValueInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth) {
351
462
  switch (node.kind) {
352
463
  case "reference": {
353
464
  const resolution = await resolvers.resolveValue(node.key, context);
354
465
  if (!resolution.found) return require_evaluation.indeterminate("not-found", `no value found for reference key ${JSON.stringify(node.key)}`);
355
466
  if (node.unit !== void 0) {
356
- if (resolution.value.kind !== "number") return require_evaluation.indeterminate("wrong-type", "a unit was expected on a reference that resolved to a non-numeric value");
467
+ if (resolution.value.kind !== "number" && resolution.value.kind !== "complex") return require_evaluation.indeterminate("wrong-type", "a unit was expected on a reference that resolved to a non-numeric value");
357
468
  if (!require_computed_value.unitsEqual(node.unit, resolution.value.unit)) return require_evaluation.indeterminate("wrong-type", "the resolved value's unit does not match the reference's expected unit");
358
469
  }
359
470
  return require_evaluation.definite(resolution.value);
@@ -362,7 +473,7 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
362
473
  if (accumulator === void 0) return require_evaluation.indeterminate("wrong-type", "accumulator used outside a reduce fold's combine expression");
363
474
  return require_evaluation.definite(accumulator);
364
475
  case "call": {
365
- const argResults = await Promise.all(node.args.map(async (arg) => evaluateValueInternal(arg, context, resolvers, accumulator, functions)));
476
+ const argResults = await Promise.all(node.args.map(async (arg) => evaluateValueInternal(arg, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)));
366
477
  const args = [];
367
478
  for (const result of argResults) {
368
479
  if (result.status === "indeterminate") return result;
@@ -383,6 +494,10 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
383
494
  kind: "text",
384
495
  value: node.value
385
496
  });
497
+ case "booleanLiteral": return require_evaluation.definite({
498
+ kind: "boolean",
499
+ value: node.value
500
+ });
386
501
  case "instantLiteral": return require_evaluation.definite({
387
502
  kind: "instant",
388
503
  value: node.value
@@ -392,19 +507,27 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
392
507
  value: node.value,
393
508
  unit: node.unit
394
509
  });
510
+ case "complexLiteral":
511
+ if ("re" in node) return require_evaluation.definite({
512
+ kind: "complex",
513
+ re: node.re,
514
+ im: node.im,
515
+ unit: node.unit
516
+ });
517
+ return require_evaluation.definite(require_complex.complexFromPolar(node.magnitude, node.phase, node.unit));
395
518
  case "arithmetic": {
396
- const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions), evaluateValueInternal(node.right, context, resolvers, accumulator, functions)]);
519
+ const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
397
520
  if (left.status === "indeterminate") return left;
398
521
  if (right.status === "indeterminate") return right;
399
522
  return applyArithmetic(node.op, left.value, right.value);
400
523
  }
401
524
  case "negate": {
402
- const operand = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions);
525
+ const operand = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
403
526
  if (operand.status === "indeterminate") return operand;
404
527
  return applyNegate(operand.value);
405
528
  }
406
529
  case "lookup": {
407
- const keyResults = await Promise.all(node.keys.map(async (key) => evaluateValueInternal(key, context, resolvers, accumulator, functions)));
530
+ const keyResults = await Promise.all(node.keys.map(async (key) => evaluateValueInternal(key, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)));
408
531
  const keyValues = [];
409
532
  for (const result of keyResults) {
410
533
  if (result.status === "indeterminate") return result;
@@ -414,15 +537,32 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
414
537
  if (!resolution.found) return require_evaluation.indeterminate("not-found", `no match found in lookup table ${JSON.stringify(node.table)}`);
415
538
  return require_evaluation.definite(resolution.value);
416
539
  }
417
- case "conditional":
418
- for (const { when, then } of node.cases) {
419
- const whenResult = await evaluatePredicateInternal(when, context, resolvers, accumulator, functions);
420
- if (whenResult.status === "indeterminate") return whenResult;
421
- if (whenResult.value) return evaluateValueInternal(then, context, resolvers, accumulator, functions);
540
+ case "conditional": {
541
+ if ((node.hitPolicy ?? "first") === "first") {
542
+ for (const { when, then } of node.cases) {
543
+ const whenResult = await evaluatePredicateInternal(when, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
544
+ if (whenResult.status === "indeterminate") return whenResult;
545
+ if (whenResult.value) return evaluateValueInternal(then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
546
+ }
547
+ return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
422
548
  }
423
- return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions);
549
+ const evaluatedCases = await Promise.all(node.cases.map(async ({ when, then }) => ({
550
+ then,
551
+ whenResult: await evaluatePredicateInternal(when, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)
552
+ })));
553
+ const matches = evaluatedCases.filter(({ whenResult }) => whenResult.status === "definite" && whenResult.value);
554
+ if (matches.length >= 2) return require_evaluation.indeterminate("domain-error", "more than one case matched under the 'unique' hit policy");
555
+ const reason = require_evaluation.firstIndeterminate(...evaluatedCases.map(({ whenResult }) => whenResult));
556
+ if (reason !== void 0) return {
557
+ status: "indeterminate",
558
+ reason
559
+ };
560
+ const [match] = matches;
561
+ if (match === void 0) return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
562
+ return evaluateValueInternal(match.then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
563
+ }
424
564
  case "fold": {
425
- const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions);
565
+ const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth);
426
566
  const filterIndeterminateReason = firstFilterIndeterminate(participating);
427
567
  if (filterIndeterminateReason !== void 0) return {
428
568
  status: "indeterminate",
@@ -430,11 +570,11 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
430
570
  };
431
571
  const includedItems = participating.filter(({ filterOutcome }) => filterOutcome === "include").map(({ item }) => item);
432
572
  if (node.combiner.mode === "reduce") {
433
- const initialResult = await evaluateValueInternal(node.combiner.initial, context, resolvers, void 0, functions);
573
+ const initialResult = await evaluateValueInternal(node.combiner.initial, context, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
434
574
  if (initialResult.status === "indeterminate") return initialResult;
435
575
  let runningAccumulator = initialResult.value;
436
576
  for (const item of includedItems) {
437
- const stepResult = await evaluateValueInternal(node.combiner.combine, item, resolvers, runningAccumulator, functions);
577
+ const stepResult = await evaluateValueInternal(node.combiner.combine, item, resolvers, runningAccumulator, functions, visitedTreeKeys, treeReferenceDepth);
438
578
  if (stepResult.status === "indeterminate") return stepResult;
439
579
  runningAccumulator = stepResult.value;
440
580
  }
@@ -444,7 +584,7 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
444
584
  const dominatesOp = node.combiner.mode === "max" ? "gt" : "lt";
445
585
  let runningExtremum;
446
586
  for (const item of includedItems) {
447
- const itemResult = await evaluateValueInternal(node.combiner.item, item, resolvers, void 0, functions);
587
+ const itemResult = await evaluateValueInternal(node.combiner.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
448
588
  if (itemResult.status === "indeterminate") return itemResult;
449
589
  if (runningExtremum === void 0) {
450
590
  runningExtremum = itemResult.value;
@@ -463,6 +603,17 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
463
603
  if (!resolution.found) return require_evaluation.indeterminate("not-found", `delegate handler for external system '${node.system}' reported no value`);
464
604
  return require_evaluation.definite(resolution.value);
465
605
  }
606
+ case "treeReference": {
607
+ if (resolvers.resolveTree === void 0) return require_evaluation.indeterminate("wrong-type", "no tree resolver registered for treeReference nodes");
608
+ const keyString = JSON.stringify(node.key);
609
+ if (visitedTreeKeys.has(keyString)) return require_evaluation.indeterminate("domain-error", "circular treeReference detected");
610
+ if (treeReferenceDepth >= MAX_TREE_REFERENCE_DEPTH) return require_evaluation.indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${MAX_TREE_REFERENCE_DEPTH.toString()}`);
611
+ const resolution = await resolvers.resolveTree(node.key, context);
612
+ if (!resolution.found) return require_evaluation.indeterminate("not-found", "treeReference key did not resolve to a tree");
613
+ const parsed = require_tree.ExpressionNodeSchema.safeParse(resolution.node);
614
+ if (!parsed.success) return require_evaluation.indeterminate("wrong-type", "the referenced tree is not a valid ExpressionNode");
615
+ return evaluateValueInternal(parsed.data, context, resolvers, accumulator, functions, /* @__PURE__ */ new Set([...visitedTreeKeys, keyString]), treeReferenceDepth + 1);
616
+ }
466
617
  default: throw new Error("unreachable expression node kind");
467
618
  }
468
619
  }
@@ -471,8 +622,8 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
471
622
  */
472
623
  function createEvaluator({ functions = require_functions.emptyFunctionRegistry }) {
473
624
  return {
474
- evaluatePredicate: async (node, context, resolvers) => evaluatePredicateInternal(node, context, resolvers, void 0, functions),
475
- evaluateValue: async (node, context, resolvers) => evaluateValueInternal(node, context, resolvers, void 0, functions)
625
+ evaluatePredicate: async (node, context, resolvers) => evaluatePredicateInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0),
626
+ evaluateValue: async (node, context, resolvers) => evaluateValueInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0)
476
627
  };
477
628
  }
478
629
  const { evaluatePredicate, evaluateValue } = createEvaluator({});