@enfyra/kernel 1.1.48 → 1.1.49

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
@@ -27,6 +27,7 @@ export function createEnfyraKernel(
27
27
  export class QueryBuilderService {
28
28
  constructor(...args: any[]);
29
29
  find(...args: any[]): Promise<any>;
30
+ aggregate(...args: any[]): Promise<any>;
30
31
  findOne(...args: any[]): Promise<any>;
31
32
  insertWithOptions(...args: any[]): Promise<any>;
32
33
  updateWithOptions(...args: any[]): Promise<any>;
@@ -300,7 +301,6 @@ export type PoolEntry = any;
300
301
 
301
302
  export const applyOperatorToMatch: any;
302
303
  export const applyWhereToKnex: any;
303
- export const buildAggregateFilter: any;
304
304
  export const buildMongoCharFoldMapJson: any;
305
305
  export const buildMongoFoldTextSearchJs: any;
306
306
  export const buildWhereClause: any;
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var bi=Object.create;var Gt=Object.defineProperty;var _i=Object.getOwnPropertyDescriptor;var wi=Object.getOwnPropertyNames;var $i=Object.getPrototypeOf,Ti=Object.prototype.hasOwnProperty;var Q=(r,e)=>()=>(r&&(e=r(r=0)),e);var On=(r,e)=>{for(var t in e)Gt(r,t,{get:e[t],enumerable:!0})},wr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of wi(e))!Ti.call(r,o)&&o!==t&&Gt(r,o,{get:()=>e[o],enumerable:!(n=_i(e,o))||n.enumerable});return r};var fe=(r,e,t)=>(t=r!=null?bi($i(r)):{},wr(e||!r||!r.__esModule?Gt(t,"default",{value:r,enumerable:!0}):t,r)),Si=r=>wr(Gt({},"__esModule",{value:!0}),r);function Ir(r){return Dn.createHash("md5").update(r).digest("hex").substring(0,8)}function Nr(r){return r.length<=vr-3?`${r}_pk`:`j_${Ir(r)}_pk`}function Mr(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=vr?n:`j_${Ir(r)}_${t}_fk`}function Mt(r,e,t){let n=`${r}:${e}:${t}`;return`j_${Dn.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function G(r){return`${r}Id`}function Et(r,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function Er(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function Ar(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function Or(r,e,t){return`${r}_${e}_${t}_fk`}function Pr(r,e,t){return`${r}_${e}_${t}_idx`}var Dn,vr,Je=Q(()=>{"use strict";Dn=fe(require("crypto")),vr=63});function un(r){return ro[r]??null}var oe,Qn,Ot,ro,Pt=Q(()=>{"use strict";oe=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),Qn=new Set(["_and","_or","_not"]),Ot=[...Array.from(Qn),...Array.from(oe)],ro={_eq:"eq",_neq:"neq",_gt:"gt",_gte:"gte",_lt:"lt",_lte:"lte",_in:"in",_not_in:"not_in",_nin:"not_in",_contains:"contains",_starts_with:"starts_with",_ends_with:"ends_with",_between:"between"}});var x,ge=Q(()=>{"use strict";x=class extends Error{constructor(t="Bad Request",n){let o=Array.isArray(t),i=o?t.join("; ")||"Bad Request":typeof t=="string"?t:JSON.stringify(t);super(i);this.statusCode=400;this.errorCode="BAD_REQUEST";this.name="BadRequestException",this.details=n,o&&(this.messages=t)}}});function Dr(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var Wr=Q(()=>{"use strict"});function Oe(r,e,t){throw new x({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${Ot.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:Ot})}function dn(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=Dr();for(let o of Object.keys(e))if(o.startsWith("_")&&!oe.has(o)){if(n&&o==="_id")continue;Oe(o,r,t)}}function J(r,e,t){if(!r||typeof r!="object")return;let n=t?.tables?.get(e),o=new Set((n?.columns??[]).map(s=>s.name)),i=new Map((n?.relations??[]).map(s=>[s.propertyName,s]));for(let[s,a]of Object.entries(r)){if(io.has(s)){if(Array.isArray(a))for(let c of a)J(c,e,t);else a&&typeof a=="object"&&J(a,e,t);continue}let u=i.get(s);if(u){if(a&&typeof a=="object"&&!Array.isArray(a)){dn(s,a,e);let c=u.targetTableName||u.targetTable;if(c){let d=Object.keys(a).filter(l=>!l.startsWith("_"));if(d.length>0){let l={};for(let f of d)l[f]=a[f];J(l,c,t)}}}continue}s.startsWith("_")&&!o.has(s)&&s!=="_id"&&Oe(s,s,e),a&&typeof a=="object"&&!Array.isArray(a)&&dn(s,a,e)}}var io,He=Q(()=>{"use strict";ge();Pt();Wr();io=new Set(["_and","_or","_not"])});function he(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:fn(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function fn(r,e){if(!r||typeof r!="object")return{node:null,hasRelationFilters:!1};let t=[],n=!1;for(let[o,i]of Object.entries(r)){let s=oo(o,i,e);s.hasRelationFilters&&(n=!0),s.node&&t.push(s.node)}return t.length===0?{node:null,hasRelationFilters:n}:t.length===1?{node:t[0],hasRelationFilters:n}:{node:{kind:"and",children:t},hasRelationFilters:n}}function oo(r,e,t){if(r==="_and")return Kr("and",e,t);if(r==="_or")return Kr("or",e,t);if(r==="_not"){let c=fn(e,t);return c.node?{node:{kind:"not",child:c.node},hasRelationFilters:c.hasRelationFilters}:{node:null,hasRelationFilters:c.hasRelationFilters}}let n=t.metadata?.tables?.get(t.currentTable),o=n?.columns?.some(c=>c.name==="_id"&&c.isPrimary),i=n?.columns?.some(c=>c.name==="id"),a=r==="id"?o&&!i?"_id":"id":r,u=n?.relations?.find(c=>c.propertyName===a);return u?so(a,e,u,t):n&&!n.columns?.find(d=>d.name===a)?(r.startsWith("_")&&r!=="_id"&&Oe(r,r,t.currentTable),console.warn(`[filter-parser] Unknown field "${r}" on table "${t.currentTable}" \u2014 skipped (not a column or relation in metadata).`),{node:null,hasRelationFilters:!1}):ao(a,e,t)}function Kr(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],o=!1;for(let i of e){let s=fn(i,t);s.hasRelationFilters&&(o=!0),s.node&&n.push(s.node)}return n.length===0?{node:null,hasRelationFilters:o}:n.length===1?{node:n[0],hasRelationFilters:o}:{node:{kind:r,children:n},hasRelationFilters:o}}function so(r,e,t,n){if(typeof e!="object"||e===null)return{node:null,hasRelationFilters:!0};let o=Object.keys(e),i=o.length===1&&(o[0]==="_is_null"||o[0]==="_is_not_null"||o[0]==="_eq"||o[0]==="_neq"||o[0]==="_in"||o[0]==="_not_in"||o[0]==="_nin"),s=n.registry.registerWithParent(n.currentTable,r,n.metadata,"left",n.currentJoinId,"filter");if(i&&o[0]==="_is_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_null===!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(i&&o[0]==="_is_not_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_not_null!==!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(i&&(o[0]==="_eq"||o[0]==="_neq")&&e[o[0]]===null)return s?{node:{kind:"relation_exists",joinId:s,negate:o[0]==="_eq"},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(!s)return{node:null,hasRelationFilters:!0};let a=t.targetTableName||t.targetTable,u={...n,parentJoinId:n.currentJoinId,currentJoinId:s,currentTable:a},c=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]),l=o.length>0&&o.every(p=>c.has(p))?{id:e}:e;return{node:fn(l,u).node,hasRelationFilters:!0}}function ao(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:co(r,t)};if(e===null)return{node:{kind:"compare",field:n,op:"is_null",value:!0},hasRelationFilters:!1};if(typeof e!="object")return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};for(let s of Object.keys(e))s.startsWith("_")&&!oe.has(s)&&Oe(s,r,t.tableName);let o=Object.entries(e).filter(([s])=>oe.has(s));if(o.length===0)return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};let i=[];for(let[s,a]of o){let u=lo(n,s,a);u&&i.push(u)}return i.length===0?{node:null,hasRelationFilters:!1}:i.length===1?{node:i[0],hasRelationFilters:!1}:{node:{kind:"and",children:i},hasRelationFilters:!1}}function lo(r,e,t){if(e==="_is_null")return{kind:"compare",field:r,op:"is_null",value:t===!0};if(e==="_is_not_null")return{kind:"compare",field:r,op:"is_null",value:t!==!0};let n=un(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function co(r,e){let t=e.metadata?.tables?.get(e.currentTable);if(!t)return!1;let n=r.includes(".")?r.split(".").pop():r,o=t.columns?.find(s=>s.name===n);if(!o)return!1;let i=(o.type||"").toLowerCase();return i==="uuid"||i==="uuidv4"||i.includes("uuid")}var jt=Q(()=>{"use strict";Pt();He()});var se,Bt=Q(()=>{"use strict";se=class{constructor(){this.map=new Map}size(){return this.map.size}has(e){return this.map.has(e)}get(e){return this.map.get(e)}getAll(){return Array.from(this.map.values())}registerWithParent(e,t,n,o="left",i=null,s="data"){let a=i?`${i}.${t}`:t;if(this.map.has(a)){let f=this.map.get(a);return o==="inner"&&(f.joinType="inner"),f.purposes.includes(s)||f.purposes.push(s),a}let u=n?.tables?.get(e);if(!u)return null;let c=u.relations?.find(f=>f.propertyName===t);if(!c)return null;let d=c.targetTableName||c.targetTable;if(!d)return null;let l={id:a,propertyName:t,parentTable:e,targetTable:d,relationType:c.type,parentJoinId:i,joinType:o,relationMeta:c,purposes:[s]};return this.map.set(a,l),a}}});async function K(r,e,t=ae){if(!Number.isInteger(t)||t<1)throw new Error("Batch fetch chunk size must be a positive integer");if(r.length<=t)return e(r);let n=[];for(let u=0;u<r.length;u+=t)n.push(r.slice(u,u+t));let o=[],i=0;async function s(){for(;i<n.length;){let u=i++;o[u]=await e(n[u])}}let a=Math.min(Xn,n.length);return await Promise.all(Array.from({length:a},s)),o.flat()}function Ye(r){let e=[],t=new Map;for(let n of r)if(n==="*"||!n.includes("."))e.push(n);else{let o=n.split("."),i=o[0],s=o.slice(1).join(".");t.has(i)||t.set(i,[]),t.get(i).push(s)}return{rootFields:e,subRelations:t}}var je,ae,Xn,Zn,ke,Xe=Q(()=>{"use strict";ge();je=16,ae=5e3,Xn=4,Zn=10;ke=class{constructor(e,t,n){this.adapter=e;this.metadataGetter=t;this.trace=n}enrichNestedDescs(e,t,n){if(!t||Object.keys(t).length===0)return e;let o=e.map(s=>{let a=t[s.relationName];if(!a)return s;let u=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(c=>c.trim()).filter(Boolean):["*"];return{...s,fields:u,userFilter:a.filter??s.userFilter,userSort:a.sort??s.userSort,userLimit:a.limit!==void 0?Number(a.limit):s.userLimit,userPage:a.page!==void 0?Number(a.page):s.userPage,nestedDeep:a.deep??s.nestedDeep}}),i=new Set(o.map(s=>s.relationName));for(let[s,a]of Object.entries(t)){if(i.has(s))continue;let u=n?.relations?.find(d=>d.propertyName===s);if(!u)continue;let c=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(d=>d.trim()).filter(Boolean):["*"];o.push({relationName:s,type:u.type,targetTable:u.targetTableName||u.targetTable,fields:c,isInverse:u.isInverse,fkColumn:u.foreignKeyColumn,mappedBy:u.mappedBy,junctionTableName:u.junctionTableName,junctionSourceColumn:u.junctionSourceColumn,junctionTargetColumn:u.junctionTargetColumn,userFilter:a.filter,userSort:a.sort,userLimit:a.limit!==void 0?Number(a.limit):void 0,userPage:a.page!==void 0?Number(a.page):void 0,nestedDeep:a.deep})}return o}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:Zn}:e}fieldsForNestedResolution(e,t){if(!t||Object.keys(t).length===0)return e;let n=new Set(e.filter(i=>i!=="*").map(i=>i.split(".")[0])),o=[...e];for(let i of Object.keys(t))n.has(i)||o.push(i);return o}uniqueValues(e){let t=new Set,n=[];for(let o of e){if(o==null)continue;let i=this.adapter.keyOf(o);t.has(i)||(t.add(i),n.push(o))}return n}assertLocalSortFields(e,t){if(!e.userSort)return;let n=Array.isArray(e.userSort)?e.userSort:String(e.userSort).split(",").map(o=>o.trim()).filter(Boolean);for(let o of n){let i=o.startsWith("-")?o.slice(1):o;if(i.includes("."))throw new x(`Sort field '${i}' is not supported on deep relation '${e.relationName}'. Sort only by local fields defined on '${e.targetTable}'.`);let s=t.columns?.some(u=>u.name===i),a=i==="id"&&t.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new x(`Sort field '${i}' does not exist on '${e.targetTable}'. Sort only by fields defined on the table metadata.`)}}async execute(e,t,n=3,o=0,i){if(e.length===0||t.length===0||o>=n)return;let s;i&&(s=await this.metadataGetter(i)??void 0),await Promise.all(t.map(a=>{let u=this.withDefaultToManyLimit(a);return u.type==="many-to-one"||u.type==="one-to-one"&&!u.isInverse?this.fetchOwnerRelation(e,u,n,o):u.type==="one-to-many"||u.type==="one-to-one"&&u.isInverse?this.fetchInverseRelation(e,u,n,o,s):u.type==="many-to-many"?this.fetchM2MRelation(e,u,n,o,s):Promise.resolve()}))}async fetchOwnerRelation(e,t,n,o){let i=this.adapter.resolveOwnerFkKey(t),s=new Set,a=[];for(let $ of e){let _=$[i];if(_==null)continue;let T=this.adapter.keyOf(_);s.has(T)||(s.add(T),a.push(_))}if(a.length===0){for(let $ of e)$[t.relationName]=null,i!==t.relationName&&delete $[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete $[t.fkColumn];return}let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{isPkOnly:c,nestedDescs:d,fetchSpec:l}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),f=this.adapter.getTargetPkField(u);if(c){for(let $ of e){let _=$[i];$[t.relationName]=_!=null?this.adapter.buildScalarRef(_,f):null,i!==t.relationName&&delete $[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete $[t.fkColumn]}return}let p=performance.now(),h=await this.adapter.fetchOwner(t.targetTable,a,l,t),y=Array.isArray(h)?h:h.docs,g=Array.isArray(h)?void 0:h.stats;this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:g?.strategy??"batch-in",roundtrips:g?.roundtrips??(Math.ceil(a.length/ae)||1),concurrencyWaves:g?.concurrencyWaves,ioConcurrency:g?.ioConcurrency,rowsTransferred:g?.rowsTransferred??y.length,rowsReturned:y.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let m=this.enrichNestedDescs(d,t.nestedDeep,u);m.length>0&&await this.execute(y,m,n,o+1,t.targetTable);let b=new Map;for(let $ of y)b.set(this.adapter.keyOf($[f]),$);for(let $ of e){let _=$[i];$[t.relationName]=_!=null&&b.get(this.adapter.keyOf(_))||null,i!==t.relationName&&delete $[i],t.fkColumn&&t.fkColumn!==t.relationName&&delete $[t.fkColumn]}}async fetchInverseRelation(e,t,n,o,i){let s=this.adapter.resolveParentPk(i),a=this.uniqueValues(e.map(E=>E[s]));if(a.length===0)return;let u=this.adapter.resolveInverseFkField(t),c=await this.metadataGetter(t.targetTable);if(!c)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,c);let{nestedDescs:d,fetchSpec:l}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),c),f=performance.now(),{docs:p,groupKeyField:h,stats:y}=await this.adapter.fetchInverse(t.targetTable,u,a,l,t),g=new Map,m=t.fields.includes(u)||t.fields.includes("*");for(let E of p){let L=E[h],S=this.adapter.keyOf(L);g.has(S)||g.set(S,[]),g.get(S).push(E)}let b=t.userLimit!==void 0&&t.userLimit>0,$=b?"per-parent-c16":"batch-in",_=b?a.length:Math.ceil(a.length/ae)||1,T=b?Math.ceil(a.length/je):void 0,k=Array.from(g.values()).reduce((E,L)=>E+L.length,0);if(this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,f,{relationType:t.type,targetTable:t.targetTable,strategy:y?.strategy??$,roundtrips:y?.roundtrips??_,concurrencyWaves:y?.concurrencyWaves??T,ioConcurrency:y?.ioConcurrency,rowsTransferred:y?.rowsTransferred??p.length,rowsReturned:k,rowsDiscarded:Math.max(0,(y?.rowsTransferred??p.length)-k),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let E of p)this.adapter.postProcessInverseChild(E,u,m);let R=this.enrichNestedDescs(d,t.nestedDeep,c);R.length>0&&await this.execute(p,R,n,o+1,t.targetTable);let I=t.type==="one-to-one";for(let E of e){let L=this.adapter.keyOf(E[s]),S=g.get(L)||[];E[t.relationName]=I?S[0]||null:S}}async fetchM2MRelation(e,t,n,o,i){let s=this.adapter.resolveParentPk(i),a=this.uniqueValues(e.map(T=>T[s]));if(a.length===0)return;let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{nestedDescs:c,fetchSpec:d}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),l=performance.now(),{grouped:f,docs:p,stats:h}=await this.adapter.fetchM2M(e,t,i,u,d),y=t.userLimit!==void 0&&t.userLimit>0,g=y?"m2m-per-parent-c16":"m2m-batch",m=y?a.length:Math.ceil(a.length/ae)||1,b=y?Math.ceil(a.length/je):void 0,$=Array.from(f.values()).reduce((T,k)=>T+k.length,0);this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,l,{relationType:t.type,targetTable:t.targetTable,strategy:h?.strategy??g,roundtrips:h?.roundtrips??m,concurrencyWaves:h?.concurrencyWaves??b,ioConcurrency:h?.ioConcurrency,rowsTransferred:h?.rowsTransferred??p.length,rowsReturned:$,rowsDiscarded:h?.rowsDiscarded??Math.max(0,(h?.rowsTransferred??p.length)-$),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort});let _=this.enrichNestedDescs(c,t.nestedDeep,u);_.length>0&&p.length>0&&await this.execute(p,_,n,o+1,t.targetTable);for(let T of e){let k=this.adapter.keyOf(T[s]);T[t.relationName]=f.get(k)||[]}}}});var Gr,Re,_n=Q(()=>{"use strict";Gr=2,Re=class{constructor(e=2){this.concurrency=e;this.active=0;this.waiters=[];if(!Number.isInteger(e)||e<1)throw new Error("Batch execution concurrency must be a positive integer")}async run(e){await this.acquire();try{return await e()}catch(t){throw this.cancel(t),t}finally{this.release()}}async acquire(){if(this.failure!==void 0)throw this.failure;if(this.active<this.concurrency){this.active+=1;return}if(await new Promise(e=>this.waiters.push(e)),this.failure!==void 0)throw this.failure;this.active+=1}release(){this.active-=1,this.failure===void 0&&this.waiters.shift()?.()}cancel(e){if(this.failure===void 0){this.failure=e;for(let t of this.waiters.splice(0))t()}}}});function F(r,e){let t=e==="mysql"?r.replace(/`/g,"``"):r.replace(/"/g,'""');switch(e){case"mysql":return`\`${t}\``;case"postgres":case"pg":case"sqlite":return`"${t}"`;case"mongodb":return r;default:return`\`${t}\``}}function Ie(r,e){return r.split(".").map(t=>t==="*"||t.startsWith('"')&&t.endsWith('"')||t.startsWith("`")&&t.endsWith("`")?t:F(t,e)).join(".")}var ue=Q(()=>{"use strict"});function ne(r,e,t){e&&xn(r,e,t,"and")}function xn(r,e,t,n){switch(e.kind){case"true":return;case"false":n==="or"?r.orWhereRaw("1 = 0"):r.whereRaw("1 = 0");return;case"and":{let o=function(){for(let i of e.children)this.where(function(){xn(this,i,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"or":{let o=function(){for(let i of e.children)this.orWhere(function(){xn(this,i,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"not":{let o=function(){this.whereNot(function(){xn(this,e.child,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"compare":Lo(r,e,t,n);return;case"relation_exists":console.warn(`[sql-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${e.joinId}) \u2014 expected to be handled by applyRelationFilters. Filter silently skipped.`);return}}function Lo(r,e,t,n){if(e.field.joinId!==null){console.warn(`[sql-render-filter] compare node has joinId=${e.field.joinId} (field=${e.field.fieldName}) but reached renderer \u2014 expected join path to handle it. Filter silently skipped.`);return}let o=Do(e.field,t),i=Ie(o,t.dbType),s=!!e.field.isUuid,a=t.dbType==="postgres",u=n==="or"?"orWhere":"where",c=n==="or"?"orWhereRaw":"whereRaw",d=n==="or"?"orWhereIn":"whereIn",l=n==="or"?"orWhereNotIn":"whereNotIn",f=n==="or"?"orWhereBetween":"whereBetween",p=n==="or"?"orWhereNull":"whereNull",h=n==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":s&&a&&typeof e.value=="string"?r[c](`${i} = ?::uuid`,[e.value]):r[u](o,"=",e.value);return;case"neq":s&&a&&typeof e.value=="string"?r[c](`${i} != ?::uuid`,[e.value]):r[u](o,"!=",e.value);return;case"gt":s&&a&&typeof e.value=="string"?r[c](`${i} > ?::uuid`,[e.value]):r[u](o,">",e.value);return;case"gte":s&&a&&typeof e.value=="string"?r[c](`${i} >= ?::uuid`,[e.value]):r[u](o,">=",e.value);return;case"lt":s&&a&&typeof e.value=="string"?r[c](`${i} < ?::uuid`,[e.value]):r[u](o,"<",e.value);return;case"lte":s&&a&&typeof e.value=="string"?r[c](`${i} <= ?::uuid`,[e.value]):r[u](o,"<=",e.value);return;case"in":{let y=li(e.value);s&&a&&y.every(g=>typeof g=="string")?r[c](`${i} = ANY(?::uuid[])`,[y]):r[d](o,y);return}case"not_in":{let y=li(e.value);s&&a&&y.every(g=>typeof g=="string")?r[c](`${i} != ALL(?::uuid[])`,[y]):r[l](o,y);return}case"contains":dr(r,i,e.value,"contains",t,n);return;case"starts_with":dr(r,i,e.value,"starts_with",t,n);return;case"ends_with":dr(r,i,e.value,"ends_with",t,n);return;case"between":Array.isArray(e.value)&&e.value.length===2&&r[f](o,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?r[p](o):r[h](o);return}}function dr(r,e,t,n,o,i){let s=i==="or"?"orWhereRaw":"whereRaw";if(o.dbType==="postgres"){let u=n==="contains"?`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?)) || '%'`:n==="starts_with"?`lower(unaccent(${e})) ILIKE lower(unaccent(?)) || '%'`:`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?))`;r[s](u,[t]);return}if(o.dbType==="sqlite"){let u=n==="contains"?`lower(${e}) LIKE '%' || lower(?) || '%'`:n==="starts_with"?`lower(${e}) LIKE lower(?) || '%'`:`lower(${e}) LIKE '%' || lower(?)`;r[s](u,[t]);return}let a=n==="contains"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:n==="starts_with"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`;r[s](a,[t])}function Do(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function li(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var fr=Q(()=>{"use strict";ue()});function Z(r){return r.columns.find(e=>e.isPrimary)||null}var qt=Q(()=>{"use strict"});var ui={};On(ui,{expandFieldsToJoinsAndSelect:()=>pr});async function pr(r,e,t,n,o,i){let s=[],a=[],u=await t(r);if(!u)return{select:[],batchFetchDescriptors:[]};let c=new Map;for(let l of e)if(l==="*"||!l.includes("."))c.has("")||c.set("",[]),c.get("").push(l);else{let f=l.split("."),p=f[0],h=f.slice(1).join(".");c.has(p)||c.set(p,[]),c.get(p).push(h)}if(i&&typeof i=="object")for(let[l,f]of Object.entries(i)){if(c.has(l))continue;let p=f&&typeof f=="object"&&f.fields!=null?Array.isArray(f.fields)?f.fields:String(f.fields).split(",").map(h=>h.trim()).filter(Boolean):["*"];c.set(l,p)}let d=c.get("")||[];for(let l of d){if(l==="*"){let h=new Set;for(let g of u.relations||[])if(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse){let m=g.foreignKeyColumn||G(g.propertyName);m&&h.add(m)}let y=new Set;for(let g of u.columns)h.has(g.name)||(s.push(`${r}.${g.name}`),y.add(g.name));for(let g of u.relations||[])!c.has(g.propertyName)&&!y.has(g.propertyName)&&c.set(g.propertyName,["id"]);continue}if(l.includes(".")){s.push(`${r}.${l}`);continue}if(u.columns?.find(h=>h.name===l)){s.push(`${r}.${l}`);continue}if(u.relations?.find(h=>h.propertyName===l)){c.has(l)||c.set(l,["id"]);continue}}return c.forEach((l,f)=>{if(f==="")return;let p=u.relations?.find(b=>b.propertyName===f);if(!p)return;if(p.type==="many-to-one"||p.type==="one-to-one"&&!p.isInverse){let b=p.foreignKeyColumn||G(p.propertyName),$=F(r,n),_=F(b,n),T=F(f,n);s.push(`${$}.${_} as ${T}`)}let y=p.targetTableName||p.targetTable,g=i?.[f],m=g?.fields!=null?Array.isArray(g.fields)?g.fields:String(g.fields).split(",").map(b=>b.trim()).filter(Boolean):l;a.push({relationName:f,type:p.type,targetTable:y,fields:m,isInverse:p.isInverse,fkColumn:p.foreignKeyColumn,mappedBy:p.mappedBy,junctionTableName:p.junctionTableName,junctionSourceColumn:p.junctionSourceColumn,junctionTargetColumn:p.junctionTargetColumn,userFilter:g?.filter,userSort:g?.sort,userLimit:g?.limit!==void 0?Number(g.limit):void 0,userPage:g?.page!==void 0?Number(g.page):void 0,nestedDeep:g?.deep})}),{select:s,batchFetchDescriptors:a}}var gr=Q(()=>{"use strict";Je();ue()});var zt,Vt,vn,lt,Wo,ct,yr=Q(()=>{"use strict";Je();ue();qt();Xe();_n();fr();Bt();jt();zt="__enfyra_row_number__",Vt="__sourceId__",vn="__targetId__",lt="__enfyra_partitioned__",Wo=5e4,ct=class{constructor(e,t="postgres",n,o=new Re){this.knex=e;this.dbType=t;this.metadata=n;this.executionBudget=o;this.pkField="id"}chunkCount(e,t=ae){return Math.ceil(e.length/t)||1}m2mTargetChunkSize(){return this.dbType==="postgres"?Wo:ae}uniqueValues(e){return Array.from(new Map(e.filter(t=>t!=null).map(t=>[this.keyOf(t),t])).values())}runQuery(e){return this.executionBudget.run(()=>e)}buildPartitionRowNumber(e,t,n){let o=[...t];o.some(s=>s.column===n)||o.push({column:n,order:"asc"});let i=o.map(s=>`?? ${s.order.toUpperCase()}`).join(", ");return this.knex.raw(`ROW_NUMBER() OVER (PARTITION BY ?? ORDER BY ${i}) as ??`,[e,...o.map(s=>s.column),zt])}buildPartitionSlice(e,t,n,o){return this.knex.from(e.as(lt)).select(`${lt}.*`).where(`${lt}.${zt}`,">",n).andWhere(`${lt}.${zt}`,"<=",n+o).orderBy(`${lt}.${t}`,"asc").orderBy(`${lt}.${zt}`,"asc")}removePartitionFields(e){for(let t of e)delete t[zt]}buildFilterTree(e,t){if(!e||!this.metadata)return null;let n=new se,o=this.metadata?.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))},{node:i}=he(e,t,o,n);return i}parseSortTokens(e,t,n){return e?(Array.isArray(e)?e:e.split(",").map(i=>i.trim()).filter(Boolean)).map(i=>{let s=i.startsWith("-"),u=(s?i.slice(1):i).split(".");if(u.length===1)return{column:n?`${n}.${u[0]}`:`${t}.${u[0]}`,order:s?"desc":"asc"};let c=u[u.length-1];return{column:`${`__sort_${u.slice(0,-1).join("_")}`}.${c}`,order:s?"desc":"asc"}}):[]}applySortJoins(e,t,n,o){if(!t||!this.metadata)return;let i=Array.isArray(t)?t:t.split(",").map(a=>a.trim()).filter(Boolean),s=new Set;for(let a of i){let c=(a.startsWith("-")?a.slice(1):a).split(".");if(c.length<=1)continue;let d=n,l=o||n;for(let f=0;f<c.length-1;f++){let p=c[f],h=this.metadata?.tables?.get(d);if(!h)break;let y=h.relations?.find(b=>b.propertyName===p);if(!y)break;let g=y.targetTableName||y.targetTable,m=`__sort_${c.slice(0,f+1).join("_")}`;if(!s.has(m)){s.add(m);let b=y.foreignKeyColumn||G(y.propertyName),$=this.metadata?.tables?.get(g),_=$&&Z($)?.name||"id";e.leftJoin(`${g} as ${m}`,`${m}.${_}`,`${l}.${b}`)}d=g,l=m}}}toKnexSelect(e,t){let n=e.indexOf(" as ");if(n!==-1){let o=e.substring(0,n),i=e.substring(n+4),s=F(i,this.dbType),a=t?`${t}.${F(o,this.dbType)}`:F(o,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${t}.${F(e,this.dbType)} as ${F(e,this.dbType)}`):e}keyOf(e){return e==null?"":String(e)}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return Z(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;return!t&&e.mappedBy&&(t=G(e.mappedBy)),t||(t=G(e.targetTable)),t}resolveParentPk(e){return e&&Z(e)?.name||"id"}resolveFields(e,t){let{rootFields:n,subRelations:o}=Ye(e),i=[];if(n.includes("*")){let c=new Set;for(let d of t.relations||[])if(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse){let l=d.foreignKeyColumn||G(d.propertyName);l&&c.add(l)}for(let d of t.columns)c.has(d.name)||i.push(d.name);for(let d of t.relations||[])o.has(d.propertyName)||o.set(d.propertyName,["id"])}else for(let c of n){let d=t.columns.find(l=>l.name===c);d?i.push(d.name):t.relations?.find(f=>f.propertyName===c)&&!o.has(c)&&o.set(c,["id"])}let s=Z(t)?.name||"id";i.includes(s)||i.push(s),o.forEach((c,d)=>{let l=t.relations?.find(f=>f.propertyName===d);if(l&&(l.type==="many-to-one"||l.type==="one-to-one"&&!l.isInverse)){let f=l.foreignKeyColumn||G(l.propertyName);f&&i.push(`${f} as ${d}`)}});let a=[];return o.forEach((c,d)=>{let l=t.relations?.find(p=>p.propertyName===d);if(!l)return;let f=l.targetTableName||l.targetTable;f&&a.push({relationName:d,type:l.type,targetTable:f,fields:c,isInverse:l.isInverse,fkColumn:l.foreignKeyColumn,mappedBy:l.mappedBy,junctionTableName:l.junctionTableName,junctionSourceColumn:l.junctionSourceColumn,junctionTargetColumn:l.junctionTargetColumn})}),{isPkOnly:i.length===1&&i[0]===s&&a.length===0,nestedDescs:a,fetchSpec:{selectCols:i,pkCol:s}}}async fetchOwner(e,t,n,o){let i=o?.userFilter?this.buildFilterTree(o.userFilter,e):null,s=o?.userSort?this.parseSortTokens(o.userSort,e):[],a=n.selectCols.map(c=>this.toKnexSelect(c)),u=await K(t,c=>{let d=this.knex(e).select(a).whereIn(n.pkCol,c);if(i&&ne(d,i,{dbType:this.dbType,rootTable:e}),s.length>0){this.applySortJoins(d,o.userSort,e);for(let l of s)d.orderBy(l.column,l.order)}return this.runQuery(d)});return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(t),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,n,o,i){let s=t,a=o.selectCols.find(h=>h.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():o.selectCols.includes(t)||o.selectCols.push(t);let u=i?.userFilter?this.buildFilterTree(i.userFilter,e):null,c=i?.userSort?this.parseSortTokens(i.userSort,e):[],d=i?.userLimit,l=i?.userPage;if(d!==void 0&&d>0){let h=l?(l-1)*d:0,y=o.selectCols.map(m=>this.toKnexSelect(m)),g=await K(n,async m=>{let b=this.knex(e).select(y).select(this.buildPartitionRowNumber(`${e}.${t}`,c,`${e}.${o.pkCol}`)).whereIn(`${e}.${t}`,m);u&&ne(b,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(b,i.userSort,e);let $=await this.runQuery(this.buildPartitionSlice(b,s,h,d));return this.removePartitionFields($),$});return{docs:g,groupKeyField:s,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(n),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length}}}let f=o.selectCols.map(h=>this.toKnexSelect(h)),p=await K(n,h=>{let y=this.knex(e).select(f).whereIn(t,h);if(u&&ne(y,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(y,i?.userSort,e),c.length>0)for(let g of c)y.orderBy(g.column,g.order);else y.orderBy(o.pkCol,"asc");return this.runQuery(y)});return{docs:p,groupKeyField:s,stats:{strategy:"batch-in",roundtrips:this.chunkCount(n),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length}}}postProcessInverseChild(e,t,n){n||delete e[t]}async selectM2MEdges(e,t,n,o,i,s,a,u){let c=`t.${s}`,d=!!a||u.some(y=>y.column!==c),l=d?u:u.map(y=>({...y,column:`${n}.${i}`})),f=t.userLimit,p=t.userPage;if(f!==void 0&&f>0){let y=p?(p-1)*f:0;return(await K(e,async m=>{let b=this.knex(n).select({[Vt]:`${n}.${o}`,[vn]:`${n}.${i}`}).whereIn(`${n}.${o}`,m);d&&(b=b.join(`${t.targetTable} as t`,`${n}.${i}`,`t.${s}`),a&&ne(b,a,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(b,t.userSort,t.targetTable,"t")),b.select(this.buildPartitionRowNumber(`${n}.${o}`,l,d?c:`${n}.${i}`));let $=await this.runQuery(this.buildPartitionSlice(b,Vt,y,f));return this.removePartitionFields($),$})).map(m=>({sourceId:m[Vt],targetId:m[vn]}))}return(await K(e,y=>{let g=this.knex(n).select({[Vt]:`${n}.${o}`,[vn]:`${n}.${i}`}).whereIn(`${n}.${o}`,y);if(d&&(g=g.join(`${t.targetTable} as t`,`${n}.${i}`,`t.${s}`),a&&ne(g,a,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(g,t.userSort,t.targetTable,"t")),g.orderBy(`${n}.${o}`,"asc"),l.length>0){for(let m of l)g.orderBy(m.column,m.order);d&&!l.some(m=>m.column===c)&&g.orderBy(c,"asc")}else g.orderBy(`${n}.${i}`,"asc");return this.runQuery(g)})).map(y=>({sourceId:y[Vt],targetId:y[vn]}))}async loadM2MTargets(e,t,n){if(t.length===0)return[];let o=n.selectCols.map(i=>this.toKnexSelect(i));return K(t,i=>this.runQuery(this.knex(e).select(o).whereIn(n.pkCol,i)),this.m2mTargetChunkSize())}async fetchM2M(e,t,n,o,i){let s=this.resolveParentPk(n),a=this.uniqueValues(e.map(R=>R[s]));if(a.length===0)return{grouped:new Map,docs:[]};let u=t.junctionTableName,c=t.junctionSourceColumn,d=t.junctionTargetColumn;if(!u||!c||!d)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let l=t.userFilter?this.buildFilterTree(t.userFilter,t.targetTable):null,f=t.userSort?this.parseSortTokens(t.userSort,t.targetTable,"t"):[],p=await this.selectM2MEdges(a,t,u,c,d,i.pkCol,l,f),h=new Map;for(let R of a)h.set(this.keyOf(R),[]);let y=i.selectCols.length===1&&i.selectCols[0]===i.pkCol,g=t.userLimit!==void 0&&t.userLimit>0,m=this.chunkCount(a),b=`t.${i.pkCol}`,$=!l&&f.every(R=>R.column===b);if(y){let R=new Map;for(let I of p){let E=this.keyOf(I.targetId);R.has(E)||R.set(E,{[i.pkCol]:I.targetId}),h.get(this.keyOf(I.sourceId))?.push(R.get(E))}return{grouped:h,docs:[],stats:{strategy:$?g?"m2m-junction-partitioned-top-k":"m2m-junction-batch":g?"m2m-filtered-edge-top-k":"m2m-filtered-edge-batch",roundtrips:m,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let _=this.uniqueValues(p.map(R=>R.targetId)),T=await this.loadM2MTargets(t.targetTable,_,i),k=new Map(T.map(R=>[this.keyOf(R[i.pkCol]),R]));for(let R of p){let I=k.get(this.keyOf(R.targetId));I&&h.get(this.keyOf(R.sourceId))?.push(I)}return{grouped:h,docs:T,stats:{strategy:g?"m2m-partitioned-edge-loader":"m2m-edge-loader",roundtrips:m+(_.length>0?this.chunkCount(_,this.m2mTargetChunkSize()):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+T.length,rowsDiscarded:0}}}}});var pi={};On(pi,{executeBatchFetches:()=>mr});async function mr(r,e,t,n,o=3,i=0,s,a="postgres",u,c){let d=new ct(r,a,u);await new ke(d,n,c).execute(e,t,o,i,s)}var br=Q(()=>{"use strict";Xe();yr()});var Jo={};On(Jo,{ALL_SUPPORTED_OPERATORS:()=>Ot,AuthenticationException:()=>bt,AuthorizationException:()=>_t,BadRequestException:()=>x,BatchExecutionBudget:()=>Re,BatchFetchEngine:()=>ke,BusinessLogicException:()=>gt,CHUNKED_FETCH_CONCURRENCY:()=>Xn,ConfigurationException:()=>kt,DEEP_TO_MANY_DEFAULT_LIMIT:()=>Zn,DEFAULT_BATCH_FETCH_IO_CONCURRENCY:()=>Gr,DEFAULT_TIMEOUT_MS:()=>Yt,DOTTED_PATH_MAX_HOPS:()=>En,DatabaseException:()=>Ke,DuplicateResourceException:()=>mt,ErrorHandler:()=>Me,ExecutorEngineService:()=>We,ExternalServiceException:()=>Tt,FIELD_OPERATORS:()=>oe,FileNotFoundException:()=>Ft,FileSizeExceededException:()=>xt,FileUploadException:()=>Rt,HttpException:()=>O,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>Zt,InvalidTokenException:()=>$t,IsolatedExecutorService:()=>Qe,JoinRegistry:()=>se,LOGICAL_OPERATORS:()=>Qn,MongoBatchAdapter:()=>et,MongoQueryExecutor:()=>it,PER_PARENT_CONCURRENCY:()=>je,QueryBuilderService:()=>dt,QueryPlanner:()=>q,ResourceNotFoundException:()=>yt,SchemaException:()=>Ct,ScriptContractService:()=>rn,ScriptExecutionException:()=>$e,ScriptTimeoutException:()=>we,ServiceUnavailableException:()=>St,SqlBatchAdapter:()=>ct,SqlQueryExecutor:()=>ut,TokenExpiredException:()=>wt,ValidationException:()=>ht,WHERE_IN_CHUNK_SIZE:()=>ae,WorkerPool:()=>It,appendIsolatedExecutorRuntimeLog:()=>H,applyOperatorToMatch:()=>cn,applyRelationFilters:()=>De,applyWhereToKnex:()=>at,assertFieldOperatorValueIsClean:()=>dn,buildAggregateFilter:()=>rt,buildMongoCharFoldMapJson:()=>Kn,buildMongoFoldTextSearchJs:()=>on,buildRelationSubquery:()=>Ut,buildSqlWherePartsFromFieldAst:()=>Jt,buildWhereClause:()=>de,camelToSnake:()=>Ar,chunkedFetch:()=>K,compileScriptSource:()=>qi,computeEngineTuning:()=>jn,createEnfyraKernel:()=>Qo,dslOpToCompareOp:()=>un,encodeMainThreadToIsolate:()=>Ln,escapeSqlValue:()=>ci,executeBatchFetches:()=>mr,executeMongoBatchFetches:()=>$n,expandFieldsToJoinsAndSelect:()=>pr,getEffectiveCpuCount:()=>Pn,getEffectiveMemoryBytes:()=>vt,getEngineTuning:()=>nn,getExecutableScript:()=>Gi,getForeignKeyColumnName:()=>G,getIoAbortSignal:()=>Fr,getJunctionColumnNames:()=>Et,getJunctionTableName:()=>Mt,getPrimaryKeyColumn:()=>Z,getScriptLegacyField:()=>Ui,getShortFkConstraintName:()=>Mr,getShortFkName:()=>Or,getShortIndexName:()=>Pr,getShortPkName:()=>Nr,hasAggregateQuery:()=>or,hasLogicalOperators:()=>_e,isExecutableJavaScript:()=>zi,isScriptTable:()=>Qi,mergeAggregateValue:()=>ve,normalizeAggregateQuery:()=>nt,normalizeFlowStepScriptConfig:()=>Xi,normalizeScriptLanguage:()=>Ji,normalizeScriptPatch:()=>Hi,normalizeScriptRecord:()=>Vi,parseBatchFields:()=>Ye,parseFields:()=>Tn,parseFilter:()=>he,perParentRun:()=>wn,quoteIdentifier:()=>F,quoteQualifiedIdentifier:()=>Ie,resolveExecutableScript:()=>Yi,rewriteFilterDenyingFields:()=>yi,rewriteSortDroppingDenied:()=>mi,runWithIoAbortSignal:()=>xr,scriptContractService:()=>re,separateFilters:()=>X,snakeToCamel:()=>Er,throwUnsupportedFieldOperator:()=>Oe,validateDeepOptions:()=>_r,validateFilterShape:()=>J,whereToMongoFilter:()=>Ve});module.exports=Si(Jo);var Yt=3e4,We=class{constructor(e){this.isolatedExecutorService=e.isolatedExecutorService}register(e,t){e.routeData.__codeBlocks||(e.routeData.__codeBlocks=[]),e.routeData.__codeBlocks.push(t)}async runBatch(e,t,n={}){let o=e.routeData.__codeBlocks||[];return o.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(o,e.routeData.context,t??Yt,n)}async run(e,t,n=Yt,o={}){return this.isolatedExecutorService.run(e,t,n,o)}};var Xt=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))}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};var Sr=require("async_hooks"),Cr=fe(require("path")),kr=require("stream"),Rr=require("worker_threads");var we=class extends Error{constructor(t=0,n){let o=typeof t=="number"&&t>0?`${t}ms`:String(t||"configured timeout");super(`Script execution timed out after ${o}`);this.statusCode=408;this.errorCode="SCRIPT_TIMEOUT";this.name="ScriptTimeoutException",this.details={timeoutMs:t,scriptId:n}}},$e=class extends Error{constructor(t,n,o){super(`Script execution failed: ${t}`);this.statusCode=400;this.errorCode="SCRIPT_EXECUTION_ERROR";this.name="ScriptExecutionException",this.details={scriptId:n,...o}}},B=class extends Error{constructor(t,n,o,i){super(t);this.statusCode=n;this.errorCode=o;this.name=this.constructor.name,this.details=i}},O=class extends B{constructor(e,t,n){super(e,t,`HTTP_${t}`,n)}},gt=class extends B{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},ht=class extends B{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},yt=class extends B{constructor(e,t){super(t?`${e} with identifier '${t}' not found`:`${e} not found`,404,"RESOURCE_NOT_FOUND",{resource:e,identifier:t})}},mt=class extends B{constructor(e,t,n){super(`${e} with ${t} '${n}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:n})}},bt=class extends B{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},_t=class extends B{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},wt=class extends B{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},$t=class extends B{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},Ke=class extends B{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},Tt=class extends B{constructor(e,t,n){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:n})}},St=class extends B{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},Ct=class extends B{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},kt=class extends B{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},Rt=class extends B{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},Ft=class extends B{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},xt=class extends B{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var Me=class{static createException(e,t,n,o,i){if(e?.includes("$throw"))switch(e){case"$throw.http":return new O(n||"Error",t||500,i);case"$throw.businessLogic":return new gt(n||"Bad request",i);case"$throw.validation":return new ht(n||"Validation failed",i);case"$throw.notFound":return new yt(i?.resource||n||"Resource",i?.identifier);case"$throw.duplicate":return new mt(i?.resource||n||"Resource",i?.field||"field",i?.value||"value");case"$throw.unauthorized":return new bt(n||"Unauthorized");case"$throw.forbidden":return new _t(n||"Forbidden");case"$throw.tokenExpired":return new wt;case"$throw.invalidToken":return new $t;case"$throw.database":return new Ke(n||"Database error",i);case"$throw.dbQuery":return new Ke(n||"Query error",i);case"$throw.externalService":return new Tt(n||"Service",n||"Error",i);case"$throw.serviceUnavailable":return new St(n||"Service");case"$throw.rateLimit":return new O(n||"Rate limit exceeded",429);case"$throw.scriptError":return new $e(n||"Script error",o,i);case"$throw.scriptTimeout":return new we(i?.timeout||5e3,o);case"$throw.schema":return new Ct(n||"Schema error",i);case"$throw.config":return new kt(n||"Configuration error",i);case"$throw.fileUpload":return new Rt(n||"File upload error",i);case"$throw.fileNotFound":return new Ft(n||"File not found");case"$throw.fileSizeExceeded":return new xt(i?.maxSize||"unknown",i?.actualSize||"unknown");case"$throw.400":return new O(n||"Bad request",400,i);case"$throw.401":return new O(n||"Authentication required",401,i);case"$throw.403":return new O(n||"Insufficient permissions",403,i);case"$throw.404":return new O(n||"Not found",404,i);case"$throw.409":return new O(n||"Conflict",409,i);case"$throw.422":return new O(n||"Validation failed",422,i);case"$throw.429":return new O(n||"Rate limit exceeded",429,i);case"$throw.500":return new O(n||"Internal server error",500,i);case"$throw.503":return new O(n||"Service unavailable",503,i);default:return new $e(n||"Unknown error",o)}if(t)switch(t){case 400:return new O(n||"Bad request",400,i);case 401:return new O(n||"Authentication required",401,i);case 403:return new O(n||"Insufficient permissions",403,i);case 404:return new O(n||"Not found",404,i);case 409:return new O(n||"Conflict",409,i);case 422:return new O(n||"Validation failed",422,i);case 429:return new O(n||"Rate limit exceeded",429,i);case 500:return new O(n||"Internal server error",500,i);case 503:return new O(n||"Service unavailable",503,i);default:return new $e(n||"Unknown error",o,i)}return new $e(n||"Unknown error",o,i)}};var en=fe(require("fs")),tn=fe(require("path")),Zt=tn.join(process.cwd(),"test","logs","isolated-executor-runtime.log");function Ci(){return process.env.ISOLATED_EXECUTOR_FILE_LOG==="0"?!1:process.env.ISOLATED_EXECUTOR_FILE_LOG==="1"?!0:process.env.JEST_WORKER_ID!==void 0}var ki=Ci();function H(r){if(ki)try{let e=tn.dirname(Zt);en.mkdirSync(e,{recursive:!0});let t=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...r})+`
2
- `;en.appendFileSync(Zt,t)}catch{}}var Te=fe(require("os")),Ue=fe(require("fs"));function vt(){try{let r=Ue.readFileSync("/sys/fs/cgroup/memory.max","utf8").trim();if(r!=="max"){let e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<Te.totalmem())return e}}catch{}try{let r=Ue.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes","utf8").trim(),e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<Te.totalmem())return e}catch{}return Te.totalmem()}function Pn(){let r=Te.availableParallelism?.()||Te.cpus()?.length||1;try{let e=Ue.readFileSync("/sys/fs/cgroup/cpu.max","utf8").trim(),[t,n]=e.split(/\s+/);if(t!=="max"){let o=parseInt(t,10),i=parseInt(n,10);if(o>0&&i>0)return Math.max(1,Math.ceil(o/i))}}catch{}try{let e=parseInt(Ue.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8").trim(),10),t=parseInt(Ue.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_period_us","utf8").trim(),10);if(e>0&&t>0)return Math.max(1,Math.ceil(e/t))}catch{}return r}var Ri=.25,Fi=2,xi=2048,vi=40,Ii=128,Ni=32;function jn(r){let e=Math.max(1,Math.trunc(r.logicalCpuCount)||1),t=Math.max(1,r.totalMemoryBytes/(1024*1024)),n=Math.min(Ii,Math.max(vi,Math.round(t/Ni))),o=t*Ri,i=Math.max(1,Math.floor(o/n)),s=Math.max(1,Math.min(e,2,i)),a=Math.min(256,Math.max(16,Math.floor(t/n/s))),u=t<xi?1:Fi,c=Math.max(1,Math.min(u,Math.floor(o/(s*n))));return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:a,isolatePoolSize:c}}function nn(){return jn({logicalCpuCount:Pn(),totalMemoryBytes:vt()})}var Wi=Cr.join(__dirname,"execution/worker.js"),Ki=1e4,Bn=new Sr.AsyncLocalStorage;function Fr(){return Bn.getStore()}function xr(r,e){return Bn.run(r,e)}var It=class{constructor(e,t,n,o,i,s,a,u=6e4){this.scriptPath=i;this.onCrash=s;this.onRotate=a;this.entries=[];this.waiting=[];this.cachedMemoryOk=!0;this.lastMemoryCheckMs=0;this.memorySampleIntervalMs=200;this.destroying=!1;this.entryCounter=0;this.max=e,this.effectiveMemory=t,this.rssCeiling=n,this.tasksCap=o,this.drainTimeoutMs=u;for(let c=0;c<e;c++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new Rr.Worker(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let o=t.tasks.get(n.id);o&&(n.type==="result"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),n.contextStats&&(t.contextStats=n.contextStats),o.onResult(n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):o.onIoCall(n))}),e.on("exit",()=>{let n=t.draining,o=this.destroying;t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,s]of t.tasks)s.abortController.abort(),s.onResult({type:"result",success:!1,error:{message:o?"Worker terminated":t.lastError?`Worker crashed: ${t.lastError}`:"Worker crashed"}});t.tasks.clear();let i=this.entries.indexOf(t);i!==-1&&this.entries.splice(i,1),!n&&!o&&(this.onCrash&&this.onCrash(),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),e.on("error",n=>{t.lastError=n.message}),this.entries.push(t),t}rotateEntry(e,t){if(e.draining)return;e.draining=!0;let n=Date.now()-e.spawnedAt;if(this.onRotate&&this.onRotate({reason:t,ageMs:n}),this.spawnEntry(),e.tasks.size===0){e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,e.worker.terminate()},this.drainTimeoutMs)}isMemoryAvailable(){let e=Date.now();return e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs&&(this.cachedMemoryOk=process.memoryUsage().rss/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e),this.cachedMemoryOk}findLeastBusy(){let e=null;for(let t of this.entries)t.draining||t.tasks.size<this.tasksCap&&(!e||t.tasks.size<e.tasks.size)&&(e=t);return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size===0||this.isMemoryAvailable())?Promise.resolve(e):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.tasks.set(t,n)}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&(e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(e&&(e.tasks.size===0||this.isMemoryAvailable()))this.waiting.shift()(e);else break}}terminateEntry(e){e.worker.terminate()}resize(e){for(this.max=Math.max(1,e);this.entries.length<this.max;)this.spawnEntry()}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,activeTasks:e.tasks.size,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}},Tr=new Set(["$helpers","$cache","$transaction","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$debug"]);function Ln(r){if(r===void 0)return JSON.stringify({__e:"u"});try{return JSON.stringify({__e:"v",d:r},(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return JSON.stringify({__e:"v",d:{__serializationError:!0,message:"Result is not JSON-serializable"}})}}var Qe=class r{constructor(e){this.logger=new Xt(r.name);this.effectiveMemory=vt();this.isolationTuning=nn();this.pool=new It(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Wi,()=>{this.crashesTotal++,this.logger.warn("Worker crashed, replacement spawned")},({reason:e,ageMs:t})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${e} age=${Math.round(t/1e3)}s`)});this.ceiling=this.isolationTuning.maxConcurrentWorkers;this.prevCpuUsage=process.cpuUsage();this.prevCpuTime=process.hrtime.bigint();this.pressureTicks=0;this.recoveryTicks=0;this.taskCounter=0;this.taskDoneTotal=0;this.taskErrorTotal=0;this.taskTimeoutTotal=0;this.rotationsTotal=0;this.crashesTotal=0;this.responseStreams=new Map;this.taskCancellers=new Map;this.taskDurationsMs=[];this.runtimeCallbackCounter=0;this.packageCacheService=e.packageCacheService,this.packageCdnLoaderService=e.packageCdnLoaderService,this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let t=process.memoryUsage().rss/this.effectiveMemory,n=process.hrtime.bigint(),o=process.cpuUsage(this.prevCpuUsage),i=Number(n-this.prevCpuTime)/1e3,s=i>0?(o.user+o.system)/i:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let a=this.pool.getMax(),u=this.pool.getWaitingCount(),c=t>.85||s>.7,d=t<.7&&s<.5,l=u>0,f=a;c?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(f=Math.max(1,a-1))):d&&l?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(f=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),f!==a&&(this.pool.resize(f),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${f} (rss=${Math.round(t*100)}% cpu=${Math.round(s*100)}% queue=${u})`))}createSnapshot(e){let t={$body:e.$body,$query:e.$query,$params:e.$params,$user:e.$user,$share:e.$share,$data:e.$data,$api:{request:e.$api?.request},$uploadedFile:e.$uploadedFile,$req:this.cloneSnapshotValue(e.$req)};for(let o of Object.keys(e)){if(!o.startsWith("$")||o in t||Tr.has(o))continue;let i=this.cloneSnapshotValue(e[o]);i!==void 0&&(t[o]=i)}let n=e.$flow;if(n!=null)try{t.$flow=this.cloneSnapshotValue(n)??{}}catch{t.$flow={}}return t}cloneSnapshotValue(e){if(typeof e!="function")try{return JSON.parse(JSON.stringify(e,(t,n)=>{if(typeof n=="bigint")return String(n);if(typeof n!="function")return n}))}catch{return}}mergeCtxChanges(e,t){if(t){t.$body!==void 0&&(e.$body=t.$body),t.$query!==void 0&&(e.$query=t.$query),t.$params!==void 0&&(e.$params=t.$params),t.$data!==void 0&&(e.$data=t.$data),t.$error!==void 0&&(e.$error=t.$error),t.$statusCode!==void 0&&(e.$statusCode=t.$statusCode),t.$share!==void 0&&(e.$share=t.$share),t.$api!==void 0&&e.$api&&(t.$api.error&&(e.$api.error=t.$api.error),t.$api.response&&(e.$api.response=t.$api.response)),t.$flow!==void 0&&t.$flow!==null&&typeof t.$flow=="object"&&e.$flow!=null&&typeof e.$flow=="object"&&Object.assign(e.$flow,t.$flow);for(let[n,o]of Object.entries(t))n.startsWith("$")&&(n==="$body"||n==="$query"||n==="$params"||n==="$data"||n==="$error"||n==="$statusCode"||n==="$share"||n==="$api"||n==="$flow"||Tr.has(n)||n==="$env"||(e[n]=o));delete e.$pkgs}}spawnAndExecute(e,t,n,o,i){return(async()=>{let s=await this.pool.dispatch();if(i?.aborted){let c=new Error("Execution aborted after client disconnect");return c.code="ERR_EXECUTION_ABORTED",c.isAbort=!0,Promise.reject(c)}let a=`t_${++this.taskCounter}`,u=Date.now();return new Promise((c,d)=>{let l=!1,f=new AbortController,p=!1,h=()=>{let _=new Error("Execution aborted after client disconnect");return _.code="ERR_EXECUTION_ABORTED",_.isAbort=!0,_},y,g=()=>{if(!(l||p)){p=!0,f.abort(),this.cleanupResponseStream(a,h());try{s.worker.postMessage({type:"cancelTask",id:a})}catch{}y=setTimeout(()=>{l||(l=!0,clearTimeout($),b(),this.taskCancellers.delete(a),this.pool.unregisterTask(s,a),this.taskErrorTotal++,H({event:"task_cancel_grace_terminate",id:a}),this.pool.terminateEntry(s),d(h()))},Ki),y.unref?.()}};this.taskCancellers.set(a,g);let m=()=>g(),b=()=>{i?.removeEventListener("abort",m)};i&&i.addEventListener("abort",m,{once:!0});let $=setTimeout(()=>{if(l)return;l=!0,y&&clearTimeout(y),f.abort();let _=new Error(`Script execution timed out after ${o}ms`);this.cleanupResponseStream(a,_),this.taskCancellers.delete(a),b(),this.pool.unregisterTask(s,a),this.taskTimeoutTotal++,H({event:"task_timeout",id:a,timeoutMs:o}),this.pool.terminateEntry(s),_.code="ERR_SCRIPT_EXECUTION_TIMEOUT",_.isTimeout=!0,d(_)},o);this.pool.registerTask(s,a,{abortController:f,onResult:_=>{if(!l){if(l=!0,clearTimeout($),y&&clearTimeout(y),this.taskCancellers.delete(a),b(),this.cleanupResponseStream(a),this.pool.unregisterTask(s,a),this.recordTaskDuration(Date.now()-u),p){f.abort(),this.taskErrorTotal++,d(h());return}if(_.success){this.taskDoneTotal++,H({event:"task_done",id:a,ok:!0});let T={value:_.value,valueAbsent:_.valueAbsent===!0,ctxChanges:_.ctxChanges};_.shortCircuit&&(T.shortCircuit=!0),c(T)}else{this.taskErrorTotal++,H({event:"task_done",id:a,ok:!1,message:_.error?.message});let T=new Error(_.error?.message||"Handler execution failed");T.statusCode=_.error?.statusCode,T.code=_.error?.code,T.details=_.error?.details,_.error?.stack&&(T.stack=_.error.stack),_.ctxChanges&&(T.ctxChanges=_.ctxChanges),this.cleanupResponseStream(a,T),d(T)}}},onIoCall:_=>{if(l)return;let T=f.signal;_.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(_,n),s.worker,_.callId,T):_.type==="transactionCall"?this.handleIoCall(()=>this.execTransactionCall(_,n,s.worker),s.worker,_.callId,T):_.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(_,n),s.worker,_.callId,T):_.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(_,n),s.worker,_.callId,T):_.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(_,n),s.worker,_.callId,T):_.type==="storageCall"?this.handleIoCall(()=>this.execStorageCall(_,n,s.worker),s.worker,_.callId,T):_.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall(_,n),s.worker,_.callId,T):_.type==="resCall"&&this.handleIoCall(()=>this.execResCall(_,n),s.worker,_.callId,T)}}),s.worker.postMessage({type:e,id:a,...t}),i?.aborted&&g()})})()}postAbortedCallError(e,t){try{e.postMessage({type:"callError",callId:t,error:JSON.stringify({__userThrow:!0,message:"Execution aborted after client disconnect",code:"ERR_EXECUTION_ABORTED"})})}catch{}}async handleIoCall(e,t,n,o){if(o?.aborted){this.postAbortedCallError(t,n);return}try{let i=await(o?Bn.run(o,e):e());if(o?.aborted){this.postAbortedCallError(t,n);return}try{t.postMessage({type:"callResult",callId:n,result:Ln(i)})}catch{}}catch(i){if(o?.aborted){this.postAbortedCallError(t,n);return}try{let s={__userThrow:!0,message:i.message,statusCode:i.statusCode,code:i.errorCode??i.code,details:i.details,messages:i.messages};t.postMessage({type:"callError",callId:n,error:JSON.stringify(s)})}catch{}}}async execRepoCall(e,t){let n=JSON.parse(e.argsJson),o=e.access==="secure"?t?.$repos?.secure?.[e.table]:t?.$repos?.[e.table];if(!o||typeof o[e.method]!="function"){let i=e.access==="secure"?"secure.":"";throw new Error(`Repo method not found: ${i}${e.table}.${e.method}`)}return o[e.method](...n)}async execTransactionCall(e,t,n){let i=JSON.parse(e.argsJson||"[]").map(a=>a?.__fnRef&&typeof a.__fnRef=="string"?(...u)=>this.invokeRuntimeCallback(n,e.id,a.__fnRef,u):a)[0];if(typeof i!="function")throw new Error("$transaction.run requires a callback");let s=t?.$transaction?.run;if(typeof s!="function")throw new Error("$transaction is not available");return await s.call(t.$transaction,i)}async execHelpersCall(e,t){let n=JSON.parse(e.argsJson),o=e.name.split("."),i=t?.$helpers;for(let s of o)i=i?.[s];if(typeof i!="function")throw new Error(`Helper not found: ${e.name}`);return i(...n)}async execSocketCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$socket?.[e.method];if(typeof o!="function")throw new Error(`Socket method not found: ${e.method}`);return o(...n)}async execCacheCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$cache?.[e.method];if(typeof o!="function")throw new Error(`Cache method not found: ${e.method}`);return o(...n)}async execStorageCall(e,t,n){let o=this.parseStorageArgs(e.argsJson,n,e.id),i=t?.$storage?.[e.method];if(typeof i!="function")throw new Error(`Storage method not found: ${e.method}`);return i(...o)}parseStorageArgs(e,t,n){return JSON.parse(e,(o,i)=>{if(i?.__fnRef&&typeof i.__fnRef=="string"){let s=i.__fnRef;return(...a)=>this.invokeRuntimeCallback(t,n,s,a)}return i})}invokeRuntimeCallback(e,t,n,o){let i=`rtcb_${++this.runtimeCallbackCounter}`;return new Promise((s,a)=>{let u=setTimeout(()=>{d(),a(new Error(`Runtime callback timed out: ${n}`))},3e4),c=l=>{if(!(l?.type!=="runtimeCallbackResult"||l.callId!==i)){if(d(),l.error){a(new Error(l.error));return}s(l.value)}},d=()=>{clearTimeout(u),e.off("message",c)};e.on("message",c),e.postMessage({type:"invokeRuntimeCallback",id:t,callId:i,callbackId:n,argsJson:JSON.stringify(o)})})}async execDispatchCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$trigger;if(typeof o!="function")throw new Error("$trigger is not available");return o(...n)}cancelTask(e){this.taskCancellers.get(e)?.()}async execResCall(e,t){if(e.method==="streamStart"){let s=JSON.parse(e.argsJson||"[]")[1]||{},a=t?.$res?.stream;if(typeof a!="function")throw new Error("Response method not found: stream");let u=new kr.PassThrough,c={stream:u};this.responseStreams.set(e.id,c);let d=t?.$res;if(d&&typeof d.once=="function"){let f=()=>{d.writableEnded!==!0&&this.cancelTask(e.id)};d.once("close",f),c.closeCleanup=()=>{typeof d.off=="function"?d.off("close",f):typeof d.removeListener=="function"&&d.removeListener("close",f)}}let l=a.call(t.$res,u,s);return l&&typeof l.catch=="function"&&l.catch(()=>{}),!0}if(e.method==="streamChunk"){let i=this.responseStreams.get(e.id);if(!i)throw new Error(`Response stream not found: ${e.id}`);let s=Buffer.from(e.chunk||"","base64");return i.stream.write(s)||await new Promise((a,u)=>{let c=()=>{l(),a()},d=f=>{l(),u(f)},l=()=>{i.stream.off("drain",c),i.stream.off("error",d)};i.stream.once("drain",c),i.stream.once("error",d)}),!0}if(e.method==="streamEnd"){let i=this.responseStreams.get(e.id);return i&&(i.closeCleanup?.(),i.stream.end(),this.responseStreams.delete(e.id)),!0}if(e.method==="streamError"){let i=this.responseStreams.get(e.id);if(i){i.closeCleanup?.();let s=e.error?.message||"Response stream failed";i.stream.destroy(new Error(s)),this.responseStreams.delete(e.id)}return!0}let n=JSON.parse(e.argsJson||"[]"),o=t?.$res?.[e.method];if(typeof o!="function")throw new Error(`Response method not found: ${e.method}`);return o.apply(t.$res,n)}cleanupResponseStream(e,t){let n=this.responseStreams.get(e);n&&(this.responseStreams.delete(e),n.closeCleanup?.(),t?n.stream.destroy(t):n.stream.end())}toWorkerCodeBlock(e){return{code:e.code,sourceCode:e.sourceCode,scriptLanguage:e.scriptLanguage,type:e.type}}async run(e,t,n,o={}){let i=Math.max(1,Math.trunc(Number(n)||3e4)),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),u=this.createSnapshot(t);H({event:"isolated_run_start",timeoutMs:i,codeLen:e?.length??0});let c;try{let d={code:e,sourceCode:o.sourceCode??e,pkgSources:a,snapshot:u,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};c=await this.spawnAndExecute("execute",d,t,i)}catch(d){let l=d;if(H({event:"isolated_run_error",message:l.message,code:l.code,isTimeout:!!l.isTimeout}),l.code==="ERR_EXECUTION_ABORTED"||l.isAbort)throw l;if(l.isTimeout||l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new we(i,e);let f=l.statusCode??(typeof l.status=="number"?l.status:void 0);throw Me.createException(l.errorPath,f,l.message||"Unknown error",e,l.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),H({event:"isolated_run_ok"}),c.valueAbsent?void 0:c.value}async runBatch(e,t,n,o={}){let i=Math.max(1,Math.trunc(Number(n)||3e4)),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),u=this.createSnapshot(t);H({event:"isolated_batch_start",timeoutMs:i,blocks:e.length});let c;try{let l={codeBlocks:e.map(f=>this.toWorkerCodeBlock(f)),pkgSources:a,snapshot:u,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};c=await this.spawnAndExecute("executeBatch",l,t,i,o.signal)}catch(d){let l=d;if(H({event:"isolated_batch_error",message:l.message,code:l.code,isTimeout:!!l.isTimeout}),l.ctxChanges&&this.mergeCtxChanges(t,l.ctxChanges),l.code==="ERR_EXECUTION_ABORTED"||l.isAbort)throw l;if(l.isTimeout||l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new we(i,"(batch execution)");let f=l.statusCode??(typeof l.status=="number"?l.status:void 0);throw Me.createException(l.errorPath,f,l.message||"Unknown error","(batch execution)",l.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),H({event:"isolated_batch_ok"}),{value:c.valueAbsent?void 0:c.value,shortCircuit:c.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let n=[...e].sort((i,s)=>i-s),o=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[o]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((o,i)=>o+i,0)/t.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),maxHeapRatio:Math.max(0,...e.workers.map(o=>o.lastHeapRatio||0))}}};var Ee=fe(require("typescript")),Nt={oauth_config_definition:"",route_handler_definition:"logic",pre_hook_definition:"code",post_hook_definition:"code",bootstrap_script_definition:"logic",websocket_definition:"connectionHandlerScript",websocket_event_definition:"handlerScript"};function Ui(r){return re.getLegacyField(r)}function Qi(r){return re.isScriptTable(r)}function Ji(r){return re.normalizeLanguage(r)}var rn=class{getLegacyField(e){return Nt[e]}isScriptTable(e){return e in Nt}normalizeLanguage(e){return e==="javascript"?"javascript":"typescript"}compileSource(e,t){if(e==null||e==="")return null;let n=String(e),i=this.normalizeLanguage(t)==="javascript"?n:this.transpileTypeScript(n);return this.assertExecutableJavaScript(i),i}isExecutableJavaScript(e){if(!e)return!1;try{return this.assertExecutableJavaScript(e),!0}catch{return!1}}normalizeRecord(e,t){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let n={...t},o=this.getLegacyField(e);return o&&(n.sourceCode===void 0||n.sourceCode===null||n.sourceCode==="")&&n[o]!==void 0&&(n.sourceCode=n[o]),n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage),o&&o in n&&delete n[o],n}normalizePatch(e,t,n){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let o=this.getLegacyField(e),i=Object.prototype.hasOwnProperty.call(t,"sourceCode")||(o?Object.prototype.hasOwnProperty.call(t,o):!1),s=Object.prototype.hasOwnProperty.call(t,"scriptLanguage");if(!i&&!s)return t;let a=i?t.sourceCode??(o?t[o]:void 0):n?.sourceCode??(o&&n?n[o]:void 0),u=s?t.scriptLanguage:n?.scriptLanguage,c={...t};return i&&(c.sourceCode=a??null),c.scriptLanguage=this.normalizeLanguage(u),c.compiledCode=this.compileSource(a,c.scriptLanguage),o&&o in c&&delete c[o],c}getExecutableScript(e){return this.resolveExecutableScript(e).code}resolveExecutableScript(e){if(!e||typeof e!="object")return{code:null,compiledCode:null,shouldPersistCompiledCode:!1};if(typeof e.sourceCode=="string"&&e.sourceCode!==""){let n=this.compileSource(e.sourceCode,e.scriptLanguage);return{code:n,compiledCode:n,shouldPersistCompiledCode:n!==e.compiledCode}}let t=Object.keys(Nt).find(n=>Nt[n]in e);if(t){let n=e[Nt[t]];if(typeof n=="string"&&n!==""){let o=this.compileSource(n,e.scriptLanguage);return{code:o,compiledCode:o,shouldPersistCompiledCode:o!==e.compiledCode}}}return typeof e.compiledCode=="string"&&e.compiledCode!==""&&this.isExecutableJavaScript(e.compiledCode)?{code:e.compiledCode,compiledCode:e.compiledCode,shouldPersistCompiledCode:!1}:{code:null,compiledCode:null,shouldPersistCompiledCode:!1}}normalizeFlowStepScriptConfig(e){if(!e||typeof e!="object")return e;let t=e.type;if(t!=="script"&&t!=="condition")return e;let n={...e},o=e.config;if(typeof o=="string")try{o=JSON.parse(o)}catch{return e}let i=o&&typeof o=="object"?o:{};n.sourceCode=n.sourceCode??i.sourceCode??i.code??null,n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage??i.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage);let s={...i};return delete s.sourceCode,delete s.scriptLanguage,delete s.compiledCode,delete s.code,{...n,config:typeof e.config=="string"?JSON.stringify(s):s}}repairContract(e){let t=this.normalizeLanguage(e?.scriptLanguage),n=e?.sourceCode??null,o=this.compileSource(n,t);return{sourceCode:n,scriptLanguage:t,code:o,compiledCode:o,shouldPersistCompiledCode:o!==e?.compiledCode}}transpileTypeScript(e){let t=Ee.default.transpileModule(e,{compilerOptions:{target:Ee.default.ScriptTarget.ES2022,module:Ee.default.ModuleKind.CommonJS,importsNotUsedAsValues:Ee.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),n=t.diagnostics?.find(o=>o.category===Ee.default.DiagnosticCategory.Error);if(n)throw new Error(Ee.default.flattenDiagnosticMessageText(n.messageText,`
1
+ "use strict";var fi=Object.create;var zt=Object.defineProperty;var pi=Object.getOwnPropertyDescriptor;var gi=Object.getOwnPropertyNames;var hi=Object.getPrototypeOf,mi=Object.prototype.hasOwnProperty;var q=(r,e)=>()=>(r&&(e=r(r=0)),e);var On=(r,e)=>{for(var t in e)zt(r,t,{get:e[t],enumerable:!0})},mr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of gi(e))!mi.call(r,i)&&i!==t&&zt(r,i,{get:()=>e[i],enumerable:!(n=pi(e,i))||n.enumerable});return r};var ue=(r,e,t)=>(t=r!=null?fi(hi(r)):{},mr(e||!r||!r.__esModule?zt(t,"default",{value:r,enumerable:!0}):t,r)),yi=r=>mr(zt({},"__esModule",{value:!0}),r);function Fr(r){return jn.createHash("md5").update(r).digest("hex").substring(0,8)}function Rr(r){return r.length<=kr-3?`${r}_pk`:`j_${Fr(r)}_pk`}function xr(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=kr?n:`j_${Fr(r)}_${t}_fk`}function xt(r,e,t){let n=`${r}:${e}:${t}`;return`j_${jn.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function J(r){return`${r}Id`}function vt(r,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function vr(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function Ir(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function Nr(r,e,t){return`${r}_${e}_${t}_fk`}function Or(r,e,t){return`${r}_${e}_${t}_idx`}var jn,kr,Ke=q(()=>{"use strict";jn=ue(require("crypto")),kr=63});function an(r){return Yi[r]??null}var we,Wn,Nt,Yi,ln=q(()=>{"use strict";we=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),Wn=new Set(["_and","_or","_not"]),Nt=[...Array.from(Wn),...Array.from(we)],Yi={_eq:"eq",_neq:"neq",_gt:"gt",_gte:"gte",_lt:"lt",_lte:"lte",_in:"in",_not_in:"not_in",_nin:"not_in",_contains:"contains",_starts_with:"starts_with",_ends_with:"ends_with",_between:"between"}});var v,de=q(()=>{"use strict";v=class extends Error{constructor(t="Bad Request",n){let i=Array.isArray(t),o=i?t.join("; ")||"Bad Request":typeof t=="string"?t:JSON.stringify(t);super(o);this.statusCode=400;this.errorCode="BAD_REQUEST";this.name="BadRequestException",this.details=n,i&&(this.messages=t)}}});function Pr(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var jr=q(()=>{"use strict"});function Oe(r,e,t){throw new v({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${Nt.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:Nt})}function cn(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=Pr();for(let i of Object.keys(e))if(i.startsWith("_")&&!we.has(i)){if(n&&i==="_id")continue;Oe(i,r,t)}}function re(r,e,t){if(!r||typeof r!="object")return;let n=t?.tables?.get(e),i=new Set((n?.columns??[]).map(s=>s.name)),o=new Map((n?.relations??[]).map(s=>[s.propertyName,s]));for(let[s,a]of Object.entries(r)){if(Xi.has(s)){if(Array.isArray(a))for(let c of a)re(c,e,t);else a&&typeof a=="object"&&re(a,e,t);continue}let u=o.get(s);if(u){if(a&&typeof a=="object"&&!Array.isArray(a)){cn(s,a,e);let c=u.targetTableName||u.targetTable;if(c){let d=Object.keys(a).filter(l=>!l.startsWith("_"));if(d.length>0){let l={};for(let f of d)l[f]=a[f];re(l,c,t)}}}continue}s.startsWith("_")&&!i.has(s)&&s!=="_id"&&Oe(s,s,e),a&&typeof a=="object"&&!Array.isArray(a)&&cn(s,a,e)}}var Xi,Je=q(()=>{"use strict";de();ln();jr();Xi=new Set(["_and","_or","_not"])});function fe(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:un(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function un(r,e){if(!r||typeof r!="object")return{node:null,hasRelationFilters:!1};let t=[],n=!1;for(let[i,o]of Object.entries(r)){let s=Zi(i,o,e);s.hasRelationFilters&&(n=!0),s.node&&t.push(s.node)}return t.length===0?{node:null,hasRelationFilters:n}:t.length===1?{node:t[0],hasRelationFilters:n}:{node:{kind:"and",children:t},hasRelationFilters:n}}function Zi(r,e,t){if(r==="_and")return Br("and",e,t);if(r==="_or")return Br("or",e,t);if(r==="_not"){let c=un(e,t);return c.node?{node:{kind:"not",child:c.node},hasRelationFilters:c.hasRelationFilters}:{node:null,hasRelationFilters:c.hasRelationFilters}}let n=t.metadata?.tables?.get(t.currentTable),i=n?.columns?.some(c=>c.name==="_id"&&c.isPrimary),o=n?.columns?.some(c=>c.name==="id"),a=r==="id"?i&&!o?"_id":"id":r,u=n?.relations?.find(c=>c.propertyName===a);return u?eo(a,e,u,t):n&&!n.columns?.find(d=>d.name===a)?(r.startsWith("_")&&r!=="_id"&&Oe(r,r,t.currentTable),console.warn(`[filter-parser] Unknown field "${r}" on table "${t.currentTable}" \u2014 skipped (not a column or relation in metadata).`),{node:null,hasRelationFilters:!1}):to(a,e,t)}function Br(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],i=!1;for(let o of e){let s=un(o,t);s.hasRelationFilters&&(i=!0),s.node&&n.push(s.node)}return n.length===0?{node:null,hasRelationFilters:i}:n.length===1?{node:n[0],hasRelationFilters:i}:{node:{kind:r,children:n},hasRelationFilters:i}}function eo(r,e,t,n){if(typeof e!="object"||e===null)return{node:null,hasRelationFilters:!0};let i=Object.keys(e),o=i.length===1&&(i[0]==="_is_null"||i[0]==="_is_not_null"||i[0]==="_eq"||i[0]==="_neq"||i[0]==="_in"||i[0]==="_not_in"||i[0]==="_nin"),s=n.registry.registerWithParent(n.currentTable,r,n.metadata,"left",n.currentJoinId,"filter");if(o&&i[0]==="_is_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_null===!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(o&&i[0]==="_is_not_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_not_null!==!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(o&&(i[0]==="_eq"||i[0]==="_neq")&&e[i[0]]===null)return s?{node:{kind:"relation_exists",joinId:s,negate:i[0]==="_eq"},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(!s)return{node:null,hasRelationFilters:!0};let a=t.targetTableName||t.targetTable,u={...n,parentJoinId:n.currentJoinId,currentJoinId:s,currentTable:a},c=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]),l=i.length>0&&i.every(p=>c.has(p))?{id:e}:e;return{node:un(l,u).node,hasRelationFilters:!0}}function to(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:ro(r,t)};if(e===null)return{node:{kind:"compare",field:n,op:"is_null",value:!0},hasRelationFilters:!1};if(typeof e!="object")return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};for(let s of Object.keys(e))s.startsWith("_")&&!we.has(s)&&Oe(s,r,t.tableName);let i=Object.entries(e).filter(([s])=>we.has(s));if(i.length===0)return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};let o=[];for(let[s,a]of i){let u=no(n,s,a);u&&o.push(u)}return o.length===0?{node:null,hasRelationFilters:!1}:o.length===1?{node:o[0],hasRelationFilters:!1}:{node:{kind:"and",children:o},hasRelationFilters:!1}}function no(r,e,t){if(e==="_is_null")return{kind:"compare",field:r,op:"is_null",value:t===!0};if(e==="_is_not_null")return{kind:"compare",field:r,op:"is_null",value:t!==!0};let n=an(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function ro(r,e){let t=e.metadata?.tables?.get(e.currentTable);if(!t)return!1;let n=r.includes(".")?r.split(".").pop():r,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")}var Ot=q(()=>{"use strict";ln();Je()});var ie,Mt=q(()=>{"use strict";ie=class{constructor(){this.map=new Map}size(){return this.map.size}has(e){return this.map.has(e)}get(e){return this.map.get(e)}getAll(){return Array.from(this.map.values())}registerWithParent(e,t,n,i="left",o=null,s="data"){let a=o?`${o}.${t}`:t;if(this.map.has(a)){let f=this.map.get(a);return i==="inner"&&(f.joinType="inner"),f.purposes.includes(s)||f.purposes.push(s),a}let u=n?.tables?.get(e);if(!u)return null;let c=u.relations?.find(f=>f.propertyName===t);if(!c)return null;let d=c.targetTableName||c.targetTable;if(!d)return null;let l={id:a,propertyName:t,parentTable:e,targetTable:d,relationType:c.type,parentJoinId:o,joinType:i,relationMeta:c,purposes:[s]};return this.map.set(a,l),a}}});async function W(r,e,t=oe){if(!Number.isInteger(t)||t<1)throw new Error("Batch fetch chunk size must be a positive integer");if(r.length<=t)return e(r);let n=[];for(let u=0;u<r.length;u+=t)n.push(r.slice(u,u+t));let i=[],o=0;async function s(){for(;o<n.length;){let u=o++;i[u]=await e(n[u])}}let a=Math.min(Hn,n.length);return await Promise.all(Array.from({length:a},s)),i.flat()}function He(r){let e=[],t=new Map;for(let n of r)if(n==="*"||!n.includes("."))e.push(n);else{let i=n.split("."),o=i[0],s=i.slice(1).join(".");t.has(o)||t.set(o,[]),t.get(o).push(s)}return{rootFields:e,subRelations:t}}var Me,oe,Hn,Gn,Se,Ge=q(()=>{"use strict";de();Me=16,oe=5e3,Hn=4,Gn=10;Se=class{constructor(e,t,n){this.adapter=e;this.metadataGetter=t;this.trace=n}enrichNestedDescs(e,t,n){if(!t||Object.keys(t).length===0)return e;let i=e.map(s=>{let a=t[s.relationName];if(!a)return s;let u=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(c=>c.trim()).filter(Boolean):["*"];return{...s,fields:u,userFilter:a.filter??s.userFilter,userSort:a.sort??s.userSort,userLimit:a.limit!==void 0?Number(a.limit):s.userLimit,userPage:a.page!==void 0?Number(a.page):s.userPage,nestedDeep:a.deep??s.nestedDeep}}),o=new Set(i.map(s=>s.relationName));for(let[s,a]of Object.entries(t)){if(o.has(s))continue;let u=n?.relations?.find(d=>d.propertyName===s);if(!u)continue;let c=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(d=>d.trim()).filter(Boolean):["*"];i.push({relationName:s,type:u.type,targetTable:u.targetTableName||u.targetTable,fields:c,isInverse:u.isInverse,fkColumn:u.foreignKeyColumn,mappedBy:u.mappedBy,junctionTableName:u.junctionTableName,junctionSourceColumn:u.junctionSourceColumn,junctionTargetColumn:u.junctionTargetColumn,userFilter:a.filter,userSort:a.sort,userLimit:a.limit!==void 0?Number(a.limit):void 0,userPage:a.page!==void 0?Number(a.page):void 0,nestedDeep:a.deep})}return i}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:Gn}:e}fieldsForNestedResolution(e,t){if(!t||Object.keys(t).length===0)return e;let n=new Set(e.filter(o=>o!=="*").map(o=>o.split(".")[0])),i=[...e];for(let o of Object.keys(t))n.has(o)||i.push(o);return i}uniqueValues(e){let t=new Set,n=[];for(let i of e){if(i==null)continue;let o=this.adapter.keyOf(i);t.has(o)||(t.add(o),n.push(i))}return n}assertLocalSortFields(e,t){if(!e.userSort)return;let n=Array.isArray(e.userSort)?e.userSort:String(e.userSort).split(",").map(i=>i.trim()).filter(Boolean);for(let i of n){let o=i.startsWith("-")?i.slice(1):i;if(o.includes("."))throw new v(`Sort field '${o}' is not supported on deep relation '${e.relationName}'. Sort only by local fields defined on '${e.targetTable}'.`);let s=t.columns?.some(u=>u.name===o),a=o==="id"&&t.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new v(`Sort field '${o}' does not exist on '${e.targetTable}'. Sort only by fields defined on the table metadata.`)}}async execute(e,t,n=3,i=0,o){if(e.length===0||t.length===0||i>=n)return;let s;o&&(s=await this.metadataGetter(o)??void 0),await Promise.all(t.map(a=>{let u=this.withDefaultToManyLimit(a);return u.type==="many-to-one"||u.type==="one-to-one"&&!u.isInverse?this.fetchOwnerRelation(e,u,n,i):u.type==="one-to-many"||u.type==="one-to-one"&&u.isInverse?this.fetchInverseRelation(e,u,n,i,s):u.type==="many-to-many"?this.fetchM2MRelation(e,u,n,i,s):Promise.resolve()}))}async fetchOwnerRelation(e,t,n,i){let o=this.adapter.resolveOwnerFkKey(t),s=new Set,a=[];for(let $ of e){let _=$[o];if(_==null)continue;let T=this.adapter.keyOf(_);s.has(T)||(s.add(T),a.push(_))}if(a.length===0){for(let $ of e)$[t.relationName]=null,o!==t.relationName&&delete $[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete $[t.fkColumn];return}let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{isPkOnly:c,nestedDescs:d,fetchSpec:l}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),f=this.adapter.getTargetPkField(u);if(c){for(let $ of e){let _=$[o];$[t.relationName]=_!=null?this.adapter.buildScalarRef(_,f):null,o!==t.relationName&&delete $[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete $[t.fkColumn]}return}let p=performance.now(),h=await this.adapter.fetchOwner(t.targetTable,a,l,t),g=Array.isArray(h)?h:h.docs,m=Array.isArray(h)?void 0:h.stats;this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:m?.strategy??"batch-in",roundtrips:m?.roundtrips??(Math.ceil(a.length/oe)||1),concurrencyWaves:m?.concurrencyWaves,ioConcurrency:m?.ioConcurrency,rowsTransferred:m?.rowsTransferred??g.length,rowsReturned:g.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let y=this.enrichNestedDescs(d,t.nestedDeep,u);y.length>0&&await this.execute(g,y,n,i+1,t.targetTable);let b=new Map;for(let $ of g)b.set(this.adapter.keyOf($[f]),$);for(let $ of e){let _=$[o];$[t.relationName]=_!=null&&b.get(this.adapter.keyOf(_))||null,o!==t.relationName&&delete $[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete $[t.fkColumn]}}async fetchInverseRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=this.uniqueValues(e.map(M=>M[s]));if(a.length===0)return;let u=this.adapter.resolveInverseFkField(t),c=await this.metadataGetter(t.targetTable);if(!c)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,c);let{nestedDescs:d,fetchSpec:l}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),c),f=performance.now(),{docs:p,groupKeyField:h,stats:g}=await this.adapter.fetchInverse(t.targetTable,u,a,l,t),m=new Map,y=t.fields.includes(u)||t.fields.includes("*");for(let M of p){let B=M[h],S=this.adapter.keyOf(B);m.has(S)||m.set(S,[]),m.get(S).push(M)}let b=t.userLimit!==void 0&&t.userLimit>0,$=b?"per-parent-c16":"batch-in",_=b?a.length:Math.ceil(a.length/oe)||1,T=b?Math.ceil(a.length/Me):void 0,C=Array.from(m.values()).reduce((M,B)=>M+B.length,0);if(this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,f,{relationType:t.type,targetTable:t.targetTable,strategy:g?.strategy??$,roundtrips:g?.roundtrips??_,concurrencyWaves:g?.concurrencyWaves??T,ioConcurrency:g?.ioConcurrency,rowsTransferred:g?.rowsTransferred??p.length,rowsReturned:C,rowsDiscarded:Math.max(0,(g?.rowsTransferred??p.length)-C),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let M of p)this.adapter.postProcessInverseChild(M,u,y);let x=this.enrichNestedDescs(d,t.nestedDeep,c);x.length>0&&await this.execute(p,x,n,i+1,t.targetTable);let I=t.type==="one-to-one";for(let M of e){let B=this.adapter.keyOf(M[s]),S=m.get(B)||[];M[t.relationName]=I?S[0]||null:S}}async fetchM2MRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=this.uniqueValues(e.map(T=>T[s]));if(a.length===0)return;let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{nestedDescs:c,fetchSpec:d}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),l=performance.now(),{grouped:f,docs:p,stats:h}=await this.adapter.fetchM2M(e,t,o,u,d),g=t.userLimit!==void 0&&t.userLimit>0,m=g?"m2m-per-parent-c16":"m2m-batch",y=g?a.length:Math.ceil(a.length/oe)||1,b=g?Math.ceil(a.length/Me):void 0,$=Array.from(f.values()).reduce((T,C)=>T+C.length,0);this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,l,{relationType:t.type,targetTable:t.targetTable,strategy:h?.strategy??m,roundtrips:h?.roundtrips??y,concurrencyWaves:h?.concurrencyWaves??b,ioConcurrency:h?.ioConcurrency,rowsTransferred:h?.rowsTransferred??p.length,rowsReturned:$,rowsDiscarded:h?.rowsDiscarded??Math.max(0,(h?.rowsTransferred??p.length)-$),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort});let _=this.enrichNestedDescs(c,t.nestedDeep,u);_.length>0&&p.length>0&&await this.execute(p,_,n,i+1,t.targetTable);for(let T of e){let C=this.adapter.keyOf(T[s]);T[t.relationName]=f.get(C)||[]}}}});var Jr,Ce,yn=q(()=>{"use strict";Jr=2,Ce=class{constructor(e=2){this.concurrency=e;this.active=0;this.waiters=[];if(!Number.isInteger(e)||e<1)throw new Error("Batch execution concurrency must be a positive integer")}async run(e){await this.acquire();try{return await e()}catch(t){throw this.cancel(t),t}finally{this.release()}}async acquire(){if(this.failure!==void 0)throw this.failure;if(this.active<this.concurrency){this.active+=1;return}if(await new Promise(e=>this.waiters.push(e)),this.failure!==void 0)throw this.failure;this.active+=1}release(){this.active-=1,this.failure===void 0&&this.waiters.shift()?.()}cancel(e){if(this.failure===void 0){this.failure=e;for(let t of this.waiters.splice(0))t()}}}});function R(r,e){let t=e==="mysql"?r.replace(/`/g,"``"):r.replace(/"/g,'""');switch(e){case"mysql":return`\`${t}\``;case"postgres":case"pg":case"sqlite":return`"${t}"`;case"mongodb":return r;default:return`\`${t}\``}}function Fe(r,e){return r.split(".").map(t=>t==="*"||t.startsWith('"')&&t.endsWith('"')||t.startsWith("`")&&t.endsWith("`")?t:R(t,e)).join(".")}var ae=q(()=>{"use strict"});function ce(r,e,t){e&&kn(r,e,t,"and")}function kn(r,e,t,n){switch(e.kind){case"true":return;case"false":n==="or"?r.orWhereRaw("1 = 0"):r.whereRaw("1 = 0");return;case"and":{let i=function(){for(let o of e.children)this.where(function(){kn(this,o,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"or":{let i=function(){for(let o of e.children)this.orWhere(function(){kn(this,o,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"not":{let i=function(){this.whereNot(function(){kn(this,e.child,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"compare":Eo(r,e,t,n);return;case"relation_exists":console.warn(`[sql-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${e.joinId}) \u2014 expected to be handled by applyRelationFilters. Filter silently skipped.`);return}}function Eo(r,e,t,n){if(e.field.joinId!==null){console.warn(`[sql-render-filter] compare node has joinId=${e.field.joinId} (field=${e.field.fieldName}) but reached renderer \u2014 expected join path to handle it. Filter silently skipped.`);return}let i=Ao(e.field,t),o=Fe(i,t.dbType),s=!!e.field.isUuid,a=t.dbType==="postgres",u=n==="or"?"orWhere":"where",c=n==="or"?"orWhereRaw":"whereRaw",d=n==="or"?"orWhereIn":"whereIn",l=n==="or"?"orWhereNotIn":"whereNotIn",f=n==="or"?"orWhereBetween":"whereBetween",p=n==="or"?"orWhereNull":"whereNull",h=n==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":s&&a&&typeof e.value=="string"?r[c](`${o} = ?::uuid`,[e.value]):r[u](i,"=",e.value);return;case"neq":s&&a&&typeof e.value=="string"?r[c](`${o} != ?::uuid`,[e.value]):r[u](i,"!=",e.value);return;case"gt":s&&a&&typeof e.value=="string"?r[c](`${o} > ?::uuid`,[e.value]):r[u](i,">",e.value);return;case"gte":s&&a&&typeof e.value=="string"?r[c](`${o} >= ?::uuid`,[e.value]):r[u](i,">=",e.value);return;case"lt":s&&a&&typeof e.value=="string"?r[c](`${o} < ?::uuid`,[e.value]):r[u](i,"<",e.value);return;case"lte":s&&a&&typeof e.value=="string"?r[c](`${o} <= ?::uuid`,[e.value]):r[u](i,"<=",e.value);return;case"in":{let g=ri(e.value);s&&a&&g.every(m=>typeof m=="string")?r[c](`${o} = ANY(?::uuid[])`,[g]):r[d](i,g);return}case"not_in":{let g=ri(e.value);s&&a&&g.every(m=>typeof m=="string")?r[c](`${o} != ALL(?::uuid[])`,[g]):r[l](i,g);return}case"contains":ar(r,o,e.value,"contains",t,n);return;case"starts_with":ar(r,o,e.value,"starts_with",t,n);return;case"ends_with":ar(r,o,e.value,"ends_with",t,n);return;case"between":Array.isArray(e.value)&&e.value.length===2&&r[f](i,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?r[p](i):r[h](i);return}}function ar(r,e,t,n,i,o){let s=o==="or"?"orWhereRaw":"whereRaw";if(i.dbType==="postgres"){let u=n==="contains"?`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?)) || '%'`:n==="starts_with"?`lower(unaccent(${e})) ILIKE lower(unaccent(?)) || '%'`:`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?))`;r[s](u,[t]);return}if(i.dbType==="sqlite"){let u=n==="contains"?`lower(${e}) LIKE '%' || lower(?) || '%'`:n==="starts_with"?`lower(${e}) LIKE lower(?) || '%'`:`lower(${e}) LIKE '%' || lower(?)`;r[s](u,[t]);return}let a=n==="contains"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:n==="starts_with"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`;r[s](a,[t])}function Ao(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function ri(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var lr=q(()=>{"use strict";ae()});function H(r){return r.columns.find(e=>e.isPrimary)||null}var qt=q(()=>{"use strict"});var ii={};On(ii,{expandFieldsToJoinsAndSelect:()=>cr});async function cr(r,e,t,n,i,o){let s=[],a=[],u=await t(r);if(!u)return{select:[],batchFetchDescriptors:[]};let c=new Map;for(let l of e)if(l==="*"||!l.includes("."))c.has("")||c.set("",[]),c.get("").push(l);else{let f=l.split("."),p=f[0],h=f.slice(1).join(".");c.has(p)||c.set(p,[]),c.get(p).push(h)}if(o&&typeof o=="object")for(let[l,f]of Object.entries(o)){if(c.has(l))continue;let p=f&&typeof f=="object"&&f.fields!=null?Array.isArray(f.fields)?f.fields:String(f.fields).split(",").map(h=>h.trim()).filter(Boolean):["*"];c.set(l,p)}let d=c.get("")||[];for(let l of d){if(l==="*"){let h=new Set;for(let m of u.relations||[])if(m.type==="many-to-one"||m.type==="one-to-one"&&!m.isInverse){let y=m.foreignKeyColumn||J(m.propertyName);y&&h.add(y)}let g=new Set;for(let m of u.columns)h.has(m.name)||(s.push(`${r}.${m.name}`),g.add(m.name));for(let m of u.relations||[])!c.has(m.propertyName)&&!g.has(m.propertyName)&&c.set(m.propertyName,["id"]);continue}if(l.includes(".")){s.push(`${r}.${l}`);continue}if(u.columns?.find(h=>h.name===l)){s.push(`${r}.${l}`);continue}if(u.relations?.find(h=>h.propertyName===l)){c.has(l)||c.set(l,["id"]);continue}}return c.forEach((l,f)=>{if(f==="")return;let p=u.relations?.find(b=>b.propertyName===f);if(!p)return;if(p.type==="many-to-one"||p.type==="one-to-one"&&!p.isInverse){let b=p.foreignKeyColumn||J(p.propertyName),$=R(r,n),_=R(b,n),T=R(f,n);s.push(`${$}.${_} as ${T}`)}let g=p.targetTableName||p.targetTable,m=o?.[f],y=m?.fields!=null?Array.isArray(m.fields)?m.fields:String(m.fields).split(",").map(b=>b.trim()).filter(Boolean):l;a.push({relationName:f,type:p.type,targetTable:g,fields:y,isInverse:p.isInverse,fkColumn:p.foreignKeyColumn,mappedBy:p.mappedBy,junctionTableName:p.junctionTableName,junctionSourceColumn:p.junctionSourceColumn,junctionTargetColumn:p.junctionTargetColumn,userFilter:m?.filter,userSort:m?.sort,userLimit:m?.limit!==void 0?Number(m.limit):void 0,userPage:m?.page!==void 0?Number(m.page):void 0,nestedDeep:m?.deep})}),{select:s,batchFetchDescriptors:a}}var ur=q(()=>{"use strict";Ke();ae()});var Ut,Qt,Fn,ot,Po,st,fr=q(()=>{"use strict";Ke();ae();qt();Ge();yn();lr();Mt();Ot();Ut="__enfyra_row_number__",Qt="__sourceId__",Fn="__targetId__",ot="__enfyra_partitioned__",Po=5e4,st=class{constructor(e,t="postgres",n,i=new Ce){this.knex=e;this.dbType=t;this.metadata=n;this.executionBudget=i;this.pkField="id"}chunkCount(e,t=oe){return Math.ceil(e.length/t)||1}m2mTargetChunkSize(){return this.dbType==="postgres"?Po:oe}uniqueValues(e){return Array.from(new Map(e.filter(t=>t!=null).map(t=>[this.keyOf(t),t])).values())}runQuery(e){return this.executionBudget.run(()=>e)}buildPartitionRowNumber(e,t,n){let i=[...t];i.some(s=>s.column===n)||i.push({column:n,order:"asc"});let o=i.map(s=>`?? ${s.order.toUpperCase()}`).join(", ");return this.knex.raw(`ROW_NUMBER() OVER (PARTITION BY ?? ORDER BY ${o}) as ??`,[e,...i.map(s=>s.column),Ut])}buildPartitionSlice(e,t,n,i){return this.knex.from(e.as(ot)).select(`${ot}.*`).where(`${ot}.${Ut}`,">",n).andWhere(`${ot}.${Ut}`,"<=",n+i).orderBy(`${ot}.${t}`,"asc").orderBy(`${ot}.${Ut}`,"asc")}removePartitionFields(e){for(let t of e)delete t[Ut]}buildFilterTree(e,t){if(!e||!this.metadata)return null;let n=new ie,i=this.metadata?.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))},{node:o}=fe(e,t,i,n);return o}parseSortTokens(e,t,n){return e?(Array.isArray(e)?e:e.split(",").map(o=>o.trim()).filter(Boolean)).map(o=>{let s=o.startsWith("-"),u=(s?o.slice(1):o).split(".");if(u.length===1)return{column:n?`${n}.${u[0]}`:`${t}.${u[0]}`,order:s?"desc":"asc"};let c=u[u.length-1];return{column:`${`__sort_${u.slice(0,-1).join("_")}`}.${c}`,order:s?"desc":"asc"}}):[]}applySortJoins(e,t,n,i){if(!t||!this.metadata)return;let o=Array.isArray(t)?t:t.split(",").map(a=>a.trim()).filter(Boolean),s=new Set;for(let a of o){let c=(a.startsWith("-")?a.slice(1):a).split(".");if(c.length<=1)continue;let d=n,l=i||n;for(let f=0;f<c.length-1;f++){let p=c[f],h=this.metadata?.tables?.get(d);if(!h)break;let g=h.relations?.find(b=>b.propertyName===p);if(!g)break;let m=g.targetTableName||g.targetTable,y=`__sort_${c.slice(0,f+1).join("_")}`;if(!s.has(y)){s.add(y);let b=g.foreignKeyColumn||J(g.propertyName),$=this.metadata?.tables?.get(m),_=$&&H($)?.name||"id";e.leftJoin(`${m} as ${y}`,`${y}.${_}`,`${l}.${b}`)}d=m,l=y}}}toKnexSelect(e,t){let n=e.indexOf(" as ");if(n!==-1){let i=e.substring(0,n),o=e.substring(n+4),s=R(o,this.dbType),a=t?`${t}.${R(i,this.dbType)}`:R(i,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${t}.${R(e,this.dbType)} as ${R(e,this.dbType)}`):e}keyOf(e){return e==null?"":String(e)}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return H(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;return!t&&e.mappedBy&&(t=J(e.mappedBy)),t||(t=J(e.targetTable)),t}resolveParentPk(e){return e&&H(e)?.name||"id"}resolveFields(e,t){let{rootFields:n,subRelations:i}=He(e),o=[];if(n.includes("*")){let c=new Set;for(let d of t.relations||[])if(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse){let l=d.foreignKeyColumn||J(d.propertyName);l&&c.add(l)}for(let d of t.columns)c.has(d.name)||o.push(d.name);for(let d of t.relations||[])i.has(d.propertyName)||i.set(d.propertyName,["id"])}else for(let c of n){let d=t.columns.find(l=>l.name===c);d?o.push(d.name):t.relations?.find(f=>f.propertyName===c)&&!i.has(c)&&i.set(c,["id"])}let s=H(t)?.name||"id";o.includes(s)||o.push(s),i.forEach((c,d)=>{let l=t.relations?.find(f=>f.propertyName===d);if(l&&(l.type==="many-to-one"||l.type==="one-to-one"&&!l.isInverse)){let f=l.foreignKeyColumn||J(l.propertyName);f&&o.push(`${f} as ${d}`)}});let a=[];return i.forEach((c,d)=>{let l=t.relations?.find(p=>p.propertyName===d);if(!l)return;let f=l.targetTableName||l.targetTable;f&&a.push({relationName:d,type:l.type,targetTable:f,fields:c,isInverse:l.isInverse,fkColumn:l.foreignKeyColumn,mappedBy:l.mappedBy,junctionTableName:l.junctionTableName,junctionSourceColumn:l.junctionSourceColumn,junctionTargetColumn:l.junctionTargetColumn})}),{isPkOnly:o.length===1&&o[0]===s&&a.length===0,nestedDescs:a,fetchSpec:{selectCols:o,pkCol:s}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?this.buildFilterTree(i.userFilter,e):null,s=i?.userSort?this.parseSortTokens(i.userSort,e):[],a=n.selectCols.map(c=>this.toKnexSelect(c)),u=await W(t,c=>{let d=this.knex(e).select(a).whereIn(n.pkCol,c);if(o&&ce(d,o,{dbType:this.dbType,rootTable:e}),s.length>0){this.applySortJoins(d,i.userSort,e);for(let l of s)d.orderBy(l.column,l.order)}return this.runQuery(d)});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=t,a=i.selectCols.find(h=>h.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():i.selectCols.includes(t)||i.selectCols.push(t);let u=o?.userFilter?this.buildFilterTree(o.userFilter,e):null,c=o?.userSort?this.parseSortTokens(o.userSort,e):[],d=o?.userLimit,l=o?.userPage;if(d!==void 0&&d>0){let h=l?(l-1)*d:0,g=i.selectCols.map(y=>this.toKnexSelect(y)),m=await W(n,async y=>{let b=this.knex(e).select(g).select(this.buildPartitionRowNumber(`${e}.${t}`,c,`${e}.${i.pkCol}`)).whereIn(`${e}.${t}`,y);u&&ce(b,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(b,o.userSort,e);let $=await this.runQuery(this.buildPartitionSlice(b,s,h,d));return this.removePartitionFields($),$});return{docs:m,groupKeyField:s,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(n),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.length}}}let f=i.selectCols.map(h=>this.toKnexSelect(h)),p=await W(n,h=>{let g=this.knex(e).select(f).whereIn(t,h);if(u&&ce(g,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(g,o?.userSort,e),c.length>0)for(let m of c)g.orderBy(m.column,m.order);else g.orderBy(i.pkCol,"asc");return this.runQuery(g)});return{docs:p,groupKeyField:s,stats:{strategy:"batch-in",roundtrips:this.chunkCount(n),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length}}}postProcessInverseChild(e,t,n){n||delete e[t]}async selectM2MEdges(e,t,n,i,o,s,a,u){let c=`t.${s}`,d=!!a||u.some(g=>g.column!==c),l=d?u:u.map(g=>({...g,column:`${n}.${o}`})),f=t.userLimit,p=t.userPage;if(f!==void 0&&f>0){let g=p?(p-1)*f:0;return(await W(e,async y=>{let b=this.knex(n).select({[Qt]:`${n}.${i}`,[Fn]:`${n}.${o}`}).whereIn(`${n}.${i}`,y);d&&(b=b.join(`${t.targetTable} as t`,`${n}.${o}`,`t.${s}`),a&&ce(b,a,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(b,t.userSort,t.targetTable,"t")),b.select(this.buildPartitionRowNumber(`${n}.${i}`,l,d?c:`${n}.${o}`));let $=await this.runQuery(this.buildPartitionSlice(b,Qt,g,f));return this.removePartitionFields($),$})).map(y=>({sourceId:y[Qt],targetId:y[Fn]}))}return(await W(e,g=>{let m=this.knex(n).select({[Qt]:`${n}.${i}`,[Fn]:`${n}.${o}`}).whereIn(`${n}.${i}`,g);if(d&&(m=m.join(`${t.targetTable} as t`,`${n}.${o}`,`t.${s}`),a&&ce(m,a,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(m,t.userSort,t.targetTable,"t")),m.orderBy(`${n}.${i}`,"asc"),l.length>0){for(let y of l)m.orderBy(y.column,y.order);d&&!l.some(y=>y.column===c)&&m.orderBy(c,"asc")}else m.orderBy(`${n}.${o}`,"asc");return this.runQuery(m)})).map(g=>({sourceId:g[Qt],targetId:g[Fn]}))}async loadM2MTargets(e,t,n){if(t.length===0)return[];let i=n.selectCols.map(o=>this.toKnexSelect(o));return W(t,o=>this.runQuery(this.knex(e).select(i).whereIn(n.pkCol,o)),this.m2mTargetChunkSize())}async fetchM2M(e,t,n,i,o){let s=this.resolveParentPk(n),a=this.uniqueValues(e.map(x=>x[s]));if(a.length===0)return{grouped:new Map,docs:[]};let u=t.junctionTableName,c=t.junctionSourceColumn,d=t.junctionTargetColumn;if(!u||!c||!d)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let l=t.userFilter?this.buildFilterTree(t.userFilter,t.targetTable):null,f=t.userSort?this.parseSortTokens(t.userSort,t.targetTable,"t"):[],p=await this.selectM2MEdges(a,t,u,c,d,o.pkCol,l,f),h=new Map;for(let x of a)h.set(this.keyOf(x),[]);let g=o.selectCols.length===1&&o.selectCols[0]===o.pkCol,m=t.userLimit!==void 0&&t.userLimit>0,y=this.chunkCount(a),b=`t.${o.pkCol}`,$=!l&&f.every(x=>x.column===b);if(g){let x=new Map;for(let I of p){let M=this.keyOf(I.targetId);x.has(M)||x.set(M,{[o.pkCol]:I.targetId}),h.get(this.keyOf(I.sourceId))?.push(x.get(M))}return{grouped:h,docs:[],stats:{strategy:$?m?"m2m-junction-partitioned-top-k":"m2m-junction-batch":m?"m2m-filtered-edge-top-k":"m2m-filtered-edge-batch",roundtrips:y,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let _=this.uniqueValues(p.map(x=>x.targetId)),T=await this.loadM2MTargets(t.targetTable,_,o),C=new Map(T.map(x=>[this.keyOf(x[o.pkCol]),x]));for(let x of p){let I=C.get(this.keyOf(x.targetId));I&&h.get(this.keyOf(x.sourceId))?.push(I)}return{grouped:h,docs:T,stats:{strategy:m?"m2m-partitioned-edge-loader":"m2m-edge-loader",roundtrips:y+(_.length>0?this.chunkCount(_,this.m2mTargetChunkSize()):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+T.length,rowsDiscarded:0}}}}});var ai={};On(ai,{executeBatchFetches:()=>pr});async function pr(r,e,t,n,i=3,o=0,s,a="postgres",u,c){let d=new st(r,a,u);await new Se(d,n,c).execute(e,t,i,o,s)}var gr=q(()=>{"use strict";Ge();fr()});var Do={};On(Do,{ALL_SUPPORTED_OPERATORS:()=>Nt,AuthenticationException:()=>gt,AuthorizationException:()=>ht,BadRequestException:()=>v,BatchExecutionBudget:()=>Ce,BatchFetchEngine:()=>Se,BusinessLogicException:()=>ut,CHUNKED_FETCH_CONCURRENCY:()=>Hn,ConfigurationException:()=>$t,DEEP_TO_MANY_DEFAULT_LIMIT:()=>Gn,DEFAULT_BATCH_FETCH_IO_CONCURRENCY:()=>Jr,DEFAULT_TIMEOUT_MS:()=>Vt,DOTTED_PATH_MAX_HOPS:()=>In,DatabaseException:()=>Le,DuplicateResourceException:()=>pt,ErrorHandler:()=>xe,ExecutorEngineService:()=>Be,ExternalServiceException:()=>bt,FIELD_OPERATORS:()=>we,FileNotFoundException:()=>St,FileSizeExceededException:()=>Ct,FileUploadException:()=>Tt,HttpException:()=>P,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>Gt,InvalidTokenException:()=>yt,IsolatedExecutorService:()=>We,JoinRegistry:()=>ie,LOGICAL_OPERATORS:()=>Wn,MongoBatchAdapter:()=>Xe,MongoQueryExecutor:()=>Ae,PER_PARENT_CONCURRENCY:()=>Me,QueryBuilderService:()=>at,QueryPlanner:()=>X,ResourceNotFoundException:()=>ft,SchemaException:()=>wt,ScriptContractService:()=>en,ScriptExecutionException:()=>ye,ScriptTimeoutException:()=>me,ServiceUnavailableException:()=>_t,SqlBatchAdapter:()=>st,SqlQueryExecutor:()=>je,TokenExpiredException:()=>mt,ValidationException:()=>dt,WHERE_IN_CHUNK_SIZE:()=>oe,WorkerPool:()=>Ft,appendIsolatedExecutorRuntimeLog:()=>Q,applyOperatorToMatch:()=>sn,applyRelationFilters:()=>Lt,applyWhereToKnex:()=>it,assertFieldOperatorValueIsClean:()=>cn,buildMongoCharFoldMapJson:()=>Ln,buildMongoFoldTextSearchJs:()=>tn,buildRelationSubquery:()=>Bt,buildSqlWherePartsFromFieldAst:()=>Wt,buildWhereClause:()=>le,camelToSnake:()=>Ir,chunkedFetch:()=>W,compileScriptSource:()=>Di,computeEngineTuning:()=>En,createEnfyraKernel:()=>Lo,dslOpToCompareOp:()=>an,encodeMainThreadToIsolate:()=>Pn,escapeSqlValue:()=>Kt,executeBatchFetches:()=>pr,executeMongoBatchFetches:()=>_n,expandFieldsToJoinsAndSelect:()=>cr,getEffectiveCpuCount:()=>Mn,getEffectiveMemoryBytes:()=>kt,getEngineTuning:()=>Zt,getExecutableScript:()=>Ui,getForeignKeyColumnName:()=>J,getIoAbortSignal:()=>Sr,getJunctionColumnNames:()=>vt,getJunctionTableName:()=>xt,getPrimaryKeyColumn:()=>H,getScriptLegacyField:()=>ji,getShortFkConstraintName:()=>xr,getShortFkName:()=>Nr,getShortIndexName:()=>Or,getShortPkName:()=>Rr,hasLogicalOperators:()=>he,isExecutableJavaScript:()=>Wi,isScriptTable:()=>Bi,normalizeAggregateQuery:()=>tt,normalizeFlowStepScriptConfig:()=>Ji,normalizeScriptLanguage:()=>Li,normalizeScriptPatch:()=>qi,normalizeScriptRecord:()=>Ki,parseBatchFields:()=>He,parseFields:()=>wn,parseFilter:()=>fe,perParentRun:()=>bn,quoteIdentifier:()=>R,quoteQualifiedIdentifier:()=>Fe,resolveExecutableScript:()=>Qi,rewriteFilterDenyingFields:()=>ui,rewriteSortDroppingDenied:()=>di,runWithIoAbortSignal:()=>Cr,scriptContractService:()=>ee,separateFilters:()=>V,snakeToCamel:()=>vr,throwUnsupportedFieldOperator:()=>Oe,validateDeepOptions:()=>hr,validateFilterShape:()=>re,whereToMongoFilter:()=>Qe});module.exports=yi(Do);var Vt=3e4,Be=class{constructor(e){this.isolatedExecutorService=e.isolatedExecutorService}register(e,t){e.routeData.__codeBlocks||(e.routeData.__codeBlocks=[]),e.routeData.__codeBlocks.push(t)}async runBatch(e,t,n={}){let i=e.routeData.__codeBlocks||[];return i.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(i,e.routeData.context,t??Vt,n)}async run(e,t,n=Vt,i={}){return this.isolatedExecutorService.run(e,t,n,i)}};var Ht=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))}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};var _r=require("async_hooks"),wr=ue(require("path")),$r=require("stream"),Tr=require("worker_threads");var me=class extends Error{constructor(t=0,n){let i=typeof t=="number"&&t>0?`${t}ms`:String(t||"configured timeout");super(`Script execution timed out after ${i}`);this.statusCode=408;this.errorCode="SCRIPT_TIMEOUT";this.name="ScriptTimeoutException",this.details={timeoutMs:t,scriptId:n}}},ye=class extends Error{constructor(t,n,i){super(`Script execution failed: ${t}`);this.statusCode=400;this.errorCode="SCRIPT_EXECUTION_ERROR";this.name="ScriptExecutionException",this.details={scriptId:n,...i}}},j=class extends Error{constructor(t,n,i,o){super(t);this.statusCode=n;this.errorCode=i;this.name=this.constructor.name,this.details=o}},P=class extends j{constructor(e,t,n){super(e,t,`HTTP_${t}`,n)}},ut=class extends j{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},dt=class extends j{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},ft=class extends j{constructor(e,t){super(t?`${e} with identifier '${t}' not found`:`${e} not found`,404,"RESOURCE_NOT_FOUND",{resource:e,identifier:t})}},pt=class extends j{constructor(e,t,n){super(`${e} with ${t} '${n}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:n})}},gt=class extends j{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},ht=class extends j{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},mt=class extends j{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},yt=class extends j{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},Le=class extends j{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},bt=class extends j{constructor(e,t,n){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:n})}},_t=class extends j{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},wt=class extends j{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},$t=class extends j{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},Tt=class extends j{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},St=class extends j{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},Ct=class extends j{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var xe=class{static createException(e,t,n,i,o){if(e?.includes("$throw"))switch(e){case"$throw.http":return new P(n||"Error",t||500,o);case"$throw.businessLogic":return new ut(n||"Bad request",o);case"$throw.validation":return new dt(n||"Validation failed",o);case"$throw.notFound":return new ft(o?.resource||n||"Resource",o?.identifier);case"$throw.duplicate":return new pt(o?.resource||n||"Resource",o?.field||"field",o?.value||"value");case"$throw.unauthorized":return new gt(n||"Unauthorized");case"$throw.forbidden":return new ht(n||"Forbidden");case"$throw.tokenExpired":return new mt;case"$throw.invalidToken":return new yt;case"$throw.database":return new Le(n||"Database error",o);case"$throw.dbQuery":return new Le(n||"Query error",o);case"$throw.externalService":return new bt(n||"Service",n||"Error",o);case"$throw.serviceUnavailable":return new _t(n||"Service");case"$throw.rateLimit":return new P(n||"Rate limit exceeded",429);case"$throw.scriptError":return new ye(n||"Script error",i,o);case"$throw.scriptTimeout":return new me(o?.timeout||5e3,i);case"$throw.schema":return new wt(n||"Schema error",o);case"$throw.config":return new $t(n||"Configuration error",o);case"$throw.fileUpload":return new Tt(n||"File upload error",o);case"$throw.fileNotFound":return new St(n||"File not found");case"$throw.fileSizeExceeded":return new Ct(o?.maxSize||"unknown",o?.actualSize||"unknown");case"$throw.400":return new P(n||"Bad request",400,o);case"$throw.401":return new P(n||"Authentication required",401,o);case"$throw.403":return new P(n||"Insufficient permissions",403,o);case"$throw.404":return new P(n||"Not found",404,o);case"$throw.409":return new P(n||"Conflict",409,o);case"$throw.422":return new P(n||"Validation failed",422,o);case"$throw.429":return new P(n||"Rate limit exceeded",429,o);case"$throw.500":return new P(n||"Internal server error",500,o);case"$throw.503":return new P(n||"Service unavailable",503,o);default:return new ye(n||"Unknown error",i)}if(t)switch(t){case 400:return new P(n||"Bad request",400,o);case 401:return new P(n||"Authentication required",401,o);case 403:return new P(n||"Insufficient permissions",403,o);case 404:return new P(n||"Not found",404,o);case 409:return new P(n||"Conflict",409,o);case 422:return new P(n||"Validation failed",422,o);case 429:return new P(n||"Rate limit exceeded",429,o);case 500:return new P(n||"Internal server error",500,o);case 503:return new P(n||"Service unavailable",503,o);default:return new ye(n||"Unknown error",i,o)}return new ye(n||"Unknown error",i,o)}};var Yt=ue(require("fs")),Xt=ue(require("path")),Gt=Xt.join(process.cwd(),"test","logs","isolated-executor-runtime.log");function bi(){return process.env.ISOLATED_EXECUTOR_FILE_LOG==="0"?!1:process.env.ISOLATED_EXECUTOR_FILE_LOG==="1"?!0:process.env.JEST_WORKER_ID!==void 0}var _i=bi();function Q(r){if(_i)try{let e=Xt.dirname(Gt);Yt.mkdirSync(e,{recursive:!0});let t=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...r})+`
2
+ `;Yt.appendFileSync(Gt,t)}catch{}}var be=ue(require("os")),De=ue(require("fs"));function kt(){try{let r=De.readFileSync("/sys/fs/cgroup/memory.max","utf8").trim();if(r!=="max"){let e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<be.totalmem())return e}}catch{}try{let r=De.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes","utf8").trim(),e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<be.totalmem())return e}catch{}return be.totalmem()}function Mn(){let r=be.availableParallelism?.()||be.cpus()?.length||1;try{let e=De.readFileSync("/sys/fs/cgroup/cpu.max","utf8").trim(),[t,n]=e.split(/\s+/);if(t!=="max"){let i=parseInt(t,10),o=parseInt(n,10);if(i>0&&o>0)return Math.max(1,Math.ceil(i/o))}}catch{}try{let e=parseInt(De.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8").trim(),10),t=parseInt(De.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_period_us","utf8").trim(),10);if(e>0&&t>0)return Math.max(1,Math.ceil(e/t))}catch{}return r}var wi=.25,$i=2,Ti=2048,Si=40,Ci=128,ki=32;function En(r){let e=Math.max(1,Math.trunc(r.logicalCpuCount)||1),t=Math.max(1,r.totalMemoryBytes/(1024*1024)),n=Math.min(Ci,Math.max(Si,Math.round(t/ki))),i=t*wi,o=Math.max(1,Math.floor(i/n)),s=Math.max(1,Math.min(e,2,o)),a=Math.min(256,Math.max(16,Math.floor(t/n/s))),u=t<Ti?1:$i,c=Math.max(1,Math.min(u,Math.floor(i/(s*n))));return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:a,isolatePoolSize:c}}function Zt(){return En({logicalCpuCount:Mn(),totalMemoryBytes:kt()})}var Ai=wr.join(__dirname,"execution/worker.js"),Pi=1e4,An=new _r.AsyncLocalStorage;function Sr(){return An.getStore()}function Cr(r,e){return An.run(r,e)}var Ft=class{constructor(e,t,n,i,o,s,a,u=6e4){this.scriptPath=o;this.onCrash=s;this.onRotate=a;this.entries=[];this.waiting=[];this.cachedMemoryOk=!0;this.lastMemoryCheckMs=0;this.memorySampleIntervalMs=200;this.destroying=!1;this.entryCounter=0;this.max=e,this.effectiveMemory=t,this.rssCeiling=n,this.tasksCap=i,this.drainTimeoutMs=u;for(let c=0;c<e;c++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new Tr.Worker(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let i=t.tasks.get(n.id);i&&(n.type==="result"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),n.contextStats&&(t.contextStats=n.contextStats),i.onResult(n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):i.onIoCall(n))}),e.on("exit",()=>{let n=t.draining,i=this.destroying;t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,s]of t.tasks)s.abortController.abort(),s.onResult({type:"result",success:!1,error:{message:i?"Worker terminated":t.lastError?`Worker crashed: ${t.lastError}`:"Worker crashed"}});t.tasks.clear();let o=this.entries.indexOf(t);o!==-1&&this.entries.splice(o,1),!n&&!i&&(this.onCrash&&this.onCrash(),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),e.on("error",n=>{t.lastError=n.message}),this.entries.push(t),t}rotateEntry(e,t){if(e.draining)return;e.draining=!0;let n=Date.now()-e.spawnedAt;if(this.onRotate&&this.onRotate({reason:t,ageMs:n}),this.spawnEntry(),e.tasks.size===0){e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,e.worker.terminate()},this.drainTimeoutMs)}isMemoryAvailable(){let e=Date.now();return e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs&&(this.cachedMemoryOk=process.memoryUsage().rss/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e),this.cachedMemoryOk}findLeastBusy(){let e=null;for(let t of this.entries)t.draining||t.tasks.size<this.tasksCap&&(!e||t.tasks.size<e.tasks.size)&&(e=t);return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size===0||this.isMemoryAvailable())?Promise.resolve(e):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.tasks.set(t,n)}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&(e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(e&&(e.tasks.size===0||this.isMemoryAvailable()))this.waiting.shift()(e);else break}}terminateEntry(e){e.worker.terminate()}resize(e){for(this.max=Math.max(1,e);this.entries.length<this.max;)this.spawnEntry()}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,activeTasks:e.tasks.size,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}},br=new Set(["$helpers","$cache","$transaction","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$debug"]);function Pn(r){if(r===void 0)return JSON.stringify({__e:"u"});try{return JSON.stringify({__e:"v",d:r},(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return JSON.stringify({__e:"v",d:{__serializationError:!0,message:"Result is not JSON-serializable"}})}}var We=class r{constructor(e){this.logger=new Ht(r.name);this.effectiveMemory=kt();this.isolationTuning=Zt();this.pool=new Ft(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Ai,()=>{this.crashesTotal++,this.logger.warn("Worker crashed, replacement spawned")},({reason:e,ageMs:t})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${e} age=${Math.round(t/1e3)}s`)});this.ceiling=this.isolationTuning.maxConcurrentWorkers;this.prevCpuUsage=process.cpuUsage();this.prevCpuTime=process.hrtime.bigint();this.pressureTicks=0;this.recoveryTicks=0;this.taskCounter=0;this.taskDoneTotal=0;this.taskErrorTotal=0;this.taskTimeoutTotal=0;this.rotationsTotal=0;this.crashesTotal=0;this.responseStreams=new Map;this.taskCancellers=new Map;this.taskDurationsMs=[];this.runtimeCallbackCounter=0;this.packageCacheService=e.packageCacheService,this.packageCdnLoaderService=e.packageCdnLoaderService,this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let t=process.memoryUsage().rss/this.effectiveMemory,n=process.hrtime.bigint(),i=process.cpuUsage(this.prevCpuUsage),o=Number(n-this.prevCpuTime)/1e3,s=o>0?(i.user+i.system)/o:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let a=this.pool.getMax(),u=this.pool.getWaitingCount(),c=t>.85||s>.7,d=t<.7&&s<.5,l=u>0,f=a;c?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(f=Math.max(1,a-1))):d&&l?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(f=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),f!==a&&(this.pool.resize(f),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${f} (rss=${Math.round(t*100)}% cpu=${Math.round(s*100)}% queue=${u})`))}createSnapshot(e){let t={$body:e.$body,$query:e.$query,$params:e.$params,$user:e.$user,$share:e.$share,$data:e.$data,$api:{request:e.$api?.request},$uploadedFile:e.$uploadedFile,$req:this.cloneSnapshotValue(e.$req)};for(let i of Object.keys(e)){if(!i.startsWith("$")||i in t||br.has(i))continue;let o=this.cloneSnapshotValue(e[i]);o!==void 0&&(t[i]=o)}let n=e.$flow;if(n!=null)try{t.$flow=this.cloneSnapshotValue(n)??{}}catch{t.$flow={}}return t}cloneSnapshotValue(e){if(typeof e!="function")try{return JSON.parse(JSON.stringify(e,(t,n)=>{if(typeof n=="bigint")return String(n);if(typeof n!="function")return n}))}catch{return}}mergeCtxChanges(e,t){if(t){t.$body!==void 0&&(e.$body=t.$body),t.$query!==void 0&&(e.$query=t.$query),t.$params!==void 0&&(e.$params=t.$params),t.$data!==void 0&&(e.$data=t.$data),t.$error!==void 0&&(e.$error=t.$error),t.$statusCode!==void 0&&(e.$statusCode=t.$statusCode),t.$share!==void 0&&(e.$share=t.$share),t.$api!==void 0&&e.$api&&(t.$api.error&&(e.$api.error=t.$api.error),t.$api.response&&(e.$api.response=t.$api.response)),t.$flow!==void 0&&t.$flow!==null&&typeof t.$flow=="object"&&e.$flow!=null&&typeof e.$flow=="object"&&Object.assign(e.$flow,t.$flow);for(let[n,i]of Object.entries(t))n.startsWith("$")&&(n==="$body"||n==="$query"||n==="$params"||n==="$data"||n==="$error"||n==="$statusCode"||n==="$share"||n==="$api"||n==="$flow"||br.has(n)||n==="$env"||(e[n]=i));delete e.$pkgs}}spawnAndExecute(e,t,n,i,o){return(async()=>{let s=await this.pool.dispatch();if(o?.aborted){let c=new Error("Execution aborted after client disconnect");return c.code="ERR_EXECUTION_ABORTED",c.isAbort=!0,Promise.reject(c)}let a=`t_${++this.taskCounter}`,u=Date.now();return new Promise((c,d)=>{let l=!1,f=new AbortController,p=!1,h=()=>{let _=new Error("Execution aborted after client disconnect");return _.code="ERR_EXECUTION_ABORTED",_.isAbort=!0,_},g,m=()=>{if(!(l||p)){p=!0,f.abort(),this.cleanupResponseStream(a,h());try{s.worker.postMessage({type:"cancelTask",id:a})}catch{}g=setTimeout(()=>{l||(l=!0,clearTimeout($),b(),this.taskCancellers.delete(a),this.pool.unregisterTask(s,a),this.taskErrorTotal++,Q({event:"task_cancel_grace_terminate",id:a}),this.pool.terminateEntry(s),d(h()))},Pi),g.unref?.()}};this.taskCancellers.set(a,m);let y=()=>m(),b=()=>{o?.removeEventListener("abort",y)};o&&o.addEventListener("abort",y,{once:!0});let $=setTimeout(()=>{if(l)return;l=!0,g&&clearTimeout(g),f.abort();let _=new Error(`Script execution timed out after ${i}ms`);this.cleanupResponseStream(a,_),this.taskCancellers.delete(a),b(),this.pool.unregisterTask(s,a),this.taskTimeoutTotal++,Q({event:"task_timeout",id:a,timeoutMs:i}),this.pool.terminateEntry(s),_.code="ERR_SCRIPT_EXECUTION_TIMEOUT",_.isTimeout=!0,d(_)},i);this.pool.registerTask(s,a,{abortController:f,onResult:_=>{if(!l){if(l=!0,clearTimeout($),g&&clearTimeout(g),this.taskCancellers.delete(a),b(),this.cleanupResponseStream(a),this.pool.unregisterTask(s,a),this.recordTaskDuration(Date.now()-u),p){f.abort(),this.taskErrorTotal++,d(h());return}if(_.success){this.taskDoneTotal++,Q({event:"task_done",id:a,ok:!0});let T={value:_.value,valueAbsent:_.valueAbsent===!0,ctxChanges:_.ctxChanges};_.shortCircuit&&(T.shortCircuit=!0),c(T)}else{this.taskErrorTotal++,Q({event:"task_done",id:a,ok:!1,message:_.error?.message});let T=new Error(_.error?.message||"Handler execution failed");T.statusCode=_.error?.statusCode,T.code=_.error?.code,T.details=_.error?.details,_.error?.stack&&(T.stack=_.error.stack),_.ctxChanges&&(T.ctxChanges=_.ctxChanges),this.cleanupResponseStream(a,T),d(T)}}},onIoCall:_=>{if(l)return;let T=f.signal;_.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(_,n),s.worker,_.callId,T):_.type==="transactionCall"?this.handleIoCall(()=>this.execTransactionCall(_,n,s.worker),s.worker,_.callId,T):_.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(_,n),s.worker,_.callId,T):_.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(_,n),s.worker,_.callId,T):_.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(_,n),s.worker,_.callId,T):_.type==="storageCall"?this.handleIoCall(()=>this.execStorageCall(_,n,s.worker),s.worker,_.callId,T):_.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall(_,n),s.worker,_.callId,T):_.type==="resCall"&&this.handleIoCall(()=>this.execResCall(_,n),s.worker,_.callId,T)}}),s.worker.postMessage({type:e,id:a,...t}),o?.aborted&&m()})})()}postAbortedCallError(e,t){try{e.postMessage({type:"callError",callId:t,error:JSON.stringify({__userThrow:!0,message:"Execution aborted after client disconnect",code:"ERR_EXECUTION_ABORTED"})})}catch{}}async handleIoCall(e,t,n,i){if(i?.aborted){this.postAbortedCallError(t,n);return}try{let o=await(i?An.run(i,e):e());if(i?.aborted){this.postAbortedCallError(t,n);return}try{t.postMessage({type:"callResult",callId:n,result:Pn(o)})}catch{}}catch(o){if(i?.aborted){this.postAbortedCallError(t,n);return}try{let s={__userThrow:!0,message:o.message,statusCode:o.statusCode,code:o.errorCode??o.code,details:o.details,messages:o.messages};t.postMessage({type:"callError",callId:n,error:JSON.stringify(s)})}catch{}}}async execRepoCall(e,t){let n=JSON.parse(e.argsJson),i=e.access==="secure"?t?.$repos?.secure?.[e.table]:t?.$repos?.[e.table];if(!i||typeof i[e.method]!="function"){let o=e.access==="secure"?"secure.":"";throw new Error(`Repo method not found: ${o}${e.table}.${e.method}`)}return i[e.method](...n)}async execTransactionCall(e,t,n){let o=JSON.parse(e.argsJson||"[]").map(a=>a?.__fnRef&&typeof a.__fnRef=="string"?(...u)=>this.invokeRuntimeCallback(n,e.id,a.__fnRef,u):a)[0];if(typeof o!="function")throw new Error("$transaction.run requires a callback");let s=t?.$transaction?.run;if(typeof s!="function")throw new Error("$transaction is not available");return await s.call(t.$transaction,o)}async execHelpersCall(e,t){let n=JSON.parse(e.argsJson),i=e.name.split("."),o=t?.$helpers;for(let s of i)o=o?.[s];if(typeof o!="function")throw new Error(`Helper not found: ${e.name}`);return o(...n)}async execSocketCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$socket?.[e.method];if(typeof i!="function")throw new Error(`Socket method not found: ${e.method}`);return i(...n)}async execCacheCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$cache?.[e.method];if(typeof i!="function")throw new Error(`Cache method not found: ${e.method}`);return i(...n)}async execStorageCall(e,t,n){let i=this.parseStorageArgs(e.argsJson,n,e.id),o=t?.$storage?.[e.method];if(typeof o!="function")throw new Error(`Storage method not found: ${e.method}`);return o(...i)}parseStorageArgs(e,t,n){return JSON.parse(e,(i,o)=>{if(o?.__fnRef&&typeof o.__fnRef=="string"){let s=o.__fnRef;return(...a)=>this.invokeRuntimeCallback(t,n,s,a)}return o})}invokeRuntimeCallback(e,t,n,i){let o=`rtcb_${++this.runtimeCallbackCounter}`;return new Promise((s,a)=>{let u=setTimeout(()=>{d(),a(new Error(`Runtime callback timed out: ${n}`))},3e4),c=l=>{if(!(l?.type!=="runtimeCallbackResult"||l.callId!==o)){if(d(),l.error){a(new Error(l.error));return}s(l.value)}},d=()=>{clearTimeout(u),e.off("message",c)};e.on("message",c),e.postMessage({type:"invokeRuntimeCallback",id:t,callId:o,callbackId:n,argsJson:JSON.stringify(i)})})}async execDispatchCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$trigger;if(typeof i!="function")throw new Error("$trigger is not available");return i(...n)}cancelTask(e){this.taskCancellers.get(e)?.()}async execResCall(e,t){if(e.method==="streamStart"){let s=JSON.parse(e.argsJson||"[]")[1]||{},a=t?.$res?.stream;if(typeof a!="function")throw new Error("Response method not found: stream");let u=new $r.PassThrough,c={stream:u};this.responseStreams.set(e.id,c);let d=t?.$res;if(d&&typeof d.once=="function"){let f=()=>{d.writableEnded!==!0&&this.cancelTask(e.id)};d.once("close",f),c.closeCleanup=()=>{typeof d.off=="function"?d.off("close",f):typeof d.removeListener=="function"&&d.removeListener("close",f)}}let l=a.call(t.$res,u,s);return l&&typeof l.catch=="function"&&l.catch(()=>{}),!0}if(e.method==="streamChunk"){let o=this.responseStreams.get(e.id);if(!o)throw new Error(`Response stream not found: ${e.id}`);let s=Buffer.from(e.chunk||"","base64");return o.stream.write(s)||await new Promise((a,u)=>{let c=()=>{l(),a()},d=f=>{l(),u(f)},l=()=>{o.stream.off("drain",c),o.stream.off("error",d)};o.stream.once("drain",c),o.stream.once("error",d)}),!0}if(e.method==="streamEnd"){let o=this.responseStreams.get(e.id);return o&&(o.closeCleanup?.(),o.stream.end(),this.responseStreams.delete(e.id)),!0}if(e.method==="streamError"){let o=this.responseStreams.get(e.id);if(o){o.closeCleanup?.();let s=e.error?.message||"Response stream failed";o.stream.destroy(new Error(s)),this.responseStreams.delete(e.id)}return!0}let n=JSON.parse(e.argsJson||"[]"),i=t?.$res?.[e.method];if(typeof i!="function")throw new Error(`Response method not found: ${e.method}`);return i.apply(t.$res,n)}cleanupResponseStream(e,t){let n=this.responseStreams.get(e);n&&(this.responseStreams.delete(e),n.closeCleanup?.(),t?n.stream.destroy(t):n.stream.end())}toWorkerCodeBlock(e){return{code:e.code,sourceCode:e.sourceCode,scriptLanguage:e.scriptLanguage,type:e.type}}async run(e,t,n,i={}){let o=Math.max(1,Math.trunc(Number(n)||3e4)),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),u=this.createSnapshot(t);Q({event:"isolated_run_start",timeoutMs:o,codeLen:e?.length??0});let c;try{let d={code:e,sourceCode:i.sourceCode??e,pkgSources:a,snapshot:u,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};c=await this.spawnAndExecute("execute",d,t,o)}catch(d){let l=d;if(Q({event:"isolated_run_error",message:l.message,code:l.code,isTimeout:!!l.isTimeout}),l.code==="ERR_EXECUTION_ABORTED"||l.isAbort)throw l;if(l.isTimeout||l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new me(o,e);let f=l.statusCode??(typeof l.status=="number"?l.status:void 0);throw xe.createException(l.errorPath,f,l.message||"Unknown error",e,l.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),Q({event:"isolated_run_ok"}),c.valueAbsent?void 0:c.value}async runBatch(e,t,n,i={}){let o=Math.max(1,Math.trunc(Number(n)||3e4)),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),u=this.createSnapshot(t);Q({event:"isolated_batch_start",timeoutMs:o,blocks:e.length});let c;try{let l={codeBlocks:e.map(f=>this.toWorkerCodeBlock(f)),pkgSources:a,snapshot:u,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};c=await this.spawnAndExecute("executeBatch",l,t,o,i.signal)}catch(d){let l=d;if(Q({event:"isolated_batch_error",message:l.message,code:l.code,isTimeout:!!l.isTimeout}),l.ctxChanges&&this.mergeCtxChanges(t,l.ctxChanges),l.code==="ERR_EXECUTION_ABORTED"||l.isAbort)throw l;if(l.isTimeout||l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new me(o,"(batch execution)");let f=l.statusCode??(typeof l.status=="number"?l.status:void 0);throw xe.createException(l.errorPath,f,l.message||"Unknown error","(batch execution)",l.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),Q({event:"isolated_batch_ok"}),{value:c.valueAbsent?void 0:c.value,shortCircuit:c.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,s)=>o-s),i=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[i]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((i,o)=>i+o,0)/t.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),maxHeapRatio:Math.max(0,...e.workers.map(i=>i.lastHeapRatio||0))}}};var ve=ue(require("typescript")),Rt={oauth_config_definition:"",route_handler_definition:"logic",pre_hook_definition:"code",post_hook_definition:"code",bootstrap_script_definition:"logic",websocket_definition:"connectionHandlerScript",websocket_event_definition:"handlerScript"};function ji(r){return ee.getLegacyField(r)}function Bi(r){return ee.isScriptTable(r)}function Li(r){return ee.normalizeLanguage(r)}var en=class{getLegacyField(e){return Rt[e]}isScriptTable(e){return e in Rt}normalizeLanguage(e){return e==="javascript"?"javascript":"typescript"}compileSource(e,t){if(e==null||e==="")return null;let n=String(e),o=this.normalizeLanguage(t)==="javascript"?n:this.transpileTypeScript(n);return this.assertExecutableJavaScript(o),o}isExecutableJavaScript(e){if(!e)return!1;try{return this.assertExecutableJavaScript(e),!0}catch{return!1}}normalizeRecord(e,t){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let n={...t},i=this.getLegacyField(e);return i&&(n.sourceCode===void 0||n.sourceCode===null||n.sourceCode==="")&&n[i]!==void 0&&(n.sourceCode=n[i]),n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage),i&&i in n&&delete n[i],n}normalizePatch(e,t,n){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let i=this.getLegacyField(e),o=Object.prototype.hasOwnProperty.call(t,"sourceCode")||(i?Object.prototype.hasOwnProperty.call(t,i):!1),s=Object.prototype.hasOwnProperty.call(t,"scriptLanguage");if(!o&&!s)return t;let a=o?t.sourceCode??(i?t[i]:void 0):n?.sourceCode??(i&&n?n[i]:void 0),u=s?t.scriptLanguage:n?.scriptLanguage,c={...t};return o&&(c.sourceCode=a??null),c.scriptLanguage=this.normalizeLanguage(u),c.compiledCode=this.compileSource(a,c.scriptLanguage),i&&i in c&&delete c[i],c}getExecutableScript(e){return this.resolveExecutableScript(e).code}resolveExecutableScript(e){if(!e||typeof e!="object")return{code:null,compiledCode:null,shouldPersistCompiledCode:!1};if(typeof e.sourceCode=="string"&&e.sourceCode!==""){let n=this.compileSource(e.sourceCode,e.scriptLanguage);return{code:n,compiledCode:n,shouldPersistCompiledCode:n!==e.compiledCode}}let t=Object.keys(Rt).find(n=>Rt[n]in e);if(t){let n=e[Rt[t]];if(typeof n=="string"&&n!==""){let i=this.compileSource(n,e.scriptLanguage);return{code:i,compiledCode:i,shouldPersistCompiledCode:i!==e.compiledCode}}}return typeof e.compiledCode=="string"&&e.compiledCode!==""&&this.isExecutableJavaScript(e.compiledCode)?{code:e.compiledCode,compiledCode:e.compiledCode,shouldPersistCompiledCode:!1}:{code:null,compiledCode:null,shouldPersistCompiledCode:!1}}normalizeFlowStepScriptConfig(e){if(!e||typeof e!="object")return e;let t=e.type;if(t!=="script"&&t!=="condition")return e;let n={...e},i=e.config;if(typeof i=="string")try{i=JSON.parse(i)}catch{return e}let o=i&&typeof i=="object"?i:{};n.sourceCode=n.sourceCode??o.sourceCode??o.code??null,n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage??o.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage);let s={...o};return delete s.sourceCode,delete s.scriptLanguage,delete s.compiledCode,delete s.code,{...n,config:typeof e.config=="string"?JSON.stringify(s):s}}repairContract(e){let t=this.normalizeLanguage(e?.scriptLanguage),n=e?.sourceCode??null,i=this.compileSource(n,t);return{sourceCode:n,scriptLanguage:t,code:i,compiledCode:i,shouldPersistCompiledCode:i!==e?.compiledCode}}transpileTypeScript(e){let t=ve.default.transpileModule(e,{compilerOptions:{target:ve.default.ScriptTarget.ES2022,module:ve.default.ModuleKind.CommonJS,importsNotUsedAsValues:ve.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),n=t.diagnostics?.find(i=>i.category===ve.default.DiagnosticCategory.Error);if(n)throw new Error(ve.default.flattenDiagnosticMessageText(n.messageText,`
3
3
  `));return t.outputText.trimEnd()}assertExecutableJavaScript(e){e&&new Function(`return (async () => {
4
4
  "use strict";
5
5
  ${e}
6
- });`)}},re=new rn;function qi(r,e){return re.compileSource(r,e)}function zi(r){return re.isExecutableJavaScript(r)}function Vi(r,e){return re.normalizeRecord(r,e)}function Hi(r,e,t){return re.normalizePatch(r,e,t)}function Gi(r){return re.getExecutableScript(r)}function Yi(r){return re.resolveExecutableScript(r)}function Xi(r){return re.normalizeFlowStepScriptConfig(r)}var Nn=require("node:fs"),gi=require("node:path");var Wn=require("mongodb");Je();function Ae(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function Y(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!Ae(r)&&(r.foreignKeyColumn||r.propertyName)||null}function U(r){return r.foreignKeyColumn||r.mappedBy||r.propertyName||null}function ce(r){if(!r||typeof r!="object")return r;if(r instanceof Wn.ObjectId)return r.toString();if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return r.map(t=>ce(t));if("buffer"in r&&r.buffer&&typeof r.buffer=="object"&&Object.keys(r.buffer).length===12)try{let t=r.buffer,n=Object.keys(t).sort((o,i)=>parseInt(o)-parseInt(i)).map(o=>t[o]);return new Wn.ObjectId(Buffer.from(n)).toString()}catch{}let e={};for(let[t,n]of Object.entries(r))e[t]=n&&typeof n=="object"&&!(n instanceof Buffer)?ce(n):n;return e}function pe(r,e){if(e.type!=="many-to-many")return null;let t=e.targetTableName||e.targetTable;if(!t)return null;if(e.mappedBy){let a=t,u=e.mappedBy,c=r,d=e.junctionTableName||Mt(a,u,c);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:d,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:c};let l=Et(a,u,c);return{junctionName:d,selfColumn:l.targetColumn,otherColumn:l.sourceColumn,owningTable:a,inverseTable:c}}let n=r,o=t,i=e.junctionTableName||Mt(n,e.propertyName,o);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:i,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:o};let s=Et(n,e.propertyName,o);return{junctionName:i,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:o}}async function At(r,e,t,n){if(!r)return{scalarFields:[],relations:[]};let o=r.tables?.get(e);if(!o)return{scalarFields:[],relations:[]};let i=new Map;for(let c of t)if(c==="*")i.has("")||i.set("",[]),i.get("").push(c);else if(c.includes(".")){let d=c.split("."),l=d[0],f=d.slice(1).join(".");i.has(l)||i.set(l,[]),i.get(l).push(f)}else o.relations?.some(l=>l.propertyName===c)?i.has(c)||i.set(c,["_id"]):(i.has("")||i.set("",[]),i.get("").push(c));if(n&&typeof n=="object")for(let[c,d]of Object.entries(n)){if(i.has(c))continue;let l=d&&typeof d=="object"&&d.fields!=null?Array.isArray(d.fields)?d.fields:String(d.fields).split(",").map(f=>f.trim()).filter(Boolean):["*"];i.set(c,l)}let s=[],a=[],u=i.get("")||[];for(let c of u)if(c==="*"){if(o.columns)for(let d of o.columns)s.includes(d.name)||s.push(d.name);if(o.relations)for(let d of o.relations)i.has(d.propertyName)||i.set(d.propertyName,["_id"])}else o.columns?.some(l=>l.name===c)&&!s.includes(c)&&s.push(c);for(let[c,d]of i.entries()){if(c==="")continue;let l=o.relations?.find(g=>g.propertyName===c);if(!l)continue;let f="",p="",h=!1;l.type==="many-to-one"||l.type==="one-to-one"?Ae(l)?(f="_id",p=U(l)||l.propertyName,h=!0):(f=Y(l)||l.propertyName,p="_id",h=!1):l.type==="one-to-many"?(f="_id",p=U(l)||l.propertyName,h=!0):l.type==="many-to-many"&&(l.mappedBy?(f="_id",p=l.mappedBy,h=!0):(f=l.propertyName,p="_id",h=!1));let y=l.type==="one-to-many"||l.type==="many-to-many";a.push({propertyName:c,targetTable:l.targetTableName,localField:f,foreignField:p,type:y?"many":"one",isInverse:h,nestedFields:d})}return{scalarFields:s,relations:a}}var sn=fe(require("fs")),Un=fe(require("path"));var Zi=new RegExp("\\p{Mark}","gu");function jr(r){return r==null?"":String(r).normalize("NFKD").replace(Zi,"").toLowerCase()}function Kn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=jr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function on(){return`function() {
7
- var M = ${Kn()};
6
+ });`)}},ee=new en;function Di(r,e){return ee.compileSource(r,e)}function Wi(r){return ee.isExecutableJavaScript(r)}function Ki(r,e){return ee.normalizeRecord(r,e)}function qi(r,e,t){return ee.normalizePatch(r,e,t)}function Ui(r){return ee.getExecutableScript(r)}function Qi(r){return ee.resolveExecutableScript(r)}function Ji(r){return ee.normalizeFlowStepScriptConfig(r)}var xn=require("node:fs"),li=require("node:path");var Bn=require("mongodb");Ke();function Ie(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function z(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!Ie(r)&&(r.foreignKeyColumn||r.propertyName)||null}function K(r){return r.foreignKeyColumn||r.mappedBy||r.propertyName||null}function te(r){if(!r||typeof r!="object")return r;if(r instanceof Bn.ObjectId)return r.toString();if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return r.map(t=>te(t));if("buffer"in r&&r.buffer&&typeof r.buffer=="object"&&Object.keys(r.buffer).length===12)try{let t=r.buffer,n=Object.keys(t).sort((i,o)=>parseInt(i)-parseInt(o)).map(i=>t[i]);return new Bn.ObjectId(Buffer.from(n)).toString()}catch{}let e={};for(let[t,n]of Object.entries(r))e[t]=n&&typeof n=="object"&&!(n instanceof Buffer)?te(n):n;return e}function Ne(r,e){if(e.type!=="many-to-many")return null;let t=e.targetTableName||e.targetTable;if(!t)return null;if(e.mappedBy){let a=t,u=e.mappedBy,c=r,d=e.junctionTableName||xt(a,u,c);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:d,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:c};let l=vt(a,u,c);return{junctionName:d,selfColumn:l.targetColumn,otherColumn:l.sourceColumn,owningTable:a,inverseTable:c}}let n=r,i=t,o=e.junctionTableName||xt(n,e.propertyName,i);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:o,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:i};let s=vt(n,e.propertyName,i);return{junctionName:o,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:i}}async function It(r,e,t,n){if(!r)return{scalarFields:[],relations:[]};let i=r.tables?.get(e);if(!i)return{scalarFields:[],relations:[]};let o=new Map;for(let c of t)if(c==="*")o.has("")||o.set("",[]),o.get("").push(c);else if(c.includes(".")){let d=c.split("."),l=d[0],f=d.slice(1).join(".");o.has(l)||o.set(l,[]),o.get(l).push(f)}else i.relations?.some(l=>l.propertyName===c)?o.has(c)||o.set(c,["_id"]):(o.has("")||o.set("",[]),o.get("").push(c));if(n&&typeof n=="object")for(let[c,d]of Object.entries(n)){if(o.has(c))continue;let l=d&&typeof d=="object"&&d.fields!=null?Array.isArray(d.fields)?d.fields:String(d.fields).split(",").map(f=>f.trim()).filter(Boolean):["*"];o.set(c,l)}let s=[],a=[],u=o.get("")||[];for(let c of u)if(c==="*"){if(i.columns)for(let d of i.columns)s.includes(d.name)||s.push(d.name);if(i.relations)for(let d of i.relations)o.has(d.propertyName)||o.set(d.propertyName,["_id"])}else i.columns?.some(l=>l.name===c)&&!s.includes(c)&&s.push(c);for(let[c,d]of o.entries()){if(c==="")continue;let l=i.relations?.find(m=>m.propertyName===c);if(!l)continue;let f="",p="",h=!1;l.type==="many-to-one"||l.type==="one-to-one"?Ie(l)?(f="_id",p=K(l)||l.propertyName,h=!0):(f=z(l)||l.propertyName,p="_id",h=!1):l.type==="one-to-many"?(f="_id",p=K(l)||l.propertyName,h=!0):l.type==="many-to-many"&&(l.mappedBy?(f="_id",p=l.mappedBy,h=!0):(f=l.propertyName,p="_id",h=!1));let g=l.type==="one-to-many"||l.type==="many-to-many";a.push({propertyName:c,targetTable:l.targetTableName,localField:f,foreignField:p,type:g?"many":"one",isInverse:h,nestedFields:d})}return{scalarFields:s,relations:a}}var nn=ue(require("fs")),Dn=ue(require("path"));var zi=new RegExp("\\p{Mark}","gu");function Mr(r){return r==null?"":String(r).normalize("NFKD").replace(zi,"").toLowerCase()}function Ln(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=Mr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function tn(){return`function() {
7
+ var M = ${Ln()};
8
8
  function foldStr(s) {
9
9
  if (s == null) return '';
10
10
  s = String(s);
@@ -49,5 +49,5 @@ ${e}
49
49
  }
50
50
  }
51
51
  return true;
52
- }`}var Br="mongo-fold-text-search.body.txt",qe=null;function eo(){let r=[Un.join(__dirname,Br),Un.join(process.cwd(),"dist","kernel","query","utils",Br)];for(let e of r)try{if(sn.existsSync(e))return sn.readFileSync(e,"utf8")}catch{}return null}function an(){if(qe!==null)return qe;let r=eo();return r?(qe=r,qe):(qe=on(),qe)}var Se=require("mongodb");function W(r,e,t,n){if(t==="_id"){if(n instanceof Se.ObjectId)return n;if(typeof n=="string")try{return new Se.ObjectId(n)}catch{return n}return n}let o=r?.tables?.get(e);if(!o){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new Se.ObjectId(n)}catch{return n}return n}if(!o.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new Se.ObjectId(n)}catch{return n}return n}let i=o.columns.find(s=>s.name===t);if(!i){if(o.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof n=="string"&&n.length===24)try{return new Se.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new Se.ObjectId(n)}catch{return n}return n}if(n==null)return n;switch(i.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 Se.ObjectId(n)}catch{return n}return n;default:return n}}var ln="__mongoFoldTextTriples";function to(r){return r==="_id"?"$_id":`$${r}`}function ze(r,e,t,n){let o=to(e),i=r[ln]??[];i.push({ref:o,needle:t,mode:n}),r[ln]=i}function no(r){let e=r[ln];if(delete r[ln],!e?.length)return;let t=[];for(let i of e)t.push(i.ref,i.needle,i.mode);let n={$eq:[{$function:{body:an(),args:t,lang:"js"}},!0]},o=r.$expr;o?r.$expr={$and:[o,n]}:r.$expr=n}function Ve(r,e,t,n){let o={},i=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]||"";i&&a==="id"&&(a="_id");let c=W(r,u,a,s.value);switch(s.operator){case"=":o[a]=c;break;case"!=":o[a]={$ne:c};break;case">":o[a]={$gt:c};break;case"<":o[a]={$lt:c};break;case">=":o[a]={$gte:c};break;case"<=":o[a]={$lte:c};break;case"like":o[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(m=>m.trim()):[d]);let l=d.map(m=>W(r,u,a,m));o[a]={$in:l};break;case"not in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(m=>m.trim()):[f]);let p=f.map(m=>W(r,u,a,m));o[a]={$nin:p};break;case"is null":o[a]=null;break;case"is not null":o[a]={$ne:null};break;case"_contains":ze(o,a,String(c),"contains");break;case"_starts_with":ze(o,a,String(c),"starts");break;case"_ends_with":ze(o,a,String(c),"ends");break;case"_between":let h=s.value;if(typeof h=="string"&&(h=h.split(",").map(m=>m.trim())),Array.isArray(h)&&h.length===2){let m=W(r,u,a,h[0]),b=W(r,u,a,h[1]);o[a]={$gte:m,$lte:b}}break;case"_is_null":let y=c===!0||c==="true";o[a]=y?{$eq:null}:{$ne:null};break;case"_is_not_null":let g=c===!0||c==="true";o[a]=g?{$ne:null}:{$eq:null};break}}return no(o),o}function Lr(r,e,t){let o=r?.tables?.get?.(e)?.columns?.find(i=>i.name===t);return o?o.isNullable!==!1:!0}function cn(r,e,t,n,o,i){switch(o){case"_contains":ze(e,n,String(i),"contains");break;case"_starts_with":ze(e,n,String(i),"starts");break;case"_ends_with":ze(e,n,String(i),"ends");break;case"_eq":e[n]=W(r,t,n,i);break;case"_neq":{let l=W(r,t,n,i);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=i;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=i;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,i)};break;case"_gte":e[n]={$gte:W(r,t,n,i)};break;case"_lt":e[n]={$lt:W(r,t,n,i)};break;case"_lte":e[n]={$lte:W(r,t,n,i)};break;case"_is_null":let u=i===!0||i==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let c=i===!0||i==="true";e[n]=c?{$ne:null}:{$eq:null};break;case"_between":let d=i;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 ie(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 o of n)if(ie(o,e))return!0}}else if(t==="_not"){if(ie(n,e))return!0}else if(e.has(t))return!0;return!1}function X(r,e){if(!r||typeof r!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},n={},o=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(o.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 i=ie(r,o);return{fieldFilters:t,relationFilters:n,hasRelations:i}}jt();Bt();var pn="__mongoFoldTextTriples";function Pe(r,e){if(!r)return{};let t={};return Lt(r,t,e),Ce(t),t}function uo(r,e){if(!r)return{};let t={};return qn(r,t,e),Ce(t),t}function me(r,e,t){if(!e)return{};let n=new se,{node:o}=he(e,t,r,n);return Pe(o,{metadata:r,rootTable:t})}function gn(r,e,t){if(!e)return{};let n=new se,{node:o}=he(e,t,r,n);return uo(o,{metadata:r,rootTable:t})}function Lt(r,e,t){switch(r.kind){case"true":return;case"false":ye(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let o=r.children.map(i=>{let s={};return Lt(i,s,t),Ce(s),s}).filter(i=>Object.keys(i).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}ye(e,...o);return}case"or":{let o=r.children.map(s=>{let a={};return Lt(s,a,t),Ce(a),a}).filter(s=>Object.keys(s).length>0);if(o.length===0)return;let i=e.$or;e.$or=i?[...i,...o]:o;return}case"not":{let n={};Lt(r.child,n,t),Ce(n);let o=e.$nor;e.$nor=o?[...o,n]:[n];return}case"compare":Qr(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 Qr(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 o=i=>W(t.metadata,t.rootTable,n,i);switch(r.op){case"eq":te(e,n,o(r.value));return;case"neq":{let i=o(r.value);zn(t,n)?ye(e,{[n]:{$ne:null}},{[n]:{$ne:i}}):te(e,n,{$ne:i});return}case"gt":te(e,n,{$gt:o(r.value)});return;case"gte":te(e,n,{$gte:o(r.value)});return;case"lt":te(e,n,{$lt:o(r.value)});return;case"lte":te(e,n,{$lte:o(r.value)});return;case"in":{let i=Ur(r.value).map(o);te(e,n,{$in:i});return}case"not_in":{let i=Ur(r.value).map(o);zn(t,n)?ye(e,{[n]:{$ne:null}},{[n]:{$nin:i}}):te(e,n,{$nin:i});return}case"between":{let i=Array.isArray(r.value)?r.value:typeof r.value=="string"?r.value.split(",").map(s=>s.trim()):null;Array.isArray(i)&&i.length===2&&te(e,n,{$gte:o(i[0]),$lte:o(i[1])});return}case"is_null":te(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":Jn(e,n,String(r.value),"contains");return;case"starts_with":Jn(e,n,String(r.value),"starts");return;case"ends_with":Jn(e,n,String(r.value),"ends");return}}function qn(r,e,t){switch(r.kind){case"true":ye(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let o=r.children.map(s=>{let a={};return qn(s,a,t),Ce(a),a}).filter(s=>Object.keys(s).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}let i=e.$or;e.$or=i?[...i,...o]:o;return}case"or":{let o=r.children.map(i=>{let s={};return qn(i,s,t),Ce(s),s}).filter(i=>Object.keys(i).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}ye(e,...o);return}case"not":Lt(r.child,e,t);return;case"compare":fo(r,e,t);return;case"relation_exists":{te(e,r.joinId,r.negate?{$ne:null}:{$eq:null});return}}}function fo(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"){te(e,n,r.value===!0?{$ne:null}:{$eq:null});return}let o={};Qr(r,o,t),Ce(o);let i={$nor:[o]};zn(t,n)?ye(e,i,{[n]:{$ne:null}}):ye(e,i)}function te(r,e,t){r[e]===void 0?r[e]=t:(ye(r,{[e]:r[e]},{[e]:t}),delete r[e])}function ye(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(o=>o.name===e);return n?n.isNullable!==!1:!0}function Ur(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function po(r){return r==="_id"?"$_id":`$${r}`}function Jn(r,e,t,n){let o=po(e),i=r[pn]??[];i.push({ref:o,needle:t,mode:n}),r[pn]=i}function Ce(r){let e=r[pn];if(delete r[pn],!e?.length)return;let t=[];for(let i of e)t.push(i.ref,i.needle,i.mode);let n={$eq:[{$function:{body:an(),args:t,lang:"js"}},!0]},o=r.$expr;o?r.$expr={$and:[o,n]}:r.$expr=n}async function be(r,e,t,n){if(!r||typeof r!="object")return{};let o=t?.tables?.get(e);if(!o)return me(t,r,e);let i=new Set((o.relations||[]).map(c=>c.propertyName));if(!ie(r,i))return me(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>be(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=>be(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}=X(r,o),u=[];if(s&&Object.keys(s).length>0){let c=me(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 go(c,d,e,o,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 o=t?.tables?.get(e);if(!o)return gn(t,r,e);let i=new Set((o.relations||[]).map(c=>c.propertyName));if(!ie(r,i))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 be(r._not,e,t,n);let{fieldFilters:s,relationFilters:a}=X(r,o),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 yo(c,d,e,o,t,n);l&&Object.keys(l).length>0&&u.push(l)}return u.length===0?{}:u.length===1?u[0]:{$or:u}}async function go(r,e,t,n,o,i){let s=(n.relations||[]).find(c=>c.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=o?.tables?.get(a);return!a||!u?{}:s.type==="many-to-one"||s.type==="one-to-one"?ho(e,s,r,a,u,o,i):s.type==="one-to-many"?zr(e,s,t,a,u,o,i):s.type==="many-to-many"?Vr(e,s,t,a,u,o,i):{}}async function ho(r,e,t,n,o,i,s){let a=Y(e)||t,u=yn(r),c=mn(u);if(c!==null)return c?{[a]:null}:{[a]:{$ne:null}};let d=Yn(u);if(d!==null){let h=bn(d.value);if(d.op==="eq")return{[a]:h};if(d.op==="neq")return{[a]:{$ne:h}};if(d.op==="in")return{[a]:{$in:h}};if(d.op==="not_in")return{$and:[{[a]:{$nin:h}},{[a]:{$ne:null}}]}}let l=await hn(u,n,o,i,s);if(!l||Object.keys(l).length===0)return{};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(h=>h._id).filter(Boolean);return p.length===0?{__impossible__:!0}:{[a]:{$in:p}}}async function yo(r,e,t,n,o,i){let s=(n.relations||[]).find(c=>c.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=o?.tables?.get(a);if(!a||!u)return{};if(s.type==="many-to-one"||s.type==="one-to-one")return mo(e,s,r,a,u,o,i);if(s.type==="one-to-many"){let c=await zr(e,s,t,a,u,o,i);return qr(c)}if(s.type==="many-to-many"){let c=await Vr(e,s,t,a,u,o,i);return qr(c)}return{}}async function mo(r,e,t,n,o,i,s){let a=Y(e)||t,u=yn(r),c=mn(u);if(c!==null)return c?{[a]:{$ne:null}}:{[a]:null};let d=Yn(u);if(d!==null){let h=bn(d.value);if(d.op==="eq")return{$and:[{[a]:{$ne:h}},{[a]:{$ne:null}}]};if(d.op==="neq")return{[a]:h};if(d.op==="in")return{$and:[{[a]:{$nin:h}},{[a]:{$ne:null}}]};if(d.op==="not_in")return{[a]:{$in:h}}}let l=await hn(u,n,o,i,s);if(!l||Object.keys(l).length===0)return{[a]:null};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(h=>h._id).filter(Boolean);return p.length===0?{[a]:{$ne:null}}:{$and:[{[a]:{$nin:p}},{[a]:{$ne:null}}]}}async function zr(r,e,t,n,o,i,s){let a=U(e)||t,u=yn(r),c=mn(u);if(c!==null){let f=await Jr(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,o,i,s);if(!d||Object.keys(d).length===0)return{};let l=await Jr(s,n,a,d);return l.length===0?{__impossible__:!0}:{_id:{$in:l}}}async function Vr(r,e,t,n,o,i,s){let a=pe(t,e);if(!a)return{};let u=yn(r),c=mn(u);if(c!==null){let y=await Vn(s,a,n,null);return c?y.length===0?{}:{_id:{$nin:y}}:y.length===0?{__impossible__:!0}:{_id:{$in:y}}}let d=Yn(u);if(d!==null){let y=bn(d.value),g=Array.isArray(y)?y:[y],m=await Vn(s,a,n,{_id:{$in:g}});return m.length===0?{__impossible__:!0}:{_id:{$in:m}}}let l=await hn(u,n,o,i,s);if(!l||Object.keys(l).length===0)return{};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(Boolean);if(p.length===0)return{__impossible__:!0};let h=await Vn(s,a,n,{_id:{$in:p}});return h.length===0?{__impossible__:!0}:{_id:{$in:h}}}async function hn(r,e,t,n,o){let i=new Set((t?.relations??[]).map(s=>s.propertyName));return ie(r,i)?be(r,e,n,o):me(n,r,e)}async function Jr(r,e,t,n){let o=await r.collection(e).find(n,{projection:{[t]:1}}).toArray(),i=new Set,s=[];for(let a of o){let u=a[t];if(u==null)continue;let c=String(u);i.has(c)||(i.add(c),s.push(u))}return s}function qr(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 o=null;n&&t&&(o=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(d=>d._id).filter(Boolean));let i=o?{[e.otherColumn]:{$in:o}}:{},s=await r.collection(e.junctionName).find(i,{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 yn(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function mn(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 Dt(r,e,t,n){let o=await At(r,e,t),i=[],s={},a={};if(n&&typeof n=="object")for(let[p,h]of Object.entries(n))if(typeof h=="object"&&h!==null){let y=Object.keys(h)[0];y&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(y)?s[p]=h:a[p]=h}else s[p]=h;if(Object.keys(s).length>0){let p={};for(let[h,y]of Object.entries(s))if(typeof y=="object"&&y!==null)for(let[g,m]of Object.entries(y))cn(r,p,e,h,g,m);else p[h]=y;Object.keys(p).length>0&&i.push({$match:p})}let c=r?.tables?.get(e)?.relations||[],d=[];for(let[p,h]of Object.entries(a))if(!o.relations.some(g=>g.propertyName===p)){let g=c.find(m=>m.propertyName===p);if(g){let m="",b="";if(g.type==="many-to-one"||g.type==="one-to-one")m=Y(g)||g.propertyName,b="_id";else if(g.type==="one-to-many")m="_id",b=U(g)||g.propertyName;else if(g.type==="many-to-many")continue;let $=g.type==="one-to-many"||g.type==="many-to-many";d.push({propertyName:p,targetTable:g.targetTableName,localField:m,foreignField:b,type:$?"many":"one",nestedFields:[]})}}let l=[...o.relations,...d];for(let p of l){let h=a[p.propertyName],y=p.nestedFields&&p.nestedFields.length>0?await Dt(r,p.targetTable,p.nestedFields,h):h?await Dt(r,p.targetTable,["_id"],h):[];p.type==="one"&&y.length>0&&y.push({$limit:1}),i.push({$lookup:{from:p.targetTable,localField:p.localField,foreignField:p.foreignField,as:p.propertyName,pipeline:y.length>0?y:void 0}}),p.type==="one"&&(i.push({$unwind:{path:`$${p.propertyName}`,preserveNullAndEmptyArrays:!0}}),h&&(Ge(h)||i.push({$match:{[p.propertyName]:{$ne:null}}})))}let f=c.filter(p=>!l.some(h=>h.propertyName===p.propertyName));if(o.scalarFields.length>0||o.relations.length>0||f.length>0){let p={_id:1};for(let y of o.scalarFields)p[y]=1;for(let y of l)p[y.propertyName]=1,y.type==="one"&&y.localField&&y.localField!==y.propertyName&&(p[y.localField]=1);if(t.includes("*"))for(let y of f){if(y.type==="one-to-many"||y.type==="many-to-many")continue;y.type==="many-to-many"?p[y.propertyName]={$map:{input:`$${y.propertyName}`,as:"item",in:{_id:"$$item"}}}:p[y.propertyName]={$cond:{if:{$ne:[`$${y.propertyName}`,null]},then:{_id:`$${y.propertyName}`},else:null}}}i.push({$project:p})}return i}async function Hr(r,e,t,n,o){let i=r?.tables?.get(t),s=i?.relations||[],a=i?.columns||[],u=s.filter(d=>!o.some(l=>l.propertyName===d.propertyName)),c=n.length===a.length||n.length===0&&o.length===0;if(u.length>0||!c){let d={_id:1};for(let l of n)d[l]=1;for(let l of o)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 Ge(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ge(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ge(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ge(e));if("_not"in r)return Ge(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||Ge(t)))return!0}return!1}Xe();var Kt=require("mongodb");Xe();_n();async function wn(r,e,t){let n=new Map,o=0;async function i(){for(;o<r.length;){let u=o++,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},i);return await Promise.all(a),n}var le="__sourceId__",Fe="__targetId__",Ze="__enfyra_target__",Wt="__enfyra_top_n_documents__",et=class{constructor(e,t,n,o=new Re){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.executionBudget=o;this.pkField="_id"}chunkCount(e){return Math.ceil(e.length/ae)||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 o={...t};for(let i of n)o[i]=1;e.push({$project:o})}}appendTopNStages(e,t,n,o,i){e.push({$group:{_id:`$${t}`,[Wt]:{$topN:{sortBy:n,output:"$$ROOT",n:o+i}}}},{$project:{[Wt]:{$slice:[`$${Wt}`,o,i]}}},{$unwind:`$${Wt}`},{$replaceRoot:{newRoot:`$${Wt}`}})}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 o=n.field.split(".");if(o.length===1)t[o[0]]=n.order;else{let i=`__sort_${o.slice(0,-1).join("_")}`;t[`${i}.${o[o.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 o=n.startsWith("-"),i=o?n.slice(1):n;return{field:i==="id"?"_id":i,order:o?-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 o=Array.isArray(n)?n:n.split(",").map(c=>c.trim()).filter(Boolean),i=[{$match:t}],s=new Set;for(let c of o){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 h=l[p],y=this.normalizeMetadata()?.tables?.get(f);if(!y)break;let g=y.relations?.find($=>$.propertyName===h);if(!g)break;let m=g.targetTableName||g.targetTable,b=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(b)){s.add(b);let $=Y(g)||g.propertyName,_=p===0?null:`__sort_${l.slice(0,p).join("_")}`,T=_?`${_}.${$}`:$;i.push({$lookup:{from:m,localField:T,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}f=m}}let a=this.buildSortFromTokens(n);a&&i.push({$sort:a});let u={};for(let c of s)u[c]=0;return Object.keys(u).length>0&&i.push({$project:u}),i}toObjectId(e){try{return typeof e=="string"?new Kt.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof Kt.ObjectId||t instanceof Kt.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(o=>!o.field.includes("."));n.length!==0&&e.sort((o,i)=>{for(let s of n){let a=this.compareSortValues(o[s.field],i[s.field]);if(a!==0)return a*s.order}return this.compareSortValues(o._id,i._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},o=[];for(let i of this.parseSortTokens(t))i.field.includes(".")||n[i.field]===void 0&&(n[i.field]=1,o.push(i.field));return{projection:n,hiddenFields:o}}removeHiddenFields(e,t){if(t.length!==0)for(let n of e)for(let o of t)delete n[o]}keyOf(e){return e==null?"":e instanceof Kt.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:o}=Ye(e),i={},s=!1;if(n.includes("*")){s=!0;for(let f of t.relations||[])o.has(f.propertyName)||o.set(f.propertyName,["_id"])}else for(let f of n){let p=t.columns.find(h=>h.name===f);p?i[p.name]=1:t.relations?.find(y=>y.propertyName===f)&&!o.has(f)&&o.set(f,["_id"])}o.forEach((f,p)=>{let h=t.relations?.find(y=>y.propertyName===p);h&&(h.type==="many-to-one"||h.type==="one-to-one"&&!h.isInverse)&&(s||(i[Y(h)||h.propertyName]=1))}),s||(i._id=1);let a=[];o.forEach((f,p)=>{let h=t.relations?.find(b=>b.propertyName===p);if(!h)return;let y=h.targetTableName||h.targetTable;if(!y)return;let g,m;h.type==="many-to-one"||h.type==="one-to-one"?Ae(h)?(g="_id",m=U(h)||h.propertyName):(g=Y(h)||h.propertyName,m="_id"):h.type==="one-to-many"?(g="_id",m=U(h)||h.propertyName):h.type==="many-to-many"&&(h.isInverse?(g="_id",m=h.mappedBy):(g=h.propertyName,m="_id")),a.push({relationName:p,type:h.type,targetTable:y,fields:f,isInverse:h.isInverse,fkColumn:h.foreignKeyColumn,mappedBy:h.mappedBy,junctionTableName:h.junctionTableName,junctionSourceColumn:h.junctionSourceColumn,junctionTargetColumn:h.junctionTargetColumn,localField:g,foreignField:m})});let u=!s&&Object.keys(i).length===1&&i._id===1&&a.length===0,c=this.fieldRenamesByTable?.get(t.name)??[],d=[];if(!s&&c.length>0)for(let f of c)i[f.newName]===1&&i[f.oldName]!==1&&(i[f.oldName]=1,d.push(f.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:i,pendingRenames:c,hiddenFields:d}}}async fetchOwner(e,t,n,o){let i=o?.userFilter?me(this.normalizeMetadata(),o.userFilter,e):null,s=this.buildSortFromTokens(o?.userSort),a=await K(t,c=>{let d={_id:{$in:c}};i&&Object.keys(i).length>0&&Object.assign(d,i);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,o,i){let s=o.projection?{...o.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let a=this.uniqueValues(n.map(m=>this.toObjectId(m))),u=i?.userFilter?me(this.normalizeMetadata(),i.userFilter,e):null,c=i?.userLimit,d=i?.userPage,l=this.hasDottedSort(i?.userSort);if(c!==void 0&&c>0){let m=d?(d-1)*c:0;if(l)throw new Error(`Dotted sort is not supported for batch relation '${i?.relationName}'`);let b=this.buildStableSort(i?.userSort),$=await K(a,async _=>{let T={[t]:{$in:_}};u&&Object.keys(u).length>0&&Object.assign(T,u);let k=[{$match:T}];this.appendTopNStages(k,t,b,m,c),k.push({$sort:{[t]:1,...b}}),this.appendPartitionProjection(k,s,[t]);let R=await this.runQuery(()=>this.db.collection(e).aggregate(k).toArray());return this.applyReadFallback(R,o)});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 m=[],b=await wn(a,async $=>{let _={[t]:$};u&&Object.keys(u).length>0&&Object.assign(_,u);let T=this.buildSortAggregatePipeline(e,_,i.userSort);s&&T.push({$project:s});let k=await this.runQuery(()=>this.db.collection(e).aggregate(T).toArray());return this.applyReadFallback(k,o)},je);for(let $ of b.values())for(let _ of $)m.push(_);return{docs:m,groupKeyField:t,stats:{strategy:"per-parent-dotted-sort",roundtrips:a.length,concurrencyWaves:Math.ceil(a.length/je),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.length}}}let f={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(f,u);let p=this.buildSortFromTokens(i?.userSort)||{_id:1},h={projection:s,sort:p},y=await K(a,m=>this.runQuery(()=>this.db.collection(e).find({[t]:{$in:m},...u||{}},h).toArray())),g=this.applyReadFallback(y,o);return{docs:g,groupKeyField:t,stats:{strategy:"batch-in",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.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 o=n.projection?{projection:n.projection}:void 0,i=await K(t,s=>this.runQuery(()=>this.db.collection(e).find({_id:{$in:s}},o).toArray()));return this.applyReadFallback(i,n)}async fetchM2MTopK(e,t,n,o,i,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 m of e)u.set(this.keyOf(m),[]);let c=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1,d=!i&&this.m2mSortCanUseJunction(t.userSort),l=this.parseSortTokens(t.userSort).find(m=>m.field==="_id")?.order??1,f=this.buildStableSort(t.userSort),p=await K(e,async m=>{if(d){let _=[{$match:{[n.selfColumn]:{$in:m}}}];return this.appendTopNStages(_,n.selfColumn,{[n.otherColumn]:l},s,a),_.push({$sort:{[n.selfColumn]:1,[n.otherColumn]:l}},{$project:{_id:0,[le]:`$${n.selfColumn}`,[Fe]:`$${n.otherColumn}`}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(_).toArray())).map(k=>({sourceId:k[le],targetId:k[Fe]}))}let b=[{$match:{[n.selfColumn]:{$in:m}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ze}},{$unwind:`$${Ze}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ze}`,{[le]:`$${n.selfColumn}`,[Fe]:`$${n.otherColumn}`}]}}}];return i&&Object.keys(i).length>0&&b.push({$match:i}),this.appendTopNStages(b,le,f,s,a),b.push({$sort:{[le]:1,...f}}),b.push({$project:{_id:0,[le]:1,[Fe]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(b).toArray())).map(_=>({sourceId:_[le],targetId:_[Fe]}))});if(c){let m=new Map;for(let b of p){let $=this.keyOf(b.targetId);m.has($)||m.set($,{_id:b.targetId}),u.get(this.keyOf(b.sourceId))?.push(m.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 h=this.uniqueValues(p.map(m=>m.targetId)),y=await this.loadM2MTargets(t.targetTable,h,o),g=new Map(y.map(m=>[this.keyOf(m._id),m]));for(let m of p){let b=g.get(this.keyOf(m.targetId));b&&u.get(this.keyOf(m.sourceId))?.push(b)}return{grouped:u,docs:y,stats:{strategy:"m2m-partitioned-edge-loader",roundtrips:this.chunkCount(e)+(h.length>0?this.chunkCount(h):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+y.length,rowsDiscarded:0}}}async fetchM2MEdgeBatch(e,t,n,o,i){let s=new Map;for(let y of e)s.set(this.keyOf(y),[]);let a=!i&&this.m2mSortCanUseJunction(t.userSort),u=this.parseSortTokens(t.userSort).find(y=>y.field==="_id")?.order??1,c=this.buildStableSort(t.userSort),d=await K(e,async y=>{if(a)return(await this.runQuery(()=>this.db.collection(n.junctionName).find({[n.selfColumn]:{$in:y}},{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 g=[{$match:{[n.selfColumn]:{$in:y}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ze}},{$unwind:`$${Ze}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ze}`,{[le]:`$${n.selfColumn}`,[Fe]:`$${n.otherColumn}`}]}}}];return i&&Object.keys(i).length>0&&g.push({$match:i}),g.push({$sort:{[le]:1,...c}},{$project:{_id:0,[le]:1,[Fe]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(g).toArray())).map(b=>({sourceId:b[le],targetId:b[Fe]}))});if(o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1){let y=new Map;for(let g of d){let m=this.keyOf(g.targetId);y.has(m)||y.set(m,{_id:g.targetId}),s.get(this.keyOf(g.sourceId))?.push(y.get(m))}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(y=>y.targetId)),p=await this.loadM2MTargets(t.targetTable,f,o),h=new Map(p.map(y=>[this.keyOf(y._id),y]));for(let y of d){let g=h.get(this.keyOf(y.targetId));g&&s.get(this.keyOf(y.sourceId))?.push(g)}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,o,i){let s=n?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=pe(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?me(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,i,d,k,l)}let p=i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1&&!d,h=this.hasDottedSort(t.userSort);if(!h)return this.fetchM2MEdgeBatch(u,t,a,i,d);let y=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(y.length===0)return{grouped:c,docs:[],stats:{strategy:"m2m-batch",roundtrips:this.chunkCount(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:0}};let g=new Set,m=[];for(let k of y){let R=k[a.otherColumn];if(R==null)continue;let I=this.keyOf(R);g.has(I)||(g.add(I),m.push(R))}let b=[],$=new Map;if(p)b=m.map(k=>({_id:k})),this.sortDocsByPk(b);else{let k={_id:{$in:m}};d&&Object.keys(d).length>0&&Object.assign(k,d);let R;if(h){let I=this.buildSortAggregatePipeline(t.targetTable,k,t.userSort);i.projection&&I.push({$project:i.projection}),R=await this.runQuery(()=>this.db.collection(t.targetTable).aggregate(I).toArray())}else{let I=this.buildSortFromTokens(t.userSort)||{_id:1},E=this.projectionWithSortFields(i.projection,t.userSort),L={sort:I};E.projection&&(L.projection=E.projection),R=await K(m,S=>this.runQuery(()=>this.db.collection(t.targetTable).find({_id:{$in:S},...d||{}},L).toArray())),t.userSort?this.sortDocsInMemory(R,t.userSort):this.sortDocsByPk(R),this.removeHiddenFields(R,E.hiddenFields)}b=this.applyReadFallback(R,i)}for(let k of b)$.set(this.keyOf(k._id),k);let _=new Map;for(let k of y){let R=this.keyOf(k[a.selfColumn]),I=this.keyOf(k[a.otherColumn]);$.has(I)&&(_.has(I)||_.set(I,[]),_.get(I).push(R))}for(let k of b){let R=_.get(this.keyOf(k._id))||[];for(let I of R)c.get(I)?.push(k)}let T=p||m.length===0?0:this.chunkCount(m);return{grouped:c,docs:b,stats:{strategy:p?"m2m-junction-batch":"m2m-batch",roundtrips:this.chunkCount(u)+T,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:y.length+b.length}}}applyReadFallback(e,t){let n=t.pendingRenames??[];if(e.length===0||n.length===0)return e;let o=new Set(t.hiddenFields??[]);for(let i of e)for(let s of n)i[s.newName]===void 0&&i[s.oldName]!==void 0&&(i[s.newName]=i[s.oldName]),(o.has(s.oldName)||i[s.newName]!==void 0)&&delete i[s.oldName];return e}};async function $n(r,e,t,n,o=3,i=0,s,a,u,c){let d=await c?.getActiveFieldRenamesByTable?.(),l=new et(r,a,d);await new ke(l,n,u).execute(e,t,o,i,s)}async function er(r,e,t){let n=[],{db:o,metadata:i,dbType:s,debugLog:a}=t,u=i?.tables?.get(e.table),c=new Set((u?.relations??[]).map(S=>S.propertyName)),d=!!e.mongoRawFilter&&!!i&&ie(e.mongoRawFilter,c),l=e.plan,f=l?.filterTree&&!l.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&i&&d){let S=await be(e.mongoRawFilter,e.table,i,o);S&&Object.keys(S).length>0&&n.push({$match:S})}else if(f){let S=Pe(l.filterTree,{metadata:i,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=Ve(i,e.where,e.table,s);n.push({$match:S})}let p=e.plan,y=p?p.hasRelationSort:e.sort?.some(S=>{if(!S.field.includes("."))return!1;let N=S.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(A=>A.propertyName===N)??!1})??!1,g=()=>p?.sortItems?Co(p.sortItems):e.sort?So(e.sort):null,m=p?.sortItems?bo(p.sortItems):[],b=p?.sortItems?_o(p.sortItems):[],$=()=>{!p||m.length===0||wo(n,e.table,p.sortItems,i)},_=()=>{!p||b.length===0||$o(n,e.table,p.sortItems,i)},T=()=>{let S=[...m,...b];S.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(S.map(N=>[N,0]))})};if(!e.mongoFieldsExpanded){$(),_();let S=g();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 N=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:N,pipeline:n}:{results:Yr(N),pipeline:n}}let{scalarFields:k,relations:R}=e.mongoFieldsExpanded;if(!y){$(),_();let S=g();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 I=[];for(let S of R)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 Dt(i,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 Dt(i,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&&(tt(A)||n.push({$match:{[S.propertyName]:{$ne:null}}})))}else I.push(S);if(y){$(),_();let S=g();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(i,n,e.table,k,[...R]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let E=performance.now(),L=await r.aggregate(n).toArray();if(e.debugTrace?.dur("db_execute",E,{table:e.table}),e.mongoCountOnly)return{results:L,pipeline:n};if(I.length>0&&L.length>0){let S=e.deep||{},N=I.map(D=>{let w=i?.tables?.get(e.table)?.relations?.find(V=>V.propertyName===D.propertyName),C=S[D.propertyName],v=C?.fields!=null?Array.isArray(C.fields)?C.fields:String(C.fields).split(",").map(V=>V.trim()).filter(Boolean):D.nestedFields&&D.nestedFields.length>0?D.nestedFields:["_id"];return{relationName:D.propertyName,type:w?.type,targetTable:D.targetTable,fields:v,isInverse:w?.isInverse,mappedBy:w?.mappedBy,junctionTableName:w?.junctionTableName,junctionSourceColumn:w?.junctionSourceColumn,junctionTargetColumn:w?.junctionTargetColumn,localField:D.localField,foreignField:D.foreignField,userFilter:C?.filter,userSort:C?.sort,userLimit:C?.limit!==void 0?Number(C.limit):void 0,userPage:C?.page!==void 0?Number(C.page):void 0,nestedDeep:C?.deep}}),A=To(i);A&&await $n(o,L,N,A,3,0,e.table,i,e.debugTrace,t.mongoPhysicalMigrationService)}return{results:Yr(L),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 bo(r){return r.filter(e=>e.function==="count").map(tr)}function _o(r){return r.filter(e=>e.function==="max"||e.function==="min").map(nr)}function wo(r,e,t,n){let o=n?.tables?.get(e),i=o?.columns?.find(s=>s.isPrimary)?.name||(o?.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=U(a)||u;r.push({$lookup:{from:c,let:{localId:`$${i}`},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=pe(e,a);if(!l)continue;r.push({$lookup:{from:l.junctionName,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${l.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}})}}}}function $o(r,e,t,n){let o=n?.tables?.get(e),i=o?.columns?.find(s=>s.isPrimary)?.name||(o?.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(g=>g.isPrimary)?.name||(d?.columns?.some(g=>g.name==="_id")?"_id":"id"),f=s.aggregateField,p=f==="id"&&d?.columns?.some(g=>g.name==="_id")?"_id":f,h=nr(s),y=s.function==="min"?"$min":"$max";if(!(!a||!c||!f)){if(a.type==="one-to-many"){let g=U(a)||u;r.push({$lookup:{from:c,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${g}`,"$$localId"]}}},{$group:{_id:null,value:{[y]:`$${p}`}}}],as:h}}),r.push({$addFields:{[h]:{$arrayElemAt:[`$${h}.value`,0]}}});continue}if(a.type==="many-to-many"){let g=pe(e,a);if(!g)continue;let m=`${h}_junction`;r.push({$lookup:{from:g.junctionName,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${g.selfColumn}`,"$$localId"]}}},{$project:{_id:0,targetId:`$${g.otherColumn}`}}],as:m}}),r.push({$lookup:{from:c,let:{targetIds:`$${m}.targetId`},pipeline:[{$match:{$expr:{$in:[`$${l}`,"$$targetIds"]}}},{$group:{_id:null,value:{[y]:`$${p}`}}}],as:h}}),r.push({$addFields:{[h]:{$arrayElemAt:[`$${h}.value`,0]}}}),r.push({$project:{[m]:0}})}}}}function To(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(o=>({name:o.name,type:o.type})),relations:n.relations||[]}:null}:null}function So(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 Co(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 tt(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>tt(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>tt(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>tt(e));if("_not"in r)return tt(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||tt(t)))return!0}return!1}function Yr(r){return r.map(ce)}function Xr(r,e){let t=[],n=[],o=e?.tables?.get(r.rootTable);if(!o)return{scalarFields:t,relations:n};for(let i of r.nodes)if(i.kind==="wildcard")for(let s of o.columns||[])t.includes(s.name)||t.push(s.name);else i.kind==="scalar"?o.columns?.some(a=>a.name===i.name)&&!t.includes(i.name)&&t.push(i.name):i.kind==="relation"&&n.push(ko(i,o,e));return{scalarFields:t,relations:n}}function ko(r,e,t){let n=e.relations?.find(c=>c.propertyName===r.propertyName),o,i,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&Ae(n)?(o="_id",i=U(n)||r.propertyName,s=!0):(o=n&&Y(n)||r.propertyName,i="_id",s=!1):r.relationType==="one-to-many"?(o="_id",i=n&&U(n)||r.propertyName,s=!0):n?.mappedBy?(o="_id",i=n.mappedBy,s=!0):(o=r.propertyName,i="_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:o,foreignField:i,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 o of n)e.push(`${t.propertyName}.${o}`)}return e}He();Bt();jt();function Tn(r,e,t,n){let o={rootTable:e,nodes:[]};if(!r||r.length===0)return o;let i=t?.tables?.get(e);if(!i)return o;let s=i.columns?.some(l=>l.name==="_id"&&l.isPrimary),a=i.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("."),h=f.substring(0,p),y=f.substring(p+1);if(!i.relations?.some(m=>m.propertyName===h))continue;c.has(h)||c.set(h,[]),c.get(h).push(y)}else if(i.relations?.some(h=>h.propertyName===f))c.has(f)||c.set(f,[u]);else{if(!i.columns?.some(y=>y.name===f))continue;d.push(f)}}if(d.includes("*")){o.nodes.push({kind:"wildcard"});for(let l of i.relations||[])c.has(l.propertyName)||c.set(l.propertyName,[u])}else for(let l of d)o.nodes.push({kind:"scalar",name:l});for(let[l,f]of c.entries()){let p=i.relations?.find(g=>g.propertyName===l);if(!p)continue;let h=p.targetTableName||p.targetTable,y={kind:"relation",propertyName:l,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:h,children:ei(f,h,t)};if(p.type==="many-to-one"||p.type==="one-to-one"){let g=n.registerWithParent(e,l,t,"left",null,"data");y.joinId=g}o.nodes.push(y)}return o}function ei(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let o=n.columns?.some(d=>d.name==="_id"&&d.isPrimary),i=n.columns?.some(d=>d.name==="id"),s=o&&!i?"_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),h=l.substring(f+1);if(!n.relations?.some(g=>g.propertyName===p))continue;a.has(p)||a.set(p,[]),a.get(p).push(h)}else if(n.relations?.some(p=>p.propertyName===l))a.has(l)||a.set(l,[s]);else{if(!n.columns?.some(h=>h.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(h=>h.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}ge();ge();var Ro=new Set(["_and","_or","_not"]);function ti(r,e){return r?.tables?.get(e)??null}function Fo(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 xo(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 o=n.indexOf(".");return o<=0||o!==n.lastIndexOf(".")?null:{functionName:t,relationName:n.slice(0,o).trim(),fieldName:n.slice(o+1).trim()}}function ir(r,e,t,n){if(Fo(r,e,t)?.isEncrypted===!0)throw new x(`Encrypted field '${t}' on '${e}' cannot be used for ${n}.`)}function Be(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){for(let n of r)Be(n,e,t);return}for(let[n,o]of Object.entries(r)){if(Ro.has(n)){Be(o,e,t);continue}if(n.startsWith("_"))continue;let i=rr(t,e,n);if(i){let s=i.targetTableName||i.targetTable;s&&Be(o,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(o=>o.trim()).filter(Boolean);for(let o of n){let i=o.startsWith("-")?o.slice(1):o;if(!i)continue;let s=xo(i);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=i.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 q=class{plan(e){let{tableName:t,fields:n,filter:o,sort:i,page:s,limit:a,meta:u,metadata:c,dbType:d}=e,l=c?.tables?.get(t),f=new se,p=this.parseFields(n),h=null;p&&l&&(h=Tn(p,t,c,f));let y=!1,g=null;if(o&&l){Be(o,t,c);let S=he(o,t,c,f);g=S.node,y=S.hasRelationFilters}let m=this.parseSort(i);l&&Sn(m,t,c);let b=[],$=!1;for(let S of m){let N=S.startsWith("-"),A=N?S.substring(1):S,D=N?"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 _=this.parseLimit(a),T=this.parsePage(s),k=T!==void 0&&_!==void 0?(T-1)*_:void 0,R=this.parseMeta(u),I=R.includes("totalCount")||R.includes("*"),E=R.includes("filterCount")||R.includes("*"),L=f.getAll();return{table:t,dbType:d,rawFields:p,rawFilter:o??null,joins:L,sortItems:b,limit:_,offset:k,needsTotalCount:I,needsFilterCount:E,hasRelationFilters:y,hasRelationSort:$,filterTree:g,fieldTree:h}}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 x(`Sort field '${n}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let o=t.columns?.some(s=>s.name===n),i=n==="id"&&t.columns?.some(s=>s.name==="_id");if(!o&&!i)throw new x(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationAggregateSort(e,t,n,o){let i=n.match(/^_(count|max|min)\(([^)]+)\)$/);if(!i){if(/^_(count|max|min)\(/.test(n))throw new x(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName), _max(relationName.fieldName), or _min(relationName.fieldName).`);return null}let s=i[1],a=i[2].trim();if(s==="count"){let g=a;if(!g||g.includes("."))throw new x(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let m=t.relations?.find(b=>b.propertyName===g);if(!m)throw new x(`Sort relation '${g}' does not exist on '${e}'.`);if(m.type!=="one-to-many"&&m.type!=="many-to-many")throw new x(`Sort function '_count(${g})' is only supported for list relations on '${e}'.`);return{functionName:s,relationName:g,relationMeta:m}}let u=a.indexOf(".");if(u<=0||u!==a.lastIndexOf("."))throw new x(`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 x(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let l=t.relations?.find(g=>g.propertyName===c);if(!l)throw new x(`Sort relation '${c}' does not exist on '${e}'.`);if(l.type!=="one-to-many"&&l.type!=="many-to-many")throw new x(`Sort function '_${s}(${c}.${d})' is only supported for list relations on '${e}'.`);let f=l.targetTableName||l.targetTable,p=o?.tables?.get(f);if(!p)throw new x(`Sort function '${n}' references unknown target table '${f}' on '${e}'.`);let h=p.columns?.find(g=>g.name===d),y=d==="id"&&p.columns?.some(g=>g.name==="_id");if(!h&&!y)throw new x(`Sort field '${d}' does not exist on '${f}' for function '_${s}(${c}.${d})'.`);if(h?.isEncrypted===!0)throw new x(`Encrypted field '${d}' on '${f}' cannot be used for sort.`);return{functionName:s,relationName:c,aggregateField:d,relationMeta:l}}registerSortJoinChain(e,t,n,o,i){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=o.registerWithParent(t,a,n,"left",i,"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,o,l)}};ge();Pt();var vo=new Set(["count","sum","avg","min","max","countRecords"]),Io=new Set(["int","integer","bigint","float","double","decimal","numeric","real","number"]),No=new Set(["_and","_or","_not"]);function xe(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function P(r,e){let t=r.replace(/^aggregate\./,"");throw new x(e,{path:r,aggregate:{[t]:e}})}function Mo(r){return typeof r!="string"?!1:Io.has(r.toLowerCase())}function ni(r){return Object.keys(r).length===0}function Eo(r,e,t){return r===!0?{}:(r==null&&P(t,`aggregate.${e} condition must be true or an object`),xe(r)||P(t,`aggregate.${e} condition must be true or an object`),r)}function Ao(r,e,t){let n=r?.tables?.get(e);return n||P(t,`Table "${e}" metadata is not available`),n}function ri(r,e){let t=r?.targetTableName??r?.targetTable;return(typeof t!="string"||t.length===0)&&P(e,"aggregate.countRecords relation target is not available"),t}function Cn(r,e,t,n){let o=Ao(t,e,n);for(let[i,s]of Object.entries(r)){if(i==="_and"||i==="_or"){Array.isArray(s)||P(n,`aggregate.countRecords ${i} condition must be an array`);for(let d of s)xe(d)||P(n,`aggregate.countRecords ${i} items must be objects`),Cn(d,e,t,n);continue}if(i==="_not"){xe(s)||P(n,"aggregate.countRecords _not condition must be an object"),Cn(s,e,t,n);continue}(i.startsWith("_")||No.has(i))&&P(n,`Unsupported aggregate.countRecords condition key "${i}"`);let a=o.columns?.find(d=>d.name===i),u=o.relations?.find(d=>d.propertyName===i);if(!a&&!u&&P(n,`Unknown aggregate.countRecords field or relation "${i}" on table "${e}"`),xe(s)||P(n,`aggregate.countRecords condition for "${i}" must be an object`),a){for(let d of Object.keys(s))oe.has(d)||P(n,`aggregate.countRecords condition for "${i}" only supports field operators`);continue}let c=ri(u,n);Cn(s,c,t,n)}}function or(r){return xe(r)&&Object.keys(r).length>0}function nt(r,e,t){if(!or(r))return[];xe(r)||P("aggregate","aggregate must be an object");let n=t?.tables?.get(e);n||P("aggregate",`Table "${e}" metadata is not available`);let o=[];for(let[i,s]of Object.entries(r)){let a=`aggregate.${i}`;(!i||typeof i!="string")&&P("aggregate","aggregate field name must be a non-empty string"),xe(s)||P(a,"aggregate field config must be an object");let u=i,c=a,d=n.columns?.find(p=>p.name===i),l=n.relations?.find(p=>p.propertyName===i);!d&&!l&&P(c,`Unknown aggregate field or relation "${i}" on table "${e}"`);let f=Object.entries(s).filter(([p])=>p!=="as");f.length===0&&P(c,"aggregate field must define at least one operation");for(let[p,h]of f){vo.has(p)||P(c,`Unsupported aggregate operation "${p}"`);let y=Eo(h,p,c);if(l&&p!=="countRecords"&&P(c,`aggregate.${p} is not supported on relation "${i}"; use countRecords`),d&&p==="countRecords"&&P(c,`aggregate.countRecords requires a relation, but "${i}" is a field`),d&&(p==="sum"||p==="avg")&&!Mo(d.type)&&P(c,`aggregate.${p} requires a numeric field, but "${i}" is "${d.type}"`),d)for(let g of Object.keys(y))oe.has(g)||P(c,`aggregate.${p} condition for "${i}" only supports field operators`);if(l&&p==="countRecords"){let g=ri(l,c);Cn(y,g,t,c)}o.push({field:i,outputKey:u,path:c,op:p,condition:y})}}return o}function rt(r,e){let t=[];return xe(r)&&!ni(r)&&t.push(r),ni(e.condition)||t.push({[e.field]:e.condition}),t.length===0?{}:t.length===1?t[0]:{_and:t}}function ve(r,e,t){r[e.outputKey]??={},r[e.outputKey][e.op]=t}var it=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 f=new q;e={...e,plan:f.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,aggregate:e.aggregate,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(f=>f.trim()))),e.filter&&(J(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let f=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(p=>p.trim());n.sort=f.map(p=>{let h=p.trim();return h.startsWith("-")?{field:h.substring(1),direction:"desc"}:{field:h,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let f=typeof e.page=="string"?parseInt(e.page,10):e.page,p=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(f-1)*p,n.limit=p}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let o=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(f=>f.trim()).filter(Boolean),i=0,s=0;(o.includes("totalCount")||o.includes("*"))&&(i=await this.mongoService.collection(e.tableName).countDocuments({}));let a=this.metadata?.tables?.get(e.tableName),u=new Set((a?.relations??[]).map(f=>f.propertyName)),c=!!n.mongoRawFilter&&ie(n.mongoRawFilter,u);if((o.includes("filterCount")||o.includes("*"))&&!c){let f=this.mongoService.collection(e.tableName),p=e.plan?.filterTree?Pe(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await f.countDocuments(p)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let d=await this.selectLegacy(n);if(e.debugMode){let f=this.lastBuiltPipeline??[],p;try{p=await this.db.collection(e.tableName).aggregate(f).explain()}catch(h){p={error:String(h)}}return{pipeline:f,explain:p}}if(c&&(o.includes("filterCount")||o.includes("*"))){let f={...n,mongoCountOnly:!0},p=await this.selectLegacy(f);s=p.length>0?p[0].count:0}let l=await this.executeAggregate(n,e.filter);return{data:d,...(o.length>0||l)&&{meta:{...o.includes("totalCount")||o.includes("*")?{totalCount:i}:{},...o.includes("filterCount")||o.includes("*")?{filterCount:s}:{},...l?{aggregate:l}:{}}}}}async selectLegacy(e){let t=[],n=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,o=this.metadata?.tables?.get(e.table),i=o?.relations&&o.relations.length>0;if(e.fields&&e.fields.length>0||n||i){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 At(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 At(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(ce);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:o}=await er(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=o,n}async executeAggregate(e,t){let n=nt(e.aggregate,e.table,e.metadata);if(n.length===0)return;let o={},i=this.db.collection(e.table);for(let s of n){let a=rt(t,s);J(a,e.table,e.metadata);let c=new q().plan({tableName:e.table,filter:a,metadata:e.metadata,dbType:"mongodb"});if(s.op==="countRecords"){let f=await this.executeRelationCountRecords(e,t,s);ve(o,s,f);continue}let d=c.hasRelationFilters?await be(a,e.table,e.metadata,this.db):c.filterTree?Pe(c.filterTree,{metadata:e.metadata,rootTable:e.table}):{},l;if(s.op==="count")l=await i.countDocuments(d);else{let[{value:f}={value:null}]=await i.aggregate([{$match:d},{$group:{_id:null,value:{[`$${s.op}`]:`$${s.field}`}}}]).toArray();l=f??0}ve(o,s,l)}return o}async executeRelationCountRecords(e,t,n){let i=e.metadata?.tables?.get(e.table)?.relations?.find(d=>d.propertyName===n.field),s=i?.targetTableName||i?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!i||!s||!a)return 0;let u=await this.resolveMatchFilter(e.table,t,e.metadata),c=await this.resolveMatchFilter(s,n.condition,e.metadata);if(i.type==="one-to-many"){let l=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(f=>f._id).filter(f=>f!=null);return l.length===0?0:await this.db.collection(s).countDocuments({$and:[c,{[i.foreignKeyColumn]:{$in:l}}]})}if(i.type==="many-to-many"){let d=pe(e.table,i);if(!d)return 0;let f=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(y=>y!=null);if(f.length===0)return 0;let h=(await this.db.collection(d.junctionName).find({[d.selfColumn]:{$in:f}},{projection:{[d.otherColumn]:1}}).toArray()).map(y=>y[d.otherColumn]).filter(y=>y!=null);return h.length===0?0:await this.db.collection(s).countDocuments({$and:[c,{_id:{$in:h}}]})}if(i.type==="many-to-one"||i.type==="one-to-one"){let d=i.foreignKeyColumn||`${n.field}Id`,f=(await this.db.collection(e.table).find(u,{projection:{[d]:1}}).toArray()).map(p=>p[d]).filter(p=>p!=null);return f.length===0?0:await this.db.collection(s).countDocuments({$and:[c,{_id:{$in:f}}]})}return 0}async resolveMatchFilter(e,t,n){if(!t||Object.keys(t).length===0)return{};J(t,e,n);let i=new q().plan({tableName:e,filter:t,metadata:n,dbType:"mongodb"});return i.hasRelationFilters?await be(t,e,n,this.db):i.filterTree?Pe(i.filterTree,{metadata:n,rootTable:e}):{}}};var kn=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}};ge();ue();var Oo=["_and","_or","_not"];function _e(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>_e(e));for(let e of Object.keys(r))if(Oo.includes(e)||typeof r[e]=="object"&&r[e]!==null&&_e(r[e]))return!0;return!1}var ii=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function Po(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function Rn(r,e,t){if(!t)return!1;let n=r;if(r.includes(".")){let s=r.split(".");n=s[s.length-1]}let o=t.columns.find(s=>s.name===n);if(!o)return!1;let i=o.type?.toLowerCase()||"";return i==="uuid"||i==="uuidv4"||i.includes("uuid")}function jo(r,e,t,n,o){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)||Rn(r,t,o),e}function oi(r,e,t,n,o,i,s){let a=o&&!e.includes(".")?`${o}.${e}`:e,u=Ie(a,i??"postgres"),c=Rn(e,o,s),d=jo(e,n,o,i,s);switch(t){case"_eq":c&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} = ?::uuid`,[n]):r.where(a,"=",d);break;case"_neq":c&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} != ?::uuid`,[n]):r.where(a,"!=",d);break;case"_gt":c&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} > ?::uuid`,[n]):r.where(a,">",d);break;case"_gte":c&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} >= ?::uuid`,[n]):r.where(a,">=",d);break;case"_lt":c&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${u} < ?::uuid`,[n]):r.where(a,"<",d);break;case"_lte":c&&i==="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&&i==="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&&i==="postgres"&&f.every(p=>typeof p=="string")?r.whereRaw(`${u} != ALL(?::uuid[])`,[f]):r.whereNotIn(a,f);break;case"_contains":i==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):i==="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":i==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE lower(unaccent(?)) || '%'`,[n]):i==="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":i==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?))`,[n]):i==="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,Po(t),n)}}function Bo(r,e,t){if(!t||!e||r.startsWith("_"))return!0;let n=r.includes(".")?r.split(".").pop():r,o=t.columns?.some(s=>s.name===n),i=t.relations?.some(s=>s.propertyName===n);return o||i}function ot(r,e,t,n="and",o,i){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let s of e)n==="and"?r.where(function(){ot(this,s,t,"and",o,i)}):r.orWhere(function(){ot(this,s,t,"and",o,i)});return}for(let[s,a]of Object.entries(e))if(Bo(s,t,i)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){ot(this,u,t,"and",o,i)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){ot(this,u,t,"and",o,i)})});continue}if(s==="_not"){r.whereNot(function(){ot(this,a,t,"and",o,i)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(c=>ii.includes(c)))for(let[c,d]of Object.entries(a))ii.includes(c)&&(n==="and"?r.where(function(){oi(this,s,c,d,t,o,i)}):r.orWhere(function(){oi(this,s,c,d,t,o,i)}));else{let c=t&&!s.includes(".")?`${t}.${s}`:s,d=Ie(c,o??"postgres");Rn(s,t,i)&&o==="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=Ie(u,o??"postgres");Rn(s,t,i)&&o==="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 de(r,e,t,n,o){return!e||typeof e!="object"||ot(r,e,t,"and",n,o),r}ue();function lr(r,e,t){return`${F(r,t)}.${F(e,t)}`}function Ne(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 si(r,e){if(!e)return!1;let t=e.columns.find(o=>o.name===r);if(!t)return!1;let n=t.type?.toLowerCase()||"";return n==="uuid"||n==="uuidv4"||n.includes("uuid")}function st(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function cr(r,e,t,n,o,i){let s=[];for(let[a,u]of Object.entries(i)){let c=await Ut(r,e,a,u,t,n,o);if(c!==null)s.push(`EXISTS (${c})`);else{let d=t.relations.find(l=>l.propertyName===a);if(d&&d.foreignKeyColumn){let l=lr(e,d.foreignKeyColumn,n),p=u.id;if(p&&typeof p=="object"){let h=st(p._is_null),y=st(p._is_not_null);if(h===!0)s.push(`${l} IS NULL`);else if(h===!1)s.push(`${l} IS NOT NULL`);else if(y===!0)s.push(`${l} IS NOT NULL`);else if(y===!1)s.push(`${l} IS NULL`);else if(p._eq!==void 0){let g=Ne(p._eq,n);s.push(`${l} = ${g}`)}else if(p._neq!==void 0){let g=Ne(p._neq,n);s.push(`${l} != ${g}`)}else if(p._in!==void 0){let m=(Array.isArray(p._in)?p._in:[p._in]).map(b=>Ne(b,n)).join(", ");s.push(`${l} IN (${m})`)}else if(p._not_in!==void 0||p._nin!==void 0){let g=p._not_in??p._nin,b=(Array.isArray(g)?g:[g]).map($=>Ne($,n)).join(", ");s.push(`${l} NOT IN (${b})`)}else if(p._gt!==void 0){let g=Ne(p._gt,n);s.push(`${l} > ${g}`)}else if(p._gte!==void 0){let g=Ne(p._gte,n);s.push(`${l} >= ${g}`)}else if(p._lt!==void 0){let g=Ne(p._lt,n);s.push(`${l} < ${g}`)}else if(p._lte!==void 0){let g=Ne(p._lte,n);s.push(`${l} <= ${g}`)}}}}}return s}function ur(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 sr(r,e,t,n,o,i){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(ur(c)){let d=e(t).select(`${t}.id`);await Le(e,d,c,t,n,o,i),u.push({idSubquery:d})}else{let{fieldFilters:d,relationFilters:l}=X(c,n),f=await cr(e,t,n,o,i,l);u.push({fieldFilters:d,subqueries:f})}s.push(u)}else if(ur(a)){let u=e(t).select(`${t}.id`);await Le(e,u,a,t,n,o,i),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:c}=X(a,n),d=await cr(e,t,n,o,i,c);s.push([{fieldFilters:u,subqueries:d}])}return s}function ai(r,e,t,n,o){if("idSubquery"in e&&e.idSubquery){r.whereIn(`${t}.id`,e.idSubquery);return}let i=e;Object.keys(i.fieldFilters).length===0&&i.subqueries.length===0||r.where(function(){Object.keys(i.fieldFilters).length>0&&de(this,i.fieldFilters,t,o,n);for(let s of i.subqueries)this.whereRaw(s)})}function ar(r,e,t,n,o){let i=!0;for(let s of e){let a=function(){for(let u of s)ai(this,u,t,n,o)};i?(r.where(a),i=!1):r.orWhere(a)}}function Fn(r,e,t,n,o,i,s){let a=si(e,o),u=si(n,i),c=`${F(r,s)}.${F(e,s)}`,d=`${F(t,s)}.${F(n,s)}`;if(s==="postgres"){if(a&&!u)return`${c} = ${d}::uuid`;if(!a&&u)return`${c}::uuid = ${d}`}return`${c} = ${d}`}async function Ut(r,e,t,n,o,i,s){let a=o.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(h=>c.has(h)))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(Fn(u,a.foreignKeyColumn,e,"id",d,o,i));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(Fn(a.junctionTableName,a.junctionTargetColumn,u,"id",f,d,i))).whereRaw(Fn(a.junctionTableName,a.junctionSourceColumn,e,"id",f,o,i));break;case"many-to-one":case"one-to-one":l=r(u).select(r.raw("1")).whereRaw(Fn(u,"id",e,a.foreignKeyColumn,d,o,i));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?d?await Le(r,l,n,u,d,i,s):l=de(l,n,u,i,d||void 0):l=de(l,n,u,i),l.toString()}async function Le(r,e,t,n,o,i,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 sr(c._or,r,n,o,i,s);e.where(function(){ar(this,d,n,o,i)})}else if(c._and&&Array.isArray(c._and)&&c._and.length>0)for(let d of c._and)await Le(r,e,d,n,o,i,s);else await Le(r,e,c,n,o,i,s);return}if(t._or&&Array.isArray(t._or)){let c=await sr(t._or,r,n,o,i,s);e.where(function(){ar(this,c,n,o,i)});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(ur(p)){let h=r(n).select(`${n}.id`);await Le(r,h,p,n,o,i,s),f.push({idSubquery:h})}else{let{fieldFilters:h,relationFilters:y}=X(p,o),g=await cr(r,n,o,i,s,y);f.push({fieldFilters:h,subqueries:g})}e.whereNot(function(){for(let p of f)ai(this,p,n,o,i)});return}if(c._or&&Array.isArray(c._or)&&c._or.length>0){let f=await sr(c._or,r,n,o,i,s);e.whereNot(function(){ar(this,f,n,o,i)});return}let{fieldFilters:d,relationFilters:l}=X(c,o);e.whereNot(function(){Object.keys(d).length>0&&de(this,d,n,i,o)});for(let[f,p]of Object.entries(l)){let h=await Ut(r,n,f,p,o,i,s);if(h===null){let y=o.relations.find(g=>g.propertyName===f);if(y&&y.foreignKeyColumn){let g=lr(n,y.foreignKeyColumn,i),b=p.id;if(b&&typeof b=="object"){let $=st(b._is_null),_=st(b._is_not_null);if($===!0)e.whereRaw(`${g} IS NOT NULL`);else if($===!1)e.whereRaw(`${g} IS NULL`);else if(_===!0)e.whereRaw(`${g} IS NULL`);else if(_===!1)e.whereRaw(`${g} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${g} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${g} = ?`,[b._neq]);else if(b._in!==void 0){let T=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${g} 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(`${g} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${h})`)}return}let{fieldFilters:a,relationFilters:u}=X(t,o);Object.keys(a).length>0&&de(e,a,n,i,o);for(let[c,d]of Object.entries(u)){let l=await Ut(r,n,c,d,o,i,s);if(l===null){let f=o.relations.find(p=>p.propertyName===c);if(f&&f.foreignKeyColumn){let p=lr(n,f.foreignKeyColumn,i),y=d.id;if(y&&typeof y=="object"){let g=st(y._is_null),m=st(y._is_not_null);if(g===!0)e.whereRaw(`${p} IS NULL`);else if(g===!1)e.whereRaw(`${p} IS NOT NULL`);else if(m===!0)e.whereRaw(`${p} IS NOT NULL`);else if(m===!1)e.whereRaw(`${p} IS NULL`);else if(y._eq!==void 0)e.whereRaw(`${p} = ?`,[y._eq]);else if(y._neq!==void 0)e.whereRaw(`${p} != ?`,[y._neq]);else if(y._in!==void 0){let b=Array.isArray(y._in)?y._in:[y._in];e.whereRaw(`${p} IN (${b.map(()=>"?").join(", ")})`,b)}else if(y._not_in!==void 0||y._nin!==void 0){let b=y._not_in??y._nin,$=Array.isArray(b)?b:[b];e.whereRaw(`${p} NOT IN (${$.map(()=>"?").join(", ")})`,$)}}}}else e.whereRaw(`EXISTS (${l})`)}}async function De(r,e,t,n,o,i,s){await Le(r,e,t,n,o,i,s)}ue();fr();He();ue();function at(r,e,t,n,o){for(let i of e){let s=i.field.split("."),a=t||s[0],u=s[s.length-1],c=Qt(n,a,u,i.value);switch(i.operator){case"=":r=r.where(i.field,"=",c);break;case"!=":r=r.where(i.field,"!=",c);break;case">":r=r.where(i.field,">",c);break;case"<":r=r.where(i.field,"<",c);break;case">=":r=r.where(i.field,">=",c);break;case"<=":r=r.where(i.field,"<=",c);break;case"like":r=r.where(i.field,"like",c);break;case"in":let d=Array.isArray(i.value)?i.value.map(y=>Qt(n,a,u,y)):[c];r=r.whereIn(i.field,d);break;case"not in":let l=Array.isArray(i.value)?i.value.map(y=>Qt(n,a,u,y)):[c];r=r.whereNotIn(i.field,l);break;case"is null":r=r.whereNull(i.field);break;case"is not null":r=r.whereNotNull(i.field);break;case"_contains":r=r.where(i.field,"like",`%${i.value}%`);break;case"_starts_with":r=r.where(i.field,"like",`${i.value}%`);break;case"_ends_with":r=r.where(i.field,"like",`%${i.value}`);break;case"_between":let f=i.value;if(typeof f=="string"&&(f=f.split(",").map(y=>y.trim())),Array.isArray(f)&&f.length===2){let y=Qt(n,a,u,f[0]),g=Qt(n,a,u,f[1]);r=r.whereBetween(i.field,[y,g])}break;case"_is_null":r=c===!0||c==="true"?r.whereNull(i.field):r.whereNotNull(i.field);break;case"_is_not_null":r=c===!0||c==="true"?r.whereNotNull(i.field):r.whereNull(i.field);break}}return r}function Jt(r,e,t,n){let o=[],i=t;if(!r||typeof r!="object")return o;for(let[s,a]of Object.entries(r))if(s==="_and"&&Array.isArray(a)){let u=a.map(c=>{let d=Jt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&o.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(c=>{let d=Jt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&o.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=Jt(a,e,t,n);u.length>0&&o.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=`${F(e,n)}.${F(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=i.columns?.find(y=>y.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")o.push(`${d} = ${l}`);else if(u==="_neq")o.push(`${d} != ${l}`);else if(u==="_gt")o.push(`${d} > ${l}`);else if(u==="_gte")o.push(`${d} >= ${l}`);else if(u==="_lt")o.push(`${d} < ${l}`);else if(u==="_lte")o.push(`${d} <= ${l}`);else if(u==="_is_null")o.push(`${d} IS NULL`);else if(u==="_is_not_null")o.push(`${d} IS NOT NULL`);else if(u==="_in"){let p=(Array.isArray(c)?c:[c]).map(h=>typeof h=="string"?`'${h.replace(/'/g,"''")}'`:String(h)).join(", ");o.push(`${d} IN (${p})`)}else if(u==="_not_in"||u==="_nin"){let p=(Array.isArray(c)?c:[c]).map(h=>typeof h=="string"?`'${h.replace(/'/g,"''")}'`:String(h)).join(", ");o.push(`${d} NOT IN (${p})`)}else if(u==="_contains"){let f=String(c).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}')) || '%'`):n==="mysql"?o.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):o.push(`lower(${d}) LIKE '%${f.toLowerCase()}%'`)}else if(u==="_starts_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${d})) ILIKE lower(unaccent('${f}')) || '%'`):n==="mysql"?o.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):o.push(`lower(${d}) LIKE '${f.toLowerCase()}%'`)}else if(u==="_ends_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}'))`):n==="mysql"?o.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci)`):o.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]);o.push(`${d} BETWEEN ${f} AND ${p}`)}}else{let u=`${F(e,n)}.${F(s,n)}`,c;a===null?c="NULL":typeof a=="string"?c=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?c=a?"true":"false":c=String(a),o.push(`${u} = ${c}`)}return o}function ci(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 Qt(r,e,t,n){if(n==null)return n;let o=r?.tables?.get(e);if(!o?.columns)return n;let i=o.columns.find(s=>s.name===t);if(!i)return n;switch(i.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}}ue();qt();Je();async function di(r,e,t,n,o,i,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(gr(),ui)),u=await a(e,t,n,o,i,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function hr(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(o=>({name:o.name,type:o.type})),relations:n.relations||[]}:null}:null}function fi(r,e,t,n,o){let i=r.targetTableName||r.targetTable;if(!i)return null;let s=r.foreignKeyColumn||G(r.propertyName);if(!s)return null;let a=l=>F(l,o),u=n?.tables?.get(i),d=(u?Z(u):null)?.name||"id";return`(SELECT ${a(i)}.${a(e)} FROM ${a(i)} WHERE ${a(i)}.${a(d)} = ${a(t)}.${a(s)})`}qt();var ut=class r{constructor(e,t,n,o){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=o;this.logger=new kn(r.name);this.debugLog=[]}async execute(e){let t=performance.now();this.metadata=e.metadata;let n=e.debugLog||[];this.debugLog=n;let o=e.debugTrace;if(e.filter&&J(e.filter,e.tableName,e.metadata),!e.plan){let w=new q;e={...e,plan:w.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 i=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=i.rawFields&&i.rawFields.length>0&&!i.rawFields.includes("*");if(i.joins.length===0&&!i.hasRelationFilters&&!i.hasRelationSort&&!u&&!a&&c){o&&o.setQueryPath("simple");let w=await this.executeSimple(e,i);return o&&o.dur("sql_executor",t,{table:e.tableName}),w}let l={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?l.fields=e.fields:typeof e.fields=="string"&&(l.fields=e.fields.split(",").map(w=>w.trim())));let f=e.filter;if(e.filter&&!_e(e.filter)){l.where=[];for(let[w,C]of Object.entries(e.filter))if(typeof C=="object"&&C!==null)for(let[v,V]of Object.entries(C)){let M;if(v==="_eq")M="=";else if(v==="_neq")M="!=";else if(v==="_in")M="in";else if(v==="_not_in"||v==="_nin")M="not in";else if(v==="_gt")M=">";else if(v==="_gte")M=">=";else if(v==="_lt")M="<";else if(v==="_lte")M="<=";else if(v==="_contains")M="_contains";else if(v==="_starts_with")M="_starts_with";else if(v==="_ends_with")M="_ends_with";else if(v==="_between")M="_between";else if(v==="_is_null")M="_is_null";else if(v==="_is_not_null")M="_is_not_null";else if(v==="_like")M="like";else if(v==="_ilike")M="ilike";else continue;l.where.push({field:w,operator:M,value:V})}else l.where.push({field:w,operator:"=",value:C})}if(e.sort){let w=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(C=>C.trim());l.sort=w.map(C=>{let v=C.trim();return v.startsWith("-")?{field:v.substring(1),direction:"desc"}:{field:v,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,h=p===void 0||Number.isNaN(p)?void 0:p<0?0:p,y=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,g=y===void 0||Number.isNaN(y)?void 0:y;g&&h!==void 0?(l.offset=(g-1)*h,l.limit=h):h!==void 0&&(l.limit=h);let m=e.plan?.sortItems??(l.sort??[]).map(w=>({joinId:null,field:w.field,direction:w.direction,fullPath:w.field})),b=[],$=[];for(let w of m){if(w.function==="count"){let C={sql:this.buildRelationCountSortSubquery(l.table,w),direction:w.direction};$.push(C);continue}if(w.function==="max"||w.function==="min"){let C={sql:this.buildRelationAggregateSortSubquery(l.table,w),direction:w.direction};$.push(C);continue}if(w.joinId===null){if(w.field.includes(".")&&!e.plan){let v=w.field.split(".")[0];if(this.metadata?.tables?.get(l.table)?.relations?.some(z=>z.propertyName===v))continue}let C={field:w.field.includes(".")?w.field:`${l.table}.${w.field}`,direction:w.direction};b.push(C),$.push(C)}else{let C=e.plan?.joins.find(v=>v.id===w.joinId);if(C&&(C.relationType==="many-to-one"||C.relationType==="one-to-one")){let v=fi(C.relationMeta,w.field,l.table,this.metadata,this.dbType);if(v){let V={sql:v,direction:w.direction};$.push(V)}}}}let _=[];if(l.fields&&l.fields.length>0||u||a){let w=hr(this.metadata),C=l.fields&&l.fields.length>0?l.fields:["*"],v=await di(this.knex,l.table,C,w,this.dbType,this.maxQueryDepth,e.deep);v.select.length>0&&(l.select=[...l.select||[],...v.select]),_=v.batchFetchDescriptors||[]}l.where&&(l.where=l.where.map(w=>w.field.includes(".")?w:{...w,field:`${l.table}.${w.field}`})),l.sort=b;let T=this.knex(l.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(w=>w.trim()).filter(Boolean),R=k.includes("filterCount")||k.includes("*"),I=k.includes("totalCount")||k.includes("*");if(l.select){let w=l.select.map(C=>typeof C=="string"&&C.trim().startsWith("(")?this.knex.raw(C):typeof C=="string"&&/ as /i.test(C)?this.knex.raw(C):C);T=T.select(w)}if(R&&T.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),I){let w=F(l.table,this.dbType);T.select(this.knex.raw(`(SELECT COUNT(*) FROM ${w}) as __total_count__`))}let E=["table_definition","column_definition","relation_definition","method_definition"].includes(l.table);if(f&&(_e(f)||Object.keys(f).length>0)){let w=this.metadata?.tables?.get(l.table);(!E&&w&&w.relations&&w.relations.length>0?X(f,w).hasRelations:!1)?await De(this.knex,T,f,l.table,w,this.dbType,v=>this.metadata?.tables?.get(v)):e.plan?.filterTree?ne(T,e.plan.filterTree,{dbType:this.dbType,rootTable:l.table}):(this.logger.debug(`buildWhereClause fallback for table=${l.table}`),T=de(T,f,l.table,this.dbType,w))}else l.where&&l.where.length>0&&(T=at(T,l.where,l.table,this.metadata,this.dbType));for(let w of $)if(w.field){let C=w.field.includes(".")?w.field:`${l.table}.${w.field}`;T=T.orderBy(C,w.direction)}else w.sql&&(T=T.orderByRaw(`${w.sql} ${w.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 L=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&&o){let w=T.toSQL().toNative();o.setSql(w.sql);try{let C=w.sql.replace(/\$\d+/g,"?"),v=await this.knex.raw(`EXPLAIN ${C}`,w.bindings);o.setExplain(this.dbType==="postgres"?v.rows:v[0])}catch(C){o.setExplain({error:String(C)})}}let N,A=performance.now();N=await T,o&&o.dur("db_execute",A,{table:e.tableName});let D=0;if(R&&N.length>0&&(D=Number(N[0].__filter_count__||0),N.forEach(w=>{delete w.__filter_count__})),I&&N.length>0&&N[0].__total_count__!==void 0&&(L=Number(N[0].__total_count__||0),N.forEach(w=>{delete w.__total_count__})),_&&_.length>0&&N.length>0){let w=hr(this.metadata);if(w){let{executeBatchFetches:C}=await Promise.resolve().then(()=>(br(),pi));await C(this.knex,N,_,w,this.maxQueryDepth??3,0,l.table,this.dbType,this.metadata,o)}}if(this.knexService){let w=performance.now();N=await this.knexService.parseResult(N,l.table),o&&o.dur("db_parseResult",w,{table:e.tableName})}else{let w=(C,v)=>{if(!C||!this.metadata)return C;let V=this.metadata.tables?.get(v);if(!V)return C;if(Array.isArray(C))return C.map(z=>w(z,v));if(typeof C!="object"||Buffer.isBuffer(C))return C;let M={...C};for(let z of V.columns)if(z.type==="simple-json"&&M[z.name]&&typeof M[z.name]=="string")try{M[z.name]=JSON.parse(M[z.name])}catch{}for(let[z,ee]of Object.entries(M))if(ee&&typeof ee=="object"&&!Array.isArray(ee)&&!Buffer.isBuffer(ee)){let An=ee;if(An.id!==void 0||An.createdAt!==void 0){let ft=V.relations?.find(pt=>pt.propertyName===z);ft&&(M[z]=w(ee,ft.targetTableName))}}else if(Array.isArray(ee)&&ee.length>0&&typeof ee[0]=="object"&&ee[0].id!==void 0){let ft=V.relations?.find(pt=>pt.propertyName===z);ft&&(M[z]=ee.map(pt=>w(pt,ft.targetTableName)))}return M};N=w(N,l.table)}o&&(o.setQueryPath("full"),o.dur("sql_executor",t,{table:e.tableName}));let j=await this.executeAggregate(l,f);return{data:N,...(k.length>0||j)&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:L}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:D}:{},...j?{aggregate:j}:{}}},...S!==void 0&&{sql:S}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,o=t.relationName||t.field,i=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=Z(s)?.name||"id",u=F(e,this.dbType),c=F(a,this.dbType);if(!n||!i)throw new x(`Sort relation '${o}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let d=n.foreignKeyColumn||n.mappedBy;if(!d)throw new x(`Sort function '_count(${o})' cannot resolve relation key on '${e}'.`);let l=F(i,this.dbType),f=F(d,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}if(n.type==="many-to-many"){let d=this.resolveManyToManyContract(n,o,e),l=F(d.tableName,this.dbType),f=F(d.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}throw new x(`Sort function '_count(${o})' is only supported for list relations on '${e}'.`)}buildRelationAggregateSortSubquery(e,t){let n=t.relationMeta,o=t.relationName||t.field,i=t.aggregateField,s=n?.targetTableName||n?.targetTable,a=this.metadata?.tables?.get(e),u=this.metadata?.tables?.get(s),c=Z(a)?.name||"id",d=Z(u)?.name||"id",l=F(e,this.dbType),f=F(c,this.dbType),p=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!p||!n||!s||!i)throw new x(`Sort function '${t.field}' is not supported on '${e}'.`);let h=F(s,this.dbType),y=F(i,this.dbType);if(n.type==="one-to-many"){let g=n.foreignKeyColumn||n.mappedBy;if(!g)throw new x(`Sort function '_${t.function}(${o}.${i})' cannot resolve relation key on '${e}'.`);let m=F(g,this.dbType);return`(SELECT ${p}(${h}.${y}) FROM ${h} WHERE ${h}.${m} = ${l}.${f})`}if(n.type==="many-to-many"){let g=this.resolveManyToManyContract(n,o,e),m=F(g.tableName,this.dbType),b=F(g.sourceColumn,this.dbType),$=F(g.targetColumn,this.dbType),_=F(d,this.dbType);return`(SELECT ${p}(${h}.${y}) FROM ${m} JOIN ${h} ON ${h}.${_} = ${m}.${$} WHERE ${m}.${b} = ${l}.${f})`}throw new x(`Sort function '_${t.function}(${o}.${i})' 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 x(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async executeSimple(e,t){let n=e.tableName,o=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],i=this.knex(n).select(o);t.filterTree&&ne(i,t.filterTree,{dbType:this.dbType,rootTable:n});for(let g of t.sortItems){let m=g.field.includes(".")?g.field:`${n}.${g.field}`;i=i.orderBy(m,g.direction)}t.limit!==void 0&&t.limit!==null&&t.limit>0&&(i=i.limit(t.limit)),t.offset!==void 0&&(i=i.offset(t.offset));let s=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(g=>g.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),u=s.includes("totalCount")||s.includes("*");if(a&&i.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),u){let g=F(n,this.dbType);i.select(this.knex.raw(`(SELECT COUNT(*) FROM ${g}) as __total_count__`))}let c=e.debugTrace,d;if(e.debugMode){let g=i.toSQL().toNative();if(d=g.sql,c){c.setSql(g.sql);try{let m=g.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${m}`,g.bindings);c.setExplain(this.dbType==="postgres"?b.rows:b[0])}catch(m){c.setExplain({error:String(m)})}}}let l=performance.now(),f;f=await i,c&&c.dur("db_execute",l,{table:n}),this.knexService&&(f=await this.knexService.parseResult(f,n));let p=0,h=0;a&&f.length>0&&(p=Number(f[0].__filter_count__||0),f.forEach(g=>delete g.__filter_count__)),u&&f.length>0&&(h=Number(f[0].__total_count__||0),f.forEach(g=>delete g.__total_count__));let y=await this.executeAggregate({table:n,aggregate:e.aggregate,metadata:e.metadata},e.filter);return{data:f,...(s.length>0||y)&&{meta:{...u?{totalCount:h}:{},...a?{filterCount:p}:{},...y?{aggregate:y}:{}}},...d!==void 0&&{sql:d}}}async executeAggregate(e,t){let n=nt(e.aggregate,e.table,e.metadata);if(n.length===0)return;let o={};for(let i of n){let s=rt(t,i);J(s,e.table,e.metadata);let u=new q().plan({tableName:e.table,filter:s,metadata:e.metadata,dbType:this.dbType});if(i.op==="countRecords"){let p=await this.executeRelationCountRecords(e,t,i);ve(o,i,p);continue}let c=this.knex(e.table);if(u.hasRelationFilters){let p=e.metadata?.tables?.get(e.table);await De(this.knex,c,s,e.table,p,this.dbType,h=>e.metadata?.tables?.get(h))}else u.filterTree&&ne(c,u.filterTree,{dbType:this.dbType,rootTable:e.table});let d=`${F(e.table,this.dbType)}.${F(i.field,this.dbType)}`,l=i.op==="count"?this.knex.raw("COUNT(*) as value"):this.knex.raw(`${i.op.toUpperCase()}(${d}) as value`),f=await c.clearSelect().select(l).first();ve(o,i,f?.value??0)}return o}async executeRelationCountRecords(e,t,n){let o=e.metadata?.tables?.get(e.table),i=o?.relations?.find(l=>l.propertyName===n.field),s=i?.targetTableName||i?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!i||!s||!a)return 0;let u=this.knex(e.table).select(`${e.table}.id`);if(t&&Object.keys(t).length>0){let f=new q().plan({tableName:e.table,filter:t,metadata:e.metadata,dbType:this.dbType});f.hasRelationFilters?await De(this.knex,u,t,e.table,o,this.dbType,p=>e.metadata?.tables?.get(p)):f.filterTree&&ne(u,f.filterTree,{dbType:this.dbType,rootTable:e.table})}let c=this.knex(s).count("* as value");if(n.condition&&Object.keys(n.condition).length>0){J(n.condition,s,e.metadata);let f=new q().plan({tableName:s,filter:n.condition,metadata:e.metadata,dbType:this.dbType});f.hasRelationFilters?await De(this.knex,c,n.condition,s,a,this.dbType,p=>e.metadata?.tables?.get(p)):f.filterTree&&ne(c,f.filterTree,{dbType:this.dbType,rootTable:s})}if(i.type==="one-to-many")c.whereIn(`${s}.${i.foreignKeyColumn}`,u);else if(i.type==="many-to-many"){let l=this.resolveManyToManyContract(i,n.field,e.table);c.whereIn(`${s}.id`,this.knex(l.tableName).select(`${l.tableName}.${l.targetColumn}`).whereIn(`${l.tableName}.${l.sourceColumn}`,u))}else(i.type==="many-to-one"||i.type==="one-to-one")&&c.whereIn(`${s}.id`,function(){this.select(`${e.table}.${i.foreignKeyColumn}`).from(e.table),t&&Object.keys(t).length>0&&this.whereIn(`${e.table}.id`,u),this.whereNotNull(`${e.table}.${i.foreignKeyColumn}`)});let d=await c.first();return Number(d?.value??0)}};var In=require("mongodb"),dt=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,Nn.mkdirSync)((0,gi.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(!In.ObjectId)return e;if(typeof e=="string")try{return new In.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(),o=Ve(n,e,t,this.dbType);return o._id!==void 0&&(o._id=this.safeObjectId(o._id)),o}async applyWhereToKnex(e,t,n){let o=await this.getMetadataForQuery();return{query:at(e,t,n??"",o,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 o=await this.mongoService.insertOne(e.table,n);t.push(ce(o))}return t}return this.mongoService.insertOne(e.table,e.data)});if(Array.isArray(e.data)){let t=[];for(let n of e.data){let o=await this.knexService.insertWithCascade(e.table,n);t.push(o)}return t}else return await this.knexService.insertWithCascade(e.table,e.data)}async select(e){let t=performance.now(),n=await this.getMetadataForQuery(),o=performance.now(),s=new q().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",o,{table:e.tableName}),a.setPlan(this.sanitizePlan(s))),this.dbType==="mongodb"){let l=await new it(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s,aggregate:e.aggregate});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}let c=await new ut(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 i=await this.buildMongoFilter(e.where,e.table),s=this.mongoService.collection(e.table),a=this.mongoService.ioSignalPublic?.()??{},u=await s.find(i,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 o=await n;for(let i of o)await this.knexService.updateWithCascade(e.table,i.id,e.data);if(e.returning){let i=t(e.table);return e.where.length>0&&await this.applyWhereToKnex(i,e.where,e.table),await i.select(e.returning)}return{affected:o.length}}async deleteWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),i=this.mongoService.collection(e.table),s=this.mongoService.ioSignalPublic?.()??{},a=await i.find(o,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 i=e.where?await this.buildMongoFilter(e.where,e.table):{};return this.mongoService.count(e.table,i)}let n=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let o=await n.count("* as count").first();return Number(o?.count||0)}whereToFilter(e){let t={},n=this.databaseConfigService.isMongoDb();for(let[o,i]of Object.entries(e))o==="id"||o==="_id"?n?t._id=this.normalizeWhereFilterValue("_id",i):t.id=this.normalizeWhereFilterValue("id",i):t[o]=this.normalizeWhereFilterValue(o,i);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 In.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[n,o]of Object.entries(e))t[n]=Array.isArray(o)?o.map(i=>this.safeObjectId(i)):this.safeObjectId(o);return t}filterToWhere(e){let t=[];for(let[n,o]of Object.entries(e))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let i=Object.entries(o)[0];if(i){let[s,a]=i,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,aggregate:e.aggregate,maxQueryDepth:e.maxQueryDepth})})}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 ce(a)}let o=await this.knexService.insertWithCascade(e,t),i=this.knexService.getKnex(),s=o||t.id;return await i(e).where("id",s).first()})}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 o of n)this.batchInserts.items.push({table:e,data:o});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(o=>this.logBatchInsertError("QueryBuilder batch insert flush failed",o))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(o=>this.logBatchInsertError("QueryBuilder batch insert flush failed",o)),{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(([o,i])=>({tableName:o,count:i.length}))}),await this.runLimited([...n.entries()],([o,i])=>this.flushBatchInsertTable(o,i)),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(o=>o.data));return}await Promise.all(t.map(o=>this.mongoService.insertOne(e,o.data)))});return}if(typeof this.knexService?.insertManyWithCascade=="function"){await this.knexService.insertManyWithCascade(e,t.map(o=>o.data));return}await Promise.all(t.map(o=>this.knexService.insertWithCascade(e,o.data)))})()}catch(n){if(t.length===1){this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,n);return}let o=Math.ceil(t.length/2);await Promise.all([this.runBatchInsertWithIsolation(e,t.slice(0,o)),this.runBatchInsertWithIsolation(e,t.slice(o))])}}groupBatchInsertsByTable(e){let t=new Map;for(let n of e){let o=t.get(n.table);o?o.push(n):t.set(n.table,[n])}return t}async runLimited(e,t){let n=0,o=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;n<e.length;){let i=e[n++];await t(i)}});await Promise.all(o)}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,Nn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
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 i=await this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n));return ce(i)}return await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first()})}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 countRecords(e,t){if(this.dbType==="mongodb")return this.mongoService.count(e,t||{});let o=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.filterToWhere(t);({query:o}=await this.applyWhereToKnex(o,s,e))}let i=await o.count("* as count").first();return Number(i?.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 o=this.safeObjectId(t);return this.mongoService.findOne(e,{_id:o})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let o={};for(let[i,s]of Object.entries(t))i==="id"||i==="_id"?o._id=this.safeObjectId(s):o[i]=s;return this.mongoService.findOne(e,o)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let o={};for(let[u,c]of Object.entries(t))u==="id"||u==="_id"?o._id=this.safeObjectId(c):o[u]=c;let i=this.mongoService.collection(e),s=this.mongoService.ioSignalPublic?.()??{};return await i.find(o,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),o=this.knexService.getKnex(),i=n||t.id;return await o(e).where("id",i).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 i=this.mongoService.getDb();if(typeof e=="string"){if(e.toLowerCase().includes("select 1"))return await i.command({ping:1});throw new Error("String queries not supported for MongoDB. Use db.command() object instead.")}return await i.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}};br();yr();gr();ue();qt();Xe();_n();ge();He();var hi=new Set(["fields","filter","sort","limit","page","deep"]),En=3;function _r(r,e,t,n=0,o=3){if(!e||typeof e!="object")return;if(n>=o)throw new x(`deep option exceeds maximum query depth of ${o}`);let i=t?.tables?.get(r),s=new Map((i?.relations??[]).map(a=>[a.propertyName,a]));for(let[a,u]of Object.entries(e)){let c=s.get(a);if(!c)throw new x(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let f of Object.keys(u))if(!hi.has(f))throw new x(`Unknown deep option key '${f}' for relation '${a}'. Allowed: ${[...hi].join(", ")}`);let d=c.type;if(u.limit!==void 0&&(d==="many-to-one"||d==="one-to-one"))throw new x(`'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 x(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let l=c.targetTableName||c.targetTable;if(l){if(u.filter&&(J(u.filter,l,t),Be(u.filter,l,t),Mn(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 h=p.startsWith("-")?p.slice(1):p;Ko(h,l,t,a,r)}}u.deep&&_r(l,u.deep,t,n+1,o)}}}function Ko(r,e,t,n,o){if(r.includes("."))throw new x(`Sort field '${r}' is not supported for relation '${n}' on '${o}'. Sort only by local fields defined on '${e}'.`);let i=t?.tables?.get(e);if(!i)throw new x(`Sort field '${r}' references unknown table '${e}' (relation '${n}' on '${o}')`);let s=i.columns?.some(u=>u.name===r),a=r==="id"&&i.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new x(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${o}')`)}var Uo=new Set(["_and","_or","_not"]);function Mn(r,e,t,n){if(!(!r||typeof r!="object"))for(let[o,i]of Object.entries(r)){if(Uo.has(o)){if(Array.isArray(i))for(let c of i)Mn(c,e,t,n);else i&&typeof i=="object"&&Mn(i,e,t,n);continue}if(o.startsWith("_")||!i||typeof i!="object"||Array.isArray(i)||!Object.keys(i).some(c=>!c.startsWith("_")))continue;let a=e+1;if(a>En)throw new x(`Filter path exceeds max dotted hops of ${En} at '${o}' (relation '${t}' on '${n}')`);let u={};for(let c of Object.keys(i))c.startsWith("_")||(u[c]=i[c]);Mn(u,a,t,n)}}function yi(r,e,t,n){return!r||typeof r!="object"?r:Ht(r,e,t,n)}function Ht(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let i=r.map(s=>Ht(s,e,t,n)).filter(s=>s!=null);return i.length>0?i:null}let o={};for(let[i,s]of Object.entries(r)){if(i==="_and"||i==="_or"){let l=(Array.isArray(s)?s:[s]).map(f=>Ht(f,e,t,n)).filter(f=>f!=null&&Object.keys(f).length>0);l.length>0&&(o[i]=l);continue}if(i==="_not"){let d=Ht(s,e,t,n);d!=null&&Object.keys(d).length>0&&(o[i]=d);continue}let a=t?.tables?.get(e),u=a?.relations?.find(d=>d.propertyName===i);if(u){if(!n(e,i,"relation"))continue;let d=u.targetTableName||u.targetTable;if(!d)continue;let l=Ht(s,d,t,n);l!=null&&Object.keys(l).length>0&&(o[i]=l);continue}if(a?.columns?.find(d=>d.name===i)){if(!n(e,i,"column"))continue;o[i]=s;continue}o[i]=s}return o}function mi(r,e,t,n){if(!r)return r;let o=Array.isArray(r)?r:r.split(",").map(s=>s.trim()).filter(Boolean),i=[];for(let s of o){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],h=f===c.length-1,y=t?.tables?.get(l);if(!y){d=!1;break}if(h)y.columns?.find(m=>m.name===p)?n(l,p,"column")||(d=!1):y.relations?.find(b=>b.propertyName===p)&&(n(l,p,"relation")||(d=!1));else{let g=y.relations?.find(m=>m.propertyName===p);if(!g){d=!1;break}if(!n(l,p,"relation")){d=!1;break}l=g.targetTableName||g.targetTable||l}}d&&i.push(s)}if(i.length!==0)return Array.isArray(r)?i:i.join(",")}jt();He();Bt();Pt();Je();ge();function Qo(r){let e=new dt({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,o=()=>(t||(t=new Qe({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),i=()=>(n||(n=new We({isolatedExecutorService:o()})),n);return{queryBuilderService:e,get isolatedExecutorService(){return o()},get executorEngineService(){return i()},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,buildAggregateFilter,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,hasAggregateQuery,hasLogicalOperators,isExecutableJavaScript,isScriptTable,mergeAggregateValue,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,perParentRun,quoteIdentifier,quoteQualifiedIdentifier,resolveExecutableScript,rewriteFilterDenyingFields,rewriteSortDroppingDenied,runWithIoAbortSignal,scriptContractService,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,validateDeepOptions,validateFilterShape,whereToMongoFilter});
52
+ }`}var Er="mongo-fold-text-search.body.txt",qe=null;function Vi(){let r=[Dn.join(__dirname,Er),Dn.join(process.cwd(),"dist","kernel","query","utils",Er)];for(let e of r)try{if(nn.existsSync(e))return nn.readFileSync(e,"utf8")}catch{}return null}function rn(){if(qe!==null)return qe;let r=Vi();return r?(qe=r,qe):(qe=tn(),qe)}var _e=require("mongodb");function D(r,e,t,n){if(t==="_id"){if(n instanceof _e.ObjectId)return n;if(typeof n=="string")try{return new _e.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 _e.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 _e.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 _e.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new _e.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 _e.ObjectId(n)}catch{return n}return n;default:return n}}var on="__mongoFoldTextTriples";function Hi(r){return r==="_id"?"$_id":`$${r}`}function Ue(r,e,t,n){let i=Hi(e),o=r[on]??[];o.push({ref:i,needle:t,mode:n}),r[on]=o}function Gi(r){let e=r[on];if(delete r[on],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:rn(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}function Qe(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=D(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=>D(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=>D(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":Ue(i,a,String(c),"contains");break;case"_starts_with":Ue(i,a,String(c),"starts");break;case"_ends_with":Ue(i,a,String(c),"ends");break;case"_between":let h=s.value;if(typeof h=="string"&&(h=h.split(",").map(y=>y.trim())),Array.isArray(h)&&h.length===2){let y=D(r,u,a,h[0]),b=D(r,u,a,h[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 m=c===!0||c==="true";i[a]=m?{$ne:null}:{$eq:null};break}}return Gi(i),i}function Ar(r,e,t){let i=r?.tables?.get?.(e)?.columns?.find(o=>o.name===t);return i?i.isNullable!==!1:!0}function sn(r,e,t,n,i,o){switch(i){case"_contains":Ue(e,n,String(o),"contains");break;case"_starts_with":Ue(e,n,String(o),"starts");break;case"_ends_with":Ue(e,n,String(o),"ends");break;case"_eq":e[n]=D(r,t,n,o);break;case"_neq":{let l=D(r,t,n,o);Ar(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=>D(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=>D(r,t,n,l));Ar(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:D(r,t,n,o)};break;case"_gte":e[n]={$gte:D(r,t,n,o)};break;case"_lt":e[n]={$lt:D(r,t,n,o)};break;case"_lte":e[n]={$lte:D(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=D(r,t,n,d[0]),f=D(r,t,n,d[1]);e[n]={$gte:l,$lte:f}}break}}var zn=require("mongodb");function ne(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(ne(i,e))return!0}}else if(t==="_not"){if(ne(n,e))return!0}else if(e.has(t))return!0;return!1}function V(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=ne(r,i);return{fieldFilters:t,relationFilters:n,hasRelations:o}}Ot();Mt();var dn="__mongoFoldTextTriples";function ze(r,e){if(!r)return{};let t={};return Et(r,t,e),$e(t),t}function io(r,e){if(!r)return{};let t={};return qn(r,t,e),$e(t),t}function ge(r,e,t){if(!e)return{};let n=new ie,{node:i}=fe(e,t,r,n);return ze(i,{metadata:r,rootTable:t})}function fn(r,e,t){if(!e)return{};let n=new ie,{node:i}=fe(e,t,r,n);return io(i,{metadata:r,rootTable:t})}function Et(r,e,t){switch(r.kind){case"true":return;case"false":pe(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let i=r.children.map(o=>{let s={};return Et(o,s,t),$e(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}pe(e,...i);return}case"or":{let i=r.children.map(s=>{let a={};return Et(s,a,t),$e(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={};Et(r.child,n,t),$e(n);let i=e.$nor;e.$nor=i?[...i,n]:[n];return}case"compare":Dr(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 Dr(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=>D(t.metadata,t.rootTable,n,o);switch(r.op){case"eq":Y(e,n,i(r.value));return;case"neq":{let o=i(r.value);Un(t,n)?pe(e,{[n]:{$ne:null}},{[n]:{$ne:o}}):Y(e,n,{$ne:o});return}case"gt":Y(e,n,{$gt:i(r.value)});return;case"gte":Y(e,n,{$gte:i(r.value)});return;case"lt":Y(e,n,{$lt:i(r.value)});return;case"lte":Y(e,n,{$lte:i(r.value)});return;case"in":{let o=Lr(r.value).map(i);Y(e,n,{$in:o});return}case"not_in":{let o=Lr(r.value).map(i);Un(t,n)?pe(e,{[n]:{$ne:null}},{[n]:{$nin:o}}):Y(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&&Y(e,n,{$gte:i(o[0]),$lte:i(o[1])});return}case"is_null":Y(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":Kn(e,n,String(r.value),"contains");return;case"starts_with":Kn(e,n,String(r.value),"starts");return;case"ends_with":Kn(e,n,String(r.value),"ends");return}}function qn(r,e,t){switch(r.kind){case"true":pe(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let i=r.children.map(s=>{let a={};return qn(s,a,t),$e(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 qn(o,s,t),$e(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}pe(e,...i);return}case"not":Et(r.child,e,t);return;case"compare":oo(r,e,t);return;case"relation_exists":{Y(e,r.joinId,r.negate?{$ne:null}:{$eq:null});return}}}function oo(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"){Y(e,n,r.value===!0?{$ne:null}:{$eq:null});return}let i={};Dr(r,i,t),$e(i);let o={$nor:[i]};Un(t,n)?pe(e,o,{[n]:{$ne:null}}):pe(e,o)}function Y(r,e,t){r[e]===void 0?r[e]=t:(pe(r,{[e]:r[e]},{[e]:t}),delete r[e])}function pe(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function Un(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(i=>i.name===e);return n?n.isNullable!==!1:!0}function Lr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function so(r){return r==="_id"?"$_id":`$${r}`}function Kn(r,e,t,n){let i=so(e),o=r[dn]??[];o.push({ref:i,needle:t,mode:n}),r[dn]=o}function $e(r){let e=r[dn];if(delete r[dn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:rn(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}async function Te(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return ge(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!ne(r,o))return ge(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>Te(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=>Te(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:{$or:d}}if(r._not)return await Jn(r._not,e,t,n)||{};let{fieldFilters:s,relationFilters:a}=V(r,i),u=[];if(s&&Object.keys(s).length>0){let c=ge(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 ao(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 Jn(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return fn(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!ne(r,o))return fn(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>Jn(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=>Jn(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 Te(r._not,e,t,n);let{fieldFilters:s,relationFilters:a}=V(r,i),u=[];if(s&&Object.keys(s).length>0){let c=fn(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 co(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 ao(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"?lo(e,s,r,a,u,i,o):s.type==="one-to-many"?qr(e,s,t,a,u,i,o):s.type==="many-to-many"?Ur(e,s,t,a,u,i,o):{}}async function lo(r,e,t,n,i,o,s){let a=z(e)||t,u=gn(r),c=hn(u);if(c!==null)return c?{[a]:null}:{[a]:{$ne:null}};let d=Vn(u);if(d!==null){let h=mn(d.value);if(d.op==="eq")return{[a]:h};if(d.op==="neq")return{[a]:{$ne:h}};if(d.op==="in")return{[a]:{$in:h}};if(d.op==="not_in")return{$and:[{[a]:{$nin:h}},{[a]:{$ne:null}}]}}let l=await pn(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(h=>h._id).filter(Boolean);return p.length===0?{__impossible__:!0}:{[a]:{$in:p}}}async function co(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 uo(e,s,r,a,u,i,o);if(s.type==="one-to-many"){let c=await qr(e,s,t,a,u,i,o);return Kr(c)}if(s.type==="many-to-many"){let c=await Ur(e,s,t,a,u,i,o);return Kr(c)}return{}}async function uo(r,e,t,n,i,o,s){let a=z(e)||t,u=gn(r),c=hn(u);if(c!==null)return c?{[a]:{$ne:null}}:{[a]:null};let d=Vn(u);if(d!==null){let h=mn(d.value);if(d.op==="eq")return{$and:[{[a]:{$ne:h}},{[a]:{$ne:null}}]};if(d.op==="neq")return{[a]:h};if(d.op==="in")return{$and:[{[a]:{$nin:h}},{[a]:{$ne:null}}]};if(d.op==="not_in")return{[a]:{$in:h}}}let l=await pn(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(h=>h._id).filter(Boolean);return p.length===0?{[a]:{$ne:null}}:{$and:[{[a]:{$nin:p}},{[a]:{$ne:null}}]}}async function qr(r,e,t,n,i,o,s){let a=K(e)||t,u=gn(r),c=hn(u);if(c!==null){let f=await Wr(s,n,a,{});return c?f.length===0?{}:{_id:{$nin:f}}:f.length===0?{__impossible__:!0}:{_id:{$in:f}}}let d=await pn(u,n,i,o,s);if(!d||Object.keys(d).length===0)return{};let l=await Wr(s,n,a,d);return l.length===0?{__impossible__:!0}:{_id:{$in:l}}}async function Ur(r,e,t,n,i,o,s){let a=Ne(t,e);if(!a)return{};let u=gn(r),c=hn(u);if(c!==null){let g=await Qn(s,a,n,null);return c?g.length===0?{}:{_id:{$nin:g}}:g.length===0?{__impossible__:!0}:{_id:{$in:g}}}let d=Vn(u);if(d!==null){let g=mn(d.value),m=Array.isArray(g)?g:[g],y=await Qn(s,a,n,{_id:{$in:m}});return y.length===0?{__impossible__:!0}:{_id:{$in:y}}}let l=await pn(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 h=await Qn(s,a,n,{_id:{$in:p}});return h.length===0?{__impossible__:!0}:{_id:{$in:h}}}async function pn(r,e,t,n,i){let o=new Set((t?.relations??[]).map(s=>s.propertyName));return ne(r,o)?Te(r,e,n,i):ge(n,r,e)}async function Wr(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 Kr(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 Qn(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 gn(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function hn(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 mn(r){if(Array.isArray(r))return r.map(e=>mn(e));if(typeof r!="string")return r;try{return new zn.ObjectId(r)}catch{return r}}function Vn(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof zn.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 At(r,e,t,n){let i=await It(r,e,t),o=[],s={},a={};if(n&&typeof n=="object")for(let[p,h]of Object.entries(n))if(typeof h=="object"&&h!==null){let g=Object.keys(h)[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]=h:a[p]=h}else s[p]=h;if(Object.keys(s).length>0){let p={};for(let[h,g]of Object.entries(s))if(typeof g=="object"&&g!==null)for(let[m,y]of Object.entries(g))sn(r,p,e,h,m,y);else p[h]=g;Object.keys(p).length>0&&o.push({$match:p})}let c=r?.tables?.get(e)?.relations||[],d=[];for(let[p,h]of Object.entries(a))if(!i.relations.some(m=>m.propertyName===p)){let m=c.find(y=>y.propertyName===p);if(m){let y="",b="";if(m.type==="many-to-one"||m.type==="one-to-one")y=z(m)||m.propertyName,b="_id";else if(m.type==="one-to-many")y="_id",b=K(m)||m.propertyName;else if(m.type==="many-to-many")continue;let $=m.type==="one-to-many"||m.type==="many-to-many";d.push({propertyName:p,targetTable:m.targetTableName,localField:y,foreignField:b,type:$?"many":"one",nestedFields:[]})}}let l=[...i.relations,...d];for(let p of l){let h=a[p.propertyName],g=p.nestedFields&&p.nestedFields.length>0?await At(r,p.targetTable,p.nestedFields,h):h?await At(r,p.targetTable,["_id"],h):[];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}}),h&&(Ve(h)||o.push({$match:{[p.propertyName]:{$ne:null}}})))}let f=c.filter(p=>!l.some(h=>h.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 Qr(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 Ve(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ve(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ve(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ve(e));if("_not"in r)return Ve(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||Ve(t)))return!0}return!1}Ge();var jt=require("mongodb");Ge();yn();async function bn(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 se="__sourceId__",ke="__targetId__",Ye="__enfyra_target__",Pt="__enfyra_top_n_documents__",Xe=class{constructor(e,t,n,i=new Ce){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.executionBudget=i;this.pkField="_id"}chunkCount(e){return Math.ceil(e.length/oe)||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}`,[Pt]:{$topN:{sortBy:n,output:"$$ROOT",n:i+o}}}},{$project:{[Pt]:{$slice:[`$${Pt}`,i,o]}}},{$unwind:`$${Pt}`},{$replaceRoot:{newRoot:`$${Pt}`}})}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 h=l[p],g=this.normalizeMetadata()?.tables?.get(f);if(!g)break;let m=g.relations?.find($=>$.propertyName===h);if(!m)break;let y=m.targetTableName||m.targetTable,b=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(b)){s.add(b);let $=z(m)||m.propertyName,_=p===0?null:`__sort_${l.slice(0,p).join("_")}`,T=_?`${_}.${$}`:$;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 jt.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof jt.ObjectId||t instanceof jt.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 jt.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}=He(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(h=>h.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 h=t.relations?.find(g=>g.propertyName===p);h&&(h.type==="many-to-one"||h.type==="one-to-one"&&!h.isInverse)&&(s||(o[z(h)||h.propertyName]=1))}),s||(o._id=1);let a=[];i.forEach((f,p)=>{let h=t.relations?.find(b=>b.propertyName===p);if(!h)return;let g=h.targetTableName||h.targetTable;if(!g)return;let m,y;h.type==="many-to-one"||h.type==="one-to-one"?Ie(h)?(m="_id",y=K(h)||h.propertyName):(m=z(h)||h.propertyName,y="_id"):h.type==="one-to-many"?(m="_id",y=K(h)||h.propertyName):h.type==="many-to-many"&&(h.isInverse?(m="_id",y=h.mappedBy):(m=h.propertyName,y="_id")),a.push({relationName:p,type:h.type,targetTable:g,fields:f,isInverse:h.isInverse,fkColumn:h.foreignKeyColumn,mappedBy:h.mappedBy,junctionTableName:h.junctionTableName,junctionSourceColumn:h.junctionSourceColumn,junctionTargetColumn:h.junctionTargetColumn,localField:m,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?ge(this.normalizeMetadata(),i.userFilter,e):null,s=this.buildSortFromTokens(i?.userSort),a=await W(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?ge(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 W(a,async _=>{let T={[t]:{$in:_}};u&&Object.keys(u).length>0&&Object.assign(T,u);let C=[{$match:T}];this.appendTopNStages(C,t,b,y,c),C.push({$sort:{[t]:1,...b}}),this.appendPartitionProjection(C,s,[t]);let x=await this.runQuery(()=>this.db.collection(e).aggregate(C).toArray());return this.applyReadFallback(x,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 bn(a,async $=>{let _={[t]:$};u&&Object.keys(u).length>0&&Object.assign(_,u);let T=this.buildSortAggregatePipeline(e,_,o.userSort);s&&T.push({$project:s});let C=await this.runQuery(()=>this.db.collection(e).aggregate(T).toArray());return this.applyReadFallback(C,i)},Me);for(let $ of b.values())for(let _ of $)y.push(_);return{docs:y,groupKeyField:t,stats:{strategy:"per-parent-dotted-sort",roundtrips:a.length,concurrencyWaves:Math.ceil(a.length/Me),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},h={projection:s,sort:p},g=await W(a,y=>this.runQuery(()=>this.db.collection(e).find({[t]:{$in:y},...u||{}},h).toArray())),m=this.applyReadFallback(g,i);return{docs:m,groupKeyField:t,stats:{strategy:"batch-in",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.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 W(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 W(e,async y=>{if(d){let _=[{$match:{[n.selfColumn]:{$in:y}}}];return this.appendTopNStages(_,n.selfColumn,{[n.otherColumn]:l},s,a),_.push({$sort:{[n.selfColumn]:1,[n.otherColumn]:l}},{$project:{_id:0,[se]:`$${n.selfColumn}`,[ke]:`$${n.otherColumn}`}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(_).toArray())).map(C=>({sourceId:C[se],targetId:C[ke]}))}let b=[{$match:{[n.selfColumn]:{$in:y}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ye}},{$unwind:`$${Ye}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ye}`,{[se]:`$${n.selfColumn}`,[ke]:`$${n.otherColumn}`}]}}}];return o&&Object.keys(o).length>0&&b.push({$match:o}),this.appendTopNStages(b,se,f,s,a),b.push({$sort:{[se]:1,...f}}),b.push({$project:{_id:0,[se]:1,[ke]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(b).toArray())).map(_=>({sourceId:_[se],targetId:_[ke]}))});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 h=this.uniqueValues(p.map(y=>y.targetId)),g=await this.loadM2MTargets(t.targetTable,h,i),m=new Map(g.map(y=>[this.keyOf(y._id),y]));for(let y of p){let b=m.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)+(h.length>0?this.chunkCount(h):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 W(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 m=[{$match:{[n.selfColumn]:{$in:g}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ye}},{$unwind:`$${Ye}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ye}`,{[se]:`$${n.selfColumn}`,[ke]:`$${n.otherColumn}`}]}}}];return o&&Object.keys(o).length>0&&m.push({$match:o}),m.push({$sort:{[se]:1,...c}},{$project:{_id:0,[se]:1,[ke]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(m).toArray())).map(b=>({sourceId:b[se],targetId:b[ke]}))});if(i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1){let g=new Map;for(let m of d){let y=this.keyOf(m.targetId);g.has(y)||g.set(y,{_id:m.targetId}),s.get(this.keyOf(m.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),h=new Map(p.map(g=>[this.keyOf(g._id),g]));for(let g of d){let m=h.get(this.keyOf(g.targetId));m&&s.get(this.keyOf(g.sourceId))?.push(m)}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=Ne(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(C=>C._id)),c=new Map;for(let C of e)c.set(this.keyOf(C._id),[]);if(u.length===0)return{grouped:c,docs:[]};let d=t.userFilter?ge(this.normalizeMetadata(),t.userFilter,t.targetTable):null,l=t.userLimit,f=t.userPage;if(l!==void 0&&l>0){let C=f?(f-1)*l:0;return this.fetchM2MTopK(u,t,a,o,d,C,l)}let p=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1&&!d,h=this.hasDottedSort(t.userSort);if(!h)return this.fetchM2MEdgeBatch(u,t,a,o,d);let g=await W(u,C=>this.runQuery(()=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:C}},{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 m=new Set,y=[];for(let C of g){let x=C[a.otherColumn];if(x==null)continue;let I=this.keyOf(x);m.has(I)||(m.add(I),y.push(x))}let b=[],$=new Map;if(p)b=y.map(C=>({_id:C})),this.sortDocsByPk(b);else{let C={_id:{$in:y}};d&&Object.keys(d).length>0&&Object.assign(C,d);let x;if(h){let I=this.buildSortAggregatePipeline(t.targetTable,C,t.userSort);o.projection&&I.push({$project:o.projection}),x=await this.runQuery(()=>this.db.collection(t.targetTable).aggregate(I).toArray())}else{let I=this.buildSortFromTokens(t.userSort)||{_id:1},M=this.projectionWithSortFields(o.projection,t.userSort),B={sort:I};M.projection&&(B.projection=M.projection),x=await W(y,S=>this.runQuery(()=>this.db.collection(t.targetTable).find({_id:{$in:S},...d||{}},B).toArray())),t.userSort?this.sortDocsInMemory(x,t.userSort):this.sortDocsByPk(x),this.removeHiddenFields(x,M.hiddenFields)}b=this.applyReadFallback(x,o)}for(let C of b)$.set(this.keyOf(C._id),C);let _=new Map;for(let C of g){let x=this.keyOf(C[a.selfColumn]),I=this.keyOf(C[a.otherColumn]);$.has(I)&&(_.has(I)||_.set(I,[]),_.get(I).push(x))}for(let C of b){let x=_.get(this.keyOf(C._id))||[];for(let I of x)c.get(I)?.push(C)}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 Xe(r,a,d);await new Se(l,n,u).execute(e,t,i,o,s)}async function Yn(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&&ne(e.mongoRawFilter,c),l=e.plan,f=l?.filterTree&&!l.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&o&&d){let S=await Te(e.mongoRawFilter,e.table,o,i);S&&Object.keys(S).length>0&&n.push({$match:S})}else if(f){let S=ze(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=Qe(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 O=S.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(A=>A.propertyName===O)??!1})??!1,m=()=>p?.sortItems?bo(p.sortItems):e.sort?yo(e.sort):null,y=p?.sortItems?fo(p.sortItems):[],b=p?.sortItems?po(p.sortItems):[],$=()=>{!p||y.length===0||go(n,e.table,p.sortItems,o)},_=()=>{!p||b.length===0||ho(n,e.table,p.sortItems,o)},T=()=>{let S=[...y,...b];S.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(S.map(O=>[O,0]))})};if(!e.mongoFieldsExpanded){$(),_();let S=m();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 L of e.select)A[L]=1;n.push({$project:A})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let O=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:O,pipeline:n}:{results:zr(O),pipeline:n}}let{scalarFields:C,relations:x}=e.mongoFieldsExpanded;if(!g){$(),_();let S=m();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 I=[];for(let S of x)if(e.sort?.some(A=>A.field.startsWith(`${S.propertyName}.`))){let A=e.mongoRawFilter?.[S.propertyName];if(S.nestedFields&&S.nestedFields.length>0){let w=await At(o,S.targetTable,S.nestedFields??[],A);S.type==="one"&&w.length>0&&w.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:w.length>0?w:void 0}})}else if(A){let w=await At(o,S.targetTable,["_id"],A);S.type==="one"&&w.length>0&&w.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:w.length>0?w: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&&(Ze(A)||n.push({$match:{[S.propertyName]:{$ne:null}}})))}else I.push(S);if(g){$(),_();let S=m();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 Qr(o,n,e.table,C,[...x]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let M=performance.now(),B=await r.aggregate(n).toArray();if(e.debugTrace?.dur("db_execute",M,{table:e.table}),e.mongoCountOnly)return{results:B,pipeline:n};if(I.length>0&&B.length>0){let S=e.deep||{},O=I.map(L=>{let k=o?.tables?.get(e.table)?.relations?.find(N=>N.propertyName===L.propertyName),F=S[L.propertyName],Z=F?.fields!=null?Array.isArray(F.fields)?F.fields:String(F.fields).split(",").map(N=>N.trim()).filter(Boolean):L.nestedFields&&L.nestedFields.length>0?L.nestedFields:["_id"];return{relationName:L.propertyName,type:k?.type,targetTable:L.targetTable,fields:Z,isInverse:k?.isInverse,mappedBy:k?.mappedBy,junctionTableName:k?.junctionTableName,junctionSourceColumn:k?.junctionSourceColumn,junctionTargetColumn:k?.junctionTargetColumn,localField:L.localField,foreignField:L.foreignField,userFilter:F?.filter,userSort:F?.sort,userLimit:F?.limit!==void 0?Number(F.limit):void 0,userPage:F?.page!==void 0?Number(F.page):void 0,nestedDeep:F?.deep}}),A=mo(o);A&&await _n(i,B,O,A,3,0,e.table,o,e.debugTrace,t.mongoPhysicalMigrationService)}return{results:zr(B),pipeline:n}}function Xn(r){return`__sort_count_${r.relationName||r.field}`}function Zn(r){return`__sort_${r.function}_${r.relationName||r.field}_${r.aggregateField||"value"}`}function fo(r){return r.filter(e=>e.function==="count").map(Xn)}function po(r){return r.filter(e=>e.function==="max"||e.function==="min").map(Zn)}function go(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=Xn(s);if(!(!a||!c)){if(a.type==="one-to-many"){let l=K(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=Ne(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 ho(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(m=>m.isPrimary)?.name||(d?.columns?.some(m=>m.name==="_id")?"_id":"id"),f=s.aggregateField,p=f==="id"&&d?.columns?.some(m=>m.name==="_id")?"_id":f,h=Zn(s),g=s.function==="min"?"$min":"$max";if(!(!a||!c||!f)){if(a.type==="one-to-many"){let m=K(a)||u;r.push({$lookup:{from:c,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${m}`,"$$localId"]}}},{$group:{_id:null,value:{[g]:`$${p}`}}}],as:h}}),r.push({$addFields:{[h]:{$arrayElemAt:[`$${h}.value`,0]}}});continue}if(a.type==="many-to-many"){let m=Ne(e,a);if(!m)continue;let y=`${h}_junction`;r.push({$lookup:{from:m.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${m.selfColumn}`,"$$localId"]}}},{$project:{_id:0,targetId:`$${m.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:h}}),r.push({$addFields:{[h]:{$arrayElemAt:[`$${h}.value`,0]}}}),r.push({$project:{[y]:0}})}}}}function mo(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 yo(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 bo(r){let e={};for(let t of r){let n=t.function==="count"?Xn(t):t.function==="max"||t.function==="min"?Zn(t):t.joinId!==null?t.fullPath:t.field;e[n]=t.direction==="asc"?1:-1}return e}function Ze(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ze(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ze(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ze(e));if("_not"in r)return Ze(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||Ze(t)))return!0}return!1}function zr(r){return r.map(te)}function Vr(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(_o(o,i,e));return{scalarFields:t,relations:n}}function _o(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&&Ie(n)?(i="_id",o=K(n)||r.propertyName,s=!0):(i=n&&z(n)||r.propertyName,o="_id",s=!1):r.relationType==="one-to-many"?(i="_id",o=n&&K(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=Hr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:i,foreignField:o,type:a?"many":"one",isInverse:s,nestedFields:u}}function Hr(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=Hr(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let i of n)e.push(`${t.propertyName}.${i}`)}return e}Je();Mt();Ot();function wn(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("."),h=f.substring(0,p),g=f.substring(p+1);if(!o.relations?.some(y=>y.propertyName===h))continue;c.has(h)||c.set(h,[]),c.get(h).push(g)}else if(o.relations?.some(h=>h.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(m=>m.propertyName===l);if(!p)continue;let h=p.targetTableName||p.targetTable,g={kind:"relation",propertyName:l,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:h,children:Gr(f,h,t)};if(p.type==="many-to-one"||p.type==="one-to-one"){let m=n.registerWithParent(e,l,t,"left",null,"data");g.joinId=m}i.nodes.push(g)}return i}function Gr(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),h=l.substring(f+1);if(!n.relations?.some(m=>m.propertyName===p))continue;a.has(p)||a.set(p,[]),a.get(p).push(h)}else if(n.relations?.some(p=>p.propertyName===l))a.has(l)||a.set(l,[s]);else{if(!n.columns?.some(h=>h.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(h=>h.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:Gr(l,p,t)})}return c}de();de();var wo=new Set(["_and","_or","_not"]);function Yr(r,e){return r?.tables?.get(e)??null}function $o(r,e,t){return Yr(r,e)?.columns?.find(n=>n.name===t)}function er(r,e,t){return Yr(r,e)?.relations?.find(n=>n.propertyName===t)}function To(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 tr(r,e,t,n){if($o(r,e,t)?.isEncrypted===!0)throw new v(`Encrypted field '${t}' on '${e}' cannot be used for ${n}.`)}function Ee(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){for(let n of r)Ee(n,e,t);return}for(let[n,i]of Object.entries(r)){if(wo.has(n)){Ee(i,e,t);continue}if(n.startsWith("_"))continue;let o=er(t,e,n);if(o){let s=o.targetTableName||o.targetTable;s&&Ee(i,s,t);continue}tr(t,e,n,"filter")}}}function $n(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=To(o);if(s){if(s.functionName==="count")continue;let c=er(t,e,s.relationName),d=c?.targetTableName||c?.targetTable;d&&tr(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){tr(t,u,d,"sort");break}let f=er(t,u,d);if(!f)break;u=f.targetTableName||f.targetTable||u}}}var X=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 ie,p=this.parseFields(n),h=null;p&&l&&(h=wn(p,t,c,f));let g=!1,m=null;if(i&&l){Ee(i,t,c);let S=fe(i,t,c,f);m=S.node,g=S.hasRelationFilters}let y=this.parseSort(o);l&&$n(y,t,c);let b=[],$=!1;for(let S of y){let O=S.startsWith("-"),A=O?S.substring(1):S,L=O?"desc":"asc";if(l){let w=this.parseRelationAggregateSort(t,l,A,c);if(w){b.push({joinId:null,field:A,direction:L,fullPath:A,function:w.functionName,relationName:w.relationName,aggregateField:w.aggregateField,relationMeta:w.relationMeta});continue}this.assertLocalSortField(t,l,A)}b.push({joinId:null,field:A,direction:L,fullPath:A})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let _=this.parseLimit(a),T=this.parsePage(s),C=T!==void 0&&_!==void 0?(T-1)*_:void 0,x=this.parseMeta(u),I=x.includes("totalCount")||x.includes("*"),M=x.includes("filterCount")||x.includes("*"),B=f.getAll();return{table:t,dbType:d,rawFields:p,rawFilter:i??null,joins:B,sortItems:b,limit:_,offset:C,needsTotalCount:I,needsFilterCount:M,hasRelationFilters:g,hasRelationSort:$,filterTree:m,fieldTree:h}}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 v(`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 v(`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 v(`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 m=a;if(!m||m.includes("."))throw new v(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let y=t.relations?.find(b=>b.propertyName===m);if(!y)throw new v(`Sort relation '${m}' does not exist on '${e}'.`);if(y.type!=="one-to-many"&&y.type!=="many-to-many")throw new v(`Sort function '_count(${m})' is only supported for list relations on '${e}'.`);return{functionName:s,relationName:m,relationMeta:y}}let u=a.indexOf(".");if(u<=0||u!==a.lastIndexOf("."))throw new v(`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 v(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let l=t.relations?.find(m=>m.propertyName===c);if(!l)throw new v(`Sort relation '${c}' does not exist on '${e}'.`);if(l.type!=="one-to-many"&&l.type!=="many-to-many")throw new v(`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 v(`Sort function '${n}' references unknown target table '${f}' on '${e}'.`);let h=p.columns?.find(m=>m.name===d),g=d==="id"&&p.columns?.some(m=>m.name==="_id");if(!h&&!g)throw new v(`Sort field '${d}' does not exist on '${f}' for function '_${s}(${c}.${d})'.`);if(h?.isEncrypted===!0)throw new v(`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)}};de();var So=new Set(["int","integer","bigint","smallint","tinyint","float","double","decimal","numeric","real","number"]),Co=new Set(["date","datetime","timestamp","timestamptz","timestamp with time zone","timestamp without time zone"]),ko=new Set(["hour","day","week","month","year"]),Fo=new Set(["count","countDistinct","sum","avg","min","max"]);function E(r,e){throw new v(e,{path:r})}function et(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Ro(r,e){let t=r?.tables?.get(e);return t||E("aggregate",`Table "${e}" metadata is not available`),t}function Xr(r,e,t){let n=r.columns?.find(i=>i.name===e);return n||E(t,`Unknown aggregate field "${e}"`),n.isEncrypted===!0&&E(t,`Encrypted field "${e}" cannot be used in aggregate queries`),n}function xo(r,e){let t=r===void 0?"UTC":r;(typeof t!="string"||t.length===0)&&E(e,"Aggregate timezone must be a non-empty IANA timezone");try{new Intl.DateTimeFormat("en-US",{timeZone:t}).format()}catch{E(e,`Invalid aggregate timezone "${t}"`)}return t}function vo(r,e){return r==null?{}:(et(r)||E(e,"Aggregate filter must be an object"),r)}function tt(r,e,t){et(r)||E("aggregate","Aggregate options must be an object");let n=Ro(t,e),i=r.dimensions===void 0?[]:r.dimensions,o=r.measures;Array.isArray(i)||E("aggregate.dimensions","Aggregate dimensions must be an array"),(!et(o)||Object.keys(o).length===0)&&E("aggregate.measures","Aggregate requires at least one measure");let s=new Set,a=i.map((g,m)=>{let y=`aggregate.dimensions[${m}]`;(!et(g)||typeof g.field!="string"||g.field.length===0)&&E(y,"Aggregate dimension requires a field");let b=Xr(n,g.field,`${y}.field`);return s.has(g.field)&&E(`${y}.field`,`Duplicate aggregate dimension "${g.field}"`),s.add(g.field),g.bucket===void 0?(g.timezone!==void 0&&E(`${y}.timezone`,"Aggregate timezone requires a bucket"),{field:g.field,outputKey:g.field,column:b}):((typeof g.bucket!="string"||!ko.has(g.bucket))&&E(`${y}.bucket`,"Aggregate bucket must be hour, day, week, month, or year"),Co.has(String(b.type).toLowerCase())||E(`${y}.bucket`,`Aggregate bucket requires a date field, but "${g.field}" is "${b.type}"`),{field:g.field,outputKey:g.field,bucket:g.bucket,timezone:xo(g.timezone,`${y}.timezone`),column:b})}),u=new Set,c=Object.entries(o).map(([g,m])=>{let y=`aggregate.measures.${g}`;(!g||!et(m))&&E(y,"Aggregate measure must be an object");let b=Object.entries(m).filter(([C])=>C!=="as");b.length!==1&&E(y,"Aggregate measure must define exactly one operation");let[$,_]=b[0];Fo.has($)||E(y,`Unsupported aggregate measure "${$}"`),(typeof _!="string"||_.length===0)&&E(y,"Aggregate measure field must be a non-empty string");let T=Xr(n,_,`${y}.${$}`);return(u.has(g)||s.has(g))&&E(y,`Aggregate output key "${g}" is duplicated`),u.add(g),["sum","avg","min","max"].includes($)&&!So.has(String(T.type).toLowerCase())&&E(y,`Aggregate ${$} requires a numeric field, but "${_}" is "${T.type}"`),{outputKey:g,operation:$,field:_,column:T}}),d=r.sort===void 0?[]:r.sort;Array.isArray(d)||E("aggregate.sort","Aggregate sort must be an array");let l=new Set([...s,...u]),f=d.map((g,m)=>{let y=`aggregate.sort[${m}]`;return(!et(g)||typeof g.field!="string"||!l.has(g.field))&&E(y,"Aggregate sort field must reference a dimension or measure output"),g.direction!=="asc"&&g.direction!=="desc"&&E(`${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),h=r.page===void 0?1:Number(r.page);return p!==void 0&&(!Number.isInteger(p)||p<=0||p>1e4)&&E("aggregate.limit","Aggregate limit must be an integer between 1 and 10000"),(!Number.isInteger(h)||h<=0)&&E("aggregate.page","Aggregate page must be a positive integer"),{tableName:e,filter:vo(r.filter,"aggregate.filter"),dimensions:a,measures:c,sort:f,page:h,limit:p}}var Ae=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 X;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&&(re(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&&ne(n.mongoRawFilter,u);if((i.includes("filterCount")||i.includes("*"))&&!c){let l=this.mongoService.collection(e.tableName),f=e.plan?.filterTree?ze(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=tt(e.aggregate,e.tableName,e.metadata),n=this.db.collection(e.tableName),i=new X().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:"mongodb"}),o=i.hasRelationFilters?await Te(t.filter,e.tableName,e.metadata,this.db):i.filterTree?ze(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(te)}}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=Vr(c.fieldTree,this.metadata),n){let l=await It(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 It(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(te);let{results:a,pipeline:u}=await Yn(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 Yn(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=i,n}};var Tn=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}};de();ae();var Io=["_and","_or","_not"];function he(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>he(e));for(let e of Object.keys(r))if(Io.includes(e)||typeof r[e]=="object"&&r[e]!==null&&he(r[e]))return!0;return!1}var Zr=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function No(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function Sn(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 Oo(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)||Sn(r,t,i),e}function ei(r,e,t,n,i,o,s){let a=i&&!e.includes(".")?`${i}.${e}`:e,u=Fe(a,o??"postgres"),c=Sn(e,i,s),d=Oo(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,No(t),n)}}function Mo(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 nt(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(){nt(this,s,t,"and",i,o)}):r.orWhere(function(){nt(this,s,t,"and",i,o)});return}for(let[s,a]of Object.entries(e))if(Mo(s,t,o)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){nt(this,u,t,"and",i,o)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){nt(this,u,t,"and",i,o)})});continue}if(s==="_not"){r.whereNot(function(){nt(this,a,t,"and",i,o)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(c=>Zr.includes(c)))for(let[c,d]of Object.entries(a))Zr.includes(c)&&(n==="and"?r.where(function(){ei(this,s,c,d,t,i,o)}):r.orWhere(function(){ei(this,s,c,d,t,i,o)}));else{let c=t&&!s.includes(".")?`${t}.${s}`:s,d=Fe(c,i??"postgres");Sn(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");Sn(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 le(r,e,t,n,i){return!e||typeof e!="object"||nt(r,e,t,"and",n,i),r}ae();function ir(r,e,t){return`${R(r,t)}.${R(e,t)}`}function Re(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 ti(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 rt(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function or(r,e,t,n,i,o){let s=[];for(let[a,u]of Object.entries(o)){let c=await Bt(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=ir(e,d.foreignKeyColumn,n),p=u.id;if(p&&typeof p=="object"){let h=rt(p._is_null),g=rt(p._is_not_null);if(h===!0)s.push(`${l} IS NULL`);else if(h===!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 m=Re(p._eq,n);s.push(`${l} = ${m}`)}else if(p._neq!==void 0){let m=Re(p._neq,n);s.push(`${l} != ${m}`)}else if(p._in!==void 0){let y=(Array.isArray(p._in)?p._in:[p._in]).map(b=>Re(b,n)).join(", ");s.push(`${l} IN (${y})`)}else if(p._not_in!==void 0||p._nin!==void 0){let m=p._not_in??p._nin,b=(Array.isArray(m)?m:[m]).map($=>Re($,n)).join(", ");s.push(`${l} NOT IN (${b})`)}else if(p._gt!==void 0){let m=Re(p._gt,n);s.push(`${l} > ${m}`)}else if(p._gte!==void 0){let m=Re(p._gte,n);s.push(`${l} >= ${m}`)}else if(p._lt!==void 0){let m=Re(p._lt,n);s.push(`${l} < ${m}`)}else if(p._lte!==void 0){let m=Re(p._lte,n);s.push(`${l} <= ${m}`)}}}}}return s}function sr(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 nr(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(sr(c)){let d=e(t).select(`${t}.id`);await Pe(e,d,c,t,n,i,o),u.push({idSubquery:d})}else{let{fieldFilters:d,relationFilters:l}=V(c,n),f=await or(e,t,n,i,o,l);u.push({fieldFilters:d,subqueries:f})}s.push(u)}else if(sr(a)){let u=e(t).select(`${t}.id`);await Pe(e,u,a,t,n,i,o),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:c}=V(a,n),d=await or(e,t,n,i,o,c);s.push([{fieldFilters:u,subqueries:d}])}return s}function ni(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&&le(this,o.fieldFilters,t,i,n);for(let s of o.subqueries)this.whereRaw(s)})}function rr(r,e,t,n,i){let o=!0;for(let s of e){let a=function(){for(let u of s)ni(this,u,t,n,i)};o?(r.where(a),o=!1):r.orWhere(a)}}function Cn(r,e,t,n,i,o,s){let a=ti(e,i),u=ti(n,o),c=`${R(r,s)}.${R(e,s)}`,d=`${R(t,s)}.${R(n,s)}`;if(s==="postgres"){if(a&&!u)return`${c} = ${d}::uuid`;if(!a&&u)return`${c}::uuid = ${d}`}return`${c} = ${d}`}async function Bt(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(h=>c.has(h)))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(Cn(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(Cn(a.junctionTableName,a.junctionTargetColumn,u,"id",f,d,o))).whereRaw(Cn(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(Cn(u,"id",e,a.foreignKeyColumn,d,i,o));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?d?await Pe(r,l,n,u,d,o,s):l=le(l,n,u,o,d||void 0):l=le(l,n,u,o),l.toString()}async function Pe(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 nr(c._or,r,n,i,o,s);e.where(function(){rr(this,d,n,i,o)})}else if(c._and&&Array.isArray(c._and)&&c._and.length>0)for(let d of c._and)await Pe(r,e,d,n,i,o,s);else await Pe(r,e,c,n,i,o,s);return}if(t._or&&Array.isArray(t._or)){let c=await nr(t._or,r,n,i,o,s);e.where(function(){rr(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(sr(p)){let h=r(n).select(`${n}.id`);await Pe(r,h,p,n,i,o,s),f.push({idSubquery:h})}else{let{fieldFilters:h,relationFilters:g}=V(p,i),m=await or(r,n,i,o,s,g);f.push({fieldFilters:h,subqueries:m})}e.whereNot(function(){for(let p of f)ni(this,p,n,i,o)});return}if(c._or&&Array.isArray(c._or)&&c._or.length>0){let f=await nr(c._or,r,n,i,o,s);e.whereNot(function(){rr(this,f,n,i,o)});return}let{fieldFilters:d,relationFilters:l}=V(c,i);e.whereNot(function(){Object.keys(d).length>0&&le(this,d,n,o,i)});for(let[f,p]of Object.entries(l)){let h=await Bt(r,n,f,p,i,o,s);if(h===null){let g=i.relations.find(m=>m.propertyName===f);if(g&&g.foreignKeyColumn){let m=ir(n,g.foreignKeyColumn,o),b=p.id;if(b&&typeof b=="object"){let $=rt(b._is_null),_=rt(b._is_not_null);if($===!0)e.whereRaw(`${m} IS NOT NULL`);else if($===!1)e.whereRaw(`${m} IS NULL`);else if(_===!0)e.whereRaw(`${m} IS NULL`);else if(_===!1)e.whereRaw(`${m} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${m} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${m} = ?`,[b._neq]);else if(b._in!==void 0){let T=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${m} NOT IN (${T.map(()=>"?").join(", ")})`,T)}else if(b._not_in!==void 0||b._nin!==void 0){let T=b._not_in??b._nin,C=Array.isArray(T)?T:[T];e.whereRaw(`${m} IN (${C.map(()=>"?").join(", ")})`,C)}}}}else e.whereRaw(`NOT EXISTS (${h})`)}return}let{fieldFilters:a,relationFilters:u}=V(t,i);Object.keys(a).length>0&&le(e,a,n,o,i);for(let[c,d]of Object.entries(u)){let l=await Bt(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=ir(n,f.foreignKeyColumn,o),g=d.id;if(g&&typeof g=="object"){let m=rt(g._is_null),y=rt(g._is_not_null);if(m===!0)e.whereRaw(`${p} IS NULL`);else if(m===!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 Lt(r,e,t,n,i,o,s){await Pe(r,e,t,n,i,o,s)}ae();ae();function it(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=Dt(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=>Dt(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=>Dt(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=Dt(n,a,u,f[0]),m=Dt(n,a,u,f[1]);r=r.whereBetween(o.field,[g,m])}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 Wt(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=Wt(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=Wt(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=Wt(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=`${R(e,n)}.${R(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(h=>typeof h=="string"?`'${h.replace(/'/g,"''")}'`:String(h)).join(", ");i.push(`${d} IN (${p})`)}else if(u==="_not_in"||u==="_nin"){let p=(Array.isArray(c)?c:[c]).map(h=>typeof h=="string"?`'${h.replace(/'/g,"''")}'`:String(h)).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=`${R(e,n)}.${R(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 Kt(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 Dt(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}}lr();Je();ae();qt();Ke();async function oi(r,e,t,n,i,o,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(ur(),ii)),u=await a(e,t,n,i,o,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function dr(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 si(r,e,t,n,i){let o=r.targetTableName||r.targetTable;if(!o)return null;let s=r.foreignKeyColumn||J(r.propertyName);if(!s)return null;let a=l=>R(l,i),u=n?.tables?.get(o),d=(u?H(u):null)?.name||"id";return`(SELECT ${a(o)}.${a(e)} FROM ${a(o)} WHERE ${a(o)}.${a(d)} = ${a(t)}.${a(s)})`}qt();var je=class r{constructor(e,t,n,i){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=i;this.logger=new Tn(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&&re(e.filter,e.tableName,e.metadata),!e.plan){let w=new X;e={...e,plan:w.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 w=await this.executeSimple(e,o);return i&&i.dur("sql_executor",t,{table:e.tableName}),w}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(w=>w.trim())));let f=e.filter;if(e.filter&&!he(e.filter)){l.where=[];for(let[w,k]of Object.entries(e.filter))if(typeof k=="object"&&k!==null)for(let[F,Z]of Object.entries(k)){let N;if(F==="_eq")N="=";else if(F==="_neq")N="!=";else if(F==="_in")N="in";else if(F==="_not_in"||F==="_nin")N="not in";else if(F==="_gt")N=">";else if(F==="_gte")N=">=";else if(F==="_lt")N="<";else if(F==="_lte")N="<=";else if(F==="_contains")N="_contains";else if(F==="_starts_with")N="_starts_with";else if(F==="_ends_with")N="_ends_with";else if(F==="_between")N="_between";else if(F==="_is_null")N="_is_null";else if(F==="_is_not_null")N="_is_not_null";else if(F==="_like")N="like";else if(F==="_ilike")N="ilike";else continue;l.where.push({field:w,operator:N,value:Z})}else l.where.push({field:w,operator:"=",value:k})}if(e.sort){let w=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(k=>k.trim());l.sort=w.map(k=>{let F=k.trim();return F.startsWith("-")?{field:F.substring(1),direction:"desc"}:{field:F,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,h=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,m=g===void 0||Number.isNaN(g)?void 0:g;m&&h!==void 0?(l.offset=(m-1)*h,l.limit=h):h!==void 0&&(l.limit=h);let y=e.plan?.sortItems??(l.sort??[]).map(w=>({joinId:null,field:w.field,direction:w.direction,fullPath:w.field})),b=[],$=[];for(let w of y){if(w.function==="count"){let k={sql:this.buildRelationCountSortSubquery(l.table,w),direction:w.direction};$.push(k);continue}if(w.function==="max"||w.function==="min"){let k={sql:this.buildRelationAggregateSortSubquery(l.table,w),direction:w.direction};$.push(k);continue}if(w.joinId===null){if(w.field.includes(".")&&!e.plan){let F=w.field.split(".")[0];if(this.metadata?.tables?.get(l.table)?.relations?.some(U=>U.propertyName===F))continue}let k={field:w.field.includes(".")?w.field:`${l.table}.${w.field}`,direction:w.direction};b.push(k),$.push(k)}else{let k=e.plan?.joins.find(F=>F.id===w.joinId);if(k&&(k.relationType==="many-to-one"||k.relationType==="one-to-one")){let F=si(k.relationMeta,w.field,l.table,this.metadata,this.dbType);if(F){let Z={sql:F,direction:w.direction};$.push(Z)}}}}let _=[];if(l.fields&&l.fields.length>0||u||a){let w=dr(this.metadata),k=l.fields&&l.fields.length>0?l.fields:["*"],F=await oi(this.knex,l.table,k,w,this.dbType,this.maxQueryDepth,e.deep);F.select.length>0&&(l.select=[...l.select||[],...F.select]),_=F.batchFetchDescriptors||[]}l.where&&(l.where=l.where.map(w=>w.field.includes(".")?w:{...w,field:`${l.table}.${w.field}`})),l.sort=b;let T=this.knex(l.table),C=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(w=>w.trim()).filter(Boolean),x=C.includes("filterCount")||C.includes("*"),I=C.includes("totalCount")||C.includes("*");if(l.select){let w=l.select.map(k=>typeof k=="string"&&k.trim().startsWith("(")?this.knex.raw(k):typeof k=="string"&&/ as /i.test(k)?this.knex.raw(k):k);T=T.select(w)}if(x&&T.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),I){let w=R(l.table,this.dbType);T.select(this.knex.raw(`(SELECT COUNT(*) FROM ${w}) as __total_count__`))}let M=["table_definition","column_definition","relation_definition","method_definition"].includes(l.table);if(f&&(he(f)||Object.keys(f).length>0)){let w=this.metadata?.tables?.get(l.table);(!M&&w&&w.relations&&w.relations.length>0?V(f,w).hasRelations:!1)?await Lt(this.knex,T,f,l.table,w,this.dbType,F=>this.metadata?.tables?.get(F)):e.plan?.filterTree?ce(T,e.plan.filterTree,{dbType:this.dbType,rootTable:l.table}):(this.logger.debug(`buildWhereClause fallback for table=${l.table}`),T=le(T,f,l.table,this.dbType,w))}else l.where&&l.where.length>0&&(T=it(T,l.where,l.table,this.metadata,this.dbType));for(let w of $)if(w.field){let k=w.field.includes(".")?w.field:`${l.table}.${w.field}`;T=T.orderBy(k,w.direction)}else w.sql&&(T=T.orderByRaw(`${w.sql} ${w.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 w=T.toSQL().toNative();i.setSql(w.sql);try{let k=w.sql.replace(/\$\d+/g,"?"),F=await this.knex.raw(`EXPLAIN ${k}`,w.bindings);i.setExplain(this.dbType==="postgres"?F.rows:F[0])}catch(k){i.setExplain({error:String(k)})}}let O,A=performance.now();O=await T,i&&i.dur("db_execute",A,{table:e.tableName});let L=0;if(x&&O.length>0&&(L=Number(O[0].__filter_count__||0),O.forEach(w=>{delete w.__filter_count__})),I&&O.length>0&&O[0].__total_count__!==void 0&&(B=Number(O[0].__total_count__||0),O.forEach(w=>{delete w.__total_count__})),_&&_.length>0&&O.length>0){let w=dr(this.metadata);if(w){let{executeBatchFetches:k}=await Promise.resolve().then(()=>(gr(),ai));await k(this.knex,O,_,w,this.maxQueryDepth??3,0,l.table,this.dbType,this.metadata,i)}}if(this.knexService){let w=performance.now();O=await this.knexService.parseResult(O,l.table),i&&i.dur("db_parseResult",w,{table:e.tableName})}else{let w=(k,F)=>{if(!k||!this.metadata)return k;let Z=this.metadata.tables?.get(F);if(!Z)return k;if(Array.isArray(k))return k.map(U=>w(U,F));if(typeof k!="object"||Buffer.isBuffer(k))return k;let N={...k};for(let U of Z.columns)if(U.type==="simple-json"&&N[U.name]&&typeof N[U.name]=="string")try{N[U.name]=JSON.parse(N[U.name])}catch{}for(let[U,G]of Object.entries(N))if(G&&typeof G=="object"&&!Array.isArray(G)&&!Buffer.isBuffer(G)){let Nn=G;if(Nn.id!==void 0||Nn.createdAt!==void 0){let lt=Z.relations?.find(ct=>ct.propertyName===U);lt&&(N[U]=w(G,lt.targetTableName))}}else if(Array.isArray(G)&&G.length>0&&typeof G[0]=="object"&&G[0].id!==void 0){let lt=Z.relations?.find(ct=>ct.propertyName===U);lt&&(N[U]=G.map(ct=>w(ct,lt.targetTableName)))}return N};O=w(O,l.table)}return i&&(i.setQueryPath("full"),i.dur("sql_executor",t,{table:e.tableName})),{data:O,...C.length>0&&{meta:{...C.includes("totalCount")||C.includes("*")?{totalCount:B}:{},...C.includes("filterCount")||C.includes("*")?{filterCount:L}:{}}},...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=H(s)?.name||"id",u=R(e,this.dbType),c=R(a,this.dbType);if(!n||!o)throw new v(`Sort relation '${i}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let d=n.foreignKeyColumn||n.mappedBy;if(!d)throw new v(`Sort function '_count(${i})' cannot resolve relation key on '${e}'.`);let l=R(o,this.dbType),f=R(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=R(d.tableName,this.dbType),f=R(d.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}throw new v(`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=H(a)?.name||"id",d=H(u)?.name||"id",l=R(e,this.dbType),f=R(c,this.dbType),p=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!p||!n||!s||!o)throw new v(`Sort function '${t.field}' is not supported on '${e}'.`);let h=R(s,this.dbType),g=R(o,this.dbType);if(n.type==="one-to-many"){let m=n.foreignKeyColumn||n.mappedBy;if(!m)throw new v(`Sort function '_${t.function}(${i}.${o})' cannot resolve relation key on '${e}'.`);let y=R(m,this.dbType);return`(SELECT ${p}(${h}.${g}) FROM ${h} WHERE ${h}.${y} = ${l}.${f})`}if(n.type==="many-to-many"){let m=this.resolveManyToManyContract(n,i,e),y=R(m.tableName,this.dbType),b=R(m.sourceColumn,this.dbType),$=R(m.targetColumn,this.dbType),_=R(d,this.dbType);return`(SELECT ${p}(${h}.${g}) FROM ${y} JOIN ${h} ON ${h}.${_} = ${y}.${$} WHERE ${y}.${b} = ${l}.${f})`}throw new v(`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 v(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}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&&ce(o,t.filterTree,{dbType:this.dbType,rootTable:n});for(let g of t.sortItems){let m=g.field.includes(".")?g.field:`${n}.${g.field}`;o=o.orderBy(m,g.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(g=>g.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 g=R(n,this.dbType);o.select(this.knex.raw(`(SELECT COUNT(*) FROM ${g}) as __total_count__`))}let c=e.debugTrace,d;if(e.debugMode){let g=o.toSQL().toNative();if(d=g.sql,c){c.setSql(g.sql);try{let m=g.sql.replace(/\$\d+/g,"?"),y=await this.knex.raw(`EXPLAIN ${m}`,g.bindings);c.setExplain(this.dbType==="postgres"?y.rows:y[0])}catch(m){c.setExplain({error:String(m)})}}}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=0,h=0;return a&&f.length>0&&(p=Number(f[0].__filter_count__||0),f.forEach(g=>delete g.__filter_count__)),u&&f.length>0&&(h=Number(f[0].__total_count__||0),f.forEach(g=>delete g.__total_count__)),{data:f,...s.length>0&&{meta:{...u?{totalCount:h}:{},...a?{filterCount:p}:{}}},...d!==void 0&&{sql:d}}}async aggregate(e){let t=tt(e.aggregate,e.tableName,e.metadata),n=this.knex(e.tableName),i=R(e.tableName,this.dbType),o=[],s=[];for(let l of t.dimensions){let f=`${i}.${R(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 ${R(l.outputKey,this.dbType)}`)),o.push(p)}for(let l of t.measures){let f=`${i}.${R(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 ${R(l.outputKey,this.dbType)}`))}let u=new X().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:this.dbType});u.hasRelationFilters?await Lt(this.knex,n,t.filter,e.tableName,e.metadata?.tables?.get(e.tableName),this.dbType,l=>e.metadata?.tables?.get(l)):u.filterTree&&ce(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(`${R(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 h=f[p.outputKey];h!=null&&typeof h=="string"&&/^-?\d+(\.\d+)?$/.test(h)&&(f[p.outputKey]=Number(h))}return f})}}buildSqlBucketExpression(e,t,n,i){let o=Kt(n);if(this.dbType==="postgres"){let s=`(${e} AT TIME ZONE ${o})`;return`DATE_TRUNC(${Kt(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 v(`Aggregate time bucket is not supported on ${this.dbType}`)}};var Rn=require("mongodb"),at=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,xn.mkdirSync)((0,li.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(!Rn.ObjectId)return e;if(typeof e=="string")try{return new Rn.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=Qe(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:it(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(te(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 X().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 Ae(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 je(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 Rn.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 Ae(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 je(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 te(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 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,xn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
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 te(o)}return await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first()})}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 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}};gr();fr();ur();ae();qt();Ge();yn();de();Je();var ci=new Set(["fields","filter","sort","limit","page","deep"]),In=3;function hr(r,e,t,n=0,i=3){if(!e||typeof e!="object")return;if(n>=i)throw new v(`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 v(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let f of Object.keys(u))if(!ci.has(f))throw new v(`Unknown deep option key '${f}' for relation '${a}'. Allowed: ${[...ci].join(", ")}`);let d=c.type;if(u.limit!==void 0&&(d==="many-to-one"||d==="one-to-one"))throw new v(`'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 v(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let l=c.targetTableName||c.targetTable;if(l){if(u.filter&&(re(u.filter,l,t),Ee(u.filter,l,t),vn(u.filter,0,a,r)),u.sort){$n(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 h=p.startsWith("-")?p.slice(1):p;jo(h,l,t,a,r)}}u.deep&&hr(l,u.deep,t,n+1,i)}}}function jo(r,e,t,n,i){if(r.includes("."))throw new v(`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 v(`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 v(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${i}')`)}var Bo=new Set(["_and","_or","_not"]);function vn(r,e,t,n){if(!(!r||typeof r!="object"))for(let[i,o]of Object.entries(r)){if(Bo.has(i)){if(Array.isArray(o))for(let c of o)vn(c,e,t,n);else o&&typeof o=="object"&&vn(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>In)throw new v(`Filter path exceeds max dotted hops of ${In} at '${i}' (relation '${t}' on '${n}')`);let u={};for(let c of Object.keys(o))c.startsWith("_")||(u[c]=o[c]);vn(u,a,t,n)}}function ui(r,e,t,n){return!r||typeof r!="object"?r:Jt(r,e,t,n)}function Jt(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let o=r.map(s=>Jt(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=>Jt(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=Jt(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=Jt(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 di(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],h=f===c.length-1,g=t?.tables?.get(l);if(!g){d=!1;break}if(h)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 m=g.relations?.find(y=>y.propertyName===p);if(!m){d=!1;break}if(!n(l,p,"relation")){d=!1;break}l=m.targetTableName||m.targetTable||l}}d&&o.push(s)}if(o.length!==0)return Array.isArray(r)?o:o.join(",")}Ot();Je();Mt();ln();Ke();de();function Lo(r){let e=new at({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,i=()=>(t||(t=new We({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),o=()=>(n||(n=new Be({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.48",
3
+ "version": "1.1.49",
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.48",
3
+ "version": "1.1.49",
4
4
  "description": "Closed-distribution Enfyra kernel runtime",
5
5
  "license": "Elastic-2.0",
6
6
  "packageManager": "yarn@4.17.0",