@enfyra/kernel 1.1.49 → 1.1.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
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,`
|
|
1
|
+
"use strict";var pi=Object.create;var zt=Object.defineProperty;var gi=Object.getOwnPropertyDescriptor;var hi=Object.getOwnPropertyNames;var mi=Object.getPrototypeOf,yi=Object.prototype.hasOwnProperty;var q=(r,e)=>()=>(r&&(e=r(r=0)),e);var Mn=(r,e)=>{for(var t in e)zt(r,t,{get:e[t],enumerable:!0})},yr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of hi(e))!yi.call(r,i)&&i!==t&&zt(r,i,{get:()=>e[i],enumerable:!(n=gi(e,i))||n.enumerable});return r};var ue=(r,e,t)=>(t=r!=null?pi(mi(r)):{},yr(e||!r||!r.__esModule?zt(t,"default",{value:r,enumerable:!0}):t,r)),bi=r=>yr(zt({},"__esModule",{value:!0}),r);function Fr(r){return Bn.createHash("md5").update(r).digest("hex").substring(0,8)}function vr(r){return r.length<=Rr-3?`${r}_pk`:`j_${Fr(r)}_pk`}function xr(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=Rr?n:`j_${Fr(r)}_${t}_fk`}function vt(r,e,t){let n=`${r}:${e}:${t}`;return`j_${Bn.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function J(r){return`${r}Id`}function xt(r,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function Ir(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function Nr(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function Er(r,e,t){return`${r}_${e}_${t}_fk`}function Mr(r,e,t){return`${r}_${e}_${t}_idx`}var Bn,Rr,Ke=q(()=>{"use strict";Bn=ue(require("crypto")),Rr=63});function ln(r){return eo[r]??null}var we,Kn,Nt,eo,cn=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"]),Kn=new Set(["_and","_or","_not"]),Nt=[...Array.from(Kn),...Array.from(we)],eo={_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 I,de=q(()=>{"use strict";I=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 jr(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var Br=q(()=>{"use strict"});function Ee(r,e,t){throw new I({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${Nt.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:Nt})}function un(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=jr();for(let i of Object.keys(e))if(i.startsWith("_")&&!we.has(i)){if(n&&i==="_id")continue;Ee(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(to.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)){un(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"&&Ee(s,s,e),a&&typeof a=="object"&&!Array.isArray(a)&&un(s,a,e)}}var to,Je=q(()=>{"use strict";de();cn();Br();to=new Set(["_and","_or","_not"])});function fe(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:dn(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function dn(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=no(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 no(r,e,t){if(r==="_and")return Lr("and",e,t);if(r==="_or")return Lr("or",e,t);if(r==="_not"){let c=dn(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?ro(a,e,u,t):n&&!n.columns?.find(d=>d.name===a)?(r.startsWith("_")&&r!=="_id"&&Ee(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}):io(a,e,t)}function Lr(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],i=!1;for(let o of e){let s=dn(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 ro(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:dn(l,u).node,hasRelationFilters:!0}}function io(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:so(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)&&Ee(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=oo(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 oo(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=ln(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function so(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 Et=q(()=>{"use strict";cn();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(Gn,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,Gn,Yn,Se,Ge=q(()=>{"use strict";de();Me=16,oe=5e3,Gn=4,Yn=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:Yn}: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 I(`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 I(`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 C=$[o];if(C==null)continue;let T=this.adapter.keyOf(C);s.has(T)||(s.add(T),a.push(C))}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 C=$[o];$[t.relationName]=C!=null?this.adapter.buildScalarRef(C,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 C=$[o];$[t.relationName]=C!=null&&b.get(this.adapter.keyOf(C))||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",C=b?a.length:Math.ceil(a.length/oe)||1,T=b?Math.ceil(a.length/Me):void 0,k=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??C,concurrencyWaves:g?.concurrencyWaves??T,ioConcurrency:g?.ioConcurrency,rowsTransferred:g?.rowsTransferred??p.length,rowsReturned:k,rowsDiscarded:Math.max(0,(g?.rowsTransferred??p.length)-k),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let M of p)this.adapter.postProcessInverseChild(M,u,y);let _=this.enrichNestedDescs(d,t.nestedDeep,c);_.length>0&&await this.execute(p,_,n,i+1,t.targetTable);let F=t.type==="one-to-one";for(let M of e){let B=this.adapter.keyOf(M[s]),S=m.get(B)||[];M[t.relationName]=F?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,k)=>T+k.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 C=this.enrichNestedDescs(c,t.nestedDeep,u);C.length>0&&p.length>0&&await this.execute(p,C,n,i+1,t.targetTable);for(let T of e){let k=this.adapter.keyOf(T[s]);T[t.relationName]=f.get(k)||[]}}}});var zr,Ce,bn=q(()=>{"use strict";zr=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 x(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 Re(r,e){return r.split(".").map(t=>t==="*"||t.startsWith('"')&&t.endsWith('"')||t.startsWith("`")&&t.endsWith("`")?t:x(t,e)).join(".")}var ae=q(()=>{"use strict"});function ce(r,e,t){e&&Rn(r,e,t,"and")}function Rn(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(){Rn(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(){Rn(this,o,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"not":{let i=function(){this.whereNot(function(){Rn(this,e.child,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"compare":jo(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 jo(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=Bo(e.field,t),o=Re(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=ii(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=ii(e.value);s&&a&&g.every(m=>typeof m=="string")?r[c](`${o} != ALL(?::uuid[])`,[g]):r[l](i,g);return}case"contains":lr(r,o,e.value,"contains",t,n);return;case"starts_with":lr(r,o,e.value,"starts_with",t,n);return;case"ends_with":lr(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 lr(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 Bo(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function ii(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var cr=q(()=>{"use strict";ae()});function H(r){return r.columns.find(e=>e.isPrimary)||null}var qt=q(()=>{"use strict"});var oi={};Mn(oi,{expandFieldsToJoinsAndSelect:()=>ur});async function ur(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),$=x(r,n),C=x(b,n),T=x(f,n);s.push(`${$}.${C} 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 dr=q(()=>{"use strict";Ke();ae()});var Ut,Qt,Fn,ot,Lo,st,pr=q(()=>{"use strict";Ke();ae();qt();Ge();bn();cr();Mt();Et();Ut="__enfyra_row_number__",Qt="__sourceId__",Fn="__targetId__",ot="__enfyra_partitioned__",Lo=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"?Lo: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),C=$&&H($)?.name||"id";e.leftJoin(`${m} as ${y}`,`${y}.${C}`,`${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=x(o,this.dbType),a=t?`${t}.${x(i,this.dbType)}`:x(i,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${t}.${x(e,this.dbType)} as ${x(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(_=>_[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 _ of a)h.set(this.keyOf(_),[]);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(_=>_.column===b);if(g){let _=new Map;for(let F of p){let M=this.keyOf(F.targetId);_.has(M)||_.set(M,{[o.pkCol]:F.targetId}),h.get(this.keyOf(F.sourceId))?.push(_.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 C=this.uniqueValues(p.map(_=>_.targetId)),T=await this.loadM2MTargets(t.targetTable,C,o),k=new Map(T.map(_=>[this.keyOf(_[o.pkCol]),_]));for(let _ of p){let F=k.get(this.keyOf(_.targetId));F&&h.get(this.keyOf(_.sourceId))?.push(F)}return{grouped:h,docs:T,stats:{strategy:m?"m2m-partitioned-edge-loader":"m2m-edge-loader",roundtrips:y+(C.length>0?this.chunkCount(C,this.m2mTargetChunkSize()):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+T.length,rowsDiscarded:0}}}}});var li={};Mn(li,{executeBatchFetches:()=>gr});async function gr(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 hr=q(()=>{"use strict";Ge();pr()});var qo={};Mn(qo,{ALL_SUPPORTED_OPERATORS:()=>Nt,AuthenticationException:()=>gt,AuthorizationException:()=>ht,BadRequestException:()=>I,BatchExecutionBudget:()=>Ce,BatchFetchEngine:()=>Se,BusinessLogicException:()=>ut,CHUNKED_FETCH_CONCURRENCY:()=>Gn,ConfigurationException:()=>$t,DEEP_TO_MANY_DEFAULT_LIMIT:()=>Yn,DEFAULT_BATCH_FETCH_IO_CONCURRENCY:()=>zr,DEFAULT_TIMEOUT_MS:()=>Vt,DOTTED_PATH_MAX_HOPS:()=>Nn,DatabaseException:()=>Le,DuplicateResourceException:()=>pt,ErrorHandler:()=>ve,ExecutorEngineService:()=>Be,ExternalServiceException:()=>bt,FIELD_OPERATORS:()=>we,FileNotFoundException:()=>St,FileSizeExceededException:()=>Ct,FileUploadException:()=>Tt,HttpException:()=>P,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>Yt,InvalidTokenException:()=>yt,IsolatedExecutorService:()=>We,JoinRegistry:()=>ie,LOGICAL_OPERATORS:()=>Kn,MongoBatchAdapter:()=>Xe,MongoQueryExecutor:()=>Ae,PER_PARENT_CONCURRENCY:()=>Me,QueryBuilderService:()=>at,QueryPlanner:()=>Z,ResourceNotFoundException:()=>ft,SchemaException:()=>wt,ScriptContractService:()=>tn,ScriptExecutionException:()=>ye,ScriptTimeoutException:()=>me,ServiceUnavailableException:()=>_t,SqlBatchAdapter:()=>st,SqlQueryExecutor:()=>je,TokenExpiredException:()=>mt,ValidationException:()=>dt,WHERE_IN_CHUNK_SIZE:()=>oe,WorkerPool:()=>Rt,appendIsolatedExecutorRuntimeLog:()=>Q,applyOperatorToMatch:()=>an,applyRelationFilters:()=>Lt,applyWhereToKnex:()=>it,assertFieldOperatorValueIsClean:()=>un,buildMongoCharFoldMapJson:()=>Dn,buildMongoFoldTextSearchJs:()=>nn,buildRelationSubquery:()=>Bt,buildSqlWherePartsFromFieldAst:()=>Wt,buildWhereClause:()=>le,camelToSnake:()=>Nr,chunkedFetch:()=>W,compileScriptSource:()=>qi,computeEngineTuning:()=>An,createEnfyraKernel:()=>Ko,dslOpToCompareOp:()=>ln,encodeMainThreadToIsolate:()=>jn,escapeSqlValue:()=>Kt,executeBatchFetches:()=>gr,executeMongoBatchFetches:()=>wn,expandFieldsToJoinsAndSelect:()=>ur,getEffectiveCpuCount:()=>On,getEffectiveMemoryBytes:()=>kt,getEngineTuning:()=>en,getExecutableScript:()=>zi,getForeignKeyColumnName:()=>J,getIoAbortSignal:()=>Cr,getJunctionColumnNames:()=>xt,getJunctionTableName:()=>vt,getPrimaryKeyColumn:()=>H,getScriptLegacyField:()=>Di,getShortFkConstraintName:()=>xr,getShortFkName:()=>Er,getShortIndexName:()=>Mr,getShortPkName:()=>vr,hasLogicalOperators:()=>he,isExecutableJavaScript:()=>Ui,isScriptTable:()=>Wi,normalizeAggregateQuery:()=>tt,normalizeFlowStepScriptConfig:()=>Hi,normalizeScriptLanguage:()=>Ki,normalizeScriptPatch:()=>Ji,normalizeScriptRecord:()=>Qi,parseBatchFields:()=>He,parseFields:()=>$n,parseFilter:()=>fe,perParentRun:()=>_n,quoteIdentifier:()=>x,quoteQualifiedIdentifier:()=>Re,resolveExecutableScript:()=>Vi,rewriteFilterDenyingFields:()=>di,rewriteSortDroppingDenied:()=>fi,runWithIoAbortSignal:()=>kr,scriptContractService:()=>te,separateFilters:()=>V,snakeToCamel:()=>Ir,throwUnsupportedFieldOperator:()=>Ee,validateDeepOptions:()=>mr,validateFilterShape:()=>re,whereToMongoFilter:()=>Qe});module.exports=bi(qo);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"),Tr=ue(require("path")),Sr=require("stream");var br=require("child_process"),_i=["PATH","HOME","NODE_ENV","TMPDIR","LANG"];function wi(){let r={};for(let e of _i){let t=process.env[e];t!==void 0&&(r[e]=t)}return r}var Gt=class{constructor(e){this.terminated=!1;this.child=(0,br.fork)(e,[],{stdio:["ignore","ignore","ignore","ipc"],env:wi(),serialization:"advanced"})}get pid(){return this.child.pid}on(e,t){return this.child.on(e,t),this}off(e,t){return this.child.off(e,t),this}postMessage(e){if(!this.child.connected)throw new Error("Executor runner IPC is closed");this.child.send(e)}terminate(){if(this.terminated)return;this.terminated=!0;try{this.child.disconnect()}catch{}try{this.child.kill("SIGTERM")}catch{}setTimeout(()=>{if(!(this.child.exitCode!==null||this.child.signalCode!==null))try{this.child.kill("SIGKILL")}catch{}},250).unref?.()}};var me=class extends Error{constructor(t=0,n,i){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,...i}}},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 ve=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 Xt=ue(require("fs")),Zt=ue(require("path")),Yt=Zt.join(process.cwd(),"test","logs","isolated-executor-runtime.log");function $i(){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 Ti=$i();function Q(r){if(Ti)try{let e=Zt.dirname(Yt);Xt.mkdirSync(e,{recursive:!0});let t=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...r})+`
|
|
2
|
+
`;Xt.appendFileSync(Yt,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 On(){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 Si=.25,Ci=16,ki=2048,Ri=40,Fi=128,vi=32;function An(r){let e=Math.max(1,Math.trunc(r.logicalCpuCount)||1),t=Math.max(1,r.totalMemoryBytes/(1024*1024)),n=Math.min(Fi,Math.max(Ri,Math.round(t/vi))),i=t*Si,o=Math.max(1,Math.floor(i/n)),s=Math.max(1,Math.min(e,2,o)),a=t<ki?1:Ci,u=Math.max(1,Math.min(a,Math.floor(i/(s*n))));return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:u,isolatePoolSize:u}}function en(){return An({logicalCpuCount:On(),totalMemoryBytes:kt()})}var Bi=Tr.join(__dirname,"execution/worker.js"),Li=1e3,Pn=new $r.AsyncLocalStorage;function Cr(){return Pn.getStore()}function kr(r,e){return Pn.run(r,e)}var Rt=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 Gt(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,reservations:0,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let i=t.tasks.get(n.id);i&&(n.type==="taskReleased"?i.onRelease?.():n.type==="result"||n.type==="taskCancelled"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),n.contextStats&&(t.contextStats=n.contextStats),i.onResult(n.type==="taskCancelled"?{type:"result",id:n.id,success:!1,taskCancelled:!0,error:{message:"Task cancelled",code:"ERR_TASK_CANCELLED"}}: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",code:i?void 0:"ERR_EXECUTOR_RUNNER_LOST",details:i?void 0:{outcome:"unknown_outcome",retryable:!1}}});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){if(t.draining)continue;let n=t.tasks.size+t.reservations;n<this.tasksCap&&(!e||n<e.tasks.size+e.reservations)&&(e=t)}return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size+e.reservations===0||this.isMemoryAvailable())?(e.reservations++,Promise.resolve(e)):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.reservations=Math.max(0,e.reservations-1),e.tasks.set(t,n)}releaseReservation(e){e.reservations=Math.max(0,e.reservations-1),this.drainWaiting()}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+e.reservations===0||this.isMemoryAvailable()))e.reservations++,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,pid:e.worker.pid,activeTasks:e.tasks.size,reservations:e.reservations,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}},wr=new Set(["$helpers","$cache","$transaction","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$debug"]);function jn(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=en();this.pool=new Rt(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Bi,()=>{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||wr.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"||wr.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){this.pool.releaseReservation(s);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,g=()=>{let _=new Error("Execution aborted after client disconnect");return _.code="ERR_EXECUTION_ABORTED",_.isAbort=!0,_},m=()=>{let _=new Error(`Script execution timed out after ${i}ms`);return _.code="ERR_SCRIPT_EXECUTION_TIMEOUT",_.isTimeout=!0,_},y,b=_=>{if(!(l||p)){p=!0,h=_,f.abort(),this.cleanupResponseStream(a,_);try{s.worker.postMessage({type:"cancelTask",id:a})}catch{}y=setTimeout(()=>{l||(l=!0,clearTimeout(k),T(),this.taskCancellers.delete(a),this.pool.unregisterTask(s,a),this.taskErrorTotal++,Q({event:"task_cancel_grace_terminate",id:a}),this.pool.terminateEntry(s),_.details={..._.details??{},outcome:"unknown_outcome",retryable:!1,escalation:"runner_terminated_after_cancel_grace"},d(_))},Li),y.unref?.()}},$=()=>b(g());this.taskCancellers.set(a,$);let C=()=>$(),T=()=>{o?.removeEventListener("abort",C)};o&&o.addEventListener("abort",C,{once:!0});let k=setTimeout(()=>{l||(this.taskTimeoutTotal++,Q({event:"task_timeout",id:a,timeoutMs:i}),b(m()))},i);this.pool.registerTask(s,a,{abortController:f,onResult:_=>{if(!l){if(_.taskCancelled===!0&&this.pool.unregisterTask(s,a),l=!0,clearTimeout(k),y&&clearTimeout(y),this.taskCancellers.delete(a),T(),this.cleanupResponseStream(a),this.recordTaskDuration(Date.now()-u),p){f.abort(),this.taskErrorTotal++,d(h??g());return}if(_.success){this.taskDoneTotal++,Q({event:"task_done",id:a,ok:!0});let F={value:_.value,valueAbsent:_.valueAbsent===!0,ctxChanges:_.ctxChanges};_.shortCircuit&&(F.shortCircuit=!0),c(F)}else{this.taskErrorTotal++,Q({event:"task_done",id:a,ok:!1,message:_.error?.message});let F=new Error(_.error?.message||"Handler execution failed");F.statusCode=_.error?.statusCode,F.code=_.error?.code,F.details=_.error?.details,_.error?.stack&&(F.stack=_.error.stack),_.ctxChanges&&(F.ctxChanges=_.ctxChanges),this.cleanupResponseStream(a,F),d(F)}}},onRelease:()=>{this.pool.unregisterTask(s,a)},onIoCall:_=>{if(l)return;let F=f.signal;_.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(_,n),s.worker,_.callId,F):_.type==="transactionCall"?this.handleIoCall(()=>this.execTransactionCall(_,n,s.worker),s.worker,_.callId,F):_.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(_,n),s.worker,_.callId,F):_.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(_,n),s.worker,_.callId,F):_.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(_,n),s.worker,_.callId,F):_.type==="storageCall"?this.handleIoCall(()=>this.execStorageCall(_,n,s.worker),s.worker,_.callId,F):_.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall(_,n),s.worker,_.callId,F):_.type==="resCall"&&this.handleIoCall(()=>this.execResCall(_,n),s.worker,_.callId,F)}}),s.worker.postMessage({type:e,id:a,...t}),o?.aborted&&$()})})()}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?Pn.run(i,e):e());if(i?.aborted){this.postAbortedCallError(t,n);return}try{t.postMessage({type:"callResult",callId:n,result:jn(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 Sr.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,l.details);l.code&&l.details&&(l.details.executorCode=l.code);let f=l.statusCode??(typeof l.status=="number"?l.status:void 0);throw ve.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)",l.details);l.code&&l.details&&(l.details.executorCode=l.code);let f=l.statusCode??(typeof l.status=="number"?l.status:void 0);throw ve.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 xe=ue(require("typescript")),Ft={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 Di(r){return te.getLegacyField(r)}function Wi(r){return te.isScriptTable(r)}function Ki(r){return te.normalizeLanguage(r)}var tn=class{getLegacyField(e){return Ft[e]}isScriptTable(e){return e in Ft}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(Ft).find(n=>Ft[n]in e);if(t){let n=e[Ft[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=xe.default.transpileModule(e,{compilerOptions:{target:xe.default.ScriptTarget.ES2022,module:xe.default.ModuleKind.CommonJS,importsNotUsedAsValues:xe.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),n=t.diagnostics?.find(i=>i.category===xe.default.DiagnosticCategory.Error);if(n)throw new Error(xe.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
|
-
});`)}},
|
|
7
|
-
var M = ${
|
|
6
|
+
});`)}},te=new tn;function qi(r,e){return te.compileSource(r,e)}function Ui(r){return te.isExecutableJavaScript(r)}function Qi(r,e){return te.normalizeRecord(r,e)}function Ji(r,e,t){return te.normalizePatch(r,e,t)}function zi(r){return te.getExecutableScript(r)}function Vi(r){return te.resolveExecutableScript(r)}function Hi(r){return te.normalizeFlowStepScriptConfig(r)}var xn=require("node:fs"),ci=require("node:path");var Ln=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 Y(r){if(!r||typeof r!="object")return r;if(r instanceof Ln.ObjectId)return r.toString();if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return r.map(t=>Y(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 Ln.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)?Y(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||vt(a,u,c);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:d,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:c};let l=xt(a,u,c);return{junctionName:d,selfColumn:l.targetColumn,otherColumn:l.sourceColumn,owningTable:a,inverseTable:c}}let n=r,i=t,o=e.junctionTableName||vt(n,e.propertyName,i);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:o,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:i};let s=xt(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 rn=ue(require("fs")),Wn=ue(require("path"));var Gi=new RegExp("\\p{Mark}","gu");function Or(r){return r==null?"":String(r).normalize("NFKD").replace(Gi,"").toLowerCase()}function Dn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=Or(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function nn(){return`function() {
|
|
7
|
+
var M = ${Dn()};
|
|
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 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});
|
|
52
|
+
}`}var Ar="mongo-fold-text-search.body.txt",qe=null;function Yi(){let r=[Wn.join(__dirname,Ar),Wn.join(process.cwd(),"dist","kernel","query","utils",Ar)];for(let e of r)try{if(rn.existsSync(e))return rn.readFileSync(e,"utf8")}catch{}return null}function on(){if(qe!==null)return qe;let r=Yi();return r?(qe=r,qe):(qe=nn(),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 sn="__mongoFoldTextTriples";function Xi(r){return r==="_id"?"$_id":`$${r}`}function Ue(r,e,t,n){let i=Xi(e),o=r[sn]??[];o.push({ref:i,needle:t,mode:n}),r[sn]=o}function Zi(r){let e=r[sn];if(delete r[sn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:on(),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 Zi(i),i}function Pr(r,e,t){let i=r?.tables?.get?.(e)?.columns?.find(o=>o.name===t);return i?i.isNullable!==!1:!0}function an(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);Pr(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));Pr(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 Vn=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}}Et();Mt();var fn="__mongoFoldTextTriples";function ze(r,e){if(!r)return{};let t={};return Ot(r,t,e),$e(t),t}function ao(r,e){if(!r)return{};let t={};return Un(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 pn(r,e,t){if(!e)return{};let n=new ie,{node:i}=fe(e,t,r,n);return ao(i,{metadata:r,rootTable:t})}function Ot(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 Ot(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 Ot(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={};Ot(r.child,n,t),$e(n);let i=e.$nor;e.$nor=i?[...i,n]:[n];return}case"compare":Wr(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 Wr(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":X(e,n,i(r.value));return;case"neq":{let o=i(r.value);Qn(t,n)?pe(e,{[n]:{$ne:null}},{[n]:{$ne:o}}):X(e,n,{$ne:o});return}case"gt":X(e,n,{$gt:i(r.value)});return;case"gte":X(e,n,{$gte:i(r.value)});return;case"lt":X(e,n,{$lt:i(r.value)});return;case"lte":X(e,n,{$lte:i(r.value)});return;case"in":{let o=Dr(r.value).map(i);X(e,n,{$in:o});return}case"not_in":{let o=Dr(r.value).map(i);Qn(t,n)?pe(e,{[n]:{$ne:null}},{[n]:{$nin:o}}):X(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&&X(e,n,{$gte:i(o[0]),$lte:i(o[1])});return}case"is_null":X(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":qn(e,n,String(r.value),"contains");return;case"starts_with":qn(e,n,String(r.value),"starts");return;case"ends_with":qn(e,n,String(r.value),"ends");return}}function Un(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 Un(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 Un(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":Ot(r.child,e,t);return;case"compare":lo(r,e,t);return;case"relation_exists":{X(e,r.joinId,r.negate?{$ne:null}:{$eq:null});return}}}function lo(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"){X(e,n,r.value===!0?{$ne:null}:{$eq:null});return}let i={};Wr(r,i,t),$e(i);let o={$nor:[i]};Qn(t,n)?pe(e,o,{[n]:{$ne:null}}):pe(e,o)}function X(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 Qn(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(i=>i.name===e);return n?n.isNullable!==!1:!0}function Dr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function co(r){return r==="_id"?"$_id":`$${r}`}function qn(r,e,t,n){let i=co(e),o=r[fn]??[];o.push({ref:i,needle:t,mode:n}),r[fn]=o}function $e(r){let e=r[fn];if(delete r[fn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:on(),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 zn(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 uo(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 zn(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return pn(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!ne(r,o))return pn(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>zn(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=>zn(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=pn(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 po(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 uo(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"?fo(e,s,r,a,u,i,o):s.type==="one-to-many"?Ur(e,s,t,a,u,i,o):s.type==="many-to-many"?Qr(e,s,t,a,u,i,o):{}}async function fo(r,e,t,n,i,o,s){let a=z(e)||t,u=hn(r),c=mn(u);if(c!==null)return c?{[a]:null}:{[a]:{$ne:null}};let d=Hn(u);if(d!==null){let h=yn(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 gn(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 po(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 go(e,s,r,a,u,i,o);if(s.type==="one-to-many"){let c=await Ur(e,s,t,a,u,i,o);return qr(c)}if(s.type==="many-to-many"){let c=await Qr(e,s,t,a,u,i,o);return qr(c)}return{}}async function go(r,e,t,n,i,o,s){let a=z(e)||t,u=hn(r),c=mn(u);if(c!==null)return c?{[a]:{$ne:null}}:{[a]:null};let d=Hn(u);if(d!==null){let h=yn(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 gn(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 Ur(r,e,t,n,i,o,s){let a=K(e)||t,u=hn(r),c=mn(u);if(c!==null){let f=await Kr(s,n,a,{});return c?f.length===0?{}:{_id:{$nin:f}}:f.length===0?{__impossible__:!0}:{_id:{$in:f}}}let d=await gn(u,n,i,o,s);if(!d||Object.keys(d).length===0)return{};let l=await Kr(s,n,a,d);return l.length===0?{__impossible__:!0}:{_id:{$in:l}}}async function Qr(r,e,t,n,i,o,s){let a=Ne(t,e);if(!a)return{};let u=hn(r),c=mn(u);if(c!==null){let g=await Jn(s,a,n,null);return c?g.length===0?{}:{_id:{$nin:g}}:g.length===0?{__impossible__:!0}:{_id:{$in:g}}}let d=Hn(u);if(d!==null){let g=yn(d.value),m=Array.isArray(g)?g:[g],y=await Jn(s,a,n,{_id:{$in:m}});return y.length===0?{__impossible__:!0}:{_id:{$in:y}}}let l=await gn(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 Jn(s,a,n,{_id:{$in:p}});return h.length===0?{__impossible__:!0}:{_id:{$in:h}}}async function gn(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 Kr(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 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 Jn(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 hn(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 yn(r){if(Array.isArray(r))return r.map(e=>yn(e));if(typeof r!="string")return r;try{return new Vn.ObjectId(r)}catch{return r}}function Hn(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof Vn.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))an(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 Jr(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();bn();async function _n(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,C=p===0?null:`__sort_${l.slice(0,p).join("_")}`,T=C?`${C}.${$}`:$;o.push({$lookup:{from:y,localField:T,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}f=y}}let a=this.buildSortFromTokens(n);a&&o.push({$sort:a});let u={};for(let c of s)u[c]=0;return Object.keys(u).length>0&&o.push({$project:u}),o}toObjectId(e){try{return typeof e=="string"?new 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 C=>{let T={[t]:{$in:C}};u&&Object.keys(u).length>0&&Object.assign(T,u);let k=[{$match:T}];this.appendTopNStages(k,t,b,y,c),k.push({$sort:{[t]:1,...b}}),this.appendPartitionProjection(k,s,[t]);let _=await this.runQuery(()=>this.db.collection(e).aggregate(k).toArray());return this.applyReadFallback(_,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 _n(a,async $=>{let C={[t]:$};u&&Object.keys(u).length>0&&Object.assign(C,u);let T=this.buildSortAggregatePipeline(e,C,o.userSort);s&&T.push({$project:s});let k=await this.runQuery(()=>this.db.collection(e).aggregate(T).toArray());return this.applyReadFallback(k,i)},Me);for(let $ of b.values())for(let C of $)y.push(C);return{docs:y,groupKeyField:t,stats:{strategy:"per-parent-dotted-sort",roundtrips:a.length,concurrencyWaves:Math.ceil(a.length/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 C=[{$match:{[n.selfColumn]:{$in:y}}}];return this.appendTopNStages(C,n.selfColumn,{[n.otherColumn]:l},s,a),C.push({$sort:{[n.selfColumn]:1,[n.otherColumn]:l}},{$project:{_id:0,[se]:`$${n.selfColumn}`,[ke]:`$${n.otherColumn}`}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(C).toArray())).map(k=>({sourceId:k[se],targetId:k[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(C=>({sourceId:C[se],targetId:C[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(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?ge(this.normalizeMetadata(),t.userFilter,t.targetTable):null,l=t.userLimit,f=t.userPage;if(l!==void 0&&l>0){let k=f?(f-1)*l:0;return this.fetchM2MTopK(u,t,a,o,d,k,l)}let p=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1&&!d,h=this.hasDottedSort(t.userSort);if(!h)return this.fetchM2MEdgeBatch(u,t,a,o,d);let g=await W(u,k=>this.runQuery(()=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:k}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray()));if(g.length===0)return{grouped:c,docs:[],stats:{strategy:"m2m-batch",roundtrips:this.chunkCount(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:0}};let m=new Set,y=[];for(let k of g){let _=k[a.otherColumn];if(_==null)continue;let F=this.keyOf(_);m.has(F)||(m.add(F),y.push(_))}let b=[],$=new Map;if(p)b=y.map(k=>({_id:k})),this.sortDocsByPk(b);else{let k={_id:{$in:y}};d&&Object.keys(d).length>0&&Object.assign(k,d);let _;if(h){let F=this.buildSortAggregatePipeline(t.targetTable,k,t.userSort);o.projection&&F.push({$project:o.projection}),_=await this.runQuery(()=>this.db.collection(t.targetTable).aggregate(F).toArray())}else{let F=this.buildSortFromTokens(t.userSort)||{_id:1},M=this.projectionWithSortFields(o.projection,t.userSort),B={sort:F};M.projection&&(B.projection=M.projection),_=await W(y,S=>this.runQuery(()=>this.db.collection(t.targetTable).find({_id:{$in:S},...d||{}},B).toArray())),t.userSort?this.sortDocsInMemory(_,t.userSort):this.sortDocsByPk(_),this.removeHiddenFields(_,M.hiddenFields)}b=this.applyReadFallback(_,o)}for(let k of b)$.set(this.keyOf(k._id),k);let C=new Map;for(let k of g){let _=this.keyOf(k[a.selfColumn]),F=this.keyOf(k[a.otherColumn]);$.has(F)&&(C.has(F)||C.set(F,[]),C.get(F).push(_))}for(let k of b){let _=C.get(this.keyOf(k._id))||[];for(let F of _)c.get(F)?.push(k)}let T=p||y.length===0?0:this.chunkCount(y);return{grouped:c,docs:b,stats:{strategy:p?"m2m-junction-batch":"m2m-batch",roundtrips:this.chunkCount(u)+T,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length+b.length}}}applyReadFallback(e,t){let n=t.pendingRenames??[];if(e.length===0||n.length===0)return e;let i=new Set(t.hiddenFields??[]);for(let o of e)for(let s of n)o[s.newName]===void 0&&o[s.oldName]!==void 0&&(o[s.newName]=o[s.oldName]),(i.has(s.oldName)||o[s.newName]!==void 0)&&delete o[s.oldName];return e}};async function wn(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 Xn(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 E=S.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(A=>A.propertyName===E)??!1})??!1,m=()=>p?.sortItems?$o(p.sortItems):e.sort?wo(e.sort):null,y=p?.sortItems?ho(p.sortItems):[],b=p?.sortItems?mo(p.sortItems):[],$=()=>{!p||y.length===0||yo(n,e.table,p.sortItems,o)},C=()=>{!p||b.length===0||bo(n,e.table,p.sortItems,o)},T=()=>{let S=[...y,...b];S.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(S.map(E=>[E,0]))})};if(!e.mongoFieldsExpanded){$(),C();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 E=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:E,pipeline:n}:{results:Vr(E),pipeline:n}}let{scalarFields:k,relations:_}=e.mongoFieldsExpanded;if(!g){$(),C();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 F=[];for(let S of _)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 F.push(S);if(g){$(),C();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 Jr(o,n,e.table,k,[..._]),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(F.length>0&&B.length>0){let S=e.deep||{},E=F.map(L=>{let R=o?.tables?.get(e.table)?.relations?.find(N=>N.propertyName===L.propertyName),v=S[L.propertyName],ee=v?.fields!=null?Array.isArray(v.fields)?v.fields:String(v.fields).split(",").map(N=>N.trim()).filter(Boolean):L.nestedFields&&L.nestedFields.length>0?L.nestedFields:["_id"];return{relationName:L.propertyName,type:R?.type,targetTable:L.targetTable,fields:ee,isInverse:R?.isInverse,mappedBy:R?.mappedBy,junctionTableName:R?.junctionTableName,junctionSourceColumn:R?.junctionSourceColumn,junctionTargetColumn:R?.junctionTargetColumn,localField:L.localField,foreignField:L.foreignField,userFilter:v?.filter,userSort:v?.sort,userLimit:v?.limit!==void 0?Number(v.limit):void 0,userPage:v?.page!==void 0?Number(v.page):void 0,nestedDeep:v?.deep}}),A=_o(o);A&&await wn(i,B,E,A,3,0,e.table,o,e.debugTrace,t.mongoPhysicalMigrationService)}return{results:Vr(B),pipeline:n}}function Zn(r){return`__sort_count_${r.relationName||r.field}`}function er(r){return`__sort_${r.function}_${r.relationName||r.field}_${r.aggregateField||"value"}`}function ho(r){return r.filter(e=>e.function==="count").map(Zn)}function mo(r){return r.filter(e=>e.function==="max"||e.function==="min").map(er)}function yo(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=Zn(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 bo(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=er(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 _o(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 wo(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 $o(r){let e={};for(let t of r){let n=t.function==="count"?Zn(t):t.function==="max"||t.function==="min"?er(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 Vr(r){return r.map(Y)}function Hr(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(To(o,i,e));return{scalarFields:t,relations:n}}function To(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=Gr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:i,foreignField:o,type:a?"many":"one",isInverse:s,nestedFields:u}}function Gr(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=Gr(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();Et();function $n(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:Yr(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 Yr(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:Yr(l,p,t)})}return c}de();de();var So=new Set(["_and","_or","_not"]);function Xr(r,e){return r?.tables?.get(e)??null}function Co(r,e,t){return Xr(r,e)?.columns?.find(n=>n.name===t)}function tr(r,e,t){return Xr(r,e)?.relations?.find(n=>n.propertyName===t)}function ko(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 nr(r,e,t,n){if(Co(r,e,t)?.isEncrypted===!0)throw new I(`Encrypted field '${t}' on '${e}' cannot be used for ${n}.`)}function Oe(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){for(let n of r)Oe(n,e,t);return}for(let[n,i]of Object.entries(r)){if(So.has(n)){Oe(i,e,t);continue}if(n.startsWith("_"))continue;let o=tr(t,e,n);if(o){let s=o.targetTableName||o.targetTable;s&&Oe(i,s,t);continue}nr(t,e,n,"filter")}}}function Tn(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=ko(o);if(s){if(s.functionName==="count")continue;let c=tr(t,e,s.relationName),d=c?.targetTableName||c?.targetTable;d&&nr(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){nr(t,u,d,"sort");break}let f=tr(t,u,d);if(!f)break;u=f.targetTableName||f.targetTable||u}}}var Z=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=$n(p,t,c,f));let g=!1,m=null;if(i&&l){Oe(i,t,c);let S=fe(i,t,c,f);m=S.node,g=S.hasRelationFilters}let y=this.parseSort(o);l&&Tn(y,t,c);let b=[],$=!1;for(let S of y){let E=S.startsWith("-"),A=E?S.substring(1):S,L=E?"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 C=this.parseLimit(a),T=this.parsePage(s),k=T!==void 0&&C!==void 0?(T-1)*C:void 0,_=this.parseMeta(u),F=_.includes("totalCount")||_.includes("*"),M=_.includes("filterCount")||_.includes("*"),B=f.getAll();return{table:t,dbType:d,rawFields:p,rawFilter:i??null,joins:B,sortItems:b,limit:C,offset:k,needsTotalCount:F,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 I(`Sort field '${n}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let i=t.columns?.some(s=>s.name===n),o=n==="id"&&t.columns?.some(s=>s.name==="_id");if(!i&&!o)throw new I(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationAggregateSort(e,t,n,i){let o=n.match(/^_(count|max|min)\(([^)]+)\)$/);if(!o){if(/^_(count|max|min)\(/.test(n))throw new I(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName), _max(relationName.fieldName), or _min(relationName.fieldName).`);return null}let s=o[1],a=o[2].trim();if(s==="count"){let m=a;if(!m||m.includes("."))throw new I(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let y=t.relations?.find(b=>b.propertyName===m);if(!y)throw new I(`Sort relation '${m}' does not exist on '${e}'.`);if(y.type!=="one-to-many"&&y.type!=="many-to-many")throw new I(`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 I(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let c=a.slice(0,u).trim(),d=a.slice(u+1).trim();if(!c||!d)throw new I(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let l=t.relations?.find(m=>m.propertyName===c);if(!l)throw new I(`Sort relation '${c}' does not exist on '${e}'.`);if(l.type!=="one-to-many"&&l.type!=="many-to-many")throw new I(`Sort function '_${s}(${c}.${d})' is only supported for list relations on '${e}'.`);let f=l.targetTableName||l.targetTable,p=i?.tables?.get(f);if(!p)throw new I(`Sort function '${n}' references unknown target table '${f}' on '${e}'.`);let h=p.columns?.find(m=>m.name===d),g=d==="id"&&p.columns?.some(m=>m.name==="_id");if(!h&&!g)throw new I(`Sort field '${d}' does not exist on '${f}' for function '_${s}(${c}.${d})'.`);if(h?.isEncrypted===!0)throw new I(`Encrypted field '${d}' on '${f}' cannot be used for sort.`);return{functionName:s,relationName:c,aggregateField:d,relationMeta:l}}registerSortJoinChain(e,t,n,i,o){let s=e.indexOf(".");if(s===-1)return null;let a=e.slice(0,s),u=e.slice(s+1),c=n?.tables?.get(t);if(!c)return null;let d=c.relations?.find(p=>p.propertyName===a);if(!d||d.type!=="many-to-one"&&d.type!=="one-to-one")return null;let l=i.registerWithParent(t,a,n,"left",o,"sort");if(!l)return null;if(!u.includes("."))return{lastJoinId:l,field:u};let f=d.targetTableName||d.targetTable;return this.registerSortJoinChain(u,f,n,i,l)}};de();var Ro=new Set(["int","integer","bigint","smallint","tinyint","float","double","decimal","numeric","real","number"]),Fo=new Set(["date","datetime","timestamp","timestamptz","timestamp with time zone","timestamp without time zone"]),vo=new Set(["hour","day","week","month","year"]),xo=new Set(["count","countDistinct","sum","avg","min","max"]);function O(r,e){throw new I(e,{path:r})}function et(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Io(r,e){let t=r?.tables?.get(e);return t||O("aggregate",`Table "${e}" metadata is not available`),t}function Zr(r,e,t){let n=r.columns?.find(i=>i.name===e);return n||O(t,`Unknown aggregate field "${e}"`),n.isEncrypted===!0&&O(t,`Encrypted field "${e}" cannot be used in aggregate queries`),n}function No(r,e){let t=r===void 0?"UTC":r;(typeof t!="string"||t.length===0)&&O(e,"Aggregate timezone must be a non-empty IANA timezone");try{new Intl.DateTimeFormat("en-US",{timeZone:t}).format()}catch{O(e,`Invalid aggregate timezone "${t}"`)}return t}function Eo(r,e){return r==null?{}:(et(r)||O(e,"Aggregate filter must be an object"),r)}function tt(r,e,t){et(r)||O("aggregate","Aggregate options must be an object");let n=Io(t,e),i=r.dimensions===void 0?[]:r.dimensions,o=r.measures;Array.isArray(i)||O("aggregate.dimensions","Aggregate dimensions must be an array"),(!et(o)||Object.keys(o).length===0)&&O("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)&&O(y,"Aggregate dimension requires a field");let b=Zr(n,g.field,`${y}.field`);return s.has(g.field)&&O(`${y}.field`,`Duplicate aggregate dimension "${g.field}"`),s.add(g.field),g.bucket===void 0?(g.timezone!==void 0&&O(`${y}.timezone`,"Aggregate timezone requires a bucket"),{field:g.field,outputKey:g.field,column:b}):((typeof g.bucket!="string"||!vo.has(g.bucket))&&O(`${y}.bucket`,"Aggregate bucket must be hour, day, week, month, or year"),Fo.has(String(b.type).toLowerCase())||O(`${y}.bucket`,`Aggregate bucket requires a date field, but "${g.field}" is "${b.type}"`),{field:g.field,outputKey:g.field,bucket:g.bucket,timezone:No(g.timezone,`${y}.timezone`),column:b})}),u=new Set,c=Object.entries(o).map(([g,m])=>{let y=`aggregate.measures.${g}`;(!g||!et(m))&&O(y,"Aggregate measure must be an object");let b=Object.entries(m).filter(([k])=>k!=="as");b.length!==1&&O(y,"Aggregate measure must define exactly one operation");let[$,C]=b[0];xo.has($)||O(y,`Unsupported aggregate measure "${$}"`),(typeof C!="string"||C.length===0)&&O(y,"Aggregate measure field must be a non-empty string");let T=Zr(n,C,`${y}.${$}`);return(u.has(g)||s.has(g))&&O(y,`Aggregate output key "${g}" is duplicated`),u.add(g),["sum","avg","min","max"].includes($)&&!Ro.has(String(T.type).toLowerCase())&&O(y,`Aggregate ${$} requires a numeric field, but "${C}" is "${T.type}"`),{outputKey:g,operation:$,field:C,column:T}}),d=r.sort===void 0?[]:r.sort;Array.isArray(d)||O("aggregate.sort","Aggregate sort must be an array");let l=new Set([...s,...u]),f=d.map((g,m)=>{let y=`aggregate.sort[${m}]`;return(!et(g)||typeof g.field!="string"||!l.has(g.field))&&O(y,"Aggregate sort field must reference a dimension or measure output"),g.direction!=="asc"&&g.direction!=="desc"&&O(`${y}.direction`,"Aggregate sort direction must be asc or desc"),{field:g.field,direction:g.direction}}),p=r.limit===void 0?void 0:Number(r.limit),h=r.page===void 0?1:Number(r.page);return p!==void 0&&(!Number.isInteger(p)||p<=0||p>1e4)&&O("aggregate.limit","Aggregate limit must be an integer between 1 and 10000"),(!Number.isInteger(h)||h<=0)&&O("aggregate.page","Aggregate page must be a positive integer"),{tableName:e,filter:Eo(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 Z;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 Z().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(Y)}}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=Hr(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(Y);let{results:a,pipeline:u}=await Xn(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 Xn(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=i,n}};var Sn=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 Mo=["_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(Mo.includes(e)||typeof r[e]=="object"&&r[e]!==null&&he(r[e]))return!0;return!1}var ei=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function Oo(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function Cn(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 Ao(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)||Cn(r,t,i),e}function ti(r,e,t,n,i,o,s){let a=i&&!e.includes(".")?`${i}.${e}`:e,u=Re(a,o??"postgres"),c=Cn(e,i,s),d=Ao(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,Oo(t),n)}}function Po(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(Po(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=>ei.includes(c)))for(let[c,d]of Object.entries(a))ei.includes(c)&&(n==="and"?r.where(function(){ti(this,s,c,d,t,i,o)}):r.orWhere(function(){ti(this,s,c,d,t,i,o)}));else{let c=t&&!s.includes(".")?`${t}.${s}`:s,d=Re(c,i??"postgres");Cn(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=Re(u,i??"postgres");Cn(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 or(r,e,t){return`${x(r,t)}.${x(e,t)}`}function Fe(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 ni(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 sr(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=or(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=Fe(p._eq,n);s.push(`${l} = ${m}`)}else if(p._neq!==void 0){let m=Fe(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=>Fe(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($=>Fe($,n)).join(", ");s.push(`${l} NOT IN (${b})`)}else if(p._gt!==void 0){let m=Fe(p._gt,n);s.push(`${l} > ${m}`)}else if(p._gte!==void 0){let m=Fe(p._gte,n);s.push(`${l} >= ${m}`)}else if(p._lt!==void 0){let m=Fe(p._lt,n);s.push(`${l} < ${m}`)}else if(p._lte!==void 0){let m=Fe(p._lte,n);s.push(`${l} <= ${m}`)}}}}}return s}function ar(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 rr(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(ar(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 sr(e,t,n,i,o,l);u.push({fieldFilters:d,subqueries:f})}s.push(u)}else if(ar(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 sr(e,t,n,i,o,c);s.push([{fieldFilters:u,subqueries:d}])}return s}function ri(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 ir(r,e,t,n,i){let o=!0;for(let s of e){let a=function(){for(let u of s)ri(this,u,t,n,i)};o?(r.where(a),o=!1):r.orWhere(a)}}function kn(r,e,t,n,i,o,s){let a=ni(e,i),u=ni(n,o),c=`${x(r,s)}.${x(e,s)}`,d=`${x(t,s)}.${x(n,s)}`;if(s==="postgres"){if(a&&!u)return`${c} = ${d}::uuid`;if(!a&&u)return`${c}::uuid = ${d}`}return`${c} = ${d}`}async function 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(kn(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(kn(a.junctionTableName,a.junctionTargetColumn,u,"id",f,d,o))).whereRaw(kn(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(kn(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 rr(c._or,r,n,i,o,s);e.where(function(){ir(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 rr(t._or,r,n,i,o,s);e.where(function(){ir(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(ar(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 sr(r,n,i,o,s,g);f.push({fieldFilters:h,subqueries:m})}e.whereNot(function(){for(let p of f)ri(this,p,n,i,o)});return}if(c._or&&Array.isArray(c._or)&&c._or.length>0){let f=await rr(c._or,r,n,i,o,s);e.whereNot(function(){ir(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=or(n,g.foreignKeyColumn,o),b=p.id;if(b&&typeof b=="object"){let $=rt(b._is_null),C=rt(b._is_not_null);if($===!0)e.whereRaw(`${m} IS NOT NULL`);else if($===!1)e.whereRaw(`${m} IS NULL`);else if(C===!0)e.whereRaw(`${m} IS NULL`);else if(C===!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,k=Array.isArray(T)?T:[T];e.whereRaw(`${m} IN (${k.map(()=>"?").join(", ")})`,k)}}}}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=or(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=`${x(e,n)}.${x(s,n)}`,l;if(c===null)l="NULL";else if(typeof c=="string"){let f=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,p=o.columns?.find(g=>g.name===s);p&&(p.type?.toLowerCase()==="uuid"||p.type?.toLowerCase().includes("uuid"))&&f.test(c)&&n==="postgres"?l=`'${c}'::uuid`:l=`'${c.replace(/'/g,"''")}'`}else typeof c=="boolean"?l=c?"true":"false":typeof c=="number"?l=String(c):l=`'${String(c).replace(/'/g,"''")}'`;if(u==="_eq")i.push(`${d} = ${l}`);else if(u==="_neq")i.push(`${d} != ${l}`);else if(u==="_gt")i.push(`${d} > ${l}`);else if(u==="_gte")i.push(`${d} >= ${l}`);else if(u==="_lt")i.push(`${d} < ${l}`);else if(u==="_lte")i.push(`${d} <= ${l}`);else if(u==="_is_null")i.push(`${d} IS NULL`);else if(u==="_is_not_null")i.push(`${d} IS NOT NULL`);else if(u==="_in"){let p=(Array.isArray(c)?c:[c]).map(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=`${x(e,n)}.${x(s,n)}`,c;a===null?c="NULL":typeof a=="string"?c=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?c=a?"true":"false":c=String(a),i.push(`${u} = ${c}`)}return i}function 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}}cr();Je();ae();qt();Ke();async function si(r,e,t,n,i,o,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(dr(),oi)),u=await a(e,t,n,i,o,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function fr(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 ai(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=>x(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 Sn(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 Z;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,R]of Object.entries(e.filter))if(typeof R=="object"&&R!==null)for(let[v,ee]of Object.entries(R)){let N;if(v==="_eq")N="=";else if(v==="_neq")N="!=";else if(v==="_in")N="in";else if(v==="_not_in"||v==="_nin")N="not in";else if(v==="_gt")N=">";else if(v==="_gte")N=">=";else if(v==="_lt")N="<";else if(v==="_lte")N="<=";else if(v==="_contains")N="_contains";else if(v==="_starts_with")N="_starts_with";else if(v==="_ends_with")N="_ends_with";else if(v==="_between")N="_between";else if(v==="_is_null")N="_is_null";else if(v==="_is_not_null")N="_is_not_null";else if(v==="_like")N="like";else if(v==="_ilike")N="ilike";else continue;l.where.push({field:w,operator:N,value:ee})}else l.where.push({field:w,operator:"=",value:R})}if(e.sort){let w=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(R=>R.trim());l.sort=w.map(R=>{let v=R.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,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 R={sql:this.buildRelationCountSortSubquery(l.table,w),direction:w.direction};$.push(R);continue}if(w.function==="max"||w.function==="min"){let R={sql:this.buildRelationAggregateSortSubquery(l.table,w),direction:w.direction};$.push(R);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(U=>U.propertyName===v))continue}let R={field:w.field.includes(".")?w.field:`${l.table}.${w.field}`,direction:w.direction};b.push(R),$.push(R)}else{let R=e.plan?.joins.find(v=>v.id===w.joinId);if(R&&(R.relationType==="many-to-one"||R.relationType==="one-to-one")){let v=ai(R.relationMeta,w.field,l.table,this.metadata,this.dbType);if(v){let ee={sql:v,direction:w.direction};$.push(ee)}}}}let C=[];if(l.fields&&l.fields.length>0||u||a){let w=fr(this.metadata),R=l.fields&&l.fields.length>0?l.fields:["*"],v=await si(this.knex,l.table,R,w,this.dbType,this.maxQueryDepth,e.deep);v.select.length>0&&(l.select=[...l.select||[],...v.select]),C=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),_=k.includes("filterCount")||k.includes("*"),F=k.includes("totalCount")||k.includes("*");if(l.select){let w=l.select.map(R=>typeof R=="string"&&R.trim().startsWith("(")?this.knex.raw(R):typeof R=="string"&&/ as /i.test(R)?this.knex.raw(R):R);T=T.select(w)}if(_&&T.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),F){let w=x(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,v=>this.metadata?.tables?.get(v)):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 R=w.field.includes(".")?w.field:`${l.table}.${w.field}`;T=T.orderBy(R,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 R=w.sql.replace(/\$\d+/g,"?"),v=await this.knex.raw(`EXPLAIN ${R}`,w.bindings);i.setExplain(this.dbType==="postgres"?v.rows:v[0])}catch(R){i.setExplain({error:String(R)})}}let E,A=performance.now();E=await T,i&&i.dur("db_execute",A,{table:e.tableName});let L=0;if(_&&E.length>0&&(L=Number(E[0].__filter_count__||0),E.forEach(w=>{delete w.__filter_count__})),F&&E.length>0&&E[0].__total_count__!==void 0&&(B=Number(E[0].__total_count__||0),E.forEach(w=>{delete w.__total_count__})),C&&C.length>0&&E.length>0){let w=fr(this.metadata);if(w){let{executeBatchFetches:R}=await Promise.resolve().then(()=>(hr(),li));await R(this.knex,E,C,w,this.maxQueryDepth??3,0,l.table,this.dbType,this.metadata,i)}}if(this.knexService){let w=performance.now();E=await this.knexService.parseResult(E,l.table),i&&i.dur("db_parseResult",w,{table:e.tableName})}else{let w=(R,v)=>{if(!R||!this.metadata)return R;let ee=this.metadata.tables?.get(v);if(!ee)return R;if(Array.isArray(R))return R.map(U=>w(U,v));if(typeof R!="object"||Buffer.isBuffer(R))return R;let N={...R};for(let U of ee.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 En=G;if(En.id!==void 0||En.createdAt!==void 0){let lt=ee.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=ee.relations?.find(ct=>ct.propertyName===U);lt&&(N[U]=G.map(ct=>w(ct,lt.targetTableName)))}return N};E=w(E,l.table)}return i&&(i.setQueryPath("full"),i.dur("sql_executor",t,{table:e.tableName})),{data:E,...k.length>0&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:B}:{},...k.includes("filterCount")||k.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=x(e,this.dbType),c=x(a,this.dbType);if(!n||!o)throw new I(`Sort relation '${i}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let d=n.foreignKeyColumn||n.mappedBy;if(!d)throw new I(`Sort function '_count(${i})' cannot resolve relation key on '${e}'.`);let l=x(o,this.dbType),f=x(d,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}if(n.type==="many-to-many"){let d=this.resolveManyToManyContract(n,i,e),l=x(d.tableName,this.dbType),f=x(d.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}throw new I(`Sort function '_count(${i})' is only supported for list relations on '${e}'.`)}buildRelationAggregateSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=t.aggregateField,s=n?.targetTableName||n?.targetTable,a=this.metadata?.tables?.get(e),u=this.metadata?.tables?.get(s),c=H(a)?.name||"id",d=H(u)?.name||"id",l=x(e,this.dbType),f=x(c,this.dbType),p=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!p||!n||!s||!o)throw new I(`Sort function '${t.field}' is not supported on '${e}'.`);let h=x(s,this.dbType),g=x(o,this.dbType);if(n.type==="one-to-many"){let m=n.foreignKeyColumn||n.mappedBy;if(!m)throw new I(`Sort function '_${t.function}(${i}.${o})' cannot resolve relation key on '${e}'.`);let y=x(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=x(m.tableName,this.dbType),b=x(m.sourceColumn,this.dbType),$=x(m.targetColumn,this.dbType),C=x(d,this.dbType);return`(SELECT ${p}(${h}.${g}) FROM ${y} JOIN ${h} ON ${h}.${C} = ${y}.${$} WHERE ${y}.${b} = ${l}.${f})`}throw new I(`Sort function '_${t.function}(${i}.${o})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,n){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new I(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async 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=x(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=x(e.tableName,this.dbType),o=[],s=[];for(let l of t.dimensions){let f=`${i}.${x(l.field,this.dbType)}`,p=l.bucket?this.buildSqlBucketExpression(f,l.bucket,l.timezone,l.column.type):f;s.push(this.knex.raw(`${p} as ${x(l.outputKey,this.dbType)}`)),o.push(p)}for(let l of t.measures){let f=`${i}.${x(l.field,this.dbType)}`,p=l.operation==="count"?`COUNT(${f})`:l.operation==="countDistinct"?`COUNT(DISTINCT ${f})`:`${l.operation.toUpperCase()}(${f})`;s.push(this.knex.raw(`${p} as ${x(l.outputKey,this.dbType)}`))}let u=new Z().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(`${x(l.field,this.dbType)} ${l.direction.toUpperCase()}`);return t.limit!==void 0&&n.limit(t.limit).offset((t.page-1)*t.limit),{data:(await n).map(l=>{let f={...l};for(let p of t.measures){let 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 I(`Aggregate time bucket is not supported on ${this.dbType}`)}};var vn=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,ci.dirname)(this.batchInsertTraceFile),{recursive:!0})}async runWithPolicy(e,t){return this.knexService?this.knexService.runWithPolicy(e,t):this.mongoService?this.mongoService.runWithPolicy(e,t):t()}async runWithFieldPermissionCheck(e,t){return this.knexService?this.knexService.runWithFieldPermissionCheck(e,t):this.mongoService?this.mongoService.runWithFieldPermissionCheck(e,t):t()}async runWithTelemetryContext(e,t){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.runWithQueryContext(e,t):await t()}getDbType(){return this.dbType}safeObjectId(e){if(!vn.ObjectId)return e;if(typeof e=="string")try{return new vn.ObjectId(e)}catch{return e}return e}async getMetadataForQuery(){let e={tables:new Map,tablesList:[]},t=this.lazyRef.metadataCacheService;return t?t.isLoaded?.()?await t.getMetadata?.()??e:t.getDirectMetadata?.()??e:e}async buildMongoFilter(e,t){let n=await this.getMetadataForQuery(),i=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(Y(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 Z().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 vn.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[n,i]of Object.entries(e))t[n]=Array.isArray(i)?i.map(o=>this.safeObjectId(o)):this.safeObjectId(i);return t}filterToWhere(e){let t=[];for(let[n,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let o=Object.entries(i)[0];if(o){let[s,a]=o,u=this.mapFilterOperatorToSql(s);t.push({field:n,operator:u,value:a})}}return t}mapFilterOperatorToSql(e){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"like",_starts_with:"like",_ends_with:"like",_is_null:"is null",_is_not_null:"is not null"}[e]||"="}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,maxQueryDepth:e.maxQueryDepth})})}async aggregate(e){return this.trackQueryMetric("aggregate",e.table,async()=>{let t=await this.getMetadataForQuery();return this.dbType==="mongodb"?new 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 Y(a)}let i=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),s=i||t.id;return await o(e).where("id",s).first()})}async insertMany(e,t){return t.length===0?[]:this.trackQueryMetric("insert_many",e,async()=>this.dbType==="mongodb"?(await this.runMongoMutationInSaga(async()=>typeof this.mongoService.insertManyWithCascade=="function"?this.mongoService.insertManyWithCascade(e,t):Promise.all(t.map(i=>this.mongoService.insertOne(e,i))))).map(i=>Y(i)):this.knexService.insertManyWithCascade(e,t))}async flushBatchInserts(){for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)await this.flushBatchInsertBuffer()}async insertManyBatch(e,t){let n=Array.isArray(t)?t:[t];for(let i of n)this.batchInserts.items.push({table:e,data:i});return this.traceBatchInsert("enqueue",{tableName:e,count:n.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i)),{accepted:!0,batch:!0,count:n.length}}async flushBatchInsertBuffer(){if(this.batchInserts.flushing){await this.batchInserts.flushPromise;return}let e=this.batchInserts.items.splice(0,this.batchInserts.items.length);if(this.batchInserts.timer&&(clearTimeout(this.batchInserts.timer),this.batchInserts.timer=void 0),e.length===0)return;this.batchInserts.flushing=!0;let t=this.executeBatchInsertFlush(e);this.batchInserts.flushPromise=t,await t}async executeBatchInsertFlush(e){let t=Date.now();try{let n=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...n.entries()].map(([i,o])=>({tableName:i,count:o.length}))}),await this.runLimited([...n.entries()],([i,o])=>this.flushBatchInsertTable(i,o)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}finally{this.batchInserts.flushing=!1,this.batchInserts.flushPromise=void 0,this.batchInserts.items.length>0&&(this.batchInserts.timer&&clearTimeout(this.batchInserts.timer),this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(n=>this.logBatchInsertError("QueryBuilder batch insert flush failed",n))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let n=Date.now();await this.runBatchInsertWithIsolation(e,t),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-n})}async runBatchInsertWithIsolation(e,t){if(t.length!==0)try{await(async()=>{if(this.dbType==="mongodb"){await this.runMongoMutationInSaga(async()=>{if(typeof this.mongoService?.insertManyWithCascade=="function"){await this.mongoService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.mongoService.insertOne(e,i.data)))});return}if(typeof this.knexService?.insertManyWithCascade=="function"){await this.knexService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.knexService.insertWithCascade(e,i.data)))})()}catch(n){if(t.length===1){this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,n);return}let i=Math.ceil(t.length/2);await Promise.all([this.runBatchInsertWithIsolation(e,t.slice(0,i)),this.runBatchInsertWithIsolation(e,t.slice(i))])}}groupBatchInsertsByTable(e){let t=new Map;for(let n of e){let i=t.get(n.table);i?i.push(n):t.set(n.table,[n])}return t}async runLimited(e,t){let n=0,i=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;n<e.length;){let o=e[n++];await t(o)}});await Promise.all(i)}readPositiveEnv(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.trunc(n):t}traceBatchInsert(e,t){this.batchInsertTraceFile&&(0,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 Y(o)}return await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first()})}async updateMany(e,t,n,i=this.getPkField()){return t.length===0?0:this.trackQueryMetric("update_many",e,async()=>{if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let a=this.mongoService.collection(e),u=this.mongoService.ioSignalPublic?.()??{};return(await a.updateMany({[i]:{$in:t}},{$set:n},u)).modifiedCount});let s=await this.knexService.getKnex()(e).whereIn(i,t).update(n);return typeof s=="number"?s:0})}async delete(e,t){return this.trackQueryMetric("delete",e,async()=>t&&typeof t=="object"&&"where"in t?await this.deleteWithOptions({table:e,where:t.where})>0:this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t)):await this.knexService.getKnex()(e).where("id",t).delete()>0)}async deleteMany(e,t,n=this.getPkField()){return t.length===0?0:this.trackQueryMetric("delete_many",e,async()=>{if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let s=this.mongoService.collection(e),a=this.mongoService.ioSignalPublic?.()??{},u=await s.find({[n]:{$in:t}},a).toArray(),c=0;for(let d of u)await this.mongoService.deleteOne(e,d._id)&&c++;return c});let o=await this.knexService.getKnex()(e).whereIn(n,t).delete();return typeof o=="number"?o:0})}async countRecords(e,t){if(this.dbType==="mongodb")return this.mongoService.count(e,t||{});let i=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.filterToWhere(t);({query:i}=await this.applyWhereToKnex(i,s,e))}let o=await i.count("* as count").first();return Number(o?.count||0)}async transaction(e){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>e(this.mongoService)):this.knexService.transaction(e)}async findById(e,t){if(this.dbType==="mongodb"){let i=this.safeObjectId(t);return this.mongoService.findOne(e,{_id:i})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[o,s]of Object.entries(t))o==="id"||o==="_id"?i._id=this.safeObjectId(s):i[o]=s;return this.mongoService.findOne(e,i)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[u,c]of Object.entries(t))u==="id"||u==="_id"?i._id=this.safeObjectId(c):i[u]=c;let o=this.mongoService.collection(e),s=this.mongoService.ioSignalPublic?.()??{};return await o.find(i,s).toArray()}return await this.knexService.getKnex()(e).where(t)}async insertAndGet(e,t){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));let n=await this.knexService.insertWithCascade(e,t),i=this.knexService.getKnex(),o=n||t.id;return await i(e).where("id",o).first()}async updateById(e,t,n){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n)):(await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first())}async deleteById(e,t){return this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t))?1:0:this.knexService.getKnex()(e).where("id",t).delete()}async raw(e,t){let n=this.dbType==="mongodb"?"mongodb":"sql";return this.trackQueryMetric("raw",n,async()=>{if(this.dbType==="mongodb"){let o=this.mongoService.getDb();if(typeof e=="string"){if(e.toLowerCase().includes("select 1"))return await o.command({ping:1});throw new Error("String queries not supported for MongoDB. Use db.command() object instead.")}return await o.command(e)}return await this.knexService.getKnex().raw(e,t)})}async trackQueryMetric(e,t,n){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.trackQuery({op:e,table:t},n):await n()}getConnection(){return this.dbType==="mongodb"?this.mongoService.getDb():this.knexService.getKnex()}getKnex(){if(this.dbType==="mongodb")throw new Error("getKnex() is not available for MongoDB. Use getConnection() or unified methods.");return this.knexService.getKnex()}getMongoDb(){if(this.dbType!=="mongodb")throw new Error("getMongoDb() is not available for SQL. Use getConnection() or unified methods.");return this.mongoService.getDb()}getDatabaseType(){return this.dbType}isMongoDb(){return this.dbType==="mongodb"}isSql(){return["mysql","postgres","mariadb","sqlite"].includes(this.dbType)}getPkField(){return this.isMongoDb()?"_id":"id"}getRecordId(e){return this.isMongoDb()?e._id:e.id}};hr();pr();dr();ae();qt();Ge();bn();de();Je();var ui=new Set(["fields","filter","sort","limit","page","deep"]),Nn=3;function mr(r,e,t,n=0,i=3){if(!e||typeof e!="object")return;if(n>=i)throw new I(`deep option exceeds maximum query depth of ${i}`);let o=t?.tables?.get(r),s=new Map((o?.relations??[]).map(a=>[a.propertyName,a]));for(let[a,u]of Object.entries(e)){let c=s.get(a);if(!c)throw new I(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let f of Object.keys(u))if(!ui.has(f))throw new I(`Unknown deep option key '${f}' for relation '${a}'. Allowed: ${[...ui].join(", ")}`);let d=c.type;if(u.limit!==void 0&&(d==="many-to-one"||d==="one-to-one"))throw new I(`'limit' not supported on many-to-one/one-to-one relations (relation '${a}' on '${r}')`);if(u.page!==void 0&&u.limit===void 0)throw new I(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let l=c.targetTableName||c.targetTable;if(l){if(u.filter&&(re(u.filter,l,t),Oe(u.filter,l,t),In(u.filter,0,a,r)),u.sort){Tn(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;Do(h,l,t,a,r)}}u.deep&&mr(l,u.deep,t,n+1,i)}}}function Do(r,e,t,n,i){if(r.includes("."))throw new I(`Sort field '${r}' is not supported for relation '${n}' on '${i}'. Sort only by local fields defined on '${e}'.`);let o=t?.tables?.get(e);if(!o)throw new I(`Sort field '${r}' references unknown table '${e}' (relation '${n}' on '${i}')`);let s=o.columns?.some(u=>u.name===r),a=r==="id"&&o.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new I(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${i}')`)}var Wo=new Set(["_and","_or","_not"]);function In(r,e,t,n){if(!(!r||typeof r!="object"))for(let[i,o]of Object.entries(r)){if(Wo.has(i)){if(Array.isArray(o))for(let c of o)In(c,e,t,n);else o&&typeof o=="object"&&In(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>Nn)throw new I(`Filter path exceeds max dotted hops of ${Nn} at '${i}' (relation '${t}' on '${n}')`);let u={};for(let c of Object.keys(o))c.startsWith("_")||(u[c]=o[c]);In(u,a,t,n)}}function di(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 fi(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(",")}Et();Je();Mt();cn();Ke();de();function Ko(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});
|