@inixiative/json-rules 2.18.0 → 2.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
${t.join(`
|
|
3
3
|
`)}`)},xc=(e,t="fieldMap")=>{ui({maps:{[t]:e}});};var Or=e=>"model"in e,Sr=e=>{let t=new Set,r=e;for(;!Or(r);){if(t.has(r))throw new Error("cycle detected in narrowing parent chain");t.add(r),r=r.parent;}return r},qe=e=>{let t=[],r=new Set,n=e;for(;!Or(n);){if(r.has(n))throw new Error("cycle detected in narrowing parent chain");r.add(n),t.unshift(n),n=n.parent;}return t},L=(e,t)=>{if(e.kind==="object")return {mapName:t,modelName:e.type};if(e.kind==="bridge"){let[r,n]=e.type.includes(":")?e.type.split(":"):[t,e.type];return {mapName:r,modelName:n}}return null};var wt=e=>e===void 0?void 0:Array.isArray(e)?e:[e],Jr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&("where"in e||"label"in e||"groupBy"in e),Ae=e=>{if(Jr(e))return e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===0)throw new Error("sources: {} is not a Condition \u2014 use `true` for an unconstrained source");return {where:e}},j=e=>{let t=Sr(e),r=e.maps===t.maps?[]:qe(e);return {lens:t,chain:r}},_t=(e,t)=>e===null?new Set(t):new Set(t.filter(r=>e.has(r))),Zr=e=>{if(!e.picks)return;if(!("relations"in e)||!e.relations)return e.picks;let t=[...e.picks];for(let r of Object.keys(e.relations))t.includes(r)||t.push(r);return t},bc=(e,t)=>{let r=Zr(t);if(r&&(e.picks=_t(e.picks,r)),t.omits)for(let n of t.omits)e.omits.add(n);},pi=(e,t,r)=>{e.set(t,_t(e.get(t)??null,r));},di=(e,t,r)=>{let n=e.get(t)??new Set;for(let o of r)n.add(o);e.set(t,n);},vc=(e,t,r)=>{if(r.enumPicks)for(let[n,o]of Object.entries(r.enumPicks))pi(e,n,o);if(r.enumOmits)for(let[n,o]of Object.entries(r.enumOmits))di(t,n,o);},Oc=(e,t)=>{if(bc(e,t),t.where!==void 0&&e.whereClauses.push(t.where),t.sources)for(let[r,n]of Object.entries(t.sources)){let o=Ae(n),a=e.sources.get(r)??[];o.where!==void 0&&a.push(o.where),e.sources.set(r,a),o.label!==void 0&&e.sourceLabels.set(r,o.label);let i=wt(o.groupBy);i!==void 0&&e.sourceGroupBys.set(r,i);}},G=(e,t,r,n)=>{let o={picks:null,omits:new Set,enumValuesByField:new Map,whereClauses:[],sources:new Map,sourceLabels:new Map,sourceGroupBys:new Map,relations:new Map},a=e.lens.maps[t],i=a?.models[r];if(!i)return o;let s=new Map,l=new Map,f=new Map,m=new Map,p=u=>{Oc(o,u),vc(s,l,u);};for(let u of e.chain){let d=u.mapDefaults?.[t];if(d){let y=d.models?.[r];y&&p(y);for(let[g,w]of Object.entries(d.enums??{}))w.picks&&pi(f,g,w.picks),w.omits&&di(m,g,w.omits);}let c=u.root;if(n.length===0){if(t===e.lens.mapName&&r===e.lens.model&&c){p(c);for(let[y,g]of Object.entries(c.relations??{}))o.relations.set(y,g);}}else {for(let y of n)if(c=c?.relations?.[y],!c)break;if(c){p(c);for(let[y,g]of Object.entries(c.relations??{}))o.relations.set(y,g);}}}for(let[u,d]of Object.entries(i.fields)){let c=d.kind==="enum",g=d.options?.map(x=>x.value)??(c?d.values??a?.enums?.[d.type]:d.values);if(!g)continue;let w=g;if(c){let x=f.get(d.type),$=m.get(d.type);x&&(w=w.filter(M=>x.has(M))),$&&(w=w.filter(M=>!$.has(M)));}let v=s.get(u),b=l.get(u);v&&(w=w.filter(x=>v.has(x))),b&&(w=w.filter(x=>!b.has(x))),o.enumValuesByField.set(u,w);}return o},Re=(e,t)=>!(e.omits.has(t)||e.picks!==null&&!e.picks.has(t)),mi=(e,t)=>e.enumValuesByField.get(t)??null,ke=(e,t,r,n,o)=>{let a=o.split("."),i=t,s=r,l=[...n],f=[];for(let m=0;m<a.length;m++){let u=e.lens.maps[i]?.models[s];if(!u)return null;let d=G(e,i,s,l),c=a[m];if(!Re(d,c))return null;let y=u.fields[c];if(!y)return null;if(y.kind==="scalar"&&y.type==="Json"&&m<a.length-1)return {mapName:i,modelName:s,relPath:l,entry:y,hopEffects:f,terminalEffect:d,terminalFieldName:c};if(m===a.length-1)return {mapName:i,modelName:s,relPath:l,entry:y,hopEffects:f,terminalEffect:d,terminalFieldName:c};f.push(d);let g=L(y,i);if(!g)return null;l=[...l,c],i=g.mapName,s=g.modelName;}return null};var Yr=(e,t)=>t.length===0?e:{all:[...t,e]},Te=(e,t)=>{if(typeof e=="boolean")return e;if("all"in e)return {...e,all:e.all.map(r=>Te(r,t))};if("any"in e)return {...e,any:e.any.map(r=>Te(r,t))};if("if"in e)return {...e,if:Te(e.if,t),then:Te(e.then,t),else:e.else!==void 0?Te(e.else,t):e.else};if("field"in e&&typeof e.field=="string"&&e.field!==""){if("path"in e&&e.path!==void 0)throw new Error(`applyLens: cannot re-root a relation grant with a path reference ('${String(e.path)}') under '${t}'. Author the grant without 'path', or anchor it at the relation itself.`);if("condition"in e&&e.condition!==void 0)throw new Error(`applyLens: cannot re-root a relation grant with a nested array/aggregate condition on '${e.field}' under '${t}'. Anchor such grants at the relation's own model.`);return {...e,field:`${t}.${e.field}`}}throw new Error(`applyLens: cannot re-root a relation grant of unknown shape under '${t}'`)},ci=(e,t)=>{let r=[];for(let n of t){let o=G(e,n.map,n.model,n.relPath);if(o.whereClauses.length!==0){if(n.isList)throw new Error(`applyLens: cannot enforce a to-many relation grant on '${n.prefix}' without an arrayOperator condition to anchor it (row-scoped). Traverse '${n.prefix}' via an array operator (any/all/none/...) so the grant can be injected safely.`);for(let a of o.whereClauses)r.push(Te(a,n.prefix));}}return r},Sc=(e,t)=>({all:[t,e]}),Ie=(e,t,r,n,o)=>{if(typeof e=="boolean")return e;if("all"in e)return {...e,all:e.all.map(a=>Ie(a,t,r,n,o))};if("any"in e)return {...e,any:e.any.map(a=>Ie(a,t,r,n,o))};if("if"in e)return {...e,if:Ie(e.if,t,r,n,o),then:Ie(e.then,t,r,n,o),else:e.else!==void 0?Ie(e.else,t,r,n,o):e.else};if("field"in e&&typeof e.field=="string"&&e.field!==""){if(!t.lens.maps[r]?.models[n])return e;let s=e.field.split("."),l=r,f=n,m=[...o],p=false,u=[];for(let d=0;d<s.length;d++){let c=t.lens.maps[l]?.models[f];if(!c)break;let y=c.fields[s[d]];if(!y)break;let g=d===s.length-1;if(y.kind!=="object"&&y.kind!=="bridge")break;let w=L(y,l);if(!w)break;m=[...m,s[d]],l=w.mapName,f=w.modelName,u.push({map:l,model:f,relPath:[...m],prefix:s.slice(0,d+1).join("."),isList:y.isList===true}),g&&(p=true);}if("condition"in e&&e.condition!==void 0&&p){let d=G(t,l,f,m),c=Ie(e.condition,t,l,f,m),y="arrayOperator"in e?e.arrayOperator:void 0,g=[];for(let b of d.whereClauses)y===O.all?g.push(b):y?c=Sc(c,b):c={all:[b,c]};let w=e.filter,v=g.length?{...e,condition:c,filter:w!==void 0?{all:[w,...g]}:g.length===1?g[0]:{all:g}}:{...e,condition:c};return Yr(v,ci(t,u.slice(0,-1)))}return Yr(e,ci(t,u))}return e},$c=(e,t)=>{let r=j(t),n=G(r,r.lens.mapName,r.lens.model,[]),o=Ie(e,r,r.lens.mapName,r.lens.model,[]);return Yr(o,n.whereClauses)};var en="parent:",tn=e=>e.startsWith(en),yi=e=>tn(e)?e.slice(en.length):e,Xr=e=>{let t=[];e.where!==void 0&&t.push(e.where);for(let r of Object.values(e.sources??{})){let n=Ae(r).where;n!==void 0&&t.push(n);}if("relations"in e&&e.relations)for(let r of Object.values(e.relations))t.push(...Xr(r));return t},rn=e=>{let t=[];e.root&&t.push(...Xr(e.root));for(let r of Object.values(e.mapDefaults??{}))for(let n of Object.values(r.models??{}))t.push(...Xr(n));return t},gi=e=>{let t=new Set;for(let r of rn(e))for(let n of Ut(r))tn(n)||t.add(n);return t},Ec=e=>{let t=new Set;for(let r of qe(e))for(let n of rn(r))for(let o of Ut(n))t.add(yi(o));return t},nn=(e,t)=>{let r={...e};if(e.where!==void 0&&(r.where=J(e.where,t)),e.sources){let n={};for(let[o,a]of Object.entries(e.sources))Jr(a)?n[o]=a.where!==void 0?{...a,where:J(a.where,t)}:a:n[o]=J(a,t);r.sources=n;}if("relations"in e&&e.relations){let n={};for(let[o,a]of Object.entries(e.relations))n[o]=nn(a,t);r.relations=n;}return r},Ac=(e,t)=>{let r={};for(let[n,o]of Object.entries(e)){let a={...o};if(o.models){let i={};for(let[s,l]of Object.entries(o.models))i[s]=nn(l,t);a.models=i;}r[n]=a;}return r},hi=(e,t)=>{if(Or(e))return e;let r={...t};for(let[n,o]of Object.entries(t))r[`${en}${n}`]=o;return {...e,parent:hi(e.parent,t),root:e.root?nn(e.root,r):void 0,mapDefaults:e.mapDefaults?Ac(e.mapDefaults,r):void 0}},on=e=>{let t=[],r=new Set;for(let o of qe(e.parent))for(let a of gi(o))r.add(a);for(let o of gi(e))r.has(o)&&t.push(`bind name '${o}' already declared by an ancestor narrowing \u2014 rename it, or reference the inherited one as 'parent:${o}'`);let n=new Set;for(let o of rn(e))for(let a of Ut(o))tn(a)&&n.add(yi(a));for(let o of n)r.has(o)||t.push(`bind 'parent:${o}' references an inherited binding no ancestor declares`);return t};var Rc=e=>{if(e.path!==void 0)return null;let t=e.value;return t===void 0?null:Array.isArray(t)?t:[t]},Ce=(e,t,r,n,o,a)=>{if(typeof e=="boolean")return;if("all"in e){for(let d of e.all)Ce(d,t,r,n,o,a);return}if("any"in e){for(let d of e.any)Ce(d,t,r,n,o,a);return}if("if"in e){Ce(e.if,t,r,n,o,a),Ce(e.then,t,r,n,o,a),e.else!==void 0&&Ce(e.else,t,r,n,o,a);return}let i=r,s=n,l=o,f=null,m=false,p=null,u=null;if("field"in e&&typeof e.field=="string"&&e.field!==""){let d=ke(t,r,n,o,e.field);if(!d){a.push({path:e.field,reason:"path does not resolve through the narrowed lens"});return}if(f=d.terminalFieldName,m=d.entry.kind==="enum",p=d.entry.type,u=mi(d.terminalEffect,f),d.entry.kind==="object"||d.entry.kind==="bridge"){let c=d.entry.kind==="object"?{mapName:d.mapName,modelName:d.entry.type}:{mapName:d.entry.type.split(":")[0]??d.mapName,modelName:d.entry.type.split(":")[1]??d.entry.type};i=c.mapName,s=c.modelName,l=[...d.relPath,f];}}if("path"in e&&typeof e.path=="string"&&e.path!==""){let d=e.path.startsWith("$."),c=d?e.path.slice(2):e.path;(d?ke(t,r,n,o,c):ke(t,t.lens.mapName,t.lens.model,[],c))||a.push({path:e.path,reason:"path (comparison ref) does not resolve through the narrowed lens"});}if("filter"in e&&e.filter!==void 0&&Ce(e.filter,t,i,s,l,a),"orderBy"in e&&Array.isArray(e.orderBy))for(let d of e.orderBy)d&&typeof d.field=="string"&&d.field!==""&&(ke(t,i,s,l,d.field)||a.push({path:d.field,reason:"orderBy field does not resolve through the narrowed lens"}));if(u&&"operator"in e&&f){let d=Rc(e);if(d){let c=new Set(u),y=m?`enum '${p}'`:`field '${f}'`;for(let g of d)typeof g=="string"&&!c.has(g)&&a.push({path:f,reason:`value '${g}' is not in the allowed set for ${y} (allowed: ${[...c].join(", ")})`});}}if("aggregate"in e&&typeof e.aggregate=="object"&&e.aggregate!==null&&typeof e.aggregate.field=="string"&&e.aggregate.field!==""){let d=e.aggregate.field;ke(t,i,s,l,d)||a.push({path:d,reason:"aggregate.field does not resolve through the narrowed lens"});}"condition"in e&&e.condition!==void 0&&Ce(e.condition,t,i,s,l,a);},an=(e,t)=>{let r=j(t),n=[];return Ce(e,r,r.lens.mapName,r.lens.model,[],n),G(r,r.lens.mapName,r.lens.model,[]),{ok:n.length===0,violations:n}};var kc=e=>({...Qr({maps:e.maps,bridges:e.bridges}),mapName:e.mapName,model:e.model});var Ar={String:"String",Boolean:"Boolean",Int:"Int",BigInt:"BigInt",Float:"Float",Decimal:"Decimal",DateTime:"DateTime",Json:"Json",Bytes:"Bytes",Enum:"Enum"},Tc=["Int","Float","Decimal","BigInt"],xt=["String",...Tc,"DateTime"],bt=["String"],$r=["String","Boolean","Int","BigInt","Float","Decimal","DateTime","Enum"],sn=Object.values(Ar),wi=sn,ZA={check:"check",toPrisma:"toPrisma",toSql:"toSql"},C=["check","toPrisma","toSql"],vt=["check","toPrisma"],Er=["check","toSql"],YA={none:"none",scalar:"scalar",ordered:"ordered",array:"array",string:"string",pattern:"pattern",range:"range",dateValue:"dateValue",dateRange:"dateRange",dateWindow:"dateWindow",dayList:"dayList",count:"count",predicate:"predicate"},oe={[h.equals]:{kinds:$r,targets:C,valueShape:"scalar"},[h.notEquals]:{kinds:$r,targets:C,valueShape:"scalar"},[h.lessThan]:{kinds:xt,targets:C,valueShape:"ordered"},[h.lessThanEquals]:{kinds:xt,targets:C,valueShape:"ordered"},[h.greaterThan]:{kinds:xt,targets:C,valueShape:"ordered"},[h.greaterThanEquals]:{kinds:xt,targets:C,valueShape:"ordered"},[h.in]:{kinds:$r,targets:C,valueShape:"array"},[h.notIn]:{kinds:$r,targets:C,valueShape:"array"},[h.contains]:{kinds:bt,targets:C,valueShape:"string"},[h.notContains]:{kinds:bt,targets:C,valueShape:"string"},[h.startsWith]:{kinds:bt,targets:C,valueShape:"string"},[h.endsWith]:{kinds:bt,targets:C,valueShape:"string"},[h.matches]:{kinds:bt,targets:Er,valueShape:"pattern"},[h.notMatches]:{kinds:bt,targets:Er,valueShape:"pattern"},[h.between]:{kinds:xt,targets:C,valueShape:"range"},[h.notBetween]:{kinds:xt,targets:C,valueShape:"range"},[h.isEmpty]:{kinds:wi,targets:C,valueShape:"none"},[h.notEmpty]:{kinds:wi,targets:C,valueShape:"none"},[h.exists]:{kinds:sn,targets:C,valueShape:"none"},[h.notExists]:{kinds:sn,targets:C,valueShape:"none"}},Me={[E.before]:{kinds:["DateTime"],targets:C,valueShape:"dateValue",acceptsExpr:true},[E.after]:{kinds:["DateTime"],targets:C,valueShape:"dateValue",acceptsExpr:true},[E.onOrBefore]:{kinds:["DateTime"],targets:C,valueShape:"dateValue",acceptsExpr:true},[E.onOrAfter]:{kinds:["DateTime"],targets:C,valueShape:"dateValue",acceptsExpr:true},[E.within]:{kinds:["DateTime"],targets:C,valueShape:"dateWindow",acceptsExpr:true},[E.between]:{kinds:["DateTime"],targets:C,valueShape:"dateRange",acceptsExpr:true},[E.notBetween]:{kinds:["DateTime"],targets:C,valueShape:"dateRange",acceptsExpr:true},[E.dayIn]:{kinds:["DateTime"],targets:Er,valueShape:"dayList",acceptsExpr:false},[E.dayNotIn]:{kinds:["DateTime"],targets:Er,valueShape:"dayList",acceptsExpr:false}},Pe={[O.all]:{targets:vt,valueShape:"predicate"},[O.any]:{targets:vt,valueShape:"predicate"},[O.none]:{targets:vt,valueShape:"predicate"},[O.atLeast]:{targets:vt,valueShape:"count"},[O.atMost]:{targets:vt,valueShape:"count"},[O.exactly]:{targets:vt,valueShape:"count"},[O.empty]:{targets:C,valueShape:"none"},[O.notEmpty]:{targets:C,valueShape:"none"}},Ot={full:"full",extremal:"extremal",none:"none"},Cc={fields:["filter","orderBy","take","skip"],sortDirs:["asc","desc"],support:{array:{check:Ot.full,toPrisma:Ot.extremal,toSql:Ot.none},aggregate:{check:Ot.full,toPrisma:Ot.none,toSql:Ot.none}}},XA=(e,t)=>Cc.support[e][t],Mc=new Set(["scalar","ordered"]),Pc=new Set(["range"]),eR=[h.equals,h.notEquals,h.lessThan,h.lessThanEquals,h.greaterThan,h.greaterThanEquals,h.between,h.notBetween],xi=e=>{let t=oe[e];return t?Mc.has(t.valueShape):false},bi=e=>{let t=oe[e];return t?Pc.has(t.valueShape):false},ln=e=>{if(Object.hasOwn(oe,e))return oe[e].valueShape;if(Object.hasOwn(Me,e))return Me[e].valueShape;if(Object.hasOwn(Pe,e))return Pe[e].valueShape;throw new Error(`Unknown operator: ${e}`)},St=(e,t)=>Object.hasOwn(oe,e)?oe[e].targets.includes(t):Object.hasOwn(Me,e)?Me[e].targets.includes(t):Object.hasOwn(Pe,e)?Pe[e].targets.includes(t):false,tR=(e,t)=>{let r=Object.keys(oe).filter(o=>{let a=oe[o];return !(!a.kinds.includes(e)||t&&!a.targets.includes(t))}),n=Object.keys(Me).filter(o=>{let a=Me[o];return !(!a.kinds.includes(e)||t&&!a.targets.includes(t))});return {field:r,date:n}},rR=e=>Object.keys(Pe).filter(t=>e?Pe[t].targets.includes(e):true);var vi=["check","toPrisma","toSql"],fn=(e,t)=>{for(let r of [...e.targets])St(t,r)||e.targets.delete(r);},Dc=(e,t)=>{if(!ne(t))return;e.targets.delete("toSql"),("aggregate"in t||ht(t)===null)&&e.targets.delete("toPrisma");},De=(e,t,r,n,o)=>{if(typeof e=="boolean")return;if(t.sources.add(r),"all"in e){for(let f of e.all)De(f,t,r,n,o);return}if("any"in e){for(let f of e.any)De(f,t,r,n,o);return}if("if"in e){De(e.if,t,r,n,o),De(e.then,t,r,n,o),e.else!==void 0&&De(e.else,t,r,n,o);return}let a=e;typeof a.operator=="string"&&fn(t,a.operator),typeof a.dateOperator=="string"&&fn(t,a.dateOperator),typeof a.arrayOperator=="string"&&fn(t,a.arrayOperator),Dc(t,a),a.filter!==void 0&&De(a.filter,t,r,n,o);let i=r,s=n,l=o;if("field"in e&&typeof e.field=="string"&&e.field!==""){let f=ke(t.policy,r,n,o,e.field);if(!f){t.violations.push(e.field);return}if(t.sources.add(f.mapName),f.mapName!==r&&(t.bridgesCrossed=true),f.entry.kind==="object"||f.entry.kind==="bridge"){f.entry.kind==="bridge"&&(t.bridgesCrossed=true);let m=f.entry.kind==="object"?{mapName:f.mapName,modelName:f.entry.type}:{mapName:f.entry.type.split(":")[0]??f.mapName,modelName:f.entry.type.split(":")[1]??f.entry.type};i=m.mapName,s=m.modelName,l=[...f.relPath,f.terminalFieldName];}}"condition"in e&&e.condition!==void 0&&De(e.condition,t,i,s,l);},Fc=(e,t)=>{let r=j(t),n={policy:r,sources:new Set,bridgesCrossed:false,targets:new Set(vi),violations:[]};if(De(e,n,r.lens.mapName,r.lens.model,[]),n.bridgesCrossed)for(let o of [...n.targets])o!=="check"&&n.targets.delete(o);return {sources:[...n.sources].sort(),bridgesCrossed:n.bridgesCrossed,supportedTargets:vi.filter(o=>n.targets.has(o)),violations:n.violations}};var Oi=(e,t,r,n,o,a,i,s)=>{let l=o.split("."),f=t,m=r,p=[...n];for(let u=0;u<l.length-1;u++){let d=e.lens.maps[f]?.models[m]?.fields[l[u]],c=d?L(d,f):null;if(!c){if(a)throw new Error(`groupBy '${o}': hop '${l[u]}' is not a resolvable relation on '${m}' \u2014 cannot guard its join`);return}p.push(l[u]),f=c.mapName,m=c.modelName;let y=p.join(".");if(i.has(y))continue;i.add(y);let g=G(e,f,m,p),w=l.slice(0,u+1).join(".");for(let v of g.whereClauses)s.push(Te(v,w));}},$t=(e,t=[])=>{if(typeof e!="object"||e===null)return t;let r=e;if(Array.isArray(r.all))for(let n of r.all)$t(n,t);if(Array.isArray(r.any))for(let n of r.any)$t(n,t);return r.if!==void 0&&($t(r.if,t),$t(r.then,t),r.else!==void 0&&$t(r.else,t)),typeof r.field=="string"&&t.push(r.field),t},Rr=(e,t,r,n,o,a)=>{let i=[],s=new Set;for(let l of o)Oi(e,t,r,n,l,true,s,i);for(let l of a)for(let f of $t(l))f.includes(".")&&Oi(e,t,r,n,f,false,s,i);return i},_c=(e,t)=>{let r=e;for(let n of t.split(".")){if(r==null||typeof r!="object")return;r=r[n];}return r==null||typeof r=="object"?void 0:String(r)},kr=(e,t)=>{let r=[];for(let n of t){let o=_c(e,n);if(o===void 0)return;r.push(o);}return r},un=(e,t)=>JSON.stringify([e??null,t]),Tr=(e,t,r,n)=>{let o=un(n,t),a=e.get(o);a===void 0?e.set(o,{value:t,...r!==void 0?{label:r}:{},...n!==void 0?{groups:n}:{}}):a.label===void 0&&r!==void 0&&e.set(o,{...a,label:r});},Cr=e=>[...e.values()].sort((t,r)=>{let n=(t.groups===void 0?0:1)-(r.groups===void 0?0:1);if(n!==0)return n;let o=t.groups??[],a=r.groups??[];for(let i=0;i<Math.max(o.length,a.length);i++){let s=(o[i]??"").localeCompare(a[i]??"","en",{numeric:true});if(s!==0)return s}return (t.label??t.value).localeCompare(r.label??r.value,"en",{numeric:true})});var Bc=(e,t)=>`${e}::${t}`,Nc=["__offpath__"],Lc=(e,t,r)=>{let n=e.get(t);if(!n){e.set(t,r.values?{...r,values:[...r.values]}:r);return}let o=n;if(r.values&&n.values){let a=new Set([...n.values,...r.values]);o={...o,values:[...a]};}else !r.values&&n.values&&(o={...o,values:void 0});r.groupBy!==void 0&&o.groupBy===void 0&&(o={...o,groupBy:r.groupBy}),o!==n&&e.set(t,o);},jc=(e,t={})=>{let r=j(e),{lens:n}=r,o=new Map;for(let u of t.sourceValues??[]){let d=`${u.mapName}::${u.model}::${u.field}`,c=o.get(d)??new Map;for(let y of u.options)c.set(un(y.groups,y.value),y);o.set(d,c);}let a=new Map,i=new Set,s=new Set,l=[{mapName:n.mapName,modelName:n.model,relPath:[],declared:true}];for(;l.length>0;){let{mapName:u,modelName:d,relPath:c,declared:y}=l.shift(),g=n.maps[u]?.models[d];if(!g)continue;let w=Bc(u,d);if(y){let x=`${w}::${c.join(".")}`;if(i.has(x))continue;i.add(x);}else {if(s.has(w))continue;s.add(w);}let v=G(r,u,d,y?c:Nc),b=a.get(w);b||(b={mapName:u,modelName:d,fields:new Map},a.set(w,b));for(let[x,$]of Object.entries(g.fields)){if(!Re(v,x))continue;let M=`${u}::${d}::${x}`,W=o.get(M),We=v.enumValuesByField.get(x),Q=We!==void 0?{...$,values:We}:$;W&&(Q={...Q,options:[...W.values()]});let Wt=v.sourceGroupBys.get(x);if(Wt!==void 0){let ie=b.fields.get(x)?.groupBy;if(ie!==void 0&&JSON.stringify(ie)!==JSON.stringify(Wt))throw new Error(`exposedSurface: '${d}.${x}' is grouped by different axes on different paths ([${ie}] vs [${Wt}]) \u2014 one surface field cannot carry two partition namespaces`);Q={...Q,groupBy:Wt};}if(Lc(b.fields,x,Q),$.kind==="object"||$.kind==="bridge"){let ie=L($,u);if(!ie)continue;y&&v.relations.has(x)?l.push({mapName:ie.mapName,modelName:ie.modelName,relPath:[...c,x],declared:true}):l.push({mapName:ie.mapName,modelName:ie.modelName,relPath:[],declared:false});}}}let f={};for(let{mapName:u,modelName:d,fields:c}of a.values()){let y=f[u];y||(y={models:{}},f[u]=y);let g={},w=new Map;for(let[v,b]of c)if(g[v]=b.options===void 0&&b.values?{...b,options:b.values.map(x=>({value:x,label:x}))}:b,b.kind==="enum"&&b.values){let x=w.get(b.type)??new Set;for(let $ of b.values)x.add($);w.set(b.type,x);}y.models[d]={...n.maps[u]?.models[d],fields:g};for(let[v,b]of w)y.enums??={},y.enums[v]=[...b];}let m=n.bridges?.filter(u=>{let[d,c]=u.endpoints,y=f[d.fieldMap]?.models[d.model]?.fields[`${c.fieldMap}:${c.model}`],g=f[c.fieldMap]?.models[c.model]?.fields[`${d.fieldMap}:${d.model}`];return y!==void 0||g!==void 0}),p={maps:f};return m&&m.length>0&&(p.bridges=m),{...p,mapName:n.mapName,model:n.model}};var Si=(e,t)=>{for(let r of t){let n=Zr(r);if(n&&!n.includes(e))return "is not in an ancestor layer's picks";if(r.omits?.includes(e))return "was omitted by an ancestor layer"}return null},Ei=(e,t,r,n,o,a,i,s)=>{let l=(f,m)=>r.map(p=>p.mapDefaults?.[f]?.models?.[m]).filter(p=>p!==void 0);for(let[f,m]of Object.entries(e.sources??{})){let p=Ae(m),u=[...t,...l(o,a)].map(y=>y.sources?.[f]).filter(y=>y!==void 0).map(Ae);if(p.label!==void 0&&!u.some(y=>y.label===p.label)){let y=Si(p.label,[...t,...l(o,a)]);y&&s.push(`${i}.sources.${f}: label column '${p.label}' ${y}`);}let d=wt(p.groupBy);if(d===void 0)continue;let c=JSON.stringify(d);if(!u.some(y=>JSON.stringify(wt(y.groupBy))===c))for(let y of d){let g=y.split("."),w=t,v=o,b=a;for(let x=0;x<g.length;x++){let $=g[x],M=Si($,[...w,...l(v,b)]);if(M){s.push(`${i}.sources.${f}: groupBy segment '${$}' ${M}`);break}if(x===g.length-1)break;let W=n[v]?.models[b]?.fields[$],We=W?L(W,v):null;if(!We)break;w=w.map(Q=>"relations"in Q?Q.relations?.[$]:void 0).filter(Q=>Q!==void 0),v=We.mapName,b=We.modelName;}}}},qc=(e,t,r,n)=>{let o=e.split("."),a=r,i=n;for(let s=0;s<o.length;s++){let l=t[a]?.models[i]?.fields[o[s]];if(!l)return `groupBy segment '${o[s]}' not on model '${i}'`;let f=s===o.length-1;if(l.kind==="object"||l.kind==="bridge"){if(f)return `groupBy must end on a scalar column, '${o[s]}' is a relation`;if(l.isList)return `groupBy cannot traverse to-many relation '${o[s]}'`;let m=L(l,a);if(!m)return `groupBy relation '${o[s]}' has no resolvable target`;a=m.mapName,i=m.modelName;continue}if(!f)return `groupBy segment '${o[s]}' is not a relation`}return null},Ai=(e,t,r,n,o,a,i,s,l,f,m=false)=>{e.picks&&e.omits&&f.push(`${l}: cannot specify both picks and omits`),m&&"relations"in e&&e.relations&&f.push(`${l}: defaults cannot declare 'relations' \u2014 relations are path-specific only`);for(let u of e.picks??[]){if(!a[u]){f.push(`${l}.picks: field '${u}' not on model`);continue}let d=false;for(let c of t){if(c.picks&&!c.picks.includes(u)){f.push(`${l}.picks: '${u}' not in ancestor's picks`),d=true;break}if(c.omits?.includes(u)){f.push(`${l}.picks: '${u}' was omitted by ancestor`),d=true;break}}d||!m&&r&&(r.picks&&!r.picks.includes(u)?f.push(`${l}.picks: '${u}' not visible from defaults.picks`):r.omits?.includes(u)&&f.push(`${l}.picks: '${u}' not visible (already excluded by defaults.omits)`));}for(let u of e.omits??[]){if(!a[u]){f.push(`${l}.omits: field '${u}' not on model`);continue}let d=false;for(let c of t){if(c.picks&&!c.picks.includes(u)){f.push(`${l}.omits: '${u}' not in ancestor's picks (already invisible)`),d=true;break}if(c.omits?.includes(u)){f.push(`${l}.omits: '${u}' already excluded by ancestor`),d=true;break}}d||!m&&r&&(r.picks&&!r.picks.includes(u)?f.push(`${l}.omits: '${u}' not visible from defaults.picks`):r.omits?.includes(u)&&f.push(`${l}.omits: '${u}' already excluded by defaults`));}let p=(u,d,c)=>{let y=a[d];if(!y){f.push(`${l}.${u}: field '${d}' not on model`);return}if(y.kind!=="enum"){f.push(`${l}.${u}: field '${d}' is not an enum field`);return}let g=y.values??s?.[y.type];for(let w of c)g&&!g.includes(w)&&f.push(`${l}.${u}.${d}: '${w}' is not a known value of enum '${y.type}'`);};for(let[u,d]of Object.entries(e.enumPicks??{}))p("enumPicks",u,d);for(let[u,d]of Object.entries(e.enumOmits??{}))p("enumOmits",u,d);if(e.where!==void 0&&e.where!==true&&e.where!==false){let u=$i(e.where,a,i);for(let d of u)f.push(`${l}.where: ${d}`);}for(let[u,d]of Object.entries(e.sources??{})){if(!a[u]){f.push(`${l}.sources: field '${u}' not on model`);continue}let c=Ae(d);c.label!==void 0&&!a[c.label]&&f.push(`${l}.sources.${u}: label column '${c.label}' not on model`);let y=wt(c.groupBy);if(y!==void 0){for(let b of y){let x=qc(b,n,o,i);x&&f.push(`${l}.sources.${u}: ${x}`);}let w=/^__group(_\d+)?$/;(w.test(u)||c.label!==void 0&&w.test(c.label))&&f.push(`${l}.sources.${u}: '__group*' names are reserved on grouped sources (sql group aliases)`);let v=JSON.stringify(y);for(let b of t){let x=b.sources?.[u];if(x===void 0)continue;let $=wt(Ae(x).groupBy);$!==void 0&&JSON.stringify($)!==v&&f.push(`${l}.sources.${u}: groupBy [${y}] conflicts with an ancestor layer's groupBy [${$}]`);}}let g=c.where;if(g!==void 0&&g!==true&&g!==false){let w=$i(g,a,i);for(let v of w)f.push(`${l}.sources.${u}: ${v}`);}}},$i=(e,t,r)=>{let n=[],o=a=>{if(a===null||typeof a!="object")return;if(Array.isArray(a)){for(let s of a)o(s);return}let i=a;if("all"in i&&Array.isArray(i.all)){for(let s of i.all)o(s);return}if("any"in i&&Array.isArray(i.any)){for(let s of i.any)o(s);return}if("if"in i){o(i.if),o(i.then),i.else!==void 0&&o(i.else);return}if("field"in i&&typeof i.field=="string"&&i.field!==""){let s=i.field.split(".")[0];t[s]||n.push(`'${i.field}' not on model ${r}`);}"condition"in i&&i.condition!==void 0&&o(i.condition);};return o(e),n},Ic=(e,t,r,n,o)=>{for(let[a,i]of Object.entries(t)){let s=r?.[a];if(!s){o.push(`mapDefaults.${e}.enums.${a}: enum not in registry`);continue}let l=null,f=new Set;for(let p of n){let u=p[a];if(u&&(u.picks&&(l=_t(l,u.picks)),u.omits))for(let d of u.omits)f.add(d);}let m=p=>!(f.has(p)||l&&!l.has(p));for(let p of i.picks??[])s.includes(p)?m(p)||o.push(`mapDefaults.${e}.enums.${a}.picks: '${p}' not visible from ancestors`):o.push(`mapDefaults.${e}.enums.${a}.picks: '${p}' not a known value`);for(let p of i.omits??[])s.includes(p)?m(p)||o.push(`mapDefaults.${e}.enums.${a}.omits: '${p}' already excluded by ancestors`):o.push(`mapDefaults.${e}.enums.${a}.omits: '${p}' not a known value`);}},Ri=(e,t,r,n,o,a,i,s,l)=>{let f=(m,p,u)=>{let d=e[p];if(!d||d.kind!=="enum")return;let c=d.type,y={picks:null,omits:new Set},g=x=>{y.picks=_t(y.picks,x);},w=x=>{for(let $ of x)y.omits.add($);},v=[...n];r&&v.push(r);for(let x of v){let $=x[c];$&&($.picks&&g($.picks),$.omits&&w($.omits));}let b=[...a];o&&b.push(o);for(let x of b){let $=x.enumPicks?.[p],M=x.enumOmits?.[p];$&&g($),M&&w(M);}for(let x of i){let $=x.enumPicks?.[p],M=x.enumOmits?.[p];$&&g($),M&&w(M);}for(let x of u)y.omits.has(x)?l.push(`${s}.${m}.${p}: '${x}' already excluded by inherited enum narrowing`):y.picks&&!y.picks.has(x)&&l.push(`${s}.${m}.${p}: '${x}' not allowed by inherited enum narrowing`);};for(let[m,p]of Object.entries(t.enumPicks??{}))f("enumPicks",m,p);for(let[m,p]of Object.entries(t.enumOmits??{}))f("enumOmits",m,p);},ki=(e,t,r,n,o,a,i,s,l)=>{let f=o[a],m=f?.models[i];if(!m)return;let p=r.mapDefaults?.[a]?.models?.[i],u=n.map(g=>g.mapDefaults?.[a]?.models?.[i]).filter(g=>g!==void 0),d=r.mapDefaults?.[a]?.enums,c=n.map(g=>g.mapDefaults?.[a]?.enums).filter(g=>g!==void 0),y=[...u.map(g=>g),...t];Ai(e,y,p,o,a,m.fields,i,f?.enums,s,l,false),Ri(m.fields,e,d,c,p,u,t,s,l),Ei(e,t,n,o,a,i,s,l);for(let[g,w]of Object.entries(e.relations??{})){let v=m.fields[g];if(!v){l.push(`${s}.relations: '${g}' not on model`);continue}if(v.kind!=="object"&&v.kind!=="bridge"){l.push(`${s}.relations: '${g}' is not a relation (kind=${v.kind})`);continue}let b=L(v,a);if(!b)continue;if(!o[b.mapName]?.models[b.modelName]){l.push(`${s}.relations.${g}: target model not found in lens`);continue}let x=t.map($=>$.relations?.[g]).filter($=>$!==void 0);ki(w,x,r,n,o,b.mapName,b.modelName,`${s}.relations.${g}`,l);}},Vc=e=>{let t=[],r=Sr(e),n=qe(e.parent);for(let[o,a]of Object.entries(e.mapDefaults??{})){let i=r.maps[o];if(!i){t.push(`mapDefaults.${o}: not in lens`);continue}let s=n.map(l=>l.mapDefaults?.[o]?.enums).filter(l=>l!==void 0);for(let[l,f]of Object.entries(a.models??{})){let m=i.models[l];if(!m){t.push(`mapDefaults.${o}.models.${l}: not in fieldMap`);continue}let p=n.map(u=>u.mapDefaults?.[o]?.models?.[l]).filter(u=>u!==void 0);Ai(f,p,void 0,r.maps,o,m.fields,l,i.enums,`mapDefaults.${o}.models.${l}`,t,true),Ri(m.fields,f,void 0,s,void 0,p,[],`mapDefaults.${o}.models.${l}`,t),Ei(f,[],n,r.maps,o,l,`mapDefaults.${o}.models.${l}`,t);}a.enums&&Ic(o,a.enums,i.enums,s,t);}if(e.root){let o=r.mapName,a=r.model,i=r.maps[o];if(!i)t.push(`root: lens map '${o}' not in lens`);else if(!i.models[a])t.push(`root: lens model '${a}' not in fieldMap`);else {let s=n.map(l=>l.root).filter(l=>l!==void 0);ki(e.root,s,e,n,r.maps,o,a,"root",t);}}if(e.root?.where!==void 0){let o=an(e.root.where,e.parent);for(let a of o.violations)t.push(`root.where: '${a.path}' ${a.reason}`);}for(let o of on(e))t.push(o);if(t.length)throw new Error(`validateNarrowing:
|
|
4
4
|
${t.join(`
|
|
5
|
-
`)}`)};var Bt=(e,t={})=>{let r=j(e),n=new Map,o=new Map;for(let i of t.sourceValues??[])o.set(`${i.path}|${i.field}`,i.options);let a=(i,s,l,f)=>{if(n.has(f))return;let m=r.lens.maps[i]?.models[s];if(!m)return;let p=G(r,i,s,l),u={};for(let[g,w]of Object.entries(m.fields)){if(!Re(p,g))continue;let v=o.get(`${f}|${g}`),b=p.enumValuesByField.get(g),x=b!==void 0?{...w,values:b}:w,$=v??b?.map(M=>({value:M,label:M}));$&&(x={...x,options:$}),u[g]=x;}let d={};for(let[g,w]of p.sources)Re(p,g)&&(d[g]=w);let c={};for(let[g,w]of p.sourceLabels)Re(p,g)&&(c[g]=w);let y={};for(let[g,w]of p.sourceGroupBys)Re(p,g)&&(y[g]=w);n.set(f,{mapName:i,modelName:s,fields:u,whereClauses:p.whereClauses,sources:d,sourceLabels:c,sourceGroupBys:y});for(let g of p.relations.keys()){let w=m.fields[g];if(!w)continue;let v=L(w,i);v&&a(v.mapName,v.modelName,[...l,g],`${f}.${g}`);}};return a(r.lens.mapName,r.lens.model,[],r.lens.model),n};var Mr=(e,t,r,n)=>{let o=e.models[t];if(!o)return null;for(let a of Object.values(o.fields))if(a.kind==="object"&&a.type===r&&(a.fromFields?.length??0)>0&&(a.toFields?.length??0)>0&&(n===void 0||a.relationName===n))return a;return null};var ae=(e,t)=>{let r=e.split("."),n=t;for(let o=r.length-1;o>=0;o--)n={[r[o]]:n};return n};var Ti,Ci=e=>{Ti=e;},Mi=(e,t,r)=>{if(ne(e))throw new Error("Windowing (orderBy/take/skip) is not supported by toPrisma(); evaluate with check().");if(!t?.map||!t?.model||!r)throw new Error("Aggregate rules require a FieldMap and model to generate a Prisma plan. Pass { map, model } options to toPrisma().");if(!e.aggregate.field)throw new Error("Prisma aggregate rules require aggregate.field to specify the numeric field on the related model.");if(e.path)throw new Error("path is not supported for Prisma aggregate rules; use value instead.");return Uc(e,t,r)},Wc=(e,t,r)=>{let n=e.split("."),o=[],a=r;for(let i=0;i<n.length;i++){let s=n[i],l=t.models[a]?.fields[s];if(!l||l.kind!=="object")throw new Error(`Field '${s}' is not a relation in model '${a}'. Prisma aggregate rules only support relation fields.`);if(i===n.length-1){if(!l.isList)throw new Error(`Field '${s}' is not a list relation in model '${a}'.`);return {segments:n,intermediateRelations:o,terminalModel:a,terminalEntry:l}}if(l.isList)throw new Error(`Intermediate field '${s}' in path '${e}' is a list relation. Only the final segment can be a list relation for aggregate rules.`);o.push({fieldName:s,entry:l,onModel:a}),a=l.type;}throw new Error(`Field path '${e}' did not terminate at a list relation.`)},Uc=(e,t,r)=>{let{map:n,model:o}=t,{intermediateRelations:a,terminalModel:i,terminalEntry:s}=Wc(e.field,n,o),l=s.type,f=e.aggregate.field??"",m=n.models[l]?.fields[f];if(!m)throw new Error(`aggregate.field '${f}' does not exist on model '${l}'.`);if(m.kind!=="scalar")throw new Error(`aggregate.field '${f}' on model '${l}' must be a scalar field, got '${m.kind}'.`);if(m.type==="Json")throw new Error(`aggregate.field '${f}' on model '${l}' is a Json field \u2014 aggregate rules require a numeric scalar.`);let p,u;if(s.fromFields&&s.fromFields.length>0){if(s.fromFields.length>1)throw new Error("Aggregate rules do not support composite FK relations.");p=s.toFields?.[0]??"id",u=s.fromFields[0];}else {let b=Mr(n,l,i,s.relationName);if(!b)throw new Error(`Cannot determine FK relationship between '${i}' and '${l}'. Ensure the FieldMap contains both sides of the relation.`);if((b.fromFields?.length??0)>1)throw new Error("Aggregate rules do not support composite FK relations.");p=b.fromFields?.[0]??"",u=b.toFields?.[0]??"";}let d=e.condition?Ti(e.condition,{...t,model:l},r):{},c=e.aggregate.mode==="sum"?"_sum":"_avg",y={[f]:{[c]:Gc(e)}},g={operation:"groupBy",model:l,args:{by:[p],where:d,having:y},extract:p},w=r.steps.length;r.steps.push(g);let v={__step:w};if(a.length>0){let b={[u]:{in:v}},x=a.map($=>$.fieldName).join(".");return ae(x,b)}return {[u]:{in:v}}},Gc=e=>{let t=e.value;switch(e.operator){case h.equals:return {equals:t};case h.notEquals:return {not:t};case h.lessThan:return {lt:t};case h.lessThanEquals:return {lte:t};case h.greaterThan:return {gt:t};case h.greaterThanEquals:return {gte:t};case h.between:{if(!Array.isArray(t)||t.length!==2)throw new Error("between requires two values");let[r,n]=t,[o,a]=r<=n?[r,n]:[n,r];return {gte:o,lte:a}}case h.notBetween:throw new Error("Operator 'notBetween' is not supported for Prisma aggregate rules.");default:throw new Error(`Operator '${e.operator}' is not supported for Prisma aggregate rules.`)}};var Pi=(e,t,r,n)=>{let{map:o,model:a}=t;if(!e.field)throw new Error("toPrisma: count-based ArrayRule requires a field path");let i=o.models[a]?.fields[e.field];if(!i||i.kind!=="object")throw new Error(`Field '${e.field}' is not a relation in model '${a}'. Count operators require a relation field.`);if(!i.isList)throw new Error(`Field '${e.field}' is not a list relation in model '${a}'. Count operators only apply to one-to-many or many-to-many relations.`);let s=i.type,l,f;if(i.fromFields&&i.fromFields.length>0){if(i.fromFields.length>1)throw new Error(`Count operators (atLeast/atMost/exactly) do not support composite FK relations ('${a}.${e.field}'). Use prisma.$queryRaw for composite FK count filtering.`);l=i.toFields?.[0]??"id",f=i.fromFields[0];}else {let g=Mr(o,s,a,i.relationName);if(!g){let v=Object.values(o.models[s]?.fields??{}).some(b=>b.kind==="object"&&b.type===a&&b.isList&&!b.fromFields?.length);throw new Error(v?`'${a}.${e.field}' is an implicit many-to-many relation. Count operators require an explicit join model with a FK \u2014 convert to an explicit @relation or use prisma.$queryRaw.`:`Cannot determine FK relationship between '${a}' and '${s}'. Ensure the FieldMap contains both sides of the relation.`)}if((g.fromFields?.length??0)>1)throw new Error(`Count operators (atLeast/atMost/exactly) do not support composite FK relations ('${a}.${e.field}'). Use prisma.$queryRaw for composite FK count filtering.`);l=g.fromFields?.[0]??"",f=g.toFields?.[0]??"";}let m=e.condition?n(e.condition,{...t,model:s},r):{},p=e.count??1,u=Kc(e.arrayOperator,p,l),d={operation:"groupBy",model:s,args:{by:[l],where:m,having:u},extract:l},c=r.steps.length;r.steps.push(d);let y={__step:c};return {[f]:{in:y}}},Kc=(e,t,r)=>{switch(e){case O.atLeast:return {[r]:{_count:{gte:t}}};case O.atMost:return {[r]:{_count:{lte:t}}};case O.exactly:return {[r]:{_count:{equals:t}}};default:throw new Error("unreachable")}};var zc="Windowing (orderBy/take/skip) is not supported by toPrisma() for this rule; only extremal (take:1, single orderBy on the compared field, aligned direction) rewrites to every/some. Evaluate other windowed rules with check().",Nt,Di=e=>{Nt=e;},pn=(e,t,r)=>{if(ne(e)){let o=ht(e);if(!o)throw new Error(zc);return pn(o,t,r)}if(e.arrayOperator===O.atLeast||e.arrayOperator===O.atMost||e.arrayOperator===O.exactly){if(t?.map&&t?.model&&r)return Pi(e,t,r,Nt);throw new Error(`ArrayOperator '${e.arrayOperator}' requires a FieldMap and model to generate a multi-step plan. Pass { map, model } options to toPrisma(). Without them, use prisma.$queryRaw for count-based relation filtering.`)}if(!e.field)throw new Error("toPrisma: ArrayRule.field is required (fieldless arrayOps are check-only)");let n=Jc(e,t,r);return ae(e.field,n)},Hc=(e,t,r)=>{let n=e.split("."),o=r;for(let a of n){let i=t.models[o]?.fields[a];if(!i||i.kind!=="object")return null;o=i.type;}return o},Qc=(e,t)=>{if(!t?.map||!t?.model||!e.field)return t;let r=Hc(e.field,t.map,t.model);return r?{...t,model:r}:t},Jc=(e,t,r)=>{let n=Qc(e,t);switch(e.arrayOperator){case O.all:if(!e.condition)throw new Error("ArrayOperator 'all' requires a condition");return {every:Nt(e.condition,n,r)};case O.any:if(!e.condition)throw new Error("ArrayOperator 'any' requires a condition");return {some:Nt(e.condition,n,r)};case O.none:if(!e.condition)throw new Error("ArrayOperator 'none' requires a condition");return {none:Nt(e.condition,n,r)};case O.empty:return {none:{}};case O.notEmpty:return {some:{}};default:throw new Error(`Unknown array operator: ${e.arrayOperator}`)}};var Zc=e=>({now:e?.now,timeZone:e?.timeZone,weekStart:e?.weekStart}),Fi=(e,t)=>{if(e===void 0||!je(e))return e;let r=z(e,Ft(t));if(!r.isValid())throw new Error(`Invalid date value: ${String(e)}`);return r.toDate()},Ni=(e,t)=>{let r=Yc(e,t);return ae(e.field,r)},dn=(e,t)=>{if(e.value!==void 0)return e.value;if(e.path){if(e.path.startsWith("$."))throw new Error(`Prisma WHERE has no column-to-column date comparison for path '${e.path}'. Use prisma.$queryRaw for field-to-field filtering.`);if(!t?.context)throw new Error(`options.context is required to resolve date path '${e.path}'. Pass context when calling toPrisma().`);return T(t.context,e.path)}},Yc=(e,t)=>{let r=Zc(t),n=()=>N(e.value)?xr(e.value,e.dateOperator,r).toDate():Fi(dn(e,t),r),o=a=>N(a)?me(a,r).toDate():Fi(a,r);switch(e.dateOperator){case E.before:return {lt:n()};case E.after:return {gt:n()};case E.onOrBefore:return {lte:n()};case E.onOrAfter:return {gte:n()};case E.within:{if(!N(e.value))throw new Error("within date operator requires a range date expression");let[a,i]=dt(e.value,r);return {gte:a.toDate(),lte:i.toDate()}}case E.between:{let a=dn(e,t);if(!Array.isArray(a)||a.length!==2)throw new Error("between date operator requires an array of two values");let[i,s]=_i(a.map(o));return {gte:i,lte:s}}case E.notBetween:{let a=dn(e,t);if(!Array.isArray(a)||a.length!==2)throw new Error("notBetween date operator requires an array of two values");let[i,s]=_i(a.map(o));return {NOT:{gte:i,lte:s}}}case E.dayIn:throw new Error("DateOperator 'dayIn' has no Prisma equivalent. Use prisma.$queryRaw with EXTRACT(DOW FROM ...) for day-of-week filtering.");case E.dayNotIn:throw new Error("DateOperator 'dayNotIn' has no Prisma equivalent. Use prisma.$queryRaw with EXTRACT(DOW FROM ...) for day-of-week filtering.");default:throw new Error(`Unknown date operator: ${e.dateOperator}`)}},_i=e=>{let[t,r]=e;return Xc(t,r)<=0?[t,r]:[r,t]},Xc=(e,t)=>{let r=Bi(e),n=Bi(t);return r<n?-1:r>n?1:0},Bi=e=>e instanceof Date?e.getTime():typeof e=="number"||typeof e=="string"?e:String(e);var Pr=(e,t,r)=>{let n=e.split("."),o=r;for(let a=0;a<n.length;a++){let i=t.models[o];if(!i)return {kind:"fallback"};let s=i.fields[n[a]];if(!s)return {kind:"fallback"};if(s.kind==="bridge")return {kind:"bridge"};if(s.kind==="scalar"&&s.type==="Json"&&a<n.length-1)return {kind:"json-path",stopIndex:a+1,jsonPath:n.slice(a+1)};if(s.kind==="object"){if(!t.models[s.type])return {kind:"fallback"};o=s.type;continue}return {kind:"direct"}}return {kind:"direct"}};var Li=(e,t)=>{if(e.operator===h.isEmpty)return {OR:[Lt(e.field,{equals:null},t),Lt(e.field,{equals:""},t)]};if(e.operator===h.notEmpty)return {AND:[Lt(e.field,{not:null},t),Lt(e.field,{not:""},t)]};let r=tg(e,t);return Lt(e.field,r,t)},eg=(e,t)=>{if(e.value!==void 0)return e.value;if(e.bind!==void 0)throw new Error(`Unresolved binding '${e.bind}' for field '${e.field}' \u2014 resolve bindings (resolveLensBindings) before compiling to Prisma.`);if(e.path){if(e.path.startsWith("$."))throw new Error(`Prisma WHERE has no column-to-column comparison for path '${e.path}'. Use prisma.$queryRaw for field-to-field filtering.`);if(!t?.context)throw new Error(`options.context is required to resolve path '${e.path}'. Pass context when calling toPrisma().`);return T(t.context,e.path)}throw new Error(`Rule for field '${e.field}' has neither value nor path set`)},tg=(e,t)=>{if(e.fuzzy)throw new Error("Fuzzy matching has no Prisma equivalent \u2014 evaluate it in memory with check().");let r=()=>eg(e,t),n=t?.datasource?.provider??br.get("prismaOptions.datasource.provider"),o=ct(e.caseInsensitive)&&Xa(n)?{mode:"insensitive"}:{};switch(e.operator){case h.equals:return {equals:r()??null,...o};case h.notEquals:return {not:r()??null,...o};case h.lessThan:return {lt:r()};case h.lessThanEquals:return {lte:r()};case h.greaterThan:return {gt:r()};case h.greaterThanEquals:return {gte:r()};case h.in:return {in:r()};case h.notIn:return {notIn:r()};case h.contains:return {contains:r(),...o};case h.notContains:return {not:{contains:r(),...o}};case h.startsWith:return {startsWith:r(),...o};case h.endsWith:return {endsWith:r(),...o};case h.matches:throw new Error("Operator 'matches' has no Prisma equivalent. Use prisma.$queryRaw for regex filtering.");case h.notMatches:throw new Error("Operator 'notMatches' has no Prisma equivalent. Use prisma.$queryRaw for regex filtering.");case h.between:{let a=r();if(!Array.isArray(a)||a.length!==2)throw new Error("between operator requires an array of two values");let[i,s]=a[0]<=a[1]?a:[a[1],a[0]];return {gte:i,lte:s}}case h.notBetween:{let a=r();if(!Array.isArray(a)||a.length!==2)throw new Error("notBetween operator requires an array of two values");let[i,s]=a[0]<=a[1]?a:[a[1],a[0]];return {NOT:{gte:i,lte:s}}}case h.isEmpty:case h.notEmpty:throw new Error("isEmpty/notEmpty handled at buildFieldRule level");case h.exists:return {not:null};case h.notExists:return {equals:null};default:throw new Error(`Unknown operator: ${e.operator}`)}},Lt=(e,t,r)=>{if(!r?.map||!r?.model)return ae(e,t);let n=Pr(e,r.map,r.model),o=e.split(".");switch(n.kind){case "fallback":case "direct":return ae(e,t);case "bridge":return {};case "json-path":{let a={path:n.jsonPath,...t},i=o.slice(0,n.stopIndex).join(".");return ae(i,a)}}};var Et,qi=e=>{Et=e;},rg=(e,t,r)=>{let n=e.split("."),o=r;for(let a of n){let i=t.models[o]?.fields[a];if(!i||i.kind!=="object")return null;o=i.type;}return o},ce=(e,t)=>{if(typeof e=="boolean"||!t?.map||!t?.model)return false;if("all"in e)return e.all.some(r=>ce(r,t));if("any"in e)return e.any.some(r=>ce(r,t));if("if"in e)return ce(e.if,t)||ce(e.then,t)||e.else!==void 0&&ce(e.else,t);if("field"in e&&typeof e.field=="string"&&e.field!==""){if(Pr(e.field,t.map,t.model).kind==="bridge")return true;if("condition"in e&&e.condition!==void 0){let n=rg(e.field,t.map,t.model);if(n&&ce(e.condition,{...t,model:n}))return true}}return false},Ii=(e,t,r)=>e.all.length===0?{}:{AND:e.all.map(n=>Et(n,t,r))},Vi=(e,t,r)=>e.any.length===0?{AND:[{id:null},{id:{not:null}}]}:{OR:e.any.map(n=>Et(n,t,r))},Wi=(e,t,r)=>{if(ce(e.if,t)||ce(e.then,t)||e.else!==void 0&&ce(e.else,t))return {};let n=Et(e.if,t,r),o={NOT:n},a=e.then===false?ji:Et(e.then,t,r);if(e.else!==void 0){let i=e.else===false?ji:Et(e.else,t,r);return {AND:[{OR:[o,a]},{OR:[n,i]}]}}return {OR:[o,a]}},ji={AND:[{id:null},{id:{not:null}}]};var jt=(e,t,r)=>{if(typeof e=="boolean"){if(e)return {};throw new Error("Boolean 'false' has no direct Prisma WHERE equivalent. toPrisma is designed for structured Rule conditions.")}if("all"in e)return Ii(e,t,r);if("any"in e)return Vi(e,t,r);if("if"in e)return Wi(e,t,r);if("arrayOperator"in e)return pn(e,t,r);if("dateOperator"in e)return Ni(e,t);if("aggregate"in e)return Mi(e,t,r);if("field"in e)return Li(e,t);throw new Error("Unknown condition type")};qi(jt);Di(jt);Ci(jt);var ng=async(e,t)=>{let r=e.steps.filter(a=>a.operation==="groupBy"),n=e.steps.find(a=>a.operation==="where");if(!n)throw new Error("executePrismaQueryPlan: result has no where step");let o=[];for(let a of r){let i=a.model.charAt(0).toLowerCase()+a.model.slice(1),s=t[i];if(!s)throw new Error(`executePrismaQueryPlan: no delegate for model '${a.model}'. Ensure prismaDelegate has a key '${i}'.`);let l=await s[a.operation](a.args);o.push(l.map(f=>f[a.extract]));}return mn(n.where,o)},mn=(e,t)=>{if(e==null)return e;if(Array.isArray(e))return e.map(r=>mn(r,t));if(typeof e=="object"){let r=e;if("__step"in r&&typeof r.__step=="number"){let o=r.__step;if(o>=t.length)throw new Error(`Step ref __step: ${o} out of range (${t.length} steps executed)`);return t[o]}let n={};for(let[o,a]of Object.entries(r))n[o]=mn(a,t);return n}return e};var og=e=>{if(!e?.map)return e;let t="maps"in e.map;if(t&&!e.mapName)throw new Error("toPrisma: 'map' is a FieldMapSet \u2014 'mapName' is required to resolve which map to use.");if(!t||!e.mapName)return e;let r=e.map.maps[e.mapName];if(!r)throw new Error(`toPrisma: fieldMap set has no entry for '${e.mapName}'`);return {...e,map:r}},Ui=(e,t)=>{let r={steps:[]},n=jt(e,og(t),r);return {steps:[...r.steps,{operation:"where",where:n}]}};var k=e=>`"${e.replace(/"/g,'""')}"`;var A=(e,t)=>(e.params.push(t),`$${++e.paramIndex}`);var qt=e=>e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_"),I=e=>{let t=e.split(".");if(t.length===1)return k(e);let[r,...n]=t;return n.length===0?k(r):Ki(k(r),n)},Gi=(e,t)=>{let r=e.split(".");if(r.length===1)return `${k(t)}.${k(e)}`;let[n,...o]=r;return Ki(`${k(t)}.${k(n)}`,o)},cn=e=>`'${e.replace(/'/g,"''")}'`,Ki=(e,t)=>{if(t.length===0)return e;let r=t.slice(0,-1).map(cn).join("->"),n=cn(t[t.length-1]);return r?`${e}->${r}->>${n}`:`${e}->>${n}`},zi=e=>{let t=e.split(".");if(t.length===1)return k(e);let[r,...n]=t;return n.length===0?k(r):ag(k(r),n)},ag=(e,t)=>{let r=t.map(cn).join("->");return `${e}->${r}`};var Hi=(e,t)=>{if(ne(e))throw new Error("Windowing (orderBy/take/skip) is not supported by toSql(); evaluate with check().");if(e.condition)throw new Error("Aggregate condition filtering is not yet supported by toSql(). Use check() for in-memory evaluation or toPrisma() for database queries.");let r=ig(e,t);return lg(r,e,t)},ig=(e,t)=>{let r=zi(e.field),{mode:n,field:o}=e.aggregate,a=n==="sum"?"SUM":"AVG",i=t.map?.models[t.currentModel??""]?.fields[e.field];if(i?.kind==="object")throw new Error(`Field '${e.field}' is a relation \u2014 toSql() cannot aggregate relation lists. Use toPrisma() instead.`);if(o?.includes("."))throw new Error(`aggregate.field '${o}' contains a nested path \u2014 toSql() only supports flat field names. Use check() for nested paths.`);if(i?.kind==="scalar"&&i?.isList===true){if(o)throw new Error("aggregate.field is not supported for native array types. Use a JSONB column for object arrays.");return `(SELECT ${a==="SUM"?"COALESCE(SUM(elem), 0)":"AVG(elem)"} FROM unnest(${r}) AS elem)`}if(o){let m=`(elem->>'${o}')::numeric`;return `(SELECT ${a==="SUM"?`COALESCE(SUM(${m}), 0)`:`AVG(${m})`} FROM jsonb_array_elements(${r}) AS elem)`}let l="elem::numeric";return `(SELECT ${a==="SUM"?`COALESCE(SUM(${l}), 0)`:`AVG(${l})`} FROM jsonb_array_elements_text(${r}) AS elem)`},sg=(e,t)=>{if(e.value!==void 0)return {type:"value",value:e.value};if(e.path){if(e.path.startsWith("$.")){let r=e.path.substring(2);return {type:"column",sql:t.currentAlias?`${k(t.currentAlias)}.${k(r)}`:I(r)}}if(!t.context)throw new Error(`BuilderState.context is required to resolve path '${e.path}'. Pass context in options.`);return {type:"value",value:T(t.context,e.path)}}throw new Error("Aggregate rule requires value or path")},lg=(e,t,r)=>{let n=sg(t,r),o=n.type==="value"?n.value:void 0,a=n.type==="column"?n.sql:void 0;switch(t.operator){case h.equals:return a?`${e} = ${a}`:o===null?`${e} IS NULL`:`${e} = ${A(r,o)}`;case h.notEquals:return a?`${e} <> ${a}`:o===null?`${e} IS NOT NULL`:`${e} <> ${A(r,o)}`;case h.lessThan:return a?`${e} < ${a}`:`${e} < ${A(r,o)}`;case h.lessThanEquals:return a?`${e} <= ${a}`:`${e} <= ${A(r,o)}`;case h.greaterThan:return a?`${e} > ${a}`:`${e} > ${A(r,o)}`;case h.greaterThanEquals:return a?`${e} >= ${a}`:`${e} >= ${A(r,o)}`;case h.between:{let i=o;if(!Array.isArray(i)||i.length!==2)throw new Error("between requires two values");let[s,l]=i[0]<=i[1]?i:[i[1],i[0]];return `${e} BETWEEN ${A(r,s)} AND ${A(r,l)}`}case h.notBetween:{let i=o;if(!Array.isArray(i)||i.length!==2)throw new Error("notBetween requires two values");let[s,l]=i[0]<=i[1]?i:[i[1],i[0]];return `${e} NOT BETWEEN ${A(r,s)} AND ${A(r,l)}`}default:throw new Error(`Operator '${t.operator}' is not supported for aggregate rules`)}};var fg="Windowing (orderBy/take/skip) is not supported by toSql(); evaluate with check().",Qi=(e,t)=>{if(ne(e))throw new Error(fg);if(!e.field)throw new Error("toSql: ArrayRule.field is required (fieldless arrayOps are check-only)");let r=I(e.field),n=t.map?.models[t.currentModel??""]?.fields[e.field],o=n?.kind==="scalar"&&n?.isList===true,a=o?`array_length(${r}, 1)`:`jsonb_array_length(${r})`;switch(e.arrayOperator){case O.empty:return o?`(${r} IS NULL OR ${a} IS NULL)`:`(${r} IS NULL OR ${a} = 0)`;case O.notEmpty:return o?`(${r} IS NOT NULL AND ${a} IS NOT NULL)`:`(${r} IS NOT NULL AND ${a} > 0)`;case O.all:case O.any:case O.none:case O.atLeast:case O.atMost:case O.exactly:throw new Error(`Array operator '${e.arrayOperator}' with conditions is not supported in SQL. Use application-level filtering for complex array operations.`);default:throw new Error(`Unknown array operator: ${e.arrayOperator}`)}};var gn=e=>{let t={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};return e.map(r=>{let n=t[r.toLowerCase()];if(n===void 0)throw new Error(`Unknown day name: ${r}`);return n})};var At=(e,t)=>{if(!t.map||!t.currentModel||!t.currentAlias)return I(e);let r=e.split("."),n=t.currentModel,o=t.currentAlias;for(let a=0;a<r.length;a++){let i=t.map.models[n];if(!i)return I(e);let s=i.fields[r[a]];if(!s)return I(e);if(s.kind==="object"){let f=`${o}.${r[a]}`,m=t.joinRegistry?.get(f),p;if(m)p=m;else {let u=t.joinCounter;if(!u)return I(e);p=`t${++u.n}`;let d=ug(t.map,n,o,s,p);if(!d)return I(e);t.joins?.push(d),t.joinRegistry?.set(f,p);}n=s.type,o=p;continue}let l=r.slice(a);return Gi(l.join("."),o)}return I(e)},ug=(e,t,r,n,o)=>{let a=n.type,i=e.models[a]?.dbName??a,s;if(n.fromFields&&n.fromFields.length>0&&n.toFields&&n.toFields.length>0)s=n.fromFields.map((l,f)=>`${k(o)}.${k(n.toFields?.[f]??"")} = ${k(r)}.${k(l)}`).join(" AND ");else {let l=pg(e,a,t,n.relationName);if(!l)return null;s=(l.fromFields??[]).map((f,m)=>`${k(o)}.${k(f)} = ${k(r)}.${k(l.toFields?.[m]??"")}`).join(" AND ");}return `LEFT JOIN ${k(i)} AS ${k(o)} ON ${s}`},pg=(e,t,r,n)=>{let o=e.models[t];if(!o)return null;for(let a of Object.values(o.fields))if(a.kind==="object"&&a.type===r&&(a.fromFields?.length??0)>0&&(a.toFields?.length??0)>0&&(n===void 0||a.relationName===n))return a;return null};var Xi=(e,t)=>{let r=At(e.field,t),n=mg(e,t),o=n.type==="value"?n.value:void 0,a=n.type==="column"?n.sql:void 0;switch(e.dateOperator){case E.before:return a!==void 0?`${r} < ${a}`:`${r} < ${A(t,o)}`;case E.after:return a!==void 0?`${r} > ${a}`:`${r} > ${A(t,o)}`;case E.onOrBefore:return a!==void 0?`${r} <= ${a}`:`${r} <= ${A(t,o)}`;case E.onOrAfter:return a!==void 0?`${r} >= ${a}`:`${r} >= ${A(t,o)}`;case E.within:{if(!N(e.value))throw new Error("within date operator requires a range date expression");let[i,s]=dt(e.value,t.dateConfig??{});return `${r} BETWEEN ${A(t,i.toDate())} AND ${A(t,s.toDate())}`}case E.between:{let i=o;if(!Array.isArray(i)||i.length!==2)throw new Error("between date operator requires an array of two values");let[s,l]=Ji(i.map(Yi(t)));return `${r} BETWEEN ${A(t,s)} AND ${A(t,l)}`}case E.notBetween:{let i=o;if(!Array.isArray(i)||i.length!==2)throw new Error("notBetween date operator requires an array of two values");let[s,l]=Ji(i.map(Yi(t)));return `${r} NOT BETWEEN ${A(t,s)} AND ${A(t,l)}`}case E.dayIn:{if(!Array.isArray(e.value))throw new Error("dayIn operator requires an array of day names");let i=gn(e.value.map(s=>String(s)));return `EXTRACT(DOW FROM ${r}) = ANY(${A(t,i)})`}case E.dayNotIn:{if(!Array.isArray(e.value))throw new Error("dayNotIn operator requires an array of day names");let i=gn(e.value.map(s=>String(s)));return `EXTRACT(DOW FROM ${r}) <> ALL(${A(t,i)})`}default:throw new Error(`Unknown date operator: ${e.dateOperator}`)}},Ji=e=>{let[t,r]=e;return dg(t,r)<=0?[t,r]:[r,t]},dg=(e,t)=>{let r=Zi(e),n=Zi(t);return r<n?-1:r>n?1:0},Zi=e=>e instanceof Date?e.getTime():typeof e=="number"||typeof e=="string"?e:String(e),es=(e,t)=>{if(e===void 0||!je(e))return e;let r=z(e,Ft(t.dateConfig??{}));if(!r.isValid())throw new Error(`Invalid date value: ${String(e)}`);return r.toDate()},Yi=e=>t=>N(t)?me(t,e.dateConfig??{}).toDate():es(t,e),mg=(e,t)=>{if(e.value!==void 0)return N(e.value)&&e.dateOperator!==E.within?{type:"value",value:xr(e.value,e.dateOperator,t.dateConfig??{}).toDate()}:{type:"value",value:Array.isArray(e.value)?e.value:es(e.value,t)};if(e.path){if(e.path.startsWith("$.")){let r=e.path.substring(2);return {type:"column",sql:t.currentAlias?`${k(t.currentAlias)}.${k(r)}`:I(r)}}if(!t.context)throw new Error(`BuilderState.context is required to resolve date path '${e.path}'. Pass context in options when calling toSql().`);return {type:"value",value:T(t.context,e.path)}}return {type:"value",value:void 0}};var ts=(e,t)=>{if(e.fuzzy)throw new Error("Fuzzy matching has no SQL equivalent \u2014 evaluate it in memory with check().");let r=At(e.field,t),n=s=>ct(e.caseInsensitive)?`LOWER(${s})`:s,o=cg(e,t),a=o.type==="value"?o.value:void 0,i=o.type==="column"?o.sql:void 0;switch(e.operator){case h.equals:return i!==void 0?`${n(r)} = ${n(i)}`:a===null?`${r} IS NULL`:`${n(r)} = ${n(A(t,a))}`;case h.notEquals:return i!==void 0?`${n(r)} <> ${n(i)}`:a===null?`${r} IS NOT NULL`:`${n(r)} <> ${n(A(t,a))}`;case h.lessThan:return i!==void 0?`${r} < ${i}`:`${r} < ${A(t,a)}`;case h.lessThanEquals:return i!==void 0?`${r} <= ${i}`:`${r} <= ${A(t,a)}`;case h.greaterThan:return i!==void 0?`${r} > ${i}`:`${r} > ${A(t,a)}`;case h.greaterThanEquals:return i!==void 0?`${r} >= ${i}`:`${r} >= ${A(t,a)}`;case h.in:return !Array.isArray(a)||a.length===0?"FALSE":`${r} = ANY(${A(t,a)})`;case h.notIn:return !Array.isArray(a)||a.length===0?"TRUE":`${r} <> ALL(${A(t,a)})`;case h.contains:return `${n(r)} LIKE ${n(A(t,`%${qt(String(a))}%`))}`;case h.notContains:return `${n(r)} NOT LIKE ${n(A(t,`%${qt(String(a))}%`))}`;case h.startsWith:return `${n(r)} LIKE ${n(A(t,`${qt(String(a))}%`))}`;case h.endsWith:return `${n(r)} LIKE ${n(A(t,`%${qt(String(a))}`))}`;case h.matches:return `${r} ~ ${A(t,a)}`;case h.notMatches:return `${r} !~ ${A(t,a)}`;case h.between:{let s=a;if(!Array.isArray(s)||s.length!==2)throw new Error("between operator requires an array of two values");let[l,f]=s[0]<=s[1]?s:[s[1],s[0]];return `${r} BETWEEN ${A(t,l)} AND ${A(t,f)}`}case h.notBetween:{let s=a;if(!Array.isArray(s)||s.length!==2)throw new Error("notBetween operator requires an array of two values");let[l,f]=s[0]<=s[1]?s:[s[1],s[0]];return `${r} NOT BETWEEN ${A(t,l)} AND ${A(t,f)}`}case h.isEmpty:return `(${r} IS NULL OR ${r} = '')`;case h.notEmpty:return `(${r} IS NOT NULL AND ${r} <> '')`;case h.exists:return `${r} IS NOT NULL`;case h.notExists:return `${r} IS NULL`;default:throw new Error(`Unknown operator: ${e.operator}`)}},cg=(e,t)=>{if(e.value!==void 0)return {type:"value",value:e.value};if(e.path){if(e.path.startsWith("$.")){let r=e.path.substring(2);return {type:"column",sql:t.currentAlias?`${k(t.currentAlias)}.${k(r)}`:I(r)}}if(!t.context)throw new Error(`BuilderState.context is required to resolve path '${e.path}'. Pass context in options when calling toSql().`);return {type:"value",value:T(t.context,e.path)}}if(e.bind!==void 0)throw new Error(`Unresolved binding '${e.bind}' for field '${e.field}' \u2014 resolve bindings (resolveLensBindings) before compiling to SQL.`);return {type:"value",value:void 0}};var Rt,rs=e=>{Rt=e;},gg=(e,t,r)=>{let n=e.split("."),o=r;for(let a=0;a<n.length;a++){let i=t.models[o];if(!i)return false;let s=i.fields[n[a]];if(!s)return false;if(s.kind==="bridge")return true;if(s.kind==="object"){o=s.type;continue}return false}return false},yg=(e,t,r)=>{let n=e.split("."),o=r;for(let a of n){let i=t.models[o]?.fields[a];if(!i||i.kind!=="object")return null;o=i.type;}return o},ge=(e,t)=>{if(typeof e=="boolean"||!t.map||!t.currentModel)return false;if("all"in e)return e.all.some(r=>ge(r,t));if("any"in e)return e.any.some(r=>ge(r,t));if("if"in e)return ge(e.if,t)||ge(e.then,t)||e.else!==void 0&&ge(e.else,t);if("field"in e&&typeof e.field=="string"&&e.field!==""){if(gg(e.field,t.map,t.currentModel))return true;if("condition"in e&&e.condition!==void 0){let r=yg(e.field,t.map,t.currentModel);if(r&&ge(e.condition,{...t,currentModel:r}))return true}}return false},ns=(e,t)=>e.all.length===0?"TRUE":`(${e.all.map(n=>Rt(n,t)).join(" AND ")})`,os=(e,t)=>e.any.length===0?"FALSE":`(${e.any.map(n=>Rt(n,t)).join(" OR ")})`,as=(e,t)=>{if(ge(e.if,t)||ge(e.then,t)||e.else!==void 0&&ge(e.else,t))return "TRUE";let r=Rt(e.if,t),n=Rt(e.then,t);if(e.else!==void 0){let o=Rt(e.else,t);return `((NOT(${r}) OR ${n}) AND (${r} OR ${o}))`}return `(NOT(${r}) OR ${n})`};var hg=(e,t,r)=>{let n=e.split("."),o=r;for(let a=0;a<n.length;a++){let i=t.models[o];if(!i)return false;let s=i.fields[n[a]];if(!s)return false;if(s.kind==="bridge")return true;if(s.kind==="object"){o=s.type;continue}return false}return false},It=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";if("field"in e&&typeof e.field=="string"&&t.map&&t.currentModel&&hg(e.field,t.map,t.currentModel))return "TRUE";if("all"in e)return ns(e,t);if("any"in e)return os(e,t);if("if"in e)return as(e,t);if("arrayOperator"in e)return Qi(e,t);if("dateOperator"in e)return Xi(e,t);if("aggregate"in e)return Hi(e,t);if("field"in e)return ts(e,t);throw new Error("Unknown condition type")};rs(It);var is=(e,t)=>{let r=!!(t?.map&&t?.model),n=t?.alias??(r?"t0":void 0),o={params:[],paramIndex:0,context:t?.context,dateConfig:{now:t?.now,timeZone:t?.timeZone,weekStart:t?.weekStart},map:t?.map,currentModel:t?.model,currentAlias:n,joinCounter:r?{n:0}:void 0,joins:r?[]:void 0,joinRegistry:r?new Map:void 0};return {sql:It(e,o),params:o.params,joins:o.joins??[]}};var Ve=e=>`"${e.replace(/"/g,'""')}"`,wg=(e,t)=>{let r=[...e,...t];return r.length===1?r[0]:{all:r}},ss=(e,t)=>{let[r,...n]=t;if(n.length===0){e[r]=true;return}let o=e[r],a=o!==void 0&&o!==true?o.select:{};ss(a,n),e[r]={select:a};},xg=e=>{let t={};for(let r of e)ss(t,r.split("."));return t},bg=(e,t,r,n,o,a,i)=>{let s=Ui(i,{map:e,mapName:t,model:r}),l=s.steps[s.steps.length-1],f=l&&"where"in l?l.where:{},m=s.steps.filter(c=>c.operation!=="where"),p={[n]:true,...o?{[o]:true}:{},...a?xg(a):{}},u={model:r,...a?{}:{distinct:[n]},select:p,where:f,...m.length?{steps:s.steps}:{}},d;try{let c,y,g,w;if(a){let M={params:[],paramIndex:0,map:e.maps[t],currentModel:r,currentAlias:"t0",joinCounter:{n:0},joins:[],joinRegistry:new Map};c=It(i,M),w=a.map(W=>At(W,M)),y=M.params,g=M.joins??[];}else ({sql:c,params:y,joins:g}=is(i,{map:e.maps[t],model:r,alias:"t0"}));let v=g.length?` ${g.join(" ")}`:"",b=c?.trim()?` WHERE ${c}`:"";d={sql:`SELECT DISTINCT ${[`${Ve("t0")}.${Ve(n)}`,...o?[`${Ve("t0")}.${Ve(o)}`]:[],...w?w.map((M,W)=>`${M} AS ${Ve(`__group_${W}`)}`):[]].join(", ")} FROM ${Ve(r)} AS ${Ve("t0")}${v}${b}`,params:y};}catch(c){d={sql:null,params:[],error:c instanceof Error?c.message:String(c)};}return {prisma:u,sql:d}},vg=e=>{let t=j(e),{lens:r}=t,n=Bt(e),o=[];for(let[a,i]of n){let s=a.split(".").slice(1);for(let[l,f]of Object.entries(i.sources)){let m=i.sourceLabels[l],p=i.sourceGroupBys[l],u=Rr(t,i.mapName,i.modelName,s,p??[],f),d=wg(i.whereClauses,[...f,...u]),{prisma:c,sql:y}=bg(r,i.mapName,i.modelName,l,m,p,d);o.push({path:a,mapName:i.mapName,model:i.modelName,field:l,...m!==void 0?{label:m}:{},...p!==void 0?{groupBy:p}:{},composedWhere:d,prisma:c,sql:y});}}return o};var Og=(e,t,r={})=>{let n=r.rowShape??"prisma",o=new Map;for(let a of t){let i=a[e.field],s=Array.isArray(i)?i:[i],l=e.label===void 0?void 0:a[e.label],f=l==null?void 0:String(l),m=e.groupBy===void 0?void 0:kr(a,n==="sql"?e.groupBy.map((p,u)=>`__group_${u}`):e.groupBy);for(let p of s)p==null||typeof p=="object"||Tr(o,String(p),f,m);}return {path:e.path,mapName:e.mapName,model:e.model,field:e.field,options:Cr(o)}};var Sg=(e,t)=>{let r=[...e];for(let n of t.split(".").slice(1)){let o=[];for(let a of r){let i=a?.[n];Array.isArray(i)?o.push(...i):i!=null&&o.push(i);}r=o;}return r},$g=e=>e.length===0?true:e.length===1?e[0]:{all:e},Eg=(e,t,r)=>{let n=[],o=j(e);for(let[a,i]of Bt(e)){let s=Object.entries(i.sources);if(s.length===0)continue;let l=Sg(t,a),f=a.split(".").slice(1);for(let[m,p]of s){let u=i.sourceLabels[m],d=i.sourceGroupBys[m],c=Rr(o,i.mapName,i.modelName,f,d??[],p),y=$g([...p,...c]),g=new Map;for(let w of l){if(H(y,w,r)!==true)continue;let v=w[m],b=Array.isArray(v)?v:[v],x=u===void 0?void 0:w[u],$=x==null?void 0:String(x),M=d===void 0?void 0:kr(w,d);for(let W of b)W==null||typeof W=="object"||Tr(g,String(W),$,M);}n.push({path:a,mapName:i.mapName,model:i.modelName,field:m,options:Cr(g)});}}return n};var Ag=new Set(["Int","BigInt","Float","Decimal","DateTime","Boolean","String"]),ls=(e,t,r)=>{let n=r.split("."),{mapName:o,modelName:a}=t;for(let i=0;i<n.length;i+=1){let s=e.maps[o]?.models[a]?.fields[n[i]];if(!s)return;if(i===n.length-1)return {entry:s,mapName:o};if(s.kind!=="object"&&s.kind!=="bridge")return;let l=L(s,o);if(!l)return;({mapName:o,modelName:a}=l);}},Rg=(e,t,r)=>{if(!r)return;let n=ls(e,t,r);return !n||n.entry.kind!=="object"&&n.entry.kind!=="bridge"?void 0:L(n.entry,n.mapName)??void 0},Fe=(e,t,r)=>{if(typeof e=="boolean")return e;if("all"in e)return {...e,all:e.all.map(n=>Fe(n,t,r))};if("any"in e)return {...e,any:e.any.map(n=>Fe(n,t,r))};if("if"in e)return {...e,if:Fe(e.if,t,r),then:Fe(e.then,t,r),...e.else!==void 0?{else:Fe(e.else,t,r)}:{}};if("arrayOperator"in e||"aggregate"in e){let n=Rg(t,r,e.field);return n?{...e,...e.condition!==void 0?{condition:Fe(e.condition,t,n)}:{},...e.filter!==void 0?{filter:Fe(e.filter,t,n)}:{}}:e}if("dateOperator"in e)return e;if("operator"in e){if(e.coerceType)return e;let n=ls(t,r,e.field);return !n||n.entry.kind!=="scalar"||!Ag.has(n.entry.type)?e:{...e,coerceType:n.entry.type}}return e},kg=(e,t)=>{let{lens:r}=j(t);return Fe(e,r,{mapName:r.mapName,modelName:r.model})};var Tg=new Set(["year","quarter","month","week","isoWeek","day","hour","minute","second"]),Cg=new Set(["years","quarters","months","weeks","days","hours","minutes","seconds"]),Mg=new Set(Object.keys(oe)),Pg=new Set(Object.keys(Pe)),Dg=new Set(Object.keys(Me)),Fg=(e,t={})=>{let r={target:t.target??"check",errors:[]};return ye(e,"$",r),{ok:r.errors.length===0,errors:r.errors}},LT=(e,t={})=>{let r=Fg(e,t);if(r.ok)return;let n=r.errors.map(o=>`${o.path}: ${o.message}`).join(`
|
|
5
|
+
`)}`)};var Bt=(e,t={})=>{let r=j(e),n=new Map,o=new Map;for(let i of t.sourceValues??[])o.set(`${i.path}|${i.field}`,i.options);let a=(i,s,l,f)=>{if(n.has(f))return;let m=r.lens.maps[i]?.models[s];if(!m)return;let p=G(r,i,s,l),u={};for(let[g,w]of Object.entries(m.fields)){if(!Re(p,g))continue;let v=o.get(`${f}|${g}`),b=p.enumValuesByField.get(g),x=b!==void 0?{...w,values:b}:w,$=v??b?.map(M=>({value:M,label:M}));$&&(x={...x,options:$}),u[g]=x;}let d={};for(let[g,w]of p.sources)Re(p,g)&&(d[g]=w);let c={};for(let[g,w]of p.sourceLabels)Re(p,g)&&(c[g]=w);let y={};for(let[g,w]of p.sourceGroupBys)Re(p,g)&&(y[g]=w);n.set(f,{mapName:i,modelName:s,fields:u,whereClauses:p.whereClauses,sources:d,sourceLabels:c,sourceGroupBys:y});for(let g of p.relations.keys()){let w=m.fields[g];if(!w)continue;let v=L(w,i);v&&a(v.mapName,v.modelName,[...l,g],`${f}.${g}`);}};return a(r.lens.mapName,r.lens.model,[],r.lens.model),n};var Mr=(e,t,r,n)=>{let o=e.models[t];if(!o)return null;for(let a of Object.values(o.fields))if(a.kind==="object"&&a.type===r&&(a.fromFields?.length??0)>0&&(a.toFields?.length??0)>0&&(n===void 0||a.relationName===n))return a;return null};var ae=(e,t)=>{let r=e.split("."),n=t;for(let o=r.length-1;o>=0;o--)n={[r[o]]:n};return n};var Ti,Ci=e=>{Ti=e;},Mi=(e,t,r)=>{if(ne(e))throw new Error("Windowing (orderBy/take/skip) is not supported by toPrisma(); evaluate with check().");if(!t?.map||!t?.model||!r)throw new Error("Aggregate rules require a FieldMap and model to generate a Prisma plan. Pass { map, model } options to toPrisma().");if(!e.aggregate.field)throw new Error("Prisma aggregate rules require aggregate.field to specify the numeric field on the related model.");if(e.path)throw new Error("path is not supported for Prisma aggregate rules; use value instead.");return Uc(e,t,r)},Wc=(e,t,r)=>{let n=e.split("."),o=[],a=r;for(let i=0;i<n.length;i++){let s=n[i],l=t.models[a]?.fields[s];if(!l||l.kind!=="object")throw new Error(`Field '${s}' is not a relation in model '${a}'. Prisma aggregate rules only support relation fields.`);if(i===n.length-1){if(!l.isList)throw new Error(`Field '${s}' is not a list relation in model '${a}'.`);return {segments:n,intermediateRelations:o,terminalModel:a,terminalEntry:l}}if(l.isList)throw new Error(`Intermediate field '${s}' in path '${e}' is a list relation. Only the final segment can be a list relation for aggregate rules.`);o.push({fieldName:s,entry:l,onModel:a}),a=l.type;}throw new Error(`Field path '${e}' did not terminate at a list relation.`)},Uc=(e,t,r)=>{let{map:n,model:o}=t,{intermediateRelations:a,terminalModel:i,terminalEntry:s}=Wc(e.field,n,o),l=s.type,f=e.aggregate.field??"",m=n.models[l]?.fields[f];if(!m)throw new Error(`aggregate.field '${f}' does not exist on model '${l}'.`);if(m.kind!=="scalar")throw new Error(`aggregate.field '${f}' on model '${l}' must be a scalar field, got '${m.kind}'.`);if(m.type==="Json")throw new Error(`aggregate.field '${f}' on model '${l}' is a Json field \u2014 aggregate rules require a numeric scalar.`);let p,u;if(s.fromFields&&s.fromFields.length>0){if(s.fromFields.length>1)throw new Error("Aggregate rules do not support composite FK relations.");p=s.toFields?.[0]??"id",u=s.fromFields[0];}else {let b=Mr(n,l,i,s.relationName);if(!b)throw new Error(`Cannot determine FK relationship between '${i}' and '${l}'. Ensure the FieldMap contains both sides of the relation.`);if((b.fromFields?.length??0)>1)throw new Error("Aggregate rules do not support composite FK relations.");p=b.fromFields?.[0]??"",u=b.toFields?.[0]??"";}let d=e.condition?Ti(e.condition,{...t,model:l},r):{},c=e.aggregate.mode==="sum"?"_sum":"_avg",y={[f]:{[c]:Gc(e)}},g={operation:"groupBy",model:l,args:{by:[p],where:d,having:y},extract:p},w=r.steps.length;r.steps.push(g);let v={__step:w};if(a.length>0){let b={[u]:{in:v}},x=a.map($=>$.fieldName).join(".");return ae(x,b)}return {[u]:{in:v}}},Gc=e=>{let t=e.value;switch(e.operator){case h.equals:return {equals:t};case h.notEquals:return {not:t};case h.lessThan:return {lt:t};case h.lessThanEquals:return {lte:t};case h.greaterThan:return {gt:t};case h.greaterThanEquals:return {gte:t};case h.between:{if(!Array.isArray(t)||t.length!==2)throw new Error("between requires two values");let[r,n]=t,[o,a]=r<=n?[r,n]:[n,r];return {gte:o,lte:a}}case h.notBetween:throw new Error("Operator 'notBetween' is not supported for Prisma aggregate rules.");default:throw new Error(`Operator '${e.operator}' is not supported for Prisma aggregate rules.`)}};var Pi=(e,t,r,n)=>{let{map:o,model:a}=t;if(!e.field)throw new Error("toPrisma: count-based ArrayRule requires a field path");let i=o.models[a]?.fields[e.field];if(!i||i.kind!=="object")throw new Error(`Field '${e.field}' is not a relation in model '${a}'. Count operators require a relation field.`);if(!i.isList)throw new Error(`Field '${e.field}' is not a list relation in model '${a}'. Count operators only apply to one-to-many or many-to-many relations.`);let s=i.type,l,f;if(i.fromFields&&i.fromFields.length>0){if(i.fromFields.length>1)throw new Error(`Count operators (atLeast/atMost/exactly) do not support composite FK relations ('${a}.${e.field}'). Use prisma.$queryRaw for composite FK count filtering.`);l=i.toFields?.[0]??"id",f=i.fromFields[0];}else {let g=Mr(o,s,a,i.relationName);if(!g){let v=Object.values(o.models[s]?.fields??{}).some(b=>b.kind==="object"&&b.type===a&&b.isList&&!b.fromFields?.length);throw new Error(v?`'${a}.${e.field}' is an implicit many-to-many relation. Count operators require an explicit join model with a FK \u2014 convert to an explicit @relation or use prisma.$queryRaw.`:`Cannot determine FK relationship between '${a}' and '${s}'. Ensure the FieldMap contains both sides of the relation.`)}if((g.fromFields?.length??0)>1)throw new Error(`Count operators (atLeast/atMost/exactly) do not support composite FK relations ('${a}.${e.field}'). Use prisma.$queryRaw for composite FK count filtering.`);l=g.fromFields?.[0]??"",f=g.toFields?.[0]??"";}let m=e.condition?n(e.condition,{...t,model:s},r):{},p=e.count??1,u=Kc(e.arrayOperator,p,l),d={operation:"groupBy",model:s,args:{by:[l],where:m,having:u},extract:l},c=r.steps.length;r.steps.push(d);let y={__step:c};return {[f]:{in:y}}},Kc=(e,t,r)=>{switch(e){case O.atLeast:return {[r]:{_count:{gte:t}}};case O.atMost:return {[r]:{_count:{lte:t}}};case O.exactly:return {[r]:{_count:{equals:t}}};default:throw new Error("unreachable")}};var zc="Windowing (orderBy/take/skip) is not supported by toPrisma() for this rule; only extremal (take:1, single orderBy on the compared field, aligned direction) rewrites to every/some. Evaluate other windowed rules with check().",Nt,Di=e=>{Nt=e;},pn=(e,t,r)=>{if(ne(e)){let o=ht(e);if(!o)throw new Error(zc);return pn(o,t,r)}if(e.arrayOperator===O.atLeast||e.arrayOperator===O.atMost||e.arrayOperator===O.exactly){if(t?.map&&t?.model&&r)return Pi(e,t,r,Nt);throw new Error(`ArrayOperator '${e.arrayOperator}' requires a FieldMap and model to generate a multi-step plan. Pass { map, model } options to toPrisma(). Without them, use prisma.$queryRaw for count-based relation filtering.`)}if(!e.field)throw new Error("toPrisma: ArrayRule.field is required (fieldless arrayOps are check-only)");let n=Jc(e,t,r);return ae(e.field,n)},Hc=(e,t,r)=>{let n=e.split("."),o=r;for(let a of n){let i=t.models[o]?.fields[a];if(!i||i.kind!=="object")return null;o=i.type;}return o},Qc=(e,t)=>{if(!t?.map||!t?.model||!e.field)return t;let r=Hc(e.field,t.map,t.model);return r?{...t,model:r}:t},Jc=(e,t,r)=>{let n=Qc(e,t);switch(e.arrayOperator){case O.all:if(!e.condition)throw new Error("ArrayOperator 'all' requires a condition");return {every:Nt(e.condition,n,r)};case O.any:if(!e.condition)throw new Error("ArrayOperator 'any' requires a condition");return {some:Nt(e.condition,n,r)};case O.none:if(!e.condition)throw new Error("ArrayOperator 'none' requires a condition");return {none:Nt(e.condition,n,r)};case O.empty:return {none:{}};case O.notEmpty:return {some:{}};default:throw new Error(`Unknown array operator: ${e.arrayOperator}`)}};var Zc=e=>({now:e?.now,timeZone:e?.timeZone,weekStart:e?.weekStart}),Fi=(e,t)=>{if(e===void 0||!je(e))return e;let r=z(e,Ft(t));if(!r.isValid())throw new Error(`Invalid date value: ${String(e)}`);return r.toDate()},Ni=(e,t)=>{let r=Yc(e,t);return ae(e.field,r)},dn=(e,t)=>{if(e.value!==void 0)return e.value;if(e.path){if(e.path.startsWith("$."))throw new Error(`Prisma WHERE has no column-to-column date comparison for path '${e.path}'. Use prisma.$queryRaw for field-to-field filtering.`);if(!t?.context)throw new Error(`options.context is required to resolve date path '${e.path}'. Pass context when calling toPrisma().`);return T(t.context,e.path)}},Yc=(e,t)=>{let r=Zc(t),n=()=>N(e.value)?xr(e.value,e.dateOperator,r).toDate():Fi(dn(e,t),r),o=a=>N(a)?me(a,r).toDate():Fi(a,r);switch(e.dateOperator){case E.before:return {lt:n()};case E.after:return {gt:n()};case E.onOrBefore:return {lte:n()};case E.onOrAfter:return {gte:n()};case E.within:{if(!N(e.value))throw new Error("within date operator requires a range date expression");let[a,i]=dt(e.value,r);return {gte:a.toDate(),lte:i.toDate()}}case E.between:{let a=dn(e,t);if(!Array.isArray(a)||a.length!==2)throw new Error("between date operator requires an array of two values");let[i,s]=_i(a.map(o));return {gte:i,lte:s}}case E.notBetween:{let a=dn(e,t);if(!Array.isArray(a)||a.length!==2)throw new Error("notBetween date operator requires an array of two values");let[i,s]=_i(a.map(o));return {NOT:{gte:i,lte:s}}}case E.dayIn:throw new Error("DateOperator 'dayIn' has no Prisma equivalent. Use prisma.$queryRaw with EXTRACT(DOW FROM ...) for day-of-week filtering.");case E.dayNotIn:throw new Error("DateOperator 'dayNotIn' has no Prisma equivalent. Use prisma.$queryRaw with EXTRACT(DOW FROM ...) for day-of-week filtering.");default:throw new Error(`Unknown date operator: ${e.dateOperator}`)}},_i=e=>{let[t,r]=e;return Xc(t,r)<=0?[t,r]:[r,t]},Xc=(e,t)=>{let r=Bi(e),n=Bi(t);return r<n?-1:r>n?1:0},Bi=e=>e instanceof Date?e.getTime():typeof e=="number"||typeof e=="string"?e:String(e);var Pr=(e,t,r)=>{let n=e.split("."),o=r;for(let a=0;a<n.length;a++){let i=t.models[o];if(!i)return {kind:"fallback"};let s=i.fields[n[a]];if(!s)return {kind:"fallback"};if(s.kind==="bridge")return {kind:"bridge"};if(s.kind==="scalar"&&s.type==="Json"&&a<n.length-1)return {kind:"json-path",stopIndex:a+1,jsonPath:n.slice(a+1)};if(s.kind==="object"){if(!t.models[s.type])return {kind:"fallback"};o=s.type;continue}return {kind:"direct"}}return {kind:"direct"}};var Li=(e,t)=>{if(e.operator===h.isEmpty)return {OR:[Lt(e.field,{equals:null},t),Lt(e.field,{equals:""},t)]};if(e.operator===h.notEmpty)return {AND:[Lt(e.field,{not:null},t),Lt(e.field,{not:""},t)]};let r=tg(e,t);return Lt(e.field,r,t)},eg=(e,t)=>{if(e.value!==void 0)return e.value;if(e.bind!==void 0)throw new Error(`Unresolved binding '${e.bind}' for field '${e.field}' \u2014 resolve bindings (resolveLensBindings) before compiling to Prisma.`);if(e.path){if(e.path.startsWith("$."))throw new Error(`Prisma WHERE has no column-to-column comparison for path '${e.path}'. Use prisma.$queryRaw for field-to-field filtering.`);if(!t?.context)throw new Error(`options.context is required to resolve path '${e.path}'. Pass context when calling toPrisma().`);return T(t.context,e.path)}throw new Error(`Rule for field '${e.field}' has neither value nor path set`)},tg=(e,t)=>{if(e.fuzzy)throw new Error("Fuzzy matching has no Prisma equivalent \u2014 evaluate it in memory with check().");let r=()=>eg(e,t),n=t?.datasource?.provider??br.get("prismaOptions.datasource.provider"),o=ct(e.caseInsensitive)&&Xa(n)?{mode:"insensitive"}:{};switch(e.operator){case h.equals:return {equals:r()??null,...o};case h.notEquals:return {not:r()??null,...o};case h.lessThan:return {lt:r()};case h.lessThanEquals:return {lte:r()};case h.greaterThan:return {gt:r()};case h.greaterThanEquals:return {gte:r()};case h.in:return {in:r()};case h.notIn:return {notIn:r()};case h.contains:return {contains:r(),...o};case h.notContains:return {not:{contains:r(),...o}};case h.startsWith:return {startsWith:r(),...o};case h.endsWith:return {endsWith:r(),...o};case h.matches:throw new Error("Operator 'matches' has no Prisma equivalent. Use prisma.$queryRaw for regex filtering.");case h.notMatches:throw new Error("Operator 'notMatches' has no Prisma equivalent. Use prisma.$queryRaw for regex filtering.");case h.between:{let a=r();if(!Array.isArray(a)||a.length!==2)throw new Error("between operator requires an array of two values");let[i,s]=a[0]<=a[1]?a:[a[1],a[0]];return {gte:i,lte:s}}case h.notBetween:{let a=r();if(!Array.isArray(a)||a.length!==2)throw new Error("notBetween operator requires an array of two values");let[i,s]=a[0]<=a[1]?a:[a[1],a[0]];return {NOT:{gte:i,lte:s}}}case h.isEmpty:case h.notEmpty:throw new Error("isEmpty/notEmpty handled at buildFieldRule level");case h.exists:return {not:null};case h.notExists:return {equals:null};default:throw new Error(`Unknown operator: ${e.operator}`)}},Lt=(e,t,r)=>{if(!r?.map||!r?.model)return ae(e,t);let n=Pr(e,r.map,r.model),o=e.split(".");switch(n.kind){case "fallback":case "direct":return ae(e,t);case "bridge":return {};case "json-path":{let a={path:n.jsonPath,...t},i=o.slice(0,n.stopIndex).join(".");return ae(i,a)}}};var Et,qi=e=>{Et=e;},rg=(e,t,r)=>{let n=e.split("."),o=r;for(let a of n){let i=t.models[o]?.fields[a];if(!i||i.kind!=="object")return null;o=i.type;}return o},ce=(e,t)=>{if(typeof e=="boolean"||!t?.map||!t?.model)return false;if("all"in e)return e.all.some(r=>ce(r,t));if("any"in e)return e.any.some(r=>ce(r,t));if("if"in e)return ce(e.if,t)||ce(e.then,t)||e.else!==void 0&&ce(e.else,t);if("field"in e&&typeof e.field=="string"&&e.field!==""){if(Pr(e.field,t.map,t.model).kind==="bridge")return true;if("condition"in e&&e.condition!==void 0){let n=rg(e.field,t.map,t.model);if(n&&ce(e.condition,{...t,model:n}))return true}}return false},Ii=(e,t,r)=>e.all.length===0?{}:{AND:e.all.map(n=>Et(n,t,r))},Vi=(e,t,r)=>e.any.length===0?{AND:[{id:null},{id:{not:null}}]}:{OR:e.any.map(n=>Et(n,t,r))},Wi=(e,t,r)=>{if(ce(e.if,t)||ce(e.then,t)||e.else!==void 0&&ce(e.else,t))return {};let n=Et(e.if,t,r),o={NOT:n},a=e.then===false?ji:Et(e.then,t,r);if(e.else!==void 0){let i=e.else===false?ji:Et(e.else,t,r);return {AND:[{OR:[o,a]},{OR:[n,i]}]}}return {OR:[o,a]}},ji={AND:[{id:null},{id:{not:null}}]};var jt=(e,t,r)=>{if(typeof e=="boolean"){if(e)return {};throw new Error("Boolean 'false' has no direct Prisma WHERE equivalent. toPrisma is designed for structured Rule conditions.")}if("all"in e)return Ii(e,t,r);if("any"in e)return Vi(e,t,r);if("if"in e)return Wi(e,t,r);if("arrayOperator"in e)return pn(e,t,r);if("dateOperator"in e)return Ni(e,t);if("aggregate"in e)return Mi(e,t,r);if("field"in e)return Li(e,t);throw new Error("Unknown condition type")};qi(jt);Di(jt);Ci(jt);var ng=async(e,t)=>{let r=e.steps.filter(a=>a.operation==="groupBy"),n=e.steps.find(a=>a.operation==="where");if(!n)throw new Error("executePrismaQueryPlan: result has no where step");let o=[];for(let a of r){let i=a.model.charAt(0).toLowerCase()+a.model.slice(1),s=t[i];if(!s)throw new Error(`executePrismaQueryPlan: no delegate for model '${a.model}'. Ensure prismaDelegate has a key '${i}'.`);let l=await s[a.operation](a.args);o.push(l.map(f=>f[a.extract]));}return mn(n.where,o)},mn=(e,t)=>{if(e==null)return e;if(Array.isArray(e))return e.map(r=>mn(r,t));if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return e;let n=e;if("__step"in n&&typeof n.__step=="number"){let a=n.__step;if(a>=t.length)throw new Error(`Step ref __step: ${a} out of range (${t.length} steps executed)`);return t[a]}let o={};for(let[a,i]of Object.entries(n))o[a]=mn(i,t);return o}return e};var og=e=>{if(!e?.map)return e;let t="maps"in e.map;if(t&&!e.mapName)throw new Error("toPrisma: 'map' is a FieldMapSet \u2014 'mapName' is required to resolve which map to use.");if(!t||!e.mapName)return e;let r=e.map.maps[e.mapName];if(!r)throw new Error(`toPrisma: fieldMap set has no entry for '${e.mapName}'`);return {...e,map:r}},Ui=(e,t)=>{let r={steps:[]},n=jt(e,og(t),r);return {steps:[...r.steps,{operation:"where",where:n}]}};var k=e=>`"${e.replace(/"/g,'""')}"`;var A=(e,t)=>(e.params.push(t),`$${++e.paramIndex}`);var qt=e=>e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_"),I=e=>{let t=e.split(".");if(t.length===1)return k(e);let[r,...n]=t;return n.length===0?k(r):Ki(k(r),n)},Gi=(e,t)=>{let r=e.split(".");if(r.length===1)return `${k(t)}.${k(e)}`;let[n,...o]=r;return Ki(`${k(t)}.${k(n)}`,o)},cn=e=>`'${e.replace(/'/g,"''")}'`,Ki=(e,t)=>{if(t.length===0)return e;let r=t.slice(0,-1).map(cn).join("->"),n=cn(t[t.length-1]);return r?`${e}->${r}->>${n}`:`${e}->>${n}`},zi=e=>{let t=e.split(".");if(t.length===1)return k(e);let[r,...n]=t;return n.length===0?k(r):ag(k(r),n)},ag=(e,t)=>{let r=t.map(cn).join("->");return `${e}->${r}`};var Hi=(e,t)=>{if(ne(e))throw new Error("Windowing (orderBy/take/skip) is not supported by toSql(); evaluate with check().");if(e.condition)throw new Error("Aggregate condition filtering is not yet supported by toSql(). Use check() for in-memory evaluation or toPrisma() for database queries.");let r=ig(e,t);return lg(r,e,t)},ig=(e,t)=>{let r=zi(e.field),{mode:n,field:o}=e.aggregate,a=n==="sum"?"SUM":"AVG",i=t.map?.models[t.currentModel??""]?.fields[e.field];if(i?.kind==="object")throw new Error(`Field '${e.field}' is a relation \u2014 toSql() cannot aggregate relation lists. Use toPrisma() instead.`);if(o?.includes("."))throw new Error(`aggregate.field '${o}' contains a nested path \u2014 toSql() only supports flat field names. Use check() for nested paths.`);if(i?.kind==="scalar"&&i?.isList===true){if(o)throw new Error("aggregate.field is not supported for native array types. Use a JSONB column for object arrays.");return `(SELECT ${a==="SUM"?"COALESCE(SUM(elem), 0)":"AVG(elem)"} FROM unnest(${r}) AS elem)`}if(o){let m=`(elem->>'${o}')::numeric`;return `(SELECT ${a==="SUM"?`COALESCE(SUM(${m}), 0)`:`AVG(${m})`} FROM jsonb_array_elements(${r}) AS elem)`}let l="elem::numeric";return `(SELECT ${a==="SUM"?`COALESCE(SUM(${l}), 0)`:`AVG(${l})`} FROM jsonb_array_elements_text(${r}) AS elem)`},sg=(e,t)=>{if(e.value!==void 0)return {type:"value",value:e.value};if(e.path){if(e.path.startsWith("$.")){let r=e.path.substring(2);return {type:"column",sql:t.currentAlias?`${k(t.currentAlias)}.${k(r)}`:I(r)}}if(!t.context)throw new Error(`BuilderState.context is required to resolve path '${e.path}'. Pass context in options.`);return {type:"value",value:T(t.context,e.path)}}throw new Error("Aggregate rule requires value or path")},lg=(e,t,r)=>{let n=sg(t,r),o=n.type==="value"?n.value:void 0,a=n.type==="column"?n.sql:void 0;switch(t.operator){case h.equals:return a?`${e} = ${a}`:o===null?`${e} IS NULL`:`${e} = ${A(r,o)}`;case h.notEquals:return a?`${e} <> ${a}`:o===null?`${e} IS NOT NULL`:`${e} <> ${A(r,o)}`;case h.lessThan:return a?`${e} < ${a}`:`${e} < ${A(r,o)}`;case h.lessThanEquals:return a?`${e} <= ${a}`:`${e} <= ${A(r,o)}`;case h.greaterThan:return a?`${e} > ${a}`:`${e} > ${A(r,o)}`;case h.greaterThanEquals:return a?`${e} >= ${a}`:`${e} >= ${A(r,o)}`;case h.between:{let i=o;if(!Array.isArray(i)||i.length!==2)throw new Error("between requires two values");let[s,l]=i[0]<=i[1]?i:[i[1],i[0]];return `${e} BETWEEN ${A(r,s)} AND ${A(r,l)}`}case h.notBetween:{let i=o;if(!Array.isArray(i)||i.length!==2)throw new Error("notBetween requires two values");let[s,l]=i[0]<=i[1]?i:[i[1],i[0]];return `${e} NOT BETWEEN ${A(r,s)} AND ${A(r,l)}`}default:throw new Error(`Operator '${t.operator}' is not supported for aggregate rules`)}};var fg="Windowing (orderBy/take/skip) is not supported by toSql(); evaluate with check().",Qi=(e,t)=>{if(ne(e))throw new Error(fg);if(!e.field)throw new Error("toSql: ArrayRule.field is required (fieldless arrayOps are check-only)");let r=I(e.field),n=t.map?.models[t.currentModel??""]?.fields[e.field],o=n?.kind==="scalar"&&n?.isList===true,a=o?`array_length(${r}, 1)`:`jsonb_array_length(${r})`;switch(e.arrayOperator){case O.empty:return o?`(${r} IS NULL OR ${a} IS NULL)`:`(${r} IS NULL OR ${a} = 0)`;case O.notEmpty:return o?`(${r} IS NOT NULL AND ${a} IS NOT NULL)`:`(${r} IS NOT NULL AND ${a} > 0)`;case O.all:case O.any:case O.none:case O.atLeast:case O.atMost:case O.exactly:throw new Error(`Array operator '${e.arrayOperator}' with conditions is not supported in SQL. Use application-level filtering for complex array operations.`);default:throw new Error(`Unknown array operator: ${e.arrayOperator}`)}};var gn=e=>{let t={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};return e.map(r=>{let n=t[r.toLowerCase()];if(n===void 0)throw new Error(`Unknown day name: ${r}`);return n})};var At=(e,t)=>{if(!t.map||!t.currentModel||!t.currentAlias)return I(e);let r=e.split("."),n=t.currentModel,o=t.currentAlias;for(let a=0;a<r.length;a++){let i=t.map.models[n];if(!i)return I(e);let s=i.fields[r[a]];if(!s)return I(e);if(s.kind==="object"){let f=`${o}.${r[a]}`,m=t.joinRegistry?.get(f),p;if(m)p=m;else {let u=t.joinCounter;if(!u)return I(e);p=`t${++u.n}`;let d=ug(t.map,n,o,s,p);if(!d)return I(e);t.joins?.push(d),t.joinRegistry?.set(f,p);}n=s.type,o=p;continue}let l=r.slice(a);return Gi(l.join("."),o)}return I(e)},ug=(e,t,r,n,o)=>{let a=n.type,i=e.models[a]?.dbName??a,s;if(n.fromFields&&n.fromFields.length>0&&n.toFields&&n.toFields.length>0)s=n.fromFields.map((l,f)=>`${k(o)}.${k(n.toFields?.[f]??"")} = ${k(r)}.${k(l)}`).join(" AND ");else {let l=pg(e,a,t,n.relationName);if(!l)return null;s=(l.fromFields??[]).map((f,m)=>`${k(o)}.${k(f)} = ${k(r)}.${k(l.toFields?.[m]??"")}`).join(" AND ");}return `LEFT JOIN ${k(i)} AS ${k(o)} ON ${s}`},pg=(e,t,r,n)=>{let o=e.models[t];if(!o)return null;for(let a of Object.values(o.fields))if(a.kind==="object"&&a.type===r&&(a.fromFields?.length??0)>0&&(a.toFields?.length??0)>0&&(n===void 0||a.relationName===n))return a;return null};var Xi=(e,t)=>{let r=At(e.field,t),n=mg(e,t),o=n.type==="value"?n.value:void 0,a=n.type==="column"?n.sql:void 0;switch(e.dateOperator){case E.before:return a!==void 0?`${r} < ${a}`:`${r} < ${A(t,o)}`;case E.after:return a!==void 0?`${r} > ${a}`:`${r} > ${A(t,o)}`;case E.onOrBefore:return a!==void 0?`${r} <= ${a}`:`${r} <= ${A(t,o)}`;case E.onOrAfter:return a!==void 0?`${r} >= ${a}`:`${r} >= ${A(t,o)}`;case E.within:{if(!N(e.value))throw new Error("within date operator requires a range date expression");let[i,s]=dt(e.value,t.dateConfig??{});return `${r} BETWEEN ${A(t,i.toDate())} AND ${A(t,s.toDate())}`}case E.between:{let i=o;if(!Array.isArray(i)||i.length!==2)throw new Error("between date operator requires an array of two values");let[s,l]=Ji(i.map(Yi(t)));return `${r} BETWEEN ${A(t,s)} AND ${A(t,l)}`}case E.notBetween:{let i=o;if(!Array.isArray(i)||i.length!==2)throw new Error("notBetween date operator requires an array of two values");let[s,l]=Ji(i.map(Yi(t)));return `${r} NOT BETWEEN ${A(t,s)} AND ${A(t,l)}`}case E.dayIn:{if(!Array.isArray(e.value))throw new Error("dayIn operator requires an array of day names");let i=gn(e.value.map(s=>String(s)));return `EXTRACT(DOW FROM ${r}) = ANY(${A(t,i)})`}case E.dayNotIn:{if(!Array.isArray(e.value))throw new Error("dayNotIn operator requires an array of day names");let i=gn(e.value.map(s=>String(s)));return `EXTRACT(DOW FROM ${r}) <> ALL(${A(t,i)})`}default:throw new Error(`Unknown date operator: ${e.dateOperator}`)}},Ji=e=>{let[t,r]=e;return dg(t,r)<=0?[t,r]:[r,t]},dg=(e,t)=>{let r=Zi(e),n=Zi(t);return r<n?-1:r>n?1:0},Zi=e=>e instanceof Date?e.getTime():typeof e=="number"||typeof e=="string"?e:String(e),es=(e,t)=>{if(e===void 0||!je(e))return e;let r=z(e,Ft(t.dateConfig??{}));if(!r.isValid())throw new Error(`Invalid date value: ${String(e)}`);return r.toDate()},Yi=e=>t=>N(t)?me(t,e.dateConfig??{}).toDate():es(t,e),mg=(e,t)=>{if(e.value!==void 0)return N(e.value)&&e.dateOperator!==E.within?{type:"value",value:xr(e.value,e.dateOperator,t.dateConfig??{}).toDate()}:{type:"value",value:Array.isArray(e.value)?e.value:es(e.value,t)};if(e.path){if(e.path.startsWith("$.")){let r=e.path.substring(2);return {type:"column",sql:t.currentAlias?`${k(t.currentAlias)}.${k(r)}`:I(r)}}if(!t.context)throw new Error(`BuilderState.context is required to resolve date path '${e.path}'. Pass context in options when calling toSql().`);return {type:"value",value:T(t.context,e.path)}}return {type:"value",value:void 0}};var ts=(e,t)=>{if(e.fuzzy)throw new Error("Fuzzy matching has no SQL equivalent \u2014 evaluate it in memory with check().");let r=At(e.field,t),n=s=>ct(e.caseInsensitive)?`LOWER(${s})`:s,o=cg(e,t),a=o.type==="value"?o.value:void 0,i=o.type==="column"?o.sql:void 0;switch(e.operator){case h.equals:return i!==void 0?`${n(r)} = ${n(i)}`:a===null?`${r} IS NULL`:`${n(r)} = ${n(A(t,a))}`;case h.notEquals:return i!==void 0?`${n(r)} <> ${n(i)}`:a===null?`${r} IS NOT NULL`:`${n(r)} <> ${n(A(t,a))}`;case h.lessThan:return i!==void 0?`${r} < ${i}`:`${r} < ${A(t,a)}`;case h.lessThanEquals:return i!==void 0?`${r} <= ${i}`:`${r} <= ${A(t,a)}`;case h.greaterThan:return i!==void 0?`${r} > ${i}`:`${r} > ${A(t,a)}`;case h.greaterThanEquals:return i!==void 0?`${r} >= ${i}`:`${r} >= ${A(t,a)}`;case h.in:return !Array.isArray(a)||a.length===0?"FALSE":`${r} = ANY(${A(t,a)})`;case h.notIn:return !Array.isArray(a)||a.length===0?"TRUE":`${r} <> ALL(${A(t,a)})`;case h.contains:return `${n(r)} LIKE ${n(A(t,`%${qt(String(a))}%`))}`;case h.notContains:return `${n(r)} NOT LIKE ${n(A(t,`%${qt(String(a))}%`))}`;case h.startsWith:return `${n(r)} LIKE ${n(A(t,`${qt(String(a))}%`))}`;case h.endsWith:return `${n(r)} LIKE ${n(A(t,`%${qt(String(a))}`))}`;case h.matches:return `${r} ~ ${A(t,a)}`;case h.notMatches:return `${r} !~ ${A(t,a)}`;case h.between:{let s=a;if(!Array.isArray(s)||s.length!==2)throw new Error("between operator requires an array of two values");let[l,f]=s[0]<=s[1]?s:[s[1],s[0]];return `${r} BETWEEN ${A(t,l)} AND ${A(t,f)}`}case h.notBetween:{let s=a;if(!Array.isArray(s)||s.length!==2)throw new Error("notBetween operator requires an array of two values");let[l,f]=s[0]<=s[1]?s:[s[1],s[0]];return `${r} NOT BETWEEN ${A(t,l)} AND ${A(t,f)}`}case h.isEmpty:return `(${r} IS NULL OR ${r} = '')`;case h.notEmpty:return `(${r} IS NOT NULL AND ${r} <> '')`;case h.exists:return `${r} IS NOT NULL`;case h.notExists:return `${r} IS NULL`;default:throw new Error(`Unknown operator: ${e.operator}`)}},cg=(e,t)=>{if(e.value!==void 0)return {type:"value",value:e.value};if(e.path){if(e.path.startsWith("$.")){let r=e.path.substring(2);return {type:"column",sql:t.currentAlias?`${k(t.currentAlias)}.${k(r)}`:I(r)}}if(!t.context)throw new Error(`BuilderState.context is required to resolve path '${e.path}'. Pass context in options when calling toSql().`);return {type:"value",value:T(t.context,e.path)}}if(e.bind!==void 0)throw new Error(`Unresolved binding '${e.bind}' for field '${e.field}' \u2014 resolve bindings (resolveLensBindings) before compiling to SQL.`);return {type:"value",value:void 0}};var Rt,rs=e=>{Rt=e;},gg=(e,t,r)=>{let n=e.split("."),o=r;for(let a=0;a<n.length;a++){let i=t.models[o];if(!i)return false;let s=i.fields[n[a]];if(!s)return false;if(s.kind==="bridge")return true;if(s.kind==="object"){o=s.type;continue}return false}return false},yg=(e,t,r)=>{let n=e.split("."),o=r;for(let a of n){let i=t.models[o]?.fields[a];if(!i||i.kind!=="object")return null;o=i.type;}return o},ge=(e,t)=>{if(typeof e=="boolean"||!t.map||!t.currentModel)return false;if("all"in e)return e.all.some(r=>ge(r,t));if("any"in e)return e.any.some(r=>ge(r,t));if("if"in e)return ge(e.if,t)||ge(e.then,t)||e.else!==void 0&&ge(e.else,t);if("field"in e&&typeof e.field=="string"&&e.field!==""){if(gg(e.field,t.map,t.currentModel))return true;if("condition"in e&&e.condition!==void 0){let r=yg(e.field,t.map,t.currentModel);if(r&&ge(e.condition,{...t,currentModel:r}))return true}}return false},ns=(e,t)=>e.all.length===0?"TRUE":`(${e.all.map(n=>Rt(n,t)).join(" AND ")})`,os=(e,t)=>e.any.length===0?"FALSE":`(${e.any.map(n=>Rt(n,t)).join(" OR ")})`,as=(e,t)=>{if(ge(e.if,t)||ge(e.then,t)||e.else!==void 0&&ge(e.else,t))return "TRUE";let r=Rt(e.if,t),n=Rt(e.then,t);if(e.else!==void 0){let o=Rt(e.else,t);return `((NOT(${r}) OR ${n}) AND (${r} OR ${o}))`}return `(NOT(${r}) OR ${n})`};var hg=(e,t,r)=>{let n=e.split("."),o=r;for(let a=0;a<n.length;a++){let i=t.models[o];if(!i)return false;let s=i.fields[n[a]];if(!s)return false;if(s.kind==="bridge")return true;if(s.kind==="object"){o=s.type;continue}return false}return false},It=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";if("field"in e&&typeof e.field=="string"&&t.map&&t.currentModel&&hg(e.field,t.map,t.currentModel))return "TRUE";if("all"in e)return ns(e,t);if("any"in e)return os(e,t);if("if"in e)return as(e,t);if("arrayOperator"in e)return Qi(e,t);if("dateOperator"in e)return Xi(e,t);if("aggregate"in e)return Hi(e,t);if("field"in e)return ts(e,t);throw new Error("Unknown condition type")};rs(It);var is=(e,t)=>{let r=!!(t?.map&&t?.model),n=t?.alias??(r?"t0":void 0),o={params:[],paramIndex:0,context:t?.context,dateConfig:{now:t?.now,timeZone:t?.timeZone,weekStart:t?.weekStart},map:t?.map,currentModel:t?.model,currentAlias:n,joinCounter:r?{n:0}:void 0,joins:r?[]:void 0,joinRegistry:r?new Map:void 0};return {sql:It(e,o),params:o.params,joins:o.joins??[]}};var Ve=e=>`"${e.replace(/"/g,'""')}"`,wg=(e,t)=>{let r=[...e,...t];return r.length===1?r[0]:{all:r}},ss=(e,t)=>{let[r,...n]=t;if(n.length===0){e[r]=true;return}let o=e[r],a=o!==void 0&&o!==true?o.select:{};ss(a,n),e[r]={select:a};},xg=e=>{let t={};for(let r of e)ss(t,r.split("."));return t},bg=(e,t,r,n,o,a,i)=>{let s=Ui(i,{map:e,mapName:t,model:r}),l=s.steps[s.steps.length-1],f=l&&"where"in l?l.where:{},m=s.steps.filter(c=>c.operation!=="where"),p={[n]:true,...o?{[o]:true}:{},...a?xg(a):{}},u={model:r,...a?{}:{distinct:[n]},select:p,where:f,...m.length?{steps:s.steps}:{}},d;try{let c,y,g,w;if(a){let M={params:[],paramIndex:0,map:e.maps[t],currentModel:r,currentAlias:"t0",joinCounter:{n:0},joins:[],joinRegistry:new Map};c=It(i,M),w=a.map(W=>At(W,M)),y=M.params,g=M.joins??[];}else ({sql:c,params:y,joins:g}=is(i,{map:e.maps[t],model:r,alias:"t0"}));let v=g.length?` ${g.join(" ")}`:"",b=c?.trim()?` WHERE ${c}`:"";d={sql:`SELECT DISTINCT ${[`${Ve("t0")}.${Ve(n)}`,...o?[`${Ve("t0")}.${Ve(o)}`]:[],...w?w.map((M,W)=>`${M} AS ${Ve(`__group_${W}`)}`):[]].join(", ")} FROM ${Ve(r)} AS ${Ve("t0")}${v}${b}`,params:y};}catch(c){d={sql:null,params:[],error:c instanceof Error?c.message:String(c)};}return {prisma:u,sql:d}},vg=e=>{let t=j(e),{lens:r}=t,n=Bt(e),o=[];for(let[a,i]of n){let s=a.split(".").slice(1);for(let[l,f]of Object.entries(i.sources)){let m=i.sourceLabels[l],p=i.sourceGroupBys[l],u=Rr(t,i.mapName,i.modelName,s,p??[],f),d=wg(i.whereClauses,[...f,...u]),{prisma:c,sql:y}=bg(r,i.mapName,i.modelName,l,m,p,d);o.push({path:a,mapName:i.mapName,model:i.modelName,field:l,...m!==void 0?{label:m}:{},...p!==void 0?{groupBy:p}:{},composedWhere:d,prisma:c,sql:y});}}return o};var Og=(e,t,r={})=>{let n=r.rowShape??"prisma",o=new Map;for(let a of t){let i=a[e.field],s=Array.isArray(i)?i:[i],l=e.label===void 0?void 0:a[e.label],f=l==null?void 0:String(l),m=e.groupBy===void 0?void 0:kr(a,n==="sql"?e.groupBy.map((p,u)=>`__group_${u}`):e.groupBy);for(let p of s)p==null||typeof p=="object"||Tr(o,String(p),f,m);}return {path:e.path,mapName:e.mapName,model:e.model,field:e.field,options:Cr(o)}};var Sg=(e,t)=>{let r=[...e];for(let n of t.split(".").slice(1)){let o=[];for(let a of r){let i=a?.[n];Array.isArray(i)?o.push(...i):i!=null&&o.push(i);}r=o;}return r},$g=e=>e.length===0?true:e.length===1?e[0]:{all:e},Eg=(e,t,r)=>{let n=[],o=j(e);for(let[a,i]of Bt(e)){let s=Object.entries(i.sources);if(s.length===0)continue;let l=Sg(t,a),f=a.split(".").slice(1);for(let[m,p]of s){let u=i.sourceLabels[m],d=i.sourceGroupBys[m],c=Rr(o,i.mapName,i.modelName,f,d??[],p),y=$g([...p,...c]),g=new Map;for(let w of l){if(H(y,w,r)!==true)continue;let v=w[m],b=Array.isArray(v)?v:[v],x=u===void 0?void 0:w[u],$=x==null?void 0:String(x),M=d===void 0?void 0:kr(w,d);for(let W of b)W==null||typeof W=="object"||Tr(g,String(W),$,M);}n.push({path:a,mapName:i.mapName,model:i.modelName,field:m,options:Cr(g)});}}return n};var Ag=new Set(["Int","BigInt","Float","Decimal","DateTime","Boolean","String"]),ls=(e,t,r)=>{let n=r.split("."),{mapName:o,modelName:a}=t;for(let i=0;i<n.length;i+=1){let s=e.maps[o]?.models[a]?.fields[n[i]];if(!s)return;if(i===n.length-1)return {entry:s,mapName:o};if(s.kind!=="object"&&s.kind!=="bridge")return;let l=L(s,o);if(!l)return;({mapName:o,modelName:a}=l);}},Rg=(e,t,r)=>{if(!r)return;let n=ls(e,t,r);return !n||n.entry.kind!=="object"&&n.entry.kind!=="bridge"?void 0:L(n.entry,n.mapName)??void 0},Fe=(e,t,r)=>{if(typeof e=="boolean")return e;if("all"in e)return {...e,all:e.all.map(n=>Fe(n,t,r))};if("any"in e)return {...e,any:e.any.map(n=>Fe(n,t,r))};if("if"in e)return {...e,if:Fe(e.if,t,r),then:Fe(e.then,t,r),...e.else!==void 0?{else:Fe(e.else,t,r)}:{}};if("arrayOperator"in e||"aggregate"in e){let n=Rg(t,r,e.field);return n?{...e,...e.condition!==void 0?{condition:Fe(e.condition,t,n)}:{},...e.filter!==void 0?{filter:Fe(e.filter,t,n)}:{}}:e}if("dateOperator"in e)return e;if("operator"in e){if(e.coerceType)return e;let n=ls(t,r,e.field);return !n||n.entry.kind!=="scalar"||!Ag.has(n.entry.type)?e:{...e,coerceType:n.entry.type}}return e},kg=(e,t)=>{let{lens:r}=j(t);return Fe(e,r,{mapName:r.mapName,modelName:r.model})};var Tg=new Set(["year","quarter","month","week","isoWeek","day","hour","minute","second"]),Cg=new Set(["years","quarters","months","weeks","days","hours","minutes","seconds"]),Mg=new Set(Object.keys(oe)),Pg=new Set(Object.keys(Pe)),Dg=new Set(Object.keys(Me)),Fg=(e,t={})=>{let r={target:t.target??"check",errors:[]};return ye(e,"$",r),{ok:r.errors.length===0,errors:r.errors}},LT=(e,t={})=>{let r=Fg(e,t);if(r.ok)return;let n=r.errors.map(o=>`${o.path}: ${o.message}`).join(`
|
|
6
6
|
`);throw new Error(`Invalid rule:
|
|
7
7
|
${n}`)},ye=(e,t,r)=>{if(typeof e=="boolean"){r.target==="toPrisma"&&e===false&&S(r,t,"boolean_false_not_supported","Boolean 'false' is not supported by toPrisma()");return}if(!Vt(e)){S(r,t,"invalid_condition","Condition must be a boolean or object");return}let n=_g(e);if(!n){S(r,t,"ambiguous_condition","Condition must be exactly one of: field rule, array rule, date rule, all, any, or if/then[/else]");return}switch(n){case "all":fs(e.all,`${t}.all`,r);break;case "any":fs(e.any,`${t}.any`,r);break;case "if":ye(e.if,`${t}.if`,r),ye(e.then,`${t}.then`,r),"else"in e&&e.else!==void 0&&ye(e.else,`${t}.else`,r);break;case "field":Bg(e,t,r);break;case "aggregate":Lg(e,t,r);break;case "array":jg(e,t,r);break;case "date":qg(e,t,r);break}},_g=e=>{let t=[];"all"in e&&t.push("all"),"any"in e&&t.push("any"),("if"in e||"then"in e||"else"in e)&&t.push("if"),"arrayOperator"in e&&t.push("array"),"dateOperator"in e&&t.push("date"),"aggregate"in e?t.push("aggregate"):"operator"in e&&t.push("field");let r=Array.from(new Set(t));return r.length!==1?null:r[0]},fs=(e,t,r)=>{if(!Array.isArray(e)){S(r,t,"logical_array_required","Logical operator requires an array of conditions");return}e.forEach((n,o)=>{ye(n,`${t}[${o}]`,r);});},Bg=(e,t,r)=>{if(typeof e.field!="string"&&S(r,`${t}.field`,"field_required","Field rule requires a string field"),typeof e.operator!="string"||!Mg.has(e.operator)){S(r,`${t}.operator`,"invalid_operator","Unknown field operator");return}let n=e.operator;St(n,r.target)||S(r,`${t}.operator`,`unsupported_${Fr(r.target)}_operator`,`Operator '${n}' is not supported by ${r.target}()`),r.target==="toPrisma"&&typeof e.path=="string"&&e.path.startsWith("$.")&&S(r,`${t}.path`,"unsupported_prisma_path",`Path '${e.path}' is not supported by toPrisma()`),e.coerceType!==void 0&&!(typeof e.coerceType=="string"&&e.coerceType in Ar)&&S(r,`${t}.coerceType`,"invalid_coerce_type",`coerceType must be one of: ${Object.keys(Ar).join(", ")}`);let o=ln(n);if(o==="none"){Vg(e,t,r);return}hn(e,t,r)&&("path"in e&&typeof e.path=="string"||Ng(o,e.value,n,`${t}.value`,r));},Ng=(e,t,r,n,o)=>{switch(e){case "scalar":case "string":e==="string"&&typeof t!="string"&&S(o,n,"invalid_string_value",`Operator '${r}' requires a string value`);return;case "ordered":yn(t)||S(o,n,"invalid_ordered_value",`Operator '${r}' requires a string, number, or Date value`);return;case "array":Array.isArray(t)||S(o,n,"invalid_membership_value",`Operator '${r}' requires an array value`);return;case "pattern":typeof t=="string"||t instanceof RegExp||S(o,n,"invalid_pattern_value",`Operator '${r}' requires a string or RegExp value`);return;case "range":Wg(t)||S(o,n,"invalid_range_value",`Operator '${r}' requires a two-item range`);return}},Lg=(e,t,r)=>{if(ds(e,t,r),typeof e.field!="string"&&S(r,`${t}.field`,"field_required","Aggregate rule requires a string field"),!Vt(e.aggregate)){S(r,`${t}.aggregate`,"invalid_aggregate","aggregate must be an object");return}let n=e.aggregate;n.mode!=="sum"&&n.mode!=="avg"&&S(r,`${t}.aggregate.mode`,"invalid_aggregate_mode","aggregate.mode must be 'sum' or 'avg'"),"field"in n&&n.field!==void 0&&typeof n.field!="string"&&S(r,`${t}.aggregate.field`,"invalid_aggregate_field","aggregate.field must be a string");let o=typeof e.operator=="string"&&xi(e.operator),a=typeof e.operator=="string"&&bi(e.operator);if(!o&&!a){S(r,`${t}.operator`,"invalid_aggregate_operator","Aggregate rules only support: equals, notEquals, lessThan, lessThanEquals, greaterThan, greaterThanEquals, between, notBetween");return}if(r.target==="toPrisma"&&e.operator===h.notBetween&&S(r,`${t}.operator`,"unsupported_prisma_aggregate_operator","Operator 'notBetween' is not supported by toPrisma() for aggregate rules"),r.target==="toPrisma"&&typeof e.path=="string"&&S(r,`${t}.path`,"unsupported_prisma_aggregate_path","path is not supported by toPrisma() for aggregate rules; use value instead"),"condition"in e&&e.condition!==void 0&&(r.target==="toSql"&&S(r,`${t}.condition`,"unsupported_sql_aggregate_condition","Aggregate condition filtering is not supported by toSql(); use check() or toPrisma()"),ye(e.condition,`${t}.condition`,r)),!hn(e,t,r)||"path"in e&&typeof e.path=="string")return;let i=e.value;a?Ug(i)||S(r,`${t}.value`,"invalid_range_value",`Operator '${e.operator}' requires a two-item numeric range`):typeof i!="number"&&S(r,`${t}.value`,"invalid_aggregate_value","Aggregate rule value must be a number");},jg=(e,t,r)=>{if(typeof e.field!="string"&&r.target!=="check"&&S(r,`${t}.field`,"field_required","Array rule requires a string field for this target"),ds(e,t,r),typeof e.arrayOperator!="string"||!Pg.has(e.arrayOperator)){S(r,`${t}.arrayOperator`,"invalid_array_operator","Unknown array operator");return}let n=e.arrayOperator;switch(St(n,r.target)||S(r,`${t}.arrayOperator`,`unsupported_${Fr(r.target)}_array_operator`,`Array operator '${n}' is not supported by ${r.target}()`),n){case O.empty:case O.notEmpty:"condition"in e&&e.condition!==void 0&&S(r,`${t}.condition`,"unexpected_condition",`Array operator '${n}' does not accept condition`),"count"in e&&e.count!==void 0&&S(r,`${t}.count`,"unexpected_count",`Array operator '${n}' does not accept count`);break;case O.all:case O.any:case O.none:!("condition"in e)||e.condition===void 0?S(r,`${t}.condition`,"missing_condition",`Array operator '${n}' requires condition`):ye(e.condition,`${t}.condition`,r),"count"in e&&e.count!==void 0&&S(r,`${t}.count`,"unexpected_count",`Array operator '${n}' does not accept count`);break;case O.atLeast:case O.atMost:case O.exactly:r.target!=="toPrisma"&&typeof e.count!="number"?S(r,`${t}.count`,"missing_count",`Array operator '${n}' requires count`):"count"in e&&e.count!==void 0&&typeof e.count!="number"&&S(r,`${t}.count`,"invalid_count","count must be a number"),r.target==="check"&&(!("condition"in e)||e.condition===void 0)?S(r,`${t}.condition`,"missing_condition",`Array operator '${n}' requires condition for check()`):"condition"in e&&e.condition!==void 0&&ye(e.condition,`${t}.condition`,r);break}},qg=(e,t,r)=>{if(typeof e.field!="string"&&S(r,`${t}.field`,"field_required","Date rule requires a string field"),typeof e.dateOperator!="string"||!Dg.has(e.dateOperator)){S(r,`${t}.dateOperator`,"invalid_date_operator","Unknown date operator");return}let n=e.dateOperator;St(n,r.target)||S(r,`${t}.dateOperator`,`unsupported_${Fr(r.target)}_date_operator`,`Date operator '${n}' is not supported by ${r.target}()`),r.target==="toPrisma"&&typeof e.path=="string"&&e.path.startsWith("$.")&&S(r,`${t}.path`,"unsupported_prisma_path",`Path '${e.path}' is not supported by toPrisma()`);let o=ln(n);if(o==="dayList"){(!Array.isArray(e.value)||!e.value.every(a=>typeof a=="string"))&&S(r,`${t}.value`,"invalid_day_list",`Date operator '${n}' requires an array of day names`),"path"in e&&e.path!==void 0&&S(r,`${t}.path`,"unexpected_path",`Date operator '${n}' does not accept path`);return}if(hn(e,t,r)&&!("path"in e&&typeof e.path=="string")){if(N(e.value)){ps(e.value,n,`${t}.value`,r);return}if(n==="within"){S(r,`${t}.value`,"invalid_date_range","Date operator 'within' requires a range date expression (a period or rolling window)");return}if(o==="dateRange"){if(!Gg(e.value)){S(r,`${t}.value`,"invalid_date_range",`Date operator '${n}' requires a two-item date range`);return}e.value.forEach((a,i)=>{N(a)?ps(a,n,`${t}.value[${i}]`,r):Dr(a)&&!z(a,"UTC").isValid()&&S(r,`${t}.value[${i}]`,"invalid_date_value",`Date operator '${n}' value '${String(a)}' does not parse as a date`);});return}if(!Dr(e.value)){S(r,`${t}.value`,"invalid_date_value",`Date operator '${n}' requires a date-like value`);return}z(e.value,"UTC").isValid()||S(r,`${t}.value`,"invalid_date_value",`Date operator '${n}' value '${String(e.value)}' does not parse as a date`);}},Ig=(e,t,r)=>{if(!Vt(e)||Object.keys(e).length===0){S(r,t,"invalid_relative_units","Relative offset requires at least one unit");return}for(let[n,o]of Object.entries(e)){if(!Cg.has(n)){S(r,`${t}.${n}`,"invalid_relative_unit",`Unknown relative unit '${n}'`);continue}(typeof o!="number"||!Number.isFinite(o)||o<0)&&S(r,`${t}.${n}`,"invalid_relative_magnitude",`Relative magnitudes must be positive numbers (got ${String(o)})`);}},us=(e,t,r)=>{(typeof e!="string"||!Tg.has(e))&&S(r,t,"invalid_period_unit",`Unknown period unit '${String(e)}'`);},ps=(e,t,r,n)=>{let o=t==="within";if(wr(e)){Ig("ago"in e?e.ago:e.ahead,r,n);return}if(Le(e)){let a="this"in e?e.this:"last"in e?e.last:e.next;us(a,r,n);return}if(Kr(e)){if(o){S(n,r,"invalid_date_range","'within' requires a range (period or rolling); a start/end edge is a single point");return}let a="start"in e?e.start:e.end;if(!Vt(a)||!Le(a)){S(n,r,"invalid_period_unit","start/end requires a this/last/next period");return}let i="this"in a?a.this:"last"in a?a.last:a.next;us(i,r,n);return}S(n,r,"invalid_date_expression","Unrecognized date expression");},hn=(e,t,r)=>{let n="value"in e&&e.value!==void 0,o=typeof e.path=="string";return n&&o?(S(r,t,"ambiguous_value_source","Rule cannot define both value and path"),false):!n&&!o?(S(r,t,"missing_value_source","Rule requires either value or path"),false):true},Vg=(e,t,r)=>{"value"in e&&e.value!==void 0&&S(r,`${t}.value`,"unexpected_value","Rule does not accept value"),"path"in e&&e.path!==void 0&&S(r,`${t}.path`,"unexpected_path","Rule does not accept path");},Fr=e=>e==="toPrisma"?"prisma":e==="toSql"?"sql":"check",Vt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),yn=e=>typeof e=="string"||typeof e=="number"||e instanceof Date,Wg=e=>Array.isArray(e)&&e.length===2&&yn(e[0])&&yn(e[1]),Ug=e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="number"&&typeof e[1]=="number",Dr=e=>typeof e=="string"||typeof e=="number"||e instanceof Date,Gg=e=>Array.isArray(e)&&e.length===2&&(Dr(e[0])||N(e[0]))&&(Dr(e[1])||N(e[1])),ds=(e,t,r)=>{if(("filter"in e&&e.filter!==void 0||"orderBy"in e&&e.orderBy!==void 0||"take"in e&&e.take!==void 0||"skip"in e&&e.skip!==void 0)&&r.target!=="check"&&(r.target==="toPrisma"&&ht(e)!==null||S(r,t,`unsupported_${Fr(r.target)}_window`,`Windowing (filter/orderBy/take/skip) is not supported by ${r.target}() for this rule; evaluate with check()`)),"filter"in e&&e.filter!==void 0&&ye(e.filter,`${t}.filter`,r),"orderBy"in e&&e.orderBy!==void 0){let o=e.orderBy;!Array.isArray(o)||o.length===0?S(r,`${t}.orderBy`,"invalid_order_by","orderBy must be a non-empty array of { field, dir }"):o.forEach((a,i)=>{(!Vt(a)||typeof a.field!="string"||a.dir!=="asc"&&a.dir!=="desc")&&S(r,`${t}.orderBy[${i}]`,"invalid_order_by",'orderBy entries must be { field: string, dir: "asc" | "desc" }');});}for(let o of ["take","skip"])if(o in e&&e[o]!==void 0){let a=e[o];(typeof a!="number"||!Number.isInteger(a)||a<0)&&S(r,`${t}.${o}`,`invalid_window_${o}`,`${o} must be a non-negative integer`);}},S=(e,t,r,n)=>{e.errors.push({path:t,code:r,message:n});};/*! Bundled license information:
|
|
8
8
|
|