@inixiative/transitions 0.6.0 → 0.7.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 +32 -28
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
# @inixiative/transitions
|
|
2
2
|
|
|
3
|
+
> One of the [inixiative](https://www.inixiative.com) building blocks. Stop rediscovering what you need to build. See [all the projects](https://github.com/inixiative).
|
|
4
|
+
|
|
3
5
|
A small, **stateless** primitive on top of [`@inixiative/json-rules`](https://github.com/inixiative/json-rules)
|
|
4
6
|
that answers two questions about an entity's lifecycle, declaratively:
|
|
5
7
|
|
|
6
|
-
- **"Can this change happen?"**
|
|
7
|
-
- **"What changes can happen?"**
|
|
8
|
-
`toPrisma
|
|
8
|
+
- **"Can this change happen?"** `checkTransition` guards a proposed update.
|
|
9
|
+
- **"What changes can happen?"** `available` lists the actions open to one record, and `eligible`
|
|
10
|
+
compiles the same rules through `toPrisma` into a query for every record an action is open to.
|
|
9
11
|
|
|
10
12
|
It is **not** a state machine (no statecharts/actors/hierarchy), does **not** own state, and does
|
|
11
13
|
**not** execute the change or run side effects. It is a guard + affordance layer. A transition is
|
|
12
|
-
**pure data
|
|
13
|
-
no deploy to change
|
|
14
|
+
**pure data**, so a tenant's lifecycle can be stored in the database and edited in a UI at runtime,
|
|
15
|
+
with no deploy to change it. Because one rule set answers both the single-record check and the
|
|
16
|
+
set query, the set query never returns a record the check would refuse; where a rule can't compile
|
|
17
|
+
to Prisma, `eligible` throws.
|
|
14
18
|
|
|
15
19
|
> Full design: [`docs/FEAT-018-transitions.md`](./docs/FEAT-018-transitions.md).
|
|
16
20
|
|
|
@@ -22,16 +26,16 @@ resource → action → Action { paths: Transition[], label? }
|
|
|
22
26
|
Side { predicate, permission?, requires? }
|
|
23
27
|
```
|
|
24
28
|
|
|
25
|
-
A `resource` key is map-qualified (`map:Model`, e.g. `db:Inquiry`)
|
|
29
|
+
A `resource` key is map-qualified (`map:Model`, e.g. `db:Inquiry`), the same convention
|
|
26
30
|
`@inixiative/permissions` uses, so a transition's `permission` can delegate into the rebac schema.
|
|
27
31
|
|
|
28
|
-
A `Transition` is one atomic `from → to` edge. An **Action** (a named verb) is the OR of its edges
|
|
32
|
+
A `Transition` is one atomic `from → to` edge. An **Action** (a named verb) is the OR of its edges:
|
|
29
33
|
disjunction lives at the action level, never inside a `Transition`, so the kernel stays atomic and
|
|
30
34
|
serializable.
|
|
31
35
|
|
|
32
|
-
The `from`/`to` asymmetry
|
|
36
|
+
The `from`/`to` asymmetry matters and applies to **both** `predicate` (legality) and
|
|
33
37
|
`permission` (authz): `from.*` is evaluated against the **current** record, `to.*` against the
|
|
34
|
-
**resulting (merged)** record. Permission only ever lives on a side
|
|
38
|
+
**resulting (merged)** record. Permission only ever lives on a side: every authz check reads a
|
|
35
39
|
concrete record, so there is no record-free action-level permission.
|
|
36
40
|
|
|
37
41
|
## Check
|
|
@@ -60,7 +64,7 @@ checkTransition(rules, 'db:Inquiry', 'approve', { status: 'approved' }, { status
|
|
|
60
64
|
```
|
|
61
65
|
|
|
62
66
|
`checkTransition(rules, resource, action, record, changes, { actor, authorize })` returns **`true`** when
|
|
63
|
-
allowed, else a structured **`Reason
|
|
67
|
+
allowed, else a structured **`Reason`**, never a bare bool:
|
|
64
68
|
|
|
65
69
|
```ts
|
|
66
70
|
type SideReason = { predicate?: string; permission?: string }; // why one side failed
|
|
@@ -69,7 +73,7 @@ type Reason = { paths: PathReason[] }; // one entry per
|
|
|
69
73
|
```
|
|
70
74
|
|
|
71
75
|
Each side reports its `predicate` (legality) and `permission` (authz) failures independently, and
|
|
72
|
-
`from`/`to` are kept separate
|
|
76
|
+
`from`/`to` are kept separate, so the caller sees every failure, not only the first. To
|
|
73
77
|
map to HTTP: a path that fails purely on `permission` is a 403; any `predicate` failure is a 409.
|
|
74
78
|
`describe(reason)` builds a human-readable message.
|
|
75
79
|
|
|
@@ -100,12 +104,12 @@ from.permission AND to.permission
|
|
|
100
104
|
|
|
101
105
|
Absent = open; `null` (or `false`) = terminal deny. Omit `authorize` to check legality only.
|
|
102
106
|
|
|
103
|
-
### `createAuthorize
|
|
107
|
+
### `createAuthorize`: the `@inixiative/permissions` adapter
|
|
104
108
|
|
|
105
109
|
Authorization is **not** reimplemented here. `createAuthorize` is a thin adapter that bridges
|
|
106
110
|
`@inixiative/permissions`' production rebac `check` onto the `Authorize` seam:
|
|
107
111
|
`createAuthorize(options)(resource)` returns an `Authorize` bound to a (map-qualified) `resource`.
|
|
108
|
-
permissions owns the whole evaluation
|
|
112
|
+
permissions owns the whole evaluation: `string` delegation with **cycle detection**, `rel` walks
|
|
109
113
|
through the schema map, cross-map bridge walks, abac `{ rule }` reading the actor as `__actor`,
|
|
110
114
|
boolean terminals, `any`/`all`, and per-row `permissionRules` overrides. Acting as yourself is a
|
|
111
115
|
walk to your own entry (`{ rel: 'user', action }` on a row hydrated with its `user`); a row without
|
|
@@ -130,8 +134,8 @@ checkTransition(rules, 'db:Inquiry', 'cancel', record, changes, {
|
|
|
130
134
|
|
|
131
135
|
`options`: `schema` (permissions' `{ bridges?, permissions }`), `map` (permissions' `SchemaMap`: which
|
|
132
136
|
model each resource is, its relations and foreign keys), optional `isSuperadmin`, and `data`
|
|
133
|
-
(supplemental hydrated rows for bridge walks). The actor is permissions' `{ model, record }`. A cyclic permission graph
|
|
134
|
-
|
|
137
|
+
(supplemental hydrated rows for bridge walks). The actor is permissions' `{ model, record }`. A cyclic permission graph
|
|
138
|
+
(permissions throws on one) is caught and denied (fail closed), so the guard terminates
|
|
135
139
|
cleanly.
|
|
136
140
|
|
|
137
141
|
## Affordance + set query
|
|
@@ -153,8 +157,8 @@ const where = await executePrismaPlan(plan, prisma);
|
|
|
153
157
|
`executePrismaPlan(plan, prisma)`, which resolves the plan's field and step references, and use
|
|
154
158
|
the `where` it returns.
|
|
155
159
|
|
|
156
|
-
A predicate evaluates with the same options json-rules' `check()` takes
|
|
157
|
-
`weekStart`, `bindings`
|
|
160
|
+
A predicate evaluates with the same options json-rules' `check()` takes (`now`, `timeZone`,
|
|
161
|
+
`weekStart`, `bindings`), passed beside `actor` / `authorize`. `checkTransition`,
|
|
158
162
|
`checkPath` and `available` give them to both sides; `eligible` resolves the bindings into the
|
|
159
163
|
predicate (and into a `{ bind }` `timeZone`) and compiles with `now`, so the set query selects
|
|
160
164
|
exactly the records the single check accepts:
|
|
@@ -168,7 +172,7 @@ eligible(rules, 'incident', 'autoResolve', options);
|
|
|
168
172
|
// → plan whose where is { AND: [{ status: … }, { lastBreachedAt: { lt: <now - window> } }] }
|
|
169
173
|
```
|
|
170
174
|
|
|
171
|
-
A guard can read its window off the record instead
|
|
175
|
+
A guard can read its window off the record instead, with nothing to bind:
|
|
172
176
|
|
|
173
177
|
```ts
|
|
174
178
|
{ field: 'lastBreachedAt', dateOperator: 'before',
|
|
@@ -176,7 +180,7 @@ A guard can read its window off the record instead — self-contained, nothing t
|
|
|
176
180
|
```
|
|
177
181
|
|
|
178
182
|
`check()` evaluates it per record; `eligible` throws on it, since a Prisma `where` can't do
|
|
179
|
-
arithmetic on a column
|
|
183
|
+
arithmetic on a column. It never returns the wrong set.
|
|
180
184
|
|
|
181
185
|
A guard that compares a column with a column (`{ field: 'approvals', operator: 'lessThan', path:
|
|
182
186
|
'required' }`) or counts a relation needs the schema to compile: pass toPrisma's `map` /
|
|
@@ -196,24 +200,24 @@ Without the schema, a column comparison throws.
|
|
|
196
200
|
`to.merge` produces the resulting record. Keyword strategies are serializable; a callback is full-power
|
|
197
201
|
but not (`isSerializable(transition)` tells you which).
|
|
198
202
|
|
|
199
|
-
- `spread` (default)
|
|
200
|
-
- `deepMerge
|
|
201
|
-
- `{ kind: 'append', path }
|
|
202
|
-
- `{ kind: 'appendUnique', path }
|
|
203
|
+
- `spread` (default): shallow overwrite
|
|
204
|
+
- `deepMerge`: recursive, arrays replaced
|
|
205
|
+
- `{ kind: 'append', path }`: concat at a field path
|
|
206
|
+
- `{ kind: 'appendUnique', path }`: concat + dedupe
|
|
203
207
|
|
|
204
208
|
## Authoring validation
|
|
205
209
|
|
|
206
210
|
`validateTransition(t, { lens?, requireSerializable? })` validates predicates (via json-rules
|
|
207
211
|
`validateRule`, plus `validateRuleInLens` when a `lens` scopes referenceable fields), merge
|
|
208
|
-
strategy, and permission shape (via `@inixiative/permissions`' `validateActionRule`: every `{ rule }` positive)
|
|
209
|
-
save before persisting a tenant config. It returns json-rules' `ValidationResult
|
|
210
|
-
`{ ok, errors: { path, message, code }[] }
|
|
212
|
+
strategy, and permission shape (via `@inixiative/permissions`' `validateActionRule`: every `{ rule }` positive). Run it on
|
|
213
|
+
save before persisting a tenant config. It returns json-rules' `ValidationResult`,
|
|
214
|
+
`{ ok, errors: { path, message, code }[] }`, and never throws, even on malformed input. json-rules'
|
|
211
215
|
issues keep their codes; transitions adds `missing_side`, `missing_predicate`, `invalid_permission`,
|
|
212
216
|
`invalid_requires`, `invalid_merge` and `unserializable_merge`.
|
|
213
217
|
|
|
214
|
-
## Not built yet (designed
|
|
218
|
+
## Not built yet (designed in the plan)
|
|
215
219
|
|
|
216
|
-
- **`requires` relation loader
|
|
220
|
+
- **`requires` relation loader:** derive a Prisma `include` from a side's `requires`, auto-load, fail
|
|
217
221
|
loud on unloaded reads, respect tenancy. The kernel ignores `requires` (it's metadata).
|
|
218
222
|
- **Permission-filtered `available()`** beyond the from-side static check.
|
|
219
223
|
- **Lens-aware structural composition** check (does A's `to` lens line up with B's `from`).
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var permissions=require('@inixiative/permissions'),jsonRules=require('@inixiative/json-rules'),lodashEs=require('lodash-es');var M=/Cycle detected/,$=(e,t)=>({check:()=>false,isSuperadmin:()=>t?.(e)??false,getActor:()=>e??null}),
|
|
1
|
+
'use strict';var permissions=require('@inixiative/permissions'),jsonRules=require('@inixiative/json-rules'),lodashEs=require('lodash-es');var M=/Cycle detected/,$=(e,t)=>({check:()=>false,isSuperadmin:()=>t?.(e)??false,getActor:()=>e??null}),B=e=>{let t=permissions.createRebacCheck(e.map);return i=>(o,r,n)=>{let a=$(n,e.isSuperadmin),p={resource:i,record:r,data:e.data?.(r,n)};try{return t(a,e.schema,p,o)}catch(s){if(s instanceof Error&&M.test(s.message))return false;throw s}}};var g=e=>Array.isArray(e)?e:e===void 0?[]:[e],V=(e,t)=>Array.isArray(t)?t:void 0,f=e=>typeof e!="function",h=(e,t,i={})=>{if(typeof e=="function")return e(t,i);let o=e??"spread";if(o==="spread")return {...t,...i};if(o==="deepMerge")return lodashEs.mergeWith(lodashEs.cloneDeep(t),lodashEs.cloneDeep(i),V);let{kind:r,path:n}=o,a=lodashEs.cloneDeep({...t,...i}),p=[...g(lodashEs.get(t,n)),...g(lodashEs.get(i,n))];return lodashEs.set(a,n,r==="appendUnique"?lodashEs.uniqWith(p,lodashEs.isEqual):p),a};var b=e=>typeof e=="string"?e:"predicate not satisfied",w=(e,t,i,o)=>!e||t===void 0?false:!e(t,i,o),A=(e,t,i={},o={})=>{let{actor:r,authorize:n,...a}=o,p=h(e.to.merge,t,i),s={},c=jsonRules.check(e.from.predicate,t,a);c!==true&&(s.predicate=b(c)),w(n,e.from.permission,t,r)&&(s.permission="not authorized");let u={},l=jsonRules.check(e.to.predicate,p,a);l!==true&&(u.predicate=b(l)),w(n,e.to.permission,p,r)&&(u.permission="not authorized");let d={};return (s.predicate||s.permission)&&(d.from=s),(u.predicate||u.permission)&&(d.to=u),d.from||d.to?d:true};var k=e=>{let t=[];return e.from?.predicate&&t.push(`from: ${e.from.predicate}`),e.from?.permission&&t.push(`from: ${e.from.permission}`),e.to?.predicate&&t.push(`to: ${e.to.predicate}`),e.to?.permission&&t.push(`to: ${e.to.permission}`),t.join("; ")||"unknown"},te=e=>e.paths.length===0?"no transition path available":e.paths.length===1?k(e.paths[0]):e.paths.map((t,i)=>`path ${i}: ${k(t)}`).join(" | ");jsonRules.registerEngineGlobals("transitions",{});var S=(e,t,i)=>{let o=e[t]?.[i];if(!o)throw new Error(`transition: no action "${i}" registered on resource "${t}"`);return o},se=(e,t,i,o,r={},n={})=>{let a=S(e,t,i),p=[];for(let s of a.paths){let c=A(s,o,r,n);if(c===true)return true;p.push(c);}return {paths:p}},ae=(e,t,i,o={})=>{let r=e[t];if(!r)return [];let{actor:n,authorize:a,...p}=o,s=(c,u)=>!a||c===void 0||a(c,u,n);return Object.entries(r).filter(([,c])=>c.paths.some(u=>jsonRules.check(u.from.predicate,i,p)===true&&s(u.from.permission,i))).map(([c])=>c)},L=(e,t)=>{if(e===void 0||typeof e=="string")return e;let i={field:"timeZone",operator:jsonRules.Operator.equals,...e},{field:o,operator:r,...n}=jsonRules.bindRule(i,t);return n},pe=(e,t,i,o={})=>{let r=S(e,t,i),{bindings:n={},timeZone:a,...p}=o,s=jsonRules.bindRule({any:r.paths.map(c=>c.from.predicate)},n);return jsonRules.toPrisma(s,{...p,timeZone:L(a,n)})};var de=e=>f(e.to.merge);var D=new Set(["spread","deepMerge"]),W=new Set(["append","appendUnique"]),Y=(e,t,i,o)=>{if(e===void 0){t.push({path:i,message:"predicate is required",code:"missing_predicate"});return}let r=[...jsonRules.validateRule(e).errors,...o?jsonRules.validateRuleInLens(e,o).errors:[]];for(let n of r)t.push({...n,path:`${i}.${n.path}`});},G=(e,t,i)=>{if(e!==void 0)for(let o of permissions.validateActionRule(e).errors)t.push({...o,path:`${i}${o.path.slice(1)}`,code:"invalid_permission"});},K=(e,t,i)=>{if(!(e===void 0||typeof e=="function")){if(typeof e=="string"){D.has(e)||t.push({path:i,message:`unknown merge strategy "${e}"`,code:"invalid_merge"});return}W.has(e.kind)?e.path||t.push({path:i,message:`merge "${e.kind}" requires a \`path\``,code:"invalid_merge"}):t.push({path:i,message:`unknown merge kind "${e.kind}"`,code:"invalid_merge"});}},T=(e,t,i,o)=>{if(e===null||typeof e!="object"){t.push({path:i,message:`\`${i}\` side is required`,code:"missing_side"});return}Y(e.predicate,t,`${i}.predicate`,o.lens),G(e.permission,t,`${i}.permission`),e.requires!==void 0&&(typeof e.requires!="object"||e.requires===null)&&t.push({path:`${i}.requires`,message:"`requires` must be a Prisma-include-shaped object",code:"invalid_requires"}),"merge"in e&&K(e.merge,t,`${i}.merge`);},ge=(e,t={})=>{let i=[];return T(e?.from,i,"from",t),T(e?.to,i,"to",t),t.requireSerializable&&!f(e?.to?.merge)&&i.push({path:"to.merge",message:"callback merge is not serializable; use a keyword strategy",code:"unserializable_merge"}),{ok:i.length===0,errors:i}};exports.applyMerge=h;exports.available=ae;exports.checkPath=A;exports.checkTransition=se;exports.createAuthorize=B;exports.describe=te;exports.eligible=pe;exports.isSerializable=de;exports.isSerializableMerge=f;exports.validateTransition=ge;//# sourceMappingURL=index.cjs.map
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/authorize.ts","../src/merge.ts","../src/check.ts","../src/describe.ts","../src/registry.ts","../src/serializable.ts","../src/validate.ts"],"names":["CYCLE","actorPermix","actor","isSuperadmin","createAuthorize","options","check","createRebacCheck","resource","rule","record","permix","subject","error","toArray","value","replaceArrays","_target","source","isSerializableMerge","merge","applyMerge","changes","strategy","mergeWith","cloneDeep","kind","path","base","merged","get","set","uniqWith","isEqual","predicateReason","result","denies","authorize","checkPath","transition","evaluation","next","from","fromPredicate","checkRule","to","toPredicate","reason","describePath","segs","describe","getAction","rules","action","found","checkTransition","paths","available","actions","allows","rec","bindTimeZone","timeZone","bindings","carrier","Operator","_field","_operator","bindRule","eligible","compile","predicate","toPrisma","isSerializable","MERGE_KEYWORDS","ARRAY_KINDS","validatePredicate","errors","lens","issues","validateRule","validateRuleInLens","issue","validatePermission","validateActionRule","validateMerge","validateSide","side","validateTransition"],"mappings":"0IAUA,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A,CAAa/C,CAAAA,EAAY,EAAA,CAAIsC,CAAAA,CAAQ,IAAA,CAAMxE,CAAO,CAAA,CAC9CA,CAAAA,CAAQ,mBAAA,EAAuB,CAACc,CAAAA,CAAoBoB,CAAAA,EAAY,EAAA,EAAI,KAAK,CAAA,EAC3EsC,EAAO,IAAA,CAAK,CACV,IAAA,CAAM,UAAA,CACN,OAAA,CAAS,4DAAA,CACT,IAAA,CAAM,sBACR,CAAC,CAAA,CACI,CAAE,EAAA,CAAIA,CAAAA,CAAO,MAAA,GAAW,CAAA,CAAG,MAAA,CAAAA,CAAO,CAC3C","file":"index.cjs","sourcesContent":["import {\n type ActionRule,\n createRebacCheck,\n type PermixLike,\n type RebacSchema,\n type SchemaMap,\n type Subject,\n} from '@inixiative/permissions';\nimport type { Actor, Authorize, Row } from './types';\n\nconst CYCLE = /Cycle detected/;\n\nexport type PermissionsAuthorizeOptions<R extends string = string> = {\n /** The permissions rebac schema: `{ bridges?, permissions }`. */\n schema: RebacSchema<R>;\n /** Which model each resource is, and its relations: where a `{ rel }` walk leads. */\n map: SchemaMap<R>;\n /** Superadmin bypass, derived from the actor; checked before any rule. */\n isSuperadmin?: (actor: Actor) => boolean;\n /**\n * Supplemental hydrated rows (`map:model → rows`) for bridge (cross-map) `rel` walks, derived from\n * the record + actor — the same shape `Subject.data` takes. Only consulted when a walk crosses a\n * bridge and a downstream action reads the far record's fields.\n */\n data?: (record: Row, actor: Actor) => Subject<R>['data'];\n};\n\nconst actorPermix = (actor: Actor, isSuperadmin?: (actor: Actor) => boolean): PermixLike => ({\n check: () => false,\n isSuperadmin: () => isSuperadmin?.(actor) ?? false,\n getActor: () => actor ?? null,\n});\n\n/**\n * Bridge `@inixiative/permissions`' rebac `check` onto transitions' {@link Authorize} seam — the\n * production evaluator, injected, not reimplemented. `createAuthorize(options)(resource)` returns an\n * `Authorize` bound to a (map-qualified) `resource`; each call evaluates a per-side `permission`\n * rule against a concrete record + actor. permissions owns the evaluation (string delegation with\n * cycle detection, `rel` walks through the schema map, cross-map bridge walks, abac `{ rule }`\n * reading the actor as `__actor`, boolean terminals, `any`/`all`, per-row `permissionRules`\n * overrides).\n */\nexport const createAuthorize = <R extends string = string>(\n options: PermissionsAuthorizeOptions<R>,\n): ((resource: R) => Authorize) => {\n const check = createRebacCheck<R>(options.map);\n\n return (resource: R): Authorize =>\n (rule, record, actor) => {\n const permix = actorPermix(actor, options.isSuperadmin);\n const subject: Subject<R> = { resource, record, data: options.data?.(record, actor) };\n try {\n return check(permix, options.schema, subject, rule as ActionRule);\n } catch (error) {\n if (error instanceof Error && CYCLE.test(error.message)) return false;\n throw error;\n }\n };\n};\n","import { cloneDeep, get, isEqual, mergeWith, set, uniqWith } from 'lodash-es';\nimport type { Merge, MergeStrategy, Row } from './types';\n\nconst toArray = (value: unknown): unknown[] =>\n Array.isArray(value) ? value : value === undefined ? [] : [value];\n\n// deepMerge replaces arrays wholesale rather than index-merging them (the intuitive default).\nconst replaceArrays = (_target: unknown, source: unknown): unknown[] | undefined =>\n Array.isArray(source) ? source : undefined;\n\n/** A transition is persistable iff its merge is absent or a keyword strategy (callbacks are not). */\nexport const isSerializableMerge = (merge?: Merge): boolean => typeof merge !== 'function';\n\n/**\n * Produce the resulting record from a current record + proposed changes.\n *\n * - `spread` (default) — shallow overwrite (`{ ...record, ...changes }`)\n * - `deepMerge` — recursive object merge, arrays replaced\n * - `{ kind: 'append', path }` — concat `changes[path]` onto `record[path]`\n * - `{ kind: 'appendUnique', path }` — append + dedupe (deep equality)\n * - a callback — full power, not serializable\n */\nexport const applyMerge = <R extends Row>(\n merge: Merge<R> | undefined,\n record: R,\n changes: Partial<R> = {},\n): R => {\n if (typeof merge === 'function') return merge(record, changes);\n\n const strategy: MergeStrategy = merge ?? 'spread';\n\n if (strategy === 'spread') return { ...record, ...changes };\n // clone BOTH inputs: mergeWith assigns nested objects/arrays from `changes` by reference, which\n // would alias the caller's `changes` into the returned record (a mutation footgun for a pure guard).\n if (strategy === 'deepMerge')\n return mergeWith(cloneDeep(record), cloneDeep(changes), replaceArrays);\n\n // field-scoped array strategies: spread the rest of `changes`, then concat at `path`.\n const { kind, path } = strategy;\n const base = cloneDeep({ ...record, ...changes }) as R;\n const merged = [...toArray(get(record, path)), ...toArray(get(changes, path))];\n set(base as Row, path, kind === 'appendUnique' ? uniqWith(merged, isEqual) : merged);\n return base;\n};\n","import { check as checkRule } from '@inixiative/json-rules';\nimport { applyMerge } from './merge';\nimport type {\n ActionRule,\n Actor,\n Authorize,\n PathReason,\n Row,\n SideReason,\n Transition,\n TransitionOptions,\n} from './types';\n\nconst predicateReason = (result: boolean | string): string =>\n typeof result === 'string' ? result : 'predicate not satisfied';\n\n/**\n * Does this permission DENY?\n * - no authorizer injected → can't deny (legality-only mode)\n * - `undefined` rule → permission absent → open → can't deny\n * - any other rule (incl. `null` = terminal deny) → delegate to the authorizer\n */\nconst denies = (\n authorize: Authorize | undefined,\n rule: ActionRule | undefined,\n record: Row,\n actor: Actor,\n): boolean => {\n if (!authorize || rule === undefined) return false;\n return !authorize(rule, record, actor);\n};\n\n/**\n * The kernel: evaluate one atomic edge. Reports every failure rather than short-circuiting —\n * `from`/`to` and predicate/permission are independent slots — so a caller sees the whole\n * picture. `from.*` reads the current `record`, `to.*` reads the merged `next` record. Returns\n * `true` when the edge is allowed, else the {@link PathReason}. Omit `authorize` for legality only;\n * json-rules' `check()` options (`now`, `bindings`, …) reach both predicates.\n */\nexport const checkPath = <R extends Row>(\n transition: Transition<R>,\n record: R,\n changes: Partial<R> = {},\n options: TransitionOptions = {},\n): true | PathReason => {\n const { actor, authorize, ...evaluation } = options;\n const next = applyMerge(transition.to.merge, record, changes);\n\n const from: SideReason = {};\n const fromPredicate = checkRule(transition.from.predicate, record as Row, evaluation);\n if (fromPredicate !== true) from.predicate = predicateReason(fromPredicate);\n if (denies(authorize, transition.from.permission, record as Row, actor))\n from.permission = 'not authorized';\n\n const to: SideReason = {};\n const toPredicate = checkRule(transition.to.predicate, next as Row, evaluation);\n if (toPredicate !== true) to.predicate = predicateReason(toPredicate);\n if (denies(authorize, transition.to.permission, next as Row, actor))\n to.permission = 'not authorized';\n\n const reason: PathReason = {};\n if (from.predicate || from.permission) reason.from = from;\n if (to.predicate || to.permission) reason.to = to;\n return reason.from || reason.to ? reason : true;\n};\n","import type { PathReason, Reason } from './types';\n\nconst describePath = (path: PathReason): string => {\n const segs: string[] = [];\n if (path.from?.predicate) segs.push(`from: ${path.from.predicate}`);\n if (path.from?.permission) segs.push(`from: ${path.from.permission}`);\n if (path.to?.predicate) segs.push(`to: ${path.to.predicate}`);\n if (path.to?.permission) segs.push(`to: ${path.to.permission}`);\n return segs.join('; ') || 'unknown';\n};\n\n/** Build a human-readable message from a structured {@link Reason} (logs / UI / error bodies). */\nexport const describe = (reason: Reason): string => {\n if (reason.paths.length === 0) return 'no transition path available';\n if (reason.paths.length === 1) return describePath(reason.paths[0]);\n return reason.paths.map((path, i) => `path ${i}: ${describePath(path)}`).join(' | ');\n};\n","import {\n bindRule,\n type Condition,\n check as checkRule,\n Operator,\n type RuleValue,\n type TimeZoneConfig,\n type ToPrismaResult,\n toPrisma,\n} from '@inixiative/json-rules';\nimport { checkPath } from './check';\nimport type {\n Action,\n ActionRule,\n CheckResult,\n EligibleOptions,\n PathReason,\n Row,\n TransitionMap,\n TransitionOptions,\n} from './types';\n\nconst getAction = (rules: TransitionMap, resource: string, action: string): Action => {\n const found = rules[resource]?.[action];\n if (!found)\n throw new Error(`transition: no action \"${action}\" registered on resource \"${resource}\"`);\n return found;\n};\n\n/**\n * Authoritative check: the FIRST path whose `from` matches the current record, whose `to` matches\n * the merged record, and whose permissions all pass, wins → `true`. If none pass, returns a\n * {@link Reason} with one {@link PathReason} per candidate path tried.\n *\n * `resource` is the (map-qualified) key into the map — e.g. `db:Inquiry`. Cross-source `permission`\n * checks are handled by the injected {@link Authorize} (wire it to a bridge-aware rebac check, bound\n * to this resource); a `predicate` that reads a bridged relation expects a stitched record.\n */\nexport const checkTransition = (\n rules: TransitionMap,\n resource: string,\n action: string,\n record: Row,\n changes: Row = {},\n options: TransitionOptions = {},\n): CheckResult => {\n const found = getAction(rules, resource, action);\n const paths: PathReason[] = [];\n for (const path of found.paths) {\n const result = checkPath(path, record, changes, options);\n if (result === true) return true;\n paths.push(result);\n }\n return { paths };\n};\n\n/**\n * Affordance hint: which actions are offerable from `record` right now. Evaluates ONLY the `from`\n * side (predicate + `from` permission against the current record) — `to` needs the merged record,\n * which doesn't exist without proposed changes, so it defers to {@link checkTransition}.\n */\nexport const available = (\n rules: TransitionMap,\n resource: string,\n record: Row,\n options: TransitionOptions = {},\n): string[] => {\n const actions = rules[resource];\n if (!actions) return [];\n const { actor, authorize, ...evaluation } = options;\n\n const allows = (rule: ActionRule | undefined, rec: Row): boolean =>\n !authorize || rule === undefined || authorize(rule, rec, actor);\n\n return Object.entries(actions)\n .filter(([, action]) =>\n action.paths.some(\n (path) =>\n checkRule(path.from.predicate, record, evaluation) === true &&\n allows(path.from.permission, record),\n ),\n )\n .map(([action]) => action);\n};\n\n// A `{ bind }` zone, resolved the way the rule's own tokens are: json-rules' bindRule over a\n// carrier leaf. An uncovered token stays a token, and toPrisma reports it unresolved.\nconst bindTimeZone = (\n timeZone: TimeZoneConfig | undefined,\n bindings: Record<string, RuleValue>,\n): TimeZoneConfig | undefined => {\n if (timeZone === undefined || typeof timeZone === 'string') return timeZone;\n const carrier = { field: 'timeZone', operator: Operator.equals, ...timeZone } as Condition;\n const { field: _field, operator: _operator, ...source } = bindRule(carrier, bindings) as Row;\n return source as TimeZoneConfig;\n};\n\n/**\n * Set query as a json-rules Prisma plan: every record currently eligible for `action` (the union\n * of all its paths' `from` predicates; a single path compiles to its predicate alone; an empty\n * action matches nothing). Takes the json-rules `check()` options plus toPrisma's schema:\n * `bindings` are resolved into the predicate and a `{ bind }` timeZone before compiling, `now`\n * reaches `toPrisma`, and `map` / `mapName` / `model` (or `lens`) let it compile a column\n * compared with a column or a count. Run it with json-rules' `executePrismaPlan(plan, prisma)`,\n * which resolves the plan's references, and the `where` selects the rows the single check\n * accepts. A guard toPrisma cannot express (a `$.` row ref in an offset or magnitude, a column\n * ref without the schema) throws.\n */\nexport const eligible = (\n rules: TransitionMap,\n resource: string,\n action: string,\n options: EligibleOptions = {},\n): ToPrismaResult => {\n const found = getAction(rules, resource, action);\n const { bindings = {}, timeZone, ...compile } = options;\n const predicate = bindRule({ any: found.paths.map((path) => path.from.predicate) }, bindings);\n return toPrisma(predicate, { ...compile, timeZone: bindTimeZone(timeZone, bindings) });\n};\n","import { isSerializableMerge } from './merge';\nimport type { Transition } from './types';\n\n/**\n * Can this transition be persisted (stored in the DB, edited in a UI, sent over the wire)?\n *\n * Predicates (json-rules) and permissions (ActionRule) are always plain JSON; the only\n * non-data escape hatch is a `to.merge` callback. So serializability reduces to the merge.\n */\nexport const isSerializable = (transition: Transition): boolean =>\n isSerializableMerge(transition.to.merge);\n","import {\n type Condition,\n type Lens,\n type LensNarrowing,\n type ValidationIssue,\n type ValidationResult,\n validateRule,\n validateRuleInLens,\n} from '@inixiative/json-rules';\nimport { validateActionRule } from '@inixiative/permissions';\nimport { isSerializableMerge } from './merge';\nimport type { ActionRule, Merge, Side, ToSide, Transition } from './types';\n\nexport type { ValidationIssue, ValidationResult };\n\nexport type ValidateOptions = {\n /** Optional field/relation allowlist; passed through to json-rules lens validation per predicate. */\n lens?: Lens | LensNarrowing;\n /** Reject callback merges (use when the transition must be persistable / tenant-configured). */\n requireSerializable?: boolean;\n};\n\nconst MERGE_KEYWORDS = new Set(['spread', 'deepMerge']);\nconst ARRAY_KINDS = new Set(['append', 'appendUnique']);\n\nconst validatePredicate = (\n predicate: Condition | undefined,\n errors: ValidationIssue[],\n path: string,\n lens?: Lens | LensNarrowing,\n): void => {\n if (predicate === undefined) {\n errors.push({ path, message: 'predicate is required', code: 'missing_predicate' });\n return;\n }\n const issues = [\n ...validateRule(predicate).errors,\n ...(lens ? validateRuleInLens(predicate, lens).errors : []),\n ];\n for (const issue of issues) errors.push({ ...issue, path: `${path}.${issue.path}` });\n};\n\nconst validatePermission = (\n rule: ActionRule | undefined,\n errors: ValidationIssue[],\n path: string,\n): void => {\n if (rule === undefined) return;\n for (const issue of validateActionRule(rule).errors)\n errors.push({ ...issue, path: `${path}${issue.path.slice(1)}`, code: 'invalid_permission' });\n};\n\nconst validateMerge = (merge: Merge | undefined, errors: ValidationIssue[], path: string): void => {\n if (merge === undefined || typeof merge === 'function') return;\n if (typeof merge === 'string') {\n if (!MERGE_KEYWORDS.has(merge))\n errors.push({ path, message: `unknown merge strategy \"${merge}\"`, code: 'invalid_merge' });\n return;\n }\n if (!ARRAY_KINDS.has(merge.kind))\n errors.push({ path, message: `unknown merge kind \"${merge.kind}\"`, code: 'invalid_merge' });\n else if (!merge.path)\n errors.push({\n path,\n message: `merge \"${merge.kind}\" requires a \\`path\\``,\n code: 'invalid_merge',\n });\n};\n\nconst validateSide = (\n side: Side | ToSide | undefined,\n errors: ValidationIssue[],\n path: string,\n options: ValidateOptions,\n): void => {\n if (side === null || typeof side !== 'object') {\n errors.push({ path, message: `\\`${path}\\` side is required`, code: 'missing_side' });\n return;\n }\n validatePredicate(side.predicate, errors, `${path}.predicate`, options.lens);\n validatePermission(side.permission, errors, `${path}.permission`);\n if (side.requires !== undefined && (typeof side.requires !== 'object' || side.requires === null))\n errors.push({\n path: `${path}.requires`,\n message: '`requires` must be a Prisma-include-shaped object',\n code: 'invalid_requires',\n });\n if ('merge' in side) validateMerge(side.merge, errors, `${path}.merge`);\n};\n\n/**\n * Authoring validation for a single transition — run on save before persisting a tenant config.\n * Returns structured issues (never throws) on malformed input: predicate validity delegates to\n * json-rules (`validateRule`, plus `validateRuleInLens` when a `lens` is supplied for\n * field/relation scoping); permission shape delegates to `@inixiative/permissions`' `validateActionRule`;\n * merge strategy is checked here.\n */\nexport const validateTransition = (\n transition: Transition,\n options: ValidateOptions = {},\n): ValidationResult => {\n const errors: ValidationIssue[] = [];\n validateSide(transition?.from, errors, 'from', options);\n validateSide(transition?.to, errors, 'to', options);\n if (options.requireSerializable && !isSerializableMerge(transition?.to?.merge))\n errors.push({\n path: 'to.merge',\n message: 'callback merge is not serializable; use a keyword strategy',\n code: 'unserializable_merge',\n });\n return { ok: errors.length === 0, errors };\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/authorize.ts","../src/merge.ts","../src/check.ts","../src/describe.ts","../src/engineGlobals.ts","../src/registry.ts","../src/serializable.ts","../src/validate.ts"],"names":["CYCLE","actorPermix","actor","isSuperadmin","createAuthorize","options","check","createRebacCheck","resource","rule","record","permix","subject","error","toArray","value","replaceArrays","_target","source","isSerializableMerge","merge","applyMerge","changes","strategy","mergeWith","cloneDeep","kind","path","base","merged","get","set","uniqWith","isEqual","predicateReason","result","denies","authorize","checkPath","transition","evaluation","next","from","fromPredicate","checkRule","to","toPredicate","reason","describePath","segs","describe","registerEngineGlobals","getAction","rules","action","found","checkTransition","paths","available","actions","allows","rec","bindTimeZone","timeZone","bindings","carrier","Operator","_field","_operator","bindRule","eligible","compile","predicate","toPrisma","isSerializable","MERGE_KEYWORDS","ARRAY_KINDS","validatePredicate","errors","lens","issues","validateRule","validateRuleInLens","issue","validatePermission","validateActionRule","validateMerge","validateSide","side","validateTransition"],"mappings":"0IAUA,IAAMA,CAAAA,CAAQ,gBAAA,CAiBRC,CAAAA,CAAc,CAACC,CAAAA,CAAcC,CAAAA,IAA0D,CAC3F,KAAA,CAAO,IAAM,KAAA,CACb,YAAA,CAAc,IAAMA,CAAAA,GAAeD,CAAK,CAAA,EAAK,KAAA,CAC7C,QAAA,CAAU,IAAMA,CAAAA,EAAS,IAC3B,CAAA,CAAA,CAWaE,CAAAA,CACXC,CAAAA,EACiC,CACjC,IAAMC,CAAAA,CAAQC,4BAAAA,CAAoBF,CAAAA,CAAQ,GAAG,CAAA,CAE7C,OAAQG,CAAAA,EACN,CAACC,CAAAA,CAAMC,CAAAA,CAAQR,CAAAA,GAAU,CACvB,IAAMS,CAAAA,CAASV,CA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A,CAAA,CAActB,CAAAA,CAAQ,IAAI,CAAA,CAC3E+E,CAAAA,CAAmBI,CAAAA,CAAK,UAAA,CAAYV,CAAAA,CAAQ,CAAA,EAAGnD,CAAI,CAAA,WAAA,CAAa,CAAA,CAC5D6D,EAAK,QAAA,GAAa,MAAA,GAAc,OAAOA,CAAAA,CAAK,QAAA,EAAa,QAAA,EAAYA,CAAAA,CAAK,QAAA,GAAa,IAAA,CAAA,EACzFV,CAAAA,CAAO,IAAA,CAAK,CACV,IAAA,CAAM,CAAA,EAAGnD,CAAI,CAAA,SAAA,CAAA,CACb,QAAS,mDAAA,CACT,IAAA,CAAM,kBACR,CAAC,CAAA,CACC,OAAA,GAAW6D,CAAAA,EAAMF,CAAAA,CAAcE,CAAAA,CAAK,KAAA,CAAOV,CAAAA,CAAQ,CAAA,EAAGnD,CAAI,CAAA,MAAA,CAAQ,EACxE,CAAA,CASa8D,GAAqB,CAChClD,CAAAA,CACAlC,CAAAA,CAA2B,EAAC,GACP,CACrB,IAAMyE,CAAAA,CAA4B,EAAC,CACnC,OAAAS,CAAAA,CAAahD,CAAAA,EAAY,IAAA,CAAMuC,CAAAA,CAAQ,MAAA,CAAQzE,CAAO,CAAA,CACtDkF,CAAAA,CAAahD,CAAAA,EAAY,EAAA,CAAIuC,CAAAA,CAAQ,IAAA,CAAMzE,CAAO,CAAA,CAC9CA,CAAAA,CAAQ,mBAAA,EAAuB,CAACc,CAAAA,CAAoBoB,CAAAA,EAAY,EAAA,EAAI,KAAK,CAAA,EAC3EuC,EAAO,IAAA,CAAK,CACV,IAAA,CAAM,UAAA,CACN,OAAA,CAAS,4DAAA,CACT,IAAA,CAAM,sBACR,CAAC,CAAA,CACI,CAAE,EAAA,CAAIA,CAAAA,CAAO,MAAA,GAAW,CAAA,CAAG,MAAA,CAAAA,CAAO,CAC3C","file":"index.cjs","sourcesContent":["import {\n type ActionRule,\n createRebacCheck,\n type PermixLike,\n type RebacSchema,\n type SchemaMap,\n type Subject,\n} from '@inixiative/permissions';\nimport type { Actor, Authorize, Row } from './types';\n\nconst CYCLE = /Cycle detected/;\n\nexport type PermissionsAuthorizeOptions<R extends string = string> = {\n /** The permissions rebac schema: `{ bridges?, permissions }`. */\n schema: RebacSchema<R>;\n /** Which model each resource is, and its relations: where a `{ rel }` walk leads. */\n map: SchemaMap<R>;\n /** Superadmin bypass, derived from the actor; checked before any rule. */\n isSuperadmin?: (actor: Actor) => boolean;\n /**\n * Supplemental hydrated rows (`map:model → rows`) for bridge (cross-map) `rel` walks, derived from\n * the record + actor — the same shape `Subject.data` takes. Only consulted when a walk crosses a\n * bridge and a downstream action reads the far record's fields.\n */\n data?: (record: Row, actor: Actor) => Subject<R>['data'];\n};\n\nconst actorPermix = (actor: Actor, isSuperadmin?: (actor: Actor) => boolean): PermixLike => ({\n check: () => false,\n isSuperadmin: () => isSuperadmin?.(actor) ?? false,\n getActor: () => actor ?? null,\n});\n\n/**\n * Bridge `@inixiative/permissions`' rebac `check` onto transitions' {@link Authorize} seam — the\n * production evaluator, injected, not reimplemented. `createAuthorize(options)(resource)` returns an\n * `Authorize` bound to a (map-qualified) `resource`; each call evaluates a per-side `permission`\n * rule against a concrete record + actor. permissions owns the evaluation (string delegation with\n * cycle detection, `rel` walks through the schema map, cross-map bridge walks, abac `{ rule }`\n * reading the actor as `__actor`, boolean terminals, `any`/`all`, per-row `permissionRules`\n * overrides).\n */\nexport const createAuthorize = <R extends string = string>(\n options: PermissionsAuthorizeOptions<R>,\n): ((resource: R) => Authorize) => {\n const check = createRebacCheck<R>(options.map);\n\n return (resource: R): Authorize =>\n (rule, record, actor) => {\n const permix = actorPermix(actor, options.isSuperadmin);\n const subject: Subject<R> = { resource, record, data: options.data?.(record, actor) };\n try {\n return check(permix, options.schema, subject, rule as ActionRule);\n } catch (error) {\n if (error instanceof Error && CYCLE.test(error.message)) return false;\n throw error;\n }\n };\n};\n","import { cloneDeep, get, isEqual, mergeWith, set, uniqWith } from 'lodash-es';\nimport type { Merge, MergeStrategy, Row } from './types';\n\nconst toArray = (value: unknown): unknown[] =>\n Array.isArray(value) ? value : value === undefined ? [] : [value];\n\n// deepMerge replaces arrays wholesale rather than index-merging them (the intuitive default).\nconst replaceArrays = (_target: unknown, source: unknown): unknown[] | undefined =>\n Array.isArray(source) ? source : undefined;\n\n/** A transition is persistable iff its merge is absent or a keyword strategy (callbacks are not). */\nexport const isSerializableMerge = (merge?: Merge): boolean => typeof merge !== 'function';\n\n/**\n * Produce the resulting record from a current record + proposed changes.\n *\n * - `spread` (default) — shallow overwrite (`{ ...record, ...changes }`)\n * - `deepMerge` — recursive object merge, arrays replaced\n * - `{ kind: 'append', path }` — concat `changes[path]` onto `record[path]`\n * - `{ kind: 'appendUnique', path }` — append + dedupe (deep equality)\n * - a callback — full power, not serializable\n */\nexport const applyMerge = <R extends Row>(\n merge: Merge<R> | undefined,\n record: R,\n changes: Partial<R> = {},\n): R => {\n if (typeof merge === 'function') return merge(record, changes);\n\n const strategy: MergeStrategy = merge ?? 'spread';\n\n if (strategy === 'spread') return { ...record, ...changes };\n // clone BOTH inputs: mergeWith assigns nested objects/arrays from `changes` by reference, which\n // would alias the caller's `changes` into the returned record (a mutation footgun for a pure guard).\n if (strategy === 'deepMerge')\n return mergeWith(cloneDeep(record), cloneDeep(changes), replaceArrays);\n\n // field-scoped array strategies: spread the rest of `changes`, then concat at `path`.\n const { kind, path } = strategy;\n const base = cloneDeep({ ...record, ...changes }) as R;\n const merged = [...toArray(get(record, path)), ...toArray(get(changes, path))];\n set(base as Row, path, kind === 'appendUnique' ? uniqWith(merged, isEqual) : merged);\n return base;\n};\n","import { check as checkRule } from '@inixiative/json-rules';\nimport { applyMerge } from './merge';\nimport type {\n ActionRule,\n Actor,\n Authorize,\n PathReason,\n Row,\n SideReason,\n Transition,\n TransitionOptions,\n} from './types';\n\nconst predicateReason = (result: boolean | string): string =>\n typeof result === 'string' ? result : 'predicate not satisfied';\n\n/**\n * Does this permission DENY?\n * - no authorizer injected → can't deny (legality-only mode)\n * - `undefined` rule → permission absent → open → can't deny\n * - any other rule (incl. `null` = terminal deny) → delegate to the authorizer\n */\nconst denies = (\n authorize: Authorize | undefined,\n rule: ActionRule | undefined,\n record: Row,\n actor: Actor,\n): boolean => {\n if (!authorize || rule === undefined) return false;\n return !authorize(rule, record, actor);\n};\n\n/**\n * The kernel: evaluate one atomic edge. Reports every failure rather than short-circuiting —\n * `from`/`to` and predicate/permission are independent slots — so a caller sees the whole\n * picture. `from.*` reads the current `record`, `to.*` reads the merged `next` record. Returns\n * `true` when the edge is allowed, else the {@link PathReason}. Omit `authorize` for legality only;\n * json-rules' `check()` options (`now`, `bindings`, …) reach both predicates.\n */\nexport const checkPath = <R extends Row>(\n transition: Transition<R>,\n record: R,\n changes: Partial<R> = {},\n options: TransitionOptions = {},\n): true | PathReason => {\n const { actor, authorize, ...evaluation } = options;\n const next = applyMerge(transition.to.merge, record, changes);\n\n const from: SideReason = {};\n const fromPredicate = checkRule(transition.from.predicate, record as Row, evaluation);\n if (fromPredicate !== true) from.predicate = predicateReason(fromPredicate);\n if (denies(authorize, transition.from.permission, record as Row, actor))\n from.permission = 'not authorized';\n\n const to: SideReason = {};\n const toPredicate = checkRule(transition.to.predicate, next as Row, evaluation);\n if (toPredicate !== true) to.predicate = predicateReason(toPredicate);\n if (denies(authorize, transition.to.permission, next as Row, actor))\n to.permission = 'not authorized';\n\n const reason: PathReason = {};\n if (from.predicate || from.permission) reason.from = from;\n if (to.predicate || to.permission) reason.to = to;\n return reason.from || reason.to ? reason : true;\n};\n","import type { PathReason, Reason } from './types';\n\nconst describePath = (path: PathReason): string => {\n const segs: string[] = [];\n if (path.from?.predicate) segs.push(`from: ${path.from.predicate}`);\n if (path.from?.permission) segs.push(`from: ${path.from.permission}`);\n if (path.to?.predicate) segs.push(`to: ${path.to.predicate}`);\n if (path.to?.permission) segs.push(`to: ${path.to.permission}`);\n return segs.join('; ') || 'unknown';\n};\n\n/** Build a human-readable message from a structured {@link Reason} (logs / UI / error bodies). */\nexport const describe = (reason: Reason): string => {\n if (reason.paths.length === 0) return 'no transition path available';\n if (reason.paths.length === 1) return describePath(reason.paths[0]);\n return reason.paths.map((path, i) => `path ${i}: ${describePath(path)}`).join(' | ');\n};\n","import { registerEngineGlobals } from '@inixiative/json-rules';\n\n// transitions' namespace in the one engine interaction point (json-rules' `engineGlobals`). Every\n// option transitions takes is per call today, so it holds no path yet.\nregisterEngineGlobals('transitions', {});\n","import {\n bindRule,\n type Condition,\n check as checkRule,\n Operator,\n type RuleValue,\n type TimeZoneConfig,\n type ToPrismaResult,\n toPrisma,\n} from '@inixiative/json-rules';\nimport { checkPath } from './check';\nimport type {\n Action,\n ActionRule,\n CheckResult,\n EligibleOptions,\n PathReason,\n Row,\n TransitionMap,\n TransitionOptions,\n} from './types';\n\nconst getAction = (rules: TransitionMap, resource: string, action: string): Action => {\n const found = rules[resource]?.[action];\n if (!found)\n throw new Error(`transition: no action \"${action}\" registered on resource \"${resource}\"`);\n return found;\n};\n\n/**\n * Authoritative check: the FIRST path whose `from` matches the current record, whose `to` matches\n * the merged record, and whose permissions all pass, wins → `true`. If none pass, returns a\n * {@link Reason} with one {@link PathReason} per candidate path tried.\n *\n * `resource` is the (map-qualified) key into the map — e.g. `db:Inquiry`. Cross-source `permission`\n * checks are handled by the injected {@link Authorize} (wire it to a bridge-aware rebac check, bound\n * to this resource); a `predicate` that reads a bridged relation expects a stitched record.\n */\nexport const checkTransition = (\n rules: TransitionMap,\n resource: string,\n action: string,\n record: Row,\n changes: Row = {},\n options: TransitionOptions = {},\n): CheckResult => {\n const found = getAction(rules, resource, action);\n const paths: PathReason[] = [];\n for (const path of found.paths) {\n const result = checkPath(path, record, changes, options);\n if (result === true) return true;\n paths.push(result);\n }\n return { paths };\n};\n\n/**\n * Affordance hint: which actions are offerable from `record` right now. Evaluates ONLY the `from`\n * side (predicate + `from` permission against the current record) — `to` needs the merged record,\n * which doesn't exist without proposed changes, so it defers to {@link checkTransition}.\n */\nexport const available = (\n rules: TransitionMap,\n resource: string,\n record: Row,\n options: TransitionOptions = {},\n): string[] => {\n const actions = rules[resource];\n if (!actions) return [];\n const { actor, authorize, ...evaluation } = options;\n\n const allows = (rule: ActionRule | undefined, rec: Row): boolean =>\n !authorize || rule === undefined || authorize(rule, rec, actor);\n\n return Object.entries(actions)\n .filter(([, action]) =>\n action.paths.some(\n (path) =>\n checkRule(path.from.predicate, record, evaluation) === true &&\n allows(path.from.permission, record),\n ),\n )\n .map(([action]) => action);\n};\n\n// A `{ bind }` zone, resolved the way the rule's own tokens are: json-rules' bindRule over a\n// carrier leaf. An uncovered token stays a token, and toPrisma reports it unresolved.\nconst bindTimeZone = (\n timeZone: TimeZoneConfig | undefined,\n bindings: Record<string, RuleValue>,\n): TimeZoneConfig | undefined => {\n if (timeZone === undefined || typeof timeZone === 'string') return timeZone;\n const carrier = { field: 'timeZone', operator: Operator.equals, ...timeZone } as Condition;\n const { field: _field, operator: _operator, ...source } = bindRule(carrier, bindings) as Row;\n return source as TimeZoneConfig;\n};\n\n/**\n * Set query as a json-rules Prisma plan: every record currently eligible for `action` (the union\n * of all its paths' `from` predicates; a single path compiles to its predicate alone; an empty\n * action matches nothing). Takes the json-rules `check()` options plus toPrisma's schema:\n * `bindings` are resolved into the predicate and a `{ bind }` timeZone before compiling, `now`\n * reaches `toPrisma`, and `map` / `mapName` / `model` (or `lens`) let it compile a column\n * compared with a column or a count. Run it with json-rules' `executePrismaPlan(plan, prisma)`,\n * which resolves the plan's references, and the `where` selects the rows the single check\n * accepts. A guard toPrisma cannot express (a `$.` row ref in an offset or magnitude, a column\n * ref without the schema) throws.\n */\nexport const eligible = (\n rules: TransitionMap,\n resource: string,\n action: string,\n options: EligibleOptions = {},\n): ToPrismaResult => {\n const found = getAction(rules, resource, action);\n const { bindings = {}, timeZone, ...compile } = options;\n const predicate = bindRule({ any: found.paths.map((path) => path.from.predicate) }, bindings);\n return toPrisma(predicate, { ...compile, timeZone: bindTimeZone(timeZone, bindings) });\n};\n","import { isSerializableMerge } from './merge';\nimport type { Transition } from './types';\n\n/**\n * Can this transition be persisted (stored in the DB, edited in a UI, sent over the wire)?\n *\n * Predicates (json-rules) and permissions (ActionRule) are always plain JSON; the only\n * non-data escape hatch is a `to.merge` callback. So serializability reduces to the merge.\n */\nexport const isSerializable = (transition: Transition): boolean =>\n isSerializableMerge(transition.to.merge);\n","import {\n type Condition,\n type Lens,\n type LensNarrowing,\n type ValidationIssue,\n type ValidationResult,\n validateRule,\n validateRuleInLens,\n} from '@inixiative/json-rules';\nimport { validateActionRule } from '@inixiative/permissions';\nimport { isSerializableMerge } from './merge';\nimport type { ActionRule, Merge, Side, ToSide, Transition } from './types';\n\nexport type { ValidationIssue, ValidationResult };\n\nexport type ValidateOptions = {\n /** Optional field/relation allowlist; passed through to json-rules lens validation per predicate. */\n lens?: Lens | LensNarrowing;\n /** Reject callback merges (use when the transition must be persistable / tenant-configured). */\n requireSerializable?: boolean;\n};\n\nconst MERGE_KEYWORDS = new Set(['spread', 'deepMerge']);\nconst ARRAY_KINDS = new Set(['append', 'appendUnique']);\n\nconst validatePredicate = (\n predicate: Condition | undefined,\n errors: ValidationIssue[],\n path: string,\n lens?: Lens | LensNarrowing,\n): void => {\n if (predicate === undefined) {\n errors.push({ path, message: 'predicate is required', code: 'missing_predicate' });\n return;\n }\n const issues = [\n ...validateRule(predicate).errors,\n ...(lens ? validateRuleInLens(predicate, lens).errors : []),\n ];\n for (const issue of issues) errors.push({ ...issue, path: `${path}.${issue.path}` });\n};\n\nconst validatePermission = (\n rule: ActionRule | undefined,\n errors: ValidationIssue[],\n path: string,\n): void => {\n if (rule === undefined) return;\n for (const issue of validateActionRule(rule).errors)\n errors.push({ ...issue, path: `${path}${issue.path.slice(1)}`, code: 'invalid_permission' });\n};\n\nconst validateMerge = (merge: Merge | undefined, errors: ValidationIssue[], path: string): void => {\n if (merge === undefined || typeof merge === 'function') return;\n if (typeof merge === 'string') {\n if (!MERGE_KEYWORDS.has(merge))\n errors.push({ path, message: `unknown merge strategy \"${merge}\"`, code: 'invalid_merge' });\n return;\n }\n if (!ARRAY_KINDS.has(merge.kind))\n errors.push({ path, message: `unknown merge kind \"${merge.kind}\"`, code: 'invalid_merge' });\n else if (!merge.path)\n errors.push({\n path,\n message: `merge \"${merge.kind}\" requires a \\`path\\``,\n code: 'invalid_merge',\n });\n};\n\nconst validateSide = (\n side: Side | ToSide | undefined,\n errors: ValidationIssue[],\n path: string,\n options: ValidateOptions,\n): void => {\n if (side === null || typeof side !== 'object') {\n errors.push({ path, message: `\\`${path}\\` side is required`, code: 'missing_side' });\n return;\n }\n validatePredicate(side.predicate, errors, `${path}.predicate`, options.lens);\n validatePermission(side.permission, errors, `${path}.permission`);\n if (side.requires !== undefined && (typeof side.requires !== 'object' || side.requires === null))\n errors.push({\n path: `${path}.requires`,\n message: '`requires` must be a Prisma-include-shaped object',\n code: 'invalid_requires',\n });\n if ('merge' in side) validateMerge(side.merge, errors, `${path}.merge`);\n};\n\n/**\n * Authoring validation for a single transition — run on save before persisting a tenant config.\n * Returns structured issues (never throws) on malformed input: predicate validity delegates to\n * json-rules (`validateRule`, plus `validateRuleInLens` when a `lens` is supplied for\n * field/relation scoping); permission shape delegates to `@inixiative/permissions`' `validateActionRule`;\n * merge strategy is checked here.\n */\nexport const validateTransition = (\n transition: Transition,\n options: ValidateOptions = {},\n): ValidationResult => {\n const errors: ValidationIssue[] = [];\n validateSide(transition?.from, errors, 'from', options);\n validateSide(transition?.to, errors, 'to', options);\n if (options.requireSerializable && !isSerializableMerge(transition?.to?.merge))\n errors.push({\n path: 'to.merge',\n message: 'callback merge is not serializable; use a keyword strategy',\n code: 'unserializable_merge',\n });\n return { ok: errors.length === 0, errors };\n};\n"]}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {createRebacCheck,validateActionRule}from'@inixiative/permissions';import {check,bindRule,toPrisma,Operator,validateRule,validateRuleInLens}from'@inixiative/json-rules';import {mergeWith,cloneDeep,get,set,uniqWith,isEqual}from'lodash-es';var M=/Cycle detected/,$=(e,t)=>({check:()=>false,isSuperadmin:()=>t?.(e)??false,getActor:()=>e??null}),
|
|
1
|
+
import {createRebacCheck,validateActionRule}from'@inixiative/permissions';import {registerEngineGlobals,check,bindRule,toPrisma,Operator,validateRule,validateRuleInLens}from'@inixiative/json-rules';import {mergeWith,cloneDeep,get,set,uniqWith,isEqual}from'lodash-es';var M=/Cycle detected/,$=(e,t)=>({check:()=>false,isSuperadmin:()=>t?.(e)??false,getActor:()=>e??null}),B=e=>{let t=createRebacCheck(e.map);return i=>(o,r,n)=>{let a=$(n,e.isSuperadmin),p={resource:i,record:r,data:e.data?.(r,n)};try{return t(a,e.schema,p,o)}catch(s){if(s instanceof Error&&M.test(s.message))return false;throw s}}};var g=e=>Array.isArray(e)?e:e===void 0?[]:[e],V=(e,t)=>Array.isArray(t)?t:void 0,f=e=>typeof e!="function",h=(e,t,i={})=>{if(typeof e=="function")return e(t,i);let o=e??"spread";if(o==="spread")return {...t,...i};if(o==="deepMerge")return mergeWith(cloneDeep(t),cloneDeep(i),V);let{kind:r,path:n}=o,a=cloneDeep({...t,...i}),p=[...g(get(t,n)),...g(get(i,n))];return set(a,n,r==="appendUnique"?uniqWith(p,isEqual):p),a};var b=e=>typeof e=="string"?e:"predicate not satisfied",w=(e,t,i,o)=>!e||t===void 0?false:!e(t,i,o),A=(e,t,i={},o={})=>{let{actor:r,authorize:n,...a}=o,p=h(e.to.merge,t,i),s={},c=check(e.from.predicate,t,a);c!==true&&(s.predicate=b(c)),w(n,e.from.permission,t,r)&&(s.permission="not authorized");let u={},l=check(e.to.predicate,p,a);l!==true&&(u.predicate=b(l)),w(n,e.to.permission,p,r)&&(u.permission="not authorized");let d={};return (s.predicate||s.permission)&&(d.from=s),(u.predicate||u.permission)&&(d.to=u),d.from||d.to?d:true};var k=e=>{let t=[];return e.from?.predicate&&t.push(`from: ${e.from.predicate}`),e.from?.permission&&t.push(`from: ${e.from.permission}`),e.to?.predicate&&t.push(`to: ${e.to.predicate}`),e.to?.permission&&t.push(`to: ${e.to.permission}`),t.join("; ")||"unknown"},te=e=>e.paths.length===0?"no transition path available":e.paths.length===1?k(e.paths[0]):e.paths.map((t,i)=>`path ${i}: ${k(t)}`).join(" | ");registerEngineGlobals("transitions",{});var S=(e,t,i)=>{let o=e[t]?.[i];if(!o)throw new Error(`transition: no action "${i}" registered on resource "${t}"`);return o},se=(e,t,i,o,r={},n={})=>{let a=S(e,t,i),p=[];for(let s of a.paths){let c=A(s,o,r,n);if(c===true)return true;p.push(c);}return {paths:p}},ae=(e,t,i,o={})=>{let r=e[t];if(!r)return [];let{actor:n,authorize:a,...p}=o,s=(c,u)=>!a||c===void 0||a(c,u,n);return Object.entries(r).filter(([,c])=>c.paths.some(u=>check(u.from.predicate,i,p)===true&&s(u.from.permission,i))).map(([c])=>c)},L=(e,t)=>{if(e===void 0||typeof e=="string")return e;let i={field:"timeZone",operator:Operator.equals,...e},{field:o,operator:r,...n}=bindRule(i,t);return n},pe=(e,t,i,o={})=>{let r=S(e,t,i),{bindings:n={},timeZone:a,...p}=o,s=bindRule({any:r.paths.map(c=>c.from.predicate)},n);return toPrisma(s,{...p,timeZone:L(a,n)})};var de=e=>f(e.to.merge);var D=new Set(["spread","deepMerge"]),W=new Set(["append","appendUnique"]),Y=(e,t,i,o)=>{if(e===void 0){t.push({path:i,message:"predicate is required",code:"missing_predicate"});return}let r=[...validateRule(e).errors,...o?validateRuleInLens(e,o).errors:[]];for(let n of r)t.push({...n,path:`${i}.${n.path}`});},G=(e,t,i)=>{if(e!==void 0)for(let o of validateActionRule(e).errors)t.push({...o,path:`${i}${o.path.slice(1)}`,code:"invalid_permission"});},K=(e,t,i)=>{if(!(e===void 0||typeof e=="function")){if(typeof e=="string"){D.has(e)||t.push({path:i,message:`unknown merge strategy "${e}"`,code:"invalid_merge"});return}W.has(e.kind)?e.path||t.push({path:i,message:`merge "${e.kind}" requires a \`path\``,code:"invalid_merge"}):t.push({path:i,message:`unknown merge kind "${e.kind}"`,code:"invalid_merge"});}},T=(e,t,i,o)=>{if(e===null||typeof e!="object"){t.push({path:i,message:`\`${i}\` side is required`,code:"missing_side"});return}Y(e.predicate,t,`${i}.predicate`,o.lens),G(e.permission,t,`${i}.permission`),e.requires!==void 0&&(typeof e.requires!="object"||e.requires===null)&&t.push({path:`${i}.requires`,message:"`requires` must be a Prisma-include-shaped object",code:"invalid_requires"}),"merge"in e&&K(e.merge,t,`${i}.merge`);},ge=(e,t={})=>{let i=[];return T(e?.from,i,"from",t),T(e?.to,i,"to",t),t.requireSerializable&&!f(e?.to?.merge)&&i.push({path:"to.merge",message:"callback merge is not serializable; use a keyword strategy",code:"unserializable_merge"}),{ok:i.length===0,errors:i}};export{h as applyMerge,ae as available,A as checkPath,se as checkTransition,B as createAuthorize,te as describe,pe as eligible,de as isSerializable,f as isSerializableMerge,ge as validateTransition};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/authorize.ts","../src/merge.ts","../src/check.ts","../src/describe.ts","../src/registry.ts","../src/serializable.ts","../src/validate.ts"],"names":["CYCLE","actorPermix","actor","isSuperadmin","createAuthorize","options","check","createRebacCheck","resource","rule","record","permix","subject","error","toArray","value","replaceArrays","_target","source","isSerializableMerge","merge","applyMerge","changes","strategy","mergeWith","cloneDeep","kind","path","base","merged","get","set","uniqWith","isEqual","predicateReason","result","denies","authorize","checkPath","transition","evaluation","next","from","fromPredicate","checkRule","to","toPredicate","reason","describePath","segs","describe","getAction","rules","action","found","checkTransition","paths","available","actions","allows","rec","bindTimeZone","timeZone","bindings","carrier","Operator","_field","_operator","bindRule","eligible","compile","predicate","toPrisma","isSerializable","MERGE_KEYWORDS","ARRAY_KINDS","validatePredicate","errors","lens","issues","validateRule","validateRuleInLens","issue","validatePermission","validateActionRule","validateMerge","validateSide","side","validateTransition"],"mappings":"qPA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,CAAAA,EAAY,EAAA,CAAIsC,CAAAA,CAAQ,IAAA,CAAMxE,CAAO,CAAA,CAC9CA,CAAAA,CAAQ,mBAAA,EAAuB,CAACc,CAAAA,CAAoBoB,CAAAA,EAAY,EAAA,EAAI,KAAK,CAAA,EAC3EsC,EAAO,IAAA,CAAK,CACV,IAAA,CAAM,UAAA,CACN,OAAA,CAAS,4DAAA,CACT,IAAA,CAAM,sBACR,CAAC,CAAA,CACI,CAAE,EAAA,CAAIA,CAAAA,CAAO,MAAA,GAAW,CAAA,CAAG,MAAA,CAAAA,CAAO,CAC3C","file":"index.js","sourcesContent":["import {\n type ActionRule,\n createRebacCheck,\n type PermixLike,\n type RebacSchema,\n type SchemaMap,\n type Subject,\n} from '@inixiative/permissions';\nimport type { Actor, Authorize, Row } from './types';\n\nconst CYCLE = /Cycle detected/;\n\nexport type PermissionsAuthorizeOptions<R extends string = string> = {\n /** The permissions rebac schema: `{ bridges?, permissions }`. */\n schema: RebacSchema<R>;\n /** Which model each resource is, and its relations: where a `{ rel }` walk leads. */\n map: SchemaMap<R>;\n /** Superadmin bypass, derived from the actor; checked before any rule. */\n isSuperadmin?: (actor: Actor) => boolean;\n /**\n * Supplemental hydrated rows (`map:model → rows`) for bridge (cross-map) `rel` walks, derived from\n * the record + actor — the same shape `Subject.data` takes. Only consulted when a walk crosses a\n * bridge and a downstream action reads the far record's fields.\n */\n data?: (record: Row, actor: Actor) => Subject<R>['data'];\n};\n\nconst actorPermix = (actor: Actor, isSuperadmin?: (actor: Actor) => boolean): PermixLike => ({\n check: () => false,\n isSuperadmin: () => isSuperadmin?.(actor) ?? false,\n getActor: () => actor ?? null,\n});\n\n/**\n * Bridge `@inixiative/permissions`' rebac `check` onto transitions' {@link Authorize} seam — the\n * production evaluator, injected, not reimplemented. `createAuthorize(options)(resource)` returns an\n * `Authorize` bound to a (map-qualified) `resource`; each call evaluates a per-side `permission`\n * rule against a concrete record + actor. permissions owns the evaluation (string delegation with\n * cycle detection, `rel` walks through the schema map, cross-map bridge walks, abac `{ rule }`\n * reading the actor as `__actor`, boolean terminals, `any`/`all`, per-row `permissionRules`\n * overrides).\n */\nexport const createAuthorize = <R extends string = string>(\n options: PermissionsAuthorizeOptions<R>,\n): ((resource: R) => Authorize) => {\n const check = createRebacCheck<R>(options.map);\n\n return (resource: R): Authorize =>\n (rule, record, actor) => {\n const permix = actorPermix(actor, options.isSuperadmin);\n const subject: Subject<R> = { resource, record, data: options.data?.(record, actor) };\n try {\n return check(permix, options.schema, subject, rule as ActionRule);\n } catch (error) {\n if (error instanceof Error && CYCLE.test(error.message)) return false;\n throw error;\n }\n };\n};\n","import { cloneDeep, get, isEqual, mergeWith, set, uniqWith } from 'lodash-es';\nimport type { Merge, MergeStrategy, Row } from './types';\n\nconst toArray = (value: unknown): unknown[] =>\n Array.isArray(value) ? value : value === undefined ? [] : [value];\n\n// deepMerge replaces arrays wholesale rather than index-merging them (the intuitive default).\nconst replaceArrays = (_target: unknown, source: unknown): unknown[] | undefined =>\n Array.isArray(source) ? source : undefined;\n\n/** A transition is persistable iff its merge is absent or a keyword strategy (callbacks are not). */\nexport const isSerializableMerge = (merge?: Merge): boolean => typeof merge !== 'function';\n\n/**\n * Produce the resulting record from a current record + proposed changes.\n *\n * - `spread` (default) — shallow overwrite (`{ ...record, ...changes }`)\n * - `deepMerge` — recursive object merge, arrays replaced\n * - `{ kind: 'append', path }` — concat `changes[path]` onto `record[path]`\n * - `{ kind: 'appendUnique', path }` — append + dedupe (deep equality)\n * - a callback — full power, not serializable\n */\nexport const applyMerge = <R extends Row>(\n merge: Merge<R> | undefined,\n record: R,\n changes: Partial<R> = {},\n): R => {\n if (typeof merge === 'function') return merge(record, changes);\n\n const strategy: MergeStrategy = merge ?? 'spread';\n\n if (strategy === 'spread') return { ...record, ...changes };\n // clone BOTH inputs: mergeWith assigns nested objects/arrays from `changes` by reference, which\n // would alias the caller's `changes` into the returned record (a mutation footgun for a pure guard).\n if (strategy === 'deepMerge')\n return mergeWith(cloneDeep(record), cloneDeep(changes), replaceArrays);\n\n // field-scoped array strategies: spread the rest of `changes`, then concat at `path`.\n const { kind, path } = strategy;\n const base = cloneDeep({ ...record, ...changes }) as R;\n const merged = [...toArray(get(record, path)), ...toArray(get(changes, path))];\n set(base as Row, path, kind === 'appendUnique' ? uniqWith(merged, isEqual) : merged);\n return base;\n};\n","import { check as checkRule } from '@inixiative/json-rules';\nimport { applyMerge } from './merge';\nimport type {\n ActionRule,\n Actor,\n Authorize,\n PathReason,\n Row,\n SideReason,\n Transition,\n TransitionOptions,\n} from './types';\n\nconst predicateReason = (result: boolean | string): string =>\n typeof result === 'string' ? result : 'predicate not satisfied';\n\n/**\n * Does this permission DENY?\n * - no authorizer injected → can't deny (legality-only mode)\n * - `undefined` rule → permission absent → open → can't deny\n * - any other rule (incl. `null` = terminal deny) → delegate to the authorizer\n */\nconst denies = (\n authorize: Authorize | undefined,\n rule: ActionRule | undefined,\n record: Row,\n actor: Actor,\n): boolean => {\n if (!authorize || rule === undefined) return false;\n return !authorize(rule, record, actor);\n};\n\n/**\n * The kernel: evaluate one atomic edge. Reports every failure rather than short-circuiting —\n * `from`/`to` and predicate/permission are independent slots — so a caller sees the whole\n * picture. `from.*` reads the current `record`, `to.*` reads the merged `next` record. Returns\n * `true` when the edge is allowed, else the {@link PathReason}. Omit `authorize` for legality only;\n * json-rules' `check()` options (`now`, `bindings`, …) reach both predicates.\n */\nexport const checkPath = <R extends Row>(\n transition: Transition<R>,\n record: R,\n changes: Partial<R> = {},\n options: TransitionOptions = {},\n): true | PathReason => {\n const { actor, authorize, ...evaluation } = options;\n const next = applyMerge(transition.to.merge, record, changes);\n\n const from: SideReason = {};\n const fromPredicate = checkRule(transition.from.predicate, record as Row, evaluation);\n if (fromPredicate !== true) from.predicate = predicateReason(fromPredicate);\n if (denies(authorize, transition.from.permission, record as Row, actor))\n from.permission = 'not authorized';\n\n const to: SideReason = {};\n const toPredicate = checkRule(transition.to.predicate, next as Row, evaluation);\n if (toPredicate !== true) to.predicate = predicateReason(toPredicate);\n if (denies(authorize, transition.to.permission, next as Row, actor))\n to.permission = 'not authorized';\n\n const reason: PathReason = {};\n if (from.predicate || from.permission) reason.from = from;\n if (to.predicate || to.permission) reason.to = to;\n return reason.from || reason.to ? reason : true;\n};\n","import type { PathReason, Reason } from './types';\n\nconst describePath = (path: PathReason): string => {\n const segs: string[] = [];\n if (path.from?.predicate) segs.push(`from: ${path.from.predicate}`);\n if (path.from?.permission) segs.push(`from: ${path.from.permission}`);\n if (path.to?.predicate) segs.push(`to: ${path.to.predicate}`);\n if (path.to?.permission) segs.push(`to: ${path.to.permission}`);\n return segs.join('; ') || 'unknown';\n};\n\n/** Build a human-readable message from a structured {@link Reason} (logs / UI / error bodies). */\nexport const describe = (reason: Reason): string => {\n if (reason.paths.length === 0) return 'no transition path available';\n if (reason.paths.length === 1) return describePath(reason.paths[0]);\n return reason.paths.map((path, i) => `path ${i}: ${describePath(path)}`).join(' | ');\n};\n","import {\n bindRule,\n type Condition,\n check as checkRule,\n Operator,\n type RuleValue,\n type TimeZoneConfig,\n type ToPrismaResult,\n toPrisma,\n} from '@inixiative/json-rules';\nimport { checkPath } from './check';\nimport type {\n Action,\n ActionRule,\n CheckResult,\n EligibleOptions,\n PathReason,\n Row,\n TransitionMap,\n TransitionOptions,\n} from './types';\n\nconst getAction = (rules: TransitionMap, resource: string, action: string): Action => {\n const found = rules[resource]?.[action];\n if (!found)\n throw new Error(`transition: no action \"${action}\" registered on resource \"${resource}\"`);\n return found;\n};\n\n/**\n * Authoritative check: the FIRST path whose `from` matches the current record, whose `to` matches\n * the merged record, and whose permissions all pass, wins → `true`. If none pass, returns a\n * {@link Reason} with one {@link PathReason} per candidate path tried.\n *\n * `resource` is the (map-qualified) key into the map — e.g. `db:Inquiry`. Cross-source `permission`\n * checks are handled by the injected {@link Authorize} (wire it to a bridge-aware rebac check, bound\n * to this resource); a `predicate` that reads a bridged relation expects a stitched record.\n */\nexport const checkTransition = (\n rules: TransitionMap,\n resource: string,\n action: string,\n record: Row,\n changes: Row = {},\n options: TransitionOptions = {},\n): CheckResult => {\n const found = getAction(rules, resource, action);\n const paths: PathReason[] = [];\n for (const path of found.paths) {\n const result = checkPath(path, record, changes, options);\n if (result === true) return true;\n paths.push(result);\n }\n return { paths };\n};\n\n/**\n * Affordance hint: which actions are offerable from `record` right now. Evaluates ONLY the `from`\n * side (predicate + `from` permission against the current record) — `to` needs the merged record,\n * which doesn't exist without proposed changes, so it defers to {@link checkTransition}.\n */\nexport const available = (\n rules: TransitionMap,\n resource: string,\n record: Row,\n options: TransitionOptions = {},\n): string[] => {\n const actions = rules[resource];\n if (!actions) return [];\n const { actor, authorize, ...evaluation } = options;\n\n const allows = (rule: ActionRule | undefined, rec: Row): boolean =>\n !authorize || rule === undefined || authorize(rule, rec, actor);\n\n return Object.entries(actions)\n .filter(([, action]) =>\n action.paths.some(\n (path) =>\n checkRule(path.from.predicate, record, evaluation) === true &&\n allows(path.from.permission, record),\n ),\n )\n .map(([action]) => action);\n};\n\n// A `{ bind }` zone, resolved the way the rule's own tokens are: json-rules' bindRule over a\n// carrier leaf. An uncovered token stays a token, and toPrisma reports it unresolved.\nconst bindTimeZone = (\n timeZone: TimeZoneConfig | undefined,\n bindings: Record<string, RuleValue>,\n): TimeZoneConfig | undefined => {\n if (timeZone === undefined || typeof timeZone === 'string') return timeZone;\n const carrier = { field: 'timeZone', operator: Operator.equals, ...timeZone } as Condition;\n const { field: _field, operator: _operator, ...source } = bindRule(carrier, bindings) as Row;\n return source as TimeZoneConfig;\n};\n\n/**\n * Set query as a json-rules Prisma plan: every record currently eligible for `action` (the union\n * of all its paths' `from` predicates; a single path compiles to its predicate alone; an empty\n * action matches nothing). Takes the json-rules `check()` options plus toPrisma's schema:\n * `bindings` are resolved into the predicate and a `{ bind }` timeZone before compiling, `now`\n * reaches `toPrisma`, and `map` / `mapName` / `model` (or `lens`) let it compile a column\n * compared with a column or a count. Run it with json-rules' `executePrismaPlan(plan, prisma)`,\n * which resolves the plan's references, and the `where` selects the rows the single check\n * accepts. A guard toPrisma cannot express (a `$.` row ref in an offset or magnitude, a column\n * ref without the schema) throws.\n */\nexport const eligible = (\n rules: TransitionMap,\n resource: string,\n action: string,\n options: EligibleOptions = {},\n): ToPrismaResult => {\n const found = getAction(rules, resource, action);\n const { bindings = {}, timeZone, ...compile } = options;\n const predicate = bindRule({ any: found.paths.map((path) => path.from.predicate) }, bindings);\n return toPrisma(predicate, { ...compile, timeZone: bindTimeZone(timeZone, bindings) });\n};\n","import { isSerializableMerge } from './merge';\nimport type { Transition } from './types';\n\n/**\n * Can this transition be persisted (stored in the DB, edited in a UI, sent over the wire)?\n *\n * Predicates (json-rules) and permissions (ActionRule) are always plain JSON; the only\n * non-data escape hatch is a `to.merge` callback. So serializability reduces to the merge.\n */\nexport const isSerializable = (transition: Transition): boolean =>\n isSerializableMerge(transition.to.merge);\n","import {\n type Condition,\n type Lens,\n type LensNarrowing,\n type ValidationIssue,\n type ValidationResult,\n validateRule,\n validateRuleInLens,\n} from '@inixiative/json-rules';\nimport { validateActionRule } from '@inixiative/permissions';\nimport { isSerializableMerge } from './merge';\nimport type { ActionRule, Merge, Side, ToSide, Transition } from './types';\n\nexport type { ValidationIssue, ValidationResult };\n\nexport type ValidateOptions = {\n /** Optional field/relation allowlist; passed through to json-rules lens validation per predicate. */\n lens?: Lens | LensNarrowing;\n /** Reject callback merges (use when the transition must be persistable / tenant-configured). */\n requireSerializable?: boolean;\n};\n\nconst MERGE_KEYWORDS = new Set(['spread', 'deepMerge']);\nconst ARRAY_KINDS = new Set(['append', 'appendUnique']);\n\nconst validatePredicate = (\n predicate: Condition | undefined,\n errors: ValidationIssue[],\n path: string,\n lens?: Lens | LensNarrowing,\n): void => {\n if (predicate === undefined) {\n errors.push({ path, message: 'predicate is required', code: 'missing_predicate' });\n return;\n }\n const issues = [\n ...validateRule(predicate).errors,\n ...(lens ? validateRuleInLens(predicate, lens).errors : []),\n ];\n for (const issue of issues) errors.push({ ...issue, path: `${path}.${issue.path}` });\n};\n\nconst validatePermission = (\n rule: ActionRule | undefined,\n errors: ValidationIssue[],\n path: string,\n): void => {\n if (rule === undefined) return;\n for (const issue of validateActionRule(rule).errors)\n errors.push({ ...issue, path: `${path}${issue.path.slice(1)}`, code: 'invalid_permission' });\n};\n\nconst validateMerge = (merge: Merge | undefined, errors: ValidationIssue[], path: string): void => {\n if (merge === undefined || typeof merge === 'function') return;\n if (typeof merge === 'string') {\n if (!MERGE_KEYWORDS.has(merge))\n errors.push({ path, message: `unknown merge strategy \"${merge}\"`, code: 'invalid_merge' });\n return;\n }\n if (!ARRAY_KINDS.has(merge.kind))\n errors.push({ path, message: `unknown merge kind \"${merge.kind}\"`, code: 'invalid_merge' });\n else if (!merge.path)\n errors.push({\n path,\n message: `merge \"${merge.kind}\" requires a \\`path\\``,\n code: 'invalid_merge',\n });\n};\n\nconst validateSide = (\n side: Side | ToSide | undefined,\n errors: ValidationIssue[],\n path: string,\n options: ValidateOptions,\n): void => {\n if (side === null || typeof side !== 'object') {\n errors.push({ path, message: `\\`${path}\\` side is required`, code: 'missing_side' });\n return;\n }\n validatePredicate(side.predicate, errors, `${path}.predicate`, options.lens);\n validatePermission(side.permission, errors, `${path}.permission`);\n if (side.requires !== undefined && (typeof side.requires !== 'object' || side.requires === null))\n errors.push({\n path: `${path}.requires`,\n message: '`requires` must be a Prisma-include-shaped object',\n code: 'invalid_requires',\n });\n if ('merge' in side) validateMerge(side.merge, errors, `${path}.merge`);\n};\n\n/**\n * Authoring validation for a single transition — run on save before persisting a tenant config.\n * Returns structured issues (never throws) on malformed input: predicate validity delegates to\n * json-rules (`validateRule`, plus `validateRuleInLens` when a `lens` is supplied for\n * field/relation scoping); permission shape delegates to `@inixiative/permissions`' `validateActionRule`;\n * merge strategy is checked here.\n */\nexport const validateTransition = (\n transition: Transition,\n options: ValidateOptions = {},\n): ValidationResult => {\n const errors: ValidationIssue[] = [];\n validateSide(transition?.from, errors, 'from', options);\n validateSide(transition?.to, errors, 'to', options);\n if (options.requireSerializable && !isSerializableMerge(transition?.to?.merge))\n errors.push({\n path: 'to.merge',\n message: 'callback merge is not serializable; use a keyword strategy',\n code: 'unserializable_merge',\n });\n return { ok: errors.length === 0, errors };\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/authorize.ts","../src/merge.ts","../src/check.ts","../src/describe.ts","../src/engineGlobals.ts","../src/registry.ts","../src/serializable.ts","../src/validate.ts"],"names":["CYCLE","actorPermix","actor","isSuperadmin","createAuthorize","options","check","createRebacCheck","resource","rule","record","permix","subject","error","toArray","value","replaceArrays","_target","source","isSerializableMerge","merge","applyMerge","changes","strategy","mergeWith","cloneDeep","kind","path","base","merged","get","set","uniqWith","isEqual","predicateReason","result","denies","authorize","checkPath","transition","evaluation","next","from","fromPredicate","checkRule","to","toPredicate","reason","describePath","segs","describe","registerEngineGlobals","getAction","rules","action","found","checkTransition","paths","available","actions","allows","rec","bindTimeZone","timeZone","bindings","carrier","Operator","_field","_operator","bindRule","eligible","compile","predicate","toPrisma","isSerializable","MERGE_KEYWORDS","ARRAY_KINDS","validatePredicate","errors","lens","issues","validateRule","validateRuleInLens","issue","validatePermission","validateActionRule","validateMerge","validateSide","side","validateTransition"],"mappings":"2QAUA,IAAMA,CAAAA,CAAQ,gBAAA,CAiBRC,CAAAA,CAAc,CAACC,CAAAA,CAAcC,CAAAA,IAA0D,CAC3F,KAAA,CAAO,IAAM,KAAA,CACb,YAAA,CAAc,IAAMA,CAAAA,GAAeD,CAAK,CAAA,EAAK,KAAA,CAC7C,QAAA,CAAU,IAAMA,CAAAA,EAAS,IAC3B,CAAA,CAAA,CAWaE,CAAAA,CACXC,CAAAA,EACiC,CACjC,IAAMC,CAAAA,CAAQC,gBAAAA,CAAoBF,CAAAA,CAAQ,GAAG,CAAA,CAE7C,OAAQG,CAAAA,EACN,CAACC,CAAAA,CAAMC,CAAAA,CAAQR,CAAAA,GAAU,CACvB,IAAMS,CAAAA,CAASV,CAAAA,CAAYC,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Q,IAAI,CAAA,CAC3E+E,CAAAA,CAAmBI,CAAAA,CAAK,UAAA,CAAYV,CAAAA,CAAQ,CAAA,EAAGnD,CAAI,CAAA,WAAA,CAAa,CAAA,CAC5D6D,EAAK,QAAA,GAAa,MAAA,GAAc,OAAOA,CAAAA,CAAK,QAAA,EAAa,QAAA,EAAYA,CAAAA,CAAK,QAAA,GAAa,IAAA,CAAA,EACzFV,CAAAA,CAAO,IAAA,CAAK,CACV,IAAA,CAAM,CAAA,EAAGnD,CAAI,CAAA,SAAA,CAAA,CACb,QAAS,mDAAA,CACT,IAAA,CAAM,kBACR,CAAC,CAAA,CACC,OAAA,GAAW6D,CAAAA,EAAMF,CAAAA,CAAcE,CAAAA,CAAK,KAAA,CAAOV,CAAAA,CAAQ,CAAA,EAAGnD,CAAI,CAAA,MAAA,CAAQ,EACxE,CAAA,CASa8D,GAAqB,CAChClD,CAAAA,CACAlC,CAAAA,CAA2B,EAAC,GACP,CACrB,IAAMyE,CAAAA,CAA4B,EAAC,CACnC,OAAAS,CAAAA,CAAahD,CAAAA,EAAY,IAAA,CAAMuC,CAAAA,CAAQ,MAAA,CAAQzE,CAAO,CAAA,CACtDkF,CAAAA,CAAahD,CAAAA,EAAY,EAAA,CAAIuC,CAAAA,CAAQ,IAAA,CAAMzE,CAAO,CAAA,CAC9CA,CAAAA,CAAQ,mBAAA,EAAuB,CAACc,CAAAA,CAAoBoB,CAAAA,EAAY,EAAA,EAAI,KAAK,CAAA,EAC3EuC,EAAO,IAAA,CAAK,CACV,IAAA,CAAM,UAAA,CACN,OAAA,CAAS,4DAAA,CACT,IAAA,CAAM,sBACR,CAAC,CAAA,CACI,CAAE,EAAA,CAAIA,CAAAA,CAAO,MAAA,GAAW,CAAA,CAAG,MAAA,CAAAA,CAAO,CAC3C","file":"index.js","sourcesContent":["import {\n type ActionRule,\n createRebacCheck,\n type PermixLike,\n type RebacSchema,\n type SchemaMap,\n type Subject,\n} from '@inixiative/permissions';\nimport type { Actor, Authorize, Row } from './types';\n\nconst CYCLE = /Cycle detected/;\n\nexport type PermissionsAuthorizeOptions<R extends string = string> = {\n /** The permissions rebac schema: `{ bridges?, permissions }`. */\n schema: RebacSchema<R>;\n /** Which model each resource is, and its relations: where a `{ rel }` walk leads. */\n map: SchemaMap<R>;\n /** Superadmin bypass, derived from the actor; checked before any rule. */\n isSuperadmin?: (actor: Actor) => boolean;\n /**\n * Supplemental hydrated rows (`map:model → rows`) for bridge (cross-map) `rel` walks, derived from\n * the record + actor — the same shape `Subject.data` takes. Only consulted when a walk crosses a\n * bridge and a downstream action reads the far record's fields.\n */\n data?: (record: Row, actor: Actor) => Subject<R>['data'];\n};\n\nconst actorPermix = (actor: Actor, isSuperadmin?: (actor: Actor) => boolean): PermixLike => ({\n check: () => false,\n isSuperadmin: () => isSuperadmin?.(actor) ?? false,\n getActor: () => actor ?? null,\n});\n\n/**\n * Bridge `@inixiative/permissions`' rebac `check` onto transitions' {@link Authorize} seam — the\n * production evaluator, injected, not reimplemented. `createAuthorize(options)(resource)` returns an\n * `Authorize` bound to a (map-qualified) `resource`; each call evaluates a per-side `permission`\n * rule against a concrete record + actor. permissions owns the evaluation (string delegation with\n * cycle detection, `rel` walks through the schema map, cross-map bridge walks, abac `{ rule }`\n * reading the actor as `__actor`, boolean terminals, `any`/`all`, per-row `permissionRules`\n * overrides).\n */\nexport const createAuthorize = <R extends string = string>(\n options: PermissionsAuthorizeOptions<R>,\n): ((resource: R) => Authorize) => {\n const check = createRebacCheck<R>(options.map);\n\n return (resource: R): Authorize =>\n (rule, record, actor) => {\n const permix = actorPermix(actor, options.isSuperadmin);\n const subject: Subject<R> = { resource, record, data: options.data?.(record, actor) };\n try {\n return check(permix, options.schema, subject, rule as ActionRule);\n } catch (error) {\n if (error instanceof Error && CYCLE.test(error.message)) return false;\n throw error;\n }\n };\n};\n","import { cloneDeep, get, isEqual, mergeWith, set, uniqWith } from 'lodash-es';\nimport type { Merge, MergeStrategy, Row } from './types';\n\nconst toArray = (value: unknown): unknown[] =>\n Array.isArray(value) ? value : value === undefined ? [] : [value];\n\n// deepMerge replaces arrays wholesale rather than index-merging them (the intuitive default).\nconst replaceArrays = (_target: unknown, source: unknown): unknown[] | undefined =>\n Array.isArray(source) ? source : undefined;\n\n/** A transition is persistable iff its merge is absent or a keyword strategy (callbacks are not). */\nexport const isSerializableMerge = (merge?: Merge): boolean => typeof merge !== 'function';\n\n/**\n * Produce the resulting record from a current record + proposed changes.\n *\n * - `spread` (default) — shallow overwrite (`{ ...record, ...changes }`)\n * - `deepMerge` — recursive object merge, arrays replaced\n * - `{ kind: 'append', path }` — concat `changes[path]` onto `record[path]`\n * - `{ kind: 'appendUnique', path }` — append + dedupe (deep equality)\n * - a callback — full power, not serializable\n */\nexport const applyMerge = <R extends Row>(\n merge: Merge<R> | undefined,\n record: R,\n changes: Partial<R> = {},\n): R => {\n if (typeof merge === 'function') return merge(record, changes);\n\n const strategy: MergeStrategy = merge ?? 'spread';\n\n if (strategy === 'spread') return { ...record, ...changes };\n // clone BOTH inputs: mergeWith assigns nested objects/arrays from `changes` by reference, which\n // would alias the caller's `changes` into the returned record (a mutation footgun for a pure guard).\n if (strategy === 'deepMerge')\n return mergeWith(cloneDeep(record), cloneDeep(changes), replaceArrays);\n\n // field-scoped array strategies: spread the rest of `changes`, then concat at `path`.\n const { kind, path } = strategy;\n const base = cloneDeep({ ...record, ...changes }) as R;\n const merged = [...toArray(get(record, path)), ...toArray(get(changes, path))];\n set(base as Row, path, kind === 'appendUnique' ? uniqWith(merged, isEqual) : merged);\n return base;\n};\n","import { check as checkRule } from '@inixiative/json-rules';\nimport { applyMerge } from './merge';\nimport type {\n ActionRule,\n Actor,\n Authorize,\n PathReason,\n Row,\n SideReason,\n Transition,\n TransitionOptions,\n} from './types';\n\nconst predicateReason = (result: boolean | string): string =>\n typeof result === 'string' ? result : 'predicate not satisfied';\n\n/**\n * Does this permission DENY?\n * - no authorizer injected → can't deny (legality-only mode)\n * - `undefined` rule → permission absent → open → can't deny\n * - any other rule (incl. `null` = terminal deny) → delegate to the authorizer\n */\nconst denies = (\n authorize: Authorize | undefined,\n rule: ActionRule | undefined,\n record: Row,\n actor: Actor,\n): boolean => {\n if (!authorize || rule === undefined) return false;\n return !authorize(rule, record, actor);\n};\n\n/**\n * The kernel: evaluate one atomic edge. Reports every failure rather than short-circuiting —\n * `from`/`to` and predicate/permission are independent slots — so a caller sees the whole\n * picture. `from.*` reads the current `record`, `to.*` reads the merged `next` record. Returns\n * `true` when the edge is allowed, else the {@link PathReason}. Omit `authorize` for legality only;\n * json-rules' `check()` options (`now`, `bindings`, …) reach both predicates.\n */\nexport const checkPath = <R extends Row>(\n transition: Transition<R>,\n record: R,\n changes: Partial<R> = {},\n options: TransitionOptions = {},\n): true | PathReason => {\n const { actor, authorize, ...evaluation } = options;\n const next = applyMerge(transition.to.merge, record, changes);\n\n const from: SideReason = {};\n const fromPredicate = checkRule(transition.from.predicate, record as Row, evaluation);\n if (fromPredicate !== true) from.predicate = predicateReason(fromPredicate);\n if (denies(authorize, transition.from.permission, record as Row, actor))\n from.permission = 'not authorized';\n\n const to: SideReason = {};\n const toPredicate = checkRule(transition.to.predicate, next as Row, evaluation);\n if (toPredicate !== true) to.predicate = predicateReason(toPredicate);\n if (denies(authorize, transition.to.permission, next as Row, actor))\n to.permission = 'not authorized';\n\n const reason: PathReason = {};\n if (from.predicate || from.permission) reason.from = from;\n if (to.predicate || to.permission) reason.to = to;\n return reason.from || reason.to ? reason : true;\n};\n","import type { PathReason, Reason } from './types';\n\nconst describePath = (path: PathReason): string => {\n const segs: string[] = [];\n if (path.from?.predicate) segs.push(`from: ${path.from.predicate}`);\n if (path.from?.permission) segs.push(`from: ${path.from.permission}`);\n if (path.to?.predicate) segs.push(`to: ${path.to.predicate}`);\n if (path.to?.permission) segs.push(`to: ${path.to.permission}`);\n return segs.join('; ') || 'unknown';\n};\n\n/** Build a human-readable message from a structured {@link Reason} (logs / UI / error bodies). */\nexport const describe = (reason: Reason): string => {\n if (reason.paths.length === 0) return 'no transition path available';\n if (reason.paths.length === 1) return describePath(reason.paths[0]);\n return reason.paths.map((path, i) => `path ${i}: ${describePath(path)}`).join(' | ');\n};\n","import { registerEngineGlobals } from '@inixiative/json-rules';\n\n// transitions' namespace in the one engine interaction point (json-rules' `engineGlobals`). Every\n// option transitions takes is per call today, so it holds no path yet.\nregisterEngineGlobals('transitions', {});\n","import {\n bindRule,\n type Condition,\n check as checkRule,\n Operator,\n type RuleValue,\n type TimeZoneConfig,\n type ToPrismaResult,\n toPrisma,\n} from '@inixiative/json-rules';\nimport { checkPath } from './check';\nimport type {\n Action,\n ActionRule,\n CheckResult,\n EligibleOptions,\n PathReason,\n Row,\n TransitionMap,\n TransitionOptions,\n} from './types';\n\nconst getAction = (rules: TransitionMap, resource: string, action: string): Action => {\n const found = rules[resource]?.[action];\n if (!found)\n throw new Error(`transition: no action \"${action}\" registered on resource \"${resource}\"`);\n return found;\n};\n\n/**\n * Authoritative check: the FIRST path whose `from` matches the current record, whose `to` matches\n * the merged record, and whose permissions all pass, wins → `true`. If none pass, returns a\n * {@link Reason} with one {@link PathReason} per candidate path tried.\n *\n * `resource` is the (map-qualified) key into the map — e.g. `db:Inquiry`. Cross-source `permission`\n * checks are handled by the injected {@link Authorize} (wire it to a bridge-aware rebac check, bound\n * to this resource); a `predicate` that reads a bridged relation expects a stitched record.\n */\nexport const checkTransition = (\n rules: TransitionMap,\n resource: string,\n action: string,\n record: Row,\n changes: Row = {},\n options: TransitionOptions = {},\n): CheckResult => {\n const found = getAction(rules, resource, action);\n const paths: PathReason[] = [];\n for (const path of found.paths) {\n const result = checkPath(path, record, changes, options);\n if (result === true) return true;\n paths.push(result);\n }\n return { paths };\n};\n\n/**\n * Affordance hint: which actions are offerable from `record` right now. Evaluates ONLY the `from`\n * side (predicate + `from` permission against the current record) — `to` needs the merged record,\n * which doesn't exist without proposed changes, so it defers to {@link checkTransition}.\n */\nexport const available = (\n rules: TransitionMap,\n resource: string,\n record: Row,\n options: TransitionOptions = {},\n): string[] => {\n const actions = rules[resource];\n if (!actions) return [];\n const { actor, authorize, ...evaluation } = options;\n\n const allows = (rule: ActionRule | undefined, rec: Row): boolean =>\n !authorize || rule === undefined || authorize(rule, rec, actor);\n\n return Object.entries(actions)\n .filter(([, action]) =>\n action.paths.some(\n (path) =>\n checkRule(path.from.predicate, record, evaluation) === true &&\n allows(path.from.permission, record),\n ),\n )\n .map(([action]) => action);\n};\n\n// A `{ bind }` zone, resolved the way the rule's own tokens are: json-rules' bindRule over a\n// carrier leaf. An uncovered token stays a token, and toPrisma reports it unresolved.\nconst bindTimeZone = (\n timeZone: TimeZoneConfig | undefined,\n bindings: Record<string, RuleValue>,\n): TimeZoneConfig | undefined => {\n if (timeZone === undefined || typeof timeZone === 'string') return timeZone;\n const carrier = { field: 'timeZone', operator: Operator.equals, ...timeZone } as Condition;\n const { field: _field, operator: _operator, ...source } = bindRule(carrier, bindings) as Row;\n return source as TimeZoneConfig;\n};\n\n/**\n * Set query as a json-rules Prisma plan: every record currently eligible for `action` (the union\n * of all its paths' `from` predicates; a single path compiles to its predicate alone; an empty\n * action matches nothing). Takes the json-rules `check()` options plus toPrisma's schema:\n * `bindings` are resolved into the predicate and a `{ bind }` timeZone before compiling, `now`\n * reaches `toPrisma`, and `map` / `mapName` / `model` (or `lens`) let it compile a column\n * compared with a column or a count. Run it with json-rules' `executePrismaPlan(plan, prisma)`,\n * which resolves the plan's references, and the `where` selects the rows the single check\n * accepts. A guard toPrisma cannot express (a `$.` row ref in an offset or magnitude, a column\n * ref without the schema) throws.\n */\nexport const eligible = (\n rules: TransitionMap,\n resource: string,\n action: string,\n options: EligibleOptions = {},\n): ToPrismaResult => {\n const found = getAction(rules, resource, action);\n const { bindings = {}, timeZone, ...compile } = options;\n const predicate = bindRule({ any: found.paths.map((path) => path.from.predicate) }, bindings);\n return toPrisma(predicate, { ...compile, timeZone: bindTimeZone(timeZone, bindings) });\n};\n","import { isSerializableMerge } from './merge';\nimport type { Transition } from './types';\n\n/**\n * Can this transition be persisted (stored in the DB, edited in a UI, sent over the wire)?\n *\n * Predicates (json-rules) and permissions (ActionRule) are always plain JSON; the only\n * non-data escape hatch is a `to.merge` callback. So serializability reduces to the merge.\n */\nexport const isSerializable = (transition: Transition): boolean =>\n isSerializableMerge(transition.to.merge);\n","import {\n type Condition,\n type Lens,\n type LensNarrowing,\n type ValidationIssue,\n type ValidationResult,\n validateRule,\n validateRuleInLens,\n} from '@inixiative/json-rules';\nimport { validateActionRule } from '@inixiative/permissions';\nimport { isSerializableMerge } from './merge';\nimport type { ActionRule, Merge, Side, ToSide, Transition } from './types';\n\nexport type { ValidationIssue, ValidationResult };\n\nexport type ValidateOptions = {\n /** Optional field/relation allowlist; passed through to json-rules lens validation per predicate. */\n lens?: Lens | LensNarrowing;\n /** Reject callback merges (use when the transition must be persistable / tenant-configured). */\n requireSerializable?: boolean;\n};\n\nconst MERGE_KEYWORDS = new Set(['spread', 'deepMerge']);\nconst ARRAY_KINDS = new Set(['append', 'appendUnique']);\n\nconst validatePredicate = (\n predicate: Condition | undefined,\n errors: ValidationIssue[],\n path: string,\n lens?: Lens | LensNarrowing,\n): void => {\n if (predicate === undefined) {\n errors.push({ path, message: 'predicate is required', code: 'missing_predicate' });\n return;\n }\n const issues = [\n ...validateRule(predicate).errors,\n ...(lens ? validateRuleInLens(predicate, lens).errors : []),\n ];\n for (const issue of issues) errors.push({ ...issue, path: `${path}.${issue.path}` });\n};\n\nconst validatePermission = (\n rule: ActionRule | undefined,\n errors: ValidationIssue[],\n path: string,\n): void => {\n if (rule === undefined) return;\n for (const issue of validateActionRule(rule).errors)\n errors.push({ ...issue, path: `${path}${issue.path.slice(1)}`, code: 'invalid_permission' });\n};\n\nconst validateMerge = (merge: Merge | undefined, errors: ValidationIssue[], path: string): void => {\n if (merge === undefined || typeof merge === 'function') return;\n if (typeof merge === 'string') {\n if (!MERGE_KEYWORDS.has(merge))\n errors.push({ path, message: `unknown merge strategy \"${merge}\"`, code: 'invalid_merge' });\n return;\n }\n if (!ARRAY_KINDS.has(merge.kind))\n errors.push({ path, message: `unknown merge kind \"${merge.kind}\"`, code: 'invalid_merge' });\n else if (!merge.path)\n errors.push({\n path,\n message: `merge \"${merge.kind}\" requires a \\`path\\``,\n code: 'invalid_merge',\n });\n};\n\nconst validateSide = (\n side: Side | ToSide | undefined,\n errors: ValidationIssue[],\n path: string,\n options: ValidateOptions,\n): void => {\n if (side === null || typeof side !== 'object') {\n errors.push({ path, message: `\\`${path}\\` side is required`, code: 'missing_side' });\n return;\n }\n validatePredicate(side.predicate, errors, `${path}.predicate`, options.lens);\n validatePermission(side.permission, errors, `${path}.permission`);\n if (side.requires !== undefined && (typeof side.requires !== 'object' || side.requires === null))\n errors.push({\n path: `${path}.requires`,\n message: '`requires` must be a Prisma-include-shaped object',\n code: 'invalid_requires',\n });\n if ('merge' in side) validateMerge(side.merge, errors, `${path}.merge`);\n};\n\n/**\n * Authoring validation for a single transition — run on save before persisting a tenant config.\n * Returns structured issues (never throws) on malformed input: predicate validity delegates to\n * json-rules (`validateRule`, plus `validateRuleInLens` when a `lens` is supplied for\n * field/relation scoping); permission shape delegates to `@inixiative/permissions`' `validateActionRule`;\n * merge strategy is checked here.\n */\nexport const validateTransition = (\n transition: Transition,\n options: ValidateOptions = {},\n): ValidationResult => {\n const errors: ValidationIssue[] = [];\n validateSide(transition?.from, errors, 'from', options);\n validateSide(transition?.to, errors, 'to', options);\n if (options.requireSerializable && !isSerializableMerge(transition?.to?.merge))\n errors.push({\n path: 'to.merge',\n message: 'callback merge is not serializable; use a keyword strategy',\n code: 'unserializable_merge',\n });\n return { ok: errors.length === 0, errors };\n};\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inixiative/transitions",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"description": "Declarative, serializable transition guard + affordance layer on top of @inixiative/json-rules",
|
|
5
5
|
"main": "./dist/index.cjs",
|
|
6
6
|
"module": "./dist/index.js",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
43
|
"@biomejs/biome": "2.5.2",
|
|
44
|
-
"@inixiative/config": "^0.5.
|
|
44
|
+
"@inixiative/config": "^0.5.193",
|
|
45
45
|
"@types/bun": "1.4.4",
|
|
46
46
|
"@types/lodash-es": "^4.17.12",
|
|
47
47
|
"lefthook": "2.1.9",
|
|
@@ -57,8 +57,8 @@
|
|
|
57
57
|
}
|
|
58
58
|
},
|
|
59
59
|
"dependencies": {
|
|
60
|
-
"@inixiative/json-rules": "^3.
|
|
61
|
-
"@inixiative/permissions": "^0.
|
|
60
|
+
"@inixiative/json-rules": "^3.18.0",
|
|
61
|
+
"@inixiative/permissions": "^0.20.0",
|
|
62
62
|
"lodash-es": "^4.18.1",
|
|
63
63
|
"zod": "^4.4.3"
|
|
64
64
|
},
|