@inixiative/json-rules 3.21.0 → 3.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import Tt from'dayjs';import XR from'dayjs/plugin/isoWeek.js';import eO from'dayjs/plugin/quarterOfYear.js';import tO from'dayjs/plugin/timezone.js';import rO from'dayjs/plugin/utc.js';import yO from'dayjs/plugin/isSameOrAfter.js';import hO from'dayjs/plugin/isSameOrBefore.js';import {distance}from'fastest-levenshtein';import {RE2JS}from're2js';var Oa=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Eg=typeof global=="object"&&global&&global.Object===Object&&global,hi=Eg;var xg=typeof self=="object"&&self&&self.Object===Object&&self,$g=hi||xg||Function("return this")(),le=$g;var vg=le.Symbol,Ne=vg;var Xl=Object.prototype,Ag=Xl.hasOwnProperty,Ng=Xl.toString,Ro=Ne?Ne.toStringTag:void 0;function Pg(e){var t=Ag.call(e,Ro),r=e[Ro];try{e[Ro]=void 0;var n=!0;}catch{}var o=Ng.call(e);return n&&(t?e[Ro]=r:delete e[Ro]),o}var ep=Pg;var kg=Object.prototype,Tg=kg.toString;function Cg(e){return Tg.call(e)}var tp=Cg;var Lg="[object Null]",Mg="[object Undefined]",rp=Ne?Ne.toStringTag:void 0;function _g(e){return e==null?e===void 0?Mg:Lg:rp&&rp in Object(e)?ep(e):tp(e)}var je=_g;function Dg(e){return e!=null&&typeof e=="object"}var fe=Dg;var Fg="[object Symbol]";function jg(e){return typeof e=="symbol"||fe(e)&&je(e)==Fg}var pn=jg;function Vg(e,t){for(var r=-1,n=e==null?0:e.length,o=Array(n);++r<n;)o[r]=t(e[r],r,e);return o}var np=Vg;var Ig=Array.isArray,G=Ig;var op=Ne?Ne.prototype:void 0,ip=op?op.toString:void 0;function sp(e){if(typeof e=="string")return e;if(G(e))return np(e,sp)+"";if(pn(e))return ip?ip.call(e):"";var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var ap=sp;function Bg(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Z=Bg;function Wg(e){return e}var fn=Wg;var Ug="[object AsyncFunction]",Kg="[object Function]",Gg="[object GeneratorFunction]",zg="[object Proxy]";function Hg(e){if(!Z(e))return false;var t=je(e);return t==Kg||t==Gg||t==Ug||t==zg}var dn=Hg;var Jg=le["__core-js_shared__"],wi=Jg;var lp=(function(){var e=/[^.]+$/.exec(wi&&wi.keys&&wi.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function Qg(e){return !!lp&&lp in e}var pp=Qg;var Zg=Function.prototype,Yg=Zg.toString;function Xg(e){if(e!=null){try{return Yg.call(e)}catch{}try{return e+""}catch{}}return ""}var It=Xg;var ey=/[\\^$.*+?()[\]{}|]/g,ty=/^\[object .+?Constructor\]$/,ry=Function.prototype,ny=Object.prototype,oy=ry.toString,iy=ny.hasOwnProperty,sy=RegExp("^"+oy.call(iy).replace(ey,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ay(e){if(!Z(e)||pp(e))return false;var t=dn(e)?sy:ty;return t.test(It(e))}var fp=ay;function ly(e,t){return e?.[t]}var dp=ly;function py(e,t){var r=dp(e,t);return fp(r)?r:void 0}var Le=py;var fy=Le(le,"WeakMap"),bi=fy;var up=Object.create,dy=(function(){function e(){}return function(t){if(!Z(t))return {};if(up)return up(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})(),cp=dy;function uy(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var mp=uy;function cy(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}var Si=cy;var my=800,gy=16,yy=Date.now;function hy(e){var t=0,r=0;return function(){var n=yy(),o=gy-(n-r);if(r=n,o>0){if(++t>=my)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var gp=hy;function wy(e){return function(){return e}}var yp=wy;var by=(function(){try{var e=Le(Object,"defineProperty");return e({},"",{}),e}catch{}})(),un=by;var Sy=un?function(e,t){return un(e,"toString",{configurable:true,enumerable:false,value:yp(t),writable:true})}:fn,hp=Sy;var Ry=gp(hp),wp=Ry;function Oy(e,t){for(var r=-1,n=e==null?0:e.length;++r<n&&t(e[r],r,e)!==false;);return e}var bp=Oy;var Ey=9007199254740991,xy=/^(?:0|[1-9]\d*)$/;function $y(e,t){var r=typeof e;return t=t??Ey,!!t&&(r=="number"||r!="symbol"&&xy.test(e))&&e>-1&&e%1==0&&e<t}var ir=$y;function vy(e,t,r){t=="__proto__"&&un?un(e,t,{configurable:true,enumerable:true,value:r,writable:true}):e[t]=r;}var cn=vy;function Ay(e,t){return e===t||e!==e&&t!==t}var yt=Ay;var Ny=Object.prototype,Py=Ny.hasOwnProperty;function ky(e,t,r){var n=e[t];(!(Py.call(e,t)&&yt(n,r))||r===void 0&&!(t in e))&&cn(e,t,r);}var mn=ky;function Ty(e,t,r,n){var o=!r;r||(r={});for(var i=-1,s=t.length;++i<s;){var a=t[i],l=n?n(r[a],e[a],a,r,e):void 0;l===void 0&&(l=e[a]),o?cn(r,a,l):mn(r,a,l);}return r}var ht=Ty;var Sp=Math.max;function Cy(e,t,r){return t=Sp(t===void 0?e.length-1:t,0),function(){for(var n=arguments,o=-1,i=Sp(n.length-t,0),s=Array(i);++o<i;)s[o]=n[t+o];o=-1;for(var a=Array(t+1);++o<t;)a[o]=n[o];return a[t]=r(s),mp(e,this,a)}}var Rp=Cy;function Ly(e,t){return wp(Rp(e,t,fn),e+"")}var Op=Ly;var My=9007199254740991;function _y(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=My}var gn=_y;function Dy(e){return e!=null&&gn(e.length)&&!dn(e)}var wt=Dy;function Fy(e,t,r){if(!Z(r))return false;var n=typeof t;return (n=="number"?wt(r)&&ir(t,r.length):n=="string"&&t in r)?yt(r[t],e):false}var Ri=Fy;function jy(e){return Op(function(t,r){var n=-1,o=r.length,i=o>1?r[o-1]:void 0,s=o>2?r[2]:void 0;for(i=e.length>3&&typeof i=="function"?(o--,i):void 0,s&&Ri(r[0],r[1],s)&&(i=o<3?void 0:i,o=1),t=Object(t);++n<o;){var a=r[n];a&&e(t,a,n,i);}return t})}var Ep=jy;var Vy=Object.prototype;function Iy(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||Vy;return e===r}var yn=Iy;function qy(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}var xp=qy;var By="[object Arguments]";function Wy(e){return fe(e)&&je(e)==By}var Ea=Wy;var $p=Object.prototype,Uy=$p.hasOwnProperty,Ky=$p.propertyIsEnumerable,Gy=Ea((function(){return arguments})())?Ea:function(e){return fe(e)&&Uy.call(e,"callee")&&!Ky.call(e,"callee")},_r=Gy;function zy(){return false}var vp=zy;var Pp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ap=Pp&&typeof module=="object"&&module&&!module.nodeType&&module,Hy=Ap&&Ap.exports===Pp,Np=Hy?le.Buffer:void 0,Jy=Np?Np.isBuffer:void 0,Qy=Jy||vp,qt=Qy;var Zy="[object Arguments]",Yy="[object Array]",Xy="[object Boolean]",eh="[object Date]",th="[object Error]",rh="[object Function]",nh="[object Map]",oh="[object Number]",ih="[object Object]",sh="[object RegExp]",ah="[object Set]",lh="[object String]",ph="[object WeakMap]",fh="[object ArrayBuffer]",dh="[object DataView]",uh="[object Float32Array]",ch="[object Float64Array]",mh="[object Int8Array]",gh="[object Int16Array]",yh="[object Int32Array]",hh="[object Uint8Array]",wh="[object Uint8ClampedArray]",bh="[object Uint16Array]",Sh="[object Uint32Array]",J={};J[uh]=J[ch]=J[mh]=J[gh]=J[yh]=J[hh]=J[wh]=J[bh]=J[Sh]=true;J[Zy]=J[Yy]=J[fh]=J[Xy]=J[dh]=J[eh]=J[th]=J[rh]=J[nh]=J[oh]=J[ih]=J[sh]=J[ah]=J[lh]=J[ph]=false;function Rh(e){return fe(e)&&gn(e.length)&&!!J[je(e)]}var kp=Rh;function Oh(e){return function(t){return e(t)}}var hn=Oh;var Tp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Oo=Tp&&typeof module=="object"&&module&&!module.nodeType&&module,Eh=Oo&&Oo.exports===Tp,xa=Eh&&hi.process,xh=(function(){try{var e=Oo&&Oo.require&&Oo.require("util").types;return e||xa&&xa.binding&&xa.binding("util")}catch{}})(),Bt=xh;var Cp=Bt&&Bt.isTypedArray,$h=Cp?hn(Cp):kp,wn=$h;var vh=Object.prototype,Ah=vh.hasOwnProperty;function Nh(e,t){var r=G(e),n=!r&&_r(e),o=!r&&!n&&qt(e),i=!r&&!n&&!o&&wn(e),s=r||n||o||i,a=s?xp(e.length,String):[],l=a.length;for(var p in e)(t||Ah.call(e,p))&&!(s&&(p=="length"||o&&(p=="offset"||p=="parent")||i&&(p=="buffer"||p=="byteLength"||p=="byteOffset")||ir(p,l)))&&a.push(p);return a}var Oi=Nh;function Ph(e,t){return function(r){return e(t(r))}}var Ei=Ph;var kh=Ei(Object.keys,Object),Lp=kh;var Th=Object.prototype,Ch=Th.hasOwnProperty;function Lh(e){if(!yn(e))return Lp(e);var t=[];for(var r in Object(e))Ch.call(e,r)&&r!="constructor"&&t.push(r);return t}var Mp=Lh;function Mh(e){return wt(e)?Oi(e):Mp(e)}var bt=Mh;function _h(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}var _p=_h;var Dh=Object.prototype,Fh=Dh.hasOwnProperty;function jh(e){if(!Z(e))return _p(e);var t=yn(e),r=[];for(var n in e)n=="constructor"&&(t||!Fh.call(e,n))||r.push(n);return r}var Dp=jh;function Vh(e){return wt(e)?Oi(e,true):Dp(e)}var St=Vh;var Ih=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,qh=/^\w*$/;function Bh(e,t){if(G(e))return false;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||pn(e)?true:qh.test(e)||!Ih.test(e)||t!=null&&e in Object(t)}var bn=Bh;var Wh=Le(Object,"create"),Wt=Wh;function Uh(){this.__data__=Wt?Wt(null):{},this.size=0;}var Fp=Uh;function Kh(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var jp=Kh;var Gh="__lodash_hash_undefined__",zh=Object.prototype,Hh=zh.hasOwnProperty;function Jh(e){var t=this.__data__;if(Wt){var r=t[e];return r===Gh?void 0:r}return Hh.call(t,e)?t[e]:void 0}var Vp=Jh;var Qh=Object.prototype,Zh=Qh.hasOwnProperty;function Yh(e){var t=this.__data__;return Wt?t[e]!==void 0:Zh.call(t,e)}var Ip=Yh;var Xh="__lodash_hash_undefined__";function ew(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Wt&&t===void 0?Xh:t,this}var qp=ew;function Sn(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1]);}}Sn.prototype.clear=Fp;Sn.prototype.delete=jp;Sn.prototype.get=Vp;Sn.prototype.has=Ip;Sn.prototype.set=qp;var $a=Sn;function tw(){this.__data__=[],this.size=0;}var Bp=tw;function rw(e,t){for(var r=e.length;r--;)if(yt(e[r][0],t))return r;return -1}var sr=rw;var nw=Array.prototype,ow=nw.splice;function iw(e){var t=this.__data__,r=sr(t,e);if(r<0)return false;var n=t.length-1;return r==n?t.pop():ow.call(t,r,1),--this.size,true}var Wp=iw;function sw(e){var t=this.__data__,r=sr(t,e);return r<0?void 0:t[r][1]}var Up=sw;function aw(e){return sr(this.__data__,e)>-1}var Kp=aw;function lw(e,t){var r=this.__data__,n=sr(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var Gp=lw;function Rn(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1]);}}Rn.prototype.clear=Bp;Rn.prototype.delete=Wp;Rn.prototype.get=Up;Rn.prototype.has=Kp;Rn.prototype.set=Gp;var ar=Rn;var pw=Le(le,"Map"),lr=pw;function fw(){this.size=0,this.__data__={hash:new $a,map:new(lr||ar),string:new $a};}var zp=fw;function dw(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var Hp=dw;function uw(e,t){var r=e.__data__;return Hp(t)?r[typeof t=="string"?"string":"hash"]:r.map}var pr=uw;function cw(e){var t=pr(this,e).delete(e);return this.size-=t?1:0,t}var Jp=cw;function mw(e){return pr(this,e).get(e)}var Qp=mw;function gw(e){return pr(this,e).has(e)}var Zp=gw;function yw(e,t){var r=pr(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var Yp=yw;function On(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1]);}}On.prototype.clear=zp;On.prototype.delete=Jp;On.prototype.get=Qp;On.prototype.has=Zp;On.prototype.set=Yp;var Dr=On;var hw="Expected a function";function va(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(hw);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],i=r.cache;if(i.has(o))return i.get(o);var s=e.apply(this,n);return r.cache=i.set(o,s)||i,s};return r.cache=new(va.Cache||Dr),r}va.Cache=Dr;var Xp=va;var ww=500;function bw(e){var t=Xp(e,function(n){return r.size===ww&&r.clear(),n}),r=t.cache;return t}var ef=bw;var Sw=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Rw=/\\(\\)?/g,Ow=ef(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(Sw,function(r,n,o,i){t.push(o?i.replace(Rw,"$1"):n||r);}),t}),tf=Ow;function Ew(e){return e==null?"":ap(e)}var rf=Ew;function xw(e,t){return G(e)?e:bn(e,t)?[e]:tf(rf(e))}var En=xw;function vw(e){if(typeof e=="string"||pn(e))return e;var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var Rt=vw;function Aw(e,t){t=En(t,e);for(var r=0,n=t.length;e!=null&&r<n;)e=e[Rt(t[r++])];return r&&r==n?e:void 0}var xi=Aw;function Nw(e,t,r){var n=e==null?void 0:xi(e,t);return n===void 0?r:n}var nf=Nw;function Pw(e,t){for(var r=-1,n=t.length,o=e.length;++r<n;)e[o+r]=t[r];return e}var $i=Pw;var kw=Ei(Object.getPrototypeOf,Object),xn=kw;var Tw="[object Object]",Cw=Function.prototype,Lw=Object.prototype,of=Cw.toString,Mw=Lw.hasOwnProperty,_w=of.call(Object);function Dw(e){if(!fe(e)||je(e)!=Tw)return false;var t=xn(e);if(t===null)return true;var r=Mw.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&of.call(r)==_w}var re=Dw;function Fw(){if(!arguments.length)return [];var e=arguments[0];return G(e)?e:[e]}var vi=Fw;function jw(){this.__data__=new ar,this.size=0;}var sf=jw;function Vw(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var af=Vw;function Iw(e){return this.__data__.get(e)}var lf=Iw;function qw(e){return this.__data__.has(e)}var pf=qw;var Bw=200;function Ww(e,t){var r=this.__data__;if(r instanceof ar){var n=r.__data__;if(!lr||n.length<Bw-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new Dr(n);}return r.set(e,t),this.size=r.size,this}var ff=Ww;function $n(e){var t=this.__data__=new ar(e);this.size=t.size;}$n.prototype.clear=sf;$n.prototype.delete=af;$n.prototype.get=lf;$n.prototype.has=pf;$n.prototype.set=ff;var Ot=$n;function Uw(e,t){return e&&ht(t,bt(t),e)}var df=Uw;function Kw(e,t){return e&&ht(t,St(t),e)}var uf=Kw;var yf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,cf=yf&&typeof module=="object"&&module&&!module.nodeType&&module,Gw=cf&&cf.exports===yf,mf=Gw?le.Buffer:void 0,gf=mf?mf.allocUnsafe:void 0;function zw(e,t){if(t)return e.slice();var r=e.length,n=gf?gf(r):new e.constructor(r);return e.copy(n),n}var Ai=zw;function Hw(e,t){for(var r=-1,n=e==null?0:e.length,o=0,i=[];++r<n;){var s=e[r];t(s,r,e)&&(i[o++]=s);}return i}var hf=Hw;function Jw(){return []}var Ni=Jw;var Qw=Object.prototype,Zw=Qw.propertyIsEnumerable,wf=Object.getOwnPropertySymbols,Yw=wf?function(e){return e==null?[]:(e=Object(e),hf(wf(e),function(t){return Zw.call(e,t)}))}:Ni,vn=Yw;function Xw(e,t){return ht(e,vn(e),t)}var bf=Xw;var eb=Object.getOwnPropertySymbols,tb=eb?function(e){for(var t=[];e;)$i(t,vn(e)),e=xn(e);return t}:Ni,Pi=tb;function rb(e,t){return ht(e,Pi(e),t)}var Sf=rb;function nb(e,t,r){var n=t(e);return G(e)?n:$i(n,r(e))}var ki=nb;function ob(e){return ki(e,bt,vn)}var Eo=ob;function ib(e){return ki(e,St,Pi)}var Rf=ib;var sb=Le(le,"DataView"),Ti=sb;var ab=Le(le,"Promise"),Ci=ab;var lb=Le(le,"Set"),Li=lb;var Of="[object Map]",pb="[object Object]",Ef="[object Promise]",xf="[object Set]",$f="[object WeakMap]",vf="[object DataView]",fb=It(Ti),db=It(lr),ub=It(Ci),cb=It(Li),mb=It(bi),Fr=je;(Ti&&Fr(new Ti(new ArrayBuffer(1)))!=vf||lr&&Fr(new lr)!=Of||Ci&&Fr(Ci.resolve())!=Ef||Li&&Fr(new Li)!=xf||bi&&Fr(new bi)!=$f)&&(Fr=function(e){var t=je(e),r=t==pb?e.constructor:void 0,n=r?It(r):"";if(n)switch(n){case fb:return vf;case db:return Of;case ub:return Ef;case cb:return xf;case mb:return $f}return t});var Ut=Fr;var gb=Object.prototype,yb=gb.hasOwnProperty;function hb(e){var t=e.length,r=new e.constructor(t);return t&&typeof e[0]=="string"&&yb.call(e,"index")&&(r.index=e.index,r.input=e.input),r}var Af=hb;var wb=le.Uint8Array,An=wb;function bb(e){var t=new e.constructor(e.byteLength);return new An(t).set(new An(e)),t}var Nn=bb;function Sb(e,t){var r=t?Nn(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}var Nf=Sb;var Rb=/\w*$/;function Ob(e){var t=new e.constructor(e.source,Rb.exec(e));return t.lastIndex=e.lastIndex,t}var Pf=Ob;var kf=Ne?Ne.prototype:void 0,Tf=kf?kf.valueOf:void 0;function Eb(e){return Tf?Object(Tf.call(e)):{}}var Cf=Eb;function xb(e,t){var r=t?Nn(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}var Mi=xb;var $b="[object Boolean]",vb="[object Date]",Ab="[object Map]",Nb="[object Number]",Pb="[object RegExp]",kb="[object Set]",Tb="[object String]",Cb="[object Symbol]",Lb="[object ArrayBuffer]",Mb="[object DataView]",_b="[object Float32Array]",Db="[object Float64Array]",Fb="[object Int8Array]",jb="[object Int16Array]",Vb="[object Int32Array]",Ib="[object Uint8Array]",qb="[object Uint8ClampedArray]",Bb="[object Uint16Array]",Wb="[object Uint32Array]";function Ub(e,t,r){var n=e.constructor;switch(t){case Lb:return Nn(e);case $b:case vb:return new n(+e);case Mb:return Nf(e,r);case _b:case Db:case Fb:case jb:case Vb:case Ib:case qb:case Bb:case Wb:return Mi(e,r);case Ab:return new n;case Nb:case Tb:return new n(e);case Pb:return Pf(e);case kb:return new n;case Cb:return Cf(e)}}var Lf=Ub;function Kb(e){return typeof e.constructor=="function"&&!yn(e)?cp(xn(e)):{}}var _i=Kb;var Gb="[object Map]";function zb(e){return fe(e)&&Ut(e)==Gb}var Mf=zb;var _f=Bt&&Bt.isMap,Hb=_f?hn(_f):Mf,Df=Hb;var Jb="[object Set]";function Qb(e){return fe(e)&&Ut(e)==Jb}var Ff=Qb;var jf=Bt&&Bt.isSet,Zb=jf?hn(jf):Ff,Vf=Zb;var Yb=1,Xb=2,eS=4,If="[object Arguments]",tS="[object Array]",rS="[object Boolean]",nS="[object Date]",oS="[object Error]",qf="[object Function]",iS="[object GeneratorFunction]",sS="[object Map]",aS="[object Number]",Bf="[object Object]",lS="[object RegExp]",pS="[object Set]",fS="[object String]",dS="[object Symbol]",uS="[object WeakMap]",cS="[object ArrayBuffer]",mS="[object DataView]",gS="[object Float32Array]",yS="[object Float64Array]",hS="[object Int8Array]",wS="[object Int16Array]",bS="[object Int32Array]",SS="[object Uint8Array]",RS="[object Uint8ClampedArray]",OS="[object Uint16Array]",ES="[object Uint32Array]",z={};z[If]=z[tS]=z[cS]=z[mS]=z[rS]=z[nS]=z[gS]=z[yS]=z[hS]=z[wS]=z[bS]=z[sS]=z[aS]=z[Bf]=z[lS]=z[pS]=z[fS]=z[dS]=z[SS]=z[RS]=z[OS]=z[ES]=true;z[oS]=z[qf]=z[uS]=false;function Di(e,t,r,n,o,i){var s,a=t&Yb,l=t&Xb,p=t&eS;if(r&&(s=o?r(e,n,o,i):r(e)),s!==void 0)return s;if(!Z(e))return e;var f=G(e);if(f){if(s=Af(e),!a)return Si(e,s)}else {var d=Ut(e),u=d==qf||d==iS;if(qt(e))return Ai(e,a);if(d==Bf||d==If||u&&!o){if(s=l||u?{}:_i(e),!a)return l?Sf(e,uf(s,e)):bf(e,df(s,e))}else {if(!z[d])return o?e:{};s=Lf(e,d,a);}}i||(i=new Ot);var c=i.get(e);if(c)return c;i.set(e,s),Vf(e)?e.forEach(function(g){s.add(Di(g,t,r,g,e,i));}):Df(e)&&e.forEach(function(g,b){s.set(b,Di(g,t,r,b,e,i));});var y=p?l?Rf:Eo:l?St:bt,m=f?void 0:y(e);return bp(m||e,function(g,b){m&&(b=g,g=e[b]),mn(s,b,Di(g,t,r,b,e,i));}),s}var Fi=Di;var xS=1,$S=4;function vS(e){return Fi(e,xS|$S)}var ji=vS;var AS=1,NS=4;function PS(e,t){return t=typeof t=="function"?t:void 0,Fi(e,AS|NS,t)}var Aa=PS;var kS="__lodash_hash_undefined__";function TS(e){return this.__data__.set(e,kS),this}var Wf=TS;function CS(e){return this.__data__.has(e)}var Uf=CS;function Vi(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Dr;++t<r;)this.add(e[t]);}Vi.prototype.add=Vi.prototype.push=Wf;Vi.prototype.has=Uf;var Kf=Vi;function LS(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return true;return false}var Ii=LS;function MS(e,t){return e.has(t)}var Gf=MS;var _S=1,DS=2;function FS(e,t,r,n,o,i){var s=r&_S,a=e.length,l=t.length;if(a!=l&&!(s&&l>a))return false;var p=i.get(e),f=i.get(t);if(p&&f)return p==t&&f==e;var d=-1,u=true,c=r&DS?new Kf:void 0;for(i.set(e,t),i.set(t,e);++d<a;){var y=e[d],m=t[d];if(n)var g=s?n(m,y,d,t,e,i):n(y,m,d,e,t,i);if(g!==void 0){if(g)continue;u=false;break}if(c){if(!Ii(t,function(b,S){if(!Gf(c,S)&&(y===b||o(y,b,r,n,i)))return c.push(S)})){u=false;break}}else if(!(y===m||o(y,m,r,n,i))){u=false;break}}return i.delete(e),i.delete(t),u}var qi=FS;function jS(e){var t=-1,r=Array(e.size);return e.forEach(function(n,o){r[++t]=[o,n];}),r}var zf=jS;function VS(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n;}),r}var Hf=VS;var IS=1,qS=2,BS="[object Boolean]",WS="[object Date]",US="[object Error]",KS="[object Map]",GS="[object Number]",zS="[object RegExp]",HS="[object Set]",JS="[object String]",QS="[object Symbol]",ZS="[object ArrayBuffer]",YS="[object DataView]",Jf=Ne?Ne.prototype:void 0,Na=Jf?Jf.valueOf:void 0;function XS(e,t,r,n,o,i,s){switch(r){case YS:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return false;e=e.buffer,t=t.buffer;case ZS:return !(e.byteLength!=t.byteLength||!i(new An(e),new An(t)));case BS:case WS:case GS:return yt(+e,+t);case US:return e.name==t.name&&e.message==t.message;case zS:case JS:return e==t+"";case KS:var a=zf;case HS:var l=n&IS;if(a||(a=Hf),e.size!=t.size&&!l)return false;var p=s.get(e);if(p)return p==t;n|=qS,s.set(e,t);var f=qi(a(e),a(t),n,o,i,s);return s.delete(e),f;case QS:if(Na)return Na.call(e)==Na.call(t)}return false}var Qf=XS;var eR=1,tR=Object.prototype,rR=tR.hasOwnProperty;function nR(e,t,r,n,o,i){var s=r&eR,a=Eo(e),l=a.length,p=Eo(t),f=p.length;if(l!=f&&!s)return false;for(var d=l;d--;){var u=a[d];if(!(s?u in t:rR.call(t,u)))return false}var c=i.get(e),y=i.get(t);if(c&&y)return c==t&&y==e;var m=true;i.set(e,t),i.set(t,e);for(var g=s;++d<l;){u=a[d];var b=e[u],S=t[u];if(n)var w=s?n(S,b,u,t,e,i):n(b,S,u,e,t,i);if(!(w===void 0?b===S||o(b,S,r,n,i):w)){m=false;break}g||(g=u=="constructor");}if(m&&!g){var R=e.constructor,O=t.constructor;R!=O&&"constructor"in e&&"constructor"in t&&!(typeof R=="function"&&R instanceof R&&typeof O=="function"&&O instanceof O)&&(m=false);}return i.delete(e),i.delete(t),m}var Zf=nR;var oR=1,Yf="[object Arguments]",Xf="[object Array]",Bi="[object Object]",iR=Object.prototype,ed=iR.hasOwnProperty;function sR(e,t,r,n,o,i){var s=G(e),a=G(t),l=s?Xf:Ut(e),p=a?Xf:Ut(t);l=l==Yf?Bi:l,p=p==Yf?Bi:p;var f=l==Bi,d=p==Bi,u=l==p;if(u&&qt(e)){if(!qt(t))return false;s=true,f=false;}if(u&&!f)return i||(i=new Ot),s||wn(e)?qi(e,t,r,n,o,i):Qf(e,t,l,r,n,o,i);if(!(r&oR)){var c=f&&ed.call(e,"__wrapped__"),y=d&&ed.call(t,"__wrapped__");if(c||y){var m=c?e.value():e,g=y?t.value():t;return i||(i=new Ot),o(m,g,r,n,i)}}return u?(i||(i=new Ot),Zf(e,t,r,n,o,i)):false}var td=sR;function rd(e,t,r,n,o){return e===t?true:e==null||t==null||!fe(e)&&!fe(t)?e!==e&&t!==t:td(e,t,r,n,rd,o)}var Pn=rd;var aR=1,lR=2;function pR(e,t,r,n){var o=r.length,i=o,s=!n;if(e==null)return !i;for(e=Object(e);o--;){var a=r[o];if(s&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return false}for(;++o<i;){a=r[o];var l=a[0],p=e[l],f=a[1];if(s&&a[2]){if(p===void 0&&!(l in e))return false}else {var d=new Ot;if(n)var u=n(p,f,l,e,t,d);if(!(u===void 0?Pn(f,p,aR|lR,n,d):u))return false}}return true}var nd=pR;function fR(e){return e===e&&!Z(e)}var Wi=fR;function dR(e){for(var t=bt(e),r=t.length;r--;){var n=t[r],o=e[n];t[r]=[n,o,Wi(o)];}return t}var od=dR;function uR(e,t){return function(r){return r==null?false:r[e]===t&&(t!==void 0||e in Object(r))}}var Ui=uR;function cR(e){var t=od(e);return t.length==1&&t[0][2]?Ui(t[0][0],t[0][1]):function(r){return r===e||nd(r,e,t)}}var id=cR;function mR(e,t){return e!=null&&t in Object(e)}var sd=mR;function gR(e,t,r){t=En(t,e);for(var n=-1,o=t.length,i=false;++n<o;){var s=Rt(t[n]);if(!(i=e!=null&&r(e,s)))break;e=e[s];}return i||++n!=o?i:(o=e==null?0:e.length,!!o&&gn(o)&&ir(s,o)&&(G(e)||_r(e)))}var ad=gR;function yR(e,t){return e!=null&&ad(e,t,sd)}var ld=yR;var hR=1,wR=2;function bR(e,t){return bn(e)&&Wi(t)?Ui(Rt(e),t):function(r){var n=nf(r,e);return n===void 0&&n===t?ld(r,e):Pn(t,n,hR|wR)}}var pd=bR;function SR(e){return function(t){return t?.[e]}}var fd=SR;function RR(e){return function(t){return xi(t,e)}}var dd=RR;function OR(e){return bn(e)?fd(Rt(e)):dd(e)}var ud=OR;function ER(e){return typeof e=="function"?e:e==null?fn:typeof e=="object"?G(e)?pd(e[0],e[1]):id(e):ud(e)}var cd=ER;function xR(e){return function(t,r,n){for(var o=-1,i=Object(t),s=n(t),a=s.length;a--;){var l=s[e?a:++o];if(r(i[l],l,i)===false)break}return t}}var md=xR;var $R=md(),Ki=$R;function vR(e,t){return e&&Ki(e,t,bt)}var gd=vR;function AR(e,t){return function(r,n){if(r==null)return r;if(!wt(r))return e(r,n);for(var o=r.length,i=t?o:-1,s=Object(r);(t?i--:++i<o)&&n(s[i],i,s)!==false;);return r}}var yd=AR;var NR=yd(gd),hd=NR;function PR(e,t,r){(r!==void 0&&!yt(e[t],r)||r===void 0&&!(t in e))&&cn(e,t,r);}var xo=PR;function kR(e){return fe(e)&&wt(e)}var wd=kR;function TR(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}var $o=TR;function CR(e){return ht(e,St(e))}var bd=CR;function LR(e,t,r,n,o,i,s){var a=$o(e,r),l=$o(t,r),p=s.get(l);if(p){xo(e,r,p);return}var f=i?i(a,l,r+"",e,t,s):void 0,d=f===void 0;if(d){var u=G(l),c=!u&&qt(l),y=!u&&!c&&wn(l);f=l,u||c||y?G(a)?f=a:wd(a)?f=Si(a):c?(d=false,f=Ai(l,true)):y?(d=false,f=Mi(l,true)):f=[]:re(l)||_r(l)?(f=a,_r(a)?f=bd(a):(!Z(a)||dn(a))&&(f=_i(l))):d=false;}d&&(s.set(l,f),o(f,l,n,i,s),s.delete(l)),xo(e,r,f);}var Sd=LR;function Rd(e,t,r,n,o){e!==t&&Ki(t,function(i,s){if(o||(o=new Ot),Z(i))Sd(e,t,s,r,Rd,n,o);else {var a=n?n($o(e,s),i,s+"",e,t,o):void 0;a===void 0&&(a=i),xo(e,s,a);}},St);}var Od=Rd;function MR(e,t){return Pn(e,t)}var Kt=MR;var _R=Ep(function(e,t,r){Od(e,t,r);}),Gi=_R;function DR(e,t,r,n){if(!Z(e))return e;t=En(t,e);for(var o=-1,i=t.length,s=i-1,a=e;a!=null&&++o<i;){var l=Rt(t[o]),p=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(o!=s){var f=a[l];p=n?n(f,l,a):void 0,p===void 0&&(p=Z(f)?f:ir(t[o+1])?[]:{});}mn(a,l,p),a=a[l];}return e}var Ed=DR;function FR(e,t,r){return e==null?e:Ed(e,t,r)}var vo=FR;function jR(e,t){var r;return hd(e,function(n,o,i){return r=t(n,o,i),!r}),!!r}var xd=jR;function VR(e,t,r){var n=G(e)?Ii:xd;return r&&Ri(e,t,r)&&(t=void 0),n(e,cd(t))}var Pa=VR;var IR=/^(\$+)\.(.*)$/,_=e=>{let t=IR.exec(e);return t?{depth:t[1].length,path:t[2]}:null},ka=(e,t,r)=>`Scope ref '${e}' needs depth ${t} but only ${r} ${r===1?"scope is":"scopes are"} in reach`,ze=(e,t)=>{let r=_(e);return r?r.depth>t.length?{outOfBounds:ka(e,r.depth,t.length)}:{scope:t[t.length-r.depth],path:r.path}:{scope:t[t.length-1],path:e}},qR=/\[(\d+)\]|\[(["'])(.*?)\2\]|([^.[\]]+)/g,BR=e=>e===""?[""]:[...e.matchAll(qR)].map(t=>t[1]??t[3]??t[4]),WR=(e,t)=>{if(e==null)return;let r=Object(e);return Object.hasOwn(r,t)?r[t]:void 0},ge=(e,t)=>BR(t).reduce(WR,e),fr=(e,t)=>{let r=ze(e,t);if("outOfBounds"in r)throw new Error(r.outOfBounds);return ge(r.scope,r.path)},zi=(e,t)=>_(e)?fr(e,t):ge(t[0],e),Ao=(e,t)=>`Scope ref '${e}' is not supported by ${t}(); evaluate with check()`,Hi=(e,t)=>{if(!(!("field"in e)||typeof e.field!="string")&&_(e.field))throw new Error(Ao(e.field,t))};var Tn={postgres:"postgres",mysql:"mysql"},vd=e=>Object.values(Tn).includes(e),Ta={string:{caseInsensitive:false,fuzzy:false},prismaOptions:{datasource:{provider:"postgresql"}},sql:{dialect:Tn.postgres},clock:{finestUnit:"second"}},UR=new Set(Object.keys(Ta)),kn=e=>Aa(e,t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!re(t)?t:void 0),$d=Symbol.for("@inixiative/json-rules/engineGlobals@3"),No=()=>{let e=globalThis;return e[$d]??={store:ji(Ta),registry:new Map},e[$d]},KR=e=>{let t={};for(let[r,n]of Object.entries(e))r.includes(".")?vo(t,r,kn(n)):t[r]=Gi(t[r]??{},kn(n));return t},Ad=(e,t,r)=>{for(let[n,o]of Object.entries(r)){let i=`${t}.${n}`;ge(e,i)===void 0&&vo(e,i,kn(o));}},GR=e=>e!=null&&typeof e.then=="function",zR=(e,t)=>{if(!e||e.includes("."))throw new Error(`engine globals namespace "${e}" must be one non-empty segment`);if(UR.has(e))throw new Error(`engine globals namespace "${e}" belongs to json-rules`);let{store:r,registry:n}=No(),o=n.get(e);if(o){if(Kt(o,t))return;throw new Error(`engine globals namespace "${e}" is registered with other defaults`)}n.set(e,kn(t)),Ad(r,e,t);},tt={set:(e,t)=>{vo(No().store,e,kn(t));},get:e=>ge(No().store,e),reset:()=>{let e=No();e.store=ji(Ta);for(let[t,r]of e.registry)Ad(e.store,t,r);},with:(e,t)=>{let r=No(),n=r.store;r.store=Gi(kn(n),KR(e));try{let o=t();if(GR(o))throw new Error("engineGlobals.with() callback must be synchronous (it returned a Promise).");return o}finally{r.store=n;}}},HR=new Set(["postgresql","cockroachdb","mongodb"]),Nd=e=>HR.has(e),oe=e=>e??tt.get("string.caseInsensitive")??false,Ji=e=>{let t=e??tt.get("string.fuzzy")??false;return t?t===true?{}:t:false};var h={equals:"equals",notEquals:"notEquals",lessThan:"lessThan",lessThanEquals:"lessThanEquals",greaterThan:"greaterThan",greaterThanEquals:"greaterThanEquals",contains:"contains",notContains:"notContains",in:"in",notIn:"notIn",matches:"matches",notMatches:"notMatches",between:"between",notBetween:"notBetween",isEmpty:"isEmpty",notEmpty:"notEmpty",exists:"exists",notExists:"notExists",startsWith:"startsWith",notStartsWith:"notStartsWith",endsWith:"endsWith",notEndsWith:"notEndsWith"},x={all:"all",any:"any",none:"none",atLeast:"atLeast",atMost:"atMost",exactly:"exactly",empty:"empty",notEmpty:"notEmpty"},A={before:"before",after:"after",onOrBefore:"onOrBefore",onOrAfter:"onOrAfter",notBefore:"notBefore",notAfter:"notAfter",within:"within",notWithin:"notWithin",between:"between",notBetween:"notBetween",dayIn:"dayIn",dayNotIn:"dayNotIn"};var N={String:"String",Boolean:"Boolean",Int:"Int",BigInt:"BigInt",Float:"Float",Decimal:"Decimal",DateTime:"DateTime",Json:"Json",Bytes:"Bytes",Enum:"Enum"},Q=["Int","Float","Decimal","BigInt"],Cn=["String",...Q,"DateTime"],dr=["String"],Qi=["String","Boolean","Int","BigInt","Float","Decimal","DateTime","Enum"],Zi=Object.values(N),Pd=Zi,JR={check:"check",toPrisma:"toPrisma",toSql:"toSql"},ko=e=>typeof e=="string"&&Object.hasOwn(N,e),D=["check","toPrisma","toSql"],Ln=["check","toPrisma"],Yi=["check","toSql"],zt={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"},Mn={[h.equals]:{kinds:Qi,targets:D,valueShape:"scalar"},[h.notEquals]:{negates:h.equals,kinds:Qi,targets:D,valueShape:"scalar"},[h.lessThan]:{kinds:Cn,targets:D,valueShape:"ordered",comparator:"lt"},[h.lessThanEquals]:{kinds:Cn,targets:D,valueShape:"ordered",comparator:"lte"},[h.greaterThan]:{kinds:Cn,targets:D,valueShape:"ordered",comparator:"gt"},[h.greaterThanEquals]:{kinds:Cn,targets:D,valueShape:"ordered",comparator:"gte"},[h.in]:{kinds:Qi,targets:D,valueShape:"array"},[h.notIn]:{negates:h.in,kinds:Qi,targets:D,valueShape:"array"},[h.contains]:{kinds:dr,targets:D,valueShape:"string"},[h.notContains]:{negates:h.contains,kinds:dr,targets:D,valueShape:"string"},[h.startsWith]:{kinds:dr,targets:D,valueShape:"string"},[h.notStartsWith]:{negates:h.startsWith,kinds:dr,targets:D,valueShape:"string"},[h.endsWith]:{kinds:dr,targets:D,valueShape:"string"},[h.notEndsWith]:{negates:h.endsWith,kinds:dr,targets:D,valueShape:"string"},[h.matches]:{kinds:dr,targets:Yi,valueShape:"pattern"},[h.notMatches]:{negates:h.matches,kinds:dr,targets:Yi,valueShape:"pattern"},[h.between]:{kinds:Cn,targets:D,valueShape:"range"},[h.notBetween]:{negates:h.between,kinds:Cn,targets:D,valueShape:"range"},[h.isEmpty]:{kinds:Pd,targets:D,valueShape:"none"},[h.notEmpty]:{kinds:Pd,targets:D,valueShape:"none"},[h.exists]:{kinds:Zi,targets:D,valueShape:"none"},[h.notExists]:{kinds:Zi,targets:D,valueShape:"none"}},_n={[A.before]:{kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"lt"},[A.after]:{kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"gt"},[A.onOrBefore]:{kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[A.onOrAfter]:{kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[A.notBefore]:{negates:A.before,kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[A.notAfter]:{negates:A.after,kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[A.within]:{kinds:["DateTime"],targets:D,valueShape:"dateWindow",acceptsExpr:true},[A.notWithin]:{negates:A.within,kinds:["DateTime"],targets:D,valueShape:"dateWindow",acceptsExpr:true},[A.between]:{kinds:["DateTime"],targets:D,valueShape:"dateRange",acceptsExpr:true},[A.notBetween]:{negates:A.between,kinds:["DateTime"],targets:D,valueShape:"dateRange",acceptsExpr:true},[A.dayIn]:{kinds:["DateTime"],targets:Yi,valueShape:"dayList",acceptsExpr:false},[A.dayNotIn]:{negates:A.dayIn,kinds:["DateTime"],targets:Yi,valueShape:"dayList",acceptsExpr:false}},Po={[x.all]:{targets:Ln,valueShape:"predicate",holdsOnNoRows:true},[x.any]:{targets:Ln,valueShape:"predicate",holdsOnNoRows:false},[x.none]:{targets:Ln,valueShape:"predicate",holdsOnNoRows:true},[x.atLeast]:{targets:Ln,valueShape:"count",comparator:"gte",holdsOnNoRows:true},[x.atMost]:{targets:Ln,valueShape:"count",comparator:"lte",holdsOnNoRows:true},[x.exactly]:{targets:Ln,valueShape:"count",comparator:"equals",holdsOnNoRows:true},[x.empty]:{targets:D,valueShape:"none",holdsOnNoRows:true},[x.notEmpty]:{targets:D,valueShape:"none",holdsOnNoRows:false}},kd={field:Mn,date:_n,array:Po},Gt=(e,t)=>Object.hasOwn(kd[t],e)?kd[t][e]:void 0,Fn=e=>typeof e.operator=="string"?Gt(e.operator,"field"):typeof e.dateOperator=="string"?Gt(e.dateOperator,"date"):void 0,ur=(e,t)=>Gt(e,t)?.comparator,Ht=(e,t)=>{let r=Gt(e,t);if(!r)throw ue(e,t);return r.valueShape},Xi=(e,t,r)=>Gt(e,t)?.targets.includes(r)??false,QR=(e,t)=>{let r=Object.keys(Mn).filter(o=>{let i=Mn[o];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))}),n=Object.keys(_n).filter(o=>{let i=_n[o];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))});return {field:r,date:n}},ZR=e=>Object.keys(Po).filter(t=>e?Po[t].targets.includes(e):true),Td=[...Object.entries(Mn),...Object.entries(_n)],Ve=(...e)=>Td.flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),He=Ve("none"),jn=Ve("ordered"),To=Ve("dateWindow"),Je=Ve("range","dateRange","dateWindow"),Cd=Ve("ordered","string","pattern","array"),Et=[h.contains,h.notContains],Ca=[h.equals,h.notEquals,h.in,h.notIn,h.exists,h.notExists],es=[...Ve("scalar","ordered","range"),h.exists,h.notExists],Dn={sum:{result:"number",comparable:true},avg:{result:"number",comparable:true},count:{result:"count",comparable:false},min:{result:"element",comparable:false},max:{result:"element",comparable:false},distinct:{result:"list",comparable:false}},xt=Object.keys(Dn).filter(e=>Dn[e].comparable),La=Object.keys(Dn),ts=e=>typeof e=="string"&&Object.hasOwn(Dn,e),Ld=[...Q,"DateTime"],Md=["String","Enum","DateTime","Boolean",...Q],YR=()=>es,$t=Ve("scalar"),cr=Ve("array"),_d=Ve("scalar","array"),Dd=Ve("dayList"),Fd=Ve("dateRange"),jd=Ve("scalar","ordered","range","dateValue","dateRange"),Vd=(...e)=>Object.entries(Po).flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),Co=Vd("count"),Ma=e=>typeof e.condition!="object"||e.condition===null?null:e.arrayOperator===x.atLeast&&e.count===1?x.any:(e.arrayOperator===x.atMost||e.arrayOperator===x.exactly)&&e.count===0?x.none:null,Lo=e=>Co.includes(e.arrayOperator)&&Ma(e)===null,rs=Vd("predicate","count"),_a=[x.any,x.all,x.none,x.empty,x.notEmpty],Id=[x.any,x.atLeast],B=[...Object.entries(Mn),...Object.entries(_n)].flatMap(([e,t])=>t.negates?[e]:[]),ns=[...B,h.isEmpty,h.notExists],qd=Object.entries(Po).flatMap(([e,t])=>t.holdsOnNoRows?[e]:[]),Bd=B.filter(e=>Ve("string").includes(e)),Vn=B.filter(e=>Je.includes(e)),Wd=(...e)=>Td.flatMap(([t,r])=>r.comparator&&e.includes(r.comparator)&&!B.includes(t)?[t]:[]),os=Wd("lt","lte"),Ud=Wd("gt","gte"),Kd=["Int","BigInt"],Gd=[...Q,"DateTime","Boolean","String"],zd=["Int","BigInt","Float","Boolean","String"],Hd=["scalar","ordered","string"],Mo=["second","minute","hour","day","week","month","quarter","year"],rt={years:{interval:"months",factor:12,calendar:true,clock:"year"},quarters:{interval:"months",factor:3,calendar:true,clock:"quarter"},months:{interval:"months",factor:1,calendar:true,clock:"month"},weeks:{interval:"days",factor:7,calendar:true,clock:"week"},days:{interval:"days",factor:1,calendar:true,clock:"day"},hours:{interval:"secs",factor:3600,calendar:false,clock:"hour"},minutes:{interval:"secs",factor:60,calendar:false,clock:"minute"},seconds:{interval:"secs",factor:1,calendar:false,clock:"second"}},Jd=["months","days","secs"],In=e=>Object.hasOwn(rt,e),jr=e=>In(e)&&rt[e].calendar,is={year:"year",quarter:"quarter",month:"month",week:"week",isoWeek:"week",day:"day",hour:"hour",minute:"minute",second:"second"},ss=Object.keys(is),Qd=e=>typeof e=="string"&&Object.hasOwn(is,e),qn=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],Zd=e=>qn.includes(e.toLowerCase()),Yd=(e,t=[])=>Object.fromEntries([...Object.entries(e).flatMap(([r,n])=>n.negates?[[n.negates,r]]:[]),...t].flatMap(([r,n])=>[[r,n],[n,r]])),_o=Yd(Mn,[[h.isEmpty,h.notEmpty],[h.exists,h.notExists]]),Xd=Yd(_n),as={[h.lessThan]:h.greaterThanEquals,[h.lessThanEquals]:h.greaterThan,[h.greaterThan]:h.lessThanEquals,[h.greaterThanEquals]:h.lessThan,[A.onOrBefore]:A.after,[A.onOrAfter]:A.before};var ls=e=>new Error(`${e}: ArrayRule.field is required (fieldless arrayOps are check-only)`),ue=(e,t)=>new Error(`Unknown ${t} operator: ${String(e)}`),eu=(e,t)=>new Error(`'${e}' is finer than the engine's clock.finestUnit '${t}'`),Bn=e=>new Error(`${e} requires a count`),nt=e=>new Error(`${e} requires a range date expression (a period or rolling window), not a single point`),Ie=e=>new Error(`${e} requires a condition to check against array elements`),mr=e=>new Error(`'${e}' is a relation: it exists or not; compare its fields with '${e}.<field>'.`),ps=e=>new Error(`'${e}' is a list of rows: compare it with an arrayOperator (any / all / none / empty / atLeast \u2026).`),fs=e=>Et.includes(e.operator)&&Ji(e.fuzzy)?new Error("Fuzzy matching has no compiled form \u2014 evaluate it in memory with check()."):null,ds=(e,t)=>!jn.includes(e)&&!Je.includes(e)?null:(Je.includes(e)&&Array.isArray(t)?t:[t]).some(n=>typeof n=="boolean"||typeof n=="object"&&n!==null&&!(n instanceof Date))?new Error(`'${e}' orders numbers, strings and dates; it can't compare ${JSON.stringify(t)}`):null,gr=e=>new Error(`aggregate.mode must be one of ${xt.join(" / ")}, not '${String(e)}'`),us=e=>new Error(`aggregate.mode must be one of ${La.join(" / ")}, not '${String(e)}'`),Wn=e=>new Error(`${e}: a value expression is exactly one of: { value }, { path }, { bind }, an aggregate ({ field, aggregate }), if / then [/ else], or a list`),Un=e=>new Error(`${e}: an aggregate value is the aggregate itself and takes no operator or value; compare it in a rule`),vt=()=>new Error("A condition is exactly one of: a field, date, array or aggregate rule, all, any, or if/then[/else]"),I=(e,t,r)=>new Error(`${t} has no ${e==="toSql"?"SQL":"Prisma"} form${r?` (${r})`:""}; use ${e==="toSql"?"check()":"toSql() or check()"}.`),At=e=>new Error(`Windowing (filter/orderBy/take/skip) is not supported by ${e}() for this rule; evaluate with check()${e==="toPrisma"?" \u2014 toPrisma compiles a filter alone and an extremal take: 1":""}.`),Kn=(e,t)=>new Error(`'${e}' reads through the to-many relation '${t.prefix}'; compare its rows with an arrayOperator rule on '${t.prefix}'.`),Gn=(e,t)=>new Error(`'${e}' continues past '${t}', which is not a Json column`),L=class extends Error{name="UsageError"};Tt.extend(rO);Tt.extend(tO);Tt.extend(eO);Tt.extend(XR);var ee=e=>{if(!re(e))return false;let t=e;return "ago"in t||"ahead"in t||"this"in t||"last"in t||"next"in t||"start"in t||"end"in t},qe="UTC",Do=e=>{if(e.now===void 0)throw new L("date expressions require `now` to be supplied to the evaluator");let t=Tt(e.now).tz(e.timeZone);if(!t.isValid())throw new L(`invalid \`now\`: ${String(e.now)}`);return t},Da=(e,t)=>Object.entries(e).reduce((r,[n,o])=>rt[n].interval===t?r+o*rt[n].factor:r,0),tu="YYYY-MM-DDTHH:mm:ss.SSS",yr=(e,t,r,n)=>{let o=Da(t,"months"),i=Da(t,"days"),s=Da(t,"secs"),a=Tt.utc(e.tz(n).format(tu));return o&&(a=a.add(r*o,"month")),i&&(a=a.add(r*i,"day")),s&&(a=a.add(r*s*1e3,"millisecond")),Tt.tz(a.format(tu),n)},nO=e=>"ago"in e||"ahead"in e,cs=(e,t)=>t===-1?{ago:e}:{ahead:e},Oe=e=>nO(e)?"ago"in e?[e.ago,-1]:[e.ahead,1]:null,Fo=e=>"this"in e||"last"in e||"next"in e,jo=e=>"start"in e||"end"in e,zn=e=>"this"in e?e.this:"last"in e?e.last:e.next,oO=e=>{let t=zn(e);if(typeof t!="string"||!ss.includes(t))throw new Error(`Unknown period unit '${String(t)}'`);return t},iO=(e,t)=>e==="week"?t.weekStart==="sunday"?"week":"isoWeek":e,Fa=(e,t)=>{let r=Do(t),n=oO(e),o=n==="isoWeek"?"week":n,i=r;"last"in e?i=r.subtract(1,o):"next"in e&&(i=r.add(1,o));let s=iO(n,t);return [i.startOf(s),i.endOf(s)]},ja=(e,t)=>{let r=Oe(e);if(r)return yr(Do(t),...r,t.timeZone);if(jo(e)){let n="start"in e?e.start:e.end,[o,i]=Fa(n,t);return "start"in e?o:i}throw new Error("a point operator requires a rolling or start/end edge expression, not a bare period")},Hn=(e,t,r)=>{if(Fo(e)){let[n,o]=Fa(e,r),i=Fn({dateOperator:t})?.negates??t;return os.includes(i)?n:o}return ja(e,r)},Jn=(e,t)=>{if(Fo(e))return Fa(e,t);let r=Oe(e);if(r){let n=Do(t),o=yr(n,...r,t.timeZone);return r[1]===-1?[o,n]:[n,o]}throw nt("within")};var ru=["value","bind","path"],Ee=e=>typeof e.path=="string"&&e.path!=="",Ir=e=>Ee(e)?_(e.path)??{depth:0,path:e.path}:null,Vo=(e,t)=>{if(e.value!==void 0)return t.value(e.value);if(e.bind!==void 0)return t.bind(e.bind,e.bindOptional);if(Ee(e))return t.path(e.path);throw new Error("No value, path or bind specified")},ms=e=>re(e)&&(e.value!==void 0||Ee(e)||typeof e.bind=="string"),Va=(e,t,r)=>{if(!r||!Object.hasOwn(r,e)){if(t===true)return null;throw new L(`Missing binding for "${e}"`)}let n=r[e];return n===void 0?null:n},gs=(e,t,r)=>{if(t===true)return null;throw new L(`Unresolved binding '${e}' \u2014 resolve bindings (bindRule / bindLens) before compiling with ${r}().`)},Be=(e,t,r)=>Vo(e,{value:n=>n,bind:(n,o)=>Va(n,o,r),path:n=>zi(n,t)??null});var ou=e=>typeof e=="object"&&e!==null,ys=e=>"if"in e||"then"in e||"else"in e,xe=e=>"arrayOperator"in e||"aggregate"in e,iu=e=>[...["all","any"].flatMap(t=>Array.isArray(e[t])?e[t].map((r,n)=>({key:t,index:n,child:r,nested:false})):[]),...ys(e)?["if","then","else"].flatMap(t=>e[t]!==void 0?[{key:t,child:e[t],nested:false}]:[]):[],...["condition","filter"].flatMap(t=>e[t]!==void 0?[{key:t,child:e[t],nested:true}]:[])],We=e=>"all"in e||"any"in e||ys(e),H=(e,t,r)=>{if(!ou(e))return;let n=e,o=t(n,r),i=o===void 0?r:o;for(let{child:s,nested:a}of iu(n))a?i!==false&&H(s,t,i):H(s,t,r);},su=(e,t,r,n)=>{let o=false;return H(e,(i,s)=>(!o&&t(i,s)&&(o=true),o?false:r?.(i,s)),n),o},hr=(e,t,r)=>{if(!ou(e))return e;let n=r,o={...e},i=t.rewrite?t.rewrite(o,n):o,s=iu(i),a=s.some(p=>p.nested)&&t.below?t.below(i,n):n;for(let p of ["all","any"])Array.isArray(i[p])&&(i[p]=[...i[p]]);for(let{key:p,index:f,child:d,nested:u}of s){if(u&&a===false)continue;let c=hr(d,t,u?a:n);f===void 0?i[p]=c:i[p][f]=c;}let l=t.after?t.after(i,n):i;return l===i&&sO(i,e)?e:l},sO=(e,t)=>{let r=Object.keys(e);return r.length!==Object.keys(t).length?false:r.every(n=>{let[o,i]=[e[n],t[n]];return o===i?true:Array.isArray(o)&&Array.isArray(i)&&o.length===i.length&&o.every((s,a)=>s===i[a])})},aO=(e,t)=>re(e)?Object.fromEntries(Object.entries(e).map(([r,n])=>[r,ms(n)?t(n,jr(r)?"whole":"number"):n])):e,Ia=(e,t)=>{let r=ee(e)?Oe(e):null;return r?cs(aO(r[0],t),r[1]):e},Qn=(e,t)=>{let r="dateOperator"in e;if(!r&&!("operator"in e))return e;let n=e;if(r&&e.value!==void 0){let o=Array.isArray(e.value)?e.value.map(i=>Ia(i,t)):Ia(e.value,t);n={...n,value:o};}if(ms(e.offset)){let o=r?{...e.offset,...e.offset.value!==void 0&&{value:Ia(e.offset.value,t)}}:e.offset;n={...n,offset:t(o,r?"shift":"number")};}return ms(n)&&(n=t(n,"value")),n},Io=e=>{let t=[];return Qn(e,(r,n)=>(t.push({source:r,role:n}),r)),t},qo=e=>Io(e).flatMap(({source:t,role:r})=>Ee(t)?[{ref:t.path,role:r}]:[]),wr=e=>qo(e).map(t=>t.ref),Zn=e=>[...Array.isArray(e.orderBy)?e.orderBy.flatMap(t=>typeof t?.field=="string"?[t.field]:[]):[],...typeof e.aggregate?.field=="string"?[e.aggregate.field]:[]],lO={all:"all",any:"any",if:"if",field:"field",aggregate:"aggregate",array:"array",date:"date"},qr=()=>(e,t)=>({required:[...e],optional:[...t]}),nu={all:qr()(["all"],["error"]),any:qr()(["any"],["error"]),if:qr()(["if","then"],["else","error"]),field:qr()(["field","operator"],["value","path","bind","bindOptional","offset","caseInsensitive","fuzzy","coerceType","error"]),aggregate:qr()(["field","aggregate","operator"],["value","path","bind","bindOptional","condition","filter","orderBy","take","skip","error"]),array:qr()(["arrayOperator"],["field","condition","count","filter","orderBy","take","skip","error"]),date:qr()(["field","dateOperator"],["value","path","bind","bindOptional","offset","error"])},pO=e=>({required:[...nu[e].required],optional:[...nu[e].optional]}),pe=e=>{let t=new Set;return "all"in e&&t.add("all"),"any"in e&&t.add("any"),ys(e)&&t.add("if"),"arrayOperator"in e&&t.add("array"),"dateOperator"in e&&t.add("date"),"aggregate"in e?t.add("aggregate"):"operator"in e&&t.add("field"),t.size===1?[...t][0]:null},K=e=>e.length===0?true:e.length===1?e[0]:{all:[...e]},qa=e=>typeof e=="object"&&"all"in e&&Array.isArray(e.all)?e.all.flatMap(qa):[e],Nt=e=>e.length===0?false:e.length===1?e[0]:{any:[...e]};var fO=e=>e===null||e instanceof Date||["string","number","boolean","bigint"].includes(typeof e),Jt=e=>{if(Array.isArray(e))return e;let t=e.list;return Array.isArray(t)?t:[]},Pt=e=>{if(Array.isArray(e))return "list";if(fO(e))return "literal";if(!re(e))return null;let t=e,r=[];return "list"in t&&r.push("list"),ys(t)&&r.push("if"),"aggregate"in t&&r.push("aggregate"),("value"in t||"path"in t||"bind"in t)&&r.push("source"),r.length===1?r[0]:null},Br=e=>{let t=e;switch(Pt(e)){case "list":return K(Jt(e).map(Br));case "if":return K([t.if,Br(t.then),...t.else===void 0?[]:[Br(t.else)]]);case "aggregate":return t;case "source":return Ee(t)?{field:t.path,operator:"exists"}:true;default:return true}};var dO=e=>Io(e).flatMap(({source:t})=>typeof t.bind=="string"?[t]:[]),Bo=(e,{required:t=false}={})=>{let r=new Set;return H(e,n=>{for(let o of dO(n))(!t||o.bindOptional!==true)&&r.add(o.bind);}),[...r].sort()},uO=e=>{let t=new Set;return H(e,r=>{typeof r.field=="string"&&t.add(r.field);for(let{ref:n}of qo(r))t.add(n);return xe(r)?false:void 0}),[...t].sort()},Ba=(e,t)=>{let r=n=>{if(typeof n.bind!="string"||!Object.hasOwn(t,n.bind))return n;let{bind:o,bindOptional:i,...s}=n;return {...s,value:Va(o,true,t)}};return hr(e,{rewrite:n=>Qn(Qn(n,r),r)})};var au=BigInt(Number.MAX_SAFE_INTEGER),Wr=e=>{if(e>au||e<-au)throw new RangeError(`BigInt ${e} is outside the safe integer range (\xB12^53); json-rules compares BigInt as Int.`);return Number(e)},Wa=e=>typeof e=="bigint"?Wr(e):typeof e=="string"&&e.trim()!==""&&Number.isFinite(Number(e))?Number(e):e,hs=(e,t)=>{if(e==null)return null;let r=Wa(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${t} reads a number (got ${String(e)})`);return r},Qe=([e,t])=>t<e?[t,e]:[e,t],ot=(e,t)=>{if(!Array.isArray(e)||e.length!==2)throw new Error(`${t} operator requires an array of two values`);return [e[0],e[1]]},Yn=(e,t)=>{let r=ot(e,t);if(!r.every(ye))throw new Error(`${t} requires two ends that order \u2014 numbers, strings or dates (got ${JSON.stringify(e)})`);return r},ws=e=>{if(!Array.isArray(e))throw new Error(`in / notIn requires a list (got ${JSON.stringify(e)})`);return e},Ze=e=>{let t=ws(e),r=t.filter(n=>n!==null);return {values:r,hasNull:r.length!==t.length}},ye=e=>typeof e=="string"||typeof e=="number"||e instanceof Date;var Ua=(e,t)=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&(!jr(t)||Number.isInteger(e))?null:`${t} must be a non-negative${jr(t)?" whole":""} number (got ${String(e)})`,Ka=(e,t,r)=>{let n=typeof e=="number"?e:hs(t(e),e.path?`'${e.path}' (${r})`:r),o=n===null?null:Ua(n,r);if(o===null)return n;if(typeof e!="number"&&Ee(e))return null;throw new Error(o)},Ur=(e,t)=>{let r={};for(let[n,o]of Object.entries(e)){if(o===void 0)continue;let i=Ka(o,t,n);if(i===null)return null;r[n]=i;}return r},kt=(e,t)=>{let r=Oe(e);if(!r)return e;let n=Ur(r[0],t);return n?cs(n,r[1]):null};var cO=e=>{let t=Oe(e);if(t)return re(t[0])?Object.keys(t[0]).flatMap(o=>In(o)?[rt[o].clock]:[]):[];let r=jo(e)?"start"in e?e.start:e.end:e;if(!re(r))return [];let n=zn(r);return Qd(n)?[is[n]]:[]},lu=(e,t)=>[...vi(e),t].filter(ee).flatMap(cO),mO=e=>vi(e).some(ee),bs=e=>Mo.indexOf(e),gO=()=>{let e=tt.get("clock.finestUnit");if(Mo.includes(e))return e;if(typeof e=="string"&&In(e))return rt[e].clock;throw new L(`clock.finestUnit reads a clock unit, singular or plural (got ${String(e)})`)},Qt=(e,t)=>{let r=lu(e,t);if(r.length===0)return null;let n=gO(),o=r.find(i=>bs(i)<bs(n));return o?eu(o,n):null},Ga=e=>re(e)?e.value:void 0,Wo=e=>{let t=null;return H(e,r=>{if(!("dateOperator"in r))return;let n=Ga(r.offset),o=Qt(r.value,n);if(o)throw o;if(mO(r.value))for(let i of lu(r.value,n))(t===null||bs(i)<t)&&(t=bs(i));}),t===null?null:Mo[t]};var Kr=(e,t)=>{if(e==null)return null;if(Array.isArray(e)){let n=e.map(o=>Kr(o,t));return n.some(o=>o===null)?null:n}let r=Wa(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`offset needs a numeric comparison value (got ${String(e)})`);return r+t},Gr=e=>hs(e,"an offset"),Xn=e=>{if(e==null)return null;let t=ee(e)?Oe(e):null;if(!t)throw new Error(`a date offset reads { ago } or { ahead } (got ${JSON.stringify(e)})`);return t};Tt.extend(rO);Tt.extend(tO);Tt.extend(hO);Tt.extend(yO);var du=(e,t,r={},n)=>{let o=fr(e.field,t),i=Zt(r,u=>Be(u,t,n)),s=i.timeZone;if(o==null)return B.includes(e.dateOperator)?true:e.error||`${e.field} has no value`;let a=ye(o)?br(o,s):null;if(!a?.isValid())throw new Error(`${e.field} is not a valid date: ${String(o)}`);let l=u=>e.error||`${e.field} ${u}`;if(Dd.includes(e.dateOperator)){let u=za(Be(e,t,n));if(u===null)return e.error||`${e.field} has no comparison value`;let c=u.includes(a.tz(s).day()),y=u.map(m=>qn[m]).join(" or ");return e.dateOperator===A.dayIn?c||l(`must be on ${y}`):!c||l(`must not be on ${y}`)}let p=SO(e,t,i,s,n);if(p===null)return e.error||`${e.field} has no comparison value`;let[f,d=f]=p;switch(e.dateOperator){case A.before:return a.isBefore(f)||l(`must be before ${f.format()}`);case A.after:return a.isAfter(f)||l(`must be after ${f.format()}`);case A.onOrBefore:return a.isSameOrBefore(f)||l(`must be on or before ${f.format()}`);case A.onOrAfter:return a.isSameOrAfter(f)||l(`must be on or after ${f.format()}`);case A.within:return a.isSameOrAfter(f)&&a.isSameOrBefore(d)||l(`must be within ${f.format()} and ${d.format()}`);case A.notBefore:return a.isSameOrAfter(f)||l(`must not be before ${f.format()}`);case A.notAfter:return a.isSameOrBefore(f)||l(`must not be after ${f.format()}`);case A.notWithin:return a.isBefore(f)||a.isAfter(d)||l(`must not be within ${f.format()} and ${d.format()}`);case A.between:return a.isSameOrAfter(f)&&a.isSameOrBefore(d)||l(`must be between ${f.format()} and ${d.format()}`);case A.notBetween:return a.isBefore(f)||a.isAfter(d)||l(`must not be between ${f.format()} and ${d.format()}`);default:throw ue(e.dateOperator,"date")}},SO=(e,t,r,n,o)=>{let i=e.dateOperator,s=g=>Be(g,t,o),a=Be(e,t,o);if(a==null)return null;let l=e.offset===void 0?void 0:s(e.offset),p=Qt(a,l);if(p)throw p;let f=l===void 0?void 0:Xn(l);if(f===null)return null;let d=g=>{if(f===void 0)return g;let b=Ur(f[0],s);return b&&yr(g,b,f[1],n)};if(To.includes(i)){if(!ee(a))throw nt(i);let g=kt(a,s);return g&&Jn(g,r)}let u=(g,b)=>{if(g==null)return null;if(ee(g)){let w=kt(g,s);return w&&ja(w,r)}let S=br(g,n);if(!S.isValid())throw new Error(`Invalid ${b}: ${String(g)}`);return S};if(Fd.includes(i)){let[g,b]=ot(a,i),S=u(g,"start date"),w=u(b,"end date");if(!S||!w)return null;let[R,O]=Qe([S,w]),$=d(R),k=d(O);return $&&k?[$,k]:null}if(Array.isArray(a))throw new Error(`${i} operator requires a single date value`);let c=g=>{let b=kt(g,s);return b&&Hn(b,i,r)},y=ee(a)?c(a):u(a,"comparison date");if(!y)return null;let m=d(y);return m&&[m]},Zt=(e,t)=>{let r=e.timeZone;if(r===void 0||typeof r=="string")return {...e,timeZone:fu(r??qe)};if(Ir(r))throw new L(`timeZone is one per evaluation; give it as a string or a { bind }, not the row path '${r.path}'`);let n=t(r);if(n!=null&&typeof n!="string")throw new L(`timeZone reads a zone name (got ${String(n)})`);return {...e,timeZone:fu(n??qe)}},pu=new Set,fu=e=>{if(pu.has(e))return e;try{new Intl.DateTimeFormat("en-US",{timeZone:e});}catch{throw new L(`invalid time zone: ${e}`)}return pu.add(e),e},RO=/\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?\s*(?:[zZ]|[+-]\d{2}(?::?\d{2})?)$/,OO=e=>RO.test(e.trim())||/\b(?:GMT|UTC)\b/.test(e),br=(e,t)=>{if(typeof e=="string"&&/^-?\d+$/.test(e.trim()))return Tt(Number(e));if(typeof e=="string"&&!OO(e)){let r=Tt(e);return r.isValid()?Tt.tz(e,t):r}return typeof e=="string"?Tt(new Date(e.trim())):Tt(e)},Ss=(e,t)=>{let r=ye(e)?br(e,t):Tt(Number.NaN);if(!r.isValid())throw new Error(`Invalid date value: ${String(e)}`);return r.toDate()},za=e=>{if(e==null)return null;if(!Array.isArray(e))throw new Error("a weekday operator requires an array of day names");return e.map(t=>{let r=qn.indexOf(String(t).toLowerCase());if(r===-1)throw new Error(`Unknown day name: ${String(t)}`);return r})};var xO=e=>e<=3?0:e<=6?1:2,$O=(e,t)=>{let{maxDistance:r,maxRatio:n}=e,o=[];return typeof r=="number"&&o.push(r),typeof n=="number"&&o.push(Math.floor(t*n)),o.length>0?Math.min(...o):xO(t)},uu=e=>e.split(/[^a-z0-9\p{L}]+/u).filter(Boolean),vO=e=>/^\d+$/.test(e),AO=(e,t,r)=>e===t?true:Math.abs(e.length-t.length)>r?false:distance(e,t)<=r,cu=(e,t,r={})=>{let n=t.trim().toLowerCase();if(!n)return true;let o=e.toLowerCase();if(o.includes(n))return true;let i=uu(n);if(i.length===0)return false;let s=uu(o);return s.length===0?false:i.every(a=>{let l=$O(r,a.length);return l===0||vO(a)?s.includes(a):s.some(p=>AO(a,p,l))})};var Sr=e=>{let t=e instanceof RegExp?e.source:e,r=e instanceof RegExp?e.flags:"";if(/[^i]/.test(r))throw new Error(`Refused pattern /${t}/${r}: only the 'i' flag is supported`);let n=r==="i";try{return {source:t,caseInsensitive:n,re:RE2JS.compile(t,n?RE2JS.CASE_INSENSITIVE:0)}}catch(o){throw new Error(`Refused pattern /${t}/: ${o.message}`)}},eo={d:"0-9",w:"0-9A-Za-z_",s:"\\t\\n\\f\\r "},gu={alnum:"0-9A-Za-z",alpha:"A-Za-z",ascii:"\\u0000-\\u007f",blank:"\\t ",cntrl:"\\u0000-\\u001f\\u007f",digit:"0-9",graph:"!-~",lower:"a-z",print:" -~",punct:"!-/:-@\\[-`{-~",space:"\\t\\n\\v\\f\\r ",upper:"A-Z",word:"0-9A-Za-z_",xdigit:"0-9A-Fa-f"},NO=/[\\^$.|?*+()[\]{}]/,Ha=255,yu=e=>e<=65535?`\\u${e.toString(16).padStart(4,"0")}`:`\\U${e.toString(16).padStart(8,"0")}`,PO=e=>NO.test(e)?`\\${e}`:e,Uo=e=>{let t=s=>{throw new Error(`Refused pattern /${e}/: ${s} has no Postgres form`)},r="",n=0,o=()=>{/^([*+?]|\{\d)/.test(e.slice(n))&&t("a quantified anchor");},i=s=>{let a=e[n+1];if(n+=2,Object.hasOwn(eo,a))return s?eo[a]:`[${eo[a]}]`;let l=a.toLowerCase();if(a!==l&&Object.hasOwn(eo,l))return s&&t(`a negated class \\${a} inside brackets`),`[^${eo[l]}]`;if(a==="p"||a==="P")return t("a Unicode class");if(a==="C")return t("\\C");if(a==="x"){let p=e[n]==="{",f=p?e.indexOf("}",n):n+2,d=e.slice(p?n+1:n,f);return n=p?f+1:f,yu(Number.parseInt(d,16))}if(a>="0"&&a<="7"){let p=a;for(;p.length<3&&e[n]>="0"&&e[n]<="7";)p+=e[n++];return yu(Number.parseInt(p,8))}if(!s&&(a==="b"||a==="B")){let p=`[${eo.w}]`;return a==="b"?`(?:(?<=${p})(?!${p})|(?<!${p})(?=${p}))`:`(?:(?<=${p})(?=${p})|(?<!${p})(?!${p}))`}if(!s&&(a==="z"||a==="A"))return o(),a==="z"?"\\Z":"\\A";if(a==="Q"){let p=e.indexOf("\\E",n),f=e.slice(n,p===-1?void 0:p);return n=p===-1?e.length:p+2,[...f].map(s?d=>/[\\\]^-]/.test(d)?`\\${d}`:d:PO).join("")}return `\\${a}`};for(;n<e.length;){let s=e[n];if(s==="\\")r+=i(false);else if(s===".")r+="[^\\n]",n++;else if(s==="("&&e[n+1]==="?"){let a=/^\(\?P?<[^>]+>/.exec(e.slice(n));a?(r+="(",n+=a[0].length):e[n+2]===":"?(r+="(?:",n+=3):t("a flag group");}else if(s==="{"){let a=/^\{(0|[1-9]\d*)(?:,(0|[1-9]\d*)?)?\}/.exec(e.slice(n));if(!a){r+="\\{",n++;continue}(Number(a[1])>Ha||Number(a[2]??0)>Ha)&&t(`a repeat count past ${Ha}`),r+=a[0],n+=a[0].length;}else if(s==="["){r+="[",n++,e[n]==="^"&&(r+="^",n++),e[n]==="]"&&(r+="\\]",n++);let a=false,l=false,p=0;for(;n<e.length&&e[n]!=="]";){let f=l?null:/^\[:(\^?)([a-z]+):\]/.exec(e.slice(n)),d=!!f||/^\\[dswDSW]/.test(e.slice(n)),u=e[n]==="-"&&p>0&&e[n+1]!=="]"&&!l;f?(f[1]&&t(`a negated class [:^${f[2]}:]`),Object.hasOwn(gu,f[2])||t(`the class [:${f[2]}:]`),r+=gu[f[2]],n+=f[0].length):e[n]==="\\"?r+=i(true):u&&a?(r+="\\-",n++):(r+=e[n]==="["?"\\[":e[n],n++);let c=l;l=u&&!a,a=d||c,p++;}r+="]",n++;}else r+=s,n++,(s==="^"||s==="$")&&o();}return r},hu=(e,t)=>{try{let{source:r}=Sr(e);return t==="toSql"&&Uo(r),null}catch(r){return r.message}};var wu=e=>e==null||e===""||Array.isArray(e)&&e.length===0,$e=(e,t)=>{let r=t==null;return r&&(e.offset!==void 0||Cd.includes(e.operator))?true:Je.includes(e.operator)?r||Array.isArray(t)&&t.some(n=>n==null):false},Xt=e=>He.includes(e.operator)||$t.includes(e.operator)&&e.value===null&&e.path===void 0&&e.bind===void 0,Os=(e,t)=>{let r=t.filter(o=>Array.isArray(o)||o===null),n=o=>r.map(i=>({...e,operator:o,value:i}));return e.operator===h.in?Nt(n(h.equals)):K(n(h.notEquals))},zr=e=>typeof e=="string"?e.toLowerCase():Array.isArray(e)?e.map(zr):e,bu=e=>typeof e=="bigint"?Wr(e):Array.isArray(e)&&e.some(t=>typeof t=="bigint")?e.map(t=>typeof t=="bigint"?Wr(t):t):e,Su=(e,t,r)=>{if(e==null)return e;if(Q.includes(t)){if(typeof e!="string"||e.trim()==="")return e;if(t==="BigInt"&&/^-?\d+$/.test(e.trim()))return Wr(BigInt(e.trim()));let n=Number(e);return Number.isFinite(n)?n:e}switch(t){case "DateTime":{if(e instanceof Date)return e.getTime();if(typeof e=="number"||typeof e!="string")return e;let n=br(e,r);return n.isValid()?n.valueOf():e}case "Boolean":return e==="true"?true:e==="false"?false:e;case "String":return typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):e;default:return e}},Yt=(e,t,r=qe)=>t===void 0?e:Array.isArray(e)?e.map(n=>Su(n,t,r)):Su(e,t,r),Ko=(e,t,r,n={},o)=>{let i=o?o.value:fr(e.field,t);if(n.absent==="unknown"&&!ns.includes(e.operator)&&(i===void 0||Ee(e)&&zi(e.path,t)===void 0))return e.error||`${e.field} is unknown`;let s=i??null,a=e.coerceType??(s instanceof Date?"DateTime":void 0),l=a==="DateTime"?Zt(n,w=>Be(w,t,r)).timeZone:qe,p=Yt(bu(s),a,l),f=!He.includes(e.operator),d=f?kO(Yt(bu(Be(e,t,r)??null),a,l),e,t,r):void 0;if(f&&$e(e,d))return B.includes(e.operator)&&p==null?true:e.error||`${e.field} has no comparison value`;let u=w=>e.error||`${e.field} ${w}${f?` ${d instanceof RegExp?String(d):JSON.stringify(d)}`:""}`,c=oe(e.caseInsensitive),y=w=>c?zr(w):w,m=y(p),g=y(d),b=Ji(e.fuzzy),S=()=>b&&typeof p=="string"&&typeof d=="string"?cu(p,d,b):Array.isArray(p)?m.some(w=>Kt(w,g)):TO(m,g);switch(e.operator){case h.equals:return Kt(m,g)||u("must equal");case h.notEquals:return !Kt(m,g)||u("must not equal");case h.lessThan:return Rs(p,d,"lt")||u("must be less than");case h.lessThanEquals:return Rs(p,d,"lte")||u("must be less than or equal to");case h.greaterThan:return Rs(p,d,"gt")||u("must be greater than");case h.greaterThanEquals:return Rs(p,d,"gte")||u("must be greater than or equal to");case h.in:return ws(g).some(w=>Kt(w,m))||u("must be one of");case h.notIn:return !ws(g).some(w=>Kt(w,m))||u("must not be one of");case h.contains:return S()||u("must contain");case h.notContains:return !S()||u("must not contain");case h.matches:return Ru(p)&&Ou(d)&&Sr(d).re.test(p)||u("must match pattern");case h.notMatches:return !Ru(p)||!Ou(d)||!Sr(d).re.test(p)||u("must not match pattern");case h.between:{let w=Eu(d,e.operator);if(!$u(p,w))return u("must be between");let R=to(p),[O,$]=w;return R>=O&&R<=$||u("must be between")}case h.notBetween:{let w=Eu(d,e.operator);if(!$u(p,w))return true;let R=to(p),[O,$]=w;return R<O||R>$||u("must not be between")}case h.isEmpty:return wu(p)||u("must be empty");case h.notEmpty:return !wu(p)||u("must not be empty");case h.exists:return p!=null||u("must exist");case h.notExists:return p==null||u("must not exist");case h.startsWith:return typeof m=="string"&&typeof g=="string"&&m.startsWith(g)||u("must start with");case h.endsWith:return typeof m=="string"&&typeof g=="string"&&m.endsWith(g)||u("must end with");case h.notStartsWith:return !(typeof m=="string"&&typeof g=="string"&&m.startsWith(g))||u("must not start with");case h.notEndsWith:return !(typeof m=="string"&&typeof g=="string"&&m.endsWith(g))||u("must not end with");default:throw new Error("Unknown operator")}},kO=(e,t,r,n)=>{if(t.offset===void 0)return e;let o=Gr(Be(t.offset,r,n));return o===null?null:Kr(e,o)},to=e=>e instanceof Date?e.getTime():e,Rs=(e,t,r)=>{if(!CO(e,t)||!ye(t))return false;let n=to(e),o=to(t);switch(r){case "lt":return n<o;case "lte":return n<=o;case "gt":return n>o;case "gte":return n>=o}},Ru=e=>typeof e=="string",Ou=e=>typeof e=="string"||e instanceof RegExp,Eu=(e,t)=>Qe(Yn(e,t).map(r=>to(r))),TO=(e,t)=>typeof e=="string"&&typeof t=="string"&&e.includes(t),CO=(e,t)=>ye(e)&&ye(t)&&xu(e)===xu(t),xu=e=>e instanceof Date?"date":typeof e,$u=(e,t)=>ye(e)&&typeof to(e)==typeof t[0];var Pe=e=>e.filter!==void 0||!!e.orderBy?.length||e.take!==void 0||e.skip!==void 0,LO=e=>{if(typeof e!="object"||e===null)return null;let t=e,r=pe(t);return r!=="field"&&r!=="date"||typeof t.field!="string"?null:{op:String(r==="date"?t.dateOperator:t.operator),field:t.field}},MO=e=>{if(e.filter!==void 0||e.skip!==void 0&&e.skip!==0||e.take!==1||e.orderBy?.length!==1)return null;let{field:t,dir:r}=e.orderBy[0];if(r!=="asc"&&r!=="desc")return null;let n=null;if(e.arrayOperator===x.all?n="all":(e.arrayOperator===x.any||e.arrayOperator===x.atLeast&&e.count===1)&&(n="any"),!n)return null;let o=LO(e.condition);if(!o||o.field!==t)return null;let i=os.includes(o.op),s=Ud.includes(o.op);if(!i&&!s)return null;let a=r==="desc";if(!(n==="all"?a&&i||!a&&s:a&&s||!a&&i))return null;let{orderBy:p,take:f,skip:d,count:u,...c}=e;if(n==="any")return {...c,arrayOperator:x.any};let y={field:t,operator:h.exists};return {any:[{field:e.field,arrayOperator:x.empty},{all:[{field:e.field,arrayOperator:x.any,condition:y},{...c,arrayOperator:x.all,condition:{if:y,then:e.condition}}]}]}},Ja=(e,t,r)=>{let n=e;return t.filter!==void 0&&r&&(n=n.filter(r)),t.orderBy?.length&&(n=vu(n,t.orderBy)),t.skip!==void 0&&(n=n.slice(t.skip)),t.take!==void 0&&(n=n.slice(0,t.take)),n},vu=(e,t)=>[...e].sort((r,n)=>{for(let{field:o,dir:i}of t){let s=_O(ge(r,o),ge(n,o),i);if(s!==0)return s}return 0}),_O=(e,t,r)=>{let n=e==null,o=t==null;if(n||o)return n===o?0:n?1:-1;let i=e instanceof Date?e.getTime():e,s=t instanceof Date?t.getTime():t,a=i<s?-1:i>s?1:0;return r==="asc"?a:-a},ro=e=>{if(!Pe(e))return e;let t=!!e.orderBy?.length||e.take!==void 0||e.skip!==void 0;if(e.filter!==void 0&&!t){let{filter:r,...n}=e;if("aggregate"in e)return {...n,condition:e.condition===void 0?r:K([r,e.condition])};switch(e.arrayOperator){case "all":return {...n,condition:{if:r,then:e.condition??true}};case "empty":return {...n,arrayOperator:"none",condition:r};case "notEmpty":return {...n,arrayOperator:"any",condition:r};default:return {...n,condition:e.condition===void 0?r:K([r,e.condition])}}}return "aggregate"in e||e.filter!==void 0?null:MO(e)};var DO=e=>H(e,t=>{let r=pe(t);if(!(r==="all"||r==="any")){if(r==="array"&&!("field"in t))return false;throw new Error("check: when data is an array, every leaf must be a fieldless arrayOperator (composable with all/any)")}}),he=(e,t,r)=>(Array.isArray(t)&&DO(e),it(e,t,{...r,scopes:[t]})),it=(e,t,r)=>{if(typeof e=="boolean")return e;let n=e;switch(pe(e)){case "all":return FO(n.all,t,r,n.error);case "any":return jO(n.any,t,r,n.error);case "if":return VO(n,t,r);case "array":return BO(n,r);case "aggregate":return qO(n,r);case "date":return du(n,r.scopes,r,r.bindings);case "field":return Ko(n,r.scopes,r.bindings,r);default:throw vt()}},Es=(e,t)=>({...e,scopes:[...e.scopes,t]}),FO=(e,t,r,n)=>{let o=[];for(let i of e){let s=it(i,t,r);s!==true&&(typeof s=="string"?o.push(s):o.push("false"));}return o.length?n||(o.length===1?o[0]:`All conditions must pass: ${o.join(" AND ")}`):true},jO=(e,t,r,n)=>{let o=[];for(let i of e){let s=it(i,t,r);if(s===true)return true;typeof s=="string"&&o.push(s);}return n||(o.length===1?o[0]:`At least one condition must pass: ${o.join(" OR ")}`)},VO=(e,t,r)=>it(e.if,t,r)===true?it(e.then,t,r):e.else!==void 0?it(e.else,t,r):true,Au=(e,t)=>{if(e==null)return [];if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e},Nu=(e,t)=>it(e,t.scopes[t.scopes.length-1],t)===true,Qa=(e,t)=>{let r=Au(fr(e.field,t.scopes),e.field),n=e.filter,o=Ja(r,e,n?s=>it(n,s,Es(t,s))===true:void 0),i=e.condition;return i?o.filter(s=>it(i,s,Es(t,s))===true):o},Go=(e,t,r,n)=>e.flatMap((o,i)=>{let s=r?ge(o,r):o;return s==null?[]:[n(s,`${t}[${i}]${r?`.${r}`:""}`)]}),IO=(e,t)=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error(`${t} must be a finite number`);return e},Za=(e,t,r,n)=>{let o=Go(t,r,n,IO),i=o.reduce((s,a)=>s+a,0);return e==="sum"?i:o.length===0?null:i/o.length},qO=(e,t)=>{let{mode:r,field:n}=e.aggregate;if(!xt.includes(r))throw gr(r);let o=Qa(e,t),i=Za(r,o,e.field,n),s={...e,field:`${e.field} ${r}`};return Ko(s,t.scopes,t.bindings,t,{value:i})},BO=(e,t)=>{let r=Au(e.field?fr(e.field,t.scopes):t.scopes[t.scopes.length-1],e.field||"(root)"),n=e.filter,o=Ja(r,e,n?d=>it(n,d,Es(t,d))===true:void 0),i=d=>e.error||`${e.field} ${d}`,s=e.condition,a=rs.includes(e.arrayOperator);if(a&&s===void 0)throw Ie(e.arrayOperator);let l=e.count??0;if(Co.includes(e.arrayOperator)&&e.count===void 0)throw Bn(e.arrayOperator);let p=0,f=0;if(a&&s!==void 0){if(o.length>0&&!Pa(o,Z))return i("contains only primitive values; use 'in' or 'contains' instead of array operators on primitive arrays");let d=o.map(u=>it(s,u,Es(t,u)));p=d.filter(u=>u===true).length,f=d.filter(u=>typeof u=="string").length;}switch(e.arrayOperator){case x.empty:return !o.length||i("must be empty");case x.notEmpty:return !!o.length||i("must not be empty");case x.all:return p===o.length||i(`all elements must match (${f} failed)`);case x.any:return !!p||i("at least one element must match");case x.none:return !p||i(`no elements should match (${p} matched)`);case x.atLeast:return p>=l||i(`at least ${l} elements must match (${p} matched)`);case x.atMost:return p<=l||i(`at most ${l} elements must match (${p} matched)`);case x.exactly:return p===l||i(`exactly ${l} elements must match (${p} matched)`);default:throw ue(e.arrayOperator,"array")}};var E=(e,t)=>e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0,er=(e,t,r)=>(Object.hasOwn(e,t)||(e[t]=r()),e[t]),C=(e,t)=>E(e?.models,t),ce=(e,t,r)=>E(C(e,t)?.fields,r);var Me=({fieldMap:e,model:t})=>`${e}:${t}`,Pu=(e,t)=>{let r=e.indexOf(":");return r===-1?{mapName:t,modelName:e}:{mapName:e.slice(0,r),modelName:e.slice(r+1)}};var ku=(e,t,r,n)=>{let o={};for(let i of e){let s=E(i,t);if(s==null)continue;let a=String(s);if(Object.hasOwn(o,a)){let l=n==="one"?`endpoint[0] must be the "one" side of a oneToMany bridge \u2014 swap endpoints if '${r}' is the "many" side`:`oneToOne bridges require unique '${t}' on both endpoints`;throw new Error(`indexBridges: duplicate '${t}' value '${a}' on '${r}' \u2014 ${l}.`)}o[a]=i;}return o},WO=(e,t)=>{let r={};for(let n of e){let o=E(n,t);o!=null&&er(r,String(o),()=>[]).push(n);}return r},Tu=(e,t)=>{let r={};for(let n of e.bridges??[]){let[o,i]=n.endpoints,s=Me(o),a=Me(i),l=n.cardinality==="oneToMany"?"one":"oneToOne",p=(u,c)=>er(er(r,u,()=>({})),c,()=>({})),f=E(t,s);f&&(p(o.fieldMap,o.model)[o.on]=ku(f,o.on,s,l));let d=E(t,a);d&&(n.cardinality==="oneToMany"?p(i.fieldMap,i.model)[i.on]=WO(d,i.on):p(i.fieldMap,i.model)[i.on]=ku(d,i.on,a,"oneToOne"));}return r};var xs=e=>{let t={maps:structuredClone(e.maps),bridges:e.bridges?structuredClone(e.bridges):void 0};for(let r of e.bridges??[]){let[n,o]=r.endpoints,i=Me(n),s=Me(o),a=C(E(t.maps,n.fieldMap),n.model),l=C(E(t.maps,o.fieldMap),o.model);if(!a)throw new Error(`stitchFieldMaps: endpoint '${i}' not found`);if(!l)throw new Error(`stitchFieldMaps: endpoint '${s}' not found`);if(n.fieldMap===o.fieldMap&&n.model===o.model)throw new Error(`stitchFieldMaps: self-bridge '${i}' to itself is not supported`);if(!E(a.fields,n.on))throw new Error(`stitchFieldMaps: endpoint '${i}' has no field '${n.on}' for join`);if(!E(l.fields,o.on))throw new Error(`stitchFieldMaps: endpoint '${s}' has no field '${o.on}' for join`);if(E(a.fields,s))throw new Error(`stitchFieldMaps: bridge '${s}' already injected on '${i}'`);if(E(l.fields,i))throw new Error(`stitchFieldMaps: bridge '${i}' already injected on '${s}'`);let p=r.cardinality==="oneToMany";a.fields[s]={kind:"bridge",type:s,isList:p},l.fields[i]={kind:"bridge",type:i,isList:false};}return t};var no=(e,t,r)=>{if(e?.isList||t?.isList){if(!(e?.isList&&!t?.isList&&Et.includes(r)))return "a list column compares with no column but by membership";if(e?.kind!=="enum"&&t?.kind!=="enum")return null}let n=[e,t].filter(o=>o?.kind==="enum");return n.length===0?null:n.length===1||e?.type!==t?.type?"an enum compares only with an enum column of its own type":$t.includes(r)?null:`an enum column orders by declaration on the database, not as check() compares its text ('${r}')`};var Ue=e=>e.kind==="scalar"&&e.type==="Json",M=e=>e.kind==="object"||e.kind==="bridge",Hr=(e,t)=>e.values??E(t,e.type);var ke=(e,t,r)=>{if(!e||!("maps"in e))return e;if(!t)throw new Error(`${r}: 'map' is a FieldMapSet \u2014 'mapName' is required to resolve which map to use.`);let n=E(e.maps,t);if(!n)throw new Error(`${r}: fieldMap set has no entry for '${t}'`);return n};var st=(e,t)=>e.kind==="object"?{mapName:t,modelName:e.type}:e.kind==="bridge"?Pu(e.type,t):null;function*Rr(e,t,r){let n=r.split("."),o=t;for(let i=0;i<n.length;i++){let s=n[i],a=ce(E(e,o.mapName),o.modelName,s),l=a?st(a,o.mapName):null;if(yield {index:i,field:s,at:o,entry:a,next:l},!l)return;o={...l,relPath:[...o.relPath,s]};}}var ie=(e,t,r)=>{let n=e.split("."),o=[],i={mapName:"",modelName:r,relPath:[]};for(let{index:s,field:a,at:l,entry:p}of Rr({"":t},i,e)){let f=l.modelName;if(!p)return {kind:"fallback",hops:o};if(p.kind==="bridge")return {kind:"bridge",hops:o};let d=s===n.length-1;if(p.kind==="object"){if(!C(t,p.type))return {kind:"fallback",hops:o};if(d)return {kind:"direct",hops:o,entry:p,model:f,column:a};o.push({field:a,prefix:n.slice(0,s+1).join("."),entry:p,from:f});continue}return d?{kind:"direct",hops:o,entry:p,model:f,column:a}:Ue(p)?{kind:"json-path",hops:o,entry:p,model:f,column:a,stopIndex:s+1,jsonPath:n.slice(s+1)}:{kind:"past-scalar",hops:o,column:a}}return {kind:"fallback",hops:o}},Or=(e,t,r)=>t&&r?ie(e,t,r):void 0,te=(e,t,r)=>{let n=Or(e,t,r);return n?.kind==="direct"?n.entry:void 0},Cu=(e,t,r)=>ie(e,t,r).hops.filter(n=>!n.entry.isList&&n.entry.isRequired===false).map(n=>n.prefix),zo=(e,t,r)=>{let n=ie(e,t,r);return n.kind==="direct"&&n.entry.kind==="object"?n.entry.type:null},Er=(e,t,r)=>ie(e,t,r).kind==="bridge",Ct=(e,t,r)=>!!t&&!!r&&su(e,(n,o)=>typeof n.field=="string"&&n.field!==""&&Er(n.field,t,o),(n,o)=>(typeof n.field=="string"?zo(n.field,t,o):o)??false,r);var Jr=e=>e?.kind==="json-path"?"json-path":e?.kind!=="direct"?"unknown":e.entry.kind==="object"?e.entry.isList?"relations":"relation":e.entry.isList?"list":e.entry.kind==="enum"?"enum":Lu(e.entry.type),Lu=e=>e===N.Json?"json":e===N.Enum?"enum":e===N.DateTime?"instant":e===N.String?"text":"scalar",$s=(e,t,r)=>{let n=te(e.field,t,r);return n?n.kind==="scalar"&&(n.type==="String"||n.type==="Json"):e.coerceType===void 0||e.coerceType==="String"||e.coerceType==="Json"},vs=(e,t,r)=>{if(Jr(Or(e,t,r))==="relations")throw ps(e)},Qr=e=>e!=="scalar"&&e!=="instant"&&e!=="list"&&e!=="enum"&&e!=="relation"&&e!=="relations",xr=(e,t)=>Qr(e)&&Mu(t),Mu=e=>typeof e=="string"||Array.isArray(e)&&e.some(Mu),Ke=(e,t,r)=>{let n=Jr(Or(e.field,t,r));return n==="unknown"&&e.coerceType!==void 0?Lu(e.coerceType):n},Ge=e=>{if(!e.isList){if(e.kind==="enum")return N.Enum;if(!(e.kind!=="scalar"||e.type===N.Json))return ko(e.type)?e.type:void 0}};var _u=new WeakSet,Ns=e=>(_u.add(e),e),Du=e=>{if(e===null||typeof e!="object")return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},Fu=e=>{let t=[],r=(n,o)=>{if(n!==null&&typeof n=="object"&&_u.has(n)){t.push({path:o});return}if(Array.isArray(n))for(let[i,s]of n.entries())r(s,[...o,i]);else if(Du(n))for(let[i,s]of Object.entries(n))r(s,[...o,i]);};return r(e,[]),t},UO=["__step","__field"],As=e=>Array.isArray(e)?e.some(As):Du(e)?Object.entries(e).some(([t,r])=>UO.includes(t)||As(r)):false;var KO={[h.equals]:"equals",[h.notEquals]:"equals",[h.lessThan]:"lt",[h.lessThanEquals]:"lte",[h.greaterThan]:"gt",[h.greaterThanEquals]:"gte"},ju=(e,t,r)=>{let n=ie(e,t,r);if(n.kind!=="direct"||n.hops.length>0)return `'${e}' is not a column of ${r} (a relation hop or an undeclared path)`;let{entry:o}=n;return M(o)?`'${e}' is a relation`:Ue(o)?`'${e}' is a Json column`:o.isList?`'${e}' is a list column`:o},Ps=(e,t,r,n,o=false)=>{let i=e.path;if(o)return {problem:"inside a counting step (a count or relation aggregate) a groupBy carries no column reference"};let s=_(i);if(s&&s.depth>1)return {problem:`'${i}' reads an enclosing scope, which a Prisma filter can't reach`};if(!s&&n)return {problem:`'${i}' reads the root row, which a Prisma relation filter can't reach`};if(!t||!r)return {problem:"comparing two columns needs the map and model"};let a=KO[e.operator];if(!a)return {problem:`'${e.operator}' takes no column reference in Prisma`};if(e.offset!==void 0)return {problem:"an offset is arithmetic, which Prisma lacks"};let l=ju(e.field,t,r);if(typeof l=="string")return {problem:l};let p=s?s.path:i,f=ju(p,t,r);if(typeof f=="string")return {problem:f};if(l.kind!==f.kind||l.type!==f.type)return {problem:`'${e.field}' (${l.type}) and '${p}' (${f.type}) are not the same type`};let d=no(l,f,e.operator);return d?{problem:d}:l.type==="String"&&oe(e.caseInsensitive)?{problem:"a case-insensitive column comparison compiles to ILIKE"}:{key:a,ref:Ns({__field:{model:r,field:p}}),field:l,column:f,columnPath:p}},ks=(e,t)=>new Error(`Path '${e}' compares to a column, which the Prisma rail supports only between columns of the same model and type: ${t}. Use toSql() or check().`),Vu=new WeakSet,Ya=new WeakSet,Zr=(e,t,r=false)=>(Vu.add(e),(r||t!==void 0&&Ya.has(t))&&Ya.add(e),e),Iu=e=>e!==void 0&&Vu.has(e),qu=e=>e!==void 0&&Ya.has(e);var Xa=e=>({field:e,operator:"notExists"}),GO=["filter","orderBy","take","skip"],Bu=(e,t)=>({field:e.field,aggregate:e.aggregate,...Object.fromEntries(["condition",...GO].filter(r=>e[r]!==void 0).map(r=>[r,e[r]])),operator:t}),zO=(e,t)=>{let r=t(e);if(r===null){let i=e.operator??e.dateOperator;return B.includes(i)?"aggregate"in e?Bu(e,"exists"):{field:e.field,operator:"exists"}:true}if("aggregate"in r){let i=E(_o,r.operator);if(i)return {...r,operator:i};let s={...r,operator:E(as,r.operator)};return r.aggregate.mode==="avg"?Nt([s,Bu(r,"notExists")]):s}if(typeof r.dateOperator=="string"){let i=E(Xd,r.dateOperator);return i?{...r,dateOperator:i}:Nt([{...r,dateOperator:E(as,r.dateOperator)},Xa(r.field)])}if(typeof r.arrayOperator=="string"){let i=r.count;switch(r.arrayOperator){case x.any:return {...r,arrayOperator:x.none};case x.none:return {...r,arrayOperator:x.any};case x.all:return {...r,arrayOperator:x.any,condition:Ye(r.condition,t)};case x.empty:return {...r,arrayOperator:x.notEmpty};case x.notEmpty:return {...r,arrayOperator:x.empty};case x.atLeast:return i<=0?false:{...r,arrayOperator:x.atMost,count:i-1};case x.atMost:return {...r,arrayOperator:x.atLeast,count:i+1};case x.exactly:return Nt([...i>0?[{...r,arrayOperator:x.atMost,count:i-1}]:[],{...r,arrayOperator:x.atLeast,count:i+1}])}}let n=E(_o,r.operator);if(n)return {...r,operator:n};let o=typeof r.path=="string"&&r.path!==""?_(r.path)??{depth:1,path:r.path}:null;return Nt([{...r,operator:E(as,r.operator)},Xa(r.field),...o&&o.depth===1?[Xa(o.path)]:[]])},Ye=(e,t=r=>r)=>{if(typeof e=="boolean")return !e;let r=e;if(Array.isArray(r.all))return Nt(r.all.map(n=>Ye(n,t)));if(Array.isArray(r.any))return K(r.any.map(n=>Ye(n,t)));if("if"in r){let n=K([r.if,Ye(r.then,t)]);return r.else===void 0?n:{any:[n,K([Ye(r.if,t),Ye(r.else,t)])]}}return zO(r,t)},Wu=e=>["field","aggregate"].includes(pe(e))&&e.value!==void 0&&$e(e,e.value)?null:e;var Uu,Ku=e=>{Uu=e;},de=(e,t,r)=>Uu(e,t,r);var HO=e=>{let t=_(e);throw t&&t.depth>1?new Error(Ao(e,"toPrisma")):new Error(`Path '${e}' compares to a column, which isn't supported on the Prisma rail; use toSql() or check().`)},at=e=>Vo(e,{value:t=>{if(As(t))throw new Error("toPrisma: a value holding a '__step' or '__field' key is reserved for the plan's own references");return t},path:t=>HO(t),bind:(t,r)=>gs(t,r,"toPrisma")}),Ho=e=>at(e),oo=e=>Zt({now:e?.now,timeZone:e?.timeZone,weekStart:e?.weekStart},Ho),io=e=>t=>{let r=typeof t.operator=="string"||typeof t.dateOperator=="string",n=t.value!==void 0||typeof t.path=="string"&&t.path!==""||typeof t.bind=="string";if(!r||!n||typeof t.operator=="string"&&typeof t.path=="string"&&t.path!=="")return t;let o=Ke({field:String(t.field)},e?.map,e?.model);if(!("aggregate"in t)&&(o==="json"||o==="json-path")&&typeof t.operator=="string"&&jn.includes(t.operator))throw I("toPrisma",`The complement of '${t.operator}' on the Json value '${t.field}'`,"it keeps values of other types");let i=at(t),s=t.offset===void 0?void 0:at(t.offset);if(t.offset!==void 0&&s==null)return null;let{path:a,bind:l,bindOptional:p,...f}=t,d={...f,value:i,...t.offset!==void 0&&{offset:{value:s}}};return typeof t.dateOperator=="string"?i==null||$e({operator:t.dateOperator},i)?null:d:Wu(d)};var Xe=()=>({}),Yr=Xe,lt=()=>({OR:[]}),el=e=>Object.keys(e).length===0,Gu=e=>{let t=Object.keys(e);return t.length===1&&t[0]==="OR"&&Array.isArray(e.OR)&&e.OR.length===0},we=e=>{if(e.some(Gu))return lt();let t=e.filter(r=>!el(r));return t.length===0?Xe():t.length===1?t[0]:{AND:t}},U=e=>{if(e.some(el))return Xe();let t=e.filter(r=>!Gu(r));return t.length===0?lt():t.length===1?t[0]:{OR:t}},_e=e=>el(e)?e:{NOT:e},zu=(e,t,r)=>we(e.all.map(n=>de(n,t,r))),Hu=(e,t,r)=>U(e.any.map(n=>de(n,t,r))),Ju=(e,t,r)=>{if(Ct(e,t?.map,t?.model))return Yr();let n=de(Ye(e.if,io(t)),t,r),o=de(e.then,t,r),i=U([n,o]);if(e.else!==void 0){let s=de(e.if,t,r),a=de(e.else,t,r);return we([i,U([s,a])])}return i};var JO=(e,t,r,n)=>{let o=C(e,t);if(!o)return null;for(let i of Object.values(o.fields))if(i.kind==="object"&&i.type===r&&(i.fromFields?.length??0)>0&&(i.toFields?.length??0)>0&&(n===void 0||i.relationName===n))return i;return null},$r=(e,t,r)=>{if(r.fromFields?.length)return r.fromFields.map((o,i)=>({here:o,there:r.toFields?.[i]??"id"}));let n=JO(e,r.type,t,r.relationName);return n?.fromFields?.length?n.fromFields.map((o,i)=>({here:n.toFields?.[i]??"id",there:o})):null},Ts=(e,t,r,n)=>{if(n.relationName===void 0)return null;let o=Object.entries(C(e,n.type)?.fields??{}).filter(([i,s])=>s.kind==="object"&&s.type===t&&s.relationName===n.relationName&&!(n.type===t&&i===r));return o.length===1?{field:o[0][0],entry:o[0][1]}:null};var Xr=(e,t)=>{let r=e.split("."),n=t;for(let o=r.length-1;o>=0;o--)n={[r[o]]:n};return n};var so=(e,t,r,n)=>{let o=e.split("."),i=ie(e,t,r);if(i.kind==="bridge")throw new Error(`'${e}' crosses a bridge: ${n.toLowerCase()} aren't supported across a bridge \u2014 no one database holds both sides.`);if(i.kind!=="direct"||i.entry.kind!=="object"){let l=i.hops.at(-1)?.entry.type??r;throw new Error(`Field '${o[i.hops.length]}' is not a relation in model '${l}'. ${n} require a relation field.`)}let s=i.hops.find(l=>l.entry.isList);if(s)throw new Error(`Intermediate field '${s.field}' in path '${e}' is a list relation. Only the final segment can be a list relation for ${n.toLowerCase()}.`);if(!i.entry.isList)throw new Error(`Field '${i.column}' is not a list relation in model '${i.model}'. ${n} only apply to one-to-many or many-to-many relations.`);let a=$r(t,i.model,i.entry);if(!a){let l=Object.values(C(t,i.entry.type)?.fields??{}).some(p=>p.kind==="object"&&p.type===i.model&&p.isList&&!p.fromFields?.length);throw new Error(l?`'${i.model}.${i.column}' is an implicit many-to-many relation. ${n} require an explicit join model with a FK \u2014 convert to an explicit @relation or use prisma.$queryRaw.`:`Cannot determine FK relationship between '${i.model}' and '${i.entry.type}'. Ensure the FieldMap contains both sides of the relation.`)}if(a.length>1)throw new Error(`${n} do not support composite FK relations ('${i.model}.${i.column}'). Use prisma.$queryRaw.`);return {through:i.hops.map(l=>l.field).join("."),target:i.entry.type,parentKey:a[0].here,targetKey:a[0].there}},Jo=(e,t,r,n,o)=>{let i={operation:"groupBy",model:t.target,args:{by:[t.targetKey],where:r,...n&&{having:n}},extract:t.targetKey},s=Ns({__step:e.steps.length});e.steps.push(i);let a={[t.parentKey]:{in:s}},l=o?_e(a):a;return t.through?Xr(t.through,l):l};var et=e=>({ok:e.length===0,errors:e}),tn=(e,t)=>{if(!e.ok)throw new Error(`${t}:
1
+ import Pt from'dayjs';import sO from'dayjs/plugin/isoWeek.js';import aO from'dayjs/plugin/quarterOfYear.js';import lO from'dayjs/plugin/timezone.js';import pO from'dayjs/plugin/utc.js';import EO from'dayjs/plugin/isSameOrAfter.js';import xO from'dayjs/plugin/isSameOrBefore.js';import {distance}from'fastest-levenshtein';import {RE2JS}from're2js';var Aa=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var kg=/^(\$+)\.(.*)$/,L=e=>{let t=kg.exec(e);return t?{depth:t[1].length,path:t[2]}:null},Na=(e,t,r)=>`Scope ref '${e}' needs depth ${t} but only ${r} ${r===1?"scope is":"scopes are"} in reach`,He=(e,t)=>{let r=L(e);return r?r.depth>t.length?{outOfBounds:Na(e,r.depth,t.length)}:{scope:t[t.length-r.depth],path:r.path}:{scope:t[t.length-1],path:e}},Tg=/\[(\d+)\]|\[(["'])(.*?)\2\]|([^.[\]]+)/g,Cg=e=>e===""?[""]:[...e.matchAll(Tg)].map(t=>t[1]??t[3]??t[4]),Lg=(e,t)=>{if(e==null)return;let r=Object(e);return Object.hasOwn(r,t)?r[t]:void 0},he=(e,t)=>Cg(t).reduce(Lg,e),ir=(e,t)=>{let r=He(e,t);if("outOfBounds"in r)throw new Error(r.outOfBounds);return he(r.scope,r.path)},$o=(e,t)=>L(e)?ir(e,t):he(t[0],e),vo=(e,t)=>`Scope ref '${e}' is not supported by ${t}(); evaluate with check()`,wi=(e,t)=>{if(!(!("field"in e)||typeof e.field!="string")&&L(e.field))throw new Error(vo(e.field,t))};var Mg=typeof global=="object"&&global&&global.Object===Object&&global,Si=Mg;var _g=typeof self=="object"&&self&&self.Object===Object&&self,Dg=Si||_g||Function("return this")(),pe=Dg;var Fg=pe.Symbol,Ae=Fg;var ap=Object.prototype,jg=ap.hasOwnProperty,Vg=ap.toString,Ao=Ae?Ae.toStringTag:void 0;function Ig(e){var t=jg.call(e,Ao),r=e[Ao];try{e[Ao]=void 0;var n=!0;}catch{}var o=Vg.call(e);return n&&(t?e[Ao]=r:delete e[Ao]),o}var lp=Ig;var qg=Object.prototype,Bg=qg.toString;function Wg(e){return Bg.call(e)}var pp=Wg;var Ug="[object Null]",Kg="[object Undefined]",dp=Ae?Ae.toStringTag:void 0;function Gg(e){return e==null?e===void 0?Kg:Ug:dp&&dp in Object(e)?lp(e):pp(e)}var qe=Gg;function zg(e){return e!=null&&typeof e=="object"}var fe=zg;var Hg="[object Symbol]";function Jg(e){return typeof e=="symbol"||fe(e)&&qe(e)==Hg}var dn=Jg;function Qg(e,t){for(var r=-1,n=e==null?0:e.length,o=Array(n);++r<n;)o[r]=t(e[r],r,e);return o}var fp=Qg;var Zg=Array.isArray,z=Zg;var up=Ae?Ae.prototype:void 0,cp=up?up.toString:void 0;function mp(e){if(typeof e=="string")return e;if(z(e))return fp(e,mp)+"";if(dn(e))return cp?cp.call(e):"";var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var gp=mp;function Xg(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var X=Xg;function ey(e){return e}var fn=ey;var ty="[object AsyncFunction]",ry="[object Function]",ny="[object GeneratorFunction]",oy="[object Proxy]";function iy(e){if(!X(e))return false;var t=qe(e);return t==ry||t==ny||t==ty||t==oy}var un=iy;var sy=pe["__core-js_shared__"],bi=sy;var yp=(function(){var e=/[^.]+$/.exec(bi&&bi.keys&&bi.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function ay(e){return !!yp&&yp in e}var hp=ay;var ly=Function.prototype,py=ly.toString;function dy(e){if(e!=null){try{return py.call(e)}catch{}try{return e+""}catch{}}return ""}var Vt=dy;var fy=/[\\^$.*+?()[\]{}|]/g,uy=/^\[object .+?Constructor\]$/,cy=Function.prototype,my=Object.prototype,gy=cy.toString,yy=my.hasOwnProperty,hy=RegExp("^"+gy.call(yy).replace(fy,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function wy(e){if(!X(e)||hp(e))return false;var t=un(e)?hy:uy;return t.test(Vt(e))}var wp=wy;function Sy(e,t){return e?.[t]}var Sp=Sy;function by(e,t){var r=Sp(e,t);return wp(r)?r:void 0}var Me=by;var Ry=Me(pe,"WeakMap"),Ri=Ry;var bp=Object.create,Oy=(function(){function e(){}return function(t){if(!X(t))return {};if(bp)return bp(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})(),Rp=Oy;function Ey(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var Op=Ey;function xy(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}var Oi=xy;var $y=800,vy=16,Ay=Date.now;function Ny(e){var t=0,r=0;return function(){var n=Ay(),o=vy-(n-r);if(r=n,o>0){if(++t>=$y)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var Ep=Ny;function Py(e){return function(){return e}}var xp=Py;var ky=(function(){try{var e=Me(Object,"defineProperty");return e({},"",{}),e}catch{}})(),cn=ky;var Ty=cn?function(e,t){return cn(e,"toString",{configurable:true,enumerable:false,value:xp(t),writable:true})}:fn,$p=Ty;var Cy=Ep($p),vp=Cy;function Ly(e,t){for(var r=-1,n=e==null?0:e.length;++r<n&&t(e[r],r,e)!==false;);return e}var Ap=Ly;var My=9007199254740991,_y=/^(?:0|[1-9]\d*)$/;function Dy(e,t){var r=typeof e;return t=t??My,!!t&&(r=="number"||r!="symbol"&&_y.test(e))&&e>-1&&e%1==0&&e<t}var sr=Dy;function Fy(e,t,r){t=="__proto__"&&cn?cn(e,t,{configurable:true,enumerable:true,value:r,writable:true}):e[t]=r;}var mn=Fy;function jy(e,t){return e===t||e!==e&&t!==t}var yt=jy;var Vy=Object.prototype,Iy=Vy.hasOwnProperty;function qy(e,t,r){var n=e[t];(!(Iy.call(e,t)&&yt(n,r))||r===void 0&&!(t in e))&&mn(e,t,r);}var gn=qy;function By(e,t,r,n){var o=!r;r||(r={});for(var i=-1,s=t.length;++i<s;){var a=t[i],l=n?n(r[a],e[a],a,r,e):void 0;l===void 0&&(l=e[a]),o?mn(r,a,l):gn(r,a,l);}return r}var ht=By;var Np=Math.max;function Wy(e,t,r){return t=Np(t===void 0?e.length-1:t,0),function(){for(var n=arguments,o=-1,i=Np(n.length-t,0),s=Array(i);++o<i;)s[o]=n[t+o];o=-1;for(var a=Array(t+1);++o<t;)a[o]=n[o];return a[t]=r(s),Op(e,this,a)}}var Pp=Wy;function Uy(e,t){return vp(Pp(e,t,fn),e+"")}var kp=Uy;var Ky=9007199254740991;function Gy(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Ky}var yn=Gy;function zy(e){return e!=null&&yn(e.length)&&!un(e)}var wt=zy;function Hy(e,t,r){if(!X(r))return false;var n=typeof t;return (n=="number"?wt(r)&&sr(t,r.length):n=="string"&&t in r)?yt(r[t],e):false}var Ei=Hy;function Jy(e){return kp(function(t,r){var n=-1,o=r.length,i=o>1?r[o-1]:void 0,s=o>2?r[2]:void 0;for(i=e.length>3&&typeof i=="function"?(o--,i):void 0,s&&Ei(r[0],r[1],s)&&(i=o<3?void 0:i,o=1),t=Object(t);++n<o;){var a=r[n];a&&e(t,a,n,i);}return t})}var Tp=Jy;var Qy=Object.prototype;function Zy(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||Qy;return e===r}var hn=Zy;function Yy(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}var Cp=Yy;var Xy="[object Arguments]";function eh(e){return fe(e)&&qe(e)==Xy}var Pa=eh;var Lp=Object.prototype,th=Lp.hasOwnProperty,rh=Lp.propertyIsEnumerable,nh=Pa((function(){return arguments})())?Pa:function(e){return fe(e)&&th.call(e,"callee")&&!rh.call(e,"callee")},Dr=nh;function oh(){return false}var Mp=oh;var Fp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,_p=Fp&&typeof module=="object"&&module&&!module.nodeType&&module,ih=_p&&_p.exports===Fp,Dp=ih?pe.Buffer:void 0,sh=Dp?Dp.isBuffer:void 0,ah=sh||Mp,It=ah;var lh="[object Arguments]",ph="[object Array]",dh="[object Boolean]",fh="[object Date]",uh="[object Error]",ch="[object Function]",mh="[object Map]",gh="[object Number]",yh="[object Object]",hh="[object RegExp]",wh="[object Set]",Sh="[object String]",bh="[object WeakMap]",Rh="[object ArrayBuffer]",Oh="[object DataView]",Eh="[object Float32Array]",xh="[object Float64Array]",$h="[object Int8Array]",vh="[object Int16Array]",Ah="[object Int32Array]",Nh="[object Uint8Array]",Ph="[object Uint8ClampedArray]",kh="[object Uint16Array]",Th="[object Uint32Array]",Q={};Q[Eh]=Q[xh]=Q[$h]=Q[vh]=Q[Ah]=Q[Nh]=Q[Ph]=Q[kh]=Q[Th]=true;Q[lh]=Q[ph]=Q[Rh]=Q[dh]=Q[Oh]=Q[fh]=Q[uh]=Q[ch]=Q[mh]=Q[gh]=Q[yh]=Q[hh]=Q[wh]=Q[Sh]=Q[bh]=false;function Ch(e){return fe(e)&&yn(e.length)&&!!Q[qe(e)]}var jp=Ch;function Lh(e){return function(t){return e(t)}}var wn=Lh;var Vp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,No=Vp&&typeof module=="object"&&module&&!module.nodeType&&module,Mh=No&&No.exports===Vp,ka=Mh&&Si.process,_h=(function(){try{var e=No&&No.require&&No.require("util").types;return e||ka&&ka.binding&&ka.binding("util")}catch{}})(),qt=_h;var Ip=qt&&qt.isTypedArray,Dh=Ip?wn(Ip):jp,Sn=Dh;var Fh=Object.prototype,jh=Fh.hasOwnProperty;function Vh(e,t){var r=z(e),n=!r&&Dr(e),o=!r&&!n&&It(e),i=!r&&!n&&!o&&Sn(e),s=r||n||o||i,a=s?Cp(e.length,String):[],l=a.length;for(var p in e)(t||jh.call(e,p))&&!(s&&(p=="length"||o&&(p=="offset"||p=="parent")||i&&(p=="buffer"||p=="byteLength"||p=="byteOffset")||sr(p,l)))&&a.push(p);return a}var xi=Vh;function Ih(e,t){return function(r){return e(t(r))}}var $i=Ih;var qh=$i(Object.keys,Object),qp=qh;var Bh=Object.prototype,Wh=Bh.hasOwnProperty;function Uh(e){if(!hn(e))return qp(e);var t=[];for(var r in Object(e))Wh.call(e,r)&&r!="constructor"&&t.push(r);return t}var Bp=Uh;function Kh(e){return wt(e)?xi(e):Bp(e)}var St=Kh;function Gh(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}var Wp=Gh;var zh=Object.prototype,Hh=zh.hasOwnProperty;function Jh(e){if(!X(e))return Wp(e);var t=hn(e),r=[];for(var n in e)n=="constructor"&&(t||!Hh.call(e,n))||r.push(n);return r}var Up=Jh;function Qh(e){return wt(e)?xi(e,true):Up(e)}var bt=Qh;var Zh=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Yh=/^\w*$/;function Xh(e,t){if(z(e))return false;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||dn(e)?true:Yh.test(e)||!Zh.test(e)||t!=null&&e in Object(t)}var bn=Xh;var ew=Me(Object,"create"),Bt=ew;function tw(){this.__data__=Bt?Bt(null):{},this.size=0;}var Kp=tw;function rw(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Gp=rw;var nw="__lodash_hash_undefined__",ow=Object.prototype,iw=ow.hasOwnProperty;function sw(e){var t=this.__data__;if(Bt){var r=t[e];return r===nw?void 0:r}return iw.call(t,e)?t[e]:void 0}var zp=sw;var aw=Object.prototype,lw=aw.hasOwnProperty;function pw(e){var t=this.__data__;return Bt?t[e]!==void 0:lw.call(t,e)}var Hp=pw;var dw="__lodash_hash_undefined__";function fw(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Bt&&t===void 0?dw:t,this}var Jp=fw;function Rn(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1]);}}Rn.prototype.clear=Kp;Rn.prototype.delete=Gp;Rn.prototype.get=zp;Rn.prototype.has=Hp;Rn.prototype.set=Jp;var Ta=Rn;function uw(){this.__data__=[],this.size=0;}var Qp=uw;function cw(e,t){for(var r=e.length;r--;)if(yt(e[r][0],t))return r;return -1}var ar=cw;var mw=Array.prototype,gw=mw.splice;function yw(e){var t=this.__data__,r=ar(t,e);if(r<0)return false;var n=t.length-1;return r==n?t.pop():gw.call(t,r,1),--this.size,true}var Zp=yw;function hw(e){var t=this.__data__,r=ar(t,e);return r<0?void 0:t[r][1]}var Yp=hw;function ww(e){return ar(this.__data__,e)>-1}var Xp=ww;function Sw(e,t){var r=this.__data__,n=ar(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var ed=Sw;function On(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1]);}}On.prototype.clear=Qp;On.prototype.delete=Zp;On.prototype.get=Yp;On.prototype.has=Xp;On.prototype.set=ed;var lr=On;var bw=Me(pe,"Map"),pr=bw;function Rw(){this.size=0,this.__data__={hash:new Ta,map:new(pr||lr),string:new Ta};}var td=Rw;function Ow(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var rd=Ow;function Ew(e,t){var r=e.__data__;return rd(t)?r[typeof t=="string"?"string":"hash"]:r.map}var dr=Ew;function xw(e){var t=dr(this,e).delete(e);return this.size-=t?1:0,t}var nd=xw;function $w(e){return dr(this,e).get(e)}var od=$w;function vw(e){return dr(this,e).has(e)}var id=vw;function Aw(e,t){var r=dr(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var sd=Aw;function En(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1]);}}En.prototype.clear=td;En.prototype.delete=nd;En.prototype.get=od;En.prototype.has=id;En.prototype.set=sd;var Fr=En;var Nw="Expected a function";function Ca(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(Nw);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],i=r.cache;if(i.has(o))return i.get(o);var s=e.apply(this,n);return r.cache=i.set(o,s)||i,s};return r.cache=new(Ca.Cache||Fr),r}Ca.Cache=Fr;var ad=Ca;var Pw=500;function kw(e){var t=ad(e,function(n){return r.size===Pw&&r.clear(),n}),r=t.cache;return t}var ld=kw;var Tw=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Cw=/\\(\\)?/g,Lw=ld(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(Tw,function(r,n,o,i){t.push(o?i.replace(Cw,"$1"):n||r);}),t}),pd=Lw;function Mw(e){return e==null?"":gp(e)}var dd=Mw;function _w(e,t){return z(e)?e:bn(e,t)?[e]:pd(dd(e))}var xn=_w;function Fw(e){if(typeof e=="string"||dn(e))return e;var t=e+"";return t=="0"&&1/e==-Infinity?"-0":t}var Rt=Fw;function jw(e,t){t=xn(t,e);for(var r=0,n=t.length;e!=null&&r<n;)e=e[Rt(t[r++])];return r&&r==n?e:void 0}var vi=jw;function Vw(e,t,r){var n=e==null?void 0:vi(e,t);return n===void 0?r:n}var fd=Vw;function Iw(e,t){for(var r=-1,n=t.length,o=e.length;++r<n;)e[o+r]=t[r];return e}var Ai=Iw;var qw=$i(Object.getPrototypeOf,Object),$n=qw;var Bw="[object Object]",Ww=Function.prototype,Uw=Object.prototype,ud=Ww.toString,Kw=Uw.hasOwnProperty,Gw=ud.call(Object);function zw(e){if(!fe(e)||qe(e)!=Bw)return false;var t=$n(e);if(t===null)return true;var r=Kw.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&ud.call(r)==Gw}var re=zw;function Hw(){if(!arguments.length)return [];var e=arguments[0];return z(e)?e:[e]}var Ni=Hw;function Jw(){this.__data__=new lr,this.size=0;}var cd=Jw;function Qw(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var md=Qw;function Zw(e){return this.__data__.get(e)}var gd=Zw;function Yw(e){return this.__data__.has(e)}var yd=Yw;var Xw=200;function eS(e,t){var r=this.__data__;if(r instanceof lr){var n=r.__data__;if(!pr||n.length<Xw-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new Fr(n);}return r.set(e,t),this.size=r.size,this}var hd=eS;function vn(e){var t=this.__data__=new lr(e);this.size=t.size;}vn.prototype.clear=cd;vn.prototype.delete=md;vn.prototype.get=gd;vn.prototype.has=yd;vn.prototype.set=hd;var Ot=vn;function tS(e,t){return e&&ht(t,St(t),e)}var wd=tS;function rS(e,t){return e&&ht(t,bt(t),e)}var Sd=rS;var Ed=typeof exports=="object"&&exports&&!exports.nodeType&&exports,bd=Ed&&typeof module=="object"&&module&&!module.nodeType&&module,nS=bd&&bd.exports===Ed,Rd=nS?pe.Buffer:void 0,Od=Rd?Rd.allocUnsafe:void 0;function oS(e,t){if(t)return e.slice();var r=e.length,n=Od?Od(r):new e.constructor(r);return e.copy(n),n}var Pi=oS;function iS(e,t){for(var r=-1,n=e==null?0:e.length,o=0,i=[];++r<n;){var s=e[r];t(s,r,e)&&(i[o++]=s);}return i}var xd=iS;function sS(){return []}var ki=sS;var aS=Object.prototype,lS=aS.propertyIsEnumerable,$d=Object.getOwnPropertySymbols,pS=$d?function(e){return e==null?[]:(e=Object(e),xd($d(e),function(t){return lS.call(e,t)}))}:ki,An=pS;function dS(e,t){return ht(e,An(e),t)}var vd=dS;var fS=Object.getOwnPropertySymbols,uS=fS?function(e){for(var t=[];e;)Ai(t,An(e)),e=$n(e);return t}:ki,Ti=uS;function cS(e,t){return ht(e,Ti(e),t)}var Ad=cS;function mS(e,t,r){var n=t(e);return z(e)?n:Ai(n,r(e))}var Ci=mS;function gS(e){return Ci(e,St,An)}var Po=gS;function yS(e){return Ci(e,bt,Ti)}var Nd=yS;var hS=Me(pe,"DataView"),Li=hS;var wS=Me(pe,"Promise"),Mi=wS;var SS=Me(pe,"Set"),_i=SS;var Pd="[object Map]",bS="[object Object]",kd="[object Promise]",Td="[object Set]",Cd="[object WeakMap]",Ld="[object DataView]",RS=Vt(Li),OS=Vt(pr),ES=Vt(Mi),xS=Vt(_i),$S=Vt(Ri),jr=qe;(Li&&jr(new Li(new ArrayBuffer(1)))!=Ld||pr&&jr(new pr)!=Pd||Mi&&jr(Mi.resolve())!=kd||_i&&jr(new _i)!=Td||Ri&&jr(new Ri)!=Cd)&&(jr=function(e){var t=qe(e),r=t==bS?e.constructor:void 0,n=r?Vt(r):"";if(n)switch(n){case RS:return Ld;case OS:return Pd;case ES:return kd;case xS:return Td;case $S:return Cd}return t});var Wt=jr;var vS=Object.prototype,AS=vS.hasOwnProperty;function NS(e){var t=e.length,r=new e.constructor(t);return t&&typeof e[0]=="string"&&AS.call(e,"index")&&(r.index=e.index,r.input=e.input),r}var Md=NS;var PS=pe.Uint8Array,Nn=PS;function kS(e){var t=new e.constructor(e.byteLength);return new Nn(t).set(new Nn(e)),t}var Pn=kS;function TS(e,t){var r=t?Pn(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}var _d=TS;var CS=/\w*$/;function LS(e){var t=new e.constructor(e.source,CS.exec(e));return t.lastIndex=e.lastIndex,t}var Dd=LS;var Fd=Ae?Ae.prototype:void 0,jd=Fd?Fd.valueOf:void 0;function MS(e){return jd?Object(jd.call(e)):{}}var Vd=MS;function _S(e,t){var r=t?Pn(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}var Di=_S;var DS="[object Boolean]",FS="[object Date]",jS="[object Map]",VS="[object Number]",IS="[object RegExp]",qS="[object Set]",BS="[object String]",WS="[object Symbol]",US="[object ArrayBuffer]",KS="[object DataView]",GS="[object Float32Array]",zS="[object Float64Array]",HS="[object Int8Array]",JS="[object Int16Array]",QS="[object Int32Array]",ZS="[object Uint8Array]",YS="[object Uint8ClampedArray]",XS="[object Uint16Array]",eb="[object Uint32Array]";function tb(e,t,r){var n=e.constructor;switch(t){case US:return Pn(e);case DS:case FS:return new n(+e);case KS:return _d(e,r);case GS:case zS:case HS:case JS:case QS:case ZS:case YS:case XS:case eb:return Di(e,r);case jS:return new n;case VS:case BS:return new n(e);case IS:return Dd(e);case qS:return new n;case WS:return Vd(e)}}var Id=tb;function rb(e){return typeof e.constructor=="function"&&!hn(e)?Rp($n(e)):{}}var Fi=rb;var nb="[object Map]";function ob(e){return fe(e)&&Wt(e)==nb}var qd=ob;var Bd=qt&&qt.isMap,ib=Bd?wn(Bd):qd,Wd=ib;var sb="[object Set]";function ab(e){return fe(e)&&Wt(e)==sb}var Ud=ab;var Kd=qt&&qt.isSet,lb=Kd?wn(Kd):Ud,Gd=lb;var pb=1,db=2,fb=4,zd="[object Arguments]",ub="[object Array]",cb="[object Boolean]",mb="[object Date]",gb="[object Error]",Hd="[object Function]",yb="[object GeneratorFunction]",hb="[object Map]",wb="[object Number]",Jd="[object Object]",Sb="[object RegExp]",bb="[object Set]",Rb="[object String]",Ob="[object Symbol]",Eb="[object WeakMap]",xb="[object ArrayBuffer]",$b="[object DataView]",vb="[object Float32Array]",Ab="[object Float64Array]",Nb="[object Int8Array]",Pb="[object Int16Array]",kb="[object Int32Array]",Tb="[object Uint8Array]",Cb="[object Uint8ClampedArray]",Lb="[object Uint16Array]",Mb="[object Uint32Array]",H={};H[zd]=H[ub]=H[xb]=H[$b]=H[cb]=H[mb]=H[vb]=H[Ab]=H[Nb]=H[Pb]=H[kb]=H[hb]=H[wb]=H[Jd]=H[Sb]=H[bb]=H[Rb]=H[Ob]=H[Tb]=H[Cb]=H[Lb]=H[Mb]=true;H[gb]=H[Hd]=H[Eb]=false;function ji(e,t,r,n,o,i){var s,a=t&pb,l=t&db,p=t&fb;if(r&&(s=o?r(e,n,o,i):r(e)),s!==void 0)return s;if(!X(e))return e;var d=z(e);if(d){if(s=Md(e),!a)return Oi(e,s)}else {var f=Wt(e),u=f==Hd||f==yb;if(It(e))return Pi(e,a);if(f==Jd||f==zd||u&&!o){if(s=l||u?{}:Fi(e),!a)return l?Ad(e,Sd(s,e)):vd(e,wd(s,e))}else {if(!H[f])return o?e:{};s=Id(e,f,a);}}i||(i=new Ot);var c=i.get(e);if(c)return c;i.set(e,s),Gd(e)?e.forEach(function(g){s.add(ji(g,t,r,g,e,i));}):Wd(e)&&e.forEach(function(g,S){s.set(S,ji(g,t,r,S,e,i));});var y=p?l?Nd:Po:l?bt:St,m=d?void 0:y(e);return Ap(m||e,function(g,S){m&&(S=g,g=e[S]),gn(s,S,ji(g,t,r,S,e,i));}),s}var Vi=ji;var _b=1,Db=4;function Fb(e){return Vi(e,_b|Db)}var Ii=Fb;var jb=1,Vb=4;function Ib(e,t){return t=typeof t=="function"?t:void 0,Vi(e,jb|Vb,t)}var La=Ib;var qb="__lodash_hash_undefined__";function Bb(e){return this.__data__.set(e,qb),this}var Qd=Bb;function Wb(e){return this.__data__.has(e)}var Zd=Wb;function qi(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Fr;++t<r;)this.add(e[t]);}qi.prototype.add=qi.prototype.push=Qd;qi.prototype.has=Zd;var Yd=qi;function Ub(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return true;return false}var Bi=Ub;function Kb(e,t){return e.has(t)}var Xd=Kb;var Gb=1,zb=2;function Hb(e,t,r,n,o,i){var s=r&Gb,a=e.length,l=t.length;if(a!=l&&!(s&&l>a))return false;var p=i.get(e),d=i.get(t);if(p&&d)return p==t&&d==e;var f=-1,u=true,c=r&zb?new Yd:void 0;for(i.set(e,t),i.set(t,e);++f<a;){var y=e[f],m=t[f];if(n)var g=s?n(m,y,f,t,e,i):n(y,m,f,e,t,i);if(g!==void 0){if(g)continue;u=false;break}if(c){if(!Bi(t,function(S,b){if(!Xd(c,b)&&(y===S||o(y,S,r,n,i)))return c.push(b)})){u=false;break}}else if(!(y===m||o(y,m,r,n,i))){u=false;break}}return i.delete(e),i.delete(t),u}var Wi=Hb;function Jb(e){var t=-1,r=Array(e.size);return e.forEach(function(n,o){r[++t]=[o,n];}),r}var ef=Jb;function Qb(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n;}),r}var tf=Qb;var Zb=1,Yb=2,Xb="[object Boolean]",eR="[object Date]",tR="[object Error]",rR="[object Map]",nR="[object Number]",oR="[object RegExp]",iR="[object Set]",sR="[object String]",aR="[object Symbol]",lR="[object ArrayBuffer]",pR="[object DataView]",rf=Ae?Ae.prototype:void 0,Ma=rf?rf.valueOf:void 0;function dR(e,t,r,n,o,i,s){switch(r){case pR:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return false;e=e.buffer,t=t.buffer;case lR:return !(e.byteLength!=t.byteLength||!i(new Nn(e),new Nn(t)));case Xb:case eR:case nR:return yt(+e,+t);case tR:return e.name==t.name&&e.message==t.message;case oR:case sR:return e==t+"";case rR:var a=ef;case iR:var l=n&Zb;if(a||(a=tf),e.size!=t.size&&!l)return false;var p=s.get(e);if(p)return p==t;n|=Yb,s.set(e,t);var d=Wi(a(e),a(t),n,o,i,s);return s.delete(e),d;case aR:if(Ma)return Ma.call(e)==Ma.call(t)}return false}var nf=dR;var fR=1,uR=Object.prototype,cR=uR.hasOwnProperty;function mR(e,t,r,n,o,i){var s=r&fR,a=Po(e),l=a.length,p=Po(t),d=p.length;if(l!=d&&!s)return false;for(var f=l;f--;){var u=a[f];if(!(s?u in t:cR.call(t,u)))return false}var c=i.get(e),y=i.get(t);if(c&&y)return c==t&&y==e;var m=true;i.set(e,t),i.set(t,e);for(var g=s;++f<l;){u=a[f];var S=e[u],b=t[u];if(n)var w=s?n(b,S,u,t,e,i):n(S,b,u,e,t,i);if(!(w===void 0?S===b||o(S,b,r,n,i):w)){m=false;break}g||(g=u=="constructor");}if(m&&!g){var R=e.constructor,O=t.constructor;R!=O&&"constructor"in e&&"constructor"in t&&!(typeof R=="function"&&R instanceof R&&typeof O=="function"&&O instanceof O)&&(m=false);}return i.delete(e),i.delete(t),m}var of=mR;var gR=1,sf="[object Arguments]",af="[object Array]",Ui="[object Object]",yR=Object.prototype,lf=yR.hasOwnProperty;function hR(e,t,r,n,o,i){var s=z(e),a=z(t),l=s?af:Wt(e),p=a?af:Wt(t);l=l==sf?Ui:l,p=p==sf?Ui:p;var d=l==Ui,f=p==Ui,u=l==p;if(u&&It(e)){if(!It(t))return false;s=true,d=false;}if(u&&!d)return i||(i=new Ot),s||Sn(e)?Wi(e,t,r,n,o,i):nf(e,t,l,r,n,o,i);if(!(r&gR)){var c=d&&lf.call(e,"__wrapped__"),y=f&&lf.call(t,"__wrapped__");if(c||y){var m=c?e.value():e,g=y?t.value():t;return i||(i=new Ot),o(m,g,r,n,i)}}return u?(i||(i=new Ot),of(e,t,r,n,o,i)):false}var pf=hR;function df(e,t,r,n,o){return e===t?true:e==null||t==null||!fe(e)&&!fe(t)?e!==e&&t!==t:pf(e,t,r,n,df,o)}var kn=df;var wR=1,SR=2;function bR(e,t,r,n){var o=r.length,i=o,s=!n;if(e==null)return !i;for(e=Object(e);o--;){var a=r[o];if(s&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return false}for(;++o<i;){a=r[o];var l=a[0],p=e[l],d=a[1];if(s&&a[2]){if(p===void 0&&!(l in e))return false}else {var f=new Ot;if(n)var u=n(p,d,l,e,t,f);if(!(u===void 0?kn(d,p,wR|SR,n,f):u))return false}}return true}var ff=bR;function RR(e){return e===e&&!X(e)}var Ki=RR;function OR(e){for(var t=St(e),r=t.length;r--;){var n=t[r],o=e[n];t[r]=[n,o,Ki(o)];}return t}var uf=OR;function ER(e,t){return function(r){return r==null?false:r[e]===t&&(t!==void 0||e in Object(r))}}var Gi=ER;function xR(e){var t=uf(e);return t.length==1&&t[0][2]?Gi(t[0][0],t[0][1]):function(r){return r===e||ff(r,e,t)}}var cf=xR;function $R(e,t){return e!=null&&t in Object(e)}var mf=$R;function vR(e,t,r){t=xn(t,e);for(var n=-1,o=t.length,i=false;++n<o;){var s=Rt(t[n]);if(!(i=e!=null&&r(e,s)))break;e=e[s];}return i||++n!=o?i:(o=e==null?0:e.length,!!o&&yn(o)&&sr(s,o)&&(z(e)||Dr(e)))}var gf=vR;function AR(e,t){return e!=null&&gf(e,t,mf)}var yf=AR;var NR=1,PR=2;function kR(e,t){return bn(e)&&Ki(t)?Gi(Rt(e),t):function(r){var n=fd(r,e);return n===void 0&&n===t?yf(r,e):kn(t,n,NR|PR)}}var hf=kR;function TR(e){return function(t){return t?.[e]}}var wf=TR;function CR(e){return function(t){return vi(t,e)}}var Sf=CR;function LR(e){return bn(e)?wf(Rt(e)):Sf(e)}var bf=LR;function MR(e){return typeof e=="function"?e:e==null?fn:typeof e=="object"?z(e)?hf(e[0],e[1]):cf(e):bf(e)}var Rf=MR;function _R(e){return function(t,r,n){for(var o=-1,i=Object(t),s=n(t),a=s.length;a--;){var l=s[e?a:++o];if(r(i[l],l,i)===false)break}return t}}var Of=_R;var DR=Of(),zi=DR;function FR(e,t){return e&&zi(e,t,St)}var Ef=FR;function jR(e,t){return function(r,n){if(r==null)return r;if(!wt(r))return e(r,n);for(var o=r.length,i=t?o:-1,s=Object(r);(t?i--:++i<o)&&n(s[i],i,s)!==false;);return r}}var xf=jR;var VR=xf(Ef),$f=VR;function IR(e,t,r){(r!==void 0&&!yt(e[t],r)||r===void 0&&!(t in e))&&mn(e,t,r);}var ko=IR;function qR(e){return fe(e)&&wt(e)}var vf=qR;function BR(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}var To=BR;function WR(e){return ht(e,bt(e))}var Af=WR;function UR(e,t,r,n,o,i,s){var a=To(e,r),l=To(t,r),p=s.get(l);if(p){ko(e,r,p);return}var d=i?i(a,l,r+"",e,t,s):void 0,f=d===void 0;if(f){var u=z(l),c=!u&&It(l),y=!u&&!c&&Sn(l);d=l,u||c||y?z(a)?d=a:vf(a)?d=Oi(a):c?(f=false,d=Pi(l,true)):y?(f=false,d=Di(l,true)):d=[]:re(l)||Dr(l)?(d=a,Dr(a)?d=Af(a):(!X(a)||un(a))&&(d=Fi(l))):f=false;}f&&(s.set(l,d),o(d,l,n,i,s),s.delete(l)),ko(e,r,d);}var Nf=UR;function Pf(e,t,r,n,o){e!==t&&zi(t,function(i,s){if(o||(o=new Ot),X(i))Nf(e,t,s,r,Pf,n,o);else {var a=n?n(To(e,s),i,s+"",e,t,o):void 0;a===void 0&&(a=i),ko(e,s,a);}},bt);}var kf=Pf;function KR(e,t){return kn(e,t)}var Ut=KR;var GR=Tp(function(e,t,r){kf(e,t,r);}),Hi=GR;function zR(e,t,r,n){if(!X(e))return e;t=xn(t,e);for(var o=-1,i=t.length,s=i-1,a=e;a!=null&&++o<i;){var l=Rt(t[o]),p=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(o!=s){var d=a[l];p=n?n(d,l,a):void 0,p===void 0&&(p=X(d)?d:sr(t[o+1])?[]:{});}gn(a,l,p),a=a[l];}return e}var Tf=zR;function HR(e,t,r){return e==null?e:Tf(e,t,r)}var Co=HR;function JR(e,t){var r;return $f(e,function(n,o,i){return r=t(n,o,i),!r}),!!r}var Cf=JR;function QR(e,t,r){var n=z(e)?Bi:Cf;return r&&Ei(e,t,r)&&(t=void 0),n(e,Rf(t))}var _a=QR;var Cn={postgres:"postgres",mysql:"mysql"},Mf=e=>Object.values(Cn).includes(e),Da={string:{caseInsensitive:false,fuzzy:false},prismaOptions:{datasource:{provider:"postgresql"}},sql:{dialect:Cn.postgres},clock:{finestUnit:"second"}},ZR=new Set(Object.keys(Da)),Tn=e=>La(e,t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&!re(t)?t:void 0),Lf=Symbol.for("@inixiative/json-rules/engineGlobals@3"),Lo=()=>{let e=globalThis;return e[Lf]??={store:Ii(Da),registry:new Map},e[Lf]},YR=e=>{let t={};for(let[r,n]of Object.entries(e))r.includes(".")?Co(t,r,Tn(n)):t[r]=Hi(t[r]??{},Tn(n));return t},_f=(e,t,r)=>{for(let[n,o]of Object.entries(r)){let i=`${t}.${n}`;he(e,i)===void 0&&Co(e,i,Tn(o));}},XR=e=>e!=null&&typeof e.then=="function",eO=(e,t)=>{if(!e||e.includes("."))throw new Error(`engine globals namespace "${e}" must be one non-empty segment`);if(ZR.has(e))throw new Error(`engine globals namespace "${e}" belongs to json-rules`);let{store:r,registry:n}=Lo(),o=n.get(e);if(o){if(Ut(o,t))return;throw new Error(`engine globals namespace "${e}" is registered with other defaults`)}n.set(e,Tn(t)),_f(r,e,t);},nt={set:(e,t)=>{Co(Lo().store,e,Tn(t));},get:e=>he(Lo().store,e),reset:()=>{let e=Lo();e.store=Ii(Da);for(let[t,r]of e.registry)_f(e.store,t,r);},with:(e,t)=>{let r=Lo(),n=r.store;r.store=Hi(Tn(n),YR(e));try{let o=t();if(XR(o))throw new Error("engineGlobals.with() callback must be synchronous (it returned a Promise).");return o}finally{r.store=n;}}},tO=new Set(["postgresql","cockroachdb","mongodb"]),Df=e=>tO.has(e),ie=e=>e??nt.get("string.caseInsensitive")??false,Ji=e=>{let t=e??nt.get("string.fuzzy")??false;return t?t===true?{}:t:false};var h={equals:"equals",notEquals:"notEquals",lessThan:"lessThan",lessThanEquals:"lessThanEquals",greaterThan:"greaterThan",greaterThanEquals:"greaterThanEquals",contains:"contains",notContains:"notContains",in:"in",notIn:"notIn",matches:"matches",notMatches:"notMatches",between:"between",notBetween:"notBetween",isEmpty:"isEmpty",notEmpty:"notEmpty",exists:"exists",notExists:"notExists",startsWith:"startsWith",notStartsWith:"notStartsWith",endsWith:"endsWith",notEndsWith:"notEndsWith"},x={all:"all",any:"any",none:"none",atLeast:"atLeast",atMost:"atMost",exactly:"exactly",empty:"empty",notEmpty:"notEmpty"},N={before:"before",after:"after",onOrBefore:"onOrBefore",onOrAfter:"onOrAfter",notBefore:"notBefore",notAfter:"notAfter",within:"within",notWithin:"notWithin",between:"between",notBetween:"notBetween",dayIn:"dayIn",dayNotIn:"dayNotIn"};var A={String:"String",Boolean:"Boolean",Int:"Int",BigInt:"BigInt",Float:"Float",Decimal:"Decimal",DateTime:"DateTime",Json:"Json",Bytes:"Bytes",Enum:"Enum"},G=["Int","Float","Decimal","BigInt"],Ln=["String",...G,"DateTime"],fr=["String"],Qi=["String","Boolean","Int","BigInt","Float","Decimal","DateTime","Enum"],Zi=Object.values(A),Ff=Zi,rO={check:"check",toPrisma:"toPrisma",toSql:"toSql"},jn=e=>typeof e=="string"&&Object.hasOwn(A,e),D=["check","toPrisma","toSql"],Mn=["check","toPrisma"],Yi=["check","toSql"],Gt={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"},_n={[h.equals]:{kinds:Qi,targets:D,valueShape:"scalar"},[h.notEquals]:{negates:h.equals,kinds:Qi,targets:D,valueShape:"scalar"},[h.lessThan]:{kinds:Ln,targets:D,valueShape:"ordered",comparator:"lt"},[h.lessThanEquals]:{kinds:Ln,targets:D,valueShape:"ordered",comparator:"lte"},[h.greaterThan]:{kinds:Ln,targets:D,valueShape:"ordered",comparator:"gt"},[h.greaterThanEquals]:{kinds:Ln,targets:D,valueShape:"ordered",comparator:"gte"},[h.in]:{kinds:Qi,targets:D,valueShape:"array"},[h.notIn]:{negates:h.in,kinds:Qi,targets:D,valueShape:"array"},[h.contains]:{kinds:fr,targets:D,valueShape:"string"},[h.notContains]:{negates:h.contains,kinds:fr,targets:D,valueShape:"string"},[h.startsWith]:{kinds:fr,targets:D,valueShape:"string"},[h.notStartsWith]:{negates:h.startsWith,kinds:fr,targets:D,valueShape:"string"},[h.endsWith]:{kinds:fr,targets:D,valueShape:"string"},[h.notEndsWith]:{negates:h.endsWith,kinds:fr,targets:D,valueShape:"string"},[h.matches]:{kinds:fr,targets:Yi,valueShape:"pattern"},[h.notMatches]:{negates:h.matches,kinds:fr,targets:Yi,valueShape:"pattern"},[h.between]:{kinds:Ln,targets:D,valueShape:"range"},[h.notBetween]:{negates:h.between,kinds:Ln,targets:D,valueShape:"range"},[h.isEmpty]:{kinds:Ff,targets:D,valueShape:"none"},[h.notEmpty]:{kinds:Ff,targets:D,valueShape:"none"},[h.exists]:{kinds:Zi,targets:D,valueShape:"none"},[h.notExists]:{kinds:Zi,targets:D,valueShape:"none"}},Dn={[N.before]:{kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"lt"},[N.after]:{kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"gt"},[N.onOrBefore]:{kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[N.onOrAfter]:{kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[N.notBefore]:{negates:N.before,kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"gte"},[N.notAfter]:{negates:N.after,kinds:["DateTime"],targets:D,valueShape:"dateValue",acceptsExpr:true,comparator:"lte"},[N.within]:{kinds:["DateTime"],targets:D,valueShape:"dateWindow",acceptsExpr:true},[N.notWithin]:{negates:N.within,kinds:["DateTime"],targets:D,valueShape:"dateWindow",acceptsExpr:true},[N.between]:{kinds:["DateTime"],targets:D,valueShape:"dateRange",acceptsExpr:true},[N.notBetween]:{negates:N.between,kinds:["DateTime"],targets:D,valueShape:"dateRange",acceptsExpr:true},[N.dayIn]:{kinds:["DateTime"],targets:Yi,valueShape:"dayList",acceptsExpr:false},[N.dayNotIn]:{negates:N.dayIn,kinds:["DateTime"],targets:Yi,valueShape:"dayList",acceptsExpr:false}},Mo={[x.all]:{targets:Mn,valueShape:"predicate",holdsOnNoRows:true},[x.any]:{targets:Mn,valueShape:"predicate",holdsOnNoRows:false},[x.none]:{targets:Mn,valueShape:"predicate",holdsOnNoRows:true},[x.atLeast]:{targets:Mn,valueShape:"count",comparator:"gte",holdsOnNoRows:true},[x.atMost]:{targets:Mn,valueShape:"count",comparator:"lte",holdsOnNoRows:true},[x.exactly]:{targets:Mn,valueShape:"count",comparator:"equals",holdsOnNoRows:true},[x.empty]:{targets:D,valueShape:"none",holdsOnNoRows:true},[x.notEmpty]:{targets:D,valueShape:"none",holdsOnNoRows:false}},jf={field:_n,date:Dn,array:Mo},Kt=(e,t)=>Object.hasOwn(jf[t],e)?jf[t][e]:void 0,Vn=e=>typeof e.operator=="string"?Kt(e.operator,"field"):typeof e.dateOperator=="string"?Kt(e.dateOperator,"date"):void 0,ur=(e,t)=>Kt(e,t)?.comparator,zt=(e,t)=>{let r=Kt(e,t);if(!r)throw me(e,t);return r.valueShape},Xi=(e,t,r)=>Kt(e,t)?.targets.includes(r)??false,nO=(e,t)=>{let r=Object.keys(_n).filter(o=>{let i=_n[o];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))}),n=Object.keys(Dn).filter(o=>{let i=Dn[o];return !(!i.kinds.includes(e)||t&&!i.targets.includes(t))});return {field:r,date:n}},oO=e=>Object.keys(Mo).filter(t=>e?Mo[t].targets.includes(e):true),Vf=[...Object.entries(_n),...Object.entries(Dn)],Be=(...e)=>Vf.flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),Je=Be("none"),In=Be("ordered"),_o=Be("dateWindow"),Qe=Be("range","dateRange","dateWindow"),If=Be("ordered","string","pattern","array"),Et=[h.contains,h.notContains],Fa=[h.equals,h.notEquals,h.in,h.notIn,h.exists,h.notExists],es=[...Be("scalar","ordered","range"),h.exists,h.notExists],Fn={sum:{result:"number",comparable:true},avg:{result:"number",comparable:true},count:{result:"count",comparable:false},min:{result:"element",comparable:false},max:{result:"element",comparable:false},distinct:{result:"list",comparable:false}},xt=Object.keys(Fn).filter(e=>Fn[e].comparable),ja=Object.keys(Fn),ts=e=>typeof e=="string"&&Object.hasOwn(Fn,e),qf=[...G,"DateTime"],Bf=["String","Enum","DateTime","Boolean",...G],iO=()=>es,_e=Be("scalar"),cr=Be("array"),Wf=Be("scalar","array"),Uf=Be("dayList"),Kf=Be("dateRange"),Gf=Be("scalar","ordered","range","dateValue","dateRange"),zf=(...e)=>Object.entries(Mo).flatMap(([t,r])=>e.includes(r.valueShape)?[t]:[]),Do=zf("count"),Va=e=>typeof e.condition!="object"||e.condition===null?null:e.arrayOperator===x.atLeast&&e.count===1?x.any:(e.arrayOperator===x.atMost||e.arrayOperator===x.exactly)&&e.count===0?x.none:null,Fo=e=>Do.includes(e.arrayOperator)&&Va(e)===null,rs=zf("predicate","count"),Ia=[x.any,x.all,x.none,x.empty,x.notEmpty],Hf=[x.any,x.atLeast],B=[...Object.entries(_n),...Object.entries(Dn)].flatMap(([e,t])=>t.negates?[e]:[]),ns=[...B,h.isEmpty,h.notExists],Jf=Object.entries(Mo).flatMap(([e,t])=>t.holdsOnNoRows?[e]:[]),Qf=B.filter(e=>Be("string").includes(e)),qn=B.filter(e=>Qe.includes(e)),Zf=(...e)=>Vf.flatMap(([t,r])=>r.comparator&&e.includes(r.comparator)&&!B.includes(t)?[t]:[]),os=Zf("lt","lte"),Yf=Zf("gt","gte"),Xf=["Int","BigInt"],eu=[...G,"DateTime","Boolean","String"],tu=["Int","BigInt","Float","Boolean","String"],ru=["scalar","ordered","string"],jo=["second","minute","hour","day","week","month","quarter","year"],ot={years:{interval:"months",factor:12,calendar:true,clock:"year"},quarters:{interval:"months",factor:3,calendar:true,clock:"quarter"},months:{interval:"months",factor:1,calendar:true,clock:"month"},weeks:{interval:"days",factor:7,calendar:true,clock:"week"},days:{interval:"days",factor:1,calendar:true,clock:"day"},hours:{interval:"secs",factor:3600,calendar:false,clock:"hour"},minutes:{interval:"secs",factor:60,calendar:false,clock:"minute"},seconds:{interval:"secs",factor:1,calendar:false,clock:"second"}},nu=["months","days","secs"],Bn=e=>Object.hasOwn(ot,e),Vr=e=>Bn(e)&&ot[e].calendar,is={year:"year",quarter:"quarter",month:"month",week:"week",isoWeek:"week",day:"day",hour:"hour",minute:"minute",second:"second"},ss=Object.keys(is),ou=e=>typeof e=="string"&&Object.hasOwn(is,e),Wn=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],iu=e=>Wn.includes(e.toLowerCase()),su=(e,t=[])=>Object.fromEntries([...Object.entries(e).flatMap(([r,n])=>n.negates?[[n.negates,r]]:[]),...t].flatMap(([r,n])=>[[r,n],[n,r]])),Vo=su(_n,[[h.isEmpty,h.notEmpty],[h.exists,h.notExists]]),au=su(Dn),as={[h.lessThan]:h.greaterThanEquals,[h.lessThanEquals]:h.greaterThan,[h.greaterThan]:h.lessThanEquals,[h.greaterThanEquals]:h.lessThan,[N.onOrBefore]:N.after,[N.onOrAfter]:N.before};var ls=e=>new Error(`${e}: ArrayRule.field is required (fieldless arrayOps are check-only)`),me=(e,t)=>new Error(`Unknown ${t} operator: ${String(e)}`),lu=(e,t)=>new Error(`'${e}' is finer than the engine's clock.finestUnit '${t}'`),Un=e=>new Error(`${e} requires a count`),it=e=>new Error(`${e} requires a range date expression (a period or rolling window), not a single point`),We=e=>new Error(`${e} requires a condition to check against array elements`),mr=e=>new Error(`'${e}' is a relation: it exists or not; compare its fields with '${e}.<field>'.`),ps=e=>new Error(`'${e}' is a list of rows: compare it with an arrayOperator (any / all / none / empty / atLeast \u2026).`),ds=e=>Et.includes(e.operator)&&Ji(e.fuzzy)?new Error("Fuzzy matching has no compiled form \u2014 evaluate it in memory with check()."):null,fs=(e,t)=>!In.includes(e)&&!Qe.includes(e)?null:(Qe.includes(e)&&Array.isArray(t)?t:[t]).some(n=>typeof n=="boolean"||typeof n=="object"&&n!==null&&!(n instanceof Date))?new Error(`'${e}' orders numbers, strings and dates; it can't compare ${JSON.stringify(t)}`):null,gr=e=>new Error(`aggregate.mode must be one of ${xt.join(" / ")}, not '${String(e)}'`),us=e=>new Error(`aggregate.mode must be one of ${ja.join(" / ")}, not '${String(e)}'`),Kn=e=>new Error(`${e}: a value expression is exactly one of: { value }, { path }, { bind }, an aggregate ({ field, aggregate }), if / then [/ else], or a list`),Gn=e=>new Error(`${e}: an aggregate value is the aggregate itself and takes no operator or value; compare it in a rule`),$t=()=>new Error("A condition is exactly one of: a field, date, array or aggregate rule, all, any, or if/then[/else]"),V=(e,t,r)=>new Error(`${t} has no ${e==="toSql"?"SQL":"Prisma"} form${r?` (${r})`:""}; use ${e==="toSql"?"check()":"toSql() or check()"}.`),cs=e=>V("toPrisma",`An aggregate rule compared against the column '${e}'`,"a groupBy's having can't read the parent row"),vt=e=>new Error(`Windowing (filter/orderBy/take/skip) is not supported by ${e}() for this rule; evaluate with check()${e==="toPrisma"?" \u2014 toPrisma compiles a filter alone and an extremal take: 1":""}.`),zn=(e,t)=>new Error(`'${e}' reads through the to-many relation '${t.prefix}'; compare its rows with an arrayOperator rule on '${t.prefix}'.`),Hn=(e,t)=>new Error(`'${e}' continues past '${t}', which is not a Json column`),M=class extends Error{name="UsageError"};Pt.extend(pO);Pt.extend(lO);Pt.extend(aO);Pt.extend(sO);var Z=e=>{if(!re(e))return false;let t=e;return "ago"in t||"ahead"in t||"this"in t||"last"in t||"next"in t||"start"in t||"end"in t},Ne="UTC",Io=e=>{if(e.now===void 0)throw new M("date expressions require `now` to be supplied to the evaluator");let t=Pt(e.now).tz(e.timeZone);if(!t.isValid())throw new M(`invalid \`now\`: ${String(e.now)}`);return t},qa=(e,t)=>Object.entries(e).reduce((r,[n,o])=>ot[n].interval===t?r+o*ot[n].factor:r,0),pu="YYYY-MM-DDTHH:mm:ss.SSS",yr=(e,t,r,n)=>{let o=qa(t,"months"),i=qa(t,"days"),s=qa(t,"secs"),a=Pt.utc(e.tz(n).format(pu));return o&&(a=a.add(r*o,"month")),i&&(a=a.add(r*i,"day")),s&&(a=a.add(r*s*1e3,"millisecond")),Pt.tz(a.format(pu),n)},dO=e=>"ago"in e||"ahead"in e,ms=(e,t)=>t===-1?{ago:e}:{ahead:e},Ee=e=>dO(e)?"ago"in e?[e.ago,-1]:[e.ahead,1]:null,qo=e=>"this"in e||"last"in e||"next"in e,Bo=e=>"start"in e||"end"in e,Jn=e=>"this"in e?e.this:"last"in e?e.last:e.next,fO=e=>{let t=Jn(e);if(typeof t!="string"||!ss.includes(t))throw new Error(`Unknown period unit '${String(t)}'`);return t},uO=(e,t)=>e==="week"?t.weekStart==="sunday"?"week":"isoWeek":e,Ba=(e,t)=>{let r=Io(t),n=fO(e),o=n==="isoWeek"?"week":n,i=r;"last"in e?i=r.subtract(1,o):"next"in e&&(i=r.add(1,o));let s=uO(n,t);return [i.startOf(s),i.endOf(s)]},Wa=(e,t)=>{let r=Ee(e);if(r)return yr(Io(t),...r,t.timeZone);if(Bo(e)){let n="start"in e?e.start:e.end,[o,i]=Ba(n,t);return "start"in e?o:i}throw new Error("a point operator requires a rolling or start/end edge expression, not a bare period")},Qn=(e,t,r)=>{if(qo(e)){let[n,o]=Ba(e,r),i=Vn({dateOperator:t})?.negates??t;return os.includes(i)?n:o}return Wa(e,r)},Zn=(e,t)=>{if(qo(e))return Ba(e,t);let r=Ee(e);if(r){let n=Io(t),o=yr(n,...r,t.timeZone);return r[1]===-1?[o,n]:[n,o]}throw it("within")};var du=["value","bind","path"],ne=e=>typeof e.path=="string"&&e.path!=="",qr=e=>ne(e)?L(e.path)??{depth:0,path:e.path}:null,Yn=(e,t)=>{if(e.value!==void 0)return t.value(e.value);if(e.bind!==void 0)return t.bind(e.bind,e.bindOptional);if(ne(e))return t.path(e.path);throw new Error("No value, path or bind specified")},gs=e=>re(e)&&(e.value!==void 0||ne(e)||typeof e.bind=="string"),ys=(e,t,r)=>{if(!r||!Object.hasOwn(r,e)){if(t===true)return null;throw new M(`Missing binding for "${e}"`)}let n=r[e];return n===void 0?null:n},hs=(e,t,r)=>{if(t===true)return null;throw new M(`Unresolved binding '${e}' \u2014 resolve bindings (bindRule / bindLens) before compiling with ${r}().`)},Ue=(e,t,r)=>Yn(e,{value:n=>n,bind:(n,o)=>ys(n,o,r),path:n=>$o(n,t)??null});var uu=e=>typeof e=="object"&&e!==null,ws=e=>"if"in e||"then"in e||"else"in e,xe=e=>"arrayOperator"in e||"aggregate"in e,cu=e=>[...["all","any"].flatMap(t=>Array.isArray(e[t])?e[t].map((r,n)=>({key:t,index:n,child:r,nested:false})):[]),...ws(e)?["if","then","else"].flatMap(t=>e[t]!==void 0?[{key:t,child:e[t],nested:false}]:[]):[],...["condition","filter"].flatMap(t=>e[t]!==void 0?[{key:t,child:e[t],nested:true}]:[])],Ke=e=>"all"in e||"any"in e||ws(e),J=(e,t,r)=>{if(!uu(e))return;let n=e,o=t(n,r),i=o===void 0?r:o;for(let{child:s,nested:a}of cu(n))a?i!==false&&J(s,t,i):J(s,t,r);},mu=(e,t,r,n)=>{let o=false;return J(e,(i,s)=>(!o&&t(i,s)&&(o=true),o?false:r?.(i,s)),n),o},hr=(e,t,r)=>{if(!uu(e))return e;let n=r,o={...e},i=t.rewrite?t.rewrite(o,n):o,s=cu(i),a=s.some(p=>p.nested)&&t.below?t.below(i,n):n;for(let p of ["all","any"])Array.isArray(i[p])&&(i[p]=[...i[p]]);for(let{key:p,index:d,child:f,nested:u}of s){if(u&&a===false)continue;let c=hr(f,t,u?a:n);d===void 0?i[p]=c:i[p][d]=c;}let l=t.after?t.after(i,n):i;return l===i&&cO(i,e)?e:l},cO=(e,t)=>{let r=Object.keys(e);return r.length!==Object.keys(t).length?false:r.every(n=>{let[o,i]=[e[n],t[n]];return o===i?true:Array.isArray(o)&&Array.isArray(i)&&o.length===i.length&&o.every((s,a)=>s===i[a])})},mO=(e,t)=>re(e)?Object.fromEntries(Object.entries(e).map(([r,n])=>[r,gs(n)?t(n,Vr(r)?"whole":"number"):n])):e,Ua=(e,t)=>{let r=Z(e)?Ee(e):null;return r?ms(mO(r[0],t),r[1]):e},Xn=(e,t)=>{let r="dateOperator"in e;if(!r&&!("operator"in e))return e;let n=e;if(r&&e.value!==void 0){let o=Array.isArray(e.value)?e.value.map(i=>Ua(i,t)):Ua(e.value,t);n={...n,value:o};}if(gs(e.offset)){let o=r?{...e.offset,...e.offset.value!==void 0&&{value:Ua(e.offset.value,t)}}:e.offset;n={...n,offset:t(o,r?"shift":"number")};}return gs(n)&&(n=t(n,"value")),n},Ur=e=>{let t=[];return Xn(e,(r,n)=>(t.push({source:r,role:n}),r)),t},Wo=e=>Ur(e).flatMap(({source:t,role:r})=>ne(t)?[{ref:t.path,role:r}]:[]),wr=e=>Wo(e).map(t=>t.ref),eo=e=>[...Array.isArray(e.orderBy)?e.orderBy.flatMap(t=>typeof t?.field=="string"?[t.field]:[]):[],...typeof e.aggregate?.field=="string"?[e.aggregate.field]:[]],gO={all:"all",any:"any",if:"if",field:"field",aggregate:"aggregate",array:"array",date:"date"},Br=()=>(e,t)=>({required:[...e],optional:[...t]}),fu={all:Br()(["all"],["error"]),any:Br()(["any"],["error"]),if:Br()(["if","then"],["else","error"]),field:Br()(["field","operator"],["value","path","bind","bindOptional","offset","caseInsensitive","fuzzy","coerceType","error"]),aggregate:Br()(["field","aggregate","operator"],["value","path","bind","bindOptional","condition","filter","orderBy","take","skip","coerceType","error"]),array:Br()(["arrayOperator"],["field","condition","count","filter","orderBy","take","skip","error"]),date:Br()(["field","dateOperator"],["value","path","bind","bindOptional","offset","error"])},yO=e=>({required:[...fu[e].required],optional:[...fu[e].optional]}),de=e=>{let t=new Set;return "all"in e&&t.add("all"),"any"in e&&t.add("any"),ws(e)&&t.add("if"),"arrayOperator"in e&&t.add("array"),"dateOperator"in e&&t.add("date"),"aggregate"in e?t.add("aggregate"):"operator"in e&&t.add("field"),t.size===1?[...t][0]:null},K=e=>e.length===0?true:e.length===1?e[0]:{all:[...e]},Ka=e=>typeof e=="object"&&"all"in e&&Array.isArray(e.all)?e.all.flatMap(Ka):[e],At=e=>e.length===0?false:e.length===1?e[0]:{any:[...e]};var hO=e=>e===null||e instanceof Date||["string","number","boolean","bigint"].includes(typeof e),Ht=e=>{if(Array.isArray(e))return e;let t=e.list;return Array.isArray(t)?t:[]},Nt=e=>{if(Array.isArray(e))return "list";if(hO(e))return "literal";if(!re(e))return null;let t=e,r=[];return "list"in t&&r.push("list"),ws(t)&&r.push("if"),"aggregate"in t&&r.push("aggregate"),("value"in t||"path"in t||"bind"in t)&&r.push("source"),r.length===1?r[0]:null},Wr=e=>{let t=e;switch(Nt(e)){case "list":return K(Ht(e).map(Wr));case "if":return K([t.if,Wr(t.then),...t.else===void 0?[]:[Wr(t.else)]]);case "aggregate":return t;case "source":return ne(t)?{field:t.path,operator:"exists"}:true;default:return true}};var wO=e=>Ur(e).flatMap(({source:t})=>typeof t.bind=="string"?[t]:[]),Uo=(e,{required:t=false}={})=>{let r=new Set;return J(e,n=>{for(let o of wO(n))(!t||o.bindOptional!==true)&&r.add(o.bind);}),[...r].sort()},SO=e=>{let t=new Set,r=(n,o,i)=>{let s=L(n);return s?s.depth===o+1?s.path:null:i||o===0?n:null};return J(e,(n,o)=>{let i=[...typeof n.field=="string"?[r(n.field,o,false)]:[],...Wo(n).map(({ref:s})=>r(s,o,true))];for(let s of i)s!==null&&t.add(s);return xe(n)?o+1:void 0},0),[...t].sort()},Ga=(e,t)=>{let r=n=>{if(typeof n.bind!="string"||!Object.hasOwn(t,n.bind))return n;let{bind:o,bindOptional:i,...s}=n;return {...s,value:ys(o,true,t)}};return hr(e,{rewrite:n=>Xn(Xn(n,r),r)})};var gu=BigInt(Number.MAX_SAFE_INTEGER),Jt=e=>{if(e>gu||e<-gu)throw new RangeError(`BigInt ${e} is outside the safe integer range (\xB12^53); json-rules compares BigInt as Int.`);return Number(e)},za=e=>typeof e=="bigint"?Jt(e):typeof e=="string"&&e.trim()!==""&&Number.isFinite(Number(e))?Number(e):e,Ss=(e,t)=>{if(e==null)return null;let r=za(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${t} reads a number (got ${String(e)})`);return r},Ze=([e,t])=>t<e?[t,e]:[e,t],st=(e,t)=>{if(!Array.isArray(e)||e.length!==2)throw new Error(`${t} operator requires an array of two values`);return [e[0],e[1]]},to=(e,t)=>{let r=st(e,t);if(!r.every(we))throw new Error(`${t} requires two ends that order \u2014 numbers, strings or dates (got ${JSON.stringify(e)})`);return r},bs=e=>{if(!Array.isArray(e))throw new Error(`in / notIn requires a list (got ${JSON.stringify(e)})`);return e},Ye=e=>{let t=bs(e),r=t.filter(n=>n!==null);return {values:r,hasNull:r.length!==t.length}},we=e=>typeof e=="string"||typeof e=="number"||e instanceof Date;var Ha=(e,t)=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&(!Vr(t)||Number.isInteger(e))?null:`${t} must be a non-negative${Vr(t)?" whole":""} number (got ${String(e)})`,Ja=(e,t,r)=>{let n=typeof e=="number"?e:Ss(t(e),e.path?`'${e.path}' (${r})`:r),o=n===null?null:Ha(n,r);if(o===null)return n;if(typeof e!="number"&&ne(e))return null;throw new Error(o)},Kr=(e,t)=>{let r={};for(let[n,o]of Object.entries(e)){if(o===void 0)continue;let i=Ja(o,t,n);if(i===null)return null;r[n]=i;}return r},Xe=(e,t)=>{let r=Ee(e);if(!r)return e;let n=Kr(r[0],t);return n?ms(n,r[1]):null};var bO=e=>{let t=Ee(e);if(t)return re(t[0])?Object.keys(t[0]).flatMap(o=>Bn(o)?[ot[o].clock]:[]):[];let r=Bo(e)?"start"in e?e.start:e.end:e;if(!re(r))return [];let n=Jn(r);return ou(n)?[is[n]]:[]},yu=(e,t)=>[...Ni(e),t].filter(Z).flatMap(bO),RO=e=>Ni(e).some(Z),Rs=e=>jo.indexOf(e),OO=()=>{let e=nt.get("clock.finestUnit");if(jo.includes(e))return e;if(typeof e=="string"&&Bn(e))return ot[e].clock;throw new M(`clock.finestUnit reads a clock unit, singular or plural (got ${String(e)})`)},Qt=(e,t)=>{let r=yu(e,t);if(r.length===0)return null;let n=OO(),o=r.find(i=>Rs(i)<Rs(n));return o?lu(o,n):null},Qa=e=>re(e)?e.value:void 0,Ko=e=>{let t=null;return J(e,r=>{if(!("dateOperator"in r))return;let n=Qa(r.offset),o=Qt(r.value,n);if(o)throw o;if(RO(r.value))for(let i of yu(r.value,n))(t===null||Rs(i)<t)&&(t=Rs(i));}),t===null?null:jo[t]};var Gr=(e,t)=>{if(e==null)return null;if(Array.isArray(e)){let n=e.map(o=>Gr(o,t));return n.some(o=>o===null)?null:n}let r=za(e);if(typeof r!="number"||!Number.isFinite(r))throw new Error(`offset needs a numeric comparison value (got ${String(e)})`);return r+t},zr=e=>Ss(e,"an offset"),ro=e=>{if(e==null)return null;let t=Z(e)?Ee(e):null;if(!t)throw new Error(`a date offset reads { ago } or { ahead } (got ${JSON.stringify(e)})`);return t};Pt.extend(pO);Pt.extend(lO);Pt.extend(xO);Pt.extend(EO);var Su=(e,t,r={},n)=>{let o=ir(e.field,t),i=Zt(r,u=>Ue(u,t,n)),s=i.timeZone;if(o==null)return B.includes(e.dateOperator)?true:e.error||`${e.field} has no value`;let a=we(o)?Sr(o,s):null;if(!a?.isValid())throw new Error(`${e.field} is not a valid date: ${String(o)}`);let l=u=>e.error||`${e.field} ${u}`;if(Uf.includes(e.dateOperator)){let u=Za(Ue(e,t,n));if(u===null)return e.error||`${e.field} has no comparison value`;let c=u.includes(a.tz(s).day()),y=u.map(m=>Wn[m]).join(" or ");return e.dateOperator===N.dayIn?c||l(`must be on ${y}`):!c||l(`must not be on ${y}`)}let p=AO(e,t,i,s,n);if(p===null)return e.error||`${e.field} has no comparison value`;let[d,f=d]=p;switch(e.dateOperator){case N.before:return a.isBefore(d)||l(`must be before ${d.format()}`);case N.after:return a.isAfter(d)||l(`must be after ${d.format()}`);case N.onOrBefore:return a.isSameOrBefore(d)||l(`must be on or before ${d.format()}`);case N.onOrAfter:return a.isSameOrAfter(d)||l(`must be on or after ${d.format()}`);case N.within:return a.isSameOrAfter(d)&&a.isSameOrBefore(f)||l(`must be within ${d.format()} and ${f.format()}`);case N.notBefore:return a.isSameOrAfter(d)||l(`must not be before ${d.format()}`);case N.notAfter:return a.isSameOrBefore(d)||l(`must not be after ${d.format()}`);case N.notWithin:return a.isBefore(d)||a.isAfter(f)||l(`must not be within ${d.format()} and ${f.format()}`);case N.between:return a.isSameOrAfter(d)&&a.isSameOrBefore(f)||l(`must be between ${d.format()} and ${f.format()}`);case N.notBetween:return a.isBefore(d)||a.isAfter(f)||l(`must not be between ${d.format()} and ${f.format()}`);default:throw me(e.dateOperator,"date")}},AO=(e,t,r,n,o)=>{let i=e.dateOperator,s=g=>Ue(g,t,o),a=Ue(e,t,o);if(a==null)return null;let l=e.offset===void 0?void 0:s(e.offset),p=Qt(a,l);if(p)throw p;let d=l===void 0?void 0:ro(l);if(d===null)return null;let f=g=>{if(d===void 0)return g;let S=Kr(d[0],s);return S&&yr(g,S,d[1],n)};if(_o.includes(i)){if(!Z(a))throw it(i);let g=Xe(a,s);return g&&Zn(g,r)}let u=(g,S)=>{if(g==null)return null;if(Z(g)){let w=Xe(g,s);return w&&Wa(w,r)}let b=Sr(g,n);if(!b.isValid())throw new Error(`Invalid ${S}: ${String(g)}`);return b};if(Kf.includes(i)){let[g,S]=st(a,i),b=u(g,"start date"),w=u(S,"end date");if(!b||!w)return null;let[R,O]=Ze([b,w]),$=f(R),k=f(O);return $&&k?[$,k]:null}if(Array.isArray(a))throw new Error(`${i} operator requires a single date value`);let c=g=>{let S=Xe(g,s);return S&&Qn(S,i,r)},y=Z(a)?c(a):u(a,"comparison date");if(!y)return null;let m=f(y);return m&&[m]},Zt=(e,t)=>{let r=e.timeZone;if(r===void 0||typeof r=="string")return {...e,timeZone:wu(r??Ne)};if(qr(r))throw new M(`timeZone is one per evaluation; give it as a string or a { bind }, not the row path '${r.path}'`);let n=t(r);if(n!=null&&typeof n!="string")throw new M(`timeZone reads a zone name (got ${String(n)})`);return {...e,timeZone:wu(n??Ne)}},hu=new Set,wu=e=>{if(hu.has(e))return e;try{new Intl.DateTimeFormat("en-US",{timeZone:e});}catch{throw new M(`invalid time zone: ${e}`)}return hu.add(e),e},NO=/\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?\s*(?:[zZ]|[+-]\d{2}(?::?\d{2})?)$/,PO=e=>NO.test(e.trim())||/\b(?:GMT|UTC)\b/.test(e),Sr=(e,t)=>{if(typeof e=="string"&&/^-?\d+$/.test(e.trim()))return Pt(Number(e));if(typeof e=="string"&&!PO(e)){let r=Pt(e);return r.isValid()?Pt.tz(e,t):r}return typeof e=="string"?Pt(new Date(e.trim())):Pt(e)},Os=(e,t)=>{let r=we(e)?Sr(e,t):Pt(Number.NaN);if(!r.isValid())throw new Error(`Invalid date value: ${String(e)}`);return r.toDate()},Za=e=>{if(e==null)return null;if(!Array.isArray(e))throw new Error("a weekday operator requires an array of day names");return e.map(t=>{let r=Wn.indexOf(String(t).toLowerCase());if(r===-1)throw new Error(`Unknown day name: ${String(t)}`);return r})};var TO=e=>e<=3?0:e<=6?1:2,CO=(e,t)=>{let{maxDistance:r,maxRatio:n}=e,o=[];return typeof r=="number"&&o.push(r),typeof n=="number"&&o.push(Math.floor(t*n)),o.length>0?Math.min(...o):TO(t)},bu=e=>e.split(/[^a-z0-9\p{L}]+/u).filter(Boolean),LO=e=>/^\d+$/.test(e),MO=(e,t,r)=>e===t?true:Math.abs(e.length-t.length)>r?false:distance(e,t)<=r,Ru=(e,t,r={})=>{let n=t.trim().toLowerCase();if(!n)return true;let o=e.toLowerCase();if(o.includes(n))return true;let i=bu(n);if(i.length===0)return false;let s=bu(o);return s.length===0?false:i.every(a=>{let l=CO(r,a.length);return l===0||LO(a)?s.includes(a):s.some(p=>MO(a,p,l))})};var br=e=>{let t=e instanceof RegExp?e.source:e,r=e instanceof RegExp?e.flags:"";if(/[^i]/.test(r))throw new Error(`Refused pattern /${t}/${r}: only the 'i' flag is supported`);let n=r==="i";try{return {source:t,caseInsensitive:n,re:RE2JS.compile(t,n?RE2JS.CASE_INSENSITIVE:0)}}catch(o){throw new Error(`Refused pattern /${t}/: ${o.message}`)}},no={d:"0-9",w:"0-9A-Za-z_",s:"\\t\\n\\f\\r "},Eu={alnum:"0-9A-Za-z",alpha:"A-Za-z",ascii:"\\u0000-\\u007f",blank:"\\t ",cntrl:"\\u0000-\\u001f\\u007f",digit:"0-9",graph:"!-~",lower:"a-z",print:" -~",punct:"!-/:-@\\[-`{-~",space:"\\t\\n\\v\\f\\r ",upper:"A-Z",word:"0-9A-Za-z_",xdigit:"0-9A-Fa-f"},_O=/[\\^$.|?*+()[\]{}]/,Ya=255,xu=e=>e<=65535?`\\u${e.toString(16).padStart(4,"0")}`:`\\U${e.toString(16).padStart(8,"0")}`,DO=e=>_O.test(e)?`\\${e}`:e,Go=e=>{let t=s=>{throw new Error(`Refused pattern /${e}/: ${s} has no Postgres form`)},r="",n=0,o=()=>{/^([*+?]|\{\d)/.test(e.slice(n))&&t("a quantified anchor");},i=s=>{let a=e[n+1];if(n+=2,Object.hasOwn(no,a))return s?no[a]:`[${no[a]}]`;let l=a.toLowerCase();if(a!==l&&Object.hasOwn(no,l))return s&&t(`a negated class \\${a} inside brackets`),`[^${no[l]}]`;if(a==="p"||a==="P")return t("a Unicode class");if(a==="C")return t("\\C");if(a==="x"){let p=e[n]==="{",d=p?e.indexOf("}",n):n+2,f=e.slice(p?n+1:n,d);return n=p?d+1:d,xu(Number.parseInt(f,16))}if(a>="0"&&a<="7"){let p=a;for(;p.length<3&&e[n]>="0"&&e[n]<="7";)p+=e[n++];return xu(Number.parseInt(p,8))}if(!s&&(a==="b"||a==="B")){let p=`[${no.w}]`;return a==="b"?`(?:(?<=${p})(?!${p})|(?<!${p})(?=${p}))`:`(?:(?<=${p})(?=${p})|(?<!${p})(?!${p}))`}if(!s&&(a==="z"||a==="A"))return o(),a==="z"?"\\Z":"\\A";if(a==="Q"){let p=e.indexOf("\\E",n),d=e.slice(n,p===-1?void 0:p);return n=p===-1?e.length:p+2,[...d].map(s?f=>/[\\\]^-]/.test(f)?`\\${f}`:f:DO).join("")}return `\\${a}`};for(;n<e.length;){let s=e[n];if(s==="\\")r+=i(false);else if(s===".")r+="[^\\n]",n++;else if(s==="("&&e[n+1]==="?"){let a=/^\(\?P?<[^>]+>/.exec(e.slice(n));a?(r+="(",n+=a[0].length):e[n+2]===":"?(r+="(?:",n+=3):t("a flag group");}else if(s==="{"){let a=/^\{(0|[1-9]\d*)(?:,(0|[1-9]\d*)?)?\}/.exec(e.slice(n));if(!a){r+="\\{",n++;continue}(Number(a[1])>Ya||Number(a[2]??0)>Ya)&&t(`a repeat count past ${Ya}`),r+=a[0],n+=a[0].length;}else if(s==="["){r+="[",n++,e[n]==="^"&&(r+="^",n++),e[n]==="]"&&(r+="\\]",n++);let a=false,l=false,p=0;for(;n<e.length&&e[n]!=="]";){let d=l?null:/^\[:(\^?)([a-z]+):\]/.exec(e.slice(n)),f=!!d||/^\\[dswDSW]/.test(e.slice(n)),u=e[n]==="-"&&p>0&&e[n+1]!=="]"&&!l;d?(d[1]&&t(`a negated class [:^${d[2]}:]`),Object.hasOwn(Eu,d[2])||t(`the class [:${d[2]}:]`),r+=Eu[d[2]],n+=d[0].length):e[n]==="\\"?r+=i(true):u&&a?(r+="\\-",n++):(r+=e[n]==="["?"\\[":e[n],n++);let c=l;l=u&&!a,a=f||c,p++;}r+="]",n++;}else r+=s,n++,(s==="^"||s==="$")&&o();}return r},$u=(e,t)=>{try{let{source:r}=br(e);return t==="toSql"&&Go(r),null}catch(r){return r.message}};var vu=e=>e==null||e===""||Array.isArray(e)&&e.length===0,Pe=(e,t)=>{let r=t==null;return r&&(e.offset!==void 0||If.includes(e.operator))?true:Qe.includes(e.operator)?r||Array.isArray(t)&&t.some(n=>n==null):false},Xt=e=>Je.includes(e.operator)||_e.includes(e.operator)&&e.value===null&&e.path===void 0&&e.bind===void 0,xs=(e,t)=>{let r=t.filter(o=>Array.isArray(o)||o===null),n=o=>r.map(i=>({...e,operator:o,value:i}));return e.operator===h.in?At(n(h.equals)):K(n(h.notEquals))},Hr=e=>typeof e=="string"?e.toLowerCase():Array.isArray(e)?e.map(Hr):e,Au=e=>typeof e=="bigint"?Jt(e):Array.isArray(e)&&e.some(t=>typeof t=="bigint")?e.map(t=>typeof t=="bigint"?Jt(t):t):e,Nu=(e,t,r)=>{if(e==null)return e;if(G.includes(t)){if(typeof e!="string"||e.trim()==="")return e;if(t==="BigInt"&&/^-?\d+$/.test(e.trim()))return Jt(BigInt(e.trim()));let n=Number(e);return Number.isFinite(n)?n:e}switch(t){case "DateTime":{if(e instanceof Date)return e.getTime();if(typeof e=="number"||typeof e!="string")return e;let n=Sr(e,r);return n.isValid()?n.valueOf():e}case "Boolean":return e==="true"?true:e==="false"?false:e;case "String":return typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):e;default:return e}},Yt=(e,t,r=Ne)=>t===void 0?e:Array.isArray(e)?e.map(n=>Nu(n,t,r)):Nu(e,t,r),zo=(e,t,r,n={},o)=>{let i=o?o.value:ir(e.field,t);if(n.absent==="unknown"&&!ns.includes(e.operator)&&(i===void 0||ne(e)&&$o(e.path,t)===void 0))return e.error||`${e.field} is unknown`;let s=i??null,a=e.coerceType??(s instanceof Date?"DateTime":void 0),l=a==="DateTime"?Zt(n,w=>Ue(w,t,r)).timeZone:Ne,p=Yt(Au(s),a,l),d=!Je.includes(e.operator),f=d?FO(Yt(Au(Ue(e,t,r)??null),a,l),e,t,r):void 0;if(d&&Pe(e,f))return B.includes(e.operator)&&p==null?true:e.error||`${e.field} has no comparison value`;let u=w=>e.error||`${e.field} ${w}${d?` ${f instanceof RegExp?String(f):JSON.stringify(f)}`:""}`,c=ie(e.caseInsensitive),y=w=>c?Hr(w):w,m=y(p),g=y(f),S=Ji(e.fuzzy),b=()=>S&&typeof p=="string"&&typeof f=="string"?Ru(p,f,S):Array.isArray(p)?m.some(w=>Ut(w,g)):jO(m,g);switch(e.operator){case h.equals:return Ut(m,g)||u("must equal");case h.notEquals:return !Ut(m,g)||u("must not equal");case h.lessThan:return Es(p,f,"lt")||u("must be less than");case h.lessThanEquals:return Es(p,f,"lte")||u("must be less than or equal to");case h.greaterThan:return Es(p,f,"gt")||u("must be greater than");case h.greaterThanEquals:return Es(p,f,"gte")||u("must be greater than or equal to");case h.in:return bs(g).some(w=>Ut(w,m))||u("must be one of");case h.notIn:return !bs(g).some(w=>Ut(w,m))||u("must not be one of");case h.contains:return b()||u("must contain");case h.notContains:return !b()||u("must not contain");case h.matches:return Pu(p)&&ku(f)&&br(f).re.test(p)||u("must match pattern");case h.notMatches:return !Pu(p)||!ku(f)||!br(f).re.test(p)||u("must not match pattern");case h.between:{let w=Tu(f,e.operator);if(!Lu(p,w))return u("must be between");let R=oo(p),[O,$]=w;return R>=O&&R<=$||u("must be between")}case h.notBetween:{let w=Tu(f,e.operator);if(!Lu(p,w))return true;let R=oo(p),[O,$]=w;return R<O||R>$||u("must not be between")}case h.isEmpty:return vu(p)||u("must be empty");case h.notEmpty:return !vu(p)||u("must not be empty");case h.exists:return p!=null||u("must exist");case h.notExists:return p==null||u("must not exist");case h.startsWith:return typeof m=="string"&&typeof g=="string"&&m.startsWith(g)||u("must start with");case h.endsWith:return typeof m=="string"&&typeof g=="string"&&m.endsWith(g)||u("must end with");case h.notStartsWith:return !(typeof m=="string"&&typeof g=="string"&&m.startsWith(g))||u("must not start with");case h.notEndsWith:return !(typeof m=="string"&&typeof g=="string"&&m.endsWith(g))||u("must not end with");default:throw new Error("Unknown operator")}},FO=(e,t,r,n)=>{if(t.offset===void 0)return e;let o=zr(Ue(t.offset,r,n));return o===null?null:Gr(e,o)},oo=e=>e instanceof Date?e.getTime():e,Es=(e,t,r)=>{if(!VO(e,t)||!we(t))return false;let n=oo(e),o=oo(t);switch(r){case "lt":return n<o;case "lte":return n<=o;case "gt":return n>o;case "gte":return n>=o}},Pu=e=>typeof e=="string",ku=e=>typeof e=="string"||e instanceof RegExp,Tu=(e,t)=>Ze(to(e,t).map(r=>oo(r))),jO=(e,t)=>typeof e=="string"&&typeof t=="string"&&e.includes(t),VO=(e,t)=>we(e)&&we(t)&&Cu(e)===Cu(t),Cu=e=>e instanceof Date?"date":typeof e,Lu=(e,t)=>we(e)&&typeof oo(e)==typeof t[0];var IO=15,qO=e=>e.replace(/^[-+]/,"").replace(/e.*$/i,"").replace(".","").replace(/^0+/,"").replace(/0+$/,"").length,$s=e=>{let t=String(e),r=Number(t);if(!Number.isFinite(r))return e;if(qO(t)>IO)throw new RangeError(`${t} has more digits than a number holds exactly; json-rules reads a coerced Decimal as a number.`);return r},vs=(e,t)=>r=>{if(e===void 0)return r;if(e==="String"){if(r instanceof Date)return r.toISOString();if(typeof r=="object"&&r!==null)return String(r)}let o=(G.includes(e)||e==="DateTime")&&typeof r=="bigint"?Jt(r):e==="Decimal"&&typeof r=="string"&&r.trim()!==""?$s(r.trim()):G.includes(e)&&typeof r=="object"&&r!==null&&!(r instanceof Date)?$s(r):r,i=Yt(o,e,t);return e==="DateTime"&&typeof i=="number"?new Date(i):i};var ke=e=>e.filter!==void 0||!!e.orderBy?.length||e.take!==void 0||e.skip!==void 0,BO=e=>{if(typeof e!="object"||e===null)return null;let t=e,r=de(t);return r!=="field"&&r!=="date"||typeof t.field!="string"?null:{op:String(r==="date"?t.dateOperator:t.operator),field:t.field}},WO=e=>{if(e.filter!==void 0||e.skip!==void 0&&e.skip!==0||e.take!==1||e.orderBy?.length!==1)return null;let{field:t,dir:r}=e.orderBy[0];if(r!=="asc"&&r!=="desc")return null;let n=null;if(e.arrayOperator===x.all?n="all":(e.arrayOperator===x.any||e.arrayOperator===x.atLeast&&e.count===1)&&(n="any"),!n)return null;let o=BO(e.condition);if(!o||o.field!==t)return null;let i=os.includes(o.op),s=Yf.includes(o.op);if(!i&&!s)return null;let a=r==="desc";if(!(n==="all"?a&&i||!a&&s:a&&s||!a&&i))return null;let{orderBy:p,take:d,skip:f,count:u,...c}=e;if(n==="any")return {...c,arrayOperator:x.any};let y={field:t,operator:h.exists};return {any:[{field:e.field,arrayOperator:x.empty},{all:[{field:e.field,arrayOperator:x.any,condition:y},{...c,arrayOperator:x.all,condition:{if:y,then:e.condition}}]}]}},Xa=(e,t,r)=>{let n=e;return t.filter!==void 0&&r&&(n=n.filter(r)),t.orderBy?.length&&(n=Mu(n,t.orderBy)),t.skip!==void 0&&(n=n.slice(t.skip)),t.take!==void 0&&(n=n.slice(0,t.take)),n},Mu=(e,t)=>[...e].sort((r,n)=>{for(let{field:o,dir:i}of t){let s=UO(he(r,o),he(n,o),i);if(s!==0)return s}return 0}),UO=(e,t,r)=>{let n=e==null,o=t==null;if(n||o)return n===o?0:n?1:-1;let i=e instanceof Date?e.getTime():e,s=t instanceof Date?t.getTime():t,a=i<s?-1:i>s?1:0;return r==="asc"?a:-a},io=e=>{if(!ke(e))return e;let t=!!e.orderBy?.length||e.take!==void 0||e.skip!==void 0;if(e.filter!==void 0&&!t){let{filter:r,...n}=e;if("aggregate"in e)return {...n,condition:e.condition===void 0?r:K([r,e.condition])};switch(e.arrayOperator){case "all":return {...n,condition:{if:r,then:e.condition??true}};case "empty":return {...n,arrayOperator:"none",condition:r};case "notEmpty":return {...n,arrayOperator:"any",condition:r};default:return {...n,condition:e.condition===void 0?r:K([r,e.condition])}}}return "aggregate"in e||e.filter!==void 0?null:WO(e)};var KO=e=>J(e,t=>{let r=de(t);if(!(r==="all"||r==="any")){if(r==="array"&&!("field"in t))return false;throw new Error("check: when data is an array, every leaf must be a fieldless arrayOperator (composable with all/any)")}}),Se=(e,t,r)=>(Array.isArray(t)&&KO(e),at(e,t,{...r,scopes:[t]})),at=(e,t,r)=>{if(typeof e=="boolean")return e;let n=e;switch(de(e)){case "all":return GO(n.all,t,r,n.error);case "any":return zO(n.any,t,r,n.error);case "if":return HO(n,t,r);case "array":return ZO(n,r);case "aggregate":return QO(n,r);case "date":return Su(n,r.scopes,r,r.bindings);case "field":return zo(n,r.scopes,r.bindings,r);default:throw $t()}},As=(e,t)=>({...e,scopes:[...e.scopes,t]}),GO=(e,t,r,n)=>{let o=[];for(let i of e){let s=at(i,t,r);s!==true&&(typeof s=="string"?o.push(s):o.push("false"));}return o.length?n||(o.length===1?o[0]:`All conditions must pass: ${o.join(" AND ")}`):true},zO=(e,t,r,n)=>{let o=[];for(let i of e){let s=at(i,t,r);if(s===true)return true;typeof s=="string"&&o.push(s);}return n||(o.length===1?o[0]:`At least one condition must pass: ${o.join(" OR ")}`)},HO=(e,t,r)=>at(e.if,t,r)===true?at(e.then,t,r):e.else!==void 0?at(e.else,t,r):true,_u=(e,t)=>{if(e==null)return [];if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e},Du=(e,t)=>at(e,t.scopes[t.scopes.length-1],t)===true,el=(e,t)=>{let r=_u(ir(e.field,t.scopes),e.field),n=e.filter,o=Xa(r,e,n?s=>at(n,s,As(t,s))===true:void 0),i=e.condition;return i?o.filter(s=>at(i,s,As(t,s))===true):o},Ho=(e,t,r,n)=>e.flatMap((o,i)=>{let s=r?he(o,r):o;return s==null?[]:[n(s,`${t}[${i}]${r?`.${r}`:""}`)]}),JO=(e,t)=>{let r=typeof e=="bigint"?Jt(e):e;if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${t} must be a finite number`);return r},tl=(e,t,r,n,o)=>{let i=vs(o,Ne),s=Ho(t,r,n,(l,p)=>JO(i(l),p)),a=s.reduce((l,p)=>l+p,0);return e==="sum"?a:s.length===0?null:a/s.length},QO=(e,t)=>{let{mode:r,field:n}=e.aggregate;if(!xt.includes(r))throw gr(r);let o=el(e,t),{coerceType:i,...s}=e,a=tl(r,o,e.field,n,i),l={...s,field:`${e.field} ${r}`};return zo(l,t.scopes,t.bindings,t,{value:a})},ZO=(e,t)=>{let r=_u(e.field?ir(e.field,t.scopes):t.scopes[t.scopes.length-1],e.field||"(root)"),n=e.filter,o=Xa(r,e,n?f=>at(n,f,As(t,f))===true:void 0),i=f=>e.error||`${e.field} ${f}`,s=e.condition,a=rs.includes(e.arrayOperator);if(a&&s===void 0)throw We(e.arrayOperator);let l=e.count??0;if(Do.includes(e.arrayOperator)&&e.count===void 0)throw Un(e.arrayOperator);let p=0,d=0;if(a&&s!==void 0){if(o.length>0&&!_a(o,X))return i("contains only primitive values; use 'in' or 'contains' instead of array operators on primitive arrays");let f=o.map(u=>at(s,u,As(t,u)));p=f.filter(u=>u===true).length,d=f.filter(u=>typeof u=="string").length;}switch(e.arrayOperator){case x.empty:return !o.length||i("must be empty");case x.notEmpty:return !!o.length||i("must not be empty");case x.all:return p===o.length||i(`all elements must match (${d} failed)`);case x.any:return !!p||i("at least one element must match");case x.none:return !p||i(`no elements should match (${p} matched)`);case x.atLeast:return p>=l||i(`at least ${l} elements must match (${p} matched)`);case x.atMost:return p<=l||i(`at most ${l} elements must match (${p} matched)`);case x.exactly:return p===l||i(`exactly ${l} elements must match (${p} matched)`);default:throw me(e.arrayOperator,"array")}};var E=(e,t)=>e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0,er=(e,t,r)=>(Object.hasOwn(e,t)||(e[t]=r()),e[t]),C=(e,t)=>E(e?.models,t),ge=(e,t,r)=>E(C(e,t)?.fields,r);var De=({fieldMap:e,model:t})=>`${e}:${t}`,Fu=(e,t)=>{let r=e.indexOf(":");return r===-1?{mapName:t,modelName:e}:{mapName:e.slice(0,r),modelName:e.slice(r+1)}};var ju=(e,t,r,n)=>{let o={};for(let i of e){let s=E(i,t);if(s==null)continue;let a=String(s);if(Object.hasOwn(o,a)){let l=n==="one"?`endpoint[0] must be the "one" side of a oneToMany bridge \u2014 swap endpoints if '${r}' is the "many" side`:`oneToOne bridges require unique '${t}' on both endpoints`;throw new Error(`indexBridges: duplicate '${t}' value '${a}' on '${r}' \u2014 ${l}.`)}o[a]=i;}return o},YO=(e,t)=>{let r={};for(let n of e){let o=E(n,t);o!=null&&er(r,String(o),()=>[]).push(n);}return r},Vu=(e,t)=>{let r={};for(let n of e.bridges??[]){let[o,i]=n.endpoints,s=De(o),a=De(i),l=n.cardinality==="oneToMany"?"one":"oneToOne",p=(u,c)=>er(er(r,u,()=>({})),c,()=>({})),d=E(t,s);d&&(p(o.fieldMap,o.model)[o.on]=ju(d,o.on,s,l));let f=E(t,a);f&&(n.cardinality==="oneToMany"?p(i.fieldMap,i.model)[i.on]=YO(f,i.on):p(i.fieldMap,i.model)[i.on]=ju(f,i.on,a,"oneToOne"));}return r};var Ns=e=>{let t={maps:structuredClone(e.maps),bridges:e.bridges?structuredClone(e.bridges):void 0};for(let r of e.bridges??[]){let[n,o]=r.endpoints,i=De(n),s=De(o),a=C(E(t.maps,n.fieldMap),n.model),l=C(E(t.maps,o.fieldMap),o.model);if(!a)throw new Error(`stitchFieldMaps: endpoint '${i}' not found`);if(!l)throw new Error(`stitchFieldMaps: endpoint '${s}' not found`);if(n.fieldMap===o.fieldMap&&n.model===o.model)throw new Error(`stitchFieldMaps: self-bridge '${i}' to itself is not supported`);if(!E(a.fields,n.on))throw new Error(`stitchFieldMaps: endpoint '${i}' has no field '${n.on}' for join`);if(!E(l.fields,o.on))throw new Error(`stitchFieldMaps: endpoint '${s}' has no field '${o.on}' for join`);if(E(a.fields,s))throw new Error(`stitchFieldMaps: bridge '${s}' already injected on '${i}'`);if(E(l.fields,i))throw new Error(`stitchFieldMaps: bridge '${i}' already injected on '${s}'`);let p=r.cardinality==="oneToMany";a.fields[s]={kind:"bridge",type:s,isList:p},l.fields[i]={kind:"bridge",type:i,isList:false};}return t};var so=(e,t,r)=>{if(e?.isList||t?.isList){if(!(e?.isList&&!t?.isList&&Et.includes(r)))return "a list column compares with no column but by membership";if(e?.kind!=="enum"&&t?.kind!=="enum")return null}let n=[e,t].filter(o=>o?.kind==="enum");return n.length===0?null:n.length===1||e?.type!==t?.type?"an enum compares only with an enum column of its own type":_e.includes(r)?null:`an enum column orders by declaration on the database, not as check() compares its text ('${r}')`};var Fe=e=>e.kind==="scalar"&&e.type==="Json",_=e=>e.kind==="object"||e.kind==="bridge",Jr=(e,t)=>e.values??E(t,e.type);var Te=(e,t,r)=>{if(!e||!("maps"in e))return e;if(!t)throw new Error(`${r}: 'map' is a FieldMapSet \u2014 'mapName' is required to resolve which map to use.`);let n=E(e.maps,t);if(!n)throw new Error(`${r}: fieldMap set has no entry for '${t}'`);return n};var lt=(e,t)=>e.kind==="object"?{mapName:t,modelName:e.type}:e.kind==="bridge"?Fu(e.type,t):null;function*Rr(e,t,r){let n=r.split("."),o=t;for(let i=0;i<n.length;i++){let s=n[i],a=ge(E(e,o.mapName),o.modelName,s),l=a?lt(a,o.mapName):null;if(yield {index:i,field:s,at:o,entry:a,next:l},!l)return;o={...l,relPath:[...o.relPath,s]};}}var se=(e,t,r)=>{let n=e.split("."),o=[],i={mapName:"",modelName:r,relPath:[]};for(let{index:s,field:a,at:l,entry:p}of Rr({"":t},i,e)){let d=l.modelName;if(!p)return {kind:"fallback",hops:o};if(p.kind==="bridge")return {kind:"bridge",hops:o};let f=s===n.length-1;if(p.kind==="object"){if(!C(t,p.type))return {kind:"fallback",hops:o};if(f)return {kind:"direct",hops:o,entry:p,model:d,column:a};o.push({field:a,prefix:n.slice(0,s+1).join("."),entry:p,from:d});continue}return f?{kind:"direct",hops:o,entry:p,model:d,column:a}:Fe(p)?{kind:"json-path",hops:o,entry:p,model:d,column:a,stopIndex:s+1,jsonPath:n.slice(s+1)}:{kind:"past-scalar",hops:o,column:a}}return {kind:"fallback",hops:o}},Or=(e,t,r)=>t&&r?se(e,t,r):void 0,Y=(e,t,r)=>{let n=Or(e,t,r);return n?.kind==="direct"?n.entry:void 0},Iu=(e,t,r)=>se(e,t,r).hops.filter(n=>!n.entry.isList&&n.entry.isRequired===false).map(n=>n.prefix),ao=(e,t,r)=>{let n=se(e,t,r);return n.kind==="direct"&&n.entry.kind==="object"?n.entry.type:null},Er=(e,t,r)=>se(e,t,r).kind==="bridge",kt=(e,t,r)=>!!t&&!!r&&mu(e,(n,o)=>typeof n.field=="string"&&n.field!==""&&Er(n.field,t,o),(n,o)=>(typeof n.field=="string"?ao(n.field,t,o):o)??false,r);var Qr=e=>e?.kind==="json-path"?"json-path":e?.kind!=="direct"?"unknown":e.entry.kind==="object"?e.entry.isList?"relations":"relation":e.entry.isList?"list":e.entry.kind==="enum"?"enum":qu(e.entry.type),qu=e=>e===A.Json?"json":e===A.Enum?"enum":e===A.DateTime?"instant":e===A.String?"text":"scalar",Ps=(e,t,r)=>{let n=Y(e.field,t,r);return n?n.kind==="scalar"&&(n.type==="String"||n.type==="Json"):e.coerceType===void 0||e.coerceType==="String"||e.coerceType==="Json"},ks=(e,t,r)=>{if(Qr(Or(e,t,r))==="relations")throw ps(e)},Zr=e=>e!=="scalar"&&e!=="instant"&&e!=="list"&&e!=="enum"&&e!=="relation"&&e!=="relations",xr=(e,t)=>Zr(e)&&Bu(t),Bu=e=>typeof e=="string"||Array.isArray(e)&&e.some(Bu),Ge=(e,t,r)=>{let n=Qr(Or(e.field,t,r));return n==="unknown"&&e.coerceType!==void 0?qu(e.coerceType):n},ze=e=>{if(!e.isList){if(e.kind==="enum")return A.Enum;if(!(e.kind!=="scalar"||e.type===A.Json))return jn(e.type)?e.type:void 0}};var nl=Symbol("unread"),rl=e=>({field:e,operator:"notExists"}),XO=["filter","orderBy","take","skip"],Wu=(e,t)=>({field:e.field,aggregate:e.aggregate,...Object.fromEntries(["condition","coerceType",...XO].filter(r=>e[r]!==void 0).map(r=>[r,e[r]])),operator:t}),eE=(e,t,r)=>{let n=t(e,r);if(n===nl)return {if:e,then:false};if(n===null){let s=e.operator??e.dateOperator;return B.includes(s)?"aggregate"in e?Wu(e,"exists"):{field:e.field,operator:"exists"}:true}if("aggregate"in n){let s=E(Vo,n.operator);if(s)return {...n,operator:s};let a={...n,operator:E(as,n.operator)};return n.aggregate.mode==="avg"?At([a,Wu(n,"notExists")]):a}if(typeof n.dateOperator=="string"){let s=E(au,n.dateOperator);return s?{...n,dateOperator:s}:At([{...n,dateOperator:E(as,n.dateOperator)},rl(n.field)])}if(typeof n.arrayOperator=="string"){let s=n.count;switch(n.arrayOperator){case x.any:return {...n,arrayOperator:x.none};case x.none:return {...n,arrayOperator:x.any};case x.all:return {...n,arrayOperator:x.any,condition:$r(n.condition,t,r+1)};case x.empty:return {...n,arrayOperator:x.notEmpty};case x.notEmpty:return {...n,arrayOperator:x.empty};case x.atLeast:return s<=0?false:{...n,arrayOperator:x.atMost,count:s-1};case x.atMost:return {...n,arrayOperator:x.atLeast,count:s+1};case x.exactly:return At([...s>0?[{...n,arrayOperator:x.atMost,count:s-1}]:[],{...n,arrayOperator:x.atLeast,count:s+1}])}}let o=E(Vo,n.operator);if(o)return {...n,operator:o};let i=typeof n.path=="string"&&n.path!==""?L(n.path)??{depth:1,path:n.path}:null;return At([{...n,operator:E(as,n.operator)},rl(n.field),...i&&i.depth===1?[rl(i.path)]:[]])},$r=(e,t=n=>n,r=0)=>{if(typeof e=="boolean")return !e;let n=e,o=i=>$r(i,t,r);if(Array.isArray(n.all))return At(n.all.map(o));if(Array.isArray(n.any))return K(n.any.map(o));if("if"in n){let i=K([n.if,o(n.then)]);return n.else===void 0?i:{any:[i,K([o(n.if),o(n.else)])]}}return eE(n,t,r)},tE=e=>["field","aggregate"].includes(de(e))&&e.value!==void 0&&Pe(e,e.value)?null:e,rE=(e,t)=>Z(e)&&Xe(e,t)===null,Uu=e=>(t,r)=>{let n=typeof t.operator=="string"||typeof t.dateOperator=="string",o=t.value!==void 0||ne(t)||typeof t.bind=="string";if(!n||!o)return t;let i=typeof t.dateOperator=="string",s=m=>i&&(m==="number"||m==="whole");if(Ur(t).some(({source:m,role:g})=>e(m,r,s(g))===nl))return nl;let a=m=>e(m,r),l=e(t,r),p=t.offset===void 0?void 0:e(t.offset,r);if(t.offset!==void 0&&p==null)return null;let{path:d,bind:f,bindOptional:u,...c}=t,y={...c,value:l,...t.offset!==void 0&&{offset:{value:p}}};return typeof t.dateOperator!="string"?tE(y):l==null||Pe({operator:t.dateOperator},l)||[l,p].flat().some(m=>rE(m,a))?null:y};var Ku=new WeakSet,Cs=e=>(Ku.add(e),e),Gu=e=>{if(e===null||typeof e!="object")return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},zu=e=>{let t=[],r=(n,o)=>{if(n!==null&&typeof n=="object"&&Ku.has(n)){t.push({path:o});return}if(Array.isArray(n))for(let[i,s]of n.entries())r(s,[...o,i]);else if(Gu(n))for(let[i,s]of Object.entries(n))r(s,[...o,i]);};return r(e,[]),t},nE=["__step","__field"],Ts=e=>Array.isArray(e)?e.some(Ts):Gu(e)?Object.entries(e).some(([t,r])=>nE.includes(t)||Ts(r)):false;var oE={[h.equals]:"equals",[h.notEquals]:"equals",[h.lessThan]:"lt",[h.lessThanEquals]:"lte",[h.greaterThan]:"gt",[h.greaterThanEquals]:"gte"},Hu=(e,t,r)=>{let n=se(e,t,r);if(n.kind!=="direct"||n.hops.length>0)return `'${e}' is not a column of ${r} (a relation hop or an undeclared path)`;let{entry:o}=n;return _(o)?`'${e}' is a relation`:Fe(o)?`'${e}' is a Json column`:o.isList?`'${e}' is a list column`:o},Ls=(e,t,r,n,o=false)=>{let i=e.path;if(o)return {problem:"inside a counting step (a count or relation aggregate) a groupBy carries no column reference"};let s=L(i);if(s&&s.depth>1)return {problem:`'${i}' reads an enclosing scope, which a Prisma filter can't reach`};if(!s&&n)return {problem:`'${i}' reads the root row, which a Prisma relation filter can't reach`};if(!t||!r)return {problem:"comparing two columns needs the map and model"};let a=oE[e.operator];if(!a)return {problem:`'${e.operator}' takes no column reference in Prisma`};if(e.offset!==void 0)return {problem:"an offset is arithmetic, which Prisma lacks"};let l=Hu(e.field,t,r);if(typeof l=="string")return {problem:l};let p=s?s.path:i,d=Hu(p,t,r);if(typeof d=="string")return {problem:d};if(l.kind!==d.kind||l.type!==d.type)return {problem:`'${e.field}' (${l.type}) and '${p}' (${d.type}) are not the same type`};let f=so(l,d,e.operator);return f?{problem:f}:l.type==="String"&&ie(e.caseInsensitive)?{problem:"a case-insensitive column comparison compiles to ILIKE"}:{key:a,ref:Cs({__field:{model:r,field:p}}),field:l,column:d,columnPath:p}},Ms=(e,t)=>new Error(`Path '${e}' compares to a column, which the Prisma rail supports only between columns of the same model and type: ${t}. Use toSql() or check().`),Ju=new WeakSet,ol=new WeakSet,Yr=(e,t,r=false)=>(Ju.add(e),(r||t!==void 0&&ol.has(t))&&ol.add(e),e),Qu=e=>e!==void 0&&Ju.has(e),Zu=e=>e!==void 0&&ol.has(e);var il=(e,t)=>{let r=Yt(e,A.DateTime,t);return typeof r=="number"&&!Number.isNaN(new Date(r).getTime())?r:void 0},iE=(e,t,r)=>n=>{if(n==null)return n;let o=il(n,r);if(o===void 0)throw new Error(`Invalid date value for DateTime field '${e}': ${String(n)}`);return t==="toPrisma"?new Date(o):new Date(o).toISOString()},lo=(e,t,r,n,o)=>{if(t==null||r?.kind==="json-path")return t;let i=r?.kind==="direct"?r.entry:void 0;if(i?.isList)return t;let s=i?ze(i):void 0;if(e.coerceType!==void 0&&s!==void 0&&e.coerceType!==s)throw new Error(`coerceType '${e.coerceType}' overrides ${s} field '${e.field}', but ${n} compares the column as stored \u2014 evaluate it in memory with check(), or drop the override.`);if((s??e.coerceType)===A.DateTime){let l=iE(e.field,n,o());return Array.isArray(t)?t.map(l):l(t)}if(e.coerceType===void 0&&s===A.String&&(Array.isArray(t)?t:[t]).some(l=>typeof l=="number"||typeof l=="boolean"))throw new Error(`'${e.field}' is String but the literal is not a string; pass a string, or stamp coerceType: 'String'.`);if(e.coerceType===void 0&&s!==void 0&&(G.includes(s)||s===A.Boolean)&&(Array.isArray(t)?t:[t]).some(l=>typeof l=="string"))throw new Error(`'${e.field}' is ${s} but the literal is a string; pass a ${s===A.Boolean?"boolean":"number"}, or stamp coerceType: '${s}'.`);return e.coerceType!==void 0&&tu.includes(e.coerceType)?Yt(t,e.coerceType,e.coerceType===A.DateTime?o():void 0):t};var _s=(e,t,r,n)=>{if(!Wf.includes(e.operator))throw new Error(`'${e.operator}' does not apply to the enum '${e.field}'; compare its values with equals / in.`);let o=ie(e.caseInsensitive),i=Jr(r,n?.enums),{values:s,hasNull:a}=Ye(_e.includes(e.operator)?[t]:t);if(!o&&(!i||s.every(f=>typeof f=="string"&&i.includes(f))))return null;if(!i)throw new Error(`'${e.field}' is an enum: a case-insensitive comparison reads its declared values, which the map doesn't list.`);let l=f=>o?f.toLowerCase():f,p=new Set(s.filter(f=>typeof f=="string").map(f=>l(f))),d=i.filter(f=>p.has(l(f)));return B.includes(e.operator)?{values:i.filter(f=>!d.includes(f)),matchesNull:!a}:{values:d,matchesNull:a}};var ae=e=>`"${e.replace(/"/g,'""')}"`;var $e=e=>e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_"),sl=(e,t,r=false)=>{let[n,...o]=e.split("."),i=t?`${ae(t)}.${ae(n)}`:ae(n);if(o.length===0)return i;let s=o.map(al),a=s.pop();return [i,...s].join("->")+(r?"->":"->>")+a},al=e=>`'${e.replace(/'/g,"''")}'`;var sE=["@prisma/client/runtime/client","@prisma/client/runtime/library"],Ds,aE=()=>{if(Ds!==void 0)return Ds;for(let e of lE())for(let t of sE)try{let r=e(t);if(r.AnyNull!==void 0)return Ds=r.AnyNull,Ds}catch{}},lE=()=>{let e=[];try{let t=globalThis.process?.getBuiltinModule?.("module")?.createRequire;t&&e.push(t(import.meta.url));}catch{}return typeof Aa=="function"&&e.push(Aa),e},Yu=()=>{let e=nt.get("prismaOptions.anyNull")??aE();if(e===void 0)throw new Error("A null check on a Json field needs Prisma's AnyNull, and @prisma/client isn't installed: engineGlobals.set('prismaOptions.anyNull', Prisma.AnyNull).");return e};var Xu,ec=e=>{Xu=e;},ue=(e,t,r)=>Xu(e,t,r);var pE=e=>{let t=L(e);throw t&&t.depth>1?new Error(vo(e,"toPrisma")):new Error(`Path '${e}' compares to a column, which isn't supported on the Prisma rail; use toSql() or check().`)},Tt=e=>Yn(e,{value:t=>{if(Ts(t))throw new Error("toPrisma: a value holding a '__step' or '__field' key is reserved for the plan's own references");return t},path:t=>pE(t),bind:(t,r)=>hs(t,r,"toPrisma")}),Jo=e=>Tt(e),po=e=>Zt({now:e?.now,timeZone:e?.timeZone,weekStart:e?.weekStart},Jo),fo=e=>{let t=Uu(r=>Tt(r));return (r,n)=>{if(typeof r.operator=="string"&&ne(r))return r;if((r.value!==void 0||typeof r.bind=="string")&&!("aggregate"in r)&&typeof r.operator=="string"&&In.includes(r.operator)){let i=Ge({field:String(r.field)},e?.map,e?.model);if(i==="json"||i==="json-path")throw V("toPrisma",`The complement of '${r.operator}' on the Json value '${r.field}'`,"it keeps values of other types")}return t(r,n)}};var et=()=>({}),Xr=et,pt=()=>({OR:[]}),ll=e=>Object.keys(e).length===0,tc=e=>{let t=Object.keys(e);return t.length===1&&t[0]==="OR"&&Array.isArray(e.OR)&&e.OR.length===0},ce=e=>{if(e.some(tc))return pt();let t=e.filter(r=>!ll(r));return t.length===0?et():t.length===1?t[0]:{AND:t}},U=e=>{if(e.some(ll))return et();let t=e.filter(r=>!tc(r));return t.length===0?pt():t.length===1?t[0]:{OR:t}},je=e=>ll(e)?e:{NOT:e},rc=(e,t,r)=>ce(e.all.map(n=>ue(n,t,r))),nc=(e,t,r)=>U(e.any.map(n=>ue(n,t,r))),oc=(e,t,r)=>{if(kt(e,t?.map,t?.model))return Xr();let n=ue($r(e.if,fo(t)),t,r),o=ue(e.then,t,r),i=U([n,o]);if(e.else!==void 0){let s=ue(e.if,t,r),a=ue(e.else,t,r);return ce([i,U([s,a])])}return i};var ic=(e,t)=>{let r=zr(Tt(t));return r===null?null:Gr(e,r)},sc=(e,t,r)=>{if(e===null)return null;let n=ro(Tt(t)),o=n&&Kr(n[0],Jo);return !n||!o?null:yr(Pt(e),o,n[1],po(r).timeZone).toDate()};var en=(e,t)=>{let r=e.split("."),n=t;for(let o=r.length-1;o>=0;o--)n={[r[o]]:n};return n};var dl=(e,t)=>Ge(e,t?.map,t?.model),Ct=e=>e==="json"||e==="json-path",vr=e=>Ct(e)?Yu():null,Ar=(e,t)=>t?.map&&t?.model?Iu(e,t.map,t.model).map(r=>en(r,{is:null})):[],fl=(e,t)=>{let r=dl(e,t);return [...Ct(r)||r==="list"||Y(e.field,t?.map,t?.model)?.isRequired===false?[tt(e.field,{equals:vr(r)},t)]:[],...Ar(e.field,t)]},Fs=(e,t,r,n)=>{if(r.mode&&Ct(n)&&Array.isArray(t))throw V("toPrisma",`A case-insensitive comparison of a Json value with the list ${JSON.stringify(t)}`);if(!r.mode||typeof t!="string")return {[e]:t,...r};if(!Ct(n))return {[e]:$e(t),...r};if(/[%_\\"\u0000-\u001f]/.test(t))throw V("toPrisma",`A case-insensitive equality on Json against '${t}'`,"Prisma matches the JSON text, where %, _, a backslash, a quote or a control character doesn't read as itself");return {[e]:t,...r}},ul=(e,t,r,n)=>{let o=t?.datasource?.provider??nt.get("prismaOptions.datasource.provider");return ie(e.caseInsensitive)&&Df(o)&&xr(r,n)?{mode:"insensitive"}:{}},ac=(e,t)=>{if(e==="list")return [{isEmpty:true}];let r=t?[{equals:""}]:[];return Ct(e)?[...r,{equals:[]}]:r},lc=e=>"isEmpty"in e?{isEmpty:false}:{not:e.equals},js=(e,t,r,n,o)=>{let i=a=>tt(e,a,o),s=ac(t,n);return r?U([i({equals:vr(t)}),...Ar(e,o),...s.map(a=>i(a))]):ce([...t==="list"?[]:[i({not:vr(t)})],...s.map(a=>i(lc(a)))])},fE=(e,t)=>{if(!Xt(e))throw mr(e.field);let n=(o=>tt(e.field,o,t))({is:{}});return Se({...e,field:"relation"},{relation:null})===true?je(n):n},uE=(e,t)=>Y(e.field,t?.map,t?.model),pl=et(),cE=(e,t,r)=>{if(t==="list"||Ct(t)||uE(e,r)?.isRequired!==true)return null;let n=e.field.split(".").slice(0,-1).join(".");return n?tt(n,{is:{}},r):pl},pc=(e,t)=>{let r=m=>tt(e.field,m,t),n=dl(e,t),o=()=>fl(e,t),i=Ps(e,t?.map,t?.model);if(n==="relation")return fE(e,t);let s=cE(e,n,t),a=s&&(s===pl?pt():je(s)),l=m=>s&&a?Se({field:"f",operator:m,value:null},{f:null})===true?a:s:null;if(s&&a&&Xt(e)){let m=ac(n,i);return e.operator===h.isEmpty?U([a,...m.map(r)]):e.operator===h.notEmpty?ce([s,...m.map(g=>r(lc(g)))]):l(e.operator)}switch(e.operator){case h.exists:case h.notExists:{if(e.operator===h.exists)return n==="list"?je(r({equals:null})):r({not:vr(n)});let m=o();return m.length?U(m):r({equals:vr(n)})}case h.isEmpty:case h.notEmpty:return js(e.field,n,e.operator===h.isEmpty,i,t)}if(ne(e)){let m=Ls(e,t?.map,t?.model,Qu(t),Zu(t));if("problem"in m)throw Ms(e.path,m.problem);let g=r({[m.key]:m.ref}),S=(O,$)=>$.isRequired===false?tt(O,{equals:null},t):null,b=(O,$)=>$.isRequired===false?tt(O,{not:null},t):pl,w=S(e.field,m.field),R=S(m.columnPath,m.column);return e.operator===h.equals?w&&R?U([g,ce([w,R])]):g:e.operator===h.notEquals?U([je(g),...w?[ce([w,b(m.columnPath,m.column)])]:[],...R?[ce([b(e.field,m.field),R])]:[]]):g}let p=dc(e,t);if(Pe(e,p))return U(B.includes(e.operator)?o():[]);if(p===null&&_e.includes(e.operator)){let m=l(e.operator);if(m)return m}if(n==="list"&&cr.includes(e.operator)&&Array.isArray(p))return ue(xs(e,p),t);if(n==="list"&&Array.isArray(p)&&p.includes(null))throw V("toPrisma",`A list holding null in '${e.field}'`);if(n==="list"&&ie(e.caseInsensitive)&&xr("text",p))throw V("toPrisma",`A case-insensitive comparison on the list '${e.field}'`);let d=n==="enum"?Y(e.field,t?.map,t?.model):void 0,f=d?_s(e,p,d,t?.map):null;if(f){let m=r({in:f.values});return f.matchesNull?U([m,...o()]):m}if(cr.includes(e.operator)){let{values:m,hasNull:g}=Ye(p),S=ul(e,t,n,m),b=Ct(n)?e.operator===h.in?U(m.map(w=>r(Fs("equals",w,S,n)))):ce(m.map(w=>r(Fs("not",w,S,n)))):r({[e.operator]:m,...S});return e.operator===h.in?g?U([b,...o()]):b:g?ce([b,s??r({not:vr(n)})]):U([b,...o()])}let u=m=>{if(!Ct(n)||m!==h.contains)return r(Qo({...e,operator:m},t));let g=r({array_contains:[mE(e,p,t,n)]});return typeof p=="string"?U([r(Qo({...e,operator:m},t)),g]):g};if(e.operator===h.contains)return u(h.contains);let c=Qf.includes(e.operator)?Vo[e.operator]:qn.includes(e.operator)?h.between:void 0;if(c){if(Ct(n))throw V("toPrisma",`'${e.operator}' on the Json value '${e.field}'`,"it keeps values of other types");return U([je(u(c)),...o()])}let y=r(Qo(e,t));return e.operator===h.equals&&p===null?U([y,...Ar(e.field,t)]):e.operator===h.notEquals&&n==="list"?p===null?je(r({equals:null})):U([je(r({equals:p})),...o()]):e.operator===h.notEquals&&p!==null?U([y,...o()]):y},dc=(e,t)=>{let r=lo(e,Tt(e),Or(e.field,t?.map,t?.model),"toPrisma",()=>po(t).timeZone);return e.offset===void 0?r:ic(r,e.offset)},Qo=(e,t)=>{let r=ds(e);if(r)throw r;let n=dl(e,t),o=()=>dc(e,t),i=p=>ul(e,t,n,p),s=p=>{let d=o();if(n==="list"){if(p!=="contains")throw new Error(`Operator '${p}' does not apply to the list '${e.field}'.`);return {has:d}}let f=Ct(n)?gE[p]:p,u=typeof d=="string"?$e(d):d;return {[f]:u,...i(d)}},a=fs(e.operator,o());if(a)throw a;let l=ur(e.operator,"field");if(l&&In.includes(e.operator))return {[l]:o()};switch(e.operator){case h.equals:{let p=o()??vr(n);return Fs("equals",p,i(p),n)}case h.notEquals:{let p=o()??vr(n);return Fs("not",p,i(p),n)}case h.in:case h.notIn:return {[e.operator]:o()};case h.contains:return s("contains");case h.startsWith:return s("startsWith");case h.endsWith:return s("endsWith");case h.matches:case h.notMatches:throw V("toPrisma",`'${e.operator}'`,"Prisma has no pattern filter");case h.between:case h.notBetween:{let[p,d]=Ze(st(o(),e.operator));return {gte:p,lte:d}}default:throw new Error(`Operator '${e.operator}' is built by buildFieldRule`)}},mE=(e,t,r,n)=>{if(typeof t=="object"&&t!==null)throw new Error(`Membership of an object or a list in the Json array '${e.field}' has no exact Prisma form; use toSql() or check().`);if(ul(e,r,n,t).mode)throw V("toPrisma",`A case-insensitive member of the Json array '${e.field}'`);return t},gE={contains:"string_contains",startsWith:"string_starts_with",endsWith:"string_ends_with"},tt=(e,t,r)=>{if(!r?.map||!r?.model)return en(e,t);let n=se(e,r.map,r.model),o=n.hops.find(s=>s.entry.isList);if(o)throw zn(e,o);let i=e.split(".");switch(n.kind){case "fallback":case "direct":return en(e,t);case "bridge":return Xr();case "past-scalar":throw Hn(e,n.column);case "json-path":{let s={path:n.jsonPath,...t},a=i.slice(0,n.stopIndex).join(".");return en(a,s)}}};var yE=(e,t,r,n)=>{let o=C(e,t);if(!o)return null;for(let i of Object.values(o.fields))if(i.kind==="object"&&i.type===r&&(i.fromFields?.length??0)>0&&(i.toFields?.length??0)>0&&(n===void 0||i.relationName===n))return i;return null},Nr=(e,t,r)=>{if(r.fromFields?.length)return r.fromFields.map((o,i)=>({here:o,there:r.toFields?.[i]??"id"}));let n=yE(e,r.type,t,r.relationName);return n?.fromFields?.length?n.fromFields.map((o,i)=>({here:n.toFields?.[i]??"id",there:o})):null},Vs=(e,t,r,n)=>{if(n.relationName===void 0)return null;let o=Object.entries(C(e,n.type)?.fields??{}).filter(([i,s])=>s.kind==="object"&&s.type===t&&s.relationName===n.relationName&&!(n.type===t&&i===r));return o.length===1?{field:o[0][0],entry:o[0][1]}:null};var uo=(e,t,r,n)=>{let o=e.split("."),i=se(e,t,r);if(i.kind==="bridge")throw new Error(`'${e}' crosses a bridge: ${n.toLowerCase()} aren't supported across a bridge \u2014 no one database holds both sides.`);if(i.kind!=="direct"||i.entry.kind!=="object"){let l=i.hops.at(-1)?.entry.type??r;throw new Error(`Field '${o[i.hops.length]}' is not a relation in model '${l}'. ${n} require a relation field.`)}let s=i.hops.find(l=>l.entry.isList);if(s)throw new Error(`Intermediate field '${s.field}' in path '${e}' is a list relation. Only the final segment can be a list relation for ${n.toLowerCase()}.`);if(!i.entry.isList)throw new Error(`Field '${i.column}' is not a list relation in model '${i.model}'. ${n} only apply to one-to-many or many-to-many relations.`);let a=Nr(t,i.model,i.entry);if(!a){let l=Object.values(C(t,i.entry.type)?.fields??{}).some(p=>p.kind==="object"&&p.type===i.model&&p.isList&&!p.fromFields?.length);throw new Error(l?`'${i.model}.${i.column}' is an implicit many-to-many relation. ${n} require an explicit join model with a FK \u2014 convert to an explicit @relation or use prisma.$queryRaw.`:`Cannot determine FK relationship between '${i.model}' and '${i.entry.type}'. Ensure the FieldMap contains both sides of the relation.`)}if(a.length>1)throw new Error(`${n} do not support composite FK relations ('${i.model}.${i.column}'). Use prisma.$queryRaw.`);return {through:i.hops.map(l=>l.field).join("."),target:i.entry.type,parentKey:a[0].here,targetKey:a[0].there}},Zo=(e,t,r,n,o)=>{let i={operation:"groupBy",model:t.target,args:{by:[t.targetKey],where:r,...n&&{having:n}},extract:t.targetKey},s=Cs({__step:e.steps.length});e.steps.push(i);let a={[t.parentKey]:{in:s}},l=o?je(a):a;return t.through?en(t.through,l):l};var ml=()=>new Error("Prisma aggregate rules require aggregate.field to specify the numeric field on the related model."),gl=(e,t,r)=>{let n=ge(e,t,r);return n?n.kind==="scalar"&&!Fe(n)&&G.includes(n.type)?null:new Error(`aggregate.field '${r}' on model '${t}' must be a numeric scalar, got '${n.kind==="scalar"?n.type:n.kind}'.`):new Error(`aggregate.field '${r}' does not exist on model '${t}'.`)},fc=(e,t,r)=>{if(ne(e))throw cs(e.path);if(ke(e)){let n=io(e);if(!n)throw vt("toPrisma");return ue(n,t,r)}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(!xt.includes(e.aggregate.mode))throw gr(e.aggregate.mode);if(!e.aggregate.field)throw ml();return hE(e,t,r)},hE=(e,t,r)=>{let n=uo(e.field,t.map,t.model,"Aggregate rules");if(e.condition&&kt(e.condition,t.map,n.target))return Xr();let o=e.aggregate.field??"",i=gl(t.map,n.target,o);if(i)throw i;let s=()=>e.condition?ue(e.condition,Yr({...t,model:n.target},t,true),r):et();if(Je.includes(e.operator))return cl(e,e.operator===h.exists,s,n,t,r);let{coerceType:a,...l}=e,p=fo(t)(l,0);if(p!==null&&p.value===null&&_e.includes(e.operator))return cl(e,e.operator===h.notEquals,s,n,t,r);if(p===null||Pe(p,p.value))return B.includes(e.operator)?cl(e,false,s,n,t,r):pt();let d=e.aggregate.mode==="sum"?0:null,f=zo(p,[{}],void 0,{},{value:d})===true,u=f?$r(p):p,c=Qo(u,t),y={[e.aggregate.mode==="sum"?"_sum":"_avg"]:c},m=qn.includes(u.operator)?je({[o]:y}):{[o]:y},g=Zo(r,n,s(),m,f);return f?U([g,...Ar(e.field,t)]):g},cl=(e,t,r,n,o,i)=>{if(e.aggregate.mode==="sum")return t?et():pt();let s=ce([r(),{[e.aggregate.field]:{not:null}}]),a=Zo(i,n,s,void 0,!t);return t?a:U([a,...Ar(e.field,o)])};var dt=e=>!Object.hasOwn(e,"parent"),Lt=e=>{let t=[],r=new Set,n=e;for(;!dt(n);){if(r.has(n))throw new Error("cycle detected in narrowing parent chain");if(Object.hasOwn(n,"model")||Object.hasOwn(n,"maps"))throw new Error("a narrowing carries a base lens key (model / maps); it has a parent instead");r.add(n),t.unshift(n),n=n.parent;}return t},ft=e=>dt(e)?e:Lt(e)[0].parent;var yl=(e,t)=>t.length?K([...t,e]):e,wE=e=>{if(wr(e).length)return false;let t=e.field,r=typeof t=="string"?L(t):null;try{return Se(r?{...e,field:r.path}:e,{})===!0}catch{return false}},hl=(e,t)=>{if(!t.length)return e;if(!wE(e))return K([...t.flatMap(o=>o.clamps),e]);let[r,...n]=t;return At([K([...r.clamps,hl(e,n)]),K([{field:r.prefix,operator:"notExists"},e])])},mo=(e,t,{paths:r=false}={})=>hr(e,{rewrite:n=>{if(Ke(n))return n;if(typeof n.field!="string"||n.field==="")throw new T(`narrowRule: cannot re-root a relation clamp of unknown shape under '${t}'`,"unsupported_clamp");let o=wr(n),i=o.find(a=>L(a));if(r&&i)throw new T(`prefixConditionFields: cannot re-root a scope ref ('${i}') under '${t}'`,"unsupported_clamp");if(o.length&&!r)throw new T(`narrowRule: cannot re-root a relation clamp with a path reference ('${o[0]}') under '${t}'. Author the clamp without 'path', or anchor it at the relation itself.`,"unsupported_clamp");if(L(n.field))throw new T(`narrowRule: cannot re-root a relation clamp with a scope ref field ('${n.field}') under '${t}'. Author the clamp against the model's own columns.`,"unsupported_clamp");if(xe(n)){for(let a of [n.condition,n.filter])if(a!==void 0&&co(a).escaping!==null)throw new T(`narrowRule: cannot re-root a relation clamp on '${n.field}' under '${t}': '${co(a).escaping}' inside it reads the row being re-rooted. Anchor such clamps at the relation's own model.`,"unsupported_clamp")}return {...r?Xn(n,a=>ne(a)?{...a,path:`${t}.${a.path}`}:a):n,field:`${t}.${n.field}`}},below:()=>false}),wl=(e,t)=>t.flatMap(r=>{let n=I(e,r.map,r.model,r.relPath);if(n.whereClauses.length===0)return [];if(r.isList)throw new T(`narrowRule: cannot enforce a to-many relation clamp on '${r.prefix}' without an arrayOperator condition to anchor it (row-scoped). Traverse '${r.prefix}' via an array operator (any/all/none/...) so the clamp can be injected safely.`,"unsupported_clamp");return [{prefix:r.prefix,clamps:n.whereClauses.map(o=>mo(o,r.prefix))}]}),uc=(e,t)=>wl(e,t).flatMap(r=>r.clamps),mc=(e,t,r)=>{let n=He(e,r);if("outOfBounds"in n)throw new T(`narrowRule: ${n.outOfBounds}`,"scope_out_of_bounds");if(!n.scope)return {hops:[],end:null};let o=e.slice(0,e.length-n.path.length);return Ce(t.lens.maps,n.scope,n.path,o==="$."?"":o)},SE=(e,t,r)=>{if(L(e))return mc(e,t,r).hops;let n=r.length===1?"":`${"$".repeat(r.length)}.`;return r[0]?Ce(t.lens.maps,r[0],e,n).hops:[]},cc=(e,t,r)=>{if(Ke(e)||typeof e.field!="string"||e.field==="")return null;let{hops:n,end:o}=mc(e.field,t,r);return {hops:n,below:o}},tn=(e,t,r)=>hr(e,{below:(n,o)=>{let i=cc(n,t,o);return i?i.below?[...o,i.below]:xe(n)?[...o,null]:false:false},after:(n,o)=>{let i=cc(n,t,o);if(!i)return n;let s=uc(t,wr(n).flatMap(f=>SE(f,t,o))),a=i.below;if(!a||!xe(n))return yl(hl(n,wl(t,i.hops)),s);let l=[...I(t,a.mapName,a.modelName,a.relPath).whereClauses,...uc(t,eo(n).flatMap(f=>Ce(t.lens.maps,a,f).hops))],p=n.condition===void 0||n.arrayOperator===x.all||ke(n),d={...n};return l.length&&p?d.filter=K([...n.filter!==void 0?[n.filter]:[],...l]):l.length&&(d.condition=K([...l,n.condition])),yl(hl(d,wl(t,i.hops.slice(0,-1))),s)}},[r]),go=(e,t)=>{let r=F(t),n=I(r,r.lens.mapName,r.lens.model,[]),o=tn(e,r,{mapName:r.lens.mapName,modelName:r.lens.model,relPath:[]});return yl(o,n.whereClauses)};var gc=e=>Array.isArray(e)?e.flatMap(gc):[e],Yo=e=>e.value===void 0?null:gc(e.value),bE=e=>il(e)!==void 0,RE=/^-?\d+(\.\d+)?$/,OE={String:{expected:"a string",fits:e=>typeof e=="string"},Enum:{expected:"a string",fits:e=>typeof e=="string"},Int:{expected:"an integer",fits:Number.isSafeInteger},BigInt:{expected:"an integer",fits:Number.isSafeInteger},Float:{expected:"a number",fits:Number.isFinite},Decimal:{expected:"a number or a numeric string",fits:e=>Number.isFinite(e)||typeof e=="string"&&RE.test(e)},Boolean:{expected:"a boolean",fits:e=>typeof e=="boolean"},DateTime:{expected:"a date",fits:bE},Json:{expected:"a value",fits:()=>true},Bytes:{expected:"a value",fits:()=>true}},EE=e=>typeof e=="string"?`'${e}'`:typeof e=="object"&&e!==null?JSON.stringify(e):String(e),Is=(e,t)=>{let r="coerceType"in e?e.coerceType:void 0,n=r??t;if(n===void 0||n===A.Json)return [];let o="operator"in e?e.operator:e.dateOperator,i=Vn(e);if(!i)return [];let a=r!==void 0&&r!==t?`field '${e.field}' coerced to ${n}`:`${n} field '${e.field}'`;if(!i.kinds.includes(n))return [{path:e.field,code:"operator_kind_mismatch",message:`operator '${o}' does not apply to ${a} (applies to: ${i.kinds.join(", ")})`}];if(e.offset!==void 0&&!("dateOperator"in e?n===A.DateTime:G.includes(n)))return [{path:e.field,code:"invalid_offset",message:`an offset does not apply to ${a}`}];if("dateOperator"in e||i.valueShape==="none"||i.valueShape==="pattern")return [];if(ru.includes(i.valueShape)&&Array.isArray(e.value))return [{path:e.field,code:"invalid_value_shape",message:`operator '${o}' compares one value, but ${a} was given a list`}];let{expected:l,fits:p}=OE[n],d=u=>{try{return p(Yt(u,n))}catch{return false}},f=u=>p(u)||r!==void 0&&d(u);return (Yo(e)??[]).filter(u=>u!==null&&!f(u)).map(u=>({path:e.field,code:"invalid_value",message:`value ${EE(u)} does not fit ${a} (expected ${l})`}))},yc=(e,t,r)=>{if(r.isList===true||Fe(r))return null;let n=_(r)?`arrayOperator '${t}' needs a list, but '${e}' is a to-one relation \u2014 a single related record; address its fields directly (e.g. '${e}.<field>')`:`arrayOperator '${t}' needs a list, but '${e}' is a single ${ze(r)??r.type} value`;return {path:e,code:"invalid_array_operator",message:n}};var xE=(e,t,r,n)=>J(e,(o,i)=>{let s=de(o);if(s===null)return n.push({path:typeof o.field=="string"?o.field:"",code:"ambiguous_condition",message:$t().message}),false;if(Ke(o))return;let a=o,l=S=>{let b=He(S,i);return "outOfBounds"in b?(n.push({path:S,code:"scope_out_of_bounds",message:b.outOfBounds}),null):{scope:b.scope,field:b.path}},p=i[i.length-1],d=true,f=null;if("field"in a&&typeof a.field=="string"&&a.field!==""){let S=ho(t,i,a.field);"issue"in S?(n.push({path:a.field,...S.issue}),d=false):{next:p,walked:f}=S;}let u=f?.entry??null,c=f?.terminalFieldName??null,y=f?.entry.kind==="enum",m=f?.entry.type??null,g=f&&f.jsonSubPath.length===0?Bs(f.terminalEffect,f.terminalFieldName):null;for(let{ref:S,role:b}of Wo(a)){let w=L(S)?l(S):{scope:Mt(t),field:S};if(!w||w.scope.open)continue;let R=yo(t,w.scope,w.field);if(!R){n.push({path:S,...qs(t,w.scope,w.field,b==="value"?"path (comparison ref) does not resolve through the narrowed lens":"offset or magnitude ref does not resolve through the narrowed lens")});continue}if(_(R.entry)){n.push({path:S,code:"not_in_lens",message:"a value ref reads a column, not a relation"});continue}let O=ze(R.entry);if(b==="value"||b==="shift"||O===void 0)continue;(b==="whole"?Xf.includes(O):G.includes(O))||n.push({path:S,code:"not_in_lens",message:`${b==="whole"?"a calendar unit reads a whole number":"an offset or magnitude reads a number"}, not ${O}`});}if(!d)return false;if("arrayOperator"in a&&typeof a.field=="string"&&u){let S=yc(a.field,a.arrayOperator,u);if(S)return n.push(S),false}if(u&&_(u)&&(s==="field"||s==="date")&&(u.isList||!Xt(a))){let S=a.field;return n.push({path:S,code:"operator_kind_mismatch",message:(u.isList?ps(S):mr(S)).message}),false}if(!u?.isList&&(s==="field"||s==="date")&&n.push(...Is(a,u?ze(u):void 0)),!p.open)for(let S of eo(a))S!==""&&!yo(t,p,S)&&n.push({path:S,...qs(t,p,S,"an orderBy or aggregate field does not resolve through the narrowed lens")});if(g&&"operator"in a&&c){let S=Yo(a);if(S){let b=new Set(g),w=y?`enum '${m}'`:`field '${c}'`;for(let R of S)typeof R=="string"&&!b.has(R)&&n.push({path:c,code:"value_not_allowed",message:`value '${R}' is not in the allowed set for ${w} (allowed: ${[...b].join(", ")})`});}}return [...i,p]},[r]),Xo=(e,t,r,n,o)=>{let i=[];return xE(e,t,{mapName:r,modelName:n,relPath:o,open:false},i),i},Pr=(e,t)=>{let r=F(t);try{let n=Xo(e,r,r.lens.mapName,r.lens.model,[]);return n.length===0&&go(e,t),rt(n)}catch(n){if(!(n instanceof T))throw n;return rt([{path:"",code:n.code,message:n.message}])}};var ri=e=>e===void 0?void 0:Array.isArray(e)?e:[e],ni=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&("where"in e||"label"in e||"groupBy"in e||"from"in e),kr=e=>{if(ni(e))return e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===0)throw $E();return {where:e}},$E=()=>new T("sources: {} is not a Condition \u2014 use `true` for an unconstrained source","invalid_source"),Rl=["__offpath__"],hc=new WeakMap,vE=(e,t)=>{if(!t)return new Map;let r=JSON.stringify([ei(t.parent),ei(e.maps),e.mapName,e.model,t.mapDefaults??null]),n=hc.get(t);if(n?.fingerprint===r)return n.trees;let o=new Map;return hc.set(t,{fingerprint:r,trees:o}),o},wc=new WeakMap,AE=0,ei=e=>{let t=wc.get(e);return t===void 0&&(t=AE++,wc.set(e,t)),t},be="\0",NE=e=>{let t=Object.entries(e.fields);return {relations:new Set(t.filter(([,r])=>_(r)).map(([r])=>r)),gated:t.filter(([,r])=>r.options!==void 0||r.kind==="enum"||r.values!==void 0)}},Ws=e=>e?String(ei(e)):"",F=e=>{let t=ft(e),r=dt(e)?[]:Lt(e);return {lens:t,chain:r,origin:r[0],memo:{trees:vE(t,r[0]),vetted:new Set,effects:new Map,places:new Map,models:new Map,refs:new Map,compiles:new Map}}},Us=(e,t)=>e===null?new Set(t):new Set(t.filter(r=>e.has(r))),PE=(e,t)=>{if(t.picks&&(e.picks=Us(e.picks,t.picks)),t.omits)for(let r of t.omits)e.omits.add(r);},Rc=(e,t,r)=>{e.set(t,Us(e.get(t)??null,r));},Oc=(e,t,r)=>{let n=e.get(t)??new Set;for(let o of r)n.add(o);e.set(t,n);},kE=(e,t,r)=>{if(r.enumPicks)for(let[n,o]of Object.entries(r.enumPicks))Rc(e,n,o);if(r.enumOmits)for(let[n,o]of Object.entries(r.enumOmits))Oc(t,n,o);},Sl=(e,t,r)=>JSON.stringify([e,t,r]),TE=(e,t,r,n,o,i,s,a)=>{if(s&&PE(e,t),t.where!==void 0&&i&&(o(t.where),e.whereClauses.push(r(t.where)),(a?e.modelWheres:e.pathWheres).push({where:t.where,layer:n})),t.sources)for(let[l,p]of Object.entries(t.sources)){let d=kr(p),f=e.sources.get(l)??[],u=e.sourceWheres.get(l)??[];d.where!==void 0&&i&&(o(d.where,true),f.push(r(d.where)),u.push(d.where)),e.sources.set(l,f),e.sourceWheres.set(l,u);let c=ri(d.groupBy);for(let[y,m,g]of [["label",d.label,e.sourceLabels.get(l)],["groupBy",c,e.sourceGroupBys.get(l)]]){if(m===void 0)continue;let S=Sl(l,y,m);g!==void 0&&Sl(l,y,g)===S||e.sourceDeclaredAt.set(S,n);}d.label!==void 0&&e.sourceLabels.set(l,d.label),c!==void 0&&e.sourceGroupBys.set(l,c),d.from==="mapDefaults"&&!e.sourcesFromMapDefaults.has(l)&&e.sourcesFromMapDefaults.set(l,n);}},T=class extends Error{constructor(r,n){super(r);this.code=n;}code;name="LensRefusal"},Ol=e=>new T(`a bare path ('${e}') reads the root row, which a clamp at a relation visit or a model default doesn't stand on: use a literal, a bind, or a \`$\` scope ref`,"invalid_value_source"),CE=(e,t,r)=>Xo(e,t,r.mapName,r.modelName,r.relPath),LE=e=>new T(`a later layer's clamp reads what its parent does not show: '${e.path}' ${e.message}`,e.code),El=e=>new T(`the scope ref '${e}' climbs out of the clamp: a clamp reads its own row ('$.'), literals and binds`,"scope_out_of_bounds"),co=e=>{let t=null,r=null;return J(e,(n,o)=>{if(Ke(n))return;let i=wr(n);for(let s of [...typeof n.field=="string"?[n.field]:[],...i]){let a=L(s);r===null&&a&&a.depth>o&&(r=s);}for(let s of i)t===null&&!L(s)&&(t=s);return xe(n)?o+1:void 0},1),{bare:t,escaping:r}},bl=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},n=[r];if(t.relPath.length>0)for(let i of Ce(e.lens.maps,r,t.relPath.join(".")).hops)n.push({mapName:i.map,modelName:i.model,relPath:i.relPath});let o=n[n.length-1];return n.length===t.relPath.length+1&&o.mapName===t.mapName&&o.modelName===t.modelName?n:null},ti=(e,t)=>{let r=e;for(let n of t)r=E(r?.relations,n);return r},xl=(e,t,r)=>{let n=i=>E(E(e.mapDefaults,i.mapName)?.models,i.modelName);if(!r){let i=n(t);return {defaults:i?[i]:[],path:void 0}}let o=[];for(let[i,s]of r.entries()){let a=ti(n(s),t.relPath.slice(i));a&&o.push(a);}return {defaults:o,path:ti(e.root,t.relPath)}},ME=(e,t,r,n)=>{let o=ti(t.root,r.relPath),i=[r.relPath.join(be),Object.keys(o?.relations??{}).join(be),(o?.omits??[]).join(be)].join(`${be}${be}`),s=n.get(i);if(s)return s;let a=new Map,l={lens:e},p=bl(l,r)??[r],d=new Set(p.map(u=>`${u.mapName}:${u.modelName}`)),f=[{at:r,below:[]}];for(;f.length>0;){let{at:u,below:c}=f.shift(),y=C(E(e.maps,u.mapName),u.modelName)?.fields??{},{defaults:m,path:g}=xl(t,u,bl(l,u)),S=new Set(m.flatMap(R=>Object.keys(R.relations??{}))),b=new Set([...m,...g?[g]:[]].flatMap(R=>R.omits??[])),w=[];for(let[R,O]of Object.entries(y)){if(!S.has(R)||b.has(R)||g?.relations!==void 0&&Object.hasOwn(g.relations,R))continue;let $=lt(O,u.mapName);if(!$||!C(E(e.maps,$.mapName),$.modelName))continue;let k=`${$.mapName}:${$.modelName}`;d.has(k)||(d.add(k),w.push(R),f.push({at:{...$,relPath:[...u.relPath,R]},below:[...c,R]}));}a.set(c.join("."),w);}return n.set(i,a),a},_E=(e,t,r,n)=>{if(!n)return xl(t,r,null).defaults.flatMap(p=>Object.keys(p.relations??{}));let o=r.relPath.length;for(;o>0&&ti(t.root,r.relPath.slice(0,o))===void 0;)o--;let i={...n[o],relPath:r.relPath.slice(0,o)},a=ME(e.lens,t,i,e.memo?.trees??new Map).get(r.relPath.slice(o).join("."))??[];return [...o===r.relPath.length?Object.keys(ti(t.root,r.relPath)?.relations??{}):[],...a]},oi=(e,t,r)=>{let n=t;for(let o of Ce(e.lens.maps,t,r).hops){let i=o.relPath[o.relPath.length-1];if(!I(e,n.mapName,n.modelName,n.relPath).relations.has(i))return o.prefix;n={mapName:o.map,modelName:o.model,relPath:o.relPath};}return null},I=(e,t,r,n)=>{let o=e.memo?Sc(e,t,r,n):null,i=o===null?void 0:e.memo?.effects.get(o);if(i){if(!e.unvetted&&i.unchecked){for(let q of i.unchecked)q();i.unchecked=null;}return i.effect}let s=[],a={picks:null,omits:new Set,enumValuesByField:new Map,whereClauses:[],pathWheres:[],modelWheres:[],sources:new Map,sourceWheres:new Map,sourceLabels:new Map,sourceGroupBys:new Map,sourceDeclaredAt:new Map,sourcesFromMapDefaults:new Map,relations:new Set,relationFields:new Set},l=E(e.lens.maps,t),p=C(l,r);if(!p)return a;let d=e.memo?.models.get(p);d||(d=NE(p),e.memo?.models.set(p,d)),a.relationFields=d.relations;let f={mapName:t,modelName:r,relPath:n},u=e.origin??e.chain[0],c=`${Ws(u)}${be}${t}${be}${r}${be}${n.join(be)}`,y=e.memo?.places.get(c);if(!y){let q=bl(e,f);y={trail:q,turnedOn:u?_E(e,u,f,q):[]},e.memo?.places.set(c,y);}let{trail:m}=y,g=new Map,S=new Map,b=new Map,w=new Map,R=q=>q,O=0,$=()=>{},k=true,le=true,P=(q,W=false)=>{TE(a,q,R,O,$,k,le,W),kE(g,S,q);};for(let[q,W]of e.chain.entries()){O=q;let Mr={...e,clamp:false,skipClampsOf:void 0,skipHidingOf:void 0,chain:e.chain.slice(0,q)};k=W!==e.skipClampsOf,le=W!==e.skipHidingOf,R=oe=>q===0?oe:tn(oe,Mr,{mapName:t,modelName:r,relPath:n});for(let[oe,Re]of Object.entries(E(W.mapDefaults,t)?.enums??{}))Re.picks&&Rc(b,oe,Re.picks),Re.omits&&Oc(w,oe,Re.omits);let{defaults:xo,path:_r}=xl(W,f,m),ye=q===0?null:Mr,gt=oe=>(Re,Oe=false)=>{let Le=e.memo?.refs.get(Re);if(Le||(Le=co(Re),e.memo?.refs.set(Re,Le)),Le.bare!==null&&!(oe&&!Oe))throw Ol(Le.bare);if(Le.escaping!==null)throw El(Le.escaping);if(!ye)return;let ip=()=>{let hi=typeof Re=="object"&&Re!==null?`${ei(Re)}${be}${Sc(ye,t,r,n)}`:null;if(hi!==null&&ye.memo?.vetted.has(hi))return;let[sp]=CE(Re,ye,f);if(sp)throw LE(sp);hi!==null&&ye.memo?.vetted.add(hi);};e.unvetted?s.push(ip):ip();};$=gt(false);let pn=E(E(W.mapDefaults,t)?.models,r);for(let oe of xo)P(oe,oe===pn);_r&&($=gt(n.length===0&&m!==null),P(_r));}if(u&&e.chain.includes(u))for(let q of y.turnedOn)a.relationFields.has(q)&&!a.omits.has(q)&&a.relations.add(q);for(let[q,W]of d.gated){let Mr=W.kind==="enum",_r=W.options?.map(oe=>oe.value)??(Mr?Jr(W,l?.enums):W.values);if(!_r)continue;let ye=_r;if(Mr){let oe=b.get(W.type),Re=w.get(W.type);oe&&(ye=ye.filter(Oe=>oe.has(Oe))),Re&&(ye=ye.filter(Oe=>!Re.has(Oe)));}let gt=g.get(q),pn=S.get(q);gt&&(ye=ye.filter(oe=>gt.has(oe))),pn&&(ye=ye.filter(oe=>!pn.has(oe))),a.enumValuesByField.set(q,ye);}return o!==null&&e.memo?.effects.set(o,{effect:a,unchecked:s.length?s:null}),a},Sc=(e,t,r,n)=>{let o=bc.get(e);if(o===void 0){o=`${Ws(e.origin)}${be}${Ws(e.skipClampsOf)}${be}${Ws(e.skipHidingOf)}${be}`;for(let i of e.chain)o+=`${ei(i)},`;bc.set(e,o);}return `${o}${be}${t}${be}${r}${be}${n.join(be)}`},bc=new WeakMap,tr=e=>{let t=[],r=(n,o)=>{let i=E(e.lens.maps,n.mapName);if(!C(i,n.modelName))return;let s=I(e,n.mapName,n.modelName,n.relPath);t.push({path:o,at:n,effect:s});for(let a of s.relations){let l=ge(i,n.modelName,a),p=l&&lt(l,n.mapName);p&&r({...p,relPath:[...n.relPath,a]},`${o}.${a}`);}};return r({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},e.lens.model),t},Ks=(e,t,r,n)=>I(e,t,r,Rl).sources.has(n),Gs=(e,t,r,n)=>new T(`source '${n}' at '${e}' offers mapDefaults.${t}.models.${r}.sources.${n}, which no layer declares`,"invalid_source"),_t=(e,t)=>e.omits.has(t)?false:e.relationFields.has(t)?e.relations.has(t):!(e.picks!==null&&!e.picks.has(t)),Bs=(e,t)=>e.enumValuesByField.get(t)??null,rn=(e,t,r)=>{let n=r.split("."),o=[],i=[];for(let{index:s,field:a,at:l,entry:p,next:d}of Rr(e.lens.maps,t,r)){if(!p)return {resolution:{outcome:"missing",index:s,hops:o},effects:i};let f=I(e,l.mapName,l.modelName,l.relPath);if(!(e.clamp&&_(p)?!f.omits.has(a):_t(f,a)))return {resolution:{outcome:"hidden",index:s,hops:o},effects:i};let c={field:a,entry:p,mapName:l.mapName,model:l.modelName,relPath:[...l.relPath]};o.push(c),i.push(f);let y=s===n.length-1;if(y||Fe(p))return {resolution:{outcome:"resolved",hops:o,terminal:c,jsonSubPath:y?[]:n.slice(s+1)},effects:i};if(!d)return {resolution:{outcome:"pastScalar",index:s,hops:o},effects:i}}return {resolution:{outcome:"missing",index:n.length,hops:o},effects:i}},wo=(e,t,r,n,o)=>{let i=o==="label"?t.sourceLabels.get(n):t.sourceGroupBys.get(n);if(i===void 0)return true;let s=t.sourceDeclaredAt.get(Sl(n,o,i)),a=(d,f)=>rn(d,r,f).resolution.outcome!=="hidden",l={...e,clamp:true},p={...l,skipHidingOf:s===void 0?void 0:e.chain[s]};return (typeof i=="string"?[i]:i).every(d=>oi(e,r,d)===null&&(a(l,d)||a(p,d)))},yo=(e,t,r)=>{let{resolution:n,effects:o}=rn(e,t,r);if(n.outcome!=="resolved")return null;let{terminal:i,jsonSubPath:s}=n;return {mapName:i.mapName,modelName:i.model,relPath:i.relPath,entry:i.entry,terminalEffect:o[o.length-1],terminalFieldName:i.field,jsonSubPath:s}},qs=(e,t,r,n)=>{let{resolution:o}=rn(e,t,r);if(o.outcome!=="hidden")return {code:"not_in_lens",message:n};let i=r.split("."),s=o.hops.at(-1),a=s?{mapName:s.mapName,modelName:s.model,relPath:[...s.relPath,s.field]}:t,l=s&&lt(s.entry,s.mapName),p=l?{...l,relPath:a.relPath}:t,d=I(e,p.mapName,p.modelName,p.relPath),f=i[o.index];return !d.relationFields.has(f)||d.omits.has(f)?{code:"not_in_lens",message:n}:{code:"not_in_lens",message:`'${i.slice(0,o.index+1).join(".")}' is a relation the lens does not turn on (turn it on with \`relations\`)`}},Mt=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[],open:false}),ho=(e,t,r)=>{let n=He(r,t);if("outOfBounds"in n)return {issue:{code:"scope_out_of_bounds",message:n.outOfBounds}};if(n.scope.open)return {from:n.scope,next:n.scope,walked:null};let o=yo(e,n.scope,n.path);if(!o)return {issue:qs(e,n.scope,n.path,"path does not resolve through the narrowed lens")};let i=Fe(o.entry),s=lt(o.entry,o.mapName),a=s?{...s,relPath:[...o.relPath,o.terminalFieldName],open:i}:{...n.scope,open:i};return {from:n.scope,next:a,walked:o}},Ce=(e,t,r,n="")=>{let o=r.split("."),i=[],s=null;for(let{index:a,field:l,at:p,entry:d,next:f}of Rr(e,t,r)){if(!d||!f)break;let u=[...p.relPath,l];i.push({map:f.mapName,model:f.modelName,relPath:u,prefix:`${n}${o.slice(0,a+1).join(".")}`,isList:d.isList===true}),a===o.length-1&&(s={...f,relPath:[...u]});}return {hops:i,end:s}};var zs=(e,t)=>{let r=F(e);return rn(r,Mt(r),t).resolution};var nn=class extends Error{constructor(r){super(`inferValueType: ${r.path}: ${r.message}`);this.issue=r;}issue},ee=(e,t,r)=>{throw new nn({path:e,code:t,message:r})};var Hs=(e,t)=>{let r=L(e);return r?(r.depth>1&&ee(t,"scope_out_of_bounds",`'${e}' reaches past the row a value expression reads`),r.path):e},Js=(e,t)=>{if(!e)throw new M(`inferValueType needs a lens to type ${t}`);return e},ii=(e,t,r)=>{let n=zs(e,t);if(n.outcome!=="resolved")return ee(r,"unresolved_path",`'${t}' does not resolve through the lens (${n.outcome})`);let o=n.hops.slice(0,-1).find(i=>_(i.entry)&&i.entry.isList);return {entry:n.terminal.entry,viaList:o?o.field:null,json:n.jsonSubPath.length>0||n.terminal.entry.type===A.Json}},si=e=>e.json?A.Json:ze({...e.entry,isList:false})??null;var Zs={kind:null,isList:false,nullable:true},DE={kind:null,isList:false,nullable:false},Qs=e=>e!==null&&G.includes(e),Ec=e=>`${e.kind??"null"}${e.isList?"[]":""}`,Ys=(e,t,r)=>{let n=e.nullable||t.nullable;if(e.kind===null&&e.isList===t.isList)return {...t,nullable:n};if(t.kind===null&&e.isList===t.isList)return {...e,nullable:n};if(e.kind===null&&!e.isList)return {...t,nullable:true};if(t.kind===null&&!t.isList)return {...e,nullable:true};if(e.isList===t.isList){if(e.kind===t.kind)return {...e,nullable:n};if(Qs(e.kind)&&Qs(t.kind))return {kind:e.kind===A.Decimal||t.kind===A.Decimal?A.Decimal:A.Float,isList:e.isList,nullable:n}}return ee(r,"value_type_mismatch",`the values here are ${Ec(e)} and ${Ec(t)}`)},Xs=(e,t)=>({...e.reduce((r,n)=>Ys(r,n,t),DE),isList:true});var FE={String:["String","Boolean","DateTime",...G],DateTime:["DateTime","String",...G],Boolean:["Boolean","String"],Enum:["String"],...Object.fromEntries(G.map(e=>[e,["String","DateTime",...G]]))},$l=(e,t)=>e===null||e===t||FE[e]?.includes(t)===true,vl=(e,t)=>`${e} values can't be read as ${t}`,jE=(e,t,r)=>{$l(e,t)||ee(r,"coerce_kind_mismatch",vl(e,t));},xc=(e,t,r)=>{let n=Hs(t.field,`${r}.field`),o=ii(e,n,`${r}.field`);return (o.viaList||o.entry.isList!==true)&&ee(`${r}.field`,"aggregate_needs_list",`'${t.field}' is not a list; an aggregate reads a list`),{field:n,list:o}},VE=(e,t,r)=>{let{field:n,list:o}=xc(e,t,r),i=t.aggregate.field;if(!_(o.entry))return i!==void 0&&ee(`${r}.aggregate.field`,"invalid_aggregate_field",`'${t.field}' holds values, not rows`),si(o);if(i===void 0)return ee(`${r}.aggregate.field`,"aggregate_field_required",`${t.aggregate.mode} over rows names the field it reads`);let s=ii(e,`${n}.${i}`,`${r}.aggregate.field`);return (_(s.entry)||s.entry.isList)&&ee(`${r}.aggregate.field`,"invalid_aggregate_field",`'${i}' is not one value per row`),si(s)},$c=(e,t,r)=>{let n=t.aggregate.mode;if(Fn[n].result==="count")return e&&xc(e,t,r),{kind:A.Int,isList:false,nullable:false};let o=VE(Js(e,`${n} over '${t.field}'`),t,r),i=n==="sum"||n==="avg",s=i&&o===A.Json?null:o;t.coerceType!==void 0&&jE(s,t.coerceType,`${r}.coerceType`);let a=t.coerceType??o,l=`${r}.aggregate.field`;return i?(Qs(a)||ee(l,"aggregate_kind_mismatch",`${n} adds numbers, not ${a??"untyped"} values`),{kind:n==="sum"||a===A.Decimal?a:A.Float,isList:false,nullable:n==="avg"}):n==="distinct"?((a===null||!Bf.includes(a))&&ee(l,"aggregate_kind_mismatch",`distinct lists strings, enums, dates, booleans and numbers, not ${a??"untyped"} values`),{kind:a,isList:true,nullable:false}):((a===null||!qf.includes(a))&&ee(l,"aggregate_kind_mismatch",`${n} orders numbers and dates, not ${a??"untyped"} values; read strings with coerceType`),{kind:a,isList:false,nullable:true})};var rt=e=>({ok:e.length===0,errors:e}),sn=(e,t)=>{if(!e.ok)throw new Error(`${t}:
2
2
  ${e.errors.map(r=>`${r.path}: ${r.message}`).join(`
3
- `)}`)},vr=(e,t={})=>{let r=tl(t);return tr(e,"$",r,1),t.positive&&ZO(e,r),et(r.errors)},tl=(e={})=>({target:e.target??"check",errors:[],map:ke(e.map,e.mapName,"toPrisma"),scopeModels:[e.model],stepScopes:[false]}),Xu=e=>{let t=tl(),r=pt(e)?ic(e,"$",t,1):null;r&&!ts(r.mode)&&v(t,"$.aggregate.mode","invalid_aggregate_mode",us(r.mode).message);let n=pt(e)?e:{},o=r?.mode;return n.coerceType!==void 0&&(ko(n.coerceType)?["distinct","min","max"].includes(o)||v(t,"$.coerceType","unexpected_coerce_type","coerceType reads the values distinct, min and max return"):v(t,"$.coerceType","invalid_coerce_type",`coerceType must be one of: ${Object.keys(N).join(", ")}`)),n.caseInsensitive!==void 0&&(typeof n.caseInsensitive!="boolean"?v(t,"$.caseInsensitive","invalid_case_insensitive","caseInsensitive must be a boolean"):o!=="distinct"&&v(t,"$.caseInsensitive","unexpected_case_insensitive","caseInsensitive folds the strings distinct returns")),et(t.errors)},ec=e=>{let t=tl();return pt(e)&&en(e,"$",t,1),et(t.errors)},QO=["if","array","aggregate"],ZO=(e,t)=>H(e,r=>{let n=pe(r),o=r.operator??r.dateOperator;return (n&&QO.includes(n)||typeof o=="string"&&ns.includes(o))&&v(t,"$","notPositive",`${n==="field"||n==="date"?o:n} can hold on a missing value`),false}),YO=(e,t={})=>{tn(vr(e,t),"validateRule");},tr=(e,t,r,n)=>{if(typeof e=="boolean")return;if(!pt(e)){v(r,t,"invalid_condition","Condition must be a boolean or object");return}let o=pe(e);if(!o){v(r,t,"ambiguous_condition",vt().message);return}switch(o){case "all":Qu(e.all,`${t}.all`,r,n);break;case "any":Qu(e.any,`${t}.any`,r,n);break;case "if":tr(e.if,`${t}.if`,r,n),tr(e.then,`${t}.then`,r,n),"else"in e&&e.else!==void 0&&tr(e.else,`${t}.else`,r,n);break;case "field":XO(e,t,r,n);break;case "aggregate":rE(e,t,r,n);break;case "array":nE(e,t,r,n);break;case "date":oE(e,t,r,n);break}},Qu=(e,t,r,n)=>{if(!Array.isArray(e)){v(r,t,"logical_array_required","Logical operator requires an array of conditions");return}e.forEach((o,i)=>{tr(o,`${t}[${i}]`,r,n);});},Ls=(e,t,r,n)=>{typeof e.field=="string"&&tc(e.field,"field",`${t}.field`,r,n);},tc=(e,t,r,n,o,i=false)=>{let s=_(e)??(t==="path"?{depth:o}:null);if(!s)return;let a=t==="field"?"Field":"Path";s.depth>o&&v(n,r,"scope_out_of_bounds",ka(e,s.depth,o)),n.target==="toPrisma"&&!i?v(n,r,`unsupported_prisma_${t}`,t==="path"?`Path '${e}' compares to a column, which isn't supported on the Prisma rail; use toSql() or check()`:`${a} '${e}' is not supported by toPrisma()`):n.target==="toSql"&&(t==="field"||s.depth>1)&&v(n,r,`unsupported_sql_${t}`,`${a} '${e}' is not supported by toSql()`);},Cs=(e,t,r,n=false)=>{e.stepScopes[t]=n||e.stepScopes[t-1]===true;let o=e.scopeModels[t-1];e.scopeModels[t]=e.map&&o&&typeof r=="string"?zo(r,e.map,o)??void 0:void 0;},en=(e,t,r,n,o=false)=>{let i=ru.filter(a=>e[a]!==void 0);if(i.length>1)return v(r,t,"ambiguous_value_source","Takes one of value, path or bind"),null;if(i.length===0)return v(r,t,"missing_value_source","Requires value, path or bind"),null;let[s]=i;return s!=="value"&&(typeof e[s]!="string"||e[s]==="")?(v(r,`${t}.${s}`,"invalid_value_source",`${s} is a non-empty string`),null):(e.bindOptional!==void 0&&(s!=="bind"||typeof e.bindOptional!="boolean")&&v(r,`${t}.bindOptional`,"invalid_value_source","bindOptional is a boolean beside bind"),s==="path"&&tc(e.path,"path",`${t}.path`,r,n,o),s)},rc=(e,t,r,n,o,i)=>{let{offset:s}=e;if(s===void 0)return;let a=`${n}.offset`;if(!jd.includes(r)){v(o,a,"unsupported_offset_operator",`Operator '${r}' has no comparison point to offset`);return}if(!pt(s)){v(o,a,"invalid_offset","An offset is one of { value }, { path } or { bind }");return}let l=en(s,a,o,i);if(l==="path"){let d=s.path,u=Ir(s);t==="date"&&u&&u.depth<=1&&o.target==="toSql"&&v(o,`${a}.path`,"unsupported_sql_path",`A row path on a date offset ('${d}') is not supported by toSql()`);return}if(l!=="value")return;let p=s.value;if(t==="field"){(typeof p!="number"||!Number.isFinite(p))&&v(o,`${a}.value`,"invalid_offset","A field offset value is a number");return}let f=pt(p)&&Object.keys(p).length===1&&ee(p)?Oe(p):null;if(!f){v(o,`${a}.value`,"invalid_offset","A date offset value is { ago } or { ahead }");return}sc(f[0],`${a}.value.${Object.keys(p)[0]}`,o,i);},nc=(e,t,r,n)=>{n.target!=="toSql"||!Je.includes(t)||Ir(e)&&v(n,`${r}.path`,"unsupported_sql_path",`A range read from the row ('${e.path}') is not supported by toSql()`);},XO=(e,t,r,n)=>{if(typeof e.field!="string"&&v(r,`${t}.field`,"field_required","Field rule requires a string field"),Ls(e,t,r,n),typeof e.operator!="string"||!Gt(e.operator,"field")){v(r,`${t}.operator`,"invalid_operator",ue(e.operator,"field").message);return}let o=e.operator;rc(e,"field",o,t,r,n),Xi(o,"field",r.target)||v(r,`${t}.operator`,`unsupported_${Ms(r.target)}_operator`,`Operator '${o}' is not supported by ${r.target}()`),e.coerceType!==void 0&&!ko(e.coerceType)&&v(r,`${t}.coerceType`,"invalid_coerce_type",`coerceType must be one of: ${Object.keys(N).join(", ")}`);let i=Ht(o,"field");if(i==="none"){ac(e,t,r);return}if(en(e,t,r,n,true)!==null){if(nc(e,o,t,r),r.target==="toPrisma"&&typeof e.path=="string"){let s=Ps(e,r.map,r.scopeModels[n-1],n>1,r.stepScopes[n-1]===true);"problem"in s&&v(r,`${t}.path`,"unsupported_prisma_path",ks(e.path,s.problem).message);}if(r.target==="toSql"&&typeof e.path=="string"&&r.map){let s=r.scopeModels[n-1],a=(_(e.path)??{path:e.path}).path,l=no(te(e.field,r.map,s),te(a,r.map,s),o);l&&v(r,`${t}.path`,"unsupported_sql_path",`'${e.path}': ${l}`);}r.target==="toSql"&&typeof e.path=="string"&&["array","pattern","string"].includes(i)&&((r.map?te(e.field,r.map,r.scopeModels[n-1]):void 0)?.isList&&Et.includes(o)||v(r,`${t}.path`,"unsupported_sql_path",`'${o}' against the column '${e.path}' has no SQL form`)),!(typeof e.path=="string"||typeof e.bind=="string")&&(eE(e,o,t,r,n),tE(i,e.value,o,`${t}.value`,r));}},eE=(e,t,r,n,o)=>{if(n.target!=="toPrisma"||!n.map||typeof e.field!="string")return;let i=te(e.field,n.map,n.scopeModels[o-1]);if(!i)return;let s=e.value,a=oe(e.caseInsensitive),l=cr.includes(t)&&Array.isArray(s),p=f=>v(n,`${r}.value`,"unsupported_prisma_operator",I("toPrisma",f).message);i.isList&&!l&&Array.isArray(s)&&s.includes(null)?p(`A list holding null in '${e.field}'`):i.isList&&!l&&a&&xr("text",s)?p(`A case-insensitive comparison on the list '${e.field}'`):Ue(i)&&a&&p(`A case-insensitive comparison on the Json column '${e.field}'`);},tE=(e,t,r,n,o)=>{switch(e){case "scalar":case "string":e==="string"&&typeof t!="string"&&v(o,n,"invalid_string_value",`Operator '${r}' requires a string value`);return;case "ordered":ye(t)||v(o,n,"invalid_ordered_value",`Operator '${r}' requires a string, number, or Date value`);return;case "array":Array.isArray(t)||v(o,n,"invalid_membership_value",`Operator '${r}' requires an array value`);return;case "pattern":{if(!(typeof t=="string"||t instanceof RegExp)){v(o,n,"invalid_pattern_value",`Operator '${r}' requires a string or RegExp value`);return}let i=hu(t,o.target);i&&v(o,n,"unsupported_pattern",i);return}case "range":try{Yn(t,r);}catch(i){v(o,n,"invalid_range_value",i.message);}return}},oc=(e,t,r,n,o)=>{let i=r.scopeModels[n-1];if(!(r.target!=="toPrisma"||!r.map||!i||typeof e.field!="string"))try{so(e.field,r.map,i,o);}catch(s){v(r,`${t}.field`,"unsupported_prisma_relation",s.message);}},ic=(e,t,r,n)=>{if(oc(e,t,r,n,"Aggregate rules"),e.offset!==void 0&&v(r,`${t}.offset`,"unexpected_offset","Aggregate rules take no offset"),lc(e,t,r,n),typeof e.field!="string"&&v(r,`${t}.field`,"field_required","Aggregate rule requires a string field"),Ls(e,t,r,n),!pt(e.aggregate))return v(r,`${t}.aggregate`,"invalid_aggregate","aggregate must be an object"),null;let o=e.aggregate;return "field"in o&&o.field!==void 0&&typeof o.field!="string"&&v(r,`${t}.aggregate.field`,"invalid_aggregate_field","aggregate.field must be a string"),"condition"in e&&e.condition!==void 0&&(r.target==="toSql"&&v(r,`${t}.condition`,"unsupported_sql_aggregate_condition","Aggregate condition filtering is not supported by toSql(); use check() or toPrisma()"),Cs(r,n,e.field,true),tr(e.condition,`${t}.condition`,r,n+1)),o},rE=(e,t,r,n)=>{let o=ic(e,t,r,n);if(!o)return;if(xt.includes(o.mode)||v(r,`${t}.aggregate.mode`,"invalid_aggregate_mode",gr(o.mode).message),!es.includes(e.operator)){v(r,`${t}.operator`,"invalid_aggregate_operator",`Aggregate rules only support: ${es.join(", ")}`);return}if(He.includes(e.operator)){ac(e,t,r);return}if(r.target==="toPrisma"&&typeof e.path=="string"&&v(r,`${t}.path`,"unsupported_prisma_aggregate_path","path is not supported by toPrisma() for aggregate rules; use value instead"),en(e,t,r,n)===null||typeof e.path=="string"||typeof e.bind=="string")return;let i=e.value;Je.includes(e.operator)?iE(i)||v(r,`${t}.value`,"invalid_range_value",`Operator '${e.operator}' requires a two-item numeric range`):typeof i!="number"&&v(r,`${t}.value`,"invalid_aggregate_value","Aggregate rule value must be a number");},nE=(e,t,r,n)=>{if(typeof e.field!="string"&&r.target!=="check"&&v(r,`${t}.field`,"field_required","Array rule requires a string field for this target"),Ls(e,t,r,n),lc(e,t,r,n),typeof e.arrayOperator!="string"||!Gt(e.arrayOperator,"array")){v(r,`${t}.arrayOperator`,"invalid_array_operator",ue(e.arrayOperator,"array").message);return}let o=e.arrayOperator;Lo(e)&&oc(e,t,r,n,"Count operators");let i=r.target==="toPrisma"&&r.map&&typeof e.field=="string"?te(e.field,r.map,r.scopeModels[n-1]):void 0;i&&!M(i)&&o!=="empty"&&o!=="notEmpty"&&v(r,`${t}.arrayOperator`,"unsupported_prisma_array_operator",I("toPrisma",`'${o}' over the array column '${e.field}'`).message),Xi(o,"array",r.target)||v(r,`${t}.arrayOperator`,`unsupported_${Ms(r.target)}_array_operator`,`Array operator '${o}' is not supported by ${r.target}()`);let s=Ht(o,"array"),a=e.condition!==void 0,l=()=>{e.count!==void 0&&v(r,`${t}.count`,"unexpected_count",`Array operator '${o}' does not accept count`);};s==="none"?(a&&v(r,`${t}.condition`,"unexpected_condition",`Array operator '${o}' does not accept condition`),l()):s==="predicate"?(a?(Cs(r,n,e.field),tr(e.condition,`${t}.condition`,r,n+1)):v(r,`${t}.condition`,"missing_condition",Ie(o).message),l()):s==="count"&&(typeof e.count!="number"?v(r,`${t}.count`,"missing_count",Bn(o).message):e.count!==void 0&&!(typeof e.count=="number"&&Number.isInteger(e.count)&&e.count>=0)&&v(r,`${t}.count`,"invalid_count","count must be a non-negative whole number"),a?(Cs(r,n,e.field,Lo(e)),tr(e.condition,`${t}.condition`,r,n+1)):v(r,`${t}.condition`,"missing_condition",Ie(o).message));},oE=(e,t,r,n)=>{if(typeof e.field!="string"&&v(r,`${t}.field`,"field_required","Date rule requires a string field"),Ls(e,t,r,n),typeof e.dateOperator!="string"||!Gt(e.dateOperator,"date")){v(r,`${t}.dateOperator`,"invalid_date_operator",ue(e.dateOperator,"date").message);return}let o=e.dateOperator;rc(e,"date",o,t,r,n);let i=Qt(e.value,Ga(e.offset));i&&v(r,t,"clock_unit_below_floor",i.message),Xi(o,"date",r.target)||v(r,`${t}.dateOperator`,`unsupported_${Ms(r.target)}_date_operator`,`Date operator '${o}' is not supported by ${r.target}()`);let s=Ht(o,"date");if(s==="dayList"){if(en(e,t,r,n)!=="value")return;let a=e.value;(!Array.isArray(a)||!a.every(l=>typeof l=="string"&&Zd(l)))&&v(r,`${t}.value`,"invalid_day_list",`Date operator '${o}' requires an array of day names (${qn.join(", ")})`);return}if(en(e,t,r,n)!==null&&(nc(e,o,t,r),!(typeof e.path=="string"||typeof e.bind=="string"))){if(ee(e.value)){Yu(e.value,o,`${t}.value`,r,n);return}if(To.includes(o)){v(r,`${t}.value`,"invalid_date_range",nt(o).message);return}if(s==="dateRange"){if(!sE(e.value)){v(r,`${t}.value`,"invalid_date_range",`Date operator '${o}' requires a two-item date range`);return}e.value.forEach((a,l)=>{ee(a)?Yu(a,o,`${t}.value[${l}]`,r,n):ye(a)&&!br(a,qe).isValid()&&v(r,`${t}.value[${l}]`,"invalid_date_value",`Date operator '${o}' value '${String(a)}' does not parse as a date`);});return}if(!ye(e.value)){v(r,`${t}.value`,"invalid_date_value",`Date operator '${o}' requires a date-like value`);return}br(e.value,qe).isValid()||v(r,`${t}.value`,"invalid_date_value",`Date operator '${o}' value '${String(e.value)}' does not parse as a date`);}},sc=(e,t,r,n)=>{if(!pt(e)||Object.keys(e).length===0){v(r,t,"invalid_relative_units","Relative offset requires at least one unit");return}for(let[o,i]of Object.entries(e)){if(!In(o)){v(r,`${t}.${o}`,"invalid_relative_unit",`Unknown relative unit '${o}'`);continue}let s=pt(i)?en(i,`${t}.${o}`,r,n):"literal";if(s===null||s==="path"||s==="bind")continue;let a=s==="value"?i.value:i,l=Ua(a,o);l&&v(r,`${t}.${o}`,"invalid_relative_magnitude",l);}},Zu=(e,t,r)=>{(typeof e!="string"||!ss.includes(e))&&v(r,t,"invalid_period_unit",`Unknown period unit '${String(e)}'`);},Yu=(e,t,r,n,o)=>{let i=To.includes(t),s=Oe(e);if(s){sc(s[0],r,n,o);return}if(Fo(e)){Zu(zn(e),r,n);return}if(jo(e)){if(i){v(n,r,"invalid_date_range",nt(t).message);return}let a="start"in e?e.start:e.end;if(!pt(a)||!Fo(a)){v(n,r,"invalid_period_unit","start/end requires a this/last/next period");return}Zu(zn(a),r,n);return}v(n,r,"invalid_date_expression","Unrecognized date expression");},ac=(e,t,r)=>{"value"in e&&e.value!==void 0&&v(r,`${t}.value`,"unexpected_value","Rule does not accept value"),"path"in e&&e.path!==void 0&&v(r,`${t}.path`,"unexpected_path","Rule does not accept path"),"bind"in e&&e.bind!==void 0&&v(r,`${t}.bind`,"unexpected_bind","Rule does not accept bind");},Ms=e=>e==="toPrisma"?"prisma":e==="toSql"?"sql":"check",pt=e=>re(e),iE=e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="number"&&typeof e[1]=="number",sE=e=>Array.isArray(e)&&e.length===2&&(ye(e[0])||ee(e[0]))&&(ye(e[1])||ee(e[1])),lc=(e,t,r,n)=>{if(Pe(e)&&r.target!=="check"&&(r.target==="toPrisma"&&ro(e)!==null||v(r,t,`unsupported_${Ms(r.target)}_window`,At(r.target).message)),"filter"in e&&e.filter!==void 0&&(Cs(r,n,e.field),tr(e.filter,`${t}.filter`,r,n+1)),"orderBy"in e&&e.orderBy!==void 0){let i=e.orderBy;Array.isArray(i)?i.forEach((s,a)=>{(!pt(s)||typeof s.field!="string"||s.dir!=="asc"&&s.dir!=="desc")&&v(r,`${t}.orderBy[${a}]`,"invalid_order_by",'orderBy entries must be { field: string, dir: "asc" | "desc" }');}):v(r,`${t}.orderBy`,"invalid_order_by","orderBy must be an array of { field, dir }");}for(let i of ["take","skip"])if(i in e&&e[i]!==void 0){let s=e[i];(typeof s!="number"||!Number.isInteger(s)||s<0)&&v(r,`${t}.${i}`,`invalid_window_${i}`,`${i} must be a non-negative integer`);}},v=(e,t,r,n)=>{e.errors.push({path:t,code:r,message:n});};var aE=/[.:]/,rl=e=>{let t=[];for(let[r,n]of Object.entries(e.maps))for(let[o,i]of Object.entries(n.models))for(let[s,a]of Object.entries(i.fields))a.kind!=="bridge"&&aE.test(s)&&t.push({path:`${Me({fieldMap:r,model:o})}.${s}`,message:"contains forbidden character . or :",code:"invalid_field_name"});return et(t)},pc=e=>tn(rl(e),"validateFieldMaps");var ft=e=>!Object.hasOwn(e,"parent"),Lt=e=>{let t=[],r=new Set,n=e;for(;!ft(n);){if(r.has(n))throw new Error("cycle detected in narrowing parent chain");if(Object.hasOwn(n,"model")||Object.hasOwn(n,"maps"))throw new Error("a narrowing carries a base lens key (model / maps); it has a parent instead");r.add(n),t.unshift(n),n=n.parent;}return t},dt=e=>ft(e)?e:Lt(e)[0].parent;var nl=(e,t)=>t.length?K([...t,e]):e,lE=e=>{if(wr(e).length)return false;let t=e.field,r=typeof t=="string"?_(t):null;try{return he(r?{...e,field:r.path}:e,{})===!0}catch{return false}},ol=(e,t)=>{if(!t.length)return e;if(!lE(e))return K([...t.flatMap(o=>o.clamps),e]);let[r,...n]=t;return Nt([K([...r.clamps,ol(e,n)]),K([{field:r.prefix,operator:"notExists"},e])])},lo=(e,t,{paths:r=false}={})=>hr(e,{rewrite:n=>{if(We(n))return n;if(typeof n.field!="string"||n.field==="")throw new T(`narrowRule: cannot re-root a relation clamp of unknown shape under '${t}'`,"unsupported_clamp");let o=wr(n),i=o.find(a=>_(a));if(r&&i)throw new T(`prefixConditionFields: cannot re-root a scope ref ('${i}') under '${t}'`,"unsupported_clamp");if(o.length&&!r)throw new T(`narrowRule: cannot re-root a relation clamp with a path reference ('${o[0]}') under '${t}'. Author the clamp without 'path', or anchor it at the relation itself.`,"unsupported_clamp");if(_(n.field))throw new T(`narrowRule: cannot re-root a relation clamp with a scope ref field ('${n.field}') under '${t}'. Author the clamp against the model's own columns.`,"unsupported_clamp");if(xe(n)){for(let a of [n.condition,n.filter])if(a!==void 0&&ao(a).escaping!==null)throw new T(`narrowRule: cannot re-root a relation clamp on '${n.field}' under '${t}': '${ao(a).escaping}' inside it reads the row being re-rooted. Anchor such clamps at the relation's own model.`,"unsupported_clamp")}return {...r?Qn(n,a=>Ee(a)?{...a,path:`${t}.${a.path}`}:a):n,field:`${t}.${n.field}`}},below:()=>false}),il=(e,t)=>t.flatMap(r=>{let n=V(e,r.map,r.model,r.relPath);if(n.whereClauses.length===0)return [];if(r.isList)throw new T(`narrowRule: cannot enforce a to-many relation clamp on '${r.prefix}' without an arrayOperator condition to anchor it (row-scoped). Traverse '${r.prefix}' via an array operator (any/all/none/...) so the clamp can be injected safely.`,"unsupported_clamp");return [{prefix:r.prefix,clamps:n.whereClauses.map(o=>lo(o,r.prefix))}]}),fc=(e,t)=>il(e,t).flatMap(r=>r.clamps),uc=(e,t,r)=>{let n=ze(e,r);if("outOfBounds"in n)throw new T(`narrowRule: ${n.outOfBounds}`,"scope_out_of_bounds");if(!n.scope)return {hops:[],end:null};let o=e.slice(0,e.length-n.path.length);return Te(t.lens.maps,n.scope,n.path,o==="$."?"":o)},pE=(e,t,r)=>{if(_(e))return uc(e,t,r).hops;let n=r.length===1?"":`${"$".repeat(r.length)}.`;return r[0]?Te(t.lens.maps,r[0],e,n).hops:[]},dc=(e,t,r)=>{if(We(e)||typeof e.field!="string"||e.field==="")return null;let{hops:n,end:o}=uc(e.field,t,r);return {hops:n,below:o}},rn=(e,t,r)=>hr(e,{below:(n,o)=>{let i=dc(n,t,o);return i?i.below?[...o,i.below]:xe(n)?[...o,null]:false:false},after:(n,o)=>{let i=dc(n,t,o);if(!i)return n;let s=fc(t,wr(n).flatMap(d=>pE(d,t,o))),a=i.below;if(!a||!xe(n))return nl(ol(n,il(t,i.hops)),s);let l=[...V(t,a.mapName,a.modelName,a.relPath).whereClauses,...fc(t,Zn(n).flatMap(d=>Te(t.lens.maps,a,d).hops))],p=n.condition===void 0||n.arrayOperator===x.all||Pe(n),f={...n};return l.length&&p?f.filter=K([...n.filter!==void 0?[n.filter]:[],...l]):l.length&&(f.condition=K([...l,n.condition])),nl(ol(f,il(t,i.hops.slice(0,-1))),s)}},[r]),po=(e,t)=>{let r=F(t),n=V(r,r.lens.mapName,r.lens.model,[]),o=rn(e,r,{mapName:r.lens.mapName,modelName:r.lens.model,relPath:[]});return nl(o,n.whereClauses)};var sl=(e,t)=>{let r=Yt(e,N.DateTime,t);return typeof r=="number"&&!Number.isNaN(new Date(r).getTime())?r:void 0},fE=(e,t,r)=>n=>{if(n==null)return n;let o=sl(n,r);if(o===void 0)throw new Error(`Invalid date value for DateTime field '${e}': ${String(n)}`);return t==="toPrisma"?new Date(o):new Date(o).toISOString()},fo=(e,t,r,n,o)=>{if(t==null||r?.kind==="json-path")return t;let i=r?.kind==="direct"?r.entry:void 0;if(i?.isList)return t;let s=i?Ge(i):void 0;if(e.coerceType!==void 0&&s!==void 0&&e.coerceType!==s)throw new Error(`coerceType '${e.coerceType}' overrides ${s} field '${e.field}', but ${n} compares the column as stored \u2014 evaluate it in memory with check(), or drop the override.`);if((s??e.coerceType)===N.DateTime){let l=fE(e.field,n,o());return Array.isArray(t)?t.map(l):l(t)}if(e.coerceType===void 0&&s===N.String&&(Array.isArray(t)?t:[t]).some(l=>typeof l=="number"||typeof l=="boolean"))throw new Error(`'${e.field}' is String but the literal is not a string; pass a string, or stamp coerceType: 'String'.`);if(e.coerceType===void 0&&s!==void 0&&(Q.includes(s)||s===N.Boolean)&&(Array.isArray(t)?t:[t]).some(l=>typeof l=="string"))throw new Error(`'${e.field}' is ${s} but the literal is a string; pass a ${s===N.Boolean?"boolean":"number"}, or stamp coerceType: '${s}'.`);return e.coerceType!==void 0&&zd.includes(e.coerceType)?Yt(t,e.coerceType,e.coerceType===N.DateTime?o():void 0):t};var cc=e=>Array.isArray(e)?e.flatMap(cc):[e],Qo=e=>e.value===void 0?null:cc(e.value),dE=e=>sl(e)!==void 0,uE=/^-?\d+(\.\d+)?$/,cE={String:{expected:"a string",fits:e=>typeof e=="string"},Enum:{expected:"a string",fits:e=>typeof e=="string"},Int:{expected:"an integer",fits:Number.isSafeInteger},BigInt:{expected:"an integer",fits:Number.isSafeInteger},Float:{expected:"a number",fits:Number.isFinite},Decimal:{expected:"a number or a numeric string",fits:e=>Number.isFinite(e)||typeof e=="string"&&uE.test(e)},Boolean:{expected:"a boolean",fits:e=>typeof e=="boolean"},DateTime:{expected:"a date",fits:dE},Json:{expected:"a value",fits:()=>true},Bytes:{expected:"a value",fits:()=>true}},mE=e=>typeof e=="string"?`'${e}'`:typeof e=="object"&&e!==null?JSON.stringify(e):String(e),_s=(e,t)=>{let r="coerceType"in e?e.coerceType:void 0,n=r??t;if(n===void 0||n===N.Json)return [];let o="operator"in e?e.operator:e.dateOperator,i=Fn(e);if(!i)return [];let a=r!==void 0&&r!==t?`field '${e.field}' coerced to ${n}`:`${n} field '${e.field}'`;if(!i.kinds.includes(n))return [{path:e.field,code:"operator_kind_mismatch",message:`operator '${o}' does not apply to ${a} (applies to: ${i.kinds.join(", ")})`}];if(e.offset!==void 0&&!("dateOperator"in e?n===N.DateTime:Q.includes(n)))return [{path:e.field,code:"invalid_offset",message:`an offset does not apply to ${a}`}];if("dateOperator"in e||i.valueShape==="none"||i.valueShape==="pattern")return [];if(Hd.includes(i.valueShape)&&Array.isArray(e.value))return [{path:e.field,code:"invalid_value_shape",message:`operator '${o}' compares one value, but ${a} was given a list`}];let{expected:l,fits:p}=cE[n],f=u=>{try{return p(Yt(u,n))}catch{return false}},d=u=>p(u)||r!==void 0&&f(u);return (Qo(e)??[]).filter(u=>u!==null&&!d(u)).map(u=>({path:e.field,code:"invalid_value",message:`value ${mE(u)} does not fit ${a} (expected ${l})`}))},mc=(e,t,r)=>{if(r.isList===true||Ue(r))return null;let n=M(r)?`arrayOperator '${t}' needs a list, but '${e}' is a to-one relation \u2014 a single related record; address its fields directly (e.g. '${e}.<field>')`:`arrayOperator '${t}' needs a list, but '${e}' is a single ${Ge(r)??r.type} value`;return {path:e,code:"invalid_array_operator",message:n}};var gE=(e,t,r,n)=>H(e,(o,i)=>{let s=pe(o);if(s===null)return n.push({path:typeof o.field=="string"?o.field:"",code:"ambiguous_condition",message:vt().message}),false;if(We(o))return;let a=o,l=b=>{let S=ze(b,i);return "outOfBounds"in S?(n.push({path:b,code:"scope_out_of_bounds",message:S.outOfBounds}),null):{scope:S.scope,field:S.path}},p=i[i.length-1],f=true,d=null;if("field"in a&&typeof a.field=="string"&&a.field!==""){let b=co(t,i,a.field);"issue"in b?(n.push({path:a.field,...b.issue}),f=false):{next:p,walked:d}=b;}let u=d?.entry??null,c=d?.terminalFieldName??null,y=d?.entry.kind==="enum",m=d?.entry.type??null,g=d&&d.jsonSubPath.length===0?Fs(d.terminalEffect,d.terminalFieldName):null;for(let{ref:b,role:S}of qo(a)){let w=_(b)?l(b):{scope:Mt(t),field:b};if(!w||w.scope.open)continue;let R=uo(t,w.scope,w.field);if(!R){n.push({path:b,...Ds(t,w.scope,w.field,S==="value"?"path (comparison ref) does not resolve through the narrowed lens":"offset or magnitude ref does not resolve through the narrowed lens")});continue}if(M(R.entry)){n.push({path:b,code:"not_in_lens",message:"a value ref reads a column, not a relation"});continue}let O=Ge(R.entry);if(S==="value"||S==="shift"||O===void 0)continue;(S==="whole"?Kd.includes(O):Q.includes(O))||n.push({path:b,code:"not_in_lens",message:`${S==="whole"?"a calendar unit reads a whole number":"an offset or magnitude reads a number"}, not ${O}`});}if(!f)return false;if("arrayOperator"in a&&typeof a.field=="string"&&u){let b=mc(a.field,a.arrayOperator,u);if(b)return n.push(b),false}if(u&&M(u)&&(s==="field"||s==="date")&&(u.isList||!Xt(a))){let b=a.field;return n.push({path:b,code:"operator_kind_mismatch",message:(u.isList?ps(b):mr(b)).message}),false}if(!u?.isList&&(s==="field"||s==="date")&&n.push(..._s(a,u?Ge(u):void 0)),!p.open)for(let b of Zn(a))b!==""&&!uo(t,p,b)&&n.push({path:b,...Ds(t,p,b,"an orderBy or aggregate field does not resolve through the narrowed lens")});if(g&&"operator"in a&&c){let b=Qo(a);if(b){let S=new Set(g),w=y?`enum '${m}'`:`field '${c}'`;for(let R of b)typeof R=="string"&&!S.has(R)&&n.push({path:c,code:"value_not_allowed",message:`value '${R}' is not in the allowed set for ${w} (allowed: ${[...S].join(", ")})`});}}return [...i,p]},[r]),Zo=(e,t,r,n,o)=>{let i=[];return gE(e,t,{mapName:r,modelName:n,relPath:o,open:false},i),i},Ar=(e,t)=>{let r=F(t);try{let n=Zo(e,r,r.lens.mapName,r.lens.model,[]);return n.length===0&&po(e,t),et(n)}catch(n){if(!(n instanceof T))throw n;return et([{path:"",code:n.code,message:n.message}])}};var ei=e=>e===void 0?void 0:Array.isArray(e)?e:[e],ti=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&("where"in e||"label"in e||"groupBy"in e||"from"in e),Nr=e=>{if(ti(e))return e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===0)throw yE();return {where:e}},yE=()=>new T("sources: {} is not a Condition \u2014 use `true` for an unconstrained source","invalid_source"),pl=["__offpath__"],gc=new WeakMap,hE=(e,t)=>{if(!t)return new Map;let r=JSON.stringify([Yo(t.parent),Yo(e.maps),e.mapName,e.model,t.mapDefaults??null]),n=gc.get(t);if(n?.fingerprint===r)return n.trees;let o=new Map;return gc.set(t,{fingerprint:r,trees:o}),o},yc=new WeakMap,wE=0,Yo=e=>{let t=yc.get(e);return t===void 0&&(t=wE++,yc.set(e,t)),t},be="\0",bE=e=>{let t=Object.entries(e.fields);return {relations:new Set(t.filter(([,r])=>M(r)).map(([r])=>r)),gated:t.filter(([,r])=>r.options!==void 0||r.kind==="enum"||r.values!==void 0)}},js=e=>e?String(Yo(e)):"",F=e=>{let t=dt(e),r=ft(e)?[]:Lt(e);return {lens:t,chain:r,origin:r[0],memo:{trees:hE(t,r[0]),vetted:new Set,effects:new Map,places:new Map,models:new Map,refs:new Map,compiles:new Map}}},Vs=(e,t)=>e===null?new Set(t):new Set(t.filter(r=>e.has(r))),SE=(e,t)=>{if(t.picks&&(e.picks=Vs(e.picks,t.picks)),t.omits)for(let r of t.omits)e.omits.add(r);},bc=(e,t,r)=>{e.set(t,Vs(e.get(t)??null,r));},Sc=(e,t,r)=>{let n=e.get(t)??new Set;for(let o of r)n.add(o);e.set(t,n);},RE=(e,t,r)=>{if(r.enumPicks)for(let[n,o]of Object.entries(r.enumPicks))bc(e,n,o);if(r.enumOmits)for(let[n,o]of Object.entries(r.enumOmits))Sc(t,n,o);},al=(e,t,r)=>JSON.stringify([e,t,r]),OE=(e,t,r,n,o,i,s,a)=>{if(s&&SE(e,t),t.where!==void 0&&i&&(o(t.where),e.whereClauses.push(r(t.where)),(a?e.modelWheres:e.pathWheres).push({where:t.where,layer:n})),t.sources)for(let[l,p]of Object.entries(t.sources)){let f=Nr(p),d=e.sources.get(l)??[],u=e.sourceWheres.get(l)??[];f.where!==void 0&&i&&(o(f.where,true),d.push(r(f.where)),u.push(f.where)),e.sources.set(l,d),e.sourceWheres.set(l,u);let c=ei(f.groupBy);for(let[y,m,g]of [["label",f.label,e.sourceLabels.get(l)],["groupBy",c,e.sourceGroupBys.get(l)]]){if(m===void 0)continue;let b=al(l,y,m);g!==void 0&&al(l,y,g)===b||e.sourceDeclaredAt.set(b,n);}f.label!==void 0&&e.sourceLabels.set(l,f.label),c!==void 0&&e.sourceGroupBys.set(l,c),f.from==="mapDefaults"&&!e.sourcesFromMapDefaults.has(l)&&e.sourcesFromMapDefaults.set(l,n);}},T=class extends Error{constructor(r,n){super(r);this.code=n;}code;name="LensRefusal"},fl=e=>new T(`a bare path ('${e}') reads the root row, which a clamp at a relation visit or a model default doesn't stand on: use a literal, a bind, or a \`$\` scope ref`,"invalid_value_source"),EE=(e,t,r)=>Zo(e,t,r.mapName,r.modelName,r.relPath),xE=e=>new T(`a later layer's clamp reads what its parent does not show: '${e.path}' ${e.message}`,e.code),dl=e=>new T(`the scope ref '${e}' climbs out of the clamp: a clamp reads its own row ('$.'), literals and binds`,"scope_out_of_bounds"),ao=e=>{let t=null,r=null;return H(e,(n,o)=>{if(We(n))return;let i=wr(n);for(let s of [...typeof n.field=="string"?[n.field]:[],...i]){let a=_(s);r===null&&a&&a.depth>o&&(r=s);}for(let s of i)t===null&&!_(s)&&(t=s);return xe(n)?o+1:void 0},1),{bare:t,escaping:r}},ll=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},n=[r];if(t.relPath.length>0)for(let i of Te(e.lens.maps,r,t.relPath.join(".")).hops)n.push({mapName:i.map,modelName:i.model,relPath:i.relPath});let o=n[n.length-1];return n.length===t.relPath.length+1&&o.mapName===t.mapName&&o.modelName===t.modelName?n:null},Xo=(e,t)=>{let r=e;for(let n of t)r=E(r?.relations,n);return r},ul=(e,t,r)=>{let n=i=>E(E(e.mapDefaults,i.mapName)?.models,i.modelName);if(!r){let i=n(t);return {defaults:i?[i]:[],path:void 0}}let o=[];for(let[i,s]of r.entries()){let a=Xo(n(s),t.relPath.slice(i));a&&o.push(a);}return {defaults:o,path:Xo(e.root,t.relPath)}},$E=(e,t,r,n)=>{let o=Xo(t.root,r.relPath),i=[r.relPath.join(be),Object.keys(o?.relations??{}).join(be),(o?.omits??[]).join(be)].join(`${be}${be}`),s=n.get(i);if(s)return s;let a=new Map,l={lens:e},p=ll(l,r)??[r],f=new Set(p.map(u=>`${u.mapName}:${u.modelName}`)),d=[{at:r,below:[]}];for(;d.length>0;){let{at:u,below:c}=d.shift(),y=C(E(e.maps,u.mapName),u.modelName)?.fields??{},{defaults:m,path:g}=ul(t,u,ll(l,u)),b=new Set(m.flatMap(R=>Object.keys(R.relations??{}))),S=new Set([...m,...g?[g]:[]].flatMap(R=>R.omits??[])),w=[];for(let[R,O]of Object.entries(y)){if(!b.has(R)||S.has(R)||g?.relations!==void 0&&Object.hasOwn(g.relations,R))continue;let $=st(O,u.mapName);if(!$||!C(E(e.maps,$.mapName),$.modelName))continue;let k=`${$.mapName}:${$.modelName}`;f.has(k)||(f.add(k),w.push(R),d.push({at:{...$,relPath:[...u.relPath,R]},below:[...c,R]}));}a.set(c.join("."),w);}return n.set(i,a),a},vE=(e,t,r,n)=>{if(!n)return ul(t,r,null).defaults.flatMap(p=>Object.keys(p.relations??{}));let o=r.relPath.length;for(;o>0&&Xo(t.root,r.relPath.slice(0,o))===void 0;)o--;let i={...n[o],relPath:r.relPath.slice(0,o)},a=$E(e.lens,t,i,e.memo?.trees??new Map).get(r.relPath.slice(o).join("."))??[];return [...o===r.relPath.length?Object.keys(Xo(t.root,r.relPath)?.relations??{}):[],...a]},ri=(e,t,r)=>{let n=t;for(let o of Te(e.lens.maps,t,r).hops){let i=o.relPath[o.relPath.length-1];if(!V(e,n.mapName,n.modelName,n.relPath).relations.has(i))return o.prefix;n={mapName:o.map,modelName:o.model,relPath:o.relPath};}return null},V=(e,t,r,n)=>{let o=e.memo?hc(e,t,r,n):null,i=o===null?void 0:e.memo?.effects.get(o);if(i){if(!e.unvetted&&i.unchecked){for(let q of i.unchecked)q();i.unchecked=null;}return i.effect}let s=[],a={picks:null,omits:new Set,enumValuesByField:new Map,whereClauses:[],pathWheres:[],modelWheres:[],sources:new Map,sourceWheres:new Map,sourceLabels:new Map,sourceGroupBys:new Map,sourceDeclaredAt:new Map,sourcesFromMapDefaults:new Map,relations:new Set,relationFields:new Set},l=E(e.lens.maps,t),p=C(l,r);if(!p)return a;let f=e.memo?.models.get(p);f||(f=bE(p),e.memo?.models.set(p,f)),a.relationFields=f.relations;let d={mapName:t,modelName:r,relPath:n},u=e.origin??e.chain[0],c=`${js(u)}${be}${t}${be}${r}${be}${n.join(be)}`,y=e.memo?.places.get(c);if(!y){let q=ll(e,d);y={trail:q,turnedOn:u?vE(e,u,d,q):[]},e.memo?.places.set(c,y);}let{trail:m}=y,g=new Map,b=new Map,S=new Map,w=new Map,R=q=>q,O=0,$=()=>{},k=true,ae=true,P=(q,W=false)=>{OE(a,q,R,O,$,k,ae,W),RE(g,b,q);};for(let[q,W]of e.chain.entries()){O=q;let Lr={...e,clamp:false,skipClampsOf:void 0,skipHidingOf:void 0,chain:e.chain.slice(0,q)};k=W!==e.skipClampsOf,ae=W!==e.skipHidingOf,R=ne=>q===0?ne:rn(ne,Lr,{mapName:t,modelName:r,relPath:n});for(let[ne,Se]of Object.entries(E(W.mapDefaults,t)?.enums??{}))Se.picks&&bc(S,ne,Se.picks),Se.omits&&Sc(w,ne,Se.omits);let{defaults:So,path:Mr}=ul(W,d,m),me=q===0?null:Lr,gt=ne=>(Se,Re=false)=>{let Ce=e.memo?.refs.get(Se);if(Ce||(Ce=ao(Se),e.memo?.refs.set(Se,Ce)),Ce.bare!==null&&!(ne&&!Re))throw fl(Ce.bare);if(Ce.escaping!==null)throw dl(Ce.escaping);if(!me)return;let Zl=()=>{let yi=typeof Se=="object"&&Se!==null?`${Yo(Se)}${be}${hc(me,t,r,n)}`:null;if(yi!==null&&me.memo?.vetted.has(yi))return;let[Yl]=EE(Se,me,d);if(Yl)throw xE(Yl);yi!==null&&me.memo?.vetted.add(yi);};e.unvetted?s.push(Zl):Zl();};$=gt(false);let ln=E(E(W.mapDefaults,t)?.models,r);for(let ne of So)P(ne,ne===ln);Mr&&($=gt(n.length===0&&m!==null),P(Mr));}if(u&&e.chain.includes(u))for(let q of y.turnedOn)a.relationFields.has(q)&&!a.omits.has(q)&&a.relations.add(q);for(let[q,W]of f.gated){let Lr=W.kind==="enum",Mr=W.options?.map(ne=>ne.value)??(Lr?Hr(W,l?.enums):W.values);if(!Mr)continue;let me=Mr;if(Lr){let ne=S.get(W.type),Se=w.get(W.type);ne&&(me=me.filter(Re=>ne.has(Re))),Se&&(me=me.filter(Re=>!Se.has(Re)));}let gt=g.get(q),ln=b.get(q);gt&&(me=me.filter(ne=>gt.has(ne))),ln&&(me=me.filter(ne=>!ln.has(ne))),a.enumValuesByField.set(q,me);}return o!==null&&e.memo?.effects.set(o,{effect:a,unchecked:s.length?s:null}),a},hc=(e,t,r,n)=>{let o=wc.get(e);if(o===void 0){o=`${js(e.origin)}${be}${js(e.skipClampsOf)}${be}${js(e.skipHidingOf)}${be}`;for(let i of e.chain)o+=`${Yo(i)},`;wc.set(e,o);}return `${o}${be}${t}${be}${r}${be}${n.join(be)}`},wc=new WeakMap,rr=e=>{let t=[],r=(n,o)=>{let i=E(e.lens.maps,n.mapName);if(!C(i,n.modelName))return;let s=V(e,n.mapName,n.modelName,n.relPath);t.push({path:o,at:n,effect:s});for(let a of s.relations){let l=ce(i,n.modelName,a),p=l&&st(l,n.mapName);p&&r({...p,relPath:[...n.relPath,a]},`${o}.${a}`);}};return r({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},e.lens.model),t},Is=(e,t,r,n)=>V(e,t,r,pl).sources.has(n),qs=(e,t,r,n)=>new T(`source '${n}' at '${e}' offers mapDefaults.${t}.models.${r}.sources.${n}, which no layer declares`,"invalid_source"),_t=(e,t)=>e.omits.has(t)?false:e.relationFields.has(t)?e.relations.has(t):!(e.picks!==null&&!e.picks.has(t)),Fs=(e,t)=>e.enumValuesByField.get(t)??null,nn=(e,t,r)=>{let n=r.split("."),o=[],i=[];for(let{index:s,field:a,at:l,entry:p,next:f}of Rr(e.lens.maps,t,r)){if(!p)return {resolution:{outcome:"missing",index:s,hops:o},effects:i};let d=V(e,l.mapName,l.modelName,l.relPath);if(!(e.clamp&&M(p)?!d.omits.has(a):_t(d,a)))return {resolution:{outcome:"hidden",index:s,hops:o},effects:i};let c={field:a,entry:p,mapName:l.mapName,model:l.modelName,relPath:[...l.relPath]};o.push(c),i.push(d);let y=s===n.length-1;if(y||Ue(p))return {resolution:{outcome:"resolved",hops:o,terminal:c,jsonSubPath:y?[]:n.slice(s+1)},effects:i};if(!f)return {resolution:{outcome:"pastScalar",index:s,hops:o},effects:i}}return {resolution:{outcome:"missing",index:n.length,hops:o},effects:i}},mo=(e,t,r,n,o)=>{let i=o==="label"?t.sourceLabels.get(n):t.sourceGroupBys.get(n);if(i===void 0)return true;let s=t.sourceDeclaredAt.get(al(n,o,i)),a=(f,d)=>nn(f,r,d).resolution.outcome!=="hidden",l={...e,clamp:true},p={...l,skipHidingOf:s===void 0?void 0:e.chain[s]};return (typeof i=="string"?[i]:i).every(f=>ri(e,r,f)===null&&(a(l,f)||a(p,f)))},uo=(e,t,r)=>{let{resolution:n,effects:o}=nn(e,t,r);if(n.outcome!=="resolved")return null;let{terminal:i,jsonSubPath:s}=n;return {mapName:i.mapName,modelName:i.model,relPath:i.relPath,entry:i.entry,terminalEffect:o[o.length-1],terminalFieldName:i.field,jsonSubPath:s}},Ds=(e,t,r,n)=>{let{resolution:o}=nn(e,t,r);if(o.outcome!=="hidden")return {code:"not_in_lens",message:n};let i=r.split("."),s=o.hops.at(-1),a=s?{mapName:s.mapName,modelName:s.model,relPath:[...s.relPath,s.field]}:t,l=s&&st(s.entry,s.mapName),p=l?{...l,relPath:a.relPath}:t,f=V(e,p.mapName,p.modelName,p.relPath),d=i[o.index];return !f.relationFields.has(d)||f.omits.has(d)?{code:"not_in_lens",message:n}:{code:"not_in_lens",message:`'${i.slice(0,o.index+1).join(".")}' is a relation the lens does not turn on (turn it on with \`relations\`)`}},Mt=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[],open:false}),co=(e,t,r)=>{let n=ze(r,t);if("outOfBounds"in n)return {issue:{code:"scope_out_of_bounds",message:n.outOfBounds}};if(n.scope.open)return {from:n.scope,next:n.scope,walked:null};let o=uo(e,n.scope,n.path);if(!o)return {issue:Ds(e,n.scope,n.path,"path does not resolve through the narrowed lens")};let i=Ue(o.entry),s=st(o.entry,o.mapName),a=s?{...s,relPath:[...o.relPath,o.terminalFieldName],open:i}:{...n.scope,open:i};return {from:n.scope,next:a,walked:o}},Te=(e,t,r,n="")=>{let o=r.split("."),i=[],s=null;for(let{index:a,field:l,at:p,entry:f,next:d}of Rr(e,t,r)){if(!f||!d)break;let u=[...p.relPath,l];i.push({map:d.mapName,model:d.modelName,relPath:u,prefix:`${n}${o.slice(0,a+1).join(".")}`,isList:f.isList===true}),a===o.length-1&&(s={...d,relPath:[...u]});}return {hops:i,end:s}};var ml="parent:",gl=e=>e.startsWith(ml),Oc=e=>gl(e)?e.slice(ml.length):e,cl=(e,t)=>{let r={...e};if(e.where!==void 0&&(r.where=t(e.where)),e.sources){let n={};for(let[o,i]of Object.entries(e.sources))n[o]=ti(i)?i.where!==void 0?{...i,where:t(i.where)}:i:t(i);r.sources=n;}if("relations"in e&&e.relations){let n={};for(let[o,i]of Object.entries(e.relations))n[o]=cl(i,t);r.relations=n;}return r},Ec=(e,t)=>{let r={};for(let[n,o]of Object.entries(e.mapDefaults??{})){let i={};for(let[s,a]of Object.entries(o.models??{}))i[s]=cl(a,t);r[n]=o.models?{...o,models:i}:o;}return {...e,root:e.root?cl(e.root,t):void 0,mapDefaults:e.mapDefaults?r:void 0}},yl=e=>{let t=[];return Ec(e,r=>(t.push(r),r)),t},Rc=e=>{let t=new Set;for(let r of yl(e))for(let n of Bo(r))gl(n)||t.add(n);return t},xc=e=>{let t=new Set;for(let r of Lt(e))for(let n of yl(r))for(let o of Bo(n,{required:true}))t.add(Oc(o));return [...t].sort()},$c=(e,t)=>{if(ft(e))return e;let r={...t};for(let[n,o]of Object.entries(t))r[`${ml}${n}`]=o;return {...Ec(e,n=>Ba(n,r)),parent:$c(e.parent,t)}},vc=(e,t)=>$c(e,t),Ac=e=>{let t=[],r=new Set;for(let o of Lt(e.parent))for(let i of Rc(o))r.add(i);for(let o of Rc(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 yl(e))for(let i of Bo(o))gl(i)&&n.add(Oc(i));for(let o of n)r.has(o)||t.push(`bind 'parent:${o}' references an inherited binding no ancestor declares`);return t};var Pc=(e,t)=>e===void 0?t:t===void 0?e:{all:[e,t]},AE=(e,t)=>{if(!e||!t)return e??t;let r={...e};for(let[n,o]of Object.entries(t)){let i=r[n];if(i===void 0){r[n]=o;continue}let s=Nr(i),a=Nr(o),l=Pc(s.where,a.where);r[n]={...s,...a,...l===void 0?{}:{where:l}};}return r},kc=(e,t)=>{let r=Pc(e?.where,t.where),n=AE(e?.sources,t.sources);return {...e,...r===void 0?{}:{where:r},...n?{sources:n}:{}}},NE=(e,t)=>{let r={...e?.models};for(let[n,o]of Object.entries(t))r[n]=kc(r[n],o);return {...e,models:r}},Nc=(e,t)=>{let r={...e.mapDefaults};for(let[n,{models:o}]of Object.entries(t.mapDefaults??{}))r[n]=NE(r[n],o);return {...e,...t.root?{root:kc(e.root,t.root)}:{},...t.mapDefaults?{mapDefaults:r}:{}}},hl=(e,t)=>ft(e)?Nc({parent:e},t):ft(e.parent)?Nc(e,t):{...e,parent:hl(e.parent,t)};var Tc=(e,t)=>{let r=F(t),n=(o,i)=>typeof o=="string"&&o!==""?co(r,i,o):null;return hr(e,{rewrite:(o,i)=>{if(pe(o)!=="field"||o.coerceType)return o;let s=n(o.field,i);if(!s||"issue"in s||!s.walked||s.walked.jsonSubPath.length)return o;let{entry:a}=s.walked;return a.kind==="scalar"&&Gd.includes(a.type)?{...o,coerceType:a.type}:o},below:(o,i)=>{if(!xe(o))return false;let s=n(o.field,i),a=s&&!("issue"in s)?s.walked?.entry:void 0;return s&&!("issue"in s)&&a&&M(a)?[...i,s.next]:false}},[Mt(r)])};var Cc=({maps:e,bridges:t,mapName:r,model:n})=>({...xs({maps:e,bridges:t}),mapName:r,model:n});var PE=(e,t)=>H(e,(r,n)=>{if(t.sources.add(n[n.length-1].mapName),We(r)||typeof r.field!="string"||r.field==="")return;let o=co(t.policy,n,r.field);return "issue"in o?false:(o.walked&&(t.sources.add(o.walked.mapName),(o.walked.entry.kind==="bridge"||o.walked.mapName!==o.from.mapName)&&(t.bridgesCrossed=true)),[...n,o.next])},[Mt(t.policy)]),Lc=(e,t)=>{let n={policy:F(t),sources:new Set,bridgesCrossed:false};return PE(e,n),{sources:[...n.sources].sort(),bridgesCrossed:n.bridgesCrossed,supportedTargets:D.filter(o=>(o==="check"||!n.bridgesCrossed)&&vr(e,{target:o,map:n.policy.lens,mapName:n.policy.lens.mapName,model:n.policy.lens.model}).ok),errors:Ar(e,t).errors}};var kE=new Set([zt.scalar,zt.ordered,zt.array,zt.dayList,zt.dateValue]),TE=new Set([zt.none,zt.count]),CE=e=>{if(e.offset!==void 0||Io(e).some(({source:r})=>r.value===void 0))return {values:[],dynamic:true};let t=Fn(e);return t?TE.has(t.valueShape)?{values:[],dynamic:false}:kE.has(t.valueShape)?"value"in e?{values:Qo(e)??[],dynamic:false}:{values:[],dynamic:false}:{values:[],dynamic:true}:{values:[],dynamic:true}},LE=e=>e instanceof Date?`d:${+e}`:e instanceof RegExp?`r:${e}`:typeof e=="object"&&e!==null?`j:${JSON.stringify(e)}`:`p:${typeof e}:${String(e)}`,Mc=(e,t)=>{let r=F(t),n=r.lens.model,o=new Map,i=new Map,s=(l,p)=>{if(l.length===0)return;let f=uo(r,{mapName:r.lens.mapName,modelName:n,relPath:[]},l.join("."));if(!f||f.jsonSubPath.length>0)return;let{mapName:d,modelName:u,relPath:c,terminalEffect:y,terminalFieldName:m}=f;if(!y.sources.has(m))return;let g=[n,...c].join("."),b=`${g}|${m}`,S=o.get(b);S||(S={path:g,mapName:d,model:u,field:m,values:[],dynamic:false},o.set(b,S));let w=CE(p);w.dynamic&&(S.dynamic=true);let R=i.get(b)??new Set;i.set(b,R);for(let O of w.values){let $=LE(O);R.has($)||(R.add($),S.values.push(O));}},a=(l,p)=>{let f=ze(l,p);if(!("outOfBounds"in f))return [...f.scope,...f.path.split(".")]};return H(e,(l,p)=>{if(We(l))return;let f=typeof l.field=="string"?a(l.field,p):p.at(-1);return f?(!xe(l)&&typeof l.field=="string"&&s(f,l),[...p,f]):false},[[]]),[...o.values()]};var Bs=(e,t,r,n)=>{let o=ME(e,t,r);if(o.options===t)return n(o.condition,o.options);try{return n(o.condition,o.options)}catch(i){if(i instanceof T||i instanceof L)throw i;try{n(e,o.options);}catch{throw i}throw new T(`${r}: the lens's clamps on this rule have no ${r} form \u2014 ${i.message}`,"unsupported_target")}},ME=(e,t,r)=>{if(t?.lens===void 0)return {condition:e,options:t};let{lens:n}=t;if(t.map!==void 0||t.mapName!==void 0||t.model!==void 0)throw new L(`${r}: pass \`lens\` or \`map\` / \`mapName\` / \`model\`, not both \u2014 the lens names its own`);let o=Ar(e,n);if(!o.ok)throw new Error(`${r}: the rule leaves the lens \u2014 ${o.errors.map(s=>`${s.path}: ${s.message}`).join("; ")}`);let i=dt(n);return {condition:po(e,n),options:{...t,lens:void 0,map:i,mapName:i.mapName,model:i.model}}};var Ws=(e,t,r,n)=>{if(!_d.includes(e.operator))throw new Error(`'${e.operator}' does not apply to the enum '${e.field}'; compare its values with equals / in.`);let o=oe(e.caseInsensitive),i=Hr(r,n?.enums),{values:s,hasNull:a}=Ze($t.includes(e.operator)?[t]:t);if(!o&&(!i||s.every(d=>typeof d=="string"&&i.includes(d))))return null;if(!i)throw new Error(`'${e.field}' is an enum: a case-insensitive comparison reads its declared values, which the map doesn't list.`);let l=d=>o?d.toLowerCase():d,p=new Set(s.filter(d=>typeof d=="string").map(d=>l(d))),f=i.filter(d=>p.has(l(d)));return B.includes(e.operator)?{values:i.filter(d=>!f.includes(d)),matchesNull:!a}:{values:f,matchesNull:a}};var se=e=>`"${e.replace(/"/g,'""')}"`;var ve=e=>e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_"),wl=(e,t,r=false)=>{let[n,...o]=e.split("."),i=t?`${se(t)}.${se(n)}`:se(n);if(o.length===0)return i;let s=o.map(bl),a=s.pop();return [i,...s].join("->")+(r?"->":"->>")+a},bl=e=>`'${e.replace(/'/g,"''")}'`;var _E=["@prisma/client/runtime/client","@prisma/client/runtime/library"],Us,DE=()=>{if(Us!==void 0)return Us;for(let e of FE())for(let t of _E)try{let r=e(t);if(r.AnyNull!==void 0)return Us=r.AnyNull,Us}catch{}},FE=()=>{let e=[];try{let t=globalThis.process?.getBuiltinModule?.("module")?.createRequire;t&&e.push(t(import.meta.url));}catch{}return typeof Oa=="function"&&e.push(Oa),e},_c=()=>{let e=tt.get("prismaOptions.anyNull")??DE();if(e===void 0)throw new Error("A null check on a Json field needs Prisma's AnyNull, and @prisma/client isn't installed: engineGlobals.set('prismaOptions.anyNull', Prisma.AnyNull).");return e};var Dc=(e,t)=>{let r=Gr(at(t));return r===null?null:Kr(e,r)},Fc=(e,t,r)=>{if(e===null)return null;let n=Xn(at(t)),o=n&&Ur(n[0],Ho);return !n||!o?null:yr(Tt(e),o,n[1],oo(r).timeZone).toDate()};var Rl=(e,t)=>Ke(e,t?.map,t?.model),Dt=e=>e==="json"||e==="json-path",Pr=e=>Dt(e)?_c():null,kr=(e,t)=>t?.map&&t?.model?Cu(e,t.map,t.model).map(r=>Xr(r,{is:null})):[],Ol=(e,t)=>{let r=Rl(e,t);return [...Dt(r)||r==="list"||te(e.field,t?.map,t?.model)?.isRequired===false?[ut(e.field,{equals:Pr(r)},t)]:[],...kr(e.field,t)]},Ks=(e,t,r,n)=>{if(r.mode&&Dt(n)&&Array.isArray(t))throw I("toPrisma",`A case-insensitive comparison of a Json value with the list ${JSON.stringify(t)}`);if(!r.mode||typeof t!="string")return {[e]:t,...r};if(!Dt(n))return {[e]:ve(t),...r};if(/[%_\\"\u0000-\u001f]/.test(t))throw I("toPrisma",`A case-insensitive equality on Json against '${t}'`,"Prisma matches the JSON text, where %, _, a backslash, a quote or a control character doesn't read as itself");return {[e]:t,...r}},El=(e,t,r,n)=>{let o=t?.datasource?.provider??tt.get("prismaOptions.datasource.provider");return oe(e.caseInsensitive)&&Nd(o)&&xr(r,n)?{mode:"insensitive"}:{}},jc=(e,t)=>{if(e==="list")return [{isEmpty:true}];let r=t?[{equals:""}]:[];return Dt(e)?[...r,{equals:[]}]:r},Vc=e=>"isEmpty"in e?{isEmpty:false}:{not:e.equals},xl=(e,t,r,n,o)=>{let i=a=>ut(e,a,o),s=jc(t,n);return r?U([i({equals:Pr(t)}),...kr(e,o),...s.map(a=>i(a))]):we([...t==="list"?[]:[i({not:Pr(t)})],...s.map(a=>i(Vc(a)))])},VE=(e,t)=>{if(!Xt(e))throw mr(e.field);let n=(o=>ut(e.field,o,t))({is:{}});return he({...e,field:"relation"},{relation:null})===true?_e(n):n},IE=(e,t)=>te(e.field,t?.map,t?.model),Sl=Xe(),qE=(e,t,r)=>{if(t==="list"||Dt(t)||IE(e,r)?.isRequired!==true)return null;let n=e.field.split(".").slice(0,-1).join(".");return n?ut(n,{is:{}},r):Sl},Ic=(e,t)=>{let r=m=>ut(e.field,m,t),n=Rl(e,t),o=()=>Ol(e,t),i=$s(e,t?.map,t?.model);if(n==="relation")return VE(e,t);let s=qE(e,n,t),a=s&&(s===Sl?lt():_e(s)),l=m=>s&&a?he({field:"f",operator:m,value:null},{f:null})===true?a:s:null;if(s&&a&&Xt(e)){let m=jc(n,i);return e.operator===h.isEmpty?U([a,...m.map(r)]):e.operator===h.notEmpty?we([s,...m.map(g=>r(Vc(g)))]):l(e.operator)}switch(e.operator){case h.exists:case h.notExists:{if(e.operator===h.exists)return n==="list"?_e(r({equals:null})):r({not:Pr(n)});let m=o();return m.length?U(m):r({equals:Pr(n)})}case h.isEmpty:case h.notEmpty:return xl(e.field,n,e.operator===h.isEmpty,i,t)}if(Ee(e)){let m=Ps(e,t?.map,t?.model,Iu(t),qu(t));if("problem"in m)throw ks(e.path,m.problem);let g=r({[m.key]:m.ref}),b=(O,$)=>$.isRequired===false?ut(O,{equals:null},t):null,S=(O,$)=>$.isRequired===false?ut(O,{not:null},t):Sl,w=b(e.field,m.field),R=b(m.columnPath,m.column);return e.operator===h.equals?w&&R?U([g,we([w,R])]):g:e.operator===h.notEquals?U([_e(g),...w?[we([w,S(m.columnPath,m.column)])]:[],...R?[we([S(e.field,m.field),R])]:[]]):g}let p=qc(e,t);if($e(e,p))return U(B.includes(e.operator)?o():[]);if(p===null&&$t.includes(e.operator)){let m=l(e.operator);if(m)return m}if(n==="list"&&cr.includes(e.operator)&&Array.isArray(p))return de(Os(e,p),t);if(n==="list"&&Array.isArray(p)&&p.includes(null))throw I("toPrisma",`A list holding null in '${e.field}'`);if(n==="list"&&oe(e.caseInsensitive)&&xr("text",p))throw I("toPrisma",`A case-insensitive comparison on the list '${e.field}'`);let f=n==="enum"?te(e.field,t?.map,t?.model):void 0,d=f?Ws(e,p,f,t?.map):null;if(d){let m=r({in:d.values});return d.matchesNull?U([m,...o()]):m}if(cr.includes(e.operator)){let{values:m,hasNull:g}=Ze(p),b=El(e,t,n,m),S=Dt(n)?e.operator===h.in?U(m.map(w=>r(Ks("equals",w,b,n)))):we(m.map(w=>r(Ks("not",w,b,n)))):r({[e.operator]:m,...b});return e.operator===h.in?g?U([S,...o()]):S:g?we([S,s??r({not:Pr(n)})]):U([S,...o()])}let u=m=>{if(!Dt(n)||m!==h.contains)return r(ni({...e,operator:m},t));let g=r({array_contains:[BE(e,p,t,n)]});return typeof p=="string"?U([r(ni({...e,operator:m},t)),g]):g};if(e.operator===h.contains)return u(h.contains);let c=Bd.includes(e.operator)?_o[e.operator]:Vn.includes(e.operator)?h.between:void 0;if(c){if(Dt(n))throw I("toPrisma",`'${e.operator}' on the Json value '${e.field}'`,"it keeps values of other types");return U([_e(u(c)),...o()])}let y=r(ni(e,t));return e.operator===h.equals&&p===null?U([y,...kr(e.field,t)]):e.operator===h.notEquals&&n==="list"?p===null?_e(r({equals:null})):U([_e(r({equals:p})),...o()]):e.operator===h.notEquals&&p!==null?U([y,...o()]):y},qc=(e,t)=>{let r=fo(e,at(e),Or(e.field,t?.map,t?.model),"toPrisma",()=>oo(t).timeZone);return e.offset===void 0?r:Dc(r,e.offset)},ni=(e,t)=>{let r=fs(e);if(r)throw r;let n=Rl(e,t),o=()=>qc(e,t),i=p=>El(e,t,n,p),s=p=>{let f=o();if(n==="list"){if(p!=="contains")throw new Error(`Operator '${p}' does not apply to the list '${e.field}'.`);return {has:f}}let d=Dt(n)?WE[p]:p,u=typeof f=="string"?ve(f):f;return {[d]:u,...i(f)}},a=ds(e.operator,o());if(a)throw a;let l=ur(e.operator,"field");if(l&&jn.includes(e.operator))return {[l]:o()};switch(e.operator){case h.equals:{let p=o()??Pr(n);return Ks("equals",p,i(p),n)}case h.notEquals:{let p=o()??Pr(n);return Ks("not",p,i(p),n)}case h.in:case h.notIn:return {[e.operator]:o()};case h.contains:return s("contains");case h.startsWith:return s("startsWith");case h.endsWith:return s("endsWith");case h.matches:case h.notMatches:throw I("toPrisma",`'${e.operator}'`,"Prisma has no pattern filter");case h.between:case h.notBetween:{let[p,f]=Qe(ot(o(),e.operator));return {gte:p,lte:f}}default:throw new Error(`Operator '${e.operator}' is built by buildFieldRule`)}},BE=(e,t,r,n)=>{if(typeof t=="object"&&t!==null)throw new Error(`Membership of an object or a list in the Json array '${e.field}' has no exact Prisma form; use toSql() or check().`);if(El(e,r,n,t).mode)throw I("toPrisma",`A case-insensitive member of the Json array '${e.field}'`);return t},WE={contains:"string_contains",startsWith:"string_starts_with",endsWith:"string_ends_with"},ut=(e,t,r)=>{if(!r?.map||!r?.model)return Xr(e,t);let n=ie(e,r.map,r.model),o=n.hops.find(s=>s.entry.isList);if(o)throw Kn(e,o);let i=e.split(".");switch(n.kind){case "fallback":case "direct":return Xr(e,t);case "bridge":return Yr();case "past-scalar":throw Gn(e,n.column);case "json-path":{let s={path:n.jsonPath,...t},a=i.slice(0,n.stopIndex).join(".");return Xr(a,s)}}};var Wc=(e,t,r)=>{if(Pe(e)){let n=ro(e);if(!n)throw At("toPrisma");return de(n,t,r)}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(!xt.includes(e.aggregate.mode))throw gr(e.aggregate.mode);if(!e.aggregate.field)throw new Error("Prisma aggregate rules require aggregate.field to specify the numeric field on the related model.");return UE(e,t,r)},UE=(e,t,r)=>{let n=so(e.field,t.map,t.model,"Aggregate rules");if(e.condition&&Ct(e.condition,t.map,n.target))return Yr();let o=e.aggregate.field??"",i=ce(t.map,n.target,o);if(!i)throw new Error(`aggregate.field '${o}' does not exist on model '${n.target}'.`);if(i.kind!=="scalar"||Ue(i)||!Q.includes(i.type))throw new Error(`aggregate.field '${o}' on model '${n.target}' must be a numeric scalar, got '${i.kind==="scalar"?i.type:i.kind}'.`);let s=()=>e.condition?de(e.condition,Zr({...t,model:n.target},t,true),r):Xe();if(He.includes(e.operator))return Bc(e,e.operator===h.exists,s,n,t,r);let a=io(t)(e);if(a===null||$e(a,a.value))return B.includes(e.operator)?Bc(e,false,s,n,t,r):lt();let l=e.aggregate.mode==="sum"?0:null,p=Ko(a,[{}],void 0,{},{value:l})===true,f=p?Ye(a):a,d=ni(f,t),u={[e.aggregate.mode==="sum"?"_sum":"_avg"]:d},c=Vn.includes(f.operator)?_e({[o]:u}):{[o]:u},y=Jo(r,n,s(),c,p);return p?U([y,...kr(e.field,t)]):y},Bc=(e,t,r,n,o,i)=>{if(e.aggregate.mode==="sum")return t?Xe():lt();let s=we([r(),{[e.aggregate.field]:{not:null}}]),a=Jo(i,n,s,void 0,!t);return t?a:U([a,...kr(e.field,o)])};var Kc=(e,t,r)=>{if(!e.field)throw new Error("toPrisma: count-based ArrayRule requires a field path");let n=so(e.field,t.map,t.model,"Count operators");if(e.condition===void 0)throw Ie(e.arrayOperator);if(e.count===void 0)throw Bn(e.arrayOperator);let o=e.count;if(e.arrayOperator===x.atLeast&&o===0)return Xe();let i=de(e.condition,Zr({...t,model:n.target},t,true),r),s=$l(e),a=s?Uc(x.atLeast,e.arrayOperator===x.atMost?o+1:1,n.targetKey):Uc(e.arrayOperator,o,n.targetKey);return Jo(r,n,i,a,s)},Uc=(e,t,r)=>{let n=ur(e,"array");if(!n)throw new Error(`'${e}' does not count`);return {[r]:{_count:{[n]:t}}}};var Gc=(e,t,r)=>{let n=zc(e,t,r);return e.field&&$l(e)&&!Hc(e.field,t)?U([n,...kr(e.field,t)]):n},$l=e=>he({...e,field:"items"},{items:[]})===true,KE=e=>{let t=Ma(e);if(!t)return null;let{count:r,...n}=e;return {...n,arrayOperator:t}},zc=(e,t,r)=>{if(Pe(e)){let s=ro(e);if(!s)throw At("toPrisma");return de(s,t,r)}if(e.condition!==void 0&&!Id.includes(e.arrayOperator)&&Ct(e.condition,t?.map,Jc(e,t)?.model))return Yr();let n=KE(e);if(n)return zc(n,t,r);if(Co.includes(e.arrayOperator)){if(t?.map&&t?.model&&r)return Kc(e,t,r);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 ls("toPrisma");let{field:o}=e;if(Hc(o,t))return GE(e,o,Ke({field:o},t?.map,t?.model),t);let i=zE(e,t,r);return ut(e.field,i,t)},Hc=(e,t)=>{let r=Ke({field:e},t?.map,t?.model);return r==="list"||r==="json"||r==="json-path"},GE=(e,t,r,n)=>{switch(e.arrayOperator){case x.empty:case x.notEmpty:return xl(t,r,e.arrayOperator===x.empty,false,n);default:throw I("toPrisma",`'${e.arrayOperator}' over the ${r==="list"?"list":"Json array"} '${t}'`,r==="list"?"test a list's membership with 'contains'":void 0)}},Jc=(e,t)=>{if(!t?.map||!t?.model||!e.field)return t&&Zr({...t});let r=zo(e.field,t.map,t.model);return Zr(r?{...t,model:r}:{...t})},zE=(e,t,r)=>{let n=Jc(e,t);switch(e.arrayOperator){case x.all:if(!e.condition)throw Ie(e.arrayOperator);return {none:de(Ye(e.condition,io(n)),n,r)};case x.any:if(!e.condition)throw Ie(e.arrayOperator);return {some:de(e.condition,n,r)};case x.none:if(!e.condition)throw Ie(e.arrayOperator);return {none:de(e.condition,n,r)};case x.empty:return {none:{}};case x.notEmpty:return {some:{}};default:throw ue(e.arrayOperator,"array")}};var Qc=(e,t)=>{let r=t?.map,n=Ke({field:e.field},r,t?.model);if(n==="json"||n==="json-path")throw I("toPrisma",`A date rule on the Json value '${e.field}'`,"Prisma compares Json text");let o=te(e.field,r,t?.model);if(o&&!M(o)&&Ge(o)!==N.DateTime)throw I("toPrisma",`A date rule on the ${o.type} field '${e.field}'`,`Prisma compares it as ${o.type}, not as an instant`);let i=B.includes(e.dateOperator)?Ol(e,t):[],s=HE(e,t);if(s===null)return U(i);let a=ut(e.field,s,t),l=Vn.includes(e.dateOperator)?_e(a):a;return U([l,...i])},HE=(e,t)=>{let r=oo(t),n=Ho,o=c=>e.offset===void 0?c:Fc(c,e.offset,t),i=c=>{if(c==null)return null;if(!ee(c))return Ss(c,r.timeZone);let y=kt(c,n);return y&&Hn(y,e.dateOperator,r).toDate()},s=()=>{let c=at(e);if(c==null)return c;let y=e.offset===void 0?void 0:at(e.offset),m=Qt(c,y);if(m)throw m;return c},a=()=>o(i(s())),l=()=>{let c=s();if(c==null)return null;let y=ot(c,e.dateOperator).map(i);if(y[0]===null||y[1]===null)return null;let[m,g]=Qe(y).map(o);return m&&g?[m,g]:null},p=()=>{let c=s();if(c==null)return null;if(!ee(c))throw nt(e.dateOperator);let y=kt(c,n);if(!y)return null;let[m,g]=Jn(y,r);return [m.toDate(),g.toDate()]},f=c=>{let y=a();return y===null?null:{[c]:y}},d=c=>c?{gte:c[0],lte:c[1]}:null,u=ur(e.dateOperator,"date");if(u)return f(u);switch(e.dateOperator){case A.within:case A.notWithin:return d(p());case A.between:case A.notBetween:return d(l());case A.dayIn:case A.dayNotIn:throw I("toPrisma",`'${e.dateOperator}'`);default:throw ue(e.dateOperator,"date")}};var vl=(e,t,r)=>{if(typeof e=="boolean")return e?{}:lt();Hi(e,"toPrisma");let n=pe(e);(n==="field"||n==="date")&&vs(e.field,t?.map,t?.model);let o=e;switch(n){case "all":return zu(o,t,r);case "any":return Hu(o,t,r);case "if":return Ju(o,t,r);case "array":return Gc(o,t,r);case "aggregate":return Wc(o,t,r);case "date":return Qc(o,t);case "field":return Ic(o,t);default:throw vt()}};Ku(vl);var Yc=(e,t,r)=>t&&r?on(e,t,r):e,ct=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gs=(e,t,r)=>{let n=ce(e,t,r);return n?.kind==="object"&&!n.isList?n.type:null},JE=["some","every","none"],oi=e=>Object.entries(e).flatMap(([t,r])=>t!=="AND"?[{[t]:r}]:(Array.isArray(r)?r:[r]).flatMap(o=>ct(o)?oi(o):[{AND:o}])),Al=(e,t,r)=>{let n=Object.keys(e);if(n.length!==1||!Gs(t,r,n[0]))return null;let o=e[n[0]];if(!ct(o))return null;let i=Object.keys(o);return i.includes("isNot")?null:i.includes("is")?i.length===1&&ct(o.is)?{key:n[0],isForm:true,inner:o.is}:null:oi(o).length?{key:n[0],isForm:false,inner:o}:null},Xc=(e,t,r)=>{let n=Al(e,t,r);if(!n)return [];let o=Gs(t,r,n.key);return [n.key,...oi(n.inner).flatMap(i=>Xc(i,t,o).map(s=>`${n.key}.${s}`))]},em=(e,t,r)=>{if(!ct(e))return null;let n=Object.keys(e);if(n.length!==1)return null;let o=Gs(t,r,n[0]),i=e[n[0]];if(!o||!ct(i))return null;let s=Object.keys(i);if(s.length===1&&s[0]==="is"&&i.is===null)return n[0];let a=em(i,t,o);return a?`${n[0]}.${a}`:null},QE=(e,t,r)=>{let n=e.map(o=>ct(o)?on(o,t,r):o);return n.some((o,i)=>o!==e[i])?n:e},Nl=(e,t)=>{let r=false,n={};for(let[o,i]of Object.entries(e))n[o]=t(o,i),n[o]!==i&&(r=true);return r?n:e},ZE=(e,t,r,n)=>{if(e==="AND"||e==="OR"||e==="NOT")return Array.isArray(t)?QE(t,r,n):ct(t)?on(t,r,n):t;let o=ce(r,n,e);if(o?.kind!=="object"||!ct(t))return t;if(o.isList)return Nl(t,(s,a)=>JE.includes(s)&&ct(a)?on(a,r,o.type):a);let i=Object.keys(t);return i.length===1&&(i[0]==="is"||i[0]==="isNot")?Nl(t,(s,a)=>ct(a)?on(a,r,o.type):a):on(t,r,o.type)},Zc=(e,t,r)=>Nl(e,(n,o)=>ZE(n,o,t,r)),YE=(e,t,r,n)=>{let o=Object.keys(e);if(o.length!==1||o[0]!=="OR"||!Array.isArray(e.OR))return null;let i=e.OR,s=i.filter(a=>{let l=em(a,r,n);return l===null||!t.has(l)});return s.length===i.length||s.length===0?null:s.length===1&&ct(s[0])?oi(s[0]):[{OR:s}]},on=(e,t,r)=>{let n=oi(e),o=false;for(let l=true;l;){l=false;let p=new Set(n.flatMap(f=>Xc(f,t,r)));n=n.flatMap(f=>{let d=YE(f,p,t,r);return d?(l=o=true,d):[f]});}let i=new Map;for(let l of n){let p=Al(l,t,r);p&&i.set(p.key,[...i.get(p.key)??[],p]);}if(!o&&![...i.values()].some(l=>l.length>1))return Zc(e,t,r);let s=new Set,a=[];for(let l of n){let p=Al(l,t,r),f=p?i.get(p.key)??[]:[];if(!p||f.length<2){a.push(Zc(l,t,r));continue}if(s.has(p.key))continue;s.add(p.key);let d=Gs(t,r,p.key),u=on(we(f.map(c=>c.inner)),t,d);a.push({[p.key]:f.some(c=>c.isForm)?{is:u}:u});}return we(a)};var rm=async(e,t)=>{let r=e.steps.filter(i=>i.operation==="groupBy"),n=e.steps.find(i=>i.operation==="where");if(!n)throw new Error("executePrismaPlan: result has no where step");let o=[];for(let i of r){let s=nm(t,i.model),a=tm(i.args,i.refs,o,t),l=await s[i.operation](a);o.push(l.map(p=>p[i.extract]).filter(p=>p!=null));}return tm(n.where,n.refs,o,t)},nm=(e,t)=>{let r=t.charAt(0).toLowerCase()+t.slice(1),n=e[r];if(!n)throw new Error(`executePrismaPlan: no delegate for model '${t}'. Ensure prismaDelegate has a key '${r}'.`);return n},XE=(e,t)=>{let r=nm(e,t.model).fields,n=r&&Object.hasOwn(r,t.field)?r[t.field]:void 0;if(n===void 0)throw new Error(`executePrismaPlan: the '${t.model}' delegate has no field reference '${t.field}' (fields.${t.field}).`);return n},ex=(e,t)=>t.reduce((r,n)=>r!==null&&typeof r=="object"&&Object.hasOwn(r,n)?r[n]:void 0,e),Pl=(e,t,r)=>{if(t.length===0)return r;let[n,...o]=t,i=e,s=Array.isArray(e)?[...e]:{...i};return s[n]=Pl(i[n],o,r),s},tm=(e,t,r,n)=>{let o=e;for(let{path:i}of t??[]){let s=ex(e,i);if(s&&typeof s.__step=="number"){let a=s.__step;if(a>=r.length)throw new Error(`Step ref __step: ${a} out of range (${r.length} steps executed)`);o=Pl(o,i,r[a]);}else if(s&&typeof s.__field=="object"&&s.__field!==null)o=Pl(o,i,XE(n,s.__field));else throw new Error(`executePrismaPlan: no reference at the recorded location ${i.join(".")}`)}return o};var tx=e=>e?.map?{...e,map:ke(e.map,e.mapName,"toPrisma")}:e,ii=(e,t)=>Bs(e,t,"toPrisma",rx),rx=(e,t)=>{let r={steps:[]},n=tx(t),o=Yc(vl(e,n,r),n?.map,n?.model),i=(s,a)=>{let l=Fu(a);return l.length?{...s,refs:l}:s};return {steps:[...r.steps.map(s=>i(s,s.args)),i({operation:"where",where:o},o)]}};var nx=/^-?\d+(\.\d+)?$/,om=e=>typeof e=="string"?nx.test(e)?Number(e):e:typeof e=="object"&&e!==null&&typeof e.toNumber=="function"?e.toNumber():e,kl=(e,t)=>e?.kind!=="scalar"||e.type!=="Decimal"?t:Array.isArray(t)?t.map(om):om(t);var zs=(e,t,r,n,o)=>{let i=`${r.mapName}\0${r.modelName}`;for(let a of t){if(typeof a=="boolean")continue;let l=e.memo?.compiles.get(a)??new Map;e.memo?.compiles.set(a,l);let p=l.get(i);if(p===void 0){let[f]=vr(a,{target:"toPrisma",map:e.lens,mapName:r.mapName,model:r.modelName}).errors;p=f?f.message:null,l.set(i,p);}if(p!==null)return new T(`${n}: ${p}`,"unsupported_clamp")}if(o)return null;let s=false;for(let a of t)H(a,l=>{("aggregate"in l||Lo(l))&&(s=true);});return s?new T(`${n} needs a counting step (executePrismaPlan), which a relation's where in a select can't run`,"unsupported_clamp"):null},Hs=(e,t)=>{try{return t()}catch(r){throw r instanceof T||r instanceof L?r:new T(`${e}: ${r.message}`,"unsupported_clamp")}};var im=(e,t)=>e===""?t:t===""?e:`${e}.${t}`,De=e=>{let t=new Set,r=o=>{o&&t.add(o);},n=(o,i)=>{let s=ze(o,i);return "outOfBounds"in s?null:im(s.scope,s.path)};return H(e,(o,i)=>{if(We(o))return;for(let l of wr(o))r(_(l)?n(l,i):l);let s=typeof o.field=="string"&&o.field!==""?n(o.field,i):null;if(r(s),!xe(o))return;let a=s??i[i.length-1];for(let l of Zn(o))r(im(a,l));return [...i,a]},[""]),[...t]};var Tl=(e,t,r,n,o)=>{let i={};for(let[s,a]of Object.entries(n.fields)){if(!_t(t,s))continue;let l=t.enumValuesByField.get(s),p=o(s)?.filter(d=>l===void 0||l.includes(d.value)),f=mo(e,t,r,s,"groupBy")?t.sourceGroupBys.get(s):void 0;i[s]={...a,...l!==void 0&&{values:l},...p!==void 0&&{options:p},...f!==void 0&&{groupBy:f}};}return i},sm=(e,t,r,n,o)=>{let{mapName:i,modelName:s}=t,a=C(E(e.lens.maps,i),s),l=Tl(e,r,t,a,c=>{let y=o.get(`${n}|${c}`),m=r.enumValuesByField.get(c);return y??E(a.fields,c)?.options??m?.map(g=>({value:g,label:g}))}),p={};for(let[c,y]of r.sources)_t(r,c)&&(p[c]=y);let f={};for(let[c,y]of r.sourceLabels)_t(r,c)&&mo(e,r,t,c,"label")&&(f[c]=y);let d={};for(let[c,y]of r.sourceGroupBys)_t(r,c)&&mo(e,r,t,c,"groupBy")&&(d[c]=y);let u={};for(let c of r.sourcesFromMapDefaults.keys()){if(!Is(e,i,s,c))throw qs(n,i,s,c);Object.hasOwn(p,c)&&(u[c]="mapDefaults");}return {mapName:i,model:s,fields:l,whereClauses:r.whereClauses,sources:p,sourceLabels:f,sourceGroupBys:d,sourceFrom:u}},am=e=>{let t=new Map;for(let r of e.sourceValues??[])t.set(`${r.path}|${r.field}`,r.options);return t},lm=(e,t={})=>si(F(e),t),si=(e,t={})=>{let r=am(t),n={};for(let{path:o,at:i,effect:s}of rr(e))n[o]=sm(e,i,s,o,r);return n},pm=(e,t,r={})=>Cl(F(e),t,r),Cl=(e,t,r={})=>{let n={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};if(t!=="")for(let s of Rr(e.lens.maps,n,t)){let a=V(e,s.at.mapName,s.at.modelName,s.at.relPath);if(!s.next||!a.relations.has(s.field))return null;n={...s.next,relPath:[...s.at.relPath,s.field]};}if(!C(E(e.lens.maps,n.mapName),n.modelName))return null;let o=V(e,n.mapName,n.modelName,n.relPath),i=[e.lens.model,...n.relPath].join(".");return sm(e,n,o,i,am(r))};var Js=(e,t,r,n,o)=>{let i=e.split("."),{hops:s}=Te(t,{mapName:r,modelName:n,relPath:[]},e),a=s.find((d,u)=>d.isList&&u<i.length-1);if(a)return `${o} cannot traverse to-many relation '${i[s.indexOf(a)]}'`;if(s.length===i.length)return `${o} must end on a scalar column, '${i.at(-1)}' is a relation`;let l=s.at(-1)??{map:r,model:n},p=i[s.length],f=ce(E(t,l.map),l.model,p);return f?M(f)?`${o} relation '${p}' has no resolvable target`:s.length===i.length-1?null:`${o} segment '${p}' is not a relation`:`${o} segment '${p}' not on model '${l.model}'`},fm=(e,t,r,n,o,i,s,a)=>{let l=Js(o,e.lens.maps,t,r,i);if(l)throw new T(`${i} '${o}': ${l}`,"invalid_source");let{hops:p}=Te(e.lens.maps,{mapName:t,modelName:r,relPath:n},o),f=p.slice(0,o.split(".").length-1);for(let d of f){let u=d.relPath.join(".");if(s.has(u))continue;s.add(u);let c=V(e,d.map,d.model,d.relPath);for(let y of c.whereClauses)a.push(lo(y,d.prefix));}},ox=(e,t,r,n,o,i)=>{let s=[],a=new Set;for(let l of o)fm(e,t,r,n,l,"groupBy",a,s);return i?.includes(".")&&fm(e,t,r,n,i,"label",a,s),s},ai=(e,t)=>{let r=ge(e,t);return r==null||typeof r=="object"?void 0:String(r)},Qs=(e,t)=>{let r=[];for(let n of t){let o=ai(e,n);if(o===void 0)return;r.push(o);}return r},Ll=(e,t)=>JSON.stringify([e??null,t]),ix=(e,t,r,n)=>{let o=Ll(n,t),i=e.get(o);i===void 0?e.set(o,{value:t,...r!==void 0?{label:r}:{},...n!==void 0?{groups:n}:{}}):r!==void 0&&(i.label===void 0||r<i.label)&&e.set(o,{...i,label:r});},Zs=(e,t,r,n,o)=>{let i=ge(t,r),s=n==null?void 0:String(n);for(let a of Array.isArray(i)?i:[i])a==null||typeof a=="object"||ix(e,String(a),s,o);},Ys=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??[],i=r.groups??[];for(let s=0;s<Math.max(o.length,i.length);s++){let a=(o[s]??"").localeCompare(i[s]??"","en",{numeric:true});if(a!==0)return a}return (t.label??t.value).localeCompare(r.label??r.value,"en",{numeric:true})||t.value.localeCompare(r.value,"en",{numeric:true})}),sx=(e,t,r,n,o)=>{let{hops:i}=ie(o,t,n),s=o.split("."),a=i.at(-1)?.entry.type??n,l=s[i.length];for(let{endpoints:p}of e.bridges??[]){let[f,d]=p;for(let[u,c]of [[f,d],[d,f]])if(u.fieldMap===r&&u.model===a&&Me(c)===l)return [...s.slice(0,i.length),u.on].join(".")}throw new T(`'${o}' crosses no bridge the lens declares on ${a}`,"not_in_lens")},Xs=(e,t,r,n)=>{let o=ke(e,t,"toPrisma");return [...new Set(n.map(i=>Er(i,o,r)?sx(e,o,t,r,i):i))]},ax=(e,t,r,n)=>{if(t.length===0)return [];let o={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},{hops:i,end:s}=Te(e.lens.maps,o,t.join("."));if(!s)throw new T(`source at '${t.join(".")}': its path doesn't resolve on the field maps`,"not_in_lens");let a=[o,...i.map(f=>({mapName:f.map,modelName:f.model}))],l=t.length;for(;l>0&&!r.has(t.slice(0,l).join("."));)l--;let p=l>0?r.get(t.slice(0,l).join("."))??null:null;for(let f=l;f<t.length;f++){let d=$=>{p=$,r.set(t.slice(0,f+1).join("."),$);},u=a[f],c=V(e,u.mapName,u.modelName,t.slice(0,f)).whereClauses,y=p===null?c:[...c,p];if(y.length===0&&!n){d(null);continue}let m=E(e.lens.maps,u.mapName),g=m&&ce(m,u.modelName,t[f]);if(!g)throw new T(`source at '${t.join(".")}': '${t[f]}' isn't declared on ${u.modelName}`,"not_in_lens");let b=a[f+1],S=Me({fieldMap:u.mapName,model:u.modelName}),w=g.kind==="bridge"?ce(E(e.lens.maps,b.mapName),b.modelName,S):void 0,R=g.kind==="bridge"?w&&{field:S,entry:w}:m?Ts(m,u.modelName,t[f],g):null;if(!R&&y.length===0){d(null);continue}if(!R)throw new T(`source at '${t.join(".")}': '${t[f]}' on ${u.modelName} declares no inverse, so the clamps above can't be carried down to it`,"unsupported_clamp");let O=K(y);try{let $={field:R.field,operator:"exists"};d(R.entry.isList?{field:R.field,arrayOperator:"any",condition:O}:y.length?K([$,lo(O,R.field)]):$);}catch($){throw $ instanceof T?new T(`source at '${t.join(".")}': the clamps above can't be carried down to it \u2014 ${$.message}`,$.code):$}}return p===null?[]:[p]},dm=e=>Tr(F(e)),Tr=(e,t=si(e))=>{let r=new Map,n=o=>{let i=r.get(o)??new Map;return r.set(o,i),i};return Object.entries(t).flatMap(([o,i])=>Object.keys(i.sources).map(s=>{let a=E(i.sourceLabels,s),l=E(i.sourceGroupBys,s),p=Object.hasOwn(i.sourceFrom,s),f={mapName:i.mapName,modelName:i.model,relPath:o.split(".").slice(1)},d=V(e,f.mapName,f.modelName,f.relPath),u=(d.sourceWheres.get(s)??[]).map(P=>rn(P,e,f)),c=ox(e,f.mapName,f.modelName,f.relPath,l??[],a),y=E(i.fields,s)?.values,m=p?d.sourcesFromMapDefaults.get(s):void 0,g=m===void 0?void 0:e.chain[m],S=[...ax(g===void 0?e:{...e,skipClampsOf:g},f.relPath,n(g),g===void 0&&!p),...u,...c,...y?[{field:s,operator:"in",value:[...y]}]:[]],w=K([...i.whereClauses,...S]),R=K([...i.whereClauses,...u,...c,...y?[{field:s,operator:"in",value:[...y]}]:[]]),O=e.lens.bridges?.length?ke(e.lens,f.mapName,"toPrisma"):void 0,$=O?[...De(w),...a===void 0?[]:[a],...l??[]].find(P=>Er(P,O,f.modelName)):void 0,k=$!==void 0&&O?K(qa(w).filter(P=>Ct(P,O,f.modelName))):void 0,ae=zs(e,[...i.whereClauses,...S],f,`source '${s}' at '${o}'`,true);if(ae)throw ae;return {path:o,visit:i,field:s,...p&&{from:"mapDefaults"},...a!==void 0&&{label:a},...l!==void 0&&{groupBy:l},where:w,rowWhere:R,...$!==void 0&&{bridged:$},...k!==void 0&&{recheck:k}}}))};var Dl=(e,t)=>{for(let r of t){let n=e;for(let o of r.split("."))n=er(n,o,()=>({}));}return e},ea=(e,t)=>{for(let[r,n]of Object.entries(t))ea(er(e,r,()=>({})),n);return e},Fl=e=>e.whereClauses.flatMap(De),um=(e,t)=>{let r=new Map;for(let n of t){if(n.from)continue;let o=n.path.split(".").slice(1).join("."),i=[n.field,...n.label===void 0?[]:[n.label],...n.groupBy??[],...De(n.rowWhere)];r.set(o,[...r.get(o)??[],...n.bridged===void 0?i:Xs(e.lens,n.visit.mapName,n.visit.model,i)]);}return r},cm=(e,t)=>e.get(t.relPath.join("."))??[],lx=(e,t,r)=>Dl(ea({},r??{}),Fl(V(e,t.mapName,t.modelName,t.relPath))),mm=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]}),jl=(e,t,r)=>({...r,relPath:[...e.relPath,t]}),px=(e,t,r,n)=>{if(!r.whereClauses.length)return;let o=K(r.whereClauses),i=zs(e,r.whereClauses,t,`toLensSelect: the clamp on '${t.relPath.join(".")}'`,false);if(i)throw i;if(e.inspect)return;let s=Hs(`toLensSelect: the clamp on '${t.relPath.join(".")}'`,()=>ii(o,{...n,map:e.lens,mapName:t.mapName,model:t.modelName})),{where:a}=s.steps[0];return Object.keys(a).length?a:void 0},fx=(e,t,r,n)=>{let o=C(e,n.type)?.fields??{},i=a=>{let l=a===void 0?void 0:E(o,a);return l&&!M(l)?a:void 0},s=e?Ts(e,t,r,n):null;return i(n.toFields?.[0])??i(s?.entry.fromFields?.[0])??i("id")},gm=(e,t,r,n,o,i)=>{let s=C(E(e.lens.maps,t.mapName),t.modelName)?.fields??{},a=V(e,t.mapName,t.modelName,t.relPath),l=r==="paths"?n:Dl(ea({},n),[...Fl(a),...cm(i,t)]),p={};for(let[f,d]of Object.entries(s)){let u=r!=="paths"&&_t(a,f),c=E(l,f);if(!u&&c===void 0||d.kind==="bridge")continue;if(d.kind!=="object"){p[f]=true;continue}let y=u?"declared":"paths";if(y==="paths"&&c===void 0)continue;let m=jl(t,f,{mapName:t.mapName,modelName:d.type}),g=gm(e,m,y,c??{},o,i),b=d.isList&&y!=="paths"&&c===void 0?px(e,m,V(e,m.mapName,m.modelName,m.relPath),o):void 0,S=Object.keys(g).length?void 0:fx(E(e.lens.maps,t.mapName),t.modelName,f,d),w=S===void 0?g:{[S]:true};Object.keys(w).length&&(p[f]={select:w,...b&&{where:b}});}return p},ym=(e,t={})=>Vl(F(e),t),Vl=(e,t={},r=Tr(e))=>{let n=gm(e,mm(e),"declared",{},t,um(e,r));if(!Object.values(n).some(o=>o===true)){let o=E(C(E(e.lens.maps,e.lens.mapName),e.lens.model)?.fields,"id");o&&!M(o)&&(n.id=true);}return {select:n}},Ml=(e,t)=>e==null?e:Array.isArray(e)?e.flatMap(r=>{let n=typeof r=="object"&&r!==null?t(r):null;return n===null?[]:[n]}):typeof e=="object"?t(e):null,_l=(e,t,r,n)=>{let o={},i=C(E(e.lens.maps,t.mapName),t.modelName);for(let[s,a]of Object.entries(n)){if(!Object.hasOwn(r,s))continue;let l=E(i?.fields,s),p=l?st(l,t.mapName):null;o[s]=p?Ml(r[s],f=>_l(e,jl(t,s,p),f,a)):kl(l,r[s]);}return o},hm=(e,t,r,n,o,i,s)=>{let a=V(e,t.mapName,t.modelName,t.relPath);if(!a.whereClauses.every(d=>he(d,r,i)===true))return null;let l=C(E(e.lens.maps,t.mapName),t.modelName)?.fields??{},p=o?Dl(ea({},n),[...Fl(a),...cm(s,t)]):{},f={};for(let[d,u]of Object.entries(l)){if(!Object.hasOwn(r,d))continue;let c=E(p,d),y=st(u,t.mapName);if(!y){(_t(a,d)||c!==void 0)&&(f[d]=kl(u,r[d]));continue}let m=jl(t,d,y);if(_t(a,d)){let g=!Array.isArray(r[d])||c!==void 0;f[d]=Ml(r[d],b=>hm(e,m,b,c??{},o,i,s)??(o&&g?_l(e,m,b,lx(e,m,c)):null));}else c!==void 0&&(f[d]=Ml(r[d],g=>_l(e,m,g,c)));}return f},wm=(e,t,{keepClampColumns:r=false,...n}={})=>{let o=F(e),i=mm(o),s=r?um(o,Tr(o)):new Map;return t.flatMap(a=>{let l=hm(o,i,a,{},r,n,s);return l===null?[]:[l]})};var dx="materializeSources needs fetched or keepClampColumns rows, not viewer rows",Il=(e,t,r)=>new L(`${e}: a row at '${t}' ${r}${r.includes(":")?" \u2014 rows across a bridge hold the far side inline under its bridge field":""}`),li=(e,t,r,n,o,i=dx)=>{for(let s of o){let a=[r];for(let{index:l,field:p,entry:f,next:d}of Rr(e.lens.maps,t,s)){if(!f)break;let u=s.split(".").slice(0,l+1).join("."),c=[];for(let y of a){if(y===null||typeof y!="object")continue;if(!Object.hasOwn(y,p))throw Il(i,n,`lacks '${u}', which a read needs`);let m=y[p];if(d&&m==null&&f.fromFields?.some(g=>{let b=y[g];return b!=null}))throw Il(i,n,`'${u}' is null while its key is set \u2014 a projection hid the row`);if(!(!d||m===null||m===void 0)){if(Array.isArray(m)!==(f.isList===true))throw Il(i,n,`'${u}' holds ${Array.isArray(m)?"a list where it names one row":"one row where it names a list"}`);c.push(...Array.isArray(m)?m:[m]);}}if(!d)break;a=c;}}},ql=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};return [r,...Te(e.lens.maps,r,t.split(".").slice(1).join(".")).hops.map(n=>({mapName:n.map,modelName:n.model,relPath:n.relPath}))]},ux=(e,t,r,n)=>{let o=r.split(".").slice(1),i=ql(e,r),s=(l,p)=>{let f=i[l],d=V(e,f.mapName,f.modelName,f.relPath).whereClauses,u=K(d),c=d.flatMap(De),y=[e.lens.model,...o.slice(0,l)].join(".");return p.filter(m=>(li(e,f,m,y,c),he(u,m,n)===true))},a=s(0,t);for(let[l,p]of o.entries()){let f=[],d=[e.lens.model,...o.slice(0,l)].join(".");for(let u of a){li(e,i[l],u,d,[p]);let c=ge(u,p);Array.isArray(c)?f.push(...c):c!=null&&f.push(c);}a=s(l+1,f);}return {rows:a,visit:i[i.length-1]}},bm=(e,t,r)=>{let n=F(e);return Tr(n).map(({path:o,visit:i,field:s,from:a,label:l,groupBy:p,rowWhere:f})=>{if(a)throw new L(`materializeSources: '${o}.${s}' offers its model's own source, which a fetched collection can't hold \u2014 query it with toSourceQueries and materializeSourceQuery.`);let d=[s,...De(f),...l===void 0?[]:[l],...p??[]],u=new Map,c=ux(n,t,o,r);for(let y of c.rows)li(n,c.visit,y,o,d),he(f,y,r)===true&&Zs(u,y,s,l===void 0?void 0:ai(y,l),p===void 0?void 0:Qs(y,p));return {path:o,mapName:i.mapName,model:i.model,field:s,options:Ys(u)}})};var ta={value:"value",query:"query"},Sm=(e,t,r={})=>{let{rowShape:n="prisma",lens:o,order:i=ta.value,...s}=r,a=n==="sql",{recheck:l}=e,p=y=>false,f=y=>true;if(l!==void 0){if(o===void 0)throw new L(`materializeSourceQuery: '${e.path}.${e.field}' reads across a bridge \u2014 its rows are candidates; pass { lens } with rows holding the far side`);let y=F(o),m=ql(y,e.path).at(-1);if(!m||m.mapName!==e.mapName||m.modelName!==e.model)throw new L(`materializeSourceQuery: the lens doesn't reach ${e.mapName}:${e.model} at '${e.path}' \u2014 pass the lens the query was compiled from`);let g=ke(y.lens,e.mapName,"toPrisma");p=w=>g!==void 0&&Er(w,g,e.model);let b=[...De(l),...e.label!==void 0&&p(e.label)?[e.label]:[],...(e.groupBy??[]).filter(p)],S="materializeSourceQuery needs candidate rows holding the far side of each bridge the source reads";f=w=>(li(y,m,w,e.path,b,S),he(l,w,s)===true);}let d=y=>e.label===void 0?void 0:a&&e.label.includes(".")&&!p(e.label)?y.__label:ai(y,e.label),u=e.groupBy?.map((y,m)=>a&&!p(y)?`__group_${m}`:y),c=new Map;for(let y of t)f(y)&&Zs(c,y,e.field,d(y),u===void 0?void 0:Qs(y,u));return {path:e.path,mapName:e.mapName,model:e.model,field:e.field,options:i===ta.query?[...c.values()]:Ys(c)}};var cx=(e,t)=>`${e}::${t}`,mx=(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 i=new Set([...n.values,...r.values]);o={...o,values:[...i]};}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);},Rm=(e,t={})=>Bl(F(e),t),Bl=(e,t={})=>{let{lens:r}=e,n=new Map;for(let l of t.sourceValues??[]){let p=`${l.mapName}::${l.model}::${l.field}`,f=n.get(p)??new Map;for(let d of l.options)f.set(Ll(d.groups,d.value),d);n.set(p,f);}let o=new Map;for(let{at:l,effect:p}of rr(e)){let{mapName:f,modelName:d}=l,u=C(E(r.maps,f),d);if(!u)continue;let c=cx(f,d),y=o.get(c);y||(y={mapName:f,modelName:d,fields:new Map},o.set(c,y));let m=Tl(e,p,l,u,g=>{let b=n.get(`${f}::${d}::${g}`);return b&&[...b.values()]});for(let[g,b]of Object.entries(m)){let S=b.groupBy,w=y.fields.get(g)?.groupBy;if(S!==void 0&&w!==void 0&&JSON.stringify(w)!==JSON.stringify(S))throw new T(`projectLens: '${d}.${g}' is grouped by different axes on different paths ([${w}] vs [${S}]) \u2014 one surface field cannot carry two partition namespaces`,"invalid_source");mx(y.fields,g,b);}}let i={};for(let{mapName:l,modelName:p,fields:f}of o.values()){let d=E(i,l);d||(d={models:{}},i[l]=d);let u={},c=new Map;for(let[y,m]of f)if(u[y]=m.options===void 0&&m.values?{...m,options:m.values.map(g=>({value:g,label:g}))}:m,m.kind==="enum"&&m.values){let g=c.get(m.type)??new Set;for(let b of m.values)g.add(b);c.set(m.type,g);}d.models[p]={...C(E(r.maps,l),p),fields:u};for(let[y,m]of c)d.enums??={},d.enums[y]=[...m];}let s=r.bridges?.filter(l=>{let[p,f]=l.endpoints,d=ce(E(i,p.fieldMap),p.model,Me(f)),u=ce(E(i,f.fieldMap),f.model,Me(p));return d!==void 0||u!==void 0}),a={maps:i};return s&&s.length>0&&(a.bridges=s),{...a,mapName:r.mapName,model:r.model}};var Om=(e,t,r,n,o)=>{if(e===void 0)return;let i=ao(e),s=n==="root.where"?null:i.bare;if(s!==null){o.push({path:n,code:"invalid_value_source",message:fl(s).message});return}let{escaping:a}=i;if(a!==null){o.push({path:n,code:"scope_out_of_bounds",message:dl(a).message});return}let l=new Set,p={...t,clamp:t.chain.length===0};for(let{mapName:f,modelName:d,relPath:u}of r)for(let c of Zo(e,p,f,d,u)){let y=`'${c.path}' ${c.message}`;l.has(y)||(l.add(y),o.push({path:n,code:c.code,message:y}));}},gx=(e,t,r,n,o,i)=>{let s={...r,chain:[...r.chain,t]},a=new Set;for(let l of n){let p=V(s,l.mapName,l.modelName,l.relPath);for(let[f,d]of Object.entries(e.sources??{})){let u=Nr(d);for(let c of ["label","groupBy"]){if(u[c]===void 0||a.has(`${f}|${c}`))continue;let y=c==="label"?u.label:ei(u.groupBy),m=c==="label"?p.sourceLabels.get(f):p.sourceGroupBys.get(f);if(JSON.stringify(y)!==JSON.stringify(m))continue;let b=(typeof m=="string"?[m]:m??[]).map(S=>ri(s,l,S)).find(S=>S!==null);if(b){a.add(`${f}|${c}`),i.push({path:`${o}.sources.${f}`,code:"invalid_source",message:`${c} '${String(u[c])}' crosses '${b}', a relation the lens does not show there (not turned on, or omitted)`});continue}mo(s,p,l,f,c)||(a.add(`${f}|${c}`),i.push({path:`${o}.sources.${f}`,code:"invalid_source",message:`${c} '${String(u[c])}' reads a column hidden by another layer`}));}}}},yx=(e,t,r,n)=>{for(let o of r){if(!t&&o.picks&&!o.picks.includes(e))return "not in ancestor's picks";if(o.omits?.includes(e))return "was omitted by ancestor"}return !t&&n?.picks&&!n.picks.includes(e)?"not visible from defaults.picks":n?.omits?.includes(e)?"already excluded by defaults":null},hx=(e,t,r,n,o,i,s,a,l,p,f,d,u=false)=>{let c=e.omits?.some(m=>{let g=E(i,m);return g===void 0||!M(g)});e.picks&&c&&p.push({path:`${l}`,code:"conflicting_selection",message:"cannot specify both picks and omits of a column"});for(let m of ["picks","omits"])for(let g of e[m]??[]){let b=E(i,g);if(!b){p.push({path:`${l}.${m}`,code:"not_in_lens",message:`field '${g}' not on model`});continue}let S=M(b);if(S&&m==="picks"){p.push({path:`${l}.picks`,code:"wrong_kind",message:`'${g}' is a relation: picks names columns; turn a relation on with \`relations\``});continue}let w=yx(g,S,t,r);w&&p.push({path:`${l}.${m}`,code:"not_visible",message:`'${g}' ${w}`});}let y=(m,g,b)=>{let S=E(i,g);if(!S){p.push({path:`${l}.${m}`,code:"not_in_lens",message:`field '${g}' not on model`});return}if(S.kind!=="enum"){p.push({path:`${l}.${m}`,code:"wrong_kind",message:`field '${g}' is not an enum field`});return}let w=Hr(S,a);for(let R of b)w&&!w.includes(R)&&p.push({path:`${l}.${m}.${g}`,code:"value_not_allowed",message:`'${R}' is not a known value of enum '${S.type}'`});};for(let[m,g]of Object.entries(e.enumPicks??{}))y("enumPicks",m,g);for(let[m,g]of Object.entries(e.enumOmits??{}))y("enumOmits",m,g);Om(e.where,f,d,`${l}.where`,p);for(let[m,g]of Object.entries(e.sources??{})){let b=E(i,m);if(!b){p.push({path:`${l}.sources`,code:"not_in_lens",message:`field '${m}' not on model`});continue}if(M(b)){p.push({path:`${l}.sources.${m}`,code:"wrong_kind",message:`'${m}' is a relation: a source offers a column's values`});continue}let S;try{S=Nr(g);}catch($){if(!($ instanceof T))throw $;p.push({path:`${l}.sources.${m}`,code:$.code,message:$.message});continue}let w=S.from;if(w!==void 0){let $=w!=="mapDefaults"?`from takes 'mapDefaults', not '${String(w)}'`:u?"a mapDefaults source is what a path source's from: 'mapDefaults' points at; it can't point itself":S.label!==void 0||S.groupBy!==void 0?"a from: 'mapDefaults' source takes the model source's label and groupBy":null;$&&p.push({path:`${l}.sources.${m}`,code:"invalid_source",message:$});}let R=S.label?.includes(".")?S.label:void 0;if(S.label!==void 0)if(R){let $=Js(R,n,o,s,"label");$&&p.push({path:`${l}.sources.${m}`,code:"invalid_source",message:`${$}`});}else {let $=E(i,S.label);$?M($)&&p.push({path:`${l}.sources.${m}`,code:"wrong_kind",message:`label '${S.label}' is a relation, not a column`}):p.push({path:`${l}.sources.${m}`,code:"not_in_lens",message:`label column '${S.label}' not on model`});}let O=ei(S.groupBy);if(O!==void 0||R!==void 0){let $=/^__(group(_\d+)?|label)$/;($.test(m)||S.label!==void 0&&$.test(S.label))&&p.push({path:`${l}.sources.${m}`,code:"invalid_source",message:"'__group*' / '__label' names are reserved on grouped or path-labeled sources (sql column aliases)"});}if(O!==void 0){for(let k of O){let ae=Js(k,n,o,s,"groupBy");ae&&p.push({path:`${l}.sources.${m}`,code:"invalid_source",message:`${ae}`});}let $=JSON.stringify(O);for(let k of t){let ae=E(k.sources,m);if(ae===void 0)continue;let P=ei(Nr(ae).groupBy);P!==void 0&&JSON.stringify(P)!==$&&p.push({path:`${l}.sources.${m}`,code:"not_visible",message:`groupBy [${O}] conflicts with an ancestor layer's groupBy [${P}]`});}}Om(S.where,f,d,`${l}.sources.${m}`,p);}},wx=(e,t,r,n,o)=>{for(let[i,s]of Object.entries(t)){let a=E(r,i);if(!a){o.push({path:`mapDefaults.${e}.enums.${i}`,code:"not_in_lens",message:"enum not in registry"});continue}let l=null,p=new Set;for(let d of n){let u=d[i];if(u&&(u.picks&&(l=Vs(l,u.picks)),u.omits))for(let c of u.omits)p.add(c);}let f=d=>!(p.has(d)||l&&!l.has(d));for(let d of s.picks??[])a.includes(d)?f(d)||o.push({path:`mapDefaults.${e}.enums.${i}.picks`,code:"not_visible",message:`'${d}' not visible from ancestors`}):o.push({path:`mapDefaults.${e}.enums.${i}.picks`,code:"value_not_allowed",message:`'${d}' not a known value`});for(let d of s.omits??[])a.includes(d)?f(d)||o.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"not_visible",message:`'${d}' already excluded by ancestors`}):o.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"value_not_allowed",message:`'${d}' not a known value`});}},bx=(e,t,r,n,o,i,s)=>{let a=V(t,r.mapName,r.modelName,r.relPath);for(let l of ["enumPicks","enumOmits"])for(let[p,f]of Object.entries(e[l]??{})){let d=E(n,p);if(d?.kind!=="enum")continue;let u=Hr(d,o)??[],c=Fs(a,p)??u;for(let y of f)u.includes(y)&&!c.includes(y)&&s.push({path:`${i}.${l}.${p}`,code:"not_visible",message:`'${y}' is not visible (not allowed by the inherited enum narrowing)`});}},Em=(e,t,r,n)=>e.map(o=>({mapName:n,modelName:r,relPath:[...o.relPath,t]})),Wl=(e,t,r,n,o,i,s,a,l,p,f)=>{let d=E(o,i),u=C(d,s);if(!u)return;let c=n.length===0,y={...p,chain:[...p.chain,r],unvetted:true},m=f.isDefault?void 0:E(E(r.mapDefaults,i)?.models,s),b=[...n.map(R=>E(E(R.mapDefaults,i)?.models,s)).filter(R=>R!==void 0),...t],S={mapName:i,modelName:s,relPath:pl};hx(e,b,m,o,i,u.fields,s,d?.enums,a,l,p,c?f.isDefault?[S,...f.parent]:f.parent:f.composed,f.isDefault),bx(e,f.isDefault?p:{...p,chain:[...p.chain,{parent:r.parent,mapDefaults:r.mapDefaults}],unvetted:true},f.isDefault?S:f.parent[0]??S,u.fields,d?.enums,a,l),gx(e,r,p,f.composed,a,l);let w={...p,chain:[...p.chain,r]};if(!f.isDefault)for(let[R,O]of Object.entries(e.sources??{}))!ti(O)||O.from!=="mapDefaults"||Is(w,i,s,R)||l.push({path:`${a}.sources.${R}`,code:"invalid_source",message:qs([dt(r).model,...f.parent[0]?.relPath??[]].join("."),i,s,R).message});for(let[R,O]of Object.entries(e.relations??{})){let $=E(u.fields,R);if(!$){l.push({path:`${a}.relations`,code:"not_in_lens",message:`'${R}' not on model`});continue}if(!M($)){l.push({path:`${a}.relations`,code:"wrong_kind",message:`'${R}' is not a relation (kind=${$.kind})`});continue}let k=W=>V(p,W.mapName,W.modelName,W.relPath).relations.has(R),ae=W=>V(y,W.mapName,W.modelName,W.relPath).relations.has(R);if(!c&&!(f.isDefault?f.parent.some(k):f.parent.every(k))){l.push({path:`${a}.relations`,code:"not_visible",message:`'${R}' is not shown by the parent${f.isDefault?` wherever ${s} is visited`:""}: only the first narrowing over the base lens turns a relation on`});continue}let P=st($,i);if(!P)continue;if(!C(E(o,P.mapName),P.modelName)){l.push({path:`${a}.relations.${R}`,code:"not_in_lens",message:"target model not found in lens"});continue}let q=t.map(W=>E(W.relations,R)).filter(W=>W!==void 0);Wl(O,q,r,n,o,P.mapName,P.modelName,`${a}.relations.${R}`,l,p,{parent:Em(f.isDefault?f.parent.filter(k):f.parent,R,P.modelName,P.mapName),composed:Em(f.composed.filter(ae),R,P.modelName,P.mapName),isDefault:f.isDefault});}},Ul=e=>{let t=[];try{Sx(e,t);}catch(r){if(!(r instanceof T))throw r;t.some(n=>n.code===r.code)||t.push({path:"",code:r.code,message:r.message});}return et(t)},Sx=(e,t)=>{let r=dt(e),n=Lt(e.parent),o=F(e.parent),i=rr(o),s=[],a=u=>{try{u();}catch(c){if(!(c instanceof T))throw c;s.push(c);}},l=null,p=()=>(l??=rr({...o,chain:[...o.chain,e],unvetted:true}),l);for(let[u,c]of Object.entries(e.mapDefaults??{})){let y=E(r.maps,u);if(!y){t.push({path:`mapDefaults.${u}`,code:"not_in_lens",message:"not in lens"});continue}let m=n.map(g=>E(g.mapDefaults,u)?.enums).filter(g=>g!==void 0);for(let[g,b]of Object.entries(c.models??{})){if(!C(y,g)){t.push({path:`mapDefaults.${u}.models.${g}`,code:"not_in_lens",message:"not in fieldMap"});continue}let w=n.map($=>E(E($.mapDefaults,u)?.models,g)).filter($=>$!==void 0),R=$=>$.map(({at:k})=>k).filter(k=>k.mapName===u&&k.modelName===g),O=[];a(()=>{O=R(p());}),a(()=>Wl(b,w,e,n,r.maps,u,g,`mapDefaults.${u}.models.${g}`,t,o,{parent:R(i),composed:O,isDefault:!0}));}c.enums&&wx(u,c.enums,y.enums,m,t);}if(e.root){let u=r.mapName,c=r.model,y=E(r.maps,u);if(!y)t.push({path:"root",code:"not_in_lens",message:`lens map '${u}' not in lens`});else if(!C(y,c))t.push({path:"root",code:"not_in_lens",message:`lens model '${c}' not in fieldMap`});else {let m=n.map(b=>b.root).filter(b=>b!==void 0),g={mapName:u,modelName:c,relPath:[]};a(()=>Wl(e.root,m,e,n,r.maps,u,c,"root",t,o,{parent:[g],composed:[g],isDefault:!1}));}}for(let u of Ac(e))t.push({path:"bindings",code:"invalid_binding",message:u});let f={...o,chain:[...o.chain,e],inspect:true},d;a(()=>{d=Tr(f,si(f));}),a(()=>Bl(f)),a(()=>Vl(f,{},d)),a(()=>{let u=new Map;for(let{at:c}of p()){u.set(c.relPath.join("."),c),a(()=>Cl(f,c.relPath.join(".")));let y=c.relPath.at(-1),m=u.get(c.relPath.slice(0,-1).join("."));if(y===void 0||!m)continue;let b=ce(E(r.maps,m.mapName),m.modelName,y)?.isList?{field:y,arrayOperator:"any",condition:!0}:{field:y,operator:"exists"};a(()=>rn(b,f,m));}});for(let u of s)t.some(c=>u.message.includes(c.message))||t.push({path:"",code:u.code,message:u.message});},ra=e=>tn(Ul(e),"validateNarrowing");function xm(e,{by:t="path",...r}={}){return t==="model"?Rm(e,r):lm(e,r)}var $m=(e,t,r,n={})=>{let o=F(e),{resolution:i}=nn(o,Mt(o),r);if(i.outcome!=="resolved")return {ok:false,reason:i.outcome};let{hops:s,terminal:a,jsonSubPath:l}=i;if(M(a.entry))return {ok:false,reason:"relation"};if(s.some(d=>d!==a&&d.entry.isList))return {ok:false,reason:"list"};let p=(d,u)=>u!==null&&typeof u=="object"&&V(o,d.mapName,d.model,d.relPath).whereClauses.every(c=>he(c,u,n)===true),f=p(s[0],t)?t:null;for(let[d,u]of s.entries()){if(f===null||typeof f!="object")return {ok:true,value:null};let c=E(f,u.field);if(u===a)return {ok:true,value:l.length?ge(c,l.join(".")):c};f=p(s[d+1],c)?c:null;}return {ok:true,value:null}};var Rx=e=>"maps"in e,vm=(e,t)=>{let r=i=>{let s=E(t,i);if(!s)throw new Error(`composeLens: no stored lens '${i}'`);return s},n=[...r(e).parents,e];if(new Set(n).size!==n.length)throw new Error(`composeLens: '${e}' lists a layer twice in its parents`);let o=null;for(let[i,s]of n.entries()){let a=r(s);if(Object.hasOwn(a,"parent"))throw new Error(`composeLens: '${s}' carries a parent; a layer composes only through \`parents\``);let{id:l,parents:p,...f}=a;if(p.join("\0")!==n.slice(0,i).join("\0"))throw new Error(`composeLens: '${s}' composes with [${p.join(", ")}], not [${n.slice(0,i).join(", ")}] as '${e}' lists`);if(Rx(a)!==(i===0))throw new Error(i===0?`composeLens: '${s}' is not a base lens, so it can't head '${e}''s parents`:`composeLens: '${s}' is a base lens, so it can only head a chain`);if(o===null){o=f;continue}let u={parent:o,...f};ra(u),o=u;}return o},Am=(e,t)=>{let r=ft(e)?[]:Lt(e);if(t.length!==r.length+1)throw new Error(`storeLens: the lens has ${r.length+1} layers, base included, but ${t.length} ids`);return [{...dt(e),id:t[0],parents:[]},...r.map(({parent:n,...o},i)=>({...o,id:t[i+1],parents:t.slice(0,i+1)}))]};var Nm=e=>e instanceof Date?e.toISOString():Array.isArray(e)&&e.some(t=>t instanceof Date)?e.map(Nm):e,j=(e,t)=>(e.params.push(Nm(t)),`$${++e.paramIndex}`);var nr=(e,t,{jsonb:r=false}={})=>{let n=()=>({sql:wl(e,void 0,r),shape:e.includes(".")?"json-path":"unknown"});if(!t.map||!t.currentModel||!t.currentAlias)return n();let o=ie(e,t.map,t.currentModel);if(o.kind==="past-scalar")throw Gn(e,o.column);if(o.kind==="bridge")throw new Error(`'${e}' crosses a bridge to another source; toSql() has no column for it`);if(o.kind==="fallback"||o.entry.kind==="object"&&o.entry.isList)return n();let i=o.hops.find(f=>f.entry.isList);if(i)throw Kn(e,i);let s=t.currentAlias;for(let f of o.hops){let d=Pm(t,s,f);if(!d)return n();s=d;}let a=Jr(o);if(o.kind==="direct"&&o.entry.kind==="object"){let f={field:o.column,entry:o.entry,from:o.model},d=$r(t.map,o.model,o.entry),u=Pm(t,s,f);return !d||!u?n():{sql:`${se(u)}.${se(d[0].there)}`,shape:a}}let l=o.kind==="json-path"?[o.column,...o.jsonPath]:[o.column],p=wl(l.join("."),s,r);return {sql:a==="json"&&!r?`NULLIF(${p}, 'null'::jsonb)`:p,shape:a}},Ft=(e,t,r)=>nr(e,t,r).sql,Pm=(e,t,r)=>{let n=`${t}.${r.field}`,o=e.joinRegistry?.get(n);if(o)return o;if(!e.joinCounter||!e.map)return null;let i=`t${e.joinCounter.n+1}`,s=Ox(e.map,r.from,t,r.entry,i);return s?(e.joinCounter.n+=1,e.joins?.push(s),e.joinRegistry?.set(n,i),i):null},Ox=(e,t,r,n,o)=>{let i=n.type,s=C(e,i)?.dbName??i,a=$r(e,t,n);if(!a)return null;let l=a.map(({here:p,there:f})=>`${se(o)}.${se(f)} = ${se(r)}.${se(p)}`).join(" AND ");return `LEFT JOIN ${se(s)} AS ${se(o)} ON ${l}`};var or={type:"value",value:null},jt=e=>e.type==="value"&&(e.value===null||e.value===void 0),Ex=(e,t)=>{let r=_(e)??{depth:1,path:e};if(r.depth>1)throw new Error(Ao(e,"toSql"));let n=nr(r.path,t);if(n.shape==="relation")throw new Error(`'${e}' is a relation; a value ref reads a column`);return {type:"column",...n}},Ae=(e,t)=>Vo(e,{value:r=>({type:"value",value:r}),path:r=>Ex(r,t),bind:(r,n)=>({type:"value",value:gs(r,n,"toSql")})}),sn=e=>t=>{let r=Ae(t,e);if(r.type==="column")throw new Error(`'${t.path}' is a row ref`);return r.value},mt=e=>Zt(e.dateConfig??{},sn(e));var xx={lt:"<",lte:"<=",gt:">",gte:">=",equals:"="},go=(e,t)=>{let r=ur(e,t);return r?{symbol:xx[r],negated:B.includes(e)}:void 0},km=(e,t)=>e.type==="column"?e.sql:j(t,e.value),Fe=(e,t)=>`(${t} OR ${e} IS NULL)`,Vt=(e,t,r=true)=>t&&r?`${e} IS NULL`:"FALSE",na=(e,t,r,n,o)=>{if(jt(r))return Vt(e,n);let i=`${e} ${t} ${km(r,o)}`;return n?Fe(e,i):i},pi=(e,t,r,n,o=true)=>{if(!t||t.some(jt))return Vt(e,r,o);let[i,s]=t.map(d=>km(d,n)),a=t.some(d=>d.type==="column"),l=a?"SYMMETRIC ":"";if(!r)return `${e} BETWEEN ${l}${i} AND ${s}`;let p=`${e} NOT BETWEEN ${l}${i} AND ${s}`,f=a?`(${p} AND ${i} IS NOT NULL AND ${s} IS NOT NULL)`:p;return o?Fe(e,f):f};var Lm=()=>{let e=tt.get("sql.dialect");if(!vd(e))throw new L(`toWhereSql: sql.dialect '${String(e)}' is not a SQL dialect \u2014 ${Object.values(Tn).join(", ")} are`);return e},Y=e=>new Error(`toWhereSql: ${e} has no SQL form here \u2014 it writes ${Ca.join(", ")}, all and any, and ${_a.join(", ")} over a to-many relation.`),Mm=(e,t)=>Kl(e,t,""),Tm=(e,t,r,n)=>{let o=Object.hasOwn(e,n)?e[n]:void 0;if(typeof o!="string"||o==="")throw new L(`toWhereSql: no ${r} for '${n}' in \`${t}\``);return o},Kl=(e,t,r,n={clamps:()=>[]})=>{Lm();let{columns:o,tables:i={},map:s,mapName:a,model:l}=t??{};if(typeof o!="object"||o===null)throw new L("toWhereSql: `columns` maps each field path to its SQL");if(typeof i!="object"||i===null)throw new L("toWhereSql: `tables` maps each to-many relation path to its table");if(!s||!l)throw new L("toWhereSql: `map` and `model` are required \u2014 a literal is typed by its column, and a date, Json or list value is refused by it");let p=ke(s,a,"toWhereSql");if(!C(p,l))throw new L(`toWhereSql: the map has no model '${l}'`);return yo(e,{map:p,model:l,column:f=>Tm(o,"columns","column",`${r}${f}`),table:f=>Tm(i,"tables","table",`${r}${f}`),clamps:"clamps"in n?n.clamps:()=>[],joined:"joined"in n?n.joined:null,joinedRow:null})},yo=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";let r=e;switch(pe(r)){case "all":{let n=r.all;return n.length?`(${n.map(o=>yo(o,t)).join(" AND ")})`:"TRUE"}case "any":{let n=r.any;return n.length?`(${n.map(o=>yo(o,t)).join(" OR ")})`:"FALSE"}case "field":return vx(e,t);case "if":throw Y("if / then / else");case "array":return $x(e,t);case "aggregate":throw Y("aggregate");case "date":throw Y(`dateOperator '${String(r.dateOperator)}'`);default:throw Y("a condition that is not exactly one node kind")}},$x=(e,t)=>{let{arrayOperator:r,field:n}=e;if(!_a.includes(r))throw Y(`arrayOperator '${r}'`);if(Pe(e))throw Y(`a window (filter / orderBy / take / skip) on '${n}'`);if(!n)throw Y(`the fieldless arrayOperator '${r}'`);let o=ie(n,t.map,t.model);if(o.kind==="fallback")throw new Error(`toWhereSql: '${n}' is not a field the map declares on ${t.model}`);if(o.kind==="bridge")throw Y(`'${n}', which crosses a bridge`);if(o.hops.length)throw Y(`arrayOperator '${r}' on '${n}', behind the relation '${o.hops[0].prefix}'`);if(o.kind!=="direct"||Jr(o)!=="relations")throw Y(`arrayOperator '${r}' on '${n}', which is not a to-many relation`);let i=$r(t.map,o.model,o.entry);if(!i)throw Y(`'${n}', whose relation keys the map does not declare`);if(rs.includes(r)&&e.condition===void 0)throw Ie(r);if(t.joinedRow!==null)throw new Error(`toWhereSql: arrayOperator '${r}' on '${n}' inside an any over the joined '${t.joinedRow}' \u2014 a joined row's own to-many relations have no join here; compile with toMany: 'subquery'`);let s={map:t.map,model:o.entry.type,column:f=>t.column(`${n}.${f}`),table:f=>t.table(`${n}.${f}`),clamps:f=>t.clamps(`${n}.${f}`),joined:t.joined,joinedRow:null};if(t.joined){if(qd.includes(r))throw new Error(`toWhereSql: arrayOperator '${r}' on '${n}', a relation the caller joins, holds when it has no rows \u2014 that takes an anti-join, not the topic's join. Only notEmpty and any(condition) read a joined relation; compile with toMany: 'subquery' for the rest`);t.joined(n,r);let f=`${s.column(i[0].there)} IS NOT NULL`;return r!==x.any?f:`(${f} AND ${yo(e.condition,{...s,joinedRow:n})})`}let a=[...i.map(({here:f,there:d})=>`${s.column(d)} = ${t.column(f)}`),...t.clamps(n).map(({where:f,clamps:d})=>`(${yo(f,{...s,clamps:d})})`)],l=f=>`(SELECT 1 FROM ${t.table(n)} WHERE ${[...a,...f?[f]:[]].join(" AND ")})`,p=()=>`(${yo(e.condition,s)})`;switch(r){case x.any:return `EXISTS ${l(p())}`;case x.none:return `NOT EXISTS ${l(p())}`;case x.all:return `NOT EXISTS ${l(`${p()} IS NOT TRUE`)}`;case x.empty:return `NOT EXISTS ${l()}`;default:return `EXISTS ${l()}`}},vx=(e,t)=>{if(!Ca.includes(e.operator))throw Y(`operator '${e.operator}'`);if(e.bind!==void 0)throw Y(`bind '${e.bind}' on '${e.field}'`);if(e.path!==void 0)throw Y(`comparing '${e.field}' with the column '${e.path}'`);if(e.offset!==void 0)throw Y(`an offset on '${e.field}'`);if(e.coerceType!==void 0)throw Y(`coerceType on '${e.field}'`);if(oe(e.caseInsensitive))throw Y(`a case-insensitive comparison on '${e.field}'`);if(_(e.field))throw Y(`the scoped field '${e.field}'`);let r=ie(e.field,t.map,t.model),n=Ax(e,r,t),[o]=r.kind==="direct"?_s(e,Ge(r.entry)):[];if(o)throw new Error(`toWhereSql: ${o.message}`);if(e.operator===h.exists)return `${n} IS NOT NULL`;if(e.operator===h.notExists)return `${n} IS NULL`;if(e.value===void 0)throw new Error("No value, path or bind specified");let i=fo(e,e.value,r,"toWhereSql",()=>qe);if($e(e,i))return Vt(n,B.includes(e.operator));let s=a=>Nx(a,e.field);switch(e.operator){case h.equals:return i===null?`${n} IS NULL`:`${n} = ${s(i)}`;case h.notEquals:return i===null?`${n} IS NOT NULL`:Fe(n,`${n} <> ${s(i)}`);case h.in:{let{values:a,hasNull:l}=Ze(Cm(e,i));if(!a.length)return l?`${n} IS NULL`:"FALSE";let p=`${n} IN (${a.map(s).join(", ")})`;return l?Fe(n,p):p}default:{let{values:a,hasNull:l}=Ze(Cm(e,i));if(!a.length)return l?`${n} IS NOT NULL`:"TRUE";let p=`${n} NOT IN (${a.map(s).join(", ")})`;return l?`(${p} AND ${n} IS NOT NULL)`:Fe(n,p)}}},Ax=(e,t,r)=>{if(t.kind==="fallback")throw new Error(`toWhereSql: '${e.field}' is not a field the map declares on ${r.model}`);if(t.kind==="past-scalar")throw Gn(e.field,t.column);if(t.kind==="bridge")throw Y(`'${e.field}', which crosses a bridge`);let n=t.hops.find(s=>s.entry.isList);if(n)throw Kn(e.field,n);let o=Jr(t),i=Xt(e);if(r.joinedRow!==null&&(t.hops.length||o==="relation"))throw new Error(`toWhereSql: '${e.field}' inside an any over the joined '${r.joinedRow}' reads the relation '${t.hops[0]?.prefix??e.field}' \u2014 a joined row's own relations have no join here; compile with toMany: 'subquery'`);if(o==="relation"&&t.kind==="direct"){if(!i)throw mr(e.field);let s=$r(r.map,t.model,t.entry);if(!s)throw Y(`'${e.field}', whose relation keys the map does not declare`);return r.column(`${e.field}.${s[0].there}`)}if(o==="relations")throw new Error(`toWhereSql: '${e.field}' is a to-many relation \u2014 its rows take an arrayOperator rule: { field: '${e.field}', arrayOperator: 'notEmpty' } for a row${r.joined?"; for no rows, compile with toMany: 'subquery'":", 'empty' for none"}`);if(o==="json"||o==="json-path")throw Y(`the Json value '${e.field}'`);if(i)return r.column(e.field);if(o==="instant")throw Y(`the date '${e.field}'`);if(o==="list")throw Y(`the list '${e.field}'`);return r.column(e.field)},Cm=(e,t)=>{if(!Array.isArray(t))throw new Error(`toWhereSql: '${e.operator}' on '${e.field}' takes a list of values`);return t},Nx=(e,t)=>{if(typeof e=="string"){let r=e.replace(/'/g,"''");return `'${Lm()===Tn.mysql?r.replace(/\\/g,"\\\\"):r}'`}if(typeof e=="number"&&Number.isFinite(e)||typeof e=="bigint")return String(e);if(typeof e=="boolean")return e?"TRUE":"FALSE";throw Y(`the value ${e instanceof Date?"a Date":JSON.stringify(e)} for '${t}'`)};var Px=(e,t,r)=>{H(r,(n,o)=>{if(typeof n.field!="string")return;let i=ri(e,o,n.field);if(i!==null)throw new Error(`toLensWhereSql: '${n.field}' at ${o.relPath.length?`'${o.relPath.join(".")}'`:"the root"} crosses '${i}', a relation the lens hides \u2014 a hop's clamps are reported at its own path, so a where may only cross hops the lens shows`);return xe(n)?Te(e.lens.maps,o,n.field).end??false:void 0},t);},Fm=(e,t,r)=>{let{end:n}=Te(e.lens.maps,t,r);if(!n)return null;let{pathWheres:o,modelWheres:i}=V(e,n.mapName,n.modelName,n.relPath);return {end:n,clamps:[...o.map(s=>({...s,isDefault:false})),...i.map(s=>({...s,isDefault:true}))]}},jm=(e,t,r)=>n=>{let o=Fm(e,t,n);return o?o.clamps.filter(i=>i.layer<r).map(i=>({where:i.where,clamps:jm(e,o.end,i.layer)})):[]},_m=(e,t,r,n)=>{let o=e.map(({where:i,layer:s})=>Kl(i,t,r,n(s)));return o.length===1?o[0]:`(${o.join(" AND ")})`},kx=(e,t)=>{let r=new Set,n=new Map;return o=>({joined:(i,s)=>{let a=Fm(e,t,i);if(!a)throw new Error(`toLensWhereSql: '${i}' reaches no relation`);let{end:l,clamps:p}=a,f=p.find(d=>d.layer>=o);if(f)throw new Error(`toLensWhereSql: the root where of layer ${o+1} reads '${i}' on the caller's join, whose ON carries a clamp of layer ${f.layer+1} (${f.isDefault?`${l.modelName}'s default where`:"its where"}) \u2014 check() reads a where through the clamps of the layers above its own only. Move that clamp into a narrowing above layer ${o+1}, or compile with toMany: 'subquery'`);if(p.some(d=>d.isDefault)){let d=`${l.mapName}.${l.modelName}`,u=n.get(d),c=l.mapName===t.mapName&&l.modelName===t.modelName?`the root is a ${l.modelName} too`:u!==void 0&&u!==i?`the root where also reads '${u}', which reaches ${l.modelName} too`:null;if(c!==null)throw new Error(`toLensWhereSql: the root where reads '${i}' on the caller's join, and ${l.modelName} has a default where, but ${c} \u2014 mapDefaults holds one predicate per model, which reads one table alias, and two aliases need it. Compile with toMany: 'subquery'`);n.set(d,i);}if(s===x.any){if(r.has(i))throw new Error(`toLensWhereSql: the root reads '${i}' with two any rules \u2014 on the caller's join one joined row stands for the relation, so both conditions would have to hold on the same row, where check() lets each find its own. Write one any whose condition says which row, or compile with toMany: 'subquery'`);r.add(i);}}})},Dm=(e,t)=>()=>({joined:r=>{throw new Error(`toLensWhereSql: ${e} reads the to-many relation '${r}' \u2014 with toMany: 'join' ${t}; only the root's where reads a joined relation`)}}),Vm=(e,{columns:t,tables:r,toMany:n="subquery"})=>{if(n!=="subquery"&&n!=="join")throw new L(`toLensWhereSql: toMany '${String(n)}' is neither 'subquery' nor 'join'`);let o=F(e),i={root:null,relations:{},mapDefaults:{}};for(let{at:s,effect:a}of rr(o)){let l={columns:t,tables:r,map:o.lens,mapName:s.mapName,model:s.modelName},p=f=>({clamps:jm(o,s,f)});for(let{where:f}of [...a.pathWheres,...a.modelWheres])Px(o,s,f);if(a.pathWheres.length){let f=s.relPath.join("."),d=n==="subquery"?p:f?Dm(`the where at '${f}'`,"it sits in that relation's join ON, ahead of the joins below it"):kx(o,s),u=_m(a.pathWheres,l,f?`${f}.`:"",d);f?i.relations[f]=u:i.root=u;}if(a.modelWheres.length){let f=er(i.mapDefaults,s.mapName,()=>({models:{}})),d=n==="subquery"?p:Dm(`the default where of ${s.modelName}`,`it compiles once for every path that reaches ${s.modelName}, and the join exists only where the lens shows the relation`),u=_m(a.modelWheres,l,`${s.modelName}.`,d),c=E(f.models,s.modelName);if(c!==void 0&&c!==u)throw new Error(`toLensWhereSql: the default where of ${s.modelName} reads a to-many relation whose clamps differ between the paths that reach ${s.modelName} \u2014 a model default compiles to one predicate for every path`);f.models[s.modelName]=u;}}return i};var Im=e=>Array.isArray(e)?e.some(Im):typeof e=="object"&&e!==null,qm=(e,t,r,n)=>{let o=`NULLIF(${t}, 'null'::jsonb)`,i=`jsonb_typeof(${o})`,s=`(${o} #>> '{}')`,a=w=>`${j(n,JSON.stringify(w))}::jsonb`,l=oe(e.caseInsensitive),p=w=>l?`LOWER(${w})`:w,f=B.includes(e.operator),d=w=>Fe(o,`NOT (${w})`);if($e(e,r))return Vt(o,f);let u=ds(e.operator,r);if(u)throw u;let c=w=>{if(Im(w))throw I("toSql",`A case-insensitive comparison of '${e.field}' with a list holding objects`);return a(zr(w))},y=w=>l&&typeof w=="string"?`(${i} = 'string' AND LOWER(${s}) = LOWER(${j(n,w)}))`:l&&Array.isArray(w)?`(${i} = 'array' AND LOWER(${o}::text)::jsonb = ${c(w)})`:`${o} = ${a(w)}`,m=w=>`(${i} = 'string' AND ${p(s)} LIKE ${p(j(n,w))})`,g=w=>{let R=O=>`(CASE WHEN ${i} = 'array' THEN EXISTS (SELECT 1 FROM jsonb_array_elements(${o}) AS e WHERE ${O}) ELSE FALSE END)`;return l&&typeof w=="string"?R(`jsonb_typeof(e) = 'string' AND LOWER(e #>> '{}') = LOWER(${j(n,w)})`):l&&Array.isArray(w)?R(`LOWER(e::text)::jsonb = ${c(w)}`):typeof w=="object"&&w!==null?R(`e = ${a(w)}`):`(${i} = 'array' AND ${o} @> ${a([w])})`},b=w=>typeof w=="string"?`(${m(`%${ve(w)}%`)} OR ${g(w)})`:g(w);switch(e.operator){case h.equals:return r===null?`${o} IS NULL`:y(r);case h.notEquals:return r===null?`${o} IS NOT NULL`:d(y(r));case h.in:case h.notIn:{let{values:w,hasNull:R}=Ze(r),O=w.length?`(${w.map(y).join(" OR ")})`:"FALSE";return e.operator===h.in?R?`(${O} OR ${o} IS NULL)`:O:R?`(NOT ${O} AND ${o} IS NOT NULL)`:d(O)}case h.between:case h.notBetween:{let[w,R]=r,O=`(${i} = jsonb_typeof(${a(w)}) AND ${o} BETWEEN ${a(w)} AND ${a(R)})`;return e.operator===h.between?O:d(O)}case h.contains:return b(r);case h.notContains:return d(b(r));case h.startsWith:return m(`${ve(String(r))}%`);case h.endsWith:return m(`%${ve(String(r))}`);case h.notStartsWith:return d(m(`${ve(String(r))}%`));case h.notEndsWith:return d(m(`%${ve(String(r))}`));case h.matches:case h.notMatches:{let{source:w,caseInsensitive:R}=Sr(r),O=`(${i} = 'string' AND ${s} ~${R?"*":""} ${j(n,Uo(w))})`;return e.operator===h.matches?O:d(O)}}let S=go(e.operator,"field")?.symbol;if(S)return `(${i} = jsonb_typeof(${a(r)}) AND ${o} ${S} ${a(r)})`;throw new Error(`Operator '${e.operator}' is not supported on a Json value in SQL`)};var Bm=e=>typeof e=="object"&&Ir(e)!==null,fi=({sql:e,shape:t},r)=>{if(t!=="json-path"&&t!=="text")return `to_timestamp(EXTRACT(EPOCH FROM ${e}))`;let n=j(r,mt(r).timeZone);return `(CASE WHEN btrim(${e}) ~ '^-?[0-9]+(\\.[0-9]+)?$' THEN to_timestamp(btrim(${e})::numeric / 1000) WHEN ${e} ~* '[0-9]{2}:[0-9]{2}(:[0-9]{2}(\\.[0-9]+)?)?\\s*(z|[+-][0-9]{2}(:?[0-9]{2})?)\\s*$' OR ${e} ~* '\\m(gmt|utc)\\M' THEN (${e})::timestamptz ELSE (${e})::timestamp AT TIME ZONE ${n} END)`},oa=e=>Object.values(e).some(Bm),Cx=(e,t,r)=>{let n=jr(r),o=n?"int":"double precision";if(typeof e=="number"||!Bm(e)){let a=Ka(e,sn(t),r);return `${j(t,a)}::${o}`}let i=Ae(e,t).sql;return `(CASE WHEN ${n?`${i} >= 0 AND ${i} = trunc(${i})`:`${i} >= 0`} THEN ${i} END)::${o}`},Lx=(e,t)=>`make_interval(${Jd.flatMap(n=>{let o=Object.keys(e).filter(i=>e[i]!==void 0&&rt[i].interval===n).map(i=>{let s=Cx(e[i],t,i),{factor:a}=rt[i];return a===1?s:`${a} * ${s}`});return o.length?[`${n} => ${o.join(" + ")}`]:[]}).join(", ")})`,di=(e,t,r,n)=>{let o=mt(n).timeZone;if(e.type==="value"&&!oa(t)){let l=Ur(t,sn(n));return e.value===null||e.value===void 0||l===null?or:{type:"value",value:yr(Tt(e.value),l,r,o).toDate()}}let i=e.type==="column"?e.computed?e.sql:fi(e,n):`${j(n,e.value??null)}::timestamptz`,s=j(n,o);return {type:"column",computed:true,sql:`(((${i} AT TIME ZONE ${s}) ${r===1?"+":"-"} ${Lx(t,n)}) AT TIME ZONE ${s})`}};var Gl=(e,t,r)=>{let n=Ae(t,r);if(e.type==="value"&&n.type==="value"){let i=Gr(n.value);return i===null?or:{type:"value",value:Kr(e.value,i)}}let o=(i,s)=>i.type==="column"?`(${i.sql})::double precision`:`${j(r,s(i.value)??null)}::double precision`;return {type:"column",computed:true,sql:`(${o(e,i=>i)} + ${o(n,Gr)})`}},Wm=(e,t,r)=>{if(jt(e))return or;let n=Ae(t,r);if(n.type==="column")throw new Error(`A row path on a date offset ('${t.path}') is check-only; evaluate with check()`);let o=Xn(n.value);return o===null?or:di(e,...o,r)};var Um,Km=e=>{Um=e;},Cr=(e,t)=>Um(e,t);var sa=(e,t,r,n=false)=>{let o=fs(e);if(o)throw o;let i=r===void 0?nr(e.field,t):{sql:r,shape:"scalar"};if(i.shape==="relation"&&!Xt(e))throw mr(e.field);let s=r===void 0||n,a=Ee(e)&&t.map&&t.currentModel?(_(e.path)??{path:e.path}).path:null;if(a!==null){let O=no(te(e.field,t.map,t.currentModel),te(a,t.map,t.currentModel),e.operator);if(O)throw I("toSql",`Comparing '${e.field}' with the column '${e.path}'`,O)}if(i.shape==="enum"&&!He.includes(e.operator)){let O=zm(e,t),$=te(e.field,t.map,t.currentModel),k=O!==ia&&$&&!$e(e,O)?Ws(e,O,$,t.map):null;if(k){let ae=`${i.sql}::text = ANY(${j(t,k.values)})`;return k.matchesNull?Fe(i.sql,ae):ae}}let l=i.shape==="enum"&&!He.includes(e.operator)&&a===null?{...i,sql:`${i.sql}::text`}:i;if((i.shape==="json"||i.shape==="json-path")&&!He.includes(e.operator)){let O=zm(e,t);if(O===ia)throw new Error(`The Json value '${e.field}' compares against an operand known when compiling, not one read per row.`);return qm(e,Ft(e.field,t,{jsonb:true}),O,t)}let f=O=>{if(O.type==="column"&&!O.computed&&(O.shape==="json"||O.shape==="json-path"))throw I("toSql",`'${e.field}' compared with a Json value read per row`,"SQL would compare its text")};if(Je.includes(e.operator)){let O=Qm(e,t);return O?.forEach(f),pi(l.sql,O,B.includes(e.operator),t,s)}let d=Hm(e,t);if(f(d),d.type==="column"&&Ht(e.operator,"field")==="string"&&!Qr(i.shape)&&i.shape!=="list")throw I("toSql",`'${e.operator}' on '${e.field}'`,"it is not text");if(d.type==="column"&&d.computed&&i.shape==="text"&&r===void 0)throw I("toSql",`'${e.field}' against a value moved by an offset`,"an offset moves a number or a date");let u=l.sql,c=go(e.operator,"field");if(c)return na(u,c.symbol,d,false,t);if(d.type==="value"&&$e(e,d.value))return Vt(u,B.includes(e.operator),s);let y=d.type==="column"&&d.computed===true,m=oe(e.caseInsensitive)&&(d.type==="column"?!y&&Qr(i.shape)&&Qr(d.shape):xr(i.shape,d.value)),g=O=>m?`LOWER(${O})`:O,b=O=>m?zr(O):O;if(i.shape==="list"&&d.type==="column"&&Et.includes(e.operator)){if(te(e.field,t.map,t.currentModel)?.type!=="String"||!Qr(d.shape))throw I("toSql",`'${e.operator}' on the list '${e.field}' with a member read per row ('${e.path}')`,"Postgres matches a member of the list's own type only");let O=oe(e.caseInsensitive)&&Qr(d.shape)?`EXISTS (SELECT 1 FROM unnest(${u}) AS e WHERE LOWER(e) = LOWER(${d.sql}))`:`array_position(${u}, ${d.sql}) IS NOT NULL`;return e.operator===h.contains?`(${d.sql} IS NOT NULL AND ${O})`:`(${u} IS NULL OR (${d.sql} IS NOT NULL AND NOT ${O}))`}if(i.shape==="list"&&d.type==="value"){let O=oe(e.caseInsensitive)&&xr("text",d.value);if(Et.includes(e.operator)){let $=j(t,d.value),k=O?`EXISTS (SELECT 1 FROM unnest(${u}) AS e WHERE LOWER(e) = LOWER(${$}))`:`array_position(${u}, ${$}) IS NOT NULL`;return e.operator===h.contains?k:`NOT ${k}`}if(cr.includes(e.operator)&&Array.isArray(d.value))return Cr(Os(e,d.value),t);if(Mx(e.operator))throw new Error(`'${e.operator}' does not apply to the list '${e.field}'; test its members with contains.`);if(O&&$t.includes(e.operator)&&Array.isArray(d.value)){let $=j(t,zr(d.value)),k=`(${u} IS NOT NULL AND ARRAY(SELECT LOWER(e) FROM unnest(${u}) AS e) = ${$})`;return e.operator===h.equals?k:Fe(u,`NOT ${k}`)}}let S=d.type==="value"?d.value:void 0,w=d.type==="column"?d.sql:void 0;if(w!==void 0&&(cr.includes(e.operator)||["pattern","string"].includes(Ht(e.operator,"field"))))throw I("toSql",`'${e.operator}' against an operand read per row ('${e.path}')`);let R=O=>s?Fe(u,O):O;switch(e.operator){case h.equals:return y?`${u} = ${w}`:w!==void 0?`${g(u)} IS NOT DISTINCT FROM ${g(w)}`:S===null?`${u} IS NULL`:`${g(u)} = ${g(j(t,S))}`;case h.notEquals:return y?R(`${u} <> ${w}`):w!==void 0?`${g(u)} IS DISTINCT FROM ${g(w)}`:S===null?`${u} IS NOT NULL`:R(`${g(u)} <> ${g(j(t,S))}`);case h.in:{let{values:O,hasNull:$}=Ze(S);if(!O.length)return $?`${u} IS NULL`:"FALSE";let k=`${g(u)} = ANY(${j(t,b(O))})`;return $?R(k):k}case h.notIn:{let{values:O,hasNull:$}=Ze(S);if(!O.length)return $?`${u} IS NOT NULL`:"TRUE";let k=`${g(u)} <> ALL(${j(t,b(O))})`;return $?`(${k} AND ${u} IS NOT NULL)`:R(k)}case h.contains:return `${g(u)} LIKE ${g(j(t,`%${ve(String(S))}%`))}`;case h.notContains:return R(`${g(u)} NOT LIKE ${g(j(t,`%${ve(String(S))}%`))}`);case h.startsWith:return `${g(u)} LIKE ${g(j(t,`${ve(String(S))}%`))}`;case h.endsWith:return `${g(u)} LIKE ${g(j(t,`%${ve(String(S))}`))}`;case h.notStartsWith:return R(`${g(u)} NOT LIKE ${g(j(t,`${ve(String(S))}%`))}`);case h.notEndsWith:return R(`${g(u)} NOT LIKE ${g(j(t,`%${ve(String(S))}`))}`);case h.matches:return Gm(u,S,false,t);case h.notMatches:return R(Gm(u,S,true,t));case h.isEmpty:case h.notEmpty:return zl(e.field,i,e.operator===h.isEmpty,t,$s(e,t.map,t.currentModel));case h.exists:return `${u} IS NOT NULL`;case h.notExists:return `${u} IS NULL`;default:throw new Error(`Unknown operator: ${e.operator}`)}},Hm=(e,t)=>{if(He.includes(e.operator))return {type:"value",value:void 0};let r=Jm(e,Ae(e,t),t);return e.offset===void 0?r:Gl(r,e.offset,t)},Jm=(e,t,r)=>t.type==="column"?t:{type:"value",value:fo(e,t.value,Or(e.field,r.map,r.currentModel),"toSql",()=>mt(r).timeZone)},Qm=(e,t)=>{let r=Jm(e,Ae(e,t),t),n=r.type==="value"?r.value:void 0;if(n==null)return null;let o=ot(n,e.operator);return o.some(i=>i!=null&&!ye(i))&&Yn(n,e.operator),Qe(o).map(i=>{let s={type:"value",value:i};return e.offset===void 0?s:Gl(s,e.offset,t)})},Gm=(e,t,r,n)=>{if(typeof t!="string"&&!(t instanceof RegExp))throw new Error("matches requires a string or RegExp pattern");let{source:o,caseInsensitive:i}=Sr(t);return `${e} ${r?"!":""}~${i?"*":""} ${j(n,Uo(o))}`},ia=Symbol("not known"),zm=(e,t)=>{if(Je.includes(e.operator)){let n=Qm(e,t);return n?n.every(o=>o.type==="value")?n.map(o=>o.value):ia:null}let r=Hm(e,t);return r.type==="value"?r.value:ia},zl=(e,t,r,n,o)=>{let{sql:i,shape:s}=t;if(s==="list")return r?`(${i} IS NULL OR cardinality(${i}) = 0)`:`cardinality(${i}) > 0`;if(s==="json"||s==="json-path"){let a=Ft(e,n,{jsonb:true}),l=["'null'::jsonb",...o?[`'""'::jsonb`]:[],"'[]'::jsonb"].join(", ");return r?`(${a} IS NULL OR ${a} IN (${l}))`:`${a} NOT IN (${l})`}return o?r?`(${i} IS NULL OR ${i} = '')`:`(${i} IS NOT NULL AND ${i} <> '')`:r?`${i} IS NULL`:`${i} IS NOT NULL`},Mx=e=>Ht(e,"field")==="string"&&!Et.includes(e);var Zm=(e,t)=>{if(Pe(e))throw At("toSql");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=_x(e,t);return sa(e,t,r,e.aggregate.mode==="avg")},_x=(e,t)=>{let{mode:r,field:n}=e.aggregate;if(!xt.includes(r))throw gr(r);let o=r==="sum"?"SUM":"AVG",i=u=>r==="sum"?`COALESCE(${o}(${u}), 0)`:`${o}(${u})`,s=Ke({field:e.field},t.map,t.currentModel);if(s==="relation"||te(e.field,t.map,t.currentModel)?.kind==="object")throw new Error(`Field '${e.field}' is a relation \u2014 toSql() cannot aggregate relation lists. Use toPrisma() instead.`);if(n?.includes("."))throw new Error(`aggregate.field '${n}' contains a nested path \u2014 toSql() only supports flat field names. Use check() for nested paths.`);let a=s==="list",l=Ft(e.field,t,{jsonb:!a}),p=a?l:`(CASE WHEN jsonb_typeof(${l}) = 'array' THEN ${l} END)`;if(a){if(n)throw new Error("aggregate.field is not supported for native array types. Use a JSONB column for object arrays.");return `(SELECT ${i("elem")} FROM unnest(${p}) AS elem)`}if(n){let u=`(elem->>${bl(n)})::numeric`;return `(SELECT ${i(u)} FROM jsonb_array_elements(${p}) AS elem)`}return `(SELECT ${i("elem::numeric")} FROM jsonb_array_elements_text(${p}) AS elem)`};var Ym=(e,t)=>{if(Pe(e))throw At("toSql");if(!e.field)throw ls("toSql");if(Ke({field:e.field},t.map,t.currentModel)==="relation"||te(e.field,t.map,t.currentModel)?.kind==="object")throw new Error(`Field '${e.field}' is a relation \u2014 relation arrays are not supported in SQL; use toPrisma().`);switch(e.arrayOperator){case x.empty:case x.notEmpty:{let n=nr(e.field,t),o=e.arrayOperator===x.empty;if(n.shape==="list")return zl(e.field,n,o,t,false);let i=Ft(e.field,t,{jsonb:true});return `(CASE WHEN jsonb_typeof(${i}) = 'array' THEN jsonb_array_length(${i}) ${o?"=":">"} 0 ELSE ${o?"TRUE":"FALSE"} END)`}case x.all:case x.any:case x.none:case x.atLeast:case x.atMost:case x.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 ue(e.arrayOperator,"array")}};var Dx=(e,t)=>e.type==="column"&&!e.computed?{type:"column",sql:fi(e,t),computed:true}:e,Xm=e=>e===void 0||e==="instant"||e==="text"||e==="json-path"||e==="unknown",eg=e=>I("toSql",`A date rule on '${e}'`,"it is not a date column"),tg=(e,t,r)=>{let n=t.some(i=>i.type==="column"),o=e.shape==="json-path"||e.shape==="text";return n||o?{lhs:fi(e,r),ends:t.map(i=>Dx(i,r))}:{lhs:e.sql,ends:t}},rg=(e,t)=>{let r=nr(e.field,t);if(!Xm(r.shape))throw eg(e.field);let n=Ae(e,t);if(n.type==="column"&&!Xm(n.shape))throw eg(String(e.path??e.field));if(!jt(n)){let s=e.offset===void 0?void 0:Ae(e.offset,t),a=Qt(n.type==="value"?n.value:void 0,s?.type==="value"?s.value:void 0);if(a)throw a}let o=go(e.dateOperator,"date");if(o){let{lhs:s,ends:a}=tg(r,[jx(e,t)],t);return na(s,o.symbol,a[0],o.negated,t)}let i=(s,a)=>{if(!s)return pi(r.sql,null,a,t);let{lhs:l,ends:p}=tg(r,s,t);return pi(l,p,a,t)};switch(e.dateOperator){case A.within:case A.notWithin:return i(Vx(e,t),B.includes(e.dateOperator));case A.between:case A.notBetween:return i(Ix(e,t),B.includes(e.dateOperator));case A.dayIn:case A.dayNotIn:{let s=e.dateOperator===A.dayNotIn,a=Ae(e,t);if(a.type==="column")throw I("toSql",`A weekday list read from the row ('${e.path}')`);let l=za(a.value);if(l===null)return Vt(r.sql,s);let p=j(t,mt(t).timeZone),f=j(t,l),d=`EXTRACT(DOW FROM (${fi(r,t)} AT TIME ZONE ${p}))`;return e.dateOperator===A.dayIn?`${d} = ANY(${f})`:Fe(r.sql,`${d} <> ALL(${f})`)}default:throw ue(e.dateOperator,"date")}},ng=e=>({type:"value",value:Do(mt(e)).toDate()}),Fx=(e,t,r)=>{let n=Oe(e);if(n&&oa(n[0]))return di(ng(r),...n,r);let o=kt(e,sn(r));return o===null?or:{type:"value",value:Hn(o,t,mt(r)).toDate()}},og=(e,t,r)=>e==null?or:ee(e)?Fx(e,t,r):{type:"value",value:Ss(e,mt(r).timeZone)},ig=(e,t,r)=>t.offset===void 0?e:Wm(e,t.offset,r),jx=(e,t)=>{let r=Ae(e,t),n=r.type==="column"?r:og(r.value,e.dateOperator,t);return ig(n,e,t)},Vx=(e,t)=>{let r=Ae(e,t);if(jt(r))return null;if(r.type==="column"||!ee(r.value))throw nt(e.dateOperator);let n=Oe(r.value);if(n&&oa(n[0])){let s=ng(t),a=di(s,...n,t);return n[1]===-1?[a,s]:[s,a]}let o=kt(r.value,sn(t));if(o===null)return null;let i=Jn(o,mt(t));return [{type:"value",value:i[0].toDate()},{type:"value",value:i[1].toDate()}]},Ix=(e,t)=>{let r=Ae(e,t);if(jt(r))return null;let n=r.type==="value"?r.value:void 0,o=ot(n,e.dateOperator).map(l=>og(l,e.dateOperator,t));if(o.some(jt))return null;let[i,s]=o;return (i.type==="value"&&s.type==="value"?Qe([i.value,s.value]).map(l=>({type:"value",value:l})):o).map(l=>ig(l,e,t))};var sg=(e,t)=>e.all.length===0?"TRUE":`(${e.all.map(n=>Cr(n,t)).join(" AND ")})`,ag=(e,t)=>e.any.length===0?"FALSE":`(${e.any.map(n=>Cr(n,t)).join(" OR ")})`,lg=(e,t)=>{if(Ct(e,t.map,t.currentModel))return "TRUE";let r=Cr(e.if,t),n=Cr(e.then,t);if(e.else!==void 0){let o=Cr(e.else,t);return `(((${r}) IS NOT TRUE OR ${n}) AND ((${r}) IS TRUE OR ${o}))`}return `((${r}) IS NOT TRUE OR ${n})`};var ui=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";if(Hi(e,"toSql"),"field"in e&&typeof e.field=="string"&&t.map&&t.currentModel&&Er(e.field,t.map,t.currentModel))return "TRUE";let r=pe(e);(r==="field"||r==="date")&&vs(e.field,t.map,t.currentModel);let n=e;switch(r){case "all":return sg(n,t);case "any":return ag(n,t);case "if":return lg(n,t);case "array":return Ym(n,t);case "aggregate":return Zm(n,t);case "date":return rg(n,t);case "field":return sa(n,t);default:throw vt()}};Km(ui);var Hl=e=>{let t=ke(e?.map,e?.mapName,"toSql"),r=!!(t&&e?.model),n=e?.alias??(r?"t0":void 0);return {params:[],paramIndex:0,dateConfig:{now:e?.now,timeZone:e?.timeZone,weekStart:e?.weekStart},map:t,currentModel:e?.model,currentAlias:n,joinCounter:r?{n:0}:void 0,joins:r?[]:void 0,joinRegistry:r?new Map:void 0}},qx=(e,t)=>Bs(e,t,"toSql",Bx),Bx=(e,t)=>{let r=Hl(t);return {sql:ui(e,r),params:r.params,joins:r.joins??[]}};var pg=(e,t)=>{let[r,...n]=t,o=e[r];if(n.length===0){o===void 0&&(e[r]=true);return}let i=o!==void 0&&o!==true?o.select:{};pg(i,n),e[r]={select:i};},Wx=(e,t,r,n,o,i,s,a,l,p)=>{let f=Hs(`source '${o}' at '${t}'`,()=>ii(a,{...l,map:e,mapName:r,model:n})),d=f.steps.at(-1),u=d.where,c=f.steps.length>1||(d.refs?.length??0)>0,y=ke(e,r,"toPrisma"),m=P=>p!==void 0&&ie(P,y,n).kind==="bridge",g=i!==void 0&&!m(i)?i:void 0,b=(s??[]).map(P=>m(P)?void 0:P),S=P=>{let q=ie(P,y,n);return q.kind==="json-path"?P.split(".").slice(0,q.stopIndex).join("."):P},w=p===void 0?[]:Xs(e,r,n,[...De(p),...i!==void 0&&g===void 0?[i]:[],...(s??[]).filter(m)].map(S)).filter(P=>P!==o),R=g?.includes(".")?g:void 0,O=[...b.filter(P=>P!==void 0),...R?[R]:[],...w],$={[o]:true,...g&&!R?{[g]:true}:{}};for(let P of O)pg($,P.split("."));let k={model:n,...s||R||p!==void 0?{}:{distinct:g?[o,g]:[o]},select:$,where:u,...c?{steps:f.steps}:{}},ae;try{for(let Re of w){let Ce=ie(Re,y,n);if(!(Ce.kind==="direct"&&!Ce.hops.length&&Ce.entry.kind!=="object"))throw new Error(Ce.kind==="direct"?`the re-check reads '${Re}' through a relation, which flat SQL rows can't hold \u2014 run the Prisma query`:`the re-check reads '${Re}', which is not a column of ${n} \u2014 run the Prisma query`)}let P=Hl({...l,map:e,mapName:r,model:n,alias:"t0"}),q=ui(a,P),W=R?Ft(R,P):void 0,Lr=b.map((Re,Ce)=>Re===void 0?void 0:`${Ft(Re,P)} AS ${se(`__group_${Ce}`)}`),So=P.joins??[],Mr=So.length?` ${So.join(" ")}`:"",me=q?.trim()?` WHERE ${q}`:"",gt=se("t0"),ln=[`${gt}.${se(o)}`,...W?[`${W} AS ${se("__label")}`]:g?[`${gt}.${se(g)}`]:[],...Lr.filter(Re=>Re!==void 0),...w.map(Re=>`${gt}.${se(Re)}`)].join(", "),ne=C(E(e.maps,r),n)?.dbName??n;ae={sql:`SELECT DISTINCT ${ln} FROM ${se(ne)} AS ${gt}${Mr}${me}`,params:P.params};}catch(P){ae={sql:null,params:[],error:P instanceof Error?P.message:String(P)};}return {prisma:k,sql:ae}},fg=(e,t={})=>{let{lens:r}=F(e);return dm(e).map(({path:n,visit:o,field:i,label:s,groupBy:a,where:l,recheck:p})=>{let f=l,{prisma:d,sql:u}=Wx(r,n,o.mapName,o.model,i,s,a,f,t,p);return {path:n,mapName:o.mapName,model:o.model,field:i,...s!==void 0?{label:s}:{},...a!==void 0?{groupBy:a}:{},composedWhere:f,prisma:d,sql:u,...p!==void 0?{recheck:p}:{}}})};var aa=(e,t)=>{let r=F(e);return nn(r,Mt(r),t).resolution};var an=class extends Error{constructor(r){super(`inferValueType: ${r.path}: ${r.message}`);this.issue=r;}issue},X=(e,t,r)=>{throw new an({path:e,code:t,message:r})};var la=(e,t)=>{let r=_(e);return r?(r.depth>1&&X(t,"scope_out_of_bounds",`'${e}' reaches past the row a value expression reads`),r.path):e},pa=(e,t)=>{if(!e)throw new L(`inferValueType needs a lens to type ${t}`);return e},ci=(e,t,r)=>{let n=aa(e,t);if(n.outcome!=="resolved")return X(r,"unresolved_path",`'${t}' does not resolve through the lens (${n.outcome})`);let o=n.hops.slice(0,-1).find(i=>M(i.entry)&&i.entry.isList);return {entry:n.terminal.entry,viaList:o?o.field:null,json:n.jsonSubPath.length>0||n.terminal.entry.type===N.Json}},mi=e=>e.json?N.Json:Ge({...e.entry,isList:false})??null;var da={kind:null,isList:false,nullable:true},Ux={kind:null,isList:false,nullable:false},fa=e=>e!==null&&Q.includes(e),dg=e=>`${e.kind??"null"}${e.isList?"[]":""}`,ua=(e,t,r)=>{let n=e.nullable||t.nullable;if(e.kind===null&&e.isList===t.isList)return {...t,nullable:n};if(t.kind===null&&e.isList===t.isList)return {...e,nullable:n};if(e.kind===null&&!e.isList)return {...t,nullable:true};if(t.kind===null&&!t.isList)return {...e,nullable:true};if(e.isList===t.isList){if(e.kind===t.kind)return {...e,nullable:n};if(fa(e.kind)&&fa(t.kind))return {kind:e.kind===N.Decimal||t.kind===N.Decimal?N.Decimal:N.Float,isList:e.isList,nullable:n}}return X(r,"value_type_mismatch",`the values here are ${dg(e)} and ${dg(t)}`)},ca=(e,t)=>({...e.reduce((r,n)=>ua(r,n,t),Ux),isList:true});var Kx={String:["String","Boolean","DateTime",...Q],DateTime:["DateTime","String",...Q],Boolean:["Boolean","String"],Enum:["String"],...Object.fromEntries(Q.map(e=>[e,["String","DateTime",...Q]]))},Gx=(e,t,r)=>{e===null||e===t||Kx[e]?.includes(t)||X(r,"coerce_kind_mismatch",`${e} values can't be read as ${t}`);},ug=(e,t,r)=>{let n=la(t.field,`${r}.field`),o=ci(e,n,`${r}.field`);return (o.viaList||o.entry.isList!==true)&&X(`${r}.field`,"aggregate_needs_list",`'${t.field}' is not a list; an aggregate reads a list`),{field:n,list:o}},zx=(e,t,r)=>{let{field:n,list:o}=ug(e,t,r),i=t.aggregate.field;if(!M(o.entry))return i!==void 0&&X(`${r}.aggregate.field`,"invalid_aggregate_field",`'${t.field}' holds values, not rows`),mi(o);if(i===void 0)return X(`${r}.aggregate.field`,"aggregate_field_required",`${t.aggregate.mode} over rows names the field it reads`);let s=ci(e,`${n}.${i}`,`${r}.aggregate.field`);return (M(s.entry)||s.entry.isList)&&X(`${r}.aggregate.field`,"invalid_aggregate_field",`'${i}' is not one value per row`),mi(s)},cg=(e,t,r)=>{let n=t.aggregate.mode;if(Dn[n].result==="count")return e&&ug(e,t,r),{kind:N.Int,isList:false,nullable:false};let o=zx(pa(e,`${n} over '${t.field}'`),t,r);t.coerceType!==void 0&&Gx(o,t.coerceType,`${r}.coerceType`);let i=t.coerceType??o,s=`${r}.aggregate.field`;return n==="sum"||n==="avg"?(fa(i)||X(s,"aggregate_kind_mismatch",`${n} adds numbers, not ${i??"untyped"} values`),{kind:n==="sum"||i===N.Decimal?i:N.Float,isList:false,nullable:n==="avg"}):n==="distinct"?((i===null||!Md.includes(i))&&X(s,"aggregate_kind_mismatch",`distinct lists strings, enums, dates, booleans and numbers, not ${i??"untyped"} values`),{kind:i,isList:true,nullable:false}):((i===null||!Ld.includes(i))&&X(s,"aggregate_kind_mismatch",`${n} orders numbers and dates, not ${i??"untyped"} values; read strings with coerceType`),{kind:i,isList:false,nullable:true})};var ma=e=>!Array.isArray(e)&&e.distinct===true,ga=(e,t=false)=>{let r=new Set,n=new Set,o=new Set;return e.filter(i=>{let[s,a]=i instanceof Date?[n,i.getTime()]:typeof i=="object"&&i!==null?[o,JSON.stringify(i)]:[r,t&&typeof i=="string"?i.toLowerCase():i];return s.has(a)?false:(s.add(a),true)})};var ya=(e,t)=>e===null?da:typeof e=="number"?{kind:Number.isInteger(e)?N.Int:N.Float,isList:false,nullable:false}:typeof e=="bigint"?{kind:N.BigInt,isList:false,nullable:false}:typeof e=="string"?{kind:N.String,isList:false,nullable:false}:typeof e=="boolean"?{kind:N.Boolean,isList:false,nullable:false}:e instanceof Date?{kind:N.DateTime,isList:false,nullable:false}:Array.isArray(e)?ca(e.map((r,n)=>{let o=`${t}[${n}]`;return Array.isArray(r)&&X(o,"nested_list","a list's items are single values"),ya(r,o)}),t):{kind:N.Json,isList:false,nullable:false};var mg=(e,t,r)=>{let n=ci(e,la(t,r),r);return n.viaList&&X(r,"to_many_path",`'${t}' reads through the to-many relation '${n.viaList}'; aggregate its rows`),M(n.entry)&&X(r,"relation_not_value",`'${t}' names a relation's rows, not a value; aggregate them`),{kind:mi(n),isList:n.entry.isList===true,nullable:n.json||n.entry.isRequired!==true}};var ho=e=>re(e)&&"aggregate"in e&&["operator","value","path","bind"].some(t=>t in e);var gg={source:["value","path","bind","bindOptional"],if:["if","then","else"],aggregate:["field","aggregate","condition","filter","orderBy","take","skip","coerceType","caseInsensitive"],list:["list","distinct"]},Jl=(e,t)=>e.map(r=>({...r,path:r.path.startsWith("$")?`${t}${r.path.slice(1)}`:`${t}.${r.path}`})),wa=(e,t,r)=>Object.keys(e).filter(n=>!gg[t].includes(n)).map(n=>({path:`${r}.${n}`,code:"unknown_key",message:`a ${t==="source"?"value source":`${t} value`} takes ${gg[t].join(", ")}, not '${n}'`})),Hx=(e,t,r)=>{if(r)return [{path:t,code:"nested_list",message:"a list's items are single values"}];let n=Jt(e).flatMap((s,a)=>ha(s,`${t}[${a}]`,true));if(Array.isArray(e))return n;let o=e,i=wa(o,"list",t);return Array.isArray(o.list)||i.push({path:`${t}.list`,code:"invalid_list",message:"list must be an array"}),o.distinct!==void 0&&typeof o.distinct!="boolean"&&i.push({path:`${t}.distinct`,code:"invalid_distinct",message:"distinct must be a boolean"}),[...i,...n]},Jx=(e,t,r)=>{let n=wa(e,"if",t);return e.if===void 0?n.push({path:`${t}.if`,code:"condition_required",message:"if / then takes an if"}):n.push(...Jl(vr(e.if).errors,`${t}.if`)),e.then===void 0?n.push({path:`${t}.then`,code:"value_required",message:"if / then takes a then"}):n.push(...ha(e.then,`${t}.then`,r)),e.else!==void 0&&n.push(...ha(e.else,`${t}.else`,r)),n},Qx=(e,t)=>[...wa(e,"aggregate",t),...e.field===""?[{path:`${t}.field`,code:"field_required",message:"an aggregate value reads a list field"}]:[],...Jl(Xu(e).errors,t)],ha=(e,t,r)=>{let n=e;switch(Pt(e)){case "literal":return [];case "list":return Hx(e,t,r);case "if":return Jx(n,t,r);case "aggregate":return Qx(n,t);case "source":return [...wa(n,"source",t),...Jl(ec(n).errors,t)];default:{let o=ho(n),i=o?Un(t):Wn(t);return [{path:t,code:o?"unexpected_comparison":"invalid_value_expression",message:i.message.slice(t.length+2)}]}}},gi=e=>et(ha(e,"$",false)),wo=e=>tn(gi(e),"Invalid value expression");var Zx=(e,t,r)=>e.value!==void 0?ya(e.value,`${r}.value`):typeof e.bind=="string"?X(r,"untyped_binding",`{ bind: '${e.bind}' } has no type until it is bound`):mg(pa(t,`the path '${String(e.path)}'`),e.path,r),Yx=(e,t,r,n)=>{let o=ba(e.then,t,`${r}.then`,n);return e.else===void 0?n?o:ua(o,da,r):ua(o,ba(e.else,t,`${r}.else`,n),r)},Xx=(e,t,r)=>{let n=ca(Jt(e).map((o,i)=>{let s=`${r}[${i}]`,a=ba(o,t,s,true);return a.isList&&X(s,"nested_list","a list's items are single values"),a}),r);return ma(e)&&n.kind===N.Json&&X(`${r}.distinct`,"distinct_over_json","distinct drops repeated values, not Json"),n},ba=(e,t,r,n)=>{switch(Pt(e)){case "literal":return ya(e,r);case "source":return Zx(e,t,r);case "aggregate":return cg(t,e,r);case "if":return Yx(e,t,r,n);case "list":return Xx(e,t,r);default:return X(r,"invalid_value_expression",Wn(r).message)}},bo=(e,t)=>(wo(e),ba(e,t,"$",false));var e$=["distinct","min","max"],t$=(e,t)=>{if(e.coerceType!==void 0||!e$.includes(e.aggregate.mode))return e;try{return bo(e,t).kind===N.DateTime?{...e,coerceType:N.DateTime}:e}catch(r){if(r instanceof an)return e;throw r}},Sa=(e,t)=>{switch(Pt(e)){case "aggregate":return t$(e,t);case "if":{let r=e;return {...r,then:Sa(r.then,t),...r.else!==void 0&&{else:Sa(r.else,t)}}}case "list":{let r=Jt(e).map(n=>Sa(n,t));return Array.isArray(e)?r:{...e,list:r}}default:return e}},yg=(e,t)=>(wo(e),Sa(e,t));var hg=(e,t)=>{let r=gi(e).errors;if(r.length>0)return {type:null,paths:[],clockUnit:null,errors:r};let n=Br(e),o=[...Ar(n,t).errors],i=null;try{i=bo(e,t);}catch(a){if(!(a instanceof an))throw a;o.push(a.issue);}let s=null;try{s=Wo(n);}catch(a){o.push({path:"$",code:"clock_unit_below_floor",message:a.message});}return {type:i,paths:De(n).sort(),clockUnit:s,errors:o}};var r$=15,n$=e=>e.replace(/^[-+]/,"").replace(/e.*$/i,"").replace(".","").replace(/^0+/,"").replace(/0+$/,"").length,Ql=e=>{let t=String(e),r=Number(t);if(!Number.isFinite(r))return e;if(n$(t)>r$)throw new RangeError(`${t} has more digits than a number holds exactly; json-rules reads a coerced Decimal as a number.`);return r},wg=(e,t)=>r=>{if(e===void 0)return r;if(e==="String"){if(r instanceof Date)return r.toISOString();if(typeof r=="object"&&r!==null)return String(r)}let o=(Q.includes(e)||e==="DateTime")&&typeof r=="bigint"?Wr(r):Q.includes(e)&&typeof r=="object"&&r!==null&&!(r instanceof Date)?Ql(r):r,i=Yt(o,e,t);return e==="DateTime"&&typeof i=="number"?new Date(i):i};var o$=(e,t)=>{if(typeof e=="number"&&Number.isFinite(e)||typeof e=="bigint")return {value:e,key:e,kind:"number"};if(e instanceof Date&&!Number.isNaN(e.getTime()))return {value:e,key:e.getTime(),kind:"date"};if(typeof e=="object"&&e!==null){let r=Ql(e);if(typeof r=="number")return {value:e,key:r,kind:"number"}}throw new Error(`${t} must be a finite number or a valid date for min / max`)},i$=(e,t,r)=>{if(e.length===0)return null;let n=new Set(e.map(o=>o.kind));if(n.size>1)throw new Error(`${r} ${t} orders one kind of value, not ${[...n].join(" and ")}`);return e.reduce((o,i)=>(t==="max"?i.key>o.key:i.key<o.key)?i:o).value},bg=(e,t,r)=>{if(ho(e))throw Un(r);if(!re(e.aggregate))throw new Error(`${r}.aggregate must be an object`);let{mode:n,field:o}=e.aggregate;if(!ts(n))throw us(n);if(typeof e.field!="string"||e.field==="")throw new Error(`${r}.field: an aggregate value reads a list field`);let i=Qa(e,t),s=e.coerceType==="DateTime"?Zt(t,l=>Be(l,t.scopes,t.bindings)).timeZone:qe,a=wg(e.coerceType,s);switch(n){case "count":return o===void 0?i.length:Go(i,e.field,o,()=>true).length;case "sum":case "avg":return Za(n,i,e.field,o);case "distinct":return ga(Go(i,e.field,o,a),oe(e.caseInsensitive));default:return i$(Go(i,e.field,o,(l,p)=>o$(a(l),p)),n,e.field)}};var Sg=(e,t,r)=>{if(e.if===void 0||e.then===void 0)throw new Error(`${r}: if / then takes both an if and a then`);return Nu(e.if,t)?{expr:e.then,path:`${r}.then`}:e.else===void 0?void 0:{expr:e.else,path:`${r}.else`}},s$=(e,t,r)=>{let n=Sg(e,t,r);return n===void 0?null:Ra(n.expr,t,n.path)},a$=(e,t,r)=>{if(!Array.isArray(e)&&!Array.isArray(e.list))throw new Error(`${r}.list must be an array`);let n=Jt(e).flatMap((o,i)=>{let s=`${r}[${i}]`,a=Pt(o);if(a==="list")throw new Error(`${s}: a list's items are single values`);if(a!=="if")return [Ra(o,t,s)];let l=Sg(o,t,s);return l===void 0?[]:[Ra(l.expr,t,l.path)]});return ma(e)?ga(n):n},Ra=(e,t,r)=>{switch(Pt(e)){case "literal":return e;case "source":return Be(e,t.scopes,t.bindings);case "aggregate":return bg(e,t,r);case "if":return s$(e,t,r);case "list":return a$(e,t,r);default:throw ho(e)?Un(r):Wn(r)}},Rg=(e,t,r={})=>Ra(e,{...r,scopes:[t]},"$");var Og=e=>Wo(Br(e));/*! Bundled license information:
3
+ `)}`)},Tr=(e,t={})=>{let r=Al(t);return rr(e,"$",r,1),t.positive&&qE(e,r),rt(r.errors)},Al=(e={})=>({target:e.target??"check",errors:[],map:Te(e.map,e.mapName,"toPrisma"),scopeModels:[e.model],stepScopes:[false]}),Pc=e=>{let t=Al(),r=ut(e)?_c(e,"$",t,1):null;r&&!ts(r.mode)&&v(t,"$.aggregate.mode","invalid_aggregate_mode",us(r.mode).message);let n=ut(e)?e:{},o=r?.mode;return o==="sum"||o==="avg"?Dc(n,"$",t,1):n.coerceType!==void 0&&(jn(n.coerceType)?["distinct","min","max"].includes(o)||v(t,"$.coerceType","unexpected_coerce_type","coerceType reads the values sum, avg, distinct, min and max read"):v(t,"$.coerceType","invalid_coerce_type",`coerceType must be one of: ${Object.keys(A).join(", ")}`)),n.caseInsensitive!==void 0&&(typeof n.caseInsensitive!="boolean"?v(t,"$.caseInsensitive","invalid_case_insensitive","caseInsensitive must be a boolean"):o!=="distinct"&&v(t,"$.caseInsensitive","unexpected_case_insensitive","caseInsensitive folds the strings distinct returns")),rt(t.errors)},kc=e=>{let t=Al();return ut(e)&&on(e,"$",t,1),rt(t.errors)},IE=["if","array","aggregate"],qE=(e,t)=>J(e,r=>{let n=de(r),o=r.operator??r.dateOperator;return (n&&IE.includes(n)||typeof o=="string"&&ns.includes(o))&&v(t,"$","notPositive",`${n==="field"||n==="date"?o:n} can hold on a missing value`),false}),BE=(e,t={})=>{sn(Tr(e,t),"validateRule");},rr=(e,t,r,n)=>{if(typeof e=="boolean")return;if(!ut(e)){v(r,t,"invalid_condition","Condition must be a boolean or object");return}let o=de(e);if(!o){v(r,t,"ambiguous_condition",$t().message);return}switch(o){case "all":vc(e.all,`${t}.all`,r,n);break;case "any":vc(e.any,`${t}.any`,r,n);break;case "if":rr(e.if,`${t}.if`,r,n),rr(e.then,`${t}.then`,r,n),"else"in e&&e.else!==void 0&&rr(e.else,`${t}.else`,r,n);break;case "field":WE(e,t,r,n);break;case "aggregate":GE(e,t,r,n);break;case "array":zE(e,t,r,n);break;case "date":HE(e,t,r,n);break}},vc=(e,t,r,n)=>{if(!Array.isArray(e)){v(r,t,"logical_array_required","Logical operator requires an array of conditions");return}e.forEach((o,i)=>{rr(o,`${t}[${i}]`,r,n);});},ta=(e,t,r,n)=>{typeof e.field=="string"&&Tc(e.field,"field",`${t}.field`,r,n);},Tc=(e,t,r,n,o,i=false)=>{let s=L(e)??(t==="path"?{depth:o}:null);if(!s)return;let a=t==="field"?"Field":"Path";s.depth>o&&v(n,r,"scope_out_of_bounds",Na(e,s.depth,o)),n.target==="toPrisma"&&!i?v(n,r,`unsupported_prisma_${t}`,t==="path"?`Path '${e}' compares to a column, which isn't supported on the Prisma rail; use toSql() or check()`:`${a} '${e}' is not supported by toPrisma()`):n.target==="toSql"&&(t==="field"||s.depth>1)&&v(n,r,`unsupported_sql_${t}`,`${a} '${e}' is not supported by toSql()`);},ea=(e,t,r,n=false)=>{e.stepScopes[t]=n||e.stepScopes[t-1]===true;let o=e.scopeModels[t-1];e.scopeModels[t]=e.map&&o&&typeof r=="string"?ao(r,e.map,o)??void 0:void 0;},on=(e,t,r,n,o=false)=>{let i=du.filter(a=>e[a]!==void 0);if(i.length>1)return v(r,t,"ambiguous_value_source","Takes one of value, path or bind"),null;if(i.length===0)return v(r,t,"missing_value_source","Requires value, path or bind"),null;let[s]=i;return s!=="value"&&(typeof e[s]!="string"||e[s]==="")?(v(r,`${t}.${s}`,"invalid_value_source",`${s} is a non-empty string`),null):(e.bindOptional!==void 0&&(s!=="bind"||typeof e.bindOptional!="boolean")&&v(r,`${t}.bindOptional`,"invalid_value_source","bindOptional is a boolean beside bind"),s==="path"&&Tc(e.path,"path",`${t}.path`,r,n,o),s)},Cc=(e,t,r,n,o,i)=>{let{offset:s}=e;if(s===void 0)return;let a=`${n}.offset`;if(!Gf.includes(r)){v(o,a,"unsupported_offset_operator",`Operator '${r}' has no comparison point to offset`);return}if(!ut(s)){v(o,a,"invalid_offset","An offset is one of { value }, { path } or { bind }");return}let l=on(s,a,o,i);if(l==="path"){let f=s.path,u=qr(s);t==="date"&&u&&u.depth<=1&&o.target==="toSql"&&v(o,`${a}.path`,"unsupported_sql_path",`A row path on a date offset ('${f}') is not supported by toSql()`);return}if(l!=="value")return;let p=s.value;if(t==="field"){(typeof p!="number"||!Number.isFinite(p))&&v(o,`${a}.value`,"invalid_offset","A field offset value is a number");return}let d=ut(p)&&Object.keys(p).length===1&&Z(p)?Ee(p):null;if(!d){v(o,`${a}.value`,"invalid_offset","A date offset value is { ago } or { ahead }");return}Fc(d[0],`${a}.value.${Object.keys(p)[0]}`,o,i);},Lc=(e,t,r,n)=>{n.target!=="toSql"||!Qe.includes(t)||qr(e)&&v(n,`${r}.path`,"unsupported_sql_path",`A range read from the row ('${e.path}') is not supported by toSql()`);},WE=(e,t,r,n)=>{if(typeof e.field!="string"&&v(r,`${t}.field`,"field_required","Field rule requires a string field"),ta(e,t,r,n),typeof e.operator!="string"||!Kt(e.operator,"field")){v(r,`${t}.operator`,"invalid_operator",me(e.operator,"field").message);return}let o=e.operator;Cc(e,"field",o,t,r,n),Xi(o,"field",r.target)||v(r,`${t}.operator`,`unsupported_${ra(r.target)}_operator`,`Operator '${o}' is not supported by ${r.target}()`),e.coerceType!==void 0&&!jn(e.coerceType)&&v(r,`${t}.coerceType`,"invalid_coerce_type",`coerceType must be one of: ${Object.keys(A).join(", ")}`);let i=zt(o,"field");if(i==="none"){jc(e,t,r);return}if(on(e,t,r,n,true)!==null){if(Lc(e,o,t,r),r.target==="toPrisma"&&typeof e.path=="string"){let s=Ls(e,r.map,r.scopeModels[n-1],n>1,r.stepScopes[n-1]===true);"problem"in s&&v(r,`${t}.path`,"unsupported_prisma_path",Ms(e.path,s.problem).message);}if(r.target==="toSql"&&typeof e.path=="string"&&r.map){let s=r.scopeModels[n-1],a=(L(e.path)??{path:e.path}).path,l=so(Y(e.field,r.map,s),Y(a,r.map,s),o);l&&v(r,`${t}.path`,"unsupported_sql_path",`'${e.path}': ${l}`);}r.target==="toSql"&&typeof e.path=="string"&&["array","pattern","string"].includes(i)&&((r.map?Y(e.field,r.map,r.scopeModels[n-1]):void 0)?.isList&&Et.includes(o)||v(r,`${t}.path`,"unsupported_sql_path",`'${o}' against the column '${e.path}' has no SQL form`)),!(typeof e.path=="string"||typeof e.bind=="string")&&(UE(e,o,t,r,n),KE(i,e.value,o,`${t}.value`,r));}},UE=(e,t,r,n,o)=>{if(n.target!=="toPrisma"||!n.map||typeof e.field!="string")return;let i=Y(e.field,n.map,n.scopeModels[o-1]);if(!i)return;let s=e.value,a=ie(e.caseInsensitive),l=cr.includes(t)&&Array.isArray(s),p=d=>v(n,`${r}.value`,"unsupported_prisma_operator",V("toPrisma",d).message);i.isList&&!l&&Array.isArray(s)&&s.includes(null)?p(`A list holding null in '${e.field}'`):i.isList&&!l&&a&&xr("text",s)?p(`A case-insensitive comparison on the list '${e.field}'`):Fe(i)&&a&&p(`A case-insensitive comparison on the Json column '${e.field}'`);},KE=(e,t,r,n,o)=>{switch(e){case "scalar":case "string":e==="string"&&typeof t!="string"&&v(o,n,"invalid_string_value",`Operator '${r}' requires a string value`);return;case "ordered":we(t)||v(o,n,"invalid_ordered_value",`Operator '${r}' requires a string, number, or Date value`);return;case "array":Array.isArray(t)||v(o,n,"invalid_membership_value",`Operator '${r}' requires an array value`);return;case "pattern":{if(!(typeof t=="string"||t instanceof RegExp)){v(o,n,"invalid_pattern_value",`Operator '${r}' requires a string or RegExp value`);return}let i=$u(t,o.target);i&&v(o,n,"unsupported_pattern",i);return}case "range":try{to(t,r);}catch(i){v(o,n,"invalid_range_value",i.message);}return}},Mc=(e,t,r,n,o)=>{let i=r.scopeModels[n-1];if(r.target!=="toPrisma"||!r.map||!i||typeof e.field!="string")return;let s;try{s=uo(e.field,r.map,i,o).target;}catch(p){v(r,`${t}.field`,"unsupported_prisma_relation",p.message);return}if(o==="Count operators")return;let a=e.aggregate?.field,l=typeof a=="string"&&a!==""?gl(r.map,s,a):ml();l&&v(r,`${t}.aggregate.field`,"unsupported_prisma_aggregate_field",l.message);},_c=(e,t,r,n)=>{if(Mc(e,t,r,n,"Aggregate rules"),e.offset!==void 0&&v(r,`${t}.offset`,"unexpected_offset","Aggregate rules take no offset"),Vc(e,t,r,n),typeof e.field!="string"&&v(r,`${t}.field`,"field_required","Aggregate rule requires a string field"),ta(e,t,r,n),!ut(e.aggregate))return v(r,`${t}.aggregate`,"invalid_aggregate","aggregate must be an object"),null;let o=e.aggregate;return "field"in o&&o.field!==void 0&&typeof o.field!="string"&&v(r,`${t}.aggregate.field`,"invalid_aggregate_field","aggregate.field must be a string"),"condition"in e&&e.condition!==void 0&&(r.target==="toSql"&&v(r,`${t}.condition`,"unsupported_sql_aggregate_condition","Aggregate condition filtering is not supported by toSql(); use check() or toPrisma()"),ea(r,n,e.field,true),rr(e.condition,`${t}.condition`,r,n+1)),o},Dc=(e,t,r,n)=>{let{coerceType:o}=e;if(o===void 0)return;let i=`${t}.coerceType`;if(!jn(o)){v(r,i,"invalid_coerce_type",`coerceType must be one of: ${Object.keys(A).join(", ")}`);return}if(!G.includes(o)){v(r,i,"aggregate_kind_mismatch",`sum and avg add numbers, not ${o}`);return}let s=r.scopeModels[n-1];if(!r.map||!s||typeof e.field!="string")return;let a=e.aggregate?.field,l=ao(e.field,r.map,s),p=l?typeof a=="string"?Y(a,r.map,l):void 0:Y(e.field,r.map,s),d=p&&p.kind==="scalar"&&!Fe(p)?p.type:null;$l(d,o)||v(r,i,"coerce_kind_mismatch",vl(d,o));},GE=(e,t,r,n)=>{let o=_c(e,t,r,n);if(!o)return;if(xt.includes(o.mode)||v(r,`${t}.aggregate.mode`,"invalid_aggregate_mode",gr(o.mode).message),Dc(e,t,r,n),!es.includes(e.operator)){v(r,`${t}.operator`,"invalid_aggregate_operator",`Aggregate rules only support: ${es.join(", ")}`);return}if(Je.includes(e.operator)){jc(e,t,r);return}if(r.target==="toPrisma"&&typeof e.path=="string"&&v(r,`${t}.path`,"unsupported_prisma_aggregate_path",cs(e.path).message),on(e,t,r,n,true)===null||typeof e.path=="string"||typeof e.bind=="string")return;let i=e.value;if(Qe.includes(e.operator))JE(i)||v(r,`${t}.value`,"invalid_range_value",`Operator '${e.operator}' requires a two-item numeric range`);else {let s=i===null&&_e.includes(e.operator);typeof i!="number"&&!s&&v(r,`${t}.value`,"invalid_aggregate_value","Aggregate rule value must be a number");}},zE=(e,t,r,n)=>{if(typeof e.field!="string"&&r.target!=="check"&&v(r,`${t}.field`,"field_required","Array rule requires a string field for this target"),ta(e,t,r,n),Vc(e,t,r,n),typeof e.arrayOperator!="string"||!Kt(e.arrayOperator,"array")){v(r,`${t}.arrayOperator`,"invalid_array_operator",me(e.arrayOperator,"array").message);return}let o=e.arrayOperator;Fo(e)&&Mc(e,t,r,n,"Count operators");let i=r.target==="toPrisma"&&r.map&&typeof e.field=="string"?Y(e.field,r.map,r.scopeModels[n-1]):void 0;i&&!_(i)&&o!=="empty"&&o!=="notEmpty"&&v(r,`${t}.arrayOperator`,"unsupported_prisma_array_operator",V("toPrisma",`'${o}' over the array column '${e.field}'`).message),Xi(o,"array",r.target)||v(r,`${t}.arrayOperator`,`unsupported_${ra(r.target)}_array_operator`,`Array operator '${o}' is not supported by ${r.target}()`);let s=zt(o,"array"),a=e.condition!==void 0,l=()=>{e.count!==void 0&&v(r,`${t}.count`,"unexpected_count",`Array operator '${o}' does not accept count`);};s==="none"?(a&&v(r,`${t}.condition`,"unexpected_condition",`Array operator '${o}' does not accept condition`),l()):s==="predicate"?(a?(ea(r,n,e.field),rr(e.condition,`${t}.condition`,r,n+1)):v(r,`${t}.condition`,"missing_condition",We(o).message),l()):s==="count"&&(typeof e.count!="number"?v(r,`${t}.count`,"missing_count",Un(o).message):e.count!==void 0&&!(typeof e.count=="number"&&Number.isInteger(e.count)&&e.count>=0)&&v(r,`${t}.count`,"invalid_count","count must be a non-negative whole number"),a?(ea(r,n,e.field,Fo(e)),rr(e.condition,`${t}.condition`,r,n+1)):v(r,`${t}.condition`,"missing_condition",We(o).message));},HE=(e,t,r,n)=>{if(typeof e.field!="string"&&v(r,`${t}.field`,"field_required","Date rule requires a string field"),ta(e,t,r,n),typeof e.dateOperator!="string"||!Kt(e.dateOperator,"date")){v(r,`${t}.dateOperator`,"invalid_date_operator",me(e.dateOperator,"date").message);return}let o=e.dateOperator;Cc(e,"date",o,t,r,n);let i=Qt(e.value,Qa(e.offset));i&&v(r,t,"clock_unit_below_floor",i.message),Xi(o,"date",r.target)||v(r,`${t}.dateOperator`,`unsupported_${ra(r.target)}_date_operator`,`Date operator '${o}' is not supported by ${r.target}()`);let s=zt(o,"date");if(s==="dayList"){if(on(e,t,r,n)!=="value")return;let a=e.value;(!Array.isArray(a)||!a.every(l=>typeof l=="string"&&iu(l)))&&v(r,`${t}.value`,"invalid_day_list",`Date operator '${o}' requires an array of day names (${Wn.join(", ")})`);return}if(on(e,t,r,n)!==null&&(Lc(e,o,t,r),!(typeof e.path=="string"||typeof e.bind=="string"))){if(Z(e.value)){Nc(e.value,o,`${t}.value`,r,n);return}if(_o.includes(o)){v(r,`${t}.value`,"invalid_date_range",it(o).message);return}if(s==="dateRange"){if(!QE(e.value)){v(r,`${t}.value`,"invalid_date_range",`Date operator '${o}' requires a two-item date range`);return}e.value.forEach((a,l)=>{Z(a)?Nc(a,o,`${t}.value[${l}]`,r,n):we(a)&&!Sr(a,Ne).isValid()&&v(r,`${t}.value[${l}]`,"invalid_date_value",`Date operator '${o}' value '${String(a)}' does not parse as a date`);});return}if(!we(e.value)){v(r,`${t}.value`,"invalid_date_value",`Date operator '${o}' requires a date-like value`);return}Sr(e.value,Ne).isValid()||v(r,`${t}.value`,"invalid_date_value",`Date operator '${o}' value '${String(e.value)}' does not parse as a date`);}},Fc=(e,t,r,n)=>{if(!ut(e)||Object.keys(e).length===0){v(r,t,"invalid_relative_units","Relative offset requires at least one unit");return}for(let[o,i]of Object.entries(e)){if(!Bn(o)){v(r,`${t}.${o}`,"invalid_relative_unit",`Unknown relative unit '${o}'`);continue}let s=ut(i)?on(i,`${t}.${o}`,r,n):"literal";if(s===null||s==="path"||s==="bind")continue;let a=s==="value"?i.value:i,l=Ha(a,o);l&&v(r,`${t}.${o}`,"invalid_relative_magnitude",l);}},Ac=(e,t,r)=>{(typeof e!="string"||!ss.includes(e))&&v(r,t,"invalid_period_unit",`Unknown period unit '${String(e)}'`);},Nc=(e,t,r,n,o)=>{let i=_o.includes(t),s=Ee(e);if(s){Fc(s[0],r,n,o);return}if(qo(e)){Ac(Jn(e),r,n);return}if(Bo(e)){if(i){v(n,r,"invalid_date_range",it(t).message);return}let a="start"in e?e.start:e.end;if(!ut(a)||!qo(a)){v(n,r,"invalid_period_unit","start/end requires a this/last/next period");return}Ac(Jn(a),r,n);return}v(n,r,"invalid_date_expression","Unrecognized date expression");},jc=(e,t,r)=>{"value"in e&&e.value!==void 0&&v(r,`${t}.value`,"unexpected_value","Rule does not accept value"),"path"in e&&e.path!==void 0&&v(r,`${t}.path`,"unexpected_path","Rule does not accept path"),"bind"in e&&e.bind!==void 0&&v(r,`${t}.bind`,"unexpected_bind","Rule does not accept bind");},ra=e=>e==="toPrisma"?"prisma":e==="toSql"?"sql":"check",ut=e=>re(e),JE=e=>Array.isArray(e)&&e.length===2&&typeof e[0]=="number"&&typeof e[1]=="number",QE=e=>Array.isArray(e)&&e.length===2&&(we(e[0])||Z(e[0]))&&(we(e[1])||Z(e[1])),Vc=(e,t,r,n)=>{if(ke(e)&&r.target!=="check"&&(r.target==="toPrisma"&&io(e)!==null||v(r,t,`unsupported_${ra(r.target)}_window`,vt(r.target).message)),"filter"in e&&e.filter!==void 0&&(ea(r,n,e.field),rr(e.filter,`${t}.filter`,r,n+1)),"orderBy"in e&&e.orderBy!==void 0){let i=e.orderBy;Array.isArray(i)?i.forEach((s,a)=>{(!ut(s)||typeof s.field!="string"||s.dir!=="asc"&&s.dir!=="desc")&&v(r,`${t}.orderBy[${a}]`,"invalid_order_by",'orderBy entries must be { field: string, dir: "asc" | "desc" }');}):v(r,`${t}.orderBy`,"invalid_order_by","orderBy must be an array of { field, dir }");}for(let i of ["take","skip"])if(i in e&&e[i]!==void 0){let s=e[i];(typeof s!="number"||!Number.isInteger(s)||s<0)&&v(r,`${t}.${i}`,`invalid_window_${i}`,`${i} must be a non-negative integer`);}},v=(e,t,r,n)=>{e.errors.push({path:t,code:r,message:n});};var ZE=/[.:]/,Nl=e=>{let t=[];for(let[r,n]of Object.entries(e.maps))for(let[o,i]of Object.entries(n.models))for(let[s,a]of Object.entries(i.fields))a.kind!=="bridge"&&ZE.test(s)&&t.push({path:`${De({fieldMap:r,model:o})}.${s}`,message:"contains forbidden character . or :",code:"invalid_field_name"});return rt(t)},Ic=e=>sn(Nl(e),"validateFieldMaps");var kl="parent:",Tl=e=>e.startsWith(kl),Bc=e=>Tl(e)?e.slice(kl.length):e,Pl=(e,t)=>{let r={...e};if(e.where!==void 0&&(r.where=t(e.where)),e.sources){let n={};for(let[o,i]of Object.entries(e.sources))n[o]=ni(i)?i.where!==void 0?{...i,where:t(i.where)}:i:t(i);r.sources=n;}if("relations"in e&&e.relations){let n={};for(let[o,i]of Object.entries(e.relations))n[o]=Pl(i,t);r.relations=n;}return r},Wc=(e,t)=>{let r={};for(let[n,o]of Object.entries(e.mapDefaults??{})){let i={};for(let[s,a]of Object.entries(o.models??{}))i[s]=Pl(a,t);r[n]=o.models?{...o,models:i}:o;}return {...e,root:e.root?Pl(e.root,t):void 0,mapDefaults:e.mapDefaults?r:void 0}},Cl=e=>{let t=[];return Wc(e,r=>(t.push(r),r)),t},qc=e=>{let t=new Set;for(let r of Cl(e))for(let n of Uo(r))Tl(n)||t.add(n);return t},Uc=e=>{let t=new Set;for(let r of Lt(e))for(let n of Cl(r))for(let o of Uo(n,{required:true}))t.add(Bc(o));return [...t].sort()},Kc=(e,t)=>{if(dt(e))return e;let r={...t};for(let[n,o]of Object.entries(t))r[`${kl}${n}`]=o;return {...Wc(e,n=>Ga(n,r)),parent:Kc(e.parent,t)}},Gc=(e,t)=>Kc(e,t),zc=e=>{let t=[],r=new Set;for(let o of Lt(e.parent))for(let i of qc(o))r.add(i);for(let o of qc(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 Cl(e))for(let i of Uo(o))Tl(i)&&n.add(Bc(i));for(let o of n)r.has(o)||t.push(`bind 'parent:${o}' references an inherited binding no ancestor declares`);return t};var Jc=(e,t)=>e===void 0?t:t===void 0?e:{all:[e,t]},YE=(e,t)=>{if(!e||!t)return e??t;let r={...e};for(let[n,o]of Object.entries(t)){let i=r[n];if(i===void 0){r[n]=o;continue}let s=kr(i),a=kr(o),l=Jc(s.where,a.where);r[n]={...s,...a,...l===void 0?{}:{where:l}};}return r},Qc=(e,t)=>{let r=Jc(e?.where,t.where),n=YE(e?.sources,t.sources);return {...e,...r===void 0?{}:{where:r},...n?{sources:n}:{}}},XE=(e,t)=>{let r={...e?.models};for(let[n,o]of Object.entries(t))r[n]=Qc(r[n],o);return {...e,models:r}},Hc=(e,t)=>{let r={...e.mapDefaults};for(let[n,{models:o}]of Object.entries(t.mapDefaults??{}))r[n]=XE(r[n],o);return {...e,...t.root?{root:Qc(e.root,t.root)}:{},...t.mapDefaults?{mapDefaults:r}:{}}},Ll=(e,t)=>dt(e)?Hc({parent:e},t):dt(e.parent)?Hc(e,t):{...e,parent:Ll(e.parent,t)};var Zc=(e,t)=>{let r=F(t),n=(o,i)=>typeof o=="string"&&o!==""?ho(r,i,o):null;return hr(e,{rewrite:(o,i)=>{if(de(o)!=="field"||o.coerceType)return o;let s=n(o.field,i);if(!s||"issue"in s||!s.walked||s.walked.jsonSubPath.length)return o;let{entry:a}=s.walked;return a.kind==="scalar"&&eu.includes(a.type)?{...o,coerceType:a.type}:o},below:(o,i)=>{if(!xe(o))return false;let s=n(o.field,i),a=s&&!("issue"in s)?s.walked?.entry:void 0;return s&&!("issue"in s)&&a&&_(a)?[...i,s.next]:false}},[Mt(r)])};var Yc=({maps:e,bridges:t,mapName:r,model:n})=>({...Ns({maps:e,bridges:t}),mapName:r,model:n});var ex=(e,t)=>J(e,(r,n)=>{if(t.sources.add(n[n.length-1].mapName),Ke(r)||typeof r.field!="string"||r.field==="")return;let o=ho(t.policy,n,r.field);return "issue"in o?false:(o.walked&&(t.sources.add(o.walked.mapName),(o.walked.entry.kind==="bridge"||o.walked.mapName!==o.from.mapName)&&(t.bridgesCrossed=true)),[...n,o.next])},[Mt(t.policy)]),Xc=(e,t)=>{let n={policy:F(t),sources:new Set,bridgesCrossed:false};return ex(e,n),{sources:[...n.sources].sort(),bridgesCrossed:n.bridgesCrossed,supportedTargets:D.filter(o=>(o==="check"||!n.bridgesCrossed)&&Tr(e,{target:o,map:n.policy.lens,mapName:n.policy.lens.mapName,model:n.policy.lens.model}).ok),errors:Pr(e,t).errors}};var tx=new Set([Gt.scalar,Gt.ordered,Gt.array,Gt.dayList,Gt.dateValue]),rx=new Set([Gt.none,Gt.count]),nx=e=>{if(e.offset!==void 0||Ur(e).some(({source:r})=>r.value===void 0))return {values:[],dynamic:true};let t=Vn(e);return t?rx.has(t.valueShape)?{values:[],dynamic:false}:tx.has(t.valueShape)?"value"in e?{values:Yo(e)??[],dynamic:false}:{values:[],dynamic:false}:{values:[],dynamic:true}:{values:[],dynamic:true}},ox=e=>e instanceof Date?`d:${+e}`:e instanceof RegExp?`r:${e}`:typeof e=="object"&&e!==null?`j:${JSON.stringify(e)}`:`p:${typeof e}:${String(e)}`,em=(e,t)=>{let r=F(t),n=r.lens.model,o=new Map,i=new Map,s=(l,p)=>{if(l.length===0)return;let d=yo(r,{mapName:r.lens.mapName,modelName:n,relPath:[]},l.join("."));if(!d||d.jsonSubPath.length>0)return;let{mapName:f,modelName:u,relPath:c,terminalEffect:y,terminalFieldName:m}=d;if(!y.sources.has(m))return;let g=[n,...c].join("."),S=`${g}|${m}`,b=o.get(S);b||(b={path:g,mapName:f,model:u,field:m,values:[],dynamic:false},o.set(S,b));let w=nx(p);w.dynamic&&(b.dynamic=true);let R=i.get(S)??new Set;i.set(S,R);for(let O of w.values){let $=ox(O);R.has($)||(R.add($),b.values.push(O));}},a=(l,p)=>{let d=He(l,p);if(!("outOfBounds"in d))return [...d.scope,...d.path.split(".")]};return J(e,(l,p)=>{if(Ke(l))return;let d=typeof l.field=="string"?a(l.field,p):p.at(-1);return d?(!xe(l)&&typeof l.field=="string"&&s(d,l),[...p,d]):false},[[]]),[...o.values()]};var na=(e,t,r,n)=>{let o=ix(e,t,r);if(o.options===t)return n(o.condition,o.options);try{return n(o.condition,o.options)}catch(i){if(i instanceof T||i instanceof M)throw i;try{n(e,o.options);}catch{throw i}throw new T(`${r}: the lens's clamps on this rule have no ${r} form \u2014 ${i.message}`,"unsupported_target")}},ix=(e,t,r)=>{if(t?.lens===void 0)return {condition:e,options:t};let{lens:n}=t;if(t.map!==void 0||t.mapName!==void 0||t.model!==void 0)throw new M(`${r}: pass \`lens\` or \`map\` / \`mapName\` / \`model\`, not both \u2014 the lens names its own`);let o=Pr(e,n);if(!o.ok)throw new Error(`${r}: the rule leaves the lens \u2014 ${o.errors.map(s=>`${s.path}: ${s.message}`).join("; ")}`);let i=ft(n);return {condition:go(e,n),options:{...t,lens:void 0,map:i,mapName:i.mapName,model:i.model}}};var rm=(e,t,r)=>{if(!e.field)throw new Error("toPrisma: count-based ArrayRule requires a field path");let n=uo(e.field,t.map,t.model,"Count operators");if(e.condition===void 0)throw We(e.arrayOperator);if(e.count===void 0)throw Un(e.arrayOperator);let o=e.count;if(e.arrayOperator===x.atLeast&&o===0)return et();let i=ue(e.condition,Yr({...t,model:n.target},t,true),r),s=Ml(e),a=s?tm(x.atLeast,e.arrayOperator===x.atMost?o+1:1,n.targetKey):tm(e.arrayOperator,o,n.targetKey);return Zo(r,n,i,a,s)},tm=(e,t,r)=>{let n=ur(e,"array");if(!n)throw new Error(`'${e}' does not count`);return {[r]:{_count:{[n]:t}}}};var nm=(e,t,r)=>{let n=om(e,t,r);return e.field&&Ml(e)&&!im(e.field,t)?U([n,...Ar(e.field,t)]):n},Ml=e=>Se({...e,field:"items"},{items:[]})===true,sx=e=>{let t=Va(e);if(!t)return null;let{count:r,...n}=e;return {...n,arrayOperator:t}},om=(e,t,r)=>{if(ke(e)){let s=io(e);if(!s)throw vt("toPrisma");return ue(s,t,r)}if(e.condition!==void 0&&!Hf.includes(e.arrayOperator)&&kt(e.condition,t?.map,sm(e,t)?.model))return Xr();let n=sx(e);if(n)return om(n,t,r);if(Do.includes(e.arrayOperator)){if(t?.map&&t?.model&&r)return rm(e,t,r);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 ls("toPrisma");let{field:o}=e;if(im(o,t))return ax(e,o,Ge({field:o},t?.map,t?.model),t);let i=lx(e,t,r);return tt(e.field,i,t)},im=(e,t)=>{let r=Ge({field:e},t?.map,t?.model);return r==="list"||r==="json"||r==="json-path"},ax=(e,t,r,n)=>{switch(e.arrayOperator){case x.empty:return js(t,r,true,false,n);case x.notEmpty:{let o=js(t,r,false,false,n);return r==="list"?o:ce([o,tt(t,{array_contains:[]},n)])}default:throw V("toPrisma",`'${e.arrayOperator}' over the ${r==="list"?"list":"Json array"} '${t}'`,r==="list"?"test a list's membership with 'contains'":void 0)}},sm=(e,t)=>{if(!t?.map||!t?.model||!e.field)return t&&Yr({...t});let r=ao(e.field,t.map,t.model);return Yr(r?{...t,model:r}:{...t})},lx=(e,t,r)=>{let n=sm(e,t);switch(e.arrayOperator){case x.all:if(!e.condition)throw We(e.arrayOperator);return {none:ue($r(e.condition,fo(n)),n,r)};case x.any:if(!e.condition)throw We(e.arrayOperator);return {some:ue(e.condition,n,r)};case x.none:if(!e.condition)throw We(e.arrayOperator);return {none:ue(e.condition,n,r)};case x.empty:return {none:{}};case x.notEmpty:return {some:{}};default:throw me(e.arrayOperator,"array")}};var am=(e,t)=>{let r=t?.map,n=Ge({field:e.field},r,t?.model);if(n==="json"||n==="json-path")throw V("toPrisma",`A date rule on the Json value '${e.field}'`,"Prisma compares Json text");let o=Y(e.field,r,t?.model);if(o&&!_(o)&&ze(o)!==A.DateTime)throw V("toPrisma",`A date rule on the ${o.type} field '${e.field}'`,`Prisma compares it as ${o.type}, not as an instant`);let i=B.includes(e.dateOperator)?fl(e,t):[],s=px(e,t);if(s===null)return U(i);let a=tt(e.field,s,t),l=qn.includes(e.dateOperator)?je(a):a;return U([l,...i])},px=(e,t)=>{let r=po(t),n=Jo,o=c=>e.offset===void 0?c:sc(c,e.offset,t),i=c=>{if(c==null)return null;if(!Z(c))return Os(c,r.timeZone);let y=Xe(c,n);return y&&Qn(y,e.dateOperator,r).toDate()},s=()=>{let c=Tt(e);if(c==null)return c;let y=e.offset===void 0?void 0:Tt(e.offset),m=Qt(c,y);if(m)throw m;return c},a=()=>o(i(s())),l=()=>{let c=s();if(c==null)return null;let y=st(c,e.dateOperator).map(i);if(y[0]===null||y[1]===null)return null;let[m,g]=Ze(y).map(o);return m&&g?[m,g]:null},p=()=>{let c=s();if(c==null)return null;if(!Z(c))throw it(e.dateOperator);let y=Xe(c,n);if(!y)return null;let[m,g]=Zn(y,r);return [m.toDate(),g.toDate()]},d=c=>{let y=a();return y===null?null:{[c]:y}},f=c=>c?{gte:c[0],lte:c[1]}:null,u=ur(e.dateOperator,"date");if(u)return d(u);switch(e.dateOperator){case N.within:case N.notWithin:return f(p());case N.between:case N.notBetween:return f(l());case N.dayIn:case N.dayNotIn:throw V("toPrisma",`'${e.dateOperator}'`);default:throw me(e.dateOperator,"date")}};var _l=(e,t,r)=>{if(typeof e=="boolean")return e?{}:pt();wi(e,"toPrisma");let n=de(e);(n==="field"||n==="date")&&ks(e.field,t?.map,t?.model);let o=e;switch(n){case "all":return rc(o,t,r);case "any":return nc(o,t,r);case "if":return oc(o,t,r);case "array":return nm(o,t,r);case "aggregate":return fc(o,t,r);case "date":return am(o,t);case "field":return pc(o,t);default:throw $t()}};ec(_l);var pm=(e,t,r)=>t&&r?an(e,t,r):e,ct=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),oa=(e,t,r)=>{let n=ge(e,t,r);return n?.kind==="object"&&!n.isList?n.type:null},dx=["some","every","none"],ai=e=>Object.entries(e).flatMap(([t,r])=>t!=="AND"?[{[t]:r}]:(Array.isArray(r)?r:[r]).flatMap(o=>ct(o)?ai(o):[{AND:o}])),Dl=(e,t,r)=>{let n=Object.keys(e);if(n.length!==1||!oa(t,r,n[0]))return null;let o=e[n[0]];if(!ct(o))return null;let i=Object.keys(o);return i.includes("isNot")?null:i.includes("is")?i.length===1&&ct(o.is)?{key:n[0],isForm:true,inner:o.is}:null:ai(o).length?{key:n[0],isForm:false,inner:o}:null},dm=(e,t,r)=>{let n=Dl(e,t,r);if(!n)return [];let o=oa(t,r,n.key);return [n.key,...ai(n.inner).flatMap(i=>dm(i,t,o).map(s=>`${n.key}.${s}`))]},fm=(e,t,r)=>{if(!ct(e))return null;let n=Object.keys(e);if(n.length!==1)return null;let o=oa(t,r,n[0]),i=e[n[0]];if(!o||!ct(i))return null;let s=Object.keys(i);if(s.length===1&&s[0]==="is"&&i.is===null)return n[0];let a=fm(i,t,o);return a?`${n[0]}.${a}`:null},fx=(e,t,r)=>{let n=e.map(o=>ct(o)?an(o,t,r):o);return n.some((o,i)=>o!==e[i])?n:e},Fl=(e,t)=>{let r=false,n={};for(let[o,i]of Object.entries(e))n[o]=t(o,i),n[o]!==i&&(r=true);return r?n:e},ux=(e,t,r,n)=>{if(e==="AND"||e==="OR"||e==="NOT")return Array.isArray(t)?fx(t,r,n):ct(t)?an(t,r,n):t;let o=ge(r,n,e);if(o?.kind!=="object"||!ct(t))return t;if(o.isList)return Fl(t,(s,a)=>dx.includes(s)&&ct(a)?an(a,r,o.type):a);let i=Object.keys(t);return i.length===1&&(i[0]==="is"||i[0]==="isNot")?Fl(t,(s,a)=>ct(a)?an(a,r,o.type):a):an(t,r,o.type)},lm=(e,t,r)=>Fl(e,(n,o)=>ux(n,o,t,r)),cx=(e,t,r,n)=>{let o=Object.keys(e);if(o.length!==1||o[0]!=="OR"||!Array.isArray(e.OR))return null;let i=e.OR,s=i.filter(a=>{let l=fm(a,r,n);return l===null||!t.has(l)});return s.length===i.length||s.length===0?null:s.length===1&&ct(s[0])?ai(s[0]):[{OR:s}]},an=(e,t,r)=>{let n=ai(e),o=false;for(let l=true;l;){l=false;let p=new Set(n.flatMap(d=>dm(d,t,r)));n=n.flatMap(d=>{let f=cx(d,p,t,r);return f?(l=o=true,f):[d]});}let i=new Map;for(let l of n){let p=Dl(l,t,r);p&&i.set(p.key,[...i.get(p.key)??[],p]);}if(!o&&![...i.values()].some(l=>l.length>1))return lm(e,t,r);let s=new Set,a=[];for(let l of n){let p=Dl(l,t,r),d=p?i.get(p.key)??[]:[];if(!p||d.length<2){a.push(lm(l,t,r));continue}if(s.has(p.key))continue;s.add(p.key);let f=oa(t,r,p.key),u=an(ce(d.map(c=>c.inner)),t,f);a.push({[p.key]:d.some(c=>c.isForm)?{is:u}:u});}return ce(a)};var cm=async(e,t)=>{let r=e.steps.filter(i=>i.operation==="groupBy"),n=e.steps.find(i=>i.operation==="where");if(!n)throw new Error("executePrismaPlan: result has no where step");let o=[];for(let i of r){let s=mm(t,i.model),a=um(i.args,i.refs,o,t),l=await s[i.operation](a);o.push(l.map(p=>p[i.extract]).filter(p=>p!=null));}return um(n.where,n.refs,o,t)},mm=(e,t)=>{let r=t.charAt(0).toLowerCase()+t.slice(1),n=e[r];if(!n)throw new Error(`executePrismaPlan: no delegate for model '${t}'. Ensure prismaDelegate has a key '${r}'.`);return n},mx=(e,t)=>{let r=mm(e,t.model).fields,n=r&&Object.hasOwn(r,t.field)?r[t.field]:void 0;if(n===void 0)throw new Error(`executePrismaPlan: the '${t.model}' delegate has no field reference '${t.field}' (fields.${t.field}).`);return n},gx=(e,t)=>t.reduce((r,n)=>r!==null&&typeof r=="object"&&Object.hasOwn(r,n)?r[n]:void 0,e),jl=(e,t,r)=>{if(t.length===0)return r;let[n,...o]=t,i=e,s=Array.isArray(e)?[...e]:{...i};return s[n]=jl(i[n],o,r),s},um=(e,t,r,n)=>{let o=e;for(let{path:i}of t??[]){let s=gx(e,i);if(s&&typeof s.__step=="number"){let a=s.__step;if(a>=r.length)throw new Error(`Step ref __step: ${a} out of range (${r.length} steps executed)`);o=jl(o,i,r[a]);}else if(s&&typeof s.__field=="object"&&s.__field!==null)o=jl(o,i,mx(n,s.__field));else throw new Error(`executePrismaPlan: no reference at the recorded location ${i.join(".")}`)}return o};var yx=e=>e?.map?{...e,map:Te(e.map,e.mapName,"toPrisma")}:e,li=(e,t)=>na(e,t,"toPrisma",hx),hx=(e,t)=>{let r={steps:[]},n=yx(t),o=pm(_l(e,n,r),n?.map,n?.model),i=(s,a)=>{let l=zu(a);return l.length?{...s,refs:l}:s};return {steps:[...r.steps.map(s=>i(s,s.args)),i({operation:"where",where:o},o)]}};var wx=/^-?\d+(\.\d+)?$/,gm=e=>typeof e=="string"?wx.test(e)?Number(e):e:typeof e=="object"&&e!==null&&typeof e.toNumber=="function"?e.toNumber():e,Vl=(e,t)=>e?.kind!=="scalar"||e.type!=="Decimal"?t:Array.isArray(t)?t.map(gm):gm(t);var ia=(e,t,r,n,o)=>{let i=`${r.mapName}\0${r.modelName}`;for(let a of t){if(typeof a=="boolean")continue;let l=e.memo?.compiles.get(a)??new Map;e.memo?.compiles.set(a,l);let p=l.get(i);if(p===void 0){let[d]=Tr(a,{target:"toPrisma",map:e.lens,mapName:r.mapName,model:r.modelName}).errors;p=d?d.message:null,l.set(i,p);}if(p!==null)return new T(`${n}: ${p}`,"unsupported_clamp")}if(o)return null;let s=false;for(let a of t)J(a,l=>{("aggregate"in l||Fo(l))&&(s=true);});return s?new T(`${n} needs a counting step (executePrismaPlan), which a relation's where in a select can't run`,"unsupported_clamp"):null},sa=(e,t)=>{try{return t()}catch(r){throw r instanceof T||r instanceof M?r:new T(`${e}: ${r.message}`,"unsupported_clamp")}};var ym=(e,t)=>e===""?t:t===""?e:`${e}.${t}`,Ve=e=>{let t=new Set,r=o=>{o&&t.add(o);},n=(o,i)=>{let s=He(o,i);return "outOfBounds"in s?null:ym(s.scope,s.path)};return J(e,(o,i)=>{if(Ke(o))return;for(let l of wr(o))r(L(l)?n(l,i):l);let s=typeof o.field=="string"&&o.field!==""?n(o.field,i):null;if(r(s),!xe(o))return;let a=s??i[i.length-1];for(let l of eo(o))r(ym(a,l));return [...i,a]},[""]),[...t]};var Il=(e,t,r,n,o)=>{let i={};for(let[s,a]of Object.entries(n.fields)){if(!_t(t,s))continue;let l=t.enumValuesByField.get(s),p=o(s)?.filter(f=>l===void 0||l.includes(f.value)),d=wo(e,t,r,s,"groupBy")?t.sourceGroupBys.get(s):void 0;i[s]={...a,...l!==void 0&&{values:l},...p!==void 0&&{options:p},...d!==void 0&&{groupBy:d}};}return i},hm=(e,t,r,n,o)=>{let{mapName:i,modelName:s}=t,a=C(E(e.lens.maps,i),s),l=Il(e,r,t,a,c=>{let y=o.get(`${n}|${c}`),m=r.enumValuesByField.get(c);return y??E(a.fields,c)?.options??m?.map(g=>({value:g,label:g}))}),p={};for(let[c,y]of r.sources)_t(r,c)&&(p[c]=y);let d={};for(let[c,y]of r.sourceLabels)_t(r,c)&&wo(e,r,t,c,"label")&&(d[c]=y);let f={};for(let[c,y]of r.sourceGroupBys)_t(r,c)&&wo(e,r,t,c,"groupBy")&&(f[c]=y);let u={};for(let c of r.sourcesFromMapDefaults.keys()){if(!Ks(e,i,s,c))throw Gs(n,i,s,c);Object.hasOwn(p,c)&&(u[c]="mapDefaults");}return {mapName:i,model:s,fields:l,whereClauses:r.whereClauses,sources:p,sourceLabels:d,sourceGroupBys:f,sourceFrom:u}},wm=e=>{let t=new Map;for(let r of e.sourceValues??[])t.set(`${r.path}|${r.field}`,r.options);return t},Sm=(e,t={})=>pi(F(e),t),pi=(e,t={})=>{let r=wm(t),n={};for(let{path:o,at:i,effect:s}of tr(e))n[o]=hm(e,i,s,o,r);return n},bm=(e,t,r={})=>ql(F(e),t,r),ql=(e,t,r={})=>{let n={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};if(t!=="")for(let s of Rr(e.lens.maps,n,t)){let a=I(e,s.at.mapName,s.at.modelName,s.at.relPath);if(!s.next||!a.relations.has(s.field))return null;n={...s.next,relPath:[...s.at.relPath,s.field]};}if(!C(E(e.lens.maps,n.mapName),n.modelName))return null;let o=I(e,n.mapName,n.modelName,n.relPath),i=[e.lens.model,...n.relPath].join(".");return hm(e,n,o,i,wm(r))};var aa=(e,t,r,n,o)=>{let i=e.split("."),{hops:s}=Ce(t,{mapName:r,modelName:n,relPath:[]},e),a=s.find((f,u)=>f.isList&&u<i.length-1);if(a)return `${o} cannot traverse to-many relation '${i[s.indexOf(a)]}'`;if(s.length===i.length)return `${o} must end on a scalar column, '${i.at(-1)}' is a relation`;let l=s.at(-1)??{map:r,model:n},p=i[s.length],d=ge(E(t,l.map),l.model,p);return d?_(d)?`${o} relation '${p}' has no resolvable target`:s.length===i.length-1?null:`${o} segment '${p}' is not a relation`:`${o} segment '${p}' not on model '${l.model}'`},Rm=(e,t,r,n,o,i,s,a)=>{let l=aa(o,e.lens.maps,t,r,i);if(l)throw new T(`${i} '${o}': ${l}`,"invalid_source");let{hops:p}=Ce(e.lens.maps,{mapName:t,modelName:r,relPath:n},o),d=p.slice(0,o.split(".").length-1);for(let f of d){let u=f.relPath.join(".");if(s.has(u))continue;s.add(u);let c=I(e,f.map,f.model,f.relPath);for(let y of c.whereClauses)a.push(mo(y,f.prefix));}},Sx=(e,t,r,n,o,i)=>{let s=[],a=new Set;for(let l of o)Rm(e,t,r,n,l,"groupBy",a,s);return i?.includes(".")&&Rm(e,t,r,n,i,"label",a,s),s},di=(e,t)=>{let r=he(e,t);return r==null||typeof r=="object"?void 0:String(r)},la=(e,t)=>{let r=[];for(let n of t){let o=di(e,n);if(o===void 0)return;r.push(o);}return r},Bl=(e,t)=>JSON.stringify([e??null,t]),bx=(e,t,r,n)=>{let o=Bl(n,t),i=e.get(o);i===void 0?e.set(o,{value:t,...r!==void 0?{label:r}:{},...n!==void 0?{groups:n}:{}}):r!==void 0&&(i.label===void 0||r<i.label)&&e.set(o,{...i,label:r});},pa=(e,t,r,n,o)=>{let i=he(t,r),s=n==null?void 0:String(n);for(let a of Array.isArray(i)?i:[i])a==null||typeof a=="object"||bx(e,String(a),s,o);},da=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??[],i=r.groups??[];for(let s=0;s<Math.max(o.length,i.length);s++){let a=(o[s]??"").localeCompare(i[s]??"","en",{numeric:true});if(a!==0)return a}return (t.label??t.value).localeCompare(r.label??r.value,"en",{numeric:true})||t.value.localeCompare(r.value,"en",{numeric:true})}),Rx=(e,t,r,n,o)=>{let{hops:i}=se(o,t,n),s=o.split("."),a=i.at(-1)?.entry.type??n,l=s[i.length];for(let{endpoints:p}of e.bridges??[]){let[d,f]=p;for(let[u,c]of [[d,f],[f,d]])if(u.fieldMap===r&&u.model===a&&De(c)===l)return [...s.slice(0,i.length),u.on].join(".")}throw new T(`'${o}' crosses no bridge the lens declares on ${a}`,"not_in_lens")},fa=(e,t,r,n)=>{let o=Te(e,t,"toPrisma");return [...new Set(n.map(i=>Er(i,o,r)?Rx(e,o,t,r,i):i))]},Ox=(e,t,r,n)=>{if(t.length===0)return [];let o={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]},{hops:i,end:s}=Ce(e.lens.maps,o,t.join("."));if(!s)throw new T(`source at '${t.join(".")}': its path doesn't resolve on the field maps`,"not_in_lens");let a=[o,...i.map(d=>({mapName:d.map,modelName:d.model}))],l=t.length;for(;l>0&&!r.has(t.slice(0,l).join("."));)l--;let p=l>0?r.get(t.slice(0,l).join("."))??null:null;for(let d=l;d<t.length;d++){let f=$=>{p=$,r.set(t.slice(0,d+1).join("."),$);},u=a[d],c=I(e,u.mapName,u.modelName,t.slice(0,d)).whereClauses,y=p===null?c:[...c,p];if(y.length===0&&!n){f(null);continue}let m=E(e.lens.maps,u.mapName),g=m&&ge(m,u.modelName,t[d]);if(!g)throw new T(`source at '${t.join(".")}': '${t[d]}' isn't declared on ${u.modelName}`,"not_in_lens");let S=a[d+1],b=De({fieldMap:u.mapName,model:u.modelName}),w=g.kind==="bridge"?ge(E(e.lens.maps,S.mapName),S.modelName,b):void 0,R=g.kind==="bridge"?w&&{field:b,entry:w}:m?Vs(m,u.modelName,t[d],g):null;if(!R&&y.length===0){f(null);continue}if(!R)throw new T(`source at '${t.join(".")}': '${t[d]}' on ${u.modelName} declares no inverse, so the clamps above can't be carried down to it`,"unsupported_clamp");let O=K(y);try{let $={field:R.field,operator:"exists"};f(R.entry.isList?{field:R.field,arrayOperator:"any",condition:O}:y.length?K([$,mo(O,R.field)]):$);}catch($){throw $ instanceof T?new T(`source at '${t.join(".")}': the clamps above can't be carried down to it \u2014 ${$.message}`,$.code):$}}return p===null?[]:[p]},Om=e=>Cr(F(e)),Cr=(e,t=pi(e))=>{let r=new Map,n=o=>{let i=r.get(o)??new Map;return r.set(o,i),i};return Object.entries(t).flatMap(([o,i])=>Object.keys(i.sources).map(s=>{let a=E(i.sourceLabels,s),l=E(i.sourceGroupBys,s),p=Object.hasOwn(i.sourceFrom,s),d={mapName:i.mapName,modelName:i.model,relPath:o.split(".").slice(1)},f=I(e,d.mapName,d.modelName,d.relPath),u=(f.sourceWheres.get(s)??[]).map(P=>tn(P,e,d)),c=Sx(e,d.mapName,d.modelName,d.relPath,l??[],a),y=E(i.fields,s)?.values,m=p?f.sourcesFromMapDefaults.get(s):void 0,g=m===void 0?void 0:e.chain[m],b=[...Ox(g===void 0?e:{...e,skipClampsOf:g},d.relPath,n(g),g===void 0&&!p),...u,...c,...y?[{field:s,operator:"in",value:[...y]}]:[]],w=K([...i.whereClauses,...b]),R=K([...i.whereClauses,...u,...c,...y?[{field:s,operator:"in",value:[...y]}]:[]]),O=e.lens.bridges?.length?Te(e.lens,d.mapName,"toPrisma"):void 0,$=O?[...Ve(w),...a===void 0?[]:[a],...l??[]].find(P=>Er(P,O,d.modelName)):void 0,k=$!==void 0&&O?K(Ka(w).filter(P=>kt(P,O,d.modelName))):void 0,le=ia(e,[...i.whereClauses,...b],d,`source '${s}' at '${o}'`,true);if(le)throw le;return {path:o,visit:i,field:s,...p&&{from:"mapDefaults"},...a!==void 0&&{label:a},...l!==void 0&&{groupBy:l},where:w,rowWhere:R,...$!==void 0&&{bridged:$},...k!==void 0&&{recheck:k}}}))};var Kl=(e,t)=>{for(let r of t){let n=e;for(let o of r.split("."))n=er(n,o,()=>({}));}return e},ua=(e,t)=>{for(let[r,n]of Object.entries(t))ua(er(e,r,()=>({})),n);return e},Gl=e=>e.whereClauses.flatMap(Ve),Em=(e,t)=>{let r=new Map;for(let n of t){if(n.from)continue;let o=n.path.split(".").slice(1).join("."),i=[n.field,...n.label===void 0?[]:[n.label],...n.groupBy??[],...Ve(n.rowWhere)];r.set(o,[...r.get(o)??[],...n.bridged===void 0?i:fa(e.lens,n.visit.mapName,n.visit.model,i)]);}return r},xm=(e,t)=>e.get(t.relPath.join("."))??[],Ex=(e,t,r)=>Kl(ua({},r??{}),Gl(I(e,t.mapName,t.modelName,t.relPath))),$m=e=>({mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]}),zl=(e,t,r)=>({...r,relPath:[...e.relPath,t]}),xx=(e,t,r,n)=>{if(!r.whereClauses.length)return;let o=K(r.whereClauses),i=ia(e,r.whereClauses,t,`toLensSelect: the clamp on '${t.relPath.join(".")}'`,false);if(i)throw i;if(e.inspect)return;let s=sa(`toLensSelect: the clamp on '${t.relPath.join(".")}'`,()=>li(o,{...n,map:e.lens,mapName:t.mapName,model:t.modelName})),{where:a}=s.steps[0];return Object.keys(a).length?a:void 0},$x=(e,t,r,n)=>{let o=C(e,n.type)?.fields??{},i=a=>{let l=a===void 0?void 0:E(o,a);return l&&!_(l)?a:void 0},s=e?Vs(e,t,r,n):null;return i(n.toFields?.[0])??i(s?.entry.fromFields?.[0])??i("id")},vm=(e,t,r,n,o,i)=>{let s=C(E(e.lens.maps,t.mapName),t.modelName)?.fields??{},a=I(e,t.mapName,t.modelName,t.relPath),l=r==="paths"?n:Kl(ua({},n),[...Gl(a),...xm(i,t)]),p={};for(let[d,f]of Object.entries(s)){let u=r!=="paths"&&_t(a,d),c=E(l,d);if(!u&&c===void 0||f.kind==="bridge")continue;if(f.kind!=="object"){p[d]=true;continue}let y=u?"declared":"paths";if(y==="paths"&&c===void 0)continue;let m=zl(t,d,{mapName:t.mapName,modelName:f.type}),g=vm(e,m,y,c??{},o,i),S=f.isList&&y!=="paths"&&c===void 0?xx(e,m,I(e,m.mapName,m.modelName,m.relPath),o):void 0,b=Object.keys(g).length?void 0:$x(E(e.lens.maps,t.mapName),t.modelName,d,f),w=b===void 0?g:{[b]:true};Object.keys(w).length&&(p[d]={select:w,...S&&{where:S}});}return p},Am=(e,t={})=>Hl(F(e),t),Hl=(e,t={},r=Cr(e))=>{let n=vm(e,$m(e),"declared",{},t,Em(e,r));if(!Object.values(n).some(o=>o===true)){let o=E(C(E(e.lens.maps,e.lens.mapName),e.lens.model)?.fields,"id");o&&!_(o)&&(n.id=true);}return {select:n}},Wl=(e,t)=>e==null?e:Array.isArray(e)?e.flatMap(r=>{let n=typeof r=="object"&&r!==null?t(r):null;return n===null?[]:[n]}):typeof e=="object"?t(e):null,Ul=(e,t,r,n)=>{let o={},i=C(E(e.lens.maps,t.mapName),t.modelName);for(let[s,a]of Object.entries(n)){if(!Object.hasOwn(r,s))continue;let l=E(i?.fields,s),p=l?lt(l,t.mapName):null;o[s]=p?Wl(r[s],d=>Ul(e,zl(t,s,p),d,a)):Vl(l,r[s]);}return o},Nm=(e,t,r,n,o,i,s)=>{let a=I(e,t.mapName,t.modelName,t.relPath);if(!a.whereClauses.every(f=>Se(f,r,i)===true))return null;let l=C(E(e.lens.maps,t.mapName),t.modelName)?.fields??{},p=o?Kl(ua({},n),[...Gl(a),...xm(s,t)]):{},d={};for(let[f,u]of Object.entries(l)){if(!Object.hasOwn(r,f))continue;let c=E(p,f),y=lt(u,t.mapName);if(!y){(_t(a,f)||c!==void 0)&&(d[f]=Vl(u,r[f]));continue}let m=zl(t,f,y);if(_t(a,f)){let g=!Array.isArray(r[f])||c!==void 0;d[f]=Wl(r[f],S=>Nm(e,m,S,c??{},o,i,s)??(o&&g?Ul(e,m,S,Ex(e,m,c)):null));}else c!==void 0&&(d[f]=Wl(r[f],g=>Ul(e,m,g,c)));}return d},Pm=(e,t,{keepClampColumns:r=false,...n}={})=>{let o=F(e),i=$m(o),s=r?Em(o,Cr(o)):new Map;return t.flatMap(a=>{let l=Nm(o,i,a,{},r,n,s);return l===null?[]:[l]})};var vx="materializeSources needs fetched or keepClampColumns rows, not viewer rows",Jl=(e,t,r)=>new M(`${e}: a row at '${t}' ${r}${r.includes(":")?" \u2014 rows across a bridge hold the far side inline under its bridge field":""}`),fi=(e,t,r,n,o,i=vx)=>{for(let s of o){let a=[r];for(let{index:l,field:p,entry:d,next:f}of Rr(e.lens.maps,t,s)){if(!d)break;let u=s.split(".").slice(0,l+1).join("."),c=[];for(let y of a){if(y===null||typeof y!="object")continue;if(!Object.hasOwn(y,p))throw Jl(i,n,`lacks '${u}', which a read needs`);let m=y[p];if(f&&m==null&&d.fromFields?.some(g=>{let S=y[g];return S!=null}))throw Jl(i,n,`'${u}' is null while its key is set \u2014 a projection hid the row`);if(!(!f||m===null||m===void 0)){if(Array.isArray(m)!==(d.isList===true))throw Jl(i,n,`'${u}' holds ${Array.isArray(m)?"a list where it names one row":"one row where it names a list"}`);c.push(...Array.isArray(m)?m:[m]);}}if(!f)break;a=c;}}},Ql=(e,t)=>{let r={mapName:e.lens.mapName,modelName:e.lens.model,relPath:[]};return [r,...Ce(e.lens.maps,r,t.split(".").slice(1).join(".")).hops.map(n=>({mapName:n.map,modelName:n.model,relPath:n.relPath}))]},Ax=(e,t,r,n)=>{let o=r.split(".").slice(1),i=Ql(e,r),s=(l,p)=>{let d=i[l],f=I(e,d.mapName,d.modelName,d.relPath).whereClauses,u=K(f),c=f.flatMap(Ve),y=[e.lens.model,...o.slice(0,l)].join(".");return p.filter(m=>(fi(e,d,m,y,c),Se(u,m,n)===true))},a=s(0,t);for(let[l,p]of o.entries()){let d=[],f=[e.lens.model,...o.slice(0,l)].join(".");for(let u of a){fi(e,i[l],u,f,[p]);let c=he(u,p);Array.isArray(c)?d.push(...c):c!=null&&d.push(c);}a=s(l+1,d);}return {rows:a,visit:i[i.length-1]}},km=(e,t,r)=>{let n=F(e);return Cr(n).map(({path:o,visit:i,field:s,from:a,label:l,groupBy:p,rowWhere:d})=>{if(a)throw new M(`materializeSources: '${o}.${s}' offers its model's own source, which a fetched collection can't hold \u2014 query it with toSourceQueries and materializeSourceQuery.`);let f=[s,...Ve(d),...l===void 0?[]:[l],...p??[]],u=new Map,c=Ax(n,t,o,r);for(let y of c.rows)fi(n,c.visit,y,o,f),Se(d,y,r)===true&&pa(u,y,s,l===void 0?void 0:di(y,l),p===void 0?void 0:la(y,p));return {path:o,mapName:i.mapName,model:i.model,field:s,options:da(u)}})};var ca={value:"value",query:"query"},Tm=(e,t,r={})=>{let{rowShape:n="prisma",lens:o,order:i=ca.value,...s}=r,a=n==="sql",{recheck:l}=e,p=y=>false,d=y=>true;if(l!==void 0){if(o===void 0)throw new M(`materializeSourceQuery: '${e.path}.${e.field}' reads across a bridge \u2014 its rows are candidates; pass { lens } with rows holding the far side`);let y=F(o),m=Ql(y,e.path).at(-1);if(!m||m.mapName!==e.mapName||m.modelName!==e.model)throw new M(`materializeSourceQuery: the lens doesn't reach ${e.mapName}:${e.model} at '${e.path}' \u2014 pass the lens the query was compiled from`);let g=Te(y.lens,e.mapName,"toPrisma");p=w=>g!==void 0&&Er(w,g,e.model);let S=[...Ve(l),...e.label!==void 0&&p(e.label)?[e.label]:[],...(e.groupBy??[]).filter(p)],b="materializeSourceQuery needs candidate rows holding the far side of each bridge the source reads";d=w=>(fi(y,m,w,e.path,S,b),Se(l,w,s)===true);}let f=y=>e.label===void 0?void 0:a&&e.label.includes(".")&&!p(e.label)?y.__label:di(y,e.label),u=e.groupBy?.map((y,m)=>a&&!p(y)?`__group_${m}`:y),c=new Map;for(let y of t)d(y)&&pa(c,y,e.field,f(y),u===void 0?void 0:la(y,u));return {path:e.path,mapName:e.mapName,model:e.model,field:e.field,options:i===ca.query?[...c.values()]:da(c)}};var Nx=(e,t)=>`${e}::${t}`,Px=(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 i=new Set([...n.values,...r.values]);o={...o,values:[...i]};}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);},Cm=(e,t={})=>Zl(F(e),t),Zl=(e,t={})=>{let{lens:r}=e,n=new Map;for(let l of t.sourceValues??[]){let p=`${l.mapName}::${l.model}::${l.field}`,d=n.get(p)??new Map;for(let f of l.options)d.set(Bl(f.groups,f.value),f);n.set(p,d);}let o=new Map;for(let{at:l,effect:p}of tr(e)){let{mapName:d,modelName:f}=l,u=C(E(r.maps,d),f);if(!u)continue;let c=Nx(d,f),y=o.get(c);y||(y={mapName:d,modelName:f,fields:new Map},o.set(c,y));let m=Il(e,p,l,u,g=>{let S=n.get(`${d}::${f}::${g}`);return S&&[...S.values()]});for(let[g,S]of Object.entries(m)){let b=S.groupBy,w=y.fields.get(g)?.groupBy;if(b!==void 0&&w!==void 0&&JSON.stringify(w)!==JSON.stringify(b))throw new T(`projectLens: '${f}.${g}' is grouped by different axes on different paths ([${w}] vs [${b}]) \u2014 one surface field cannot carry two partition namespaces`,"invalid_source");Px(y.fields,g,S);}}let i={};for(let{mapName:l,modelName:p,fields:d}of o.values()){let f=E(i,l);f||(f={models:{}},i[l]=f);let u={},c=new Map;for(let[y,m]of d)if(u[y]=m.options===void 0&&m.values?{...m,options:m.values.map(g=>({value:g,label:g}))}:m,m.kind==="enum"&&m.values){let g=c.get(m.type)??new Set;for(let S of m.values)g.add(S);c.set(m.type,g);}f.models[p]={...C(E(r.maps,l),p),fields:u};for(let[y,m]of c)f.enums??={},f.enums[y]=[...m];}let s=r.bridges?.filter(l=>{let[p,d]=l.endpoints,f=ge(E(i,p.fieldMap),p.model,De(d)),u=ge(E(i,d.fieldMap),d.model,De(p));return f!==void 0||u!==void 0}),a={maps:i};return s&&s.length>0&&(a.bridges=s),{...a,mapName:r.mapName,model:r.model}};var Lm=(e,t,r,n,o)=>{if(e===void 0)return;let i=co(e),s=n==="root.where"?null:i.bare;if(s!==null){o.push({path:n,code:"invalid_value_source",message:Ol(s).message});return}let{escaping:a}=i;if(a!==null){o.push({path:n,code:"scope_out_of_bounds",message:El(a).message});return}let l=new Set,p={...t,clamp:t.chain.length===0};for(let{mapName:d,modelName:f,relPath:u}of r)for(let c of Xo(e,p,d,f,u)){let y=`'${c.path}' ${c.message}`;l.has(y)||(l.add(y),o.push({path:n,code:c.code,message:y}));}},kx=(e,t,r,n,o,i)=>{let s={...r,chain:[...r.chain,t]},a=new Set;for(let l of n){let p=I(s,l.mapName,l.modelName,l.relPath);for(let[d,f]of Object.entries(e.sources??{})){let u=kr(f);for(let c of ["label","groupBy"]){if(u[c]===void 0||a.has(`${d}|${c}`))continue;let y=c==="label"?u.label:ri(u.groupBy),m=c==="label"?p.sourceLabels.get(d):p.sourceGroupBys.get(d);if(JSON.stringify(y)!==JSON.stringify(m))continue;let S=(typeof m=="string"?[m]:m??[]).map(b=>oi(s,l,b)).find(b=>b!==null);if(S){a.add(`${d}|${c}`),i.push({path:`${o}.sources.${d}`,code:"invalid_source",message:`${c} '${String(u[c])}' crosses '${S}', a relation the lens does not show there (not turned on, or omitted)`});continue}wo(s,p,l,d,c)||(a.add(`${d}|${c}`),i.push({path:`${o}.sources.${d}`,code:"invalid_source",message:`${c} '${String(u[c])}' reads a column hidden by another layer`}));}}}},Tx=(e,t,r,n)=>{for(let o of r){if(!t&&o.picks&&!o.picks.includes(e))return "not in ancestor's picks";if(o.omits?.includes(e))return "was omitted by ancestor"}return !t&&n?.picks&&!n.picks.includes(e)?"not visible from defaults.picks":n?.omits?.includes(e)?"already excluded by defaults":null},Cx=(e,t,r,n,o,i,s,a,l,p,d,f,u=false)=>{let c=e.omits?.some(m=>{let g=E(i,m);return g===void 0||!_(g)});e.picks&&c&&p.push({path:`${l}`,code:"conflicting_selection",message:"cannot specify both picks and omits of a column"});for(let m of ["picks","omits"])for(let g of e[m]??[]){let S=E(i,g);if(!S){p.push({path:`${l}.${m}`,code:"not_in_lens",message:`field '${g}' not on model`});continue}let b=_(S);if(b&&m==="picks"){p.push({path:`${l}.picks`,code:"wrong_kind",message:`'${g}' is a relation: picks names columns; turn a relation on with \`relations\``});continue}let w=Tx(g,b,t,r);w&&p.push({path:`${l}.${m}`,code:"not_visible",message:`'${g}' ${w}`});}let y=(m,g,S)=>{let b=E(i,g);if(!b){p.push({path:`${l}.${m}`,code:"not_in_lens",message:`field '${g}' not on model`});return}if(b.kind!=="enum"){p.push({path:`${l}.${m}`,code:"wrong_kind",message:`field '${g}' is not an enum field`});return}let w=Jr(b,a);for(let R of S)w&&!w.includes(R)&&p.push({path:`${l}.${m}.${g}`,code:"value_not_allowed",message:`'${R}' is not a known value of enum '${b.type}'`});};for(let[m,g]of Object.entries(e.enumPicks??{}))y("enumPicks",m,g);for(let[m,g]of Object.entries(e.enumOmits??{}))y("enumOmits",m,g);Lm(e.where,d,f,`${l}.where`,p);for(let[m,g]of Object.entries(e.sources??{})){let S=E(i,m);if(!S){p.push({path:`${l}.sources`,code:"not_in_lens",message:`field '${m}' not on model`});continue}if(_(S)){p.push({path:`${l}.sources.${m}`,code:"wrong_kind",message:`'${m}' is a relation: a source offers a column's values`});continue}let b;try{b=kr(g);}catch($){if(!($ instanceof T))throw $;p.push({path:`${l}.sources.${m}`,code:$.code,message:$.message});continue}let w=b.from;if(w!==void 0){let $=w!=="mapDefaults"?`from takes 'mapDefaults', not '${String(w)}'`:u?"a mapDefaults source is what a path source's from: 'mapDefaults' points at; it can't point itself":b.label!==void 0||b.groupBy!==void 0?"a from: 'mapDefaults' source takes the model source's label and groupBy":null;$&&p.push({path:`${l}.sources.${m}`,code:"invalid_source",message:$});}let R=b.label?.includes(".")?b.label:void 0;if(b.label!==void 0)if(R){let $=aa(R,n,o,s,"label");$&&p.push({path:`${l}.sources.${m}`,code:"invalid_source",message:`${$}`});}else {let $=E(i,b.label);$?_($)&&p.push({path:`${l}.sources.${m}`,code:"wrong_kind",message:`label '${b.label}' is a relation, not a column`}):p.push({path:`${l}.sources.${m}`,code:"not_in_lens",message:`label column '${b.label}' not on model`});}let O=ri(b.groupBy);if(O!==void 0||R!==void 0){let $=/^__(group(_\d+)?|label)$/;($.test(m)||b.label!==void 0&&$.test(b.label))&&p.push({path:`${l}.sources.${m}`,code:"invalid_source",message:"'__group*' / '__label' names are reserved on grouped or path-labeled sources (sql column aliases)"});}if(O!==void 0){for(let k of O){let le=aa(k,n,o,s,"groupBy");le&&p.push({path:`${l}.sources.${m}`,code:"invalid_source",message:`${le}`});}let $=JSON.stringify(O);for(let k of t){let le=E(k.sources,m);if(le===void 0)continue;let P=ri(kr(le).groupBy);P!==void 0&&JSON.stringify(P)!==$&&p.push({path:`${l}.sources.${m}`,code:"not_visible",message:`groupBy [${O}] conflicts with an ancestor layer's groupBy [${P}]`});}}Lm(b.where,d,f,`${l}.sources.${m}`,p);}},Lx=(e,t,r,n,o)=>{for(let[i,s]of Object.entries(t)){let a=E(r,i);if(!a){o.push({path:`mapDefaults.${e}.enums.${i}`,code:"not_in_lens",message:"enum not in registry"});continue}let l=null,p=new Set;for(let f of n){let u=f[i];if(u&&(u.picks&&(l=Us(l,u.picks)),u.omits))for(let c of u.omits)p.add(c);}let d=f=>!(p.has(f)||l&&!l.has(f));for(let f of s.picks??[])a.includes(f)?d(f)||o.push({path:`mapDefaults.${e}.enums.${i}.picks`,code:"not_visible",message:`'${f}' not visible from ancestors`}):o.push({path:`mapDefaults.${e}.enums.${i}.picks`,code:"value_not_allowed",message:`'${f}' not a known value`});for(let f of s.omits??[])a.includes(f)?d(f)||o.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"not_visible",message:`'${f}' already excluded by ancestors`}):o.push({path:`mapDefaults.${e}.enums.${i}.omits`,code:"value_not_allowed",message:`'${f}' not a known value`});}},Mx=(e,t,r,n,o,i,s)=>{let a=I(t,r.mapName,r.modelName,r.relPath);for(let l of ["enumPicks","enumOmits"])for(let[p,d]of Object.entries(e[l]??{})){let f=E(n,p);if(f?.kind!=="enum")continue;let u=Jr(f,o)??[],c=Bs(a,p)??u;for(let y of d)u.includes(y)&&!c.includes(y)&&s.push({path:`${i}.${l}.${p}`,code:"not_visible",message:`'${y}' is not visible (not allowed by the inherited enum narrowing)`});}},Mm=(e,t,r,n)=>e.map(o=>({mapName:n,modelName:r,relPath:[...o.relPath,t]})),Yl=(e,t,r,n,o,i,s,a,l,p,d)=>{let f=E(o,i),u=C(f,s);if(!u)return;let c=n.length===0,y={...p,chain:[...p.chain,r],unvetted:true},m=d.isDefault?void 0:E(E(r.mapDefaults,i)?.models,s),S=[...n.map(R=>E(E(R.mapDefaults,i)?.models,s)).filter(R=>R!==void 0),...t],b={mapName:i,modelName:s,relPath:Rl};Cx(e,S,m,o,i,u.fields,s,f?.enums,a,l,p,c?d.isDefault?[b,...d.parent]:d.parent:d.composed,d.isDefault),Mx(e,d.isDefault?p:{...p,chain:[...p.chain,{parent:r.parent,mapDefaults:r.mapDefaults}],unvetted:true},d.isDefault?b:d.parent[0]??b,u.fields,f?.enums,a,l),kx(e,r,p,d.composed,a,l);let w={...p,chain:[...p.chain,r]};if(!d.isDefault)for(let[R,O]of Object.entries(e.sources??{}))!ni(O)||O.from!=="mapDefaults"||Ks(w,i,s,R)||l.push({path:`${a}.sources.${R}`,code:"invalid_source",message:Gs([ft(r).model,...d.parent[0]?.relPath??[]].join("."),i,s,R).message});for(let[R,O]of Object.entries(e.relations??{})){let $=E(u.fields,R);if(!$){l.push({path:`${a}.relations`,code:"not_in_lens",message:`'${R}' not on model`});continue}if(!_($)){l.push({path:`${a}.relations`,code:"wrong_kind",message:`'${R}' is not a relation (kind=${$.kind})`});continue}let k=W=>I(p,W.mapName,W.modelName,W.relPath).relations.has(R),le=W=>I(y,W.mapName,W.modelName,W.relPath).relations.has(R);if(!c&&!(d.isDefault?d.parent.some(k):d.parent.every(k))){l.push({path:`${a}.relations`,code:"not_visible",message:`'${R}' is not shown by the parent${d.isDefault?` wherever ${s} is visited`:""}: only the first narrowing over the base lens turns a relation on`});continue}let P=lt($,i);if(!P)continue;if(!C(E(o,P.mapName),P.modelName)){l.push({path:`${a}.relations.${R}`,code:"not_in_lens",message:"target model not found in lens"});continue}let q=t.map(W=>E(W.relations,R)).filter(W=>W!==void 0);Yl(O,q,r,n,o,P.mapName,P.modelName,`${a}.relations.${R}`,l,p,{parent:Mm(d.isDefault?d.parent.filter(k):d.parent,R,P.modelName,P.mapName),composed:Mm(d.composed.filter(le),R,P.modelName,P.mapName),isDefault:d.isDefault});}},Xl=e=>{let t=[];try{_x(e,t);}catch(r){if(!(r instanceof T))throw r;t.some(n=>n.code===r.code)||t.push({path:"",code:r.code,message:r.message});}return rt(t)},_x=(e,t)=>{let r=ft(e),n=Lt(e.parent),o=F(e.parent),i=tr(o),s=[],a=u=>{try{u();}catch(c){if(!(c instanceof T))throw c;s.push(c);}},l=null,p=()=>(l??=tr({...o,chain:[...o.chain,e],unvetted:true}),l);for(let[u,c]of Object.entries(e.mapDefaults??{})){let y=E(r.maps,u);if(!y){t.push({path:`mapDefaults.${u}`,code:"not_in_lens",message:"not in lens"});continue}let m=n.map(g=>E(g.mapDefaults,u)?.enums).filter(g=>g!==void 0);for(let[g,S]of Object.entries(c.models??{})){if(!C(y,g)){t.push({path:`mapDefaults.${u}.models.${g}`,code:"not_in_lens",message:"not in fieldMap"});continue}let w=n.map($=>E(E($.mapDefaults,u)?.models,g)).filter($=>$!==void 0),R=$=>$.map(({at:k})=>k).filter(k=>k.mapName===u&&k.modelName===g),O=[];a(()=>{O=R(p());}),a(()=>Yl(S,w,e,n,r.maps,u,g,`mapDefaults.${u}.models.${g}`,t,o,{parent:R(i),composed:O,isDefault:!0}));}c.enums&&Lx(u,c.enums,y.enums,m,t);}if(e.root){let u=r.mapName,c=r.model,y=E(r.maps,u);if(!y)t.push({path:"root",code:"not_in_lens",message:`lens map '${u}' not in lens`});else if(!C(y,c))t.push({path:"root",code:"not_in_lens",message:`lens model '${c}' not in fieldMap`});else {let m=n.map(S=>S.root).filter(S=>S!==void 0),g={mapName:u,modelName:c,relPath:[]};a(()=>Yl(e.root,m,e,n,r.maps,u,c,"root",t,o,{parent:[g],composed:[g],isDefault:!1}));}}for(let u of zc(e))t.push({path:"bindings",code:"invalid_binding",message:u});let d={...o,chain:[...o.chain,e],inspect:true},f;a(()=>{f=Cr(d,pi(d));}),a(()=>Zl(d)),a(()=>Hl(d,{},f)),a(()=>{let u=new Map;for(let{at:c}of p()){u.set(c.relPath.join("."),c),a(()=>ql(d,c.relPath.join(".")));let y=c.relPath.at(-1),m=u.get(c.relPath.slice(0,-1).join("."));if(y===void 0||!m)continue;let S=ge(E(r.maps,m.mapName),m.modelName,y)?.isList?{field:y,arrayOperator:"any",condition:!0}:{field:y,operator:"exists"};a(()=>tn(S,d,m));}});for(let u of s)t.some(c=>u.message.includes(c.message))||t.push({path:"",code:u.code,message:u.message});},ma=e=>sn(Xl(e),"validateNarrowing");function _m(e,{by:t="path",...r}={}){return t==="model"?Cm(e,r):Sm(e,r)}var Dm=(e,t,r,n={})=>{let o=F(e),{resolution:i}=rn(o,Mt(o),r);if(i.outcome!=="resolved")return {ok:false,reason:i.outcome};let{hops:s,terminal:a,jsonSubPath:l}=i;if(_(a.entry))return {ok:false,reason:"relation"};if(s.some(f=>f!==a&&f.entry.isList))return {ok:false,reason:"list"};let p=(f,u)=>u!==null&&typeof u=="object"&&I(o,f.mapName,f.model,f.relPath).whereClauses.every(c=>Se(c,u,n)===true),d=p(s[0],t)?t:null;for(let[f,u]of s.entries()){if(d===null||typeof d!="object")return {ok:true,value:null};let c=E(d,u.field);if(u===a)return {ok:true,value:l.length?he(c,l.join(".")):c};d=p(s[f+1],c)?c:null;}return {ok:true,value:null}};var Dx=e=>"maps"in e,Fm=(e,t)=>{let r=i=>{let s=E(t,i);if(!s)throw new Error(`composeLens: no stored lens '${i}'`);return s},n=[...r(e).parents,e];if(new Set(n).size!==n.length)throw new Error(`composeLens: '${e}' lists a layer twice in its parents`);let o=null;for(let[i,s]of n.entries()){let a=r(s);if(Object.hasOwn(a,"parent"))throw new Error(`composeLens: '${s}' carries a parent; a layer composes only through \`parents\``);let{id:l,parents:p,...d}=a;if(p.join("\0")!==n.slice(0,i).join("\0"))throw new Error(`composeLens: '${s}' composes with [${p.join(", ")}], not [${n.slice(0,i).join(", ")}] as '${e}' lists`);if(Dx(a)!==(i===0))throw new Error(i===0?`composeLens: '${s}' is not a base lens, so it can't head '${e}''s parents`:`composeLens: '${s}' is a base lens, so it can only head a chain`);if(o===null){o=d;continue}let u={parent:o,...d};ma(u),o=u;}return o},jm=(e,t)=>{let r=dt(e)?[]:Lt(e);if(t.length!==r.length+1)throw new Error(`storeLens: the lens has ${r.length+1} layers, base included, but ${t.length} ids`);return [{...ft(e),id:t[0],parents:[]},...r.map(({parent:n,...o},i)=>({...o,id:t[i+1],parents:t.slice(0,i+1)}))]};var Vm=e=>e instanceof Date?e.toISOString():Array.isArray(e)&&e.some(t=>t instanceof Date)?e.map(Vm):e,j=(e,t)=>(e.params.push(Vm(t)),`$${++e.paramIndex}`);var nr=(e,t,{jsonb:r=false}={})=>{let n=()=>({sql:sl(e,void 0,r),shape:e.includes(".")?"json-path":"unknown"});if(!t.map||!t.currentModel||!t.currentAlias)return n();let o=se(e,t.map,t.currentModel);if(o.kind==="past-scalar")throw Hn(e,o.column);if(o.kind==="bridge")throw new Error(`'${e}' crosses a bridge to another source; toSql() has no column for it`);if(o.kind==="fallback"||o.entry.kind==="object"&&o.entry.isList)return n();let i=o.hops.find(d=>d.entry.isList);if(i)throw zn(e,i);let s=t.currentAlias;for(let d of o.hops){let f=Im(t,s,d);if(!f)return n();s=f;}let a=Qr(o);if(o.kind==="direct"&&o.entry.kind==="object"){let d={field:o.column,entry:o.entry,from:o.model},f=Nr(t.map,o.model,o.entry),u=Im(t,s,d);return !f||!u?n():{sql:`${ae(u)}.${ae(f[0].there)}`,shape:a}}let l=o.kind==="json-path"?[o.column,...o.jsonPath]:[o.column],p=sl(l.join("."),s,r);return {sql:a==="json"&&!r?`NULLIF(${p}, 'null'::jsonb)`:p,shape:a}},Dt=(e,t,r)=>nr(e,t,r).sql,Im=(e,t,r)=>{let n=`${t}.${r.field}`,o=e.joinRegistry?.get(n);if(o)return o;if(!e.joinCounter||!e.map)return null;let i=`t${e.joinCounter.n+1}`,s=Fx(e.map,r.from,t,r.entry,i);return s?(e.joinCounter.n+=1,e.joins?.push(s),e.joinRegistry?.set(n,i),i):null},Fx=(e,t,r,n,o)=>{let i=n.type,s=C(e,i)?.dbName??i,a=Nr(e,t,n);if(!a)return null;let l=a.map(({here:p,there:d})=>`${ae(o)}.${ae(d)} = ${ae(r)}.${ae(p)}`).join(" AND ");return `LEFT JOIN ${ae(s)} AS ${ae(o)} ON ${l}`};var or={type:"value",value:null},Ft=e=>e.type==="value"&&(e.value===null||e.value===void 0),jx=(e,t)=>{let r=L(e)??{depth:1,path:e};if(r.depth>1)throw new Error(vo(e,"toSql"));let n=nr(r.path,t);if(n.shape==="relation")throw new Error(`'${e}' is a relation; a value ref reads a column`);return {type:"column",...n}},ve=(e,t)=>Yn(e,{value:r=>({type:"value",value:r}),path:r=>jx(r,t),bind:(r,n)=>({type:"value",value:hs(r,n,"toSql")})}),ln=e=>t=>{let r=ve(t,e);if(r.type==="column")throw new Error(`'${t.path}' is a row ref`);return r.value},mt=e=>Zt(e.dateConfig??{},ln(e));var Vx={lt:"<",lte:"<=",gt:">",gte:">=",equals:"="},So=(e,t)=>{let r=ur(e,t);return r?{symbol:Vx[r],negated:B.includes(e)}:void 0},qm=(e,t)=>e.type==="column"?e.sql:j(t,e.value),Ie=(e,t)=>`(${t} OR ${e} IS NULL)`,jt=(e,t,r=true)=>t&&r?`${e} IS NULL`:"FALSE",ga=(e,t,r,n,o)=>{if(Ft(r))return jt(e,n);let i=`${e} ${t} ${qm(r,o)}`;return n?Ie(e,i):i},ui=(e,t,r,n,o=true)=>{if(!t||t.some(Ft))return jt(e,r,o);let[i,s]=t.map(f=>qm(f,n)),a=t.some(f=>f.type==="column"),l=a?"SYMMETRIC ":"";if(!r)return `${e} BETWEEN ${l}${i} AND ${s}`;let p=`${e} NOT BETWEEN ${l}${i} AND ${s}`,d=a?`(${p} AND ${i} IS NOT NULL AND ${s} IS NOT NULL)`:p;return o?Ie(e,d):d};var Um=()=>{let e=nt.get("sql.dialect");if(!Mf(e))throw new M(`toWhereSql: sql.dialect '${String(e)}' is not a SQL dialect \u2014 ${Object.values(Cn).join(", ")} are`);return e},te=e=>new Error(`toWhereSql: ${e} has no SQL form here \u2014 it writes ${Fa.join(", ")}, all and any, and ${Ia.join(", ")} over a to-many relation.`),Km=(e,t)=>ep(e,t,""),Bm=(e,t,r,n)=>{let o=Object.hasOwn(e,n)?e[n]:void 0;if(typeof o!="string"||o==="")throw new M(`toWhereSql: no ${r} for '${n}' in \`${t}\``);return o},ep=(e,t,r,n={clamps:()=>[]})=>{Um();let{columns:o,tables:i={},map:s,mapName:a,model:l}=t??{};if(typeof o!="object"||o===null)throw new M("toWhereSql: `columns` maps each field path to its SQL");if(typeof i!="object"||i===null)throw new M("toWhereSql: `tables` maps each to-many relation path to its table");if(!s||!l)throw new M("toWhereSql: `map` and `model` are required \u2014 a literal is typed by its column, and a date, Json or list value is refused by it");let p=Te(s,a,"toWhereSql");if(!C(p,l))throw new M(`toWhereSql: the map has no model '${l}'`);return bo(e,{map:p,model:l,column:d=>Bm(o,"columns","column",`${r}${d}`),table:d=>Bm(i,"tables","table",`${r}${d}`),clamps:"clamps"in n?n.clamps:()=>[],joined:"joined"in n?n.joined:null,joinedRow:null})},bo=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";let r=e;switch(de(r)){case "all":{let n=r.all;return n.length?`(${n.map(o=>bo(o,t)).join(" AND ")})`:"TRUE"}case "any":{let n=r.any;return n.length?`(${n.map(o=>bo(o,t)).join(" OR ")})`:"FALSE"}case "field":return qx(e,t);case "if":throw te("if / then / else");case "array":return Ix(e,t);case "aggregate":throw te("aggregate");case "date":throw te(`dateOperator '${String(r.dateOperator)}'`);default:throw te("a condition that is not exactly one node kind")}},Ix=(e,t)=>{let{arrayOperator:r,field:n}=e;if(!Ia.includes(r))throw te(`arrayOperator '${r}'`);if(ke(e))throw te(`a window (filter / orderBy / take / skip) on '${n}'`);if(!n)throw te(`the fieldless arrayOperator '${r}'`);let o=se(n,t.map,t.model);if(o.kind==="fallback")throw new Error(`toWhereSql: '${n}' is not a field the map declares on ${t.model}`);if(o.kind==="bridge")throw te(`'${n}', which crosses a bridge`);if(o.hops.length)throw te(`arrayOperator '${r}' on '${n}', behind the relation '${o.hops[0].prefix}'`);if(o.kind!=="direct"||Qr(o)!=="relations")throw te(`arrayOperator '${r}' on '${n}', which is not a to-many relation`);let i=Nr(t.map,o.model,o.entry);if(!i)throw te(`'${n}', whose relation keys the map does not declare`);if(rs.includes(r)&&e.condition===void 0)throw We(r);if(t.joinedRow!==null)throw new Error(`toWhereSql: arrayOperator '${r}' on '${n}' inside an any over the joined '${t.joinedRow}' \u2014 a joined row's own to-many relations have no join here; compile with toMany: 'subquery'`);let s={map:t.map,model:o.entry.type,column:d=>t.column(`${n}.${d}`),table:d=>t.table(`${n}.${d}`),clamps:d=>t.clamps(`${n}.${d}`),joined:t.joined,joinedRow:null};if(t.joined){if(Jf.includes(r))throw new Error(`toWhereSql: arrayOperator '${r}' on '${n}', a relation the caller joins, holds when it has no rows \u2014 that takes an anti-join, not the topic's join. Only notEmpty and any(condition) read a joined relation; compile with toMany: 'subquery' for the rest`);t.joined(n,r);let d=`${s.column(i[0].there)} IS NOT NULL`;return r!==x.any?d:`(${d} AND ${bo(e.condition,{...s,joinedRow:n})})`}let a=[...i.map(({here:d,there:f})=>`${s.column(f)} = ${t.column(d)}`),...t.clamps(n).map(({where:d,clamps:f})=>`(${bo(d,{...s,clamps:f})})`)],l=d=>`(SELECT 1 FROM ${t.table(n)} WHERE ${[...a,...d?[d]:[]].join(" AND ")})`,p=()=>`(${bo(e.condition,s)})`;switch(r){case x.any:return `EXISTS ${l(p())}`;case x.none:return `NOT EXISTS ${l(p())}`;case x.all:return `NOT EXISTS ${l(`${p()} IS NOT TRUE`)}`;case x.empty:return `NOT EXISTS ${l()}`;default:return `EXISTS ${l()}`}},qx=(e,t)=>{if(!Fa.includes(e.operator))throw te(`operator '${e.operator}'`);if(e.bind!==void 0)throw te(`bind '${e.bind}' on '${e.field}'`);if(e.path!==void 0)throw te(`comparing '${e.field}' with the column '${e.path}'`);if(e.offset!==void 0)throw te(`an offset on '${e.field}'`);if(e.coerceType!==void 0)throw te(`coerceType on '${e.field}'`);if(ie(e.caseInsensitive))throw te(`a case-insensitive comparison on '${e.field}'`);if(L(e.field))throw te(`the scoped field '${e.field}'`);let r=se(e.field,t.map,t.model),n=Bx(e,r,t),[o]=r.kind==="direct"?Is(e,ze(r.entry)):[];if(o)throw new Error(`toWhereSql: ${o.message}`);if(e.operator===h.exists)return `${n} IS NOT NULL`;if(e.operator===h.notExists)return `${n} IS NULL`;if(e.value===void 0)throw new Error("No value, path or bind specified");let i=lo(e,e.value,r,"toWhereSql",()=>Ne);if(Pe(e,i))return jt(n,B.includes(e.operator));let s=a=>Wx(a,e.field);switch(e.operator){case h.equals:return i===null?`${n} IS NULL`:`${n} = ${s(i)}`;case h.notEquals:return i===null?`${n} IS NOT NULL`:Ie(n,`${n} <> ${s(i)}`);case h.in:{let{values:a,hasNull:l}=Ye(Wm(e,i));if(!a.length)return l?`${n} IS NULL`:"FALSE";let p=`${n} IN (${a.map(s).join(", ")})`;return l?Ie(n,p):p}default:{let{values:a,hasNull:l}=Ye(Wm(e,i));if(!a.length)return l?`${n} IS NOT NULL`:"TRUE";let p=`${n} NOT IN (${a.map(s).join(", ")})`;return l?`(${p} AND ${n} IS NOT NULL)`:Ie(n,p)}}},Bx=(e,t,r)=>{if(t.kind==="fallback")throw new Error(`toWhereSql: '${e.field}' is not a field the map declares on ${r.model}`);if(t.kind==="past-scalar")throw Hn(e.field,t.column);if(t.kind==="bridge")throw te(`'${e.field}', which crosses a bridge`);let n=t.hops.find(s=>s.entry.isList);if(n)throw zn(e.field,n);let o=Qr(t),i=Xt(e);if(r.joinedRow!==null&&(t.hops.length||o==="relation"))throw new Error(`toWhereSql: '${e.field}' inside an any over the joined '${r.joinedRow}' reads the relation '${t.hops[0]?.prefix??e.field}' \u2014 a joined row's own relations have no join here; compile with toMany: 'subquery'`);if(o==="relation"&&t.kind==="direct"){if(!i)throw mr(e.field);let s=Nr(r.map,t.model,t.entry);if(!s)throw te(`'${e.field}', whose relation keys the map does not declare`);return r.column(`${e.field}.${s[0].there}`)}if(o==="relations")throw new Error(`toWhereSql: '${e.field}' is a to-many relation \u2014 its rows take an arrayOperator rule: { field: '${e.field}', arrayOperator: 'notEmpty' } for a row${r.joined?"; for no rows, compile with toMany: 'subquery'":", 'empty' for none"}`);if(o==="json"||o==="json-path")throw te(`the Json value '${e.field}'`);if(i)return r.column(e.field);if(o==="instant")throw te(`the date '${e.field}'`);if(o==="list")throw te(`the list '${e.field}'`);return r.column(e.field)},Wm=(e,t)=>{if(!Array.isArray(t))throw new Error(`toWhereSql: '${e.operator}' on '${e.field}' takes a list of values`);return t},Wx=(e,t)=>{if(typeof e=="string"){let r=e.replace(/'/g,"''");return `'${Um()===Cn.mysql?r.replace(/\\/g,"\\\\"):r}'`}if(typeof e=="number"&&Number.isFinite(e)||typeof e=="bigint")return String(e);if(typeof e=="boolean")return e?"TRUE":"FALSE";throw te(`the value ${e instanceof Date?"a Date":JSON.stringify(e)} for '${t}'`)};var Ux=(e,t,r)=>{J(r,(n,o)=>{if(typeof n.field!="string")return;let i=oi(e,o,n.field);if(i!==null)throw new Error(`toLensWhereSql: '${n.field}' at ${o.relPath.length?`'${o.relPath.join(".")}'`:"the root"} crosses '${i}', a relation the lens hides \u2014 a hop's clamps are reported at its own path, so a where may only cross hops the lens shows`);return xe(n)?Ce(e.lens.maps,o,n.field).end??false:void 0},t);},Hm=(e,t,r)=>{let{end:n}=Ce(e.lens.maps,t,r);if(!n)return null;let{pathWheres:o,modelWheres:i}=I(e,n.mapName,n.modelName,n.relPath);return {end:n,clamps:[...o.map(s=>({...s,isDefault:false})),...i.map(s=>({...s,isDefault:true}))]}},Jm=(e,t,r)=>n=>{let o=Hm(e,t,n);return o?o.clamps.filter(i=>i.layer<r).map(i=>({where:i.where,clamps:Jm(e,o.end,i.layer)})):[]},Gm=(e,t,r,n)=>{let o=e.map(({where:i,layer:s})=>ep(i,t,r,n(s)));return o.length===1?o[0]:`(${o.join(" AND ")})`},Kx=(e,t)=>{let r=new Set,n=new Map;return o=>({joined:(i,s)=>{let a=Hm(e,t,i);if(!a)throw new Error(`toLensWhereSql: '${i}' reaches no relation`);let{end:l,clamps:p}=a,d=p.find(f=>f.layer>=o);if(d)throw new Error(`toLensWhereSql: the root where of layer ${o+1} reads '${i}' on the caller's join, whose ON carries a clamp of layer ${d.layer+1} (${d.isDefault?`${l.modelName}'s default where`:"its where"}) \u2014 check() reads a where through the clamps of the layers above its own only. Move that clamp into a narrowing above layer ${o+1}, or compile with toMany: 'subquery'`);if(p.some(f=>f.isDefault)){let f=`${l.mapName}.${l.modelName}`,u=n.get(f),c=l.mapName===t.mapName&&l.modelName===t.modelName?`the root is a ${l.modelName} too`:u!==void 0&&u!==i?`the root where also reads '${u}', which reaches ${l.modelName} too`:null;if(c!==null)throw new Error(`toLensWhereSql: the root where reads '${i}' on the caller's join, and ${l.modelName} has a default where, but ${c} \u2014 mapDefaults holds one predicate per model, which reads one table alias, and two aliases need it. Compile with toMany: 'subquery'`);n.set(f,i);}if(s===x.any){if(r.has(i))throw new Error(`toLensWhereSql: the root reads '${i}' with two any rules \u2014 on the caller's join one joined row stands for the relation, so both conditions would have to hold on the same row, where check() lets each find its own. Write one any whose condition says which row, or compile with toMany: 'subquery'`);r.add(i);}}})},zm=(e,t)=>()=>({joined:r=>{throw new Error(`toLensWhereSql: ${e} reads the to-many relation '${r}' \u2014 with toMany: 'join' ${t}; only the root's where reads a joined relation`)}}),Qm=(e,{columns:t,tables:r,toMany:n="subquery"})=>{if(n!=="subquery"&&n!=="join")throw new M(`toLensWhereSql: toMany '${String(n)}' is neither 'subquery' nor 'join'`);let o=F(e),i={root:null,relations:{},mapDefaults:{}};for(let{at:s,effect:a}of tr(o)){let l={columns:t,tables:r,map:o.lens,mapName:s.mapName,model:s.modelName},p=d=>({clamps:Jm(o,s,d)});for(let{where:d}of [...a.pathWheres,...a.modelWheres])Ux(o,s,d);if(a.pathWheres.length){let d=s.relPath.join("."),f=n==="subquery"?p:d?zm(`the where at '${d}'`,"it sits in that relation's join ON, ahead of the joins below it"):Kx(o,s),u=Gm(a.pathWheres,l,d?`${d}.`:"",f);d?i.relations[d]=u:i.root=u;}if(a.modelWheres.length){let d=er(i.mapDefaults,s.mapName,()=>({models:{}})),f=n==="subquery"?p:zm(`the default where of ${s.modelName}`,`it compiles once for every path that reaches ${s.modelName}, and the join exists only where the lens shows the relation`),u=Gm(a.modelWheres,l,`${s.modelName}.`,f),c=E(d.models,s.modelName);if(c!==void 0&&c!==u)throw new Error(`toLensWhereSql: the default where of ${s.modelName} reads a to-many relation whose clamps differ between the paths that reach ${s.modelName} \u2014 a model default compiles to one predicate for every path`);d.models[s.modelName]=u;}}return i};var Zm=e=>Array.isArray(e)?e.some(Zm):typeof e=="object"&&e!==null,Ym=(e,t,r,n)=>{let o=`NULLIF(${t}, 'null'::jsonb)`,i=`jsonb_typeof(${o})`,s=`(${o} #>> '{}')`,a=w=>`${j(n,JSON.stringify(w))}::jsonb`,l=ie(e.caseInsensitive),p=w=>l?`LOWER(${w})`:w,d=B.includes(e.operator),f=w=>Ie(o,`NOT (${w})`);if(Pe(e,r))return jt(o,d);let u=fs(e.operator,r);if(u)throw u;let c=w=>{if(Zm(w))throw V("toSql",`A case-insensitive comparison of '${e.field}' with a list holding objects`);return a(Hr(w))},y=w=>l&&typeof w=="string"?`(${i} = 'string' AND LOWER(${s}) = LOWER(${j(n,w)}))`:l&&Array.isArray(w)?`(${i} = 'array' AND LOWER(${o}::text)::jsonb = ${c(w)})`:`${o} = ${a(w)}`,m=w=>`(${i} = 'string' AND ${p(s)} LIKE ${p(j(n,w))})`,g=w=>{let R=O=>`(CASE WHEN ${i} = 'array' THEN EXISTS (SELECT 1 FROM jsonb_array_elements(${o}) AS e WHERE ${O}) ELSE FALSE END)`;return l&&typeof w=="string"?R(`jsonb_typeof(e) = 'string' AND LOWER(e #>> '{}') = LOWER(${j(n,w)})`):l&&Array.isArray(w)?R(`LOWER(e::text)::jsonb = ${c(w)}`):typeof w=="object"&&w!==null?R(`e = ${a(w)}`):`(${i} = 'array' AND ${o} @> ${a([w])})`},S=w=>typeof w=="string"?`(${m(`%${$e(w)}%`)} OR ${g(w)})`:g(w);switch(e.operator){case h.equals:return r===null?`${o} IS NULL`:y(r);case h.notEquals:return r===null?`${o} IS NOT NULL`:f(y(r));case h.in:case h.notIn:{let{values:w,hasNull:R}=Ye(r),O=w.length?`(${w.map(y).join(" OR ")})`:"FALSE";return e.operator===h.in?R?`(${O} OR ${o} IS NULL)`:O:R?`(NOT ${O} AND ${o} IS NOT NULL)`:f(O)}case h.between:case h.notBetween:{let[w,R]=r,O=`(${i} = jsonb_typeof(${a(w)}) AND ${o} BETWEEN ${a(w)} AND ${a(R)})`;return e.operator===h.between?O:f(O)}case h.contains:return S(r);case h.notContains:return f(S(r));case h.startsWith:return m(`${$e(String(r))}%`);case h.endsWith:return m(`%${$e(String(r))}`);case h.notStartsWith:return f(m(`${$e(String(r))}%`));case h.notEndsWith:return f(m(`%${$e(String(r))}`));case h.matches:case h.notMatches:{let{source:w,caseInsensitive:R}=br(r),O=`(${i} = 'string' AND ${s} ~${R?"*":""} ${j(n,Go(w))})`;return e.operator===h.matches?O:f(O)}}let b=So(e.operator,"field")?.symbol;if(b)return `(${i} = jsonb_typeof(${a(r)}) AND ${o} ${b} ${a(r)})`;throw new Error(`Operator '${e.operator}' is not supported on a Json value in SQL`)};var Xm=e=>typeof e=="object"&&qr(e)!==null,ci=({sql:e,shape:t},r)=>{if(t!=="json-path"&&t!=="text")return `to_timestamp(EXTRACT(EPOCH FROM ${e}))`;let n=j(r,mt(r).timeZone);return `(CASE WHEN btrim(${e}) ~ '^-?[0-9]+(\\.[0-9]+)?$' THEN to_timestamp(btrim(${e})::numeric / 1000) WHEN ${e} ~* '[0-9]{2}:[0-9]{2}(:[0-9]{2}(\\.[0-9]+)?)?\\s*(z|[+-][0-9]{2}(:?[0-9]{2})?)\\s*$' OR ${e} ~* '\\m(gmt|utc)\\M' THEN (${e})::timestamptz ELSE (${e})::timestamp AT TIME ZONE ${n} END)`},ya=e=>Object.values(e).some(Xm),zx=(e,t,r)=>{let n=Vr(r),o=n?"int":"double precision";if(typeof e=="number"||!Xm(e)){let a=Ja(e,ln(t),r);return `${j(t,a)}::${o}`}let i=ve(e,t).sql;return `(CASE WHEN ${n?`${i} >= 0 AND ${i} = trunc(${i})`:`${i} >= 0`} THEN ${i} END)::${o}`},Hx=(e,t)=>`make_interval(${nu.flatMap(n=>{let o=Object.keys(e).filter(i=>e[i]!==void 0&&ot[i].interval===n).map(i=>{let s=zx(e[i],t,i),{factor:a}=ot[i];return a===1?s:`${a} * ${s}`});return o.length?[`${n} => ${o.join(" + ")}`]:[]}).join(", ")})`,mi=(e,t,r,n)=>{let o=mt(n).timeZone;if(e.type==="value"&&!ya(t)){let l=Kr(t,ln(n));return e.value===null||e.value===void 0||l===null?or:{type:"value",value:yr(Pt(e.value),l,r,o).toDate()}}let i=e.type==="column"?e.computed?e.sql:ci(e,n):`${j(n,e.value??null)}::timestamptz`,s=j(n,o);return {type:"column",computed:true,sql:`(((${i} AT TIME ZONE ${s}) ${r===1?"+":"-"} ${Hx(t,n)}) AT TIME ZONE ${s})`}};var tp=(e,t,r)=>{let n=ve(t,r);if(e.type==="value"&&n.type==="value"){let i=zr(n.value);return i===null?or:{type:"value",value:Gr(e.value,i)}}let o=(i,s)=>i.type==="column"?`(${i.sql})::double precision`:`${j(r,s(i.value)??null)}::double precision`;return {type:"column",computed:true,sql:`(${o(e,i=>i)} + ${o(n,zr)})`}},eg=(e,t,r)=>{if(Ft(e))return or;let n=ve(t,r);if(n.type==="column")throw new Error(`A row path on a date offset ('${t.path}') is check-only; evaluate with check()`);let o=ro(n.value);return o===null?or:mi(e,...o,r)};var tg,rg=e=>{tg=e;},Lr=(e,t)=>tg(e,t);var wa=(e,t,r,n=false)=>{let o=ds(e);if(o)throw o;let i=r===void 0?nr(e.field,t):{sql:r,shape:"scalar"};if(i.shape==="relation"&&!Xt(e))throw mr(e.field);let s=r===void 0||n,a=ne(e)&&t.map&&t.currentModel?(L(e.path)??{path:e.path}).path:null;if(a!==null){let O=so(Y(e.field,t.map,t.currentModel),Y(a,t.map,t.currentModel),e.operator);if(O)throw V("toSql",`Comparing '${e.field}' with the column '${e.path}'`,O)}if(i.shape==="enum"&&!Je.includes(e.operator)){let O=og(e,t),$=Y(e.field,t.map,t.currentModel),k=O!==ha&&$&&!Pe(e,O)?_s(e,O,$,t.map):null;if(k){let le=`${i.sql}::text = ANY(${j(t,k.values)})`;return k.matchesNull?Ie(i.sql,le):le}}let l=i.shape==="enum"&&!Je.includes(e.operator)&&a===null?{...i,sql:`${i.sql}::text`}:i;if((i.shape==="json"||i.shape==="json-path")&&!Je.includes(e.operator)){let O=og(e,t);if(O===ha)throw new Error(`The Json value '${e.field}' compares against an operand known when compiling, not one read per row.`);return Ym(e,Dt(e.field,t,{jsonb:true}),O,t)}let d=O=>{if(O.type==="column"&&!O.computed&&(O.shape==="json"||O.shape==="json-path"))throw V("toSql",`'${e.field}' compared with a Json value read per row`,"SQL would compare its text")};if(Qe.includes(e.operator)){let O=ag(e,t);return O?.forEach(d),ui(l.sql,O,B.includes(e.operator),t,s)}let f=ig(e,t);if(d(f),f.type==="column"&&zt(e.operator,"field")==="string"&&!Zr(i.shape)&&i.shape!=="list")throw V("toSql",`'${e.operator}' on '${e.field}'`,"it is not text");if(f.type==="column"&&f.computed&&i.shape==="text"&&r===void 0)throw V("toSql",`'${e.field}' against a value moved by an offset`,"an offset moves a number or a date");let u=l.sql,c=So(e.operator,"field");if(c)return ga(u,c.symbol,f,false,t);if(f.type==="value"&&Pe(e,f.value))return jt(u,B.includes(e.operator),s);let y=f.type==="column"&&f.computed===true,m=ie(e.caseInsensitive)&&(f.type==="column"?!y&&Zr(i.shape)&&Zr(f.shape):xr(i.shape,f.value)),g=O=>m?`LOWER(${O})`:O,S=O=>m?Hr(O):O;if(i.shape==="list"&&f.type==="column"&&Et.includes(e.operator)){if(Y(e.field,t.map,t.currentModel)?.type!=="String"||!Zr(f.shape))throw V("toSql",`'${e.operator}' on the list '${e.field}' with a member read per row ('${e.path}')`,"Postgres matches a member of the list's own type only");let O=ie(e.caseInsensitive)&&Zr(f.shape)?`EXISTS (SELECT 1 FROM unnest(${u}) AS e WHERE LOWER(e) = LOWER(${f.sql}))`:`array_position(${u}, ${f.sql}) IS NOT NULL`;return e.operator===h.contains?`(${f.sql} IS NOT NULL AND ${O})`:`(${u} IS NULL OR (${f.sql} IS NOT NULL AND NOT ${O}))`}if(i.shape==="list"&&f.type==="value"){let O=ie(e.caseInsensitive)&&xr("text",f.value);if(Et.includes(e.operator)){let $=j(t,f.value),k=O?`EXISTS (SELECT 1 FROM unnest(${u}) AS e WHERE LOWER(e) = LOWER(${$}))`:`array_position(${u}, ${$}) IS NOT NULL`;return e.operator===h.contains?k:`NOT ${k}`}if(cr.includes(e.operator)&&Array.isArray(f.value))return Lr(xs(e,f.value),t);if(Jx(e.operator))throw new Error(`'${e.operator}' does not apply to the list '${e.field}'; test its members with contains.`);if(O&&_e.includes(e.operator)&&Array.isArray(f.value)){let $=j(t,Hr(f.value)),k=`(${u} IS NOT NULL AND ARRAY(SELECT LOWER(e) FROM unnest(${u}) AS e) = ${$})`;return e.operator===h.equals?k:Ie(u,`NOT ${k}`)}}let b=f.type==="value"?f.value:void 0,w=f.type==="column"?f.sql:void 0;if(w!==void 0&&(cr.includes(e.operator)||["pattern","string"].includes(zt(e.operator,"field"))))throw V("toSql",`'${e.operator}' against an operand read per row ('${e.path}')`);let R=O=>s?Ie(u,O):O;switch(e.operator){case h.equals:return y?`${u} = ${w}`:w!==void 0?`${g(u)} IS NOT DISTINCT FROM ${g(w)}`:b===null?`${u} IS NULL`:`${g(u)} = ${g(j(t,b))}`;case h.notEquals:return y?R(`${u} <> ${w}`):w!==void 0?`${g(u)} IS DISTINCT FROM ${g(w)}`:b===null?`${u} IS NOT NULL`:R(`${g(u)} <> ${g(j(t,b))}`);case h.in:{let{values:O,hasNull:$}=Ye(b);if(!O.length)return $?`${u} IS NULL`:"FALSE";let k=`${g(u)} = ANY(${j(t,S(O))})`;return $?R(k):k}case h.notIn:{let{values:O,hasNull:$}=Ye(b);if(!O.length)return $?`${u} IS NOT NULL`:"TRUE";let k=`${g(u)} <> ALL(${j(t,S(O))})`;return $?`(${k} AND ${u} IS NOT NULL)`:R(k)}case h.contains:return `${g(u)} LIKE ${g(j(t,`%${$e(String(b))}%`))}`;case h.notContains:return R(`${g(u)} NOT LIKE ${g(j(t,`%${$e(String(b))}%`))}`);case h.startsWith:return `${g(u)} LIKE ${g(j(t,`${$e(String(b))}%`))}`;case h.endsWith:return `${g(u)} LIKE ${g(j(t,`%${$e(String(b))}`))}`;case h.notStartsWith:return R(`${g(u)} NOT LIKE ${g(j(t,`${$e(String(b))}%`))}`);case h.notEndsWith:return R(`${g(u)} NOT LIKE ${g(j(t,`%${$e(String(b))}`))}`);case h.matches:return ng(u,b,false,t);case h.notMatches:return R(ng(u,b,true,t));case h.isEmpty:case h.notEmpty:return rp(e.field,i,e.operator===h.isEmpty,t,Ps(e,t.map,t.currentModel));case h.exists:return `${u} IS NOT NULL`;case h.notExists:return `${u} IS NULL`;default:throw new Error(`Unknown operator: ${e.operator}`)}},ig=(e,t)=>{if(Je.includes(e.operator))return {type:"value",value:void 0};let r=sg(e,ve(e,t),t);return e.offset===void 0?r:tp(r,e.offset,t)},sg=(e,t,r)=>t.type==="column"?t:{type:"value",value:lo(e,t.value,Or(e.field,r.map,r.currentModel),"toSql",()=>mt(r).timeZone)},ag=(e,t)=>{let r=sg(e,ve(e,t),t),n=r.type==="value"?r.value:void 0;if(n==null)return null;let o=st(n,e.operator);return o.some(i=>i!=null&&!we(i))&&to(n,e.operator),Ze(o).map(i=>{let s={type:"value",value:i};return e.offset===void 0?s:tp(s,e.offset,t)})},ng=(e,t,r,n)=>{if(typeof t!="string"&&!(t instanceof RegExp))throw new Error("matches requires a string or RegExp pattern");let{source:o,caseInsensitive:i}=br(t);return `${e} ${r?"!":""}~${i?"*":""} ${j(n,Go(o))}`},ha=Symbol("not known"),og=(e,t)=>{if(Qe.includes(e.operator)){let n=ag(e,t);return n?n.every(o=>o.type==="value")?n.map(o=>o.value):ha:null}let r=ig(e,t);return r.type==="value"?r.value:ha},rp=(e,t,r,n,o)=>{let{sql:i,shape:s}=t;if(s==="list")return r?`(${i} IS NULL OR cardinality(${i}) = 0)`:`cardinality(${i}) > 0`;if(s==="json"||s==="json-path"){let a=Dt(e,n,{jsonb:true}),l=["'null'::jsonb",...o?[`'""'::jsonb`]:[],"'[]'::jsonb"].join(", ");return r?`(${a} IS NULL OR ${a} IN (${l}))`:`${a} NOT IN (${l})`}return o?r?`(${i} IS NULL OR ${i} = '')`:`(${i} IS NOT NULL AND ${i} <> '')`:r?`${i} IS NULL`:`${i} IS NOT NULL`},Jx=e=>zt(e,"field")==="string"&&!Et.includes(e);var lg=(e,t)=>{if(ke(e))throw vt("toSql");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=Qx(e,t),{coerceType:n,...o}=e;return wa(o,t,r,e.aggregate.mode==="avg")},Qx=(e,t)=>{let{mode:r,field:n}=e.aggregate;if(!xt.includes(r))throw gr(r);let o=r==="sum"?"SUM":"AVG",i=u=>r==="sum"?`COALESCE(${o}(${u}), 0)`:`${o}(${u})`,s=Ge({field:e.field},t.map,t.currentModel);if(s==="relation"||Y(e.field,t.map,t.currentModel)?.kind==="object")throw new Error(`Field '${e.field}' is a relation \u2014 toSql() cannot aggregate relation lists. Use toPrisma() instead.`);if(n?.includes("."))throw new Error(`aggregate.field '${n}' contains a nested path \u2014 toSql() only supports flat field names. Use check() for nested paths.`);let a=s==="list",l=Dt(e.field,t,{jsonb:!a}),p=a?l:`(CASE WHEN jsonb_typeof(${l}) = 'array' THEN ${l} END)`;if(a){if(n)throw new Error("aggregate.field is not supported for native array types. Use a JSONB column for object arrays.");return `(SELECT ${i(e.coerceType?"elem::numeric":"elem")} FROM unnest(${p}) AS elem)`}if(n){let u=`(elem->>${al(n)})::numeric`;return `(SELECT ${i(u)} FROM jsonb_array_elements(${p}) AS elem)`}return `(SELECT ${i("elem::numeric")} FROM jsonb_array_elements_text(${p}) AS elem)`};var pg=(e,t)=>{if(ke(e))throw vt("toSql");if(!e.field)throw ls("toSql");if(Ge({field:e.field},t.map,t.currentModel)==="relation"||Y(e.field,t.map,t.currentModel)?.kind==="object")throw new Error(`Field '${e.field}' is a relation \u2014 relation arrays are not supported in SQL; use toPrisma().`);switch(e.arrayOperator){case x.empty:case x.notEmpty:{let n=nr(e.field,t),o=e.arrayOperator===x.empty;if(n.shape==="list")return rp(e.field,n,o,t,false);let i=Dt(e.field,t,{jsonb:true});return `(CASE WHEN jsonb_typeof(${i}) = 'array' THEN jsonb_array_length(${i}) ${o?"=":">"} 0 ELSE ${o?"TRUE":"FALSE"} END)`}case x.all:case x.any:case x.none:case x.atLeast:case x.atMost:case x.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 me(e.arrayOperator,"array")}};var Zx=(e,t)=>e.type==="column"&&!e.computed?{type:"column",sql:ci(e,t),computed:true}:e,dg=e=>e===void 0||e==="instant"||e==="text"||e==="json-path"||e==="unknown",fg=e=>V("toSql",`A date rule on '${e}'`,"it is not a date column"),ug=(e,t,r)=>{let n=t.some(i=>i.type==="column"),o=e.shape==="json-path"||e.shape==="text";return n||o?{lhs:ci(e,r),ends:t.map(i=>Zx(i,r))}:{lhs:e.sql,ends:t}},cg=(e,t)=>{let r=nr(e.field,t);if(!dg(r.shape))throw fg(e.field);let n=ve(e,t);if(n.type==="column"&&!dg(n.shape))throw fg(String(e.path??e.field));if(!Ft(n)){let s=e.offset===void 0?void 0:ve(e.offset,t),a=Qt(n.type==="value"?n.value:void 0,s?.type==="value"?s.value:void 0);if(a)throw a}let o=So(e.dateOperator,"date");if(o){let{lhs:s,ends:a}=ug(r,[Xx(e,t)],t);return ga(s,o.symbol,a[0],o.negated,t)}let i=(s,a)=>{if(!s)return ui(r.sql,null,a,t);let{lhs:l,ends:p}=ug(r,s,t);return ui(l,p,a,t)};switch(e.dateOperator){case N.within:case N.notWithin:return i(e$(e,t),B.includes(e.dateOperator));case N.between:case N.notBetween:return i(t$(e,t),B.includes(e.dateOperator));case N.dayIn:case N.dayNotIn:{let s=e.dateOperator===N.dayNotIn,a=ve(e,t);if(a.type==="column")throw V("toSql",`A weekday list read from the row ('${e.path}')`);let l=Za(a.value);if(l===null)return jt(r.sql,s);let p=j(t,mt(t).timeZone),d=j(t,l),f=`EXTRACT(DOW FROM (${ci(r,t)} AT TIME ZONE ${p}))`;return e.dateOperator===N.dayIn?`${f} = ANY(${d})`:Ie(r.sql,`${f} <> ALL(${d})`)}default:throw me(e.dateOperator,"date")}},mg=e=>({type:"value",value:Io(mt(e)).toDate()}),Yx=(e,t,r)=>{let n=Ee(e);if(n&&ya(n[0]))return mi(mg(r),...n,r);let o=Xe(e,ln(r));return o===null?or:{type:"value",value:Qn(o,t,mt(r)).toDate()}},gg=(e,t,r)=>e==null?or:Z(e)?Yx(e,t,r):{type:"value",value:Os(e,mt(r).timeZone)},yg=(e,t,r)=>t.offset===void 0?e:eg(e,t.offset,r),Xx=(e,t)=>{let r=ve(e,t),n=r.type==="column"?r:gg(r.value,e.dateOperator,t);return yg(n,e,t)},e$=(e,t)=>{let r=ve(e,t);if(Ft(r))return null;if(r.type==="column"||!Z(r.value))throw it(e.dateOperator);let n=Ee(r.value);if(n&&ya(n[0])){let s=mg(t),a=mi(s,...n,t);return n[1]===-1?[a,s]:[s,a]}let o=Xe(r.value,ln(t));if(o===null)return null;let i=Zn(o,mt(t));return [{type:"value",value:i[0].toDate()},{type:"value",value:i[1].toDate()}]},t$=(e,t)=>{let r=ve(e,t);if(Ft(r))return null;let n=r.type==="value"?r.value:void 0,o=st(n,e.dateOperator).map(l=>gg(l,e.dateOperator,t));if(o.some(Ft))return null;let[i,s]=o;return (i.type==="value"&&s.type==="value"?Ze([i.value,s.value]).map(l=>({type:"value",value:l})):o).map(l=>yg(l,e,t))};var hg=(e,t)=>e.all.length===0?"TRUE":`(${e.all.map(n=>Lr(n,t)).join(" AND ")})`,wg=(e,t)=>e.any.length===0?"FALSE":`(${e.any.map(n=>Lr(n,t)).join(" OR ")})`,Sg=(e,t)=>{if(kt(e,t.map,t.currentModel))return "TRUE";let r=Lr(e.if,t),n=Lr(e.then,t);if(e.else!==void 0){let o=Lr(e.else,t);return `(((${r}) IS NOT TRUE OR ${n}) AND ((${r}) IS TRUE OR ${o}))`}return `((${r}) IS NOT TRUE OR ${n})`};var gi=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";if(wi(e,"toSql"),"field"in e&&typeof e.field=="string"&&t.map&&t.currentModel&&Er(e.field,t.map,t.currentModel))return "TRUE";let r=de(e);(r==="field"||r==="date")&&ks(e.field,t.map,t.currentModel);let n=e;switch(r){case "all":return hg(n,t);case "any":return wg(n,t);case "if":return Sg(n,t);case "array":return pg(n,t);case "aggregate":return lg(n,t);case "date":return cg(n,t);case "field":return wa(n,t);default:throw $t()}};rg(gi);var np=e=>{let t=Te(e?.map,e?.mapName,"toSql"),r=!!(t&&e?.model),n=e?.alias??(r?"t0":void 0);return {params:[],paramIndex:0,dateConfig:{now:e?.now,timeZone:e?.timeZone,weekStart:e?.weekStart},map:t,currentModel:e?.model,currentAlias:n,joinCounter:r?{n:0}:void 0,joins:r?[]:void 0,joinRegistry:r?new Map:void 0}},r$=(e,t)=>na(e,t,"toSql",n$),n$=(e,t)=>{let r=np(t);return {sql:gi(e,r),params:r.params,joins:r.joins??[]}};var bg=(e,t)=>{let[r,...n]=t,o=e[r];if(n.length===0){o===void 0&&(e[r]=true);return}let i=o!==void 0&&o!==true?o.select:{};bg(i,n),e[r]={select:i};},o$=(e,t,r,n,o,i,s,a,l,p)=>{let d=sa(`source '${o}' at '${t}'`,()=>li(a,{...l,map:e,mapName:r,model:n})),f=d.steps.at(-1),u=f.where,c=d.steps.length>1||(f.refs?.length??0)>0,y=Te(e,r,"toPrisma"),m=P=>p!==void 0&&se(P,y,n).kind==="bridge",g=i!==void 0&&!m(i)?i:void 0,S=(s??[]).map(P=>m(P)?void 0:P),b=P=>{let q=se(P,y,n);return q.kind==="json-path"?P.split(".").slice(0,q.stopIndex).join("."):P},w=p===void 0?[]:fa(e,r,n,[...Ve(p),...i!==void 0&&g===void 0?[i]:[],...(s??[]).filter(m)].map(b)).filter(P=>P!==o),R=g?.includes(".")?g:void 0,O=[...S.filter(P=>P!==void 0),...R?[R]:[],...w],$={[o]:true,...g&&!R?{[g]:true}:{}};for(let P of O)bg($,P.split("."));let k={model:n,...s||R||p!==void 0?{}:{distinct:g?[o,g]:[o]},select:$,where:u,...c?{steps:d.steps}:{}},le;try{for(let Oe of w){let Le=se(Oe,y,n);if(!(Le.kind==="direct"&&!Le.hops.length&&Le.entry.kind!=="object"))throw new Error(Le.kind==="direct"?`the re-check reads '${Oe}' through a relation, which flat SQL rows can't hold \u2014 run the Prisma query`:`the re-check reads '${Oe}', which is not a column of ${n} \u2014 run the Prisma query`)}let P=np({...l,map:e,mapName:r,model:n,alias:"t0"}),q=gi(a,P),W=R?Dt(R,P):void 0,Mr=S.map((Oe,Le)=>Oe===void 0?void 0:`${Dt(Oe,P)} AS ${ae(`__group_${Le}`)}`),xo=P.joins??[],_r=xo.length?` ${xo.join(" ")}`:"",ye=q?.trim()?` WHERE ${q}`:"",gt=ae("t0"),pn=[`${gt}.${ae(o)}`,...W?[`${W} AS ${ae("__label")}`]:g?[`${gt}.${ae(g)}`]:[],...Mr.filter(Oe=>Oe!==void 0),...w.map(Oe=>`${gt}.${ae(Oe)}`)].join(", "),oe=C(E(e.maps,r),n)?.dbName??n;le={sql:`SELECT DISTINCT ${pn} FROM ${ae(oe)} AS ${gt}${_r}${ye}`,params:P.params};}catch(P){le={sql:null,params:[],error:P instanceof Error?P.message:String(P)};}return {prisma:k,sql:le}},Rg=(e,t={})=>{let{lens:r}=F(e);return Om(e).map(({path:n,visit:o,field:i,label:s,groupBy:a,where:l,recheck:p})=>{let d=l,{prisma:f,sql:u}=o$(r,n,o.mapName,o.model,i,s,a,d,t,p);return {path:n,mapName:o.mapName,model:o.model,field:i,...s!==void 0?{label:s}:{},...a!==void 0?{groupBy:a}:{},composedWhere:d,prisma:f,sql:u,...p!==void 0?{recheck:p}:{}}})};var Sa=e=>!Array.isArray(e)&&e.distinct===true,ba=(e,t=false)=>{let r=new Set,n=new Set,o=new Set;return e.filter(i=>{let[s,a]=i instanceof Date?[n,i.getTime()]:typeof i=="object"&&i!==null?[o,JSON.stringify(i)]:[r,t&&typeof i=="string"?i.toLowerCase():i];return s.has(a)?false:(s.add(a),true)})};var Ra=(e,t)=>e===null?Zs:typeof e=="number"?{kind:Number.isInteger(e)?A.Int:A.Float,isList:false,nullable:false}:typeof e=="bigint"?{kind:A.BigInt,isList:false,nullable:false}:typeof e=="string"?{kind:A.String,isList:false,nullable:false}:typeof e=="boolean"?{kind:A.Boolean,isList:false,nullable:false}:e instanceof Date?{kind:A.DateTime,isList:false,nullable:false}:Array.isArray(e)?Xs(e.map((r,n)=>{let o=`${t}[${n}]`;return Array.isArray(r)&&ee(o,"nested_list","a list's items are single values"),Ra(r,o)}),t):{kind:A.Json,isList:false,nullable:false};var Og=(e,t,r)=>{let n=ii(e,Hs(t,r),r);return n.viaList&&ee(r,"to_many_path",`'${t}' reads through the to-many relation '${n.viaList}'; aggregate its rows`),_(n.entry)&&ee(r,"relation_not_value",`'${t}' names a relation's rows, not a value; aggregate them`),{kind:si(n),isList:n.entry.isList===true,nullable:n.json||n.entry.isRequired!==true}};var Ro=e=>re(e)&&"aggregate"in e&&["operator","value","path","bind"].some(t=>t in e);var Eg={source:["value","path","bind","bindOptional"],if:["if","then","else"],aggregate:["field","aggregate","condition","filter","orderBy","take","skip","coerceType","caseInsensitive"],list:["list","distinct"]},op=(e,t)=>e.map(r=>({...r,path:r.path.startsWith("$")?`${t}${r.path.slice(1)}`:`${t}.${r.path}`})),Ea=(e,t,r)=>Object.keys(e).filter(n=>!Eg[t].includes(n)).map(n=>({path:`${r}.${n}`,code:"unknown_key",message:`a ${t==="source"?"value source":`${t} value`} takes ${Eg[t].join(", ")}, not '${n}'`})),i$=(e,t,r)=>{if(r)return [{path:t,code:"nested_list",message:"a list's items are single values"}];let n=Ht(e).flatMap((s,a)=>Oa(s,`${t}[${a}]`,true));if(Array.isArray(e))return n;let o=e,i=Ea(o,"list",t);return Array.isArray(o.list)||i.push({path:`${t}.list`,code:"invalid_list",message:"list must be an array"}),o.distinct!==void 0&&typeof o.distinct!="boolean"&&i.push({path:`${t}.distinct`,code:"invalid_distinct",message:"distinct must be a boolean"}),[...i,...n]},s$=(e,t,r)=>{let n=Ea(e,"if",t);return e.if===void 0?n.push({path:`${t}.if`,code:"condition_required",message:"if / then takes an if"}):n.push(...op(Tr(e.if).errors,`${t}.if`)),e.then===void 0?n.push({path:`${t}.then`,code:"value_required",message:"if / then takes a then"}):n.push(...Oa(e.then,`${t}.then`,r)),e.else!==void 0&&n.push(...Oa(e.else,`${t}.else`,r)),n},a$=(e,t)=>[...Ea(e,"aggregate",t),...e.field===""?[{path:`${t}.field`,code:"field_required",message:"an aggregate value reads a list field"}]:[],...op(Pc(e).errors,t)],Oa=(e,t,r)=>{let n=e;switch(Nt(e)){case "literal":return [];case "list":return i$(e,t,r);case "if":return s$(n,t,r);case "aggregate":return a$(n,t);case "source":return [...Ea(n,"source",t),...op(kc(n).errors,t)];default:{let o=Ro(n),i=o?Gn(t):Kn(t);return [{path:t,code:o?"unexpected_comparison":"invalid_value_expression",message:i.message.slice(t.length+2)}]}}},yi=e=>rt(Oa(e,"$",false)),Oo=e=>sn(yi(e),"Invalid value expression");var l$=(e,t,r)=>e.value!==void 0?Ra(e.value,`${r}.value`):typeof e.bind=="string"?ee(r,"untyped_binding",`{ bind: '${e.bind}' } has no type until it is bound`):Og(Js(t,`the path '${String(e.path)}'`),e.path,r),p$=(e,t,r,n)=>{let o=xa(e.then,t,`${r}.then`,n);return e.else===void 0?n?o:Ys(o,Zs,r):Ys(o,xa(e.else,t,`${r}.else`,n),r)},d$=(e,t,r)=>{let n=Xs(Ht(e).map((o,i)=>{let s=`${r}[${i}]`,a=xa(o,t,s,true);return a.isList&&ee(s,"nested_list","a list's items are single values"),a}),r);return Sa(e)&&n.kind===A.Json&&ee(`${r}.distinct`,"distinct_over_json","distinct drops repeated values, not Json"),n},xa=(e,t,r,n)=>{switch(Nt(e)){case "literal":return Ra(e,r);case "source":return l$(e,t,r);case "aggregate":return $c(t,e,r);case "if":return p$(e,t,r,n);case "list":return d$(e,t,r);default:return ee(r,"invalid_value_expression",Kn(r).message)}},Eo=(e,t)=>(Oo(e),xa(e,t,"$",false));var f$=["distinct","min","max"],u$=(e,t)=>{if(e.coerceType!==void 0||!f$.includes(e.aggregate.mode))return e;try{return Eo(e,t).kind===A.DateTime?{...e,coerceType:A.DateTime}:e}catch(r){if(r instanceof nn)return e;throw r}},$a=(e,t)=>{switch(Nt(e)){case "aggregate":return u$(e,t);case "if":{let r=e;return {...r,then:$a(r.then,t),...r.else!==void 0&&{else:$a(r.else,t)}}}case "list":{let r=Ht(e).map(n=>$a(n,t));return Array.isArray(e)?r:{...e,list:r}}default:return e}},xg=(e,t)=>(Oo(e),$a(e,t));var $g=(e,t)=>{let r=yi(e).errors;if(r.length>0)return {type:null,paths:[],clockUnit:null,errors:r};let n=Wr(e),o=[...Pr(n,t).errors],i=null;try{i=Eo(e,t);}catch(a){if(!(a instanceof nn))throw a;o.push(a.issue);}let s=null;try{s=Ko(n);}catch(a){o.push({path:"$",code:"clock_unit_below_floor",message:a.message});}return {type:i,paths:Ve(n).sort(),clockUnit:s,errors:o}};var c$=(e,t)=>{if(typeof e=="number"&&Number.isFinite(e)||typeof e=="bigint")return {value:e,key:e,kind:"number"};if(e instanceof Date&&!Number.isNaN(e.getTime()))return {value:e,key:e.getTime(),kind:"date"};if(typeof e=="object"&&e!==null){let r=$s(e);if(typeof r=="number")return {value:e,key:r,kind:"number"}}throw new Error(`${t} must be a finite number or a valid date for min / max`)},m$=(e,t,r)=>{if(e.length===0)return null;let n=new Set(e.map(o=>o.kind));if(n.size>1)throw new Error(`${r} ${t} orders one kind of value, not ${[...n].join(" and ")}`);return e.reduce((o,i)=>(t==="max"?i.key>o.key:i.key<o.key)?i:o).value},vg=(e,t,r)=>{if(Ro(e))throw Gn(r);if(!re(e.aggregate))throw new Error(`${r}.aggregate must be an object`);let{mode:n,field:o}=e.aggregate;if(!ts(n))throw us(n);if(typeof e.field!="string"||e.field==="")throw new Error(`${r}.field: an aggregate value reads a list field`);let i=el(e,t),s=e.coerceType==="DateTime"?Zt(t,l=>Ue(l,t.scopes,t.bindings)).timeZone:Ne,a=vs(e.coerceType,s);switch(n){case "count":return o===void 0?i.length:Ho(i,e.field,o,()=>true).length;case "sum":case "avg":return tl(n,i,e.field,o,e.coerceType);case "distinct":return ba(Ho(i,e.field,o,a),ie(e.caseInsensitive));default:return m$(Ho(i,e.field,o,(l,p)=>c$(a(l),p)),n,e.field)}};var Ag=(e,t,r)=>{if(e.if===void 0||e.then===void 0)throw new Error(`${r}: if / then takes both an if and a then`);return Du(e.if,t)?{expr:e.then,path:`${r}.then`}:e.else===void 0?void 0:{expr:e.else,path:`${r}.else`}},g$=(e,t,r)=>{let n=Ag(e,t,r);return n===void 0?null:va(n.expr,t,n.path)},y$=(e,t,r)=>{if(!Array.isArray(e)&&!Array.isArray(e.list))throw new Error(`${r}.list must be an array`);let n=Ht(e).flatMap((o,i)=>{let s=`${r}[${i}]`,a=Nt(o);if(a==="list")throw new Error(`${s}: a list's items are single values`);if(a!=="if")return [va(o,t,s)];let l=Ag(o,t,s);return l===void 0?[]:[va(l.expr,t,l.path)]});return Sa(e)?ba(n):n},va=(e,t,r)=>{switch(Nt(e)){case "literal":return e;case "source":return Ue(e,t.scopes,t.bindings);case "aggregate":return vg(e,t,r);case "if":return g$(e,t,r);case "list":return y$(e,t,r);default:throw Ro(e)?Gn(r):Kn(r)}},Ng=(e,t,r={})=>va(e,{...r,scopes:[t]},"$");var Pg=e=>Ko(Wr(e));/*! Bundled license information:
4
4
 
5
5
  lodash-es/lodash.js:
6
6
  (**
@@ -12,5 +12,5 @@ lodash-es/lodash.js:
12
12
  * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
13
13
  * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
14
14
  *)
15
- */export{Zi as ALL_KINDS,x as ArrayOperator,Mo as CLOCK_UNITS,lO as ConditionShape,A as DateOperator,N as FieldKind,T as LensRefusal,Q as NUMERIC_KINDS,h as Operator,JR as RuleTarget,ta as SourceOptionOrder,Tn as SqlDialect,L as UsageError,La as VALUE_AGGREGATE_MODES,zt as ValueShape,we as andWhere,pc as assertValidFieldMaps,ra as assertValidNarrowing,YO as assertValidRule,wo as assertValidValue,vc as bindLens,Ba as bindRule,he as check,hl as clampLens,Wo as clockUnit,Tc as coerceRule,yg as coerceValue,vm as composeLens,Cc as createLens,Lc as describeRule,Mc as describeRuleSources,hg as describeValue,tt as engineGlobals,Rg as evaluateValue,rm as executePrismaPlan,YR as getAggregateOperators,ZR as getArrayOperators,pO as getConditionShapeKeys,dt as getLensRoot,QR as getOperatorsForKind,Ht as getValueShape,Tu as indexBridges,bo as inferValueType,pm as lensVisit,Bo as listBindings,uO as listFields,xc as listLensBindings,Xe as matchAll,lt as matchNothing,Sm as materializeSourceQuery,bm as materializeSources,po as narrowRule,U as orWhere,vu as orderRecords,_ as parseScopeRef,lo as prefixConditionFields,xm as projectLens,wm as projectRows,$m as readLensValue,ze as readScopeRef,zR as registerEngineGlobals,xs as stitchFieldMaps,Am as storeLens,ym as toLensSelect,Vm as toLensWhereSql,ii as toPrisma,fg as toSourceQueries,qx as toSql,Mm as toWhereSql,rl as validateFieldMaps,Ul as validateNarrowing,vr as validateRule,Ar as validateRuleInLens,gi as validateValue,Og as valueClockUnit,aa as walkLensPath};//# sourceMappingURL=index.js.map
15
+ */export{Zi as ALL_KINDS,x as ArrayOperator,jo as CLOCK_UNITS,gO as ConditionShape,N as DateOperator,A as FieldKind,T as LensRefusal,G as NUMERIC_KINDS,h as Operator,rO as RuleTarget,ca as SourceOptionOrder,Cn as SqlDialect,M as UsageError,ja as VALUE_AGGREGATE_MODES,Gt as ValueShape,ce as andWhere,Ic as assertValidFieldMaps,ma as assertValidNarrowing,BE as assertValidRule,Oo as assertValidValue,Gc as bindLens,Ga as bindRule,Se as check,Ll as clampLens,Ko as clockUnit,Zc as coerceRule,xg as coerceValue,Fm as composeLens,Yc as createLens,Xc as describeRule,em as describeRuleSources,$g as describeValue,nt as engineGlobals,Ng as evaluateValue,cm as executePrismaPlan,iO as getAggregateOperators,oO as getArrayOperators,yO as getConditionShapeKeys,ft as getLensRoot,nO as getOperatorsForKind,zt as getValueShape,Vu as indexBridges,Eo as inferValueType,bm as lensVisit,Uo as listBindings,SO as listFields,Uc as listLensBindings,et as matchAll,pt as matchNothing,Tm as materializeSourceQuery,km as materializeSources,go as narrowRule,U as orWhere,Mu as orderRecords,L as parseScopeRef,mo as prefixConditionFields,_m as projectLens,Pm as projectRows,Dm as readLensValue,He as readScopeRef,eO as registerEngineGlobals,Ns as stitchFieldMaps,jm as storeLens,Am as toLensSelect,Qm as toLensWhereSql,li as toPrisma,Rg as toSourceQueries,r$ as toSql,Km as toWhereSql,Nl as validateFieldMaps,Xl as validateNarrowing,Tr as validateRule,Pr as validateRuleInLens,yi as validateValue,Pg as valueClockUnit,zs as walkLensPath};//# sourceMappingURL=index.js.map
16
16
  //# sourceMappingURL=index.js.map