@inixiative/json-rules 3.16.0 → 3.17.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 +143 -116
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +27 -5
- package/dist/index.d.ts +27 -5
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
# @inixiative/json-rules
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> One of the [inixiative](https://www.inixiative.com) building blocks. Stop rediscovering what you need to build. The [vocabulary](https://www.inixiative.com/vocabulary.html) defines every primitive (`Condition`, `FieldMap`, lens, sources, builders and the layers built on them); [all the projects](https://github.com/inixiative) are on GitHub.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
- Prisma query planning
|
|
7
|
-
- PostgreSQL `WHERE` generation
|
|
5
|
+
A serializable rules engine for TypeScript. You write a rule once, as JSON, and the same rule AST runs in three places:
|
|
8
6
|
|
|
9
|
-
|
|
7
|
+
- `check()` evaluates it against in-memory data and returns `true` or the rule's own error message.
|
|
8
|
+
- `toPrisma()` compiles it into a Prisma query plan.
|
|
9
|
+
- `toSql()` compiles it into a PostgreSQL `WHERE` clause. `toWhereSql()` and `toLensWhereSql()` write inline predicates for PostgreSQL or MySQL.
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
So a rule that validates a form can also select the matching rows, without a second implementation that has to agree with the first. Because a rule is plain data, you can store it in your database, let a tenant edit it, and validate it before you save it. Operators are enums (`Operator`, `ArrayOperator`, `DateOperator`), the rule types are generic TypeScript types (`Condition`), and `{ bind }` placeholders are filled at check time or ahead of compiling with `bindRule`. Under a lens, a rule may read only the fields and relations the lens exposes, and the compilers throw on a rule that reaches past it.
|
|
12
12
|
|
|
13
13
|
## Installation
|
|
14
14
|
|
|
@@ -42,10 +42,10 @@ check(rule, { age: 16 }); // "Must be 18 or older"
|
|
|
42
42
|
- nested logical conditions with `all` / `any`
|
|
43
43
|
- `if` / `then` / `else`
|
|
44
44
|
- array validation against nested object elements
|
|
45
|
-
- array aggregates
|
|
46
|
-
- ordered windowing
|
|
45
|
+
- array aggregates: `sum` and `avg` across numeric arrays or relation lists
|
|
46
|
+
- ordered windowing: first/last `N` with `orderBy` / `take` / `skip` (`check()`; `toPrisma()` compiles the extremal case and a `filter` alone)
|
|
47
47
|
- date comparisons with timezone-aware runtime evaluation
|
|
48
|
-
- relative & calendar date expressions
|
|
48
|
+
- relative & calendar date expressions ("last 30 days", "this month") via `within` and `ago`/`ahead`/`this`/`last`/`next`
|
|
49
49
|
- relative value references via `path`, and `$$.` scope refs up through nested arrays
|
|
50
50
|
- custom error messages on every rule
|
|
51
51
|
- compilation to Prisma and PostgreSQL for supported subsets
|
|
@@ -222,12 +222,12 @@ NULL items are skipped, as SQL's `SUM` / `AVG` skip them.
|
|
|
222
222
|
### Relative & Calendar Date Expressions
|
|
223
223
|
|
|
224
224
|
A date rule's `value` can be a structured, serializable expression instead of an
|
|
225
|
-
absolute date. Magnitudes are always **positive
|
|
225
|
+
absolute date. Magnitudes are always **positive**; the keyword carries the direction.
|
|
226
226
|
A period (`this` / `last` / `next`) names a dayjs unit: `day`, `week`, `isoWeek`, `month`,
|
|
227
227
|
`quarter`, `year`, `hour`, `minute`, `second`. A rolling amount (`ago` / `ahead`) counts
|
|
228
228
|
`years`, `quarters`, `months`, `weeks`, `days`, `hours`, `minutes`, `seconds`.
|
|
229
229
|
|
|
230
|
-
**Point expressions**
|
|
230
|
+
**Point expressions** pair with `before` / `after` / `onOrBefore` / `onOrAfter` /
|
|
231
231
|
`notBefore` / `notAfter`,
|
|
232
232
|
or as `between` endpoints:
|
|
233
233
|
|
|
@@ -246,7 +246,7 @@ or as `between` endpoints:
|
|
|
246
246
|
{ field: 'completedAt', dateOperator: DateOperator.before, value: { end: { last: 'month' } } }
|
|
247
247
|
```
|
|
248
248
|
|
|
249
|
-
**Range expressions**
|
|
249
|
+
**Range expressions** pair with `within` / `notWithin`:
|
|
250
250
|
|
|
251
251
|
```ts
|
|
252
252
|
// "this month"
|
|
@@ -263,14 +263,14 @@ or as `between` endpoints:
|
|
|
263
263
|
{ field: 'lastLoginAt', dateOperator: DateOperator.notWithin, value: { ago: { days: 30 } } }
|
|
264
264
|
```
|
|
265
265
|
|
|
266
|
-
A **bare period** with `before` / `after` resolves to the only sensible edge
|
|
266
|
+
A **bare period** with `before` / `after` resolves to the only sensible edge:
|
|
267
267
|
`before { last: 'month' }` is *before the start* of last month, `after { next: 'month' }`
|
|
268
268
|
is *after the end* of next month. Use `{ start: … }` / `{ end: … }` for the other edge.
|
|
269
269
|
|
|
270
270
|
#### The `now` contract and config
|
|
271
271
|
|
|
272
272
|
Relative/calendar expressions need a reference instant. `now` is an **explicit
|
|
273
|
-
evaluator input
|
|
273
|
+
evaluator input**: there is no implicit `Date.now()` inside the library. Pass it
|
|
274
274
|
on the same options bag as everything else; `check`/`toPrisma`/`toSql` **throw** if
|
|
275
275
|
a relative expression is used without it.
|
|
276
276
|
|
|
@@ -282,14 +282,14 @@ toSql(rule, { now });
|
|
|
282
282
|
|
|
283
283
|
| Option | Default | Governs |
|
|
284
284
|
| --- | --- | --- |
|
|
285
|
-
| `now` |
|
|
286
|
-
| `timeZone` | `'UTC'` | how `now` and period boundaries localize
|
|
285
|
+
| `now` | none (required when a relative/period expression is present) | the anchor instant |
|
|
286
|
+
| `timeZone` | `'UTC'` | how `now` and period boundaries localize: a zone name, or a `{ bind }` read from the bindings |
|
|
287
287
|
| `weekStart` | `'monday'` (ISO / isoWeek) | start of `week` for `this`/`last`/`next` |
|
|
288
288
|
|
|
289
289
|
Compilers resolve expressions to concrete `Date` bounds at compile time, so
|
|
290
290
|
`check()`, `toPrisma()`, and `toSql()` all compare the same instant.
|
|
291
291
|
|
|
292
|
-
### Windowing
|
|
292
|
+
### Windowing: first/last with `orderBy` / `take` / `skip`
|
|
293
293
|
|
|
294
294
|
Array and aggregate rules accept an ordered-window selector that runs **before** the
|
|
295
295
|
predicate. Pipeline: filter → order → skip → take. Direction comes from `orderBy.dir`, so
|
|
@@ -313,16 +313,16 @@ clamp there under `all`). `orderBy` is a non-empty array of `{ field, dir: 'asc'
|
|
|
313
313
|
`all` is vacuously true on an empty window, `atLeast: 1` (or `any`) is false. To require
|
|
314
314
|
"the windowed element matches **and** one exists," combine `all` with `notEmpty` / `atLeast: 1`.
|
|
315
315
|
|
|
316
|
-
> **Compilation.** `toPrisma()` compiles the **extremal** case
|
|
316
|
+
> **Compilation.** `toPrisma()` compiles the **extremal** case: `take: 1`, a single
|
|
317
317
|
> `orderBy`, and a monotonic condition on that same field, with the direction aligned so
|
|
318
318
|
> the extremal element is binding (`all` + desc + `before`, `any` + desc + `after`, etc.).
|
|
319
319
|
> It rewrites to relation filters: the rule above, with `completedAt` required, is "no missions,
|
|
320
|
-
> or some and none since the bound"
|
|
320
|
+
> or some and none since the bound": `{ OR: [{ fanMissions: { none: {} } }, { AND: [{ fanMissions:
|
|
321
321
|
> { some: {} } }, { fanMissions: { none: { completedAt: { gte: <now-30d> } } } }] }] }`. A `filter`
|
|
322
322
|
> alone (no `orderBy` / `take` / `skip`) folds into the rule: `all` through the exact complement
|
|
323
|
-
> of its condition, the rest as `filter AND condition`. Any other windowed rule
|
|
323
|
+
> of its condition, the rest as `filter AND condition`. Any other windowed rule (`take > 1`,
|
|
324
324
|
> `skip`, multi-key `orderBy`, a different/non-monotonic condition, a misaligned direction, or a
|
|
325
|
-
> `filter` beside an ordered window
|
|
325
|
+
> `filter` beside an ordered window) throws a clear "unsupported" error. `toSql()` does not
|
|
326
326
|
> compile windowing at all (no relation subqueries in a `WHERE` fragment). Evaluate the
|
|
327
327
|
> unsupported cases in memory with `check()`.
|
|
328
328
|
|
|
@@ -333,7 +333,7 @@ through `{ bind }` (`check(rule, row, { bindings })`; `bindRule` before compilin
|
|
|
333
333
|
|
|
334
334
|
### Root Row Reference
|
|
335
335
|
|
|
336
|
-
A bare path reads the root row
|
|
336
|
+
A bare path reads the root row: the record `check()` evaluates, the table a compiler compiles
|
|
337
337
|
against:
|
|
338
338
|
|
|
339
339
|
```ts
|
|
@@ -349,7 +349,7 @@ against:
|
|
|
349
349
|
Inside an array operator's `condition` or `filter`, `$.` reads from the current element.
|
|
350
350
|
Each additional `$` reaches one enclosing element further out: `$$.` is the element of the
|
|
351
351
|
enclosing array operator, `$$$.` the one above that, up to the root row. Logical
|
|
352
|
-
combinators (`all` / `any` / `if`) never add a level
|
|
352
|
+
combinators (`all` / `any` / `if`) never add a level; only array and aggregate rules do.
|
|
353
353
|
|
|
354
354
|
Both `field` and `path` take the prefix. A bare `field` is always the current element; a
|
|
355
355
|
bare `path` is always the root row.
|
|
@@ -386,7 +386,7 @@ same visit (a bare path at the root, `$.` inside a relation filter), of exactly
|
|
|
386
386
|
no offset. The plan carries a `{ __field }` sentinel that `executePrismaPlan` resolves to
|
|
387
387
|
`prisma.<model>.fields.<column>`; read a plan's where only through it. Anything else throws, and
|
|
388
388
|
`validateRule(rule, { target: 'toPrisma', map, model })` / `describeRule` report it first. Every
|
|
389
|
-
other scope ref
|
|
389
|
+
other scope ref (a `$$.` path or any prefixed `field`) is check-only; both compilers throw.
|
|
390
390
|
|
|
391
391
|
### Offsets and Unit Amounts
|
|
392
392
|
|
|
@@ -418,7 +418,7 @@ instead of `now`:
|
|
|
418
418
|
`listBindings` lists it. A date offset read per row (a column holding
|
|
419
419
|
`{ ago: … }`) is check-only; to size a shift from the row, read the amount instead.
|
|
420
420
|
|
|
421
|
-
Any relative-date unit
|
|
421
|
+
Any relative-date unit, in a `value` expression or an offset's rolling shift, is a number or a
|
|
422
422
|
value source: `{ path }` from the row, `{ bind }`, or `{ value }`. A relative
|
|
423
423
|
window can take its size from the row it judges:
|
|
424
424
|
|
|
@@ -431,7 +431,7 @@ window can take its size from the row it judges:
|
|
|
431
431
|
Offsets apply to the comparison operators (`equals` … `greaterThanEquals`, `before` …
|
|
432
432
|
`notAfter`) and to both ends of `between` / `notBetween`. Units apply as Postgres applies an
|
|
433
433
|
interval to a wall-clock time in the evaluation's `timeZone` (UTC by default): months (years,
|
|
434
|
-
quarters, months), then days (weeks, days), then time
|
|
434
|
+
quarters, months), then days (weeks, days), then time, so every rail lands on the same instant
|
|
435
435
|
at a month end and across a DST change. Calendar units (years … days) are whole numbers and every
|
|
436
436
|
unit is non-negative: a literal that isn't fails validation, and a value read from data that
|
|
437
437
|
isn't reads as null. A null comparison value, offset or magnitude, or a range missing an end,
|
|
@@ -451,22 +451,22 @@ field, a rolling shift on a DateTime.
|
|
|
451
451
|
|
|
452
452
|
## Rule Introspection
|
|
453
453
|
|
|
454
|
-
Reading a stored rule's own content
|
|
454
|
+
Reading a stored rule's own content (which values it names, which bindings it needs) is
|
|
455
455
|
engine work, not caller work: a walk written outside the engine goes blind the day the rule
|
|
456
456
|
format grows a node type, and it goes blind silently.
|
|
457
457
|
|
|
458
458
|
| Function | Purpose |
|
|
459
459
|
| --- | --- |
|
|
460
|
-
| `listBindings(rule, { required: true })` | Names a bindings map must cover
|
|
461
|
-
| `listBindings(rule)` | Every `{ bind }` name in the tree, optional or not, sorted
|
|
460
|
+
| `listBindings(rule, { required: true })` | Names a bindings map must cover: every `{ bind }` token not marked `bindOptional`, sorted. A name optional at one leaf and required at another is required. |
|
|
461
|
+
| `listBindings(rule)` | Every `{ bind }` name in the tree, optional or not, sorted: what a lens declares. |
|
|
462
462
|
| `bindRule(rule, bindings)` | Substitutes covered binds with their values, leaving uncovered tokens in place (partial resolution). |
|
|
463
463
|
| `clockUnit(rule)` | The finest clock unit the rule's answer can change by while its data stays the same: the smallest unit any relative date in the tree names (`{ ago: { hours: 2 } }` → `hour`, `{ this: 'week' }` → `week`, `isoWeek` → `week`), one of `CLOCK_UNITS` (`second` … `year`); throws on a unit finer than the engine's `clock.finestUnit`, as evaluating the rule does. `null` when it reads no clock: absolute dates, column compares and their offsets, weekday lists. A caller re-evaluates a stored rule on that tick instead of guessing from its JSON. |
|
|
464
464
|
|
|
465
465
|
A leaf may mark its bind optional: `{ field, operator, bind: 'region', bindOptional: true }`. An
|
|
466
|
-
unsupplied required bind is a caller bug
|
|
466
|
+
unsupplied required bind is a caller bug: `check()` throws, and both compilers refuse a
|
|
467
467
|
surviving token. An unsupplied *optional* bind is `null` wherever absence is final: `check()`
|
|
468
468
|
compares against `null`, `toPrisma` / `toSql` compile the token as `null`. The rule is evaluated
|
|
469
|
-
as written
|
|
469
|
+
as written. The leaf is never pruned, so `in {{bind}}` with nothing bound matches nothing rather
|
|
470
470
|
than everything.
|
|
471
471
|
|
|
472
472
|
|
|
@@ -618,7 +618,7 @@ const where = await executePrismaPlan(plan, prisma);
|
|
|
618
618
|
|
|
619
619
|
### Json null checks
|
|
620
620
|
|
|
621
|
-
A Json column holds a DB NULL or a JSON `null`, and a path inside it can be absent
|
|
621
|
+
A Json column holds a DB NULL or a JSON `null`, and a path inside it can be absent. `check()`
|
|
622
622
|
reads all three as null, and Prisma matches them together only with its `AnyNull` instance,
|
|
623
623
|
which it knows by identity. `toPrisma()` takes it from your installed `@prisma/client` (an
|
|
624
624
|
optional peer dependency), so there is nothing to configure; set `prismaOptions.anyNull` only to
|
|
@@ -639,8 +639,8 @@ null` and `in [null]` included, except the ones that hold on a missing value (`i
|
|
|
639
639
|
for real rows (a pseudo record a grant is checked against), so a rule passes only on what the row
|
|
640
640
|
pins. `check()` only; the compilers read real columns.
|
|
641
641
|
|
|
642
|
-
`validateRule(rule, { positive: true })` refuses every shape that can hold on a missing value
|
|
643
|
-
`if`/`then`/`else`, array and aggregate rules, the negations, `isEmpty` and `notExists`
|
|
642
|
+
`validateRule(rule, { positive: true })` refuses every shape that can hold on a missing value
|
|
643
|
+
(`if`/`then`/`else`, array and aggregate rules, the negations, `isEmpty` and `notExists`), so a rule
|
|
644
644
|
checked that way passes only on what the row carries. A rule that means "no value" says `equals
|
|
645
645
|
null`.
|
|
646
646
|
|
|
@@ -664,16 +664,43 @@ engineGlobals.get('string.caseInsensitive'); // true
|
|
|
664
664
|
engineGlobals.set('prismaOptions.datasource.provider', 'mysql');
|
|
665
665
|
engineGlobals.set('sql.dialect', SqlDialect.mysql); // what toWhereSql / toLensWhereSql write
|
|
666
666
|
engineGlobals.set('clock.finestUnit', 'hour'); // a rule reading minutes or seconds fails to evaluate
|
|
667
|
-
engineGlobals.reset(); // back to the defaults
|
|
667
|
+
engineGlobals.reset(); // back to the defaults, registered namespaces' included
|
|
668
668
|
|
|
669
669
|
// A scoped override: merged over the current state for the duration of a synchronous callback.
|
|
670
|
-
|
|
670
|
+
// Flat paths or the nested shape.
|
|
671
|
+
const result = engineGlobals.with({ 'string.caseInsensitive': true }, () => check(rule, data));
|
|
671
672
|
```
|
|
672
673
|
|
|
673
674
|
`with()` restores the previous state when the callback returns or throws. The callback must be
|
|
674
675
|
synchronous: one that returns a Promise throws. `set()` copies plain data and keeps a class
|
|
675
676
|
instance (like `AnyNull`) as given, since Prisma recognizes it by identity.
|
|
676
677
|
|
|
678
|
+
### One engine interaction point for the libraries built on it
|
|
679
|
+
|
|
680
|
+
`engineGlobals` is the settings store for every engine built on json-rules (permissions,
|
|
681
|
+
transitions, rules-builder). A library registers its own namespace, once, at the top of the module
|
|
682
|
+
that reads it, and adds its paths to the types by augmentation:
|
|
683
|
+
|
|
684
|
+
```ts
|
|
685
|
+
import { engineGlobals, registerEngineGlobals } from '@inixiative/json-rules';
|
|
686
|
+
|
|
687
|
+
declare module '@inixiative/json-rules' {
|
|
688
|
+
interface EngineGlobalValues { 'permissions.idField': string }
|
|
689
|
+
}
|
|
690
|
+
registerEngineGlobals('permissions', { idField: 'id' });
|
|
691
|
+
|
|
692
|
+
engineGlobals.set('permissions.idField', 'uuid'); // the app, at boot
|
|
693
|
+
```
|
|
694
|
+
|
|
695
|
+
- A namespace is one segment and never one of json-rules' own roots (`string`, `prismaOptions`,
|
|
696
|
+
`sql`, `clock`). A library registers only its own, and reads its own and those of the engines
|
|
697
|
+
below it.
|
|
698
|
+
- Defaults go in under a value already set, so an app may configure a library before importing it.
|
|
699
|
+
Registering the same defaults again is a no-op; different ones throw.
|
|
700
|
+
- The store lives on `globalThis` under `Symbol.for('@inixiative/json-rules/engineGlobals@3')`:
|
|
701
|
+
every 3.x copy in the process (a nested install, an ESM and a CJS build) reads and writes the same
|
|
702
|
+
settings.
|
|
703
|
+
|
|
677
704
|
## PostgreSQL SQL Generation
|
|
678
705
|
|
|
679
706
|
`toSql()` converts a rule into a parameterized PostgreSQL `WHERE` clause.
|
|
@@ -713,11 +740,11 @@ as `toPrisma()` takes it. A set without `mapName` throws.
|
|
|
713
740
|
toSql(rule, { map: lens, mapName: 'prisma', model: 'Post' });
|
|
714
741
|
```
|
|
715
742
|
|
|
716
|
-
## Inline Predicates
|
|
743
|
+
## Inline Predicates: `toWhereSql`, `toLensWhereSql`
|
|
717
744
|
|
|
718
745
|
Two small helpers write a condition, or a lens's row filters, as a SQL predicate for a caller
|
|
719
746
|
that names its own columns and writes its own joins (an Omni topic, for one). They write the
|
|
720
|
-
engine's `sql.dialect`
|
|
747
|
+
engine's `sql.dialect` (`SqlDialect.postgres` by default, `SqlDialect.mysql` the other) and
|
|
721
748
|
are not a second `toSql`: `toSql` and `toPrisma` are unchanged.
|
|
722
749
|
|
|
723
750
|
```ts
|
|
@@ -757,15 +784,15 @@ toLensWhereSql(lens, { columns, tables });
|
|
|
757
784
|
|
|
758
785
|
- **Operators:** `equals`, `notEquals`, `in`, `notIn`, `exists`, `notExists`, inside `all` / `any`
|
|
759
786
|
(and `true` / `false`), and `any` / `all` / `none` / `empty` / `notEmpty` over a to-many relation
|
|
760
|
-
(below). Anything else
|
|
761
|
-
aggregate, `if` / `then` / `else`
|
|
787
|
+
(below). Anything else (another operator, a date rule, a count or windowed array rule, an
|
|
788
|
+
aggregate, `if` / `then` / `else`) throws, naming it. So do binds, `path` (column-to-column),
|
|
762
789
|
offsets, `coerceType`, case-insensitivity, a path across a bridge, a field rule through a to-many
|
|
763
790
|
relation, anything Json (a stored JSON null is a value to SQL and null to `check()`), and a
|
|
764
791
|
DateTime or list *value*. A DateTime's or list's existence compiles: `deletedAt notExists`, a
|
|
765
792
|
lens's soft-delete `where`, is `… IS NULL`. A rule with no `value` throws, as on every rail.
|
|
766
793
|
- **To-many relations:** an array rule on a to-many relation of the model is one subquery on the
|
|
767
794
|
relation's table, keyed to the row: `any` / `notEmpty` is `EXISTS`, `none` / `empty` is
|
|
768
|
-
`NOT EXISTS`, and `all` is `NOT EXISTS` of a row whose condition `IS NOT TRUE
|
|
795
|
+
`NOT EXISTS`, and `all` is `NOT EXISTS` of a row whose condition `IS NOT TRUE`, so a NULL result
|
|
769
796
|
fails, as in `check()`. The map gives the keys (`relationKeys`; a composite key ANDs every pair):
|
|
770
797
|
the row's side reads `columns['<key>']`, the related side `columns['<relation>.<key>']`.
|
|
771
798
|
`tables['<relation>']` is the table, written after `FROM` as given, with the alias its columns
|
|
@@ -774,15 +801,15 @@ toLensWhereSql(lens, { columns, tables });
|
|
|
774
801
|
another one (`profile.affiliations`), a relation missing from `tables`, `atLeast` / `atMost` /
|
|
775
802
|
`exactly`, a window (`filter` / `orderBy` / `take` / `skip`) and a fieldless array rule throw.
|
|
776
803
|
- **Map:** `map` / `mapName` / `model` are required. A value is checked against its column's
|
|
777
|
-
kind (`leafFitViolations`, as `validateNarrowing` checks it) and an undeclared path is refused
|
|
804
|
+
kind (`leafFitViolations`, as `validateNarrowing` checks it) and an undeclared path is refused, because
|
|
778
805
|
MySQL casts a mistyped literal instead of erroring, so `score = TRUE` would match 1 where
|
|
779
806
|
`check()` matches nothing. The map also finds a to-one relation's key for its `exists`
|
|
780
807
|
(`columns['<relation>.<key>']`: the related row's key, NULL when there is none), and says which
|
|
781
808
|
values have no form here.
|
|
782
809
|
- **Columns:** `columns` maps a field path to the caller's SQL, used as written; the engine writes
|
|
783
|
-
no joins and no identifiers. A path missing from it throws, naming the path
|
|
810
|
+
no joins and no identifiers. A path missing from it throws, naming the path; it never falls back
|
|
784
811
|
to a quoted name, which MySQL's default mode reads as a string literal.
|
|
785
|
-
- **Values** are written inline
|
|
812
|
+
- **Values** are written inline; there are no placeholders to fill. A string doubles `'`; on
|
|
786
813
|
MySQL it doubles `\` too (MySQL's default mode reads a backslash as an escape;
|
|
787
814
|
`NO_BACKSLASH_ESCAPES` is not supported). `in` is `IN (…)`; an enum compares as written, with no
|
|
788
815
|
cast.
|
|
@@ -794,10 +821,10 @@ toLensWhereSql(lens, { columns, tables });
|
|
|
794
821
|
|
|
795
822
|
`toLensWhereSql(lens, { columns, tables?, toMany? })` mirrors the lens: the root path's `where`s under `root` (null
|
|
796
823
|
when it has none), each relation path's own under `relations`, keyed by the path, and each model
|
|
797
|
-
default's (`mapDefaults[map].models[model].where`) under `mapDefaults`, keyed the same way
|
|
824
|
+
default's (`mapDefaults[map].models[model].where`) under `mapDefaults`, keyed the same way: one
|
|
798
825
|
predicate per model however many paths reach it. Each is the `where` as its layer wrote it: a
|
|
799
826
|
parent layer's clamp on a hop is reported at that hop's path, never folded into what a later
|
|
800
|
-
layer wrote through it. A `where` that reads through a relation the lens hides throws
|
|
827
|
+
layer wrote through it. A `where` that reads through a relation the lens hides throws, because that
|
|
801
828
|
hop's clamps have no path to report at, and `check()` still carries them. A lens that spans maps
|
|
802
829
|
reports every map's defaults; a caller writing one database reads its own map's. A path `where` reads `columns` by its path from the lens model (`status` at the root,
|
|
803
830
|
`brandReferenceRequestFanUsers.id` below it); a model default by `'<Model>.<field>'`
|
|
@@ -818,7 +845,7 @@ the lens hides throws, and its condition's fields are checked from the relation,
|
|
|
818
845
|
model it sits on. A model default compiles to one predicate for every path that reaches its
|
|
819
846
|
model, so it throws when a to-many relation it reads carries different clamps on two of them.
|
|
820
847
|
|
|
821
|
-
**Join mode
|
|
848
|
+
**Join mode: `toMany: 'join'`.** For a caller that can't run a correlated subquery (an Omni
|
|
822
849
|
topic rebuilds one as its own query and loses the correlation), the root's `where` reads a to-many
|
|
823
850
|
relation on the row the caller's join brings instead. Nothing about the join is a new option: the
|
|
824
851
|
caller LEFT JOINs each to-many relation the root's `where` reads (a relation the lens declares),
|
|
@@ -841,7 +868,7 @@ toLensWhereSql(lens, { columns, toMany: 'join' });
|
|
|
841
868
|
so one column decides. `cond` may hold on a missing value (`endedAt notExists`): the
|
|
842
869
|
`IS NOT NULL` guard has already dropped the all-NULL row of a parent with no rows.
|
|
843
870
|
- **Positive operators only.** `empty`, `none` and `all` can hold with no rows (the catalog's
|
|
844
|
-
`holdsOnNoRows`), which takes an anti-join, not the topic's join
|
|
871
|
+
`holdsOnNoRows`), which takes an anti-join, not the topic's join: `all(cond)` is
|
|
845
872
|
`none(NOT cond)`, and the join drops the parents with no rows that `all` keeps. They throw, as do
|
|
846
873
|
the counts, `exists` / `notExists` on the relation (a to-many relation has one spelling, an
|
|
847
874
|
`arrayOperator` rule) and a field read through it (`affiliations.affiliation`).
|
|
@@ -884,21 +911,21 @@ Not every backend supports every rule shape.
|
|
|
884
911
|
| Array `all` / `any` / `none` | Yes | Yes | No |
|
|
885
912
|
| Array `atLeast` / `atMost` / `exactly` | Yes | Yes, with `map` + `model` | No |
|
|
886
913
|
| Array `empty` / `notEmpty` | Yes | Yes | Yes (list and Json columns, not relations) |
|
|
887
|
-
| Aggregate `sum` / `avg
|
|
888
|
-
| Aggregate `sum` / `avg
|
|
914
|
+
| Aggregate `sum` / `avg`, primitive or object array | Yes | No | Yes |
|
|
915
|
+
| Aggregate `sum` / `avg`, relation list | Yes | Yes, with `map` + `model` | No |
|
|
889
916
|
| Date comparisons | Yes | Most | Yes |
|
|
890
917
|
| Date expressions (`ago`/`ahead`/`this`/`last`/`next`/`start`/`end`) + `within` | Yes | Yes | Yes |
|
|
891
918
|
| `dayIn` / `dayNotIn` | Yes | No | Yes |
|
|
892
919
|
| Windowing (`filter` / `orderBy` / `take` / `skip`) | Yes | Extremal (`take: 1`, aligned, no `filter`), or a `filter` alone | No |
|
|
893
|
-
| `path
|
|
894
|
-
| `offset` and unit amounts
|
|
895
|
-
| `offset` and unit amounts
|
|
920
|
+
| `path`: a bare root-row column, or `$.` the current element's | Yes (reads the row) | Same model, same visit, exactly the same type, with `equals` / `notEquals` / `lessThan(Equals)` / `greaterThan(Equals)` (a Prisma field reference, resolved by `executePrismaPlan`); anything else throws | Yes (a column; not in a relation filter, not a substring or set operator) |
|
|
921
|
+
| `offset` and unit amounts, value or bind | Yes | Yes | Yes |
|
|
922
|
+
| `offset` and unit amounts, row refs (`$.` or bare) | Yes | No | Yes (not a date offset's) |
|
|
896
923
|
| `$$.` scope refs and `$`-prefixed `field` | Yes | No | No |
|
|
897
924
|
|
|
898
925
|
### NULL Semantics
|
|
899
926
|
|
|
900
|
-
A negated operator is the complement of its positive form
|
|
901
|
-
`check()` gives, where `null !== 'x'` is
|
|
927
|
+
A negated operator is the complement of its positive form: the same answer
|
|
928
|
+
`check()` gives, where `null !== 'x'` is true. SQL's three-valued logic
|
|
902
929
|
disagrees (`col <> 'x'` is NULL, never true, for a NULL column), so the
|
|
903
930
|
compilers carry NULL rows explicitly:
|
|
904
931
|
|
|
@@ -914,19 +941,19 @@ compilers carry NULL rows explicitly:
|
|
|
914
941
|
The **absent set** of a path is wider than a NULL leaf: an optional to-one hop can be NULL too,
|
|
915
942
|
and `{ rel: { col: { equals: null } } }` only matches when the relation exists. So every negation
|
|
916
943
|
also carries `{ rel: { is: null } }` for each optional to-one hop on the path (licensed by the
|
|
917
|
-
relation entry's `isRequired: false`)
|
|
944
|
+
relation entry's `isRequired: false`). `profile.bio notEquals 'x'` compiles to
|
|
918
945
|
`{ OR: [{ profile: { bio: { not: 'x' } } }, { profile: { bio: { equals: null } } }, { profile: { is: null } }] }`,
|
|
919
946
|
matching check() (a missing hop reads as NULL) and toSql (LEFT JOIN + `IS NULL`). `equals null`
|
|
920
947
|
and `in [null, …]` carry the same hop arms: a user with no profile has a NULL `profile.bio`.
|
|
921
948
|
|
|
922
|
-
`toPrisma()` can only add the null arm when it knows the column is nullable
|
|
949
|
+
`toPrisma()` can only add the null arm when it knows the column is nullable, because
|
|
923
950
|
an `equals: null` on a NOT NULL column is a Prisma validation error. Nullability
|
|
924
951
|
comes from the field map: `FieldMapEntry.isRequired: false` (prisma-map emits it).
|
|
925
952
|
Without `{ map, model }`, or on an entry that doesn't declare it, the bare
|
|
926
953
|
`not` / `notIn` is emitted and NULL rows fall out, as they always did.
|
|
927
954
|
|
|
928
955
|
Date rules follow the same split. The positive operators answer non-match on both
|
|
929
|
-
rails
|
|
956
|
+
rails: a bare boundary is not something a NULL column satisfies, so `check()`
|
|
930
957
|
reports the rule's ordinary non-match (honoring `error`) and the compilers keep the
|
|
931
958
|
bare `<` / `BETWEEN`. The negative-flavored ones (`notBefore`, `notAfter`, `notWithin`, `notBetween`, `dayNotIn`) follow
|
|
932
959
|
the negation ruling instead: a never-set date is not in the range, so a null column
|
|
@@ -940,7 +967,7 @@ positive operator, ask for them:
|
|
|
940
967
|
| `notAfter X` / `notBefore X` | matches | `(col <= $1 OR col IS NULL)` / `(col >= $1 OR col IS NULL)` | `{ OR: [{ col: { lte } }, { col: { equals: null } }] }` (nullable column) |
|
|
941
968
|
| `notWithin { ago: { days: 30 } }` | matches | `(col NOT BETWEEN $1 AND $2 OR col IS NULL)` | `{ OR: [{ NOT: { col: { gte, lte } } }, { col: { equals: null } }] }` (nullable column) |
|
|
942
969
|
| `notBetween` | matches | `(col NOT BETWEEN $1 AND $2 OR col IS NULL)` | `{ OR: [{ NOT: { col: … } }, { col: { equals: null } }] }` (nullable column, same field-map licensing as above) |
|
|
943
|
-
| `dayNotIn` | matches | `(EXTRACT(DOW FROM col) <> ALL($1) OR col IS NULL)` |
|
|
970
|
+
| `dayNotIn` | matches | `(EXTRACT(DOW FROM col) <> ALL($1) OR col IS NULL)` | none (no Prisma output) |
|
|
944
971
|
| `notExists` OR `before` | matches via the first arm | `(col IS NULL OR col < $1)` | `{ OR: [{ col: { equals: null } }, { col: { lt: … } }] }` |
|
|
945
972
|
|
|
946
973
|
`0` is an instant (1970-01-01) and compares; `''` is malformed data and raises
|
|
@@ -952,9 +979,9 @@ positive operator, ask for them:
|
|
|
952
979
|
- `dayIn` and `dayNotIn` are not supported by Prisma output
|
|
953
980
|
- `path: '$.field'` column-to-column comparisons are not supported by Prisma `WHERE`; no scope ref (`$$.` path, prefixed `field`) compiles
|
|
954
981
|
- count-based and aggregate relation operators require `{ map, model }`
|
|
955
|
-
- aggregate rules on JSON/native stored arrays are not supported by Prisma
|
|
982
|
+
- aggregate rules on JSON/native stored arrays are not supported by Prisma; use `toSql()` or `check()` for those
|
|
956
983
|
- element conditions (`all` / `any` / `none` / counts) over a scalar list or a Json array are not supported by Prisma; test a list's membership with `contains`
|
|
957
|
-
- a field path through a to-many relation (`posts.title`) is an error on both compilers
|
|
984
|
+
- a field path through a to-many relation (`posts.title`) is an error on both compilers; compare its rows with an array rule on `posts`
|
|
958
985
|
- Prisma loads a NULL scalar-list column as `[]`, so `check()` over Prisma-loaded rows reads it as an empty list while the compilers read NULL; a list Prisma writes is never NULL, so this only matters for rows written outside Prisma
|
|
959
986
|
|
|
960
987
|
### SQL Limitations
|
|
@@ -978,7 +1005,7 @@ engines themselves differ:
|
|
|
978
1005
|
- Ordered string comparisons (`lessThan`, `between` on text) follow each engine's order:
|
|
979
1006
|
`check()` compares UTF-16 code units, Postgres the column's collation.
|
|
980
1007
|
- An array or aggregate rule on a Json value that isn't an array is a data error. `check()`
|
|
981
|
-
throws on it; SQL can't raise per row, so it reads the value as an empty array
|
|
1008
|
+
throws on it; SQL can't raise per row, so it reads the value as an empty array, for an
|
|
982
1009
|
aggregate and for `empty` / `notEmpty` alike.
|
|
983
1010
|
|
|
984
1011
|
## TypeScript Types
|
|
@@ -1028,18 +1055,18 @@ Lens & bridges:
|
|
|
1028
1055
|
|
|
1029
1056
|
A lens has three forms, each with its own job:
|
|
1030
1057
|
|
|
1031
|
-
- **Composed
|
|
1058
|
+
- **Composed**: a `Lens`, or a `LensNarrowing` whose `parent` holds the layer above it as an
|
|
1032
1059
|
object, down to the base lens. Every evaluator takes this form.
|
|
1033
|
-
- **Stored
|
|
1060
|
+
- **Stored**: `StoredLens`, one record per layer: its `id`, `parents` (the ids of every layer it
|
|
1034
1061
|
composes with, the base lens first) and its own part. The base lens is the root-most record,
|
|
1035
1062
|
stored as itself with no parents. `storeLens(lens, ids)` writes a composed lens out as records;
|
|
1036
|
-
`composeLens(id, records)` reads them back
|
|
1063
|
+
`composeLens(id, records)` reads them back (fetch the layer, then the ids it lists), validating
|
|
1037
1064
|
each layer against the ones above it and failing closed on a missing record, a base out of
|
|
1038
1065
|
place, or a parent whose own list disagrees.
|
|
1039
|
-
- **Projected
|
|
1066
|
+
- **Projected**: what a lens exposes, which never leads back to the lens:
|
|
1040
1067
|
- `projectLens(lens)` returns `Record<dottedPath, ProjectedVisit>` for per-path checks where
|
|
1041
1068
|
sibling paths to the same model diverge.
|
|
1042
|
-
- `projectLens(lens, { by: 'model' })` returns the leak-safe total surface *as a Lens
|
|
1069
|
+
- `projectLens(lens, { by: 'model' })` returns the leak-safe total surface *as a Lens*: every
|
|
1043
1070
|
model the relations turned on reach, with the full narrowing applied, unioned per model, `where`
|
|
1044
1071
|
stripped. Use it as the server→client builder surface; it never exposes the raw lens. It is a
|
|
1045
1072
|
view, not a gate: as a lens it is bare and turns no relation on, so gate rules against the
|
|
@@ -1137,7 +1164,7 @@ Two error classes say whose input went wrong; each sets `name`, so check with `i
|
|
|
1137
1164
|
| Class | Thrown when | Fix |
|
|
1138
1165
|
| --- | --- | --- |
|
|
1139
1166
|
| `UsageError` | The caller's input is missing or malformed: no `now` for a relative date, an invalid `now` or time zone, a bind never bound (`bindRule` / `bindLens` before compiling; `bindings` for `check`). | Supply the input. |
|
|
1140
|
-
| `LensRefusal` (`code`) | The lens itself can't do it: a later layer's clamp reads what its parent hides, a clamp or source a compile has no form for, a source path that can't carry its link. | Fix the lens
|
|
1167
|
+
| `LensRefusal` (`code`) | The lens itself can't do it: a later layer's clamp reads what its parent hides, a clamp or source a compile has no form for, a source path that can't carry its link. | Fix the lens; `validateNarrowing` reports the same refusal as an issue. |
|
|
1141
1168
|
|
|
1142
1169
|
```ts
|
|
1143
1170
|
import { LensRefusal, UsageError } from '@inixiative/json-rules';
|
|
@@ -1178,35 +1205,35 @@ check(
|
|
|
1178
1205
|
|
|
1179
1206
|
## Lens & Multi-Source Data
|
|
1180
1207
|
|
|
1181
|
-
> **For the full lens guide
|
|
1208
|
+
> **For the full lens guide, including the three anchor layers for `where`
|
|
1182
1209
|
> (root, model-default, relation-descent), the `all` operator filter-first
|
|
1183
|
-
> trick, per-model enum narrowing, and a validate-then-apply usage pattern
|
|
1210
|
+
> trick, per-model enum narrowing, and a validate-then-apply usage pattern,
|
|
1184
1211
|
> see [docs/LENS.md](./docs/LENS.md).**
|
|
1185
1212
|
> This section covers the high-level shape and the multi-source bridges.
|
|
1186
1213
|
|
|
1187
1214
|
### What a lens is *for*
|
|
1188
1215
|
|
|
1189
|
-
A lens is not a query filter. It
|
|
1190
|
-
over data**
|
|
1216
|
+
A lens is not a query filter. It is a composable, **enforceable model of authority
|
|
1217
|
+
over data** (*what a party can see and what it can do*), delegated down a chain of
|
|
1191
1218
|
trust boundaries (platform → org → space → subtenant → client). Each layer can only
|
|
1192
1219
|
**narrow**, never widen (`validateNarrowing` keeps the chain monotonic), and the
|
|
1193
1220
|
boundary is **enforced, not documented**:
|
|
1194
1221
|
|
|
1195
|
-
- a rule authored against a lens provably can't reference outside it
|
|
1196
|
-
`validateRuleInLens`, at author time;
|
|
1222
|
+
- a rule authored against a lens provably can't reference outside it
|
|
1223
|
+
(`validateRuleInLens`, at author time);
|
|
1197
1224
|
- the row-scope **`where` is the clamp, applied server-side at execution** via
|
|
1198
|
-
`narrowRule
|
|
1199
|
-
- what reaches an untrusted party reveals nothing hidden
|
|
1225
|
+
`narrowRule`; the authored rule never sees it and can't escape it;
|
|
1226
|
+
- what reaches an untrusted party reveals nothing hidden (`projectLens(…, { by: 'model' })`).
|
|
1200
1227
|
|
|
1201
1228
|
A lens defines a **surface area**, reused for distinct, separately-enforced
|
|
1202
1229
|
constraints that may **diverge**: the *data-flow* surface (what you receive / pass
|
|
1203
1230
|
into an interpolated template / expose to a client) vs the *reasoning* surface
|
|
1204
|
-
(what you may author predicates against
|
|
1205
|
-
|
|
1231
|
+
(what you may author predicates against, which can be narrower than what you
|
|
1232
|
+
get back). One predicate DSL (`Condition`) expresses both the **clamp**
|
|
1206
1233
|
(`where`) and the **use** (rules), compiling to `check` / `toPrisma` / `toSql`.
|
|
1207
1234
|
That's why the same primitive backs permissions, email targeting/conditions,
|
|
1208
|
-
feature flags, and state-transition guards
|
|
1209
|
-
|
|
1235
|
+
feature flags, and state-transition guards: each composes on the same authority
|
|
1236
|
+
and visibility model.
|
|
1210
1237
|
|
|
1211
1238
|
### How it's built
|
|
1212
1239
|
|
|
@@ -1214,7 +1241,7 @@ The `Lens` primitive is a schema-aware view layer over one or more `FieldMap`s.
|
|
|
1214
1241
|
|
|
1215
1242
|
### FieldMap & FieldMapSet
|
|
1216
1243
|
|
|
1217
|
-
A `FieldMap` is `{ models, enums? }
|
|
1244
|
+
A `FieldMap` is `{ models, enums? }`: models keyed by name, plus an optional enum registry scoped to that source. A `FieldMapSet` groups one or more `FieldMap`s and declares the cross-source edges between them:
|
|
1218
1245
|
|
|
1219
1246
|
```ts
|
|
1220
1247
|
import { stitchFieldMaps } from '@inixiative/json-rules';
|
|
@@ -1240,7 +1267,7 @@ const set = stitchFieldMaps({
|
|
|
1240
1267
|
});
|
|
1241
1268
|
```
|
|
1242
1269
|
|
|
1243
|
-
`stitchFieldMaps()` injects bridge entries as `kind: 'bridge'` fields on each endpoint model
|
|
1270
|
+
`stitchFieldMaps()` injects bridge entries as `kind: 'bridge'` fields on each endpoint model, addressable in rules via `<fieldMap>:<Model>` notation (e.g. `salesforce:Contact.industry`). Each endpoint's `on` is the symmetric join field used at eval time for hydration. Bridge cardinality controls list-vs-single on each side.
|
|
1244
1271
|
|
|
1245
1272
|
### Lens
|
|
1246
1273
|
|
|
@@ -1257,12 +1284,12 @@ const lens = createLens({
|
|
|
1257
1284
|
});
|
|
1258
1285
|
```
|
|
1259
1286
|
|
|
1260
|
-
The lens is **schema only
|
|
1287
|
+
The lens is **schema only**; no data lives on it. Runtime data (rows, foreign tables, FE picker sources) is passed alongside, separately, when you need it.
|
|
1261
1288
|
|
|
1262
1289
|
### Relations
|
|
1263
1290
|
|
|
1264
1291
|
Relations are fields, off by default. A bare lens reads its anchor model's columns and nothing
|
|
1265
|
-
else. The first narrowing over the base lens turns a relation on through the relation object
|
|
1292
|
+
else. The first narrowing over the base lens turns a relation on through the relation object,
|
|
1266
1293
|
never through `picks`, which names columns only:
|
|
1267
1294
|
|
|
1268
1295
|
```ts
|
|
@@ -1289,7 +1316,7 @@ validateRuleInLens({ field: 'posts', arrayOperator: ArrayOperator.any, condition
|
|
|
1289
1316
|
visited, and may nest further relations.
|
|
1290
1317
|
- **Only the first narrowing turns relations on; later layers narrow.** A later layer may omit a
|
|
1291
1318
|
relation (`omits: ['org']`, which `picks` never conflicts with), or restate one its parent shows
|
|
1292
|
-
to add that hop's narrowing
|
|
1319
|
+
to add that hop's narrowing; a restatement hides nothing else. Naming a relation its parent
|
|
1293
1320
|
doesn't show fails `validateNarrowing` (`not_visible`), and does nothing at runtime.
|
|
1294
1321
|
- **The model defaults grow a tree.** From the anchor and every spelled path, model-default
|
|
1295
1322
|
turn-ons are followed breadth-first, each model once, at its nearest reach (ties: the earlier
|
|
@@ -1298,7 +1325,7 @@ validateRuleInLens({ field: 'posts', arrayOperator: ArrayOperator.any, condition
|
|
|
1298
1325
|
agree and stay small. `lensVisit(lens, 'org.users')` resolves one visit on demand, as
|
|
1299
1326
|
`projectLens` would give it, or `null`.
|
|
1300
1327
|
- **Clamps.** The first narrowing's `where`s (and source eligibility `where`s) may read any
|
|
1301
|
-
relation on the schema; a later layer's may read only what its parent shows
|
|
1328
|
+
relation on the schema; a later layer's may read only what its parent shows, so a delegate can't
|
|
1302
1329
|
probe a relation it can't see (`validateNarrowing` reports it; every posture throws). A bare
|
|
1303
1330
|
value `path` reads the root row, so only `root.where` may hold one. `toLensSelect` fetches exactly the columns clamps read, and
|
|
1304
1331
|
`projectRows({ keepClampColumns: true })` keeps them for a re-check.
|
|
@@ -1326,7 +1353,7 @@ const narrowing: LensNarrowing = {
|
|
|
1326
1353
|
};
|
|
1327
1354
|
```
|
|
1328
1355
|
|
|
1329
|
-
Composition across chained narrowings is pure intersection: relations are turned on by the first narrowing and only hidden after it. `where` clauses are anchored to the model they describe
|
|
1356
|
+
Composition across chained narrowings is pure intersection: relations are turned on by the first narrowing and only hidden after it. `where` clauses are anchored to the model they describe: `root.where` ANDs at the lens anchor, `mapDefaults[X].models[Y].where` injects at every visit of Y in map X, and `root.relations[R]...where` injects when the rule descends through R. Under the `all` array operator the clamp goes into the rule's window `filter`, so out-of-scope rows are dropped before the user's "every row matches" check; `check()` and `toPrisma` run it. See [docs/LENS.md](./docs/LENS.md) for the full anchor semantics.
|
|
1330
1357
|
|
|
1331
1358
|
### Lens Utilities
|
|
1332
1359
|
|
|
@@ -1334,15 +1361,15 @@ Composition across chained narrowings is pure intersection: relations are turned
|
|
|
1334
1361
|
| --- | --- |
|
|
1335
1362
|
| `validateNarrowing(narrowing)` | Returns `{ ok, errors: { path, message, code }[] }` for structural or chain problems, one code each: `not_in_lens`, `not_visible` (an item an ancestor hid, or a relation the parent doesn't show), `conflicting_selection` (picks beside an omitted column), `wrong_kind` (a relation named in `picks`, among others), `value_not_allowed`, `invalid_source` (a source label / axis crossing a relation that is off, among others), `invalid_binding`, plus the lens gate's codes for a `where`. `assertValidNarrowing` throws instead. Call at narrowing construction. |
|
|
1336
1363
|
| `assertValidFieldMaps(set)` | Throws when a field name in any map holds `.` or `:` (a path step and a bridge marker). `validateFieldMaps(set)` returns `{ ok, errors }` with code `invalid_field_name`. To check a single map, wrap it: `assertValidFieldMaps({ maps: { prisma: map } })`. |
|
|
1337
|
-
| `projectLens(lens)` | Returns `Record<dottedPath, ProjectedVisit
|
|
1338
|
-
| `describeRuleSources(rule, lens)` | The values a rule names at each source the lens declares, keyed like `projectLens` (`path` + `field`, with the source's `mapName` / `model`). Resolved through the lens like `walkLensPath`, so `mapDefaults` sources answer wherever a relation turned on reaches their model. `dynamic: true` when the set can't be enumerated: a `path` / `bind` leaf, an offset or a read amount that moves the value, a substring / pattern / range / window operator, or an operator the catalog doesn't know
|
|
1364
|
+
| `projectLens(lens)` | Returns `Record<dottedPath, ProjectedVisit>`: each path the relations turned on reach keys its own resolved narrowing (path picks/omits/enums chain-intersected ∩ `mapDefaults` for the target model); a relation field appears only where it is on. Sibling paths to the same model stay independent. Use for SDK-contract / OpenAPI emission, search-field enumeration, validation whitelists. See [docs/LENS.md §10](./docs/LENS.md). |
|
|
1365
|
+
| `describeRuleSources(rule, lens)` | The values a rule names at each source the lens declares, keyed like `projectLens` (`path` + `field`, with the source's `mapName` / `model`). Resolved through the lens like `walkLensPath`, so `mapDefaults` sources answer wherever a relation turned on reaches their model. `dynamic: true` when the set can't be enumerated: a `path` / `bind` leaf, an offset or a read amount that moves the value, a substring / pattern / range / window operator, or an operator the catalog doesn't know; callers fail closed on it. The reverse question for a reference registry ("which rows does this rule name"): join `model` + `values`. |
|
|
1339
1366
|
| `validateRuleInLens(rule, lens)` | Validates a user rule's field paths and enum values against the narrowed lens, path-aware. Returns `{ ok, errors: { path, message, code }[] }` like `validateRule` (codes such as `not_in_lens`, `operator_kind_mismatch`, `invalid_value`, `value_not_allowed`). Every relation a field, a value ref, an offset or an `orderBy` / aggregate field crosses must be turned on. A bare value `path` is a root-row column, gated like a field. The security gate. |
|
|
1340
|
-
| `describeRule(rule, lens)` | `{ sources, bridgesCrossed, supportedTargets, errors }`: the maps a rule reads, whether it crosses a bridge, which of `check` / `toPrisma` / `toSql` can run it (by the rule's shape, as `validateRule` reads it
|
|
1367
|
+
| `describeRule(rule, lens)` | `{ sources, bridgesCrossed, supportedTargets, errors }`: the maps a rule reads, whether it crosses a bridge, which of `check` / `toPrisma` / `toSql` can run it (by the rule's shape, as `validateRule` reads it; a compiler may still refuse a field's kind, such as a date rule on a String column on Prisma), and the lens gate's `ValidationIssue`s. For routing and UX; `validateRuleInLens` stays the gate. |
|
|
1341
1368
|
| `getLensRoot(lensOrNarrowing)` | The base lens a narrowing chain is rooted at; a lens is its own. Throws on a cyclic chain. |
|
|
1342
1369
|
| `clampLens(lens, clamps)` | The lens with `clamps` (`{ root?: { where }, mapDefaults?: { [map]: { models: { [model]: { where?, sources? } } } } }`) ANDed into its first narrowing over the base lens, one added over a bare lens; later layers kept as they were. Only the first layer's clamps read the whole schema, so a clamp on what a later layer hides goes here. A source's `where` ANDs; its `label` / `groupBy` win, and a source clamp on a field with none adds that option set. Wheres only narrow. |
|
|
1343
|
-
| `lensVisit(lens, relationPath, options?)` | One visit as `projectLens` (by path) gives it
|
|
1370
|
+
| `lensVisit(lens, relationPath, options?)` | One visit as `projectLens` (by path) gives it (its shown fields with values and options, sources, labels and axes) at a dotted relation path from the anchor (`''` for the anchor), resolved on demand: nothing is enumerated, so it is cheap on any schema. `null` when a relation on the path isn't shown there (off, omitted, or outside the model-default tree). A builder walks a lens with it instead of re-deriving the lens's rules. |
|
|
1344
1371
|
| `walkLensPath(lens, path)` | Resolves one dotted path through the lens hop by hop: `{ outcome: 'resolved', hops, terminal, jsonSubPath }`, or `hidden` (a column it doesn't keep, or a relation it doesn't turn on there) / `missing` / `pastScalar` with the failing `index`. |
|
|
1345
|
-
| `readLensValue(lens, row, path, options?)` | One value off a row, as the lens shows it: `{ ok: true, value }`, or `{ ok: false, reason }`
|
|
1372
|
+
| `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. |
|
|
1346
1373
|
| `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)). |
|
|
1347
1374
|
| `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`. |
|
|
1348
1375
|
| `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. |
|
|
@@ -1430,18 +1457,18 @@ const projection = projectLens(narrowing, { sourceValues: [values] });
|
|
|
1430
1457
|
|
|
1431
1458
|
| Function | Purpose |
|
|
1432
1459
|
| --- | --- |
|
|
1433
|
-
| `toSourceQueries(lensOrNarrowing, options?)` | `SourceQuery[]`, one per sourced field: `{ path, mapName, model, field, label?, groupBy?, composedWhere, prisma, sql, recheck? }`. `options` is the clock (`now`, `timeZone`, `weekStart`) a relative date in the where compiles with
|
|
1460
|
+
| `toSourceQueries(lensOrNarrowing, options?)` | `SourceQuery[]`, one per sourced field: `{ path, mapName, model, field, label?, groupBy?, composedWhere, prisma, sql, recheck? }`. `options` is the clock (`now`, `timeZone`, `weekStart`) a relative date in the where compiles with: required for one, a plain usage error without it; bind a lens's binds with `bindLens` first. `prisma.steps` is present when the where needs `executePrismaPlan` (a count step, or a column reference to resolve): query with the where it returns. `sql.sql` is `null` with an `error` when SQL can't express the where. A source that reads across a bridge gets an over-fetching query and a `recheck`: its rows are candidates, not options (see "Sources across a bridge"). `distinct` is the value and a sibling label column; a grouped source or a dotted label drops it, so every label comes back and the least one is picked. |
|
|
1434
1461
|
| `materializeSourceQuery(query, rows, { rowShape?, lens?, now?, … })` | One query's fetched rows as `SourceValues`. `rowShape` is `'prisma'` (default: a dotted `label` and each `groupBy` axis come nested) or `'sql'` (they come flat as `__label` / `__group_i`). Options are deduplicated and sorted. A query with `recheck` needs `lens` and rows holding the far side: it re-checks each candidate (`check`, with the clock and bindings given) and reads a bridged label or axis from the far side; a missing far side is a `UsageError`. |
|
|
1435
|
-
| `materializeSources(lensOrNarrowing, rows, options?)` | `SourceValues[]` for every sourced field, from the rows the lens fetches
|
|
1462
|
+
| `materializeSources(lensOrNarrowing, rows, options?)` | `SourceValues[]` for every sourced field, from the rows the lens fetches: `toLensSelect`'s rows as fetched, or as `projectRows(…, { keepClampColumns: true })` keeps them. A viewer's projection drops what sources read: a row lacking any key a read walks (through each relation and list element to the column) that a source or a clamp on its path reads throws a `UsageError` (a fetch returns every key it selects, NULL as `null`). The path is walked down the rows (the tree is its link), each level's clamps met, and each row it reaches must meet, through `check()` with `options`, its visit's clamps, its source `where` narrowed as a rule is, the guards of the relations its label and axes cross and the values the lens allows, so it offers what `toSourceQueries` does. A scalar-list field gives one option per element; a value takes its least label. A `from: 'mapDefaults'` source throws (see below). |
|
|
1436
1463
|
|
|
1437
1464
|
Options never offer a value the lens disallows: `projectLens` drops fetched values outside a
|
|
1438
1465
|
field's allowed set. Nor do they come through a row the lens hides: each source `where` is
|
|
1439
|
-
narrowed under the whole lens as `narrowRule` narrows a rule
|
|
1466
|
+
narrowed under the whole lens as `narrowRule` narrows a rule: every relation it crosses carries
|
|
1440
1467
|
that visit's clamps, inside an array condition (into its `condition`, or its `filter` under `all`,
|
|
1441
1468
|
a window or no condition) and on each hop and terminal relation of a dotted path. A clamp a rule
|
|
1442
1469
|
couldn't carry there (one narrowRule can't re-root, a to-many relation read flat) is refused, as
|
|
1443
1470
|
it is for a rule; so is a source whose query has a window toPrisma can't compile (by its shape,
|
|
1444
|
-
before anything compiles
|
|
1471
|
+
before anything compiles; `materializeSources` refuses it too, so the two never disagree).
|
|
1445
1472
|
|
|
1446
1473
|
#### Two kinds of source
|
|
1447
1474
|
|
|
@@ -1449,7 +1476,7 @@ A source declared down a relation path offers the rows **reachable** from there:
|
|
|
1449
1476
|
carried down through each relation's inverse (where the map declares one), and every clamp above
|
|
1450
1477
|
it with it, so a Tag source under `User.tagAttachments.tag` offers the tags a live
|
|
1451
1478
|
attachment of an in-tenant user points at. When a field should offer every row the lens lets its
|
|
1452
|
-
model show
|
|
1479
|
+
model show (linked or not, what a rule may *name*), point the path source at the model's own
|
|
1453
1480
|
source:
|
|
1454
1481
|
|
|
1455
1482
|
```ts
|
|
@@ -1476,34 +1503,34 @@ mapDefaults: {
|
|
|
1476
1503
|
},
|
|
1477
1504
|
```
|
|
1478
1505
|
|
|
1479
|
-
`from: 'mapDefaults'` resolves where it sits
|
|
1480
|
-
model>].sources[<field>]`
|
|
1506
|
+
`from: 'mapDefaults'` resolves where it sits (`mapDefaults[<this path's map>].models[<this path's
|
|
1507
|
+
model>].sources[<field>]`) and takes that source's eligibility (tenancy included), label and
|
|
1481
1508
|
axes; its own `where`, and child layers, only narrow it. A pointer drops the clamps the path
|
|
1482
1509
|
carries down only in the layer that declares it: every layer before or after it still carries
|
|
1483
1510
|
theirs, so a child's pointer can only narrow what its parent gave, and a tenant layer added after a
|
|
1484
1511
|
pointer always narrows it. How depends on how it scopes: through `mapDefaults` (the model's own
|
|
1485
1512
|
clamp or source) the pointer still offers unlinked rows; through a root `where` the clamp can only
|
|
1486
|
-
reach the pointer down the path, so it offers just the linked rows
|
|
1513
|
+
reach the pointer down the path, so it offers just the linked rows, and across a bridge the
|
|
1487
1514
|
clamp comes back as the query's `recheck` (below). Scope tenancy through `mapDefaults` to keep a pointer's unlinked rows.
|
|
1488
1515
|
A pointer whose model declares no source fails `validateNarrowing` (`invalid_source`) and throws
|
|
1489
1516
|
from `projectLens` (by path) / `toSourceQueries` / `materializeSources`, even where a layer hides
|
|
1490
1517
|
its field; `projectLens(…, { by: 'model' })` and `describeRuleSources` read the lens without
|
|
1491
1518
|
validating it. Across a bridge it is how a picker gets options at all: the
|
|
1492
1519
|
model source compiles against the far map alone, with that map's own tenancy, where a path source
|
|
1493
|
-
over-fetches and re-checks (see "Sources across a bridge"). A clamp a path can't carry down
|
|
1494
|
-
map declares no inverse
|
|
1520
|
+
over-fetches and re-checks (see "Sources across a bridge"). A clamp a path can't carry down (a relation whose
|
|
1521
|
+
map declares no inverse) is a `LensRefusal`, never an empty list. `materializeSources` refuses a pointer, because a fetched collection can't hold unlinked
|
|
1495
1522
|
rows; query it with `toSourceQueries` and `materializeSourceQuery`.
|
|
1496
1523
|
|
|
1497
1524
|
#### Sources across a bridge
|
|
1498
1525
|
|
|
1499
1526
|
A source whose path, `where`, `label` or an axis reads across a bridge can't be decided by one
|
|
1500
|
-
database
|
|
1527
|
+
database: each holds one side. `toSourceQueries` still returns a real query for the side it can
|
|
1501
1528
|
see, and marks it with `recheck`:
|
|
1502
1529
|
|
|
1503
1530
|
- **The query over-fetches.** What reads across the bridge compiles to TRUE (the compilers'
|
|
1504
1531
|
over-fetch), so the query never pre-filters on what it can't see: its rows are a **superset** of
|
|
1505
1532
|
the true options. Everything local is still decided by the database.
|
|
1506
|
-
- **`recheck` is what the database couldn't decide
|
|
1533
|
+
- **`recheck` is what the database couldn't decide**: the conjuncts of `composedWhere` that read
|
|
1507
1534
|
across a bridge, or `true` when only the label or an axis does. **If `recheck` is present, the
|
|
1508
1535
|
query's rows are candidates, not options.** A source that reads no bridge has no `recheck`.
|
|
1509
1536
|
- **The query selects local columns only:** the value, a local label and local axes, the local
|
|
@@ -1511,15 +1538,15 @@ see, and marks it with `recheck`:
|
|
|
1511
1538
|
read crosses first). It drops `distinct`, since candidates differ in what the re-check reads. A
|
|
1512
1539
|
label or axis across the bridge is not selected.
|
|
1513
1540
|
- **Load the far side, then materialize.** Put the far row inline on each candidate under its
|
|
1514
|
-
bridge field (the `indexBridges` shape
|
|
1541
|
+
bridge field (the `indexBridges` shape: one row, or a list where the bridge names many) and
|
|
1515
1542
|
call `materializeSourceQuery(query, rows, { lens, rowShape?, now? })`. It requires every key the
|
|
1516
|
-
re-check and a bridged label or axis read, as `materializeSources` does
|
|
1543
|
+
re-check and a bridged label or axis read, as `materializeSources` does (a candidate without
|
|
1517
1544
|
the far side, a far row without a column read, or a list where the bridge names one row throws a
|
|
1518
|
-
`UsageError`
|
|
1545
|
+
`UsageError`), keeps the candidates `check(recheck, row)` holds, and reads the label and axes
|
|
1519
1546
|
across the bridge from the far side, in either row shape. Without `lens` it throws.
|
|
1520
1547
|
- **A source past a bridge** (its path crosses one) is queried against its own model's map; the
|
|
1521
1548
|
clamps above it are carried back across the bridge through the far model's bridge field, and
|
|
1522
|
-
come back as its `recheck
|
|
1549
|
+
come back as its `recheck`, so each candidate holds the near rows inline
|
|
1523
1550
|
(`{ id, industry, 'prisma:FanUser': [{ email, … }] }`).
|
|
1524
1551
|
- **A re-check reading into a Json column selects the column whole** (`meta: true`, never a nested
|
|
1525
1552
|
select into it); the re-check reads inside it in memory.
|
|
@@ -1559,20 +1586,20 @@ const holds = forRecheck.filter((row) => check(narrowRule(rule, narrowing), row,
|
|
|
1559
1586
|
|
|
1560
1587
|
| Function | Purpose |
|
|
1561
1588
|
| --- | --- |
|
|
1562
|
-
| `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
|
|
1563
|
-
| `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
|
|
1589
|
+
| `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 })`. |
|
|
1590
|
+
| `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. |
|
|
1564
1591
|
|
|
1565
1592
|
### Evaluating Across Bridges
|
|
1566
1593
|
|
|
1567
|
-
`path:` refs (used for value comparisons) walk via the same dotted-path mechanism as `field:`. Bridge keys (`'salesforce:Contact'`) are
|
|
1594
|
+
`path:` refs (used for value comparisons) walk via the same dotted-path mechanism as `field:`. Bridge keys (`'salesforce:Contact'`) are plain object properties, so `path: 'salesforce:Contact.industry'` works in both `field:` (left side) and `path:` (right side) positions.
|
|
1568
1595
|
|
|
1569
1596
|
**Limitations to know:**
|
|
1570
1597
|
|
|
1571
|
-
- **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
|
|
1572
|
-
- **Bridge keys are plain object properties.** The engine doesn't consult `lens.bridges` at eval time
|
|
1598
|
+
- **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.
|
|
1599
|
+
- **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.
|
|
1573
1600
|
|
|
1574
1601
|
|
|
1575
|
-
`check()` itself is bridge-unaware
|
|
1602
|
+
`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:
|
|
1576
1603
|
|
|
1577
1604
|
```ts
|
|
1578
1605
|
const fanUser = { id: 'u1', email: 'a@b.com', crmId: 'c1' };
|
|
@@ -1586,7 +1613,7 @@ const rule = { field: 'salesforce:Contact.industry', operator: Operator.equals,
|
|
|
1586
1613
|
check(rule, data);
|
|
1587
1614
|
```
|
|
1588
1615
|
|
|
1589
|
-
For **bidirectional traversal**, use JavaScript object references
|
|
1616
|
+
For **bidirectional traversal**, use JavaScript object references. `check`'s path walker handles circular structures fine because rules are finite trees and only resolve named paths:
|
|
1590
1617
|
|
|
1591
1618
|
```ts
|
|
1592
1619
|
fanUser['salesforce:Contact'] = contact;
|
|
@@ -1615,7 +1642,7 @@ check(
|
|
|
1615
1642
|
);
|
|
1616
1643
|
```
|
|
1617
1644
|
|
|
1618
|
-
The lens schema (with `Bridge.endpoints[*].on`) is what tells the caller how to fetch and index foreign data. The runtime engine
|
|
1645
|
+
The lens schema (with `Bridge.endpoints[*].on`) is what tells the caller how to fetch and index foreign data. The runtime engine walks the resulting structure.
|
|
1619
1646
|
|
|
1620
1647
|
## Examples
|
|
1621
1648
|
|