UNPKG

@react-querybuilder/core

Version:

React Query Builder component for constructing queries and filters, with utilities for executing them in various database and evaluation contexts

1 lines 70.6 kB
import{produce as e}from"immer";import{numericQuantity as t,numericRegex as n}from"numeric-quantity";const r=`~`,i=`------`,a=`~`,o=i,s=i,c=`~`,l=i,u=i,d=`~`,f=i,p=i,m={fields:{title:`Field`,placeholderName:`~`,placeholderLabel:o,placeholderGroupLabel:s},operators:{title:`Operator`,placeholderName:`~`,placeholderLabel:l,placeholderGroupLabel:u},values:{title:`Values`,placeholderName:`~`,placeholderLabel:f,placeholderGroupLabel:p},matchMode:{title:`Match mode`},matchThreshold:{title:`Match threshold`},value:{title:`Value`},removeRule:{label:`⨯`,title:`Remove rule`},removeGroup:{label:`⨯`,title:`Remove group`},addRule:{label:`+ Rule`,title:`Add rule`},addGroup:{label:`+ Group`,title:`Add group`},combinators:{title:`Combinator`},notToggle:{label:`Not`,title:`Invert this group`},cloneRule:{label:`⧉`,title:`Clone rule`},cloneRuleGroup:{label:`⧉`,title:`Clone group`},shiftActionUp:{label:`˄`,title:`Shift up`},shiftActionDown:{label:`˅`,title:`Shift down`},dragHandle:{label:`⁞⁞`,title:`Drag handle`},lockRule:{label:`🔓`,title:`Lock rule`},lockGroup:{label:`🔓`,title:`Lock group`},lockRuleDisabled:{label:`🔒`,title:`Unlock rule`},lockGroupDisabled:{label:`🔒`,title:`Unlock group`},muteRule:{label:`🔊`,title:`Mute rule`},muteGroup:{label:`🔊`,title:`Mute group`},unmuteRule:{label:`🔇`,title:`Unmute rule`},unmuteGroup:{label:`🔇`,title:`Unmute group`},valueSourceSelector:{title:`Value source`}},h=`,`,g={"=":`=`,"!=":`!=`,"<":`<`,">":`>`,"<=":`<=`,">=":`>=`,contains:`contains`,beginsWith:`begins with`,endsWith:`ends with`,doesNotContain:`does not contain`,doesNotBeginWith:`does not begin with`,doesNotEndWith:`does not end with`,null:`is null`,notNull:`is not null`,in:`in`,notIn:`not in`,between:`between`,notBetween:`not between`},_={and:`AND`,or:`OR`,xor:`XOR`},v=[{name:`=`,value:`=`,label:`=`},{name:`!=`,value:`!=`,label:`!=`},{name:`<`,value:`<`,label:`<`},{name:`>`,value:`>`,label:`>`},{name:`<=`,value:`<=`,label:`<=`},{name:`>=`,value:`>=`,label:`>=`},{name:`contains`,value:`contains`,label:`contains`},{name:`beginsWith`,value:`beginsWith`,label:`begins with`},{name:`endsWith`,value:`endsWith`,label:`ends with`},{name:`doesNotContain`,value:`doesNotContain`,label:`does not contain`},{name:`doesNotBeginWith`,value:`doesNotBeginWith`,label:`does not begin with`},{name:`doesNotEndWith`,value:`doesNotEndWith`,label:`does not end with`},{name:`null`,value:`null`,label:`is null`},{name:`notNull`,value:`notNull`,label:`is not null`},{name:`in`,value:`in`,label:`in`},{name:`notIn`,value:`notIn`,label:`not in`},{name:`between`,value:`between`,label:`between`},{name:`notBetween`,value:`notBetween`,label:`not between`}],y={"=":`!=`,"!=":`=`,"<":`>=`,"<=":`>`,">":`<=`,">=":`<`,beginsWith:`doesNotBeginWith`,doesNotBeginWith:`beginsWith`,endsWith:`doesNotEndWith`,doesNotEndWith:`endsWith`,contains:`doesNotContain`,doesNotContain:`contains`,between:`notBetween`,notBetween:`between`,in:`notIn`,notIn:`in`,notNull:`null`,null:`notNull`},b=[{name:`and`,value:`and`,label:`AND`},{name:`or`,value:`or`,label:`OR`}],x=[...b,{name:`xor`,value:`xor`,label:`XOR`}],S=[{name:`all`,value:`all`,label:`all`},{name:`some`,value:`some`,label:`some`},{name:`none`,value:`none`,label:`none`},{name:`atLeast`,value:`atLeast`,label:`at least`},{name:`atMost`,value:`atMost`,label:`at most`},{name:`exactly`,value:`exactly`,label:`exactly`}],C={queryBuilder:`queryBuilder`,ruleGroup:`ruleGroup`,header:`ruleGroup-header`,body:`ruleGroup-body`,combinators:`ruleGroup-combinators`,addRule:`ruleGroup-addRule`,addGroup:`ruleGroup-addGroup`,cloneRule:`rule-cloneRule`,cloneGroup:`ruleGroup-cloneGroup`,removeGroup:`ruleGroup-remove`,notToggle:`ruleGroup-notToggle`,rule:`rule`,fields:`rule-fields`,matchMode:`rule-matchMode`,matchThreshold:`rule-matchThreshold`,operators:`rule-operators`,value:`rule-value`,removeRule:`rule-remove`,betweenRules:`betweenRules`,valid:`queryBuilder-valid`,invalid:`queryBuilder-invalid`,shiftActions:`shiftActions`,dndDragging:`dndDragging`,dndOver:`dndOver`,dndCopy:`dndCopy`,dndGroup:`dndGroup`,dndDropNotAllowed:`dndDropNotAllowed`,dragHandle:`queryBuilder-dragHandle`,disabled:`queryBuilder-disabled`,muted:`queryBuilder-muted`,lockRule:`rule-lock`,lockGroup:`ruleGroup-lock`,muteRule:`rule-mute`,muteGroup:`ruleGroup-mute`,valueSource:`rule-valueSource`,valueListItem:`rule-value-list-item`,branches:`queryBuilder-branches`,justified:`queryBuilder-justified`,hasSubQuery:`rule-hasSubQuery`},w={queryBuilder:``,ruleGroup:``,header:``,body:``,combinators:``,addRule:``,addGroup:``,cloneRule:``,cloneGroup:``,removeGroup:``,notToggle:``,rule:``,fields:``,matchMode:``,matchThreshold:``,operators:``,value:``,removeRule:``,shiftActions:``,dragHandle:``,lockRule:``,lockGroup:``,muteRule:``,muteGroup:``,muted:``,valueSource:``,actionElement:``,valueSelector:``,betweenRules:``,valid:``,invalid:``,dndDragging:``,dndOver:``,dndGroup:``,dndCopy:``,dndDropNotAllowed:``,disabled:``,valueListItem:``,branches:``,hasSubQuery:``},T={empty:`empty`,invalidCombinator:`invalid combinator`,invalidIndependentCombinators:`invalid independent combinators`},E={rule:`rule`,ruleGroup:`rule-group`,inlineCombinator:`inline-combinator`,addGroup:`add-group`,removeGroup:`remove-group`,cloneGroup:`clone-group`,cloneRule:`clone-rule`,addRule:`add-rule`,removeRule:`remove-rule`,combinators:`combinators`,fields:`fields`,operators:`operators`,valueEditor:`value-editor`,notToggle:`not-toggle`,shiftActions:`shift-actions`,dragHandle:`drag-handle`,lockRule:`lock-rule`,lockGroup:`lock-group`,muteRule:`mute-rule`,muteGroup:`mute-group`,valueSourceSelector:`value-source-selector`,matchModeEditor:`match-mode-editor`},D={parentPathDisabled:`action aborted: parent path disabled`,pathDisabled:`action aborted: path is disabled`,queryUpdate:`query updated`,onAddRuleFalse:`onAddRule callback returned false`,onAddGroupFalse:`onAddGroup callback returned false`,onGroupRuleFalse:`onGroupRule callback returned false`,onGroupGroupFalse:`onGroupGroup callback returned false`,onMoveRuleFalse:`onMoveRule callback returned false`,onMoveGroupFalse:`onMoveGroup callback returned false`,onRemoveFalse:`onRemove callback returned false`,add:`rule or group added`,remove:`rule or group removed`,update:`rule or group updated`,move:`rule or group moved`,group:`rule or group grouped with another`},O=[],k={addRuleToNewGroups:!1,autoSelectField:!0,autoSelectOperator:!0,autoSelectValue:!1,debugMode:!1,enableDragAndDrop:!1,enableMountQueryChange:!0,listsAsArrays:!1,resetOnFieldChange:!0,resetOnOperatorChange:!1,showCloneButtons:!1,showCombinatorsBetweenRules:!1,showLockButtons:!1,showMuteButtons:!1,showNotToggle:!1,showShiftActions:!1,suppressStandardClassnames:!1},A=(e,t=`,`)=>typeof e==`string`?e.split(`\\${t}`).map(e=>e.split(t)).reduce((e,n,r)=>r===0?n:[...e.slice(0,-1),`${e.at(-1)}${t}${n[0]}`,...n.slice(1)],[]):[],j=(e,t=`,`)=>e.map(e=>`${e??``}`.replaceAll(t[0],`\\${t[0]}`)).join(t),M=e=>typeof e==`string`?e.trim():e,N=(e,{retainEmptyStrings:t}={})=>Array.isArray(e)?e.map(e=>M(e)):typeof e==`string`?A(e,`,`).filter(t?()=>!0:e=>!/^\s*$/.test(e)).map(e=>e.trim()):typeof e==`number`?[e]:[],ee=e=>e.every(e=>e===!1||(e??!1)!==!1);function te(e){let t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`)if(Array.isArray(e)){let i=e.length;for(t=0;t<i;t++)e[t]&&(n=te(e[t]))&&(r&&(r+=` `),r+=n)}else for(n in e)e[n]&&(r&&(r+=` `),r+=n);return r}function ne(...e){let t=0,n,r,i=``,a=e.length;for(;t<a;t++)(n=e[t])&&(r=te(n))&&(i&&(i+=` `),i+=r);return i}const P=e=>typeof e==`string`?e.toLowerCase():e,re=new RegExp(n.source.replace(/^\^/,String.raw`^\s*`).replace(/\$$/,String.raw`\s*$`)),F=e=>typeof e!=`object`||!e?!1:Object.getPrototypeOf(e)===Object.prototype,I=e=>e==null||e===``,ie=e=>F(e)&&`field`in e&&typeof e.field==`string`,L=e=>F(e)&&Array.isArray(e.rules),R=e=>L(e)&&typeof e.combinator==`string`,ae=e=>L(e)&&e.combinator===void 0,oe=[`or`,`xor`,`and`],se=(e,t)=>P(e)===t,ce=(t,n=0)=>{let r=oe[n];return t.rules.includes(r)?e(t,e=>{let t=0;for(;t<e.rules.length-2;){if(se(e.rules[t+1],r)){t+=2;continue}let i=e.rules.findIndex((e,n)=>n>t&&typeof e==`string`&&P(e)===r);if(i===-1){e.rules.splice(t,e.rules.length,ce({rules:e.rules.slice(t)},n+1));break}else e.rules.splice(t,i-t,ce({rules:e.rules.slice(t,i)},n+1))}}):n<oe.length-2?ce(t,n+1):t},z=e=>{if(R(e))return e;let t=ce(e),n=t.rules.map(e=>typeof e==`string`||!L(e)?e:z(e)),r=n.length<2?`and`:n[1],i=n.filter(e=>typeof e!=`string`);return{...t,combinator:r,rules:i}},le=e=>{if(ae(e))return e;let{combinator:t,...n}=e,r=[],{length:i}=e.rules;for(let[n,a]of e.rules.entries())L(a)?r.push(le(a)):r.push(a),t&&n<i-1&&r.push(t);return{...n,rules:r}};function ue(e){return ae(e)?z(e):le(e)}const de=e=>{let t={},n=e=>{e.id&&t[e.id]},r=e=>{let i=[];if(e.rules.length===0)i.push(T.empty);else if(!R(e)){let t=!1;for(let n=0;n<e.rules.length&&!t;n++)(n%2==0&&typeof e.rules[n]==`string`||n%2==1&&typeof e.rules[n]!=`string`||n%2==1&&typeof e.rules[n]==`string`&&!b.map(e=>e.name).includes(e.rules[n]))&&(t=!0);t&&i.push(T.invalidIndependentCombinators)}R(e)&&!b.map(e=>e.name).includes(e.combinator)&&e.rules.length>1&&i.push(T.invalidCombinator),e.id&&(t[e.id]=i.length>0?{valid:!1,reasons:i}:!0);for(let t of e.rules)typeof t==`string`||(L(t)?r(t):n(t))};return r(e),t},fe=Object.keys,pe=Object.entries,me=e=>F(e)&&`name`in e&&typeof e.name==`string`,he=e=>F(e)&&`value`in e&&typeof e.value==`string`;function B(t,n,r){return e(e=>{let t={},i=!!n;if(typeof e==`string`)return{...n,name:e,value:e,label:r?.[e]??e};if(me(e)&&!he(e)?(t.value=e.name,i=!0):!me(e)&&he(e)&&(t.name=e.value,i=!0),i)return Object.assign({},n,e,t)})(t)}function ge(t,n,r){return Array.isArray(t)?e(e=>{if(Ce(e))for(let t of e)for(let[e,i]of t.options.entries())t.options[e]=B(i,n,r);else for(let[t,i]of e.entries())e[t]=B(i,n,r)})(t):[]}function _e(e,t){return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,B(n,t)]))}const ve=e=>ye(e),ye=e=>{let t=new Set,n=[];for(let r of e)t.has(r.value??r.name)||(t.add(r.value??r.name),n.push(r));return e.length===n.length?e:n},be=e=>Array.isArray(e)&&e.length>0&&F(e[0])&&`options`in e[0]&&Array.isArray(e[0].options),xe=e=>{let t=!1;if(Array.isArray(e))for(let n of e)if(me(n)||he(n))t=!0;else return!1;return t},Se=e=>{let t=!1;if(Array.isArray(e))for(let n of e)if(me(n)&&he(n))t=!0;else return!1;return t},Ce=(e,{allowEmpty:t=!1}={})=>{let n=!1;if(Array.isArray(e))for(let r of e)if(F(r)&&`options`in r&&(xe(r.options)||t&&Array.isArray(r.options)&&r.options.length===0))n=!0;else return!1;return n},we=(e,{allowEmpty:t=!1}={})=>{let n=!1;if(Array.isArray(e))for(let r of e)if(F(r)&&`options`in r&&(Se(r.options)||t&&Array.isArray(r.options)&&r.options.length===0))n=!0;else return!1;return n};function V(e,t){return(Ce(e,{allowEmpty:!0})?e.flatMap(e=>e.options):e).find(e=>e.value===t||e.name===t)}function H(e){if(!Array.isArray(e)||e.length===0)return null;if(Ce(e,{allowEmpty:!0})){for(let t of e)if(t.options.length>0)return t.options[0].value??t.options[0].name;return null}return e[0].value??e[0].name}const Te=e=>ye(be(e)?e.flatMap(e=>e.options):e),Ee=e=>{let t=new Set,n=new Set,r=[];for(let i of e)if(!t.has(i.label)){t.add(i.label);let e=[];for(let t of i.options)n.has(t.value??t.name)||(n.add(t.value??t.name),e.push(B(t)));r.push({...i,options:e})}return r},De=e=>Ce(e)?Ee(e):ye(e.map(e=>B(e))),Oe=e=>{let{optionList:t,baseOption:n={},labelMap:r={},placeholder:{placeholderName:a=`~`,placeholderLabel:o=i,placeholderGroupLabel:s=i}={},autoSelectOption:c=!0}=e,l={id:a,name:a,value:a,label:o},u=t??[l],d=[],f=Array.isArray(u)?ge(u,n,r):fe(_e(u,n)).map(e=>({...u[e],name:e,value:e})).sort((e,t)=>e.label.localeCompare(t.label));d=Ce(f)?Ee(c?f:[{label:s,options:[l]},...f]):ye(c?f:[l,...f]);let p={};if(Array.isArray(u))if(Ce(d))for(let e of d)for(let t of e.options)p[t.value??t.name]=B(t,n);else for(let e of d)p[e.value??e.name]=B(e,n);else{let e=_e(u,n);p=c?e:{...e,[a]:l}}return{defaultOption:l,optionList:d,optionsMap:p}},ke=(e,t,n)=>{let r=B(e),i=B(n);return r.value===i.value?!1:typeof r.comparator==`string`?r[r.comparator]===i[r.comparator]:r.comparator?.(i,t)??!1},Ae=(e,t,n)=>{if(!e.comparator){let n=t=>(t.value??t.name)!==(e.value??e.name);return Ce(t)?t.map(e=>({...e,options:e.options.filter(e=>n(e))})):t.filter(e=>n(e))}return Ce(t)?t.map(t=>({...t,options:t.options.filter(t=>ke(e,n,t))})).filter(e=>e.options.length>0):t.filter(t=>ke(e,n,t))},U=(e,{parseNumbers:n,bigIntOnOverflow:r}={})=>{if(!n||typeof e==`bigint`||typeof e==`number`)return e;if(n===`native`)return Number.parseFloat(e);let i=t(e,{allowTrailingInvalid:n===`enhanced`,bigIntOnOverflow:r,romanNumerals:!1,round:!1});return typeof i==`bigint`||!Number.isNaN(i)?i:e},je=(t,n,r)=>e(t,e=>{for(let[t,i]of Object.entries(n))i===!1?delete e[t]:i&&t!==i&&t in e&&(e[i]=e[t],r&&delete e[t])});function W(e,t={}){let{ruleProcessor:n=e=>e,ruleGroupProcessor:r=e=>e,propertyMap:i={},combinatorMap:a={},operatorMap:o={},omitPath:s=!1,deleteRemappedProperties:c=!0}=t,l=e=>({...r(je({...e,...R(e)?{combinator:a[e.combinator]??e.combinator}:{}},i,c)),...i.rules===!1?null:{[i.rules??`rules`]:e.rules.map((t,r)=>{let u=s?null:{path:[...e.path,r]};return typeof t==`string`?a[t]??t:L(t)?l({...t,...u}):n(je({...t,...u,...`operator`in t?{operator:o[t.operator]??t.operator}:{}},i,c))})}});return l({...e,...s?null:{path:[]}})}const Me=e=>F(e)&&typeof e.valid==`boolean`,G=(e,t,n)=>{if(e.muted)return!1;if(typeof t==`boolean`)return t;if(Me(t))return t.valid;if(typeof n==`function`&&!L(e)){let t=n(e);if(typeof t==`boolean`)return t;if(Me(t))return t.valid}return!0},Ne=({parseNumbers:e,inputType:t})=>{if(typeof e==`string`){let[n,r]=e.split(`-`);return r===`limited`?t===`number`?n:!1:n}return e?`strict`:!1},Pe=e=>{switch(P(e)){case`null`:return`is null`;case`notnull`:return`is not null`;case`notin`:return`not in`;case`notbetween`:return`not between`;case`contains`:case`beginswith`:case`endswith`:return`like`;case`doesnotcontain`:case`doesnotbeginwith`:case`doesnotendwith`:return`not like`;default:return e}},Fe={"=":`$eq`,"!=":`$ne`,"<":`$lt`,"<=":`$lte`,">":`$gt`,">=":`$gte`,in:`$in`,notin:`$nin`,notIn:`$nin`},Ie={"=":`equals`,"!=":`not`,"<":`lt`,"<=":`lte`,">":`gt`,">=":`gte`,in:`in`,notin:`notIn`},Le={and:`&&`,or:`||`},Re={startsWith:(e,t)=>typeof e==`string`&&e.startsWith(t),endsWith:(e,t)=>typeof e==`string`&&e.endsWith(t)},ze=(e,t)=>({...e,rules:e.rules.map(e=>{if(typeof e==`string`)return e;if(L(e))return ze(e,t);let n=V(t.fields,e.field),r=Ne({parseNumbers:t.parseNumbers,inputType:n?.inputType});if(Array.isArray(e.value))return{...e,value:e.value.map(e=>U(e,{parseNumbers:r}))};let i=N(e.value,{retainEmptyStrings:!0}).map(e=>U(e,{parseNumbers:r}));if(i.every(e=>typeof e==`number`)){if(i.length>1)return{...e,value:i};if(i.length===1)return{...e,value:i[0]}}return e})}),K=e=>typeof e==`string`&&e.length>0||typeof e==`number`&&!Number.isNaN(e)||typeof e!=`string`&&typeof e!=`number`,q=(e,t)=>!!t&&(typeof e==`number`||typeof e==`bigint`||typeof e==`string`&&re.test(e)),Be=e=>e.length>=3,Ve=(e=[``,``])=>Array.isArray(e)?e:typeof e==`string`?[e,e]:e??[``,``],He=(e,{quoteFieldNamesWith:t,fieldIdentifierSeparator:n})=>{let[r,i]=Ve(t);return typeof n==`string`&&n.length>0?j(A(e,n).map(e=>`${r}${e}${i}`),n):`${r}${e}${i}`},Ue=[`S`,`V`,`O`],We=e=>{let t=[],n=new Set(Ue);for(let r of e.toUpperCase())if(n.has(r)&&(t.push(r),n.delete(r),n.size===0))break;for(let e of Ue)n.has(e)&&t.push(e);return t},Ge={groupPrefix:``,groupPrefix_not_xor:`either zero or more than one of`,groupPrefix_xor:`exactly one of`,groupSuffix:`is true`,groupSuffix_not:`is not true`},Ke=(e,t,n)=>t.startsWith(e)&&n.every(e=>t.includes(`_${e}`)&&t.match(/_/g)?.length===n.length),qe=(e,t,n=[])=>n.length===0?t[e]??Ge[e]??``:Object.entries(t).find(([t])=>Ke(e,t,n))?.[1]??Object.entries(Ge).find(([t])=>Ke(e,t,n))?.[1]??Ge[e]??``,J=e=>{let{mode:t,threshold:n}=e.match??{};if(t){if(!L(e.value))return!1;let r=P(t),i=r===`atleast`&&n===1?`some`:r===`atmost`&&n===0?`none`:r;return(i===`atleast`||i===`atmost`||i===`exactly`)&&(typeof n!=`number`||n<0)?!1:{mode:i,threshold:n}}},Je=(e,t)=>typeof t==`bigint`?{$bigint:t.toString()}:t,Ye=(e,t)=>F(t)&&Object.keys(t).length===1&&typeof t.$bigint==`string`?BigInt(t.$bigint):t,Xe=(e,t)=>{let{fields:n,fallbackExpression:r,getParseNumberBoolean:i,placeholderFieldName:a,placeholderOperatorName:o,placeholderValueName:s,ruleProcessor:c,validateRule:l,validationMap:u}=t,d=(e,f)=>{if(!G(e,u[e.id??``]))return f?r:``;let p=[],m=``,h=!0;for(let r of e.rules){if(typeof r==`string`){m=Le[r];continue}if(L(r)){let e=d(r);e&&(!h&&m&&(p.push(m),m=``),h=!1,p.push(e));continue}let[e,u]=l(r);if(!G(r,e,u)||r.field===a||r.operator===o||s!==void 0&&r.value===s)continue;let f=V(n,r.field),g=c(r,{...t,parseNumbers:i(f?.inputType),escapeQuotes:(r.valueSource??`value`)===`value`,fieldData:f});g&&(!h&&m&&(p.push(m),m=``),h=!1,p.push(g))}let g=p.join(R(e)?` ${Le[e.combinator]} `:` `),[_,v]=e.not||!f?[`${e.not?`!`:``}(`,`)`]:[``,``];return g?`${_}${g}${v}`:r};return d(e,!0)},Ze=e=>e.startsWith(`not`)||e.startsWith(`doesnot`),Qe=(e,t)=>typeof e!=`string`||!t?`${e}`:e.replaceAll(`"`,`\\"`),$e=(e,t={})=>{let{escapeQuotes:n,parseNumbers:r,preserveValueOrder:i}=t,{field:a,operator:o,value:s,valueSource:c}=e,l=c===`field`,u=P(o===`=`?`==`:o),d=typeof s==`number`||typeof s==`boolean`||typeof s==`bigint`||q(s,r),f=J(e);if(f===!1)return``;if(f){let{mode:n,threshold:r}=f,i=`elem_alias`,o=Xe(W(e.value,{ruleProcessor:e=>({...e,field:`${i}${e.field?`.${e.field}`:``}`})}),t);switch(n){case`all`:return`${a}.all(${i}, ${o})`;case`none`:case`some`:return`${n===`none`?`!`:``}${a}.exists(${i}, ${o})`;case`atleast`:case`atmost`:case`exactly`:{let e=`double(${a}.size())`,t=`${a}.filter(${i}, ${o}).size()`,s=n===`atleast`?`>=`:n===`atmost`?`<=`:`==`;return r>0&&r<1?`${t} ${s} (${e} * ${r})`:`${t} ${s} ${r}`}}}switch(u){case`<`:case`<=`:case`==`:case`!=`:case`>`:case`>=`:return`${a} ${u} ${l||d?M(s):`"${Qe(s,n)}"`}`;case`contains`:case`doesnotcontain`:return`${Ze(u)?`!`:``}${a}.contains(${l?M(s):`"${Qe(s,n)}"`})`;case`beginswith`:case`doesnotbeginwith`:return`${Ze(u)?`!`:``}${a}.startsWith(${l?M(s):`"${Qe(s,n)}"`})`;case`endswith`:case`doesnotendwith`:return`${Ze(u)?`!`:``}${a}.endsWith(${l?M(s):`"${Qe(s,n)}"`})`;case`null`:return`${a} == null`;case`notnull`:return`${a} != null`;case`in`:case`notin`:{let[e,t]=Ze(u)?[`!(`,`)`]:[``,``];return`${e}${a} in [${N(s).map(e=>l||q(e,r)?`${M(e)}`:`"${Qe(e,n)}"`).join(`, `)}]${t}`}case`between`:case`notbetween`:{let e=N(s);if(e.length>=2&&!I(e[0])&&!I(e[1])){let[t,o]=e,s=r!==!1,c=q(t,s)?U(t,{parseNumbers:s}):NaN,d=q(o,s)?U(o,{parseNumbers:s}):NaN,f=Number.isNaN(c)?l?`${t}`:`"${Qe(t,n)}"`:c,p=Number.isNaN(d)?l?`${o}`:`"${Qe(o,n)}"`:d;if(!i&&f===c&&p===d&&d<c){let e=d;p=c,f=e}return u===`between`?`(${a} >= ${f} && ${a} <= ${p})`:`(${a} < ${f} || ${a} > ${p})`}else return``}}return``},et={$and:[{$expr:!0}]},tt=(e,t,n)=>{let{fields:r,getParseNumberBoolean:i,placeholderFieldName:a,placeholderOperatorName:o,placeholderValueName:s,ruleProcessor:c,validateRule:l,validationMap:u}=t,d=(e,f)=>{if(!G(e,u[e.id??``]))return f?et:!1;let p=`$${P(e.combinator)}`,m=!1,h=e.rules.map(e=>{if(L(e)){let t=d(e);return t?(m=!0,t):!1}let[u,f]=l(e);if(!G(e,u,f)||e.field===a||e.operator===o||s!==void 0&&e.value===s)return!1;let p=V(r,e.field);return c(e,{...t,parseNumbers:i(p?.inputType),fieldData:p},n)}).filter(Boolean);return h.length>0?h.length===1&&!m?h[0]:{[p]:h}:et};return d(z(e),!0)},nt=(e,t,n=!1)=>q(e,n||typeof e==`bigint`)?Number(U(e,{parseNumbers:`strict`})):t,rt=(e,t={})=>{let{field:n,operator:r,value:i,valueSource:a}=e,{parseNumbers:o,preserveValueOrder:s,context:c}=t,l=a===`field`,{avoidFieldsAsKeys:u}=c??{},d=J(e);if(d===!1)return;if(d){let{mode:e,threshold:r}=d,a={$size:{$ifNull:[`$${n}`,[]]}},o=tt(W(i,{ruleProcessor:e=>({...e,field:e.field?`${n}.${e.field}`:n})}),{...t,ruleProcessor:rt,context:{...t.context,avoidFieldsAsKeys:!1}}),s=tt(W(i,{ruleProcessor:e=>({...e,field:e.field?`$item.${e.field}`:`$item`})}),{...t,ruleProcessor:rt,context:{...t.context,avoidFieldsAsKeys:!0}}),c={$size:{$ifNull:[{$filter:{input:`$${n}`,as:`item`,cond:{$and:[s]}}},[]]}};switch(e){case`all`:return{$expr:{$eq:[c,a]}};case`none`:return{$nor:[o]};case`some`:return o;case`atleast`:case`atmost`:case`exactly`:{let t=e===`atleast`?Fe[`>=`]:e===`atmost`?Fe[`<=`]:Fe[`=`];return r>0&&r<1?{$expr:{[t]:[c,{$multiply:[a,r]}]}}:{$expr:{[t]:[c,r]}}}}}if(r===`=`&&!l)return u?{$eq:[`$${n}`,nt(i,i,o)]}:{[n]:nt(i,i,o)};let f=P(r);switch(f){case`<`:case`<=`:case`=`:case`!=`:case`>`:case`>=`:{let e=Fe[f];return l?{[e]:[`$${n}`,`$${i}`]}:u?{$and:[{$ne:[`$${n}`,null]},{[e]:[`$${n}`,nt(i,i,o)]}]}:{[n]:{[e]:nt(i,i,o)}}}case`contains`:return l?{$where:`this.${n}.includes(this.${i})`}:u?{$regexMatch:{input:`$${n}`,regex:i}}:{[n]:{$regex:i}};case`beginswith`:return l?{$where:`this.${n}.startsWith(this.${i})`}:u?{$regexMatch:{input:`$${n}`,regex:`^${i}`}}:{[n]:{$regex:`^${i}`}};case`endswith`:return l?{$where:`this.${n}.endsWith(this.${i})`}:u?{$regexMatch:{input:`$${n}`,regex:`${i}$`}}:{[n]:{$regex:`${i}$`}};case`doesnotcontain`:return l?{$where:`!this.${n}.includes(this.${i})`}:u?{$not:{$regexMatch:{input:`$${n}`,regex:i}}}:{[n]:{$not:{$regex:i}}};case`doesnotbeginwith`:return l?{$where:`!this.${n}.startsWith(this.${i})`}:u?{$not:{$regexMatch:{input:`$${n}`,regex:`^${i}`}}}:{[n]:{$not:{$regex:`^${i}`}}};case`doesnotendwith`:return l?{$where:`!this.${n}.endsWith(this.${i})`}:u?{$not:{$regexMatch:{input:`$${n}`,regex:`${i}$`}}}:{[n]:{$not:{$regex:`${i}$`}}};case`null`:return u?{$eq:[`$${n}`,null]}:{[n]:null};case`notnull`:return u?{$ne:[`$${n}`,null]}:{[n]:{$ne:null}};case`in`:case`notin`:{let e=N(i);return l?{$where:`${f===`notin`?`!`:``}[${e.map(e=>`this.${e}`).join(`,`)}].includes(this.${n})`}:u?f===`notin`?{$not:{[Fe.in]:[`$${n}`,e.map(e=>nt(e,e,o))]}}:{[Fe[f]]:[`$${n}`,e.map(e=>nt(e,e,o))]}:{[n]:{[Fe[f]]:e.map(e=>nt(e,e,o))}}}case`between`:case`notbetween`:{let e=N(i);if(e.length>=2&&K(e[0])&&K(e[1])){let[t,r]=e,i=nt(t,NaN,!0),a=nt(r,NaN,!0),o=l||Number.isNaN(i)?t:i,c=l||Number.isNaN(a)?r:a;if(!s&&o===i&&c===a&&a<i){let e=a;c=i,o=e}return f===`between`?l?{$gte:[`$${n}`,`$${o}`],$lte:[`$${n}`,`$${c}`]}:u?{$and:[{$gte:[`$${n}`,o]},{$lte:[`$${n}`,c]}]}:{[n]:{$gte:o,$lte:c}}:l?{$or:[{$lt:[`$${n}`,`$${o}`]},{$gt:[`$${n}`,`$${c}`]}]}:u?{$or:[{$lt:[`$${n}`,o]},{$gt:[`$${n}`,c]}]}:{$or:[{[n]:{$lt:o}},{[n]:{$gt:c}}]}}else return``}}return``},it=(e,t)=>{let n=rt(e,t);return n?JSON.stringify(n):``},at=(e,t)=>{let{fields:n,fallbackExpression:r,getParseNumberBoolean:i,placeholderFieldName:a,placeholderOperatorName:o,placeholderValueName:s,ruleProcessor:c,validateRule:l,validationMap:u}=t,d=(e,f)=>{if(!G(e,u[e.id??``]))return f?r:``;let p=[],m=``,h=!0;for(let r of e.rules){if(typeof r==`string`){m=r;continue}if(L(r)){let e=d(r);e&&(!h&&m&&(p.push(m),m=``),h=!1,p.push(e));continue}let[e,u]=l(r);if(!G(r,e,u)||r.field===a||r.operator===o||s!==void 0&&r.value===s)continue;let f=V(n,r.field),g=c(r,{...t,parseNumbers:i(f?.inputType),escapeQuotes:(r.valueSource??`value`)===`value`,fieldData:f});g&&(!h&&m&&(p.push(m),m=``),h=!1,p.push(g))}let g=p.join(R(e)?` ${e.combinator} `:` `),[_,v]=e.not||!f?[`${e.not?`!`:``}(`,`)`]:[``,``];return g?`${_}${g}${v}`:r};return d(e,!0)},ot=e=>e.startsWith(`not`)||e.startsWith(`doesnot`),st=(e,t)=>t?`!(${e})`:e,ct=(e,t)=>typeof e!=`string`||!t?`${e}`:e.replaceAll(`'`,`\\'`),lt=(e,t={})=>{let{field:n,operator:r,value:i,valueSource:a}=e,{escapeQuotes:o,parseNumbers:s,preserveValueOrder:c}=t,l=a===`field`,u=P(r===`=`?`==`:r),d=typeof i==`number`||typeof i==`boolean`||typeof i==`bigint`||q(i,s),f=J(e);if(f===!1)return``;if(f){let{mode:r,threshold:i}=f,a=at(W(e.value,{ruleProcessor:e=>({...e,field:e.field||`#this`})}),t),o=`${n}.size()`,s=`${n}.?[${a}].size()`;switch(r){case`all`:return`${s} == ${o}`;case`none`:return`${s} == 0`;case`some`:return`${s} >= 1`;case`atleast`:case`atmost`:case`exactly`:{let e=r===`atleast`?`>=`:r===`atmost`?`<=`:`==`;return i>0&&i<1?`${s} ${e} (${o} * ${i})`:`${s} ${e} ${i}`}}}switch(u){case`<`:case`<=`:case`==`:case`!=`:case`>`:case`>=`:return`${n} ${u} ${l||d?M(i):`'${ct(i,o)}'`}`;case`contains`:case`doesnotcontain`:return st(`${n} matches ${l||d?M(i):`'${ct(i,o)}'`}`,ot(u));case`beginswith`:case`doesnotbeginwith`:return st(`${n} matches ${l?`'^'.concat(${M(i)})`:`'${typeof i==`string`&&!i.startsWith(`^`)||d?`^`:``}${ct(i,o)}'`}`,ot(u));case`endswith`:case`doesnotendwith`:return st(`${n} matches ${l?`${M(i)}.concat('$')`:`'${ct(i,o)}${typeof i==`string`&&!i.endsWith(`$`)||d?`$`:``}'`}`,ot(u));case`null`:return`${n} == null`;case`notnull`:return`${n} != null`;case`in`:case`notin`:{let e=ot(u)?`!`:``,t=N(i);return t.length>0?`${e}(${t.map(e=>`${n} == ${l||q(e,s)?`${M(e)}`:`'${ct(e,o)}'`}`).join(` or `)})`:``}case`between`:case`notbetween`:{let e=N(i);if(e.length>=2&&!I(e[0])&&!I(e[1])){let[t,r]=e,i=s!==!1,a=q(t,i)?U(t,{parseNumbers:i}):NaN,d=q(r,i)?U(r,{parseNumbers:i}):NaN,f=Number.isNaN(a)?l?`${t}`:`'${ct(t,o)}'`:a,p=Number.isNaN(d)?l?`${r}`:`'${ct(r,o)}'`:d;if(!c&&f===a&&p===d&&d<a){let e=d;p=a,f=e}return u===`between`?`(${n} >= ${f} and ${n} <= ${p})`:`(${n} < ${f} or ${n} > ${p})`}else return``}}return``},ut=(e,t,n)=>n&&typeof e==`string`?e.replaceAll(`${t}`,`${t}${t}`):e,dt=({operator:e,value:t,valueSource:n},{escapeQuotes:r,parseNumbers:i,preserveValueOrder:a,quoteFieldNamesWith:o,quoteValuesWith:s,concatOperator:c=`||`,fieldIdentifierSeparator:l,wrapValueWith:u=[``,``],translations:d}={})=>{let f=n===`field`,p=P(e),m=s||`'`,h=e=>`${u[0]}${m}${e}${m}${u[1]}`,g=e=>ut(e,m,r),_=e=>h(g(e)),v=e=>He(e,{quoteFieldNamesWith:o,fieldIdentifierSeparator:l}),y=(...e)=>c.toUpperCase()===`CONCAT`?`CONCAT(${e.join(`, `)})`:e.join(` ${c} `);switch(p){case`null`:case`notnull`:return``;case`in`:case`notin`:{let e=N(t);return e.length>0?`(${e.map(e=>f?v(e):q(e,i)?`${M(e)}`:`${_(e)}`).join(`, `)})`:``}case`between`:case`notbetween`:{let e=N(t,{retainEmptyStrings:!0});if(e.length<2||!K(e[0])||!K(e[1]))return``;let[n,r]=e,o=q(n,i)?U(n,{parseNumbers:`strict`}):NaN,s=q(r,i)?U(r,{parseNumbers:`strict`}):NaN,c=Number.isNaN(o)?f?`${n}`:n:o,l=Number.isNaN(s)?f?`${r}`:r:s,u=[c,l];return!a&&c===o&&l===s&&s<o&&(u[0]=s,u[1]=o),(f?u.map(e=>v(e)):u.every(e=>q(e,i))?u.map(e=>U(e,{parseNumbers:`strict`})):u.map(e=>_(e))).join(` ${d?.and??`and`} `)}case`contains`:case`doesnotcontain`:return f?y(h(`%`),v(t),h(`%`)):h(`%${g(t)}%`);case`beginswith`:case`doesnotbeginwith`:return f?y(v(t),h(`%`)):h(`${g(t)}%`);case`endswith`:case`doesnotendwith`:return f?y(h(`%`),v(t)):h(`%${g(t)}`)}return typeof t==`boolean`?t?`TRUE`:`FALSE`:f?v(t):q(t,i)?`${M(t)}`:`${_(t)}`},ft=(e,t)=>{let n=t??{},{parseNumbers:r,preserveValueOrder:i,context:a={}}=n,{columns:o,drizzleOperators:s,useRawFields:c}=a;if(!o||!s)return;let{between:l,eq:u,gt:d,gte:f,inArray:p,isNotNull:m,isNull:h,like:g,lt:_,lte:v,ne:y,notBetween:b,notInArray:x,notLike:S,sql:C}=s,{field:w,operator:T,value:E,valueSource:D}=e,O=c&&/[a-z][a-z0-9]*/i.test(w)?C.raw(w):o[w],k=P(T),A=D===`field`,j=e=>A?o[e]:e;if(!O)return;let M=J(e);if(M!==!1){if(M){if(n.preset!==`postgresql`)return;let{mode:t,threshold:r}=M,i=`elem_alias`,a=pt(W(e.value,{ruleProcessor:e=>({...e,field:i})}),{...n,context:{...n.context,useRawFields:!0}});switch(t){case`all`:return C`(select count(*) from unnest(${O}) as ${C.raw(i)} where ${a({},s)}) = array_length(${O}, 1)`;case`none`:return C`not exists (select 1 from unnest(${O}) as ${C.raw(i)} where ${a({},s)})`;case`some`:return C`exists (select 1 from unnest(${O}) as ${C.raw(i)} where ${a({},s)})`;case`atleast`:case`atmost`:case`exactly`:{let e=t===`atleast`?`>=`:t===`atmost`?`<=`:`=`;return r>0&&r<1?C`(select count(*) / array_length(${O}, 1) from unnest(${O}) as ${C.raw(i)} where ${a({},s)}) ${C.raw(`${e} ${r}`)}`:C`(select count(*) from unnest(${O}) as ${C.raw(i)} where ${a({},s)}) ${C.raw(`${e} ${r}`)}`}}}switch(k){case`=`:return u(O,j(E));case`!=`:return y(O,j(E));case`>`:return d(O,j(E));case`<`:return _(O,j(E));case`>=`:return f(O,j(E));case`<=`:return v(O,j(E));case`beginswith`:case`doesnotbeginwith`:return(k===`doesnotbeginwith`?S:g)(O,A?C`${j(E)} || '%'`:`${E}%`);case`contains`:case`doesnotcontain`:return(k===`doesnotcontain`?S:g)(O,A?C`'%' || ${j(E)} || '%'`:`%${E}%`);case`endswith`:case`doesnotendwith`:return(k===`doesnotendwith`?S:g)(O,A?C`'%' || ${j(E)}`:`%${E}`);case`null`:return h(O);case`notnull`:return m(O);case`in`:case`notin`:{let e=N(E).map(e=>j(e));return k===`notin`?x(O,e):p(O,e)}case`between`:case`notbetween`:{let e=N(E);if(e.length>=2&&K(e[0])&&K(e[1])){let[t,n]=e,a=r!==!1;if(!A&&q(t,a)&&q(n,a)){let e=U(t,{parseNumbers:a}),r=U(n,{parseNumbers:a});if(!i&&r<e){let i=r;n=e,t=i}else t=e,n=r}else A&&(t=j(t),n=j(n));return k===`notbetween`?b(O,t,n):l(O,t,n)}return}default:return}}},pt=(e,t,n)=>(n,r)=>{let{fields:i,getParseNumberBoolean:a,placeholderFieldName:o,placeholderOperatorName:s,placeholderValueName:c,validateRule:l,validationMap:u}=t;if(!n||!r)return;let{and:d,not:f,or:p}=r,m=ft,h=(e,g)=>{if(!G(e,u[e.id??``]))return;let _=e.rules.map(e=>{if(L(e))return h(e);let[u,d]=l(e);if(!G(e,u,d)||e.field===o||e.operator===s||c!==void 0&&e.value===c)return;let f=V(i,e.field);return m(e,{...t,parseNumbers:a(f?.inputType),fieldData:f,context:{...t.context,columns:n,drizzleOperators:r}})}).filter(Boolean);if(_.length===0)return;let v=e.combinator===`or`?p(..._):d(..._);return e.not?f(v):v};return h(z(e),!0)},mt=(e,t)=>{let{fields:n,getParseNumberBoolean:r,placeholderFieldName:i,placeholderOperatorName:a,placeholderValueName:o,ruleProcessor:s,validateRule:c,validationMap:l}=t,u=e=>{if(!G(e,l[e.id??``]))return!1;let d=e.rules.map(e=>{if(L(e))return u(e);let[l,d]=c(e);if(!G(e,l,d)||e.field===i||e.operator===a||o!==void 0&&e.value===o)return!1;let f=V(n,e.field);return s(e,{...t,parseNumbers:r(f?.inputType),fieldData:f})}).filter(Boolean);return d.length===0?!1:{bool:e.not?{must_not:/^or$/i.test(e.combinator)?{bool:{should:d}}:d}:{[/^or$/i.test(e.combinator)?`should`:`must`]:d}}},d=u(z(e));return d===!1?{}:d},ht=(e,t)=>{let{fields:n,fallbackExpression:r,getParseNumberBoolean:i,placeholderFieldName:a,placeholderOperatorName:o,placeholderValueName:s,ruleProcessor:c,validateRule:l,validationMap:u}=t,d=(e,f)=>{if(!G(e,u[e.id??``]))return f?r:``;let p=[],m=``,h=!0;for(let r of e.rules){if(typeof r==`string`){m=r;continue}if(L(r)){let e=d(r);e&&(!h&&m&&(p.push(m),m=``),h=!1,p.push(e));continue}let[e,u]=l(r);if(!G(r,e,u)||r.field===a||r.operator===o||s!==void 0&&r.value===s)continue;let f=V(n,r.field),g=c(r,{...t,parseNumbers:i(f?.inputType),escapeQuotes:(r.valueSource??`value`)===`value`,fieldData:f});g&&(!h&&m&&(p.push(m),m=``),h=!1,p.push(g))}let g=p.join(R(e)?` ${e.combinator} `:` `),[_,v]=e.not||!f?[`${e.not?`$not`:``}(`,`)`]:[``,``];return g?`${_}${g}${v}`:r};return d(e,!0)},gt=(e,t)=>{let{fields:n,getParseNumberBoolean:r,placeholderFieldName:i,placeholderOperatorName:a,placeholderValueName:o,ruleProcessor:s,validateRule:c,validationMap:l}=t,u=z(e),d=(e,u)=>{if(!G(e,l[e.id??``]))return!1;let f=e.rules.map(e=>{if(L(e))return d(e);let[l,u]=c(e);if(!G(e,l,u)||e.field===i||e.operator===a||o!==void 0&&e.value===o)return!1;let f=V(n,e.field);return s(e,{...t,parseNumbers:r(f?.inputType),fieldData:f})}).filter(Boolean);if(f.length===0)return!1;let p={[e.combinator]:f};return e.not?{"!":p}:p};return d(u,!0)},_t=(e,t)=>{let{fields:n,fallbackExpression:r,getParseNumberBoolean:i,placeholderFieldName:a,placeholderOperatorName:o,placeholderValueName:s,ruleProcessor:c,validateRule:l,validationMap:u}=t,d=(e,f)=>{if(!G(e,u[e.id??``]))return f?r:``;let p=e.rules.map(e=>{if(L(e))return d(e);let[r,u]=l(e);if(!G(e,r,u)||e.field===a||e.operator===o||s!==void 0&&e.value===s)return``;let f=V(n,e.field);return c(e,{...t,parseNumbers:i(f?.inputType),escapeQuotes:(e.valueSource??`value`)===`value`,fieldData:f})}).filter(Boolean),m=p.join(``),[h,g]=e.not?[`(!`,`)`]:[``,``],[_,v]=p.length>1?[`${h}(${e.combinator===`or`?`|`:`&`}`,`)${g}`]:[h,g];return m?`${_}${m}${v}`:r};return d(z(e),!0)},vt=e=>e.startsWith(`{`)&&e.endsWith(`}`),yt=(e,t,n)=>{let{fields:r,fallbackExpression:i,getParseNumberBoolean:a,placeholderFieldName:o,placeholderOperatorName:s,placeholderValueName:c,ruleProcessor:l,validateRule:u,validationMap:d}=t,f=(e,p)=>{if(!G(e,d[e.id??``]))return p?i:``;let m=`"$${P(e.combinator)}"`,h=!1,g=e.rules.map(e=>{if(L(e)){let t=f(e);return t?(h=!0,vt(t)?t:`{${t}}`):``}let[i,d]=u(e);if(!G(e,i,d)||e.field===o||e.operator===s||c!==void 0&&e.value===c)return``;let p=V(r,e.field);return l(e,{...t,parseNumbers:a(p?.inputType),fieldData:p},n)}).filter(Boolean);return g.length>0?g.length===1&&!h?g[0]:`${m}:[${g.join(`,`)}]`:i},p=f(z(e),!0);return vt(p)?p:`{${p}}`},bt=(e,t)=>{let{fields:n,fallbackExpression:r,getParseNumberBoolean:i,placeholderFieldName:a,placeholderOperatorName:o,placeholderValueName:s,ruleProcessor:c,translations:l,validateRule:u,validationMap:d}=t,f=(e,p)=>{if(!G(e,d[e.id??``]))return p?r:``;let m=ae(e)&&e.rules.some(e=>typeof e==`string`&&P(e)===`xor`)?z(e):e,h=[],g=``,_=!0;for(let e of m.rules){if(typeof e==`string`){g=`, ${l[e]??e} `;continue}if(L(e)){let t=f(e,m.rules.length===1&&!(m.not||/^xor$/i.test(m.combinator??``)));t&&(!_&&g&&(h.push(g),g=``),_=!1,h.push(t));continue}let[r,d]=u(e);if(!G(e,r,d)||e.field===a||e.operator===o||s!==void 0&&e.value===s)continue;let p=(e.valueSource??`value`)===`value`,v=V(n,e.field),y=c(e,{...t,parseNumbers:i(v?.inputType),escapeQuotes:p,fieldData:v});y&&(!_&&g&&(h.push(g),g=``),_=!1,h.push(y))}if(h.length===0)return r;let v=P(m.combinator??``)===`xor`,y=v?m.combinator.slice(1):m.combinator,b=m.not||!p||v&&h.length>1,[x,S]=[`groupPrefix`,`groupSuffix`].map(e=>m.not?v?qe(e,l,[`not`,`xor`]):qe(e,l,[`not`]):v?qe(e,l,[`xor`]):qe(e,l)),C=b?`${x} (`.trim():``,w=b?`) ${S}`.trim():``;return`${C}${h.join(R(m)?`, ${l[y]??y} `:``)}${w}`};return f(e,!0)},xt=(e,t)=>{let{format:n,fields:r,fallbackExpression:i,getParseNumberBoolean:a,placeholderFieldName:o,placeholderOperatorName:s,placeholderValueName:c,ruleProcessor:l,validateRule:u,validationMap:d}=t,f=n===`parameterized`,p=[],m={},h=new Map,g=e=>{h.has(e)||h.set(e,new Set);let t=`${e}_${h.get(e).size+1}`;return h.get(e).add(t),t},_=e=>{let[i,d]=u(e);if(!G(e,i,d)||e.field===o||e.operator===s||c!==void 0&&e.value===c)return``;let f=V(r,e.field),_=Object.fromEntries([...h.entries()].map(([e,t])=>[e,[...t]])),v=l(e,{...t,parseNumbers:a(f?.inputType),getNextNamedParam:g,fieldParamNames:_,fieldData:f},{processedParams:p});if(!F(v))return``;let{sql:y,params:b}=v;if(typeof y!=`string`||!y)return``;if(n===`parameterized`&&Array.isArray(b))p.push(...b);else if(n===`parameterized_named`&&F(b)){Object.assign(m,b);for(let t of Object.keys(b))h.get(e.field)?.add(t)}return y},v=(e,t)=>{if(!G(e,d[e.id??``]))return t?i:``;let n=[],r=``,a=!0;for(let t of e.rules){if(typeof t==`string`){r=t;continue}if(L(t)){let i=v(t,e.rules.length===1);i&&(!a&&r&&(n.push(r),r=``),a=!1,n.push(i));continue}let i=_(t);i&&(!a&&r&&(n.push(r),r=``),a=!1,n.push(i))}return n.length===0?i:`${e.not?`NOT `:``}(${n.join(R(e)?` ${e.combinator} `:` `)})`};return f?{sql:v(e,!0),params:p}:{sql:v(e,!0),params:m}},St={},Ct=(e,t)=>{let{fields:n,getParseNumberBoolean:r,placeholderFieldName:i,placeholderOperatorName:a,placeholderValueName:o,ruleProcessor:s,validateRule:c,validationMap:l}=t,u=(e,d)=>{if(!G(e,l[e.id??``]))return d?St:void 0;let f=e.combinator.toUpperCase(),p=!1,m=e.rules.map(e=>{if(L(e)){let t=u(e);return t?(p=!0,t):void 0}let[l,d]=c(e);if(!G(e,l,d)||e.field===i||e.operator===a||o!==void 0&&e.value===o)return;let f=V(n,e.field);return s(e,{...t,parseNumbers:r(f?.inputType),fieldData:f})}).filter(Boolean);return m.length>0?m.length===1&&!p?m[0]:{[f]:m}:St},d=u(z(e),!0);return e.not?{NOT:d}:d},wt=(e,t)=>{let{fields:n,getParseNumberBoolean:r,placeholderFieldName:i,placeholderOperatorName:a,placeholderValueName:o,ruleProcessor:s,validateRule:c,validationMap:l,context:u={}}=t,{sequelizeOperators:d}=u;if(!d)return;let f=(e,u)=>{if(!G(e,l[e.id??``]))return;let p=e.combinator.toUpperCase(),m=!1,h=e.rules.map(e=>{if(L(e)){let t=f(e);return t?(m=!0,t):void 0}let[l,u]=c(e);if(!G(e,l,u)||e.field===i||e.operator===a||o!==void 0&&e.value===o)return;let d=V(n,e.field);return s(e,{...t,parseNumbers:r(d?.inputType),fieldData:d})}).filter(Boolean);if(h.length===0)return;let g=h.length===1&&!m?h[0]:{[P(p)===`or`?d.or:d.and]:h};return e.not?{[d.not]:g}:g};return f(z(e),!0)},Tt=(e,t)=>{let{fields:n,fallbackExpression:r,getParseNumberBoolean:i,placeholderFieldName:a,placeholderOperatorName:o,placeholderValueName:s,ruleProcessor:c,validateRule:l,validationMap:u}=t,d=(e,f)=>{if(!G(e,u[e.id??``]))return f?r:``;let p=[],m=``,h=!0;for(let r of e.rules){if(typeof r==`string`){m=r;continue}if(L(r)){let t=d(r,e.rules.length===1);t&&(!h&&m&&(p.push(m),m=``),h=!1,p.push(t));continue}let[u,f]=l(r);if(!G(r,u,f)||r.field===a||r.operator===o||s!==void 0&&r.value===s)continue;let g=(r.valueSource??`value`)===`value`,_=V(n,r.field),v=c(r,{...t,parseNumbers:i(_?.inputType),escapeQuotes:g,fieldData:_});v&&(!h&&m&&(p.push(m),m=``),h=!1,p.push(v))}return p.length===0?r:`${e.not?`NOT `:``}(${p.join(R(e)?` ${e.combinator} `:` `)})`};return d(e,!0)},Et={"<":`lt`,"<=":`lte`,">":`gt`,">=":`gte`},Dt=(e,t)=>e.startsWith(`not`)||e.startsWith(`doesnot`)?{bool:{must_not:t}}:t,Ot=e=>e?.replace(/('|\\)/g,`\\$1`),kt={beginswith:`startsWith`,doesnotbeginwith:`startsWith`,doesnotcontain:`contains`,doesnotendwith:`endsWith`,endswith:`endsWith`},At=(e,t,n)=>{let r=`doc['${e}'].value.${kt[t]??t}(doc['${n}'].value)`;return t.startsWith(`d`)?`!${r}`:r},jt=(e,t)=>typeof e==`boolean`?e:q(e,t)?U(e,{parseNumbers:t}):e,Mt=(e,t={})=>{let{field:n,operator:r,value:i,valueSource:a}=e,{parseNumbers:o,preserveValueOrder:s}=t,c=P(r);if(J(e))return!1;if(a===`field`){if(N(i).some(e=>typeof e!=`string`))return!1;let e=Ot(n);switch(c){case`=`:case`!=`:case`>`:case`>=`:case`<`:case`<=`:{let t=c===`=`?`==`:c,n=Ot(i);return n?{bool:{filter:{script:{script:`doc['${e}'].value ${t} doc['${n}'].value`}}}}:!1}case`in`:case`notin`:{let t=N(i);if(t.length>0){let n=t.map(t=>({bool:{filter:{script:{script:`doc['${e}'].value == doc['${t}'].value`}}}}));return{bool:c===`in`?{should:n}:{must_not:n}}}return!1}case`between`:case`notbetween`:{let t=N(i);if(t.length>=2&&t[0]&&t[1]){let n=`doc['${e}'].value >= doc['${t[0]}'].value && doc['${e}'].value <= doc['${t[1]}'].value`;return{bool:{filter:{script:{script:c===`notbetween`?`!(${n})`:n}}}}}return!1}case`contains`:case`doesnotcontain`:case`beginswith`:case`doesnotbeginwith`:case`endswith`:case`doesnotendwith`:{let t=Ot(i);return t?{bool:{filter:{script:{script:At(e,c,t)}}}}:!1}}}switch(c){case`<`:case`<=`:case`>`:case`>=`:return{range:{[n]:{[Et[c]]:jt(i,o)}}};case`=`:return{term:{[n]:jt(i,o)}};case`!=`:return{bool:{must_not:{term:{[n]:jt(i,o)}}}};case`null`:return{bool:{must_not:{exists:{field:n}}}};case`notnull`:return{exists:{field:n}};case`in`:case`notin`:{let e=N(i).map(e=>jt(e,o));if(e.length>0){let t=e.map(e=>({term:{[n]:jt(e,o)}}));return{bool:c===`in`?{should:t}:{must_not:t}}}return!1}case`between`:case`notbetween`:{let e=N(i);if(e.length>=2&&K(e[0])&&K(e[1])){let[t,r]=e,i=o!==!1;if(q(t,i)&&q(r,i)){let e=U(t,{parseNumbers:i}),n=U(r,{parseNumbers:i});if(!s&&n<e){let i=n;r=e,t=i}else t=e,r=n}return Dt(c,{range:{[n]:{gte:t,lte:r}}})}return!1}case`contains`:case`doesnotcontain`:return Dt(c,{regexp:{[n]:{value:`.*${i}.*`}}});case`beginswith`:case`doesnotbeginwith`:return Dt(c,{regexp:{[n]:{value:`${i}.*`}}});case`endswith`:case`doesnotendwith`:return Dt(c,{regexp:{[n]:{value:`.*${i}`}}})}return!1},Nt=e=>e.startsWith(`not`)||e.startsWith(`doesnot`),Pt=(e,t)=>`"${typeof e!=`string`||!t?`${e}`:e.replaceAll(`"`,`\\"`)}"`,Ft=(e,t)=>t?`$not(${e})`:e,It=e=>`${e}`.replaceAll(/[/$()*+.?[\\\]^{|}]/g,String.raw`\$&`).replaceAll(`-`,String.raw`\x2d`),Lt=(e,t={})=>{let{field:n,operator:r,value:i,valueSource:a}=e,{escapeQuotes:o,parseNumbers:s,preserveValueOrder:c,quoteFieldNamesWith:l=[``,``],fieldIdentifierSeparator:u=``}=t,d=a===`field`,f=typeof i==`number`||typeof i==`boolean`||typeof i==`bigint`||q(i,s),p=e=>He(e,{quoteFieldNamesWith:l,fieldIdentifierSeparator:u}),m=J(e);if(m===!1)return;if(m){let{mode:e,threshold:r}=m,a=`$count(${p(n)})`,o=`$count($filter(${p(n)}, function($v) {${ht(W(i,{ruleProcessor:e=>({...e,field:e.field?`$v.${e.field}`:`$v`})}),t)}}))`;switch(e){case`all`:return`${o} = ${a}`;case`none`:return`${o} = 0`;case`some`:return`${o} > 0`;case`atleast`:case`atmost`:case`exactly`:{let t=e===`atleast`?`>=`:e===`atmost`?`<=`:`=`;return r>0&&r<1?`${o} ${t} (${a} * ${r})`:`${o} ${t} ${r}`}}}let h=P(r);switch(h){case`<`:case`<=`:case`=`:case`!=`:case`>`:case`>=`:return`${p(n)} ${h} ${d?p(M(i)):f?M(i):Pt(i,o)}`;case`contains`:case`doesnotcontain`:return Ft(`$contains(${p(n)}, ${d?p(M(i)):Pt(i,o)})`,Nt(h));case`beginswith`:case`doesnotbeginwith`:return Ft(d?`$substring(${p(n)}, 0, $length(${p(M(i))})) = ${p(M(i))}`:`$contains(${p(n)}, /^${It(i)}/)`,Nt(h));case`endswith`:case`doesnotendwith`:return Ft(d?`$substring(${p(n)}, $length(${p(n)}) - $length(${p(M(i))})) = ${p(M(i))}`:`$contains(${p(n)}, /${It(i)}$/)`,Nt(h));case`null`:return`${p(n)} = null`;case`notnull`:return`${p(n)} != null`;case`in`:case`notin`:{let e=N(i);return Ft(`${p(n)} in [${e.map(e=>d?`${p(M(e))}`:q(e,s)?`${M(e)}`:Pt(e,o)).join(`, `)}]`,Nt(h))}case`between`:case`notbetween`:{let e=N(i);if(e.length<2||I(e[0])||I(e[1]))return``;let[t,r]=e,a=s!==!1,l=q(t,a)?U(t,{parseNumbers:a}):NaN,u=q(r,a)?U(r,{parseNumbers:a}):NaN,f=Number.isNaN(l)?d?`${t}`:t:l,m=Number.isNaN(u)?d?`${r}`:r:u;if(!c&&f===l&&m===u&&u<l){let e=u;m=l,f=e}let g=q(t,s)&&q(r,s),_=(e,t)=>d?p(e):g?t:Pt(t,o),v=`${p(n)} >= ${_(t,f)} and ${p(n)} <= ${_(r,m)}`;return h===`between`?`(${v})`:Ft(v,!0)}}return``},Rt=e=>e.replace(/^(=)$/,`$1=`).replace(/^notnull$/i,`!=`).replace(/^null$/i,`==`),zt=(e,t)=>e.startsWith(`not`)||e.startsWith(`doesnot`)?{"!":t}:t,Bt=(e,t={})=>{let{field:n,operator:r,value:i,valueSource:a}=e,{parseNumbers:o,preserveValueOrder:s}=t,c=a===`field`,l={var:n},u=e=>c?{var:`${e}`}:q(e,o)?U(e,{parseNumbers:o}):e,d=J(e);if(d===!1)return!1;if(d){let{mode:e,threshold:r}=d;switch(e){case`all`:case`none`:case`some`:return{[e]:[{var:n},i.rules.length===1&&!L(i.rules[0])?Bt(i.rules[0],t):gt(i,t)]};case`atleast`:case`atmost`:case`exactly`:{let a=e===`atleast`?`>=`:e===`atmost`?`<=`:`==`,o={reduce:[{filter:[{var:n},i.rules.length===1&&!L(i.rules[0])?Bt(i.rules[0],t):gt(i,t)]},{"+":[1,{var:`accumulator`}]},0]};if(r>0&&r<1){let e={reduce:[{var:n},{"+":[1,{var:`accumulator`}]},0]};return{[a]:[o,{"*":[e,r]}]}}return{[a]:[o,r]}}}}let f=P(r);switch(f){case`<`:case`<=`:case`=`:case`!=`:case`>`:case`>=`:return{[Rt(f)]:[l,u(i)]};case`null`:case`notnull`:return{[`${f===`notnull`?`!`:`=`}=`]:[l,null]};case`in`:case`notin`:return zt(f,{in:[l,N(i).map(e=>u(e))]});case`between`:case`notbetween`:{let e=N(i);if(e.length>=2&&K(e[0])&&K(e[1])){let[t,n]=e,r=o!==!1;if(!c&&q(t,r)&&q(n,r)){let e=U(t,{parseNumbers:r}),i=U(n,{parseNumbers:r});if(!s&&i<e){let r=i;n=e,t=r}else t=e,n=i}else c&&(t={var:t},n={var:n});return zt(f,{"<=":[t,l,n]})}return!1}case`contains`:case`doesnotcontain`:return zt(f,{in:[u(i),l]});case`beginswith`:case`doesnotbeginwith`:return zt(f,{startsWith:[l,u(i)]});case`endswith`:case`doesnotendwith`:return zt(f,{endsWith:[l,u(i)]})}return!1},Vt=(e,t)=>t?`(!${e})`:`${e}`,Ht=e=>`${M(e)}`.replaceAll(/[()&|=<>~*\\/]/g,e=>`\\${e.codePointAt(0).toString(16)}`),Ut=(e,t={})=>{let{field:n,operator:r,value:i,valueSource:a}=e,{preserveValueOrder:o}=t,s=P(r);if(a===`field`||I(i)&&s!==`null`&&s!==`notnull`||J(e))return``;switch(s){case`=`:case`!=`:return Vt(`(${n}=${Ht(i)})`,s===`!=`);case`>`:case`>=`:return`(${n}>=${Ht(i)})`;case`<`:case`<=`:return`(${n}<=${Ht(i)})`;case`contains`:case`doesnotcontain`:return Vt(`(${n}=*${Ht(i)}*)`,s===`doesnotcontain`);case`beginswith`:case`doesnotbeginwith`:return Vt(`(${n}=${Ht(i)}*)`,s===`doesnotbeginwith`);case`endswith`:case`doesnotendwith`:return Vt(`(${n}=*${Ht(i)})`,s===`doesnotendwith`);case`null`:case`notnull`:return Vt(`(${n}=*)`,s===`notnull`);case`in`:case`notin`:return Vt(`(|${N(i).map(e=>`(${n}=${Ht(e)})`).join(``)})`,s===`notin`);case`between`:case`notbetween`:{let e=N(i);if(e.length<2||I(e[0])||I(e[1]))return``;let[t,r]=e,a=q(t,!0)?U(t,{parseNumbers:!0}):NaN,c=q(r,!0)?U(r,{parseNumbers:!0}):NaN,l=Number.isNaN(a)?t:a,u=Number.isNaN(c)?r:c;if(!o&&l===a&&u===c&&c<a){let e=c;u=a,l=e}return Vt(`(&(${n}>=${Ht(l)})(${n}<=${Ht(u)}))`,s===`notbetween`)}}return``},Wt=(e,t,n)=>n&&typeof e==`string`?e.replaceAll(`${t}`,`${t}${t}`):e,Gt=(e,t={})=>{let{escapeQuotes:n,fields:r,parseNumbers:i,quoteFieldNamesWith:a,quoteValuesWith:o,fieldIdentifierSeparator:s,translations:c}=t,l=e.valueSource===`field`,u=P(e.operator),d=o||`'`,f=e=>`${d}${e}${d}`,p=e=>Wt(e,d,n),m=e=>f(p(e)),h=e=>He(e,{quoteFieldNamesWith:a,fieldIdentifierSeparator:s}),g=c??{},_=g.or??`or`,v=g.true??`true`,y=g.false??`false`;switch(u){case`null`:case`notnull`:return``;case`between`:case`notbetween`:{if(!l)return dt(e,t);let n=N(e.value,{retainEmptyStrings:!0}).slice(0,2).map(e=>h(V(r??[],e)?.label??e));return n.length<2||!K(n[0])||!K(n[1])?``:dt({...e,value:n},t)}case`in`:case`notin`:{let t=N(e.value);if(t.length===0)return``;let n=t.map(e=>l?h(V(r??[],e)?.label??e):q(e,i)?`${M(e)}`:`${m(e)}`);return`${n.slice(0,-1).join(`, `)}${n.length>2?`,`:``} ${_} ${n.at(-1)}`}}return typeof e.value==`boolean`?e.value?v:y:l?h(V(r??[],e.value)?.label??e.value):q(e.value,i)?`${M(e.value)}`:`${m(e.value)}`},Kt={"=":[`is`,`is the same as the value in`],"!=":[`is not`,`is not the same as the value in`],"<":[`is less than`,`is less than the value in`],">":[`is greater than`,`is greater than the value in`],"<=":[`is less than or equal to`,`is less than or equal to the value in`],">=":[`is greater than or equal to`,`is greater than or equal to the value in`],contains:[`contains`,`contains the value in`],beginswith:[`starts with`,`starts with the value in`],endswith:[`ends with`,`ends with the value in`],doesnotcontain:[`does not contain`,`does not contain the value in`],doesnotbeginwith:[`does not start with`,`does not start with the value in`],doesnotendwith:[`does not end with`,`does not end with the value in`],null:`is null`,notnull:`is not null`,in:[`is one of the values`,`is the same as a value in`],notin:[`is not one of the values`,`is not the same as any value in`],between:[`is between`,`is between the values in`],notbetween:[`is not between`,`is not between the values in`]},qt=()=>[],Jt=(e,t={})=>{let{field:n,operator:r,valueSource:i=`value`}=e,{getOperators:a=qt,operatorMap:o=Kt}=t,s=new Map(Object.entries(Kt));for(let[e,t]of Object.entries(o))s.set(P(e),t);let c=Object.fromEntries(s),{value:l,label:u}=V(ge(a(n,{fieldData:t.fieldData??{name:n,value:n,label:n}})??[]),r)??{name:r,value:r,label:r},d=c[l]??c[P(l)]??[u,u];return typeof d==`string`?d:d[i===`field`?1:0]},Yt=(e,t)=>{let{field:n,operator:r}=e,{fieldData:i,quoteFieldNamesWith:a=[``,``],fieldIdentifierSeparator:o=``,quoteValuesWith:s=`'`,operatorProcessor:c=Jt,valueProcessor:l=Gt,concatOperator:u=`||`,wordOrder:d=`SVO`}=t??{},f=He(i?.label??n,{quoteFieldNamesWith:a,fieldIdentifierSeparator:o}),p=J(e);if(p===!1)return``;if(p){let{mode:n,threshold:r}=p,a=bt(e.value,{...t,fields:ge(i?.subproperties??[])}),o=(i?.subproperties?.length??0)>0;switch(n){case`all`:return`(${o?`for `:``}every item in ${f}${o?`,`:``} ${a})`;case`none`:return`(${o?`for `:``}no item in ${f}${o?`,`:``} ${a})`;case`some`:return`(${o?`for `:``}at least one item in ${f}${o?`,`:``} ${a})`;case`atleast`:case`atmost`:case`exactly`:{let e=n.replace(`at`,`at `);return r>0&&r<1?`(${o?`for `:``}${e} ${r*100}% of the items in ${f}${o?`,`:``} ${a})`:`(${o?`for `:``}${e} ${r} of the items in ${f}${o?`,`:``} ${a})`}}}let m=l(e,{...t,quoteFieldNamesWith:a,fieldIdentifierSeparator:o,quoteValuesWith:s,concatOperator:u}),h=P(r);if((h===`in`||h===`notin`||h===`between`||h===`notbetween`)&&!m)return``;let g={S:f,V:c(e,t),O:m};return We(d).map(e=>`${g[e]}`).join(` `).trim()},Xt=e=>P(Pe(e.operator)),Zt=(e,t={})=>{let{quoteFieldNamesWith:n=[``,``],fieldIdentifierSeparator:r=``,quoteValuesWith:i=`'`,operatorProcessor:a=Xt,valueProcessor:o=dt,concatOperator:s=`||`}=t,c=e=>He(e,{quoteFieldNamesWith:n,fieldIdentifierSeparator:r}),l=c(e.field),u=J(e);if(u===!1)return;if(u){if(t?.preset!==`postgresql`)return``;let{mode:n,threshold:r}=u,i=`elem_alias`,a=Tt(W(e.value,{ruleProcessor:e=>({...e,field:i})}),t);switch(n){case`all`:return`(select count(*) from unnest(${l}) as ${c(i)} where ${a}) = array_length(${l}, 1)`;case`none`:return`not exists (select 1 from unnest(${l}) as ${c(i)} where ${a})`;case`some`:return`exists (select 1 from unnest(${l}) as ${c(i)} where ${a})`;case`atleast`:case`atmost`:case`exactly`:{let e=n===`atleast`?`>=`:n===`atmost`?`<=`:`=`;return`(select count(*)${r>0&&r<1?` / array_length(${l}, 1)`:``} from unnest(${l}) as ${c(i)} where ${a}) ${e} ${r}`}}}let d=o(e,{...t,quoteFieldNamesWith:n,fieldIdentifierSeparator:r,quoteValuesWith:i,concatOperator:s}),f=a(e,t),p=P(f);return(p===`in`||p===`not in`||p===`between`||p===`not between`)&&!d?``:`${l} ${f} ${d}`.trim()},Qt=(e,t,n)=>{let{fieldData:r,format:i,getNextNamedParam:a,parseNumbers:o,paramPrefix:s,paramsKeepPrefix:c,numberedParams:l,quoteFieldNamesWith:u=[``,``],fieldIdentifierSeparator:d,concatOperator:f,operatorProcessor:p=Xt,valueProcessor:m=dt}=t??{},{processedParams:h=[]}=n??{},g=i===`parameterized`,_=[],v={},y=e=>g?{sql:e,params:_}:{sql:e,params:v},b=e=>He(e,{quoteFieldNamesWith:u,fieldIdentifierSeparator:d}),x=b(e.field),S=J(e);if(S===!1)return;if(S){if(t?.preset!==`postgresql`)return y(``);let{mode:n,threshold:r}=S,i=`elem_alias`,{sql:a,params:o}=xt(W(e.value,{ruleProcessor:e=>({...e,field:i})}),{...t,fields:[]});switch(Array.isArray(o)?_.push(...o):Object.assign(v,o),n){case`all`:return y(`(select count(*) from unnest(${x}) as ${b(i)} where ${a}) = array_length(${x}, 1)`);case`none`:return y(`not exists (select 1 from unn