import{buildOr as t,buildAnd as n,CompoundCondition as r}from"@ucast/mongo2js";function e(t){return Array.isArray(t)?t:[t]}const o=new Set(["__proto__","constructor","prototype"]);function i(t,n,r){let e=t;let i=n;if(n.indexOf(".")!==-1){const r=n.split(".");i=r.pop();e=r.reduce((t,n)=>{if(o.has(n))return t;t[n]=t[n]||{};return t[n]},t)}if(!o.has(i))e[i]=r}const s=t=>Array.isArray(t)?t.join(","):t;function u(t,n){return t.map(t=>{const r=[s(t.action||t.actions),typeof n==="function"?e(t.subject).map(n).join(","):s(t.subject),t.conditions||0,t.inverted?1:0,t.fields?s(t.fields):0,t.reason||""];while(r.length>0&&!r[r.length-1])r.pop();return r})}function c(t,n){return t.map(([t,r,e,o,i,s])=>{const u=r.split(",");const c={inverted:!!o,action:t.split(","),subject:typeof n==="function"?u.map(n):u};if(e)c.conditions=e;if(i)c.fields=i.split(",");if(s)c.reason=s;return c})}function f(t,n,r,e){const o=t.detectSubjectType(r);const i=t.possibleRulesFor(n,o);const s=new Set;const u=s.delete.bind(s);const c=s.add.bind(s);let f=i.length;while(f--){const t=i[f];if(t.matchesConditions(r)){const n=t.inverted?u:c;e.fieldsFrom(t).forEach(n)}}return Array.from(s)}class l{constructor(t,n,r){this.t=t;this.o=n;this.i=r}ofType(t){return f(this.t,this.o,t,{fieldsFrom:this.u(t)})}of(t){return f(this.t,this.o,t,{fieldsFrom:this.u(this.t.detectSubjectType(t))})}u(t){return n=>n.fields||this.i(t)}}function h(t,n,r){return t.rulesFor(n,r).reduce((t,n)=>{if(n.inverted||!n.conditions)return t;return Object.keys(n.conditions).reduce((t,r)=>{const e=n.conditions[r];if(!e||e.constructor!==Object)i(t,r,e);return t},t)},{})}function a(t,n,r,e){const o=[];const i=[];const s=t.rulesFor(n,r);for(let t=0;t<s.length;t++){const n=s[t];const r=n.inverted?o:i;if(!n.conditions)if(n.inverted)break;else return o.length?{$and:o}:{};else r.push(e(n))}if(!i.length)return null;return o.length?{$or:i,$and:o}:{$or:i}}function p(t){if(!t.ast)throw new Error(`Ability rule "${JSON.stringify(t)}" does not have "ast" property. So, cannot be used to generate AST`);return t.inverted?new r("not",[t.ast]):t.ast}function y(r,e,o){const i=a(r,e,o,p);if(i===null)return null;if(!i.$and)return i.$or?t(i.$or):n([]);if(i.$or)i.$and.push(t(i.$or));return n(i.$and)}export{l as AccessibleFields,u as packRules,f as permittedFieldsOf,y as rulesToAST,h as rulesToFields,a as rulesToQuery,c as unpackRules};
//# sourceMappingURL=index.mjs.map
