@inixiative/json-rules 1.1.1 → 1.2.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.cjs CHANGED
@@ -1,2 +1,4 @@
1
- 'use strict';var lodash=require('lodash'),m=require('dayjs'),F=require('dayjs/plugin/utc'),M=require('dayjs/plugin/timezone'),V=require('dayjs/plugin/isSameOrBefore'),P=require('dayjs/plugin/isSameOrAfter'),pg=require('pg');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var m__default=/*#__PURE__*/_interopDefault(m);var F__default=/*#__PURE__*/_interopDefault(F);var M__default=/*#__PURE__*/_interopDefault(M);var V__default=/*#__PURE__*/_interopDefault(V);var P__default=/*#__PURE__*/_interopDefault(P);var E=(f=>(f.equals="equals",f.notEquals="notEquals",f.lessThan="lessThan",f.lessThanEquals="lessThanEquals",f.greaterThan="greaterThan",f.greaterThanEquals="greaterThanEquals",f.contains="contains",f.notContains="notContains",f.in="in",f.notIn="notIn",f.matches="matches",f.notMatches="notMatches",f.between="between",f.notBetween="notBetween",f.isEmpty="isEmpty",f.notEmpty="notEmpty",f.exists="exists",f.notExists="notExists",f.startsWith="startsWith",f.endsWith="endsWith",f))(E||{}),b=(u=>(u.all="all",u.any="any",u.none="none",u.atLeast="atLeast",u.atMost="atMost",u.exactly="exactly",u.empty="empty",u.notEmpty="notEmpty",u))(b||{}),v=(u=>(u.before="before",u.after="after",u.onOrBefore="onOrBefore",u.onOrAfter="onOrAfter",u.between="between",u.notBetween="notBetween",u.dayIn="dayIn",u.dayNotIn="dayNotIn",u))(v||{});m__default.default.extend(F__default.default);m__default.default.extend(M__default.default);m__default.default.extend(V__default.default);m__default.default.extend(P__default.default);var q=(e,t,r)=>{let a=lodash.get(t,e.field);if(!a)throw new Error(`${e.field} is null or undefined`);let s=m__default.default(a);if(!s.isValid())throw new Error(`${e.field} is not a valid date: ${a}`);let i=p=>e.error||`${e.field} ${p}`,o=K(e,t,r,s,a),n=o[0],u=o[1];switch(e.dateOperator){case "before":return s.isBefore(n)||i(`must be before ${n.format()}`);case "after":return s.isAfter(n)||i(`must be after ${n.format()}`);case "onOrBefore":return s.isSameOrBefore(n)||i(`must be on or before ${n.format()}`);case "onOrAfter":return s.isSameOrAfter(n)||i(`must be on or after ${n.format()}`);case "between":return s.isSameOrAfter(n)&&s.isSameOrBefore(u)||i(`must be between ${n.format()} and ${u.format()}`);case "notBetween":return s.isBefore(n)||s.isAfter(u)||i(`must not be between ${n.format()} and ${u.format()}`);case "dayIn":if(!Array.isArray(e.value))throw new Error("dayIn operator requires an array of day names");let p=s.format("dddd").toLowerCase(),y=e.value.map(g=>g.toLowerCase());return y.includes(p)||i(`must be on ${y.join(" or ")}`);case "dayNotIn":if(!Array.isArray(e.value))throw new Error("dayNotIn operator requires an array of day names");let W=s.format("dddd").toLowerCase(),B=e.value.map(g=>g.toLowerCase());return !B.includes(W)||i(`must not be on ${B.join(" or ")}`);default:throw new Error("Unknown date operator")}},K=(e,t,r,a,s)=>{if(["between","notBetween"].includes(e.dateOperator)){if(!Array.isArray(e.value)||e.value.length!==2)throw new Error(`${e.dateOperator} operator requires an array of two dates`);let n=A(e.value[0],s),u=A(e.value[1],s);if(!n.isValid())throw new Error(`Invalid start date: ${e.value[0]}`);if(!u.isValid())throw new Error(`Invalid end date: ${e.value[1]}`);return [n,u]}if(["before","after","onOrBefore","onOrAfter"].includes(e.dateOperator)){let n;if(e.value!==void 0)n=e.value;else if(e.path)e.path.startsWith("$.")?n=lodash.get(t,e.path.substring(2)):n=lodash.get(r,e.path);else throw new Error("No value or path specified for date comparison");let u=A(n,s);if(!u.isValid())throw new Error(`Invalid comparison date: ${n}`);return [u,void 0]}return [m__default.default(),void 0]},A=(e,t)=>{let r=String(e);if(r.includes("Z")||r.includes("T")&&(r.includes("+")||r.match(/T.*-\d{2}:/)))return m__default.default(e);let s=String(t),i=0;if(s.includes("+")||s.includes("T")&&s.match(/T.*-\d{2}:/)){let n=s.match(/([+-])(\d{2}):(\d{2})/);n&&(i=(n[1]==="+"?1:-1)*(parseInt(n[2])*60+parseInt(n[3])));}else s.includes("Z")||(i=0);return r.match(/^\d{4}-\d{2}-\d{2}$/)?m__default.default(e+"T00:00:00").subtract(i,"minute"):m__default.default(e).subtract(i,"minute")};var R=(e,t,r)=>{let a=lodash.get(t,e.field),i=!["isEmpty","notEmpty","exists","notExists"].includes(e.operator),o=i?_(e,t,r):void 0,n=u=>e.error||`${e.field} ${u}${i?" "+JSON.stringify(o):""}`;switch(e.operator){case "equals":return a===o||n("must equal");case "notEquals":return a!==o||n("must not equal");case "lessThan":return a<o||n("must be less than");case "lessThanEquals":return a<=o||n("must be less than or equal to");case "greaterThan":return a>o||n("must be greater than");case "greaterThanEquals":return a>=o||n("must be greater than or equal to");case "in":return o?.includes(a)||n("must be one of");case "notIn":return !o?.includes(a)||n("must not be one of");case "contains":return a?.includes(o)||n("must contain");case "notContains":return !a?.includes(o)||n("must not contain");case "matches":return !!a?.match(o)||n("must match pattern");case "notMatches":return !a?.match(o)||n("must not match pattern");case "between":if(!Array.isArray(o)||o.length!==2)throw new Error("between operator requires an array of two values");return a>=o[0]&&a<=o[1]||n("must be between");case "notBetween":if(!Array.isArray(o)||o.length!==2)throw new Error("notBetween operator requires an array of two values");return a<o[0]||a>o[1]||n("must not be between");case "isEmpty":return lodash.isEmpty(a)||n("must be empty");case "notEmpty":return !lodash.isEmpty(a)||n("must not be empty");case "exists":return a!==void 0||n("must exist");case "notExists":return a===void 0||n("must not exist");case "startsWith":return a?.startsWith?.(o)||n("must start with");case "endsWith":return a?.endsWith?.(o)||n("must end with");default:throw new Error("Unknown operator")}},_=(e,t,r)=>{if(e.value!==void 0)return e.value;if(e.path)return e.path.startsWith("$.")?lodash.get(t,e.path.substring(2)):lodash.get(r,e.path);throw new Error("No value or path specified")};var c=(e,t,r=t)=>typeof e=="boolean"?e:"all"in e?Y(e.all,t,r,e.error):"any"in e?Z(e.any,t,r,e.error):"arrayOperator"in e?G(e,t,r):"dateOperator"in e?q(e,t,r):"field"in e?R(e,t,r):"if"in e?Q(e,t,r):false,Y=(e,t,r,a)=>{let s=[];for(let i of e){let o=c(i,t,r);o!==true&&(typeof o=="string"?s.push(o):s.push("false"));}return s.length?a||(s.length===1?s[0]:`All conditions must pass: ${s.join(" AND ")}`):true},Z=(e,t,r,a)=>{let s=[];for(let i of e){let o=c(i,t,r);if(typeof o!="string")return true;s.push(o);}return a||(s.length===1?s[0]:`At least one condition must pass: ${s.join(" OR ")}`)},Q=(e,t,r)=>c(e.if,t,r)===true?c(e.then,t,r):e.else?c(e.else,t,r):true,G=(e,t,r)=>{let a=lodash.get(r,e.field);if(!Array.isArray(a))throw new Error(`${e.field} must be an array`);let s=p=>e.error||`${e.field} ${p}`,i=["all","any","none","atLeast","atMost","exactly"],o=["atLeast","atMost","exactly"];if(i.includes(e.arrayOperator)&&!e.condition)throw new Error(`${e.arrayOperator} requires a condition to check against array elements`);if(o.includes(e.arrayOperator)&&e.count===void 0)throw new Error(`${e.arrayOperator} requires a count`);let n=0,u=0;if(i.includes(e.arrayOperator)){if(!lodash.some(a,lodash.isObject))throw new Error(`${e.field} contains only primitive values. Use 'in' or 'contains' operators instead of array operators for primitive arrays`);let p=a.map(y=>c(e.condition,y,r));n=p.filter(y=>y===true).length,u=p.filter(y=>typeof y=="string").length;}switch(e.arrayOperator){case "empty":return !a.length||s("must be empty");case "notEmpty":return !!a.length||s("must not be empty");case "all":return n===a.length||s(`all elements must match (${u} failed)`);case "any":return !!n||s("at least one element must match");case "none":return !n||s(`no elements should match (${n} matched)`);case "atLeast":return n>=e.count||s(`at least ${e.count} elements must match (${n} matched)`);case "atMost":return n<=e.count||s(`at most ${e.count} elements must match (${n} matched)`);case "exactly":return n===e.count||s(`exactly ${e.count} elements must match (${n} matched)`);default:throw new Error("Unknown array operator")}};var l=(e,t)=>(e.params.push(t),`$${++e.paramIndex}`),$=e=>e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_"),h=e=>{let t=e.split(".");if(t.length===1)return pg.escapeIdentifier(e);let[r,...a]=t;if(a.length===0)return pg.escapeIdentifier(r);let s=n=>`'${n.replace(/'/g,"''")}'`,i=a.slice(0,-1).map(s).join("->"),o=s(a[a.length-1]);return i?`${pg.escapeIdentifier(r)}->${i}->>${o}`:`${pg.escapeIdentifier(r)}->>${o}`},N=e=>{let t={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};return e.map(r=>{let a=t[r.toLowerCase()];if(a===void 0)throw new Error(`Unknown day name: ${r}`);return a})};var I=(e,t)=>{let r=h(e.field);switch(e.operator){case "equals":return e.value===null?`${r} IS NULL`:`${r} = ${l(t,e.value)}`;case "notEquals":return e.value===null?`${r} IS NOT NULL`:`${r} <> ${l(t,e.value)}`;case "lessThan":return `${r} < ${l(t,e.value)}`;case "lessThanEquals":return `${r} <= ${l(t,e.value)}`;case "greaterThan":return `${r} > ${l(t,e.value)}`;case "greaterThanEquals":return `${r} >= ${l(t,e.value)}`;case "in":return !Array.isArray(e.value)||e.value.length===0?"FALSE":`${r} = ANY(${l(t,e.value)})`;case "notIn":return !Array.isArray(e.value)||e.value.length===0?"TRUE":`${r} <> ALL(${l(t,e.value)})`;case "contains":return `${r} LIKE ${l(t,`%${$(String(e.value))}%`)}`;case "notContains":return `${r} NOT LIKE ${l(t,`%${$(String(e.value))}%`)}`;case "startsWith":return `${r} LIKE ${l(t,`${$(String(e.value))}%`)}`;case "endsWith":return `${r} LIKE ${l(t,`%${$(String(e.value))}`)}`;case "matches":return `${r} ~ ${l(t,e.value)}`;case "notMatches":return `${r} !~ ${l(t,e.value)}`;case "between":if(!Array.isArray(e.value)||e.value.length!==2)throw new Error("between operator requires an array of two values");return `${r} BETWEEN ${l(t,e.value[0])} AND ${l(t,e.value[1])}`;case "notBetween":if(!Array.isArray(e.value)||e.value.length!==2)throw new Error("notBetween operator requires an array of two values");return `${r} NOT BETWEEN ${l(t,e.value[0])} AND ${l(t,e.value[1])}`;case "isEmpty":return `(${r} IS NULL OR ${r} = '')`;case "notEmpty":return `(${r} IS NOT NULL AND ${r} <> '')`;case "exists":return `${r} IS NOT NULL`;case "notExists":return `${r} IS NULL`;default:throw new Error(`Unknown operator: ${e.operator}`)}};var D=(e,t)=>{let r=h(e.field);switch(e.dateOperator){case "before":return `${r} < ${l(t,e.value)}`;case "after":return `${r} > ${l(t,e.value)}`;case "onOrBefore":return `${r} <= ${l(t,e.value)}`;case "onOrAfter":return `${r} >= ${l(t,e.value)}`;case "between":if(!Array.isArray(e.value)||e.value.length!==2)throw new Error("between date operator requires an array of two values");return `${r} BETWEEN ${l(t,e.value[0])} AND ${l(t,e.value[1])}`;case "notBetween":if(!Array.isArray(e.value)||e.value.length!==2)throw new Error("notBetween date operator requires an array of two values");return `${r} NOT BETWEEN ${l(t,e.value[0])} AND ${l(t,e.value[1])}`;case "dayIn":{let a=N(e.value);return `EXTRACT(DOW FROM ${r}) = ANY(${l(t,a)})`}case "dayNotIn":{let a=N(e.value);return `EXTRACT(DOW FROM ${r}) <> ALL(${l(t,a)})`}default:throw new Error(`Unknown date operator: ${e.dateOperator}`)}};var C=(e,t)=>{let r=h(e.field),a=e.arrayType==="native",s=a?`array_length(${r}, 1)`:`jsonb_array_length(${r})`;switch(e.arrayOperator){case "empty":return a?`(${r} IS NULL OR ${s} IS NULL)`:`(${r} IS NULL OR ${s} = 0)`;case "notEmpty":return a?`(${r} IS NOT NULL AND ${s} IS NOT NULL)`:`(${r} IS NOT NULL AND ${s} > 0)`;case "all":case "any":case "none":case "atLeast":case "atMost":case "exactly":throw new Error(`Array operator '${e.arrayOperator}' with conditions is not supported in SQL. Use application-level filtering for complex array operations.`);default:throw new Error(`Unknown array operator: ${e.arrayOperator}`)}};var d,O=e=>{d=e;},U=(e,t)=>e.all.length===0?"TRUE":`(${e.all.map(a=>d(a,t)).join(" AND ")})`,j=(e,t)=>e.any.length===0?"FALSE":`(${e.any.map(a=>d(a,t)).join(" OR ")})`,k=(e,t)=>{let r=d(e.if,t),a=d(e.then,t),s=e.else?d(e.else,t):"TRUE";return e.else?`((NOT(${r}) OR ${a}) AND (${r} OR ${s}))`:`(NOT(${r}) OR ${a})`};var L=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";if("all"in e)return U(e,t);if("any"in e)return j(e,t);if("if"in e)return k(e,t);if("arrayOperator"in e)return C(e);if("dateOperator"in e)return D(e,t);if("field"in e)return I(e,t);throw new Error("Unknown condition type")};O(L);var Ce=e=>{let t={params:[],paramIndex:0};return {sql:L(e,t),params:t.params}};exports.ArrayOperator=b;exports.DateOperator=v;exports.Operator=E;exports.check=c;exports.toSql=Ce;//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var lodash=require('lodash'),O=require('dayjs'),Be=require('dayjs/plugin/isSameOrAfter'),Te=require('dayjs/plugin/isSameOrBefore'),Se=require('dayjs/plugin/timezone'),xe=require('dayjs/plugin/utc'),pg=require('pg');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var O__default=/*#__PURE__*/_interopDefault(O);var Be__default=/*#__PURE__*/_interopDefault(Be);var Te__default=/*#__PURE__*/_interopDefault(Te);var Se__default=/*#__PURE__*/_interopDefault(Se);var xe__default=/*#__PURE__*/_interopDefault(xe);var u={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",endsWith:"endsWith"},l={all:"all",any:"any",none:"none",atLeast:"atLeast",atMost:"atMost",exactly:"exactly",empty:"empty",notEmpty:"notEmpty"},f={before:"before",after:"after",onOrBefore:"onOrBefore",onOrAfter:"onOrAfter",between:"between",notBetween:"notBetween",dayIn:"dayIn",dayNotIn:"dayNotIn"};O__default.default.extend(xe__default.default);O__default.default.extend(Se__default.default);O__default.default.extend(Te__default.default);O__default.default.extend(Be__default.default);var J=(e,t,r)=>{let n=lodash.get(t,e.field);if(!n)throw new Error(`${e.field} is null or undefined`);if(!V(n))throw new Error(`${e.field} is not a valid date: ${String(n)}`);let a=O__default.default(n);if(!a.isValid())throw new Error(`${e.field} is not a valid date: ${n}`);let o=d=>e.error||`${e.field} ${d}`,s=Ce(e,t,r,a,n),i=s[0],p=s[1];switch(e.dateOperator){case f.before:return a.isBefore(i)||o(`must be before ${i.format()}`);case f.after:return a.isAfter(i)||o(`must be after ${i.format()}`);case f.onOrBefore:return a.isSameOrBefore(i)||o(`must be on or before ${i.format()}`);case f.onOrAfter:return a.isSameOrAfter(i)||o(`must be on or after ${i.format()}`);case f.between:{if(!p)throw new Error("between operator requires an end date");return a.isSameOrAfter(i)&&a.isSameOrBefore(p)||o(`must be between ${i.format()} and ${p?.format()}`)}case f.notBetween:{if(!p)throw new Error("notBetween operator requires an end date");return a.isBefore(i)||a.isAfter(p)||o(`must not be between ${i.format()} and ${p?.format()}`)}case f.dayIn:{if(!Array.isArray(e.value))throw new Error("dayIn operator requires an array of day names");let d=a.format("dddd").toLowerCase(),y=e.value.map(h=>String(h).toLowerCase());return y.includes(d)||o(`must be on ${y.join(" or ")}`)}case f.dayNotIn:{if(!Array.isArray(e.value))throw new Error("dayNotIn operator requires an array of day names");let d=a.format("dddd").toLowerCase(),y=e.value.map(h=>String(h).toLowerCase());return !y.includes(d)||o(`must not be on ${y.join(" or ")}`)}default:throw new Error("Unknown date operator")}},Ce=(e,t,r,n,a)=>{if([f.between,f.notBetween].includes(e.dateOperator)){if(!Array.isArray(e.value)||e.value.length!==2)throw new Error(`${e.dateOperator} operator requires an array of two dates`);let[i,p]=e.value,d=_(i,a),y=_(p,a);if(!d.isValid())throw new Error(`Invalid start date: ${e.value[0]}`);if(!y.isValid())throw new Error(`Invalid end date: ${e.value[1]}`);let[h,g]=d.isBefore(y)||d.isSame(y)?[d,y]:[y,d];return [h,g]}if([f.before,f.after,f.onOrBefore,f.onOrAfter].includes(e.dateOperator)){let i;if(e.value!==void 0){if(Array.isArray(e.value))throw new Error(`${e.dateOperator} operator requires a single date value`);i=e.value;}else if(e.path)if(e.path.startsWith("$.")){let d=lodash.get(t,e.path.substring(2));i=V(d)?d:void 0;}else {let d=lodash.get(r,e.path);i=V(d)?d:void 0;}else throw new Error("No value or path specified for date comparison");let p=_(i,a);if(!p.isValid())throw new Error(`Invalid comparison date: ${i}`);return [p,void 0]}return [O__default.default(),void 0]},_=(e,t)=>{let r=String(e);if(r.includes("Z")||r.includes("T")&&(r.includes("+")||r.match(/T.*-\d{2}:/)))return O__default.default(e);let a=String(t),o=0;if(a.includes("+")||a.includes("T")&&a.match(/T.*-\d{2}:/)){let i=a.match(/([+-])(\d{2}):(\d{2})/);i&&(o=(i[1]==="+"?1:-1)*(parseInt(i[2],10)*60+parseInt(i[3],10)));}else a.includes("Z")||(o=0);return r.match(/^\d{4}-\d{2}-\d{2}$/)?O__default.default(`${e}T00:00:00`).subtract(o,"minute"):O__default.default(e).subtract(o,"minute")},V=e=>typeof e=="string"||typeof e=="number"||e instanceof Date;var Y=(e,t,r)=>{let n=lodash.get(t,e.field),o=![u.isEmpty,u.notEmpty,u.exists,u.notExists].includes(e.operator),s=o?Fe(e,t,r):void 0,i=p=>e.error||`${e.field} ${p}${o?` ${JSON.stringify(s)}`:""}`;switch(e.operator){case u.equals:return n===s||i("must equal");case u.notEquals:return n!==s||i("must not equal");case u.lessThan:return F(n,s,"lt")||i("must be less than");case u.lessThanEquals:return F(n,s,"lte")||i("must be less than or equal to");case u.greaterThan:return F(n,s,"gt")||i("must be greater than");case u.greaterThanEquals:return F(n,s,"gte")||i("must be greater than or equal to");case u.in:return Array.isArray(s)&&s.includes(n)||i("must be one of");case u.notIn:return !Array.isArray(s)||!s.includes(n)||i("must not be one of");case u.contains:return X(n,s)||i("must contain");case u.notContains:return !X(n,s)||i("must not contain");case u.matches:return G(n)&&(s instanceof RegExp||typeof s=="string")&&!!n.match(s)||i("must match pattern");case u.notMatches:return !G(n)||!(s instanceof RegExp||typeof s=="string")||!n.match(s)||i("must not match pattern");case u.between:{let p=H(s);if(!p)throw new Error("between operator requires an array of two values");if(!A(n))return i("must be between");let d=k(n),[y,h]=p;return d>=y&&d<=h||i("must be between")}case u.notBetween:{let p=H(s);if(!p)throw new Error("notBetween operator requires an array of two values");if(!A(n))return true;let d=k(n),[y,h]=p;return d<y||d>h||i("must not be between")}case u.isEmpty:return lodash.isEmpty(n)||i("must be empty");case u.notEmpty:return !lodash.isEmpty(n)||i("must not be empty");case u.exists:return n!==void 0||i("must exist");case u.notExists:return n===void 0||i("must not exist");case u.startsWith:return typeof n=="string"&&typeof s=="string"&&n.startsWith(s)||i("must start with");case u.endsWith:return typeof n=="string"&&typeof s=="string"&&n.endsWith(s)||i("must end with");default:throw new Error("Unknown operator")}},Fe=(e,t,r)=>{if(e.value!==void 0)return e.value;if(e.path)return e.path.startsWith("$.")?lodash.get(t,e.path.substring(2)):lodash.get(r,e.path);throw new Error("No value or path specified")},A=e=>typeof e=="string"||typeof e=="number"||e instanceof Date,k=e=>e instanceof Date?e.getTime():e,F=(e,t,r)=>{if(!A(e)||!A(t))return false;let n=k(e),a=k(t);switch(r){case "lt":return n<a;case "lte":return n<=a;case "gt":return n>a;case "gte":return n>=a}},G=e=>typeof e=="string",H=e=>{if(!Array.isArray(e)||e.length!==2)return null;let[t,r]=e;if(!A(t)||!A(r))return null;let n=k(t),a=k(r);return n<=a?[n,a]:[a,n]},X=(e,t)=>typeof e=="string"?typeof t=="string"&&e.includes(t):Array.isArray(e)?e.includes(t):false;var v=(e,t,r=t)=>typeof e=="boolean"?e:"all"in e?Ne(e.all,t,r,e.error):"any"in e?Ve(e.any,t,r,e.error):"arrayOperator"in e?Me(e,t,r):"dateOperator"in e?J(e,t,r):"field"in e?Y(e,t,r):"if"in e?Le(e,t,r):false,Ne=(e,t,r,n)=>{let a=[];for(let o of e){let s=v(o,t,r);s!==true&&(typeof s=="string"?a.push(s):a.push("false"));}return a.length?n||(a.length===1?a[0]:`All conditions must pass: ${a.join(" AND ")}`):true},Ve=(e,t,r,n)=>{let a=[];for(let o of e){let s=v(o,t,r);if(s===true)return true;typeof s=="string"&&a.push(s);}return n||(a.length===1?a[0]:`At least one condition must pass: ${a.join(" OR ")}`)},Le=(e,t,r)=>v(e.if,t,r)===true?v(e.then,t,r):e.else?v(e.else,t,r):true,Me=(e,t,r)=>{let n=lodash.get(t,e.field);if(!Array.isArray(n))throw new Error(`${e.field} must be an array`);let a=h=>e.error||`${e.field} ${h}`,o=[l.all,l.any,l.none,l.atLeast,l.atMost,l.exactly],s=[l.atLeast,l.atMost,l.exactly],i=e.condition;if(o.includes(e.arrayOperator)&&!i)throw new Error(`${e.arrayOperator} requires a condition to check against array elements`);let p=e.count;if(s.includes(e.arrayOperator)&&p===void 0)throw new Error(`${e.arrayOperator} requires a count`);let d=0,y=0;if(o.includes(e.arrayOperator)){if(!i)throw new Error(`${e.arrayOperator} requires a condition to check against array elements`);if(!lodash.some(n,lodash.isObject))throw new Error(`${e.field} contains only primitive values. Use 'in' or 'contains' operators instead of array operators for primitive arrays`);let h=n.map(g=>v(i,g,r));d=h.filter(g=>g===true).length,y=h.filter(g=>typeof g=="string").length;}switch(e.arrayOperator){case l.empty:return !n.length||a("must be empty");case l.notEmpty:return !!n.length||a("must not be empty");case l.all:return d===n.length||a(`all elements must match (${y} failed)`);case l.any:return !!d||a("at least one element must match");case l.none:return !d||a(`no elements should match (${d} matched)`);case l.atLeast:if(p===void 0)throw new Error(`${e.arrayOperator} requires a count`);return d>=p||a(`at least ${p} elements must match (${d} matched)`);case l.atMost:if(p===void 0)throw new Error(`${e.arrayOperator} requires a count`);return d<=p||a(`at most ${p} elements must match (${d} matched)`);case l.exactly:if(p===void 0)throw new Error(`${e.arrayOperator} requires a count`);return d===p||a(`exactly ${p} elements must match (${d} matched)`);default:throw new Error("Unknown array operator")}};var Z=(e,t,r,n)=>{let{map:a,model:o}=t,s=a[o]?.fields[e.field];if(!s||s.kind!=="object")throw new Error(`Field '${e.field}' is not a relation in model '${o}'. Count operators require a relation field.`);if(!s.isList)throw new Error(`Field '${e.field}' is not a list relation in model '${o}'. Count operators only apply to one-to-many or many-to-many relations.`);let i=s.type,p,d;if(s.fromFields&&s.fromFields.length>0){if(s.fromFields.length>1)throw new Error(`Count operators (atLeast/atMost/exactly) do not support composite FK relations ('${o}.${e.field}'). Use prisma.$queryRaw for composite FK count filtering.`);p=s.toFields?.[0]??"id",d=s.fromFields[0];}else {let x=We(a,i,o,s.relationName);if(!x){let qe=Object.values(a[i]?.fields??{}).some(C=>C.kind==="object"&&C.type===o&&C.isList&&!C.fromFields?.length);throw new Error(qe?`'${o}.${e.field}' is an implicit many-to-many relation. Count operators require an explicit join model with a FK \u2014 convert to an explicit @relation or use prisma.$queryRaw.`:`Cannot determine FK relationship between '${o}' and '${i}'. Ensure the FieldMap contains both sides of the relation.`)}if((x.fromFields?.length??0)>1)throw new Error(`Count operators (atLeast/atMost/exactly) do not support composite FK relations ('${o}.${e.field}'). Use prisma.$queryRaw for composite FK count filtering.`);p=x.fromFields?.[0]??"",d=x.toFields?.[0]??"";}let y=e.condition?n(e.condition,{...t,model:i},r):{},h=e.count??1,g=je(e.arrayOperator,h),S={operation:"groupBy",model:i,args:{by:[p],where:y,having:g},extract:p},ve=r.steps.length;r.steps.push(S);let De={__step:ve};return {[d]:{in:De}}},We=(e,t,r,n)=>{let a=e[t];if(!a)return null;for(let o of Object.values(a.fields))if(o.kind==="object"&&o.type===r&&(o.fromFields?.length??0)>0&&(o.toFields?.length??0)>0&&(n===void 0||o.relationName===n))return o;return null},je=(e,t)=>{switch(e){case l.atLeast:return {_count:{_all:{gte:t}}};case l.atMost:return {_count:{_all:{lte:t}}};case l.exactly:return {_count:{_all:{equals:t}}};default:throw new Error("unreachable")}};var b=(e,t)=>{let r=e.split("."),n=t;for(let a=r.length-1;a>=0;a--)n={[r[a]]:n};return n};var B,ee=e=>{B=e;},re=(e,t,r)=>{if(e.arrayOperator===l.atLeast||e.arrayOperator===l.atMost||e.arrayOperator===l.exactly){if(t?.map&&t?.model&&r)return Z(e,t,r,B);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.`)}let n=Ue(e,t,r);return b(e.field,n)},Ue=(e,t,r)=>{switch(e.arrayOperator){case l.all:if(!e.condition)throw new Error("ArrayOperator 'all' requires a condition");return {every:B(e.condition,t,r)};case l.any:if(!e.condition)throw new Error("ArrayOperator 'any' requires a condition");return {some:B(e.condition,t,r)};case l.none:if(!e.condition)throw new Error("ArrayOperator 'none' requires a condition");return {none:B(e.condition,t,r)};case l.empty:return {none:{}};case l.notEmpty:return {some:{}};default:throw new Error(`Unknown array operator: ${e.arrayOperator}`)}};var ae=(e,t)=>{let r=Je(e,t);return b(e.field,r)},ze=(e,t)=>{if(e.value!==void 0)return e.value;if(e.path){if(e.path.startsWith("$."))throw new Error(`Prisma WHERE has no column-to-column date comparison for path '${e.path}'. Use prisma.$queryRaw for field-to-field filtering.`);if(!t?.context)throw new Error(`options.context is required to resolve date path '${e.path}'. Pass context when calling toPrisma().`);return lodash.get(t.context,e.path)}},Je=(e,t)=>{let r=()=>ze(e,t);switch(e.dateOperator){case f.before:return {lt:r()};case f.after:return {gt:r()};case f.onOrBefore:return {lte:r()};case f.onOrAfter:return {gte:r()};case f.between:{let n=r();if(!Array.isArray(n)||n.length!==2)throw new Error("between date operator requires an array of two values");let[a,o]=te(n);return {gte:a,lte:o}}case f.notBetween:{let n=r();if(!Array.isArray(n)||n.length!==2)throw new Error("notBetween date operator requires an array of two values");let[a,o]=te(n);return {NOT:{gte:a,lte:o}}}case f.dayIn:throw new Error("DateOperator 'dayIn' has no Prisma equivalent. Use prisma.$queryRaw with EXTRACT(DOW FROM ...) for day-of-week filtering.");case f.dayNotIn:throw new Error("DateOperator 'dayNotIn' has no Prisma equivalent. Use prisma.$queryRaw with EXTRACT(DOW FROM ...) for day-of-week filtering.");default:throw new Error(`Unknown date operator: ${e.dateOperator}`)}},te=e=>{let[t,r]=e;return Qe(t,r)<=0?[t,r]:[r,t]},Qe=(e,t)=>{let r=ne(e),n=ne(t);return r<n?-1:r>n?1:0},ne=e=>e instanceof Date?e.getTime():typeof e=="number"||typeof e=="string"?e:String(e);var oe=(e,t,r)=>{let n=e.split("."),a=r;for(let o=0;o<n.length;o++){let s=t[a];if(!s)return {kind:"fallback"};let i=s.fields[n[o]];if(!i)return {kind:"fallback"};if(i.kind==="scalar"&&i.type==="Json"&&o<n.length-1)return {kind:"json-path",stopIndex:o+1,jsonPath:n.slice(o+1)};if(i.kind==="object"){if(!t[i.type])return {kind:"fallback"};a=i.type;continue}return {kind:"direct"}}return {kind:"direct"}};var se=(e,t)=>{let r=Xe(e,t);return Ye(e.field,r,t)},He=(e,t)=>{if(e.value!==void 0)return e.value;if(e.path){if(e.path.startsWith("$."))throw new Error(`Prisma WHERE has no column-to-column comparison for path '${e.path}'. Use prisma.$queryRaw for field-to-field filtering.`);if(!t?.context)throw new Error(`options.context is required to resolve path '${e.path}'. Pass context when calling toPrisma().`);return lodash.get(t.context,e.path)}throw new Error(`Rule for field '${e.field}' has neither value nor path set`)},Xe=(e,t)=>{let r=()=>He(e,t);switch(e.operator){case u.equals:return {equals:r()??null};case u.notEquals:return {not:r()??null};case u.lessThan:return {lt:r()};case u.lessThanEquals:return {lte:r()};case u.greaterThan:return {gt:r()};case u.greaterThanEquals:return {gte:r()};case u.in:return {in:r()};case u.notIn:return {notIn:r()};case u.contains:return {contains:r()};case u.notContains:return {not:{contains:r()}};case u.startsWith:return {startsWith:r()};case u.endsWith:return {endsWith:r()};case u.matches:throw new Error("Operator 'matches' has no Prisma equivalent. Use prisma.$queryRaw for regex filtering.");case u.notMatches:throw new Error("Operator 'notMatches' has no Prisma equivalent. Use prisma.$queryRaw for regex filtering.");case u.between:{let n=r();if(!Array.isArray(n)||n.length!==2)throw new Error("between operator requires an array of two values");let[a,o]=n[0]<=n[1]?n:[n[1],n[0]];return {gte:a,lte:o}}case u.notBetween:{let n=r();if(!Array.isArray(n)||n.length!==2)throw new Error("notBetween operator requires an array of two values");let[a,o]=n[0]<=n[1]?n:[n[1],n[0]];return {NOT:{gte:a,lte:o}}}case u.isEmpty:return {in:[null,""]};case u.notEmpty:return {notIn:[null,""]};case u.exists:return {not:null};case u.notExists:return {equals:null};default:throw new Error(`Unknown operator: ${e.operator}`)}},Ye=(e,t,r)=>{if(!r?.map||!r?.model)return b(e,t);let n=oe(e,r.map,r.model),a=e.split(".");switch(n.kind){case "fallback":case "direct":return b(e,t);case "json-path":{let o={path:n.jsonPath,...t},s=a.slice(0,n.stopIndex).join(".");return b(s,o)}}};var D,ie=e=>{D=e;},ue=(e,t,r)=>e.all.length===0?{}:{AND:e.all.map(n=>D(n,t,r))},le=(e,t,r)=>e.any.length===0?{AND:[{id:null},{id:{not:null}}]}:{OR:e.any.map(n=>D(n,t,r))},pe=(e,t,r)=>{let n=D(e.if,t,r),a={NOT:n},o=D(e.then,t,r);if(e.else){let s=D(e.else,t,r);return {AND:[{OR:[a,o]},{OR:[n,s]}]}}return {OR:[a,o]}};var P=(e,t,r)=>{if(typeof e=="boolean"){if(e)return {};throw new Error("Boolean 'false' has no direct Prisma WHERE equivalent. toPrisma is designed for structured Rule conditions.")}if("all"in e)return ue(e,t,r);if("any"in e)return le(e,t,r);if("if"in e)return pe(e,t,r);if("arrayOperator"in e)return re(e,t,r);if("dateOperator"in e)return ae(e,t);if("field"in e)return se(e,t);throw new Error("Unknown condition type")};ie(P);ee(P);var Ze=async(e,t)=>{let r=e.steps.filter(o=>o.operation==="groupBy"),n=e.steps.find(o=>o.operation==="where");if(!n)throw new Error("executePrismaQueryPlan: result has no where step");let a=[];for(let o of r){let s=o.model.charAt(0).toLowerCase()+o.model.slice(1),i=t[s];if(!i)throw new Error(`executePrismaQueryPlan: no delegate for model '${o.model}'. Ensure prismaDelegate has a key '${s}'.`);let p=await i[o.operation](o.args);a.push(p.map(d=>d[o.extract]));}return M(n.where,a)},M=(e,t)=>{if(e==null)return e;if(Array.isArray(e))return e.map(r=>M(r,t));if(typeof e=="object"){let r=e;if("__step"in r&&typeof r.__step=="number"){let a=r.__step;if(a>=t.length)throw new Error(`Step ref __step: ${a} out of range (${t.length} steps executed)`);return t[a]}let n={};for(let[a,o]of Object.entries(r))n[a]=M(o,t);return n}return e};var pt=(e,t)=>{let r={steps:[]},n=P(e,t,r);return {steps:[...r.steps,{operation:"where",where:n}]}};var T=e=>e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_"),w=e=>{let t=e.split(".");if(t.length===1)return pg.escapeIdentifier(e);let[r,...n]=t;return n.length===0?pg.escapeIdentifier(r):ce(pg.escapeIdentifier(r),n)},fe=(e,t)=>{let r=e.split(".");if(r.length===1)return `${pg.escapeIdentifier(t)}.${pg.escapeIdentifier(e)}`;let[n,...a]=r;return ce(`${pg.escapeIdentifier(t)}.${pg.escapeIdentifier(n)}`,a)},de=e=>`'${e.replace(/'/g,"''")}'`,ce=(e,t)=>{if(t.length===0)return e;let r=t.slice(0,-1).map(de).join("->"),n=de(t[t.length-1]);return r?`${e}->${r}->>${n}`:`${e}->>${n}`};var me=(e,t)=>{let r=w(e.field),n=e.arrayType==="native",a=n?`array_length(${r}, 1)`:`jsonb_array_length(${r})`;switch(e.arrayOperator){case l.empty:return n?`(${r} IS NULL OR ${a} IS NULL)`:`(${r} IS NULL OR ${a} = 0)`;case l.notEmpty:return n?`(${r} IS NOT NULL AND ${a} IS NOT NULL)`:`(${r} IS NOT NULL AND ${a} > 0)`;case l.all:case l.any:case l.none:case l.atLeast:case l.atMost:case l.exactly:throw new Error(`Array operator '${e.arrayOperator}' with conditions is not supported in SQL. Use application-level filtering for complex array operations.`);default:throw new Error(`Unknown array operator: ${e.arrayOperator}`)}};var W=e=>{let t={sunday:0,monday:1,tuesday:2,wednesday:3,thursday:4,friday:5,saturday:6};return e.map(r=>{let n=t[r.toLowerCase()];if(n===void 0)throw new Error(`Unknown day name: ${r}`);return n})};var I=(e,t)=>{if(!t.map||!t.currentModel||!t.currentAlias)return w(e);let r=e.split("."),n=t.currentModel,a=t.currentAlias;for(let o=0;o<r.length;o++){let s=t.map[n];if(!s)return w(e);let i=s.fields[r[o]];if(!i)return w(e);if(i.kind==="object"){let d=`${a}.${r[o]}`,y=t.joinRegistry?.get(d),h;if(y)h=y;else {let g=t.joinCounter;if(!g)return w(e);h=`t${++g.n}`;let S=er(t.map,n,a,i,h);if(!S)return w(e);t.joins?.push(S),t.joinRegistry?.set(d,h);}n=i.type,a=h;continue}let p=r.slice(o);return fe(p.join("."),a)}return w(e)},er=(e,t,r,n,a)=>{let o=n.type,s=e[o]?.dbName??o,i;if(n.fromFields&&n.fromFields.length>0&&n.toFields&&n.toFields.length>0)i=n.fromFields.map((p,d)=>`${pg.escapeIdentifier(a)}.${pg.escapeIdentifier(n.toFields?.[d]??"")} = ${pg.escapeIdentifier(r)}.${pg.escapeIdentifier(p)}`).join(" AND ");else {let p=rr(e,o,t,n.relationName);if(!p)return null;i=(p.fromFields??[]).map((d,y)=>`${pg.escapeIdentifier(a)}.${pg.escapeIdentifier(d)} = ${pg.escapeIdentifier(r)}.${pg.escapeIdentifier(p.toFields?.[y]??"")}`).join(" AND ");}return `LEFT JOIN ${pg.escapeIdentifier(s)} AS ${pg.escapeIdentifier(a)} ON ${i}`},rr=(e,t,r,n)=>{let a=e[t];if(!a)return null;for(let o of Object.values(a.fields))if(o.kind==="object"&&o.type===r&&(o.fromFields?.length??0)>0&&(o.toFields?.length??0)>0&&(n===void 0||o.relationName===n))return o;return null};var m=(e,t)=>(e.params.push(t),`$${++e.paramIndex}`);var ge=(e,t)=>{let r=I(e.field,t),n=ar(e,t),a=n.type==="value"?n.value:void 0,o=n.type==="column"?n.sql:void 0;switch(e.dateOperator){case f.before:return o!==void 0?`${r} < ${o}`:`${r} < ${m(t,a)}`;case f.after:return o!==void 0?`${r} > ${o}`:`${r} > ${m(t,a)}`;case f.onOrBefore:return o!==void 0?`${r} <= ${o}`:`${r} <= ${m(t,a)}`;case f.onOrAfter:return o!==void 0?`${r} >= ${o}`:`${r} >= ${m(t,a)}`;case f.between:{let s=a;if(!Array.isArray(s)||s.length!==2)throw new Error("between date operator requires an array of two values");let[i,p]=he(s);return `${r} BETWEEN ${m(t,i)} AND ${m(t,p)}`}case f.notBetween:{let s=a;if(!Array.isArray(s)||s.length!==2)throw new Error("notBetween date operator requires an array of two values");let[i,p]=he(s);return `${r} NOT BETWEEN ${m(t,i)} AND ${m(t,p)}`}case f.dayIn:{if(!Array.isArray(e.value))throw new Error("dayIn operator requires an array of day names");let s=W(e.value.map(i=>String(i)));return `EXTRACT(DOW FROM ${r}) = ANY(${m(t,s)})`}case f.dayNotIn:{if(!Array.isArray(e.value))throw new Error("dayNotIn operator requires an array of day names");let s=W(e.value.map(i=>String(i)));return `EXTRACT(DOW FROM ${r}) <> ALL(${m(t,s)})`}default:throw new Error(`Unknown date operator: ${e.dateOperator}`)}},he=e=>{let[t,r]=e;return nr(t,r)<=0?[t,r]:[r,t]},nr=(e,t)=>{let r=we(e),n=we(t);return r<n?-1:r>n?1:0},we=e=>e instanceof Date?e.getTime():typeof e=="number"||typeof e=="string"?e:String(e),ar=(e,t)=>{if(e.value!==void 0)return {type:"value",value:e.value};if(e.path){if(e.path.startsWith("$.")){let r=e.path.substring(2);return {type:"column",sql:t.currentAlias?`${pg.escapeIdentifier(t.currentAlias)}.${pg.escapeIdentifier(r)}`:w(r)}}if(!t.context)throw new Error(`BuilderState.context is required to resolve date path '${e.path}'. Pass context in options when calling toSql().`);return {type:"value",value:lodash.get(t.context,e.path)}}return {type:"value",value:void 0}};var Oe=(e,t)=>{let r=I(e.field,t),n=sr(e,t),a=n.type==="value"?n.value:void 0,o=n.type==="column"?n.sql:void 0;switch(e.operator){case u.equals:return o!==void 0?`${r} = ${o}`:a===null?`${r} IS NULL`:`${r} = ${m(t,a)}`;case u.notEquals:return o!==void 0?`${r} <> ${o}`:a===null?`${r} IS NOT NULL`:`${r} <> ${m(t,a)}`;case u.lessThan:return o!==void 0?`${r} < ${o}`:`${r} < ${m(t,a)}`;case u.lessThanEquals:return o!==void 0?`${r} <= ${o}`:`${r} <= ${m(t,a)}`;case u.greaterThan:return o!==void 0?`${r} > ${o}`:`${r} > ${m(t,a)}`;case u.greaterThanEquals:return o!==void 0?`${r} >= ${o}`:`${r} >= ${m(t,a)}`;case u.in:return !Array.isArray(a)||a.length===0?"FALSE":`${r} = ANY(${m(t,a)})`;case u.notIn:return !Array.isArray(a)||a.length===0?"TRUE":`${r} <> ALL(${m(t,a)})`;case u.contains:return `${r} LIKE ${m(t,`%${T(String(a))}%`)}`;case u.notContains:return `${r} NOT LIKE ${m(t,`%${T(String(a))}%`)}`;case u.startsWith:return `${r} LIKE ${m(t,`${T(String(a))}%`)}`;case u.endsWith:return `${r} LIKE ${m(t,`%${T(String(a))}`)}`;case u.matches:return `${r} ~ ${m(t,a)}`;case u.notMatches:return `${r} !~ ${m(t,a)}`;case u.between:{let s=a;if(!Array.isArray(s)||s.length!==2)throw new Error("between operator requires an array of two values");let[i,p]=s[0]<=s[1]?s:[s[1],s[0]];return `${r} BETWEEN ${m(t,i)} AND ${m(t,p)}`}case u.notBetween:{let s=a;if(!Array.isArray(s)||s.length!==2)throw new Error("notBetween operator requires an array of two values");let[i,p]=s[0]<=s[1]?s:[s[1],s[0]];return `${r} NOT BETWEEN ${m(t,i)} AND ${m(t,p)}`}case u.isEmpty:return `(${r} IS NULL OR ${r} = '')`;case u.notEmpty:return `(${r} IS NOT NULL AND ${r} <> '')`;case u.exists:return `${r} IS NOT NULL`;case u.notExists:return `${r} IS NULL`;default:throw new Error(`Unknown operator: ${e.operator}`)}},sr=(e,t)=>{if(e.value!==void 0)return {type:"value",value:e.value};if(e.path){if(e.path.startsWith("$.")){let r=e.path.substring(2);return {type:"column",sql:t.currentAlias?`${pg.escapeIdentifier(t.currentAlias)}.${pg.escapeIdentifier(r)}`:w(r)}}if(!t.context)throw new Error(`BuilderState.context is required to resolve path '${e.path}'. Pass context in options when calling toSql().`);return {type:"value",value:lodash.get(t.context,e.path)}}return {type:"value",value:void 0}};var q,be=e=>{q=e;},Re=(e,t)=>e.all.length===0?"TRUE":`(${e.all.map(n=>q(n,t)).join(" AND ")})`,Ee=(e,t)=>e.any.length===0?"FALSE":`(${e.any.map(n=>q(n,t)).join(" OR ")})`,Ae=(e,t)=>{let r=q(e.if,t),n=q(e.then,t),a=e.else?q(e.else,t):"TRUE";return e.else?`((NOT(${r}) OR ${n}) AND (${r} OR ${a}))`:`(NOT(${r}) OR ${n})`};var j=(e,t)=>{if(typeof e=="boolean")return e?"TRUE":"FALSE";if("all"in e)return Re(e,t);if("any"in e)return Ee(e,t);if("if"in e)return Ae(e,t);if("arrayOperator"in e)return me(e);if("dateOperator"in e)return ge(e,t);if("field"in e)return Oe(e,t);throw new Error("Unknown condition type")};be(j);var Kt=(e,t)=>{let r=!!(t?.map&&t?.model),n=t?.alias??(r?"t0":void 0),a={params:[],paramIndex:0,context:t?.context,map:t?.map,currentModel:t?.model,currentAlias:n,joinCounter:r?{n:0}:void 0,joins:r?[]:void 0,joinRegistry:r?new Map:void 0};return {sql:j(e,a),params:a.params,joins:a.joins??[]}};var ir=new Set(Object.values(u)),ur=new Set(Object.values(l)),lr=new Set(Object.values(f)),pr=(e,t={})=>{let r={target:t.target??"check",errors:[]};return E(e,"$",r),{ok:r.errors.length===0,errors:r.errors}},Qt=(e,t={})=>{let r=pr(e,t);if(r.ok)return;let n=r.errors.map(a=>`${a.path}: ${a.message}`).join(`
2
+ `);throw new Error(`Invalid rule:
3
+ ${n}`)},E=(e,t,r)=>{if(typeof e=="boolean"){r.target==="toPrisma"&&e===false&&c(r,t,"boolean_false_not_supported","Boolean 'false' is not supported by toPrisma()");return}if(!gr(e)){c(r,t,"invalid_condition","Condition must be a boolean or object");return}let n=dr(e);if(!n){c(r,t,"ambiguous_condition","Condition must be exactly one of: field rule, array rule, date rule, all, any, or if/then[/else]");return}switch(n){case "all":ke(e.all,`${t}.all`,r);break;case "any":ke(e.any,`${t}.any`,r);break;case "if":E(e.if,`${t}.if`,r),E(e.then,`${t}.then`,r),"else"in e&&e.else!==void 0&&E(e.else,`${t}.else`,r);break;case "field":fr(e,t,r);break;case "array":cr(e,t,r);break;case "date":mr(e,t,r);break}},dr=e=>{let t=[];"all"in e&&t.push("all"),"any"in e&&t.push("any"),("if"in e||"then"in e||"else"in e)&&t.push("if"),"arrayOperator"in e&&t.push("array"),"dateOperator"in e&&t.push("date"),"operator"in e&&t.push("field");let r=Array.from(new Set(t));return r.length!==1?null:r[0]},ke=(e,t,r)=>{if(!Array.isArray(e)){c(r,t,"logical_array_required","Logical operator requires an array of conditions");return}e.forEach((n,a)=>{E(n,`${t}[${a}]`,r);});},fr=(e,t,r)=>{if(typeof e.field!="string"&&c(r,`${t}.field`,"field_required","Field rule requires a string field"),typeof e.operator!="string"||!ir.has(e.operator)){c(r,`${t}.operator`,"invalid_operator","Unknown field operator");return}let n=e.operator;if(r.target==="toPrisma"&&((n===u.matches||n===u.notMatches)&&"operator"in e&&c(r,`${t}.operator`,"unsupported_prisma_operator",`Operator '${n}' is not supported by toPrisma()`),typeof e.path=="string"&&e.path.startsWith("$.")&&c(r,`${t}.path`,"unsupported_prisma_path",`Path '${e.path}' is not supported by toPrisma()`)),hr(n)){yr(e,t,r);return}if(!U(e,t,r)||"path"in e&&typeof e.path=="string")return;let a=e.value;switch(n){case u.lessThan:case u.lessThanEquals:case u.greaterThan:case u.greaterThanEquals:K(a)||c(r,`${t}.value`,"invalid_ordered_value",`Operator '${n}' requires a string, number, or Date value`);break;case u.in:case u.notIn:Array.isArray(a)||c(r,`${t}.value`,"invalid_membership_value",`Operator '${n}' requires an array value`);break;case u.matches:case u.notMatches:typeof a=="string"||a instanceof RegExp||c(r,`${t}.value`,"invalid_pattern_value",`Operator '${n}' requires a string or RegExp value`);break;case u.startsWith:case u.endsWith:typeof a!="string"&&c(r,`${t}.value`,"invalid_string_value",`Operator '${n}' requires a string value`);break;case u.between:case u.notBetween:$r(a)||c(r,`${t}.value`,"invalid_range_value",`Operator '${n}' requires a two-item range`);break}},cr=(e,t,r)=>{if(typeof e.field!="string"&&c(r,`${t}.field`,"field_required","Array rule requires a string field"),typeof e.arrayOperator!="string"||!ur.has(e.arrayOperator)){c(r,`${t}.arrayOperator`,"invalid_array_operator","Unknown array operator");return}let n=e.arrayOperator;switch(r.target==="toSql"&&wr(n)&&c(r,`${t}.arrayOperator`,"unsupported_sql_array_operator",`Array operator '${n}' is not supported by toSql()`),n){case l.empty:case l.notEmpty:"condition"in e&&e.condition!==void 0&&c(r,`${t}.condition`,"unexpected_condition",`Array operator '${n}' does not accept condition`),"count"in e&&e.count!==void 0&&c(r,`${t}.count`,"unexpected_count",`Array operator '${n}' does not accept count`);break;case l.all:case l.any:case l.none:!("condition"in e)||e.condition===void 0?c(r,`${t}.condition`,"missing_condition",`Array operator '${n}' requires condition`):E(e.condition,`${t}.condition`,r),"count"in e&&e.count!==void 0&&c(r,`${t}.count`,"unexpected_count",`Array operator '${n}' does not accept count`);break;case l.atLeast:case l.atMost:case l.exactly:r.target!=="toPrisma"&&typeof e.count!="number"?c(r,`${t}.count`,"missing_count",`Array operator '${n}' requires count`):"count"in e&&e.count!==void 0&&typeof e.count!="number"&&c(r,`${t}.count`,"invalid_count","count must be a number"),r.target==="check"&&(!("condition"in e)||e.condition===void 0)?c(r,`${t}.condition`,"missing_condition",`Array operator '${n}' requires condition for check()`):"condition"in e&&e.condition!==void 0&&E(e.condition,`${t}.condition`,r);break}},mr=(e,t,r)=>{if(typeof e.field!="string"&&c(r,`${t}.field`,"field_required","Date rule requires a string field"),typeof e.dateOperator!="string"||!lr.has(e.dateOperator)){c(r,`${t}.dateOperator`,"invalid_date_operator","Unknown date operator");return}let n=e.dateOperator;switch(r.target==="toPrisma"&&((n===f.dayIn||n===f.dayNotIn)&&"dateOperator"in e&&c(r,`${t}.dateOperator`,"unsupported_prisma_date_operator",`Date operator '${n}' is not supported by toPrisma()`),typeof e.path=="string"&&e.path.startsWith("$.")&&c(r,`${t}.path`,"unsupported_prisma_path",`Path '${e.path}' is not supported by toPrisma()`)),n){case f.dayIn:case f.dayNotIn:(!Array.isArray(e.value)||!e.value.every(a=>typeof a=="string"))&&c(r,`${t}.value`,"invalid_day_list",`Date operator '${n}' requires an array of day names`),"path"in e&&e.path!==void 0&&c(r,`${t}.path`,"unexpected_path",`Date operator '${n}' does not accept path`);return;case f.between:case f.notBetween:if(!U(e,t,r)||"path"in e&&typeof e.path=="string")return;Or(e.value)||c(r,`${t}.value`,"invalid_date_range",`Date operator '${n}' requires a two-item date range`);return;default:if(!U(e,t,r)||"path"in e&&typeof e.path=="string")return;z(e.value)||c(r,`${t}.value`,"invalid_date_value",`Date operator '${n}' requires a date-like value`);}},U=(e,t,r)=>{let n="value"in e&&e.value!==void 0,a=typeof e.path=="string";return n&&a?(c(r,t,"ambiguous_value_source","Rule cannot define both value and path"),false):!n&&!a?(c(r,t,"missing_value_source","Rule requires either value or path"),false):true},yr=(e,t,r)=>{"value"in e&&e.value!==void 0&&c(r,`${t}.value`,"unexpected_value","Rule does not accept value"),"path"in e&&e.path!==void 0&&c(r,`${t}.path`,"unexpected_path","Rule does not accept path");},hr=e=>e===u.isEmpty||e===u.notEmpty||e===u.exists||e===u.notExists,wr=e=>e===l.all||e===l.any||e===l.none||e===l.atLeast||e===l.atMost||e===l.exactly,gr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),K=e=>typeof e=="string"||typeof e=="number"||e instanceof Date,$r=e=>Array.isArray(e)&&e.length===2&&K(e[0])&&K(e[1]),z=e=>typeof e=="string"||typeof e=="number"||e instanceof Date,Or=e=>Array.isArray(e)&&e.length===2&&z(e[0])&&z(e[1]),c=(e,t,r,n)=>{e.errors.push({path:t,code:r,message:n});};exports.ArrayOperator=l;exports.DateOperator=f;exports.Operator=u;exports.assertValidRule=Qt;exports.check=v;exports.executePrismaQueryPlan=Ze;exports.toPrisma=pt;exports.toSql=Kt;exports.validateRule=pr;//# sourceMappingURL=index.cjs.map
2
4
  //# sourceMappingURL=index.cjs.map