@enfyra/kernel 1.1.56 → 1.1.57

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.d.ts CHANGED
@@ -34,6 +34,7 @@ export class QueryBuilderService {
34
34
  deleteWithOptions(...args: any[]): Promise<any>;
35
35
  count(...args: any[]): Promise<number>;
36
36
  insert(...args: any[]): Promise<any>;
37
+ createMany(...args: any[]): Promise<any[]>;
37
38
  insertMany(...args: any[]): Promise<any[]>;
38
39
  update(...args: any[]): Promise<any>;
39
40
  updateMany(...args: any[]): Promise<number>;
package/dist/index.js CHANGED
@@ -49,5 +49,5 @@ ${e}
49
49
  }
50
50
  }
51
51
  return true;
52
- }`}var Br="mongo-fold-text-search.body.txt",Ue=null;function so(){let r=[qn.join(__dirname,Br),qn.join(process.cwd(),"dist","kernel","query","utils",Br)];for(let e of r)try{if(on.existsSync(e))return on.readFileSync(e,"utf8")}catch{}return null}function sn(){if(Ue!==null)return Ue;let r=so();return r?(Ue=r,Ue):(Ue=rn(),Ue)}var we=require("mongodb");function W(r,e,t,n){if(t==="_id"){if(n instanceof we.ObjectId)return n;if(typeof n=="string")try{return new we.ObjectId(n)}catch{return n}return n}let i=r?.tables?.get(e);if(!i){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}return n}if(!i.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}return n}let o=i.columns.find(s=>s.name===t);if(!o){if(i.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}return n}if(n==null)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;case"uuid":if(typeof n=="string")try{return new we.ObjectId(n)}catch{return n}return n;default:return n}}var an="__mongoFoldTextTriples";function ao(r){return r==="_id"?"$_id":`$${r}`}function Qe(r,e,t,n){let i=ao(e),o=r[an]??[];o.push({ref:i,needle:t,mode:n}),r[an]=o}function lo(r){let e=r[an];if(delete r[an],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:sn(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}function Je(r,e,t,n){let i={},o=n==="mongodb"||!n;for(let s of e){let a=s.field.includes(".")?s.field.split(".").pop()??s.field:s.field,u=t||s.field.split(".")[0]||"";o&&a==="id"&&(a="_id");let c=W(r,u,a,s.value);switch(s.operator){case"=":i[a]=c;break;case"!=":i[a]={$ne:c};break;case">":i[a]={$gt:c};break;case"<":i[a]={$lt:c};break;case">=":i[a]={$gte:c};break;case"<=":i[a]={$lte:c};break;case"like":i[a]={$regex:c.replace(/%/g,".*"),$options:"i"};break;case"in":let d=s.value;Array.isArray(d)||(d=typeof d=="string"&&d.includes(",")?d.split(",").map(y=>y.trim()):[d]);let l=d.map(y=>W(r,u,a,y));i[a]={$in:l};break;case"not in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(y=>y.trim()):[f]);let p=f.map(y=>W(r,u,a,y));i[a]={$nin:p};break;case"is null":i[a]=null;break;case"is not null":i[a]={$ne:null};break;case"_contains":Qe(i,a,String(c),"contains");break;case"_starts_with":Qe(i,a,String(c),"starts");break;case"_ends_with":Qe(i,a,String(c),"ends");break;case"_between":let m=s.value;if(typeof m=="string"&&(m=m.split(",").map(y=>y.trim())),Array.isArray(m)&&m.length===2){let y=W(r,u,a,m[0]),b=W(r,u,a,m[1]);i[a]={$gte:y,$lte:b}}break;case"_is_null":let g=c===!0||c==="true";i[a]=g?{$eq:null}:{$ne:null};break;case"_is_not_null":let h=c===!0||c==="true";i[a]=h?{$ne:null}:{$eq:null};break}}return lo(i),i}function Lr(r,e,t){let i=r?.tables?.get?.(e)?.columns?.find(o=>o.name===t);return i?i.isNullable!==!1:!0}function ln(r,e,t,n,i,o){switch(i){case"_contains":Qe(e,n,String(o),"contains");break;case"_starts_with":Qe(e,n,String(o),"starts");break;case"_ends_with":Qe(e,n,String(o),"ends");break;case"_eq":e[n]=W(r,t,n,o);break;case"_neq":{let l=W(r,t,n,o);Lr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:l}})):e[n]={$ne:l};break}case"_in":{let l=o;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(p=>p.trim()):[l]);let f=l.map(p=>W(r,t,n,p));e[n]={$in:f};break}case"_not_in":case"_nin":let s=o;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(l=>l.trim()):[s]);let a=s.map(l=>W(r,t,n,l));Lr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$nin:a}})):e[n]={$nin:a};break;case"_gt":e[n]={$gt:W(r,t,n,o)};break;case"_gte":e[n]={$gte:W(r,t,n,o)};break;case"_lt":e[n]={$lt:W(r,t,n,o)};break;case"_lte":e[n]={$lte:W(r,t,n,o)};break;case"_is_null":let u=o===!0||o==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let c=o===!0||o==="true";e[n]=c?{$ne:null}:{$eq:null};break;case"_between":let d=o;if(typeof d=="string"&&(d=d.split(",").map(l=>l.trim())),Array.isArray(d)&&d.length===2){let l=W(r,t,n,d[0]),f=W(r,t,n,d[1]);e[n]={$gte:l,$lte:f}}break}}var Gn=require("mongodb");function re(r,e){if(!r||typeof r!="object")return!1;for(let[t,n]of Object.entries(r))if(t==="_and"||t==="_or"){if(Array.isArray(n)){for(let i of n)if(re(i,e))return!0}}else if(t==="_not"){if(re(n,e))return!0}else if(e.has(t))return!0;return!1}function G(r,e){if(!r||typeof r!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},n={},i=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(r)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(i.has(s))if(typeof a=="object"&&a!==null){let u=Object.keys(a);if(u.some(d=>d.startsWith("_"))){let d=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&d.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let o=re(r,i);return{fieldFilters:t,relationFilters:n,hasRelations:o}}Et();Ot();var pn="__mongoFoldTextTriples";function Ve(r,e){if(!r)return{};let t={};return At(r,t,e),Te(t),t}function yo(r,e){if(!r)return{};let t={};return Jn(r,t,e),Te(t),t}function he(r,e,t){if(!e)return{};let n=new oe,{node:i}=pe(e,t,r,n);return Ve(i,{metadata:r,rootTable:t})}function gn(r,e,t){if(!e)return{};let n=new oe,{node:i}=pe(e,t,r,n);return yo(i,{metadata:r,rootTable:t})}function At(r,e,t){switch(r.kind){case"true":return;case"false":ge(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let i=r.children.map(o=>{let s={};return At(o,s,t),Te(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}ge(e,...i);return}case"or":{let i=r.children.map(s=>{let a={};return At(s,a,t),Te(a),a}).filter(s=>Object.keys(s).length>0);if(i.length===0)return;let o=e.$or;e.$or=o?[...o,...i]:i;return}case"not":{let n={};At(r.child,n,t),Te(n);let i=e.$nor;e.$nor=i?[...i,n]:[n];return}case"compare":Ur(r,e,t);return;case"relation_exists":{console.warn(`[mongo-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${r.joinId}) \u2014 expected applyRelationFilters or null-only short-circuit to handle it. Filter silently skipped.`);return}}}function Ur(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let i=o=>W(t.metadata,t.rootTable,n,o);switch(r.op){case"eq":ee(e,n,i(r.value));return;case"neq":{let o=i(r.value);zn(t,n)?ge(e,{[n]:{$ne:null}},{[n]:{$ne:o}}):ee(e,n,{$ne:o});return}case"gt":ee(e,n,{$gt:i(r.value)});return;case"gte":ee(e,n,{$gte:i(r.value)});return;case"lt":ee(e,n,{$lt:i(r.value)});return;case"lte":ee(e,n,{$lte:i(r.value)});return;case"in":{let o=qr(r.value).map(i);ee(e,n,{$in:o});return}case"not_in":{let o=qr(r.value).map(i);zn(t,n)?ge(e,{[n]:{$ne:null}},{[n]:{$nin:o}}):ee(e,n,{$nin:o});return}case"between":{let o=Array.isArray(r.value)?r.value:typeof r.value=="string"?r.value.split(",").map(s=>s.trim()):null;Array.isArray(o)&&o.length===2&&ee(e,n,{$gte:i(o[0]),$lte:i(o[1])});return}case"is_null":ee(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":Qn(e,n,String(r.value),"contains");return;case"starts_with":Qn(e,n,String(r.value),"starts");return;case"ends_with":Qn(e,n,String(r.value),"ends");return}}function Jn(r,e,t){switch(r.kind){case"true":ge(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let i=r.children.map(s=>{let a={};return Jn(s,a,t),Te(a),a}).filter(s=>Object.keys(s).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}let o=e.$or;e.$or=o?[...o,...i]:i;return}case"or":{let i=r.children.map(o=>{let s={};return Jn(o,s,t),Te(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}ge(e,...i);return}case"not":At(r.child,e,t);return;case"compare":bo(r,e,t);return;case"relation_exists":{ee(e,r.joinId,r.negate?{$ne:null}:{$eq:null});return}}}function bo(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached false renderer \u2014 expected relation resolver to handle it. Filter silently skipped.`);return}if(r.op==="is_null"){ee(e,n,r.value===!0?{$ne:null}:{$eq:null});return}let i={};Ur(r,i,t),Te(i);let o={$nor:[i]};zn(t,n)?ge(e,o,{[n]:{$ne:null}}):ge(e,o)}function ee(r,e,t){r[e]===void 0?r[e]=t:(ge(r,{[e]:r[e]},{[e]:t}),delete r[e])}function ge(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function zn(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(i=>i.name===e);return n?n.isNullable!==!1:!0}function qr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function _o(r){return r==="_id"?"$_id":`$${r}`}function Qn(r,e,t,n){let i=_o(e),o=r[pn]??[];o.push({ref:i,needle:t,mode:n}),r[pn]=o}function Te(r){let e=r[pn];if(delete r[pn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:sn(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}async function Se(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return he(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!re(r,o))return he(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>Se(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._or&&Array.isArray(r._or)){let d=(await Promise.all(r._or.map(l=>Se(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:{$or:d}}if(r._not)return await Hn(r._not,e,t,n)||{};let{fieldFilters:s,relationFilters:a}=G(r,i),u=[];if(s&&Object.keys(s).length>0){let c=he(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(a&&Object.keys(a).length>0)for(let[c,d]of Object.entries(a)){let l=await wo(c,d,e,i,t,n);l&&Object.keys(l).length>0&&u.push(l)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function Hn(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return gn(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!re(r,o))return gn(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>Hn(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$or:d}}if(r._or&&Array.isArray(r._or)){let d=(await Promise.all(r._or.map(l=>Hn(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._not)return Se(r._not,e,t,n);let{fieldFilters:s,relationFilters:a}=G(r,i),u=[];if(s&&Object.keys(s).length>0){let c=gn(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(a&&Object.keys(a).length>0)for(let[c,d]of Object.entries(a)){let l=await To(c,d,e,i,t,n);l&&Object.keys(l).length>0&&u.push(l)}return u.length===0?{}:u.length===1?u[0]:{$or:u}}async function wo(r,e,t,n,i,o){let s=(n.relations||[]).find(c=>c.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=i?.tables?.get(a);return!a||!u?{}:s.type==="many-to-one"||s.type==="one-to-one"?$o(e,s,r,a,u,i,o):s.type==="one-to-many"?zr(e,s,t,a,u,i,o):s.type==="many-to-many"?Vr(e,s,t,a,u,i,o):{}}async function $o(r,e,t,n,i,o,s){let a=H(e)||t,u=mn(r),c=yn(u);if(c!==null)return c?{[a]:null}:{[a]:{$ne:null}};let d=Yn(u);if(d!==null){let m=bn(d.value);if(d.op==="eq")return{[a]:m};if(d.op==="neq")return{[a]:{$ne:m}};if(d.op==="in")return{[a]:{$in:m}};if(d.op==="not_in")return{$and:[{[a]:{$nin:m}},{[a]:{$ne:null}}]}}let l=await hn(u,n,i,o,s);if(!l||Object.keys(l).length===0)return{};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(m=>m._id).filter(Boolean);return p.length===0?{__impossible__:!0}:{[a]:{$in:p}}}async function To(r,e,t,n,i,o){let s=(n.relations||[]).find(c=>c.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=i?.tables?.get(a);if(!a||!u)return{};if(s.type==="many-to-one"||s.type==="one-to-one")return So(e,s,r,a,u,i,o);if(s.type==="one-to-many"){let c=await zr(e,s,t,a,u,i,o);return Jr(c)}if(s.type==="many-to-many"){let c=await Vr(e,s,t,a,u,i,o);return Jr(c)}return{}}async function So(r,e,t,n,i,o,s){let a=H(e)||t,u=mn(r),c=yn(u);if(c!==null)return c?{[a]:{$ne:null}}:{[a]:null};let d=Yn(u);if(d!==null){let m=bn(d.value);if(d.op==="eq")return{$and:[{[a]:{$ne:m}},{[a]:{$ne:null}}]};if(d.op==="neq")return{[a]:m};if(d.op==="in")return{$and:[{[a]:{$nin:m}},{[a]:{$ne:null}}]};if(d.op==="not_in")return{[a]:{$in:m}}}let l=await hn(u,n,i,o,s);if(!l||Object.keys(l).length===0)return{[a]:null};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(m=>m._id).filter(Boolean);return p.length===0?{[a]:{$ne:null}}:{$and:[{[a]:{$nin:p}},{[a]:{$ne:null}}]}}async function zr(r,e,t,n,i,o,s){let a=q(e)||t,u=mn(r),c=yn(u);if(c!==null){let f=await Qr(s,n,a,{});return c?f.length===0?{}:{_id:{$nin:f}}:f.length===0?{__impossible__:!0}:{_id:{$in:f}}}let d=await hn(u,n,i,o,s);if(!d||Object.keys(d).length===0)return{};let l=await Qr(s,n,a,d);return l.length===0?{__impossible__:!0}:{_id:{$in:l}}}async function Vr(r,e,t,n,i,o,s){let a=Me(t,e);if(!a)return{};let u=mn(r),c=yn(u);if(c!==null){let g=await Vn(s,a,n,null);return c?g.length===0?{}:{_id:{$nin:g}}:g.length===0?{__impossible__:!0}:{_id:{$in:g}}}let d=Yn(u);if(d!==null){let g=bn(d.value),h=Array.isArray(g)?g:[g],y=await Vn(s,a,n,{_id:{$in:h}});return y.length===0?{__impossible__:!0}:{_id:{$in:y}}}let l=await hn(u,n,i,o,s);if(!l||Object.keys(l).length===0)return{};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);if(p.length===0)return{__impossible__:!0};let m=await Vn(s,a,n,{_id:{$in:p}});return m.length===0?{__impossible__:!0}:{_id:{$in:m}}}async function hn(r,e,t,n,i){let o=new Set((t?.relations??[]).map(s=>s.propertyName));return re(r,o)?Se(r,e,n,i):he(n,r,e)}async function Qr(r,e,t,n){let i=await r.collection(e).find(n,{projection:{[t]:1}}).toArray(),o=new Set,s=[];for(let a of i){let u=a[t];if(u==null)continue;let c=String(u);o.has(c)||(o.add(c),s.push(u))}return s}function Jr(r){if(!r||Object.keys(r).length===0)return{};if(r.__impossible__===!0)return{};let e=r._id;if(e&&typeof e=="object"&&!Array.isArray(e)){if(Array.isArray(e.$in))return{_id:{$nin:e.$in}};if(Array.isArray(e.$nin))return{_id:{$in:e.$nin}}}return{$nor:[r]}}async function Vn(r,e,t,n){let i=null;n&&t&&(i=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(d=>d._id).filter(Boolean));let o=i?{[e.otherColumn]:{$in:i}}:{},s=await r.collection(e.junctionName).find(o,{projection:{[e.selfColumn]:1}}).toArray(),a=new Set,u=[];for(let c of s){let d=c[e.selfColumn];if(d==null)continue;let l=String(d);a.has(l)||(a.add(l),u.push(d))}return u}function mn(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function yn(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0],n=r[t];return t==="_is_null"?n===!0:t==="_is_not_null"?n!==!0:t==="_eq"?n===null?!0:null:t==="_neq"&&n===null?!1:null}function bn(r){if(Array.isArray(r))return r.map(e=>bn(e));if(typeof r!="string")return r;try{return new Gn.ObjectId(r)}catch{return r}}function Yn(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof Gn.ObjectId)return{op:"eq",value:r};if(r==null)return null;if(typeof r!="object")return{op:"eq",value:r};if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0];return t==="_eq"?{op:"eq",value:r._eq}:t==="_neq"?{op:"neq",value:r._neq}:t==="_in"&&Array.isArray(r._in)?{op:"in",value:r._in}:t==="_not_in"&&Array.isArray(r._not_in)?{op:"not_in",value:r._not_in}:null}async function Pt(r,e,t,n){let i=await Nt(r,e,t),o=[],s={},a={};if(n&&typeof n=="object")for(let[p,m]of Object.entries(n))if(typeof m=="object"&&m!==null){let g=Object.keys(m)[0];g&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(g)?s[p]=m:a[p]=m}else s[p]=m;if(Object.keys(s).length>0){let p={};for(let[m,g]of Object.entries(s))if(typeof g=="object"&&g!==null)for(let[h,y]of Object.entries(g))ln(r,p,e,m,h,y);else p[m]=g;Object.keys(p).length>0&&o.push({$match:p})}let c=r?.tables?.get(e)?.relations||[],d=[];for(let[p,m]of Object.entries(a))if(!i.relations.some(h=>h.propertyName===p)){let h=c.find(y=>y.propertyName===p);if(h){let y="",b="";if(h.type==="many-to-one"||h.type==="one-to-one")y=H(h)||h.propertyName,b="_id";else if(h.type==="one-to-many")y="_id",b=q(h)||h.propertyName;else if(h.type==="many-to-many")continue;let _=h.type==="one-to-many"||h.type==="many-to-many";d.push({propertyName:p,targetTable:h.targetTableName,localField:y,foreignField:b,type:_?"many":"one",nestedFields:[]})}}let l=[...i.relations,...d];for(let p of l){let m=a[p.propertyName],g=p.nestedFields&&p.nestedFields.length>0?await Pt(r,p.targetTable,p.nestedFields,m):m?await Pt(r,p.targetTable,["_id"],m):[];p.type==="one"&&g.length>0&&g.push({$limit:1}),o.push({$lookup:{from:p.targetTable,localField:p.localField,foreignField:p.foreignField,as:p.propertyName,pipeline:g.length>0?g:void 0}}),p.type==="one"&&(o.push({$unwind:{path:`$${p.propertyName}`,preserveNullAndEmptyArrays:!0}}),m&&(He(m)||o.push({$match:{[p.propertyName]:{$ne:null}}})))}let f=c.filter(p=>!l.some(m=>m.propertyName===p.propertyName));if(i.scalarFields.length>0||i.relations.length>0||f.length>0){let p={_id:1};for(let g of i.scalarFields)p[g]=1;for(let g of l)p[g.propertyName]=1,g.type==="one"&&g.localField&&g.localField!==g.propertyName&&(p[g.localField]=1);if(t.includes("*"))for(let g of f){if(g.type==="one-to-many"||g.type==="many-to-many")continue;g.type==="many-to-many"?p[g.propertyName]={$map:{input:`$${g.propertyName}`,as:"item",in:{_id:"$$item"}}}:p[g.propertyName]={$cond:{if:{$ne:[`$${g.propertyName}`,null]},then:{_id:`$${g.propertyName}`},else:null}}}o.push({$project:p})}return o}async function Hr(r,e,t,n,i){let o=r?.tables?.get(t),s=o?.relations||[],a=o?.columns||[],u=s.filter(d=>!i.some(l=>l.propertyName===d.propertyName)),c=n.length===a.length||n.length===0&&i.length===0;if(u.length>0||!c){let d={_id:1};for(let l of n)d[l]=1;for(let l of i)d[l.propertyName]=1,l.type==="one"&&l.localField&&l.localField!==l.propertyName&&(d[l.localField]=1);for(let l of u){if(l.type==="one-to-many"||l.type==="many-to-many")continue;l.type==="many-to-many"?d[l.propertyName]={$map:{input:`$${l.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[l.propertyName]={$cond:{if:{$ne:[`$${l.propertyName}`,null]},then:{_id:`$${l.propertyName}`},else:null}}}e.push({$project:d})}}function He(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>He(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>He(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>He(e));if("_not"in r)return He(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||He(t)))return!0}return!1}Ye();var Bt=require("mongodb");Ye();_n();async function wn(r,e,t){let n=new Map,i=0;async function o(){for(;i<r.length;){let u=i++,c=r[u];n.set(String(c),await e(c))}}let s=Math.min(t,r.length);if(s===0)return n;let a=Array.from({length:s},o);return await Promise.all(a),n}var ae="__sourceId__",Re="__targetId__",Xe="__enfyra_target__",jt="__enfyra_top_n_documents__",Ze=class{constructor(e,t,n,i=new ke){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.executionBudget=i;this.pkField="_id"}chunkCount(e){return Math.ceil(e.length/se)||1}runQuery(e){return this.executionBudget.run(e)}uniqueValues(e){return Array.from(new Map(e.filter(t=>t!=null).map(t=>[this.keyOf(t),t])).values())}buildStableSort(e,t="_id"){let n=this.buildSortFromTokens(e)||{};return n[t]===void 0&&(n[t]=1),n}appendPartitionProjection(e,t,n){if(t){let i={...t};for(let o of n)i[o]=1;e.push({$project:i})}}appendTopNStages(e,t,n,i,o){e.push({$group:{_id:`$${t}`,[jt]:{$topN:{sortBy:n,output:"$$ROOT",n:i+o}}}},{$project:{[jt]:{$slice:[`$${jt}`,i,o]}}},{$unwind:`$${jt}`},{$replaceRoot:{newRoot:`$${jt}`}})}normalizeMetadata(){return this.metadata?this.metadata.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortFromTokens(e){let t={};for(let n of this.parseSortTokens(e)){let i=n.field.split(".");if(i.length===1)t[i[0]]=n.order;else{let o=`__sort_${i.slice(0,-1).join("_")}`;t[`${o}.${i[i.length-1]}`]=n.order}}return Object.keys(t).length>0?t:void 0}parseSortTokens(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).map(n=>{let i=n.startsWith("-"),o=i?n.slice(1):n;return{field:o==="id"?"_id":o,order:i?-1:1}}):[]}hasDottedSort(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).some(n=>(n.startsWith("-")?n.slice(1):n).includes(".")):!1}buildSortAggregatePipeline(e,t,n){let i=Array.isArray(n)?n:n.split(",").map(c=>c.trim()).filter(Boolean),o=[{$match:t}],s=new Set;for(let c of i){let l=(c.startsWith("-")?c.slice(1):c).split(".");if(l.length<=1)continue;let f=e;for(let p=0;p<l.length-1;p++){let m=l[p],g=this.normalizeMetadata()?.tables?.get(f);if(!g)break;let h=g.relations?.find(_=>_.propertyName===m);if(!h)break;let y=h.targetTableName||h.targetTable,b=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(b)){s.add(b);let _=H(h)||h.propertyName,C=p===0?null:`__sort_${l.slice(0,p).join("_")}`,T=C?`${C}.${_}`:_;o.push({$lookup:{from:y,localField:T,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}f=y}}let a=this.buildSortFromTokens(n);a&&o.push({$sort:a});let u={};for(let c of s)u[c]=0;return Object.keys(u).length>0&&o.push({$project:u}),o}toObjectId(e){try{return typeof e=="string"?new Bt.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof Bt.ObjectId||t instanceof Bt.ObjectId?this.keyOf(e).localeCompare(this.keyOf(t)):typeof e=="number"&&typeof t=="number"?e-t:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="string"&&typeof t=="string"?e.localeCompare(t):e<t?-1:e>t?1:0}sortDocsInMemory(e,t){let n=this.parseSortTokens(t).filter(i=>!i.field.includes("."));n.length!==0&&e.sort((i,o)=>{for(let s of n){let a=this.compareSortValues(i[s.field],o[s.field]);if(a!==0)return a*s.order}return this.compareSortValues(i._id,o._id)})}sortDocsByPk(e){e.sort((t,n)=>this.compareSortValues(t._id,n._id))}projectionWithSortFields(e,t){if(!e)return{projection:e,hiddenFields:[]};let n={...e},i=[];for(let o of this.parseSortTokens(t))o.field.includes(".")||n[o.field]===void 0&&(n[o.field]=1,i.push(o.field));return{projection:n,hiddenFields:i}}removeHiddenFields(e,t){if(t.length!==0)for(let n of e)for(let i of t)delete n[i]}keyOf(e){return e==null?"":e instanceof Bt.ObjectId||typeof e=="object"&&typeof e.toHexString=="function"?e.toHexString():String(e)}buildScalarRef(e){return{[this.pkField]:e}}getTargetPkField(e){return this.pkField}resolveOwnerFkKey(e){return e.localField||e.fkColumn||e.relationName}resolveInverseFkField(e){return e.foreignField?e.foreignField:e.mappedBy?e.mappedBy:e.relationName}resolveParentPk(e){return this.pkField}resolveFields(e,t){let{rootFields:n,subRelations:i}=Ge(e),o={},s=!1;if(n.includes("*")){s=!0;for(let f of t.relations||[])i.has(f.propertyName)||i.set(f.propertyName,["_id"])}else for(let f of n){let p=t.columns.find(m=>m.name===f);p?o[p.name]=1:t.relations?.find(g=>g.propertyName===f)&&!i.has(f)&&i.set(f,["_id"])}i.forEach((f,p)=>{let m=t.relations?.find(g=>g.propertyName===p);m&&(m.type==="many-to-one"||m.type==="one-to-one"&&!m.isInverse)&&(s||(o[H(m)||m.propertyName]=1))}),s||(o._id=1);let a=[];i.forEach((f,p)=>{let m=t.relations?.find(b=>b.propertyName===p);if(!m)return;let g=m.targetTableName||m.targetTable;if(!g)return;let h,y;m.type==="many-to-one"||m.type==="one-to-one"?Ne(m)?(h="_id",y=q(m)||m.propertyName):(h=H(m)||m.propertyName,y="_id"):m.type==="one-to-many"?(h="_id",y=q(m)||m.propertyName):m.type==="many-to-many"&&(m.isInverse?(h="_id",y=m.mappedBy):(h=m.propertyName,y="_id")),a.push({relationName:p,type:m.type,targetTable:g,fields:f,isInverse:m.isInverse,fkColumn:m.foreignKeyColumn,mappedBy:m.mappedBy,junctionTableName:m.junctionTableName,junctionSourceColumn:m.junctionSourceColumn,junctionTargetColumn:m.junctionTargetColumn,localField:h,foreignField:y})});let u=!s&&Object.keys(o).length===1&&o._id===1&&a.length===0,c=this.fieldRenamesByTable?.get(t.name)??[],d=[];if(!s&&c.length>0)for(let f of c)o[f.newName]===1&&o[f.oldName]!==1&&(o[f.oldName]=1,d.push(f.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:o,pendingRenames:c,hiddenFields:d}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?he(this.normalizeMetadata(),i.userFilter,e):null,s=this.buildSortFromTokens(i?.userSort),a=await K(t,c=>{let d={_id:{$in:c}};o&&Object.keys(o).length>0&&Object.assign(d,o);let l={projection:n.projection};return s&&(l.sort=s),this.runQuery(()=>this.db.collection(e).find(d,l).toArray())}),u=this.applyReadFallback(a,n);return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(t),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,n,i,o){let s=i.projection?{...i.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let a=this.uniqueValues(n.map(y=>this.toObjectId(y))),u=o?.userFilter?he(this.normalizeMetadata(),o.userFilter,e):null,c=o?.userLimit,d=o?.userPage,l=this.hasDottedSort(o?.userSort);if(c!==void 0&&c>0){let y=d?(d-1)*c:0;if(l)throw new Error(`Dotted sort is not supported for batch relation '${o?.relationName}'`);let b=this.buildStableSort(o?.userSort),_=await K(a,async C=>{let T={[t]:{$in:C}};u&&Object.keys(u).length>0&&Object.assign(T,u);let k=[{$match:T}];this.appendTopNStages(k,t,b,y,c),k.push({$sort:{[t]:1,...b}}),this.appendPartitionProjection(k,s,[t]);let F=await this.runQuery(()=>this.db.collection(e).aggregate(k).toArray());return this.applyReadFallback(F,i)});return{docs:_,groupKeyField:t,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:_.length}}}if(s&&(s[t]=1),l){let y=[],b=await wn(a,async _=>{let C={[t]:_};u&&Object.keys(u).length>0&&Object.assign(C,u);let T=this.buildSortAggregatePipeline(e,C,o.userSort);s&&T.push({$project:s});let k=await this.runQuery(()=>this.db.collection(e).aggregate(T).toArray());return this.applyReadFallback(k,i)},Oe);for(let _ of b.values())for(let C of _)y.push(C);return{docs:y,groupKeyField:t,stats:{strategy:"per-parent-dotted-sort",roundtrips:a.length,concurrencyWaves:Math.ceil(a.length/Oe),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:y.length}}}let f={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(f,u);let p=this.buildSortFromTokens(o?.userSort)||{_id:1},m={projection:s,sort:p},g=await K(a,y=>this.runQuery(()=>this.db.collection(e).find({[t]:{$in:y},...u||{}},m).toArray())),h=this.applyReadFallback(g,i);return{docs:h,groupKeyField:t,stats:{strategy:"batch-in",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:h.length}}}postProcessInverseChild(e,t,n){n||delete e[t]}m2mSortCanUseJunction(e){return this.parseSortTokens(e).every(t=>t.field==="_id")}async loadM2MTargets(e,t,n){if(t.length===0)return[];let i=n.projection?{projection:n.projection}:void 0,o=await K(t,s=>this.runQuery(()=>this.db.collection(e).find({_id:{$in:s}},i).toArray()));return this.applyReadFallback(o,n)}async fetchM2MTopK(e,t,n,i,o,s,a){if(this.hasDottedSort(t.userSort))throw new Error(`Dotted sort is not supported for batch relation '${t.relationName}'`);let u=new Map;for(let y of e)u.set(this.keyOf(y),[]);let c=i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1,d=!o&&this.m2mSortCanUseJunction(t.userSort),l=this.parseSortTokens(t.userSort).find(y=>y.field==="_id")?.order??1,f=this.buildStableSort(t.userSort),p=await K(e,async y=>{if(d){let C=[{$match:{[n.selfColumn]:{$in:y}}}];return this.appendTopNStages(C,n.selfColumn,{[n.otherColumn]:l},s,a),C.push({$sort:{[n.selfColumn]:1,[n.otherColumn]:l}},{$project:{_id:0,[ae]:`$${n.selfColumn}`,[Re]:`$${n.otherColumn}`}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(C).toArray())).map(k=>({sourceId:k[ae],targetId:k[Re]}))}let b=[{$match:{[n.selfColumn]:{$in:y}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Xe}},{$unwind:`$${Xe}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Xe}`,{[ae]:`$${n.selfColumn}`,[Re]:`$${n.otherColumn}`}]}}}];return o&&Object.keys(o).length>0&&b.push({$match:o}),this.appendTopNStages(b,ae,f,s,a),b.push({$sort:{[ae]:1,...f}}),b.push({$project:{_id:0,[ae]:1,[Re]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(b).toArray())).map(C=>({sourceId:C[ae],targetId:C[Re]}))});if(c){let y=new Map;for(let b of p){let _=this.keyOf(b.targetId);y.has(_)||y.set(_,{_id:b.targetId}),u.get(this.keyOf(b.sourceId))?.push(y.get(_))}return{grouped:u,docs:[],stats:{strategy:d?"m2m-junction-partitioned-top-k":"m2m-filtered-edge-top-k",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let m=this.uniqueValues(p.map(y=>y.targetId)),g=await this.loadM2MTargets(t.targetTable,m,i),h=new Map(g.map(y=>[this.keyOf(y._id),y]));for(let y of p){let b=h.get(this.keyOf(y.targetId));b&&u.get(this.keyOf(y.sourceId))?.push(b)}return{grouped:u,docs:g,stats:{strategy:"m2m-partitioned-edge-loader",roundtrips:this.chunkCount(e)+(m.length>0?this.chunkCount(m):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+g.length,rowsDiscarded:0}}}async fetchM2MEdgeBatch(e,t,n,i,o){let s=new Map;for(let g of e)s.set(this.keyOf(g),[]);let a=!o&&this.m2mSortCanUseJunction(t.userSort),u=this.parseSortTokens(t.userSort).find(g=>g.field==="_id")?.order??1,c=this.buildStableSort(t.userSort),d=await K(e,async g=>{if(a)return(await this.runQuery(()=>this.db.collection(n.junctionName).find({[n.selfColumn]:{$in:g}},{projection:{_id:0,[n.selfColumn]:1,[n.otherColumn]:1},sort:{[n.selfColumn]:1,[n.otherColumn]:u}}).toArray())).map(_=>({sourceId:_[n.selfColumn],targetId:_[n.otherColumn]}));let h=[{$match:{[n.selfColumn]:{$in:g}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Xe}},{$unwind:`$${Xe}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Xe}`,{[ae]:`$${n.selfColumn}`,[Re]:`$${n.otherColumn}`}]}}}];return o&&Object.keys(o).length>0&&h.push({$match:o}),h.push({$sort:{[ae]:1,...c}},{$project:{_id:0,[ae]:1,[Re]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(h).toArray())).map(b=>({sourceId:b[ae],targetId:b[Re]}))});if(i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1){let g=new Map;for(let h of d){let y=this.keyOf(h.targetId);g.has(y)||g.set(y,{_id:h.targetId}),s.get(this.keyOf(h.sourceId))?.push(g.get(y))}return{grouped:s,docs:[],stats:{strategy:a?"m2m-junction-batch":"m2m-filtered-edge-batch",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length,rowsDiscarded:0}}}let f=this.uniqueValues(d.map(g=>g.targetId)),p=await this.loadM2MTargets(t.targetTable,f,i),m=new Map(p.map(g=>[this.keyOf(g._id),g]));for(let g of d){let h=m.get(this.keyOf(g.targetId));h&&s.get(this.keyOf(g.sourceId))?.push(h)}return{grouped:s,docs:p,stats:{strategy:"m2m-edge-loader",roundtrips:this.chunkCount(e)+(f.length>0?this.chunkCount(f):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length+p.length,rowsDiscarded:0}}}async fetchM2M(e,t,n,i,o){let s=n?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=Me(s,{type:"many-to-many",propertyName:t.relationName,targetTable:t.targetTable,mappedBy:t.isInverse?t.mappedBy:void 0,junctionTableName:t.junctionTableName,junctionSourceColumn:t.junctionSourceColumn,junctionTargetColumn:t.junctionTargetColumn});if(!a)throw new Error(`Failed to resolve junction info for ${s}.${t.relationName}`);let u=this.uniqueValues(e.map(k=>k._id)),c=new Map;for(let k of e)c.set(this.keyOf(k._id),[]);if(u.length===0)return{grouped:c,docs:[]};let d=t.userFilter?he(this.normalizeMetadata(),t.userFilter,t.targetTable):null,l=t.userLimit,f=t.userPage;if(l!==void 0&&l>0){let k=f?(f-1)*l:0;return this.fetchM2MTopK(u,t,a,o,d,k,l)}let p=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1&&!d,m=this.hasDottedSort(t.userSort);if(!m)return this.fetchM2MEdgeBatch(u,t,a,o,d);let g=await K(u,k=>this.runQuery(()=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:k}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray()));if(g.length===0)return{grouped:c,docs:[],stats:{strategy:"m2m-batch",roundtrips:this.chunkCount(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:0}};let h=new Set,y=[];for(let k of g){let F=k[a.otherColumn];if(F==null)continue;let w=this.keyOf(F);h.has(w)||(h.add(w),y.push(F))}let b=[],_=new Map;if(p)b=y.map(k=>({_id:k})),this.sortDocsByPk(b);else{let k={_id:{$in:y}};d&&Object.keys(d).length>0&&Object.assign(k,d);let F;if(m){let w=this.buildSortAggregatePipeline(t.targetTable,k,t.userSort);o.projection&&w.push({$project:o.projection}),F=await this.runQuery(()=>this.db.collection(t.targetTable).aggregate(w).toArray())}else{let w=this.buildSortFromTokens(t.userSort)||{_id:1},v=this.projectionWithSortFields(o.projection,t.userSort),B={sort:w};v.projection&&(B.projection=v.projection),F=await K(y,S=>this.runQuery(()=>this.db.collection(t.targetTable).find({_id:{$in:S},...d||{}},B).toArray())),t.userSort?this.sortDocsInMemory(F,t.userSort):this.sortDocsByPk(F),this.removeHiddenFields(F,v.hiddenFields)}b=this.applyReadFallback(F,o)}for(let k of b)_.set(this.keyOf(k._id),k);let C=new Map;for(let k of g){let F=this.keyOf(k[a.selfColumn]),w=this.keyOf(k[a.otherColumn]);_.has(w)&&(C.has(w)||C.set(w,[]),C.get(w).push(F))}for(let k of b){let F=C.get(this.keyOf(k._id))||[];for(let w of F)c.get(w)?.push(k)}let T=p||y.length===0?0:this.chunkCount(y);return{grouped:c,docs:b,stats:{strategy:p?"m2m-junction-batch":"m2m-batch",roundtrips:this.chunkCount(u)+T,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length+b.length}}}applyReadFallback(e,t){let n=t.pendingRenames??[];if(e.length===0||n.length===0)return e;let i=new Set(t.hiddenFields??[]);for(let o of e)for(let s of n)o[s.newName]===void 0&&o[s.oldName]!==void 0&&(o[s.newName]=o[s.oldName]),(i.has(s.oldName)||o[s.newName]!==void 0)&&delete o[s.oldName];return e}};async function $n(r,e,t,n,i=3,o=0,s,a,u,c){let d=await c?.getActiveFieldRenamesByTable?.(),l=new Ze(r,a,d);await new Ce(l,n,u).execute(e,t,i,o,s)}async function er(r,e,t){let n=[],{db:i,metadata:o,dbType:s,debugLog:a}=t,u=o?.tables?.get(e.table),c=new Set((u?.relations??[]).map(S=>S.propertyName)),d=!!e.mongoRawFilter&&!!o&&re(e.mongoRawFilter,c),l=e.plan,f=l?.filterTree&&!l.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&o&&d){let S=await Se(e.mongoRawFilter,e.table,o,i);S&&Object.keys(S).length>0&&n.push({$match:S})}else if(f){let S=Ve(l.filterTree,{metadata:o,rootTable:e.table});Object.keys(S).length>0&&n.push({$match:S})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let S=Je(o,e.where,e.table,s);n.push({$match:S})}let p=e.plan,g=p?p.hasRelationSort:e.sort?.some(S=>{if(!S.field.includes("."))return!1;let M=S.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(A=>A.propertyName===M)??!1})??!1,h=()=>p?.sortItems?Io(p.sortItems):e.sort?vo(e.sort):null,y=p?.sortItems?Co(p.sortItems):[],b=p?.sortItems?ko(p.sortItems):[],_=()=>{!p||y.length===0||Ro(n,e.table,p.sortItems,o)},C=()=>{!p||b.length===0||Fo(n,e.table,p.sortItems,o)},T=()=>{let S=[...y,...b];S.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(S.map(M=>[M,0]))})};if(!e.mongoFieldsExpanded){_(),C();let S=h();if(S&&n.push({$sort:S}),e.mongoCountOnly?n.push({$count:"count"}):(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit})),T(),e.select){let A={};for(let D of e.select)A[D]=1;n.push({$project:A})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let M=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:M,pipeline:n}:{results:Yr(M),pipeline:n}}let{scalarFields:k,relations:F}=e.mongoFieldsExpanded;if(!g){_(),C();let S=h();S&&n.push({$sort:S}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}let w=[];for(let S of F)if(e.sort?.some(A=>A.field.startsWith(`${S.propertyName}.`))){let A=e.mongoRawFilter?.[S.propertyName];if(S.nestedFields&&S.nestedFields.length>0){let j=await Pt(o,S.targetTable,S.nestedFields??[],A);S.type==="one"&&j.length>0&&j.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:j.length>0?j:void 0}})}else if(A){let j=await Pt(o,S.targetTable,["_id"],A);S.type==="one"&&j.length>0&&j.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:j.length>0?j:void 0}})}else n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName}});S.type==="one"&&(n.push({$unwind:{path:`$${S.propertyName}`,preserveNullAndEmptyArrays:!0}}),A&&(et(A)||n.push({$match:{[S.propertyName]:{$ne:null}}})))}else w.push(S);if(g){_(),C();let S=h();S&&n.push({$sort:S}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}T(),await Hr(o,n,e.table,k,[...F]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let v=performance.now(),B=await r.aggregate(n).toArray();if(e.debugTrace?.dur("db_execute",v,{table:e.table}),e.mongoCountOnly)return{results:B,pipeline:n};if(w.length>0&&B.length>0){let S=e.deep||{},M=w.map(D=>{let $=o?.tables?.get(e.table)?.relations?.find(J=>J.propertyName===D.propertyName),R=S[D.propertyName],N=R?.fields!=null?Array.isArray(R.fields)?R.fields:String(R.fields).split(",").map(J=>J.trim()).filter(Boolean):D.nestedFields&&D.nestedFields.length>0?D.nestedFields:["_id"];return{relationName:D.propertyName,type:$?.type,targetTable:D.targetTable,fields:N,isInverse:$?.isInverse,mappedBy:$?.mappedBy,junctionTableName:$?.junctionTableName,junctionSourceColumn:$?.junctionSourceColumn,junctionTargetColumn:$?.junctionTargetColumn,localField:D.localField,foreignField:D.foreignField,userFilter:R?.filter,userSort:R?.sort,userLimit:R?.limit!==void 0?Number(R.limit):void 0,userPage:R?.page!==void 0?Number(R.page):void 0,nestedDeep:R?.deep}}),A=xo(o);A&&await $n(i,B,M,A,3,0,e.table,o,e.debugTrace,t.mongoPhysicalMigrationService)}return{results:Yr(B),pipeline:n}}function tr(r){return`__sort_count_${r.relationName||r.field}`}function nr(r){return`__sort_${r.function}_${r.relationName||r.field}_${r.aggregateField||"value"}`}function Co(r){return r.filter(e=>e.function==="count").map(tr)}function ko(r){return r.filter(e=>e.function==="max"||e.function==="min").map(nr)}function Ro(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="count")continue;let a=s.relationMeta,u=s.relationName||s.field,c=a?.targetTableName||a?.targetTable,d=tr(s);if(!(!a||!c)){if(a.type==="one-to-many"){let l=q(a)||u;r.push({$lookup:{from:c,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${l}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let l=Me(e,a);if(!l)continue;r.push({$lookup:{from:l.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${l.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}})}}}}function Fo(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="max"&&s.function!=="min")continue;let a=s.relationMeta,u=s.relationName||s.field,c=a?.targetTableName||a?.targetTable,d=n?.tables?.get(c),l=d?.columns?.find(h=>h.isPrimary)?.name||(d?.columns?.some(h=>h.name==="_id")?"_id":"id"),f=s.aggregateField,p=f==="id"&&d?.columns?.some(h=>h.name==="_id")?"_id":f,m=nr(s),g=s.function==="min"?"$min":"$max";if(!(!a||!c||!f)){if(a.type==="one-to-many"){let h=q(a)||u;r.push({$lookup:{from:c,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${h}`,"$$localId"]}}},{$group:{_id:null,value:{[g]:`$${p}`}}}],as:m}}),r.push({$addFields:{[m]:{$arrayElemAt:[`$${m}.value`,0]}}});continue}if(a.type==="many-to-many"){let h=Me(e,a);if(!h)continue;let y=`${m}_junction`;r.push({$lookup:{from:h.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${h.selfColumn}`,"$$localId"]}}},{$project:{_id:0,targetId:`$${h.otherColumn}`}}],as:y}}),r.push({$lookup:{from:c,let:{targetIds:`$${y}.targetId`},pipeline:[{$match:{$expr:{$in:[`$${l}`,"$$targetIds"]}}},{$group:{_id:null,value:{[g]:`$${p}`}}}],as:m}}),r.push({$addFields:{[m]:{$arrayElemAt:[`$${m}.value`,0]}}}),r.push({$project:{[y]:0}})}}}}function xo(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(i=>({name:i.name,type:i.type})),relations:n.relations||[]}:null}:null}function vo(r){let e={};for(let t of r){let n=t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function Io(r){let e={};for(let t of r){let n=t.function==="count"?tr(t):t.function==="max"||t.function==="min"?nr(t):t.joinId!==null?t.fullPath:t.field;e[n]=t.direction==="asc"?1:-1}return e}function et(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>et(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>et(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>et(e));if("_not"in r)return et(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||et(t)))return!0}return!1}function Yr(r){return r.map(Z)}function Xr(r,e){let t=[],n=[],i=e?.tables?.get(r.rootTable);if(!i)return{scalarFields:t,relations:n};for(let o of r.nodes)if(o.kind==="wildcard")for(let s of i.columns||[])t.includes(s.name)||t.push(s.name);else o.kind==="scalar"?i.columns?.some(a=>a.name===o.name)&&!t.includes(o.name)&&t.push(o.name):o.kind==="relation"&&n.push(No(o,i,e));return{scalarFields:t,relations:n}}function No(r,e,t){let n=e.relations?.find(c=>c.propertyName===r.propertyName),i,o,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&Ne(n)?(i="_id",o=q(n)||r.propertyName,s=!0):(i=n&&H(n)||r.propertyName,o="_id",s=!1):r.relationType==="one-to-many"?(i="_id",o=n&&q(n)||r.propertyName,s=!0):n?.mappedBy?(i="_id",o=n.mappedBy,s=!0):(i=r.propertyName,o="_id",s=!1);let a=r.relationType==="one-to-many"||r.relationType==="many-to-many",u=Zr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:i,foreignField:o,type:a?"many":"one",isInverse:s,nestedFields:u}}function Zr(r){let e=[];for(let t of r)if(t.kind==="wildcard")e.push("*");else if(t.kind==="scalar")e.push(t.name);else if(t.kind==="relation"){let n=Zr(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let i of n)e.push(`${t.propertyName}.${i}`)}return e}ze();Ot();Et();function Tn(r,e,t,n){let i={rootTable:e,nodes:[]};if(!r||r.length===0)return i;let o=t?.tables?.get(e);if(!o)return i;let s=o.columns?.some(l=>l.name==="_id"&&l.isPrimary),a=o.columns?.some(l=>l.name==="id"),u=s&&!a?"_id":"id",c=new Map,d=[];for(let l of r){let f=l==="id"?u:l;if(f==="*")d.push("*");else if(f.includes(".")){let p=f.indexOf("."),m=f.substring(0,p),g=f.substring(p+1);if(!o.relations?.some(y=>y.propertyName===m))continue;c.has(m)||c.set(m,[]),c.get(m).push(g)}else if(o.relations?.some(m=>m.propertyName===f))c.has(f)||c.set(f,[u]);else{if(!o.columns?.some(g=>g.name===f))continue;d.push(f)}}if(d.includes("*")){i.nodes.push({kind:"wildcard"});for(let l of o.relations||[])c.has(l.propertyName)||c.set(l.propertyName,[u])}else for(let l of d)i.nodes.push({kind:"scalar",name:l});for(let[l,f]of c.entries()){let p=o.relations?.find(h=>h.propertyName===l);if(!p)continue;let m=p.targetTableName||p.targetTable,g={kind:"relation",propertyName:l,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:m,children:ei(f,m,t)};if(p.type==="many-to-one"||p.type==="one-to-one"){let h=n.registerWithParent(e,l,t,"left",null,"data");g.joinId=h}i.nodes.push(g)}return i}function ei(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let i=n.columns?.some(d=>d.name==="_id"&&d.isPrimary),o=n.columns?.some(d=>d.name==="id"),s=i&&!o?"_id":"id",a=new Map,u=[];for(let d of r){let l=d==="id"?s:d;if(l==="*")u.push("*");else if(l.includes(".")){let f=l.indexOf("."),p=l.substring(0,f),m=l.substring(f+1);if(!n.relations?.some(h=>h.propertyName===p))continue;a.has(p)||a.set(p,[]),a.get(p).push(m)}else if(n.relations?.some(p=>p.propertyName===l))a.has(l)||a.set(l,[s]);else{if(!n.columns?.some(m=>m.name===l))continue;u.push(l)}}let c=[];if(u.includes("*")){c.push({kind:"wildcard"});for(let d of n.relations||[])a.has(d.propertyName)||a.set(d.propertyName,[s])}else for(let d of u)c.push({kind:"scalar",name:d});for(let[d,l]of a.entries()){let f=n.relations?.find(m=>m.propertyName===d);if(!f)continue;let p=f.targetTableName||f.targetTable;c.push({kind:"relation",propertyName:d,joinId:null,relationType:f.type,isInverse:!!f.isInverse,targetTable:p,children:ei(l,p,t)})}return c}fe();fe();var Mo=new Set(["_and","_or","_not"]);function ti(r,e){return r?.tables?.get(e)??null}function Eo(r,e,t){return ti(r,e)?.columns?.find(n=>n.name===t)}function rr(r,e,t){return ti(r,e)?.relations?.find(n=>n.propertyName===t)}function Oo(r){let e=r.match(/^_(count|max|min)\(([^)]+)\)$/);if(!e)return null;let t=e[1],n=e[2].trim();if(t==="count")return{functionName:t,relationName:n};let i=n.indexOf(".");return i<=0||i!==n.lastIndexOf(".")?null:{functionName:t,relationName:n.slice(0,i).trim(),fieldName:n.slice(i+1).trim()}}function ir(r,e,t,n){if(Eo(r,e,t)?.isEncrypted===!0)throw new I(`Encrypted field '${t}' on '${e}' cannot be used for ${n}.`)}function Ae(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){for(let n of r)Ae(n,e,t);return}for(let[n,i]of Object.entries(r)){if(Mo.has(n)){Ae(i,e,t);continue}if(n.startsWith("_"))continue;let o=rr(t,e,n);if(o){let s=o.targetTableName||o.targetTable;s&&Ae(i,s,t);continue}ir(t,e,n,"filter")}}}function Sn(r,e,t){if(!r)return;let n=Array.isArray(r)?r:r.split(",").map(i=>i.trim()).filter(Boolean);for(let i of n){let o=i.startsWith("-")?i.slice(1):i;if(!o)continue;let s=Oo(o);if(s){if(s.functionName==="count")continue;let c=rr(t,e,s.relationName),d=c?.targetTableName||c?.targetTable;d&&ir(t,d,s.fieldName,"sort");continue}let a=o.split("."),u=e;for(let c=0;c<a.length;c++){let d=a[c];if(c===a.length-1){ir(t,u,d,"sort");break}let f=rr(t,u,d);if(!f)break;u=f.targetTableName||f.targetTable||u}}}var te=class{plan(e){let{tableName:t,fields:n,filter:i,sort:o,page:s,limit:a,meta:u,metadata:c,dbType:d}=e,l=c?.tables?.get(t),f=new oe,p=this.parseFields(n),m=null;p&&l&&(m=Tn(p,t,c,f));let g=!1,h=null;if(i&&l){Ae(i,t,c);let S=pe(i,t,c,f);h=S.node,g=S.hasRelationFilters}let y=this.parseSort(o);l&&Sn(y,t,c);let b=[],_=!1;for(let S of y){let M=S.startsWith("-"),A=M?S.substring(1):S,D=M?"desc":"asc";if(l){let j=this.parseRelationAggregateSort(t,l,A,c);if(j){b.push({joinId:null,field:A,direction:D,fullPath:A,function:j.functionName,relationName:j.relationName,aggregateField:j.aggregateField,relationMeta:j.relationMeta});continue}this.assertLocalSortField(t,l,A)}b.push({joinId:null,field:A,direction:D,fullPath:A})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let C=this.parseLimit(a),T=this.parsePage(s),k=T!==void 0&&C!==void 0?(T-1)*C:void 0,F=this.parseMeta(u),w=F.includes("totalCount")||F.includes("*"),v=F.includes("filterCount")||F.includes("*"),B=f.getAll();return{table:t,dbType:d,rawFields:p,rawFilter:i??null,joins:B,sortItems:b,limit:C,offset:k,needsTotalCount:w,needsFilterCount:v,hasRelationFilters:g,hasRelationSort:_,filterTree:h,fieldTree:m}}parseFields(e){if(e)return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):e.split(",").map(t=>t.trim()).filter(Boolean)}parseSort(e){return e?(Array.isArray(e)?e:e.split(",")).map(n=>n.trim()).filter(Boolean):[]}parseLimit(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;if(!Number.isNaN(t))return t<0?0:t}parsePage(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;return Number.isNaN(t)?void 0:t}parseMeta(e){return e?Array.isArray(e)?e:e.split(",").map(t=>t.trim()).filter(Boolean):[]}assertLocalSortField(e,t,n){if(n.includes("."))throw new I(`Sort field '${n}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let i=t.columns?.some(s=>s.name===n),o=n==="id"&&t.columns?.some(s=>s.name==="_id");if(!i&&!o)throw new I(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationAggregateSort(e,t,n,i){let o=n.match(/^_(count|max|min)\(([^)]+)\)$/);if(!o){if(/^_(count|max|min)\(/.test(n))throw new I(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName), _max(relationName.fieldName), or _min(relationName.fieldName).`);return null}let s=o[1],a=o[2].trim();if(s==="count"){let h=a;if(!h||h.includes("."))throw new I(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let y=t.relations?.find(b=>b.propertyName===h);if(!y)throw new I(`Sort relation '${h}' does not exist on '${e}'.`);if(y.type!=="one-to-many"&&y.type!=="many-to-many")throw new I(`Sort function '_count(${h})' is only supported for list relations on '${e}'.`);return{functionName:s,relationName:h,relationMeta:y}}let u=a.indexOf(".");if(u<=0||u!==a.lastIndexOf("."))throw new I(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let c=a.slice(0,u).trim(),d=a.slice(u+1).trim();if(!c||!d)throw new I(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let l=t.relations?.find(h=>h.propertyName===c);if(!l)throw new I(`Sort relation '${c}' does not exist on '${e}'.`);if(l.type!=="one-to-many"&&l.type!=="many-to-many")throw new I(`Sort function '_${s}(${c}.${d})' is only supported for list relations on '${e}'.`);let f=l.targetTableName||l.targetTable,p=i?.tables?.get(f);if(!p)throw new I(`Sort function '${n}' references unknown target table '${f}' on '${e}'.`);let m=p.columns?.find(h=>h.name===d),g=d==="id"&&p.columns?.some(h=>h.name==="_id");if(!m&&!g)throw new I(`Sort field '${d}' does not exist on '${f}' for function '_${s}(${c}.${d})'.`);if(m?.isEncrypted===!0)throw new I(`Encrypted field '${d}' on '${f}' cannot be used for sort.`);return{functionName:s,relationName:c,aggregateField:d,relationMeta:l}}registerSortJoinChain(e,t,n,i,o){let s=e.indexOf(".");if(s===-1)return null;let a=e.slice(0,s),u=e.slice(s+1),c=n?.tables?.get(t);if(!c)return null;let d=c.relations?.find(p=>p.propertyName===a);if(!d||d.type!=="many-to-one"&&d.type!=="one-to-one")return null;let l=i.registerWithParent(t,a,n,"left",o,"sort");if(!l)return null;if(!u.includes("."))return{lastJoinId:l,field:u};let f=d.targetTableName||d.targetTable;return this.registerSortJoinChain(u,f,n,i,l)}};fe();var Ao=new Set(["int","integer","bigint","smallint","tinyint","float","double","decimal","numeric","real","number"]),Po=new Set(["date","datetime","timestamp","timestamptz","timestamp with time zone","timestamp without time zone"]),jo=new Set(["hour","day","week","month","year"]),Bo=new Set(["count","countDistinct","sum","avg","min","max"]);function O(r,e){throw new I(e,{path:r})}function tt(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Lo(r,e){let t=r?.tables?.get(e);return t||O("aggregate",`Table "${e}" metadata is not available`),t}function ni(r,e,t){let n=r.columns?.find(i=>i.name===e);return n||O(t,`Unknown aggregate field "${e}"`),n.isEncrypted===!0&&O(t,`Encrypted field "${e}" cannot be used in aggregate queries`),n}function Do(r,e){let t=r===void 0?"UTC":r;(typeof t!="string"||t.length===0)&&O(e,"Aggregate timezone must be a non-empty IANA timezone");try{new Intl.DateTimeFormat("en-US",{timeZone:t}).format()}catch{O(e,`Invalid aggregate timezone "${t}"`)}return t}function Wo(r,e){return r==null?{}:(tt(r)||O(e,"Aggregate filter must be an object"),r)}function nt(r,e,t){tt(r)||O("aggregate","Aggregate options must be an object");let n=Lo(t,e),i=r.dimensions===void 0?[]:r.dimensions,o=r.measures;Array.isArray(i)||O("aggregate.dimensions","Aggregate dimensions must be an array"),(!tt(o)||Object.keys(o).length===0)&&O("aggregate.measures","Aggregate requires at least one measure");let s=new Set,a=i.map((g,h)=>{let y=`aggregate.dimensions[${h}]`;(!tt(g)||typeof g.field!="string"||g.field.length===0)&&O(y,"Aggregate dimension requires a field");let b=ni(n,g.field,`${y}.field`);return s.has(g.field)&&O(`${y}.field`,`Duplicate aggregate dimension "${g.field}"`),s.add(g.field),g.bucket===void 0?(g.timezone!==void 0&&O(`${y}.timezone`,"Aggregate timezone requires a bucket"),{field:g.field,outputKey:g.field,column:b}):((typeof g.bucket!="string"||!jo.has(g.bucket))&&O(`${y}.bucket`,"Aggregate bucket must be hour, day, week, month, or year"),Po.has(String(b.type).toLowerCase())||O(`${y}.bucket`,`Aggregate bucket requires a date field, but "${g.field}" is "${b.type}"`),{field:g.field,outputKey:g.field,bucket:g.bucket,timezone:Do(g.timezone,`${y}.timezone`),column:b})}),u=new Set,c=Object.entries(o).map(([g,h])=>{let y=`aggregate.measures.${g}`;(!g||!tt(h))&&O(y,"Aggregate measure must be an object");let b=Object.entries(h).filter(([k])=>k!=="as");b.length!==1&&O(y,"Aggregate measure must define exactly one operation");let[_,C]=b[0];Bo.has(_)||O(y,`Unsupported aggregate measure "${_}"`),(typeof C!="string"||C.length===0)&&O(y,"Aggregate measure field must be a non-empty string");let T=ni(n,C,`${y}.${_}`);return(u.has(g)||s.has(g))&&O(y,`Aggregate output key "${g}" is duplicated`),u.add(g),["sum","avg","min","max"].includes(_)&&!Ao.has(String(T.type).toLowerCase())&&O(y,`Aggregate ${_} requires a numeric field, but "${C}" is "${T.type}"`),{outputKey:g,operation:_,field:C,column:T}}),d=r.sort===void 0?[]:r.sort;Array.isArray(d)||O("aggregate.sort","Aggregate sort must be an array");let l=new Set([...s,...u]),f=d.map((g,h)=>{let y=`aggregate.sort[${h}]`;return(!tt(g)||typeof g.field!="string"||!l.has(g.field))&&O(y,"Aggregate sort field must reference a dimension or measure output"),g.direction!=="asc"&&g.direction!=="desc"&&O(`${y}.direction`,"Aggregate sort direction must be asc or desc"),{field:g.field,direction:g.direction}}),p=r.limit===void 0?void 0:Number(r.limit),m=r.page===void 0?1:Number(r.page);return p!==void 0&&(!Number.isInteger(p)||p<=0||p>1e4)&&O("aggregate.limit","Aggregate limit must be an integer between 1 and 10000"),(!Number.isInteger(m)||m<=0)&&O("aggregate.page","Aggregate page must be a positive integer"),{tableName:e,filter:Wo(r.filter,"aggregate.filter"),dimensions:a,measures:c,sort:f,page:m,limit:p}}var Pe=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.debugLog=[];this.lastBuiltPipeline=null;this.db=e.getDb()}async execute(e){if(this.metadata=e.metadata,this.dbType=e.dbType||"mongodb",!e.plan){let l=new te;e={...e,plan:l.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:"mongodb"})}}let t=e.debugLog||[];this.debugLog=t;let n={table:e.tableName,metadata:e.metadata,debugTrace:e.debugTrace};if(e.pipeline&&(n.pipeline=e.pipeline),e.fields&&(Array.isArray(e.fields)?n.fields=e.fields:typeof e.fields=="string"&&(n.fields=e.fields.split(",").map(l=>l.trim()))),e.filter&&(ie(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let l=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(f=>f.trim());n.sort=l.map(f=>{let p=f.trim();return p.startsWith("-")?{field:p.substring(1),direction:"desc"}:{field:p,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let l=typeof e.page=="string"?parseInt(e.page,10):e.page,f=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(l-1)*f,n.limit=f}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let i=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(l=>l.trim()).filter(Boolean),o=0,s=0;(i.includes("totalCount")||i.includes("*"))&&(o=await this.mongoService.collection(e.tableName).countDocuments({}));let a=this.metadata?.tables?.get(e.tableName),u=new Set((a?.relations??[]).map(l=>l.propertyName)),c=!!n.mongoRawFilter&&re(n.mongoRawFilter,u);if((i.includes("filterCount")||i.includes("*"))&&!c){let l=this.mongoService.collection(e.tableName),f=e.plan?.filterTree?Ve(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await l.countDocuments(f)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let d=await this.selectLegacy(n);if(e.debugMode){let l=this.lastBuiltPipeline??[],f;try{f=await this.db.collection(e.tableName).aggregate(l).explain()}catch(p){f={error:String(p)}}return{pipeline:l,explain:f}}if(c&&(i.includes("filterCount")||i.includes("*"))){let l={...n,mongoCountOnly:!0},f=await this.selectLegacy(l);s=f.length>0?f[0].count:0}return{data:d,...i.length>0&&{meta:{...i.includes("totalCount")||i.includes("*")?{totalCount:o}:{},...i.includes("filterCount")||i.includes("*")?{filterCount:s}:{}}}}}async aggregate(e){this.metadata=e.metadata,this.dbType=e.dbType||"mongodb";let t=nt(e.aggregate,e.tableName,e.metadata),n=this.db.collection(e.tableName),i=new te().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:"mongodb"}),o=i.hasRelationFilters?await Se(t.filter,e.tableName,e.metadata,this.db):i.filterTree?Ve(i.filterTree,{metadata:e.metadata,rootTable:e.tableName}):{},s=[];Object.keys(o).length>0&&s.push({$match:o});let a={_id:{}},u={};for(let d of t.dimensions){let l=`$${d.field}`,f=d.bucket?{$dateTrunc:{date:l,unit:d.bucket,timezone:d.timezone}}:l;a._id[d.outputKey]=f,u[d.outputKey]=`$_id.${d.outputKey}`}for(let d of t.measures){let l=`$${d.field}`;a[d.outputKey]=d.operation==="count"?{$sum:{$cond:[{$ne:[l,null]},1,0]}}:d.operation==="countDistinct"?{$addToSet:l}:{[`$${d.operation}`]:l},u[d.outputKey]=d.operation==="countDistinct"?{$size:{$setDifference:[`$${d.outputKey}`,[null]]}}:`$${d.outputKey}`}return s.push({$group:a},{$project:{_id:0,...u}}),t.sort.length>0&&s.push({$sort:Object.fromEntries(t.sort.map(d=>[d.field,d.direction==="asc"?1:-1]))}),t.limit!==void 0&&s.push({$skip:(t.page-1)*t.limit},{$limit:t.limit}),this.lastBuiltPipeline=s,e.debugMode?{pipeline:s,explain:await n.aggregate(s).explain()}:{data:(await n.aggregate(s).toArray()).map(Z)}}async selectLegacy(e){let t=[],n=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,i=this.metadata?.tables?.get(e.table),o=i?.relations&&i.relations.length>0;if(e.fields&&e.fields.length>0||n||o){let c=e.plan,d=e.fields&&e.fields.length>0?e.fields:["*"];if(e.fields&&e.fields.length>0&&c?.fieldTree){if(e.mongoFieldsExpanded=Xr(c.fieldTree,this.metadata),n){let l=await Nt(this.metadata,e.table,[],e.deep),f=new Set(e.mongoFieldsExpanded.relations.map(p=>p.propertyName));e.mongoFieldsExpanded.relations.push(...l.relations.filter(p=>!f.has(p.propertyName)))}}else console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await Nt(this.metadata,e.table,d,e.deep);if(this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let l=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:l.scalarFields},t=l.hiddenFields}}e.where&&(e.where=e.where.map(c=>c.field.includes(".")?c:{...c,field:`${e.table}.${c.field}`}));let s=this.db.collection(e.table);if(e.pipeline)return this.debugLog&&this.debugLog.push({type:"MongoDB Custom Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(e.pipeline))}),(await s.aggregate(e.pipeline).toArray()).map(Z);let{results:a,pipeline:u}=await er(s,e,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=u,this.mongoPhysicalMigrationService?await this.mongoPhysicalMigrationService.applyReadFallback(e.table,a,t):a}async executeAggregationPipeline(e,t){let{results:n,pipeline:i}=await er(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=i,n}};var Cn=class{constructor(e){this.context=e}log(e){console.log(this.format(e))}warn(e){console.warn(this.format(e))}error(e,t){console.error(this.format(e)),t&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}fatal(e,t){this.error(e,t)}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};fe();le();var Ko=["_and","_or","_not"];function me(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>me(e));for(let e of Object.keys(r))if(Ko.includes(e)||typeof r[e]=="object"&&r[e]!==null&&me(r[e]))return!0;return!1}var ri=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function qo(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function kn(r,e,t){if(!t)return!1;let n=r;if(r.includes(".")){let s=r.split(".");n=s[s.length-1]}let i=t.columns.find(s=>s.name===n);if(!i)return!1;let o=i.type?.toLowerCase()||"";return o==="uuid"||o==="uuidv4"||o.includes("uuid")}function Uo(r,e,t,n,i){return n!=="postgres"||typeof e!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||kn(r,t,i),e}function ii(r,e,t,n,i,o,s){let a=i&&!e.includes(".")?`${i}.${e}`:e,u=Fe(a,o??"postgres"),c=kn(e,i,s),d=Uo(e,n,i,o,s);switch(t){case"_eq":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} = ?::uuid`,[n]):r.where(a,"=",d);break;case"_neq":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} != ?::uuid`,[n]):r.where(a,"!=",d);break;case"_gt":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} > ?::uuid`,[n]):r.where(a,">",d);break;case"_gte":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} >= ?::uuid`,[n]):r.where(a,">=",d);break;case"_lt":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} < ?::uuid`,[n]):r.where(a,"<",d);break;case"_lte":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} <= ?::uuid`,[n]):r.where(a,"<=",d);break;case"_in":let l=n;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(p=>p.trim()):[l]),c&&o==="postgres"&&l.every(p=>typeof p=="string")?r.whereRaw(`${u} = ANY(?::uuid[])`,[l]):r.whereIn(a,l);break;case"_not_in":case"_nin":let f=n;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]),c&&o==="postgres"&&f.every(p=>typeof p=="string")?r.whereRaw(`${u} != ALL(?::uuid[])`,[f]):r.whereNotIn(a,f);break;case"_contains":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_starts_with":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${u}) LIKE lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_ends_with":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?))`,[n]):o==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?)`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`,[n]);break;case"_between":Array.isArray(n)&&n.length===2&&r.whereBetween(a,[n[0],n[1]]);break;case"_is_null":n===!0?r.whereNull(a):r.whereNotNull(a);break;case"_is_not_null":n===!0?r.whereNotNull(a):r.whereNull(a);break;default:r.where(a,qo(t),n)}}function Qo(r,e,t){if(!t||!e||r.startsWith("_"))return!0;let n=r.includes(".")?r.split(".").pop():r,i=t.columns?.some(s=>s.name===n),o=t.relations?.some(s=>s.propertyName===n);return i||o}function rt(r,e,t,n="and",i,o){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let s of e)n==="and"?r.where(function(){rt(this,s,t,"and",i,o)}):r.orWhere(function(){rt(this,s,t,"and",i,o)});return}for(let[s,a]of Object.entries(e))if(Qo(s,t,o)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){rt(this,u,t,"and",i,o)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){rt(this,u,t,"and",i,o)})});continue}if(s==="_not"){r.whereNot(function(){rt(this,a,t,"and",i,o)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(c=>ri.includes(c)))for(let[c,d]of Object.entries(a))ri.includes(c)&&(n==="and"?r.where(function(){ii(this,s,c,d,t,i,o)}):r.orWhere(function(){ii(this,s,c,d,t,i,o)}));else{let c=t&&!s.includes(".")?`${t}.${s}`:s,d=Fe(c,i??"postgres");kn(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${d} = ?::uuid`,[a]):r.orWhereRaw(`${d} = ?::uuid`,[a]):n==="and"?r.where(c,"=",a):r.orWhere(c,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s,c=Fe(u,i??"postgres");kn(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${c} = ?::uuid`,[a]):r.orWhereRaw(`${c} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function ce(r,e,t,n,i){return!e||typeof e!="object"||rt(r,e,t,"and",n,i),r}le();function ar(r,e,t){return`${x(r,t)}.${x(e,t)}`}function xe(r,e){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function oi(r,e){if(!e)return!1;let t=e.columns.find(i=>i.name===r);if(!t)return!1;let n=t.type?.toLowerCase()||"";return n==="uuid"||n==="uuidv4"||n.includes("uuid")}function it(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function lr(r,e,t,n,i,o){let s=[];for(let[a,u]of Object.entries(o)){let c=await Lt(r,e,a,u,t,n,i);if(c!==null)s.push(`EXISTS (${c})`);else{let d=t.relations.find(l=>l.propertyName===a);if(d&&d.foreignKeyColumn){let l=ar(e,d.foreignKeyColumn,n),p=u.id;if(p&&typeof p=="object"){let m=it(p._is_null),g=it(p._is_not_null);if(m===!0)s.push(`${l} IS NULL`);else if(m===!1)s.push(`${l} IS NOT NULL`);else if(g===!0)s.push(`${l} IS NOT NULL`);else if(g===!1)s.push(`${l} IS NULL`);else if(p._eq!==void 0){let h=xe(p._eq,n);s.push(`${l} = ${h}`)}else if(p._neq!==void 0){let h=xe(p._neq,n);s.push(`${l} != ${h}`)}else if(p._in!==void 0){let y=(Array.isArray(p._in)?p._in:[p._in]).map(b=>xe(b,n)).join(", ");s.push(`${l} IN (${y})`)}else if(p._not_in!==void 0||p._nin!==void 0){let h=p._not_in??p._nin,b=(Array.isArray(h)?h:[h]).map(_=>xe(_,n)).join(", ");s.push(`${l} NOT IN (${b})`)}else if(p._gt!==void 0){let h=xe(p._gt,n);s.push(`${l} > ${h}`)}else if(p._gte!==void 0){let h=xe(p._gte,n);s.push(`${l} >= ${h}`)}else if(p._lt!==void 0){let h=xe(p._lt,n);s.push(`${l} < ${h}`)}else if(p._lte!==void 0){let h=xe(p._lte,n);s.push(`${l} <= ${h}`)}}}}}return s}function cr(r){return!r||typeof r!="object"||Array.isArray(r)?!1:!!(r._and&&Array.isArray(r._and)||r._or&&Array.isArray(r._or)||r._not!==void 0&&r._not!==null)}async function or(r,e,t,n,i,o){let s=[];for(let a of r)if(a._and&&Array.isArray(a._and)&&a._and.length>0){let u=[];for(let c of a._and)if(cr(c)){let d=e(t).select(`${t}.id`);await je(e,d,c,t,n,i,o),u.push({idSubquery:d})}else{let{fieldFilters:d,relationFilters:l}=G(c,n),f=await lr(e,t,n,i,o,l);u.push({fieldFilters:d,subqueries:f})}s.push(u)}else if(cr(a)){let u=e(t).select(`${t}.id`);await je(e,u,a,t,n,i,o),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:c}=G(a,n),d=await lr(e,t,n,i,o,c);s.push([{fieldFilters:u,subqueries:d}])}return s}function si(r,e,t,n,i){if("idSubquery"in e&&e.idSubquery){r.whereIn(`${t}.id`,e.idSubquery);return}let o=e;Object.keys(o.fieldFilters).length===0&&o.subqueries.length===0||r.where(function(){Object.keys(o.fieldFilters).length>0&&ce(this,o.fieldFilters,t,i,n);for(let s of o.subqueries)this.whereRaw(s)})}function sr(r,e,t,n,i){let o=!0;for(let s of e){let a=function(){for(let u of s)si(this,u,t,n,i)};o?(r.where(a),o=!1):r.orWhere(a)}}function Rn(r,e,t,n,i,o,s){let a=oi(e,i),u=oi(n,o),c=`${x(r,s)}.${x(e,s)}`,d=`${x(t,s)}.${x(n,s)}`;if(s==="postgres"){if(a&&!u)return`${c} = ${d}::uuid`;if(!a&&u)return`${c}::uuid = ${d}`}return`${c} = ${d}`}async function Lt(r,e,t,n,i,o,s){let a=i.relations.find(f=>f.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${e}"`);let u=a.targetTableName||a.targetTable;if(!u)throw new Error(`Relation "${t}" in table "${e}" is missing targetTable/targetTableName. Relation metadata: ${JSON.stringify(a,null,2)}`);let c=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn){let f=Object.keys(n||{});if(f.length===1&&f[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(m=>c.has(m)))return null}let d=s?await s(u):null,l;switch(a.type){case"one-to-many":l=r(u).select(r.raw("1")).whereRaw(Rn(u,a.foreignKeyColumn,e,"id",d,i,o));break;case"many-to-many":let f=s?await s(a.junctionTableName):null;l=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw(Rn(a.junctionTableName,a.junctionTargetColumn,u,"id",f,d,o))).whereRaw(Rn(a.junctionTableName,a.junctionSourceColumn,e,"id",f,i,o));break;case"many-to-one":case"one-to-one":l=r(u).select(r.raw("1")).whereRaw(Rn(u,"id",e,a.foreignKeyColumn,d,i,o));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?d?await je(r,l,n,u,d,o,s):l=ce(l,n,u,o,d||void 0):l=ce(l,n,u,o),l.toString()}async function je(r,e,t,n,i,o,s){if(!t||typeof t!="object")return;if(t._and&&Array.isArray(t._and)){for(let c of t._and)if(c._or&&Array.isArray(c._or)&&c._or.length>0){let d=await or(c._or,r,n,i,o,s);e.where(function(){sr(this,d,n,i,o)})}else if(c._and&&Array.isArray(c._and)&&c._and.length>0)for(let d of c._and)await je(r,e,d,n,i,o,s);else await je(r,e,c,n,i,o,s);return}if(t._or&&Array.isArray(t._or)){let c=await or(t._or,r,n,i,o,s);e.where(function(){sr(this,c,n,i,o)});return}if(t._not){let c=t._not;if(c._and&&Array.isArray(c._and)&&c._and.length>0){let f=[];for(let p of c._and)if(cr(p)){let m=r(n).select(`${n}.id`);await je(r,m,p,n,i,o,s),f.push({idSubquery:m})}else{let{fieldFilters:m,relationFilters:g}=G(p,i),h=await lr(r,n,i,o,s,g);f.push({fieldFilters:m,subqueries:h})}e.whereNot(function(){for(let p of f)si(this,p,n,i,o)});return}if(c._or&&Array.isArray(c._or)&&c._or.length>0){let f=await or(c._or,r,n,i,o,s);e.whereNot(function(){sr(this,f,n,i,o)});return}let{fieldFilters:d,relationFilters:l}=G(c,i);e.whereNot(function(){Object.keys(d).length>0&&ce(this,d,n,o,i)});for(let[f,p]of Object.entries(l)){let m=await Lt(r,n,f,p,i,o,s);if(m===null){let g=i.relations.find(h=>h.propertyName===f);if(g&&g.foreignKeyColumn){let h=ar(n,g.foreignKeyColumn,o),b=p.id;if(b&&typeof b=="object"){let _=it(b._is_null),C=it(b._is_not_null);if(_===!0)e.whereRaw(`${h} IS NOT NULL`);else if(_===!1)e.whereRaw(`${h} IS NULL`);else if(C===!0)e.whereRaw(`${h} IS NULL`);else if(C===!1)e.whereRaw(`${h} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${h} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${h} = ?`,[b._neq]);else if(b._in!==void 0){let T=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${h} NOT IN (${T.map(()=>"?").join(", ")})`,T)}else if(b._not_in!==void 0||b._nin!==void 0){let T=b._not_in??b._nin,k=Array.isArray(T)?T:[T];e.whereRaw(`${h} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${m})`)}return}let{fieldFilters:a,relationFilters:u}=G(t,i);Object.keys(a).length>0&&ce(e,a,n,o,i);for(let[c,d]of Object.entries(u)){let l=await Lt(r,n,c,d,i,o,s);if(l===null){let f=i.relations.find(p=>p.propertyName===c);if(f&&f.foreignKeyColumn){let p=ar(n,f.foreignKeyColumn,o),g=d.id;if(g&&typeof g=="object"){let h=it(g._is_null),y=it(g._is_not_null);if(h===!0)e.whereRaw(`${p} IS NULL`);else if(h===!1)e.whereRaw(`${p} IS NOT NULL`);else if(y===!0)e.whereRaw(`${p} IS NOT NULL`);else if(y===!1)e.whereRaw(`${p} IS NULL`);else if(g._eq!==void 0)e.whereRaw(`${p} = ?`,[g._eq]);else if(g._neq!==void 0)e.whereRaw(`${p} != ?`,[g._neq]);else if(g._in!==void 0){let b=Array.isArray(g._in)?g._in:[g._in];e.whereRaw(`${p} IN (${b.map(()=>"?").join(", ")})`,b)}else if(g._not_in!==void 0||g._nin!==void 0){let b=g._not_in??g._nin,_=Array.isArray(b)?b:[b];e.whereRaw(`${p} NOT IN (${_.map(()=>"?").join(", ")})`,_)}}}}else e.whereRaw(`EXISTS (${l})`)}}async function Dt(r,e,t,n,i,o,s){await je(r,e,t,n,i,o,s)}le();le();function ot(r,e,t,n,i){for(let o of e){let s=o.field.split("."),a=t||s[0],u=s[s.length-1],c=Wt(n,a,u,o.value);switch(o.operator){case"=":r=r.where(o.field,"=",c);break;case"!=":r=r.where(o.field,"!=",c);break;case">":r=r.where(o.field,">",c);break;case"<":r=r.where(o.field,"<",c);break;case">=":r=r.where(o.field,">=",c);break;case"<=":r=r.where(o.field,"<=",c);break;case"like":r=r.where(o.field,"like",c);break;case"in":let d=Array.isArray(o.value)?o.value.map(g=>Wt(n,a,u,g)):[c];r=r.whereIn(o.field,d);break;case"not in":let l=Array.isArray(o.value)?o.value.map(g=>Wt(n,a,u,g)):[c];r=r.whereNotIn(o.field,l);break;case"is null":r=r.whereNull(o.field);break;case"is not null":r=r.whereNotNull(o.field);break;case"_contains":r=r.where(o.field,"like",`%${o.value}%`);break;case"_starts_with":r=r.where(o.field,"like",`${o.value}%`);break;case"_ends_with":r=r.where(o.field,"like",`%${o.value}`);break;case"_between":let f=o.value;if(typeof f=="string"&&(f=f.split(",").map(g=>g.trim())),Array.isArray(f)&&f.length===2){let g=Wt(n,a,u,f[0]),h=Wt(n,a,u,f[1]);r=r.whereBetween(o.field,[g,h])}break;case"_is_null":r=c===!0||c==="true"?r.whereNull(o.field):r.whereNotNull(o.field);break;case"_is_not_null":r=c===!0||c==="true"?r.whereNotNull(o.field):r.whereNull(o.field);break}}return r}function Kt(r,e,t,n){let i=[],o=t;if(!r||typeof r!="object")return i;for(let[s,a]of Object.entries(r))if(s==="_and"&&Array.isArray(a)){let u=a.map(c=>{let d=Kt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&i.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(c=>{let d=Kt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&i.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=Kt(a,e,t,n);u.length>0&&i.push(`NOT (${u.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[u,c]of Object.entries(a)){let d=`${x(e,n)}.${x(s,n)}`,l;if(c===null)l="NULL";else if(typeof c=="string"){let f=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,p=o.columns?.find(g=>g.name===s);p&&(p.type?.toLowerCase()==="uuid"||p.type?.toLowerCase().includes("uuid"))&&f.test(c)&&n==="postgres"?l=`'${c}'::uuid`:l=`'${c.replace(/'/g,"''")}'`}else typeof c=="boolean"?l=c?"true":"false":typeof c=="number"?l=String(c):l=`'${String(c).replace(/'/g,"''")}'`;if(u==="_eq")i.push(`${d} = ${l}`);else if(u==="_neq")i.push(`${d} != ${l}`);else if(u==="_gt")i.push(`${d} > ${l}`);else if(u==="_gte")i.push(`${d} >= ${l}`);else if(u==="_lt")i.push(`${d} < ${l}`);else if(u==="_lte")i.push(`${d} <= ${l}`);else if(u==="_is_null")i.push(`${d} IS NULL`);else if(u==="_is_not_null")i.push(`${d} IS NOT NULL`);else if(u==="_in"){let p=(Array.isArray(c)?c:[c]).map(m=>typeof m=="string"?`'${m.replace(/'/g,"''")}'`:String(m)).join(", ");i.push(`${d} IN (${p})`)}else if(u==="_not_in"||u==="_nin"){let p=(Array.isArray(c)?c:[c]).map(m=>typeof m=="string"?`'${m.replace(/'/g,"''")}'`:String(m)).join(", ");i.push(`${d} NOT IN (${p})`)}else if(u==="_contains"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${d}) LIKE '%${f.toLowerCase()}%'`)}else if(u==="_starts_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE lower(unaccent('${f}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${d}) LIKE '${f.toLowerCase()}%'`)}else if(u==="_ends_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}'))`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci)`):i.push(`lower(${d}) LIKE '%${f.toLowerCase()}'`)}else if(u==="_between"&&Array.isArray(c)&&c.length===2){let f=typeof c[0]=="string"?`'${c[0].replace(/'/g,"''")}'`:String(c[0]),p=typeof c[1]=="string"?`'${c[1].replace(/'/g,"''")}'`:String(c[1]);i.push(`${d} BETWEEN ${f} AND ${p}`)}}else{let u=`${x(e,n)}.${x(s,n)}`,c;a===null?c="NULL":typeof a=="string"?c=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?c=a?"true":"false":c=String(a),i.push(`${u} = ${c}`)}return i}function qt(r){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Wt(r,e,t,n){if(n==null)return n;let i=r?.tables?.get(e);if(!i?.columns)return n;let o=i.columns.find(s=>s.name===t);if(!o)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;default:return n}}dr();ze();le();Ut();qe();async function ci(r,e,t,n,i,o,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(pr(),li)),u=await a(e,t,n,i,o,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function gr(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(i=>({name:i.name,type:i.type})),relations:n.relations||[]}:null}:null}function ui(r,e,t,n,i){let o=r.targetTableName||r.targetTable;if(!o)return null;let s=r.foreignKeyColumn||V(r.propertyName);if(!s)return null;let a=l=>x(l,i),u=n?.tables?.get(o),d=(u?Y(u):null)?.name||"id";return`(SELECT ${a(o)}.${a(e)} FROM ${a(o)} WHERE ${a(o)}.${a(d)} = ${a(t)}.${a(s)})`}Ut();async function di(r,e,t,n,i){let o={};if(n.includes("totalCount")||n.includes("*")){let s=await r(t).count("* as count").first();o.totalCount=Number(s?.count||0)}if(n.includes("filterCount")||n.includes("*")){let a=await e.clone().clearSelect().clearOrder().clear("limit").clear("offset").countDistinct(`${t}.id as count`).first();o.filterCount=Number(a?.count||0)}return o}var Be=class r{constructor(e,t,n,i){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=i;this.logger=new Cn(r.name);this.debugLog=[]}async execute(e){let t=performance.now();this.metadata=e.metadata;let n=e.debugLog||[];this.debugLog=n;let i=e.debugTrace;if(e.filter&&ie(e.filter,e.tableName,e.metadata),!e.plan){let $=new te;e={...e,plan:$.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:this.dbType})}}let o=e.plan,s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,u=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,c=o.rawFields&&o.rawFields.length>0&&!o.rawFields.includes("*");if(o.joins.length===0&&!o.hasRelationFilters&&!o.hasRelationSort&&!u&&!a&&c){i&&i.setQueryPath("simple");let $=await this.executeSimple(e,o);return i&&i.dur("sql_executor",t,{table:e.tableName}),$}let l={table:e.tableName,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?l.fields=e.fields:typeof e.fields=="string"&&(l.fields=e.fields.split(",").map($=>$.trim())));let f=e.filter;if(e.filter&&!me(e.filter)){l.where=[];for(let[$,R]of Object.entries(e.filter))if(typeof R=="object"&&R!==null)for(let[N,J]of Object.entries(R)){let E;if(N==="_eq")E="=";else if(N==="_neq")E="!=";else if(N==="_in")E="in";else if(N==="_not_in"||N==="_nin")E="not in";else if(N==="_gt")E=">";else if(N==="_gte")E=">=";else if(N==="_lt")E="<";else if(N==="_lte")E="<=";else if(N==="_contains")E="_contains";else if(N==="_starts_with")E="_starts_with";else if(N==="_ends_with")E="_ends_with";else if(N==="_between")E="_between";else if(N==="_is_null")E="_is_null";else if(N==="_is_not_null")E="_is_not_null";else if(N==="_like")E="like";else if(N==="_ilike")E="ilike";else continue;l.where.push({field:$,operator:E,value:J})}else l.where.push({field:$,operator:"=",value:R})}if(e.sort){let $=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(R=>R.trim());l.sort=$.map(R=>{let N=R.trim();return N.startsWith("-")?{field:N.substring(1),direction:"desc"}:{field:N,direction:"asc"}})}else l.sort=[{field:"id",direction:"asc"}];let p=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,m=p===void 0||Number.isNaN(p)?void 0:p<0?0:p,g=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,h=g===void 0||Number.isNaN(g)?void 0:g;h&&m!==void 0?(l.offset=(h-1)*m,l.limit=m):m!==void 0&&(l.limit=m);let y=e.plan?.sortItems??(l.sort??[]).map($=>({joinId:null,field:$.field,direction:$.direction,fullPath:$.field})),b=[],_=[];for(let $ of y){if($.function==="count"){let R={sql:this.buildRelationCountSortSubquery(l.table,$),direction:$.direction};_.push(R);continue}if($.function==="max"||$.function==="min"){let R={sql:this.buildRelationAggregateSortSubquery(l.table,$),direction:$.direction};_.push(R);continue}if($.joinId===null){if($.field.includes(".")&&!e.plan){let N=$.field.split(".")[0];if(this.metadata?.tables?.get(l.table)?.relations?.some(Q=>Q.propertyName===N))continue}let R={field:$.field.includes(".")?$.field:`${l.table}.${$.field}`,direction:$.direction};b.push(R),_.push(R)}else{let R=e.plan?.joins.find(N=>N.id===$.joinId);if(R&&(R.relationType==="many-to-one"||R.relationType==="one-to-one")){let N=ui(R.relationMeta,$.field,l.table,this.metadata,this.dbType);if(N){let J={sql:N,direction:$.direction};_.push(J)}}}}let C=[];if(l.fields&&l.fields.length>0||u||a){let $=gr(this.metadata),R=l.fields&&l.fields.length>0?l.fields:["*"],N=await ci(this.knex,l.table,R,$,this.dbType,this.maxQueryDepth,e.deep);N.select.length>0&&(l.select=[...l.select||[],...N.select]),C=N.batchFetchDescriptors||[]}l.where&&(l.where=l.where.map($=>$.field.includes(".")?$:{...$,field:`${l.table}.${$.field}`})),l.sort=b;let T=this.knex(l.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map($=>$.trim()).filter(Boolean),F=k.includes("filterCount")||k.includes("*"),w=k.includes("totalCount")||k.includes("*");if(l.select){let $=l.select.map(R=>typeof R=="string"&&R.trim().startsWith("(")?this.knex.raw(R):typeof R=="string"&&/ as /i.test(R)?this.knex.raw(R):R);T=T.select($)}if(F&&T.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),w){let $=x(l.table,this.dbType);T.select(this.knex.raw(`(SELECT COUNT(*) FROM ${$}) as __total_count__`))}let v=["table_definition","column_definition","relation_definition","method_definition"].includes(l.table);if(f&&(me(f)||Object.keys(f).length>0)){let $=this.metadata?.tables?.get(l.table);(!v&&$&&$.relations&&$.relations.length>0?G(f,$).hasRelations:!1)?await Dt(this.knex,T,f,l.table,$,this.dbType,N=>this.metadata?.tables?.get(N)):e.plan?.filterTree?ue(T,e.plan.filterTree,{dbType:this.dbType,rootTable:l.table}):(this.logger.debug(`buildWhereClause fallback for table=${l.table}`),T=ce(T,f,l.table,this.dbType,$))}else l.where&&l.where.length>0&&(T=ot(T,l.where,l.table,this.metadata,this.dbType));for(let $ of _)if($.field){let R=$.field.includes(".")?$.field:`${l.table}.${$.field}`;T=T.orderBy(R,$.direction)}else $.sql&&(T=T.orderByRaw(`${$.sql} ${$.direction.toUpperCase()}`));l.groupBy&&(T=T.groupBy(l.groupBy)),l.offset&&(T=T.offset(l.offset)),l.limit!==void 0&&l.limit!==null&&l.limit>0&&(T=T.limit(l.limit));let B=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:l.table,sql:T.toSQL().toNative()});let S;if(e.debugMode&&(S=T.toSQL().toNative().sql),e.debugMode&&i){let $=T.toSQL().toNative();i.setSql($.sql);try{let R=$.sql.replace(/\$\d+/g,"?"),N=await this.knex.raw(`EXPLAIN ${R}`,$.bindings);i.setExplain(this.dbType==="postgres"?N.rows:N[0])}catch(R){i.setExplain({error:String(R)})}}let M,A=performance.now();M=await T,i&&i.dur("db_execute",A,{table:e.tableName});let D=await this.resolveEmptyPageMeta(T,l.table,k,M.length),j=D.filterCount??0;if(B=D.totalCount??0,F&&M.length>0&&(j=Number(M[0].__filter_count__||0),M.forEach($=>{delete $.__filter_count__})),w&&M.length>0&&M[0].__total_count__!==void 0&&(B=Number(M[0].__total_count__||0),M.forEach($=>{delete $.__total_count__})),C&&C.length>0&&M.length>0){let $=gr(this.metadata);if($){let{executeBatchFetches:R}=await Promise.resolve().then(()=>(yr(),fi));await R(this.knex,M,C,$,this.maxQueryDepth??3,0,l.table,this.dbType,this.metadata,i)}}if(this.knexService){let $=performance.now();M=await this.knexService.parseResult(M,l.table),i&&i.dur("db_parseResult",$,{table:e.tableName})}else{let $=(R,N)=>{if(!R||!this.metadata)return R;let J=this.metadata.tables?.get(N);if(!J)return R;if(Array.isArray(R))return R.map(Q=>$(Q,N));if(typeof R!="object"||Buffer.isBuffer(R))return R;let E={...R};for(let Q of J.columns)if(Q.type==="simple-json"&&E[Q.name]&&typeof E[Q.name]=="string")try{E[Q.name]=JSON.parse(E[Q.name])}catch{}for(let[Q,X]of Object.entries(E))if(X&&typeof X=="object"&&!Array.isArray(X)&&!Buffer.isBuffer(X)){let En=X;if(En.id!==void 0||En.createdAt!==void 0){let ct=J.relations?.find(ut=>ut.propertyName===Q);ct&&(E[Q]=$(X,ct.targetTableName))}}else if(Array.isArray(X)&&X.length>0&&typeof X[0]=="object"&&X[0].id!==void 0){let ct=J.relations?.find(ut=>ut.propertyName===Q);ct&&(E[Q]=X.map(ut=>$(ut,ct.targetTableName)))}return E};M=$(M,l.table)}return i&&(i.setQueryPath("full"),i.dur("sql_executor",t,{table:e.tableName})),{data:M,...k.length>0&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:B}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:j}:{}}},...S!==void 0&&{sql:S}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=Y(s)?.name||"id",u=x(e,this.dbType),c=x(a,this.dbType);if(!n||!o)throw new I(`Sort relation '${i}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let d=n.foreignKeyColumn||n.mappedBy;if(!d)throw new I(`Sort function '_count(${i})' cannot resolve relation key on '${e}'.`);let l=x(o,this.dbType),f=x(d,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}if(n.type==="many-to-many"){let d=this.resolveManyToManyContract(n,i,e),l=x(d.tableName,this.dbType),f=x(d.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}throw new I(`Sort function '_count(${i})' is only supported for list relations on '${e}'.`)}buildRelationAggregateSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=t.aggregateField,s=n?.targetTableName||n?.targetTable,a=this.metadata?.tables?.get(e),u=this.metadata?.tables?.get(s),c=Y(a)?.name||"id",d=Y(u)?.name||"id",l=x(e,this.dbType),f=x(c,this.dbType),p=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!p||!n||!s||!o)throw new I(`Sort function '${t.field}' is not supported on '${e}'.`);let m=x(s,this.dbType),g=x(o,this.dbType);if(n.type==="one-to-many"){let h=n.foreignKeyColumn||n.mappedBy;if(!h)throw new I(`Sort function '_${t.function}(${i}.${o})' cannot resolve relation key on '${e}'.`);let y=x(h,this.dbType);return`(SELECT ${p}(${m}.${g}) FROM ${m} WHERE ${m}.${y} = ${l}.${f})`}if(n.type==="many-to-many"){let h=this.resolveManyToManyContract(n,i,e),y=x(h.tableName,this.dbType),b=x(h.sourceColumn,this.dbType),_=x(h.targetColumn,this.dbType),C=x(d,this.dbType);return`(SELECT ${p}(${m}.${g}) FROM ${y} JOIN ${m} ON ${m}.${C} = ${y}.${_} WHERE ${y}.${b} = ${l}.${f})`}throw new I(`Sort function '_${t.function}(${i}.${o})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,n){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new I(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async resolveEmptyPageMeta(e,t,n,i){return i>0||n.length===0?{}:di(this.knex,e,t,n,!1)}async executeSimple(e,t){let n=e.tableName,i=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],o=this.knex(n).select(i);t.filterTree&&ue(o,t.filterTree,{dbType:this.dbType,rootTable:n});for(let h of t.sortItems){let y=h.field.includes(".")?h.field:`${n}.${h.field}`;o=o.orderBy(y,h.direction)}t.limit!==void 0&&t.limit!==null&&t.limit>0&&(o=o.limit(t.limit)),t.offset!==void 0&&(o=o.offset(t.offset));let s=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(h=>h.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),u=s.includes("totalCount")||s.includes("*");if(a&&o.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),u){let h=x(n,this.dbType);o.select(this.knex.raw(`(SELECT COUNT(*) FROM ${h}) as __total_count__`))}let c=e.debugTrace,d;if(e.debugMode){let h=o.toSQL().toNative();if(d=h.sql,c){c.setSql(h.sql);try{let y=h.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${y}`,h.bindings);c.setExplain(this.dbType==="postgres"?b.rows:b[0])}catch(y){c.setExplain({error:String(y)})}}}let l=performance.now(),f;f=await o,c&&c.dur("db_execute",l,{table:n}),this.knexService&&(f=await this.knexService.parseResult(f,n));let p=await this.resolveEmptyPageMeta(o,n,s,f.length),m=p.filterCount??0,g=p.totalCount??0;return a&&f.length>0&&(m=Number(f[0].__filter_count__||0),f.forEach(h=>delete h.__filter_count__)),u&&f.length>0&&(g=Number(f[0].__total_count__||0),f.forEach(h=>delete h.__total_count__)),{data:f,...s.length>0&&{meta:{...u?{totalCount:g}:{},...a?{filterCount:m}:{}}},...d!==void 0&&{sql:d}}}async aggregate(e){let t=nt(e.aggregate,e.tableName,e.metadata),n=this.knex(e.tableName),i=x(e.tableName,this.dbType),o=[],s=[];for(let l of t.dimensions){let f=`${i}.${x(l.field,this.dbType)}`,p=l.bucket?this.buildSqlBucketExpression(f,l.bucket,l.timezone,l.column.type):f;s.push(this.knex.raw(`${p} as ${x(l.outputKey,this.dbType)}`)),o.push(p)}for(let l of t.measures){let f=`${i}.${x(l.field,this.dbType)}`,p=l.operation==="count"?`COUNT(${f})`:l.operation==="countDistinct"?`COUNT(DISTINCT ${f})`:`${l.operation.toUpperCase()}(${f})`;s.push(this.knex.raw(`${p} as ${x(l.outputKey,this.dbType)}`))}let u=new te().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:this.dbType});u.hasRelationFilters?await Dt(this.knex,n,t.filter,e.tableName,e.metadata?.tables?.get(e.tableName),this.dbType,l=>e.metadata?.tables?.get(l)):u.filterTree&&ue(n,u.filterTree,{dbType:this.dbType,rootTable:e.tableName}),n.select(s),o.length>0&&n.groupByRaw(o.join(", "));for(let l of t.sort)n.orderByRaw(`${x(l.field,this.dbType)} ${l.direction.toUpperCase()}`);return t.limit!==void 0&&n.limit(t.limit).offset((t.page-1)*t.limit),{data:(await n).map(l=>{let f={...l};for(let p of t.measures){let m=f[p.outputKey];m!=null&&typeof m=="string"&&/^-?\d+(\.\d+)?$/.test(m)&&(f[p.outputKey]=Number(m))}return f})}}buildSqlBucketExpression(e,t,n,i){let o=qt(n);if(this.dbType==="postgres"){let s=`(${e} AT TIME ZONE ${o})`;return`DATE_TRUNC(${qt(t)}, ${s})`}if(this.dbType==="mysql"){let s=`CONVERT_TZ(${e}, '+00:00', ${o})`;return t==="year"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-01-01'), '%Y-%m-%d')`:t==="month"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-01'), '%Y-%m-%d')`:t==="week"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%u-1'), '%Y-%u-%d')`:t==="day"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-%d'), '%Y-%m-%d')`:`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-%d %H:00:00'), '%Y-%m-%d %H:%i:%s')`}throw new I(`Aggregate time bucket is not supported on ${this.dbType}`)}};var vn=require("mongodb"),lt=class{constructor(e){this.debugLog=[];this.batchInserts={items:[],flushing:!1};this.knexService=e.knexService,this.mongoService=e.mongoService,this.databaseConfigService=e.databaseConfigService,this.runtimeMetricsCollectorService=e.runtimeMetricsCollectorService,this.lazyRef=e.lazyRef,this.dbType=this.databaseConfigService.getDbType(),this.batchInsertMaxSize=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_SIZE",100),this.batchInsertMaxWaitMs=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_WAIT_MS",100),this.batchInsertConcurrency=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_CONCURRENCY",5),this.batchInsertTraceFile=process.env.QUERY_BUILDER_BATCH_TRACE_FILE||process.env.DYNAMIC_CREATE_BATCH_TRACE_FILE,this.batchInsertTraceFile&&(0,In.mkdirSync)((0,pi.dirname)(this.batchInsertTraceFile),{recursive:!0})}async runWithPolicy(e,t){return this.knexService?this.knexService.runWithPolicy(e,t):this.mongoService?this.mongoService.runWithPolicy(e,t):t()}async runWithFieldPermissionCheck(e,t){return this.knexService?this.knexService.runWithFieldPermissionCheck(e,t):this.mongoService?this.mongoService.runWithFieldPermissionCheck(e,t):t()}async runWithTelemetryContext(e,t){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.runWithQueryContext(e,t):await t()}getDbType(){return this.dbType}safeObjectId(e){if(!vn.ObjectId)return e;if(typeof e=="string")try{return new vn.ObjectId(e)}catch{return e}return e}async getMetadataForQuery(){let e={tables:new Map,tablesList:[]},t=this.lazyRef.metadataCacheService;return t?t.isLoaded?.()?await t.getMetadata?.()??e:t.getDirectMetadata?.()??e:e}async buildMongoFilter(e,t){let n=await this.getMetadataForQuery(),i=Je(n,e,t,this.dbType);return i._id!==void 0&&(i._id=this.safeObjectId(i._id)),i}async applyWhereToKnex(e,t,n){let i=await this.getMetadataForQuery();return{query:ot(e,t,n??"",i,this.dbType)}}async runMongoMutationInSaga(e){return!this.mongoService?.runInSaga||this.mongoService.isInSaga?.()?e():(await this.mongoService.runInSaga(e)).data}async insertWithOptions(e){if(e.batch)return await this.insertManyBatch(e.table,e.data);if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{if(Array.isArray(e.data)){let t=[];for(let n of e.data){let i=await this.mongoService.insertOne(e.table,n);t.push(Z(i))}return t}return this.mongoService.insertOne(e.table,e.data)});if(Array.isArray(e.data)){let t=[];for(let n of e.data){let i=await this.knexService.insertWithCascade(e.table,n);t.push(i)}return t}else return await this.knexService.insertWithCascade(e.table,e.data)}async select(e){let t=performance.now(),n=await this.getMetadataForQuery(),i=performance.now(),s=new te().plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:n,dbType:this.dbType}),a=e.debugTrace;if(a&&(a.dur("qb_planner",i,{table:e.tableName}),a.setPlan(this.sanitizePlan(s))),this.dbType==="mongodb"){let l=await new Pe(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}let c=await new Be(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:n,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),c}sanitizePlan(e){return{rawFields:e.rawFields,hasRelationFilters:e.hasRelationFilters,hasRelationSort:e.hasRelationSort,joins:e.joins?.length??0,sortItems:e.sortItems,limit:e.limit,offset:e.offset,page:e.page,isSimpleQuery:e.joins?.length===0&&!e.hasRelationFilters&&!e.hasRelationSort}}async updateWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),s=this.mongoService.collection(e.table),a=this.mongoService.ioSignalPublic?.()??{},u=await s.find(o,a).toArray(),c=[];for(let d of u){let l=await this.mongoService.updateOne(e.table,d._id,e.data);c.push(l)}return c});let t=this.knexService.getKnex(),n=t(e.table);e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n;for(let o of i)await this.knexService.updateWithCascade(e.table,o.id,e.data);if(e.returning){let o=t(e.table);return e.where.length>0&&await this.applyWhereToKnex(o,e.where,e.table),await o.select(e.returning)}return{affected:i.length}}async deleteWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let i=await this.buildMongoFilter(e.where,e.table),o=this.mongoService.collection(e.table),s=this.mongoService.ioSignalPublic?.()??{},a=await o.find(i,s).toArray(),u=0;for(let c of a)await this.mongoService.deleteOne(e.table,c._id)&&u++;return u});let n=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table)),await n.delete()}async count(e){if(this.dbType==="mongodb"){let o=e.where?await this.buildMongoFilter(e.where,e.table):{};return this.mongoService.count(e.table,o)}let n=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n.count("* as count").first();return Number(i?.count||0)}whereToFilter(e){let t={},n=this.databaseConfigService.isMongoDb();for(let[i,o]of Object.entries(e))i==="id"||i==="_id"?n?t._id=this.normalizeWhereFilterValue("_id",o):t.id=this.normalizeWhereFilterValue("id",o):t[i]=this.normalizeWhereFilterValue(i,o);return t}normalizeWhereFilterValue(e,t){return this.isFilterOperatorObject(t)?this.databaseConfigService.isMongoDb()&&e==="_id"?this.normalizeMongoIdOperatorValue(t):t:{_eq:this.databaseConfigService.isMongoDb()&&e==="_id"?this.safeObjectId(t):t}}isFilterOperatorObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof vn.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[n,i]of Object.entries(e))t[n]=Array.isArray(i)?i.map(o=>this.safeObjectId(o)):this.safeObjectId(i);return t}filterToWhere(e){let t=[];for(let[n,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let o=Object.entries(i)[0];if(o){let[s,a]=o,u=this.mapFilterOperatorToSql(s);t.push({field:n,operator:u,value:a})}}return t}mapFilterOperatorToSql(e){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"like",_starts_with:"like",_ends_with:"like",_is_null:"is null",_is_not_null:"is not null"}[e]||"="}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,maxQueryDepth:e.maxQueryDepth})})}async aggregate(e){return this.trackQueryMetric("aggregate",e.table,async()=>{let t=await this.getMetadataForQuery();return this.dbType==="mongodb"?new Pe(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).aggregate({tableName:e.table,aggregate:e.aggregate,metadata:t,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,dbType:this.dbType}):new Be(this.knexService.getKnex(),this.dbType,this.knexService).aggregate({tableName:e.table,aggregate:e.aggregate,metadata:t,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t,n){return n?.batch?await this.insertManyBatch(e,t):this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let a=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return Z(a)}let i=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),s=i||t.id;return await o(e).where("id",s).first()})}async insertMany(e,t){return t.length===0?[]:this.trackQueryMetric("insert_many",e,async()=>this.dbType==="mongodb"?(await this.runMongoMutationInSaga(async()=>typeof this.mongoService.insertManyWithCascade=="function"?this.mongoService.insertManyWithCascade(e,t):Promise.all(t.map(i=>this.mongoService.insertOne(e,i))))).map(i=>Z(i)):this.knexService.insertManyWithCascade(e,t))}async flushBatchInserts(){for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)await this.flushBatchInsertBuffer()}async insertManyBatch(e,t){let n=Array.isArray(t)?t:[t];for(let i of n)this.batchInserts.items.push({table:e,data:i});return this.traceBatchInsert("enqueue",{tableName:e,count:n.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i)),{accepted:!0,batch:!0,count:n.length}}async flushBatchInsertBuffer(){if(this.batchInserts.flushing){await this.batchInserts.flushPromise;return}let e=this.batchInserts.items.splice(0,this.batchInserts.items.length);if(this.batchInserts.timer&&(clearTimeout(this.batchInserts.timer),this.batchInserts.timer=void 0),e.length===0)return;this.batchInserts.flushing=!0;let t=this.executeBatchInsertFlush(e);this.batchInserts.flushPromise=t,await t}async executeBatchInsertFlush(e){let t=Date.now();try{let n=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...n.entries()].map(([i,o])=>({tableName:i,count:o.length}))}),await this.runLimited([...n.entries()],([i,o])=>this.flushBatchInsertTable(i,o)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}finally{this.batchInserts.flushing=!1,this.batchInserts.flushPromise=void 0,this.batchInserts.items.length>0&&(this.batchInserts.timer&&clearTimeout(this.batchInserts.timer),this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(n=>this.logBatchInsertError("QueryBuilder batch insert flush failed",n))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let n=Date.now();await this.runBatchInsertWithIsolation(e,t),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-n})}async runBatchInsertWithIsolation(e,t){if(t.length!==0)try{await(async()=>{if(this.dbType==="mongodb"){await this.runMongoMutationInSaga(async()=>{if(typeof this.mongoService?.insertManyWithCascade=="function"){await this.mongoService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.mongoService.insertOne(e,i.data)))});return}if(typeof this.knexService?.insertManyWithCascade=="function"){await this.knexService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.knexService.insertWithCascade(e,i.data)))})()}catch(n){if(t.length===1){this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,n);return}let i=Math.ceil(t.length/2);await Promise.all([this.runBatchInsertWithIsolation(e,t.slice(0,i)),this.runBatchInsertWithIsolation(e,t.slice(i))])}}groupBatchInsertsByTable(e){let t=new Map;for(let n of e){let i=t.get(n.table);i?i.push(n):t.set(n.table,[n])}return t}async runLimited(e,t){let n=0,i=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;n<e.length;){let o=e[n++];await t(o)}});await Promise.all(i)}readPositiveEnv(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.trunc(n):t}traceBatchInsert(e,t){this.batchInsertTraceFile&&(0,In.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
52
+ }`}var Br="mongo-fold-text-search.body.txt",Ue=null;function so(){let r=[qn.join(__dirname,Br),qn.join(process.cwd(),"dist","kernel","query","utils",Br)];for(let e of r)try{if(on.existsSync(e))return on.readFileSync(e,"utf8")}catch{}return null}function sn(){if(Ue!==null)return Ue;let r=so();return r?(Ue=r,Ue):(Ue=rn(),Ue)}var we=require("mongodb");function W(r,e,t,n){if(t==="_id"){if(n instanceof we.ObjectId)return n;if(typeof n=="string")try{return new we.ObjectId(n)}catch{return n}return n}let i=r?.tables?.get(e);if(!i){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}return n}if(!i.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}return n}let o=i.columns.find(s=>s.name===t);if(!o){if(i.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}return n}if(n==null)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;case"uuid":if(typeof n=="string")try{return new we.ObjectId(n)}catch{return n}return n;default:return n}}var an="__mongoFoldTextTriples";function ao(r){return r==="_id"?"$_id":`$${r}`}function Qe(r,e,t,n){let i=ao(e),o=r[an]??[];o.push({ref:i,needle:t,mode:n}),r[an]=o}function lo(r){let e=r[an];if(delete r[an],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:sn(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}function Je(r,e,t,n){let i={},o=n==="mongodb"||!n;for(let s of e){let a=s.field.includes(".")?s.field.split(".").pop()??s.field:s.field,u=t||s.field.split(".")[0]||"";o&&a==="id"&&(a="_id");let c=W(r,u,a,s.value);switch(s.operator){case"=":i[a]=c;break;case"!=":i[a]={$ne:c};break;case">":i[a]={$gt:c};break;case"<":i[a]={$lt:c};break;case">=":i[a]={$gte:c};break;case"<=":i[a]={$lte:c};break;case"like":i[a]={$regex:c.replace(/%/g,".*"),$options:"i"};break;case"in":let d=s.value;Array.isArray(d)||(d=typeof d=="string"&&d.includes(",")?d.split(",").map(y=>y.trim()):[d]);let l=d.map(y=>W(r,u,a,y));i[a]={$in:l};break;case"not in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(y=>y.trim()):[f]);let p=f.map(y=>W(r,u,a,y));i[a]={$nin:p};break;case"is null":i[a]=null;break;case"is not null":i[a]={$ne:null};break;case"_contains":Qe(i,a,String(c),"contains");break;case"_starts_with":Qe(i,a,String(c),"starts");break;case"_ends_with":Qe(i,a,String(c),"ends");break;case"_between":let m=s.value;if(typeof m=="string"&&(m=m.split(",").map(y=>y.trim())),Array.isArray(m)&&m.length===2){let y=W(r,u,a,m[0]),b=W(r,u,a,m[1]);i[a]={$gte:y,$lte:b}}break;case"_is_null":let g=c===!0||c==="true";i[a]=g?{$eq:null}:{$ne:null};break;case"_is_not_null":let h=c===!0||c==="true";i[a]=h?{$ne:null}:{$eq:null};break}}return lo(i),i}function Lr(r,e,t){let i=r?.tables?.get?.(e)?.columns?.find(o=>o.name===t);return i?i.isNullable!==!1:!0}function ln(r,e,t,n,i,o){switch(i){case"_contains":Qe(e,n,String(o),"contains");break;case"_starts_with":Qe(e,n,String(o),"starts");break;case"_ends_with":Qe(e,n,String(o),"ends");break;case"_eq":e[n]=W(r,t,n,o);break;case"_neq":{let l=W(r,t,n,o);Lr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:l}})):e[n]={$ne:l};break}case"_in":{let l=o;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(p=>p.trim()):[l]);let f=l.map(p=>W(r,t,n,p));e[n]={$in:f};break}case"_not_in":case"_nin":let s=o;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(l=>l.trim()):[s]);let a=s.map(l=>W(r,t,n,l));Lr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$nin:a}})):e[n]={$nin:a};break;case"_gt":e[n]={$gt:W(r,t,n,o)};break;case"_gte":e[n]={$gte:W(r,t,n,o)};break;case"_lt":e[n]={$lt:W(r,t,n,o)};break;case"_lte":e[n]={$lte:W(r,t,n,o)};break;case"_is_null":let u=o===!0||o==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let c=o===!0||o==="true";e[n]=c?{$ne:null}:{$eq:null};break;case"_between":let d=o;if(typeof d=="string"&&(d=d.split(",").map(l=>l.trim())),Array.isArray(d)&&d.length===2){let l=W(r,t,n,d[0]),f=W(r,t,n,d[1]);e[n]={$gte:l,$lte:f}}break}}var Gn=require("mongodb");function re(r,e){if(!r||typeof r!="object")return!1;for(let[t,n]of Object.entries(r))if(t==="_and"||t==="_or"){if(Array.isArray(n)){for(let i of n)if(re(i,e))return!0}}else if(t==="_not"){if(re(n,e))return!0}else if(e.has(t))return!0;return!1}function G(r,e){if(!r||typeof r!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},n={},i=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(r)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(i.has(s))if(typeof a=="object"&&a!==null){let u=Object.keys(a);if(u.some(d=>d.startsWith("_"))){let d=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&d.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let o=re(r,i);return{fieldFilters:t,relationFilters:n,hasRelations:o}}Et();Ot();var pn="__mongoFoldTextTriples";function Ve(r,e){if(!r)return{};let t={};return At(r,t,e),Te(t),t}function yo(r,e){if(!r)return{};let t={};return Jn(r,t,e),Te(t),t}function he(r,e,t){if(!e)return{};let n=new oe,{node:i}=pe(e,t,r,n);return Ve(i,{metadata:r,rootTable:t})}function gn(r,e,t){if(!e)return{};let n=new oe,{node:i}=pe(e,t,r,n);return yo(i,{metadata:r,rootTable:t})}function At(r,e,t){switch(r.kind){case"true":return;case"false":ge(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let i=r.children.map(o=>{let s={};return At(o,s,t),Te(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}ge(e,...i);return}case"or":{let i=r.children.map(s=>{let a={};return At(s,a,t),Te(a),a}).filter(s=>Object.keys(s).length>0);if(i.length===0)return;let o=e.$or;e.$or=o?[...o,...i]:i;return}case"not":{let n={};At(r.child,n,t),Te(n);let i=e.$nor;e.$nor=i?[...i,n]:[n];return}case"compare":Ur(r,e,t);return;case"relation_exists":{console.warn(`[mongo-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${r.joinId}) \u2014 expected applyRelationFilters or null-only short-circuit to handle it. Filter silently skipped.`);return}}}function Ur(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let i=o=>W(t.metadata,t.rootTable,n,o);switch(r.op){case"eq":ee(e,n,i(r.value));return;case"neq":{let o=i(r.value);zn(t,n)?ge(e,{[n]:{$ne:null}},{[n]:{$ne:o}}):ee(e,n,{$ne:o});return}case"gt":ee(e,n,{$gt:i(r.value)});return;case"gte":ee(e,n,{$gte:i(r.value)});return;case"lt":ee(e,n,{$lt:i(r.value)});return;case"lte":ee(e,n,{$lte:i(r.value)});return;case"in":{let o=qr(r.value).map(i);ee(e,n,{$in:o});return}case"not_in":{let o=qr(r.value).map(i);zn(t,n)?ge(e,{[n]:{$ne:null}},{[n]:{$nin:o}}):ee(e,n,{$nin:o});return}case"between":{let o=Array.isArray(r.value)?r.value:typeof r.value=="string"?r.value.split(",").map(s=>s.trim()):null;Array.isArray(o)&&o.length===2&&ee(e,n,{$gte:i(o[0]),$lte:i(o[1])});return}case"is_null":ee(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":Qn(e,n,String(r.value),"contains");return;case"starts_with":Qn(e,n,String(r.value),"starts");return;case"ends_with":Qn(e,n,String(r.value),"ends");return}}function Jn(r,e,t){switch(r.kind){case"true":ge(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let i=r.children.map(s=>{let a={};return Jn(s,a,t),Te(a),a}).filter(s=>Object.keys(s).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}let o=e.$or;e.$or=o?[...o,...i]:i;return}case"or":{let i=r.children.map(o=>{let s={};return Jn(o,s,t),Te(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}ge(e,...i);return}case"not":At(r.child,e,t);return;case"compare":bo(r,e,t);return;case"relation_exists":{ee(e,r.joinId,r.negate?{$ne:null}:{$eq:null});return}}}function bo(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached false renderer \u2014 expected relation resolver to handle it. Filter silently skipped.`);return}if(r.op==="is_null"){ee(e,n,r.value===!0?{$ne:null}:{$eq:null});return}let i={};Ur(r,i,t),Te(i);let o={$nor:[i]};zn(t,n)?ge(e,o,{[n]:{$ne:null}}):ge(e,o)}function ee(r,e,t){r[e]===void 0?r[e]=t:(ge(r,{[e]:r[e]},{[e]:t}),delete r[e])}function ge(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function zn(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(i=>i.name===e);return n?n.isNullable!==!1:!0}function qr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function _o(r){return r==="_id"?"$_id":`$${r}`}function Qn(r,e,t,n){let i=_o(e),o=r[pn]??[];o.push({ref:i,needle:t,mode:n}),r[pn]=o}function Te(r){let e=r[pn];if(delete r[pn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:sn(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}async function Se(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return he(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!re(r,o))return he(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>Se(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._or&&Array.isArray(r._or)){let d=(await Promise.all(r._or.map(l=>Se(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:{$or:d}}if(r._not)return await Hn(r._not,e,t,n)||{};let{fieldFilters:s,relationFilters:a}=G(r,i),u=[];if(s&&Object.keys(s).length>0){let c=he(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(a&&Object.keys(a).length>0)for(let[c,d]of Object.entries(a)){let l=await wo(c,d,e,i,t,n);l&&Object.keys(l).length>0&&u.push(l)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function Hn(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return gn(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!re(r,o))return gn(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>Hn(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$or:d}}if(r._or&&Array.isArray(r._or)){let d=(await Promise.all(r._or.map(l=>Hn(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._not)return Se(r._not,e,t,n);let{fieldFilters:s,relationFilters:a}=G(r,i),u=[];if(s&&Object.keys(s).length>0){let c=gn(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(a&&Object.keys(a).length>0)for(let[c,d]of Object.entries(a)){let l=await To(c,d,e,i,t,n);l&&Object.keys(l).length>0&&u.push(l)}return u.length===0?{}:u.length===1?u[0]:{$or:u}}async function wo(r,e,t,n,i,o){let s=(n.relations||[]).find(c=>c.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=i?.tables?.get(a);return!a||!u?{}:s.type==="many-to-one"||s.type==="one-to-one"?$o(e,s,r,a,u,i,o):s.type==="one-to-many"?zr(e,s,t,a,u,i,o):s.type==="many-to-many"?Vr(e,s,t,a,u,i,o):{}}async function $o(r,e,t,n,i,o,s){let a=H(e)||t,u=mn(r),c=yn(u);if(c!==null)return c?{[a]:null}:{[a]:{$ne:null}};let d=Yn(u);if(d!==null){let m=bn(d.value);if(d.op==="eq")return{[a]:m};if(d.op==="neq")return{[a]:{$ne:m}};if(d.op==="in")return{[a]:{$in:m}};if(d.op==="not_in")return{$and:[{[a]:{$nin:m}},{[a]:{$ne:null}}]}}let l=await hn(u,n,i,o,s);if(!l||Object.keys(l).length===0)return{};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(m=>m._id).filter(Boolean);return p.length===0?{__impossible__:!0}:{[a]:{$in:p}}}async function To(r,e,t,n,i,o){let s=(n.relations||[]).find(c=>c.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=i?.tables?.get(a);if(!a||!u)return{};if(s.type==="many-to-one"||s.type==="one-to-one")return So(e,s,r,a,u,i,o);if(s.type==="one-to-many"){let c=await zr(e,s,t,a,u,i,o);return Jr(c)}if(s.type==="many-to-many"){let c=await Vr(e,s,t,a,u,i,o);return Jr(c)}return{}}async function So(r,e,t,n,i,o,s){let a=H(e)||t,u=mn(r),c=yn(u);if(c!==null)return c?{[a]:{$ne:null}}:{[a]:null};let d=Yn(u);if(d!==null){let m=bn(d.value);if(d.op==="eq")return{$and:[{[a]:{$ne:m}},{[a]:{$ne:null}}]};if(d.op==="neq")return{[a]:m};if(d.op==="in")return{$and:[{[a]:{$nin:m}},{[a]:{$ne:null}}]};if(d.op==="not_in")return{[a]:{$in:m}}}let l=await hn(u,n,i,o,s);if(!l||Object.keys(l).length===0)return{[a]:null};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(m=>m._id).filter(Boolean);return p.length===0?{[a]:{$ne:null}}:{$and:[{[a]:{$nin:p}},{[a]:{$ne:null}}]}}async function zr(r,e,t,n,i,o,s){let a=q(e)||t,u=mn(r),c=yn(u);if(c!==null){let f=await Qr(s,n,a,{});return c?f.length===0?{}:{_id:{$nin:f}}:f.length===0?{__impossible__:!0}:{_id:{$in:f}}}let d=await hn(u,n,i,o,s);if(!d||Object.keys(d).length===0)return{};let l=await Qr(s,n,a,d);return l.length===0?{__impossible__:!0}:{_id:{$in:l}}}async function Vr(r,e,t,n,i,o,s){let a=Me(t,e);if(!a)return{};let u=mn(r),c=yn(u);if(c!==null){let g=await Vn(s,a,n,null);return c?g.length===0?{}:{_id:{$nin:g}}:g.length===0?{__impossible__:!0}:{_id:{$in:g}}}let d=Yn(u);if(d!==null){let g=bn(d.value),h=Array.isArray(g)?g:[g],y=await Vn(s,a,n,{_id:{$in:h}});return y.length===0?{__impossible__:!0}:{_id:{$in:y}}}let l=await hn(u,n,i,o,s);if(!l||Object.keys(l).length===0)return{};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);if(p.length===0)return{__impossible__:!0};let m=await Vn(s,a,n,{_id:{$in:p}});return m.length===0?{__impossible__:!0}:{_id:{$in:m}}}async function hn(r,e,t,n,i){let o=new Set((t?.relations??[]).map(s=>s.propertyName));return re(r,o)?Se(r,e,n,i):he(n,r,e)}async function Qr(r,e,t,n){let i=await r.collection(e).find(n,{projection:{[t]:1}}).toArray(),o=new Set,s=[];for(let a of i){let u=a[t];if(u==null)continue;let c=String(u);o.has(c)||(o.add(c),s.push(u))}return s}function Jr(r){if(!r||Object.keys(r).length===0)return{};if(r.__impossible__===!0)return{};let e=r._id;if(e&&typeof e=="object"&&!Array.isArray(e)){if(Array.isArray(e.$in))return{_id:{$nin:e.$in}};if(Array.isArray(e.$nin))return{_id:{$in:e.$nin}}}return{$nor:[r]}}async function Vn(r,e,t,n){let i=null;n&&t&&(i=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(d=>d._id).filter(Boolean));let o=i?{[e.otherColumn]:{$in:i}}:{},s=await r.collection(e.junctionName).find(o,{projection:{[e.selfColumn]:1}}).toArray(),a=new Set,u=[];for(let c of s){let d=c[e.selfColumn];if(d==null)continue;let l=String(d);a.has(l)||(a.add(l),u.push(d))}return u}function mn(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function yn(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0],n=r[t];return t==="_is_null"?n===!0:t==="_is_not_null"?n!==!0:t==="_eq"?n===null?!0:null:t==="_neq"&&n===null?!1:null}function bn(r){if(Array.isArray(r))return r.map(e=>bn(e));if(typeof r!="string")return r;try{return new Gn.ObjectId(r)}catch{return r}}function Yn(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof Gn.ObjectId)return{op:"eq",value:r};if(r==null)return null;if(typeof r!="object")return{op:"eq",value:r};if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0];return t==="_eq"?{op:"eq",value:r._eq}:t==="_neq"?{op:"neq",value:r._neq}:t==="_in"&&Array.isArray(r._in)?{op:"in",value:r._in}:t==="_not_in"&&Array.isArray(r._not_in)?{op:"not_in",value:r._not_in}:null}async function Pt(r,e,t,n){let i=await Nt(r,e,t),o=[],s={},a={};if(n&&typeof n=="object")for(let[p,m]of Object.entries(n))if(typeof m=="object"&&m!==null){let g=Object.keys(m)[0];g&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(g)?s[p]=m:a[p]=m}else s[p]=m;if(Object.keys(s).length>0){let p={};for(let[m,g]of Object.entries(s))if(typeof g=="object"&&g!==null)for(let[h,y]of Object.entries(g))ln(r,p,e,m,h,y);else p[m]=g;Object.keys(p).length>0&&o.push({$match:p})}let c=r?.tables?.get(e)?.relations||[],d=[];for(let[p,m]of Object.entries(a))if(!i.relations.some(h=>h.propertyName===p)){let h=c.find(y=>y.propertyName===p);if(h){let y="",b="";if(h.type==="many-to-one"||h.type==="one-to-one")y=H(h)||h.propertyName,b="_id";else if(h.type==="one-to-many")y="_id",b=q(h)||h.propertyName;else if(h.type==="many-to-many")continue;let _=h.type==="one-to-many"||h.type==="many-to-many";d.push({propertyName:p,targetTable:h.targetTableName,localField:y,foreignField:b,type:_?"many":"one",nestedFields:[]})}}let l=[...i.relations,...d];for(let p of l){let m=a[p.propertyName],g=p.nestedFields&&p.nestedFields.length>0?await Pt(r,p.targetTable,p.nestedFields,m):m?await Pt(r,p.targetTable,["_id"],m):[];p.type==="one"&&g.length>0&&g.push({$limit:1}),o.push({$lookup:{from:p.targetTable,localField:p.localField,foreignField:p.foreignField,as:p.propertyName,pipeline:g.length>0?g:void 0}}),p.type==="one"&&(o.push({$unwind:{path:`$${p.propertyName}`,preserveNullAndEmptyArrays:!0}}),m&&(He(m)||o.push({$match:{[p.propertyName]:{$ne:null}}})))}let f=c.filter(p=>!l.some(m=>m.propertyName===p.propertyName));if(i.scalarFields.length>0||i.relations.length>0||f.length>0){let p={_id:1};for(let g of i.scalarFields)p[g]=1;for(let g of l)p[g.propertyName]=1,g.type==="one"&&g.localField&&g.localField!==g.propertyName&&(p[g.localField]=1);if(t.includes("*"))for(let g of f){if(g.type==="one-to-many"||g.type==="many-to-many")continue;g.type==="many-to-many"?p[g.propertyName]={$map:{input:`$${g.propertyName}`,as:"item",in:{_id:"$$item"}}}:p[g.propertyName]={$cond:{if:{$ne:[`$${g.propertyName}`,null]},then:{_id:`$${g.propertyName}`},else:null}}}o.push({$project:p})}return o}async function Hr(r,e,t,n,i){let o=r?.tables?.get(t),s=o?.relations||[],a=o?.columns||[],u=s.filter(d=>!i.some(l=>l.propertyName===d.propertyName)),c=n.length===a.length||n.length===0&&i.length===0;if(u.length>0||!c){let d={_id:1};for(let l of n)d[l]=1;for(let l of i)d[l.propertyName]=1,l.type==="one"&&l.localField&&l.localField!==l.propertyName&&(d[l.localField]=1);for(let l of u){if(l.type==="one-to-many"||l.type==="many-to-many")continue;l.type==="many-to-many"?d[l.propertyName]={$map:{input:`$${l.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[l.propertyName]={$cond:{if:{$ne:[`$${l.propertyName}`,null]},then:{_id:`$${l.propertyName}`},else:null}}}e.push({$project:d})}}function He(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>He(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>He(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>He(e));if("_not"in r)return He(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||He(t)))return!0}return!1}Ye();var Bt=require("mongodb");Ye();_n();async function wn(r,e,t){let n=new Map,i=0;async function o(){for(;i<r.length;){let u=i++,c=r[u];n.set(String(c),await e(c))}}let s=Math.min(t,r.length);if(s===0)return n;let a=Array.from({length:s},o);return await Promise.all(a),n}var ae="__sourceId__",Re="__targetId__",Xe="__enfyra_target__",jt="__enfyra_top_n_documents__",Ze=class{constructor(e,t,n,i=new ke){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.executionBudget=i;this.pkField="_id"}chunkCount(e){return Math.ceil(e.length/se)||1}runQuery(e){return this.executionBudget.run(e)}uniqueValues(e){return Array.from(new Map(e.filter(t=>t!=null).map(t=>[this.keyOf(t),t])).values())}buildStableSort(e,t="_id"){let n=this.buildSortFromTokens(e)||{};return n[t]===void 0&&(n[t]=1),n}appendPartitionProjection(e,t,n){if(t){let i={...t};for(let o of n)i[o]=1;e.push({$project:i})}}appendTopNStages(e,t,n,i,o){e.push({$group:{_id:`$${t}`,[jt]:{$topN:{sortBy:n,output:"$$ROOT",n:i+o}}}},{$project:{[jt]:{$slice:[`$${jt}`,i,o]}}},{$unwind:`$${jt}`},{$replaceRoot:{newRoot:`$${jt}`}})}normalizeMetadata(){return this.metadata?this.metadata.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortFromTokens(e){let t={};for(let n of this.parseSortTokens(e)){let i=n.field.split(".");if(i.length===1)t[i[0]]=n.order;else{let o=`__sort_${i.slice(0,-1).join("_")}`;t[`${o}.${i[i.length-1]}`]=n.order}}return Object.keys(t).length>0?t:void 0}parseSortTokens(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).map(n=>{let i=n.startsWith("-"),o=i?n.slice(1):n;return{field:o==="id"?"_id":o,order:i?-1:1}}):[]}hasDottedSort(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).some(n=>(n.startsWith("-")?n.slice(1):n).includes(".")):!1}buildSortAggregatePipeline(e,t,n){let i=Array.isArray(n)?n:n.split(",").map(c=>c.trim()).filter(Boolean),o=[{$match:t}],s=new Set;for(let c of i){let l=(c.startsWith("-")?c.slice(1):c).split(".");if(l.length<=1)continue;let f=e;for(let p=0;p<l.length-1;p++){let m=l[p],g=this.normalizeMetadata()?.tables?.get(f);if(!g)break;let h=g.relations?.find(_=>_.propertyName===m);if(!h)break;let y=h.targetTableName||h.targetTable,b=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(b)){s.add(b);let _=H(h)||h.propertyName,C=p===0?null:`__sort_${l.slice(0,p).join("_")}`,T=C?`${C}.${_}`:_;o.push({$lookup:{from:y,localField:T,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}f=y}}let a=this.buildSortFromTokens(n);a&&o.push({$sort:a});let u={};for(let c of s)u[c]=0;return Object.keys(u).length>0&&o.push({$project:u}),o}toObjectId(e){try{return typeof e=="string"?new Bt.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof Bt.ObjectId||t instanceof Bt.ObjectId?this.keyOf(e).localeCompare(this.keyOf(t)):typeof e=="number"&&typeof t=="number"?e-t:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="string"&&typeof t=="string"?e.localeCompare(t):e<t?-1:e>t?1:0}sortDocsInMemory(e,t){let n=this.parseSortTokens(t).filter(i=>!i.field.includes("."));n.length!==0&&e.sort((i,o)=>{for(let s of n){let a=this.compareSortValues(i[s.field],o[s.field]);if(a!==0)return a*s.order}return this.compareSortValues(i._id,o._id)})}sortDocsByPk(e){e.sort((t,n)=>this.compareSortValues(t._id,n._id))}projectionWithSortFields(e,t){if(!e)return{projection:e,hiddenFields:[]};let n={...e},i=[];for(let o of this.parseSortTokens(t))o.field.includes(".")||n[o.field]===void 0&&(n[o.field]=1,i.push(o.field));return{projection:n,hiddenFields:i}}removeHiddenFields(e,t){if(t.length!==0)for(let n of e)for(let i of t)delete n[i]}keyOf(e){return e==null?"":e instanceof Bt.ObjectId||typeof e=="object"&&typeof e.toHexString=="function"?e.toHexString():String(e)}buildScalarRef(e){return{[this.pkField]:e}}getTargetPkField(e){return this.pkField}resolveOwnerFkKey(e){return e.localField||e.fkColumn||e.relationName}resolveInverseFkField(e){return e.foreignField?e.foreignField:e.mappedBy?e.mappedBy:e.relationName}resolveParentPk(e){return this.pkField}resolveFields(e,t){let{rootFields:n,subRelations:i}=Ge(e),o={},s=!1;if(n.includes("*")){s=!0;for(let f of t.relations||[])i.has(f.propertyName)||i.set(f.propertyName,["_id"])}else for(let f of n){let p=t.columns.find(m=>m.name===f);p?o[p.name]=1:t.relations?.find(g=>g.propertyName===f)&&!i.has(f)&&i.set(f,["_id"])}i.forEach((f,p)=>{let m=t.relations?.find(g=>g.propertyName===p);m&&(m.type==="many-to-one"||m.type==="one-to-one"&&!m.isInverse)&&(s||(o[H(m)||m.propertyName]=1))}),s||(o._id=1);let a=[];i.forEach((f,p)=>{let m=t.relations?.find(b=>b.propertyName===p);if(!m)return;let g=m.targetTableName||m.targetTable;if(!g)return;let h,y;m.type==="many-to-one"||m.type==="one-to-one"?Ne(m)?(h="_id",y=q(m)||m.propertyName):(h=H(m)||m.propertyName,y="_id"):m.type==="one-to-many"?(h="_id",y=q(m)||m.propertyName):m.type==="many-to-many"&&(m.isInverse?(h="_id",y=m.mappedBy):(h=m.propertyName,y="_id")),a.push({relationName:p,type:m.type,targetTable:g,fields:f,isInverse:m.isInverse,fkColumn:m.foreignKeyColumn,mappedBy:m.mappedBy,junctionTableName:m.junctionTableName,junctionSourceColumn:m.junctionSourceColumn,junctionTargetColumn:m.junctionTargetColumn,localField:h,foreignField:y})});let u=!s&&Object.keys(o).length===1&&o._id===1&&a.length===0,c=this.fieldRenamesByTable?.get(t.name)??[],d=[];if(!s&&c.length>0)for(let f of c)o[f.newName]===1&&o[f.oldName]!==1&&(o[f.oldName]=1,d.push(f.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:o,pendingRenames:c,hiddenFields:d}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?he(this.normalizeMetadata(),i.userFilter,e):null,s=this.buildSortFromTokens(i?.userSort),a=await K(t,c=>{let d={_id:{$in:c}};o&&Object.keys(o).length>0&&Object.assign(d,o);let l={projection:n.projection};return s&&(l.sort=s),this.runQuery(()=>this.db.collection(e).find(d,l).toArray())}),u=this.applyReadFallback(a,n);return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(t),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,n,i,o){let s=i.projection?{...i.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let a=this.uniqueValues(n.map(y=>this.toObjectId(y))),u=o?.userFilter?he(this.normalizeMetadata(),o.userFilter,e):null,c=o?.userLimit,d=o?.userPage,l=this.hasDottedSort(o?.userSort);if(c!==void 0&&c>0){let y=d?(d-1)*c:0;if(l)throw new Error(`Dotted sort is not supported for batch relation '${o?.relationName}'`);let b=this.buildStableSort(o?.userSort),_=await K(a,async C=>{let T={[t]:{$in:C}};u&&Object.keys(u).length>0&&Object.assign(T,u);let k=[{$match:T}];this.appendTopNStages(k,t,b,y,c),k.push({$sort:{[t]:1,...b}}),this.appendPartitionProjection(k,s,[t]);let F=await this.runQuery(()=>this.db.collection(e).aggregate(k).toArray());return this.applyReadFallback(F,i)});return{docs:_,groupKeyField:t,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:_.length}}}if(s&&(s[t]=1),l){let y=[],b=await wn(a,async _=>{let C={[t]:_};u&&Object.keys(u).length>0&&Object.assign(C,u);let T=this.buildSortAggregatePipeline(e,C,o.userSort);s&&T.push({$project:s});let k=await this.runQuery(()=>this.db.collection(e).aggregate(T).toArray());return this.applyReadFallback(k,i)},Oe);for(let _ of b.values())for(let C of _)y.push(C);return{docs:y,groupKeyField:t,stats:{strategy:"per-parent-dotted-sort",roundtrips:a.length,concurrencyWaves:Math.ceil(a.length/Oe),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:y.length}}}let f={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(f,u);let p=this.buildSortFromTokens(o?.userSort)||{_id:1},m={projection:s,sort:p},g=await K(a,y=>this.runQuery(()=>this.db.collection(e).find({[t]:{$in:y},...u||{}},m).toArray())),h=this.applyReadFallback(g,i);return{docs:h,groupKeyField:t,stats:{strategy:"batch-in",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:h.length}}}postProcessInverseChild(e,t,n){n||delete e[t]}m2mSortCanUseJunction(e){return this.parseSortTokens(e).every(t=>t.field==="_id")}async loadM2MTargets(e,t,n){if(t.length===0)return[];let i=n.projection?{projection:n.projection}:void 0,o=await K(t,s=>this.runQuery(()=>this.db.collection(e).find({_id:{$in:s}},i).toArray()));return this.applyReadFallback(o,n)}async fetchM2MTopK(e,t,n,i,o,s,a){if(this.hasDottedSort(t.userSort))throw new Error(`Dotted sort is not supported for batch relation '${t.relationName}'`);let u=new Map;for(let y of e)u.set(this.keyOf(y),[]);let c=i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1,d=!o&&this.m2mSortCanUseJunction(t.userSort),l=this.parseSortTokens(t.userSort).find(y=>y.field==="_id")?.order??1,f=this.buildStableSort(t.userSort),p=await K(e,async y=>{if(d){let C=[{$match:{[n.selfColumn]:{$in:y}}}];return this.appendTopNStages(C,n.selfColumn,{[n.otherColumn]:l},s,a),C.push({$sort:{[n.selfColumn]:1,[n.otherColumn]:l}},{$project:{_id:0,[ae]:`$${n.selfColumn}`,[Re]:`$${n.otherColumn}`}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(C).toArray())).map(k=>({sourceId:k[ae],targetId:k[Re]}))}let b=[{$match:{[n.selfColumn]:{$in:y}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Xe}},{$unwind:`$${Xe}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Xe}`,{[ae]:`$${n.selfColumn}`,[Re]:`$${n.otherColumn}`}]}}}];return o&&Object.keys(o).length>0&&b.push({$match:o}),this.appendTopNStages(b,ae,f,s,a),b.push({$sort:{[ae]:1,...f}}),b.push({$project:{_id:0,[ae]:1,[Re]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(b).toArray())).map(C=>({sourceId:C[ae],targetId:C[Re]}))});if(c){let y=new Map;for(let b of p){let _=this.keyOf(b.targetId);y.has(_)||y.set(_,{_id:b.targetId}),u.get(this.keyOf(b.sourceId))?.push(y.get(_))}return{grouped:u,docs:[],stats:{strategy:d?"m2m-junction-partitioned-top-k":"m2m-filtered-edge-top-k",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let m=this.uniqueValues(p.map(y=>y.targetId)),g=await this.loadM2MTargets(t.targetTable,m,i),h=new Map(g.map(y=>[this.keyOf(y._id),y]));for(let y of p){let b=h.get(this.keyOf(y.targetId));b&&u.get(this.keyOf(y.sourceId))?.push(b)}return{grouped:u,docs:g,stats:{strategy:"m2m-partitioned-edge-loader",roundtrips:this.chunkCount(e)+(m.length>0?this.chunkCount(m):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+g.length,rowsDiscarded:0}}}async fetchM2MEdgeBatch(e,t,n,i,o){let s=new Map;for(let g of e)s.set(this.keyOf(g),[]);let a=!o&&this.m2mSortCanUseJunction(t.userSort),u=this.parseSortTokens(t.userSort).find(g=>g.field==="_id")?.order??1,c=this.buildStableSort(t.userSort),d=await K(e,async g=>{if(a)return(await this.runQuery(()=>this.db.collection(n.junctionName).find({[n.selfColumn]:{$in:g}},{projection:{_id:0,[n.selfColumn]:1,[n.otherColumn]:1},sort:{[n.selfColumn]:1,[n.otherColumn]:u}}).toArray())).map(_=>({sourceId:_[n.selfColumn],targetId:_[n.otherColumn]}));let h=[{$match:{[n.selfColumn]:{$in:g}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Xe}},{$unwind:`$${Xe}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Xe}`,{[ae]:`$${n.selfColumn}`,[Re]:`$${n.otherColumn}`}]}}}];return o&&Object.keys(o).length>0&&h.push({$match:o}),h.push({$sort:{[ae]:1,...c}},{$project:{_id:0,[ae]:1,[Re]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(h).toArray())).map(b=>({sourceId:b[ae],targetId:b[Re]}))});if(i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1){let g=new Map;for(let h of d){let y=this.keyOf(h.targetId);g.has(y)||g.set(y,{_id:h.targetId}),s.get(this.keyOf(h.sourceId))?.push(g.get(y))}return{grouped:s,docs:[],stats:{strategy:a?"m2m-junction-batch":"m2m-filtered-edge-batch",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length,rowsDiscarded:0}}}let f=this.uniqueValues(d.map(g=>g.targetId)),p=await this.loadM2MTargets(t.targetTable,f,i),m=new Map(p.map(g=>[this.keyOf(g._id),g]));for(let g of d){let h=m.get(this.keyOf(g.targetId));h&&s.get(this.keyOf(g.sourceId))?.push(h)}return{grouped:s,docs:p,stats:{strategy:"m2m-edge-loader",roundtrips:this.chunkCount(e)+(f.length>0?this.chunkCount(f):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length+p.length,rowsDiscarded:0}}}async fetchM2M(e,t,n,i,o){let s=n?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=Me(s,{type:"many-to-many",propertyName:t.relationName,targetTable:t.targetTable,mappedBy:t.isInverse?t.mappedBy:void 0,junctionTableName:t.junctionTableName,junctionSourceColumn:t.junctionSourceColumn,junctionTargetColumn:t.junctionTargetColumn});if(!a)throw new Error(`Failed to resolve junction info for ${s}.${t.relationName}`);let u=this.uniqueValues(e.map(k=>k._id)),c=new Map;for(let k of e)c.set(this.keyOf(k._id),[]);if(u.length===0)return{grouped:c,docs:[]};let d=t.userFilter?he(this.normalizeMetadata(),t.userFilter,t.targetTable):null,l=t.userLimit,f=t.userPage;if(l!==void 0&&l>0){let k=f?(f-1)*l:0;return this.fetchM2MTopK(u,t,a,o,d,k,l)}let p=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1&&!d,m=this.hasDottedSort(t.userSort);if(!m)return this.fetchM2MEdgeBatch(u,t,a,o,d);let g=await K(u,k=>this.runQuery(()=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:k}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray()));if(g.length===0)return{grouped:c,docs:[],stats:{strategy:"m2m-batch",roundtrips:this.chunkCount(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:0}};let h=new Set,y=[];for(let k of g){let F=k[a.otherColumn];if(F==null)continue;let w=this.keyOf(F);h.has(w)||(h.add(w),y.push(F))}let b=[],_=new Map;if(p)b=y.map(k=>({_id:k})),this.sortDocsByPk(b);else{let k={_id:{$in:y}};d&&Object.keys(d).length>0&&Object.assign(k,d);let F;if(m){let w=this.buildSortAggregatePipeline(t.targetTable,k,t.userSort);o.projection&&w.push({$project:o.projection}),F=await this.runQuery(()=>this.db.collection(t.targetTable).aggregate(w).toArray())}else{let w=this.buildSortFromTokens(t.userSort)||{_id:1},v=this.projectionWithSortFields(o.projection,t.userSort),B={sort:w};v.projection&&(B.projection=v.projection),F=await K(y,S=>this.runQuery(()=>this.db.collection(t.targetTable).find({_id:{$in:S},...d||{}},B).toArray())),t.userSort?this.sortDocsInMemory(F,t.userSort):this.sortDocsByPk(F),this.removeHiddenFields(F,v.hiddenFields)}b=this.applyReadFallback(F,o)}for(let k of b)_.set(this.keyOf(k._id),k);let C=new Map;for(let k of g){let F=this.keyOf(k[a.selfColumn]),w=this.keyOf(k[a.otherColumn]);_.has(w)&&(C.has(w)||C.set(w,[]),C.get(w).push(F))}for(let k of b){let F=C.get(this.keyOf(k._id))||[];for(let w of F)c.get(w)?.push(k)}let T=p||y.length===0?0:this.chunkCount(y);return{grouped:c,docs:b,stats:{strategy:p?"m2m-junction-batch":"m2m-batch",roundtrips:this.chunkCount(u)+T,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length+b.length}}}applyReadFallback(e,t){let n=t.pendingRenames??[];if(e.length===0||n.length===0)return e;let i=new Set(t.hiddenFields??[]);for(let o of e)for(let s of n)o[s.newName]===void 0&&o[s.oldName]!==void 0&&(o[s.newName]=o[s.oldName]),(i.has(s.oldName)||o[s.newName]!==void 0)&&delete o[s.oldName];return e}};async function $n(r,e,t,n,i=3,o=0,s,a,u,c){let d=await c?.getActiveFieldRenamesByTable?.(),l=new Ze(r,a,d);await new Ce(l,n,u).execute(e,t,i,o,s)}async function er(r,e,t){let n=[],{db:i,metadata:o,dbType:s,debugLog:a}=t,u=o?.tables?.get(e.table),c=new Set((u?.relations??[]).map(S=>S.propertyName)),d=!!e.mongoRawFilter&&!!o&&re(e.mongoRawFilter,c),l=e.plan,f=l?.filterTree&&!l.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&o&&d){let S=await Se(e.mongoRawFilter,e.table,o,i);S&&Object.keys(S).length>0&&n.push({$match:S})}else if(f){let S=Ve(l.filterTree,{metadata:o,rootTable:e.table});Object.keys(S).length>0&&n.push({$match:S})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let S=Je(o,e.where,e.table,s);n.push({$match:S})}let p=e.plan,g=p?p.hasRelationSort:e.sort?.some(S=>{if(!S.field.includes("."))return!1;let M=S.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(A=>A.propertyName===M)??!1})??!1,h=()=>p?.sortItems?Io(p.sortItems):e.sort?vo(e.sort):null,y=p?.sortItems?Co(p.sortItems):[],b=p?.sortItems?ko(p.sortItems):[],_=()=>{!p||y.length===0||Ro(n,e.table,p.sortItems,o)},C=()=>{!p||b.length===0||Fo(n,e.table,p.sortItems,o)},T=()=>{let S=[...y,...b];S.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(S.map(M=>[M,0]))})};if(!e.mongoFieldsExpanded){_(),C();let S=h();if(S&&n.push({$sort:S}),e.mongoCountOnly?n.push({$count:"count"}):(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit})),T(),e.select){let A={};for(let D of e.select)A[D]=1;n.push({$project:A})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let M=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:M,pipeline:n}:{results:Yr(M),pipeline:n}}let{scalarFields:k,relations:F}=e.mongoFieldsExpanded;if(!g){_(),C();let S=h();S&&n.push({$sort:S}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}let w=[];for(let S of F)if(e.sort?.some(A=>A.field.startsWith(`${S.propertyName}.`))){let A=e.mongoRawFilter?.[S.propertyName];if(S.nestedFields&&S.nestedFields.length>0){let j=await Pt(o,S.targetTable,S.nestedFields??[],A);S.type==="one"&&j.length>0&&j.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:j.length>0?j:void 0}})}else if(A){let j=await Pt(o,S.targetTable,["_id"],A);S.type==="one"&&j.length>0&&j.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:j.length>0?j:void 0}})}else n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName}});S.type==="one"&&(n.push({$unwind:{path:`$${S.propertyName}`,preserveNullAndEmptyArrays:!0}}),A&&(et(A)||n.push({$match:{[S.propertyName]:{$ne:null}}})))}else w.push(S);if(g){_(),C();let S=h();S&&n.push({$sort:S}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}T(),await Hr(o,n,e.table,k,[...F]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let v=performance.now(),B=await r.aggregate(n).toArray();if(e.debugTrace?.dur("db_execute",v,{table:e.table}),e.mongoCountOnly)return{results:B,pipeline:n};if(w.length>0&&B.length>0){let S=e.deep||{},M=w.map(D=>{let $=o?.tables?.get(e.table)?.relations?.find(J=>J.propertyName===D.propertyName),R=S[D.propertyName],N=R?.fields!=null?Array.isArray(R.fields)?R.fields:String(R.fields).split(",").map(J=>J.trim()).filter(Boolean):D.nestedFields&&D.nestedFields.length>0?D.nestedFields:["_id"];return{relationName:D.propertyName,type:$?.type,targetTable:D.targetTable,fields:N,isInverse:$?.isInverse,mappedBy:$?.mappedBy,junctionTableName:$?.junctionTableName,junctionSourceColumn:$?.junctionSourceColumn,junctionTargetColumn:$?.junctionTargetColumn,localField:D.localField,foreignField:D.foreignField,userFilter:R?.filter,userSort:R?.sort,userLimit:R?.limit!==void 0?Number(R.limit):void 0,userPage:R?.page!==void 0?Number(R.page):void 0,nestedDeep:R?.deep}}),A=xo(o);A&&await $n(i,B,M,A,3,0,e.table,o,e.debugTrace,t.mongoPhysicalMigrationService)}return{results:Yr(B),pipeline:n}}function tr(r){return`__sort_count_${r.relationName||r.field}`}function nr(r){return`__sort_${r.function}_${r.relationName||r.field}_${r.aggregateField||"value"}`}function Co(r){return r.filter(e=>e.function==="count").map(tr)}function ko(r){return r.filter(e=>e.function==="max"||e.function==="min").map(nr)}function Ro(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="count")continue;let a=s.relationMeta,u=s.relationName||s.field,c=a?.targetTableName||a?.targetTable,d=tr(s);if(!(!a||!c)){if(a.type==="one-to-many"){let l=q(a)||u;r.push({$lookup:{from:c,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${l}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let l=Me(e,a);if(!l)continue;r.push({$lookup:{from:l.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${l.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}})}}}}function Fo(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="max"&&s.function!=="min")continue;let a=s.relationMeta,u=s.relationName||s.field,c=a?.targetTableName||a?.targetTable,d=n?.tables?.get(c),l=d?.columns?.find(h=>h.isPrimary)?.name||(d?.columns?.some(h=>h.name==="_id")?"_id":"id"),f=s.aggregateField,p=f==="id"&&d?.columns?.some(h=>h.name==="_id")?"_id":f,m=nr(s),g=s.function==="min"?"$min":"$max";if(!(!a||!c||!f)){if(a.type==="one-to-many"){let h=q(a)||u;r.push({$lookup:{from:c,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${h}`,"$$localId"]}}},{$group:{_id:null,value:{[g]:`$${p}`}}}],as:m}}),r.push({$addFields:{[m]:{$arrayElemAt:[`$${m}.value`,0]}}});continue}if(a.type==="many-to-many"){let h=Me(e,a);if(!h)continue;let y=`${m}_junction`;r.push({$lookup:{from:h.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${h.selfColumn}`,"$$localId"]}}},{$project:{_id:0,targetId:`$${h.otherColumn}`}}],as:y}}),r.push({$lookup:{from:c,let:{targetIds:`$${y}.targetId`},pipeline:[{$match:{$expr:{$in:[`$${l}`,"$$targetIds"]}}},{$group:{_id:null,value:{[g]:`$${p}`}}}],as:m}}),r.push({$addFields:{[m]:{$arrayElemAt:[`$${m}.value`,0]}}}),r.push({$project:{[y]:0}})}}}}function xo(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(i=>({name:i.name,type:i.type})),relations:n.relations||[]}:null}:null}function vo(r){let e={};for(let t of r){let n=t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function Io(r){let e={};for(let t of r){let n=t.function==="count"?tr(t):t.function==="max"||t.function==="min"?nr(t):t.joinId!==null?t.fullPath:t.field;e[n]=t.direction==="asc"?1:-1}return e}function et(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>et(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>et(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>et(e));if("_not"in r)return et(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||et(t)))return!0}return!1}function Yr(r){return r.map(Z)}function Xr(r,e){let t=[],n=[],i=e?.tables?.get(r.rootTable);if(!i)return{scalarFields:t,relations:n};for(let o of r.nodes)if(o.kind==="wildcard")for(let s of i.columns||[])t.includes(s.name)||t.push(s.name);else o.kind==="scalar"?i.columns?.some(a=>a.name===o.name)&&!t.includes(o.name)&&t.push(o.name):o.kind==="relation"&&n.push(No(o,i,e));return{scalarFields:t,relations:n}}function No(r,e,t){let n=e.relations?.find(c=>c.propertyName===r.propertyName),i,o,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&Ne(n)?(i="_id",o=q(n)||r.propertyName,s=!0):(i=n&&H(n)||r.propertyName,o="_id",s=!1):r.relationType==="one-to-many"?(i="_id",o=n&&q(n)||r.propertyName,s=!0):n?.mappedBy?(i="_id",o=n.mappedBy,s=!0):(i=r.propertyName,o="_id",s=!1);let a=r.relationType==="one-to-many"||r.relationType==="many-to-many",u=Zr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:i,foreignField:o,type:a?"many":"one",isInverse:s,nestedFields:u}}function Zr(r){let e=[];for(let t of r)if(t.kind==="wildcard")e.push("*");else if(t.kind==="scalar")e.push(t.name);else if(t.kind==="relation"){let n=Zr(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let i of n)e.push(`${t.propertyName}.${i}`)}return e}ze();Ot();Et();function Tn(r,e,t,n){let i={rootTable:e,nodes:[]};if(!r||r.length===0)return i;let o=t?.tables?.get(e);if(!o)return i;let s=o.columns?.some(l=>l.name==="_id"&&l.isPrimary),a=o.columns?.some(l=>l.name==="id"),u=s&&!a?"_id":"id",c=new Map,d=[];for(let l of r){let f=l==="id"?u:l;if(f==="*")d.push("*");else if(f.includes(".")){let p=f.indexOf("."),m=f.substring(0,p),g=f.substring(p+1);if(!o.relations?.some(y=>y.propertyName===m))continue;c.has(m)||c.set(m,[]),c.get(m).push(g)}else if(o.relations?.some(m=>m.propertyName===f))c.has(f)||c.set(f,[u]);else{if(!o.columns?.some(g=>g.name===f))continue;d.push(f)}}if(d.includes("*")){i.nodes.push({kind:"wildcard"});for(let l of o.relations||[])c.has(l.propertyName)||c.set(l.propertyName,[u])}else for(let l of d)i.nodes.push({kind:"scalar",name:l});for(let[l,f]of c.entries()){let p=o.relations?.find(h=>h.propertyName===l);if(!p)continue;let m=p.targetTableName||p.targetTable,g={kind:"relation",propertyName:l,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:m,children:ei(f,m,t)};if(p.type==="many-to-one"||p.type==="one-to-one"){let h=n.registerWithParent(e,l,t,"left",null,"data");g.joinId=h}i.nodes.push(g)}return i}function ei(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let i=n.columns?.some(d=>d.name==="_id"&&d.isPrimary),o=n.columns?.some(d=>d.name==="id"),s=i&&!o?"_id":"id",a=new Map,u=[];for(let d of r){let l=d==="id"?s:d;if(l==="*")u.push("*");else if(l.includes(".")){let f=l.indexOf("."),p=l.substring(0,f),m=l.substring(f+1);if(!n.relations?.some(h=>h.propertyName===p))continue;a.has(p)||a.set(p,[]),a.get(p).push(m)}else if(n.relations?.some(p=>p.propertyName===l))a.has(l)||a.set(l,[s]);else{if(!n.columns?.some(m=>m.name===l))continue;u.push(l)}}let c=[];if(u.includes("*")){c.push({kind:"wildcard"});for(let d of n.relations||[])a.has(d.propertyName)||a.set(d.propertyName,[s])}else for(let d of u)c.push({kind:"scalar",name:d});for(let[d,l]of a.entries()){let f=n.relations?.find(m=>m.propertyName===d);if(!f)continue;let p=f.targetTableName||f.targetTable;c.push({kind:"relation",propertyName:d,joinId:null,relationType:f.type,isInverse:!!f.isInverse,targetTable:p,children:ei(l,p,t)})}return c}fe();fe();var Mo=new Set(["_and","_or","_not"]);function ti(r,e){return r?.tables?.get(e)??null}function Eo(r,e,t){return ti(r,e)?.columns?.find(n=>n.name===t)}function rr(r,e,t){return ti(r,e)?.relations?.find(n=>n.propertyName===t)}function Oo(r){let e=r.match(/^_(count|max|min)\(([^)]+)\)$/);if(!e)return null;let t=e[1],n=e[2].trim();if(t==="count")return{functionName:t,relationName:n};let i=n.indexOf(".");return i<=0||i!==n.lastIndexOf(".")?null:{functionName:t,relationName:n.slice(0,i).trim(),fieldName:n.slice(i+1).trim()}}function ir(r,e,t,n){if(Eo(r,e,t)?.isEncrypted===!0)throw new I(`Encrypted field '${t}' on '${e}' cannot be used for ${n}.`)}function Ae(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){for(let n of r)Ae(n,e,t);return}for(let[n,i]of Object.entries(r)){if(Mo.has(n)){Ae(i,e,t);continue}if(n.startsWith("_"))continue;let o=rr(t,e,n);if(o){let s=o.targetTableName||o.targetTable;s&&Ae(i,s,t);continue}ir(t,e,n,"filter")}}}function Sn(r,e,t){if(!r)return;let n=Array.isArray(r)?r:r.split(",").map(i=>i.trim()).filter(Boolean);for(let i of n){let o=i.startsWith("-")?i.slice(1):i;if(!o)continue;let s=Oo(o);if(s){if(s.functionName==="count")continue;let c=rr(t,e,s.relationName),d=c?.targetTableName||c?.targetTable;d&&ir(t,d,s.fieldName,"sort");continue}let a=o.split("."),u=e;for(let c=0;c<a.length;c++){let d=a[c];if(c===a.length-1){ir(t,u,d,"sort");break}let f=rr(t,u,d);if(!f)break;u=f.targetTableName||f.targetTable||u}}}var te=class{plan(e){let{tableName:t,fields:n,filter:i,sort:o,page:s,limit:a,meta:u,metadata:c,dbType:d}=e,l=c?.tables?.get(t),f=new oe,p=this.parseFields(n),m=null;p&&l&&(m=Tn(p,t,c,f));let g=!1,h=null;if(i&&l){Ae(i,t,c);let S=pe(i,t,c,f);h=S.node,g=S.hasRelationFilters}let y=this.parseSort(o);l&&Sn(y,t,c);let b=[],_=!1;for(let S of y){let M=S.startsWith("-"),A=M?S.substring(1):S,D=M?"desc":"asc";if(l){let j=this.parseRelationAggregateSort(t,l,A,c);if(j){b.push({joinId:null,field:A,direction:D,fullPath:A,function:j.functionName,relationName:j.relationName,aggregateField:j.aggregateField,relationMeta:j.relationMeta});continue}this.assertLocalSortField(t,l,A)}b.push({joinId:null,field:A,direction:D,fullPath:A})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let C=this.parseLimit(a),T=this.parsePage(s),k=T!==void 0&&C!==void 0?(T-1)*C:void 0,F=this.parseMeta(u),w=F.includes("totalCount")||F.includes("*"),v=F.includes("filterCount")||F.includes("*"),B=f.getAll();return{table:t,dbType:d,rawFields:p,rawFilter:i??null,joins:B,sortItems:b,limit:C,offset:k,needsTotalCount:w,needsFilterCount:v,hasRelationFilters:g,hasRelationSort:_,filterTree:h,fieldTree:m}}parseFields(e){if(e)return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):e.split(",").map(t=>t.trim()).filter(Boolean)}parseSort(e){return e?(Array.isArray(e)?e:e.split(",")).map(n=>n.trim()).filter(Boolean):[]}parseLimit(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;if(!Number.isNaN(t))return t<0?0:t}parsePage(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;return Number.isNaN(t)?void 0:t}parseMeta(e){return e?Array.isArray(e)?e:e.split(",").map(t=>t.trim()).filter(Boolean):[]}assertLocalSortField(e,t,n){if(n.includes("."))throw new I(`Sort field '${n}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let i=t.columns?.some(s=>s.name===n),o=n==="id"&&t.columns?.some(s=>s.name==="_id");if(!i&&!o)throw new I(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationAggregateSort(e,t,n,i){let o=n.match(/^_(count|max|min)\(([^)]+)\)$/);if(!o){if(/^_(count|max|min)\(/.test(n))throw new I(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName), _max(relationName.fieldName), or _min(relationName.fieldName).`);return null}let s=o[1],a=o[2].trim();if(s==="count"){let h=a;if(!h||h.includes("."))throw new I(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let y=t.relations?.find(b=>b.propertyName===h);if(!y)throw new I(`Sort relation '${h}' does not exist on '${e}'.`);if(y.type!=="one-to-many"&&y.type!=="many-to-many")throw new I(`Sort function '_count(${h})' is only supported for list relations on '${e}'.`);return{functionName:s,relationName:h,relationMeta:y}}let u=a.indexOf(".");if(u<=0||u!==a.lastIndexOf("."))throw new I(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let c=a.slice(0,u).trim(),d=a.slice(u+1).trim();if(!c||!d)throw new I(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let l=t.relations?.find(h=>h.propertyName===c);if(!l)throw new I(`Sort relation '${c}' does not exist on '${e}'.`);if(l.type!=="one-to-many"&&l.type!=="many-to-many")throw new I(`Sort function '_${s}(${c}.${d})' is only supported for list relations on '${e}'.`);let f=l.targetTableName||l.targetTable,p=i?.tables?.get(f);if(!p)throw new I(`Sort function '${n}' references unknown target table '${f}' on '${e}'.`);let m=p.columns?.find(h=>h.name===d),g=d==="id"&&p.columns?.some(h=>h.name==="_id");if(!m&&!g)throw new I(`Sort field '${d}' does not exist on '${f}' for function '_${s}(${c}.${d})'.`);if(m?.isEncrypted===!0)throw new I(`Encrypted field '${d}' on '${f}' cannot be used for sort.`);return{functionName:s,relationName:c,aggregateField:d,relationMeta:l}}registerSortJoinChain(e,t,n,i,o){let s=e.indexOf(".");if(s===-1)return null;let a=e.slice(0,s),u=e.slice(s+1),c=n?.tables?.get(t);if(!c)return null;let d=c.relations?.find(p=>p.propertyName===a);if(!d||d.type!=="many-to-one"&&d.type!=="one-to-one")return null;let l=i.registerWithParent(t,a,n,"left",o,"sort");if(!l)return null;if(!u.includes("."))return{lastJoinId:l,field:u};let f=d.targetTableName||d.targetTable;return this.registerSortJoinChain(u,f,n,i,l)}};fe();var Ao=new Set(["int","integer","bigint","smallint","tinyint","float","double","decimal","numeric","real","number"]),Po=new Set(["date","datetime","timestamp","timestamptz","timestamp with time zone","timestamp without time zone"]),jo=new Set(["hour","day","week","month","year"]),Bo=new Set(["count","countDistinct","sum","avg","min","max"]);function O(r,e){throw new I(e,{path:r})}function tt(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Lo(r,e){let t=r?.tables?.get(e);return t||O("aggregate",`Table "${e}" metadata is not available`),t}function ni(r,e,t){let n=r.columns?.find(i=>i.name===e);return n||O(t,`Unknown aggregate field "${e}"`),n.isEncrypted===!0&&O(t,`Encrypted field "${e}" cannot be used in aggregate queries`),n}function Do(r,e){let t=r===void 0?"UTC":r;(typeof t!="string"||t.length===0)&&O(e,"Aggregate timezone must be a non-empty IANA timezone");try{new Intl.DateTimeFormat("en-US",{timeZone:t}).format()}catch{O(e,`Invalid aggregate timezone "${t}"`)}return t}function Wo(r,e){return r==null?{}:(tt(r)||O(e,"Aggregate filter must be an object"),r)}function nt(r,e,t){tt(r)||O("aggregate","Aggregate options must be an object");let n=Lo(t,e),i=r.dimensions===void 0?[]:r.dimensions,o=r.measures;Array.isArray(i)||O("aggregate.dimensions","Aggregate dimensions must be an array"),(!tt(o)||Object.keys(o).length===0)&&O("aggregate.measures","Aggregate requires at least one measure");let s=new Set,a=i.map((g,h)=>{let y=`aggregate.dimensions[${h}]`;(!tt(g)||typeof g.field!="string"||g.field.length===0)&&O(y,"Aggregate dimension requires a field");let b=ni(n,g.field,`${y}.field`);return s.has(g.field)&&O(`${y}.field`,`Duplicate aggregate dimension "${g.field}"`),s.add(g.field),g.bucket===void 0?(g.timezone!==void 0&&O(`${y}.timezone`,"Aggregate timezone requires a bucket"),{field:g.field,outputKey:g.field,column:b}):((typeof g.bucket!="string"||!jo.has(g.bucket))&&O(`${y}.bucket`,"Aggregate bucket must be hour, day, week, month, or year"),Po.has(String(b.type).toLowerCase())||O(`${y}.bucket`,`Aggregate bucket requires a date field, but "${g.field}" is "${b.type}"`),{field:g.field,outputKey:g.field,bucket:g.bucket,timezone:Do(g.timezone,`${y}.timezone`),column:b})}),u=new Set,c=Object.entries(o).map(([g,h])=>{let y=`aggregate.measures.${g}`;(!g||!tt(h))&&O(y,"Aggregate measure must be an object");let b=Object.entries(h).filter(([k])=>k!=="as");b.length!==1&&O(y,"Aggregate measure must define exactly one operation");let[_,C]=b[0];Bo.has(_)||O(y,`Unsupported aggregate measure "${_}"`),(typeof C!="string"||C.length===0)&&O(y,"Aggregate measure field must be a non-empty string");let T=ni(n,C,`${y}.${_}`);return(u.has(g)||s.has(g))&&O(y,`Aggregate output key "${g}" is duplicated`),u.add(g),["sum","avg","min","max"].includes(_)&&!Ao.has(String(T.type).toLowerCase())&&O(y,`Aggregate ${_} requires a numeric field, but "${C}" is "${T.type}"`),{outputKey:g,operation:_,field:C,column:T}}),d=r.sort===void 0?[]:r.sort;Array.isArray(d)||O("aggregate.sort","Aggregate sort must be an array");let l=new Set([...s,...u]),f=d.map((g,h)=>{let y=`aggregate.sort[${h}]`;return(!tt(g)||typeof g.field!="string"||!l.has(g.field))&&O(y,"Aggregate sort field must reference a dimension or measure output"),g.direction!=="asc"&&g.direction!=="desc"&&O(`${y}.direction`,"Aggregate sort direction must be asc or desc"),{field:g.field,direction:g.direction}}),p=r.limit===void 0?void 0:Number(r.limit),m=r.page===void 0?1:Number(r.page);return p!==void 0&&(!Number.isInteger(p)||p<=0||p>1e4)&&O("aggregate.limit","Aggregate limit must be an integer between 1 and 10000"),(!Number.isInteger(m)||m<=0)&&O("aggregate.page","Aggregate page must be a positive integer"),{tableName:e,filter:Wo(r.filter,"aggregate.filter"),dimensions:a,measures:c,sort:f,page:m,limit:p}}var Pe=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.debugLog=[];this.lastBuiltPipeline=null;this.db=e.getDb()}async execute(e){if(this.metadata=e.metadata,this.dbType=e.dbType||"mongodb",!e.plan){let l=new te;e={...e,plan:l.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:"mongodb"})}}let t=e.debugLog||[];this.debugLog=t;let n={table:e.tableName,metadata:e.metadata,debugTrace:e.debugTrace};if(e.pipeline&&(n.pipeline=e.pipeline),e.fields&&(Array.isArray(e.fields)?n.fields=e.fields:typeof e.fields=="string"&&(n.fields=e.fields.split(",").map(l=>l.trim()))),e.filter&&(ie(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let l=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(f=>f.trim());n.sort=l.map(f=>{let p=f.trim();return p.startsWith("-")?{field:p.substring(1),direction:"desc"}:{field:p,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let l=typeof e.page=="string"?parseInt(e.page,10):e.page,f=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(l-1)*f,n.limit=f}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let i=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(l=>l.trim()).filter(Boolean),o=0,s=0;(i.includes("totalCount")||i.includes("*"))&&(o=await this.mongoService.collection(e.tableName).countDocuments({}));let a=this.metadata?.tables?.get(e.tableName),u=new Set((a?.relations??[]).map(l=>l.propertyName)),c=!!n.mongoRawFilter&&re(n.mongoRawFilter,u);if((i.includes("filterCount")||i.includes("*"))&&!c){let l=this.mongoService.collection(e.tableName),f=e.plan?.filterTree?Ve(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await l.countDocuments(f)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let d=await this.selectLegacy(n);if(e.debugMode){let l=this.lastBuiltPipeline??[],f;try{f=await this.db.collection(e.tableName).aggregate(l).explain()}catch(p){f={error:String(p)}}return{pipeline:l,explain:f}}if(c&&(i.includes("filterCount")||i.includes("*"))){let l={...n,mongoCountOnly:!0},f=await this.selectLegacy(l);s=f.length>0?f[0].count:0}return{data:d,...i.length>0&&{meta:{...i.includes("totalCount")||i.includes("*")?{totalCount:o}:{},...i.includes("filterCount")||i.includes("*")?{filterCount:s}:{}}}}}async aggregate(e){this.metadata=e.metadata,this.dbType=e.dbType||"mongodb";let t=nt(e.aggregate,e.tableName,e.metadata),n=this.db.collection(e.tableName),i=new te().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:"mongodb"}),o=i.hasRelationFilters?await Se(t.filter,e.tableName,e.metadata,this.db):i.filterTree?Ve(i.filterTree,{metadata:e.metadata,rootTable:e.tableName}):{},s=[];Object.keys(o).length>0&&s.push({$match:o});let a={_id:{}},u={};for(let d of t.dimensions){let l=`$${d.field}`,f=d.bucket?{$dateTrunc:{date:l,unit:d.bucket,timezone:d.timezone}}:l;a._id[d.outputKey]=f,u[d.outputKey]=`$_id.${d.outputKey}`}for(let d of t.measures){let l=`$${d.field}`;a[d.outputKey]=d.operation==="count"?{$sum:{$cond:[{$ne:[l,null]},1,0]}}:d.operation==="countDistinct"?{$addToSet:l}:{[`$${d.operation}`]:l},u[d.outputKey]=d.operation==="countDistinct"?{$size:{$setDifference:[`$${d.outputKey}`,[null]]}}:`$${d.outputKey}`}return s.push({$group:a},{$project:{_id:0,...u}}),t.sort.length>0&&s.push({$sort:Object.fromEntries(t.sort.map(d=>[d.field,d.direction==="asc"?1:-1]))}),t.limit!==void 0&&s.push({$skip:(t.page-1)*t.limit},{$limit:t.limit}),this.lastBuiltPipeline=s,e.debugMode?{pipeline:s,explain:await n.aggregate(s).explain()}:{data:(await n.aggregate(s).toArray()).map(Z)}}async selectLegacy(e){let t=[],n=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,i=this.metadata?.tables?.get(e.table),o=i?.relations&&i.relations.length>0;if(e.fields&&e.fields.length>0||n||o){let c=e.plan,d=e.fields&&e.fields.length>0?e.fields:["*"];if(e.fields&&e.fields.length>0&&c?.fieldTree){if(e.mongoFieldsExpanded=Xr(c.fieldTree,this.metadata),n){let l=await Nt(this.metadata,e.table,[],e.deep),f=new Set(e.mongoFieldsExpanded.relations.map(p=>p.propertyName));e.mongoFieldsExpanded.relations.push(...l.relations.filter(p=>!f.has(p.propertyName)))}}else console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await Nt(this.metadata,e.table,d,e.deep);if(this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let l=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:l.scalarFields},t=l.hiddenFields}}e.where&&(e.where=e.where.map(c=>c.field.includes(".")?c:{...c,field:`${e.table}.${c.field}`}));let s=this.db.collection(e.table);if(e.pipeline)return this.debugLog&&this.debugLog.push({type:"MongoDB Custom Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(e.pipeline))}),(await s.aggregate(e.pipeline).toArray()).map(Z);let{results:a,pipeline:u}=await er(s,e,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=u,this.mongoPhysicalMigrationService?await this.mongoPhysicalMigrationService.applyReadFallback(e.table,a,t):a}async executeAggregationPipeline(e,t){let{results:n,pipeline:i}=await er(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=i,n}};var Cn=class{constructor(e){this.context=e}log(e){console.log(this.format(e))}warn(e){console.warn(this.format(e))}error(e,t){console.error(this.format(e)),t&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}fatal(e,t){this.error(e,t)}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};fe();le();var Ko=["_and","_or","_not"];function me(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>me(e));for(let e of Object.keys(r))if(Ko.includes(e)||typeof r[e]=="object"&&r[e]!==null&&me(r[e]))return!0;return!1}var ri=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function qo(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function kn(r,e,t){if(!t)return!1;let n=r;if(r.includes(".")){let s=r.split(".");n=s[s.length-1]}let i=t.columns.find(s=>s.name===n);if(!i)return!1;let o=i.type?.toLowerCase()||"";return o==="uuid"||o==="uuidv4"||o.includes("uuid")}function Uo(r,e,t,n,i){return n!=="postgres"||typeof e!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||kn(r,t,i),e}function ii(r,e,t,n,i,o,s){let a=i&&!e.includes(".")?`${i}.${e}`:e,u=Fe(a,o??"postgres"),c=kn(e,i,s),d=Uo(e,n,i,o,s);switch(t){case"_eq":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} = ?::uuid`,[n]):r.where(a,"=",d);break;case"_neq":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} != ?::uuid`,[n]):r.where(a,"!=",d);break;case"_gt":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} > ?::uuid`,[n]):r.where(a,">",d);break;case"_gte":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} >= ?::uuid`,[n]):r.where(a,">=",d);break;case"_lt":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} < ?::uuid`,[n]):r.where(a,"<",d);break;case"_lte":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} <= ?::uuid`,[n]):r.where(a,"<=",d);break;case"_in":let l=n;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(p=>p.trim()):[l]),c&&o==="postgres"&&l.every(p=>typeof p=="string")?r.whereRaw(`${u} = ANY(?::uuid[])`,[l]):r.whereIn(a,l);break;case"_not_in":case"_nin":let f=n;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]),c&&o==="postgres"&&f.every(p=>typeof p=="string")?r.whereRaw(`${u} != ALL(?::uuid[])`,[f]):r.whereNotIn(a,f);break;case"_contains":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_starts_with":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${u}) LIKE lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_ends_with":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?))`,[n]):o==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?)`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`,[n]);break;case"_between":Array.isArray(n)&&n.length===2&&r.whereBetween(a,[n[0],n[1]]);break;case"_is_null":n===!0?r.whereNull(a):r.whereNotNull(a);break;case"_is_not_null":n===!0?r.whereNotNull(a):r.whereNull(a);break;default:r.where(a,qo(t),n)}}function Qo(r,e,t){if(!t||!e||r.startsWith("_"))return!0;let n=r.includes(".")?r.split(".").pop():r,i=t.columns?.some(s=>s.name===n),o=t.relations?.some(s=>s.propertyName===n);return i||o}function rt(r,e,t,n="and",i,o){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let s of e)n==="and"?r.where(function(){rt(this,s,t,"and",i,o)}):r.orWhere(function(){rt(this,s,t,"and",i,o)});return}for(let[s,a]of Object.entries(e))if(Qo(s,t,o)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){rt(this,u,t,"and",i,o)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){rt(this,u,t,"and",i,o)})});continue}if(s==="_not"){r.whereNot(function(){rt(this,a,t,"and",i,o)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(c=>ri.includes(c)))for(let[c,d]of Object.entries(a))ri.includes(c)&&(n==="and"?r.where(function(){ii(this,s,c,d,t,i,o)}):r.orWhere(function(){ii(this,s,c,d,t,i,o)}));else{let c=t&&!s.includes(".")?`${t}.${s}`:s,d=Fe(c,i??"postgres");kn(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${d} = ?::uuid`,[a]):r.orWhereRaw(`${d} = ?::uuid`,[a]):n==="and"?r.where(c,"=",a):r.orWhere(c,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s,c=Fe(u,i??"postgres");kn(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${c} = ?::uuid`,[a]):r.orWhereRaw(`${c} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function ce(r,e,t,n,i){return!e||typeof e!="object"||rt(r,e,t,"and",n,i),r}le();function ar(r,e,t){return`${x(r,t)}.${x(e,t)}`}function xe(r,e){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function oi(r,e){if(!e)return!1;let t=e.columns.find(i=>i.name===r);if(!t)return!1;let n=t.type?.toLowerCase()||"";return n==="uuid"||n==="uuidv4"||n.includes("uuid")}function it(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function lr(r,e,t,n,i,o){let s=[];for(let[a,u]of Object.entries(o)){let c=await Lt(r,e,a,u,t,n,i);if(c!==null)s.push(`EXISTS (${c})`);else{let d=t.relations.find(l=>l.propertyName===a);if(d&&d.foreignKeyColumn){let l=ar(e,d.foreignKeyColumn,n),p=u.id;if(p&&typeof p=="object"){let m=it(p._is_null),g=it(p._is_not_null);if(m===!0)s.push(`${l} IS NULL`);else if(m===!1)s.push(`${l} IS NOT NULL`);else if(g===!0)s.push(`${l} IS NOT NULL`);else if(g===!1)s.push(`${l} IS NULL`);else if(p._eq!==void 0){let h=xe(p._eq,n);s.push(`${l} = ${h}`)}else if(p._neq!==void 0){let h=xe(p._neq,n);s.push(`${l} != ${h}`)}else if(p._in!==void 0){let y=(Array.isArray(p._in)?p._in:[p._in]).map(b=>xe(b,n)).join(", ");s.push(`${l} IN (${y})`)}else if(p._not_in!==void 0||p._nin!==void 0){let h=p._not_in??p._nin,b=(Array.isArray(h)?h:[h]).map(_=>xe(_,n)).join(", ");s.push(`${l} NOT IN (${b})`)}else if(p._gt!==void 0){let h=xe(p._gt,n);s.push(`${l} > ${h}`)}else if(p._gte!==void 0){let h=xe(p._gte,n);s.push(`${l} >= ${h}`)}else if(p._lt!==void 0){let h=xe(p._lt,n);s.push(`${l} < ${h}`)}else if(p._lte!==void 0){let h=xe(p._lte,n);s.push(`${l} <= ${h}`)}}}}}return s}function cr(r){return!r||typeof r!="object"||Array.isArray(r)?!1:!!(r._and&&Array.isArray(r._and)||r._or&&Array.isArray(r._or)||r._not!==void 0&&r._not!==null)}async function or(r,e,t,n,i,o){let s=[];for(let a of r)if(a._and&&Array.isArray(a._and)&&a._and.length>0){let u=[];for(let c of a._and)if(cr(c)){let d=e(t).select(`${t}.id`);await je(e,d,c,t,n,i,o),u.push({idSubquery:d})}else{let{fieldFilters:d,relationFilters:l}=G(c,n),f=await lr(e,t,n,i,o,l);u.push({fieldFilters:d,subqueries:f})}s.push(u)}else if(cr(a)){let u=e(t).select(`${t}.id`);await je(e,u,a,t,n,i,o),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:c}=G(a,n),d=await lr(e,t,n,i,o,c);s.push([{fieldFilters:u,subqueries:d}])}return s}function si(r,e,t,n,i){if("idSubquery"in e&&e.idSubquery){r.whereIn(`${t}.id`,e.idSubquery);return}let o=e;Object.keys(o.fieldFilters).length===0&&o.subqueries.length===0||r.where(function(){Object.keys(o.fieldFilters).length>0&&ce(this,o.fieldFilters,t,i,n);for(let s of o.subqueries)this.whereRaw(s)})}function sr(r,e,t,n,i){let o=!0;for(let s of e){let a=function(){for(let u of s)si(this,u,t,n,i)};o?(r.where(a),o=!1):r.orWhere(a)}}function Rn(r,e,t,n,i,o,s){let a=oi(e,i),u=oi(n,o),c=`${x(r,s)}.${x(e,s)}`,d=`${x(t,s)}.${x(n,s)}`;if(s==="postgres"){if(a&&!u)return`${c} = ${d}::uuid`;if(!a&&u)return`${c}::uuid = ${d}`}return`${c} = ${d}`}async function Lt(r,e,t,n,i,o,s){let a=i.relations.find(f=>f.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${e}"`);let u=a.targetTableName||a.targetTable;if(!u)throw new Error(`Relation "${t}" in table "${e}" is missing targetTable/targetTableName. Relation metadata: ${JSON.stringify(a,null,2)}`);let c=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn){let f=Object.keys(n||{});if(f.length===1&&f[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(m=>c.has(m)))return null}let d=s?await s(u):null,l;switch(a.type){case"one-to-many":l=r(u).select(r.raw("1")).whereRaw(Rn(u,a.foreignKeyColumn,e,"id",d,i,o));break;case"many-to-many":let f=s?await s(a.junctionTableName):null;l=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw(Rn(a.junctionTableName,a.junctionTargetColumn,u,"id",f,d,o))).whereRaw(Rn(a.junctionTableName,a.junctionSourceColumn,e,"id",f,i,o));break;case"many-to-one":case"one-to-one":l=r(u).select(r.raw("1")).whereRaw(Rn(u,"id",e,a.foreignKeyColumn,d,i,o));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?d?await je(r,l,n,u,d,o,s):l=ce(l,n,u,o,d||void 0):l=ce(l,n,u,o),l.toString()}async function je(r,e,t,n,i,o,s){if(!t||typeof t!="object")return;if(t._and&&Array.isArray(t._and)){for(let c of t._and)if(c._or&&Array.isArray(c._or)&&c._or.length>0){let d=await or(c._or,r,n,i,o,s);e.where(function(){sr(this,d,n,i,o)})}else if(c._and&&Array.isArray(c._and)&&c._and.length>0)for(let d of c._and)await je(r,e,d,n,i,o,s);else await je(r,e,c,n,i,o,s);return}if(t._or&&Array.isArray(t._or)){let c=await or(t._or,r,n,i,o,s);e.where(function(){sr(this,c,n,i,o)});return}if(t._not){let c=t._not;if(c._and&&Array.isArray(c._and)&&c._and.length>0){let f=[];for(let p of c._and)if(cr(p)){let m=r(n).select(`${n}.id`);await je(r,m,p,n,i,o,s),f.push({idSubquery:m})}else{let{fieldFilters:m,relationFilters:g}=G(p,i),h=await lr(r,n,i,o,s,g);f.push({fieldFilters:m,subqueries:h})}e.whereNot(function(){for(let p of f)si(this,p,n,i,o)});return}if(c._or&&Array.isArray(c._or)&&c._or.length>0){let f=await or(c._or,r,n,i,o,s);e.whereNot(function(){sr(this,f,n,i,o)});return}let{fieldFilters:d,relationFilters:l}=G(c,i);e.whereNot(function(){Object.keys(d).length>0&&ce(this,d,n,o,i)});for(let[f,p]of Object.entries(l)){let m=await Lt(r,n,f,p,i,o,s);if(m===null){let g=i.relations.find(h=>h.propertyName===f);if(g&&g.foreignKeyColumn){let h=ar(n,g.foreignKeyColumn,o),b=p.id;if(b&&typeof b=="object"){let _=it(b._is_null),C=it(b._is_not_null);if(_===!0)e.whereRaw(`${h} IS NOT NULL`);else if(_===!1)e.whereRaw(`${h} IS NULL`);else if(C===!0)e.whereRaw(`${h} IS NULL`);else if(C===!1)e.whereRaw(`${h} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${h} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${h} = ?`,[b._neq]);else if(b._in!==void 0){let T=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${h} NOT IN (${T.map(()=>"?").join(", ")})`,T)}else if(b._not_in!==void 0||b._nin!==void 0){let T=b._not_in??b._nin,k=Array.isArray(T)?T:[T];e.whereRaw(`${h} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${m})`)}return}let{fieldFilters:a,relationFilters:u}=G(t,i);Object.keys(a).length>0&&ce(e,a,n,o,i);for(let[c,d]of Object.entries(u)){let l=await Lt(r,n,c,d,i,o,s);if(l===null){let f=i.relations.find(p=>p.propertyName===c);if(f&&f.foreignKeyColumn){let p=ar(n,f.foreignKeyColumn,o),g=d.id;if(g&&typeof g=="object"){let h=it(g._is_null),y=it(g._is_not_null);if(h===!0)e.whereRaw(`${p} IS NULL`);else if(h===!1)e.whereRaw(`${p} IS NOT NULL`);else if(y===!0)e.whereRaw(`${p} IS NOT NULL`);else if(y===!1)e.whereRaw(`${p} IS NULL`);else if(g._eq!==void 0)e.whereRaw(`${p} = ?`,[g._eq]);else if(g._neq!==void 0)e.whereRaw(`${p} != ?`,[g._neq]);else if(g._in!==void 0){let b=Array.isArray(g._in)?g._in:[g._in];e.whereRaw(`${p} IN (${b.map(()=>"?").join(", ")})`,b)}else if(g._not_in!==void 0||g._nin!==void 0){let b=g._not_in??g._nin,_=Array.isArray(b)?b:[b];e.whereRaw(`${p} NOT IN (${_.map(()=>"?").join(", ")})`,_)}}}}else e.whereRaw(`EXISTS (${l})`)}}async function Dt(r,e,t,n,i,o,s){await je(r,e,t,n,i,o,s)}le();le();function ot(r,e,t,n,i){for(let o of e){let s=o.field.split("."),a=t||s[0],u=s[s.length-1],c=Wt(n,a,u,o.value);switch(o.operator){case"=":r=r.where(o.field,"=",c);break;case"!=":r=r.where(o.field,"!=",c);break;case">":r=r.where(o.field,">",c);break;case"<":r=r.where(o.field,"<",c);break;case">=":r=r.where(o.field,">=",c);break;case"<=":r=r.where(o.field,"<=",c);break;case"like":r=r.where(o.field,"like",c);break;case"in":let d=Array.isArray(o.value)?o.value.map(g=>Wt(n,a,u,g)):[c];r=r.whereIn(o.field,d);break;case"not in":let l=Array.isArray(o.value)?o.value.map(g=>Wt(n,a,u,g)):[c];r=r.whereNotIn(o.field,l);break;case"is null":r=r.whereNull(o.field);break;case"is not null":r=r.whereNotNull(o.field);break;case"_contains":r=r.where(o.field,"like",`%${o.value}%`);break;case"_starts_with":r=r.where(o.field,"like",`${o.value}%`);break;case"_ends_with":r=r.where(o.field,"like",`%${o.value}`);break;case"_between":let f=o.value;if(typeof f=="string"&&(f=f.split(",").map(g=>g.trim())),Array.isArray(f)&&f.length===2){let g=Wt(n,a,u,f[0]),h=Wt(n,a,u,f[1]);r=r.whereBetween(o.field,[g,h])}break;case"_is_null":r=c===!0||c==="true"?r.whereNull(o.field):r.whereNotNull(o.field);break;case"_is_not_null":r=c===!0||c==="true"?r.whereNotNull(o.field):r.whereNull(o.field);break}}return r}function Kt(r,e,t,n){let i=[],o=t;if(!r||typeof r!="object")return i;for(let[s,a]of Object.entries(r))if(s==="_and"&&Array.isArray(a)){let u=a.map(c=>{let d=Kt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&i.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(c=>{let d=Kt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&i.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=Kt(a,e,t,n);u.length>0&&i.push(`NOT (${u.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[u,c]of Object.entries(a)){let d=`${x(e,n)}.${x(s,n)}`,l;if(c===null)l="NULL";else if(typeof c=="string"){let f=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,p=o.columns?.find(g=>g.name===s);p&&(p.type?.toLowerCase()==="uuid"||p.type?.toLowerCase().includes("uuid"))&&f.test(c)&&n==="postgres"?l=`'${c}'::uuid`:l=`'${c.replace(/'/g,"''")}'`}else typeof c=="boolean"?l=c?"true":"false":typeof c=="number"?l=String(c):l=`'${String(c).replace(/'/g,"''")}'`;if(u==="_eq")i.push(`${d} = ${l}`);else if(u==="_neq")i.push(`${d} != ${l}`);else if(u==="_gt")i.push(`${d} > ${l}`);else if(u==="_gte")i.push(`${d} >= ${l}`);else if(u==="_lt")i.push(`${d} < ${l}`);else if(u==="_lte")i.push(`${d} <= ${l}`);else if(u==="_is_null")i.push(`${d} IS NULL`);else if(u==="_is_not_null")i.push(`${d} IS NOT NULL`);else if(u==="_in"){let p=(Array.isArray(c)?c:[c]).map(m=>typeof m=="string"?`'${m.replace(/'/g,"''")}'`:String(m)).join(", ");i.push(`${d} IN (${p})`)}else if(u==="_not_in"||u==="_nin"){let p=(Array.isArray(c)?c:[c]).map(m=>typeof m=="string"?`'${m.replace(/'/g,"''")}'`:String(m)).join(", ");i.push(`${d} NOT IN (${p})`)}else if(u==="_contains"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${d}) LIKE '%${f.toLowerCase()}%'`)}else if(u==="_starts_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE lower(unaccent('${f}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${d}) LIKE '${f.toLowerCase()}%'`)}else if(u==="_ends_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}'))`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci)`):i.push(`lower(${d}) LIKE '%${f.toLowerCase()}'`)}else if(u==="_between"&&Array.isArray(c)&&c.length===2){let f=typeof c[0]=="string"?`'${c[0].replace(/'/g,"''")}'`:String(c[0]),p=typeof c[1]=="string"?`'${c[1].replace(/'/g,"''")}'`:String(c[1]);i.push(`${d} BETWEEN ${f} AND ${p}`)}}else{let u=`${x(e,n)}.${x(s,n)}`,c;a===null?c="NULL":typeof a=="string"?c=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?c=a?"true":"false":c=String(a),i.push(`${u} = ${c}`)}return i}function qt(r){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Wt(r,e,t,n){if(n==null)return n;let i=r?.tables?.get(e);if(!i?.columns)return n;let o=i.columns.find(s=>s.name===t);if(!o)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;default:return n}}dr();ze();le();Ut();qe();async function ci(r,e,t,n,i,o,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(pr(),li)),u=await a(e,t,n,i,o,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function gr(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(i=>({name:i.name,type:i.type})),relations:n.relations||[]}:null}:null}function ui(r,e,t,n,i){let o=r.targetTableName||r.targetTable;if(!o)return null;let s=r.foreignKeyColumn||V(r.propertyName);if(!s)return null;let a=l=>x(l,i),u=n?.tables?.get(o),d=(u?Y(u):null)?.name||"id";return`(SELECT ${a(o)}.${a(e)} FROM ${a(o)} WHERE ${a(o)}.${a(d)} = ${a(t)}.${a(s)})`}Ut();async function di(r,e,t,n,i){let o={};if(n.includes("totalCount")||n.includes("*")){let s=await r(t).count("* as count").first();o.totalCount=Number(s?.count||0)}if(n.includes("filterCount")||n.includes("*")){let a=await e.clone().clearSelect().clearOrder().clear("limit").clear("offset").countDistinct(`${t}.id as count`).first();o.filterCount=Number(a?.count||0)}return o}var Be=class r{constructor(e,t,n,i){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=i;this.logger=new Cn(r.name);this.debugLog=[]}async execute(e){let t=performance.now();this.metadata=e.metadata;let n=e.debugLog||[];this.debugLog=n;let i=e.debugTrace;if(e.filter&&ie(e.filter,e.tableName,e.metadata),!e.plan){let $=new te;e={...e,plan:$.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:this.dbType})}}let o=e.plan,s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,u=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,c=o.rawFields&&o.rawFields.length>0&&!o.rawFields.includes("*");if(o.joins.length===0&&!o.hasRelationFilters&&!o.hasRelationSort&&!u&&!a&&c){i&&i.setQueryPath("simple");let $=await this.executeSimple(e,o);return i&&i.dur("sql_executor",t,{table:e.tableName}),$}let l={table:e.tableName,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?l.fields=e.fields:typeof e.fields=="string"&&(l.fields=e.fields.split(",").map($=>$.trim())));let f=e.filter;if(e.filter&&!me(e.filter)){l.where=[];for(let[$,R]of Object.entries(e.filter))if(typeof R=="object"&&R!==null)for(let[N,J]of Object.entries(R)){let E;if(N==="_eq")E="=";else if(N==="_neq")E="!=";else if(N==="_in")E="in";else if(N==="_not_in"||N==="_nin")E="not in";else if(N==="_gt")E=">";else if(N==="_gte")E=">=";else if(N==="_lt")E="<";else if(N==="_lte")E="<=";else if(N==="_contains")E="_contains";else if(N==="_starts_with")E="_starts_with";else if(N==="_ends_with")E="_ends_with";else if(N==="_between")E="_between";else if(N==="_is_null")E="_is_null";else if(N==="_is_not_null")E="_is_not_null";else if(N==="_like")E="like";else if(N==="_ilike")E="ilike";else continue;l.where.push({field:$,operator:E,value:J})}else l.where.push({field:$,operator:"=",value:R})}if(e.sort){let $=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(R=>R.trim());l.sort=$.map(R=>{let N=R.trim();return N.startsWith("-")?{field:N.substring(1),direction:"desc"}:{field:N,direction:"asc"}})}else l.sort=[{field:"id",direction:"asc"}];let p=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,m=p===void 0||Number.isNaN(p)?void 0:p<0?0:p,g=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,h=g===void 0||Number.isNaN(g)?void 0:g;h&&m!==void 0?(l.offset=(h-1)*m,l.limit=m):m!==void 0&&(l.limit=m);let y=e.plan?.sortItems??(l.sort??[]).map($=>({joinId:null,field:$.field,direction:$.direction,fullPath:$.field})),b=[],_=[];for(let $ of y){if($.function==="count"){let R={sql:this.buildRelationCountSortSubquery(l.table,$),direction:$.direction};_.push(R);continue}if($.function==="max"||$.function==="min"){let R={sql:this.buildRelationAggregateSortSubquery(l.table,$),direction:$.direction};_.push(R);continue}if($.joinId===null){if($.field.includes(".")&&!e.plan){let N=$.field.split(".")[0];if(this.metadata?.tables?.get(l.table)?.relations?.some(Q=>Q.propertyName===N))continue}let R={field:$.field.includes(".")?$.field:`${l.table}.${$.field}`,direction:$.direction};b.push(R),_.push(R)}else{let R=e.plan?.joins.find(N=>N.id===$.joinId);if(R&&(R.relationType==="many-to-one"||R.relationType==="one-to-one")){let N=ui(R.relationMeta,$.field,l.table,this.metadata,this.dbType);if(N){let J={sql:N,direction:$.direction};_.push(J)}}}}let C=[];if(l.fields&&l.fields.length>0||u||a){let $=gr(this.metadata),R=l.fields&&l.fields.length>0?l.fields:["*"],N=await ci(this.knex,l.table,R,$,this.dbType,this.maxQueryDepth,e.deep);N.select.length>0&&(l.select=[...l.select||[],...N.select]),C=N.batchFetchDescriptors||[]}l.where&&(l.where=l.where.map($=>$.field.includes(".")?$:{...$,field:`${l.table}.${$.field}`})),l.sort=b;let T=this.knex(l.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map($=>$.trim()).filter(Boolean),F=k.includes("filterCount")||k.includes("*"),w=k.includes("totalCount")||k.includes("*");if(l.select){let $=l.select.map(R=>typeof R=="string"&&R.trim().startsWith("(")?this.knex.raw(R):typeof R=="string"&&/ as /i.test(R)?this.knex.raw(R):R);T=T.select($)}if(F&&T.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),w){let $=x(l.table,this.dbType);T.select(this.knex.raw(`(SELECT COUNT(*) FROM ${$}) as __total_count__`))}let v=["table_definition","column_definition","relation_definition","method_definition"].includes(l.table);if(f&&(me(f)||Object.keys(f).length>0)){let $=this.metadata?.tables?.get(l.table);(!v&&$&&$.relations&&$.relations.length>0?G(f,$).hasRelations:!1)?await Dt(this.knex,T,f,l.table,$,this.dbType,N=>this.metadata?.tables?.get(N)):e.plan?.filterTree?ue(T,e.plan.filterTree,{dbType:this.dbType,rootTable:l.table}):(this.logger.debug(`buildWhereClause fallback for table=${l.table}`),T=ce(T,f,l.table,this.dbType,$))}else l.where&&l.where.length>0&&(T=ot(T,l.where,l.table,this.metadata,this.dbType));for(let $ of _)if($.field){let R=$.field.includes(".")?$.field:`${l.table}.${$.field}`;T=T.orderBy(R,$.direction)}else $.sql&&(T=T.orderByRaw(`${$.sql} ${$.direction.toUpperCase()}`));l.groupBy&&(T=T.groupBy(l.groupBy)),l.offset&&(T=T.offset(l.offset)),l.limit!==void 0&&l.limit!==null&&l.limit>0&&(T=T.limit(l.limit));let B=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:l.table,sql:T.toSQL().toNative()});let S;if(e.debugMode&&(S=T.toSQL().toNative().sql),e.debugMode&&i){let $=T.toSQL().toNative();i.setSql($.sql);try{let R=$.sql.replace(/\$\d+/g,"?"),N=await this.knex.raw(`EXPLAIN ${R}`,$.bindings);i.setExplain(this.dbType==="postgres"?N.rows:N[0])}catch(R){i.setExplain({error:String(R)})}}let M,A=performance.now();M=await T,i&&i.dur("db_execute",A,{table:e.tableName});let D=await this.resolveEmptyPageMeta(T,l.table,k,M.length),j=D.filterCount??0;if(B=D.totalCount??0,F&&M.length>0&&(j=Number(M[0].__filter_count__||0),M.forEach($=>{delete $.__filter_count__})),w&&M.length>0&&M[0].__total_count__!==void 0&&(B=Number(M[0].__total_count__||0),M.forEach($=>{delete $.__total_count__})),C&&C.length>0&&M.length>0){let $=gr(this.metadata);if($){let{executeBatchFetches:R}=await Promise.resolve().then(()=>(yr(),fi));await R(this.knex,M,C,$,this.maxQueryDepth??3,0,l.table,this.dbType,this.metadata,i)}}if(this.knexService){let $=performance.now();M=await this.knexService.parseResult(M,l.table),i&&i.dur("db_parseResult",$,{table:e.tableName})}else{let $=(R,N)=>{if(!R||!this.metadata)return R;let J=this.metadata.tables?.get(N);if(!J)return R;if(Array.isArray(R))return R.map(Q=>$(Q,N));if(typeof R!="object"||Buffer.isBuffer(R))return R;let E={...R};for(let Q of J.columns)if(Q.type==="simple-json"&&E[Q.name]&&typeof E[Q.name]=="string")try{E[Q.name]=JSON.parse(E[Q.name])}catch{}for(let[Q,X]of Object.entries(E))if(X&&typeof X=="object"&&!Array.isArray(X)&&!Buffer.isBuffer(X)){let En=X;if(En.id!==void 0||En.createdAt!==void 0){let ct=J.relations?.find(ut=>ut.propertyName===Q);ct&&(E[Q]=$(X,ct.targetTableName))}}else if(Array.isArray(X)&&X.length>0&&typeof X[0]=="object"&&X[0].id!==void 0){let ct=J.relations?.find(ut=>ut.propertyName===Q);ct&&(E[Q]=X.map(ut=>$(ut,ct.targetTableName)))}return E};M=$(M,l.table)}return i&&(i.setQueryPath("full"),i.dur("sql_executor",t,{table:e.tableName})),{data:M,...k.length>0&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:B}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:j}:{}}},...S!==void 0&&{sql:S}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=Y(s)?.name||"id",u=x(e,this.dbType),c=x(a,this.dbType);if(!n||!o)throw new I(`Sort relation '${i}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let d=n.foreignKeyColumn||n.mappedBy;if(!d)throw new I(`Sort function '_count(${i})' cannot resolve relation key on '${e}'.`);let l=x(o,this.dbType),f=x(d,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}if(n.type==="many-to-many"){let d=this.resolveManyToManyContract(n,i,e),l=x(d.tableName,this.dbType),f=x(d.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}throw new I(`Sort function '_count(${i})' is only supported for list relations on '${e}'.`)}buildRelationAggregateSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=t.aggregateField,s=n?.targetTableName||n?.targetTable,a=this.metadata?.tables?.get(e),u=this.metadata?.tables?.get(s),c=Y(a)?.name||"id",d=Y(u)?.name||"id",l=x(e,this.dbType),f=x(c,this.dbType),p=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!p||!n||!s||!o)throw new I(`Sort function '${t.field}' is not supported on '${e}'.`);let m=x(s,this.dbType),g=x(o,this.dbType);if(n.type==="one-to-many"){let h=n.foreignKeyColumn||n.mappedBy;if(!h)throw new I(`Sort function '_${t.function}(${i}.${o})' cannot resolve relation key on '${e}'.`);let y=x(h,this.dbType);return`(SELECT ${p}(${m}.${g}) FROM ${m} WHERE ${m}.${y} = ${l}.${f})`}if(n.type==="many-to-many"){let h=this.resolveManyToManyContract(n,i,e),y=x(h.tableName,this.dbType),b=x(h.sourceColumn,this.dbType),_=x(h.targetColumn,this.dbType),C=x(d,this.dbType);return`(SELECT ${p}(${m}.${g}) FROM ${y} JOIN ${m} ON ${m}.${C} = ${y}.${_} WHERE ${y}.${b} = ${l}.${f})`}throw new I(`Sort function '_${t.function}(${i}.${o})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,n){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new I(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async resolveEmptyPageMeta(e,t,n,i){return i>0||n.length===0?{}:di(this.knex,e,t,n,!1)}async executeSimple(e,t){let n=e.tableName,i=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],o=this.knex(n).select(i);t.filterTree&&ue(o,t.filterTree,{dbType:this.dbType,rootTable:n});for(let h of t.sortItems){let y=h.field.includes(".")?h.field:`${n}.${h.field}`;o=o.orderBy(y,h.direction)}t.limit!==void 0&&t.limit!==null&&t.limit>0&&(o=o.limit(t.limit)),t.offset!==void 0&&(o=o.offset(t.offset));let s=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(h=>h.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),u=s.includes("totalCount")||s.includes("*");if(a&&o.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),u){let h=x(n,this.dbType);o.select(this.knex.raw(`(SELECT COUNT(*) FROM ${h}) as __total_count__`))}let c=e.debugTrace,d;if(e.debugMode){let h=o.toSQL().toNative();if(d=h.sql,c){c.setSql(h.sql);try{let y=h.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${y}`,h.bindings);c.setExplain(this.dbType==="postgres"?b.rows:b[0])}catch(y){c.setExplain({error:String(y)})}}}let l=performance.now(),f;f=await o,c&&c.dur("db_execute",l,{table:n}),this.knexService&&(f=await this.knexService.parseResult(f,n));let p=await this.resolveEmptyPageMeta(o,n,s,f.length),m=p.filterCount??0,g=p.totalCount??0;return a&&f.length>0&&(m=Number(f[0].__filter_count__||0),f.forEach(h=>delete h.__filter_count__)),u&&f.length>0&&(g=Number(f[0].__total_count__||0),f.forEach(h=>delete h.__total_count__)),{data:f,...s.length>0&&{meta:{...u?{totalCount:g}:{},...a?{filterCount:m}:{}}},...d!==void 0&&{sql:d}}}async aggregate(e){let t=nt(e.aggregate,e.tableName,e.metadata),n=this.knex(e.tableName),i=x(e.tableName,this.dbType),o=[],s=[];for(let l of t.dimensions){let f=`${i}.${x(l.field,this.dbType)}`,p=l.bucket?this.buildSqlBucketExpression(f,l.bucket,l.timezone,l.column.type):f;s.push(this.knex.raw(`${p} as ${x(l.outputKey,this.dbType)}`)),o.push(p)}for(let l of t.measures){let f=`${i}.${x(l.field,this.dbType)}`,p=l.operation==="count"?`COUNT(${f})`:l.operation==="countDistinct"?`COUNT(DISTINCT ${f})`:`${l.operation.toUpperCase()}(${f})`;s.push(this.knex.raw(`${p} as ${x(l.outputKey,this.dbType)}`))}let u=new te().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:this.dbType});u.hasRelationFilters?await Dt(this.knex,n,t.filter,e.tableName,e.metadata?.tables?.get(e.tableName),this.dbType,l=>e.metadata?.tables?.get(l)):u.filterTree&&ue(n,u.filterTree,{dbType:this.dbType,rootTable:e.tableName}),n.select(s),o.length>0&&n.groupByRaw(o.join(", "));for(let l of t.sort)n.orderByRaw(`${x(l.field,this.dbType)} ${l.direction.toUpperCase()}`);return t.limit!==void 0&&n.limit(t.limit).offset((t.page-1)*t.limit),{data:(await n).map(l=>{let f={...l};for(let p of t.measures){let m=f[p.outputKey];m!=null&&typeof m=="string"&&/^-?\d+(\.\d+)?$/.test(m)&&(f[p.outputKey]=Number(m))}return f})}}buildSqlBucketExpression(e,t,n,i){let o=qt(n);if(this.dbType==="postgres"){let s=`(${e} AT TIME ZONE ${o})`;return`DATE_TRUNC(${qt(t)}, ${s})`}if(this.dbType==="mysql"){let s=`CONVERT_TZ(${e}, '+00:00', ${o})`;return t==="year"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-01-01'), '%Y-%m-%d')`:t==="month"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-01'), '%Y-%m-%d')`:t==="week"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%u-1'), '%Y-%u-%d')`:t==="day"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-%d'), '%Y-%m-%d')`:`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-%d %H:00:00'), '%Y-%m-%d %H:%i:%s')`}throw new I(`Aggregate time bucket is not supported on ${this.dbType}`)}};var vn=require("mongodb"),lt=class{constructor(e){this.debugLog=[];this.batchInserts={items:[],flushing:!1};this.knexService=e.knexService,this.mongoService=e.mongoService,this.databaseConfigService=e.databaseConfigService,this.runtimeMetricsCollectorService=e.runtimeMetricsCollectorService,this.lazyRef=e.lazyRef,this.dbType=this.databaseConfigService.getDbType(),this.batchInsertMaxSize=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_SIZE",100),this.batchInsertMaxWaitMs=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_WAIT_MS",100),this.batchInsertConcurrency=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_CONCURRENCY",5),this.batchInsertTraceFile=process.env.QUERY_BUILDER_BATCH_TRACE_FILE||process.env.DYNAMIC_CREATE_BATCH_TRACE_FILE,this.batchInsertTraceFile&&(0,In.mkdirSync)((0,pi.dirname)(this.batchInsertTraceFile),{recursive:!0})}async runWithPolicy(e,t){return this.knexService?this.knexService.runWithPolicy(e,t):this.mongoService?this.mongoService.runWithPolicy(e,t):t()}async runWithFieldPermissionCheck(e,t){return this.knexService?this.knexService.runWithFieldPermissionCheck(e,t):this.mongoService?this.mongoService.runWithFieldPermissionCheck(e,t):t()}async runWithTelemetryContext(e,t){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.runWithQueryContext(e,t):await t()}getDbType(){return this.dbType}safeObjectId(e){if(!vn.ObjectId)return e;if(typeof e=="string")try{return new vn.ObjectId(e)}catch{return e}return e}async getMetadataForQuery(){let e={tables:new Map,tablesList:[]},t=this.lazyRef.metadataCacheService;return t?t.isLoaded?.()?await t.getMetadata?.()??e:t.getDirectMetadata?.()??e:e}async buildMongoFilter(e,t){let n=await this.getMetadataForQuery(),i=Je(n,e,t,this.dbType);return i._id!==void 0&&(i._id=this.safeObjectId(i._id)),i}async applyWhereToKnex(e,t,n){let i=await this.getMetadataForQuery();return{query:ot(e,t,n??"",i,this.dbType)}}async runMongoMutationInSaga(e){return!this.mongoService?.runInSaga||this.mongoService.isInSaga?.()?e():(await this.mongoService.runInSaga(e)).data}async insertWithOptions(e){if(e.batch)return await this.insertManyBatch(e.table,e.data);if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{if(Array.isArray(e.data)){let t=[];for(let n of e.data){let i=await this.mongoService.insertOne(e.table,n);t.push(Z(i))}return t}return this.mongoService.insertOne(e.table,e.data)});if(Array.isArray(e.data)){let t=[];for(let n of e.data){let i=await this.knexService.insertWithCascade(e.table,n);t.push(i)}return t}else return await this.knexService.insertWithCascade(e.table,e.data)}async select(e){let t=performance.now(),n=await this.getMetadataForQuery(),i=performance.now(),s=new te().plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:n,dbType:this.dbType}),a=e.debugTrace;if(a&&(a.dur("qb_planner",i,{table:e.tableName}),a.setPlan(this.sanitizePlan(s))),this.dbType==="mongodb"){let l=await new Pe(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}let c=await new Be(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:n,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),c}sanitizePlan(e){return{rawFields:e.rawFields,hasRelationFilters:e.hasRelationFilters,hasRelationSort:e.hasRelationSort,joins:e.joins?.length??0,sortItems:e.sortItems,limit:e.limit,offset:e.offset,page:e.page,isSimpleQuery:e.joins?.length===0&&!e.hasRelationFilters&&!e.hasRelationSort}}async updateWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),s=this.mongoService.collection(e.table),a=this.mongoService.ioSignalPublic?.()??{},u=await s.find(o,a).toArray(),c=[];for(let d of u){let l=await this.mongoService.updateOne(e.table,d._id,e.data);c.push(l)}return c});let t=this.knexService.getKnex(),n=t(e.table);e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n;for(let o of i)await this.knexService.updateWithCascade(e.table,o.id,e.data);if(e.returning){let o=t(e.table);return e.where.length>0&&await this.applyWhereToKnex(o,e.where,e.table),await o.select(e.returning)}return{affected:i.length}}async deleteWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let i=await this.buildMongoFilter(e.where,e.table),o=this.mongoService.collection(e.table),s=this.mongoService.ioSignalPublic?.()??{},a=await o.find(i,s).toArray(),u=0;for(let c of a)await this.mongoService.deleteOne(e.table,c._id)&&u++;return u});let n=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table)),await n.delete()}async count(e){if(this.dbType==="mongodb"){let o=e.where?await this.buildMongoFilter(e.where,e.table):{};return this.mongoService.count(e.table,o)}let n=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n.count("* as count").first();return Number(i?.count||0)}whereToFilter(e){let t={},n=this.databaseConfigService.isMongoDb();for(let[i,o]of Object.entries(e))i==="id"||i==="_id"?n?t._id=this.normalizeWhereFilterValue("_id",o):t.id=this.normalizeWhereFilterValue("id",o):t[i]=this.normalizeWhereFilterValue(i,o);return t}normalizeWhereFilterValue(e,t){return this.isFilterOperatorObject(t)?this.databaseConfigService.isMongoDb()&&e==="_id"?this.normalizeMongoIdOperatorValue(t):t:{_eq:this.databaseConfigService.isMongoDb()&&e==="_id"?this.safeObjectId(t):t}}isFilterOperatorObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof vn.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[n,i]of Object.entries(e))t[n]=Array.isArray(i)?i.map(o=>this.safeObjectId(o)):this.safeObjectId(i);return t}filterToWhere(e){let t=[];for(let[n,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let o=Object.entries(i)[0];if(o){let[s,a]=o,u=this.mapFilterOperatorToSql(s);t.push({field:n,operator:u,value:a})}}return t}mapFilterOperatorToSql(e){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"like",_starts_with:"like",_ends_with:"like",_is_null:"is null",_is_not_null:"is not null"}[e]||"="}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,maxQueryDepth:e.maxQueryDepth})})}async aggregate(e){return this.trackQueryMetric("aggregate",e.table,async()=>{let t=await this.getMetadataForQuery();return this.dbType==="mongodb"?new Pe(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).aggregate({tableName:e.table,aggregate:e.aggregate,metadata:t,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,dbType:this.dbType}):new Be(this.knexService.getKnex(),this.dbType,this.knexService).aggregate({tableName:e.table,aggregate:e.aggregate,metadata:t,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t,n){return n?.batch?await this.insertManyBatch(e,t):this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let a=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return Z(a)}let i=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),s=i||t.id;return await o(e).where("id",s).first()})}async createMany(e,t){return t.length===0?[]:this.trackQueryMetric("insert_many",e,async()=>this.dbType==="mongodb"?(await this.runMongoMutationInSaga(async()=>typeof this.mongoService.insertManyWithCascade=="function"?this.mongoService.insertManyWithCascade(e,t):Promise.all(t.map(i=>this.mongoService.insertOne(e,i))))).map(i=>Z(i)):this.knexService.insertManyWithCascade(e,t))}async insertMany(e,t){return this.createMany(e,t)}async flushBatchInserts(){for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)await this.flushBatchInsertBuffer()}async insertManyBatch(e,t){let n=Array.isArray(t)?t:[t];for(let i of n)this.batchInserts.items.push({table:e,data:i});return this.traceBatchInsert("enqueue",{tableName:e,count:n.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i)),{accepted:!0,batch:!0,count:n.length}}async flushBatchInsertBuffer(){if(this.batchInserts.flushing){await this.batchInserts.flushPromise;return}let e=this.batchInserts.items.splice(0,this.batchInserts.items.length);if(this.batchInserts.timer&&(clearTimeout(this.batchInserts.timer),this.batchInserts.timer=void 0),e.length===0)return;this.batchInserts.flushing=!0;let t=this.executeBatchInsertFlush(e);this.batchInserts.flushPromise=t,await t}async executeBatchInsertFlush(e){let t=Date.now();try{let n=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...n.entries()].map(([i,o])=>({tableName:i,count:o.length}))}),await this.runLimited([...n.entries()],([i,o])=>this.flushBatchInsertTable(i,o)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}finally{this.batchInserts.flushing=!1,this.batchInserts.flushPromise=void 0,this.batchInserts.items.length>0&&(this.batchInserts.timer&&clearTimeout(this.batchInserts.timer),this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(n=>this.logBatchInsertError("QueryBuilder batch insert flush failed",n))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let n=Date.now();await this.runBatchInsertWithIsolation(e,t),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-n})}async runBatchInsertWithIsolation(e,t){if(t.length!==0)try{await(async()=>{if(this.dbType==="mongodb"){await this.runMongoMutationInSaga(async()=>{if(typeof this.mongoService?.insertManyWithCascade=="function"){await this.mongoService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.mongoService.insertOne(e,i.data)))});return}if(typeof this.knexService?.insertManyWithCascade=="function"){await this.knexService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.knexService.insertWithCascade(e,i.data)))})()}catch(n){if(t.length===1){this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,n);return}let i=Math.ceil(t.length/2);await Promise.all([this.runBatchInsertWithIsolation(e,t.slice(0,i)),this.runBatchInsertWithIsolation(e,t.slice(i))])}}groupBatchInsertsByTable(e){let t=new Map;for(let n of e){let i=t.get(n.table);i?i.push(n):t.set(n.table,[n])}return t}async runLimited(e,t){let n=0,i=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;n<e.length;){let o=e[n++];await t(o)}});await Promise.all(i)}readPositiveEnv(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.trunc(n):t}traceBatchInsert(e,t){this.batchInsertTraceFile&&(0,In.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
53
53
  `)}logBatchInsertError(e,t){let n=t?.message||String(t);this.traceBatchInsert("error",{message:e,error:n,code:t?.code,detail:t?.detail}),console.error(`${e}: ${n}`)}async update(e,t,n){return this.trackQueryMetric("update",e,async()=>{if(t&&typeof t=="object"&&"where"in t)return await this.updateWithOptions({table:e,where:t.where,data:n});if(this.dbType==="mongodb"){let o=await this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n));return Z(o)}return await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first()})}async updateMany(e,t,n,i=this.getPkField()){return t.length===0?0:this.trackQueryMetric("update_many",e,async()=>{if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let a=this.mongoService.collection(e),u=this.mongoService.ioSignalPublic?.()??{};return(await a.updateMany({[i]:{$in:t}},{$set:n},u)).modifiedCount});let s=await this.knexService.getKnex()(e).whereIn(i,t).update(n);return typeof s=="number"?s:0})}async delete(e,t){return this.trackQueryMetric("delete",e,async()=>t&&typeof t=="object"&&"where"in t?await this.deleteWithOptions({table:e,where:t.where})>0:this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t)):await this.knexService.getKnex()(e).where("id",t).delete()>0)}async deleteMany(e,t,n=this.getPkField()){return t.length===0?0:this.trackQueryMetric("delete_many",e,async()=>{if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let s=this.mongoService.collection(e),a=this.mongoService.ioSignalPublic?.()??{},u=await s.find({[n]:{$in:t}},a).toArray(),c=0;for(let d of u)await this.mongoService.deleteOne(e,d._id)&&c++;return c});let o=await this.knexService.getKnex()(e).whereIn(n,t).delete();return typeof o=="number"?o:0})}async countRecords(e,t){if(this.dbType==="mongodb")return this.mongoService.count(e,t||{});let i=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.filterToWhere(t);({query:i}=await this.applyWhereToKnex(i,s,e))}let o=await i.count("* as count").first();return Number(o?.count||0)}async transaction(e){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>e(this.mongoService)):this.knexService.transaction(e)}async findById(e,t){if(this.dbType==="mongodb"){let i=this.safeObjectId(t);return this.mongoService.findOne(e,{_id:i})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[o,s]of Object.entries(t))o==="id"||o==="_id"?i._id=this.safeObjectId(s):i[o]=s;return this.mongoService.findOne(e,i)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[u,c]of Object.entries(t))u==="id"||u==="_id"?i._id=this.safeObjectId(c):i[u]=c;let o=this.mongoService.collection(e),s=this.mongoService.ioSignalPublic?.()??{};return await o.find(i,s).toArray()}return await this.knexService.getKnex()(e).where(t)}async insertAndGet(e,t){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));let n=await this.knexService.insertWithCascade(e,t),i=this.knexService.getKnex(),o=n||t.id;return await i(e).where("id",o).first()}async updateById(e,t,n){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n)):(await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first())}async deleteById(e,t){return this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t))?1:0:this.knexService.getKnex()(e).where("id",t).delete()}async raw(e,t){let n=this.dbType==="mongodb"?"mongodb":"sql";return this.trackQueryMetric("raw",n,async()=>{if(this.dbType==="mongodb"){let o=this.mongoService.getDb();if(typeof e=="string"){if(e.toLowerCase().includes("select 1"))return await o.command({ping:1});throw new Error("String queries not supported for MongoDB. Use db.command() object instead.")}return await o.command(e)}return await this.knexService.getKnex().raw(e,t)})}async trackQueryMetric(e,t,n){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.trackQuery({op:e,table:t},n):await n()}getConnection(){return this.dbType==="mongodb"?this.mongoService.getDb():this.knexService.getKnex()}getKnex(){if(this.dbType==="mongodb")throw new Error("getKnex() is not available for MongoDB. Use getConnection() or unified methods.");return this.knexService.getKnex()}getMongoDb(){if(this.dbType!=="mongodb")throw new Error("getMongoDb() is not available for SQL. Use getConnection() or unified methods.");return this.mongoService.getDb()}getDatabaseType(){return this.dbType}isMongoDb(){return this.dbType==="mongodb"}isSql(){return["mysql","postgres","mariadb","sqlite"].includes(this.dbType)}getPkField(){return this.isMongoDb()?"_id":"id"}getRecordId(e){return this.isMongoDb()?e._id:e.id}};yr();hr();pr();le();Ut();Ye();_n();fe();ze();var gi=new Set(["fields","filter","sort","limit","page","deep"]),Mn=3;function br(r,e,t,n=0,i=3){if(!e||typeof e!="object")return;if(n>=i)throw new I(`deep option exceeds maximum query depth of ${i}`);let o=t?.tables?.get(r),s=new Map((o?.relations??[]).map(a=>[a.propertyName,a]));for(let[a,u]of Object.entries(e)){let c=s.get(a);if(!c)throw new I(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let f of Object.keys(u))if(!gi.has(f))throw new I(`Unknown deep option key '${f}' for relation '${a}'. Allowed: ${[...gi].join(", ")}`);let d=c.type;if(u.limit!==void 0&&(d==="many-to-one"||d==="one-to-one"))throw new I(`'limit' not supported on many-to-one/one-to-one relations (relation '${a}' on '${r}')`);if(u.page!==void 0&&u.limit===void 0)throw new I(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let l=c.targetTableName||c.targetTable;if(l){if(u.filter&&(ie(u.filter,l,t),Ae(u.filter,l,t),Nn(u.filter,0,a,r)),u.sort){Sn(u.sort,l,t);let f=Array.isArray(u.sort)?u.sort:String(u.sort).split(",").map(p=>p.trim()).filter(Boolean);for(let p of f){let m=p.startsWith("-")?p.slice(1):p;Ho(m,l,t,a,r)}}u.deep&&br(l,u.deep,t,n+1,i)}}}function Ho(r,e,t,n,i){if(r.includes("."))throw new I(`Sort field '${r}' is not supported for relation '${n}' on '${i}'. Sort only by local fields defined on '${e}'.`);let o=t?.tables?.get(e);if(!o)throw new I(`Sort field '${r}' references unknown table '${e}' (relation '${n}' on '${i}')`);let s=o.columns?.some(u=>u.name===r),a=r==="id"&&o.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new I(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${i}')`)}var Go=new Set(["_and","_or","_not"]);function Nn(r,e,t,n){if(!(!r||typeof r!="object"))for(let[i,o]of Object.entries(r)){if(Go.has(i)){if(Array.isArray(o))for(let c of o)Nn(c,e,t,n);else o&&typeof o=="object"&&Nn(o,e,t,n);continue}if(i.startsWith("_")||!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).some(c=>!c.startsWith("_")))continue;let a=e+1;if(a>Mn)throw new I(`Filter path exceeds max dotted hops of ${Mn} at '${i}' (relation '${t}' on '${n}')`);let u={};for(let c of Object.keys(o))c.startsWith("_")||(u[c]=o[c]);Nn(u,a,t,n)}}function hi(r,e,t,n){return!r||typeof r!="object"?r:zt(r,e,t,n)}function zt(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let o=r.map(s=>zt(s,e,t,n)).filter(s=>s!=null);return o.length>0?o:null}let i={};for(let[o,s]of Object.entries(r)){if(o==="_and"||o==="_or"){let l=(Array.isArray(s)?s:[s]).map(f=>zt(f,e,t,n)).filter(f=>f!=null&&Object.keys(f).length>0);l.length>0&&(i[o]=l);continue}if(o==="_not"){let d=zt(s,e,t,n);d!=null&&Object.keys(d).length>0&&(i[o]=d);continue}let a=t?.tables?.get(e),u=a?.relations?.find(d=>d.propertyName===o);if(u){if(!n(e,o,"relation"))continue;let d=u.targetTableName||u.targetTable;if(!d)continue;let l=zt(s,d,t,n);l!=null&&Object.keys(l).length>0&&(i[o]=l);continue}if(a?.columns?.find(d=>d.name===o)){if(!n(e,o,"column"))continue;i[o]=s;continue}i[o]=s}return i}function mi(r,e,t,n){if(!r)return r;let i=Array.isArray(r)?r:r.split(",").map(s=>s.trim()).filter(Boolean),o=[];for(let s of i){let c=(s.startsWith("-")?s.slice(1):s).split("."),d=!0,l=e;for(let f=0;f<c.length;f++){let p=c[f],m=f===c.length-1,g=t?.tables?.get(l);if(!g){d=!1;break}if(m)g.columns?.find(y=>y.name===p)?n(l,p,"column")||(d=!1):g.relations?.find(b=>b.propertyName===p)&&(n(l,p,"relation")||(d=!1));else{let h=g.relations?.find(y=>y.propertyName===p);if(!h){d=!1;break}if(!n(l,p,"relation")){d=!1;break}l=h.targetTableName||h.targetTable||l}}d&&o.push(s)}if(o.length!==0)return Array.isArray(r)?o:o.join(",")}Et();ze();Ot();un();qe();fe();function Yo(r){let e=new lt({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,i=()=>(t||(t=new Ke({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),o=()=>(n||(n=new Le({isolatedExecutorService:i()})),n);return{queryBuilderService:e,get isolatedExecutorService(){return i()},get executorEngineService(){return o()},async onDestroy(){await t?.onDestroy?.()}}}0&&(module.exports={ALL_SUPPORTED_OPERATORS,AuthenticationException,AuthorizationException,BadRequestException,BatchExecutionBudget,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,DEEP_TO_MANY_DEFAULT_LIMIT,DEFAULT_BATCH_FETCH_IO_CONCURRENCY,DEFAULT_TIMEOUT_MS,DOTTED_PATH_MAX_HOPS,DatabaseException,DuplicateResourceException,ErrorHandler,ExecutorEngineService,ExternalServiceException,FIELD_OPERATORS,FileNotFoundException,FileSizeExceededException,FileUploadException,HttpException,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH,InvalidTokenException,IsolatedExecutorService,JoinRegistry,LOGICAL_OPERATORS,MongoBatchAdapter,MongoQueryExecutor,PER_PARENT_CONCURRENCY,QueryBuilderService,QueryPlanner,ResourceNotFoundException,SchemaException,ScriptContractService,ScriptExecutionException,ScriptTimeoutException,ServiceUnavailableException,SqlBatchAdapter,SqlQueryExecutor,TokenExpiredException,ValidationException,WHERE_IN_CHUNK_SIZE,WorkerPool,appendIsolatedExecutorRuntimeLog,applyOperatorToMatch,applyRelationFilters,applyWhereToKnex,assertFieldOperatorValueIsClean,buildMongoCharFoldMapJson,buildMongoFoldTextSearchJs,buildRelationSubquery,buildSqlWherePartsFromFieldAst,buildWhereClause,camelToSnake,chunkedFetch,compileScriptSource,computeEngineTuning,createEnfyraKernel,dslOpToCompareOp,encodeMainThreadToIsolate,escapeSqlValue,executeBatchFetches,executeMongoBatchFetches,expandFieldsToJoinsAndSelect,getEffectiveCpuCount,getEffectiveMemoryBytes,getEngineTuning,getExecutableScript,getForeignKeyColumnName,getIoAbortSignal,getJunctionColumnNames,getJunctionTableName,getPrimaryKeyColumn,getScriptLegacyField,getShortFkConstraintName,getShortFkName,getShortIndexName,getShortPkName,hasLogicalOperators,isExecutableJavaScript,isScriptTable,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,perParentRun,quoteIdentifier,quoteQualifiedIdentifier,resolveExecutableScript,rewriteFilterDenyingFields,rewriteSortDroppingDenied,runWithIoAbortSignal,scriptContractService,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,validateDeepOptions,validateFilterShape,whereToMongoFilter});
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "@enfyra/kernel",
3
- "version": "1.1.56",
3
+ "version": "1.1.57",
4
4
  "source": "bundled-compiled-kernel"
5
5
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enfyra/kernel",
3
- "version": "1.1.56",
3
+ "version": "1.1.57",
4
4
  "description": "Closed-distribution Enfyra kernel runtime",
5
5
  "license": "Elastic-2.0",
6
6
  "packageManager": "yarn@4.17.0",
@@ -31,6 +31,7 @@
31
31
  "test:executor-error-metadata": "yarn build && node scripts/test-executor-error-metadata.mjs",
32
32
  "test:executor-lanes": "yarn build && node scripts/test-executor-lane-tuning.mjs",
33
33
  "test:executor-multiplexing": "yarn build && node scripts/test-executor-multiplexing.mjs",
34
+ "test:query-builder-many-contract": "yarn build && node scripts/test-query-builder-many-contract.mjs",
34
35
  "bench:executor-lanes": "yarn build && node scripts/benchmark-executor-lanes.mjs",
35
36
  "test:sql-identifiers": "yarn build && node scripts/test-sql-identifier-quoting.mjs",
36
37
  "test:relation-aggregate-sort": "node scripts/test-relation-aggregate-sort.mjs",