@inixiative/json-rules 4.3.0 → 4.5.1

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 CHANGED
@@ -169,7 +169,8 @@ Supported comparison operators for aggregate rules: `equals`, `notEquals`, `less
169
169
 
170
170
  ### Aggregate Rule
171
171
 
172
- Computes `sum` or `avg` of an array and compares the result to a value.
172
+ Computes `sum` or `avg` of an array and compares the result to a value — or picks the window's
173
+ values (`pick`, check() only; see Value Expressions) and compares those.
173
174
 
174
175
  ```ts
175
176
  // Primitive numeric array
@@ -240,9 +241,35 @@ already use. `evaluateValue(expression, row, options)` takes what `check()` take
240
241
  values, as SQL's `AVG`, and in an aggregate rule), `count` (the rows; with `aggregate.field`, the rows whose field has a value),
241
242
  `min` and `max` (numbers or dates, the value as stored; null over no rows), and `distinct`
242
243
  (strings, enums, dates, booleans or numbers: the values without repeats, first seen first, NULLs
243
- skipped; `[]` over no rows). The window
244
- runs first (filter → order → skip → take), then `condition`. An aggregate rule still compares
245
- `sum` / `avg` only.
244
+ skipped; `[]` over no rows), and `pick` (any kind: the rows' values themselves, in the window's
245
+ order, NULLs skipped — one value for `take: 1`, null over no row; a list otherwise, `[]` over none;
246
+ with no `orderBy` it picks in the order the rows are in). A window orders its keys as the rows
247
+ carry them: values in mixed forms (numbers as strings, dates as strings in differing formats) order
248
+ oddly, so coerce the rows first (`coerceValue` stamps the picked values, not the order keys).
249
+ In a rule, a `take: 1` pick over no row is absent, as a path the row doesn't carry: null by
250
+ default, unknown under `absent: 'unknown'`; a row that holds NULL is null either way.
251
+ The window runs first (filter → order → skip → take), then `condition`. An aggregate rule compares
252
+ `sum`, `avg` and `pick`.
253
+
254
+ ```ts
255
+ // The winning source's job title: the jobTitle row with the lowest sourceRank
256
+ {
257
+ field: 'enrichments',
258
+ filter: { field: 'field', operator: 'equals', value: 'jobTitle' },
259
+ orderBy: [{ field: 'sourceRank', dir: 'asc' }],
260
+ take: 1,
261
+ aggregate: { mode: 'pick', field: 'value' },
262
+ }
263
+ // As a rule: add a comparison. A take-1 pick compares as a field holding the value does;
264
+ // a list pick (any take but 1) takes contains / notContains of one value.
265
+ { ...winningJobTitle, operator: 'equals', value: 'CTO' }
266
+ ```
267
+
268
+ `pick` is check() / `evaluateValue` only: it is what its window orders, and neither compiler
269
+ compiles an ordered window — `toSql` compiles no window, and a Prisma `where` can't read "the
270
+ first row by X" of a relation. `validateRule` refuses it for `toSql` / `toPrisma`
271
+ (`unsupported_sql_aggregate_mode` / `unsupported_prisma_aggregate_mode`), and the compilers throw
272
+ the same message.
246
273
 
247
274
  Values compare as stored, kind by kind: `distinct` keeps `1`, `Decimal('1')`, `1n` and `'1'` as
248
275
  four values, which shows mixed data rather than hiding it. To read them as one kind, give
@@ -296,7 +323,7 @@ What a consumer checks before saving one:
296
323
  | Function | Purpose |
297
324
  | --- | --- |
298
325
  | `validateValue(expr)` / `assertValidValue(expr)` | The shape, without data: each node exactly one kind, known keys, a known mode, and every condition it holds valid as `validateRule` sees it. |
299
- | `inferValueType(expr, lens?)` | `{ kind, isList, nullable }`: a literal's kind, a path's column kind through the lens, `count` → `Int`, `sum` → the column's numeric kind, `avg` → `Float` (`Decimal` stays `Decimal`, nullable), `min` / `max` → the column's kind (nullable), `distinct` → a list of the column's kind (never null); with `coerceType`, that kind. Branches and list items must agree; two numeric kinds read as `Decimal` when either is, else `Float`. Throws on an expression with no type. The lens is needed wherever a column's kind is read. |
326
+ | `inferValueType(expr, lens?)` | `{ kind, isList, nullable }`: a literal's kind, a path's column kind through the lens, `count` → `Int`, `sum` → the column's numeric kind, `avg` → `Float` (`Decimal` stays `Decimal`, nullable), `min` / `max` → the column's kind (nullable), `distinct` → a list of the column's kind (never null), `pick` → the column's kind (nullable) for `take: 1`, else a list of it; with `coerceType`, that kind. Branches and list items must agree; two numeric kinds read as `Decimal` when either is, else `Float`. Throws on an expression with no type. The lens is needed wherever a column's kind is read. |
300
327
  | `valueClockUnit(expr)` | `clockUnit` over every condition the expression holds: a 90-day window reads `day`. |
301
328
  | `describeValue(expr, lens)` | Its type, the dotted paths it reads (`brandReferenceRequestFanUsers.activatedAt`), its clock unit, and every issue (shape, lens gate, type) as `{ path, code, message }`, without throwing. |
302
329
 
@@ -774,6 +801,20 @@ null check (`equals null`, `in` with null among its values), so a rule checked t
774
801
  on what the row carries. A null check holds on every row without a value, which is how a rule ends
775
802
  up granting everything; name the value that is there instead (a kind, an explicit `'none'`).
776
803
 
804
+ It also refuses a match without an `exists`: a field compared with a `path` or a `bind` needs an
805
+ `exists` on it beside it in an `all`, because two missing values match (`ownerId equals
806
+ actor:User.id` holds on a record with no owner and a call with no actor). A comparison with a
807
+ literal needs none: a missing value already fails it, bridged or not. Bridging only links a row
808
+ that is there; a read of one that is not is missing like any other. The `exists` names the exact
809
+ field, and counts from any `all` above the comparison, never from an `any`:
810
+
811
+ ```ts
812
+ { all: [
813
+ { field: 'ownerId', operator: 'exists' },
814
+ { field: 'ownerId', operator: 'equals', path: 'actor:User.id' },
815
+ ] }
816
+ ```
817
+
777
818
  ## Engine Globals
778
819
 
779
820
  `engineGlobals` holds process-wide defaults. Keys are dotted paths into one state object, and `set` / `get` are typed per path (`EngineGlobalPath`, `EngineGlobalValues`): each path takes only its own values.
@@ -1201,7 +1242,7 @@ Lens & bridges:
1201
1242
  - `validateNarrowing`, `assertValidNarrowing`, `validateRuleInLens`, `narrowRule`, `coerceRule`
1202
1243
  - `bindLens`, `listLensBindings`, `getLensRoot`, `clampLens`, `LensClamps`
1203
1244
  - `projectLens`, `walkLensPath`, `readLensValue`, `LensValue`, `describeRule`, `describeRuleSources`
1204
- - `toLensSelect`, `projectRows`, `LensSelect`, `LensRelationSelect`, `LensSelectOptions`, `ProjectRowsOptions`
1245
+ - `toLensSelect`, `projectRows`, `LensQuery`, `LensSelect`, `LensRelationSelect`, `LensOrderBy`, `LensOrderKey`, `LensSelectOptions`, `ProjectRowsOptions`
1205
1246
  - `toSourceQueries`, `materializeSources`, `materializeSourceQuery`
1206
1247
  - `toLensWhereSql`, `LensWhereSql`, `LensWhereSqlOptions`
1207
1248
  - `PathProjection`, `ProjectedVisit`, `ProjectLensOptions`, `LensPathHop`, `LensPathResolution`, `RuleDescription`, `RuleSourceDescription`, `SourceQuery`, `SourcePrismaQuery`, `SourceSqlQuery`, `SourceSelect`, `SourceValues`, `SourceRowShape`, `MaterializeSourceQueryOptions`
@@ -1534,7 +1575,7 @@ Composition across chained narrowings is pure intersection: relations are turned
1534
1575
  | `readLensValue(lens, row, path, options?)` | One value off a row, as the lens shows it: `{ ok: true, value }`, or `{ ok: false, reason }`, where `reason` is `hidden` / `missing` / `pastScalar` (the walk `validateRuleInLens` gates a field with), `relation` (the path ends on rows, not a value) or `list` (it crosses a to-many). Each row on the way, the root included, is checked against its visit's clamps: one a clamp hides, or a missing one, reads `null`. Only own properties are read, into a Json column too. `options` is what each clamp is checked with (`now`, `bindings`). For values a template interpolates. |
1535
1576
  | `orderRecords(items, orderBy)` | Records sorted by an `OrderBy` exactly as a window orders them on every rail: each key in turn, own-property path reads, `dir` order, NULL or absent last in either direction, ties in input order. Returns a new array. Strings sort in JavaScript code-unit order, which can differ from a database's collation (see [Where the Rails Differ](#where-the-rails-differ)). |
1536
1577
  | `narrowRule(rule, narrowing)` | Composes the user rule with the lens's `where` clauses, injecting each at its anchor in the rule tree. Under an `all`, the clamp goes into the rule's window `filter`, which `check()` evaluates and `toPrisma` folds into the rule (`toSql` compiles no relation arrays). Other rules pass to `check` / `toPrisma` / `toSql`. |
1537
- | `coerceValue(expression, lens)` | Stamps each `distinct` / `min` / `max` over a DateTime column with `coerceType: 'DateTime'`, so rows that carry dates as ISO strings (plain JSON) read them as dates. Leaves other kinds (a Decimal `min` / `max` still returns the value as stored), an aggregate that names its own `coerceType`, and one the lens can't type. |
1578
+ | `coerceValue(expression, lens)` | Stamps each `distinct` / `min` / `max` / `pick` over a DateTime column with `coerceType: 'DateTime'`, so rows that carry dates as ISO strings (plain JSON) read them as dates. Leaves other kinds (a Decimal `min` / `max` still returns the value as stored), an aggregate that names its own `coerceType`, and one the lens can't type. |
1538
1579
  | `coerceRule(rule, lens)` | Stamps each field rule with its field's `coerceType` from the lens (`Int`, `Float`, `Decimal`, `BigInt`, `DateTime`, `Boolean`, `String`). Leaves date rules, aggregate comparisons, rules that already carry a `coerceType`, and anything below a Json column alone. |
1539
1580
 
1540
1581
  ```ts
@@ -1749,7 +1790,7 @@ const holds = forRecheck.filter((row) => check(narrowRule(rule, narrowing), row,
1749
1790
 
1750
1791
  | Function | Purpose |
1751
1792
  | --- | --- |
1752
- | `toLensSelect(lensOrNarrowing, options?)` | `{ select }` for `findMany` at the base model. It selects each visit's visible columns and the relations turned on there (one that is off is not fetched; the model-default tree bounds it), and every column a `where` on the way reads. A to-many relation carries its visit's clamps compiled as its `where`, so related rows come pre-narrowed, unless a clamp reads that list: a clamp reads it whole, as the database does, so it is fetched whole and `projectRows` cuts it. A to-one relation takes no `where` in Prisma, so `projectRows` drops one its clamp hides. A relation that shows no column (one turned on with all its columns hidden, or one a clamp reads only for presence or a count) is fetched by its key alone (the join key, else `id`), even a hidden one, as a clamp's columns are; never another column. The fetch carries it for the re-check and a viewer's projection drops it; a model with no key is not fetched, and presence on it can't be re-checked from fetched rows. A root that shows no column is selected by its `id` likewise. Bridges are skipped. It also selects what each projected source reads (the value, its label and axes, and every column and relation its option query's condition reads), as it does a clamp's columns, so `materializeSources` over the fetched rows offers what the database does; a viewer's projection drops them. For a source across a bridge that is its local reads: what it reads on this side, hidden or not, and each crossed bridge's local `on` key, so the rows plus the far side loaded under its bridge field answer it. A to-many relation's clamp that needs a counting step (a count or an aggregate), or has a window toPrisma can't compile, is refused (a `LensRefusal`, which `validateNarrowing` reports) before anything compiles. `options` is the clock for compiling the clamps. The root's own clamps are the query's `where`: `toPrisma(rule, { lens })`. |
1793
+ | `toLensSelect(lensOrNarrowing, options?)` | `{ select }` for `findMany` at the base model, with `orderBy` beside it when the lens orders the root rows (`root.orderBy`, or a model default on the root model); spread both into the query. It selects each visit's visible columns and the relations turned on there (one that is off is not fetched; the model-default tree bounds it), and every column a `where` on the way reads. A to-many relation carries its visit's clamps compiled as its `where`, so related rows come pre-narrowed, unless a clamp reads that list: a clamp reads it whole, as the database does, so it is fetched whole and `projectRows` cuts it. A to-one relation takes no `where` in Prisma, so `projectRows` drops one its clamp hides. A relation that shows no column (one turned on with all its columns hidden, or one a clamp reads only for presence or a count) is fetched by its key alone (the join key, else `id`), even a hidden one, as a clamp's columns are; never another column. The fetch carries it for the re-check and a viewer's projection drops it; a model with no key is not fetched, and presence on it can't be re-checked from fetched rows. A root that shows no column is selected by its `id` likewise. Bridges are skipped. It also selects what each projected source reads (the value, its label and axes, and every column and relation its option query's condition reads), as it does a clamp's columns, so `materializeSources` over the fetched rows offers what the database does; a viewer's projection drops them. For a source across a bridge that is its local reads: what it reads on this side, hidden or not, and each crossed bridge's local `on` key, so the rows plus the far side loaded under its bridge field answer it. A to-many relation's clamp that needs a counting step (a count or an aggregate), or has a window toPrisma can't compile, is refused (a `LensRefusal`, which `validateNarrowing` reports) before anything compiles. `options` is the clock for compiling the clamps. The root's own clamps are the query's `where`: `toPrisma(rule, { lens })`. |
1753
1794
  | `projectRows(lensOrNarrowing, rows, options?)` | Rows cut to what the lens shows, recursively. Hidden columns, and relations that are off or omitted, are removed. A row a visit's `where` hides is dropped from the root or a list, and a to-one row becomes `null`. `keepClampColumns: true` keeps the columns those `where`s and the projected sources read, even hidden ones, and a hidden to-one row, or a hidden row of a list a clamp reads, as those columns alone, so `check(narrowRule(rule, lens), row)` re-tests the clamps as the database does, for any rule the lens admits; that output carries hidden values, so never return it to a viewer. The other options (`now`, `bindings`) are what each `where` is checked with. A `Decimal` column's value, whether a Decimal.js-like object such as Prisma's `Decimal` (anything with `toNumber()`) or a numeric string, comes back a number, a list column element by element; a non-numeric value passes through. Plain JSON out. |
1754
1795
 
1755
1796
  ### Supplied bridges (no join)
@@ -1781,7 +1822,7 @@ tells the two apart (`JoinedBridge`, `SuppliedBridge`).
1781
1822
  **Limitations to know:**
1782
1823
 
1783
1824
  - **1-many bridge arrays are not iterable mid-path.** `field: 'crm:MarketingEvent.campaign'` or `path: 'crm:MarketingEvent.campaign'` returns `undefined` when the bridge value is an array: a path read follows own properties one segment at a time and doesn't fan out across array elements. Use a numeric index (`crm:MarketingEvent.0.campaign` or `crm:MarketingEvent[0].campaign`) or `arrayOperator` on the `field:` side to iterate. A name on `Object.prototype` (`constructor`, `toString`) reads as absent.
1784
- - **Bridge keys are plain object properties.** The engine doesn't consult `lens.bridges` at eval time; callers structure `data` correctly using the schema as a guide. Use `indexBridges(lens, rawForeign)` to pre-index foreign rows by `on` field, then embed under bridge keys per anchor row.
1825
+ - **Bridge keys are plain object properties.** `check()` doesn't consult `lens.bridges`; `recordWithBridgeData(set, 'app:Doc', record, data)` fills them from the same `data` `indexBridges` takes (rows keyed `map:Model`; a supplied bridge's second endpoint gets one row). It drops every key the record carries that names a model of the set's maps (a record cannot bring its own `actor:User`), puts each joined bridge's far row (found by `on`) and each supplied bridge's given row under its endpoint key, and strips bridge keys from the far rows it embeds.
1785
1826
 
1786
1827
 
1787
1828
  `check()` itself is bridge-unaware: it walks paths via plain property access. The lens primitive is **schema metadata** (what fields exist, what bridges link them, what `on` fields join each side). The caller is responsible for structuring `data` accordingly: