@inixiative/transitions 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -136,13 +136,13 @@ available(rules, 'db:Inquiry', record, { actor, authorize });
136
136
  // → ['approve', 'reject', 'cancel'] (from-side only — `to` needs proposed changes, so it defers to checkTransition)
137
137
 
138
138
  eligible(rules, 'db:Inquiry', 'approve');
139
- // → { OR: [{ status: { equals: 'pending' } }] } (Prisma where for "every record eligible for approve")
139
+ // → { status: { equals: 'pending' } } (Prisma where for "every record eligible for approve")
140
140
  ```
141
141
 
142
142
  A predicate evaluates with the same options json-rules' `check()` takes — `now`, `timeZone`,
143
- `weekStart`, `bindings`, `context` — passed beside `actor` / `authorize`. `checkTransition`,
143
+ `weekStart`, `bindings` — passed beside `actor` / `authorize`. `checkTransition`,
144
144
  `checkPath` and `available` give them to both sides; `eligible` resolves the bindings into the
145
- predicate and compiles with `now` / `context`, so the set query selects exactly the records the
145
+ predicate and compiles with `now`, so the set query selects exactly the records the
146
146
  single check accepts:
147
147
 
148
148
  ```ts
@@ -151,7 +151,7 @@ const options = { now, bindings: { quietWindow: { ago: { seconds: 1800 } } } };
151
151
 
152
152
  checkTransition(rules, 'incident', 'autoResolve', incident, { status: 'resolved' }, options);
153
153
  eligible(rules, 'incident', 'autoResolve', options);
154
- // → { OR: [{ AND: [{ status: … }, { lastBreachedAt: { lt: <now - window> } }] }] }
154
+ // → { AND: [{ status: … }, { lastBreachedAt: { lt: <now - window> } }] }
155
155
  ```
156
156
 
157
157
  A guard can read its window off the record instead — self-contained, nothing to bind:
@@ -177,10 +177,12 @@ but not (`isSerializable(transition)` tells you which).
177
177
  ## Authoring validation
178
178
 
179
179
  `validateTransition(t, { lens?, requireSerializable? })` validates predicates (via json-rules
180
- `validateRule`, plus `checkRuleAgainstLens` when a `lens` scopes referenceable fields), merge
180
+ `validateRule`, plus `validateRuleInLens` when a `lens` scopes referenceable fields), merge
181
181
  strategy, and permission shape (via `@inixiative/permissions`' zod `actionRuleSchema`) — run it on
182
- save before persisting a tenant config. It returns structured `{ ok, errors }` (never throws), even on
183
- malformed input.
182
+ save before persisting a tenant config. It returns json-rules' `ValidationResult` —
183
+ `{ ok, errors: { path, message, code }[] }` — and never throws, even on malformed input. json-rules'
184
+ issues keep their codes; transitions adds `missing_side`, `missing_predicate`, `invalid_permission`,
185
+ `invalid_requires`, `invalid_merge` and `unserializable_merge`.
184
186
 
185
187
  ## Not built yet (designed — see the plan)
186
188
 
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'),actionRuleSchema=require('@inixiative/permissions/actionRuleSchema');var $=/Cycle detected/,M=(e,t)=>({check:()=>false,isSuperadmin:()=>t?.(e)??false,getUserId:()=>e?.id??null}),K=e=>{let t=e.resolveRelation??((n,i)=>i),o=permissions.createRebacCheck(t);return n=>(i,r,s)=>{let p=M(s,e.isSuperadmin),c={resource:n,record:r,data:e.data?.(r,s)};try{return o(p,e.schema,c,i)}catch(a){if(a instanceof Error&&$.test(a.message))return false;throw a}}};var g=e=>Array.isArray(e)?e:e===void 0?[]:[e],O=(e,t)=>Array.isArray(t)?t:void 0,d=e=>typeof e!="function",h=(e,t,o={})=>{if(typeof e=="function")return e(t,o);let n=e??"spread";if(n==="spread")return {...t,...o};if(n==="deepMerge")return lodashEs.mergeWith(lodashEs.cloneDeep(t),lodashEs.cloneDeep(o),O);let{kind:i,path:r}=n,s=lodashEs.cloneDeep({...t,...o}),p=[...g(lodashEs.get(t,r)),...g(lodashEs.get(o,r))];return lodashEs.set(s,r,i==="appendUnique"?lodashEs.uniqWith(p,lodashEs.isEqual):p),s};var w=e=>typeof e=="string"?e:"predicate not satisfied",b=(e,t,o,n)=>!e||t===void 0?false:!e(t,o,n),A=(e,t,o={},n={})=>{let{actor:i,authorize:r,...s}=n,p=h(e.to.merge,t,o),c={},a=jsonRules.check(e.from.predicate,t,s);a!==true&&(c.predicate=w(a)),b(r,e.from.permission,t,i)&&(c.permission="not authorized");let u={},l=jsonRules.check(e.to.predicate,p,s);l!==true&&(u.predicate=w(l)),b(r,e.to.permission,p,i)&&(u.permission="not authorized");let f={};return (c.predicate||c.permission)&&(f.from=c),(u.predicate||u.permission)&&(f.to=u),f.from||f.to?f: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"},X=e=>e.paths.length===0?"no transition path available":e.paths.length===1?k(e.paths[0]):e.paths.map((t,o)=>`path ${o}: ${k(t)}`).join(" | ");var x=(e,t,o)=>{let n=e[t]?.[o];if(!n)throw new Error(`transition: no action "${o}" registered on resource "${t}"`);return n},oe=(e,t,o,n,i={},r={})=>{let s=x(e,t,o),p=[];for(let c of s.paths){let a=A(c,n,i,r);if(a===true)return true;p.push(a);}return {paths:p}},ne=(e,t,o,n={})=>{let i=e[t];if(!i)return [];let{actor:r,authorize:s,...p}=n,c=(a,u)=>!s||a===void 0||s(a,u,r);return Object.entries(i).filter(([,a])=>a.paths.some(u=>jsonRules.check(u.from.predicate,o,p)===true&&c(u.from.permission,o))).map(([a])=>a)},ie=(e,t,o,n={})=>{let i=x(e,t,o),{bindings:r={},...s}=n,p=jsonRules.resolveBindings({any:i.paths.map(a=>a.from.predicate)},r),{steps:c}=jsonRules.toPrisma(p,s);return c[c.length-1].where};var ae=e=>d(e.to.merge);var N=new Set(["spread","deepMerge"]),_=new Set(["append","appendUnique"]),D=(e,t,o,n)=>{if(e===void 0){t.push({path:o,message:"predicate is required"});return}let i=jsonRules.validateRule(e);for(let r of i.errors)t.push({path:`${o}.${r.path}`,message:r.message});if(n){let r=jsonRules.checkRuleAgainstLens(e,n);for(let s of r.violations)t.push({path:`${o}.${s.path}`,message:s.reason});}},U=(e,t,o)=>{if(e===void 0)return;let n=actionRuleSchema.actionRuleSchema.safeParse(e);if(!n.success)for(let i of n.error.issues)i.path.length===0?t.push({path:o,message:"unrecognized ActionRule shape"}):t.push({path:`${o}.${i.path.join(".")}`,message:i.message});},W=(e,t,o)=>{if(!(e===void 0||typeof e=="function")){if(typeof e=="string"){N.has(e)||t.push({path:o,message:`unknown merge strategy "${e}"`});return}_.has(e.kind)?e.path||t.push({path:o,message:`merge "${e.kind}" requires a \`path\``}):t.push({path:o,message:`unknown merge kind "${e.kind}"`});}},S=(e,t,o,n)=>{if(e===null||typeof e!="object"){t.push({path:o,message:`\`${o}\` side is required`});return}D(e.predicate,t,`${o}.predicate`,n.lens),U(e.permission,t,`${o}.permission`),e.requires!==void 0&&(typeof e.requires!="object"||e.requires===null)&&t.push({path:`${o}.requires`,message:"`requires` must be a Prisma-include-shaped object"}),"merge"in e&&W(e.merge,t,`${o}.merge`);},de=(e,t={})=>{let o=[];return S(e?.from,o,"from",t),S(e?.to,o,"to",t),t.requireSerializable&&!d(e?.to?.merge)&&o.push({path:"to.merge",message:"callback merge is not serializable; use a keyword strategy"}),{ok:o.length===0,errors:o}};exports.applyMerge=h;exports.available=ne;exports.checkPath=A;exports.checkTransition=oe;exports.createAuthorize=K;exports.describe=X;exports.eligible=ie;exports.isSerializable=ae;exports.isSerializableMerge=d;exports.validateTransition=de;//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var permissions=require('@inixiative/permissions'),jsonRules=require('@inixiative/json-rules'),lodashEs=require('lodash-es'),actionRuleSchema=require('@inixiative/permissions/actionRuleSchema');var v=/Cycle detected/,M=(e,t)=>({check:()=>false,isSuperadmin:()=>t?.(e)??false,getUserId:()=>e?.id??null}),K=e=>{let t=e.resolveRelation??((o,n)=>n),i=permissions.createRebacCheck(t);return o=>(n,r,a)=>{let p=M(a,e.isSuperadmin),c={resource:o,record:r,data:e.data?.(r,a)};try{return i(p,e.schema,c,n)}catch(s){if(s instanceof Error&&v.test(s.message))return false;throw s}}};var g=e=>Array.isArray(e)?e:e===void 0?[]:[e],O=(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),O);let{kind:n,path:r}=o,a=lodashEs.cloneDeep({...t,...i}),p=[...g(lodashEs.get(t,r)),...g(lodashEs.get(i,r))];return lodashEs.set(a,r,n==="appendUnique"?lodashEs.uniqWith(p,lodashEs.isEqual):p),a};var w=e=>typeof e=="string"?e:"predicate not satisfied",b=(e,t,i,o)=>!e||t===void 0?false:!e(t,i,o),A=(e,t,i={},o={})=>{let{actor:n,authorize:r,...a}=o,p=h(e.to.merge,t,i),c={},s=jsonRules.check(e.from.predicate,t,a);s!==true&&(c.predicate=w(s)),b(r,e.from.permission,t,n)&&(c.permission="not authorized");let u={},m=jsonRules.check(e.to.predicate,p,a);m!==true&&(u.predicate=w(m)),b(r,e.to.permission,p,n)&&(u.permission="not authorized");let d={};return (c.predicate||c.permission)&&(d.from=c),(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"},X=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(" | ");var x=(e,t,i)=>{let o=e[t]?.[i];if(!o)throw new Error(`transition: no action "${i}" registered on resource "${t}"`);return o},ie=(e,t,i,o,n={},r={})=>{let a=x(e,t,i),p=[];for(let c of a.paths){let s=A(c,o,n,r);if(s===true)return true;p.push(s);}return {paths:p}},oe=(e,t,i,o={})=>{let n=e[t];if(!n)return [];let{actor:r,authorize:a,...p}=o,c=(s,u)=>!a||s===void 0||a(s,u,r);return Object.entries(n).filter(([,s])=>s.paths.some(u=>jsonRules.check(u.from.predicate,i,p)===true&&c(u.from.permission,i))).map(([s])=>s)},ne=(e,t,i,o={})=>{let n=x(e,t,i),{bindings:r={},...a}=o,p=jsonRules.bindRule({any:n.paths.map(s=>s.from.predicate)},r),{steps:c}=jsonRules.toPrisma(p,a);return c[c.length-1].where};var ae=e=>f(e.to.merge);var E=new Set(["spread","deepMerge"]),N=new Set(["append","appendUnique"]),D=(e,t,i,o)=>{if(e===void 0){t.push({path:i,message:"predicate is required",code:"missing_predicate"});return}let n=[...jsonRules.validateRule(e).errors,...o?jsonRules.validateRuleInLens(e,o).errors:[]];for(let r of n)t.push({...r,path:`${i}.${r.path}`});},U=(e,t,i)=>{if(e===void 0)return;let o=actionRuleSchema.actionRuleSchema.safeParse(e);if(!o.success)for(let n of o.error.issues)n.path.length===0?t.push({path:i,message:"unrecognized ActionRule shape",code:"invalid_permission"}):t.push({path:`${i}.${n.path.join(".")}`,message:n.message,code:"invalid_permission"});},W=(e,t,i)=>{if(!(e===void 0||typeof e=="function")){if(typeof e=="string"){E.has(e)||t.push({path:i,message:`unknown merge strategy "${e}"`,code:"invalid_merge"});return}N.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"});}},S=(e,t,i,o)=>{if(e===null||typeof e!="object"){t.push({path:i,message:`\`${i}\` side is required`,code:"missing_side"});return}D(e.predicate,t,`${i}.predicate`,o.lens),U(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&&W(e.merge,t,`${i}.merge`);},fe=(e,t={})=>{let i=[];return S(e?.from,i,"from",t),S(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=oe;exports.checkPath=A;exports.checkTransition=ie;exports.createAuthorize=K;exports.describe=X;exports.eligible=ne;exports.isSerializable=ae;exports.isSerializableMerge=f;exports.validateTransition=fe;//# sourceMappingURL=index.cjs.map
2
2
  //# sourceMappingURL=index.cjs.map
@@ -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","resolveRelation","_resource","segment","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","i","getAction","rules","action","found","checkTransition","paths","available","actions","allows","rec","eligible","bindings","compile","predicate","resolveBindings","steps","toPrisma","isSerializable","MERGE_KEYWORDS","ARRAY_KINDS","validatePredicate","errors","lens","validateRule","issue","lensCheck","checkRuleAgainstLens","violation","validatePermission","parsed","actionRuleSchema","validateMerge","validateSide","side","validateTransition"],"mappings":"+MAYA,IAAMA,CAAAA,CAAQ,gBAAA,CAwBRC,CAAAA,CAAc,CAACC,CAAAA,CAAcC,CAAAA,IAA0D,CAC3F,KAAA,CAAO,IAAM,KAAA,CACb,YAAA,CAAc,IAAMA,CAAAA,GAAeD,CAAK,CAAA,EAAK,KAAA,CAC7C,SAAA,CAAW,IAAMA,CAAAA,EAAO,EAAA,EAAM,IAChC,CAAA,CAAA,CAUaE,CAAAA,CACXC,CAAAA,EACiC,CACjC,IAAMC,CAAAA,CACJD,CAAAA,CAAQ,eAAA,GAAoB,CAACE,CAA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IA,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 ResolveRelation,\n type Subject,\n} from '@inixiative/permissions';\nimport type { Actor, Authorize, Row } from './types';\n\n// permissions surfaces a cyclic permission graph by throwing; the transitions guard denies (fail\n// closed) so a misconfigured schema terminates cleanly instead of propagating out of the kernel.\nconst CYCLE = /Cycle detected/;\n\nexport type PermissionsAuthorizeOptions<R extends string = string> = {\n /** The permissions rebac schema: `{ bridges?, permissions }`. */\n schema: RebacSchema<R>;\n /**\n * Resolve a hydrated relation field to the resource it points at (the ORM-specific seam).\n * Default: the relation segment name doubles as the resource key. Cross-map bridges are resolved\n * by the engine from `schema.bridges`, not here.\n */\n resolveRelation?: ResolveRelation<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\n// The transitions seam carries no pre-granted (role-derived) permix state, so a direct permix grant\n// always misses and authorization is decided entirely by the schema. The actor supplies only its id\n// (for `{ self }`) and an optional superadmin bypass.\nconst actorPermix = (actor: Actor, isSuperadmin?: (actor: Actor) => boolean): PermixLike => ({\n check: () => false,\n isSuperadmin: () => isSuperadmin?.(actor) ?? false,\n getUserId: () => actor?.id ?? 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, intra-map `rel` walks via `resolveRelation`, cross-map bridge walks, `{ self }`,\n * abac `{ rule }`, boolean terminals, `any`/`all`, per-row `permissionRules` overrides).\n */\nexport const createAuthorize = <R extends string = string>(\n options: PermissionsAuthorizeOptions<R>,\n): ((resource: R) => Authorize) => {\n const resolveRelation: ResolveRelation<R> =\n options.resolveRelation ?? ((_resource, segment) => segment as R);\n const check = createRebacCheck<R>(resolveRelation);\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`, `context`, …) 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 { check as checkRule, resolveBindings, toPrisma } from '@inixiative/json-rules';\nimport { checkPath } from './check';\nimport type {\n Action,\n ActionRule,\n CheckResult,\n PathReason,\n PredicateOptions,\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/**\n * Set query: one OR'd Prisma `where` matching every record currently eligible for `action`\n * (the union of all its paths' `from` predicates). Empty action → match-nothing. Takes the same\n * json-rules `check()` options: `bindings` are resolved into the predicate before compiling, and\n * `now` / `context` reach `toPrisma`, so the set query selects the rows the single check accepts.\n * A guard toPrisma cannot express (a `$.` row ref in an offset or magnitude) throws.\n */\nexport const eligible = (\n rules: TransitionMap,\n resource: string,\n action: string,\n options: PredicateOptions = {},\n): Row => {\n const found = getAction(rules, resource, action);\n const { bindings = {}, ...compile } = options;\n const predicate = resolveBindings(\n { any: found.paths.map((path) => path.from.predicate) },\n bindings,\n );\n // toPrisma always terminates a plan in a WhereStep (and throws on count-based ops,\n // which would need a multi-step plan, since we pass no map/model). Trust that contract.\n const { steps } = toPrisma(predicate, compile);\n return (steps[steps.length - 1] as { where: Row }).where;\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 checkRuleAgainstLens,\n type Lens,\n type LensNarrowing,\n validateRule,\n} from '@inixiative/json-rules';\nimport { actionRuleSchema } from '@inixiative/permissions/actionRuleSchema';\nimport { isSerializableMerge } from './merge';\nimport type { ActionRule, Merge, Side, ToSide, Transition } from './types';\n\nexport type ValidationIssue = { path: string; message: string };\nexport type ValidationResult = { ok: boolean; errors: ValidationIssue[] };\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' });\n return;\n }\n const result = validateRule(predicate);\n for (const issue of result.errors)\n errors.push({ path: `${path}.${issue.path}`, message: issue.message });\n if (lens) {\n const lensCheck = checkRuleAgainstLens(predicate, lens);\n for (const violation of lensCheck.violations)\n errors.push({ path: `${path}.${violation.path}`, message: violation.reason });\n }\n};\n\n// Validate the whole ActionRule against `@inixiative/permissions`' zod schema — the single source of\n// truth for the algebra (boolean terminals, string delegation, `{ rel, action }`, `{ self }`, abac\n// `{ rule }`, `any`/`all`, `null`). A malformed rule yields a structured issue rather than throwing.\nconst validatePermission = (\n rule: ActionRule | undefined,\n errors: ValidationIssue[],\n path: string,\n): void => {\n if (rule === undefined) return; // absent = open\n const parsed = actionRuleSchema.safeParse(rule);\n if (parsed.success) return;\n for (const issue of parsed.error.issues) {\n // A root union failure (zod reports an empty relative path) means none of the ActionRule shapes\n // matched; nested issues keep their zod path + message.\n if (issue.path.length === 0) {\n errors.push({ path, message: 'unrecognized ActionRule shape' });\n } else {\n errors.push({ path: `${path}.${issue.path.join('.')}`, message: issue.message });\n }\n }\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}\"` });\n return;\n }\n if (!ARRAY_KINDS.has(merge.kind))\n errors.push({ path, message: `unknown merge kind \"${merge.kind}\"` });\n else if (!merge.path) errors.push({ path, message: `merge \"${merge.kind}\" requires a \\`path\\`` });\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` });\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 });\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 `checkRuleAgainstLens` when a `lens` is supplied for\n * field/relation scoping); permission shape delegates to `@inixiative/permissions`' `actionRuleSchema`;\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 });\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/registry.ts","../src/serializable.ts","../src/validate.ts"],"names":["CYCLE","actorPermix","actor","isSuperadmin","createAuthorize","options","resolveRelation","_resource","segment","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","eligible","bindings","compile","predicate","bindRule","steps","toPrisma","isSerializable","MERGE_KEYWORDS","ARRAY_KINDS","validatePredicate","errors","lens","issues","validateRule","validateRuleInLens","issue","validatePermission","parsed","actionRuleSchema","validateMerge","validateSide","side","validateTransition"],"mappings":"+MAYA,IAAMA,CAAAA,CAAQ,gBAAA,CAwBRC,CAAAA,CAAc,CAACC,CAAAA,CAAcC,CAAAA,IAA0D,CAC3F,KAAA,CAAO,IAAM,KAAA,CACb,YAAA,CAAc,IAAMA,CAAAA,GAAeD,CAAK,CAAA,EAAK,KAAA,CAC7C,SAAA,CAAW,IAAMA,CAAAA,EAAO,EAAA,EAAM,IAChC,CAAA,CAAA,CAUaE,CAAAA,CACXC,CAAAA,EACiC,CACjC,IAAMC,CAAAA,CACJD,CAAAA,CAAQ,eAAA,GAAoB,CAACE,CAAAA,CAAWC,CAAAA,GAAYA,CAAAA,CAAAA,CAChDC,CAAAA,CAAQC,4BAAAA,CAAoBJ,CAAe,CAAA,CAEjD,OAAQK,CAAAA,EACN,CAACC,CAAAA,CAAMC,CAAAA,CAAQX,CAAAA,GAAU,CACvB,IAAMY,CAAAA,CAASb,CAAAA,CAAYC,CAAAA,CAAOG,CAAAA,CAAQ,YAAY,CAAA,CAChDU,CAAAA,CAAsB,CAA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AAa,CAAA,CAC5DwD,CAAAA,CAAK,QAAA,GAAa,MAAA,GAAc,OAAOA,CAAAA,CAAK,QAAA,EAAa,QAAA,EAAYA,CAAAA,CAAK,QAAA,GAAa,IAAA,CAAA,EACzFX,CAAAA,CAAO,IAAA,CAAK,CACV,IAAA,CAAM,CAAA,EAAG7C,CAAI,CAAA,SAAA,CAAA,CACb,OAAA,CAAS,oDACT,IAAA,CAAM,kBACR,CAAC,CAAA,CACC,OAAA,GAAWwD,CAAAA,EAAMF,CAAAA,CAAcE,CAAAA,CAAK,KAAA,CAAOX,CAAAA,CAAQ,CAAA,EAAG7C,CAAI,CAAA,MAAA,CAAQ,EACxE,CAAA,CASayD,EAAAA,CAAqB,CAChC7C,CAAAA,CACArC,CAAAA,CAA2B,EAAC,GACP,CACrB,IAAMsE,CAAAA,CAA4B,EAAC,CACnC,OAAAU,CAAAA,CAAa3C,CAAAA,EAAY,IAAA,CAAMiC,CAAAA,CAAQ,MAAA,CAAQtE,CAAO,CAAA,CACtDgF,CAAAA,CAAa3C,CAAAA,EAAY,EAAA,CAAIiC,CAAAA,CAAQ,IAAA,CAAMtE,CAAO,CAAA,CAC9CA,CAAAA,CAAQ,mBAAA,EAAuB,CAACiB,CAAAA,CAAoBoB,CAAAA,EAAY,EAAA,EAAI,KAAK,CAAA,EAC3EiC,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 ResolveRelation,\n type Subject,\n} from '@inixiative/permissions';\nimport type { Actor, Authorize, Row } from './types';\n\n// permissions surfaces a cyclic permission graph by throwing; the transitions guard denies (fail\n// closed) so a misconfigured schema terminates cleanly instead of propagating out of the kernel.\nconst CYCLE = /Cycle detected/;\n\nexport type PermissionsAuthorizeOptions<R extends string = string> = {\n /** The permissions rebac schema: `{ bridges?, permissions }`. */\n schema: RebacSchema<R>;\n /**\n * Resolve a hydrated relation field to the resource it points at (the ORM-specific seam).\n * Default: the relation segment name doubles as the resource key. Cross-map bridges are resolved\n * by the engine from `schema.bridges`, not here.\n */\n resolveRelation?: ResolveRelation<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\n// The transitions seam carries no pre-granted (role-derived) permix state, so a direct permix grant\n// always misses and authorization is decided entirely by the schema. The actor supplies only its id\n// (for `{ self }`) and an optional superadmin bypass.\nconst actorPermix = (actor: Actor, isSuperadmin?: (actor: Actor) => boolean): PermixLike => ({\n check: () => false,\n isSuperadmin: () => isSuperadmin?.(actor) ?? false,\n getUserId: () => actor?.id ?? 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, intra-map `rel` walks via `resolveRelation`, cross-map bridge walks, `{ self }`,\n * abac `{ rule }`, boolean terminals, `any`/`all`, per-row `permissionRules` overrides).\n */\nexport const createAuthorize = <R extends string = string>(\n options: PermissionsAuthorizeOptions<R>,\n): ((resource: R) => Authorize) => {\n const resolveRelation: ResolveRelation<R> =\n options.resolveRelation ?? ((_resource, segment) => segment as R);\n const check = createRebacCheck<R>(resolveRelation);\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 { bindRule, check as checkRule, toPrisma } from '@inixiative/json-rules';\nimport { checkPath } from './check';\nimport type {\n Action,\n ActionRule,\n CheckResult,\n PathReason,\n PredicateOptions,\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/**\n * Set query: one Prisma `where` matching every record currently eligible for `action` (the\n * union of all its paths' `from` predicates; a single path compiles to its predicate alone).\n * Empty action → match-nothing. Takes the same\n * json-rules `check()` options: `bindings` are resolved into the predicate before compiling, and\n * `now` reaches `toPrisma`, so the set query selects the rows the single check accepts.\n * A guard toPrisma cannot express (a `$.` row ref in an offset or magnitude) throws.\n */\nexport const eligible = (\n rules: TransitionMap,\n resource: string,\n action: string,\n options: PredicateOptions = {},\n): Row => {\n const found = getAction(rules, resource, action);\n const { bindings = {}, ...compile } = options;\n const predicate = bindRule({ any: found.paths.map((path) => path.from.predicate) }, bindings);\n // toPrisma always terminates a plan in a WhereStep (and throws on count-based ops,\n // which would need a multi-step plan, since we pass no map/model). Trust that contract.\n const { steps } = toPrisma(predicate, compile);\n return (steps[steps.length - 1] as { where: Row }).where;\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 { actionRuleSchema } from '@inixiative/permissions/actionRuleSchema';\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\n// Validate the whole ActionRule against `@inixiative/permissions`' zod schema — the single source of\n// truth for the algebra (boolean terminals, string delegation, `{ rel, action }`, `{ self }`, abac\n// `{ rule }`, `any`/`all`, `null`). A malformed rule yields a structured issue rather than throwing.\nconst validatePermission = (\n rule: ActionRule | undefined,\n errors: ValidationIssue[],\n path: string,\n): void => {\n if (rule === undefined) return; // absent = open\n const parsed = actionRuleSchema.safeParse(rule);\n if (parsed.success) return;\n for (const issue of parsed.error.issues) {\n // A root union failure (zod reports an empty relative path) means none of the ActionRule shapes\n // matched; nested issues keep their zod path + message.\n if (issue.path.length === 0) {\n errors.push({ path, message: 'unrecognized ActionRule shape', code: 'invalid_permission' });\n } else {\n errors.push({\n path: `${path}.${issue.path.join('.')}`,\n message: issue.message,\n code: 'invalid_permission',\n });\n }\n }\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`' `actionRuleSchema`;\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.d.cts CHANGED
@@ -1,8 +1,7 @@
1
1
  import { ActionRule, RebacSchema, ResolveRelation, Subject } from '@inixiative/permissions';
2
2
  export { ActionRule } from '@inixiative/permissions';
3
- import { Condition, CheckOptions, Lens, LensNarrowing } from '@inixiative/json-rules';
4
-
5
- type Row = Record<string, unknown>;
3
+ import { Row, Condition, CheckOptions, Lens, LensNarrowing, ValidationResult } from '@inixiative/json-rules';
4
+ export { Row, ValidationIssue, ValidationResult } from '@inixiative/json-rules';
6
5
 
7
6
  type Actor = ({
8
7
  id?: string | null;
@@ -79,13 +78,10 @@ type AuthorizeOptions = {
79
78
  };
80
79
  /**
81
80
  * json-rules' own `check()` options — `now` / `timeZone` / `weekStart` for relative dates,
82
- * `bindings` for `{ bind }` tokens, `context` for bare paths — with `context` a row, since a
83
- * transition's predicates read rows. Both predicates get them, and {@link eligible} compiles
84
- * with them.
81
+ * `bindings` for `{ bind }` tokens (caller values are binds) — so the same options serve `check()`
82
+ * and {@link eligible}'s `toPrisma`.
85
83
  */
86
- type PredicateOptions = Omit<CheckOptions, 'context'> & {
87
- context?: Row;
88
- };
84
+ type PredicateOptions = CheckOptions;
89
85
  /** A transition check: who acts, and what its predicates evaluate with. */
90
86
  type TransitionOptions = AuthorizeOptions & PredicateOptions;
91
87
 
@@ -122,7 +118,7 @@ declare const createAuthorize: <R extends string = string>(options: PermissionsA
122
118
  * `from`/`to` and predicate/permission are independent slots — so a caller sees the whole
123
119
  * picture. `from.*` reads the current `record`, `to.*` reads the merged `next` record. Returns
124
120
  * `true` when the edge is allowed, else the {@link PathReason}. Omit `authorize` for legality only;
125
- * json-rules' `check()` options (`now`, `bindings`, `context`, …) reach both predicates.
121
+ * json-rules' `check()` options (`now`, `bindings`, …) reach both predicates.
126
122
  */
127
123
  declare const checkPath: <R extends Row>(transition: Transition<R>, record: R, changes?: Partial<R>, options?: TransitionOptions) => true | PathReason;
128
124
 
@@ -159,10 +155,11 @@ declare const checkTransition: (rules: TransitionMap, resource: string, action:
159
155
  */
160
156
  declare const available: (rules: TransitionMap, resource: string, record: Row, options?: TransitionOptions) => string[];
161
157
  /**
162
- * Set query: one OR'd Prisma `where` matching every record currently eligible for `action`
163
- * (the union of all its paths' `from` predicates). Empty action → match-nothing. Takes the same
158
+ * Set query: one Prisma `where` matching every record currently eligible for `action` (the
159
+ * union of all its paths' `from` predicates; a single path compiles to its predicate alone).
160
+ * Empty action → match-nothing. Takes the same
164
161
  * json-rules `check()` options: `bindings` are resolved into the predicate before compiling, and
165
- * `now` / `context` reach `toPrisma`, so the set query selects the rows the single check accepts.
162
+ * `now` reaches `toPrisma`, so the set query selects the rows the single check accepts.
166
163
  * A guard toPrisma cannot express (a `$.` row ref in an offset or magnitude) throws.
167
164
  */
168
165
  declare const eligible: (rules: TransitionMap, resource: string, action: string, options?: PredicateOptions) => Row;
@@ -175,14 +172,6 @@ declare const eligible: (rules: TransitionMap, resource: string, action: string,
175
172
  */
176
173
  declare const isSerializable: (transition: Transition) => boolean;
177
174
 
178
- type ValidationIssue = {
179
- path: string;
180
- message: string;
181
- };
182
- type ValidationResult = {
183
- ok: boolean;
184
- errors: ValidationIssue[];
185
- };
186
175
  type ValidateOptions = {
187
176
  /** Optional field/relation allowlist; passed through to json-rules lens validation per predicate. */
188
177
  lens?: Lens | LensNarrowing;
@@ -192,10 +181,10 @@ type ValidateOptions = {
192
181
  /**
193
182
  * Authoring validation for a single transition — run on save before persisting a tenant config.
194
183
  * Returns structured issues (never throws) on malformed input: predicate validity delegates to
195
- * json-rules (`validateRule`, plus `checkRuleAgainstLens` when a `lens` is supplied for
184
+ * json-rules (`validateRule`, plus `validateRuleInLens` when a `lens` is supplied for
196
185
  * field/relation scoping); permission shape delegates to `@inixiative/permissions`' `actionRuleSchema`;
197
186
  * merge strategy is checked here.
198
187
  */
199
188
  declare const validateTransition: (transition: Transition, options?: ValidateOptions) => ValidationResult;
200
189
 
201
- export { type Action, type Actor, type Authorize, type AuthorizeOptions, type CheckResult, type Include, type Merge, type MergeStrategy, type PathReason, type PermissionsAuthorizeOptions, type PredicateOptions, type Reason, type Row, type Side, type SideReason, type ToSide, type Transition, type TransitionMap, type TransitionOptions, type ValidateOptions, type ValidationIssue, type ValidationResult, applyMerge, available, checkPath, checkTransition, createAuthorize, describe, eligible, isSerializable, isSerializableMerge, validateTransition };
190
+ export { type Action, type Actor, type Authorize, type AuthorizeOptions, type CheckResult, type Include, type Merge, type MergeStrategy, type PathReason, type PermissionsAuthorizeOptions, type PredicateOptions, type Reason, type Side, type SideReason, type ToSide, type Transition, type TransitionMap, type TransitionOptions, type ValidateOptions, applyMerge, available, checkPath, checkTransition, createAuthorize, describe, eligible, isSerializable, isSerializableMerge, validateTransition };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,7 @@
1
1
  import { ActionRule, RebacSchema, ResolveRelation, Subject } from '@inixiative/permissions';
2
2
  export { ActionRule } from '@inixiative/permissions';
3
- import { Condition, CheckOptions, Lens, LensNarrowing } from '@inixiative/json-rules';
4
-
5
- type Row = Record<string, unknown>;
3
+ import { Row, Condition, CheckOptions, Lens, LensNarrowing, ValidationResult } from '@inixiative/json-rules';
4
+ export { Row, ValidationIssue, ValidationResult } from '@inixiative/json-rules';
6
5
 
7
6
  type Actor = ({
8
7
  id?: string | null;
@@ -79,13 +78,10 @@ type AuthorizeOptions = {
79
78
  };
80
79
  /**
81
80
  * json-rules' own `check()` options — `now` / `timeZone` / `weekStart` for relative dates,
82
- * `bindings` for `{ bind }` tokens, `context` for bare paths — with `context` a row, since a
83
- * transition's predicates read rows. Both predicates get them, and {@link eligible} compiles
84
- * with them.
81
+ * `bindings` for `{ bind }` tokens (caller values are binds) — so the same options serve `check()`
82
+ * and {@link eligible}'s `toPrisma`.
85
83
  */
86
- type PredicateOptions = Omit<CheckOptions, 'context'> & {
87
- context?: Row;
88
- };
84
+ type PredicateOptions = CheckOptions;
89
85
  /** A transition check: who acts, and what its predicates evaluate with. */
90
86
  type TransitionOptions = AuthorizeOptions & PredicateOptions;
91
87
 
@@ -122,7 +118,7 @@ declare const createAuthorize: <R extends string = string>(options: PermissionsA
122
118
  * `from`/`to` and predicate/permission are independent slots — so a caller sees the whole
123
119
  * picture. `from.*` reads the current `record`, `to.*` reads the merged `next` record. Returns
124
120
  * `true` when the edge is allowed, else the {@link PathReason}. Omit `authorize` for legality only;
125
- * json-rules' `check()` options (`now`, `bindings`, `context`, …) reach both predicates.
121
+ * json-rules' `check()` options (`now`, `bindings`, …) reach both predicates.
126
122
  */
127
123
  declare const checkPath: <R extends Row>(transition: Transition<R>, record: R, changes?: Partial<R>, options?: TransitionOptions) => true | PathReason;
128
124
 
@@ -159,10 +155,11 @@ declare const checkTransition: (rules: TransitionMap, resource: string, action:
159
155
  */
160
156
  declare const available: (rules: TransitionMap, resource: string, record: Row, options?: TransitionOptions) => string[];
161
157
  /**
162
- * Set query: one OR'd Prisma `where` matching every record currently eligible for `action`
163
- * (the union of all its paths' `from` predicates). Empty action → match-nothing. Takes the same
158
+ * Set query: one Prisma `where` matching every record currently eligible for `action` (the
159
+ * union of all its paths' `from` predicates; a single path compiles to its predicate alone).
160
+ * Empty action → match-nothing. Takes the same
164
161
  * json-rules `check()` options: `bindings` are resolved into the predicate before compiling, and
165
- * `now` / `context` reach `toPrisma`, so the set query selects the rows the single check accepts.
162
+ * `now` reaches `toPrisma`, so the set query selects the rows the single check accepts.
166
163
  * A guard toPrisma cannot express (a `$.` row ref in an offset or magnitude) throws.
167
164
  */
168
165
  declare const eligible: (rules: TransitionMap, resource: string, action: string, options?: PredicateOptions) => Row;
@@ -175,14 +172,6 @@ declare const eligible: (rules: TransitionMap, resource: string, action: string,
175
172
  */
176
173
  declare const isSerializable: (transition: Transition) => boolean;
177
174
 
178
- type ValidationIssue = {
179
- path: string;
180
- message: string;
181
- };
182
- type ValidationResult = {
183
- ok: boolean;
184
- errors: ValidationIssue[];
185
- };
186
175
  type ValidateOptions = {
187
176
  /** Optional field/relation allowlist; passed through to json-rules lens validation per predicate. */
188
177
  lens?: Lens | LensNarrowing;
@@ -192,10 +181,10 @@ type ValidateOptions = {
192
181
  /**
193
182
  * Authoring validation for a single transition — run on save before persisting a tenant config.
194
183
  * Returns structured issues (never throws) on malformed input: predicate validity delegates to
195
- * json-rules (`validateRule`, plus `checkRuleAgainstLens` when a `lens` is supplied for
184
+ * json-rules (`validateRule`, plus `validateRuleInLens` when a `lens` is supplied for
196
185
  * field/relation scoping); permission shape delegates to `@inixiative/permissions`' `actionRuleSchema`;
197
186
  * merge strategy is checked here.
198
187
  */
199
188
  declare const validateTransition: (transition: Transition, options?: ValidateOptions) => ValidationResult;
200
189
 
201
- export { type Action, type Actor, type Authorize, type AuthorizeOptions, type CheckResult, type Include, type Merge, type MergeStrategy, type PathReason, type PermissionsAuthorizeOptions, type PredicateOptions, type Reason, type Row, type Side, type SideReason, type ToSide, type Transition, type TransitionMap, type TransitionOptions, type ValidateOptions, type ValidationIssue, type ValidationResult, applyMerge, available, checkPath, checkTransition, createAuthorize, describe, eligible, isSerializable, isSerializableMerge, validateTransition };
190
+ export { type Action, type Actor, type Authorize, type AuthorizeOptions, type CheckResult, type Include, type Merge, type MergeStrategy, type PathReason, type PermissionsAuthorizeOptions, type PredicateOptions, type Reason, type Side, type SideReason, type ToSide, type Transition, type TransitionMap, type TransitionOptions, type ValidateOptions, applyMerge, available, checkPath, checkTransition, createAuthorize, describe, eligible, isSerializable, isSerializableMerge, validateTransition };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import {createRebacCheck}from'@inixiative/permissions';import {check,resolveBindings,toPrisma,validateRule,checkRuleAgainstLens}from'@inixiative/json-rules';import {mergeWith,cloneDeep,get,set,uniqWith,isEqual}from'lodash-es';import {actionRuleSchema}from'@inixiative/permissions/actionRuleSchema';var $=/Cycle detected/,M=(e,t)=>({check:()=>false,isSuperadmin:()=>t?.(e)??false,getUserId:()=>e?.id??null}),K=e=>{let t=e.resolveRelation??((n,i)=>i),o=createRebacCheck(t);return n=>(i,r,s)=>{let p=M(s,e.isSuperadmin),c={resource:n,record:r,data:e.data?.(r,s)};try{return o(p,e.schema,c,i)}catch(a){if(a instanceof Error&&$.test(a.message))return false;throw a}}};var g=e=>Array.isArray(e)?e:e===void 0?[]:[e],O=(e,t)=>Array.isArray(t)?t:void 0,d=e=>typeof e!="function",h=(e,t,o={})=>{if(typeof e=="function")return e(t,o);let n=e??"spread";if(n==="spread")return {...t,...o};if(n==="deepMerge")return mergeWith(cloneDeep(t),cloneDeep(o),O);let{kind:i,path:r}=n,s=cloneDeep({...t,...o}),p=[...g(get(t,r)),...g(get(o,r))];return set(s,r,i==="appendUnique"?uniqWith(p,isEqual):p),s};var w=e=>typeof e=="string"?e:"predicate not satisfied",b=(e,t,o,n)=>!e||t===void 0?false:!e(t,o,n),A=(e,t,o={},n={})=>{let{actor:i,authorize:r,...s}=n,p=h(e.to.merge,t,o),c={},a=check(e.from.predicate,t,s);a!==true&&(c.predicate=w(a)),b(r,e.from.permission,t,i)&&(c.permission="not authorized");let u={},l=check(e.to.predicate,p,s);l!==true&&(u.predicate=w(l)),b(r,e.to.permission,p,i)&&(u.permission="not authorized");let f={};return (c.predicate||c.permission)&&(f.from=c),(u.predicate||u.permission)&&(f.to=u),f.from||f.to?f: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"},X=e=>e.paths.length===0?"no transition path available":e.paths.length===1?k(e.paths[0]):e.paths.map((t,o)=>`path ${o}: ${k(t)}`).join(" | ");var x=(e,t,o)=>{let n=e[t]?.[o];if(!n)throw new Error(`transition: no action "${o}" registered on resource "${t}"`);return n},oe=(e,t,o,n,i={},r={})=>{let s=x(e,t,o),p=[];for(let c of s.paths){let a=A(c,n,i,r);if(a===true)return true;p.push(a);}return {paths:p}},ne=(e,t,o,n={})=>{let i=e[t];if(!i)return [];let{actor:r,authorize:s,...p}=n,c=(a,u)=>!s||a===void 0||s(a,u,r);return Object.entries(i).filter(([,a])=>a.paths.some(u=>check(u.from.predicate,o,p)===true&&c(u.from.permission,o))).map(([a])=>a)},ie=(e,t,o,n={})=>{let i=x(e,t,o),{bindings:r={},...s}=n,p=resolveBindings({any:i.paths.map(a=>a.from.predicate)},r),{steps:c}=toPrisma(p,s);return c[c.length-1].where};var ae=e=>d(e.to.merge);var N=new Set(["spread","deepMerge"]),_=new Set(["append","appendUnique"]),D=(e,t,o,n)=>{if(e===void 0){t.push({path:o,message:"predicate is required"});return}let i=validateRule(e);for(let r of i.errors)t.push({path:`${o}.${r.path}`,message:r.message});if(n){let r=checkRuleAgainstLens(e,n);for(let s of r.violations)t.push({path:`${o}.${s.path}`,message:s.reason});}},U=(e,t,o)=>{if(e===void 0)return;let n=actionRuleSchema.safeParse(e);if(!n.success)for(let i of n.error.issues)i.path.length===0?t.push({path:o,message:"unrecognized ActionRule shape"}):t.push({path:`${o}.${i.path.join(".")}`,message:i.message});},W=(e,t,o)=>{if(!(e===void 0||typeof e=="function")){if(typeof e=="string"){N.has(e)||t.push({path:o,message:`unknown merge strategy "${e}"`});return}_.has(e.kind)?e.path||t.push({path:o,message:`merge "${e.kind}" requires a \`path\``}):t.push({path:o,message:`unknown merge kind "${e.kind}"`});}},S=(e,t,o,n)=>{if(e===null||typeof e!="object"){t.push({path:o,message:`\`${o}\` side is required`});return}D(e.predicate,t,`${o}.predicate`,n.lens),U(e.permission,t,`${o}.permission`),e.requires!==void 0&&(typeof e.requires!="object"||e.requires===null)&&t.push({path:`${o}.requires`,message:"`requires` must be a Prisma-include-shaped object"}),"merge"in e&&W(e.merge,t,`${o}.merge`);},de=(e,t={})=>{let o=[];return S(e?.from,o,"from",t),S(e?.to,o,"to",t),t.requireSerializable&&!d(e?.to?.merge)&&o.push({path:"to.merge",message:"callback merge is not serializable; use a keyword strategy"}),{ok:o.length===0,errors:o}};export{h as applyMerge,ne as available,A as checkPath,oe as checkTransition,K as createAuthorize,X as describe,ie as eligible,ae as isSerializable,d as isSerializableMerge,de as validateTransition};//# sourceMappingURL=index.js.map
1
+ import {createRebacCheck}from'@inixiative/permissions';import {check,bindRule,toPrisma,validateRule,validateRuleInLens}from'@inixiative/json-rules';import {mergeWith,cloneDeep,get,set,uniqWith,isEqual}from'lodash-es';import {actionRuleSchema}from'@inixiative/permissions/actionRuleSchema';var v=/Cycle detected/,M=(e,t)=>({check:()=>false,isSuperadmin:()=>t?.(e)??false,getUserId:()=>e?.id??null}),K=e=>{let t=e.resolveRelation??((o,n)=>n),i=createRebacCheck(t);return o=>(n,r,a)=>{let p=M(a,e.isSuperadmin),c={resource:o,record:r,data:e.data?.(r,a)};try{return i(p,e.schema,c,n)}catch(s){if(s instanceof Error&&v.test(s.message))return false;throw s}}};var g=e=>Array.isArray(e)?e:e===void 0?[]:[e],O=(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),O);let{kind:n,path:r}=o,a=cloneDeep({...t,...i}),p=[...g(get(t,r)),...g(get(i,r))];return set(a,r,n==="appendUnique"?uniqWith(p,isEqual):p),a};var w=e=>typeof e=="string"?e:"predicate not satisfied",b=(e,t,i,o)=>!e||t===void 0?false:!e(t,i,o),A=(e,t,i={},o={})=>{let{actor:n,authorize:r,...a}=o,p=h(e.to.merge,t,i),c={},s=check(e.from.predicate,t,a);s!==true&&(c.predicate=w(s)),b(r,e.from.permission,t,n)&&(c.permission="not authorized");let u={},m=check(e.to.predicate,p,a);m!==true&&(u.predicate=w(m)),b(r,e.to.permission,p,n)&&(u.permission="not authorized");let d={};return (c.predicate||c.permission)&&(d.from=c),(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"},X=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(" | ");var x=(e,t,i)=>{let o=e[t]?.[i];if(!o)throw new Error(`transition: no action "${i}" registered on resource "${t}"`);return o},ie=(e,t,i,o,n={},r={})=>{let a=x(e,t,i),p=[];for(let c of a.paths){let s=A(c,o,n,r);if(s===true)return true;p.push(s);}return {paths:p}},oe=(e,t,i,o={})=>{let n=e[t];if(!n)return [];let{actor:r,authorize:a,...p}=o,c=(s,u)=>!a||s===void 0||a(s,u,r);return Object.entries(n).filter(([,s])=>s.paths.some(u=>check(u.from.predicate,i,p)===true&&c(u.from.permission,i))).map(([s])=>s)},ne=(e,t,i,o={})=>{let n=x(e,t,i),{bindings:r={},...a}=o,p=bindRule({any:n.paths.map(s=>s.from.predicate)},r),{steps:c}=toPrisma(p,a);return c[c.length-1].where};var ae=e=>f(e.to.merge);var E=new Set(["spread","deepMerge"]),N=new Set(["append","appendUnique"]),D=(e,t,i,o)=>{if(e===void 0){t.push({path:i,message:"predicate is required",code:"missing_predicate"});return}let n=[...validateRule(e).errors,...o?validateRuleInLens(e,o).errors:[]];for(let r of n)t.push({...r,path:`${i}.${r.path}`});},U=(e,t,i)=>{if(e===void 0)return;let o=actionRuleSchema.safeParse(e);if(!o.success)for(let n of o.error.issues)n.path.length===0?t.push({path:i,message:"unrecognized ActionRule shape",code:"invalid_permission"}):t.push({path:`${i}.${n.path.join(".")}`,message:n.message,code:"invalid_permission"});},W=(e,t,i)=>{if(!(e===void 0||typeof e=="function")){if(typeof e=="string"){E.has(e)||t.push({path:i,message:`unknown merge strategy "${e}"`,code:"invalid_merge"});return}N.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"});}},S=(e,t,i,o)=>{if(e===null||typeof e!="object"){t.push({path:i,message:`\`${i}\` side is required`,code:"missing_side"});return}D(e.predicate,t,`${i}.predicate`,o.lens),U(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&&W(e.merge,t,`${i}.merge`);},fe=(e,t={})=>{let i=[];return S(e?.from,i,"from",t),S(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,oe as available,A as checkPath,ie as checkTransition,K as createAuthorize,X as describe,ne as eligible,ae as isSerializable,f as isSerializableMerge,fe 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","resolveRelation","_resource","segment","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","i","getAction","rules","action","found","checkTransition","paths","available","actions","allows","rec","eligible","bindings","compile","predicate","resolveBindings","steps","toPrisma","isSerializable","MERGE_KEYWORDS","ARRAY_KINDS","validatePredicate","errors","lens","validateRule","issue","lensCheck","checkRuleAgainstLens","violation","validatePermission","parsed","actionRuleSchema","validateMerge","validateSide","side","validateTransition"],"mappings":"0SAYA,IAAMA,CAAAA,CAAQ,gBAAA,CAwBRC,CAAAA,CAAc,CAACC,CAAAA,CAAcC,CAAAA,IAA0D,CAC3F,KAAA,CAAO,IAAM,KAAA,CACb,YAAA,CAAc,IAAMA,CAAAA,GAAeD,CAAK,CAAA,EAAK,KAAA,CAC7C,SAAA,CAAW,IAAMA,C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AI,KAAK,CAAA,EAC3EkC,CAAAA,CAAO,IAAA,CAAK,CACV,IAAA,CAAM,UAAA,CACN,OAAA,CAAS,4DACX,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 ResolveRelation,\n type Subject,\n} from '@inixiative/permissions';\nimport type { Actor, Authorize, Row } from './types';\n\n// permissions surfaces a cyclic permission graph by throwing; the transitions guard denies (fail\n// closed) so a misconfigured schema terminates cleanly instead of propagating out of the kernel.\nconst CYCLE = /Cycle detected/;\n\nexport type PermissionsAuthorizeOptions<R extends string = string> = {\n /** The permissions rebac schema: `{ bridges?, permissions }`. */\n schema: RebacSchema<R>;\n /**\n * Resolve a hydrated relation field to the resource it points at (the ORM-specific seam).\n * Default: the relation segment name doubles as the resource key. Cross-map bridges are resolved\n * by the engine from `schema.bridges`, not here.\n */\n resolveRelation?: ResolveRelation<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\n// The transitions seam carries no pre-granted (role-derived) permix state, so a direct permix grant\n// always misses and authorization is decided entirely by the schema. The actor supplies only its id\n// (for `{ self }`) and an optional superadmin bypass.\nconst actorPermix = (actor: Actor, isSuperadmin?: (actor: Actor) => boolean): PermixLike => ({\n check: () => false,\n isSuperadmin: () => isSuperadmin?.(actor) ?? false,\n getUserId: () => actor?.id ?? 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, intra-map `rel` walks via `resolveRelation`, cross-map bridge walks, `{ self }`,\n * abac `{ rule }`, boolean terminals, `any`/`all`, per-row `permissionRules` overrides).\n */\nexport const createAuthorize = <R extends string = string>(\n options: PermissionsAuthorizeOptions<R>,\n): ((resource: R) => Authorize) => {\n const resolveRelation: ResolveRelation<R> =\n options.resolveRelation ?? ((_resource, segment) => segment as R);\n const check = createRebacCheck<R>(resolveRelation);\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`, `context`, …) 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 { check as checkRule, resolveBindings, toPrisma } from '@inixiative/json-rules';\nimport { checkPath } from './check';\nimport type {\n Action,\n ActionRule,\n CheckResult,\n PathReason,\n PredicateOptions,\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/**\n * Set query: one OR'd Prisma `where` matching every record currently eligible for `action`\n * (the union of all its paths' `from` predicates). Empty action → match-nothing. Takes the same\n * json-rules `check()` options: `bindings` are resolved into the predicate before compiling, and\n * `now` / `context` reach `toPrisma`, so the set query selects the rows the single check accepts.\n * A guard toPrisma cannot express (a `$.` row ref in an offset or magnitude) throws.\n */\nexport const eligible = (\n rules: TransitionMap,\n resource: string,\n action: string,\n options: PredicateOptions = {},\n): Row => {\n const found = getAction(rules, resource, action);\n const { bindings = {}, ...compile } = options;\n const predicate = resolveBindings(\n { any: found.paths.map((path) => path.from.predicate) },\n bindings,\n );\n // toPrisma always terminates a plan in a WhereStep (and throws on count-based ops,\n // which would need a multi-step plan, since we pass no map/model). Trust that contract.\n const { steps } = toPrisma(predicate, compile);\n return (steps[steps.length - 1] as { where: Row }).where;\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 checkRuleAgainstLens,\n type Lens,\n type LensNarrowing,\n validateRule,\n} from '@inixiative/json-rules';\nimport { actionRuleSchema } from '@inixiative/permissions/actionRuleSchema';\nimport { isSerializableMerge } from './merge';\nimport type { ActionRule, Merge, Side, ToSide, Transition } from './types';\n\nexport type ValidationIssue = { path: string; message: string };\nexport type ValidationResult = { ok: boolean; errors: ValidationIssue[] };\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' });\n return;\n }\n const result = validateRule(predicate);\n for (const issue of result.errors)\n errors.push({ path: `${path}.${issue.path}`, message: issue.message });\n if (lens) {\n const lensCheck = checkRuleAgainstLens(predicate, lens);\n for (const violation of lensCheck.violations)\n errors.push({ path: `${path}.${violation.path}`, message: violation.reason });\n }\n};\n\n// Validate the whole ActionRule against `@inixiative/permissions`' zod schema — the single source of\n// truth for the algebra (boolean terminals, string delegation, `{ rel, action }`, `{ self }`, abac\n// `{ rule }`, `any`/`all`, `null`). A malformed rule yields a structured issue rather than throwing.\nconst validatePermission = (\n rule: ActionRule | undefined,\n errors: ValidationIssue[],\n path: string,\n): void => {\n if (rule === undefined) return; // absent = open\n const parsed = actionRuleSchema.safeParse(rule);\n if (parsed.success) return;\n for (const issue of parsed.error.issues) {\n // A root union failure (zod reports an empty relative path) means none of the ActionRule shapes\n // matched; nested issues keep their zod path + message.\n if (issue.path.length === 0) {\n errors.push({ path, message: 'unrecognized ActionRule shape' });\n } else {\n errors.push({ path: `${path}.${issue.path.join('.')}`, message: issue.message });\n }\n }\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}\"` });\n return;\n }\n if (!ARRAY_KINDS.has(merge.kind))\n errors.push({ path, message: `unknown merge kind \"${merge.kind}\"` });\n else if (!merge.path) errors.push({ path, message: `merge \"${merge.kind}\" requires a \\`path\\`` });\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` });\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 });\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 `checkRuleAgainstLens` when a `lens` is supplied for\n * field/relation scoping); permission shape delegates to `@inixiative/permissions`' `actionRuleSchema`;\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 });\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/registry.ts","../src/serializable.ts","../src/validate.ts"],"names":["CYCLE","actorPermix","actor","isSuperadmin","createAuthorize","options","resolveRelation","_resource","segment","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","eligible","bindings","compile","predicate","bindRule","steps","toPrisma","isSerializable","MERGE_KEYWORDS","ARRAY_KINDS","validatePredicate","errors","lens","issues","validateRule","validateRuleInLens","issue","validatePermission","parsed","actionRuleSchema","validateMerge","validateSide","side","validateTransition"],"mappings":"iSAYA,IAAMA,CAAAA,CAAQ,gBAAA,CAwBRC,CAAAA,CAAc,CAACC,CAAAA,CAAcC,CAAAA,IAA0D,CAC3F,KAAA,CAAO,IAAM,KAAA,CACb,YAAA,CAAc,IAAMA,CAAAA,GAAeD,CAAK,CAAA,EAAK,KAAA,CAC7C,SAAA,CAAW,IAAMA,CAAAA,EAAO,EAAA,EAAM,IAChC,CAAA,CAAA,CAUaE,CAAAA,CACXC,CAAAA,EACiC,CACjC,IAAMC,CAAAA,CACJD,CAAAA,CAAQ,eAAA,GAAoB,CAACE,CAAAA,CAAWC,CAAAA,GAAYA,CAAAA,CAAAA,CAChDC,CAAAA,CAAQC,gBAAAA,CAAoBJ,CAAe,CAAA,CAEjD,OAAQK,CAAAA,EACN,CAACC,CAAAA,CAAMC,CAAAA,C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Q,IAAI,CAAA,CAC3E4E,CAAAA,CAAmBK,CAAAA,CAAK,UAAA,CAAYX,CAAAA,CAAQ,CAAA,EAAG7C,CAAI,CAAA,WAAA,CAAa,CAAA,CAC5DwD,CAAAA,CAAK,QAAA,GAAa,MAAA,GAAc,OAAOA,CAAAA,CAAK,QAAA,EAAa,QAAA,EAAYA,CAAAA,CAAK,QAAA,GAAa,IAAA,CAAA,EACzFX,CAAAA,CAAO,IAAA,CAAK,CACV,IAAA,CAAM,CAAA,EAAG7C,CAAI,CAAA,SAAA,CAAA,CACb,OAAA,CAAS,oDACT,IAAA,CAAM,kBACR,CAAC,CAAA,CACC,OAAA,GAAWwD,CAAAA,EAAMF,CAAAA,CAAcE,CAAAA,CAAK,KAAA,CAAOX,CAAAA,CAAQ,CAAA,EAAG7C,CAAI,CAAA,MAAA,CAAQ,EACxE,CAAA,CASayD,EAAAA,CAAqB,CAChC7C,CAAAA,CACArC,CAAAA,CAA2B,EAAC,GACP,CACrB,IAAMsE,CAAAA,CAA4B,EAAC,CACnC,OAAAU,CAAAA,CAAa3C,CAAAA,EAAY,IAAA,CAAMiC,CAAAA,CAAQ,MAAA,CAAQtE,CAAO,CAAA,CACtDgF,CAAAA,CAAa3C,CAAAA,EAAY,EAAA,CAAIiC,CAAAA,CAAQ,IAAA,CAAMtE,CAAO,CAAA,CAC9CA,CAAAA,CAAQ,mBAAA,EAAuB,CAACiB,CAAAA,CAAoBoB,CAAAA,EAAY,EAAA,EAAI,KAAK,CAAA,EAC3EiC,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 ResolveRelation,\n type Subject,\n} from '@inixiative/permissions';\nimport type { Actor, Authorize, Row } from './types';\n\n// permissions surfaces a cyclic permission graph by throwing; the transitions guard denies (fail\n// closed) so a misconfigured schema terminates cleanly instead of propagating out of the kernel.\nconst CYCLE = /Cycle detected/;\n\nexport type PermissionsAuthorizeOptions<R extends string = string> = {\n /** The permissions rebac schema: `{ bridges?, permissions }`. */\n schema: RebacSchema<R>;\n /**\n * Resolve a hydrated relation field to the resource it points at (the ORM-specific seam).\n * Default: the relation segment name doubles as the resource key. Cross-map bridges are resolved\n * by the engine from `schema.bridges`, not here.\n */\n resolveRelation?: ResolveRelation<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\n// The transitions seam carries no pre-granted (role-derived) permix state, so a direct permix grant\n// always misses and authorization is decided entirely by the schema. The actor supplies only its id\n// (for `{ self }`) and an optional superadmin bypass.\nconst actorPermix = (actor: Actor, isSuperadmin?: (actor: Actor) => boolean): PermixLike => ({\n check: () => false,\n isSuperadmin: () => isSuperadmin?.(actor) ?? false,\n getUserId: () => actor?.id ?? 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, intra-map `rel` walks via `resolveRelation`, cross-map bridge walks, `{ self }`,\n * abac `{ rule }`, boolean terminals, `any`/`all`, per-row `permissionRules` overrides).\n */\nexport const createAuthorize = <R extends string = string>(\n options: PermissionsAuthorizeOptions<R>,\n): ((resource: R) => Authorize) => {\n const resolveRelation: ResolveRelation<R> =\n options.resolveRelation ?? ((_resource, segment) => segment as R);\n const check = createRebacCheck<R>(resolveRelation);\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 { bindRule, check as checkRule, toPrisma } from '@inixiative/json-rules';\nimport { checkPath } from './check';\nimport type {\n Action,\n ActionRule,\n CheckResult,\n PathReason,\n PredicateOptions,\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/**\n * Set query: one Prisma `where` matching every record currently eligible for `action` (the\n * union of all its paths' `from` predicates; a single path compiles to its predicate alone).\n * Empty action → match-nothing. Takes the same\n * json-rules `check()` options: `bindings` are resolved into the predicate before compiling, and\n * `now` reaches `toPrisma`, so the set query selects the rows the single check accepts.\n * A guard toPrisma cannot express (a `$.` row ref in an offset or magnitude) throws.\n */\nexport const eligible = (\n rules: TransitionMap,\n resource: string,\n action: string,\n options: PredicateOptions = {},\n): Row => {\n const found = getAction(rules, resource, action);\n const { bindings = {}, ...compile } = options;\n const predicate = bindRule({ any: found.paths.map((path) => path.from.predicate) }, bindings);\n // toPrisma always terminates a plan in a WhereStep (and throws on count-based ops,\n // which would need a multi-step plan, since we pass no map/model). Trust that contract.\n const { steps } = toPrisma(predicate, compile);\n return (steps[steps.length - 1] as { where: Row }).where;\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 { actionRuleSchema } from '@inixiative/permissions/actionRuleSchema';\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\n// Validate the whole ActionRule against `@inixiative/permissions`' zod schema — the single source of\n// truth for the algebra (boolean terminals, string delegation, `{ rel, action }`, `{ self }`, abac\n// `{ rule }`, `any`/`all`, `null`). A malformed rule yields a structured issue rather than throwing.\nconst validatePermission = (\n rule: ActionRule | undefined,\n errors: ValidationIssue[],\n path: string,\n): void => {\n if (rule === undefined) return; // absent = open\n const parsed = actionRuleSchema.safeParse(rule);\n if (parsed.success) return;\n for (const issue of parsed.error.issues) {\n // A root union failure (zod reports an empty relative path) means none of the ActionRule shapes\n // matched; nested issues keep their zod path + message.\n if (issue.path.length === 0) {\n errors.push({ path, message: 'unrecognized ActionRule shape', code: 'invalid_permission' });\n } else {\n errors.push({\n path: `${path}.${issue.path.join('.')}`,\n message: issue.message,\n code: 'invalid_permission',\n });\n }\n }\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`' `actionRuleSchema`;\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.2.0",
3
+ "version": "0.4.0",
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",
@@ -18,7 +18,7 @@
18
18
  "lint": "biome check .",
19
19
  "format": "biome format --write .",
20
20
  "check": "bun run typecheck && bun run lint && bun run test",
21
- "prepare": "lefthook install",
21
+ "prepare": "if git rev-parse --git-dir >/dev/null 2>&1; then lefthook install; fi",
22
22
  "prepublishOnly": "bun run check && bun run build"
23
23
  },
24
24
  "keywords": [
@@ -41,7 +41,7 @@
41
41
  },
42
42
  "devDependencies": {
43
43
  "@biomejs/biome": "2.5.2",
44
- "@inixiative/config": "^0.5.47",
44
+ "@inixiative/config": "^0.5.61",
45
45
  "@types/bun": "1.4.2",
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": "^2.27.0",
61
- "@inixiative/permissions": "^0.3.4",
60
+ "@inixiative/json-rules": "^3.4.0",
61
+ "@inixiative/permissions": "^0.4.0",
62
62
  "lodash-es": "^4.18.1",
63
63
  "zod": "^4.4.3"
64
64
  },