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.
package/dist/evaluator.js CHANGED
@@ -1,6 +1,8 @@
1
+ import { complexFromPolar } from "./complex.js";
1
2
  import { combineUnitsForDivide, combineUnitsForMultiply, unitsEqual } from "./computed-value.js";
2
3
  import { definite, firstIndeterminate, indeterminate } from "./evaluation.js";
3
4
  import { emptyFunctionRegistry } from "./functions.js";
5
+ import { ExpressionNodeSchema, PredicateNodeSchema } from "./tree.js";
4
6
  //#region src/evaluator.ts
5
7
  /**
6
8
  * `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.
@@ -74,6 +76,10 @@ function compareValues(op, left, right) {
74
76
  if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot compare numbers with incompatible units");
75
77
  return definite(applyComparisonOperator(op, left.value, right.value));
76
78
  case "text": return indeterminate("wrong-type", "text values are not comparable via 'compare'; use 'textCompare'");
79
+ case "boolean":
80
+ if (right.kind !== "boolean") return indeterminate("wrong-type", `cannot compare a 'boolean' value with a '${right.kind}' value`);
81
+ if (op !== "eq" && op !== "neq") return indeterminate("wrong-type", `booleans have no natural ordering; '${op}' is only defined for 'eq'/'neq'`);
82
+ return definite(op === "eq" ? left.value === right.value : left.value !== right.value);
77
83
  case "instant": {
78
84
  if (right.kind !== "instant") return indeterminate("wrong-type", `cannot compare an 'instant' value with a '${right.kind}' value`);
79
85
  const leftEpoch = toEpochMilliseconds(left.value);
@@ -85,6 +91,11 @@ function compareValues(op, left, right) {
85
91
  case "duration":
86
92
  if (right.kind !== "duration") return indeterminate("wrong-type", `cannot compare a 'duration' value with a '${right.kind}' value`);
87
93
  return definite(applyComparisonOperator(op, toMilliseconds(left.value, left.unit), toMilliseconds(right.value, right.unit)));
94
+ case "complex":
95
+ 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`);
96
+ if (right.kind !== "complex") return indeterminate("wrong-type", `cannot compare a 'complex' value with a '${right.kind}' value`);
97
+ if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot compare complex values with incompatible units");
98
+ return definite(op === "eq" ? left.re === right.re && left.im === right.im : left.re !== right.re || left.im !== right.im);
88
99
  default: throw new Error("unreachable computed-value kind");
89
100
  }
90
101
  }
@@ -119,6 +130,9 @@ function computeMembershipMatch(operand, candidate) {
119
130
  case "text":
120
131
  if (candidate.kind !== "text") return indeterminate("wrong-type", `cannot compare a 'text' value with a '${candidate.kind}' value for membership`);
121
132
  return definite(operand.value === candidate.value);
133
+ case "boolean":
134
+ if (candidate.kind !== "boolean") return indeterminate("wrong-type", `cannot compare a 'boolean' value with a '${candidate.kind}' value for membership`);
135
+ return definite(operand.value === candidate.value);
122
136
  case "instant": {
123
137
  if (candidate.kind !== "instant") return indeterminate("wrong-type", `cannot compare an 'instant' value with a '${candidate.kind}' value for membership`);
124
138
  const operandEpoch = toEpochMilliseconds(operand.value);
@@ -130,6 +144,10 @@ function computeMembershipMatch(operand, candidate) {
130
144
  case "duration":
131
145
  if (candidate.kind !== "duration") return indeterminate("wrong-type", `cannot compare a 'duration' value with a '${candidate.kind}' value for membership`);
132
146
  return definite(toMilliseconds(operand.value, operand.unit) === toMilliseconds(candidate.value, candidate.unit));
147
+ case "complex":
148
+ if (candidate.kind !== "complex") return indeterminate("wrong-type", `cannot compare a 'complex' value with a '${candidate.kind}' value for membership`);
149
+ if (!unitsEqual(operand.unit, candidate.unit)) return indeterminate("wrong-type", "cannot compare complex values with incompatible units for membership");
150
+ return definite(operand.re === candidate.re && operand.im === candidate.im);
133
151
  default: throw new Error("unreachable computed-value kind");
134
152
  }
135
153
  }
@@ -150,8 +168,15 @@ function applyNegate(operand) {
150
168
  value: -operand.value,
151
169
  unit: operand.unit
152
170
  });
171
+ case "complex": return definite({
172
+ kind: "complex",
173
+ re: -operand.re,
174
+ im: -operand.im,
175
+ unit: operand.unit
176
+ });
153
177
  case "text":
154
- case "instant": return indeterminate("wrong-type", `cannot negate a '${operand.kind}' value`);
178
+ case "instant":
179
+ case "boolean": return indeterminate("wrong-type", `cannot negate a '${operand.kind}' value`);
155
180
  default: throw new Error("unreachable computed-value kind");
156
181
  }
157
182
  }
@@ -221,6 +246,75 @@ function applyArithmeticOnDurations(op, left, right) {
221
246
  default: throw new Error("unreachable arithmetic operator");
222
247
  }
223
248
  }
249
+ /** 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. */
250
+ function toComplexValue(value) {
251
+ if (value.kind === "complex") return value;
252
+ return {
253
+ kind: "complex",
254
+ re: value.value,
255
+ im: 0,
256
+ unit: value.unit
257
+ };
258
+ }
259
+ /** 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. */
260
+ function multiplyComplexValues(left, right) {
261
+ return {
262
+ kind: "complex",
263
+ re: left.re * right.re - left.im * right.im,
264
+ im: left.re * right.im + left.im * right.re,
265
+ unit: combineUnitsForMultiply(left.unit, right.unit)
266
+ };
267
+ }
268
+ /** 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. */
269
+ function applyArithmeticOnComplex(op, left, right) {
270
+ switch (op) {
271
+ case "add":
272
+ if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot add complex values with incompatible units");
273
+ return definite({
274
+ kind: "complex",
275
+ re: left.re + right.re,
276
+ im: left.im + right.im,
277
+ unit: left.unit
278
+ });
279
+ case "subtract":
280
+ if (!unitsEqual(left.unit, right.unit)) return indeterminate("wrong-type", "cannot subtract complex values with incompatible units");
281
+ return definite({
282
+ kind: "complex",
283
+ re: left.re - right.re,
284
+ im: left.im - right.im,
285
+ unit: left.unit
286
+ });
287
+ case "multiply": return definite(multiplyComplexValues(left, right));
288
+ case "divide": {
289
+ const divisorSquaredMagnitude = right.re * right.re + right.im * right.im;
290
+ if (divisorSquaredMagnitude === 0) return indeterminate("domain-error", "division by zero");
291
+ return definite({
292
+ kind: "complex",
293
+ re: (left.re * right.re + left.im * right.im) / divisorSquaredMagnitude,
294
+ im: (left.im * right.re - left.re * right.im) / divisorSquaredMagnitude,
295
+ unit: combineUnitsForDivide(left.unit, right.unit)
296
+ });
297
+ }
298
+ case "modulo": return indeterminate("domain-error", "'modulo' is undefined for complex values");
299
+ default: throw new Error("unreachable arithmetic operator");
300
+ }
301
+ }
302
+ /** `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). */
303
+ function applyComplexPower(base, exponent) {
304
+ if (exponent.kind !== "number" || !Number.isInteger(exponent.value)) return indeterminate("wrong-type", "'power' with a complex operand requires a real integer exponent");
305
+ if (!isDimensionless(base.unit) || !isDimensionless(exponent.unit)) return indeterminate("wrong-type", "'power' requires dimensionless operands");
306
+ const complexUnit = {
307
+ kind: "complex",
308
+ re: 1,
309
+ im: 0,
310
+ unit: {}
311
+ };
312
+ const complexBase = toComplexValue(base);
313
+ let repeatedProduct = complexUnit;
314
+ for (let applied = 0; applied < Math.abs(exponent.value); applied += 1) repeatedProduct = multiplyComplexValues(repeatedProduct, complexBase);
315
+ if (exponent.value >= 0) return definite(repeatedProduct);
316
+ return applyArithmeticOnComplex("divide", complexUnit, repeatedProduct);
317
+ }
224
318
  /**
225
319
  * 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.
226
320
  */
@@ -249,21 +343,27 @@ function applyArithmetic(op, left, right) {
249
343
  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`);
250
344
  if (left.kind === "duration" && right.kind === "duration") return applyArithmeticOnDurations(op, left, right);
251
345
  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`);
252
- if (left.kind !== "number") return indeterminate("wrong-type", `arithmetic requires numeric operands; got a '${left.kind}' value`);
253
- if (right.kind !== "number") return indeterminate("wrong-type", `arithmetic requires numeric operands; got a '${right.kind}' value`);
346
+ if (left.kind !== "number" && left.kind !== "complex") return indeterminate("wrong-type", `arithmetic requires numeric operands; got a '${left.kind}' value`);
347
+ if (right.kind !== "number" && right.kind !== "complex") return indeterminate("wrong-type", `arithmetic requires numeric operands; got a '${right.kind}' value`);
348
+ if (left.kind === "complex" || right.kind === "complex") {
349
+ if (op === "power") return applyComplexPower(left, right);
350
+ return applyArithmeticOnComplex(op, toComplexValue(left), toComplexValue(right));
351
+ }
254
352
  return applyArithmeticOnNumbers(op, left, right);
255
353
  }
354
+ /** 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. */
355
+ const MAX_TREE_REFERENCE_DEPTH = 100;
256
356
  /**
257
357
  * 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.
258
358
  */
259
- async function resolveParticipatingItems(collection, filter, context, resolvers, functions) {
359
+ async function resolveParticipatingItems(collection, filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth) {
260
360
  const candidates = await resolvers.resolveCollection(collection, context);
261
361
  return Promise.all(candidates.map(async (item) => {
262
362
  if (filter === void 0) return {
263
363
  item,
264
364
  filterOutcome: "include"
265
365
  };
266
- const filterResult = await evaluatePredicateInternal(filter, item, resolvers, void 0, functions);
366
+ const filterResult = await evaluatePredicateInternal(filter, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
267
367
  if (filterResult.status === "indeterminate") return {
268
368
  item,
269
369
  filterOutcome: filterResult
@@ -281,40 +381,40 @@ function firstFilterIndeterminate(participating) {
281
381
  if (filterOutcome.status === "indeterminate") return filterOutcome.reason;
282
382
  }
283
383
  }
284
- async function evaluatePredicateInternal(node, context, resolvers, accumulator, functions) {
384
+ async function evaluatePredicateInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth) {
285
385
  switch (node.kind) {
286
386
  case "not": {
287
- const operand = await evaluatePredicateInternal(node.operand, context, resolvers, accumulator, functions);
387
+ const operand = await evaluatePredicateInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
288
388
  if (operand.status === "indeterminate") return operand;
289
389
  return definite(!operand.value);
290
390
  }
291
391
  case "and": {
292
- const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions)]);
392
+ const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
293
393
  return combineAnd(left, right);
294
394
  }
295
395
  case "or": {
296
- const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions)]);
396
+ const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
297
397
  return combineOr(left, right);
298
398
  }
299
- case "allOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions)))).reduce(combineAnd, definite(true));
300
- case "anyOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions)))).reduce(combineOr, definite(false));
399
+ case "allOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)))).reduce(combineAnd, definite(true));
400
+ case "anyOf": return (await Promise.all(node.operands.map(async (operand) => evaluatePredicateInternal(operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)))).reduce(combineOr, definite(false));
301
401
  case "compare": {
302
- const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions), evaluateValueInternal(node.right, context, resolvers, accumulator, functions)]);
402
+ const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
303
403
  if (left.status === "indeterminate") return left;
304
404
  if (right.status === "indeterminate") return right;
305
405
  return compareValues(node.op, left.value, right.value);
306
406
  }
307
407
  case "textCompare": {
308
- const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions), evaluateValueInternal(node.right, context, resolvers, accumulator, functions)]);
408
+ const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
309
409
  if (left.status === "indeterminate") return left;
310
410
  if (right.status === "indeterminate") return right;
311
411
  return compareText(node.op, left.value, right.value);
312
412
  }
313
413
  case "memberOf": {
314
- const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions);
414
+ const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
315
415
  if (operandResult.status === "indeterminate") return operandResult;
316
416
  const candidateOutcomes = await Promise.all(node.candidates.map(async (candidate) => {
317
- const candidateResult = await evaluateValueInternal(candidate, context, resolvers, accumulator, functions);
417
+ const candidateResult = await evaluateValueInternal(candidate, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
318
418
  if (candidateResult.status === "indeterminate") return candidateResult;
319
419
  return computeMembershipMatch(operandResult.value, candidateResult.value);
320
420
  }));
@@ -327,32 +427,43 @@ async function evaluatePredicateInternal(node, context, resolvers, accumulator,
327
427
  return definite(node.op === "notIn");
328
428
  }
329
429
  case "exists": {
330
- const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions);
430
+ const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
331
431
  if (operandResult.status === "indeterminate" && operandResult.reason.code === "not-found") return definite(false);
332
432
  return definite(true);
333
433
  }
334
434
  case "some":
335
435
  case "every": {
336
- const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions);
436
+ const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth);
337
437
  const votes = (await Promise.all(participating.map(async ({ item, filterOutcome }) => {
338
438
  if (filterOutcome === "exclude") return void 0;
339
439
  if (filterOutcome !== "include") return filterOutcome;
340
- return evaluatePredicateInternal(node.item, item, resolvers, void 0, functions);
440
+ return evaluatePredicateInternal(node.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
341
441
  }))).filter((vote) => vote !== void 0);
342
442
  const combine = node.kind === "some" ? combineOr : combineAnd;
343
443
  const identity = node.kind === "some" ? definite(false) : definite(true);
344
444
  return votes.reduce(combine, identity);
345
445
  }
446
+ case "treeReference": {
447
+ if (resolvers.resolveTree === void 0) return indeterminate("wrong-type", "no tree resolver registered for treeReference nodes");
448
+ const keyString = JSON.stringify(node.key);
449
+ if (visitedTreeKeys.has(keyString)) return indeterminate("domain-error", "circular treeReference detected");
450
+ if (treeReferenceDepth >= MAX_TREE_REFERENCE_DEPTH) return indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${MAX_TREE_REFERENCE_DEPTH.toString()}`);
451
+ const resolution = await resolvers.resolveTree(node.key, context);
452
+ if (!resolution.found) return indeterminate("not-found", "treeReference key did not resolve to a tree");
453
+ const parsed = PredicateNodeSchema.safeParse(resolution.node);
454
+ if (!parsed.success) return indeterminate("wrong-type", "the referenced tree is not a valid PredicateNode");
455
+ return evaluatePredicateInternal(parsed.data, context, resolvers, accumulator, functions, /* @__PURE__ */ new Set([...visitedTreeKeys, keyString]), treeReferenceDepth + 1);
456
+ }
346
457
  default: throw new Error("unreachable predicate node kind");
347
458
  }
348
459
  }
349
- async function evaluateValueInternal(node, context, resolvers, accumulator, functions) {
460
+ async function evaluateValueInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth) {
350
461
  switch (node.kind) {
351
462
  case "reference": {
352
463
  const resolution = await resolvers.resolveValue(node.key, context);
353
464
  if (!resolution.found) return indeterminate("not-found", `no value found for reference key ${JSON.stringify(node.key)}`);
354
465
  if (node.unit !== void 0) {
355
- if (resolution.value.kind !== "number") return indeterminate("wrong-type", "a unit was expected on a reference that resolved to a non-numeric value");
466
+ if (resolution.value.kind !== "number" && resolution.value.kind !== "complex") return indeterminate("wrong-type", "a unit was expected on a reference that resolved to a non-numeric value");
356
467
  if (!unitsEqual(node.unit, resolution.value.unit)) return indeterminate("wrong-type", "the resolved value's unit does not match the reference's expected unit");
357
468
  }
358
469
  return definite(resolution.value);
@@ -361,7 +472,7 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
361
472
  if (accumulator === void 0) return indeterminate("wrong-type", "accumulator used outside a reduce fold's combine expression");
362
473
  return definite(accumulator);
363
474
  case "call": {
364
- const argResults = await Promise.all(node.args.map(async (arg) => evaluateValueInternal(arg, context, resolvers, accumulator, functions)));
475
+ const argResults = await Promise.all(node.args.map(async (arg) => evaluateValueInternal(arg, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)));
365
476
  const args = [];
366
477
  for (const result of argResults) {
367
478
  if (result.status === "indeterminate") return result;
@@ -382,6 +493,10 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
382
493
  kind: "text",
383
494
  value: node.value
384
495
  });
496
+ case "booleanLiteral": return definite({
497
+ kind: "boolean",
498
+ value: node.value
499
+ });
385
500
  case "instantLiteral": return definite({
386
501
  kind: "instant",
387
502
  value: node.value
@@ -391,19 +506,27 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
391
506
  value: node.value,
392
507
  unit: node.unit
393
508
  });
509
+ case "complexLiteral":
510
+ if ("re" in node) return definite({
511
+ kind: "complex",
512
+ re: node.re,
513
+ im: node.im,
514
+ unit: node.unit
515
+ });
516
+ return definite(complexFromPolar(node.magnitude, node.phase, node.unit));
394
517
  case "arithmetic": {
395
- const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions), evaluateValueInternal(node.right, context, resolvers, accumulator, functions)]);
518
+ const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth), evaluateValueInternal(node.right, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)]);
396
519
  if (left.status === "indeterminate") return left;
397
520
  if (right.status === "indeterminate") return right;
398
521
  return applyArithmetic(node.op, left.value, right.value);
399
522
  }
400
523
  case "negate": {
401
- const operand = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions);
524
+ const operand = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
402
525
  if (operand.status === "indeterminate") return operand;
403
526
  return applyNegate(operand.value);
404
527
  }
405
528
  case "lookup": {
406
- const keyResults = await Promise.all(node.keys.map(async (key) => evaluateValueInternal(key, context, resolvers, accumulator, functions)));
529
+ const keyResults = await Promise.all(node.keys.map(async (key) => evaluateValueInternal(key, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)));
407
530
  const keyValues = [];
408
531
  for (const result of keyResults) {
409
532
  if (result.status === "indeterminate") return result;
@@ -413,15 +536,32 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
413
536
  if (!resolution.found) return indeterminate("not-found", `no match found in lookup table ${JSON.stringify(node.table)}`);
414
537
  return definite(resolution.value);
415
538
  }
416
- case "conditional":
417
- for (const { when, then } of node.cases) {
418
- const whenResult = await evaluatePredicateInternal(when, context, resolvers, accumulator, functions);
419
- if (whenResult.status === "indeterminate") return whenResult;
420
- if (whenResult.value) return evaluateValueInternal(then, context, resolvers, accumulator, functions);
539
+ case "conditional": {
540
+ if ((node.hitPolicy ?? "first") === "first") {
541
+ for (const { when, then } of node.cases) {
542
+ const whenResult = await evaluatePredicateInternal(when, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
543
+ if (whenResult.status === "indeterminate") return whenResult;
544
+ if (whenResult.value) return evaluateValueInternal(then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
545
+ }
546
+ return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
421
547
  }
422
- return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions);
548
+ const evaluatedCases = await Promise.all(node.cases.map(async ({ when, then }) => ({
549
+ then,
550
+ whenResult: await evaluatePredicateInternal(when, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)
551
+ })));
552
+ const matches = evaluatedCases.filter(({ whenResult }) => whenResult.status === "definite" && whenResult.value);
553
+ if (matches.length >= 2) return indeterminate("domain-error", "more than one case matched under the 'unique' hit policy");
554
+ const reason = firstIndeterminate(...evaluatedCases.map(({ whenResult }) => whenResult));
555
+ if (reason !== void 0) return {
556
+ status: "indeterminate",
557
+ reason
558
+ };
559
+ const [match] = matches;
560
+ if (match === void 0) return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
561
+ return evaluateValueInternal(match.then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
562
+ }
423
563
  case "fold": {
424
- const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions);
564
+ const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth);
425
565
  const filterIndeterminateReason = firstFilterIndeterminate(participating);
426
566
  if (filterIndeterminateReason !== void 0) return {
427
567
  status: "indeterminate",
@@ -429,11 +569,11 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
429
569
  };
430
570
  const includedItems = participating.filter(({ filterOutcome }) => filterOutcome === "include").map(({ item }) => item);
431
571
  if (node.combiner.mode === "reduce") {
432
- const initialResult = await evaluateValueInternal(node.combiner.initial, context, resolvers, void 0, functions);
572
+ const initialResult = await evaluateValueInternal(node.combiner.initial, context, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
433
573
  if (initialResult.status === "indeterminate") return initialResult;
434
574
  let runningAccumulator = initialResult.value;
435
575
  for (const item of includedItems) {
436
- const stepResult = await evaluateValueInternal(node.combiner.combine, item, resolvers, runningAccumulator, functions);
576
+ const stepResult = await evaluateValueInternal(node.combiner.combine, item, resolvers, runningAccumulator, functions, visitedTreeKeys, treeReferenceDepth);
437
577
  if (stepResult.status === "indeterminate") return stepResult;
438
578
  runningAccumulator = stepResult.value;
439
579
  }
@@ -443,7 +583,7 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
443
583
  const dominatesOp = node.combiner.mode === "max" ? "gt" : "lt";
444
584
  let runningExtremum;
445
585
  for (const item of includedItems) {
446
- const itemResult = await evaluateValueInternal(node.combiner.item, item, resolvers, void 0, functions);
586
+ const itemResult = await evaluateValueInternal(node.combiner.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
447
587
  if (itemResult.status === "indeterminate") return itemResult;
448
588
  if (runningExtremum === void 0) {
449
589
  runningExtremum = itemResult.value;
@@ -462,6 +602,17 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
462
602
  if (!resolution.found) return indeterminate("not-found", `delegate handler for external system '${node.system}' reported no value`);
463
603
  return definite(resolution.value);
464
604
  }
605
+ case "treeReference": {
606
+ if (resolvers.resolveTree === void 0) return indeterminate("wrong-type", "no tree resolver registered for treeReference nodes");
607
+ const keyString = JSON.stringify(node.key);
608
+ if (visitedTreeKeys.has(keyString)) return indeterminate("domain-error", "circular treeReference detected");
609
+ if (treeReferenceDepth >= MAX_TREE_REFERENCE_DEPTH) return indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${MAX_TREE_REFERENCE_DEPTH.toString()}`);
610
+ const resolution = await resolvers.resolveTree(node.key, context);
611
+ if (!resolution.found) return indeterminate("not-found", "treeReference key did not resolve to a tree");
612
+ const parsed = ExpressionNodeSchema.safeParse(resolution.node);
613
+ if (!parsed.success) return indeterminate("wrong-type", "the referenced tree is not a valid ExpressionNode");
614
+ return evaluateValueInternal(parsed.data, context, resolvers, accumulator, functions, /* @__PURE__ */ new Set([...visitedTreeKeys, keyString]), treeReferenceDepth + 1);
615
+ }
465
616
  default: throw new Error("unreachable expression node kind");
466
617
  }
467
618
  }
@@ -470,8 +621,8 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
470
621
  */
471
622
  function createEvaluator({ functions = emptyFunctionRegistry }) {
472
623
  return {
473
- evaluatePredicate: async (node, context, resolvers) => evaluatePredicateInternal(node, context, resolvers, void 0, functions),
474
- evaluateValue: async (node, context, resolvers) => evaluateValueInternal(node, context, resolvers, void 0, functions)
624
+ evaluatePredicate: async (node, context, resolvers) => evaluatePredicateInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0),
625
+ evaluateValue: async (node, context, resolvers) => evaluateValueInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0)
475
626
  };
476
627
  }
477
628
  const { evaluatePredicate, evaluateValue } = createEvaluator({});
package/dist/index.cjs CHANGED
@@ -1,21 +1,27 @@
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_derived_aggregates = require("./derived-aggregates.cjs");
4
5
  const require_derived_connectives = require("./derived-connectives.cjs");
6
+ const require_derived_values = require("./derived-values.cjs");
5
7
  const require_evaluation = require("./evaluation.cjs");
6
8
  const require_functions = require("./functions.cjs");
7
- const require_evaluator = require("./evaluator.cjs");
8
9
  const require_json_value = require("./json-value.cjs");
9
10
  const require_tree = require("./tree.cjs");
11
+ const require_evaluator = require("./evaluator.cjs");
10
12
  exports.AccumulatorNodeSchema = require_tree.AccumulatorNodeSchema;
11
13
  exports.AllOfNodeSchema = require_tree.AllOfNodeSchema;
12
14
  exports.AndNodeSchema = require_tree.AndNodeSchema;
13
15
  exports.AnyOfNodeSchema = require_tree.AnyOfNodeSchema;
14
16
  exports.ArithmeticNodeSchema = require_tree.ArithmeticNodeSchema;
15
17
  exports.ArithmeticOperatorSchema = require_tree.ArithmeticOperatorSchema;
18
+ exports.BooleanLiteralNodeSchema = require_tree.BooleanLiteralNodeSchema;
16
19
  exports.CallNodeSchema = require_tree.CallNodeSchema;
17
20
  exports.CompareNodeSchema = require_tree.CompareNodeSchema;
18
21
  exports.ComparisonOperatorSchema = require_tree.ComparisonOperatorSchema;
22
+ exports.ComplexLiteralNodeSchema = require_tree.ComplexLiteralNodeSchema;
23
+ exports.ComplexPolarLiteralNodeSchema = require_tree.ComplexPolarLiteralNodeSchema;
24
+ exports.ComplexRectangularLiteralNodeSchema = require_tree.ComplexRectangularLiteralNodeSchema;
19
25
  exports.ComputedValueSchema = require_computed_value.ComputedValueSchema;
20
26
  exports.ConditionalCaseSchema = require_tree.ConditionalCaseSchema;
21
27
  exports.ConditionalNodeSchema = require_tree.ConditionalNodeSchema;
@@ -27,6 +33,7 @@ exports.ExistsNodeSchema = require_tree.ExistsNodeSchema;
27
33
  exports.ExpressionNodeSchema = require_tree.ExpressionNodeSchema;
28
34
  exports.FoldCombinerSchema = require_tree.FoldCombinerSchema;
29
35
  exports.FoldNodeSchema = require_tree.FoldNodeSchema;
36
+ exports.HitPolicySchema = require_tree.HitPolicySchema;
30
37
  exports.IndeterminateReasonSchema = require_evaluation.IndeterminateReasonSchema;
31
38
  exports.InstantLiteralNodeSchema = require_tree.InstantLiteralNodeSchema;
32
39
  exports.JsonValueSchema = require_json_value.JsonValueSchema;
@@ -43,11 +50,17 @@ exports.SomeNodeSchema = require_tree.SomeNodeSchema;
43
50
  exports.TextCompareNodeSchema = require_tree.TextCompareNodeSchema;
44
51
  exports.TextComparisonOperatorSchema = require_tree.TextComparisonOperatorSchema;
45
52
  exports.TextLiteralNodeSchema = require_tree.TextLiteralNodeSchema;
53
+ exports.TreeReferenceNodeSchema = require_tree.TreeReferenceNodeSchema;
46
54
  exports.UnitSchema = require_computed_value.UnitSchema;
47
55
  exports.and = require_derived_connectives.and;
48
56
  exports.average = require_derived_aggregates.average;
57
+ exports.coalesce = require_derived_values.coalesce;
49
58
  exports.combineUnitsForDivide = require_computed_value.combineUnitsForDivide;
50
59
  exports.combineUnitsForMultiply = require_computed_value.combineUnitsForMultiply;
60
+ exports.complexFromPolar = require_complex.complexFromPolar;
61
+ exports.complexLiteralFromPolar = require_complex.complexLiteralFromPolar;
62
+ exports.complexMagnitude = require_complex.complexMagnitude;
63
+ exports.complexPhase = require_complex.complexPhase;
51
64
  exports.count = require_derived_aggregates.count;
52
65
  exports.createEvaluator = require_evaluator.createEvaluator;
53
66
  exports.definite = require_evaluation.definite;
package/dist/index.d.cts CHANGED
@@ -1,10 +1,12 @@
1
1
  import { ComputedValue, ComputedValueSchema, DurationUnit, DurationUnitSchema, Unit, UnitSchema, combineUnitsForDivide, combineUnitsForMultiply, unitsEqual } from "./computed-value.cjs";
2
2
  import { n as JsonValueSchema, t as JsonValue } from "./json-value-B1Hjjjri.cjs";
3
- import { AccumulatorNode, AccumulatorNodeSchema, AllOfNode, AllOfNodeSchema, AndNode, AndNodeSchema, AnyOfNode, AnyOfNodeSchema, ArithmeticNode, ArithmeticNodeSchema, ArithmeticOperator, ArithmeticOperatorSchema, CallNode, CallNodeSchema, CompareNode, CompareNodeSchema, ComparisonOperator, ComparisonOperatorSchema, ConditionalCase, ConditionalCaseSchema, ConditionalNode, ConditionalNodeSchema, DelegateNode, DelegateNodeSchema, DurationLiteralNode, DurationLiteralNodeSchema, EveryNode, EveryNodeSchema, ExistsNode, ExistsNodeSchema, ExpressionNode, ExpressionNodeSchema, FoldCombiner, FoldCombinerSchema, FoldNode, FoldNodeSchema, InstantLiteralNode, InstantLiteralNodeSchema, LookupNode, LookupNodeSchema, MemberOfNode, MemberOfNodeSchema, MembershipOperator, MembershipOperatorSchema, NegateNode, NegateNodeSchema, NotNode, NotNodeSchema, NumberLiteralNode, NumberLiteralNodeSchema, OrNode, OrNodeSchema, PredicateNode, PredicateNodeSchema, ReferenceNode, ReferenceNodeSchema, SomeNode, SomeNodeSchema, TextCompareNode, TextCompareNodeSchema, TextComparisonOperator, TextComparisonOperatorSchema, TextLiteralNode, TextLiteralNodeSchema } from "./tree.cjs";
3
+ import { AccumulatorNode, AccumulatorNodeSchema, AllOfNode, AllOfNodeSchema, AndNode, AndNodeSchema, AnyOfNode, AnyOfNodeSchema, ArithmeticNode, ArithmeticNodeSchema, ArithmeticOperator, ArithmeticOperatorSchema, BooleanLiteralNode, BooleanLiteralNodeSchema, CallNode, CallNodeSchema, CompareNode, CompareNodeSchema, ComparisonOperator, ComparisonOperatorSchema, ComplexLiteralNode, ComplexLiteralNodeSchema, ComplexPolarLiteralNode, ComplexPolarLiteralNodeSchema, ComplexRectangularLiteralNode, ComplexRectangularLiteralNodeSchema, ConditionalCase, ConditionalCaseSchema, ConditionalNode, ConditionalNodeSchema, DelegateNode, DelegateNodeSchema, DurationLiteralNode, DurationLiteralNodeSchema, EveryNode, EveryNodeSchema, ExistsNode, ExistsNodeSchema, ExpressionNode, ExpressionNodeSchema, FoldCombiner, FoldCombinerSchema, FoldNode, FoldNodeSchema, HitPolicy, HitPolicySchema, InstantLiteralNode, InstantLiteralNodeSchema, LookupNode, LookupNodeSchema, MemberOfNode, MemberOfNodeSchema, MembershipOperator, MembershipOperatorSchema, NegateNode, NegateNodeSchema, NotNode, NotNodeSchema, NumberLiteralNode, NumberLiteralNodeSchema, OrNode, OrNodeSchema, PredicateNode, PredicateNodeSchema, ReferenceNode, ReferenceNodeSchema, SomeNode, SomeNodeSchema, TextCompareNode, TextCompareNodeSchema, TextComparisonOperator, TextComparisonOperatorSchema, TextLiteralNode, TextLiteralNodeSchema, TreeReferenceNode, TreeReferenceNodeSchema } from "./tree.cjs";
4
+ import { complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase } from "./complex.cjs";
4
5
  import { average, count, presenceOf, sum } from "./derived-aggregates.cjs";
5
6
  import { and, iff, implies, nand, none, nor, not, or, xor } from "./derived-connectives.cjs";
7
+ import { coalesce } from "./derived-values.cjs";
6
8
  import { Evaluation, IndeterminateReason, IndeterminateReasonSchema, definite, firstIndeterminate, indeterminate } from "./evaluation.cjs";
7
9
  import { FunctionRegistry, emptyFunctionRegistry } from "./functions.cjs";
8
- import { EvaluationContext, Resolution, Resolvers } from "./resolvers.cjs";
10
+ import { EvaluationContext, Resolution, Resolvers, TreeResolution } from "./resolvers.cjs";
9
11
  import { createEvaluator, evaluatePredicate, evaluateValue } from "./evaluator.cjs";
10
- export { type AccumulatorNode, AccumulatorNodeSchema, type AllOfNode, AllOfNodeSchema, type AndNode, AndNodeSchema, type AnyOfNode, AnyOfNodeSchema, type ArithmeticNode, ArithmeticNodeSchema, type ArithmeticOperator, ArithmeticOperatorSchema, type CallNode, CallNodeSchema, type CompareNode, CompareNodeSchema, type ComparisonOperator, ComparisonOperatorSchema, type ComputedValue, ComputedValueSchema, type ConditionalCase, ConditionalCaseSchema, type ConditionalNode, ConditionalNodeSchema, type DelegateNode, DelegateNodeSchema, type DurationLiteralNode, DurationLiteralNodeSchema, type DurationUnit, DurationUnitSchema, type Evaluation, type EvaluationContext, type EveryNode, EveryNodeSchema, type ExistsNode, ExistsNodeSchema, type ExpressionNode, ExpressionNodeSchema, type FoldCombiner, FoldCombinerSchema, type FoldNode, FoldNodeSchema, type FunctionRegistry, type IndeterminateReason, IndeterminateReasonSchema, type InstantLiteralNode, InstantLiteralNodeSchema, type JsonValue, JsonValueSchema, type LookupNode, LookupNodeSchema, type MemberOfNode, MemberOfNodeSchema, type MembershipOperator, MembershipOperatorSchema, type NegateNode, NegateNodeSchema, type NotNode, NotNodeSchema, type NumberLiteralNode, NumberLiteralNodeSchema, type OrNode, OrNodeSchema, type PredicateNode, PredicateNodeSchema, type ReferenceNode, ReferenceNodeSchema, type Resolution, type Resolvers, type SomeNode, SomeNodeSchema, type TextCompareNode, TextCompareNodeSchema, type TextComparisonOperator, TextComparisonOperatorSchema, type TextLiteralNode, TextLiteralNodeSchema, type Unit, UnitSchema, and, average, combineUnitsForDivide, combineUnitsForMultiply, count, createEvaluator, definite, emptyFunctionRegistry, evaluatePredicate, evaluateValue, firstIndeterminate, iff, implies, indeterminate, nand, none, nor, not, or, presenceOf, sum, unitsEqual, xor };
12
+ export { type AccumulatorNode, AccumulatorNodeSchema, type AllOfNode, AllOfNodeSchema, type AndNode, AndNodeSchema, type AnyOfNode, AnyOfNodeSchema, type ArithmeticNode, ArithmeticNodeSchema, type ArithmeticOperator, ArithmeticOperatorSchema, type BooleanLiteralNode, BooleanLiteralNodeSchema, type CallNode, CallNodeSchema, type CompareNode, CompareNodeSchema, type ComparisonOperator, ComparisonOperatorSchema, type ComplexLiteralNode, ComplexLiteralNodeSchema, type ComplexPolarLiteralNode, ComplexPolarLiteralNodeSchema, type ComplexRectangularLiteralNode, ComplexRectangularLiteralNodeSchema, type ComputedValue, ComputedValueSchema, type ConditionalCase, ConditionalCaseSchema, type ConditionalNode, ConditionalNodeSchema, type DelegateNode, DelegateNodeSchema, type DurationLiteralNode, DurationLiteralNodeSchema, type DurationUnit, DurationUnitSchema, type Evaluation, type EvaluationContext, type EveryNode, EveryNodeSchema, type ExistsNode, ExistsNodeSchema, type ExpressionNode, ExpressionNodeSchema, type FoldCombiner, FoldCombinerSchema, type FoldNode, FoldNodeSchema, type FunctionRegistry, type HitPolicy, HitPolicySchema, type IndeterminateReason, IndeterminateReasonSchema, type InstantLiteralNode, InstantLiteralNodeSchema, type JsonValue, JsonValueSchema, type LookupNode, LookupNodeSchema, type MemberOfNode, MemberOfNodeSchema, type MembershipOperator, MembershipOperatorSchema, type NegateNode, NegateNodeSchema, type NotNode, NotNodeSchema, type NumberLiteralNode, NumberLiteralNodeSchema, type OrNode, OrNodeSchema, type PredicateNode, PredicateNodeSchema, type ReferenceNode, ReferenceNodeSchema, type Resolution, type Resolvers, type SomeNode, SomeNodeSchema, type TextCompareNode, TextCompareNodeSchema, type TextComparisonOperator, TextComparisonOperatorSchema, type TextLiteralNode, TextLiteralNodeSchema, type TreeReferenceNode, TreeReferenceNodeSchema, type TreeResolution, type Unit, UnitSchema, and, average, coalesce, combineUnitsForDivide, combineUnitsForMultiply, complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase, count, createEvaluator, definite, emptyFunctionRegistry, evaluatePredicate, evaluateValue, firstIndeterminate, iff, implies, indeterminate, nand, none, nor, not, or, presenceOf, sum, unitsEqual, xor };
package/dist/index.d.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  import { ComputedValue, ComputedValueSchema, DurationUnit, DurationUnitSchema, Unit, UnitSchema, combineUnitsForDivide, combineUnitsForMultiply, unitsEqual } from "./computed-value.js";
2
2
  import { n as JsonValueSchema, t as JsonValue } from "./json-value-B1Hjjjri.js";
3
- import { AccumulatorNode, AccumulatorNodeSchema, AllOfNode, AllOfNodeSchema, AndNode, AndNodeSchema, AnyOfNode, AnyOfNodeSchema, ArithmeticNode, ArithmeticNodeSchema, ArithmeticOperator, ArithmeticOperatorSchema, CallNode, CallNodeSchema, CompareNode, CompareNodeSchema, ComparisonOperator, ComparisonOperatorSchema, ConditionalCase, ConditionalCaseSchema, ConditionalNode, ConditionalNodeSchema, DelegateNode, DelegateNodeSchema, DurationLiteralNode, DurationLiteralNodeSchema, EveryNode, EveryNodeSchema, ExistsNode, ExistsNodeSchema, ExpressionNode, ExpressionNodeSchema, FoldCombiner, FoldCombinerSchema, FoldNode, FoldNodeSchema, InstantLiteralNode, InstantLiteralNodeSchema, LookupNode, LookupNodeSchema, MemberOfNode, MemberOfNodeSchema, MembershipOperator, MembershipOperatorSchema, NegateNode, NegateNodeSchema, NotNode, NotNodeSchema, NumberLiteralNode, NumberLiteralNodeSchema, OrNode, OrNodeSchema, PredicateNode, PredicateNodeSchema, ReferenceNode, ReferenceNodeSchema, SomeNode, SomeNodeSchema, TextCompareNode, TextCompareNodeSchema, TextComparisonOperator, TextComparisonOperatorSchema, TextLiteralNode, TextLiteralNodeSchema } from "./tree.js";
3
+ import { AccumulatorNode, AccumulatorNodeSchema, AllOfNode, AllOfNodeSchema, AndNode, AndNodeSchema, AnyOfNode, AnyOfNodeSchema, ArithmeticNode, ArithmeticNodeSchema, ArithmeticOperator, ArithmeticOperatorSchema, BooleanLiteralNode, BooleanLiteralNodeSchema, CallNode, CallNodeSchema, CompareNode, CompareNodeSchema, ComparisonOperator, ComparisonOperatorSchema, ComplexLiteralNode, ComplexLiteralNodeSchema, ComplexPolarLiteralNode, ComplexPolarLiteralNodeSchema, ComplexRectangularLiteralNode, ComplexRectangularLiteralNodeSchema, ConditionalCase, ConditionalCaseSchema, ConditionalNode, ConditionalNodeSchema, DelegateNode, DelegateNodeSchema, DurationLiteralNode, DurationLiteralNodeSchema, EveryNode, EveryNodeSchema, ExistsNode, ExistsNodeSchema, ExpressionNode, ExpressionNodeSchema, FoldCombiner, FoldCombinerSchema, FoldNode, FoldNodeSchema, HitPolicy, HitPolicySchema, InstantLiteralNode, InstantLiteralNodeSchema, LookupNode, LookupNodeSchema, MemberOfNode, MemberOfNodeSchema, MembershipOperator, MembershipOperatorSchema, NegateNode, NegateNodeSchema, NotNode, NotNodeSchema, NumberLiteralNode, NumberLiteralNodeSchema, OrNode, OrNodeSchema, PredicateNode, PredicateNodeSchema, ReferenceNode, ReferenceNodeSchema, SomeNode, SomeNodeSchema, TextCompareNode, TextCompareNodeSchema, TextComparisonOperator, TextComparisonOperatorSchema, TextLiteralNode, TextLiteralNodeSchema, TreeReferenceNode, TreeReferenceNodeSchema } from "./tree.js";
4
+ import { complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase } from "./complex.js";
4
5
  import { average, count, presenceOf, sum } from "./derived-aggregates.js";
5
6
  import { and, iff, implies, nand, none, nor, not, or, xor } from "./derived-connectives.js";
7
+ import { coalesce } from "./derived-values.js";
6
8
  import { Evaluation, IndeterminateReason, IndeterminateReasonSchema, definite, firstIndeterminate, indeterminate } from "./evaluation.js";
7
9
  import { FunctionRegistry, emptyFunctionRegistry } from "./functions.js";
8
- import { EvaluationContext, Resolution, Resolvers } from "./resolvers.js";
10
+ import { EvaluationContext, Resolution, Resolvers, TreeResolution } from "./resolvers.js";
9
11
  import { createEvaluator, evaluatePredicate, evaluateValue } from "./evaluator.js";
10
- export { type AccumulatorNode, AccumulatorNodeSchema, type AllOfNode, AllOfNodeSchema, type AndNode, AndNodeSchema, type AnyOfNode, AnyOfNodeSchema, type ArithmeticNode, ArithmeticNodeSchema, type ArithmeticOperator, ArithmeticOperatorSchema, type CallNode, CallNodeSchema, type CompareNode, CompareNodeSchema, type ComparisonOperator, ComparisonOperatorSchema, type ComputedValue, ComputedValueSchema, type ConditionalCase, ConditionalCaseSchema, type ConditionalNode, ConditionalNodeSchema, type DelegateNode, DelegateNodeSchema, type DurationLiteralNode, DurationLiteralNodeSchema, type DurationUnit, DurationUnitSchema, type Evaluation, type EvaluationContext, type EveryNode, EveryNodeSchema, type ExistsNode, ExistsNodeSchema, type ExpressionNode, ExpressionNodeSchema, type FoldCombiner, FoldCombinerSchema, type FoldNode, FoldNodeSchema, type FunctionRegistry, type IndeterminateReason, IndeterminateReasonSchema, type InstantLiteralNode, InstantLiteralNodeSchema, type JsonValue, JsonValueSchema, type LookupNode, LookupNodeSchema, type MemberOfNode, MemberOfNodeSchema, type MembershipOperator, MembershipOperatorSchema, type NegateNode, NegateNodeSchema, type NotNode, NotNodeSchema, type NumberLiteralNode, NumberLiteralNodeSchema, type OrNode, OrNodeSchema, type PredicateNode, PredicateNodeSchema, type ReferenceNode, ReferenceNodeSchema, type Resolution, type Resolvers, type SomeNode, SomeNodeSchema, type TextCompareNode, TextCompareNodeSchema, type TextComparisonOperator, TextComparisonOperatorSchema, type TextLiteralNode, TextLiteralNodeSchema, type Unit, UnitSchema, and, average, combineUnitsForDivide, combineUnitsForMultiply, count, createEvaluator, definite, emptyFunctionRegistry, evaluatePredicate, evaluateValue, firstIndeterminate, iff, implies, indeterminate, nand, none, nor, not, or, presenceOf, sum, unitsEqual, xor };
12
+ export { type AccumulatorNode, AccumulatorNodeSchema, type AllOfNode, AllOfNodeSchema, type AndNode, AndNodeSchema, type AnyOfNode, AnyOfNodeSchema, type ArithmeticNode, ArithmeticNodeSchema, type ArithmeticOperator, ArithmeticOperatorSchema, type BooleanLiteralNode, BooleanLiteralNodeSchema, type CallNode, CallNodeSchema, type CompareNode, CompareNodeSchema, type ComparisonOperator, ComparisonOperatorSchema, type ComplexLiteralNode, ComplexLiteralNodeSchema, type ComplexPolarLiteralNode, ComplexPolarLiteralNodeSchema, type ComplexRectangularLiteralNode, ComplexRectangularLiteralNodeSchema, type ComputedValue, ComputedValueSchema, type ConditionalCase, ConditionalCaseSchema, type ConditionalNode, ConditionalNodeSchema, type DelegateNode, DelegateNodeSchema, type DurationLiteralNode, DurationLiteralNodeSchema, type DurationUnit, DurationUnitSchema, type Evaluation, type EvaluationContext, type EveryNode, EveryNodeSchema, type ExistsNode, ExistsNodeSchema, type ExpressionNode, ExpressionNodeSchema, type FoldCombiner, FoldCombinerSchema, type FoldNode, FoldNodeSchema, type FunctionRegistry, type HitPolicy, HitPolicySchema, type IndeterminateReason, IndeterminateReasonSchema, type InstantLiteralNode, InstantLiteralNodeSchema, type JsonValue, JsonValueSchema, type LookupNode, LookupNodeSchema, type MemberOfNode, MemberOfNodeSchema, type MembershipOperator, MembershipOperatorSchema, type NegateNode, NegateNodeSchema, type NotNode, NotNodeSchema, type NumberLiteralNode, NumberLiteralNodeSchema, type OrNode, OrNodeSchema, type PredicateNode, PredicateNodeSchema, type ReferenceNode, ReferenceNodeSchema, type Resolution, type Resolvers, type SomeNode, SomeNodeSchema, type TextCompareNode, TextCompareNodeSchema, type TextComparisonOperator, TextComparisonOperatorSchema, type TextLiteralNode, TextLiteralNodeSchema, type TreeReferenceNode, TreeReferenceNodeSchema, type TreeResolution, type Unit, UnitSchema, and, average, coalesce, combineUnitsForDivide, combineUnitsForMultiply, complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase, count, createEvaluator, definite, emptyFunctionRegistry, evaluatePredicate, evaluateValue, firstIndeterminate, iff, implies, indeterminate, nand, none, nor, not, or, presenceOf, sum, unitsEqual, xor };
package/dist/index.js CHANGED
@@ -1,9 +1,11 @@
1
+ import { complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase } from "./complex.js";
1
2
  import { ComputedValueSchema, DurationUnitSchema, UnitSchema, combineUnitsForDivide, combineUnitsForMultiply, unitsEqual } from "./computed-value.js";
2
3
  import { average, count, presenceOf, sum } from "./derived-aggregates.js";
3
4
  import { and, iff, implies, nand, none, nor, not, or, xor } from "./derived-connectives.js";
5
+ import { coalesce } from "./derived-values.js";
4
6
  import { IndeterminateReasonSchema, definite, firstIndeterminate, indeterminate } from "./evaluation.js";
5
7
  import { emptyFunctionRegistry } from "./functions.js";
6
- import { createEvaluator, evaluatePredicate, evaluateValue } from "./evaluator.js";
7
8
  import { JsonValueSchema } from "./json-value.js";
8
- import { AccumulatorNodeSchema, AllOfNodeSchema, AndNodeSchema, AnyOfNodeSchema, ArithmeticNodeSchema, ArithmeticOperatorSchema, CallNodeSchema, CompareNodeSchema, ComparisonOperatorSchema, ConditionalCaseSchema, ConditionalNodeSchema, DelegateNodeSchema, DurationLiteralNodeSchema, EveryNodeSchema, ExistsNodeSchema, ExpressionNodeSchema, FoldCombinerSchema, FoldNodeSchema, InstantLiteralNodeSchema, LookupNodeSchema, MemberOfNodeSchema, MembershipOperatorSchema, NegateNodeSchema, NotNodeSchema, NumberLiteralNodeSchema, OrNodeSchema, PredicateNodeSchema, ReferenceNodeSchema, SomeNodeSchema, TextCompareNodeSchema, TextComparisonOperatorSchema, TextLiteralNodeSchema } from "./tree.js";
9
- export { AccumulatorNodeSchema, AllOfNodeSchema, AndNodeSchema, AnyOfNodeSchema, ArithmeticNodeSchema, ArithmeticOperatorSchema, CallNodeSchema, CompareNodeSchema, ComparisonOperatorSchema, ComputedValueSchema, ConditionalCaseSchema, ConditionalNodeSchema, DelegateNodeSchema, DurationLiteralNodeSchema, DurationUnitSchema, EveryNodeSchema, ExistsNodeSchema, ExpressionNodeSchema, FoldCombinerSchema, FoldNodeSchema, IndeterminateReasonSchema, InstantLiteralNodeSchema, JsonValueSchema, LookupNodeSchema, MemberOfNodeSchema, MembershipOperatorSchema, NegateNodeSchema, NotNodeSchema, NumberLiteralNodeSchema, OrNodeSchema, PredicateNodeSchema, ReferenceNodeSchema, SomeNodeSchema, TextCompareNodeSchema, TextComparisonOperatorSchema, TextLiteralNodeSchema, UnitSchema, and, average, combineUnitsForDivide, combineUnitsForMultiply, count, createEvaluator, definite, emptyFunctionRegistry, evaluatePredicate, evaluateValue, firstIndeterminate, iff, implies, indeterminate, nand, none, nor, not, or, presenceOf, sum, unitsEqual, xor };
9
+ import { AccumulatorNodeSchema, AllOfNodeSchema, AndNodeSchema, AnyOfNodeSchema, ArithmeticNodeSchema, ArithmeticOperatorSchema, BooleanLiteralNodeSchema, CallNodeSchema, CompareNodeSchema, ComparisonOperatorSchema, ComplexLiteralNodeSchema, ComplexPolarLiteralNodeSchema, ComplexRectangularLiteralNodeSchema, ConditionalCaseSchema, ConditionalNodeSchema, DelegateNodeSchema, DurationLiteralNodeSchema, EveryNodeSchema, ExistsNodeSchema, ExpressionNodeSchema, FoldCombinerSchema, FoldNodeSchema, HitPolicySchema, InstantLiteralNodeSchema, LookupNodeSchema, MemberOfNodeSchema, MembershipOperatorSchema, NegateNodeSchema, NotNodeSchema, NumberLiteralNodeSchema, OrNodeSchema, PredicateNodeSchema, ReferenceNodeSchema, SomeNodeSchema, TextCompareNodeSchema, TextComparisonOperatorSchema, TextLiteralNodeSchema, TreeReferenceNodeSchema } from "./tree.js";
10
+ import { createEvaluator, evaluatePredicate, evaluateValue } from "./evaluator.js";
11
+ export { AccumulatorNodeSchema, AllOfNodeSchema, AndNodeSchema, AnyOfNodeSchema, ArithmeticNodeSchema, ArithmeticOperatorSchema, BooleanLiteralNodeSchema, CallNodeSchema, CompareNodeSchema, ComparisonOperatorSchema, ComplexLiteralNodeSchema, ComplexPolarLiteralNodeSchema, ComplexRectangularLiteralNodeSchema, ComputedValueSchema, ConditionalCaseSchema, ConditionalNodeSchema, DelegateNodeSchema, DurationLiteralNodeSchema, DurationUnitSchema, EveryNodeSchema, ExistsNodeSchema, ExpressionNodeSchema, FoldCombinerSchema, FoldNodeSchema, HitPolicySchema, IndeterminateReasonSchema, InstantLiteralNodeSchema, JsonValueSchema, LookupNodeSchema, MemberOfNodeSchema, MembershipOperatorSchema, NegateNodeSchema, NotNodeSchema, NumberLiteralNodeSchema, OrNodeSchema, PredicateNodeSchema, ReferenceNodeSchema, SomeNodeSchema, TextCompareNodeSchema, TextComparisonOperatorSchema, TextLiteralNodeSchema, TreeReferenceNodeSchema, UnitSchema, and, average, coalesce, combineUnitsForDivide, combineUnitsForMultiply, complexFromPolar, complexLiteralFromPolar, complexMagnitude, complexPhase, count, createEvaluator, definite, emptyFunctionRegistry, evaluatePredicate, evaluateValue, firstIndeterminate, iff, implies, indeterminate, nand, none, nor, not, or, presenceOf, sum, unitsEqual, xor };
@@ -11,8 +11,15 @@ type Resolution = {
11
11
  } | {
12
12
  found: false;
13
13
  };
14
+ /** The `resolveTree` counterpart to `Resolution`: `found: true` carries the referenced tree as opaque JSON, re-validated by the evaluator (see the `treeReference` node kind) rather than trusted as already-shaped `PredicateNode`/`ExpressionNode`. */
15
+ type TreeResolution = {
16
+ found: true;
17
+ node: JsonValue;
18
+ } | {
19
+ found: false;
20
+ };
14
21
  /**
15
- * Three independent points of extension, each supplied separately by the embedding consumer, each treated as pure data to hand over -- never as resolver logic living inside the schema itself. Plain TypeScript interfaces, not Zod schemas: resolvers are never serialised, only ever supplied in-process at evaluation time.
22
+ * Three core, required points of extension, plus two further independent optional ones (`resolveDelegate`, `resolveTree`), each supplied separately by the embedding consumer, each treated as pure data to hand over -- never as resolver logic living inside the schema itself. Plain TypeScript interfaces, not Zod schemas: resolvers are never serialised, only ever supplied in-process at evaluation time.
16
23
  */
17
24
  interface Resolvers {
18
25
  /** Resolver 1 -- a single opaque key to a single value (`reference`). */
@@ -23,6 +30,8 @@ interface Resolvers {
23
30
  resolveCollection: (collection: JsonValue, context: EvaluationContext) => Promise<unknown[]>;
24
31
  /** Optional, separate from the three core contracts -- see the `delegate` node kind. */
25
32
  resolveDelegate?: (system: string, payload: JsonValue, context: EvaluationContext) => Promise<Resolution>;
33
+ /** Optional, separate from the three core contracts -- see the `treeReference` node kind. Absence is `wrong-type`, the same deliberate-absence treatment as an unregistered `resolveDelegate`, not a masked bug -- and keeps this an additive, non-breaking interface change for every existing consumer. */
34
+ resolveTree?: (key: JsonValue, context: EvaluationContext) => Promise<TreeResolution>;
26
35
  }
27
36
  //#endregion
28
- export { EvaluationContext, Resolution, Resolvers };
37
+ export { EvaluationContext, Resolution, Resolvers, TreeResolution };
@@ -11,8 +11,15 @@ type Resolution = {
11
11
  } | {
12
12
  found: false;
13
13
  };
14
+ /** The `resolveTree` counterpart to `Resolution`: `found: true` carries the referenced tree as opaque JSON, re-validated by the evaluator (see the `treeReference` node kind) rather than trusted as already-shaped `PredicateNode`/`ExpressionNode`. */
15
+ type TreeResolution = {
16
+ found: true;
17
+ node: JsonValue;
18
+ } | {
19
+ found: false;
20
+ };
14
21
  /**
15
- * Three independent points of extension, each supplied separately by the embedding consumer, each treated as pure data to hand over -- never as resolver logic living inside the schema itself. Plain TypeScript interfaces, not Zod schemas: resolvers are never serialised, only ever supplied in-process at evaluation time.
22
+ * Three core, required points of extension, plus two further independent optional ones (`resolveDelegate`, `resolveTree`), each supplied separately by the embedding consumer, each treated as pure data to hand over -- never as resolver logic living inside the schema itself. Plain TypeScript interfaces, not Zod schemas: resolvers are never serialised, only ever supplied in-process at evaluation time.
16
23
  */
17
24
  interface Resolvers {
18
25
  /** Resolver 1 -- a single opaque key to a single value (`reference`). */
@@ -23,6 +30,8 @@ interface Resolvers {
23
30
  resolveCollection: (collection: JsonValue, context: EvaluationContext) => Promise<unknown[]>;
24
31
  /** Optional, separate from the three core contracts -- see the `delegate` node kind. */
25
32
  resolveDelegate?: (system: string, payload: JsonValue, context: EvaluationContext) => Promise<Resolution>;
33
+ /** Optional, separate from the three core contracts -- see the `treeReference` node kind. Absence is `wrong-type`, the same deliberate-absence treatment as an unregistered `resolveDelegate`, not a masked bug -- and keeps this an additive, non-breaking interface change for every existing consumer. */
34
+ resolveTree?: (key: JsonValue, context: EvaluationContext) => Promise<TreeResolution>;
26
35
  }
27
36
  //#endregion
28
- export { EvaluationContext, Resolution, Resolvers };
37
+ export { EvaluationContext, Resolution, Resolvers, TreeResolution };