trilean 1.0.13 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +79 -8
- package/dist/derived-values.cjs +24 -0
- package/dist/derived-values.d.cts +10 -0
- package/dist/derived-values.d.ts +10 -0
- package/dist/derived-values.js +23 -0
- package/dist/evaluator.cjs +74 -32
- package/dist/evaluator.js +74 -32
- package/dist/index.cjs +5 -1
- package/dist/index.d.cts +4 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +4 -3
- package/dist/resolvers.d.cts +11 -2
- package/dist/resolvers.d.ts +11 -2
- package/dist/tree.cjs +14 -2
- package/dist/tree.d.cts +26 -1
- package/dist/tree.d.ts +26 -1
- package/dist/tree.js +13 -3
- package/package.json +1 -1
- package/schemas/trilean.schema.json +1 -1
package/README.md
CHANGED
|
@@ -188,7 +188,7 @@ These hold across every part of the design below, and any implementation change
|
|
|
188
188
|
|
|
189
189
|
- **No assumptions about consumer data.** The only places this package touches real data are three named resolver contracts (see [Resolvers](#resolvers)). The schema stores *what to pass* to a resolver, never any resolver logic itself, and never interprets the meaning of an opaque key, table identifier, or collection reference.
|
|
190
190
|
- **Three outcomes, never two.** Every evaluation produces a definite result or an indeterminate result carrying a reason — never a bare `boolean`/`number`, and never a thrown exception for a data-quality problem. See [The evaluation model](#the-evaluation-model).
|
|
191
|
-
- **Derived constructs are compositions, not new logic.** Anything describable as "some other primitive, wired together" is implemented that way, so its correctness is inherited rather than requiring separate proof. See [Derived connectives](#derived-connectives)
|
|
191
|
+
- **Derived constructs are compositions, not new logic.** Anything describable as "some other primitive, wired together" is implemented that way, so its correctness is inherited rather than requiring separate proof. See [Derived connectives](#derived-connectives), [Derived aggregates](#derived-aggregates), and [Derived values](#derived-values).
|
|
192
192
|
- **One schema, mechanically derived artefacts.** A single canonical type definition produces the runtime validator and the portable wire-format schema; they cannot drift apart because there is only one source. See [Schema strategy](#schema-strategy).
|
|
193
193
|
- **Generic examples only.** Every example in this document uses invented, placeholder field names (`temperature`, `orderTotal`, `isActive`, `x`, `y`, `amount`, `items`) with no resemblance to any particular company, product, or industry's real data model.
|
|
194
194
|
|
|
@@ -353,7 +353,8 @@ type PredicateNode =
|
|
|
353
353
|
| { kind: "memberOf"; op: MembershipOperator; operand: ExpressionNode; candidates: ExpressionNode[] }
|
|
354
354
|
| { kind: "exists"; operand: ExpressionNode }
|
|
355
355
|
| { kind: "some"; collection: JsonValue; item: PredicateNode; filter?: PredicateNode }
|
|
356
|
-
| { kind: "every"; collection: JsonValue; item: PredicateNode; filter?: PredicateNode }
|
|
356
|
+
| { kind: "every"; collection: JsonValue; item: PredicateNode; filter?: PredicateNode }
|
|
357
|
+
| { kind: "treeReference"; key: JsonValue };
|
|
357
358
|
```
|
|
358
359
|
|
|
359
360
|
### `not`, `and`, `or`
|
|
@@ -409,6 +410,8 @@ type FoldCombiner =
|
|
|
409
410
|
| { mode: "min"; item: ExpressionNode }
|
|
410
411
|
| { mode: "reduce"; initial: ExpressionNode; combine: ExpressionNode };
|
|
411
412
|
|
|
413
|
+
type HitPolicy = "first" | "unique";
|
|
414
|
+
|
|
412
415
|
type ExpressionNode =
|
|
413
416
|
| { kind: "numberLiteral"; value: number; unit?: Unit }
|
|
414
417
|
| { kind: "textLiteral"; value: string }
|
|
@@ -419,10 +422,11 @@ type ExpressionNode =
|
|
|
419
422
|
| { kind: "negate"; operand: ExpressionNode }
|
|
420
423
|
| { kind: "call"; fn: string; args: ExpressionNode[] }
|
|
421
424
|
| { kind: "lookup"; table: JsonValue; keys: ExpressionNode[] }
|
|
422
|
-
| { kind: "conditional"; cases: { when: PredicateNode; then: ExpressionNode }[]; fallback: ExpressionNode }
|
|
425
|
+
| { kind: "conditional"; hitPolicy?: HitPolicy; cases: { when: PredicateNode; then: ExpressionNode }[]; fallback: ExpressionNode }
|
|
423
426
|
| { kind: "fold"; collection: JsonValue; filter?: PredicateNode; combiner: FoldCombiner }
|
|
424
427
|
| { kind: "accumulator" }
|
|
425
|
-
| { kind: "delegate"; system: string; payload: JsonValue }
|
|
428
|
+
| { kind: "delegate"; system: string; payload: JsonValue }
|
|
429
|
+
| { kind: "treeReference"; key: JsonValue };
|
|
426
430
|
```
|
|
427
431
|
|
|
428
432
|
A `textLiteral` kind is included even though it is not separately enumerated as its own top-level construct, because `textCompare`'s symmetry requirement (either side may be an arbitrary computed value, per the section above) is meaningless without a way to write a constant string or pattern — matching a field against the fixed text `"active"`, or against a fixed regular expression, needs a text constant on one side. This is a structural consequence of the symmetry already required for text matching, not an added feature.
|
|
@@ -465,7 +469,16 @@ Resolves a single value from a named external table-like source, keyed by one or
|
|
|
465
469
|
|
|
466
470
|
### `conditional`
|
|
467
471
|
|
|
468
|
-
A piecewise/conditional-value node: an ordered, possibly-empty list of `{ when, then }` cases plus a required `fallback`.
|
|
472
|
+
A piecewise/conditional-value node: an ordered, possibly-empty list of `{ when, then }` cases plus a required `fallback`. An optional `hitPolicy` field (`"first"` or `"unique"`) decides how cases are read; absent is treated as `"first"` — the exact, unchanged behaviour of every tree serialised before this field existed, not a masked-bug fallback.
|
|
473
|
+
|
|
474
|
+
**`hitPolicy: "first"`** (the default). Evaluates to the `then` of the first case whose `when` predicate is definitely `true`; if no case matches, evaluates to `fallback`. If evaluating a `when` predicate produces an indeterminate outcome **before any earlier case has matched**, the whole `conditional` node's own result is that same indeterminate outcome (reason preserved) — evaluation does not skip past an unknown guard to try the next one, because doing so could silently pick a later branch that only looks correct because an earlier one couldn't actually be checked.
|
|
475
|
+
|
|
476
|
+
**`hitPolicy: "unique"`** asserts that at most one case is expected to match, and treats two or more matches as a data error rather than silently taking the first. Every case's `when` is evaluated concurrently (there is no "earlier case" to short-circuit on), then resolved in this order:
|
|
477
|
+
|
|
478
|
+
1. **Two or more cases are definitely `true`** — `domain-error` ("more than one case matched under the 'unique' hit policy"), regardless of any other case's own indeterminacy. This mirrors `memberOf`/`some`/`every`'s existing absorption: a confirmed outcome (here, "there is a genuine ambiguity") cannot be undone by an unrelated case's data problem.
|
|
479
|
+
2. Otherwise, **any case's `when` is indeterminate** — the whole node is indeterminate with that reason (first such candidate, in declared case order, per [The evaluation model](#the-evaluation-model)'s tie-break rule). This is deliberately **not** absorbed by a single already-confirmed match, unlike step 1 above and unlike `memberOf`/`some`/`every`'s own absorption: an unresolved case might still turn out to be a second match, so "exactly one match so far" cannot be trusted as final until every other case is known to not also match.
|
|
480
|
+
3. Otherwise, **exactly one case is definitely `true`** — evaluate and return that case's `then`. No other case's `then` is ever evaluated.
|
|
481
|
+
4. Otherwise (zero matches, and nothing indeterminate) — evaluate and return `fallback`, exactly as `"first"` already does.
|
|
469
482
|
|
|
470
483
|
### `fold`
|
|
471
484
|
|
|
@@ -538,10 +551,58 @@ const average = (collection: JsonValue, item: ExpressionNode, filter?: Predicate
|
|
|
538
551
|
|
|
539
552
|
`average` is `sum` divided by `count` over the same `collection`/`filter`, with no `probe` — `sum`'s own `item` already forces every participating item's projected value to resolve, so `average`'s numerator is already indeterminate under exactly the condition a `count` probe exists to detect, with nothing left to duplicate. Nothing new to verify for the empty-collection case either: division's own already-established rule (zero divisor is `domain-error`) is *why* `average` over an empty collection is `domain-error`, since `count` over an empty collection is `0` and `sum(...)/0` already means exactly that.
|
|
540
553
|
|
|
554
|
+
### Derived values
|
|
555
|
+
|
|
556
|
+
`coalesce` is never its own evaluated node kind — it is a builder function that assembles an ordinary `conditional`, the same treatment [Derived connectives](#derived-connectives) and [Derived aggregates](#derived-aggregates) already give `xor`/`nand`/`nor`/`implies`/`iff`/`none`/`sum`/`count`/`average`: correctness is inherited from the mechanism it's built from, rather than needing its own independent implementation that could silently drift from it.
|
|
557
|
+
|
|
558
|
+
```ts
|
|
559
|
+
const coalesce = (
|
|
560
|
+
first: ExpressionNode,
|
|
561
|
+
second: ExpressionNode,
|
|
562
|
+
...rest: ExpressionNode[]
|
|
563
|
+
): ExpressionNode =>
|
|
564
|
+
[first, second, ...rest].reduceRight(
|
|
565
|
+
(fallback, candidate): ExpressionNode => ({
|
|
566
|
+
kind: "conditional",
|
|
567
|
+
cases: [{ when: { kind: "exists", operand: candidate }, then: candidate }],
|
|
568
|
+
fallback,
|
|
569
|
+
}),
|
|
570
|
+
);
|
|
571
|
+
```
|
|
572
|
+
|
|
573
|
+
Built right-to-left over the full candidate list via `reduceRight`, needing no seed value: `first`/`second` are required arguments (rather than accepting a single `ExpressionNode[]`), which guarantees the list always has at least two elements, so the no-initial-value overload of `reduceRight` never hits an empty array.
|
|
574
|
+
|
|
575
|
+
**Worked correctness check.** `coalesce`'s only interesting behaviour — whether a given candidate is skipped past or propagated — reduces entirely to what its single `exists` probe reports, per [`exists`](#exists)'s and [`conditional`](#conditional)'s own already-established rules:
|
|
576
|
+
|
|
577
|
+
| A candidate's own evaluation | `exists(candidate)` | The `conditional` case | `coalesce` evaluates to |
|
|
578
|
+
|---|---|---|---|
|
|
579
|
+
| A definite value | definite `true` | matches | The candidate's value (re-evaluated as `then`, same result) |
|
|
580
|
+
| Indeterminate, `not-found` | definite `false` | does not match | The next candidate (the enclosing `fallback`), evaluated fresh |
|
|
581
|
+
| Indeterminate, `wrong-type` | definite `true` | matches | The candidate's own `wrong-type` result (re-evaluated as `then`) |
|
|
582
|
+
| Indeterminate, `domain-error` | definite `true` | matches | The candidate's own `domain-error` result (re-evaluated as `then`) |
|
|
583
|
+
|
|
584
|
+
Falling through to the next candidate therefore happens only on `exists`'s own `false` — a genuinely absent value (`not-found`) — never on a candidate that resolved to something merely unusable (`wrong-type`/`domain-error`): `exists` already draws exactly that line, and `coalesce` inherits it unmodified rather than re-deciding it. This is the one behaviour a naive reimplementation is likely to get backwards (treating *any* indeterminate candidate as "try the next one"), so it is worth stating explicitly rather than leaving it to be inferred from the composition alone.
|
|
585
|
+
|
|
586
|
+
A real implementation may memoise a candidate's single evaluation rather than running its resolver twice — once for the `exists` probe, once again for `then` — exactly the same performance caveat [Derived aggregates](#derived-aggregates)'s `presenceOf` already documents for its own `memberOf` probe; resolvers are pure functions of their inputs throughout this design, so this is a performance choice, not a correctness one.
|
|
587
|
+
|
|
541
588
|
### `delegate`
|
|
542
589
|
|
|
543
590
|
An explicitly-named external system plus an arbitrary, unevaluated JSON payload, standing in for the whole node without this package attempting to evaluate it itself — see [Out of scope](#out-of-scope). Evaluating a `delegate` node is not part of this package's own evaluation semantics. The reference evaluator accepts an optional delegate handler per external system name; if none is registered for the named `system`, evaluating the node is indeterminate (`wrong-type`, "no delegate handler registered for external system '<name>'"). Consumers who want a `delegate` node to actually resolve are expected either to register a handler, or to pre-process the tree — walk it, find delegation nodes, invoke the named external system out of band, and substitute the result as a literal — before the tree ever reaches this package's evaluator.
|
|
544
591
|
|
|
592
|
+
### `treeReference`
|
|
593
|
+
|
|
594
|
+
A reference to a whole other tree, identified by an opaque `key` (see [Resolvers](#resolvers)) — the only node kind valid from *both* a `PredicateNode` and an `ExpressionNode` position: the exact same schema is appended as the last member of each of the two discriminated unions above, not two separately-declared copies that happen to look alike. Unlike [`delegate`](#delegate), which hands the whole node off to an *external* system this package never evaluates, `treeReference` resolves to *another tree of this same schema* and evaluates it with this same evaluator — a sub-rule reference, not an escape hatch.
|
|
595
|
+
|
|
596
|
+
`resolveTree` is optional on `Resolvers`, for the same reason `resolveDelegate` is: a well-defined indeterminate result on absence, not a masked bug, and an additive, non-breaking interface change for every consumer implemented before this node kind existed. If no `resolveTree` is registered, evaluating a `treeReference` node is `wrong-type` ("no tree resolver registered for treeReference nodes"). If the resolver reports no match, the result is `not-found`.
|
|
597
|
+
|
|
598
|
+
A resolved tree is never merely trusted — it is re-validated with a fresh `PredicateNodeSchema`/`ExpressionNodeSchema` parse (`PredicateNodeSchema` from a predicate-position reference, `ExpressionNodeSchema` from an expression-position one) before evaluation proceeds, exactly the same discipline the top-level tree itself is subject to when it first arrives at this package. A resolver fetching "a named rule from storage" is very often surfacing the same non-developer-authored JSON the top-level tree already is, with no static guarantee it still matches the schema; a failed parse is `wrong-type`.
|
|
599
|
+
|
|
600
|
+
`context` and the enclosing fold's `accumulator` both pass through a `treeReference` unchanged — the referenced tree shares the caller's evaluation scope, like a subroutine call, not a nested evaluation with its own fresh context. There is deliberately no mechanism to override the context at a `treeReference` boundary; a consumer wanting that already has [`delegate`](#delegate).
|
|
601
|
+
|
|
602
|
+
**Cycle and depth protection.** A tree that references itself, directly or through a longer chain, is guarded by two independent, layered checks rather than one: a cycle detector tracks every `key` (by its `JSON.stringify`'d form) already on the current reference chain, and reports `domain-error` ("circular treeReference detected") the moment a repeat is seen; a fixed depth cap separately reports `domain-error` ("...exceeds the maximum depth") on a long *acyclic* chain the cycle detector alone would never catch. Neither check is a substitute for the other.
|
|
603
|
+
|
|
604
|
+
**A known, accepted design consequence.** `resolveTree` has no built-in way to know whether a given `key` is being resolved from a predicate-position or an expression-position reference — the same is already true of `reference.key` and `lookup.table`, neither of which carries a type discriminator either. A consumer needing to disambiguate structures their own key accordingly (e.g. `{ kind: "predicate", id: "..." }` as the `JsonValue` itself) rather than this schema growing a bespoke field for it.
|
|
605
|
+
|
|
545
606
|
## Collections
|
|
546
607
|
|
|
547
608
|
Both `fold` and the two quantifier leaves (`some`/`every`, and transitively `none`) need "a collection of items" resolved from something the schema itself treats as opaque data. The schema's job is only to carry an opaque reference to what collection is meant, plus a sub-node (an `ExpressionNode` for `fold`, a `PredicateNode` for the quantifiers) to be evaluated once per resolved item, using that single item as its evaluation context, plus an optional per-item pre-filter — see [Pre-filtering which items participate](#pre-filtering-which-items-participate).
|
|
@@ -564,13 +625,17 @@ An item whose `filter` is itself indeterminate is never silently included or exc
|
|
|
564
625
|
|
|
565
626
|
## Resolvers
|
|
566
627
|
|
|
567
|
-
Three
|
|
628
|
+
Three core, required points of extension, plus two further independent optional ones, each supplied separately by the embedding consumer, each treated by the schema as pure data to hand over — never as resolver logic living inside the schema itself:
|
|
568
629
|
|
|
569
630
|
```ts
|
|
570
631
|
type Resolution =
|
|
571
632
|
| { found: true; value: ComputedValue }
|
|
572
633
|
| { found: false };
|
|
573
634
|
|
|
635
|
+
type TreeResolution =
|
|
636
|
+
| { found: true; node: JsonValue }
|
|
637
|
+
| { found: false };
|
|
638
|
+
|
|
574
639
|
interface Resolvers {
|
|
575
640
|
/** Resolver 1 — a single opaque key to a single value (IV.reference). */
|
|
576
641
|
resolveValue(key: JsonValue, context: EvaluationContext): Promise<Resolution>;
|
|
@@ -583,10 +648,15 @@ interface Resolvers {
|
|
|
583
648
|
|
|
584
649
|
/** Optional, separate from the three core contracts — see the `delegate` node kind. */
|
|
585
650
|
resolveDelegate?(system: string, payload: JsonValue, context: EvaluationContext): Promise<Resolution>;
|
|
651
|
+
|
|
652
|
+
/** Optional, separate from the three core contracts — see the `treeReference` node kind. */
|
|
653
|
+
resolveTree?(key: JsonValue, context: EvaluationContext): Promise<TreeResolution>;
|
|
586
654
|
}
|
|
587
655
|
```
|
|
588
656
|
|
|
589
|
-
`resolveCollection` takes no narrowing parameter of its own: it always returns the full candidate list for the given reference, and narrowing which of those candidates actually take part is handled uniformly, after resolution, by the `filter` mechanism described under [Pre-filtering which items participate](#pre-filtering-which-items-participate) — no resolver needs a bespoke narrowing argument for this. It also returns a plain array rather than a `Resolution` envelope: a collection's "nothing here" state is unambiguously an empty array, unlike a single value's absence, which needs an explicit flag to distinguish "there is genuinely nothing here" from any value the resolver might otherwise legitimately return. Each resolver may itself be asynchronous, independently of the others. None of the three needs to know anything about the other two; a consumer implementing all
|
|
657
|
+
`resolveCollection` takes no narrowing parameter of its own: it always returns the full candidate list for the given reference, and narrowing which of those candidates actually take part is handled uniformly, after resolution, by the `filter` mechanism described under [Pre-filtering which items participate](#pre-filtering-which-items-participate) — no resolver needs a bespoke narrowing argument for this. It also returns a plain array rather than a `Resolution` envelope: a collection's "nothing here" state is unambiguously an empty array, unlike a single value's absence, which needs an explicit flag to distinguish "there is genuinely nothing here" from any value the resolver might otherwise legitimately return. Each resolver may itself be asynchronous, independently of the others. None of the three core resolvers needs to know anything about the other two, or about either optional one; a consumer implementing all five is free to have them share underlying data-access logic, but the schema and evaluator never require or assume that they do.
|
|
658
|
+
|
|
659
|
+
`resolveTree` returns a `TreeResolution`, deliberately shaped like `Resolution` but distinct from it: `node` carries opaque JSON — the referenced tree, re-validated by the evaluator rather than trusted (see [`treeReference`](#treereference)) — where `Resolution`'s `value` carries an already-typed `ComputedValue`. It is otherwise the same "found" envelope for the same reason: a `treeReference`'s absence needs to be distinguishable from any tree the resolver might otherwise legitimately return, exactly as a `reference`'s absence needs to be distinguishable from any value. `resolveDelegate` and `resolveTree` solve different problems and are never a substitute for one another: `resolveDelegate` hands a payload to an *external* system this package never evaluates; `resolveTree` hands back *more of this same schema*, for this same evaluator to keep evaluating.
|
|
590
660
|
|
|
591
661
|
## Evaluator entry points
|
|
592
662
|
|
|
@@ -654,10 +724,11 @@ How each reason category can arise, per node kind. "Propagates" means: an indete
|
|
|
654
724
|
| `negate` | operand not found | operand not `number`/`duration` | never directly |
|
|
655
725
|
| `call` | any argument not found | unregistered function name, or an argument of the wrong kind for that function | argument outside the function's valid domain (e.g. negative input to `squareRoot`) |
|
|
656
726
|
| `lookup` | any key not found, or resolver reports no match | a key expression resolves to the wrong kind for that table | never directly |
|
|
657
|
-
| `conditional` | an unmatched guard's own evaluation is `not-found`, before any earlier guard matched
|
|
727
|
+
| `conditional` | `"first"`: an unmatched guard's own evaluation is `not-found`, before any earlier guard matched.<br>`"unique"`: any case's `when` is `not-found`, unless 2+ cases already definitely matched (see `domain-error`, which then takes priority).<br>Both: also the chosen branch's (`then`/`fallback`) own result if it is `not-found`. | Same pattern as `not-found`, substituting `wrong-type` throughout (guard evaluation and chosen branch alike). | `"unique"` only: 2+ cases are definitely `true` — see [`conditional`](#conditional)'s absorption order.<br>Both: same pattern as `not-found`, substituting `domain-error` (guard evaluation and chosen branch alike). |
|
|
658
728
|
| `fold` | any participating item's `filter`, `item`, or `combine` evaluation is `not-found`; or a `reduce`'s `initial` is `not-found` | any participating item's `filter`, `item`, or `combine` evaluation is `wrong-type`; or a `reduce`'s `initial` is `wrong-type` | empty (post-filter) collection with `max`/`min` (no first item to seed from); or any participating item's `item`/`combine` evaluation is `domain-error`; or a `reduce`'s `initial` is `domain-error` |
|
|
659
729
|
| `accumulator` | never | used outside a reduce fold's `combine` expression | never |
|
|
660
730
|
| `delegate` | never (no resolution attempted without a handler) | no handler registered for the named `system` | never |
|
|
731
|
+
| `treeReference` | resolver reports no match | no `resolveTree` registered; or the resolved node fails schema validation | a circular reference is detected; or the reference chain exceeds the maximum depth |
|
|
661
732
|
|
|
662
733
|
## Worked example
|
|
663
734
|
|
|
@@ -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 };
|
package/dist/evaluator.cjs
CHANGED
|
@@ -2,6 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
2
2
|
const require_computed_value = require("./computed-value.cjs");
|
|
3
3
|
const require_evaluation = require("./evaluation.cjs");
|
|
4
4
|
const require_functions = require("./functions.cjs");
|
|
5
|
+
const require_tree = require("./tree.cjs");
|
|
5
6
|
//#region src/evaluator.ts
|
|
6
7
|
/**
|
|
7
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.
|
|
@@ -254,17 +255,19 @@ function applyArithmetic(op, left, right) {
|
|
|
254
255
|
if (right.kind !== "number") return require_evaluation.indeterminate("wrong-type", `arithmetic requires numeric operands; got a '${right.kind}' value`);
|
|
255
256
|
return applyArithmeticOnNumbers(op, left, right);
|
|
256
257
|
}
|
|
258
|
+
/** 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. */
|
|
259
|
+
const MAX_TREE_REFERENCE_DEPTH = 100;
|
|
257
260
|
/**
|
|
258
261
|
* 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
262
|
*/
|
|
260
|
-
async function resolveParticipatingItems(collection, filter, context, resolvers, functions) {
|
|
263
|
+
async function resolveParticipatingItems(collection, filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth) {
|
|
261
264
|
const candidates = await resolvers.resolveCollection(collection, context);
|
|
262
265
|
return Promise.all(candidates.map(async (item) => {
|
|
263
266
|
if (filter === void 0) return {
|
|
264
267
|
item,
|
|
265
268
|
filterOutcome: "include"
|
|
266
269
|
};
|
|
267
|
-
const filterResult = await evaluatePredicateInternal(filter, item, resolvers, void 0, functions);
|
|
270
|
+
const filterResult = await evaluatePredicateInternal(filter, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
|
|
268
271
|
if (filterResult.status === "indeterminate") return {
|
|
269
272
|
item,
|
|
270
273
|
filterOutcome: filterResult
|
|
@@ -282,40 +285,40 @@ function firstFilterIndeterminate(participating) {
|
|
|
282
285
|
if (filterOutcome.status === "indeterminate") return filterOutcome.reason;
|
|
283
286
|
}
|
|
284
287
|
}
|
|
285
|
-
async function evaluatePredicateInternal(node, context, resolvers, accumulator, functions) {
|
|
288
|
+
async function evaluatePredicateInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth) {
|
|
286
289
|
switch (node.kind) {
|
|
287
290
|
case "not": {
|
|
288
|
-
const operand = await evaluatePredicateInternal(node.operand, context, resolvers, accumulator, functions);
|
|
291
|
+
const operand = await evaluatePredicateInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
289
292
|
if (operand.status === "indeterminate") return operand;
|
|
290
293
|
return require_evaluation.definite(!operand.value);
|
|
291
294
|
}
|
|
292
295
|
case "and": {
|
|
293
|
-
const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions)]);
|
|
296
|
+
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
297
|
return combineAnd(left, right);
|
|
295
298
|
}
|
|
296
299
|
case "or": {
|
|
297
|
-
const [left, right] = await Promise.all([evaluatePredicateInternal(node.left, context, resolvers, accumulator, functions), evaluatePredicateInternal(node.right, context, resolvers, accumulator, functions)]);
|
|
300
|
+
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
301
|
return combineOr(left, right);
|
|
299
302
|
}
|
|
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));
|
|
303
|
+
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));
|
|
304
|
+
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
305
|
case "compare": {
|
|
303
|
-
const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions), evaluateValueInternal(node.right, context, resolvers, accumulator, functions)]);
|
|
306
|
+
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
307
|
if (left.status === "indeterminate") return left;
|
|
305
308
|
if (right.status === "indeterminate") return right;
|
|
306
309
|
return compareValues(node.op, left.value, right.value);
|
|
307
310
|
}
|
|
308
311
|
case "textCompare": {
|
|
309
|
-
const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions), evaluateValueInternal(node.right, context, resolvers, accumulator, functions)]);
|
|
312
|
+
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
313
|
if (left.status === "indeterminate") return left;
|
|
311
314
|
if (right.status === "indeterminate") return right;
|
|
312
315
|
return compareText(node.op, left.value, right.value);
|
|
313
316
|
}
|
|
314
317
|
case "memberOf": {
|
|
315
|
-
const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions);
|
|
318
|
+
const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
316
319
|
if (operandResult.status === "indeterminate") return operandResult;
|
|
317
320
|
const candidateOutcomes = await Promise.all(node.candidates.map(async (candidate) => {
|
|
318
|
-
const candidateResult = await evaluateValueInternal(candidate, context, resolvers, accumulator, functions);
|
|
321
|
+
const candidateResult = await evaluateValueInternal(candidate, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
319
322
|
if (candidateResult.status === "indeterminate") return candidateResult;
|
|
320
323
|
return computeMembershipMatch(operandResult.value, candidateResult.value);
|
|
321
324
|
}));
|
|
@@ -328,26 +331,37 @@ async function evaluatePredicateInternal(node, context, resolvers, accumulator,
|
|
|
328
331
|
return require_evaluation.definite(node.op === "notIn");
|
|
329
332
|
}
|
|
330
333
|
case "exists": {
|
|
331
|
-
const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions);
|
|
334
|
+
const operandResult = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
332
335
|
if (operandResult.status === "indeterminate" && operandResult.reason.code === "not-found") return require_evaluation.definite(false);
|
|
333
336
|
return require_evaluation.definite(true);
|
|
334
337
|
}
|
|
335
338
|
case "some":
|
|
336
339
|
case "every": {
|
|
337
|
-
const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions);
|
|
340
|
+
const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth);
|
|
338
341
|
const votes = (await Promise.all(participating.map(async ({ item, filterOutcome }) => {
|
|
339
342
|
if (filterOutcome === "exclude") return void 0;
|
|
340
343
|
if (filterOutcome !== "include") return filterOutcome;
|
|
341
|
-
return evaluatePredicateInternal(node.item, item, resolvers, void 0, functions);
|
|
344
|
+
return evaluatePredicateInternal(node.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
|
|
342
345
|
}))).filter((vote) => vote !== void 0);
|
|
343
346
|
const combine = node.kind === "some" ? combineOr : combineAnd;
|
|
344
347
|
const identity = node.kind === "some" ? require_evaluation.definite(false) : require_evaluation.definite(true);
|
|
345
348
|
return votes.reduce(combine, identity);
|
|
346
349
|
}
|
|
350
|
+
case "treeReference": {
|
|
351
|
+
if (resolvers.resolveTree === void 0) return require_evaluation.indeterminate("wrong-type", "no tree resolver registered for treeReference nodes");
|
|
352
|
+
const keyString = JSON.stringify(node.key);
|
|
353
|
+
if (visitedTreeKeys.has(keyString)) return require_evaluation.indeterminate("domain-error", "circular treeReference detected");
|
|
354
|
+
if (treeReferenceDepth >= MAX_TREE_REFERENCE_DEPTH) return require_evaluation.indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${MAX_TREE_REFERENCE_DEPTH.toString()}`);
|
|
355
|
+
const resolution = await resolvers.resolveTree(node.key, context);
|
|
356
|
+
if (!resolution.found) return require_evaluation.indeterminate("not-found", "treeReference key did not resolve to a tree");
|
|
357
|
+
const parsed = require_tree.PredicateNodeSchema.safeParse(resolution.node);
|
|
358
|
+
if (!parsed.success) return require_evaluation.indeterminate("wrong-type", "the referenced tree is not a valid PredicateNode");
|
|
359
|
+
return evaluatePredicateInternal(parsed.data, context, resolvers, accumulator, functions, /* @__PURE__ */ new Set([...visitedTreeKeys, keyString]), treeReferenceDepth + 1);
|
|
360
|
+
}
|
|
347
361
|
default: throw new Error("unreachable predicate node kind");
|
|
348
362
|
}
|
|
349
363
|
}
|
|
350
|
-
async function evaluateValueInternal(node, context, resolvers, accumulator, functions) {
|
|
364
|
+
async function evaluateValueInternal(node, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth) {
|
|
351
365
|
switch (node.kind) {
|
|
352
366
|
case "reference": {
|
|
353
367
|
const resolution = await resolvers.resolveValue(node.key, context);
|
|
@@ -362,7 +376,7 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
362
376
|
if (accumulator === void 0) return require_evaluation.indeterminate("wrong-type", "accumulator used outside a reduce fold's combine expression");
|
|
363
377
|
return require_evaluation.definite(accumulator);
|
|
364
378
|
case "call": {
|
|
365
|
-
const argResults = await Promise.all(node.args.map(async (arg) => evaluateValueInternal(arg, context, resolvers, accumulator, functions)));
|
|
379
|
+
const argResults = await Promise.all(node.args.map(async (arg) => evaluateValueInternal(arg, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)));
|
|
366
380
|
const args = [];
|
|
367
381
|
for (const result of argResults) {
|
|
368
382
|
if (result.status === "indeterminate") return result;
|
|
@@ -393,18 +407,18 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
393
407
|
unit: node.unit
|
|
394
408
|
});
|
|
395
409
|
case "arithmetic": {
|
|
396
|
-
const [left, right] = await Promise.all([evaluateValueInternal(node.left, context, resolvers, accumulator, functions), evaluateValueInternal(node.right, context, resolvers, accumulator, functions)]);
|
|
410
|
+
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
411
|
if (left.status === "indeterminate") return left;
|
|
398
412
|
if (right.status === "indeterminate") return right;
|
|
399
413
|
return applyArithmetic(node.op, left.value, right.value);
|
|
400
414
|
}
|
|
401
415
|
case "negate": {
|
|
402
|
-
const operand = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions);
|
|
416
|
+
const operand = await evaluateValueInternal(node.operand, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
403
417
|
if (operand.status === "indeterminate") return operand;
|
|
404
418
|
return applyNegate(operand.value);
|
|
405
419
|
}
|
|
406
420
|
case "lookup": {
|
|
407
|
-
const keyResults = await Promise.all(node.keys.map(async (key) => evaluateValueInternal(key, context, resolvers, accumulator, functions)));
|
|
421
|
+
const keyResults = await Promise.all(node.keys.map(async (key) => evaluateValueInternal(key, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)));
|
|
408
422
|
const keyValues = [];
|
|
409
423
|
for (const result of keyResults) {
|
|
410
424
|
if (result.status === "indeterminate") return result;
|
|
@@ -414,15 +428,32 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
414
428
|
if (!resolution.found) return require_evaluation.indeterminate("not-found", `no match found in lookup table ${JSON.stringify(node.table)}`);
|
|
415
429
|
return require_evaluation.definite(resolution.value);
|
|
416
430
|
}
|
|
417
|
-
case "conditional":
|
|
418
|
-
|
|
419
|
-
const
|
|
420
|
-
|
|
421
|
-
|
|
431
|
+
case "conditional": {
|
|
432
|
+
if ((node.hitPolicy ?? "first") === "first") {
|
|
433
|
+
for (const { when, then } of node.cases) {
|
|
434
|
+
const whenResult = await evaluatePredicateInternal(when, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
435
|
+
if (whenResult.status === "indeterminate") return whenResult;
|
|
436
|
+
if (whenResult.value) return evaluateValueInternal(then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
437
|
+
}
|
|
438
|
+
return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
422
439
|
}
|
|
423
|
-
|
|
440
|
+
const evaluatedCases = await Promise.all(node.cases.map(async ({ when, then }) => ({
|
|
441
|
+
then,
|
|
442
|
+
whenResult: await evaluatePredicateInternal(when, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth)
|
|
443
|
+
})));
|
|
444
|
+
const matches = evaluatedCases.filter(({ whenResult }) => whenResult.status === "definite" && whenResult.value);
|
|
445
|
+
if (matches.length >= 2) return require_evaluation.indeterminate("domain-error", "more than one case matched under the 'unique' hit policy");
|
|
446
|
+
const reason = require_evaluation.firstIndeterminate(...evaluatedCases.map(({ whenResult }) => whenResult));
|
|
447
|
+
if (reason !== void 0) return {
|
|
448
|
+
status: "indeterminate",
|
|
449
|
+
reason
|
|
450
|
+
};
|
|
451
|
+
const [match] = matches;
|
|
452
|
+
if (match === void 0) return evaluateValueInternal(node.fallback, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
453
|
+
return evaluateValueInternal(match.then, context, resolvers, accumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
454
|
+
}
|
|
424
455
|
case "fold": {
|
|
425
|
-
const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions);
|
|
456
|
+
const participating = await resolveParticipatingItems(node.collection, node.filter, context, resolvers, functions, visitedTreeKeys, treeReferenceDepth);
|
|
426
457
|
const filterIndeterminateReason = firstFilterIndeterminate(participating);
|
|
427
458
|
if (filterIndeterminateReason !== void 0) return {
|
|
428
459
|
status: "indeterminate",
|
|
@@ -430,11 +461,11 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
430
461
|
};
|
|
431
462
|
const includedItems = participating.filter(({ filterOutcome }) => filterOutcome === "include").map(({ item }) => item);
|
|
432
463
|
if (node.combiner.mode === "reduce") {
|
|
433
|
-
const initialResult = await evaluateValueInternal(node.combiner.initial, context, resolvers, void 0, functions);
|
|
464
|
+
const initialResult = await evaluateValueInternal(node.combiner.initial, context, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
|
|
434
465
|
if (initialResult.status === "indeterminate") return initialResult;
|
|
435
466
|
let runningAccumulator = initialResult.value;
|
|
436
467
|
for (const item of includedItems) {
|
|
437
|
-
const stepResult = await evaluateValueInternal(node.combiner.combine, item, resolvers, runningAccumulator, functions);
|
|
468
|
+
const stepResult = await evaluateValueInternal(node.combiner.combine, item, resolvers, runningAccumulator, functions, visitedTreeKeys, treeReferenceDepth);
|
|
438
469
|
if (stepResult.status === "indeterminate") return stepResult;
|
|
439
470
|
runningAccumulator = stepResult.value;
|
|
440
471
|
}
|
|
@@ -444,7 +475,7 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
444
475
|
const dominatesOp = node.combiner.mode === "max" ? "gt" : "lt";
|
|
445
476
|
let runningExtremum;
|
|
446
477
|
for (const item of includedItems) {
|
|
447
|
-
const itemResult = await evaluateValueInternal(node.combiner.item, item, resolvers, void 0, functions);
|
|
478
|
+
const itemResult = await evaluateValueInternal(node.combiner.item, item, resolvers, void 0, functions, visitedTreeKeys, treeReferenceDepth);
|
|
448
479
|
if (itemResult.status === "indeterminate") return itemResult;
|
|
449
480
|
if (runningExtremum === void 0) {
|
|
450
481
|
runningExtremum = itemResult.value;
|
|
@@ -463,6 +494,17 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
463
494
|
if (!resolution.found) return require_evaluation.indeterminate("not-found", `delegate handler for external system '${node.system}' reported no value`);
|
|
464
495
|
return require_evaluation.definite(resolution.value);
|
|
465
496
|
}
|
|
497
|
+
case "treeReference": {
|
|
498
|
+
if (resolvers.resolveTree === void 0) return require_evaluation.indeterminate("wrong-type", "no tree resolver registered for treeReference nodes");
|
|
499
|
+
const keyString = JSON.stringify(node.key);
|
|
500
|
+
if (visitedTreeKeys.has(keyString)) return require_evaluation.indeterminate("domain-error", "circular treeReference detected");
|
|
501
|
+
if (treeReferenceDepth >= MAX_TREE_REFERENCE_DEPTH) return require_evaluation.indeterminate("domain-error", `treeReference chain exceeds the maximum depth of ${MAX_TREE_REFERENCE_DEPTH.toString()}`);
|
|
502
|
+
const resolution = await resolvers.resolveTree(node.key, context);
|
|
503
|
+
if (!resolution.found) return require_evaluation.indeterminate("not-found", "treeReference key did not resolve to a tree");
|
|
504
|
+
const parsed = require_tree.ExpressionNodeSchema.safeParse(resolution.node);
|
|
505
|
+
if (!parsed.success) return require_evaluation.indeterminate("wrong-type", "the referenced tree is not a valid ExpressionNode");
|
|
506
|
+
return evaluateValueInternal(parsed.data, context, resolvers, accumulator, functions, /* @__PURE__ */ new Set([...visitedTreeKeys, keyString]), treeReferenceDepth + 1);
|
|
507
|
+
}
|
|
466
508
|
default: throw new Error("unreachable expression node kind");
|
|
467
509
|
}
|
|
468
510
|
}
|
|
@@ -471,8 +513,8 @@ async function evaluateValueInternal(node, context, resolvers, accumulator, func
|
|
|
471
513
|
*/
|
|
472
514
|
function createEvaluator({ functions = require_functions.emptyFunctionRegistry }) {
|
|
473
515
|
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)
|
|
516
|
+
evaluatePredicate: async (node, context, resolvers) => evaluatePredicateInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0),
|
|
517
|
+
evaluateValue: async (node, context, resolvers) => evaluateValueInternal(node, context, resolvers, void 0, functions, /* @__PURE__ */ new Set(), 0)
|
|
476
518
|
};
|
|
477
519
|
}
|
|
478
520
|
const { evaluatePredicate, evaluateValue } = createEvaluator({});
|