@enfyra/kernel 1.1.63 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,10 @@
1
- "use strict";var pi=Object.create;var zt=Object.defineProperty;var gi=Object.getOwnPropertyDescriptor;var hi=Object.getOwnPropertyNames;var yi=Object.getPrototypeOf,mi=Object.prototype.hasOwnProperty;var U=(r,e)=>()=>(r&&(e=r(r=0)),e);var In=(r,e)=>{for(var t in e)zt(r,t,{get:e[t],enumerable:!0})},hr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of hi(e))!mi.call(r,i)&&i!==t&&zt(r,i,{get:()=>e[i],enumerable:!(n=gi(e,i))||n.enumerable});return r};var xe=(r,e,t)=>(t=r!=null?pi(yi(r)):{},hr(e||!r||!r.__esModule?zt(t,"default",{value:r,enumerable:!0}):t,r)),bi=r=>hr(zt({},"__esModule",{value:!0}),r);function Rr(r){return Pn.createHash("md5").update(r).digest("hex").substring(0,8)}function xr(r){return r.length<=kr-3?`${r}_pk`:`j_${Rr(r)}_pk`}function Fr(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=kr?n:`j_${Rr(r)}_${t}_fk`}function Ft(r,e,t){let n=`${r}:${e}:${t}`;return`j_${Pn.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function z(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 Er(r,e,t){return`${r}_${e}_${t}_idx`}var Pn,kr,Ke=U(()=>{"use strict";Pn=xe(require("crypto")),kr=63});function on(r){return ro[r]??null}var _e,Dn,Nt,ro,sn=U(()=>{"use strict";_e=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),Dn=new Set(["_and","_or","_not"]),Nt=[...Array.from(Dn),...Array.from(_e)],ro={_eq:"eq",_neq:"neq",_gt:"gt",_gte:"gte",_lt:"lt",_lte:"lte",_in:"in",_not_in:"not_in",_nin:"not_in",_contains:"contains",_starts_with:"starts_with",_ends_with:"ends_with",_between:"between"}});var I,ue=U(()=>{"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 Pr(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var jr=U(()=>{"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 an(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("_")&&!_e.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(io.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)){an(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)&&an(s,a,e)}}var io,Je=U(()=>{"use strict";ue();sn();jr();io=new Set(["_and","_or","_not"])});function de(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:ln(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function ln(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=oo(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 oo(r,e,t){if(r==="_and")return Br("and",e,t);if(r==="_or")return Br("or",e,t);if(r==="_not"){let c=ln(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?so(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}):ao(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=ln(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 so(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:ln(l,u).node,hasRelationFilters:!0}}function ao(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:co(r,t)};if(e===null)return{node:{kind:"compare",field:n,op:"is_null",value:!0},hasRelationFilters:!1};if(typeof e!="object")return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};for(let s of Object.keys(e))s.startsWith("_")&&!_e.has(s)&&Ee(s,r,t.tableName);let i=Object.entries(e).filter(([s])=>_e.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=lo(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 lo(r,e,t){if(e==="_is_null")return{kind:"compare",field:r,op:"is_null",value:t===!0};if(e==="_is_not_null")return{kind:"compare",field:r,op:"is_null",value:t!==!0};let n=on(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function co(r,e){let t=e.metadata?.tables?.get(e.currentTable);if(!t)return!1;let n=r.includes(".")?r.split(".").pop():r,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=U(()=>{"use strict";sn();Je()});var ie,Mt=U(()=>{"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 K(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(Vn,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,Vn,Hn,Te,Ge=U(()=>{"use strict";ue();Me=16,oe=5e3,Vn=4,Hn=10;Te=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:Hn}: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 w of e){let C=w[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 w of e)w[t.relationName]=null,o!==t.relationName&&delete w[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete w[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 w of e){let C=w[o];w[t.relationName]=C!=null?this.adapter.buildScalarRef(C,f):null,o!==t.relationName&&delete w[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete w[t.fkColumn]}return}let p=performance.now(),y=await this.adapter.fetchOwner(t.targetTable,a,l,t),g=Array.isArray(y)?y:y.docs,h=Array.isArray(y)?void 0:y.stats;this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:h?.strategy??"batch-in",roundtrips:h?.roundtrips??(Math.ceil(a.length/oe)||1),concurrencyWaves:h?.concurrencyWaves,ioConcurrency:h?.ioConcurrency,rowsTransferred:h?.rowsTransferred??g.length,rowsReturned:g.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let m=this.enrichNestedDescs(d,t.nestedDeep,u);m.length>0&&await this.execute(g,m,n,i+1,t.targetTable);let b=new Map;for(let w of g)b.set(this.adapter.keyOf(w[f]),w);for(let w of e){let C=w[o];w[t.relationName]=C!=null&&b.get(this.adapter.keyOf(C))||null,o!==t.relationName&&delete w[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete w[t.fkColumn]}}async fetchInverseRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=this.uniqueValues(e.map(v=>v[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:y,stats:g}=await this.adapter.fetchInverse(t.targetTable,u,a,l,t),h=new Map,m=t.fields.includes(u)||t.fields.includes("*");for(let v of p){let j=v[y],S=this.adapter.keyOf(j);h.has(S)||h.set(S,[]),h.get(S).push(v)}let b=t.userLimit!==void 0&&t.userLimit>0,w=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(h.values()).reduce((v,j)=>v+j.length,0);if(this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,f,{relationType:t.type,targetTable:t.targetTable,strategy:g?.strategy??w,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 v of p)this.adapter.postProcessInverseChild(v,u,m);let x=this.enrichNestedDescs(d,t.nestedDeep,c);x.length>0&&await this.execute(p,x,n,i+1,t.targetTable);let _=t.type==="one-to-one";for(let v of e){let j=this.adapter.keyOf(v[s]),S=h.get(j)||[];v[t.relationName]=_?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:y}=await this.adapter.fetchM2M(e,t,o,u,d),g=t.userLimit!==void 0&&t.userLimit>0,h=g?"m2m-per-parent-c16":"m2m-batch",m=g?a.length:Math.ceil(a.length/oe)||1,b=g?Math.ceil(a.length/Me):void 0,w=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:y?.strategy??h,roundtrips:y?.roundtrips??m,concurrencyWaves:y?.concurrencyWaves??b,ioConcurrency:y?.ioConcurrency,rowsTransferred:y?.rowsTransferred??p.length,rowsReturned:w,rowsDiscarded:y?.rowsDiscarded??Math.max(0,(y?.rowsTransferred??p.length)-w),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 Jr,Se,hn=U(()=>{"use strict";Jr=2,Se=class{constructor(e=2){this.concurrency=e;this.active=0;this.waiters=[];if(!Number.isInteger(e)||e<1)throw new Error("Batch execution concurrency must be a positive integer")}async run(e){await this.acquire();try{return await e()}catch(t){throw this.cancel(t),t}finally{this.release()}}async acquire(){if(this.failure!==void 0)throw this.failure;if(this.active<this.concurrency){this.active+=1;return}if(await new Promise(e=>this.waiters.push(e)),this.failure!==void 0)throw this.failure;this.active+=1}release(){this.active-=1,this.failure===void 0&&this.waiters.shift()?.()}cancel(e){if(this.failure===void 0){this.failure=e;for(let t of this.waiters.splice(0))t()}}}});function F(r,e){let t=e==="mysql"?r.replace(/`/g,"``"):r.replace(/"/g,'""');switch(e){case"mysql":return`\`${t}\``;case"postgres":case"pg":case"sqlite":return`"${t}"`;case"mongodb":return r;default:return`\`${t}\``}}function ke(r,e){return r.split(".").map(t=>t==="*"||t.startsWith('"')&&t.endsWith('"')||t.startsWith("`")&&t.endsWith("`")?t:F(t,e)).join(".")}var ae=U(()=>{"use strict"});function ce(r,e,t){e&&Sn(r,e,t,"and")}function Sn(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(){Sn(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(){Sn(this,o,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"not":{let i=function(){this.whereNot(function(){Sn(this,e.child,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"compare":Do(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 Do(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=Wo(e.field,t),o=ke(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",y=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(h=>typeof h=="string")?r[c](`${o} = ANY(?::uuid[])`,[g]):r[d](i,g);return}case"not_in":{let g=ri(e.value);s&&a&&g.every(h=>typeof h=="string")?r[c](`${o} != ALL(?::uuid[])`,[g]):r[l](i,g);return}case"contains":sr(r,o,e.value,"contains",t,n);return;case"starts_with":sr(r,o,e.value,"starts_with",t,n);return;case"ends_with":sr(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[y](i);return}}function sr(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 Wo(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 ar=U(()=>{"use strict";ae()});function G(r){return r.columns.find(e=>e.isPrimary)||null}var qt=U(()=>{"use strict"});var ii={};In(ii,{expandFieldsToJoinsAndSelect:()=>lr});async function lr(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],y=f.slice(1).join(".");c.has(p)||c.set(p,[]),c.get(p).push(y)}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(y=>y.trim()).filter(Boolean):["*"];c.set(l,p)}let d=c.get("")||[];for(let l of d){if(l==="*"){let y=new Set;for(let h of u.relations||[])if(h.type==="many-to-one"||h.type==="one-to-one"&&!h.isInverse){let m=h.foreignKeyColumn||z(h.propertyName);m&&y.add(m)}let g=new Set;for(let h of u.columns)y.has(h.name)||(s.push(`${r}.${h.name}`),g.add(h.name));for(let h of u.relations||[])!c.has(h.propertyName)&&!g.has(h.propertyName)&&c.set(h.propertyName,["id"]);continue}if(l.includes(".")){s.push(`${r}.${l}`);continue}if(u.columns?.find(y=>y.name===l)){s.push(`${r}.${l}`);continue}if(u.relations?.find(y=>y.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||z(p.propertyName),w=F(r,n),C=F(b,n),T=F(f,n);s.push(`${w}.${C} as ${T}`)}let g=p.targetTableName||p.targetTable,h=o?.[f],m=h?.fields!=null?Array.isArray(h.fields)?h.fields:String(h.fields).split(",").map(b=>b.trim()).filter(Boolean):l;a.push({relationName:f,type:p.type,targetTable:g,fields:m,isInverse:p.isInverse,fkColumn:p.foreignKeyColumn,mappedBy:p.mappedBy,junctionTableName:p.junctionTableName,junctionSourceColumn:p.junctionSourceColumn,junctionTargetColumn:p.junctionTargetColumn,userFilter:h?.filter,userSort:h?.sort,userLimit:h?.limit!==void 0?Number(h.limit):void 0,userPage:h?.page!==void 0?Number(h.page):void 0,nestedDeep:h?.deep})}),{select:s,batchFetchDescriptors:a}}var cr=U(()=>{"use strict";Ke();ae()});var Ut,Qt,Cn,ot,Ko,st,dr=U(()=>{"use strict";Ke();ae();qt();Ge();hn();ar();Mt();Et();Ut="__enfyra_row_number__",Qt="__sourceId__",Cn="__targetId__",ot="__enfyra_partitioned__",Ko=5e4,st=class{constructor(e,t="postgres",n,i=new Se){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"?Ko: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}=de(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],y=this.metadata?.tables?.get(d);if(!y)break;let g=y.relations?.find(b=>b.propertyName===p);if(!g)break;let h=g.targetTableName||g.targetTable,m=`__sort_${c.slice(0,f+1).join("_")}`;if(!s.has(m)){s.add(m);let b=g.foreignKeyColumn||z(g.propertyName),w=this.metadata?.tables?.get(h),C=w&&G(w)?.name||"id";e.leftJoin(`${h} as ${m}`,`${m}.${C}`,`${l}.${b}`)}d=h,l=m}}}toKnexSelect(e,t){let n=e.indexOf(" as ");if(n!==-1){let i=e.substring(0,n),o=e.substring(n+4),s=F(o,this.dbType),a=t?`${t}.${F(i,this.dbType)}`:F(i,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${t}.${F(e,this.dbType)} as ${F(e,this.dbType)}`):e}keyOf(e){return e==null?"":String(e)}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return G(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;return!t&&e.mappedBy&&(t=z(e.mappedBy)),t||(t=z(e.targetTable)),t}resolveParentPk(e){return e&&G(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||z(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=G(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||z(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 K(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(y=>y.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 y=l?(l-1)*d:0,g=i.selectCols.map(m=>this.toKnexSelect(m)),h=await K(n,async m=>{let b=this.knex(e).select(g).select(this.buildPartitionRowNumber(`${e}.${t}`,c,`${e}.${i.pkCol}`)).whereIn(`${e}.${t}`,m);u&&ce(b,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(b,o.userSort,e);let w=await this.runQuery(this.buildPartitionSlice(b,s,y,d));return this.removePartitionFields(w),w});return{docs:h,groupKeyField:s,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(n),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:h.length}}}let f=i.selectCols.map(y=>this.toKnexSelect(y)),p=await K(n,y=>{let g=this.knex(e).select(f).whereIn(t,y);if(u&&ce(g,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(g,o?.userSort,e),c.length>0)for(let h of c)g.orderBy(h.column,h.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 K(e,async m=>{let b=this.knex(n).select({[Qt]:`${n}.${i}`,[Cn]:`${n}.${o}`}).whereIn(`${n}.${i}`,m);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 w=await this.runQuery(this.buildPartitionSlice(b,Qt,g,f));return this.removePartitionFields(w),w})).map(m=>({sourceId:m[Qt],targetId:m[Cn]}))}return(await K(e,g=>{let h=this.knex(n).select({[Qt]:`${n}.${i}`,[Cn]:`${n}.${o}`}).whereIn(`${n}.${i}`,g);if(d&&(h=h.join(`${t.targetTable} as t`,`${n}.${o}`,`t.${s}`),a&&ce(h,a,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(h,t.userSort,t.targetTable,"t")),h.orderBy(`${n}.${i}`,"asc"),l.length>0){for(let m of l)h.orderBy(m.column,m.order);d&&!l.some(m=>m.column===c)&&h.orderBy(c,"asc")}else h.orderBy(`${n}.${o}`,"asc");return this.runQuery(h)})).map(g=>({sourceId:g[Qt],targetId:g[Cn]}))}async loadM2MTargets(e,t,n){if(t.length===0)return[];let i=n.selectCols.map(o=>this.toKnexSelect(o));return K(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),y=new Map;for(let x of a)y.set(this.keyOf(x),[]);let g=o.selectCols.length===1&&o.selectCols[0]===o.pkCol,h=t.userLimit!==void 0&&t.userLimit>0,m=this.chunkCount(a),b=`t.${o.pkCol}`,w=!l&&f.every(x=>x.column===b);if(g){let x=new Map;for(let _ of p){let v=this.keyOf(_.targetId);x.has(v)||x.set(v,{[o.pkCol]:_.targetId}),y.get(this.keyOf(_.sourceId))?.push(x.get(v))}return{grouped:y,docs:[],stats:{strategy:w?h?"m2m-junction-partitioned-top-k":"m2m-junction-batch":h?"m2m-filtered-edge-top-k":"m2m-filtered-edge-batch",roundtrips:m,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let C=this.uniqueValues(p.map(x=>x.targetId)),T=await this.loadM2MTargets(t.targetTable,C,o),k=new Map(T.map(x=>[this.keyOf(x[o.pkCol]),x]));for(let x of p){let _=k.get(this.keyOf(x.targetId));_&&y.get(this.keyOf(x.sourceId))?.push(_)}return{grouped:y,docs:T,stats:{strategy:h?"m2m-partitioned-edge-loader":"m2m-edge-loader",roundtrips:m+(C.length>0?this.chunkCount(C,this.m2mTargetChunkSize()):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+T.length,rowsDiscarded:0}}}}});var li={};In(li,{executeBatchFetches:()=>fr});async function fr(r,e,t,n,i=3,o=0,s,a="postgres",u,c){let d=new st(r,a,u);await new Te(d,n,c).execute(e,t,i,o,s)}var pr=U(()=>{"use strict";Ge();dr()});var Jo={};In(Jo,{ALL_SUPPORTED_OPERATORS:()=>Nt,AuthenticationException:()=>gt,AuthorizationException:()=>ht,BadRequestException:()=>I,BatchExecutionBudget:()=>Se,BatchFetchEngine:()=>Te,BusinessLogicException:()=>ut,CHUNKED_FETCH_CONCURRENCY:()=>Vn,ConfigurationException:()=>$t,DEEP_TO_MANY_DEFAULT_LIMIT:()=>Hn,DEFAULT_BATCH_FETCH_IO_CONCURRENCY:()=>Jr,DEFAULT_TIMEOUT_MS:()=>Vt,DOTTED_PATH_MAX_HOPS:()=>Fn,DatabaseException:()=>Le,DuplicateResourceException:()=>pt,ErrorHandler:()=>Fe,ExecutorEngineService:()=>Be,ExternalServiceException:()=>bt,FIELD_OPERATORS:()=>_e,FileNotFoundException:()=>St,FileSizeExceededException:()=>Ct,FileUploadException:()=>Tt,HttpException:()=>P,InvalidTokenException:()=>mt,IsolatedExecutorService:()=>We,JoinRegistry:()=>ie,LOGICAL_OPERATORS:()=>Dn,MongoBatchAdapter:()=>Xe,MongoQueryExecutor:()=>Ae,PER_PARENT_CONCURRENCY:()=>Me,QueryBuilderService:()=>at,QueryPlanner:()=>ee,ResourceNotFoundException:()=>ft,SchemaException:()=>wt,ScriptContractService:()=>Xt,ScriptExecutionException:()=>ye,ScriptTimeoutException:()=>he,ServiceUnavailableException:()=>_t,SqlBatchAdapter:()=>st,SqlQueryExecutor:()=>je,TokenExpiredException:()=>yt,ValidationException:()=>dt,WHERE_IN_CHUNK_SIZE:()=>oe,WorkerPool:()=>Rt,applyOperatorToMatch:()=>rn,applyRelationFilters:()=>Lt,applyWhereToKnex:()=>it,assertFieldOperatorValueIsClean:()=>an,buildMongoCharFoldMapJson:()=>Bn,buildMongoFoldTextSearchJs:()=>Zt,buildRelationSubquery:()=>Bt,buildSqlWherePartsFromFieldAst:()=>Wt,buildWhereClause:()=>le,camelToSnake:()=>Ir,chunkedFetch:()=>K,compileScriptSource:()=>Ji,computeEngineTuning:()=>Mn,createEnfyraKernel:()=>Qo,dslOpToCompareOp:()=>on,encodeMainThreadToIsolate:()=>An,escapeSqlValue:()=>Kt,executeBatchFetches:()=>fr,executeMongoBatchFetches:()=>mn,expandFieldsToJoinsAndSelect:()=>lr,getEffectiveCpuCount:()=>En,getEffectiveMemoryBytes:()=>kt,getEngineTuning:()=>Yt,getExecutableScript:()=>Gi,getForeignKeyColumnName:()=>z,getIoAbortSignal:()=>Sr,getJunctionColumnNames:()=>vt,getJunctionTableName:()=>Ft,getPrimaryKeyColumn:()=>G,getScriptLegacyField:()=>qi,getShortFkConstraintName:()=>Fr,getShortFkName:()=>Nr,getShortIndexName:()=>Er,getShortPkName:()=>xr,hasLogicalOperators:()=>ge,isExecutableJavaScript:()=>zi,isScriptTable:()=>Ui,normalizeAggregateQuery:()=>tt,normalizeFlowStepScriptConfig:()=>Xi,normalizeScriptLanguage:()=>Qi,normalizeScriptPatch:()=>Hi,normalizeScriptRecord:()=>Vi,parseBatchFields:()=>He,parseFields:()=>bn,parseFilter:()=>de,perParentRun:()=>yn,quoteIdentifier:()=>F,quoteQualifiedIdentifier:()=>ke,resolveExecutableScript:()=>Yi,rewriteFilterDenyingFields:()=>di,rewriteSortDroppingDenied:()=>fi,runWithIoAbortSignal:()=>Cr,scriptContractService:()=>te,separateFilters:()=>H,snakeToCamel:()=>vr,throwUnsupportedFieldOperator:()=>Ee,validateDeepOptions:()=>gr,validateFilterShape:()=>re,whereToMongoFilter:()=>Qe});module.exports=bi(Jo);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 wr=require("async_hooks"),$r=xe(require("path")),Tr=require("stream");var yr=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.stderrTail="";this.child=(0,yr.fork)(e,[],{stdio:["ignore","ignore","pipe","ipc"],env:wi(),serialization:"advanced"}),this.child.stderr?.on("data",t=>{this.stderrTail=(this.stderrTail+t.toString("utf8")).slice(-8192)})}get stderr(){return this.stderrTail}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 he=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}}},L=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 L{constructor(e,t,n){super(e,t,`HTTP_${t}`,n)}},ut=class extends L{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},dt=class extends L{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},ft=class extends L{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 L{constructor(e,t,n){super(`${e} with ${t} '${n}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:n})}},gt=class extends L{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},ht=class extends L{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},yt=class extends L{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},mt=class extends L{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},Le=class extends L{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},bt=class extends L{constructor(e,t,n){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:n})}},_t=class extends L{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},wt=class extends L{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},$t=class extends L{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},Tt=class extends L{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},St=class extends L{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},Ct=class extends L{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var Fe=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 yt;case"$throw.invalidToken":return new mt;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 he(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 me=xe(require("os")),De=xe(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<me.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<me.totalmem())return e}catch{}return me.totalmem()}function En(){let r=me.availableParallelism?.()||me.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 $i=.25,Nn=128,Ti=2,Si=4,Ci=6,ki=8,Ri=2048,xi=40,Fi=128,vi=32;function Ii(r){let e=Math.trunc(Number(r));if(!(!Number.isFinite(e)||e<1))return Math.min(Nn,e)}function Ni(r){let e=Math.trunc(Number(r));return!Number.isFinite(e)||e<1?Ci:Math.min(ki,e)}function mr(r){return 2**Math.ceil(Math.log2(Math.max(1,r)))}function Mn(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(xi,Math.round(t/vi))),i=t*$i,o=Math.max(1,Math.floor(i/n)),s=Math.max(1,Math.min(e,2,o)),a=Math.max(1,Math.floor(i/(s*n))),u=Math.min(Nn,mr(e*Ti)),c=Math.min(Nn,mr(e*Si)),d=Math.max(u,Math.min(c,a)),l=Ii(r.maxLanesPerRunner)??d,f=t<Ri?1:l,p=Math.max(1,Math.min(f,a)),y=Ni(r.tasksPerIsolate),g=p*y;return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:g,isolatePoolSize:p,tasksPerIsolate:y}}function Yt(){return Mn({logicalCpuCount:En(),totalMemoryBytes:kt()})}var Wi=$r.join(__dirname,"execution/worker.js"),Ki=1e3,On=new wr.AsyncLocalStorage;function Sr(){return On.getStore()}function Cr(r,e){return On.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),typeof n.runnerRssBytes=="number"&&(t.lastRssBytes=n.runnerRssBytes),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",(n,i)=>{let o=t.draining,s=this.destroying,a={entryId:t.id,pid:t.worker.pid,exitCode:n,exitSignal:i??null,lastError:t.lastError||t.worker.stderr||void 0,terminationReason:t.terminationReason,lastHeapRatio:t.lastHeapRatio,lastRssBytes:t.lastRssBytes,activeTasks:[...t.tasks.values()].map(c=>c.diagnostics)};t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,c]of t.tasks)c.abortController.abort(),c.onResult({type:"result",success:!1,error:{message:s?"Worker terminated":t.lastError?`Worker crashed: ${t.lastError}`:"Worker crashed",code:s?void 0:"ERR_EXECUTOR_RUNNER_LOST",details:s?void 0:{outcome:"unknown_outcome",retryable:!1}}});t.tasks.clear();let u=this.entries.indexOf(t);u!==-1&&this.entries.splice(u,1),!o&&!s&&(this.onCrash?.(a),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,t="host_requested"){e.terminationReason=t,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,lastRssBytes:e.lastRssBytes??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}},_r=new Set(["$helpers","$cache","$transaction","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$debug"]);function An(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.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.queueWaitDurationsMs=[];this.runtimeCallbackCounter=0;this.packageCacheService=e.packageCacheService,this.onExecutionFinished=e.onExecutionFinished,this.packageCdnLoaderService=e.packageCdnLoaderService,this.isolationTuning=e.tuning??Yt(),this.ceiling=this.isolationTuning.maxConcurrentWorkers,this.pool=new Rt(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Wi,t=>{this.crashesTotal++;let n={event:"executor_worker_crashed",occurredAt:new Date().toISOString(),...t};this.logger.warn(n);try{e.onExecutorWorkerCrash?.(n)}catch(i){this.logger.warn({event:"executor_worker_crash_report_failed",error:i instanceof Error?i.message:String(i)})}},({reason:t,ageMs:n})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${t} age=${Math.round(n/1e3)}s`)}),this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerIsolate} tasks/isolate, ${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||_r.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"||_r.has(n)||n==="$env"||(e[n]=i));delete e.$pkgs}}spawnAndExecute(e,t,n,i,o){return(async()=>{let s=Date.now(),a=await this.pool.dispatch();if(this.recordQueueWait(Date.now()-s),o?.aborted){this.pool.releaseReservation(a);let d=new Error("Execution aborted after client disconnect");return d.code="ERR_EXECUTION_ABORTED",d.isAbort=!0,Promise.reject(d)}let u=`t_${++this.taskCounter}`,c=Date.now();return new Promise((d,l)=>{let f=!1,p=new AbortController,y=!1,g,h=()=>{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,_},b,w=_=>{if(!(f||y)){y=!0,g=_,p.abort(),this.cleanupResponseStream(u,_);try{a.worker.postMessage({type:"cancelTask",id:u})}catch{}b=setTimeout(()=>{f||(f=!0,clearTimeout(x),k(),this.taskCancellers.delete(u),this.pool.unregisterTask(a,u),this.taskErrorTotal++,this.pool.terminateEntry(a,_.isTimeout?"timeout_cancel_grace":"client_abort_cancel_grace"),_.details={..._.details??{},outcome:"unknown_outcome",retryable:!1,escalation:"runner_terminated_after_cancel_grace"},l(_))},Ki),b.unref?.()}},C=()=>w(h());this.taskCancellers.set(u,C);let T=()=>C(),k=()=>{o?.removeEventListener("abort",T)};o&&o.addEventListener("abort",T,{once:!0});let x=setTimeout(()=>{f||(this.taskTimeoutTotal++,w(m()))},i);this.pool.registerTask(a,u,{abortController:p,diagnostics:this.createWorkerTaskDiagnostics(e,t,n,i),onResult:_=>{if(!f){try{this.onExecutionFinished?.({diagnostics:this.createWorkerTaskDiagnostics(e,t,n,i),logs:Array.isArray(_.diagnosticLogs?.logs)?_.diagnosticLogs.logs:Array.isArray(_.ctxChanges?.$share?.$logs)?_.ctxChanges.$share.$logs:[],logsTruncated:_.diagnosticLogs?.truncated===!0||_.ctxChanges?.$share?.$logsTruncated===!0,statusCode:_.error?.statusCode??_.ctxChanges?.$statusCode,error:_.success||y?void 0:_.error})}catch(v){this.logger.error("Executor diagnostic callback failed",v)}if(_.taskCancelled===!0&&this.pool.unregisterTask(a,u),f=!0,clearTimeout(x),b&&clearTimeout(b),this.taskCancellers.delete(u),k(),this.cleanupResponseStream(u),this.recordTaskDuration(Date.now()-c),y){p.abort(),this.taskErrorTotal++,l(g??h());return}if(_.success){this.taskDoneTotal++;let v={value:_.value,valueAbsent:_.valueAbsent===!0,ctxChanges:_.ctxChanges};_.shortCircuit&&(v.shortCircuit=!0),d(v)}else{this.taskErrorTotal++;let v=new Error(_.error?.message||"Handler execution failed");v.statusCode=_.error?.statusCode,v.code=_.error?.code,v.errorCode=_.error?.code,v.details=_.error?.details,_.error?.stack&&(v.stack=_.error.stack),_.ctxChanges&&(v.ctxChanges=_.ctxChanges),this.cleanupResponseStream(u,v),l(v)}}},onRelease:()=>{this.pool.unregisterTask(a,u)},onIoCall:_=>{if(f)return;if(_.type==="executionError"){try{this.onExecutionFinished?.({diagnostics:{...this.createWorkerTaskDiagnostics(e,t,n,i),scriptBlocks:[{type:_.sourceKind,scriptId:_.scriptId==null?void 0:String(_.scriptId)}]},logs:[],logsTruncated:!1,error:_.error})}catch(j){this.logger.error("Executor diagnostic callback failed",j)}return}let v=p.signal;_.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(_,n),a.worker,_.callId,v):_.type==="transactionCall"?this.handleIoCall(()=>this.execTransactionCall(_,n,a.worker),a.worker,_.callId,v):_.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(_,n),a.worker,_.callId,v):_.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(_,n),a.worker,_.callId,v):_.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(_,n),a.worker,_.callId,v):_.type==="storageCall"?this.handleIoCall(()=>this.execStorageCall(_,n,a.worker),a.worker,_.callId,v):_.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall(_,n),a.worker,_.callId,v):_.type==="resCall"&&this.handleIoCall(()=>this.execResCall(_,n),a.worker,_.callId,v)}}),a.worker.postMessage({type:e,id:u,...t}),o?.aborted&&C()})})()}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?On.run(i,e):e());if(i?.aborted){this.postAbortedCallError(t,n);return}try{t.postMessage({type:"callResult",callId:n,result:An(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,errorPath:o.errorPath,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){let f=new Error(String(l.error));try{let p=JSON.parse(String(l.error));p?.__userThrow&&(f.message=String(p.message??f.message),f.statusCode=p.statusCode,f.code=p.code??(Number.isInteger(p.statusCode)?`HTTP_${p.statusCode}`:void 0),f.errorCode=f.code,f.errorPath=p.errorPath,f.details=p.details,f.messages=p.messages)}catch{}a(f);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 Tr.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,scriptId:e.scriptId,type:e.type}}createWorkerTaskDiagnostics(e,t,n,i){let o=n?.$api?.request?.correlationId,s=Array.isArray(t.codeBlocks)?t.codeBlocks.map(a=>({type:a?.type==="preHook"||a?.type==="postHook"||a?.type==="handler"?a.type:"run",...a?.scriptId!==void 0&&a?.scriptId!==null?{scriptId:String(a.scriptId)}:{}})):[{type:typeof t.sourceKind=="string"?t.sourceKind:"run",...t.scriptId==null?{}:{scriptId:String(t.scriptId)}}];return{...typeof o=="string"&&o?{correlationId:o}:{},timeoutMs:i,isolateMemoryLimitMb:Number(t.memoryLimitMb||0),isolatePoolSize:Number(t.isolatePoolSize||0),tasksPerIsolate:Number(t.tasksPerIsolate||0),scriptBlocks:s}}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),c;try{let d={code:e,scriptId:i.scriptId,sourceKind:i.sourceKind,sourceCode:i.sourceCode??e,pkgSources:a,snapshot:u,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize,tasksPerIsolate:this.isolationTuning.tasksPerIsolate};c=await this.spawnAndExecute("execute",d,t,o)}catch(d){let l=d;if(l.code==="ERR_EXECUTION_ABORTED"||l.isAbort)throw l;if(l.isTimeout||l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new he(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 Fe.createException(l.errorPath,f,l.message||"Unknown error",e,l.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),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),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,tasksPerIsolate:this.isolationTuning.tasksPerIsolate};c=await this.spawnAndExecute("executeBatch",l,t,o,i.signal)}catch(d){let l=d;if(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 he(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 Fe.createException(l.errorPath,f,l.message||"Unknown error","(batch execution)",l.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),{value:c.valueAbsent?void 0:c.value,shortCircuit:c.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}recordQueueWait(e){this.queueWaitDurationsMs.push(e),this.queueWaitDurationsMs.length>512&&this.queueWaitDurationsMs.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((s,a)=>s+a,0)/t.length,i=this.queueWaitDurationsMs,o=i.length===0?0:i.reduce((s,a)=>s+a,0)/i.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),avgQueueWaitMs:o,p95QueueWaitMs:this.percentile(i,95),p99QueueWaitMs:this.percentile(i,99),maxHeapRatio:Math.max(0,...e.workers.map(s=>s.lastHeapRatio||0)),runnerRssBytes:e.workers.reduce((s,a)=>s+(a.lastRssBytes||0),0)}}};var ve=xe(require("typescript")),xt={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 qi(r){return te.getLegacyField(r)}function Ui(r){return te.isScriptTable(r)}function Qi(r){return te.normalizeLanguage(r)}var Xt=class{getLegacyField(e){return xt[e]}isScriptTable(e){return e in xt}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(xt).find(n=>xt[n]in e);if(t){let n=e[xt[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,`
2
- `));return t.outputText.trimEnd()}assertExecutableJavaScript(e){e&&new Function(`return (async () => {
3
- "use strict";
4
- ${e}
5
- });`)}},te=new Xt;function Ji(r,e){return te.compileSource(r,e)}function zi(r){return te.isExecutableJavaScript(r)}function Vi(r,e){return te.normalizeRecord(r,e)}function Hi(r,e,t){return te.normalizePatch(r,e,t)}function Gi(r){return te.getExecutableScript(r)}function Yi(r){return te.resolveExecutableScript(r)}function Xi(r){return te.normalizeFlowStepScriptConfig(r)}var Rn=require("node:fs"),ci=require("node:path");var jn=require("mongodb");Ke();function Ie(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function V(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!Ie(r)&&(r.foreignKeyColumn||r.propertyName)||null}function q(r){return r.foreignKeyColumn||r.mappedBy||r.propertyName||null}function X(r){if(!r||typeof r!="object")return r;if(r instanceof jn.ObjectId)return r.toString();if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return r.map(t=>X(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 jn.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)?X(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||Ft(a,u,c);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:d,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:c};let l=vt(a,u,c);return{junctionName:d,selfColumn:l.targetColumn,otherColumn:l.sourceColumn,owningTable:a,inverseTable:c}}let n=r,i=t,o=e.junctionTableName||Ft(n,e.propertyName,i);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:o,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:i};let s=vt(n,e.propertyName,i);return{junctionName:o,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:i}}async function It(r,e,t,n){if(!r)return{scalarFields:[],relations:[]};let i=r.tables?.get(e);if(!i)return{scalarFields:[],relations:[]};let o=new Map;for(let c of t)if(c==="*")o.has("")||o.set("",[]),o.get("").push(c);else if(c.includes(".")){let d=c.split("."),l=d[0],f=d.slice(1).join(".");o.has(l)||o.set(l,[]),o.get(l).push(f)}else i.relations?.some(l=>l.propertyName===c)?o.has(c)||o.set(c,["_id"]):(o.has("")||o.set("",[]),o.get("").push(c));if(n&&typeof n=="object")for(let[c,d]of Object.entries(n)){if(o.has(c))continue;let l=d&&typeof d=="object"&&d.fields!=null?Array.isArray(d.fields)?d.fields:String(d.fields).split(",").map(f=>f.trim()).filter(Boolean):["*"];o.set(c,l)}let s=[],a=[],u=o.get("")||[];for(let c of u)if(c==="*"){if(i.columns)for(let d of i.columns)s.includes(d.name)||s.push(d.name);if(i.relations)for(let d of i.relations)o.has(d.propertyName)||o.set(d.propertyName,["_id"])}else i.columns?.some(l=>l.name===c)&&!s.includes(c)&&s.push(c);for(let[c,d]of o.entries()){if(c==="")continue;let l=i.relations?.find(h=>h.propertyName===c);if(!l)continue;let f="",p="",y=!1;l.type==="many-to-one"||l.type==="one-to-one"?Ie(l)?(f="_id",p=q(l)||l.propertyName,y=!0):(f=V(l)||l.propertyName,p="_id",y=!1):l.type==="one-to-many"?(f="_id",p=q(l)||l.propertyName,y=!0):l.type==="many-to-many"&&(l.mappedBy?(f="_id",p=l.mappedBy,y=!0):(f=l.propertyName,p="_id",y=!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:y,nestedFields:d})}return{scalarFields:s,relations:a}}var en=xe(require("fs")),Ln=xe(require("path"));var Zi=new RegExp("\\p{Mark}","gu");function Mr(r){return r==null?"":String(r).normalize("NFKD").replace(Zi,"").toLowerCase()}function Bn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=Mr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function Zt(){return`function() {
6
- var M = ${Bn()};
1
+ "use strict";var ws=Object.create;var Or=Object.defineProperty;var _s=Object.getOwnPropertyDescriptor;var Ss=Object.getOwnPropertyNames;var $s=Object.getPrototypeOf,Ts=Object.prototype.hasOwnProperty;var z=(n,e)=>()=>(n&&(e=n(n=0)),e);var Un=(n,e)=>{for(var t in e)Or(n,t,{get:e[t],enumerable:!0})},Oo=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ss(e))!Ts.call(n,o)&&o!==t&&Or(n,o,{get:()=>e[o],enumerable:!(r=_s(e,o))||r.enumerable});return n};var He=(n,e,t)=>(t=n!=null?ws($s(n)):{},Oo(e||!n||!n.__esModule?Or(t,"default",{value:n,enumerable:!0}):t,n)),ks=n=>Oo(Or({},"__esModule",{value:!0}),n);function la(n){return!!(typeof n._bsontype=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer||n instanceof RegExp)}function Xe(n,e=new WeakMap){if(!n||typeof n!="object")return n;let t=e.get(n);if(t)return t;if(Array.isArray(n)){let i=[];e.set(n,i);for(let s of n)i.push(Xe(s,e));return i}if(n instanceof Map){let i=new Map;e.set(n,i);for(let[s,a]of n)i.set(Xe(s,e),Xe(a,e));return i}if(n instanceof Set){let i=new Set;e.set(n,i);for(let s of n)i.add(Xe(s,e));return i}if(n instanceof Date)return new Date(n.getTime());if(la(n))return n;let r=Object.getPrototypeOf(n);if(r!==Object.prototype&&r!==null)throw new TypeError("Join metadata must contain plain cloneable values");let o=Object.create(r);e.set(n,o);for(let[i,s]of Object.entries(n))Object.defineProperty(o,i,{value:Xe(s,e),enumerable:!0,configurable:!0,writable:!0});return o}function to(n){return{...n,relationMeta:Xe(n.relationMeta),purposes:[...n.purposes]}}var Te,sr=z(()=>{"use strict";Te=class{constructor(){this.map=new Map}size(){return this.map.size}has(e){return this.map.has(e)}get(e){let t=this.map.get(e);return t?to(t):void 0}getAll(){return Array.from(this.map.values(),to)}createCheckpoint(){return this.getAll()}restoreCheckpoint(e){let t=new Map;for(let r of e){let o=to(r);if(t.has(o.id))throw new Error(`Duplicate join registry checkpoint ID "${o.id}"`);t.set(o.id,o)}for(let r of t.values()){if(r.parentJoinId===null){if(r.id!==r.propertyName)throw new Error(`Invalid root join ID "${r.id}"`);continue}let o=t.get(r.parentJoinId);if(!o||o.targetTable!==r.parentTable||r.id!==`${r.parentJoinId}.${r.propertyName}`)throw new Error(`Invalid parent join for "${r.id}"`)}this.map.clear();for(let[r,o]of t)this.map.set(r,o)}registerWithParent(e,t,r,o="left",i=null,s="data"){let a=i?`${i}.${t}`:t,c=r?.tables?.get(e);if(!c)return null;let u=c.relations?.find(d=>d.propertyName===t);if(!u)return null;let l=u.targetTableName||u.targetTable;if(!l)return null;if(i!==null){let d=this.map.get(i);if(!d||d.targetTable!==e)throw new Error(`Invalid parent join for "${a}"`)}if(this.map.has(a)){let d=this.map.get(a);if(d.parentTable!==e||d.propertyName!==t||d.targetTable!==l||d.relationType!==u.type||d.parentJoinId!==i)throw new Error(`Join registry collision for "${a}"`);return o==="inner"&&(d.joinType="inner"),d.purposes.includes(s)||d.purposes.push(s),a}let f={id:a,propertyName:t,parentTable:e,targetTable:l,relationType:u.type,parentJoinId:i,joinType:o,relationMeta:Xe(u),purposes:[s]};return this.map.set(a,f),a}}});function ei(n){let e=new Set(n),t={get size(){return e.size},has(r){return e.has(r)},forEach(r,o){for(let i of e)r.call(o,i,i,t)},entries(){return e.entries()},keys(){return e.keys()},values(){return e.values()},[Symbol.iterator](){return e[Symbol.iterator]()}};return Object.freeze(t)}function Qr(n){return Object.prototype.hasOwnProperty.call(Zo,n)?Zo[n]:null}var de,ro,ar,Zo,wt=z(()=>{"use strict";de=ei(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),ro=ei(["_and","_or","_not"]),ar=Object.freeze([...ro,...de]),Zo=Object.assign(Object.create(null),{_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 w,re=z(()=>{"use strict";w=class extends Error{constructor(t="Bad Request",r){let o=Array.isArray(t),i;if(o)i=t.join("; ")||"Bad Request";else if(typeof t=="string")i=t;else try{i=JSON.stringify(t)||"Bad Request"}catch{i="Bad Request"}super(i);this.statusCode=400;this.errorCode="BAD_REQUEST";this.name="BadRequestException",this.details=r,o&&(this.messages=[...t])}}});function ti(){let n=process.env.DB_URI||"";return n.startsWith("mongodb://")||n.startsWith("mongodb+srv://")}var ri=z(()=>{"use strict"});function Ze(n,e,t){throw new w({message:`Unsupported filter operator "${n}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${ar.join(", ")}.`,error:"UnsupportedFilterOperator",operator:n,field:e,supportedOperators:ar})}function no(n,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let r=ti();for(let o of Object.keys(e))if(o.startsWith("_")&&!de.has(o)){if(r&&o==="_id")continue;Ze(o,n,t)}}function ni(n){if(n>ne)throw new w(`Filter nesting depth exceeds maximum of ${ne}`)}function oi(n,e,t,r){if(!n||typeof n!="object")return;if(ni(e),t.has(n))throw new w("Filter contains a circular reference");let o=r.get(n);if(!(o!==void 0&&o>=e)){t.add(n);try{for(let i of Object.values(n))oi(i,e+1,t,r);r.set(n,Math.max(o??-1,e))}finally{t.delete(n)}}}function ua(n,e,t){let r=t.get(n);if(r)return r;let o=e?.tables?.get(n);if(!o)throw new w(`Filter validation requires metadata for table '${n}'`);let i=o?.columns??[],s={columnNames:new Set(i.map(a=>a.name)),relationMap:new Map((o?.relations??[]).map(a=>[a.propertyName,a])),acceptsIdAlias:i.some(a=>a.name==="_id"&&a.isPrimary)&&!i.some(a=>a.name==="id")};return t.set(n,s),s}function lr(n,e,t,r,o,i,s,a=!1){if(!n||typeof n!="object")return;if(ni(r),o.has(n))throw new w("Filter contains a circular reference");let c=`${e}:${a?"nested":"root"}`,u=s.get(n),l=u?.get(c);if(!(l!==void 0&&l>=r)){o.add(n);try{if(Array.isArray(n)){for(let y of n)lr(y,e,t,r+1,o,i,s,a);let h=u??new Map;h.set(c,Math.max(h.get(c)??-1,r)),s.set(n,h);return}let{columnNames:f,relationMap:d,acceptsIdAlias:p}=ua(e,t,i);for(let[h,y]of Object.entries(n)){if(a&&de.has(h)){if(h==="_is_null"||h==="_is_not_null"){if(typeof y!="boolean")throw new w(`Relation filter operator '${h}' requires a boolean value`)}else if((h==="_in"||h==="_not_in"||h==="_nin"||h==="_between")&&!Array.isArray(y))throw new w(`Relation filter operator '${h}' requires an array value`);continue}if(ca.has(h)){if(h==="_and"||h==="_or"){if(!Array.isArray(y)||y.some(S=>!S||typeof S!="object"||Array.isArray(S)))throw new w(`Filter '${h}' value must be an array of filter objects`)}else if(!y||typeof y!="object"||Array.isArray(y))throw new w("Filter '_not' value must be a filter object");lr(y,e,t,r+1,o,i,s,a);continue}let m=d.get(h);if(m){if(y===null)continue;if(typeof y!="object"||Array.isArray(y)){lr({id:{_eq:y}},m.targetTableName||m.targetTable,t,r+1,o,i,s,!0);continue}let S=m.targetTableName||m.targetTable;if(typeof S!="string"||!S||!t?.tables?.has(S))throw new w(`Filter relation '${h}' on '${e}' has no resolvable target table metadata`);lr(y,S,t,r+1,o,i,s,!0);continue}let b=p&&(h==="id"||h==="_id"),_=f.has("_id")&&h==="_id";if(h.startsWith("_")&&!f.has(h)&&!b&&Ze(h,h,e),!f.has(h)&&!b&&!_)throw new w(`Unknown filter field '${h}' on table '${e}'`);y&&typeof y=="object"&&no(h,y,e)}let g=u??new Map;g.set(c,Math.max(g.get(c)??-1,r)),s.set(n,g)}finally{o.delete(n)}}}function Le(n,e,t){if(!n||typeof n!="object"||Array.isArray(n))throw new w("Filter must be an object");oi(n,0,new Set,new WeakMap),lr(n,e,t,0,new Set,new Map,new WeakMap)}var ne,ca,qe=z(()=>{"use strict";re();ri();wt();ne=64,ca=new Set(["_and","_or","_not"])});function Me(n,e,t,r){if(n===void 0)return{node:null,hasRelationFilters:!1};if(!n||typeof n!="object"||Array.isArray(n))throw new w("Filter must be an object");let o={tableName:e,metadata:t,registry:r,parentJoinId:null,currentJoinId:null,currentTable:e,depth:0,ancestors:new Set},i=r.createCheckpoint();try{return Jr(n,o)}catch(s){throw r.restoreCheckpoint(i),s}}function Jr(n,e){if(!n||typeof n!="object"||Array.isArray(n))throw new w("Logical filter operand must be a filter object");if(e.depth>ne)throw new w(`Filter nesting depth exceeds maximum of ${ne}`);if(e.ancestors.has(n))throw new w("Filter contains a circular reference");e.ancestors.add(n);let t=e.registry.createCheckpoint();try{let r=[],o=!1,i=!1;for(let[s,a]of Object.entries(n)){let c=fa(s,a,e),u=c.node;if(u?.kind==="false")return e.registry.restoreCheckpoint(t),{node:u,hasRelationFilters:!1};if(u?.kind==="true"){i=!0;continue}c.hasRelationFilters&&(o=!0),u&&r.push(u)}return r.length===0?{node:i?{kind:"true"}:null,hasRelationFilters:o}:r.length===1?{node:r[0],hasRelationFilters:o}:{node:{kind:"and",children:r},hasRelationFilters:o}}finally{e.ancestors.delete(n)}}function si(n){return{...n,depth:n.depth+1}}function fa(n,e,t){if(n==="_and")return ii("and",e,t);if(n==="_or")return ii("or",e,t);if(n==="_not"){if(!e||typeof e!="object"||Array.isArray(e))throw new w("Filter '_not' value must be a filter object");let u=t.registry.createCheckpoint(),l=Jr(e,si(t)),f=l.node??{kind:"true"};return f.kind==="true"||f.kind==="false"?(t.registry.restoreCheckpoint(u),{node:{kind:f.kind==="true"?"false":"true"},hasRelationFilters:!1}):{node:{kind:"not",child:f},hasRelationFilters:l.hasRelationFilters}}let r=t.metadata?.tables?.get(t.currentTable);if(!r)throw new w(`Filter parsing requires metadata for table '${t.currentTable}'`);let o=r.columns?.some(u=>u.name==="_id"&&u.isPrimary),i=r?.columns?.some(u=>u.name==="id"),a=n==="id"?o&&!i?"_id":"id":n,c=r?.relations?.find(u=>u.propertyName===a);if(c)return zr(a,e,c,t);if(r&&!r.columns?.find(l=>l.name===a))throw n.startsWith("_")&&n!=="_id"&&Ze(n,n,t.currentTable),new w(`Unknown field '${n}' on table '${t.currentTable}'`);return da(a,e,t)}function ii(n,e,t){if(!Array.isArray(e))throw new w(`Filter '${n}' value must be an array`);let r=t.registry.createCheckpoint(),o=[],i=!1;for(let a of e){if(!a||typeof a!="object"||Array.isArray(a))throw new w(`Filter '${n}' entries must be filter objects`);let c=t.registry.createCheckpoint(),u=Jr(a,si(t)),l=u.node??{kind:"true"};n==="and"&&l.kind==="true"||n==="or"&&l.kind==="false"?t.registry.restoreCheckpoint(c):u.hasRelationFilters&&(i=!0),o.push(l)}if(o.length===0)return{node:{kind:n==="and"?"true":"false"},hasRelationFilters:i};if(n==="or"&&o.some(a=>a.kind==="true"))return t.registry.restoreCheckpoint(r),{node:{kind:"true"},hasRelationFilters:!1};if(n==="and"&&o.some(a=>a.kind==="false"))return t.registry.restoreCheckpoint(r),{node:{kind:"false"},hasRelationFilters:!1};let s=o.filter(a=>n==="and"?a.kind!=="true":a.kind!=="false");return s.length===0?{node:{kind:n==="and"?"true":"false"},hasRelationFilters:i}:s.length===1?{node:s[0],hasRelationFilters:i}:{node:{kind:n,children:s},hasRelationFilters:i}}function zr(n,e,t,r){if(typeof e!="object"||e===null||Array.isArray(e))return e===null?zr(n,{id:{_is_null:!0}},t,r):Array.isArray(e)?zr(n,{id:{_in:e}},t,r):zr(n,{id:{_eq:e}},t,r);let o=Object.keys(e);if(o.length===0)return{node:null,hasRelationFilters:!1};let i=r.registry.createCheckpoint(),s=o.length===1&&(o[0]==="_is_null"||o[0]==="_is_not_null"||o[0]==="_eq"||o[0]==="_neq"||o[0]==="_in"||o[0]==="_not_in"||o[0]==="_nin"),a=r.registry.registerWithParent(r.currentTable,n,r.metadata,"left",r.currentJoinId,"filter");if(s&&(o[0]==="_is_null"||o[0]==="_is_not_null")&&typeof e[o[0]]!="boolean")throw new w(`Relation null-check operator '${o[0]}' requires a boolean value`);if(!a)throw new w(`Unable to register filter join for relation '${n}'`);if(s&&o[0]==="_is_null")return{node:{kind:"relation_exists",joinId:a,negate:e._is_null===!0},hasRelationFilters:!0};if(s&&o[0]==="_is_not_null")return{node:{kind:"relation_exists",joinId:a,negate:e._is_not_null!==!0},hasRelationFilters:!0};if(s&&(o[0]==="_eq"||o[0]==="_neq")&&e[o[0]]===null)return{node:{kind:"relation_exists",joinId:a,negate:o[0]==="_eq"},hasRelationFilters:!0};let c=t.targetTableName||t.targetTable;if(!c)throw new w(`Relation '${n}' has no target table metadata`);let u={...r,parentJoinId:r.currentJoinId,currentJoinId:a,currentTable:c,depth:r.depth+1},l=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte","_between"]),d=o.length>0&&o.every(g=>l.has(g))?{id:e}:e,p=Jr(d,u);return!p.node||p.node.kind==="true"||p.node.kind==="false"?(r.registry.restoreCheckpoint(i),{node:p.node,hasRelationFilters:!1}):{node:p.node,hasRelationFilters:!0}}function oo(n,e,t){if(!(!n||typeof n!="object")){if(e>ne)throw new w(`Filter nesting depth exceeds maximum of ${ne}`);if(t.has(n))throw new w("Filter contains a circular reference");t.add(n);try{for(let r of Object.values(n))oo(r,e+1,t)}finally{t.delete(n)}}}function da(n,e,t){let r={joinId:t.currentJoinId,fieldName:n,isUuid:ga(n,t)};if(e===null)return{node:{kind:"compare",field:r,op:"is_null",value:!0},hasRelationFilters:!1};if(typeof e!="object")return{node:{kind:"compare",field:r,op:"eq",value:e},hasRelationFilters:!1};for(let s of Object.keys(e))s.startsWith("_")&&!de.has(s)&&Ze(s,n,t.tableName);let o=Object.entries(e).filter(([s])=>de.has(s));if(o.length>0&&o.length!==Object.keys(e).length)throw new w(`Field '${n}' has mixed filter operators and object properties`);if(o.length===0)return oo(e,t.depth+1,new Set),{node:{kind:"compare",field:r,op:"eq",value:e},hasRelationFilters:!1};let i=[];for(let[s,a]of o){if(oo(a,t.depth+1,new Set),(s==="_in"||s==="_not_in"||s==="_nin")&&!Array.isArray(a))throw new w(`Filter operator '${s}' requires an array value`);if(s==="_between"&&(!Array.isArray(a)||a.length!==2))throw new w("Filter operator '_between' requires an array with exactly two values");let c=pa(r,s,a);c&&i.push(c)}return i.length===0?{node:null,hasRelationFilters:!1}:i.length===1?{node:i[0],hasRelationFilters:!1}:{node:{kind:"and",children:i},hasRelationFilters:!1}}function pa(n,e,t){if(e==="_is_null"||e==="_is_not_null"){if(typeof t!="boolean")throw new w(`Filter operator '${e}' requires a boolean value`);return{kind:"compare",field:n,op:"is_null",value:e==="_is_null"?t:!t}}let r=Qr(e);return r?{kind:"compare",field:n,op:r,value:t}:null}function ga(n,e){let t=e.metadata?.tables?.get(e.currentTable);if(!t)return!1;let r=n.includes(".")?n.split(".").pop():n,o=t.columns?.find(a=>a.name===r);if(!o)return!1;let s=(typeof o.type=="string"?o.type:typeof o.type?.name=="string"?o.type.name:"").toLowerCase();return s==="uuid"||s==="uuidv4"||s.includes("uuid")}var cr=z(()=>{"use strict";wt();qe();re()});function ur(n){return Buffer.byteLength(n,"utf8")<=ya}function Xr(n){return n.map(e=>`${Buffer.byteLength(e,"utf8")}:${e}`).join("|")}function fr(n){return co.createHash("md5").update(n).digest("hex").substring(0,8)}function di(n){let e=`${n}_pk`;return ur(e)?e:`j_${fr(n)}_pk`}function pi(n,e,t){let r=`${n}_${e}_foreign`;return ur(r)?r:`j_${fr(n)}_${t}_fk`}function dr(n,e,t){let r=[n,e,t],o=r.some(s=>s.includes(":"))?Xr(r):r.join(":");return`j_${co.createHash("sha1").update(o).digest("hex").slice(0,12)}`}function ie(n){let e=`${n}Id`;return ur(e)?e:`fk_${fr(Xr([n,"Id"]))}`}function pr(n,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function gi(n){return n.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function hi(n){return n.replace(/([A-Z])/g,"_$1").toLowerCase()}function mi(n,e,t){let r=`${n}_${e}_${t}_fk`;return ur(r)?r:`r_${fr(Xr([n,e,t]))}_${t}_fk`}function yi(n,e,t){let r=`${n}_${e}_${t}_idx`;return ur(r)?r:`r_${fr(Xr([n,e,t]))}_${t}_idx`}var co,ya,et=z(()=>{"use strict";co=He(require("crypto")),ya=63});var St,ae,hr,mr,$t=z(()=>{"use strict";St=16,ae=5e3,hr=4,mr=10});var Ea,nn,Ei=z(()=>{"use strict";re();$t();Ea=new Set(["many-to-one","one-to-one","one-to-many","many-to-many"]),nn=class{constructor(e,t){this.adapter=e;this.metadataGetter=t}normalizeDeepFields(e,t){if(e===void 0)return t;if(!Array.isArray(e)&&typeof e!="string")throw new w("Deep relation fields must be a string or string array");let r=Array.isArray(e)?e:e.split(",").map(o=>o.trim()).filter(Boolean);if(r.some(o=>typeof o!="string"))throw new w("Deep relation fields must be strings");return r.map(o=>o.trim()).filter(Boolean)}normalizeDeepSort(e){if(e!==void 0){if(Array.isArray(e)){if(e.some(t=>typeof t!="string"))throw new w("Deep relation sort entries must be strings");return e.map(t=>t.trim()).filter(Boolean)}if(typeof e!="string")throw new w("Deep relation sort must be a string or string array");return e}}normalizeDeepPagination(e,t){if(e===void 0)return;if(typeof e!="number"&&typeof e!="string")throw new w(`Deep relation ${t} must be an integer`);let r=String(e);if(!/^\d+$/.test(r))throw new w(`Deep relation ${t} must be an integer`);let o=Number(r),i=t==="limit"?0:1;if(!Number.isSafeInteger(o)||o<i)throw new w(`Deep relation ${t} must be a safe integer greater than or equal to ${i}`);return o}normalizeDescriptors(e){let t=new Set;for(let r of e){if(t.has(r.relationName))throw new w(`Duplicate deep relation '${r.relationName}'`);t.add(r.relationName)}return e.map(r=>{if(!Ea.has(r.type))throw new w(`Unsupported relation type '${r.type}' for '${r.relationName}'`);return this.withDefaultToManyLimit({...r,fields:this.normalizeDeepFields(r.fields,[]),userSort:this.normalizeDeepSort(r.userSort),userLimit:this.normalizeDeepPagination(r.userLimit,"limit"),userPage:this.normalizeDeepPagination(r.userPage,"page")})})}entryValue(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}enrichNestedDescs(e,t,r,o){if(t===void 0)return e;if(!t||typeof t!="object"||Array.isArray(t))throw new w("Nested deep options must be an object");if(Object.keys(t).length===0)return e;let i=e.map(a=>{if(!Object.prototype.hasOwnProperty.call(t,a.relationName))return a;let c=t[a.relationName];if(!c||typeof c!="object"||Array.isArray(c))throw new w(`Nested deep option for relation '${a.relationName}' must be an object`);let u=this.entryValue(c,"fields"),l=this.entryValue(c,"filter"),f=this.entryValue(c,"sort"),d=this.entryValue(c,"limit"),p=this.entryValue(c,"page"),g=this.entryValue(c,"deep");return{...a,fields:this.normalizeDeepFields(u,o?.has(a.relationName)&&a.fields.length>0?a.fields:["*"]),userFilter:l??a.userFilter,userSort:f!==void 0?this.normalizeDeepSort(f):a.userSort,userLimit:d!==void 0?this.normalizeDeepPagination(d,"limit"):a.userLimit,userPage:p!==void 0?this.normalizeDeepPagination(p,"page"):a.userPage,nestedDeep:g??a.nestedDeep}}),s=new Set(i.map(a=>a.relationName));for(let[a,c]of Object.entries(t)){if(s.has(a))continue;if(!c||typeof c!="object"||Array.isArray(c))throw new w(`Nested deep option for relation '${a}' must be an object`);let u=r?.relations?.find(m=>m.propertyName===a);if(!u)throw new w(`Unknown nested deep relation '${a}' on '${r?.name??"unknown"}'`);let l=this.entryValue(c,"fields"),f=this.entryValue(c,"filter"),d=this.entryValue(c,"sort"),p=this.entryValue(c,"limit"),g=this.entryValue(c,"page"),h=this.entryValue(c,"deep"),y=this.normalizeDeepFields(l,["*"]);i.push({relationName:a,type:u.type,targetTable:u.targetTableName||u.targetTable,fields:y,isInverse:u.isInverse,fkColumn:u.foreignKeyColumn,mappedBy:u.mappedBy,junctionTableName:u.junctionTableName,junctionSourceColumn:u.junctionSourceColumn,junctionTargetColumn:u.junctionTargetColumn,userFilter:f,userSort:this.normalizeDeepSort(d),userLimit:this.normalizeDeepPagination(p,"limit"),userPage:this.normalizeDeepPagination(g,"page"),nestedDeep:h})}return i}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:10}:e}projectedRelations(e){let t=new Set;for(let r of e)r==="*"||!r.includes(".")||t.add(r.split(".")[0]);return t}fieldsForNestedResolution(e,t){if(!t||Object.keys(t).length===0)return e;let r=new Set(e.filter(i=>i!=="*").map(i=>i.split(".")[0])),o=[...e];for(let i of Object.keys(t))r.has(i)||o.push(i);return o}getMetadata(e,t){let r=t.metadataByTable.get(e);if(r)return r;let o=this.metadataGetter(e);return t.metadataByTable.set(e,o),o}async prepareDescriptor(e,t,r,o){let i=await this.getMetadata(e.targetTable,o);if(!i)throw new Error(`Metadata not found for target table: ${e.targetTable}`);this.assertLocalSortFields(e,i);let{nestedDescs:s,fetchSpec:a}=this.adapter.resolveFields(this.fieldsForNestedResolution(e.fields,e.nestedDeep),i);if(r+1>=t)return{desc:e,targetMeta:i,fetchSpec:a,children:[]};let c=await Promise.all(this.normalizeDescriptors(this.enrichNestedDescs(s,e.nestedDeep,i,this.projectedRelations(e.fields))).map(u=>this.prepareDescriptor(u,t,r+1,o)));return{desc:e,targetMeta:i,fetchSpec:a,children:c}}assertLocalSortFields(e,t){if(!e.userSort)return;let r=Array.isArray(e.userSort)?e.userSort:String(e.userSort).split(",").map(o=>o.trim()).filter(Boolean);for(let o of r){let i=o.startsWith("-")?o.slice(1):o;if(i.includes("."))throw new w(`Sort field '${i}' is not supported on deep relation '${e.relationName}'. Sort only by local fields defined on '${e.targetTable}'.`);let s=t.columns?.some(c=>c.name===i),a=i==="id"&&t.columns?.some(c=>c.name==="_id");if(!s&&!a)throw new w(`Sort field '${i}' does not exist on '${e.targetTable}'. Sort only by fields defined on the table metadata.`)}}}});async function K(n,e,t=5e3){if(!Number.isInteger(t)||t<1)throw new Error("Batch fetch chunk size must be a positive integer");if(n.length===0)return[];if(n.length<=t)return e(n);let r=[];for(let f=0;f<n.length;f+=t)r.push(n.slice(f,f+t));let o=[],i=0,s=!1,a=!1,c;async function u(){for(;!s;){let f=i;if(f>=r.length)return;i+=1;try{o[f]=await e(r[f])}catch(d){a||(a=!0,c=d),s=!0}}}let l=Math.min(4,r.length);if(await Promise.all(Array.from({length:l},()=>u())),a)throw c;return o.flat()}function nt(n){let e=[],t=new Map;for(let r of n)if(r==="*"||!r.includes("."))e.push(r);else{let o=r.split("."),i=o[0],s=o.slice(1).join(".");t.has(i)||t.set(i,[]),t.get(i).push(s)}return{rootFields:e,subRelations:t}}var xi=z(()=>{"use strict";$t()});var We,Oe=z(()=>{"use strict";re();Ei();$t();xi();$t();We=class{constructor(e,t,r){this.adapter=e;this.trace=r;this.plan=new nn(e,t)}uniqueValues(e){let t=new Set,r=[];for(let o of e){if(o==null)continue;let i=this.adapter.keyOf(o);t.has(i)||(t.add(i),r.push(o))}return r}setRelation(e,t,r){let o=Object.getOwnPropertyDescriptor(e,t);if(o&&!o.configurable){Object.defineProperty(e,t,{value:r});return}Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}assertCommitCanApply(e,t,r){for(let o of t){let i=o.desc;for(let s of e){let a=Object.getOwnPropertyDescriptor(s,i.relationName);if(!a&&!Object.isExtensible(s))throw new Error(`Cannot add relation '${i.relationName}' to a non-extensible result`);if(a&&!a.configurable&&(!("writable"in a)||!a.writable))throw new Error(`Cannot replace non-writable relation '${i.relationName}'`);for(let c of i.injectedParentFields??[]){if(r.has(c))continue;let u=Object.getOwnPropertyDescriptor(s,c);if(u&&!u.configurable)throw new Error(`Cannot remove injected relation field '${c}'`)}}}}createStagingParent(e){let t=Object.create(Object.getPrototypeOf(e));for(let r of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,r);"value"in o?Object.defineProperty(t,r,{value:o.value,enumerable:o.enumerable,writable:!0,configurable:!0}):Object.defineProperty(t,r,{get:o.get,set:o.set,enumerable:o.enumerable,configurable:!0})}return t}async execute(e,t,r=3,o=0,i){if(!Number.isSafeInteger(r)||r<0)throw new w("Maximum query depth must be a non-negative safe integer");if(!Number.isSafeInteger(o)||o<0)throw new w("Current query depth must be a non-negative safe integer");if(t.length===0||o>=r)return;let s={metadataByTable:new Map},a;if(i&&(a=await this.plan.getMetadata(i,s)??void 0,!a))throw new Error(`Metadata not found for parent table: ${i}`);let c=await Promise.all(this.plan.normalizeDescriptors(t).map(u=>this.plan.prepareDescriptor(u,r,o,s)));await this.executePrepared(e,c,r,o,a,s)}async executePrepared(e,t,r,o,i,s){if(e.length===0)return;let a=new Array(t.length),c=new Array(t.length),u=0,l=!1,f,d=async()=>{for(;!l&&u<t.length;){let g=u;u+=1;let h=t[g],y=h.desc,m=e.map(b=>this.createStagingParent(b));try{y.type==="many-to-one"||y.type==="one-to-one"&&!y.isInverse?await this.fetchOwnerRelation(m,h,r,o,s):y.type==="one-to-many"||y.type==="one-to-one"&&y.isInverse?await this.fetchInverseRelation(m,h,r,o,i,s):y.type==="many-to-many"&&await this.fetchM2MRelation(m,h,r,o,i,s),a[g]=m.map(b=>b[y.relationName]),c[g]={status:"fulfilled",value:void 0}}catch(b){c[g]={status:"rejected",reason:b},l||(f=b),l=!0}}};if(await Promise.all(Array.from({length:Math.min(4,t.length)},()=>d())),l)throw f;let p=new Set(t.map(({desc:g})=>g.relationName));this.assertCommitCanApply(e,t,p);for(let g=0;g<t.length;g+=1){let h=t[g].desc,y=a[g];for(let m=0;m<e.length;m+=1){this.setRelation(e[m],h.relationName,y[m]);for(let b of h.injectedParentFields??[])p.has(b)||delete e[m][b]}}}async fetchOwnerRelation(e,t,r,o,i){let{desc:s,targetMeta:a,fetchSpec:c,children:u}=t,l=this.adapter.resolveOwnerFkKey(s),f=new Set,d=[];for(let _ of e){let S=_[l];if(S==null)continue;let E=this.adapter.keyOf(S);f.has(E)||(f.add(E),d.push(S))}if(d.length===0){for(let _ of e)this.setRelation(_,s.relationName,null),l!==s.relationName&&delete _[l],s.fkColumn&&s.fkColumn!==s.relationName&&delete _[s.fkColumn];return}let p=this.adapter.getTargetPkField(a),g=performance.now(),h=await this.adapter.fetchOwner(s.targetTable,d,c,s),y=Array.isArray(h)?h:h.docs,m=Array.isArray(h)?void 0:h.stats;this.trace?.dur(`batch_fetch_L${o}_${s.relationName}`,g,{relationType:s.type,targetTable:s.targetTable,strategy:m?.strategy??"batch-in",roundtrips:m?.roundtrips??(Math.ceil(d.length/5e3)||1),concurrencyWaves:m?.concurrencyWaves,ioConcurrency:m?.ioConcurrency,rowsTransferred:m?.rowsTransferred??y.length,rowsReturned:y.length,rowsDiscarded:0,userFilter:!!s.userFilter,userSort:!!s.userSort});let b=new Map;for(let _ of y)b.set(this.adapter.keyOf(_[p]),_);u.length>0&&await this.executePrepared(y,u,r,o+1,a,i);for(let _ of e){let S=_[l];this.setRelation(_,s.relationName,S!=null&&b.get(this.adapter.keyOf(S))||null),l!==s.relationName&&delete _[l],s.fkColumn&&s.fkColumn!==s.relationName&&delete _[s.fkColumn]}}async fetchInverseRelation(e,t,r,o,i,s){let{desc:a,targetMeta:c,fetchSpec:u,children:l}=t,f=this.adapter.resolveParentPk(i),d=this.uniqueValues(e.map(M=>M[f]));if(d.length===0){for(let M of e)this.setRelation(M,a.relationName,a.type==="one-to-one"?null:[]);return}let p=this.adapter.resolveInverseFkField(a),g=performance.now(),{docs:h,groupKeyField:y,stats:m}=await this.adapter.fetchInverse(a.targetTable,p,d,u,a),b=new Map,_=a.fields.includes("*")||a.fields.some(M=>M===p||M.startsWith(`${p}.`));for(let M of h){let O=M[y],j=this.adapter.keyOf(O);b.has(j)||b.set(j,[]),b.get(j).push(M)}let S=a.userLimit!==void 0&&a.userLimit>0,E=S?"per-parent-c16":"batch-in",C=S?d.length:Math.ceil(d.length/5e3)||1,x=S?Math.ceil(d.length/16):void 0,v=Array.from(b.values()).reduce((M,O)=>M+O.length,0);if(this.trace?.dur(`batch_fetch_L${o}_${a.relationName}`,g,{relationType:a.type,targetTable:a.targetTable,strategy:m?.strategy??E,roundtrips:m?.roundtrips??C,concurrencyWaves:m?.concurrencyWaves??x,ioConcurrency:m?.ioConcurrency,rowsTransferred:m?.rowsTransferred??h.length,rowsReturned:v,rowsDiscarded:Math.max(0,(m?.rowsTransferred??h.length)-v),userLimit:a.userLimit,userFilter:!!a.userFilter,userSort:!!a.userSort}),l.length>0&&await this.executePrepared(h,l,r,o+1,c,s),this.adapter.postProcessInverseChild)for(let M of h)this.adapter.postProcessInverseChild(M,p,_);let R=a.type==="one-to-one";for(let M of e){let O=M[f];if(O==null){this.setRelation(M,a.relationName,R?null:[]);continue}let j=b.get(this.adapter.keyOf(O))||[];this.setRelation(M,a.relationName,R?j[0]||null:j)}}async fetchM2MRelation(e,t,r,o,i,s){let{desc:a,targetMeta:c,fetchSpec:u,children:l}=t,f=this.adapter.resolveParentPk(i),d=this.uniqueValues(e.map(x=>x[f]));if(d.length===0){for(let x of e)this.setRelation(x,a.relationName,[]);return}let p=e.filter(x=>x[f]!=null),g=performance.now(),{grouped:h,docs:y,stats:m}=await this.adapter.fetchM2M(p,a,i,c,u),b=a.userLimit!==void 0&&a.userLimit>0,_=b?"m2m-per-parent-c16":"m2m-batch",S=b?d.length:Math.ceil(d.length/5e3)||1,E=b?Math.ceil(d.length/16):void 0,C=Array.from(h.values()).reduce((x,v)=>x+v.length,0);if(this.trace?.dur(`batch_fetch_L${o}_${a.relationName}`,g,{relationType:a.type,targetTable:a.targetTable,strategy:m?.strategy??_,roundtrips:m?.roundtrips??S,concurrencyWaves:m?.concurrencyWaves??E,ioConcurrency:m?.ioConcurrency,rowsTransferred:m?.rowsTransferred??y.length,rowsReturned:C,rowsDiscarded:m?.rowsDiscarded??Math.max(0,(m?.rowsTransferred??y.length)-C),userLimit:a.userLimit,userFilter:!!a.userFilter,userSort:!!a.userSort}),l.length>0){let x=Array.from(new Set(Array.from(h.values()).flat()));x.length>0&&await this.executePrepared(x,l,r,o+1,c,s)}for(let x of e){let v=x[f];if(v==null){this.setRelation(x,a.relationName,[]);continue}let R=this.adapter.keyOf(v);this.setRelation(x,a.relationName,h.get(R)||[])}}}});var Ri,Ke,on=z(()=>{"use strict";Ri=2,Ke=class{constructor(e=2){this.concurrency=e;this.active=0;this.waiters=[];this.waiterHead=0;this.failed=!1;if(!Number.isInteger(e)||e<1)throw new Error("Batch execution concurrency must be a positive integer")}async run(e){await this.acquire();try{if(this.failed)throw this.failure;return await e()}catch(t){throw this.cancel(t),t}finally{this.release()}}async acquire(){if(this.failed)throw this.failure;if(this.active<this.concurrency){this.active+=1;return}if(!await new Promise(t=>this.waiters.push(t)))throw this.failure;if(this.failed)throw this.active-=1,this.failure}release(){if(this.active<1)throw new Error("Batch execution permit underflow");if(this.failed){this.active-=1;return}let e=this.waiters[this.waiterHead];if(e){this.waiters[this.waiterHead]=void 0,this.waiterHead+=1,this.waiterHead>1024&&this.waiterHead*2>this.waiters.length&&(this.waiters.splice(0,this.waiterHead),this.waiterHead=0),e(!0);return}this.active-=1}cancel(e){if(!this.failed){this.failed=!0,this.failure=e;for(let t=this.waiterHead;t<this.waiters.length;t+=1)this.waiters[t]?.(!1);this.waiters.length=0,this.waiterHead=0}}}});function I(n,e){if(e==="mongodb")return n;let t=["postgres","pg","sqlite"].includes(e)?'"':"`";return t+n.split(t).join(t+t)+t}function Je(n,e){let t=[],r=0;for(;r<n.length;){let o=n[r];if(o==='"'||o==="`"){r++;let i="",s=!1;for(;r<n.length;){let a=n[r++];if(a!==o){i+=a;continue}if(n[r]===o){i+=o,r++;continue}s=!0;break}if(!s||r<n.length&&n[r]!==".")throw new Error("Invalid quoted SQL identifier");t.push(I(i,e))}else{let i=n.indexOf(".",r),s=n.slice(r,i===-1?void 0:i);if(!s)throw new Error("Invalid qualified SQL identifier");t.push(s==="*"?s:I(s,e)),r=i===-1?n.length:i}if(r<n.length&&(r++,r===n.length))throw new Error("Invalid qualified SQL identifier")}if(t.length===0)throw new Error("Invalid qualified SQL identifier");return t.join(".")}var Se=z(()=>{"use strict"});function ee(n){return n.columns.find(e=>e.isPrimary)||null}var ft=z(()=>{"use strict"});function ue(n,e,t){e&&Pt(n,e,t,"and")}function Pt(n,e,t,r){switch(e.kind){case"true":r==="or"?n.orWhereRaw("1 = 1"):n.whereRaw("1 = 1");return;case"false":r==="or"?n.orWhereRaw("1 = 0"):n.whereRaw("1 = 0");return;case"and":{if(e.children.length===0){Pt(n,{kind:"true"},t,r);return}let o=function(){for(let i of e.children)this.where(function(){Pt(this,i,t,"and")})};r==="or"?n.orWhere(o):n.where(o);return}case"or":{if(e.children.length===0){Pt(n,{kind:"false"},t,r);return}let o=function(){for(let i of e.children)this.orWhere(function(){Pt(this,i,t,"and")})};r==="or"?n.orWhere(o):n.where(o);return}case"not":{let o=function(){this.whereNot(function(){Pt(this,e.child,t,"and")})};r==="or"?n.orWhere(o):n.where(o);return}case"compare":ll(n,e,t,r);return;case"relation_exists":throw new Error(`SQL relation_exists node requires a materialized join: ${e.joinId}`)}}function ll(n,e,t,r){if(e.field.joinId!==null)throw new Error(`SQL comparison requires a materialized join target: ${e.field.joinId}`);let o=ul(e.field,t),i=Je(o,t.dbType),s=!!e.field.isUuid,a=t.dbType==="postgres",c=r==="or"?"orWhere":"where",u=r==="or"?"orWhereRaw":"whereRaw",l=r==="or"?"orWhereIn":"whereIn",f=r==="or"?"orWhereNotIn":"whereNotIn",d=r==="or"?"orWhereBetween":"whereBetween",p=r==="or"?"orWhereNull":"whereNull",g=r==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":e.value===null?n[p](o):s&&a&&typeof e.value=="string"?n[u](`${i} = ?::uuid`,[e.value]):n[c](o,"=",e.value);return;case"neq":e.value===null?n[g](o):s&&a&&typeof e.value=="string"?n[u](`${i} != ?::uuid`,[e.value]):n[c](o,"!=",e.value);return;case"gt":s&&a&&typeof e.value=="string"?n[u](`${i} > ?::uuid`,[e.value]):n[c](o,">",e.value);return;case"gte":s&&a&&typeof e.value=="string"?n[u](`${i} >= ?::uuid`,[e.value]):n[c](o,">=",e.value);return;case"lt":s&&a&&typeof e.value=="string"?n[u](`${i} < ?::uuid`,[e.value]):n[c](o,"<",e.value);return;case"lte":s&&a&&typeof e.value=="string"?n[u](`${i} <= ?::uuid`,[e.value]):n[c](o,"<=",e.value);return;case"in":{let h=as(e.value);h.length===0?n[u]("1 = 0"):s&&a&&h.every(y=>typeof y=="string")?n[u](`${i} = ANY(?::uuid[])`,[h]):n[l](o,h);return}case"not_in":{let h=as(e.value);h.length===0?n[u]("1 = 1"):s&&a&&h.every(y=>typeof y=="string")?n[u](`${i} != ALL(?::uuid[])`,[h]):n[f](o,h);return}case"contains":Co(n,i,e.value,"contains",t,r);return;case"starts_with":Co(n,i,e.value,"starts_with",t,r);return;case"ends_with":Co(n,i,e.value,"ends_with",t,r);return;case"between":if(!Array.isArray(e.value)||e.value.length!==2)throw new Error("Invalid between filter value");n[d](o,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?n[p](o):n[g](o);return}}function cl(n){return String(n).replace(/=/g,"==").replace(/%/g,"=%").replace(/_/g,"=_")}function Co(n,e,t,r,o,i){let s=i==="or"?"orWhereRaw":"whereRaw",a=cl(t);if(o.dbType==="postgres"){let u=r==="contains"?`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?)) || '%' ESCAPE '='`:r==="starts_with"?`lower(unaccent(${e})) ILIKE lower(unaccent(?)) || '%' ESCAPE '='`:`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?)) ESCAPE '='`;n[s](u,[a]);return}if(o.dbType==="sqlite"){let u=r==="contains"?`lower(${e}) LIKE '%' || lower(?) || '%' ESCAPE '='`:r==="starts_with"?`lower(${e}) LIKE lower(?) || '%' ESCAPE '='`:`lower(${e}) LIKE '%' || lower(?) ESCAPE '='`;n[s](u,[a]);return}let c=r==="contains"?`lower(${e}) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(?) COLLATE utf8mb4_general_ci, '%') ESCAPE '='`:r==="starts_with"?`lower(${e}) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(?) COLLATE utf8mb4_general_ci, '%') ESCAPE '='`:`lower(${e}) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(?) COLLATE utf8mb4_general_ci) ESCAPE '='`;n[s](c,[a])}function ul(n,e){let t=n.fieldName.split(".");if(t.some(r=>!r))throw new Error("Invalid SQL filter field");if(t.length===1)return`${e.rootTable}.${t[0]}`;if(t.length!==2||t[0]!==e.rootTable)throw new Error("Invalid SQL filter field");return n.fieldName}function as(n){return Array.isArray(n)?n:typeof n=="string"&&n.includes(",")?n.split(",").map(e=>e.trim()):[n]}var Rr=z(()=>{"use strict";Se()});var us={};Un(us,{expandFieldsToJoinsAndSelect:()=>Ro});function cs(n,e,t){if(n===void 0)return;let r=typeof n=="number",o=typeof n=="string"&&/^\d+$/.test(n.trim());if(!r&&!o)throw new Error(t);let i=Number(n);if(!Number.isSafeInteger(i)||i<e)throw new Error(t);return i}function fl(n){return cs(n,0,"SQL relation limit must be a non-negative safe integer")}function dl(n){return cs(n,1,"SQL relation page must be a positive safe integer")}function jt(n,e){return n&&Object.prototype.hasOwnProperty.call(n,e)?n[e]:void 0}function ls(n){if(typeof n!="string"&&!Array.isArray(n))throw new Error("SQL relation fields must be a string or string array");let e=typeof n=="string"?n.split(","):n;if(e.some(t=>typeof t!="string"))throw new Error("SQL relation fields must be strings");return e.map(t=>t.trim()).filter(Boolean)}async function Ro(n,e,t,r,o,i){if(o!==void 0&&(!Number.isSafeInteger(o)||o<0))throw new Error("SQL maximum query depth must be a non-negative safe integer");let s=[],a=[],c=await t(n);if(!c)throw new Error(`SQL field expansion requires metadata for '${n}'`);let u=new Map,l=new Set;for(let h of e){let y=h.split(".").map(b=>b.trim());if(y.some(b=>b.length===0))throw new Error(`Malformed SQL field path '${h}'`);let m=y.join(".");if(m==="*"||y.length===1)u.has("")||u.set("",[]),u.get("").push(m);else{let b=y[0],_=y.slice(1).join(".");u.has(b)||u.set(b,[]),u.get(b).push(_)}}if(i&&typeof i=="object")for(let[h,y]of Object.entries(i)){if(u.has(h))continue;let m=y&&typeof y=="object"&&y.fields!=null?ls(y.fields):["*"];u.set(h,m)}let f=u.get("")||[],d=new Set,p=new Set,g=h=>`${I(n,r)}.${I(h,r)}`;for(let h of f){if(h==="*"){let b=new Set;for(let S of c.relations||[])if(S.type==="many-to-one"||S.type==="one-to-one"&&!S.isInverse){let E=S.foreignKeyColumn||ie(S.propertyName);E&&b.add(E)}let _=new Set;for(let S of c.columns)b.has(S.name)||(s.push(g(S.name)),d.add(S.name),_.add(S.name));for(let S of c.relations||[])!u.has(S.propertyName)&&!_.has(S.propertyName)&&(u.set(S.propertyName,[]),l.add(S.propertyName));continue}if(h.includes(".")){s.push(g(h));continue}if(c.columns?.find(b=>b.name===h)){s.push(g(h)),d.add(h);continue}if(c.relations?.find(b=>b.propertyName===h)){u.has(h)||(u.set(h,[]),l.add(h));continue}}for(let[h,y]of u){if(h==="")continue;let m=c.relations?.find(v=>v.propertyName===h);if(!m)continue;if(o===0)throw new Error("SQL relation exceeds maximum query depth");if(m.type==="one-to-one"&&typeof m.isInverse!="boolean")throw new Error(`SQL one-to-one relation '${h}' requires ownership metadata`);let b=m.type==="many-to-one"||m.type==="one-to-one"&&m.isInverse===!1,_=[];if(d.has(h))throw new Error(`SQL relation '${h}' on '${n}' conflicts with a selected root column`);if(p.add(h),b){let v=m.foreignKeyColumn||ie(m.propertyName);if(!c.columns.some(j=>j.name===v))throw new Error(`SQL relation '${h}' foreign key '${v}' is missing from '${n}' metadata`);let R=I(n,r),M=I(v,r),O=I(h,r);s.push(`${R}.${M} as ${O}`),_.push(h)}else{let v=c.columns.filter(R=>R.isPrimary===!0);if(v.length===0)throw new Error(`SQL relation '${h}' on '${n}' requires parent primary key metadata`);for(let R of v){if(p.has(R.name))throw new Error(`SQL parent key '${R.name}' on '${n}' conflicts with a relation output`);d.has(R.name)||(s.push(g(R.name)),d.add(R.name),_.push(R.name))}}let S=m.targetTableName||m.targetTable,E=i&&Object.prototype.hasOwnProperty.call(i,h)?i[h]:void 0,C=jt(E,"fields"),x=C!=null?ls(C):y;if(C==null&&l.has(h)){let v=await t(S);if(!v)throw new Error(`SQL relation '${h}' requires target metadata for '${S}'`);if(x=v.columns.filter(R=>R.isPrimary===!0).map(R=>R.name),x.length===0)throw new Error(`SQL relation '${h}' requires target primary key metadata`)}a.push({relationName:h,type:m.type,targetTable:S,fields:x,isInverse:m.isInverse,fkColumn:b?m.foreignKeyColumn||ie(m.propertyName):m.foreignKeyColumn,injectedParentFields:_.length>0?_:void 0,mappedBy:m.mappedBy,junctionTableName:m.junctionTableName,junctionSourceColumn:m.junctionSourceColumn,junctionTargetColumn:m.junctionTargetColumn,userFilter:jt(E,"filter"),userSort:jt(E,"sort"),userLimit:fl(jt(E,"limit")),userPage:dl(jt(E,"page")),nestedDeep:jt(E,"deep")})}return{select:s,batchFetchDescriptors:a}}var Fo=z(()=>{"use strict";et();Se()});var Mr,Dt,Bn,fs=z(()=>{"use strict";Oe();cr();sr();et();ft();Se();Mr="__enfyra_row_number__",Dt="__enfyra_partitioned__",Bn=class{constructor(e,t,r){this.knex=e;this.dbType=t;this.metadata=r}getTableMetadata(e){let t=this.metadata?.tables??this.metadata;if(t)return typeof t.get=="function"?t.get(e):t[e]}sortAlias(e){return`__sort_${e.map(t=>`${t.length}_${t}`).join("_")}`}buildPartitionRowNumber(e,t,r){let o=[...t];o.some(s=>s.column===r)||o.push({column:r,order:"asc"});let i=o.map(s=>`?? ${s.order.toUpperCase()}`).join(", ");return this.knex.raw(`ROW_NUMBER() OVER (PARTITION BY ?? ORDER BY ${i}) as ??`,[e,...o.map(s=>s.column),Mr])}buildPartitionSlice(e,t,r,o){return this.knex.from(e.as(Dt)).select(`${Dt}.*`).where(`${Dt}.${Mr}`,">",r).andWhere(`${Dt}.${Mr}`,"<=",r+o).orderBy(`${Dt}.${t}`,"asc").orderBy(`${Dt}.${Mr}`,"asc")}removePartitionFields(e){for(let t of e)delete t[Mr]}buildFilterTree(e,t){if(!e||!this.metadata)return null;let r=new Te,o=this.metadata?.tables?this.metadata:{tables:this.metadata instanceof Map?this.metadata:new Map(Object.entries(this.metadata))},{node:i}=Me(e,t,o,r);return i}parseSortTokens(e,t,r){return e?(Array.isArray(e)?e:e.split(",").map(i=>i.trim()).filter(Boolean)).map(i=>{let s=i.startsWith("-"),c=(s?i.slice(1):i).split(".");if(c.length===1)return{column:r?`${r}.${c[0]}`:`${t}.${c[0]}`,order:s?"desc":"asc"};let u=c[c.length-1];return{column:`${this.sortAlias(c.slice(0,-1))}.${u}`,order:s?"desc":"asc"}}):[]}applySortJoins(e,t,r,o){if(!t||!this.metadata)return;let i=Array.isArray(t)?t:t.split(",").map(a=>a.trim()).filter(Boolean),s=new Set;for(let a of i){let u=(a.startsWith("-")?a.slice(1):a).split(".");if(u.length<=1)continue;let l=r,f=o||r;for(let d=0;d<u.length-1;d++){let p=u[d],g=this.getTableMetadata(l);if(!g)break;let h=g.relations?.find(b=>b.propertyName===p);if(!h)break;if(h.isInverse||h.type==="one-to-many"||h.type==="many-to-many")throw new Error(`Dotted sort through inverse or to-many relation '${p}' is not supported`);let y=h.targetTableName||h.targetTable,m=this.sortAlias(u.slice(0,d+1));if(!s.has(m)){s.add(m);let b=h.foreignKeyColumn||ie(h.propertyName),_=this.getTableMetadata(y),S=_&&ee(_)?.name||"id";e.leftJoin(`${y} as ${m}`,`${m}.${S}`,`${f}.${b}`)}l=y,f=m}}}toKnexSelect(e,t){let r=e.indexOf(" as ");if(r!==-1){let o=e.substring(0,r),i=e.substring(r+4),s=I(i,this.dbType),a=t?`${I(t,this.dbType)}.${I(o,this.dbType)}`:I(o,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${I(t,this.dbType)}.${I(e,this.dbType)} as ${I(e,this.dbType)}`):e}resolveFields(e,t){let{rootFields:r,subRelations:o}=nt(e),i=[];if(r.includes("*")){let u=new Set;for(let l of t.relations||[])if(l.type==="many-to-one"||l.type==="one-to-one"&&!l.isInverse){let f=l.foreignKeyColumn||ie(l.propertyName);f&&u.add(f)}for(let l of t.columns)u.has(l.name)||i.push(l.name);for(let l of t.relations||[])o.has(l.propertyName)||o.set(l.propertyName,["id"])}else for(let u of r){let l=t.columns.find(f=>f.name===u);l?i.push(l.name):t.relations?.find(d=>d.propertyName===u)&&!o.has(u)&&o.set(u,["id"])}let s=ee(t)?.name||"id";i.includes(s)||i.push(s),o.forEach((u,l)=>{let f=t.relations?.find(d=>d.propertyName===l);if(f&&(f.type==="many-to-one"||f.type==="one-to-one"&&!f.isInverse)){let d=f.foreignKeyColumn||ie(f.propertyName);d&&i.push(`${d} as ${l}`)}});let a=[];return o.forEach((u,l)=>{let f=t.relations?.find(p=>p.propertyName===l);if(!f)return;let d=f.targetTableName||f.targetTable;d&&a.push({relationName:l,type:f.type,targetTable:d,fields:u,isInverse:f.isInverse,fkColumn:f.foreignKeyColumn,mappedBy:f.mappedBy,junctionTableName:f.junctionTableName,junctionSourceColumn:f.junctionSourceColumn,junctionTargetColumn:f.junctionTargetColumn})}),{isPkOnly:i.length===1&&i[0]===s&&a.length===0,nestedDescs:a,fetchSpec:{selectCols:i,pkCol:s}}}}});var Ar,Dn,gl,Lt,vo=z(()=>{"use strict";on();Oe();et();ft();fs();Rr();Ar="__sourceId__",Dn="__targetId__",gl=5e4,Lt=class{constructor(e,t="postgres",r,o=new Ke){this.knex=e;this.dbType=t;this.metadata=r;this.executionBudget=o;this.pkField="id";this.batchQuery=new Bn(e,t,r)}resolveFields(e,t){return this.batchQuery.resolveFields(e,t)}chunkCount(e,t=5e3){return Math.ceil(e.length/t)||1}m2mTargetChunkSize(){return this.dbType==="postgres"?gl:5e3}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)}keyOf(e){if(e===null)return"null:";if(e===void 0)return"undefined:";if(typeof e=="number")return Number.isNaN(e)?"number:nan":Object.is(e,-0)?"number:-0":`number:${e}`;if(typeof e=="bigint")return`bigint:${e}`;if(typeof e=="boolean")return`boolean:${e}`;if(typeof e=="string")return`string:${e.length}:${e}`;if(e instanceof Date)return`date:${e.toISOString()}`;throw new Error("SQL relation identity must be a scalar value")}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return ee(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;if(!t&&e.mappedBy&&(t=ie(e.mappedBy)),!t)throw new Error(`Missing inverse foreign key metadata for relation: ${e.relationName}`);return t}resolveParentPk(e){return e&&ee(e)?.name||"id"}async fetchOwner(e,t,r,o){let i=o?.userFilter?this.batchQuery.buildFilterTree(o.userFilter,e):null,s=o?.userSort?this.batchQuery.parseSortTokens(o.userSort,e):[],a=r.selectCols.map(l=>this.batchQuery.toKnexSelect(l,e)),c=this.uniqueValues(t),u=await K(c,l=>{let f=this.knex(e).select(a).whereIn(`${e}.${r.pkCol}`,l);if(i&&ue(f,i,{dbType:this.dbType,rootTable:e}),s.length>0){this.batchQuery.applySortJoins(f,o.userSort,e);for(let d of s)f.orderBy(d.column,d.order)}return this.runQuery(f)});return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(c),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,r,o,i){let s=t,a=o.selectCols.find(h=>h.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():o.selectCols.includes(t)||o.selectCols.push(t);let c=i?.userFilter?this.batchQuery.buildFilterTree(i.userFilter,e):null,u=i?.userSort?this.batchQuery.parseSortTokens(i.userSort,e):[],l=i?.userLimit,f=i?.userPage,d=this.uniqueValues(r);if(l!==void 0&&l>0){let h=f?(f-1)*l:0,y=o.selectCols.map(b=>this.batchQuery.toKnexSelect(b,e)),m=await K(d,async b=>{let _=this.knex(e).select(y).select(this.batchQuery.buildPartitionRowNumber(`${e}.${t}`,u,`${e}.${o.pkCol}`)).whereIn(`${e}.${t}`,b);c&&ue(_,c,{dbType:this.dbType,rootTable:e}),this.batchQuery.applySortJoins(_,i.userSort,e);let S=await this.runQuery(this.batchQuery.buildPartitionSlice(_,s,h,l));return this.batchQuery.removePartitionFields(S),S});return{docs:m,groupKeyField:s,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(d),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.length}}}let p=o.selectCols.map(h=>this.batchQuery.toKnexSelect(h,e)),g=await K(d,h=>{let y=this.knex(e).select(p).whereIn(`${e}.${t}`,h);if(c&&ue(y,c,{dbType:this.dbType,rootTable:e}),this.batchQuery.applySortJoins(y,i?.userSort,e),u.length>0)for(let m of u)y.orderBy(m.column,m.order);else y.orderBy(`${e}.${o.pkCol}`,"asc");return this.runQuery(y)});return{docs:g,groupKeyField:s,stats:{strategy:"batch-in",roundtrips:this.chunkCount(d),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length}}}postProcessInverseChild(e,t,r){r||delete e[t]}async selectM2MEdges(e,t,r,o,i,s,a,c){let u=`t.${s}`,l=!!a||c.some(h=>h.column!==u),f=l?c:c.map(h=>({...h,column:`${r}.${i}`})),d=t.userLimit,p=t.userPage;if(d!==void 0&&d>0){let h=p?(p-1)*d:0;return(await K(e,async m=>{let b=this.knex(r).select({[Ar]:`${r}.${o}`,[Dn]:`${r}.${i}`}).whereIn(`${r}.${o}`,m);l&&(b=b.join(`${t.targetTable} as t`,`${r}.${i}`,`t.${s}`),a&&ue(b,a,{dbType:this.dbType,rootTable:"t"}),this.batchQuery.applySortJoins(b,t.userSort,t.targetTable,"t")),b.select(this.batchQuery.buildPartitionRowNumber(`${r}.${o}`,f,l?u:`${r}.${i}`));let _=await this.runQuery(this.batchQuery.buildPartitionSlice(b,Ar,h,d));return this.batchQuery.removePartitionFields(_),_})).map(m=>({sourceId:m[Ar],targetId:m[Dn]}))}return(await K(e,h=>{let y=this.knex(r).select({[Ar]:`${r}.${o}`,[Dn]:`${r}.${i}`}).whereIn(`${r}.${o}`,h);if(l&&(y=y.join(`${t.targetTable} as t`,`${r}.${i}`,`t.${s}`),a&&ue(y,a,{dbType:this.dbType,rootTable:"t"}),this.batchQuery.applySortJoins(y,t.userSort,t.targetTable,"t")),y.orderBy(`${r}.${o}`,"asc"),f.length>0){for(let m of f)y.orderBy(m.column,m.order);l&&!f.some(m=>m.column===u)&&y.orderBy(u,"asc")}else y.orderBy(`${r}.${i}`,"asc");return this.runQuery(y)})).map(h=>({sourceId:h[Ar],targetId:h[Dn]}))}async loadM2MTargets(e,t,r){if(t.length===0)return[];let o=r.selectCols.map(i=>this.batchQuery.toKnexSelect(i));return K(t,i=>this.runQuery(this.knex(e).select(o).whereIn(r.pkCol,i)),this.m2mTargetChunkSize())}async fetchM2M(e,t,r,o,i){let s=this.resolveParentPk(r),a=this.uniqueValues(e.map(x=>x[s]));if(a.length===0)return{grouped:new Map,docs:[]};let c=t.junctionTableName,u=t.junctionSourceColumn,l=t.junctionTargetColumn;if(!c||!u||!l)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let f=t.userFilter?this.batchQuery.buildFilterTree(t.userFilter,t.targetTable):null,d=t.userSort?this.batchQuery.parseSortTokens(t.userSort,t.targetTable,"t"):[],p=await this.selectM2MEdges(a,t,c,u,l,i.pkCol,f,d),g=new Map;for(let x of a)g.set(this.keyOf(x),[]);let h=i.selectCols.length===1&&i.selectCols[0]===i.pkCol,y=t.userLimit!==void 0&&t.userLimit>0,m=this.chunkCount(a),b=`t.${i.pkCol}`,_=!f&&d.every(x=>x.column===b);if(h){let x=new Map;for(let v of p){let R=this.keyOf(v.targetId);x.has(R)||x.set(R,{[i.pkCol]:v.targetId}),g.get(this.keyOf(v.sourceId))?.push(x.get(R))}return{grouped:g,docs:[],stats:{strategy:_?y?"m2m-junction-partitioned-top-k":"m2m-junction-batch":y?"m2m-filtered-edge-top-k":"m2m-filtered-edge-batch",roundtrips:m,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let S=this.uniqueValues(p.map(x=>x.targetId)),E=await this.loadM2MTargets(t.targetTable,S,i),C=new Map(E.map(x=>[this.keyOf(x[i.pkCol]),x]));for(let x of p){let v=C.get(this.keyOf(x.targetId));v&&g.get(this.keyOf(x.sourceId))?.push(v)}return{grouped:g,docs:E,stats:{strategy:y?"m2m-partitioned-edge-loader":"m2m-edge-loader",roundtrips:m+(S.length>0?this.chunkCount(S,this.m2mTargetChunkSize()):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+E.length,rowsDiscarded:0}}}}});var ds={};Un(ds,{executeBatchFetches:()=>Mo});async function Mo(n,e,t,r,o=3,i=0,s,a="postgres",c,u){let l=new Lt(n,a,c);await new We(l,r,u).execute(e,t,o,i,s)}var Ao=z(()=>{"use strict";Oe();vo()});var ml={};Un(ml,{ALL_SUPPORTED_OPERATORS:()=>ar,AuthenticationException:()=>zt,AuthorizationException:()=>Jt,BadRequestException:()=>w,BatchExecutionBudget:()=>Ke,BatchFetchEngine:()=>We,BusinessLogicException:()=>Wt,CHUNKED_FETCH_CONCURRENCY:()=>hr,ConfigurationException:()=>Zt,DEEP_TO_MANY_DEFAULT_LIMIT:()=>mr,DEFAULT_BATCH_FETCH_IO_CONCURRENCY:()=>Ri,DEFAULT_TIMEOUT_MS:()=>Nr,DOTTED_PATH_MAX_HOPS:()=>me,DatabaseException:()=>ht,DuplicateResourceException:()=>Qt,ErrorHandler:()=>Ve,ExecutorEngineService:()=>gt,ExternalServiceException:()=>Gt,FIELD_OPERATORS:()=>de,FileNotFoundException:()=>tr,FileSizeExceededException:()=>rr,FileUploadException:()=>er,HttpException:()=>W,InvalidTokenException:()=>Vt,IsolatedExecutorService:()=>bt,JoinRegistry:()=>Te,LOGICAL_OPERATORS:()=>ro,MongoBatchAdapter:()=>Rt,MongoQueryExecutor:()=>lt,PER_PARENT_CONCURRENCY:()=>St,QueryBuilderService:()=>qt,QueryPlanner:()=>pe,ResourceNotFoundException:()=>Ut,SchemaException:()=>Xt,ScriptContractService:()=>Ur,ScriptExecutionException:()=>De,ScriptTimeoutException:()=>Be,ServiceUnavailableException:()=>Yt,SqlBatchAdapter:()=>Lt,SqlQueryExecutor:()=>pt,TokenExpiredException:()=>Ht,ValidationException:()=>Kt,WHERE_IN_CHUNK_SIZE:()=>ae,WorkerPool:()=>Ge,applyOperatorToMatch:()=>$r,applyRelationFilters:()=>Nt,applyWhereToKnex:()=>Bt,assertFieldOperatorValueIsClean:()=>no,buildMongoCharFoldMapJson:()=>ho,buildMongoFoldTextSearchJs:()=>fn,buildMongoSortSpec:()=>po,buildMongoSortSpecFromPlan:()=>gr,buildRelationSortSubquery:()=>Nn,buildRelationSubquery:()=>is,buildSqlWherePartsFromFieldAst:()=>vr,buildWhereClause:()=>ut,camelToSnake:()=>hi,checkIfFilterContainsIsNull:()=>Qi,chunkedFetch:()=>K,compileScriptSource:()=>ta,computeEngineTuning:()=>Gn,createEnfyraKernel:()=>hl,dslOpToCompareOp:()=>Qr,encodeMainThreadToIsolate:()=>ir,escapeSqlValue:()=>we,executeAggregationPipeline:()=>Fn,executeBatchFetches:()=>Mo,executeCountQueries:()=>Mn,executeMongoBatchFetches:()=>bn,expandFieldsMongo:()=>tt,expandFieldsToJoinsAndSelect:()=>Ro,expandFieldsToSelect:()=>On,getEffectiveCpuCount:()=>Vn,getEffectiveMemoryBytes:()=>or,getEngineTuning:()=>Br,getExecutableScript:()=>ia,getForeignKeyColumnName:()=>ie,getIoAbortSignal:()=>Xn,getJunctionColumnNames:()=>pr,getJunctionTableName:()=>dr,getMetadataGetter:()=>Fr,getMongoInverseRelationForeignField:()=>V,getMongoMetadataGetter:()=>ko,getMongoStoredRelationField:()=>X,getPrimaryKeyColumn:()=>ee,getScriptLegacyField:()=>Xs,getShortFkConstraintName:()=>pi,getShortFkName:()=>mi,getShortIndexName:()=>yi,getShortPkName:()=>di,hasLogicalOperators:()=>ct,isExecutableJavaScript:()=>ra,isMongoInverseRelation:()=>ge,isScriptTable:()=>Zs,normalizeAggregateQuery:()=>At,normalizeFlowStepScriptConfig:()=>aa,normalizeMongoDocument:()=>se,normalizeMongoResults:()=>Rn,normalizeScriptLanguage:()=>ea,normalizeScriptPatch:()=>oa,normalizeScriptRecord:()=>na,parseBatchFields:()=>nt,parseFields:()=>Vr,parseFilter:()=>Me,parseSortInput:()=>ps,perParentRun:()=>ys,quoteIdentifier:()=>I,quoteQualifiedIdentifier:()=>Je,renderFilterToKnex:()=>ue,resolveExecutableScript:()=>sa,resolveMongoJunctionInfo:()=>he,rewriteFilterDenyingFields:()=>hs,rewriteSortDroppingDenied:()=>ms,runWithIoAbortSignal:()=>Zn,scriptContractService:()=>$e,separateFilters:()=>Ae,snakeToCamel:()=>gi,throwUnsupportedFieldOperator:()=>Ze,validateDeepOptions:()=>rt,validateFilterShape:()=>Le,whereToMongoFilter:()=>It});module.exports=ks(ml);var Nr=3e4,gt=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,r={}){let o=e.routeData.__codeBlocks||[];return o.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(o,e.routeData.context,t??Nr,r)}async run(e,t,r=Nr,o={}){return this.isolatedExecutorService.run(e,t,r,o)}};var Xo=He(require("path"));var Be=class extends Error{constructor(t=0,r,o){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={...o,timeoutMs:t,scriptId:r,outcome:o?.outcome??"timed_out",retryable:!1}}},De=class extends Error{constructor(t,r,o){super(`Script execution failed: ${t}`);this.statusCode=400;this.errorCode="SCRIPT_EXECUTION_ERROR";this.name="ScriptExecutionException",this.details={...o,scriptId:r}}},J=class extends Error{constructor(t,r,o,i){if(!Number.isInteger(r)||r<400||r>599)throw new TypeError("Kernel exception statusCode must be an integer from 400 to 599");super(t);this.statusCode=r;this.errorCode=o;this.name=this.constructor.name,this.details=i}},W=class extends J{constructor(e,t,r){super(e,t,`HTTP_${t}`,r)}},Wt=class extends J{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},Kt=class extends J{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},Ut=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})}},Qt=class extends J{constructor(e,t,r){super(`${e} with ${t} '${r}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:r})}},zt=class extends J{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},Jt=class extends J{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},Ht=class extends J{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},Vt=class extends J{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},ht=class extends J{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},Gt=class extends J{constructor(e,t,r){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:r})}},Yt=class extends J{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},Xt=class extends J{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},Zt=class extends J{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},er=class extends J{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},tr=class extends J{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},rr=class extends J{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var Pr=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!==void 0&&console.error(this.format(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;try{typeof e=="string"?t=e:e instanceof Error?t=e.stack??e.message:t=JSON.stringify(e,(o,i)=>typeof i=="bigint"?i.toString():i)??String(e)}catch{try{t=String(e)}catch{t="[Unserializable value]"}}return this.context?`[${this.context}] ${t}`:t}};var Qn=new Set(["__proto__","prototype","constructor","caller","callee","arguments"]);function oe(n,e,t=!1){if(Qn.has(e))throw new Error(`Host capability property is forbidden: ${e}`);if((typeof n!="object"||n===null)&&typeof n!="function")return;let r=n,o=new Set;for(;r&&r!==Object.prototype&&r!==Function.prototype;){if(o.size>=64)throw new Error("Host capability prototype traversal limit exceeded");if(o.has(r))throw new Error("Cyclic host capability prototype");if(o.add(r),Object.prototype.hasOwnProperty.call(r,e))return n[e];r=Object.getPrototypeOf(r)}if(t&&!Object.prototype.hasOwnProperty.call(Object.prototype,e)&&!Object.prototype.hasOwnProperty.call(Function.prototype,e)&&e in n)return n[e]}var No=new Set(["$helpers","$cache","$transaction","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$streams","$debug"]);function Jn(n){let e={$body:n.$body,$query:n.$query,$params:n.$params,$user:n.$user,$share:n.$share,$data:n.$data,$api:{request:n.$api?.request},$uploadedFile:n.$uploadedFile,$req:zn(n.$req)};for(let r of Object.keys(n)){if(!r.startsWith("$")||r in e||No.has(r))continue;let o=zn(n[r]);o!==void 0&&(e[r]=o)}let t=n.$flow;if(t!=null)try{e.$flow=zn(t)??{}}catch{e.$flow={}}return e}function zn(n){if(typeof n!="function")try{return JSON.parse(JSON.stringify(n,(e,t)=>{if(typeof t=="bigint")return String(t);if(typeof t!="function")return t}))}catch{return}}function nr(n,e){if(e){for(let t of["$body","$query","$params","$data","$error","$statusCode","$share"])Object.prototype.hasOwnProperty.call(e,t)&&(n[t]=e[t]);if(e.$api&&typeof e.$api=="object"&&n.$api&&typeof n.$api=="object"&&(Object.prototype.hasOwnProperty.call(e.$api,"error")&&(n.$api.error=e.$api.error),Object.prototype.hasOwnProperty.call(e.$api,"response")&&(n.$api.response=e.$api.response)),e.$flow!==void 0&&e.$flow!==null&&typeof e.$flow=="object"&&n.$flow!==null&&n.$flow!==void 0&&typeof n.$flow=="object")for(let[t,r]of Object.entries(e.$flow))Qn.has(t)||Object.defineProperty(n.$flow,t,{value:r,enumerable:!0,configurable:!0,writable:!0});for(let[t,r]of Object.entries(e))t.startsWith("$")&&(t==="$body"||t==="$query"||t==="$params"||t==="$data"||t==="$error"||t==="$statusCode"||t==="$share"||t==="$api"||t==="$flow"||No.has(t)||t==="$env"||(n[t]=r));delete n.$pkgs}}var yt=He(require("os"));var jo=He(require("fs")),jr=require("path");function mt(n){try{return jo.readFileSync(n,"utf8").trim()}catch{return""}}function Po(n){return n.replace(/\\([0-7]{3})/g,(e,t)=>String.fromCharCode(parseInt(t,8)))}function Bo(n,e){let t=new Set([e?"/sys/fs/cgroup":`/sys/fs/cgroup/${n}`]),r=mt("/proc/self/cgroup").split(`
2
+ `);for(let o of mt("/proc/self/mountinfo").split(`
3
+ `)){let[i,s]=o.split(" - ");if(!s)continue;let a=s.split(" ");if(a[0]!==(e?"cgroup2":"cgroup")||!e&&!a[2]?.split(",").includes(n))continue;let c=i.split(" "),u=Po(c[3]??""),l=Po(c[4]??"");if(!(!u.startsWith("/")||!l.startsWith("/")))for(let f of r){let d=/^\d+:([^:]*):(\/.*)$/.exec(f);if(!d||(e?d[1]!=="":!d[1].split(",").includes(n)))continue;let p=jr.posix.normalize(d[2]);if(u!=="/"&&p!==u&&!p.startsWith(`${u}/`))continue;let g=u==="/"?p.slice(1):p.slice(u.length+1),h=jr.posix.join(l,g);for(;(h===l||h.startsWith(`${l}/`))&&(t.add(h),h!==l);)h=jr.posix.dirname(h)}}return t}function Do(n){let e=n;for(let t of[!0,!1])for(let r of Bo("memory",t)){let o=Number(mt(`${r}/${t?"memory.max":"memory.limit_in_bytes"}`));Number.isFinite(o)&&o>0&&(e=Math.min(e,o))}return e}function Lo(n){let e=n;for(let t of[!0,!1])for(let r of Bo("cpu",t)){let[o,i]=t?mt(`${r}/cpu.max`).split(/\s+/).map(Number):[Number(mt(`${r}/cpu.cfs_quota_us`)),Number(mt(`${r}/cpu.cfs_period_us`))];o>0&&i>0&&Number.isFinite(o)&&Number.isFinite(i)&&(e=Math.min(e,Math.max(1,Math.ceil(o/i))))}return e}function or(){return Do(yt.totalmem())}function Vn(){return Lo(yt.availableParallelism?.()||yt.cpus()?.length||1)}var Es=.25,Hn=128,xs=2,Cs=4,Rs=6,Fs=8,Is=2048,vs=40,Ms=128,As=32;function Os(n){let e=Math.trunc(Number(n));if(!(!Number.isFinite(e)||e<1))return Math.min(Hn,e)}function Ns(n){let e=Math.trunc(Number(n));return!Number.isFinite(e)||e<1?Rs:Math.min(Fs,e)}function qo(n){return 2**Math.ceil(Math.log2(Math.max(1,n)))}function Gn(n){let e=Math.max(1,Math.trunc(n.logicalCpuCount)||1),t=Math.max(1,n.totalMemoryBytes/(1024*1024)),r=Math.min(Ms,Math.max(vs,Math.round(t/As))),o=t*Es,i=Math.max(1,Math.floor(o/r)),s=Math.max(1,Math.min(e,2,i)),a=Math.max(1,Math.floor(o/(s*r))),c=Math.min(Hn,qo(e*xs)),u=Math.min(Hn,qo(e*Cs)),l=Math.max(c,Math.min(u,a)),f=Os(n.maxLanesPerRunner)??l,d=t<Is?1:f,p=Math.max(1,Math.min(d,a)),g=Ns(n.tasksPerIsolate),h=p*g;return{maxConcurrentWorkers:s,isolateMemoryLimitMb:r,tasksPerWorkerCap:h,isolatePoolSize:p,tasksPerIsolate:g}}function Br(){return Gn({logicalCpuCount:Vn(),totalMemoryBytes:or()})}var Ve=class{static createException(e,t,r,o,i){if(e?.includes("$throw"))switch(e){case"$throw.http":return new W(r||"Error",t||500,i);case"$throw.businessLogic":return new Wt(r||"Bad request",i);case"$throw.validation":return new Kt(r||"Validation failed",i);case"$throw.notFound":return new Ut(i?.resource||r||"Resource",i?.identifier);case"$throw.duplicate":return new Qt(i?.resource||r||"Resource",i?.field||"field",i?.value??"value");case"$throw.unauthorized":return new zt(r||"Unauthorized");case"$throw.forbidden":return new Jt(r||"Forbidden");case"$throw.tokenExpired":return new Ht;case"$throw.invalidToken":return new Vt;case"$throw.database":return new ht(r||"Database error",i);case"$throw.dbQuery":return new ht(r||"Query error",i);case"$throw.externalService":return new Gt(r||"Service",r||"Error",i);case"$throw.serviceUnavailable":return new Yt(r||"Service");case"$throw.rateLimit":return new W(r||"Rate limit exceeded",429,i);case"$throw.scriptError":return new De(r||"Script error",o,i);case"$throw.scriptTimeout":return new Be(i?.timeout||5e3,o);case"$throw.schema":return new Xt(r||"Schema error",i);case"$throw.config":return new Zt(r||"Configuration error",i);case"$throw.fileUpload":return new er(r||"File upload error",i);case"$throw.fileNotFound":return new tr(r||"File not found");case"$throw.fileSizeExceeded":return new rr(i?.maxSize??"unknown",i?.actualSize??"unknown");case"$throw.400":return new W(r||"Bad request",400,i);case"$throw.401":return new W(r||"Authentication required",401,i);case"$throw.403":return new W(r||"Insufficient permissions",403,i);case"$throw.404":return new W(r||"Not found",404,i);case"$throw.409":return new W(r||"Conflict",409,i);case"$throw.422":return new W(r||"Validation failed",422,i);case"$throw.429":return new W(r||"Rate limit exceeded",429,i);case"$throw.500":return new W(r||"Internal server error",500,i);case"$throw.503":return new W(r||"Service unavailable",503,i);default:return new De(r||"Unknown error",o,i)}if(t)switch(t){case 400:return new W(r||"Bad request",400,i);case 401:return new W(r||"Authentication required",401,i);case 403:return new W(r||"Insufficient permissions",403,i);case 404:return new W(r||"Not found",404,i);case 409:return new W(r||"Conflict",409,i);case 422:return new W(r||"Validation failed",422,i);case 429:return new W(r||"Rate limit exceeded",429,i);case 500:return new W(r||"Internal server error",500,i);case 503:return new W(r||"Service unavailable",503,i);default:return new De(r||"Unknown error",o,i)}return new De(r||"Unknown error",o,i)}};function Wo(n){return Math.min(2147483647,n+Math.ceil(n*.15))}function Yn(n,e,t){Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0})}function Ie(n,e,t){if(!Object.prototype.hasOwnProperty.call(n,e))return!1;let r=new Set(t);return Object.keys(n).every(o=>r.has(o))}var Ko=Object.freeze({Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,...typeof globalThis.Float16Array>"u"?{}:{Float16Array:globalThis.Float16Array},...typeof BigInt64Array>"u"?{}:{BigInt64Array},...typeof BigUint64Array>"u"?{}:{BigUint64Array}});function fe(n,e){if(!n||typeof n!="object")return n;let t=n;if(Ie(t,"__plainObject",["__plainObject"])){let o={};for(let[i,s]of Object.entries(t.__plainObject||{}))Yn(o,i,fe(s,e));return o}if(Ie(t,"__nullPrototype",["__nullPrototype"])){let o=Object.create(null);for(let[i,s]of Object.entries(t.__nullPrototype||{}))Yn(o,i,fe(s,e));return o}if(Ie(t,"__e",["__e"])&&t.__e==="u")return;if(e&&Ie(t,"__fnRef",["__fnRef"])&&typeof t.__fnRef=="string")return e(t.__fnRef);if(Ie(t,"__number",["__number"])){if(t.__number==="nan")return Number.NaN;if(t.__number==="infinity")return Number.POSITIVE_INFINITY;if(t.__number==="-infinity")return Number.NEGATIVE_INFINITY;if(t.__number==="-0")return-0;throw new TypeError(`Unsupported executor number: ${t.__number}`)}if(Ie(t,"__bigint",["__bigint"]))return BigInt(t.__bigint);if(Ie(t,"__map",["__map"]))return new Map((t.__map||[]).map(([o,i])=>[fe(o,e),fe(i,e)]));if(Ie(t,"__arrayBuffer",["__arrayBuffer"]))return Uint8Array.from(t.__arrayBuffer||[]).buffer;if(Ie(t,"__typedArray",["__typedArray","bytes","data"])){let o=Uint8Array.from(t.bytes||t.data||[]);if(t.__typedArray==="DataView")return new DataView(o.buffer);let i=Ko[String(t.__typedArray)];if(!Object.prototype.hasOwnProperty.call(Ko,t.__typedArray)||typeof i!="function")throw new TypeError(`Unsupported executor typed array: ${t.__typedArray}`);return new i(o.buffer)}if(Array.isArray(n))return n.map(o=>fe(o,e));let r={};for(let[o,i]of Object.entries(t))Yn(r,o,fe(i,e));return r}function ve(n){try{if(n instanceof Error)return n}catch{}let e="Unknown error";try{n===void 0?e="Operation rejected with undefined":n===null?e="Operation rejected with null":e=String(n)}catch{}return new Error(e)}function Uo(n){let e=new WeakSet;try{return JSON.stringify(n,(t,r)=>{if(typeof r=="bigint")return r.toString();if(!(typeof r=="function"||typeof r=="symbol")){if(r&&typeof r=="object"){if(e.has(r))return"[Circular]";e.add(r)}return r}})}catch{let t="Host capability call failed",r;try{t=String(n.message||t)}catch{}try{typeof n.code=="string"&&(r=n.code)}catch{}return JSON.stringify({__userThrow:!0,message:t,code:r})}}function ir(n){if(n===void 0)return JSON.stringify({__e:"u"});try{return JSON.stringify({__e:"v",d:n},(e,t)=>typeof t=="bigint"?{__bigint:t.toString()}:t)}catch{return JSON.stringify({__e:"v",d:{__serializationError:!0,message:"Result is not JSON-serializable"}})}}var Qo=require("async_hooks"),Dr=new Qo.AsyncLocalStorage;function Xn(){return Dr.getStore()}function Zn(n,e){return Dr.run(n,e)}var Lr=class{constructor(e,t){this.taskAbortSignals=e;this.taskDeadlines=t;this.runtimeCallbackCounter=0}postAbortedCallError(e,t){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,r,o){if(o?.aborted){this.postAbortedCallError(t,r);return}try{let i=await(o?Dr.run(o,e):e());if(o?.aborted){this.postAbortedCallError(t,r);return}await t.postMessage({type:"callResult",callId:r,result:ir(i)})}catch(i){if(o?.aborted){this.postAbortedCallError(t,r);return}let s=ve(i),a={__userThrow:!0,message:s.message,statusCode:s.statusCode,code:s.errorCode??s.code,errorPath:s.errorPath,details:s.details,messages:s.messages};await t.postMessage({type:"callError",callId:r,error:Uo(a)}).catch(()=>{})}}parseExecutorArgs(e,t,r){let o=JSON.parse(e||"[]");return fe(o,t&&r?s=>(...a)=>this.invokeRuntimeCallback(t,r,s,a):void 0)}async execRepoCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=e.access==="secure"?oe(t?.$repos,"secure",!0):t?.$repos,i=oe(o,String(e.table),!0),s=oe(i,String(e.method));if(!i||typeof s!="function"){let a=e.access==="secure"?"secure.":"";throw new Error(`Repo method not found: ${a}${e.table}.${e.method}`)}return s.apply(i,r)}async execTransactionCall(e,t,r){let i=this.parseExecutorArgs(e.argsJson,r,e.id)[0];if(typeof i!="function")throw new Error("$transaction.run requires a callback");let s=t?.$transaction?.run;if(typeof s!="function")throw new Error("$transaction is not available");return await s.call(t.$transaction,i)}async execHelpersCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=String(e.name).split("."),i=t?.$helpers,s=i;for(let a of o)i=s,s=oe(s,a);if(typeof s!="function")throw new Error(`Helper not found: ${e.name}`);return s.apply(i,r)}async execSocketCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=t?.$socket,i=oe(o,String(e.method));if(typeof i!="function")throw new Error(`Socket method not found: ${e.method}`);return i.apply(o,r)}async execCacheCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=t?.$cache,i=oe(o,String(e.method));if(typeof i!="function")throw new Error(`Cache not found: ${e.method}`);return i.apply(o,r)}async execStorageCall(e,t,r){let o=this.parseStorageArgs(e.argsJson,r,e.id),i=t?.$storage,s=oe(i,String(e.method));if(typeof s!="function")throw new Error(`Storage method not found: ${e.method}`);return s.apply(i,o)}parseStorageArgs(e,t,r){return this.parseExecutorArgs(e,t,r)}invokeRuntimeCallback(e,t,r,o){let i=`rtcb_${++this.runtimeCallbackCounter}`,s=this.taskAbortSignals.get(t),a=this.taskDeadlines.get(t)??Date.now()+3e4,c=Math.max(1,a-Date.now())+500;return new Promise((u,l)=>{let f=!1,d=b=>{f||(f=!0,m(),b())},p=setTimeout(()=>{d(()=>l(new Error(`Runtime callback timed out: ${r}`)))},c),g=()=>{d(()=>l(new Error("Runtime callback was cancelled")))},h=()=>{d(()=>l(new Error("Runtime callback worker exited")))},y=b=>{if(!(b?.type!=="runtimeCallbackResult"||b.callId!==i)){if(b.error){let _=new Error(String(b.error));try{let S=JSON.parse(String(b.error));S?.__userThrow&&(_.message=String(S.message??_.message),_.statusCode=S.statusCode,_.code=S.code??(Number.isInteger(S.statusCode)?`HTTP_${S.statusCode}`:void 0),_.errorCode=_.code,_.errorPath=S.errorPath,_.details=S.details,_.messages=S.messages)}catch{}d(()=>l(_));return}d(()=>u(b.value))}},m=()=>{clearTimeout(p),e.off("message",y),e.off("exit",h),s?.removeEventListener("abort",g)};if(e.on("message",y),e.on("exit",h),s?.addEventListener("abort",g,{once:!0}),s?.aborted){g();return}try{e.postMessage({type:"invokeRuntimeCallback",id:t,callId:i,callbackId:r,argsJson:JSON.stringify(o)}).catch(b=>d(()=>l(b)))}catch(b){d(()=>l(b))}})}async execDispatchCall(e,t){let r=this.parseExecutorArgs(e.argsJson),o=oe(t,"$trigger");if(typeof o!="function")throw new Error("$trigger is not available");return o.apply(t,r)}};var Jo=require("stream");var eo=32*1024*1024,zo=Math.ceil(eo/3)*4,qr=class{constructor(e,t){this.cancelTask=e;this.parseExecutorArgs=t;this.responseStreams=new Map}async execResCall(e,t){if(e.method==="json"){let s=oe(t?.$res,"__enfyraJson");if(typeof s!="function")throw new Error("Native JSON response is not available");return await s.call(t.$res,String(e.jsonText),e.options||{})}if(e.method==="bytes"){let s=oe(t?.$res,"__enfyraBytes");if(typeof s!="function")throw new Error("Native binary response is not available");let a=String(e.bytes||"");if(a.length>zo)throw new Error("Native binary response exceeded 32 MiB");let c=Buffer.from(a,"base64");if(c.byteLength>eo)throw new Error("Native binary response exceeded 32 MiB");return await s.call(t.$res,c,e.options||{})}if(e.method==="streamStart"){if(this.responseStreams.has(e.id))throw new Error(`Response stream already exists: ${e.id}`);let a=JSON.parse(e.argsJson||"[]")[1]||{},c=oe(t?.$res,"stream");if(typeof c!="function")throw new Error("Response method not found: stream");let u=new Jo.PassThrough;u.on("error",()=>{});let l={stream:u};this.responseStreams.set(e.id,l);let f=t?.$res;if(f&&typeof f.once=="function"){let d=()=>{f.writableEnded!==!0&&this.cancelTask(e.id)};f.once("close",d),l.closeCleanup=()=>{typeof f.off=="function"?f.off("close",d):typeof f.removeListener=="function"&&f.removeListener("close",d)}}try{let d=c.call(t.$res,u,a);return d&&typeof d.then=="function"&&(l.completion=Promise.resolve(d).then(()=>{},p=>{let g=ve(p);throw this.responseStreams.get(e.id)===l&&(this.cleanupResponseStream(e.id,g),this.cancelTask(e.id)),g}),l.completion.catch(()=>{})),!0}catch(d){let p=ve(d);throw this.cleanupResponseStream(e.id,p),p}}if(e.method==="streamChunk"){let s=this.responseStreams.get(e.id);if(!s)throw new Error(`Response stream not found: ${e.id}`);let a=String(e.chunk||"");if(a.length>zo)throw new Error("Response stream chunk exceeded 32 MiB");let c=Buffer.from(a,"base64");if(c.byteLength>eo)throw new Error("Response stream chunk exceeded 32 MiB");if(s.stream.destroyed)throw new Error("Response stream closed before drain");return s.stream.write(c)||await new Promise((u,l)=>{let f=()=>{g(),u()},d=h=>{g(),l(h)},p=()=>{g(),l(new Error("Response stream closed before drain"))},g=()=>{s.stream.off("drain",f),s.stream.off("error",d),s.stream.off("close",p)};s.stream.once("drain",f),s.stream.once("error",d),s.stream.once("close",p)}),!0}if(e.method==="streamEnd"){let s=this.responseStreams.get(e.id);if(s){s.stream.end();try{await s.completion}finally{this.responseStreams.get(e.id)===s&&(s.closeCleanup?.(),this.responseStreams.delete(e.id))}}return!0}if(e.method==="streamError"){let s=this.responseStreams.get(e.id);if(s){s.closeCleanup?.();let a=e.error?.message||"Response stream failed";s.stream.destroy(new Error(a)),this.responseStreams.delete(e.id)}return!0}let r=this.parseExecutorArgs(e.argsJson),o=t?.$res,i=oe(o,String(e.method));if(typeof i!="function")throw new Error(`Response method not found: ${e.method}`);return i.apply(o,r)}cleanupResponseStream(e,t){let r=this.responseStreams.get(e);r&&(this.responseStreams.delete(e),r.closeCleanup?.(),t?r.stream.destroy(t):r.stream.end())}};var Ho=require("child_process"),Vo=require("string_decoder"),js=["PATH","HOME","NODE_ENV","TMPDIR","LANG"];function Bs(){let n={};for(let e of js){let t=process.env[e];t!==void 0&&(n[e]=t)}return n}var Wr=class{constructor(e){this.terminated=!1;this.stderrTail="";this.stderrDecoder=new Vo.StringDecoder("utf8");this.child=(0,Ho.fork)(e,[],{stdio:["ignore","ignore","pipe","ipc"],env:Bs(),execArgv:[],serialization:"advanced"}),this.child.on("error",t=>{this.stderrTail=(this.stderrTail+t.message).slice(-8192)}),this.child.stderr?.on("data",t=>{this.stderrTail=(this.stderrTail+this.stderrDecoder.write(t)).slice(-8192)}),this.child.stderr?.on("end",()=>{this.stderrTail=(this.stderrTail+this.stderrDecoder.end()).slice(-8192)})}get stderr(){return this.stderrTail}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){return this.child.connected?new Promise((t,r)=>{try{this.child.send(e,o=>{o?r(o):t()})}catch(o){r(o)}}):Promise.reject(new Error("Executor runner IPC is closed"))}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 Ge=class{constructor(e,t,r,o,i,s,a,c=6e4){this.scriptPath=i;this.onCrash=s;this.onRotate=a;this.entries=[];this.waiting=[];this.cachedMemoryOk=!0;this.lastMemoryCheckMs=0;this.memorySampleIntervalMs=200;this.destroying=!1;this.entryCounter=0;this.max=e,this.effectiveMemory=t,this.rssCeiling=r,this.tasksCap=o,this.drainTimeoutMs=c;for(let u=0;u<e;u++)this.spawnEntry()}getEntries(){return this.entries}clearDrainTimeout(e){e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0)}reportObserverError(e,t){let r=t instanceof Error?t.message:String(t);console.error(`[executor-pool] ${e}: ${r}`)}spawnEntry(){let e=new Wr(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,reservations:0,draining:!1,spawnedAt:Date.now()};return e.on("message",r=>{let o=t.tasks.get(r.id);if(o)if(r.type==="taskReleased")o.onRelease?.();else if(r.type==="taskLane")o.onLane?.(r.laneKey);else if(r.type==="taskFailure")o.onFailure?.(r.error);else if(r.type==="result"||r.type==="taskCancelled"){typeof r.heapRatio=="number"&&(t.lastHeapRatio=r.heapRatio),typeof r.runnerRssBytes=="number"&&(t.lastRssBytes=r.runnerRssBytes),r.contextStats&&(t.contextStats=r.contextStats);let i=r;r.type==="taskCancelled"&&(i={type:"result",id:r.id,success:!1,taskCancelled:!0,error:{message:"Task cancelled",code:"ERR_TASK_CANCELLED"}});try{o.onResult(i)}catch(s){this.reportObserverError("task result callback failed",s)}!t.draining&&typeof r.heapRatio=="number"&&r.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(r.heapRatio*100)}%`)}else o.onIoCall(r)}),e.on("exit",(r,o)=>{let i=t.draining,s=this.destroying;t.draining=!0;let a={entryId:t.id,pid:t.worker.pid,exitCode:r,exitSignal:o??null,lastError:t.lastError||t.worker.stderr||void 0,terminationReason:t.terminationReason,lastHeapRatio:t.lastHeapRatio,lastRssBytes:t.lastRssBytes,activeTasks:[...t.tasks.values()].map(l=>l.diagnostics)};this.clearDrainTimeout(t);let c="Worker crashed";s?c="Worker terminated":t.lastError&&(c=`Worker crashed: ${t.lastError}`);for(let[,l]of t.tasks){l.abortController.abort();try{l.onResult({type:"result",success:!1,error:{message:c,code:s?void 0:"ERR_EXECUTOR_RUNNER_LOST",details:s?void 0:{outcome:"unknown_outcome",retryable:!1}}})}catch(f){this.reportObserverError("worker-exit task callback failed",f)}}t.tasks.clear();let u=this.entries.indexOf(t);if(u!==-1&&this.entries.splice(u,1),(!i||t.replaceOnExit)&&!s){try{this.onCrash?.(a)}catch(f){this.reportObserverError("worker crash observer failed",f)}this.entries.filter(f=>!f.draining).length<this.max&&this.spawnEntry()}this.drainWaiting()}),e.on("error",r=>{t.lastError=r.message}),this.entries.push(t),t}rotateEntry(e,t){if(this.destroying||e.draining)return;e.draining=!0;let r=Date.now()-e.spawnedAt;try{this.onRotate?.({reason:t,ageMs:r})}catch(o){this.reportObserverError("worker rotation observer failed",o)}if(this.spawnEntry(),this.drainWaiting(),e.tasks.size===0&&e.reservations===0){this.clearDrainTimeout(e),e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,this.abortEntryTasks(e),e.worker.terminate()},this.drainTimeoutMs)}abortEntryTasks(e){for(let t of e.tasks.values())t.abortController.abort()}isMemoryAvailable(){let e=Date.now();if(e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs){let t=this.entries.reduce((r,o)=>r+(o.lastRssBytes??0),0);this.cachedMemoryOk=(process.memoryUsage().rss+t)/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e}return this.cachedMemoryOk}hasActiveWork(){return this.entries.some(e=>e.tasks.size>0||e.reservations>0)}canDispatch(){return!this.hasActiveWork()||this.isMemoryAvailable()}findLeastBusy(){let e=null;for(let t of this.entries){if(t.draining)continue;let r=t.tasks.size+t.reservations;r<this.tasksCap&&(!e||r<e.tasks.size+e.reservations)&&(e=t)}return e}dispatch(e){if(this.destroying)return Promise.reject(new Error("Executor worker pool is shutting down"));if(e?.aborted)return Promise.reject(new Error("Execution aborted before dispatch"));let t=this.findLeastBusy();return t&&this.canDispatch()?(t.reservations++,Promise.resolve(t)):new Promise((r,o)=>{let i={resolve:r,reject:o,signal:e};e&&(i.onAbort=()=>{let s=this.waiting.indexOf(i);s!==-1&&this.waiting.splice(s,1),o(new Error("Execution aborted before dispatch"))},e.addEventListener("abort",i.onAbort,{once:!0})),this.waiting.push(i)})}registerTask(e,t,r){e.reservations=Math.max(0,e.reservations-1),e.tasks.set(t,r)}releaseReservation(e){e.reservations=Math.max(0,e.reservations-1),e.draining&&e.tasks.size===0&&e.reservations===0&&(this.clearDrainTimeout(e),e.worker.terminate()),this.drainWaiting()}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&e.reservations===0&&(this.clearDrainTimeout(e),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(!e||!this.canDispatch())break;let t=this.waiting.shift();if(t.signal?.aborted){t.reject(new Error("Execution aborted before dispatch"));continue}t.signal&&t.onAbort&&t.signal.removeEventListener("abort",t.onAbort),e.reservations++,t.resolve(e)}}terminateEntry(e,t="host_requested"){e.draining&&e.terminationReason||(e.draining=!0,e.replaceOnExit=!0,e.terminationReason=t,this.clearDrainTimeout(e),this.abortEntryTasks(e),e.worker.terminate())}resize(e){this.max=Math.max(1,e);let t=this.entries.filter(i=>!i.draining);for(;t.length<this.max;)t.push(this.spawnEntry());let r=t.length-this.max;if(r<=0){this.drainWaiting();return}let o=t.sort((i,s)=>i.tasks.size+i.reservations-(s.tasks.size+s.reservations)).slice(0,r);for(let i of o)i.draining=!0;this.drainWaiting();for(let i of o)i.tasks.size===0&&i.reservations===0?(this.clearDrainTimeout(i),i.worker.terminate()):(this.clearDrainTimeout(i),i.drainTimeout=setTimeout(()=>{i.drainTimeout=void 0,this.abortEntryTasks(i),i.worker.terminate()},this.drainTimeoutMs))}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,lastRssBytes:e.lastRssBytes??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;let e=new Error("Executor worker pool was destroyed");for(let t of this.waiting.splice(0))t.signal&&t.onAbort&&t.signal.removeEventListener("abort",t.onAbort),t.reject(e);for(let t of this.entries)t.draining=!0,t.terminationReason="pool_destroyed",this.clearDrainTimeout(t),this.abortEntryTasks(t),t.worker.terminate();this.entries.length=0}};var Vs=Xo.join(__dirname,"execution/worker.js"),Gs=3e4,Ys=2147483647;function Yo(n){let e=Number(n);return Number.isFinite(e)?Math.max(1,Math.min(Ys,Math.trunc(e))):Gs}var bt=class n{constructor(e){this.logger=new Pr(n.name);this.effectiveMemory=or();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.taskCancellers=new Map;this.taskAbortSignals=new Map;this.taskDeadlines=new Map;this.taskDurationsMs=[];this.queueWaitDurationsMs=[];this.hostIo=new Lr(this.taskAbortSignals,this.taskDeadlines);this.responseBridge=new qr(e=>this.cancelTask(e),e=>this.hostIo.parseExecutorArgs(e));this.packageCacheService=e.packageCacheService,this.onExecutionFinished=e.onExecutionFinished,this.packageCdnLoaderService=e.packageCdnLoaderService,this.isolationTuning=e.tuning??Br(),this.ceiling=this.isolationTuning.maxConcurrentWorkers,this.pool=new Ge(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Vs,t=>{this.crashesTotal++;let r={event:"executor_worker_crashed",occurredAt:new Date().toISOString(),...t};this.logger.warn(r);try{e.onExecutorWorkerCrash?.(r)}catch(o){this.logger.warn({event:"executor_worker_crash_report_failed",error:o instanceof Error?o.message:String(o)})}},({reason:t,ageMs:r})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${t} age=${Math.round(r/1e3)}s`)}),this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerIsolate} tasks/isolate, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let e=this.pool.getEntries().reduce((g,h)=>g+(h.lastRssBytes??0),0),r=(process.memoryUsage().rss+e)/this.effectiveMemory,o=process.hrtime.bigint(),i=process.cpuUsage(this.prevCpuUsage),s=Number(o-this.prevCpuTime)/1e3,a=s>0?(i.user+i.system)/s:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=o;let c=this.pool.getMax(),u=this.pool.getWaitingCount(),l=r>.85||a>.7,f=r<.7&&a<.5,d=u>0,p=c;l?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(p=Math.max(1,c-1))):f&&d?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(p=Math.min(this.ceiling,c+2))):(this.pressureTicks=0,this.recoveryTicks=0),p!==c&&(this.pool.resize(p),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${c} -> ${p} (rss=${Math.round(r*100)}% cpu=${Math.round(a*100)}% queue=${u})`))}spawnAndExecute(e,t,r,o,i){return(async()=>{let s=Date.now(),a;try{a=await this.pool.dispatch(i)}catch(l){if(i?.aborted){let f=new Error("Execution aborted before dispatch");throw f.code="ERR_EXECUTION_ABORTED",f.isAbort=!0,f}throw l}if(this.recordQueueWait(Date.now()-s),i?.aborted){this.pool.releaseReservation(a);let l=new Error("Execution aborted after client disconnect");return l.code="ERR_EXECUTION_ABORTED",l.isAbort=!0,Promise.reject(l)}let c=`t_${++this.taskCounter}`,u=Date.now();return new Promise((l,f)=>{let d=!1,p=new AbortController;this.taskAbortSignals.set(c,p.signal);let g=Wo(o);this.taskDeadlines.set(c,u+g);let h=!1,y,m,b=()=>{let k=new Error("Execution aborted after client disconnect");return k.code="ERR_EXECUTION_ABORTED",k.isAbort=!0,k},_=()=>{let k=new Error(`Script execution timed out after ${o}ms`);return k.code="ERR_SCRIPT_EXECUTION_TIMEOUT",k.isTimeout=!0,k},S,E,C=!1,x=k=>{if(!(d||h)){h=!0,y=k,p.abort(),this.responseBridge.cleanupResponseStream(c,k);try{a.worker.postMessage({type:"cancelTask",id:c}).catch(()=>{})}catch{}S=setTimeout(()=>{d||(d=!0,E&&clearTimeout(E),M(),this.taskCancellers.delete(c),this.taskAbortSignals.delete(c),this.taskDeadlines.delete(c),this.recordTaskDuration(Date.now()-u),this.pool.terminateEntry(a,k.isTimeout?"timeout_cancel_grace":k.isAbort?"client_abort_cancel_grace":"failure_cancel_grace"),this.pool.unregisterTask(a,c),this.taskErrorTotal++,k.details={...k.details??{},outcome:"unknown_outcome",retryable:!1,escalation:"runner_terminated_after_cancel_grace"},f(k))},1e4),S.unref?.()}},v=()=>x(b());this.taskCancellers.set(c,v);let R=()=>v(),M=()=>{i?.removeEventListener("abort",R)};i&&(i.addEventListener("abort",R,{once:!0}),i.aborted&&v());let O=()=>{E&&clearTimeout(E),S&&clearTimeout(S),this.taskCancellers.delete(c),this.taskAbortSignals.delete(c),this.taskDeadlines.delete(c),M(),this.responseBridge.cleanupResponseStream(c),this.recordTaskDuration(Date.now()-u)},j=()=>{O(),this.pool.unregisterTask(a,c)},N=25,P=()=>{d||(this.taskTimeoutTotal++,x(_()))},Y=u+g+[...a.tasks.keys()].reduce((k,$)=>{if($===c)return k;let T=this.taskDeadlines.get($);return k+(T===void 0?0:Math.max(0,T-u))},0),te=()=>{if(!(d||h)){if(!C&&Date.now()>=Y){this.taskTimeoutTotal++,x(_());return}if(!C){E=setTimeout(te,N),E.unref?.();return}this.taskDeadlines.set(c,Date.now()+g),E=setTimeout(P,g),E.unref?.()}};E=setTimeout(te,N),E.unref?.(),this.pool.registerTask(a,c,{abortController:p,onLane:()=>{d||h||C||(C=!0,E&&clearTimeout(E),te())},diagnostics:this.createWorkerTaskDiagnostics(e,t,r,o),onFailure:k=>{if(d||h)return;m=k;let $=new Error(k.message);$.code=k.code,$.errorCode=k.code,$.statusCode=k.statusCode,$.errorPath=k.errorPath,$.details=k.details,k.stack&&($.stack=k.stack),$.isTimeout=k.code==="ERR_SCRIPT_EXECUTION_TIMEOUT",$.isTimeout&&!h&&!d&&this.taskTimeoutTotal++,x($)},onResult:k=>{if(!d){d=!0;try{this.onExecutionFinished?.({diagnostics:this.createWorkerTaskDiagnostics(e,t,r,o),logs:Array.isArray(k.diagnosticLogs?.logs)?k.diagnosticLogs.logs:Array.isArray(k.ctxChanges?.$share?.$logs)?k.ctxChanges.$share.$logs:[],logsTruncated:k.diagnosticLogs?.truncated===!0||k.ctxChanges?.$share?.$logsTruncated===!0,statusCode:k.error?.statusCode??k.ctxChanges?.$statusCode,error:m??(k.success||h?void 0:k.error)})}catch($){this.logger.error("Executor diagnostic callback failed",$)}if(k.taskCancelled===!0&&this.pool.unregisterTask(a,c),O(),h){this.taskErrorTotal++;try{k.ctxChanges&&y&&(y.ctxChanges=fe(k.ctxChanges)),f(y??b())}catch($){f(ve($))}return}if(k.success)try{let $={value:fe(k.value),valueAbsent:k.valueAbsent===!0,ctxChanges:fe(k.ctxChanges)};k.shortCircuit&&($.shortCircuit=!0),this.taskDoneTotal++,l($)}catch($){p.abort();let T=ve($);this.taskErrorTotal++,this.responseBridge.cleanupResponseStream(c,T),f(T)}else try{let $=new Error(k.error?.message||"Handler execution failed");$.statusCode=k.error?.statusCode,$.code=k.error?.code,$.errorCode=k.error?.code,$.details=k.error?.details,k.error?.stack&&($.stack=k.error.stack),k.ctxChanges&&($.ctxChanges=fe(k.ctxChanges)),this.taskErrorTotal++,this.responseBridge.cleanupResponseStream(c,$),f($)}catch($){p.abort();let T=ve($);this.taskErrorTotal++,this.responseBridge.cleanupResponseStream(c,T),f(T)}}},onRelease:()=>{this.pool.unregisterTask(a,c)},onIoCall:k=>{if(d||k.type==="executionError")return;let $=p.signal;k.type==="repoCall"?this.hostIo.handleIoCall(()=>this.hostIo.execRepoCall(k,r),a.worker,k.callId,$):k.type==="transactionCall"?this.hostIo.handleIoCall(()=>this.hostIo.execTransactionCall(k,r,a.worker),a.worker,k.callId,$):k.type==="helpersCall"?this.hostIo.handleIoCall(()=>this.hostIo.execHelpersCall(k,r),a.worker,k.callId,$):k.type==="socketCall"?this.hostIo.handleIoCall(()=>this.hostIo.execSocketCall(k,r),a.worker,k.callId,$):k.type==="cacheCall"?this.hostIo.handleIoCall(()=>this.hostIo.execCacheCall(k,r),a.worker,k.callId,$):k.type==="storageCall"?this.hostIo.handleIoCall(()=>this.hostIo.execStorageCall(k,r,a.worker),a.worker,k.callId,$):k.type==="dispatchCall"?this.hostIo.handleIoCall(()=>this.hostIo.execDispatchCall(k,r),a.worker,k.callId,$):k.type==="resCall"&&this.hostIo.handleIoCall(()=>this.responseBridge.execResCall(k,r),a.worker,k.callId,$)}}),a.worker.postMessage({type:e,id:c,...t}).then(()=>{i?.aborted&&v()}).catch(k=>{d||(d=!0,p.abort(),j(),this.taskErrorTotal++,f(k))})})})()}cancelTask(e){this.taskCancellers.get(e)?.()}toWorkerCodeBlock(e){return{code:e.code,sourceCode:e.sourceCode,scriptLanguage:e.scriptLanguage,scriptId:e.scriptId,type:e.type}}createWorkerTaskDiagnostics(e,t,r,o){let i=r?.$api?.request?.correlationId,s=Array.isArray(t.codeBlocks)?t.codeBlocks.map(a=>({type:a?.type==="preHook"||a?.type==="postHook"||a?.type==="handler"?a.type:"run",...a?.scriptId!==void 0&&a?.scriptId!==null?{scriptId:String(a.scriptId)}:{}})):[{type:typeof t.sourceKind=="string"?t.sourceKind:"run",...t.scriptId==null?{}:{scriptId:String(t.scriptId)}}];return{...typeof i=="string"&&i?{correlationId:i}:{},timeoutMs:o,isolateMemoryLimitMb:Number(t.memoryLimitMb||0),isolatePoolSize:Number(t.isolatePoolSize||0),tasksPerIsolate:Number(t.tasksPerIsolate||0),scriptBlocks:s}}async run(e,t,r,o={}){let i=Yo(r),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),c=Jn(t),u;try{let l={code:e,scriptId:o.scriptId,sourceKind:o.sourceKind,sourceCode:o.sourceCode??e,pkgSources:a,snapshot:c,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize,tasksPerIsolate:this.isolationTuning.tasksPerIsolate};u=await this.spawnAndExecute("execute",l,t,i)}catch(l){let f=l;if(f.ctxChanges&&nr(t,f.ctxChanges),f.code==="ERR_EXECUTION_ABORTED"||f.isAbort)throw f;if(f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new Be(i,e,f.details);f.code&&f.details&&(f.details.executorCode=f.code);let d=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw Ve.createException(f.errorPath,d,f.message||"Unknown error",e,f.details||{})}return nr(t,u.ctxChanges||{}),u.valueAbsent?void 0:u.value}async runBatch(e,t,r,o={}){let i=Yo(r),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),c=Jn(t),u;try{let f={codeBlocks:e.map(d=>this.toWorkerCodeBlock(d)),pkgSources:a,snapshot:c,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize,tasksPerIsolate:this.isolationTuning.tasksPerIsolate};u=await this.spawnAndExecute("executeBatch",f,t,i,o.signal)}catch(l){let f=l;if(f.ctxChanges&&nr(t,f.ctxChanges),f.code==="ERR_EXECUTION_ABORTED"||f.isAbort)throw f;if(f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new Be(i,"(batch execution)",f.details);f.code&&f.details&&(f.details.executorCode=f.code);let d=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw Ve.createException(f.errorPath,d,f.message||"Unknown error","(batch execution)",f.details||{})}return nr(t,u.ctxChanges||{}),{value:u.valueAbsent?void 0:u.value,shortCircuit:u.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}recordQueueWait(e){this.queueWaitDurationsMs.push(e),this.queueWaitDurationsMs.length>512&&this.queueWaitDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let r=[...e].sort((i,s)=>i-s),o=Math.min(r.length-1,Math.max(0,Math.ceil(t/100*r.length)-1));return r[o]}resetLatencyMetrics(){this.taskDurationsMs.length=0,this.queueWaitDurationsMs.length=0}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,r=t.length===0?0:t.reduce((s,a)=>s+a,0)/t.length,o=this.queueWaitDurationsMs,i=o.length===0?0:o.reduce((s,a)=>s+a,0)/o.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:r,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),avgQueueWaitMs:i,p95QueueWaitMs:this.percentile(o,95),p99QueueWaitMs:this.percentile(o,99),maxHeapRatio:Math.max(0,...e.workers.map(s=>s.lastHeapRatio||0)),runnerRssBytes:e.workers.reduce((s,a)=>s+(a.lastRssBytes||0),0)}}};var Ye=He(require("typescript")),Kr={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 Xs(n){return $e.getLegacyField(n)}function Zs(n){return $e.isScriptTable(n)}function ea(n){return $e.normalizeLanguage(n)}var Ur=class{getLegacyField(e){return Object.prototype.hasOwnProperty.call(Kr,e)?Kr[e]:void 0}isScriptTable(e){return Object.prototype.hasOwnProperty.call(Kr,e)}normalizeLanguage(e){return e==="javascript"?"javascript":"typescript"}compileSource(e,t){if(e==null||e==="")return null;let r=String(e),i=this.normalizeLanguage(t)==="javascript"?r:this.transpileTypeScript(r);return this.assertExecutableJavaScript(i),i}isExecutableJavaScript(e){if(!e)return!1;try{return this.assertExecutableJavaScript(e),!0}catch{return!1}}normalizeRecord(e,t){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let r={...t},o=this.getLegacyField(e);return o&&(r.sourceCode===void 0||r.sourceCode===null||r.sourceCode==="")&&r[o]!==void 0&&(r.sourceCode=r[o]),r.scriptLanguage=this.normalizeLanguage(r.scriptLanguage),r.compiledCode=this.compileSource(r.sourceCode,r.scriptLanguage),o&&o in r&&delete r[o],r}normalizePatch(e,t,r){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let o=this.getLegacyField(e),i=Object.prototype.hasOwnProperty.call(t,"sourceCode"),s=o?Object.prototype.hasOwnProperty.call(t,o):!1,a=i||s,c=Object.prototype.hasOwnProperty.call(t,"scriptLanguage"),u={...t};if(!a&&!c)return delete u.compiledCode,u;if(!a&&!r)throw new Error("Existing script data is required when changing scriptLanguage.");let l;i?l=t.sourceCode:s&&o?l=t[o]:(l=r?.sourceCode,l===void 0&&o&&r&&(l=r[o]));let f=c?t.scriptLanguage:r?.scriptLanguage;return a&&(u.sourceCode=l??null),u.scriptLanguage=this.normalizeLanguage(f),u.compiledCode=this.compileSource(l,u.scriptLanguage),o&&o in u&&delete u[o],u}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 r=this.compileSource(e.sourceCode,e.scriptLanguage);return{code:r,compiledCode:r,shouldPersistCompiledCode:r!==e.compiledCode}}let t=Object.values(Kr).filter(r=>r!=="").map(r=>Object.prototype.hasOwnProperty.call(e,r)?e[r]:void 0).find(r=>typeof r=="string"&&r!=="");if(typeof t=="string"){let r=this.compileSource(t,e.scriptLanguage);return{code:r,compiledCode:r,shouldPersistCompiledCode:r!==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 r={...e},o=e.config;if(typeof o=="string")try{o=JSON.parse(o)}catch{return e}let i=o&&typeof o=="object"?o:{};r.sourceCode=r.sourceCode??i.sourceCode??i.code??null,r.scriptLanguage=this.normalizeLanguage(r.scriptLanguage??i.scriptLanguage),r.compiledCode=this.compileSource(r.sourceCode,r.scriptLanguage);let s={...i};return delete s.sourceCode,delete s.scriptLanguage,delete s.compiledCode,delete s.code,{...r,config:typeof e.config=="string"?JSON.stringify(s):s}}repairContract(e){let t=this.normalizeLanguage(e?.scriptLanguage),r=e?.sourceCode??null,o=this.compileSource(r,t);return{sourceCode:r,scriptLanguage:t,code:o,compiledCode:o,shouldPersistCompiledCode:o!==e?.compiledCode}}transpileTypeScript(e){let t=Ye.default.transpileModule(e,{compilerOptions:{target:Ye.default.ScriptTarget.ES2022,module:Ye.default.ModuleKind.CommonJS,importsNotUsedAsValues:Ye.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),r=t.diagnostics?.find(o=>o.category===Ye.default.DiagnosticCategory.Error);if(r)throw new Error(Ye.default.flattenDiagnosticMessageText(r.messageText,`
4
+ `));return t.outputText.trimEnd()}assertExecutableJavaScript(e){if(!e)return;let t=Object.getPrototypeOf(async function(){}).constructor;new t(`"use strict";
5
+ ${e}`)}},$e=new Ur;function ta(n,e){return $e.compileSource(n,e)}function ra(n){return $e.isExecutableJavaScript(n)}function na(n,e){return $e.normalizeRecord(n,e)}function oa(n,e,t){return $e.normalizePatch(n,e,t)}function ia(n){return $e.getExecutableScript(n)}function sa(n){return $e.resolveExecutableScript(n)}function aa(n){return $e.normalizeFlowStepScriptConfig(n)}sr();cr();re();var ai=64;function li(n){let e=(n?.columns??[]).filter(t=>t.isPrimary===!0).map(t=>t.name);return e.length>0?e:n?.columns?.some(t=>t.name==="id")?["id"]:n?.columns?.some(t=>t.name==="_id")?["_id"]:[]}function ci(n,e){if(n!=="id")return n;if(e.columns?.some(r=>r.name==="id"))return"id";let t=li(e);return t.length===1?t[0]:n}function Hr(n,e){let t=n.targetTableName||n.targetTable,r=e?.tables?.get(t);if(!r)throw new w(`Field relation '${n.propertyName}' has no target table metadata`);let o=li(r);if(o.length===0)throw new w(`Field relation '${n.propertyName}' target '${t}' has no primary key metadata`);return o}function Vr(n,e,t,r){let o={rootTable:e,nodes:[]};if(n===void 0)return o;if(!Array.isArray(n))throw new w("Query fields must be an array");if(n.some(a=>typeof a!="string"))throw new w("Query field entries must be strings");if(n.length===0)return o;let i=t?.tables?.get(e);if(!i)throw new w(`Field parsing requires metadata for table '${e}'`);let s=r.createCheckpoint();try{let a=new Map,c=[],u=new Set(n.map(l=>ci(l,i)));for(let l of u)if(l==="*")c.push("*");else if(l.includes(".")){let f=l.indexOf("."),d=l.substring(0,f),p=l.substring(f+1);if(!d||!p)throw new w(`Invalid field path '${l}'`);if(!i.relations?.some(h=>h.propertyName===d))continue;a.has(d)||a.set(d,[]),a.get(d).push(p)}else if(i.relations?.some(d=>d.propertyName===l)){a.has(l)||a.set(l,[]);let d=i.relations.find(p=>p.propertyName===l);for(let p of Hr(d,t))a.get(l).includes(p)||a.get(l).push(p)}else{if(!i.columns?.some(p=>p.name===l))continue;c.push(l)}if(c.includes("*")){o.nodes.push({kind:"wildcard"});for(let l of i.relations||[])a.has(l.propertyName)||a.set(l.propertyName,Hr(l,t))}else for(let l of c)o.nodes.push({kind:"scalar",name:l});for(let[l,f]of a.entries()){let d=i.relations?.find(y=>y.propertyName===l);if(!d)continue;let p=d.targetTableName||d.targetTable;if(typeof p!="string"||!p||!t?.tables?.has(p))throw new w(`Field relation '${l}' on '${e}' has no resolvable target table metadata`);let g=ui(f,p,t,1);if(g.length===0)continue;let h={kind:"relation",propertyName:l,joinId:null,relationType:d.type,isInverse:!!d.isInverse,targetTable:p,children:g};if(d.type==="many-to-one"||d.type==="one-to-one"){let y=r.registerWithParent(e,l,t,"left",null,"data");h.joinId=y}o.nodes.push(h)}return o}catch(a){throw r.restoreCheckpoint(s),a}}function ui(n,e,t,r){if(r>ai)throw new w(`Field nesting depth exceeds maximum of ${ai}`);let o=t?.tables?.get(e);if(!o)throw new w(`Field parsing requires metadata for table '${e}'`);let i=new Map,s=[],a=new Set(n.map(u=>ci(u,o)));for(let u of a)if(u==="*")s.push("*");else if(u.includes(".")){let l=u.indexOf("."),f=u.substring(0,l),d=u.substring(l+1);if(!f||!d)throw new w(`Invalid field path '${u}'`);if(!o.relations?.some(g=>g.propertyName===f))continue;i.has(f)||i.set(f,[]),i.get(f).push(d)}else if(o.relations?.some(f=>f.propertyName===u)){i.has(u)||i.set(u,[]);let f=o.relations.find(d=>d.propertyName===u);for(let d of Hr(f,t))i.get(u).includes(d)||i.get(u).push(d)}else{if(!o.columns?.some(d=>d.name===u))continue;s.push(u)}let c=[];if(s.includes("*")){c.push({kind:"wildcard"});for(let u of o.relations||[])i.has(u.propertyName)||i.set(u.propertyName,Hr(u,t))}else for(let u of s)c.push({kind:"scalar",name:u});for(let[u,l]of i.entries()){let f=o.relations?.find(g=>g.propertyName===u);if(!f)continue;let d=f.targetTableName||f.targetTable;if(typeof d!="string"||!d||!t?.tables?.has(d))throw new w(`Field relation '${u}' on '${e}' has no resolvable target table metadata`);let p=ui(l,d,t,r+1);p.length!==0&&c.push({kind:"relation",propertyName:u,joinId:null,relationType:f.type,isInverse:!!f.isInverse,targetTable:d,children:p})}return c}re();function fi(n,e,t){return n.filter(r=>{let o=r.split(".");if(o.some(s=>!s))throw new w(`Invalid field path '${r}'`);let i=e;for(let s=0;s<o.length;s++){let a=t?.tables?.get(i);if(!a)throw new w(`Field parsing requires metadata for table '${i}'`);let c=o[s],u=s===o.length-1;if(u&&c==="*"||u&&a.columns?.some(f=>f.name===c||c==="id"&&f.name==="_id"))return!0;let l=a.relations?.find(f=>f.propertyName===c);if(!l)return!1;if(u)return!0;i=l.targetTableName||l.targetTable}return!1})}re();re();qe();var ha=new Set(["_and","_or","_not"]);function lo(n,e){return n?.tables?.get(e)??null}function io(n,e,t){return lo(n,e)?.columns?.find(r=>r.name===t)}function so(n,e,t){return lo(n,e)?.relations?.find(r=>r.propertyName===t)}function ma(n){let e=n.match(/^_(count|max|min)\(([^)]+)\)$/);if(!e)return null;let t=e[1],r=e[2].trim();if(t==="count")return{functionName:t,relationName:r};let o=r.indexOf(".");return o<=0||o!==r.lastIndexOf(".")?null:{functionName:t,relationName:r.slice(0,o).trim(),fieldName:r.slice(o+1).trim()}}function ao(n,e,t,r){if(!lo(n,e))throw new w(`${r==="filter"?"Filter":"Sort"} validation requires metadata for table '${e}'`);let i=io(n,e,t)??(t==="id"?io(n,e,"_id"):void 0);if(!i)throw new w(`${r==="filter"?"Filter":"Sort"} field '${t}' does not exist on '${e}'`);if(i.isEncrypted===!0)throw new w(`Encrypted field '${t}' on '${e}' cannot be used for ${r}.`)}function Gr(n,e,t,r,o){if(!(!n||typeof n!="object")){if(r>ne)throw new w(`Filter nesting depth exceeds maximum of ${ne}`);if(o.has(n))throw new w("Filter contains a circular reference");o.add(n);try{if(Array.isArray(n)){for(let i of n)Gr(i,e,t,r+1,o);return}for(let[i,s]of Object.entries(n)){if(ha.has(i)){Gr(s,e,t,r+1,o);continue}let a=so(t,e,i),c=a?null:io(t,e,i);if(c?.isEncrypted===!0)throw new w(`Encrypted field '${i}' on '${e}' cannot be used for filter.`);if(!(i.startsWith("_")&&!c&&!a)){if(a){let u=a.targetTableName||a.targetTable;if(typeof u!="string"||!u)throw new w(`Filter relation '${i}' on '${e}' has no target table metadata`);Gr(s,u,t,r+1,o);continue}ao(t,e,i,"filter")}}}finally{o.delete(n)}}}function Yr(n,e,t){Gr(n,e,t,0,new Set)}function _t(n,e,t){if(n===void 0)return;if(typeof n!="string"&&!Array.isArray(n))throw new w("Sort must be a string or string array");let r=Array.isArray(n)?n:n.split(",");if(r.some(i=>typeof i!="string"))throw new w("Sort entries must be strings");let o=r.map(i=>i.trim()).filter(Boolean);for(let i of o){let s=i.startsWith("-")?i.slice(1):i;if(!s)continue;let a=ma(s);if(a){let l=so(t,e,a.relationName);if(!l)throw new w(`Sort relation '${a.relationName}' does not exist on '${e}'`);if(a.functionName==="count")continue;let f=l.targetTableName||l.targetTable;if(typeof f!="string"||!f)throw new w(`Sort relation '${a.relationName}' on '${e}' has no target table metadata`);ao(t,f,a.fieldName,"sort");continue}let c=s.split("."),u=e;for(let l=0;l<c.length;l++){let f=c[l];if(l===c.length-1){ao(t,u,f,"sort");break}let p=so(t,u,f);if(!p)throw new w(`Sort path '${s}' references unknown relation '${f}' on '${u}'`);let g=p.targetTableName||p.targetTable;if(typeof g!="string"||!g)throw new w(`Sort relation '${f}' on '${u}' has no target table metadata`);u=g}}}var pe=class{plan(e){let{tableName:t,fields:r,filter:o,sort:i,page:s,limit:a,meta:c,metadata:u,dbType:l}=e,f=u?.tables?.get(t);if(!f)throw new w(`Query planning requires metadata for table '${t}'`);let d=new Te,p=this.parseFields(r),g=p===void 0?void 0:fi(p,t,u),h=null;g&&f&&(h=Vr(g,t,u,d));let y=!1,m=null;if(o!=null){Yr(o,t,u);let N=Me(o,t,u,d);m=N.node,y=N.hasRelationFilters}let b=this.parseLimit(a),_=this.parsePage(s),S=this.parseSort(i);f&&_t(S,t,u);let E=[],C=!1;for(let N of S){let P=N.startsWith("-"),Y=P?N.substring(1):N,te=P?"desc":"asc";if(f){let k=this.parseRelationAggregateSort(t,f,Y,u,l);if(k){C=!0,E.push({joinId:null,field:Y,direction:te,fullPath:Y,function:k.functionName,relationName:k.relationName,aggregateField:k.aggregateField,relationMeta:k.relationMeta});continue}let $=this.resolveLocalSortField(t,f,Y,l);E.push({joinId:null,field:$,direction:te,fullPath:$});continue}E.push({joinId:null,field:Y,direction:te,fullPath:Y})}if(_!==void 0&&b===void 0)throw new w("Query page requires limit to be present");let x=(f?.columns??[]).filter(N=>N.isPrimary===!0).map(N=>N.name);if(x.length===0&&l==="mongodb"&&f?.columns?.some(N=>N.name==="_id")&&x.push("_id"),E.length===0)for(let N of x)_t([N],t,u),E.push({joinId:null,field:N,direction:"asc",fullPath:N});else if(_!==void 0&&b!==void 0)for(let N of x)E.some(P=>P.joinId===null&&P.field===N)||(_t([N],t,u),E.push({joinId:null,field:N,direction:"asc",fullPath:N}));if(_!==void 0&&b!==void 0&&x.length===0)throw new w(`Query pagination requires a deterministic primary key on '${t}'`);let v=_!==void 0&&b!==void 0?(_-1)*b:void 0;if(v!==void 0&&!Number.isSafeInteger(v))throw new w("Query pagination offset exceeds safe integer range");let R=this.parseMeta(c),M=R.includes("totalCount")||R.includes("*"),O=R.includes("filterCount")||R.includes("*"),j=d.getAll();return{table:t,dbType:l,rawFields:g,rawFilter:o??null,joins:j,sortItems:E,limit:b,offset:v,needsTotalCount:M,needsFilterCount:O,hasRelationFilters:y,hasRelationSort:C,filterTree:m,fieldTree:h}}parseFields(e){if(e!=null){if(Array.isArray(e)){if(e.some(t=>typeof t!="string"))throw new w("Query field entries must be strings");return e.map(t=>t.trim()).filter(Boolean)}if(typeof e!="string")throw new w("Query fields must be a string or string array");return e.split(",").map(t=>t.trim()).filter(Boolean)}}parseSort(e){if(e==null)return[];if(Array.isArray(e)){if(e.some(t=>typeof t!="string"))throw new w("Query sort entries must be strings");return e.map(t=>t.trim()).filter(Boolean)}if(typeof e!="string")throw new w("Query sort must be a string or string array");return e.split(",").map(t=>t.trim()).filter(Boolean)}parseLimit(e){if(e==null)return;let t=String(e);if(!/^\d+$/.test(t))throw new w("Query limit must be a non-negative integer");let r=Number(t);if(!Number.isSafeInteger(r))throw new w("Query limit must be a safe integer");return r}parsePage(e){if(e==null)return;let t=String(e);if(!/^\d+$/.test(t))throw new w("Query page must be a positive integer");let r=Number(t);if(!Number.isSafeInteger(r)||r<1)throw new w("Query page must be a positive safe integer");return r}parseMeta(e){if(e==null)return[];if(Array.isArray(e)){if(e.some(t=>typeof t!="string"))throw new w("Query meta entries must be strings");return e.map(t=>t.trim()).filter(Boolean)}if(typeof e!="string")throw new w("Query meta must be a string or string array");return e.split(",").map(t=>t.trim()).filter(Boolean)}resolveLocalSortField(e,t,r,o){if(r.includes("."))throw new w(`Sort field '${r}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let i=t.columns?.some(a=>a.name===r),s=!i&&o==="mongodb"&&r==="id"&&t.columns?.some(a=>a.name==="_id");if(!i&&!s)throw new w(`Sort field '${r}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`);return s?"_id":r}parseRelationAggregateSort(e,t,r,o,i){let s=r.match(/^_(count|max|min)\(([^)]+)\)$/);if(!s){if(/^_(count|max|min)\(/.test(r))throw new w(`Sort function '${r}' is not supported on '${e}'. Use _count(relationName), _max(relationName.fieldName), or _min(relationName.fieldName).`);return null}let a=s[1],c=s[2].trim();if(a==="count"){let y=c;if(!y||y.includes("."))throw new w(`Sort function '${r}' is not supported on '${e}'. Use a direct relation name in _count().`);let m=t.relations?.find(b=>b.propertyName===y);if(!m)throw new w(`Sort relation '${y}' does not exist on '${e}'.`);if(m.type!=="one-to-many"&&m.type!=="many-to-many")throw new w(`Sort function '_count(${y})' is only supported for list relations on '${e}'.`);return{functionName:a,relationName:y,relationMeta:m}}let u=c.indexOf(".");if(u<=0||u!==c.lastIndexOf("."))throw new w(`Sort function '${r}' is not supported on '${e}'. Use _${a}(relationName.fieldName).`);let l=c.slice(0,u).trim(),f=c.slice(u+1).trim();if(!l||!f)throw new w(`Sort function '${r}' is not supported on '${e}'. Use _${a}(relationName.fieldName).`);let d=t.relations?.find(y=>y.propertyName===l);if(!d)throw new w(`Sort relation '${l}' does not exist on '${e}'.`);if(d.type!=="one-to-many"&&d.type!=="many-to-many")throw new w(`Sort function '_${a}(${l}.${f})' is only supported for list relations on '${e}'.`);let p=d.targetTableName||d.targetTable,g=o?.tables?.get(p);if(!g)throw new w(`Sort function '${r}' references unknown target table '${p}' on '${e}'.`);let h=g.columns?.find(y=>y.name===f)??(i==="mongodb"&&f==="id"?g.columns?.find(y=>y.name==="_id"):void 0);if(!h)throw new w(`Sort field '${f}' does not exist on '${p}' for function '_${a}(${l}.${f})'.`);if(h?.isEncrypted===!0)throw new w(`Encrypted field '${f}' on '${p}' cannot be used for sort.`);return{functionName:a,relationName:l,aggregateField:h.name,relationMeta:d}}};var Zr=require("mongodb");et();function ge(n){return n.type==="one-to-many"||n.isInverse===!0||n.type==="one-to-one"&&!!n.mappedBy}function X(n){return(n.type==="many-to-one"||n.type==="one-to-one")&&!ge(n)&&(n.foreignKeyColumn||n.propertyName)||null}function V(n){return n.foreignKeyColumn||n.mappedBy||n.propertyName||null}function ba(n){return n instanceof Zr.ObjectId?!0:n==null||typeof n!="object"?!1:n._bsontype==="ObjectId"||n._bsontype==="ObjectID"?typeof n.toHexString=="function"||n.id instanceof Uint8Array:!1}function wa(n){if(n==null||typeof n!="object"||Array.isArray(n))return!1;let e=Object.keys(n);if(e.length!==1||e[0]!=="buffer")return!1;let t=n.buffer;return!!t&&typeof t=="object"&&Object.keys(t).length===12}function se(n){if(!n||typeof n!="object")return n;if(ba(n))return typeof n.toHexString=="function"?n.toHexString():new Zr.ObjectId(Buffer.from(n.id??n.buffer)).toString();if(n instanceof Date)return n.toISOString();if(Buffer.isBuffer(n))return n;if(Array.isArray(n))return n.map(t=>se(t));if(wa(n))try{let t=n.buffer,r=Object.keys(t).sort((o,i)=>parseInt(o,10)-parseInt(i,10)).map(o=>t[o]);return new Zr.ObjectId(Buffer.from(r)).toString()}catch{}let e={};for(let[t,r]of Object.entries(n))Object.defineProperty(e,t,{value:se(r),enumerable:!0,configurable:!0,writable:!0});return e}function he(n,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,c=e.mappedBy,u=n,l=e.junctionTableName||dr(a,c,u);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:l,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:u};let f=pr(a,c,u);return{junctionName:l,selfColumn:f.targetColumn,otherColumn:f.sourceColumn,owningTable:a,inverseTable:u}}let r=n,o=t,i=e.junctionTableName||dr(r,e.propertyName,o);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:i,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:r,inverseTable:o};let s=pr(r,e.propertyName,o);return{junctionName:i,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:r,inverseTable:o}}var tn=require("node:fs"),bi=require("node:path"),en=class{constructor(e,t,r,o){this.dbType=e;this.knexService=t;this.mongoService=r;this.runMongoMutationInSaga=o;this.batchInserts={items:[],flushing:!1};if(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)try{(0,tn.mkdirSync)((0,bi.dirname)(this.batchInsertTraceFile),{recursive:!0})}catch{}}async flush(){let e=this.batchInserts.failure;for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)try{await this.flushBatchInsertBuffer()}catch(t){e??={reason:t}}if(e??=this.batchInserts.failure,this.batchInserts.failure=void 0,e)throw e.reason}async enqueue(e,t){let r=Array.isArray(t)?t:[t],o=r.map(i=>({table:e,data:this.cloneBatchInsertRow(i)}));for(let i of o)this.batchInserts.items.push(i);return this.traceBatchInsert("enqueue",{tableName:e,count:r.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:r.length}}cloneBatchInsertRow(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}async flushBatchInsertBuffer(){for(;this.batchInserts.flushing;)if(await this.batchInserts.flushPromise,this.batchInserts.items.length===0)return;let e=this.batchInserts.items.splice(0,this.batchInsertMaxSize);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 r=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...r.entries()].map(([o,i])=>({tableName:o,count:i.length}))}),await this.runLimited([...r.entries()],([o,i])=>this.flushBatchInsertTable(o,i)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}catch(r){throw this.batchInserts.failure??={reason:r},r}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(r=>this.logBatchInsertError("QueryBuilder batch insert flush failed",r))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let r=Date.now();await this.runBatchInsertWithIsolation(e,t),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-r})}async runBatchInsertWithIsolation(e,t){if(t.length===0)return;if(!(this.dbType==="mongodb"?typeof this.mongoService?.insertManyWithCascade=="function":typeof this.knexService?.insertManyWithCascade=="function")){let o=async()=>{await this.runLimited(t,async i=>{this.dbType==="mongodb"?await this.mongoService.insertOne(e,i.data):await this.knexService.insertWithCascade(e,i.data)})};this.dbType==="mongodb"?await this.runMongoMutationInSaga(o):await o();return}try{this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.insertManyWithCascade(e,t.map(o=>o.data))):await this.knexService.insertManyWithCascade(e,t.map(o=>o.data))}catch(o){if(t.length===1)throw this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,o),o;let i=Math.ceil(t.length/2),s;for(let a of[t.slice(0,i),t.slice(i)])try{await this.runBatchInsertWithIsolation(e,a)}catch(c){s??={reason:c}}if(s)throw s.reason}}groupBatchInsertsByTable(e){let t=new Map;for(let r of e){let o=t.get(r.table);o?o.push(r):t.set(r.table,[r])}return t}async runLimited(e,t){let r=0,o,i=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;r<e.length;){let s=e[r++];try{await t(s)}catch(a){o??={reason:a}}}});if(await Promise.all(i),o)throw o.reason}readPositiveEnv(e,t){let r=Number(process.env[e]);return!Number.isSafeInteger(r)||r<=0?t:r}traceBatchInsert(e,t){if(this.batchInsertTraceFile)try{(0,tn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
6
+ `)}catch{}}logBatchInsertError(e,t){let r=t?.message||String(t);this.traceBatchInsert("error",{message:e,error:r,code:t?.code,detail:t?.detail}),console.error(`${e}: ${r}`)}};async function tt(n,e,t,r){if(!n)return{scalarFields:[],relations:[]};let o=n.tables?.get(e);if(!o)return{scalarFields:[],relations:[]};let i=new Map;for(let u of t)if(u==="*")i.has("")||i.set("",[]),i.get("").push(u);else if(u.includes(".")&&o.relations?.some(l=>l.propertyName===u.split(".")[0])){let l=u.split("."),f=l[0],d=l.slice(1).join(".");i.has(f)||i.set(f,[]),i.get(f).push(d)}else if(o.relations?.some(f=>f.propertyName===u)){let f=i.get(u)??[];f.includes("_id")||f.push("_id"),i.set(u,f)}else i.has("")||i.set("",[]),i.get("").push(u);if(r&&typeof r=="object")for(let[u,l]of Object.entries(r)){if(i.has(u))continue;let f=l&&typeof l=="object"&&l.fields!=null?Array.isArray(l.fields)?l.fields:String(l.fields).split(",").map(d=>d.trim()).filter(Boolean):["*"];i.set(u,f)}let s=[],a=[],c=i.get("")||[];for(let u of c)if(u==="*"){if(o.columns)for(let l of o.columns)s.includes(l.name)||s.push(l.name);if(o.relations)for(let l of o.relations)i.has(l.propertyName)||i.set(l.propertyName,["_id"])}else o.columns?.some(f=>f.name===u)&&!s.includes(u)&&s.push(u);for(let[u,l]of i.entries()){if(u==="")continue;let f=o.relations?.find(y=>y.propertyName===u);if(!f)continue;let d="",p="",g=!1;f.type==="many-to-one"||f.type==="one-to-one"?ge(f)?(d="_id",p=V(f)||f.propertyName,g=!0):(d=X(f)||f.propertyName,p="_id",g=!1):f.type==="one-to-many"?(d="_id",p=V(f)||f.propertyName,g=!0):f.type==="many-to-many"&&(f.mappedBy?(d="_id",p=f.mappedBy,g=!0):(d=f.propertyName,p="_id",g=!1));let h=f.type==="one-to-many"||f.type==="many-to-many";a.push({propertyName:u,targetTable:f.targetTableName,localField:d,foreignField:p,type:h?"many":"one",isInverse:g,nestedFields:l})}return{scalarFields:s,relations:a}}re();qe();var wi=new Set(["fields","filter","sort","limit","page","deep"]),me=3;function _a(n,e,t,r,o){let i=Array.isArray(n)?n:typeof n=="string"?n.split(","):null;if(!i||i.some(s=>typeof s!="string"))throw new w(`Deep fields for relation '${r}' on '${o}' must be strings`);for(let s of i){let a=s.trim();if(!a||a==="*")continue;let c=a.split(".");if(c.some(l=>!l))throw new w(`Invalid deep field path '${a}'`);let u=e;for(let l=0;l<c.length;l+=1){let f=c[l],d=t?.tables?.get(u);if(!d)throw new w(`Deep fields require metadata for target table '${u}'`);let p=l===c.length-1,g=d.columns?.find(b=>b.name===f),h=f==="id"&&d.columns?.some(b=>b.name==="_id");if(p&&(g||h))break;let y=d.relations?.find(b=>b.propertyName===f);if(!y)break;if(l+1>me)throw new w(`Deep field path exceeds max relation hops of ${me} at '${f}'`);let m=y.targetTableName||y.targetTable;if(typeof m!="string"||!m||!t?.tables?.has(m))throw new w(`Deep field relation '${f}' on '${u}' has no resolvable target table metadata`);if(p)break;u=m}}}function _i(n,e,t,r){if(!Number.isSafeInteger(n)||(e==="limit"?Number(n)<0:Number(n)<1))throw new w(`Deep ${e} for relation '${t}' on '${r}' must be a ${e==="limit"?"non-negative":"positive"} safe integer`);return n}function rt(n,e,t,r=0,o=3){if(!e||typeof e!="object"||Array.isArray(e))throw new w("deep option must be an object");if(!Number.isSafeInteger(r)||r<0||!Number.isSafeInteger(o)||o<1||o>64)throw new w("Deep option recursion bounds must be safe integers within 0..64");if(r>=o)throw new w(`deep option exceeds maximum query depth of ${o}`);let i=t?.tables?.get(n),s=new Map((i?.relations??[]).map(a=>[a.propertyName,a]));for(let[a,c]of Object.entries(e)){let u=s.get(a);if(!u)throw new w(`Unknown relation '${a}' on '${n}'`);if(!c||typeof c!="object"||Array.isArray(c))throw new w(`Deep option for relation '${a}' must be an object`);for(let d of Object.keys(c))if(!wi.has(d))throw new w(`Unknown deep option key '${d}' for relation '${a}'. Allowed: ${[...wi].join(", ")}`);let l=u.type;if(c.limit!==void 0&&(l==="many-to-one"||l==="one-to-one"))throw new w(`'limit' not supported on many-to-one/one-to-one relations (relation '${a}' on '${n}')`);if(c.limit!==void 0&&_i(c.limit,"limit",a,n),c.page!==void 0&&_i(c.page,"page",a,n),c.page!==void 0&&c.limit===void 0)throw new w(`'page' requires 'limit' to be present (relation '${a}' on '${n}')`);let f=u.targetTableName||u.targetTable;if(typeof f!="string"||!f||!t?.tables?.has(f))throw new w(`Relation '${a}' on '${n}' has no resolvable target table metadata`);if(c.fields!==void 0&&_a(c.fields,f,t,a,n),c.filter!==void 0){if(!c.filter||typeof c.filter!="object"||Array.isArray(c.filter))throw new w(`Deep filter for relation '${a}' on '${n}' must be an object`);rn(c.filter,0,a,n,f,t,0,new Set),Le(c.filter,f,t),Yr(c.filter,f,t)}if(c.sort!==void 0){if(typeof c.sort!="string"&&!Array.isArray(c.sort))throw new w(`Deep sort for relation '${a}' on '${n}' must be a string or string array`);let d=Array.isArray(c.sort)?c.sort:c.sort.split(",").map(p=>p.trim()).filter(Boolean);if(d.some(p=>typeof p!="string"))throw new w(`Sort entries must be strings (relation '${a}' on '${n}')`);_t(d,f,t);for(let p of d){let g=p.startsWith("-")?p.slice(1):p;Sa(g,f,t,a,n)}}c.deep!==void 0&&rt(f,c.deep,t,r+1,o)}}function Sa(n,e,t,r,o){if(n.includes("."))throw new w(`Sort field '${n}' is not supported for relation '${r}' on '${o}'. Sort only by local fields defined on '${e}'.`);let i=t?.tables?.get(e);if(!i)throw new w(`Sort field '${n}' references unknown table '${e}' (relation '${r}' on '${o}')`);let s=i.columns?.some(c=>c.name===n),a=n==="id"&&i.columns?.some(c=>c.name==="_id");if(!s&&!a)throw new w(`Sort field '${n}' does not exist on '${e}' (relation '${r}' on '${o}')`)}var $a=new Set(["_and","_or","_not"]);function Ta(n,e,t,r,o,i){let s=n.split(".");if(s.some(p=>!p))throw new w(`Invalid dotted filter path '${n}'`);let a=e,c=r;for(let p of s.slice(0,-1)){let g=t?.tables?.get(a);if(!g)throw new w(`Filter path '${n}' references unknown table '${a}'`);let h=g.relations?.find(m=>m.propertyName===p);if(!h)throw new w(`Filter path '${n}' references unknown relation '${p}' on '${a}'`);if(c+=1,c>me)throw new w(`Filter path exceeds max dotted hops of ${me} at '${p}' (relation '${o}' on '${i}')`);let y=h.targetTableName||h.targetTable;if(!y)throw new w(`Filter relation '${p}' on '${a}' has no target table`);a=y}let u=s[s.length-1],l=t?.tables?.get(a);if(!l)throw new w(`Filter path '${n}' references unknown table '${a}'`);let f=l.columns?.some(p=>p.name===u),d=u==="id"&&l.columns?.some(p=>p.name==="_id");if(!f&&!d)throw new w(`Filter path '${n}' references unknown field '${u}' on '${a}'`);return{tableName:a,relationDepth:c}}function rn(n,e,t,r,o,i,s,a){if(!(!n||typeof n!="object")){if(s>64)throw new w("Filter nesting depth exceeds maximum of 64");if(a.has(n))throw new w("Filter contains a circular reference");a.add(n);try{if(Array.isArray(n)){for(let l of n)rn(l,e,t,r,o,i,s+1,a);return}let c=i?.tables?.get(o);if(!c)throw new w(`Filter validation requires metadata for table '${o}'`);let u=new Map((c?.relations??[]).map(l=>[l.propertyName,l]));for(let[l,f]of Object.entries(n)){if($a.has(l)){rn(f,e,t,r,o,i,s+1,a);continue}if(l.includes(".")){if(Ta(l,o,i,e,t,r).relationDepth>me)throw new w(`Filter path exceeds max dotted hops of ${me} at '${l}' (relation '${t}' on '${r}')`);continue}let d=u.get(l);if(!d){if(l.startsWith("_"))continue;continue}let p=e+1;if(p>me)throw new w(`Filter path exceeds max dotted hops of ${me} at '${l}' (relation '${t}' on '${r}')`);let g=d.targetTableName||d.targetTable;g&&rn(f,p,t,r,g,i,s+1,a)}}finally{a.delete(n)}}}function ye(n,e){if(!n||typeof n!="object")return!1;for(let[t,r]of Object.entries(n))if(t==="_and"||t==="_or"){if(Array.isArray(r)){for(let o of r)if(ye(o,e))return!0}}else if(t==="_not"){if(ye(r,e))return!0}else if(e.has(t))return!0;return!1}function Ae(n,e){if(!n||typeof n!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},r={},o=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(n)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(o.has(s))if(typeof a=="object"&&a!==null){let c=Object.keys(a);if(c.some(l=>l.startsWith("_"))){let l=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];c.length>0&&c.every(f=>l.includes(f))?r[s]={id:a}:r[s]=a}else r[s]=a}else r[s]=a;else t[s]=a}let i=ye(n,o);return{fieldFilters:t,relationFilters:r,hasRelations:i}}function uo(n){return`__sort_count_${n.relationName||n.field}`}function fo(n){let e=n.relationName||n.field,t=n.aggregateField||"value";return`__sort_${n.function}_${e.length}_${e}_${t.length}_${t}`}function Si(n){return n.filter(e=>e.function==="count").map(uo)}function $i(n){return n.filter(e=>(e.function==="max"||e.function==="min")&&e.aggregateField).map(fo)}function Ti(n,e,t,r){for(let i of t){if(i.function!=="count")continue;let s=i.relationMeta,a=i.relationName||i.field,c=s?.targetTableName||s?.targetTable,u=uo(i);if(!(!s||!c)){if(s.type==="one-to-many"){let l=V(s)||a;n.push({$lookup:{from:c,let:{localId:"$_id"},pipeline:[{$match:{$expr:{$eq:[`$${l}`,"$$localId"]}}},{$count:"value"}],as:u}}),n.push({$addFields:{[u]:{$ifNull:[{$arrayElemAt:[`$${u}.value`,0]},0]}}});continue}if(s.type==="many-to-many"){let l=he(e,s);if(!l)continue;n.push({$lookup:{from:l.junctionName,let:{localId:"$_id"},pipeline:[{$match:{$expr:{$eq:[`$${l.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:u}}),n.push({$addFields:{[u]:{$ifNull:[{$arrayElemAt:[`$${u}.value`,0]},0]}}})}}}}function ki(n,e,t,r){for(let i of t){if(i.function!=="max"&&i.function!=="min")continue;let s=i.relationMeta,a=i.relationName||i.field,c=s?.targetTableName||s?.targetTable,u=i.aggregateField;if(!s||!c||!u)continue;let l="_id",f=u,d=fo(i),p=i.function==="min"?"$min":"$max";if(s.type==="one-to-many"){let g=V(s)||a;n.push({$lookup:{from:c,let:{localId:"$_id"},pipeline:[{$match:{$expr:{$eq:[`$${g}`,"$$localId"]}}},{$group:{_id:null,value:{[p]:`$${f}`}}}],as:d}}),n.push({$addFields:{[d]:{$arrayElemAt:[`$${d}.value`,0]}}});continue}if(s.type==="many-to-many"){let g=he(e,s);if(!g)continue;let h="__enfyra_relation_aggregate_target__";n.push({$lookup:{from:g.junctionName,let:{localId:"$_id"},pipeline:[{$match:{$expr:{$eq:[`$${g.selfColumn}`,"$$localId"]}}},{$lookup:{from:c,localField:g.otherColumn,foreignField:l,as:h}},{$unwind:`$${h}`},{$group:{_id:null,value:{[p]:`$${h}.${f}`}}}],as:d}}),n.push({$addFields:{[d]:{$arrayElemAt:[`$${d}.value`,0]}}})}}}function ka(n){let e=n.split(".");return e[e.length-1]==="id"&&(e[e.length-1]="_id"),e.join(".")}function po(n){let e=Object.create(null);for(let t of n){let r=ka(t.field);Object.defineProperty(e,r,{value:t.direction==="asc"?1:-1,enumerable:!0,configurable:!0,writable:!0})}return e}function gr(n){let e=Object.create(null);for(let t of n){if((t.function==="max"||t.function==="min")&&!t.aggregateField)continue;let r=t.function==="count"?uo(t):t.function==="max"||t.function==="min"?fo(t):t.joinId!==null?t.fullPath:t.field;Object.defineProperty(e,r,{value:t.direction==="asc"?1:-1,enumerable:!0,configurable:!0,writable:!0})}return e}Oe();var Bi=require("mongodb");on();Oe();Oe();function Fi(n,e,t){let{rootFields:r,subRelations:o}=nt(n),i={},s=!1;if(r.includes("*")){s=!0;for(let d of e.relations||[])o.has(d.propertyName)||o.set(d.propertyName,["_id"])}else for(let d of r){let p=e.columns.find(g=>g.name===d);p?i[p.name]=1:e.relations?.find(h=>h.propertyName===d)&&!o.has(d)&&o.set(d,["_id"])}o.forEach((d,p)=>{let g=e.relations?.find(h=>h.propertyName===p);g&&(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse)&&(s||(i[X(g)||g.propertyName]=1))}),s||(i._id=1);let a=[];o.forEach((d,p)=>{let g=e.relations?.find(b=>b.propertyName===p);if(!g)return;let h=g.targetTableName||g.targetTable;if(!h)return;let y,m;g.type==="many-to-one"||g.type==="one-to-one"?ge(g)?(y="_id",m=V(g)||g.propertyName):(y=X(g)||g.propertyName,m="_id"):g.type==="one-to-many"?(y="_id",m=V(g)||g.propertyName):g.type==="many-to-many"&&(g.isInverse?(y="_id",m=g.mappedBy):(y=g.propertyName,m="_id")),a.push({relationName:p,type:g.type,targetTable:h,fields:d,isInverse:g.isInverse,fkColumn:g.foreignKeyColumn,mappedBy:g.mappedBy,junctionTableName:g.junctionTableName,junctionSourceColumn:g.junctionSourceColumn,junctionTargetColumn:g.junctionTargetColumn,localField:y,foreignField:m})});let c=!s&&Object.keys(i).length===1&&i._id===1&&a.length===0,u=t?.get(e.name)??[],l=[];if(!s&&u.length>0)for(let d of u)i[d.newName]===1&&i[d.oldName]!==1&&(i[d.oldName]=1,l.push(d.oldName));return{isPkOnly:c,nestedDescs:a,fetchSpec:{projection:s?void 0:i,pendingRenames:u,hiddenFields:l}}}function Ne(n,e){let t=e.pendingRenames??[];if(n.length===0||t.length===0)return n;let r=new Set(e.hiddenFields??[]);for(let o of n){let i=Object.getOwnPropertyDescriptors(o),s=[],a=new Set;for(let c of t){let u=Object.prototype.hasOwnProperty.call(i,c.newName),l=Object.prototype.hasOwnProperty.call(i,c.oldName)?i[c.oldName]:void 0;!u&&l&&s.push({name:c.newName,value:l.value}),(r.has(c.oldName)||u||l)&&a.add(c.oldName)}for(let c of s)Object.defineProperty(o,c.name,{value:c.value,enumerable:!0,configurable:!0,writable:!0});for(let c of a)delete o[c]}return n}Oe();var sn=require("mongodb");function Ii(n){return`__sort_${n.map(e=>`${e.length}_${e}`).join("_")}`}function Ue(n){let e={};for(let t of ke(n)){let r=t.field.split("."),o=r[r.length-1]==="id"?"_id":r[r.length-1];if(r.length===1)Object.defineProperty(e,o,{value:t.order,enumerable:!0,writable:!0,configurable:!0});else{let i=Ii(r.slice(0,-1));e[`${i}.${o}`]=t.order}}return Object.keys(e).length>0?e:void 0}function ke(n){return n?(Array.isArray(n)?n:n.split(",")).map(t=>String(t).trim()).filter(Boolean).map(t=>{let r=t.startsWith("-"),o=r?t.slice(1):t;return{field:o==="id"?"_id":o,order:r?-1:1}}):[]}function yr(n){return ke(n).some(e=>e.field.includes("."))}function an(n,e,t,r=!1,o){let i=ke(t).map(p=>`${p.order===-1?"-":""}${p.field}`),s=[{$match:e}],a=new Set,c=new Map,u=new Set((o?.tables?.get(n)?.columns??[]).map(p=>p.name)),l=p=>{let g=p.join("."),h=c.get(g);if(h)return h;let y=Ii(p),m=y,b=1;for(;u.has(m);)m=`${y}_${b++}`;return u.add(m),c.set(g,m),m};for(let p of i){let h=(p.startsWith("-")?p.slice(1):p).split(".");if(h.length<=1)continue;let y=n;for(let m=0;m<h.length-1;m++){let b=h[m],_=o?.tables?.get(y);if(!_)throw new Error(`MongoDB sort metadata not found for table '${y}'`);let S=_.relations?.find(x=>x.propertyName===b);if(!S)throw new Error(`MongoDB dotted sort relation '${y}.${b}' was not found`);let E=S.targetTableName||S.targetTable,C=l(h.slice(0,m+1));if(ge(S)||S.type==="one-to-many"||S.type==="many-to-many")throw new Error(`Dotted sort through inverse or to-many relation '${b}' is not supported`);if(!a.has(C)){a.add(C);let x=X(S)||S.propertyName,v=m===0?null:l(h.slice(0,m)),R=v?`${v}.${x}`:x;s.push({$lookup:{from:E,localField:R,foreignField:"_id",as:C}},{$unwind:{path:`$${C}`,preserveNullAndEmptyArrays:!0}})}y=E}}let f={};for(let p of ke(t)){let g=p.field.split(".");if(g.length===1)Object.defineProperty(f,g[0],{value:p.order,enumerable:!0,writable:!0,configurable:!0});else{let h=g[g.length-1]==="id"?"_id":g[g.length-1];f[`${l(g.slice(0,-1))}.${h}`]=p.order}}f._id===void 0&&(f._id=1),s.push({$sort:f});let d={};for(let p of a)d[p]=0;return!r&&Object.keys(d).length>0&&s.push({$project:d}),s}function ot(n,e){let t=i=>i==null?1:typeof i=="number"?2:typeof i=="string"?3:i instanceof sn.ObjectId?7:typeof i=="boolean"?8:i instanceof Date?9:typeof i=="object"&&!Array.isArray(i)?4:Array.isArray(i)?5:100,r=t(n),o=t(e);if(r!==o)return r<o?-1:1;if(n==null&&e==null)return 0;if(typeof n=="number"&&typeof e=="number")return n===e||Number.isNaN(n)&&Number.isNaN(e)?0:Number.isNaN(n)?-1:Number.isNaN(e)?1:n<e?-1:1;if(n instanceof Date&&e instanceof Date){let i=n.getTime(),s=e.getTime();return Number.isNaN(i)&&Number.isNaN(s)?0:Number.isNaN(i)?-1:Number.isNaN(s)?1:i===s?0:i<s?-1:1}if(n instanceof sn.ObjectId&&e instanceof sn.ObjectId)return Buffer.compare(n.id,e.id);if(typeof n=="string"&&typeof e=="string")return Buffer.compare(Buffer.from(n),Buffer.from(e));if(typeof n=="boolean"&&typeof e=="boolean")return n===e?0:n?1:-1;throw new Error("MongoDB in-memory merge does not support object sort keys")}function vi(n,e){let t=ke(e).filter(r=>!r.field.includes("."));t.length!==0&&n.sort((r,o)=>{for(let i of t){let s=ot(r[i.field],o[i.field]);if(s!==0)return s*i.order}return ot(r._id,o._id)})}function Mi(n){n.sort((e,t)=>ot(e._id,t._id))}var xa=new Set(["__proto__","constructor","prototype"]);function le(n){return n===0||n===!1}function go(n){let e=Object.entries(n??{});return e.length===0?!1:e.every(([t])=>t==="_id")?e.some(([,t])=>le(t)):e.some(([t,r])=>t!=="_id"&&le(r))}function it(n,e){if(!n||Object.keys(n).length===0)return;let t={...n},r=go(t);for(let o of e){let i=Object.keys(t).filter(s=>s===o||o.startsWith(s+".")||s.startsWith(o+"."));if(r)for(let s of i)le(t[s])&&delete t[s];else if(!i.some(s=>!le(t[s])&&(s===o||o.startsWith(s+".")))){for(let s of i)delete t[s];Object.defineProperty(t,o,{value:1,enumerable:!0,configurable:!0,writable:!0})}}return Object.keys(t).length>0?t:void 0}function Ai(n,e,t){let r=it(e,t);r&&n.push({$project:r})}function ln(n,e){if(!n||Object.keys(n).length===0)return{projection:void 0,hiddenFields:[]};let t=[],r=go(n),o=[...ke(e).map(a=>a.field),"_id"],i=[...new Set(o)],s=it(n,i.filter(a=>!(a==="_id"&&n._id===void 0)));for(let a of i)if(r)for(let[c,u]of Object.entries(n))le(u)&&(c===a||a.startsWith(c+".")||c.startsWith(a+"."))&&t.push(c);else!(a==="_id"&&n._id===void 0)&&!Object.keys(n).some(c=>!le(n[c])&&(c===a||a.startsWith(c+".")))&&t.push(a);return{projection:s,hiddenFields:[...new Set(t)]}}function cn(n,e){if(e)for(let t of n)delete t._id}function un(n,e,t=[]){if(e&&Object.keys(e).length===0&&(e=void 0),!e&&t.length===0)return;let r=e?go(e):!1,o=e?Object.entries(e):[],i=u=>{if(u.some(l=>xa.has(l)))throw new Error("Unsafe MongoDB projection path")},s=(u,l)=>{if(u==null)return;if(l.length===0)return u;if(Array.isArray(u))return u.map(h=>s(h,l));let[f,...d]=l;if(!Object.prototype.hasOwnProperty.call(u,f))return;let p=s(u[f],d);if(p===void 0)return;let g=Object.create(null);return Object.defineProperty(g,f,{value:p,enumerable:!0,configurable:!0,writable:!0}),g},a=(u,l)=>{if(l===void 0)return u;if(Array.isArray(l)){let p=Array.isArray(u)?u:[];return l.forEach((g,h)=>{p[h]=a(p[h],g)}),p}if(!l||typeof l!="object")return l;let f=Object.getPrototypeOf(l);if(f!==null&&f!==Object.prototype)return l;let d=u&&typeof u=="object"&&!Array.isArray(u)?u:Object.create(null);for(let[p,g]of Object.entries(l))Object.defineProperty(d,p,{value:a(d[p],g),enumerable:!0,configurable:!0,writable:!0});return d},c=(u,l)=>{if(u==null||l.length===0)return;if(Array.isArray(u)){for(let p of u)c(p,l);return}let[f,...d]=l;if(Object.prototype.hasOwnProperty.call(u,f)){if(d.length===0){delete u[f];return}c(u[f],d)}};for(let u of n){if(e)if(r)for(let[l,f]of o){let d=l.split(".");i(d),le(f)&&c(u,d)}else{let l=Object.create(null);for(let[f,d]of o){if(le(d))continue;let p=f.split(".");i(p),l=a(l,s(u,p))}!le(e._id)&&u._id!==void 0&&Object.defineProperty(l,"_id",{value:u._id,enumerable:!0,configurable:!0,writable:!0});for(let f of Object.keys(u))delete u[f];for(let[f,d]of Object.entries(l))Object.defineProperty(u,f,{value:d,enumerable:!0,configurable:!0,writable:!0})}for(let l of Object.keys(u))t.some(f=>l.startsWith(f))&&delete u[l]}}var wr=require("mongodb");$t();var br="__enfyra_top_n_documents__";function Z(n){return Math.ceil(n.length/5e3)||1}function st(n){return Array.from(new Map(n.filter(e=>e!=null).map(e=>[B(e),e])).values())}function Tt(n,e="_id"){let t=Ue(n)||{};return t[e]===void 0&&(t[e]=1),t}function Pe(n,e){return!e||Object.keys(e).length===0?n:{$and:[n,e]}}function _r(n,e,t,r,o){n.push({$group:{_id:`$${e}`,[br]:{$topN:{sortBy:t,output:"$$ROOT",n:r+o}}}},{$project:{[br]:{$slice:[`$${br}`,r,o]}}},{$unwind:`$${br}`},{$replaceRoot:{newRoot:`$${br}`}})}function B(n){return n instanceof wr.ObjectId?`objectId:${n.toHexString()}`:typeof n=="object"&&typeof n?.toHexString=="function"?`objectId:${n.toHexString()}`:n===void 0?"undefined:":typeof n=="object"&&n!==null?`bson:${Buffer.from(wr.BSON.serialize({value:n})).toString("base64")}`:`${typeof n}:${wr.BSON.EJSON.stringify(n,{relaxed:!1})}`}var dn=He(require("fs")),mo=He(require("path"));var Ca=new RegExp("\\p{Mark}","gu");function Oi(n){return n==null?"":String(n).normalize("NFKD").replace(Ca,"").toLowerCase()}function ho(){let n={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),r=Oi(t);r!==t&&(n[t]=r)}catch{}return JSON.stringify(n)}function fn(){return`function() {
7
+ var M = ${ho()};
7
8
  function foldStr(s) {
8
9
  if (s == null) return '';
9
10
  s = String(s);
@@ -48,5 +49,4 @@ ${e}
48
49
  }
49
50
  }
50
51
  return true;
51
- }`}var Or="mongo-fold-text-search.body.txt",qe=null;function eo(){let r=[Ln.join(__dirname,Or),Ln.join(process.cwd(),"dist","kernel","query","utils",Or)];for(let e of r)try{if(en.existsSync(e))return en.readFileSync(e,"utf8")}catch{}return null}function tn(){if(qe!==null)return qe;let r=eo();return r?(qe=r,qe):(qe=Zt(),qe)}var be=require("mongodb");function W(r,e,t,n){if(t==="_id"){if(n instanceof be.ObjectId)return n;if(typeof n=="string")try{return new be.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 be.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 be.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 be.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new be.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 be.ObjectId(n)}catch{return n}return n;default:return n}}var nn="__mongoFoldTextTriples";function to(r){return r==="_id"?"$_id":`$${r}`}function Ue(r,e,t,n){let i=to(e),o=r[nn]??[];o.push({ref:i,needle:t,mode:n}),r[nn]=o}function no(r){let e=r[nn];if(delete r[nn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:tn(),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=W(r,u,a,s.value);switch(s.operator){case"=":i[a]=c;break;case"!=":i[a]={$ne:c};break;case">":i[a]={$gt:c};break;case"<":i[a]={$lt:c};break;case">=":i[a]={$gte:c};break;case"<=":i[a]={$lte:c};break;case"like":i[a]={$regex:c.replace(/%/g,".*"),$options:"i"};break;case"in":let d=s.value;Array.isArray(d)||(d=typeof d=="string"&&d.includes(",")?d.split(",").map(m=>m.trim()):[d]);let l=d.map(m=>W(r,u,a,m));i[a]={$in:l};break;case"not in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(m=>m.trim()):[f]);let p=f.map(m=>W(r,u,a,m));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 y=s.value;if(typeof y=="string"&&(y=y.split(",").map(m=>m.trim())),Array.isArray(y)&&y.length===2){let m=W(r,u,a,y[0]),b=W(r,u,a,y[1]);i[a]={$gte:m,$lte:b}}break;case"_is_null":let g=c===!0||c==="true";i[a]=g?{$eq:null}:{$ne:null};break;case"_is_not_null":let h=c===!0||c==="true";i[a]=h?{$ne:null}:{$eq:null};break}}return no(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 rn(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]=W(r,t,n,o);break;case"_neq":{let l=W(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=>W(r,t,n,p));e[n]={$in:f};break}case"_not_in":case"_nin":let s=o;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(l=>l.trim()):[s]);let a=s.map(l=>W(r,t,n,l));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:W(r,t,n,o)};break;case"_gte":e[n]={$gte:W(r,t,n,o)};break;case"_lt":e[n]={$lt:W(r,t,n,o)};break;case"_lte":e[n]={$lte:W(r,t,n,o)};break;case"_is_null":let u=o===!0||o==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let c=o===!0||o==="true";e[n]=c?{$ne:null}:{$eq:null};break;case"_between":let d=o;if(typeof d=="string"&&(d=d.split(",").map(l=>l.trim())),Array.isArray(d)&&d.length===2){let l=W(r,t,n,d[0]),f=W(r,t,n,d[1]);e[n]={$gte:l,$lte:f}}break}}var Jn=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 H(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 cn="__mongoFoldTextTriples";function ze(r,e){if(!r)return{};let t={};return Ot(r,t,e),we(t),t}function uo(r,e){if(!r)return{};let t={};return Kn(r,t,e),we(t),t}function pe(r,e,t){if(!e)return{};let n=new ie,{node:i}=de(e,t,r,n);return ze(i,{metadata:r,rootTable:t})}function un(r,e,t){if(!e)return{};let n=new ie,{node:i}=de(e,t,r,n);return uo(i,{metadata:r,rootTable:t})}function Ot(r,e,t){switch(r.kind){case"true":return;case"false":fe(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let i=r.children.map(o=>{let s={};return Ot(o,s,t),we(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}fe(e,...i);return}case"or":{let i=r.children.map(s=>{let a={};return Ot(s,a,t),we(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),we(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=>W(t.metadata,t.rootTable,n,o);switch(r.op){case"eq":Z(e,n,i(r.value));return;case"neq":{let o=i(r.value);qn(t,n)?fe(e,{[n]:{$ne:null}},{[n]:{$ne:o}}):Z(e,n,{$ne:o});return}case"gt":Z(e,n,{$gt:i(r.value)});return;case"gte":Z(e,n,{$gte:i(r.value)});return;case"lt":Z(e,n,{$lt:i(r.value)});return;case"lte":Z(e,n,{$lte:i(r.value)});return;case"in":{let o=Lr(r.value).map(i);Z(e,n,{$in:o});return}case"not_in":{let o=Lr(r.value).map(i);qn(t,n)?fe(e,{[n]:{$ne:null}},{[n]:{$nin:o}}):Z(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&&Z(e,n,{$gte:i(o[0]),$lte:i(o[1])});return}case"is_null":Z(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":Wn(e,n,String(r.value),"contains");return;case"starts_with":Wn(e,n,String(r.value),"starts");return;case"ends_with":Wn(e,n,String(r.value),"ends");return}}function Kn(r,e,t){switch(r.kind){case"true":fe(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let i=r.children.map(s=>{let a={};return Kn(s,a,t),we(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 Kn(o,s,t),we(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}fe(e,...i);return}case"not":Ot(r.child,e,t);return;case"compare":fo(r,e,t);return;case"relation_exists":{Z(e,r.joinId,r.negate?{$ne:null}:{$eq:null});return}}}function fo(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached false renderer \u2014 expected relation resolver to handle it. Filter silently skipped.`);return}if(r.op==="is_null"){Z(e,n,r.value===!0?{$ne:null}:{$eq:null});return}let i={};Dr(r,i,t),we(i);let o={$nor:[i]};qn(t,n)?fe(e,o,{[n]:{$ne:null}}):fe(e,o)}function Z(r,e,t){r[e]===void 0?r[e]=t:(fe(r,{[e]:r[e]},{[e]:t}),delete r[e])}function fe(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 Lr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function po(r){return r==="_id"?"$_id":`$${r}`}function Wn(r,e,t,n){let i=po(e),o=r[cn]??[];o.push({ref:i,needle:t,mode:n}),r[cn]=o}function we(r){let e=r[cn];if(delete r[cn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:tn(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}async function $e(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return pe(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!ne(r,o))return pe(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>$e(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=>$e(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:{$or:d}}if(r._not)return await Qn(r._not,e,t,n)||{};let{fieldFilters:s,relationFilters:a}=H(r,i),u=[];if(s&&Object.keys(s).length>0){let c=pe(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(a&&Object.keys(a).length>0)for(let[c,d]of Object.entries(a)){let l=await go(c,d,e,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 Qn(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return un(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!ne(r,o))return un(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>Qn(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=>Qn(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 $e(r._not,e,t,n);let{fieldFilters:s,relationFilters:a}=H(r,i),u=[];if(s&&Object.keys(s).length>0){let c=un(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(a&&Object.keys(a).length>0)for(let[c,d]of Object.entries(a)){let l=await yo(c,d,e,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 go(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"?ho(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 ho(r,e,t,n,i,o,s){let a=V(e)||t,u=fn(r),c=pn(u);if(c!==null)return c?{[a]:null}:{[a]:{$ne:null}};let d=zn(u);if(d!==null){let y=gn(d.value);if(d.op==="eq")return{[a]:y};if(d.op==="neq")return{[a]:{$ne:y}};if(d.op==="in")return{[a]:{$in:y}};if(d.op==="not_in")return{$and:[{[a]:{$nin:y}},{[a]:{$ne:null}}]}}let l=await dn(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(y=>y._id).filter(Boolean);return p.length===0?{__impossible__:!0}:{[a]:{$in:p}}}async function yo(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 mo(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 mo(r,e,t,n,i,o,s){let a=V(e)||t,u=fn(r),c=pn(u);if(c!==null)return c?{[a]:{$ne:null}}:{[a]:null};let d=zn(u);if(d!==null){let y=gn(d.value);if(d.op==="eq")return{$and:[{[a]:{$ne:y}},{[a]:{$ne:null}}]};if(d.op==="neq")return{[a]:y};if(d.op==="in")return{$and:[{[a]:{$nin:y}},{[a]:{$ne:null}}]};if(d.op==="not_in")return{[a]:{$in:y}}}let l=await dn(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(y=>y._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=q(e)||t,u=fn(r),c=pn(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 dn(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=fn(r),c=pn(u);if(c!==null){let g=await Un(s,a,n,null);return c?g.length===0?{}:{_id:{$nin:g}}:g.length===0?{__impossible__:!0}:{_id:{$in:g}}}let d=zn(u);if(d!==null){let g=gn(d.value),h=Array.isArray(g)?g:[g],m=await Un(s,a,n,{_id:{$in:h}});return m.length===0?{__impossible__:!0}:{_id:{$in:m}}}let l=await dn(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 y=await Un(s,a,n,{_id:{$in:p}});return y.length===0?{__impossible__:!0}:{_id:{$in:y}}}async function dn(r,e,t,n,i){let o=new Set((t?.relations??[]).map(s=>s.propertyName));return ne(r,o)?$e(r,e,n,i):pe(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 Un(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 fn(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function pn(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 gn(r){if(Array.isArray(r))return r.map(e=>gn(e));if(typeof r!="string")return r;try{return new Jn.ObjectId(r)}catch{return r}}function zn(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof Jn.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,y]of Object.entries(n))if(typeof y=="object"&&y!==null){let g=Object.keys(y)[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]=y:a[p]=y}else s[p]=y;if(Object.keys(s).length>0){let p={};for(let[y,g]of Object.entries(s))if(typeof g=="object"&&g!==null)for(let[h,m]of Object.entries(g))rn(r,p,e,y,h,m);else p[y]=g;Object.keys(p).length>0&&o.push({$match:p})}let c=r?.tables?.get(e)?.relations||[],d=[];for(let[p,y]of Object.entries(a))if(!i.relations.some(h=>h.propertyName===p)){let h=c.find(m=>m.propertyName===p);if(h){let m="",b="";if(h.type==="many-to-one"||h.type==="one-to-one")m=V(h)||h.propertyName,b="_id";else if(h.type==="one-to-many")m="_id",b=q(h)||h.propertyName;else if(h.type==="many-to-many")continue;let w=h.type==="one-to-many"||h.type==="many-to-many";d.push({propertyName:p,targetTable:h.targetTableName,localField:m,foreignField:b,type:w?"many":"one",nestedFields:[]})}}let l=[...i.relations,...d];for(let p of l){let y=a[p.propertyName],g=p.nestedFields&&p.nestedFields.length>0?await At(r,p.targetTable,p.nestedFields,y):y?await At(r,p.targetTable,["_id"],y):[];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}}),y&&(Ve(y)||o.push({$match:{[p.propertyName]:{$ne:null}}})))}let f=c.filter(p=>!l.some(y=>y.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();hn();async function yn(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__",Ce="__targetId__",Ye="__enfyra_target__",Pt="__enfyra_top_n_documents__",Xe=class{constructor(e,t,n,i=new Se){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 y=l[p],g=this.normalizeMetadata()?.tables?.get(f);if(!g)break;let h=g.relations?.find(w=>w.propertyName===y);if(!h)break;let m=h.targetTableName||h.targetTable,b=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(b)){s.add(b);let w=V(h)||h.propertyName,C=p===0?null:`__sort_${l.slice(0,p).join("_")}`,T=C?`${C}.${w}`:w;o.push({$lookup:{from:m,localField:T,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}f=m}}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(y=>y.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 y=t.relations?.find(g=>g.propertyName===p);y&&(y.type==="many-to-one"||y.type==="one-to-one"&&!y.isInverse)&&(s||(o[V(y)||y.propertyName]=1))}),s||(o._id=1);let a=[];i.forEach((f,p)=>{let y=t.relations?.find(b=>b.propertyName===p);if(!y)return;let g=y.targetTableName||y.targetTable;if(!g)return;let h,m;y.type==="many-to-one"||y.type==="one-to-one"?Ie(y)?(h="_id",m=q(y)||y.propertyName):(h=V(y)||y.propertyName,m="_id"):y.type==="one-to-many"?(h="_id",m=q(y)||y.propertyName):y.type==="many-to-many"&&(y.isInverse?(h="_id",m=y.mappedBy):(h=y.propertyName,m="_id")),a.push({relationName:p,type:y.type,targetTable:g,fields:f,isInverse:y.isInverse,fkColumn:y.foreignKeyColumn,mappedBy:y.mappedBy,junctionTableName:y.junctionTableName,junctionSourceColumn:y.junctionSourceColumn,junctionTargetColumn:y.junctionTargetColumn,localField:h,foreignField:m})});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?pe(this.normalizeMetadata(),i.userFilter,e):null,s=this.buildSortFromTokens(i?.userSort),a=await K(t,c=>{let d={_id:{$in:c}};o&&Object.keys(o).length>0&&Object.assign(d,o);let l={projection:n.projection};return s&&(l.sort=s),this.runQuery(()=>this.db.collection(e).find(d,l).toArray())}),u=this.applyReadFallback(a,n);return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(t),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,n,i,o){let s=i.projection?{...i.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let a=this.uniqueValues(n.map(m=>this.toObjectId(m))),u=o?.userFilter?pe(this.normalizeMetadata(),o.userFilter,e):null,c=o?.userLimit,d=o?.userPage,l=this.hasDottedSort(o?.userSort);if(c!==void 0&&c>0){let m=d?(d-1)*c:0;if(l)throw new Error(`Dotted sort is not supported for batch relation '${o?.relationName}'`);let b=this.buildStableSort(o?.userSort),w=await K(a,async C=>{let T={[t]:{$in:C}};u&&Object.keys(u).length>0&&Object.assign(T,u);let k=[{$match:T}];this.appendTopNStages(k,t,b,m,c),k.push({$sort:{[t]:1,...b}}),this.appendPartitionProjection(k,s,[t]);let x=await this.runQuery(()=>this.db.collection(e).aggregate(k).toArray());return this.applyReadFallback(x,i)});return{docs:w,groupKeyField:t,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:w.length}}}if(s&&(s[t]=1),l){let m=[],b=await yn(a,async w=>{let C={[t]:w};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 w of b.values())for(let C of w)m.push(C);return{docs:m,groupKeyField:t,stats:{strategy:"per-parent-dotted-sort",roundtrips:a.length,concurrencyWaves:Math.ceil(a.length/Me),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.length}}}let f={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(f,u);let p=this.buildSortFromTokens(o?.userSort)||{_id:1},y={projection:s,sort:p},g=await K(a,m=>this.runQuery(()=>this.db.collection(e).find({[t]:{$in:m},...u||{}},y).toArray())),h=this.applyReadFallback(g,i);return{docs:h,groupKeyField:t,stats:{strategy:"batch-in",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:h.length}}}postProcessInverseChild(e,t,n){n||delete e[t]}m2mSortCanUseJunction(e){return this.parseSortTokens(e).every(t=>t.field==="_id")}async loadM2MTargets(e,t,n){if(t.length===0)return[];let i=n.projection?{projection:n.projection}:void 0,o=await K(t,s=>this.runQuery(()=>this.db.collection(e).find({_id:{$in:s}},i).toArray()));return this.applyReadFallback(o,n)}async fetchM2MTopK(e,t,n,i,o,s,a){if(this.hasDottedSort(t.userSort))throw new Error(`Dotted sort is not supported for batch relation '${t.relationName}'`);let u=new Map;for(let m of e)u.set(this.keyOf(m),[]);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(m=>m.field==="_id")?.order??1,f=this.buildStableSort(t.userSort),p=await K(e,async m=>{if(d){let C=[{$match:{[n.selfColumn]:{$in:m}}}];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}`,[Ce]:`$${n.otherColumn}`}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(C).toArray())).map(k=>({sourceId:k[se],targetId:k[Ce]}))}let b=[{$match:{[n.selfColumn]:{$in:m}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ye}},{$unwind:`$${Ye}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ye}`,{[se]:`$${n.selfColumn}`,[Ce]:`$${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,[Ce]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(b).toArray())).map(C=>({sourceId:C[se],targetId:C[Ce]}))});if(c){let m=new Map;for(let b of p){let w=this.keyOf(b.targetId);m.has(w)||m.set(w,{_id:b.targetId}),u.get(this.keyOf(b.sourceId))?.push(m.get(w))}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 y=this.uniqueValues(p.map(m=>m.targetId)),g=await this.loadM2MTargets(t.targetTable,y,i),h=new Map(g.map(m=>[this.keyOf(m._id),m]));for(let m of p){let b=h.get(this.keyOf(m.targetId));b&&u.get(this.keyOf(m.sourceId))?.push(b)}return{grouped:u,docs:g,stats:{strategy:"m2m-partitioned-edge-loader",roundtrips:this.chunkCount(e)+(y.length>0?this.chunkCount(y):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+g.length,rowsDiscarded:0}}}async fetchM2MEdgeBatch(e,t,n,i,o){let s=new Map;for(let g of e)s.set(this.keyOf(g),[]);let a=!o&&this.m2mSortCanUseJunction(t.userSort),u=this.parseSortTokens(t.userSort).find(g=>g.field==="_id")?.order??1,c=this.buildStableSort(t.userSort),d=await K(e,async g=>{if(a)return(await this.runQuery(()=>this.db.collection(n.junctionName).find({[n.selfColumn]:{$in:g}},{projection:{_id:0,[n.selfColumn]:1,[n.otherColumn]:1},sort:{[n.selfColumn]:1,[n.otherColumn]:u}}).toArray())).map(w=>({sourceId:w[n.selfColumn],targetId:w[n.otherColumn]}));let h=[{$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}`,[Ce]:`$${n.otherColumn}`}]}}}];return o&&Object.keys(o).length>0&&h.push({$match:o}),h.push({$sort:{[se]:1,...c}},{$project:{_id:0,[se]:1,[Ce]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(h).toArray())).map(b=>({sourceId:b[se],targetId:b[Ce]}))});if(i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1){let g=new Map;for(let h of d){let m=this.keyOf(h.targetId);g.has(m)||g.set(m,{_id:h.targetId}),s.get(this.keyOf(h.sourceId))?.push(g.get(m))}return{grouped:s,docs:[],stats:{strategy:a?"m2m-junction-batch":"m2m-filtered-edge-batch",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length,rowsDiscarded:0}}}let f=this.uniqueValues(d.map(g=>g.targetId)),p=await this.loadM2MTargets(t.targetTable,f,i),y=new Map(p.map(g=>[this.keyOf(g._id),g]));for(let g of d){let h=y.get(this.keyOf(g.targetId));h&&s.get(this.keyOf(g.sourceId))?.push(h)}return{grouped:s,docs:p,stats:{strategy:"m2m-edge-loader",roundtrips:this.chunkCount(e)+(f.length>0?this.chunkCount(f):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length+p.length,rowsDiscarded:0}}}async fetchM2M(e,t,n,i,o){let s=n?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=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?pe(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,y=this.hasDottedSort(t.userSort);if(!y)return this.fetchM2MEdgeBatch(u,t,a,o,d);let g=await K(u,k=>this.runQuery(()=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:k}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray()));if(g.length===0)return{grouped:c,docs:[],stats:{strategy:"m2m-batch",roundtrips:this.chunkCount(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:0}};let h=new Set,m=[];for(let k of g){let x=k[a.otherColumn];if(x==null)continue;let _=this.keyOf(x);h.has(_)||(h.add(_),m.push(x))}let b=[],w=new Map;if(p)b=m.map(k=>({_id:k})),this.sortDocsByPk(b);else{let k={_id:{$in:m}};d&&Object.keys(d).length>0&&Object.assign(k,d);let x;if(y){let _=this.buildSortAggregatePipeline(t.targetTable,k,t.userSort);o.projection&&_.push({$project:o.projection}),x=await this.runQuery(()=>this.db.collection(t.targetTable).aggregate(_).toArray())}else{let _=this.buildSortFromTokens(t.userSort)||{_id:1},v=this.projectionWithSortFields(o.projection,t.userSort),j={sort:_};v.projection&&(j.projection=v.projection),x=await K(m,S=>this.runQuery(()=>this.db.collection(t.targetTable).find({_id:{$in:S},...d||{}},j).toArray())),t.userSort?this.sortDocsInMemory(x,t.userSort):this.sortDocsByPk(x),this.removeHiddenFields(x,v.hiddenFields)}b=this.applyReadFallback(x,o)}for(let k of b)w.set(this.keyOf(k._id),k);let C=new Map;for(let k of g){let x=this.keyOf(k[a.selfColumn]),_=this.keyOf(k[a.otherColumn]);w.has(_)&&(C.has(_)||C.set(_,[]),C.get(_).push(x))}for(let k of b){let x=C.get(this.keyOf(k._id))||[];for(let _ of x)c.get(_)?.push(k)}let T=p||m.length===0?0:this.chunkCount(m);return{grouped:c,docs:b,stats:{strategy:p?"m2m-junction-batch":"m2m-batch",roundtrips:this.chunkCount(u)+T,ioConcurrency:this.executionBudget.concurrency,rowsTransferred: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 mn(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 Te(l,n,u).execute(e,t,i,o,s)}async function Gn(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 $e(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,h=()=>p?.sortItems?Co(p.sortItems):e.sort?So(e.sort):null,m=p?.sortItems?bo(p.sortItems):[],b=p?.sortItems?_o(p.sortItems):[],w=()=>{!p||m.length===0||wo(n,e.table,p.sortItems,o)},C=()=>{!p||b.length===0||$o(n,e.table,p.sortItems,o)},T=()=>{let S=[...m,...b];S.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(S.map(E=>[E,0]))})};if(!e.mongoFieldsExpanded){w(),C();let S=h();if(S&&n.push({$sort:S}),e.mongoCountOnly?n.push({$count:"count"}):(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit})),T(),e.select){let A={};for(let D of e.select)A[D]=1;n.push({$project:A})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let E=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:E,pipeline:n}:{results:zr(E),pipeline:n}}let{scalarFields:k,relations:x}=e.mongoFieldsExpanded;if(!g){w(),C();let S=h();S&&n.push({$sort:S}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}let _=[];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 B=await At(o,S.targetTable,S.nestedFields??[],A);S.type==="one"&&B.length>0&&B.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:B.length>0?B:void 0}})}else if(A){let B=await At(o,S.targetTable,["_id"],A);S.type==="one"&&B.length>0&&B.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:B.length>0?B: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 _.push(S);if(g){w(),C();let S=h();S&&n.push({$sort:S}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}T(),await Qr(o,n,e.table,k,[...x]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let v=performance.now(),j=await r.aggregate(n).toArray();if(e.debugTrace?.dur("db_execute",v,{table:e.table}),e.mongoCountOnly)return{results:j,pipeline:n};if(_.length>0&&j.length>0){let S=e.deep||{},E=_.map(D=>{let $=o?.tables?.get(e.table)?.relations?.find(J=>J.propertyName===D.propertyName),R=S[D.propertyName],N=R?.fields!=null?Array.isArray(R.fields)?R.fields:String(R.fields).split(",").map(J=>J.trim()).filter(Boolean):D.nestedFields&&D.nestedFields.length>0?D.nestedFields:["_id"];return{relationName:D.propertyName,type:$?.type,targetTable:D.targetTable,fields:N,isInverse:$?.isInverse,mappedBy:$?.mappedBy,junctionTableName:$?.junctionTableName,junctionSourceColumn:$?.junctionSourceColumn,junctionTargetColumn:$?.junctionTargetColumn,localField:D.localField,foreignField:D.foreignField,userFilter:R?.filter,userSort:R?.sort,userLimit:R?.limit!==void 0?Number(R.limit):void 0,userPage:R?.page!==void 0?Number(R.page):void 0,nestedDeep:R?.deep}}),A=To(o);A&&await mn(i,j,E,A,3,0,e.table,o,e.debugTrace,t.mongoPhysicalMigrationService)}return{results:zr(j),pipeline:n}}function Yn(r){return`__sort_count_${r.relationName||r.field}`}function Xn(r){return`__sort_${r.function}_${r.relationName||r.field}_${r.aggregateField||"value"}`}function bo(r){return r.filter(e=>e.function==="count").map(Yn)}function _o(r){return r.filter(e=>e.function==="max"||e.function==="min").map(Xn)}function wo(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=Yn(s);if(!(!a||!c)){if(a.type==="one-to-many"){let l=q(a)||u;r.push({$lookup:{from:c,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${l}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let l=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 $o(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="max"&&s.function!=="min")continue;let a=s.relationMeta,u=s.relationName||s.field,c=a?.targetTableName||a?.targetTable,d=n?.tables?.get(c),l=d?.columns?.find(h=>h.isPrimary)?.name||(d?.columns?.some(h=>h.name==="_id")?"_id":"id"),f=s.aggregateField,p=f==="id"&&d?.columns?.some(h=>h.name==="_id")?"_id":f,y=Xn(s),g=s.function==="min"?"$min":"$max";if(!(!a||!c||!f)){if(a.type==="one-to-many"){let h=q(a)||u;r.push({$lookup:{from:c,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${h}`,"$$localId"]}}},{$group:{_id:null,value:{[g]:`$${p}`}}}],as:y}}),r.push({$addFields:{[y]:{$arrayElemAt:[`$${y}.value`,0]}}});continue}if(a.type==="many-to-many"){let h=Ne(e,a);if(!h)continue;let m=`${y}_junction`;r.push({$lookup:{from:h.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${h.selfColumn}`,"$$localId"]}}},{$project:{_id:0,targetId:`$${h.otherColumn}`}}],as:m}}),r.push({$lookup:{from:c,let:{targetIds:`$${m}.targetId`},pipeline:[{$match:{$expr:{$in:[`$${l}`,"$$targetIds"]}}},{$group:{_id:null,value:{[g]:`$${p}`}}}],as:y}}),r.push({$addFields:{[y]:{$arrayElemAt:[`$${y}.value`,0]}}}),r.push({$project:{[m]:0}})}}}}function To(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(i=>({name:i.name,type:i.type})),relations:n.relations||[]}:null}:null}function So(r){let e={};for(let t of r){let n=t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function Co(r){let e={};for(let t of r){let n=t.function==="count"?Yn(t):t.function==="max"||t.function==="min"?Xn(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(X)}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(ko(o,i,e));return{scalarFields:t,relations:n}}function ko(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=q(n)||r.propertyName,s=!0):(i=n&&V(n)||r.propertyName,o="_id",s=!1):r.relationType==="one-to-many"?(i="_id",o=n&&q(n)||r.propertyName,s=!0):n?.mappedBy?(i="_id",o=n.mappedBy,s=!0):(i=r.propertyName,o="_id",s=!1);let a=r.relationType==="one-to-many"||r.relationType==="many-to-many",u=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();Et();function bn(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("."),y=f.substring(0,p),g=f.substring(p+1);if(!o.relations?.some(m=>m.propertyName===y))continue;c.has(y)||c.set(y,[]),c.get(y).push(g)}else if(o.relations?.some(y=>y.propertyName===f))c.has(f)||c.set(f,[u]);else{if(!o.columns?.some(g=>g.name===f))continue;d.push(f)}}if(d.includes("*")){i.nodes.push({kind:"wildcard"});for(let l of o.relations||[])c.has(l.propertyName)||c.set(l.propertyName,[u])}else for(let l of d)i.nodes.push({kind:"scalar",name:l});for(let[l,f]of c.entries()){let p=o.relations?.find(h=>h.propertyName===l);if(!p)continue;let y=p.targetTableName||p.targetTable,g={kind:"relation",propertyName:l,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:y,children:Gr(f,y,t)};if(p.type==="many-to-one"||p.type==="one-to-one"){let h=n.registerWithParent(e,l,t,"left",null,"data");g.joinId=h}i.nodes.push(g)}return i}function 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),y=l.substring(f+1);if(!n.relations?.some(h=>h.propertyName===p))continue;a.has(p)||a.set(p,[]),a.get(p).push(y)}else if(n.relations?.some(p=>p.propertyName===l))a.has(l)||a.set(l,[s]);else{if(!n.columns?.some(y=>y.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(y=>y.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}ue();ue();var Ro=new Set(["_and","_or","_not"]);function Yr(r,e){return r?.tables?.get(e)??null}function xo(r,e,t){return Yr(r,e)?.columns?.find(n=>n.name===t)}function Zn(r,e,t){return Yr(r,e)?.relations?.find(n=>n.propertyName===t)}function Fo(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 er(r,e,t,n){if(xo(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(Ro.has(n)){Oe(i,e,t);continue}if(n.startsWith("_"))continue;let o=Zn(t,e,n);if(o){let s=o.targetTableName||o.targetTable;s&&Oe(i,s,t);continue}er(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=Fo(o);if(s){if(s.functionName==="count")continue;let c=Zn(t,e,s.relationName),d=c?.targetTableName||c?.targetTable;d&&er(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){er(t,u,d,"sort");break}let f=Zn(t,u,d);if(!f)break;u=f.targetTableName||f.targetTable||u}}}var ee=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),y=null;p&&l&&(y=bn(p,t,c,f));let g=!1,h=null;if(i&&l){Oe(i,t,c);let S=de(i,t,c,f);h=S.node,g=S.hasRelationFilters}let m=this.parseSort(o);l&&_n(m,t,c);let b=[],w=!1;for(let S of m){let E=S.startsWith("-"),A=E?S.substring(1):S,D=E?"desc":"asc";if(l){let B=this.parseRelationAggregateSort(t,l,A,c);if(B){b.push({joinId:null,field:A,direction:D,fullPath:A,function:B.functionName,relationName:B.relationName,aggregateField:B.aggregateField,relationMeta:B.relationMeta});continue}this.assertLocalSortField(t,l,A)}b.push({joinId:null,field:A,direction:D,fullPath:A})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let C=this.parseLimit(a),T=this.parsePage(s),k=T!==void 0&&C!==void 0?(T-1)*C:void 0,x=this.parseMeta(u),_=x.includes("totalCount")||x.includes("*"),v=x.includes("filterCount")||x.includes("*"),j=f.getAll();return{table:t,dbType:d,rawFields:p,rawFilter:i??null,joins:j,sortItems:b,limit:C,offset:k,needsTotalCount:_,needsFilterCount:v,hasRelationFilters:g,hasRelationSort:w,filterTree:h,fieldTree:y}}parseFields(e){if(e)return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):e.split(",").map(t=>t.trim()).filter(Boolean)}parseSort(e){return e?(Array.isArray(e)?e:e.split(",")).map(n=>n.trim()).filter(Boolean):[]}parseLimit(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;if(!Number.isNaN(t))return t<0?0:t}parsePage(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;return Number.isNaN(t)?void 0:t}parseMeta(e){return e?Array.isArray(e)?e:e.split(",").map(t=>t.trim()).filter(Boolean):[]}assertLocalSortField(e,t,n){if(n.includes("."))throw new I(`Sort field '${n}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let i=t.columns?.some(s=>s.name===n),o=n==="id"&&t.columns?.some(s=>s.name==="_id");if(!i&&!o)throw new I(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationAggregateSort(e,t,n,i){let o=n.match(/^_(count|max|min)\(([^)]+)\)$/);if(!o){if(/^_(count|max|min)\(/.test(n))throw new I(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName), _max(relationName.fieldName), or _min(relationName.fieldName).`);return null}let s=o[1],a=o[2].trim();if(s==="count"){let h=a;if(!h||h.includes("."))throw new I(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let m=t.relations?.find(b=>b.propertyName===h);if(!m)throw new I(`Sort relation '${h}' does not exist on '${e}'.`);if(m.type!=="one-to-many"&&m.type!=="many-to-many")throw new I(`Sort function '_count(${h})' is only supported for list relations on '${e}'.`);return{functionName:s,relationName:h,relationMeta:m}}let u=a.indexOf(".");if(u<=0||u!==a.lastIndexOf("."))throw new I(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let c=a.slice(0,u).trim(),d=a.slice(u+1).trim();if(!c||!d)throw new I(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let l=t.relations?.find(h=>h.propertyName===c);if(!l)throw new I(`Sort relation '${c}' does not exist on '${e}'.`);if(l.type!=="one-to-many"&&l.type!=="many-to-many")throw new I(`Sort function '_${s}(${c}.${d})' is only supported for list relations on '${e}'.`);let f=l.targetTableName||l.targetTable,p=i?.tables?.get(f);if(!p)throw new I(`Sort function '${n}' references unknown target table '${f}' on '${e}'.`);let y=p.columns?.find(h=>h.name===d),g=d==="id"&&p.columns?.some(h=>h.name==="_id");if(!y&&!g)throw new I(`Sort field '${d}' does not exist on '${f}' for function '_${s}(${c}.${d})'.`);if(y?.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)}};ue();var vo=new Set(["int","integer","bigint","smallint","tinyint","float","double","decimal","numeric","real","number"]),Io=new Set(["date","datetime","timestamp","timestamptz","timestamp with time zone","timestamp without time zone"]),No=new Set(["hour","day","week","month","year"]),Eo=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 Mo(r,e){let t=r?.tables?.get(e);return t||O("aggregate",`Table "${e}" metadata is not available`),t}function Xr(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 Oo(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 Ao(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=Mo(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,h)=>{let m=`aggregate.dimensions[${h}]`;(!et(g)||typeof g.field!="string"||g.field.length===0)&&O(m,"Aggregate dimension requires a field");let b=Xr(n,g.field,`${m}.field`);return s.has(g.field)&&O(`${m}.field`,`Duplicate aggregate dimension "${g.field}"`),s.add(g.field),g.bucket===void 0?(g.timezone!==void 0&&O(`${m}.timezone`,"Aggregate timezone requires a bucket"),{field:g.field,outputKey:g.field,column:b}):((typeof g.bucket!="string"||!No.has(g.bucket))&&O(`${m}.bucket`,"Aggregate bucket must be hour, day, week, month, or year"),Io.has(String(b.type).toLowerCase())||O(`${m}.bucket`,`Aggregate bucket requires a date field, but "${g.field}" is "${b.type}"`),{field:g.field,outputKey:g.field,bucket:g.bucket,timezone:Oo(g.timezone,`${m}.timezone`),column:b})}),u=new Set,c=Object.entries(o).map(([g,h])=>{let m=`aggregate.measures.${g}`;(!g||!et(h))&&O(m,"Aggregate measure must be an object");let b=Object.entries(h).filter(([k])=>k!=="as");b.length!==1&&O(m,"Aggregate measure must define exactly one operation");let[w,C]=b[0];Eo.has(w)||O(m,`Unsupported aggregate measure "${w}"`),(typeof C!="string"||C.length===0)&&O(m,"Aggregate measure field must be a non-empty string");let T=Xr(n,C,`${m}.${w}`);return(u.has(g)||s.has(g))&&O(m,`Aggregate output key "${g}" is duplicated`),u.add(g),["sum","avg","min","max"].includes(w)&&!vo.has(String(T.type).toLowerCase())&&O(m,`Aggregate ${w} requires a numeric field, but "${C}" is "${T.type}"`),{outputKey:g,operation:w,field:C,column:T}}),d=r.sort===void 0?[]:r.sort;Array.isArray(d)||O("aggregate.sort","Aggregate sort must be an array");let l=new Set([...s,...u]),f=d.map((g,h)=>{let m=`aggregate.sort[${h}]`;return(!et(g)||typeof g.field!="string"||!l.has(g.field))&&O(m,"Aggregate sort field must reference a dimension or measure output"),g.direction!=="asc"&&g.direction!=="desc"&&O(`${m}.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),y=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(y)||y<=0)&&O("aggregate.page","Aggregate page must be a positive integer"),{tableName:e,filter:Ao(r.filter,"aggregate.filter"),dimensions:a,measures:c,sort:f,page:y,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 ee;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 ee().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:"mongodb"}),o=i.hasRelationFilters?await $e(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(X)}}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(X);let{results:a,pipeline:u}=await Gn(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 Gn(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=i,n}};var wn=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}};ue();ae();var Po=["_and","_or","_not"];function ge(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>ge(e));for(let e of Object.keys(r))if(Po.includes(e)||typeof r[e]=="object"&&r[e]!==null&&ge(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 jo(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function $n(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 Bo(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)||$n(r,t,i),e}function ei(r,e,t,n,i,o,s){let a=i&&!e.includes(".")?`${i}.${e}`:e,u=ke(a,o??"postgres"),c=$n(e,i,s),d=Bo(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,jo(t),n)}}function Lo(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(Lo(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=ke(c,i??"postgres");$n(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=ke(u,i??"postgres");$n(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 rr(r,e,t){return`${F(r,t)}.${F(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 ir(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=rr(e,d.foreignKeyColumn,n),p=u.id;if(p&&typeof p=="object"){let y=rt(p._is_null),g=rt(p._is_not_null);if(y===!0)s.push(`${l} IS NULL`);else if(y===!1)s.push(`${l} IS NOT NULL`);else if(g===!0)s.push(`${l} IS NOT NULL`);else if(g===!1)s.push(`${l} IS NULL`);else if(p._eq!==void 0){let h=Re(p._eq,n);s.push(`${l} = ${h}`)}else if(p._neq!==void 0){let h=Re(p._neq,n);s.push(`${l} != ${h}`)}else if(p._in!==void 0){let m=(Array.isArray(p._in)?p._in:[p._in]).map(b=>Re(b,n)).join(", ");s.push(`${l} IN (${m})`)}else if(p._not_in!==void 0||p._nin!==void 0){let h=p._not_in??p._nin,b=(Array.isArray(h)?h:[h]).map(w=>Re(w,n)).join(", ");s.push(`${l} NOT IN (${b})`)}else if(p._gt!==void 0){let h=Re(p._gt,n);s.push(`${l} > ${h}`)}else if(p._gte!==void 0){let h=Re(p._gte,n);s.push(`${l} >= ${h}`)}else if(p._lt!==void 0){let h=Re(p._lt,n);s.push(`${l} < ${h}`)}else if(p._lte!==void 0){let h=Re(p._lte,n);s.push(`${l} <= ${h}`)}}}}}return s}function or(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 tr(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(or(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}=H(c,n),f=await ir(e,t,n,i,o,l);u.push({fieldFilters:d,subqueries:f})}s.push(u)}else if(or(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}=H(a,n),d=await ir(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 nr(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 Tn(r,e,t,n,i,o,s){let a=ti(e,i),u=ti(n,o),c=`${F(r,s)}.${F(e,s)}`,d=`${F(t,s)}.${F(n,s)}`;if(s==="postgres"){if(a&&!u)return`${c} = ${d}::uuid`;if(!a&&u)return`${c}::uuid = ${d}`}return`${c} = ${d}`}async function 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(y=>c.has(y)))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(Tn(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(Tn(a.junctionTableName,a.junctionTargetColumn,u,"id",f,d,o))).whereRaw(Tn(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(Tn(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 tr(c._or,r,n,i,o,s);e.where(function(){nr(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 tr(t._or,r,n,i,o,s);e.where(function(){nr(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(or(p)){let y=r(n).select(`${n}.id`);await Pe(r,y,p,n,i,o,s),f.push({idSubquery:y})}else{let{fieldFilters:y,relationFilters:g}=H(p,i),h=await ir(r,n,i,o,s,g);f.push({fieldFilters:y,subqueries:h})}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 tr(c._or,r,n,i,o,s);e.whereNot(function(){nr(this,f,n,i,o)});return}let{fieldFilters:d,relationFilters:l}=H(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 y=await Bt(r,n,f,p,i,o,s);if(y===null){let g=i.relations.find(h=>h.propertyName===f);if(g&&g.foreignKeyColumn){let h=rr(n,g.foreignKeyColumn,o),b=p.id;if(b&&typeof b=="object"){let w=rt(b._is_null),C=rt(b._is_not_null);if(w===!0)e.whereRaw(`${h} IS NOT NULL`);else if(w===!1)e.whereRaw(`${h} IS NULL`);else if(C===!0)e.whereRaw(`${h} IS NULL`);else if(C===!1)e.whereRaw(`${h} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${h} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${h} = ?`,[b._neq]);else if(b._in!==void 0){let T=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${h} NOT IN (${T.map(()=>"?").join(", ")})`,T)}else if(b._not_in!==void 0||b._nin!==void 0){let T=b._not_in??b._nin,k=Array.isArray(T)?T:[T];e.whereRaw(`${h} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${y})`)}return}let{fieldFilters:a,relationFilters:u}=H(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=rr(n,f.foreignKeyColumn,o),g=d.id;if(g&&typeof g=="object"){let h=rt(g._is_null),m=rt(g._is_not_null);if(h===!0)e.whereRaw(`${p} IS NULL`);else if(h===!1)e.whereRaw(`${p} IS NOT NULL`);else if(m===!0)e.whereRaw(`${p} IS NOT NULL`);else if(m===!1)e.whereRaw(`${p} IS NULL`);else if(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,w=Array.isArray(b)?b:[b];e.whereRaw(`${p} NOT IN (${w.map(()=>"?").join(", ")})`,w)}}}}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]),h=Dt(n,a,u,f[1]);r=r.whereBetween(o.field,[g,h])}break;case"_is_null":r=c===!0||c==="true"?r.whereNull(o.field):r.whereNotNull(o.field);break;case"_is_not_null":r=c===!0||c==="true"?r.whereNotNull(o.field):r.whereNull(o.field);break}}return r}function 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=`${F(e,n)}.${F(s,n)}`,l;if(c===null)l="NULL";else if(typeof c=="string"){let f=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,p=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(y=>typeof y=="string"?`'${y.replace(/'/g,"''")}'`:String(y)).join(", ");i.push(`${d} IN (${p})`)}else if(u==="_not_in"||u==="_nin"){let p=(Array.isArray(c)?c:[c]).map(y=>typeof y=="string"?`'${y.replace(/'/g,"''")}'`:String(y)).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=`${F(e,n)}.${F(s,n)}`,c;a===null?c="NULL":typeof a=="string"?c=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?c=a?"true":"false":c=String(a),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}}ar();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(()=>(cr(),ii)),u=await a(e,t,n,i,o,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function ur(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||z(r.propertyName);if(!s)return null;let a=l=>F(l,i),u=n?.tables?.get(o),d=(u?G(u):null)?.name||"id";return`(SELECT ${a(o)}.${a(e)} FROM ${a(o)} WHERE ${a(o)}.${a(d)} = ${a(t)}.${a(s)})`}qt();async function ai(r,e,t,n,i){let o={};if(n.includes("totalCount")||n.includes("*")){let s=await r(t).count("* as count").first();o.totalCount=Number(s?.count||0)}if(n.includes("filterCount")||n.includes("*")){let a=await e.clone().clearSelect().clearOrder().clear("limit").clear("offset").countDistinct(`${t}.id as count`).first();o.filterCount=Number(a?.count||0)}return o}var je=class r{constructor(e,t,n,i){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=i;this.logger=new wn(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 $=new ee;e={...e,plan:$.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:this.dbType})}}let o=e.plan,s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,u=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,c=o.rawFields&&o.rawFields.length>0&&!o.rawFields.includes("*");if(o.joins.length===0&&!o.hasRelationFilters&&!o.hasRelationSort&&!u&&!a&&c){i&&i.setQueryPath("simple");let $=await this.executeSimple(e,o);return i&&i.dur("sql_executor",t,{table:e.tableName}),$}let l={table:e.tableName,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?l.fields=e.fields:typeof e.fields=="string"&&(l.fields=e.fields.split(",").map($=>$.trim())));let f=e.filter;if(e.filter&&!ge(e.filter)){l.where=[];for(let[$,R]of Object.entries(e.filter))if(typeof R=="object"&&R!==null)for(let[N,J]of Object.entries(R)){let M;if(N==="_eq")M="=";else if(N==="_neq")M="!=";else if(N==="_in")M="in";else if(N==="_not_in"||N==="_nin")M="not in";else if(N==="_gt")M=">";else if(N==="_gte")M=">=";else if(N==="_lt")M="<";else if(N==="_lte")M="<=";else if(N==="_contains")M="_contains";else if(N==="_starts_with")M="_starts_with";else if(N==="_ends_with")M="_ends_with";else if(N==="_between")M="_between";else if(N==="_is_null")M="_is_null";else if(N==="_is_not_null")M="_is_not_null";else if(N==="_like")M="like";else if(N==="_ilike")M="ilike";else continue;l.where.push({field:$,operator:M,value:J})}else l.where.push({field:$,operator:"=",value:R})}if(e.sort){let $=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(R=>R.trim());l.sort=$.map(R=>{let N=R.trim();return N.startsWith("-")?{field:N.substring(1),direction:"desc"}:{field:N,direction:"asc"}})}else l.sort=[{field:"id",direction:"asc"}];let p=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,y=p===void 0||Number.isNaN(p)?void 0:p<0?0:p,g=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,h=g===void 0||Number.isNaN(g)?void 0:g;h&&y!==void 0?(l.offset=(h-1)*y,l.limit=y):y!==void 0&&(l.limit=y);let m=e.plan?.sortItems??(l.sort??[]).map($=>({joinId:null,field:$.field,direction:$.direction,fullPath:$.field})),b=[],w=[];for(let $ of m){if($.function==="count"){let R={sql:this.buildRelationCountSortSubquery(l.table,$),direction:$.direction};w.push(R);continue}if($.function==="max"||$.function==="min"){let R={sql:this.buildRelationAggregateSortSubquery(l.table,$),direction:$.direction};w.push(R);continue}if($.joinId===null){if($.field.includes(".")&&!e.plan){let N=$.field.split(".")[0];if(this.metadata?.tables?.get(l.table)?.relations?.some(Q=>Q.propertyName===N))continue}let R={field:$.field.includes(".")?$.field:`${l.table}.${$.field}`,direction:$.direction};b.push(R),w.push(R)}else{let R=e.plan?.joins.find(N=>N.id===$.joinId);if(R&&(R.relationType==="many-to-one"||R.relationType==="one-to-one")){let N=si(R.relationMeta,$.field,l.table,this.metadata,this.dbType);if(N){let J={sql:N,direction:$.direction};w.push(J)}}}}let C=[];if(l.fields&&l.fields.length>0||u||a){let $=ur(this.metadata),R=l.fields&&l.fields.length>0?l.fields:["*"],N=await oi(this.knex,l.table,R,$,this.dbType,this.maxQueryDepth,e.deep);N.select.length>0&&(l.select=[...l.select||[],...N.select]),C=N.batchFetchDescriptors||[]}l.where&&(l.where=l.where.map($=>$.field.includes(".")?$:{...$,field:`${l.table}.${$.field}`})),l.sort=b;let T=this.knex(l.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map($=>$.trim()).filter(Boolean),x=k.includes("filterCount")||k.includes("*"),_=k.includes("totalCount")||k.includes("*");if(l.select){let $=l.select.map(R=>typeof R=="string"&&R.trim().startsWith("(")?this.knex.raw(R):typeof R=="string"&&/ as /i.test(R)?this.knex.raw(R):R);T=T.select($)}if(x&&T.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),_){let $=F(l.table,this.dbType);T.select(this.knex.raw(`(SELECT COUNT(*) FROM ${$}) as __total_count__`))}let v=["table_definition","column_definition","relation_definition","method_definition"].includes(l.table);if(f&&(ge(f)||Object.keys(f).length>0)){let $=this.metadata?.tables?.get(l.table);(!v&&$&&$.relations&&$.relations.length>0?H(f,$).hasRelations:!1)?await Lt(this.knex,T,f,l.table,$,this.dbType,N=>this.metadata?.tables?.get(N)):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,$))}else l.where&&l.where.length>0&&(T=it(T,l.where,l.table,this.metadata,this.dbType));for(let $ of w)if($.field){let R=$.field.includes(".")?$.field:`${l.table}.${$.field}`;T=T.orderBy(R,$.direction)}else $.sql&&(T=T.orderByRaw(`${$.sql} ${$.direction.toUpperCase()}`));l.groupBy&&(T=T.groupBy(l.groupBy)),l.offset&&(T=T.offset(l.offset)),l.limit!==void 0&&l.limit!==null&&l.limit>0&&(T=T.limit(l.limit));let j=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:l.table,sql:T.toSQL().toNative()});let S;if(e.debugMode&&(S=T.toSQL().toNative().sql),e.debugMode&&i){let $=T.toSQL().toNative();i.setSql($.sql);try{let R=$.sql.replace(/\$\d+/g,"?"),N=await this.knex.raw(`EXPLAIN ${R}`,$.bindings);i.setExplain(this.dbType==="postgres"?N.rows:N[0])}catch(R){i.setExplain({error:String(R)})}}let E,A=performance.now();E=await T,i&&i.dur("db_execute",A,{table:e.tableName});let D=await this.resolveEmptyPageMeta(T,l.table,k,E.length),B=D.filterCount??0;if(j=D.totalCount??0,x&&E.length>0&&(B=Number(E[0].__filter_count__||0),E.forEach($=>{delete $.__filter_count__})),_&&E.length>0&&E[0].__total_count__!==void 0&&(j=Number(E[0].__total_count__||0),E.forEach($=>{delete $.__total_count__})),C&&C.length>0&&E.length>0){let $=ur(this.metadata);if($){let{executeBatchFetches:R}=await Promise.resolve().then(()=>(pr(),li));await R(this.knex,E,C,$,this.maxQueryDepth??3,0,l.table,this.dbType,this.metadata,i)}}if(this.knexService){let $=performance.now();E=await this.knexService.parseResult(E,l.table),i&&i.dur("db_parseResult",$,{table:e.tableName})}else{let $=(R,N)=>{if(!R||!this.metadata)return R;let J=this.metadata.tables?.get(N);if(!J)return R;if(Array.isArray(R))return R.map(Q=>$(Q,N));if(typeof R!="object"||Buffer.isBuffer(R))return R;let M={...R};for(let Q of J.columns)if(Q.type==="simple-json"&&M[Q.name]&&typeof M[Q.name]=="string")try{M[Q.name]=JSON.parse(M[Q.name])}catch{}for(let[Q,Y]of Object.entries(M))if(Y&&typeof Y=="object"&&!Array.isArray(Y)&&!Buffer.isBuffer(Y)){let vn=Y;if(vn.id!==void 0||vn.createdAt!==void 0){let lt=J.relations?.find(ct=>ct.propertyName===Q);lt&&(M[Q]=$(Y,lt.targetTableName))}}else if(Array.isArray(Y)&&Y.length>0&&typeof Y[0]=="object"&&Y[0].id!==void 0){let lt=J.relations?.find(ct=>ct.propertyName===Q);lt&&(M[Q]=Y.map(ct=>$(ct,lt.targetTableName)))}return M};E=$(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:j}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:B}:{}}},...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=G(s)?.name||"id",u=F(e,this.dbType),c=F(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=F(o,this.dbType),f=F(d,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}if(n.type==="many-to-many"){let d=this.resolveManyToManyContract(n,i,e),l=F(d.tableName,this.dbType),f=F(d.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}throw new 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=G(a)?.name||"id",d=G(u)?.name||"id",l=F(e,this.dbType),f=F(c,this.dbType),p=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!p||!n||!s||!o)throw new I(`Sort function '${t.field}' is not supported on '${e}'.`);let y=F(s,this.dbType),g=F(o,this.dbType);if(n.type==="one-to-many"){let h=n.foreignKeyColumn||n.mappedBy;if(!h)throw new I(`Sort function '_${t.function}(${i}.${o})' cannot resolve relation key on '${e}'.`);let m=F(h,this.dbType);return`(SELECT ${p}(${y}.${g}) FROM ${y} WHERE ${y}.${m} = ${l}.${f})`}if(n.type==="many-to-many"){let h=this.resolveManyToManyContract(n,i,e),m=F(h.tableName,this.dbType),b=F(h.sourceColumn,this.dbType),w=F(h.targetColumn,this.dbType),C=F(d,this.dbType);return`(SELECT ${p}(${y}.${g}) FROM ${m} JOIN ${y} ON ${y}.${C} = ${m}.${w} WHERE ${m}.${b} = ${l}.${f})`}throw new I(`Sort function '_${t.function}(${i}.${o})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,n){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new I(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async resolveEmptyPageMeta(e,t,n,i){return i>0||n.length===0?{}:ai(this.knex,e,t,n,!1)}async executeSimple(e,t){let n=e.tableName,i=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],o=this.knex(n).select(i);t.filterTree&&ce(o,t.filterTree,{dbType:this.dbType,rootTable:n});for(let h of t.sortItems){let m=h.field.includes(".")?h.field:`${n}.${h.field}`;o=o.orderBy(m,h.direction)}t.limit!==void 0&&t.limit!==null&&t.limit>0&&(o=o.limit(t.limit)),t.offset!==void 0&&(o=o.offset(t.offset));let s=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(h=>h.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),u=s.includes("totalCount")||s.includes("*");if(a&&o.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),u){let h=F(n,this.dbType);o.select(this.knex.raw(`(SELECT COUNT(*) FROM ${h}) as __total_count__`))}let c=e.debugTrace,d;if(e.debugMode){let h=o.toSQL().toNative();if(d=h.sql,c){c.setSql(h.sql);try{let m=h.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${m}`,h.bindings);c.setExplain(this.dbType==="postgres"?b.rows:b[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=await this.resolveEmptyPageMeta(o,n,s,f.length),y=p.filterCount??0,g=p.totalCount??0;return a&&f.length>0&&(y=Number(f[0].__filter_count__||0),f.forEach(h=>delete h.__filter_count__)),u&&f.length>0&&(g=Number(f[0].__total_count__||0),f.forEach(h=>delete h.__total_count__)),{data:f,...s.length>0&&{meta:{...u?{totalCount:g}:{},...a?{filterCount:y}:{}}},...d!==void 0&&{sql:d}}}async aggregate(e){let t=tt(e.aggregate,e.tableName,e.metadata),n=this.knex(e.tableName),i=F(e.tableName,this.dbType),o=[],s=[];for(let l of t.dimensions){let f=`${i}.${F(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 ${F(l.outputKey,this.dbType)}`)),o.push(p)}for(let l of t.measures){let f=`${i}.${F(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 ${F(l.outputKey,this.dbType)}`))}let u=new ee().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(`${F(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 y=f[p.outputKey];y!=null&&typeof y=="string"&&/^-?\d+(\.\d+)?$/.test(y)&&(f[p.outputKey]=Number(y))}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 kn=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,Rn.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(!kn.ObjectId)return e;if(typeof e=="string")try{return new kn.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(X(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 ee().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(!Array.isArray(e.where))throw new TypeError("Delete conditions must be an array");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 kn.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 X(a)}let i=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),s=i||t.id;return await o(e).where("id",s).first()})}async createMany(e,t){return t.length===0?[]:this.trackQueryMetric("insert_many",e,async()=>this.dbType==="mongodb"?(await this.runMongoMutationInSaga(async()=>typeof this.mongoService.insertManyWithCascade=="function"?this.mongoService.insertManyWithCascade(e,t):Promise.all(t.map(i=>this.mongoService.insertOne(e,i))))).map(i=>X(i)):this.knexService.insertManyWithCascade(e,t))}async insertMany(e,t){return this.createMany(e,t)}async flushBatchInserts(){for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)await this.flushBatchInsertBuffer()}async insertManyBatch(e,t){let n=Array.isArray(t)?t:[t];for(let i of n)this.batchInserts.items.push({table:e,data:i});return this.traceBatchInsert("enqueue",{tableName:e,count:n.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i)),{accepted:!0,batch:!0,count:n.length}}async flushBatchInsertBuffer(){if(this.batchInserts.flushing){await this.batchInserts.flushPromise;return}let e=this.batchInserts.items.splice(0,this.batchInserts.items.length);if(this.batchInserts.timer&&(clearTimeout(this.batchInserts.timer),this.batchInserts.timer=void 0),e.length===0)return;this.batchInserts.flushing=!0;let t=this.executeBatchInsertFlush(e);this.batchInserts.flushPromise=t,await t}async executeBatchInsertFlush(e){let t=Date.now();try{let n=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...n.entries()].map(([i,o])=>({tableName:i,count:o.length}))}),await this.runLimited([...n.entries()],([i,o])=>this.flushBatchInsertTable(i,o)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}finally{this.batchInserts.flushing=!1,this.batchInserts.flushPromise=void 0,this.batchInserts.items.length>0&&(this.batchInserts.timer&&clearTimeout(this.batchInserts.timer),this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(n=>this.logBatchInsertError("QueryBuilder batch insert flush failed",n))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let n=Date.now();await this.runBatchInsertWithIsolation(e,t),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-n})}async runBatchInsertWithIsolation(e,t){if(t.length!==0)try{await(async()=>{if(this.dbType==="mongodb"){await this.runMongoMutationInSaga(async()=>{if(typeof this.mongoService?.insertManyWithCascade=="function"){await this.mongoService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.mongoService.insertOne(e,i.data)))});return}if(typeof this.knexService?.insertManyWithCascade=="function"){await this.knexService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.knexService.insertWithCascade(e,i.data)))})()}catch(n){if(t.length===1){this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,n);return}let i=Math.ceil(t.length/2);await Promise.all([this.runBatchInsertWithIsolation(e,t.slice(0,i)),this.runBatchInsertWithIsolation(e,t.slice(i))])}}groupBatchInsertsByTable(e){let t=new Map;for(let n of e){let i=t.get(n.table);i?i.push(n):t.set(n.table,[n])}return t}async runLimited(e,t){let n=0,i=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;n<e.length;){let o=e[n++];await t(o)}});await Promise.all(i)}readPositiveEnv(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.trunc(n):t}traceBatchInsert(e,t){this.batchInsertTraceFile&&(0,Rn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
52
- `)}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 X(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}};pr();dr();cr();ae();qt();Ge();hn();ue();Je();var ui=new Set(["fields","filter","sort","limit","page","deep"]),Fn=3;function gr(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),xn(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 y=p.startsWith("-")?p.slice(1):p;qo(y,l,t,a,r)}}u.deep&&gr(l,u.deep,t,n+1,i)}}}function qo(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 Uo=new Set(["_and","_or","_not"]);function xn(r,e,t,n){if(!(!r||typeof r!="object"))for(let[i,o]of Object.entries(r)){if(Uo.has(i)){if(Array.isArray(o))for(let c of o)xn(c,e,t,n);else o&&typeof o=="object"&&xn(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>Fn)throw new I(`Filter path exceeds max dotted hops of ${Fn} at '${i}' (relation '${t}' on '${n}')`);let u={};for(let c of Object.keys(o))c.startsWith("_")||(u[c]=o[c]);xn(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],y=f===c.length-1,g=t?.tables?.get(l);if(!g){d=!1;break}if(y)g.columns?.find(m=>m.name===p)?n(l,p,"column")||(d=!1):g.relations?.find(b=>b.propertyName===p)&&(n(l,p,"relation")||(d=!1));else{let h=g.relations?.find(m=>m.propertyName===p);if(!h){d=!1;break}if(!n(l,p,"relation")){d=!1;break}l=h.targetTableName||h.targetTable||l}}d&&o.push(s)}if(o.length!==0)return Array.isArray(r)?o:o.join(",")}Et();Je();Mt();sn();Ke();ue();function Qo(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,onExecutorWorkerCrash:r.onExecutorWorkerCrash,onExecutionFinished:r.onExecutionFinished})),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,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,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 Ni="mongo-fold-text-search.body.txt",kt=null;function Ra(){let n=[mo.join(__dirname,Ni),mo.join(process.cwd(),"dist","kernel","query","utils",Ni)];for(let e of n)try{if(dn.existsSync(e))return dn.readFileSync(e,"utf8")}catch{}return null}function pn(){if(kt!==null)return kt;let n=Ra();return n?(kt=n,kt):(kt=fn(),kt)}var be=require("mongodb");function G(n,e,t,r){if(t==="_id"){if(r instanceof be.ObjectId)return r;if(typeof r=="string")try{return new be.ObjectId(r)}catch{return r}return r}let o=n?.tables?.get(e);if(!o){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof r=="string"&&r.length===24)try{return new be.ObjectId(r)}catch{return r}return r}if(!o.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof r=="string"&&r.length===24)try{return new be.ObjectId(r)}catch{return r}return r}let i=o.columns.find(s=>s.name===t);if(!i){if(o.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof r=="string"&&r.length===24)try{return new be.ObjectId(r)}catch{return r}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof r=="string"&&r.length===24)try{return new be.ObjectId(r)}catch{return r}return r}if(r==null)return r;switch(i.type){case"long":case"bigint":{if(be.Long.isLong(r)&&!r.unsigned)return r;if(typeof r=="number"&&!Number.isSafeInteger(r))throw new TypeError("MongoDB bigint requires an exact integer");if(!["string","number","bigint"].includes(typeof r)&&!be.Long.isLong(r))throw new TypeError("MongoDB bigint requires an integer");let s=String(r);if(!/^[+-]?\d+$/.test(s))throw new TypeError("MongoDB bigint requires an integer");let a=BigInt(s);if(a<-(1n<<63n)||a>=1n<<63n)throw new RangeError("MongoDB bigint exceeds signed 64-bit range");return be.Long.fromBigInt(a)}case"int":case"integer":case"smallint":case"tinyint":return typeof r=="string"?parseInt(r,10):Number(r);case"float":case"double":case"decimal":case"numeric":case"real":return typeof r=="string"?parseFloat(r):Number(r);case"boolean":case"bool":return typeof r=="string"?r==="true"||r==="1":!!r;case"date":case"datetime":case"timestamp":return typeof r=="string"?new Date(r):r;case"objectId":case"ObjectId":if(r instanceof be.ObjectId)return r;if(typeof r=="string")try{return new be.ObjectId(r)}catch{return r}return r;case"uuid":return r;default:return r}}cr();sr();var gn="__mongoFoldTextTriples";function xt(n,e){if(!n)return{};let t={};return Et(n,t,e),at(t),t}function Fa(n,e){if(!n)return{};let t={};return hn(n,t,e),at(t),t}function ce(n,e,t){if(!e)return{};let r=new Te,{node:o}=Me(e,t,n,r);return xt(o,{metadata:n,rootTable:t})}function mn(n,e,t){if(!e)return{};let r=new Te,{node:o}=Me(e,t,n,r);return Fa(o,{metadata:n,rootTable:t})}function Et(n,e,t){switch(n.kind){case"true":return;case"false":Ee(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let o=n.children.map(i=>{let s={};return Et(i,s,t),at(s),s}).filter(i=>Object.keys(i).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}Ee(e,...o);return}case"or":{let r=n.children.map(o=>{let i={};return Et(o,i,t),at(i),i});if(r.some(o=>Object.keys(o).length===0))return;if(r.length===0){Et({kind:"false"},e,t);return}Ee(e,{$or:r});return}case"not":hn(n.child,e,t);return;case"compare":ji(n,e,t);return;case"relation_exists":{console.warn(`[mongo-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${n.joinId}) \u2014 expected applyRelationFilters or null-only short-circuit to handle it. Filter silently skipped.`);return}}}function ji(n,e,t){let r=n.field.fieldName;if(n.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${n.field.joinId} (field=${n.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let o=i=>G(t.metadata,t.rootTable,r,i);switch(n.op){case"eq":_e(e,r,o(n.value));return;case"neq":{let i=o(n.value);bo(t,r)?Ee(e,{[r]:{$ne:null}},{[r]:{$ne:i}}):_e(e,r,{$ne:i});return}case"gt":_e(e,r,{$gt:o(n.value)});return;case"gte":_e(e,r,{$gte:o(n.value)});return;case"lt":_e(e,r,{$lt:o(n.value)});return;case"lte":_e(e,r,{$lte:o(n.value)});return;case"in":{let i=Pi(n.value).map(o);_e(e,r,{$in:i});return}case"not_in":{let i=Pi(n.value).map(o);bo(t,r)?Ee(e,{[r]:{$ne:null}},{[r]:{$nin:i}}):_e(e,r,{$nin:i});return}case"between":{let i=Array.isArray(n.value)?n.value:typeof n.value=="string"?n.value.split(",").map(s=>s.trim()):null;Array.isArray(i)&&i.length===2&&_e(e,r,{$gte:o(i[0]),$lte:o(i[1])});return}case"is_null":_e(e,r,n.value===!0?{$eq:null}:{$ne:null});return;case"contains":yo(e,r,String(n.value),"contains");return;case"starts_with":yo(e,r,String(n.value),"starts");return;case"ends_with":yo(e,r,String(n.value),"ends");return}}function hn(n,e,t){switch(n.kind){case"true":Ee(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let r=n.children.map(o=>{let i={};return hn(o,i,t),at(i),i});if(r.some(o=>Object.keys(o).length===0))return;if(r.length===0){Et({kind:"false"},e,t);return}Ee(e,{$or:r});return}case"or":{let o=n.children.map(i=>{let s={};return hn(i,s,t),at(s),s}).filter(i=>Object.keys(i).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}Ee(e,...o);return}case"not":Et(n.child,e,t);return;case"compare":Ia(n,e,t);return;case"relation_exists":{_e(e,n.joinId,n.negate?{$ne:null}:{$eq:null});return}}}function Ia(n,e,t){let r=n.field.fieldName;if(n.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${n.field.joinId} (field=${n.field.fieldName}) but reached false renderer \u2014 expected relation resolver to handle it. Filter silently skipped.`);return}if(n.op==="is_null"){_e(e,r,n.value===!0?{$ne:null}:{$eq:null});return}let o={};ji(n,o,t),at(o);let i={$nor:[o]};bo(t,r)?Ee(e,i,{[r]:{$ne:null}}):Ee(e,i)}function _e(n,e,t){n[e]===void 0?n[e]=t:(Ee(n,{[e]:n[e]},{[e]:t}),delete n[e])}function Ee(n,...e){if(e.length===0)return;let t=n.$and;n.$and=t?[...t,...e]:e}function bo(n,e){let r=n.metadata?.tables?.get?.(n.rootTable)?.columns?.find(o=>o.name===e);return r?r.isNullable!==!1:!0}function Pi(n){return Array.isArray(n)?n:typeof n=="string"&&n.includes(",")?n.split(",").map(e=>e.trim()):[n]}function va(n){return n==="_id"?"$_id":`$${n}`}function yo(n,e,t,r){let o=va(e),i=n[gn]??[];i.push({ref:o,needle:t,mode:r}),n[gn]=i}function at(n){let e=n[gn];if(delete n[gn],!e?.length)return;let t=[];for(let i of e)t.push(i.ref,{$literal:i.needle},i.mode);let r={$eq:[{$function:{body:pn(),args:t,lang:"js"}},!0]},o=n.$expr;Object.prototype.hasOwnProperty.call(n,"$expr")?n.$expr={$and:[o,r]}:n.$expr=r}var xe="__sourceId__",Qe="__targetId__",Ct="__enfyra_target__",yn=class{constructor(e,t,r){this.db=e;this.metadata=t;this.executionBudget=r}runQuery(e){return this.executionBudget.run(e)}normalizeMetadata(){return this.metadata?this.metadata.tables instanceof Map?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}m2mSortCanUseJunction(e){return ke(e).every(t=>t.field==="_id")}async loadM2MTargets(e,t,r){if(t.length===0)return{docs:[],hideId:!1};let o=le(r.projection?._id),i=it(r.projection,["_id"]),s=i?{projection:i}:void 0,a=await K(t,c=>this.runQuery(()=>this.db.collection(e).find({_id:{$in:c}},s).toArray()));return{docs:Ne(a,r),hideId:o}}async fetchM2MTopK(e,t,r,o,i,s,a){if(yr(t.userSort))throw new Error(`Dotted sort is not supported for batch relation '${t.relationName}'`);let c=new Map;for(let _ of e)c.set(B(_),[]);let u=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1,l=!i&&this.m2mSortCanUseJunction(t.userSort),f=ke(t.userSort).find(_=>_.field==="_id")?.order??1,d=Tt(t.userSort),p=await K(e,async _=>{if(l&&!u){let C=[{$match:{[r.selfColumn]:{$in:_}}}];return _r(C,r.selfColumn,{[r.otherColumn]:f},s,a),C.push({$sort:{[r.selfColumn]:1,[r.otherColumn]:f}},{$project:{_id:0,[xe]:`$${r.selfColumn}`,[Qe]:`$${r.otherColumn}`}}),(await this.runQuery(()=>this.db.collection(r.junctionName).aggregate(C).toArray())).map(v=>({sourceId:v[xe],targetId:v[Qe]}))}let S=[{$match:{[r.selfColumn]:{$in:_}}},{$lookup:{from:t.targetTable,localField:r.otherColumn,foreignField:"_id",as:Ct}},{$unwind:`$${Ct}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ct}`,{[xe]:`$${r.selfColumn}`,[Qe]:`$${r.otherColumn}`}]}}}];return i&&Object.keys(i).length>0&&S.push({$match:i}),_r(S,xe,d,s,a),S.push({$sort:{[xe]:1,...d}}),S.push({$project:{_id:0,[xe]:1,[Qe]:1}}),(await this.runQuery(()=>this.db.collection(r.junctionName).aggregate(S).toArray())).map(C=>({sourceId:C[xe],targetId:C[Qe]}))});if(u){let _=new Map;for(let S of p){let E=B(S.targetId);_.has(E)||_.set(E,{_id:S.targetId}),c.get(B(S.sourceId))?.push(_.get(E))}return{grouped:c,docs:[],stats:{strategy:l?"m2m-junction-partitioned-top-k":"m2m-filtered-edge-top-k",roundtrips:Z(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let g=st(p.map(_=>_.targetId)),h=await this.loadM2MTargets(t.targetTable,g,o),{docs:y}=h,m=new Map(y.map(_=>[B(_._id),_])),b=0;for(let _ of p){let S=m.get(B(_.targetId)),E=c.get(B(_.sourceId));S&&E&&(E.push(S),b+=1)}return cn(y,h.hideId),{grouped:c,docs:y,stats:{strategy:"m2m-partitioned-edge-loader",roundtrips:Z(e)+(g.length>0?Z(g):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+y.length,rowsDiscarded:p.length-b}}}async fetchM2MEdgeBatch(e,t,r,o,i){let s=new Map;for(let m of e)s.set(B(m),[]);let a=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1,c=!i&&this.m2mSortCanUseJunction(t.userSort),u=ke(t.userSort).find(m=>m.field==="_id")?.order??1,l=Tt(t.userSort),f=await K(e,async m=>{if(c&&!a)return(await this.runQuery(()=>this.db.collection(r.junctionName).find({[r.selfColumn]:{$in:m}},{projection:{_id:0,[r.selfColumn]:1,[r.otherColumn]:1},sort:{[r.selfColumn]:1,[r.otherColumn]:u}}).toArray())).map(E=>({sourceId:E[r.selfColumn],targetId:E[r.otherColumn]}));let b=[{$match:{[r.selfColumn]:{$in:m}}},{$lookup:{from:t.targetTable,localField:r.otherColumn,foreignField:"_id",as:Ct}},{$unwind:`$${Ct}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ct}`,{[xe]:`$${r.selfColumn}`,[Qe]:`$${r.otherColumn}`}]}}}];return i&&Object.keys(i).length>0&&b.push({$match:i}),b.push({$sort:{[xe]:1,...l}},{$project:{_id:0,[xe]:1,[Qe]:1}}),(await this.runQuery(()=>this.db.collection(r.junctionName).aggregate(b).toArray())).map(S=>({sourceId:S[xe],targetId:S[Qe]}))});if(a){let m=new Map;for(let b of f){let _=B(b.targetId);m.has(_)||m.set(_,{_id:b.targetId}),s.get(B(b.sourceId))?.push(m.get(_))}return{grouped:s,docs:[],stats:{strategy:c?"m2m-junction-batch":"m2m-filtered-edge-batch",roundtrips:Z(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:f.length,rowsDiscarded:0}}}let d=st(f.map(m=>m.targetId)),p=await this.loadM2MTargets(t.targetTable,d,o),{docs:g}=p,h=new Map(g.map(m=>[B(m._id),m])),y=0;for(let m of f){let b=h.get(B(m.targetId)),_=s.get(B(m.sourceId));b&&_&&(_.push(b),y+=1)}return cn(g,p.hideId),{grouped:s,docs:g,stats:{strategy:"m2m-edge-loader",roundtrips:Z(e)+(d.length>0?Z(d):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:f.length+g.length,rowsDiscarded:f.length-y}}}async fetchM2M(e,t,r,o,i){let s=r?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=he(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 c=st(e.map(R=>R._id)),u=new Map;for(let R of e)u.set(B(R._id),[]);if(c.length===0)return{grouped:u,docs:[]};let l=t.userFilter?ce(this.normalizeMetadata(),t.userFilter,t.targetTable):null,f=t.userLimit,d=t.userPage;if(f!==void 0&&(!Number.isSafeInteger(f)||f<0))throw new Error("MongoDB relation limit must be a non-negative safe integer");if(d!==void 0&&(!Number.isSafeInteger(d)||d<1))throw new Error("MongoDB relation page must be a positive safe integer");if(f!==void 0&&f>0){let R=d?(d-1)*f:0;if(!Number.isSafeInteger(R))throw new Error("MongoDB relation pagination offset is too large");return this.fetchM2MTopK(c,t,a,i,l,R,f)}let p=yr(t.userSort);if(!p)return this.fetchM2MEdgeBatch(c,t,a,i,l);let g=await K(c,R=>this.runQuery(()=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:R}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray()));if(g.length===0)return{grouped:u,docs:[],stats:{strategy:"m2m-batch",roundtrips:Z(c),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:0}};let h=new Set,y=[];for(let R of g){let M=R[a.otherColumn];if(M==null)continue;let O=B(M);h.has(O)||(h.add(O),y.push(M))}if(y.length===0)return{grouped:u,docs:[],stats:{strategy:"m2m-batch",roundtrips:Z(c),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length}};let m=[],b=new Map,_=le(i.projection?._id),S=Pe({_id:{$in:y}},l),E;if(p){E=await K(y,async M=>{let O=Pe({_id:{$in:M}},l),j=an(t.targetTable,O,t.userSort,!0,this.normalizeMetadata());return this.runQuery(()=>this.db.collection(t.targetTable).aggregate(j).toArray())});let R=Tt(t.userSort);E.sort((M,O)=>{for(let[j,N]of Object.entries(R)){let P=(te,k)=>k.split(".").reduce(($,T)=>$?.[T],te),Y=ot(P(M,j),P(O,j));if(Y!==0)return Y*N}return 0})}else{let R=Ue(t.userSort)||{_id:1},M=ln(i.projection,t.userSort),O={sort:R};M.projection&&(O.projection=M.projection),E=await K(y,j=>this.runQuery(()=>this.db.collection(t.targetTable).find(Pe({_id:{$in:j}},l),O).toArray())),Ne(E,i),t.userSort?vi(E,t.userSort):Mi(E)}let C=new WeakMap;for(let R of E)C.set(R,B(R._id));m=p?Ne(E,i):E;for(let R of m)b.set(C.get(R),R);let x=new Map;for(let R of g){let M=B(R[a.selfColumn]),O=B(R[a.otherColumn]);b.has(O)&&(x.has(O)||x.set(O,[]),x.get(O).push(M))}for(let R of m){let M=x.get(C.get(R))||[];for(let O of M)u.get(O)?.push(R)}un(m,i.projection,p?["__sort_"]:[]),cn(m,_);let v=y.length===0?0:Z(y);return{grouped:u,docs:m,stats:{strategy:"m2m-batch",roundtrips:Z(c)+v,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length+m.length}}}};var Rt=class{constructor(e,t,r,o=new Ke){this.db=e;this.metadata=t;this.fieldRenamesByTable=r;this.executionBudget=o;this.hiddenInverseIds=new WeakSet;this.pkField="_id"}buildSortFromTokens(e){return Ue(e)}compareSortValues(e,t){return ot(e,t)}projectionWithSortFields(e,t){return ln(e,t)}keyOf(e){return B(e)}async fetchM2M(e,t,r,o,i){return new yn(this.db,this.metadata,this.executionBudget).fetchM2M(e,t,r,o,i)}runQuery(e){return this.executionBudget.run(e)}inverseKeyFields(e,t){return[e,...(t.pendingRenames??[]).filter(r=>r.newName===e).map(r=>r.oldName)]}inverseScope(e,t){return e.length===1?{[e[0]]:t}:{$or:e.map(r=>({[r]:t}))}}normalizeInverseKey(e,t,r){for(let o of e){if(o[t]!==void 0)continue;let i=r.find(s=>s!==t&&o[s]!==void 0);i&&(o[t]=o[i])}}normalizeMetadata(){return this.metadata?this.metadata.tables instanceof Map?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortAggregatePipeline(e,t,r,o=!1){return an(e,t,r,o,this.normalizeMetadata())}toObjectId(e){try{return typeof e=="string"?new Bi.ObjectId(e):e}catch{return e}}applyPublicProjection(e,t,r=[]){return un(e,t,r)}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){return Fi(e,t,this.fieldRenamesByTable)}async fetchOwner(e,t,r,o){let i=o?.userFilter?ce(this.normalizeMetadata(),o.userFilter,e):null,s=Ue(o?.userSort),a=it(r.projection,["_id"]),c=st(t),u=await K(c,f=>{let d=Pe({_id:{$in:f}},i),p={projection:a};return s&&(p.sort=s),this.runQuery(()=>this.db.collection(e).find(d,p).toArray())}),l=Ne(u,r);return{docs:l,stats:{strategy:"batch-in",roundtrips:Z(c),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:l.length}}}async fetchInverse(e,t,r,o,i){let s=this.inverseKeyFields(t,o),a=it(o.projection,[...s,"_id"]),c=S=>{if(le(o.projection?._id))for(let E of S)this.hiddenInverseIds.add(E);return S},u=st(r.map(S=>this.toObjectId(S))),l=i?.userFilter?ce(this.normalizeMetadata(),i.userFilter,e):null,f=i?.userLimit,d=i?.userPage,p=yr(i?.userSort);if(f!==void 0&&f>0){let S=d?(d-1)*f:0;if(p)throw new Error(`Dotted sort is not supported for batch relation '${i?.relationName}'`);let E=Tt(i?.userSort),C=await K(u,async x=>{let R=[{$match:Pe(this.inverseScope(s,{$in:x}),l)}];s.length>1&&R.push({$set:{[t]:{$ifNull:s.map(O=>`$${O}`)}}},{$match:{[t]:{$in:x}}}),_r(R,t,E,S,f),R.push({$sort:{[t]:1,...E}}),Ai(R,a,[t]);let M=await this.runQuery(()=>this.db.collection(e).aggregate(R).toArray());return Ne(M,o)});return{docs:c(C),groupKeyField:t,stats:{strategy:"partitioned-top-k",roundtrips:Z(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:C.length}}}if(p){let S=await K(u,async C=>{let x=Pe(this.inverseScope(s,{$in:C}),l),v=this.buildSortAggregatePipeline(e,x,i.userSort);s.length>1&&v.splice(1,0,{$set:{[t]:{$ifNull:s.map(M=>`$${M}`)}}},{$match:{[t]:{$in:C}}});let R=v.find(M=>M.$sort);return R&&(R.$sort={[t]:1,...R.$sort}),a&&v.push({$project:a}),this.runQuery(()=>this.db.collection(e).aggregate(v).toArray())});this.normalizeInverseKey(S,t,s);let E=Ne(S,o);return{docs:c(E),groupKeyField:t,stats:{strategy:"batch-dotted-sort",roundtrips:Z(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:E.length}}}let g=Ue(i?.userSort)||{_id:1},h={projection:a,sort:g},y=await K(u,async S=>{let E=await this.runQuery(()=>this.db.collection(e).find(Pe(this.inverseScope(s,{$in:S}),l),h).toArray());this.normalizeInverseKey(E,t,s);let C=new Set(S.map(x=>B(x)));return E.filter(x=>C.has(B(x[t])))});this.normalizeInverseKey(y,t,s);let m=new Set(u.map(S=>B(S))),b=Array.from(new Map(y.filter(S=>m.has(B(S[t]))).map(S=>[`${B(S[t])}:${B(S._id)}`,S])).values()),_=Ne(b,o);return{docs:c(_),groupKeyField:t,stats:{strategy:"batch-in",roundtrips:Z(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:_.length}}}postProcessInverseChild(e,t,r){this.hiddenInverseIds.delete(e)&&delete e._id,r||delete e[t]}};async function bn(n,e,t,r,o=3,i=0,s,a,c,u){let l=await u?.getActiveFieldRenamesByTable?.(),f=new Rt(n,a,l);await new We(f,r,c).execute(e,t,o,i,s)}var _n=new WeakMap,Ma=new Set(["__proto__","constructor","prototype"]);function Sr(n){if(n.split(".").some(t=>t.length===0||t.startsWith("$")||Ma.has(t)))throw new Error(`Invalid MongoDB field: ${n}`)}function Ce(n,e){let t=n.$and;if(t===void 0){n.$and=[e];return}if(!Array.isArray(t))throw new Error("Invalid MongoDB $and predicate");t.push(e)}function Di(n){Ce(n,{_id:{$exists:!1,$type:"null"}})}function q(n,e,t){if(Sr(e),!Object.prototype.hasOwnProperty.call(n,e)){n[e]=t;return}let r=n[e];delete n[e],Ce(n,{[e]:r}),Ce(n,{[e]:t})}function Aa(n){let e="^";for(let t of String(n))t==="%"?e+="[\\s\\S]*":t==="_"?e+="[\\s\\S]":e+=t.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&");return`${e}(?![\\s\\S])`}function Oa(n){return Sr(n),n==="_id"?"$_id":`$${n}`}function Ft(n,e,t,r){let o=Oa(e),i=_n.get(n)??[];i.push({ref:o,needle:t,mode:r}),_n.set(n,i)}function wn(n){let e=_n.get(n);if(_n.delete(n),!e?.length)return;let t=[];for(let i of e)t.push(i.ref,{$literal:i.needle},i.mode);let r={$eq:[{$function:{body:pn(),args:t,lang:"js"}},!0]},o=n.$expr;Object.prototype.hasOwnProperty.call(n,"$expr")?n.$expr={$and:[o,r]}:n.$expr=r}function It(n,e,t,r){let o={},i=r==="mongodb"||!r;for(let s of e){Sr(s.field);let a=i&&t&&s.field.startsWith(`${t}.`)?s.field.slice(t.length+1):i||!s.field.includes(".")?s.field:s.field.split(".").pop()??s.field,c=t??"";i&&a==="id"&&(a="_id");let u=G(n,c,a,s.value);switch(Sr(a),s.operator){case"=":q(o,a,u!==null&&typeof u=="object"?{$eq:u}:u);break;case"!=":Sn(n,c,a)?(Ce(o,{[a]:{$ne:null}}),Ce(o,{[a]:{$ne:u}})):q(o,a,{$ne:u});break;case">":q(o,a,{$gt:u});break;case"<":q(o,a,{$lt:u});break;case">=":q(o,a,{$gte:u});break;case"<=":q(o,a,{$lte:u});break;case"like":q(o,a,{$regex:Aa(u),$options:"i"});break;case"in":let l=s.value;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(m=>m.trim()):[l]);let f=l.map(m=>G(n,c,a,m)).filter(m=>m!==null);q(o,a,{$in:f});break;case"not in":let d=s.value;Array.isArray(d)||(d=typeof d=="string"&&d.includes(",")?d.split(",").map(m=>m.trim()):[d]);let p=d.map(m=>G(n,c,a,m));if(p.some(m=>m===null)){Di(o);break}Sn(n,c,a)?(Ce(o,{[a]:{$ne:null}}),Ce(o,{[a]:{$nin:p}})):q(o,a,{$nin:p});break;case"is null":q(o,a,null);break;case"is not null":q(o,a,{$ne:null});break;case"_contains":Ft(o,a,String(u),"contains");break;case"_starts_with":Ft(o,a,String(u),"starts");break;case"_ends_with":Ft(o,a,String(u),"ends");break;case"_between":let g=s.value;if(typeof g=="string"&&(g=g.split(",").map(m=>m.trim())),Array.isArray(g)&&g.length===2){let m=G(n,c,a,g[0]),b=G(n,c,a,g[1]);q(o,a,{$gte:m,$lte:b})}break;case"_is_null":let h=s.value===!0||s.value==="true";q(o,a,h?{$eq:null}:{$ne:null});break;case"_is_not_null":let y=s.value===!0||s.value==="true";q(o,a,y?{$ne:null}:{$eq:null});break}}return wn(o),o}function Sn(n,e,t){let o=n?.tables?.get?.(e)?.columns?.find(i=>i.name===t);return o?o.isNullable!==!1:!0}function $r(n,e,t,r,o,i){switch(Sr(r),o){case"_contains":Ft(e,r,String(i),"contains"),wn(e);break;case"_starts_with":Ft(e,r,String(i),"starts"),wn(e);break;case"_ends_with":Ft(e,r,String(i),"ends"),wn(e);break;case"_eq":{let f=G(n,t,r,i);q(e,r,f!==null&&typeof f=="object"?{$eq:f}:f);break}case"_neq":{let f=G(n,t,r,i);Sn(n,t,r)?(Ce(e,{[r]:{$ne:null}}),Ce(e,{[r]:{$ne:f}})):q(e,r,{$ne:f});break}case"_in":{let f=i;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]);let d=f.map(p=>G(n,t,r,p)).filter(p=>p!==null);q(e,r,{$in:d});break}case"_not_in":case"_nin":let s=i;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(f=>f.trim()):[s]);let a=s.map(f=>G(n,t,r,f));if(a.some(f=>f===null)){Di(e);break}Sn(n,t,r)?(Ce(e,{[r]:{$ne:null}}),Ce(e,{[r]:{$nin:a}})):q(e,r,{$nin:a});break;case"_gt":q(e,r,{$gt:G(n,t,r,i)});break;case"_gte":q(e,r,{$gte:G(n,t,r,i)});break;case"_lt":q(e,r,{$lt:G(n,t,r,i)});break;case"_lte":q(e,r,{$lte:G(n,t,r,i)});break;case"_is_null":q(e,r,i===!0||i==="true"?{$eq:null}:{$ne:null});break;case"_is_not_null":q(e,r,i===!0||i==="true"?{$ne:null}:{$eq:null});break;case"_between":let l=i;if(typeof l=="string"&&(l=l.split(",").map(f=>f.trim())),Array.isArray(l)&&l.length===2){let f=G(n,t,r,l[0]),d=G(n,t,r,l[1]);q(e,r,{$gte:f,$lte:d})}break}}var _o=require("mongodb");function vt(n,e){if(e)return n.some(r=>r&&Object.keys(r).length===0)?{}:n.length===0?{_id:{$in:[]}}:n.length===1?n[0]:{$or:n};let t=n.filter(r=>r&&Object.keys(r).length>0);return t.length===0?{}:t.length===1?t[0]:{$and:t}}async function je(n,e,t,r){if(!n||typeof n!="object")return{};let o=t?.tables?.get(e);if(!o)return ce(t,n,e);let i=new Set((o.relations||[]).map(l=>l.propertyName));if(!ye(n,i))return ce(t,n,e);let s=Object.entries(n);if(s.length>1){let l=await Promise.all(s.map(([f,d])=>je({[f]:d},e,t,r)));return vt(l,!1)}if(Array.isArray(n._and)){let l=await Promise.all(n._and.map(f=>je(f,e,t,r)));return vt(l,!1)}if(Array.isArray(n._or)){let l=await Promise.all(n._or.map(f=>je(f,e,t,r)));return vt(l,!0)}if(Object.prototype.hasOwnProperty.call(n,"_not"))return $n(n._not,e,t,r);let{fieldFilters:a,relationFilters:c}=Ae(n,o),u=[];if(a&&Object.keys(a).length>0){let l=ce(t,a,e);l&&Object.keys(l).length>0&&u.push(l)}if(c&&Object.keys(c).length>0)for(let[l,f]of Object.entries(c)){let d=await Na(l,f,e,o,t,r);d&&Object.keys(d).length>0&&u.push(d)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function $n(n,e,t,r){if(!n||typeof n!="object")return{};let o=t?.tables?.get(e);if(!o)return mn(t,n,e);let i=new Set((o.relations||[]).map(l=>l.propertyName));if(!ye(n,i))return mn(t,n,e);let s=Object.entries(n);if(s.length>1){let l=await Promise.all(s.map(([f,d])=>$n({[f]:d},e,t,r)));return vt(l,!0)}if(Array.isArray(n._and)){let l=await Promise.all(n._and.map(f=>$n(f,e,t,r)));return vt(l,!0)}if(Array.isArray(n._or)){let l=await Promise.all(n._or.map(f=>$n(f,e,t,r)));return vt(l,!1)}if(Object.prototype.hasOwnProperty.call(n,"_not"))return je(n._not,e,t,r);let{fieldFilters:a,relationFilters:c}=Ae(n,o),u=[];if(a&&Object.keys(a).length>0){let l=mn(t,a,e);l&&Object.keys(l).length>0&&u.push(l)}if(c&&Object.keys(c).length>0)for(let[l,f]of Object.entries(c)){let d=await ja(l,f,e,o,t,r);d&&Object.keys(d).length>0&&u.push(d)}return u.length===0?{}:u.length===1?u[0]:{$or:u}}async function Na(n,e,t,r,o,i){let s=(r.relations||[]).find(u=>u.propertyName===n);if(!s)return{};let a=s.targetTableName||s.targetTable,c=o?.tables?.get(a);return!a||!c?{}:s.type==="many-to-one"||s.type==="one-to-one"?Pa(e,s,n,a,c,o,i):s.type==="one-to-many"?Wi(e,s,t,a,c,o,i):s.type==="many-to-many"?Ki(e,s,t,a,c,o,i):{}}async function Pa(n,e,t,r,o,i,s){let a=X(e)||t,c=kn(n),u=En(c);if(u!==null)return u?{[a]:null}:{[a]:{$ne:null}};let l=So(c);if(l!==null){let g=xn(l.value);if(l.op==="eq")return{[a]:g};if(l.op==="neq")return{$and:[{[a]:{$ne:g}},{[a]:{$ne:null}}]};if(l.op==="in")return{[a]:{$in:g}};if(l.op==="not_in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]}}let f=await Tn(c,r,o,i,s);if(!f||Object.keys(f).length===0)return{};let p=(await s.collection(r).find(f,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(g=>g!=null);return p.length===0?ze():{[a]:{$in:p}}}async function ja(n,e,t,r,o,i){let s=(r.relations||[]).find(u=>u.propertyName===n);if(!s)return{};let a=s.targetTableName||s.targetTable,c=o?.tables?.get(a);if(!a||!c)return{};if(s.type==="many-to-one"||s.type==="one-to-one")return Ba(e,s,n,a,c,o,i);if(s.type==="one-to-many"){let u=await Wi(e,s,t,a,c,o,i);return qi(u)}if(s.type==="many-to-many"){let u=await Ki(e,s,t,a,c,o,i);return qi(u)}return{}}async function Ba(n,e,t,r,o,i,s){let a=X(e)||t,c=kn(n),u=En(c);if(u!==null)return u?{[a]:{$ne:null}}:{[a]:null};let l=So(c);if(l!==null){let g=xn(l.value);if(l.op==="eq")return{$and:[{[a]:{$ne:g}},{[a]:{$ne:null}}]};if(l.op==="neq")return{[a]:g};if(l.op==="in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]};if(l.op==="not_in")return{[a]:{$in:g}}}let f=await Tn(c,r,o,i,s);if(!f||Object.keys(f).length===0)return{[a]:null};let p=(await s.collection(r).find(f,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(g=>g!=null);return p.length===0?{[a]:{$ne:null}}:{$and:[{[a]:{$nin:p}},{[a]:{$ne:null}}]}}async function Wi(n,e,t,r,o,i,s){let a=V(e)||t,c=kn(n),u=En(c);if(u!==null){let d=await Li(s,r,a,{});return u?d.length===0?{}:{_id:{$nin:d}}:d.length===0?ze():{_id:{$in:d}}}let l=await Tn(c,r,o,i,s);if(!l||Object.keys(l).length===0)return{};let f=await Li(s,r,a,l);return f.length===0?ze():{_id:{$in:f}}}async function Ki(n,e,t,r,o,i,s){let a=he(t,e);if(!a)return{};let c=kn(n),u=En(c);if(u!==null){let h=await wo(s,a,r,null);return u?h.length===0?{}:{_id:{$nin:h}}:h.length===0?ze():{_id:{$in:h}}}let l=So(c);if(l!==null){let h=xn(l.value),y=Array.isArray(h)?h:[h],m=await wo(s,a,r,{_id:l.op==="neq"||l.op==="not_in"?{$nin:y,$ne:null}:{$in:y}});return m.length===0?ze():{_id:{$in:m}}}let f=await Tn(c,r,o,i,s);if(!f||Object.keys(f).length===0)return{};let p=(await s.collection(r).find(f,{projection:{_id:1}}).toArray()).map(h=>h._id).filter(h=>h!=null);if(p.length===0)return ze();let g=await wo(s,a,r,{_id:{$in:p}});return g.length===0?ze():{_id:{$in:g}}}async function Tn(n,e,t,r,o){let i=new Set((t?.relations??[]).map(s=>s.propertyName));return ye(n,i)?je(n,e,r,o):ce(r,n,e)}async function Li(n,e,t,r){let o=await n.collection(e).find(r,{projection:{[t]:1}}).toArray(),i=new Set,s=[];for(let a of o){let c=a[t];if(c==null)continue;let u=String(c);i.has(u)||(i.add(u),s.push(c))}return s}function ze(){return{_id:{$in:[]}}}function Da(n){if(!n||typeof n!="object")return!1;let e=Object.keys(n);if(e.length!==1||e[0]!=="_id")return!1;let t=n._id;return!!t&&typeof t=="object"&&Array.isArray(t.$in)&&t.$in.length===0}function qi(n){if(!n||Object.keys(n).length===0)return ze();if(Da(n))return{};let e=n._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:[n]}}async function wo(n,e,t,r){let o=null;r&&t&&(o=(await n.collection(t).find(r,{projection:{_id:1}}).toArray()).map(l=>l._id).filter(l=>l!=null));let i=o?{[e.otherColumn]:{$in:o}}:{},s=await n.collection(e.junctionName).find(i,{projection:{[e.selfColumn]:1}}).toArray(),a=new Set,c=[];for(let u of s){let l=u[e.selfColumn];if(l==null)continue;let f=String(l);a.has(f)||(a.add(f),c.push(l))}return c}function kn(n){return n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===1&&n.id&&typeof n.id=="object"?n.id:n}function En(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let e=Object.keys(n);if(e.length!==1)return null;let t=e[0],r=n[t];return t==="_is_null"?r===!0:t==="_is_not_null"?r!==!0:t==="_eq"?r===null?!0:null:t==="_neq"&&r===null?!1:null}function xn(n){if(Array.isArray(n))return n.map(e=>xn(e));if(typeof n!="string")return n;try{return new _o.ObjectId(n)}catch{return n}}function So(n){if(Array.isArray(n))return{op:"in",value:n};if(n instanceof _o.ObjectId)return{op:"eq",value:n};if(n==null)return null;if(typeof n!="object")return{op:"eq",value:n};if(!n||typeof n!="object"||Array.isArray(n))return null;let e=Object.keys(n);if(e.length!==1)return null;let t=e[0];return t==="_eq"?{op:"eq",value:n._eq}:t==="_neq"?{op:"neq",value:n._neq}:t==="_in"&&Array.isArray(n._in)?{op:"in",value:n._in}:t==="_not_in"&&Array.isArray(n._not_in)?{op:"not_in",value:n._not_in}:null}function Tr(n){let{targetTable:e,localField:t,foreignField:r,alias:o,pipeline:i,junction:s}=n,a=u=>({$match:{$expr:{$and:[{$ne:[{$ifNull:["$$localId",null]},null]},{$ne:[{$ifNull:[`$${u}`,null]},null]},{$eq:[`$${u}`,"$$localId"]}]}}});if(!s)return{$lookup:{from:e,let:{localId:`$${t}`},pipeline:[a(r),...i],as:o}};let c="__enfyra_sorted_relation_target__";return{$lookup:{from:s.junctionName,let:{localId:`$${t}`},pipeline:[a(s.selfColumn),Tr({targetTable:e,localField:s.otherColumn,foreignField:r,alias:c,pipeline:[]}),{$unwind:`$${c}`},{$replaceRoot:{newRoot:`$${c}`}},...i],as:o}}}wt();async function $o(n,e,t,r,o=1){if(o>me)throw new Error(`MongoDB lookup exceeds maximum relation depth of ${me}`);let i=n?.tables?.get(e);if(!i)throw new Error(`Metadata not found for lookup table '${e}'`);let s=i.relations??[],a=t.map(g=>g==="id"&&!i.columns?.some(h=>h.name==="id")?"_id":g),c=await tt(n,e,a),u=[],l=new Map;if(r&&["_and","_or","_not"].some(g=>Object.prototype.hasOwnProperty.call(r,g))){if(ye(r,new Set(s.map(h=>h.propertyName))))throw new Error(`Logical relation filter is not supported inside nested lookup '${e}'`);let g=ce(n,r,e);Object.keys(g).length>0&&u.push({$match:g})}else if(r){let g={};for(let[h,y]of Object.entries(r)){let m=s.find(_=>_.propertyName===h),b=y&&typeof y=="object"&&Object.keys(y).every(_=>de.has(_));if(m&&y&&typeof y=="object"&&!b)l.set(h,y);else if(y&&typeof y=="object")for(let[_,S]of Object.entries(y))$r(n,g,e,h,_,S);else $r(n,g,e,h,"_eq",y)}Object.keys(g).length>0&&u.push({$match:g})}let d=[...c.relations];for(let g of l.keys()){if(d.some(m=>m.propertyName===g))continue;let h=s.find(m=>m.propertyName===g),y=h.type==="one-to-many"||ge(h);d.push({propertyName:g,targetTable:h.targetTableName||h.targetTable,localField:y||h.type==="many-to-many"?"_id":X(h)||g,foreignField:y&&h.type!=="many-to-many"?V(h)||g:"_id",type:h.type==="one-to-many"||h.type==="many-to-many"?"many":"one",nestedFields:["_id"]})}for(let g of d){let h=s.find(b=>b.propertyName===g.propertyName),y=l.get(g.propertyName),m=await $o(n,g.targetTable,g.nestedFields.length?g.nestedFields:["_id"],y,o+1);g.type==="one"&&m.push({$limit:1}),u.push(Tr({targetTable:g.targetTable,localField:h?.type==="many-to-many"?"_id":g.localField,foreignField:g.foreignField,alias:g.propertyName,pipeline:m,junction:h?.type==="many-to-many"?he(e,h):null})),g.type==="one"&&u.push({$unwind:{path:`$${g.propertyName}`,preserveNullAndEmptyArrays:!0}}),y&&u.push({$match:g.type==="one"?{[g.propertyName]:{$ne:null}}:{[`${g.propertyName}.0`]:{$exists:!0}}})}let p={_id:1};for(let g of c.scalarFields)p[g]=1;for(let g of c.relations)p[g.propertyName]=1;return u.push({$project:p}),u}async function Ui(n,e,t,r,o){let i={_id:1};for(let s of r)i[s]=1;for(let s of o)s.type==="one"&&s.localField&&(i[s.localField]=1);e.push({$project:i})}function To(n,e){if(!n||typeof n!="object"||Array.isArray(n))return!1;let t=Object.entries(n);return t.length>0&&t.every(([r,o])=>r===e?!0:r==="_not"?To(o,e):r==="_and"||r==="_or"?Array.isArray(o)&&o.length>0&&o.every(i=>To(i,e)):!1)}function Cn(n,e){if(!n||typeof n!="object"||Array.isArray(n))return;let t=[];if(Object.prototype.hasOwnProperty.call(n,e)&&t.push(n[e]),Array.isArray(n._and)){let r=n._and.map(o=>Cn(o,e)).filter(o=>o!==void 0);t.push(...r)}if(Array.isArray(n._or)&&n._or.length>0){let r=n._or.map(o=>Cn(o,e));r.every(o=>o!==void 0)&&t.push({_or:r})}if(To(n._not,e)){let r=Cn(n._not,e);r!==void 0&&t.push({_not:r})}if(t.length!==0)return t.length===1?t[0]:{_and:t}}async function Fn(n,e,t){let r=[],{db:o,metadata:i,dbType:s,debugLog:a}=t,c=t.execute!==!1;e.deep!==void 0&&rt(e.table,e.deep,i);let u=e.offset??0,l=e.limit===0?void 0:e.limit;if(!Number.isSafeInteger(u)||u<0)throw new Error("MongoDB offset must be a non-negative safe integer");if(l!=null&&(!Number.isSafeInteger(l)||l<0))throw new Error("MongoDB limit must be a non-negative safe integer");!e.mongoRawFilter&&e.plan?.rawFilter&&(e={...e,mongoRawFilter:e.plan.rawFilter});let f=i?.tables?.get(e.table),d=new Set((f?.relations??[]).map(T=>T.propertyName)),p=!!e.mongoRawFilter&&!!i&&ye(e.mongoRawFilter,d),g=e.plan,h=g?.filterTree&&!g.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&i&&p){let T=await je(e.mongoRawFilter,e.table,i,o);T&&Object.keys(T).length>0&&r.push({$match:T})}else if(h){let T=xt(g.filterTree,{metadata:i,rootTable:e.table});Object.keys(T).length>0&&r.push({$match:T})}else if(e.mongoRawFilter){let T=ce(i,e.mongoRawFilter,e.table);Object.keys(T).length>0&&r.push({$match:T})}else if(e.where){let T=It(i,e.where,e.table,s);r.push({$match:T})}let y=e.plan,b=y?y.hasRelationSort:e.sort?.some(T=>{if(!T.field.includes("."))return!1;let F=T.field.split(".")[0];return d.has(F)||(e.mongoFieldsExpanded?.relations?.some(L=>L.propertyName===F)??!1)})??!1,_=(T,F=e.table)=>{let L=T.split("."),A=F;for(let H of L.slice(0,-1)){let U=i?.tables?.get(A)?.relations?.find(Fe=>Fe.propertyName===H);if(!U)return T;A=U.targetTableName||U.targetTable}let Re=i?.tables?.get(A);return L.at(-1)==="id"&&!Re?.columns?.some(H=>H.name==="id")&&(L[L.length-1]="_id"),L.join(".")},S=()=>{let T=y?.sortItems?.length?gr(y.sortItems):e.sort?.length?Object.fromEntries(e.sort.map(F=>[_(F.field),F.direction==="desc"?-1:1])):null;return T&&Object.keys(T).length>0?T:null},E=y?.sortItems?Si(y.sortItems):[],C=y?.sortItems?$i(y.sortItems):[],x=new Set((i?.tables?.get(e.table)?.columns??[]).map(T=>T.name));for(let T of e.mongoCountOnly?[]:[...E,...C])if(x.has(T))throw new Error(`MongoDB relation sort alias conflicts with a root field: ${T}`);let v=()=>{!y||E.length===0||Ti(r,e.table,y.sortItems,i)},R=()=>{!y||C.length===0||ki(r,e.table,y.sortItems,i)},M=()=>{let T=[...E,...C];T.length===0||e.mongoCountOnly||r.push({$project:Object.fromEntries(T.map(F=>[F,0]))})};if(!e.mongoFieldsExpanded){if(b&&!e.mongoCountOnly&&(y?.sortItems.some(F=>!F.function&&F.joinId!==null)??!0))throw new Error("MongoDB relation sort requires expanded relation fields");if(!e.mongoCountOnly){v(),R();let F=S();F&&r.push({$sort:F})}if(e.mongoCountOnly?r.push({$count:"count"}):(u>0&&r.push({$skip:u}),l!=null&&l>0&&r.push({$limit:l})),M(),!e.mongoCountOnly&&e.select?.length){let F={_id:0};for(let L of e.select)F[_(L)]=1;r.push({$project:F})}if(a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:[...r]}),!c)return{results:[],pipeline:r};let T=await n.aggregate(r).toArray();return e.mongoCountOnly?{results:T,pipeline:r}:{results:Rn(T),pipeline:r}}let{scalarFields:O,relations:j}=e.mongoFieldsExpanded;if(!b){if(!e.mongoCountOnly){v(),R();let T=S();T&&r.push({$sort:T})}e.mongoCountOnly||(u>0&&r.push({$skip:u}),l!=null&&l>0&&r.push({$limit:l}))}let N=new Set(e.mongoCountOnly?[]:y?.sortItems.filter(T=>T.joinId!==null&&!T.function).map(T=>T.fullPath.split(".")[0])??e.sort?.filter(T=>T.field.includes(".")&&(d.has(T.field.split(".")[0])||j.some(F=>F.propertyName===T.field.split(".")[0]))).map(T=>T.field.split(".")[0])??[]);for(let T of N)if(!j.some(F=>F.propertyName===T))throw new Error(`MongoDB relation sort expansion is missing for '${T}'`);let P=j,Y=new Map,te=new Set([...x,...j.map(T=>T.propertyName)]);for(let T of j){if(!N.has(T.propertyName))continue;let F=`__enfyra_relation_sort_${Y.size}`;for(;te.has(F);)F+="_";te.add(F),Y.set(T.propertyName,F);let L=(y?.sortItems??e.sort?.map(U=>({fullPath:U.field,direction:U.direction,function:void 0}))??[]).filter(U=>!U.function&&U.fullPath.startsWith(`${T.propertyName}.`)),A=L.map(U=>U.fullPath.slice(T.propertyName.length+1)),Re=await $o(i,T.targetTable,A.length?A:["_id"],Cn(e.mongoRawFilter,T.propertyName)),H=Object.create(null);for(let U of L){let Fe=U.fullPath.slice(T.propertyName.length+1);H[y?Fe:_(Fe,T.targetTable)]=U.direction==="desc"?-1:1}H._id===void 0&&(H._id=1),Re.push({$sort:H},{$limit:1});let Q=i?.tables?.get(e.table)?.relations?.find(U=>U.propertyName===T.propertyName);r.push(Tr({targetTable:T.targetTable,localField:Q?.type==="many-to-many"?"_id":T.localField,foreignField:T.foreignField,alias:F,pipeline:Re,junction:Q?.type==="many-to-many"?he(e.table,Q):null})),r.push({$unwind:{path:`$${F}`,preserveNullAndEmptyArrays:!0}})}if(b){if(!e.mongoCountOnly){v(),R();let T=S();if(T){let F=Object.create(null);for(let[L,A]of Object.entries(T)){let[Re,...H]=L.split("."),Q=Y.get(Re);F[Q&&H.length?`${Q}.${H.join(".")}`:L]=A}r.push({$sort:F})}}e.mongoCountOnly||(u>0&&r.push({$skip:u}),l!=null&&l>0&&r.push({$limit:l}))}if(e.mongoCountOnly?r.push({$count:"count"}):(M(),await Ui(i,r,e.table,O,[...j])),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:[...r]}),!c)return{results:[],pipeline:r};let k=performance.now(),$=await n.aggregate(r).toArray();if(e.debugTrace?.dur("db_execute",k,{table:e.table}),e.mongoCountOnly)return{results:$,pipeline:r};if(P.length>0&&$.length>0){let T=e.deep||{},F=P.map(A=>{let H=i?.tables?.get(e.table)?.relations?.find(Kn=>Kn.propertyName===A.propertyName),Q=T[A.propertyName],U=Q?.limit===void 0?void 0:Number(Q.limit),Fe=Q?.page===void 0?void 0:Number(Q.page);if(U!==void 0&&(!Number.isSafeInteger(U)||U<0))throw new Error("MongoDB relation limit must be a non-negative safe integer");if(Fe!==void 0&&(!Number.isSafeInteger(Fe)||Fe<1))throw new Error("MongoDB relation page must be a positive safe integer");let bs=Q?.fields!=null?Array.isArray(Q.fields)?Q.fields:String(Q.fields).split(",").map(Kn=>Kn.trim()).filter(Boolean):A.nestedFields&&A.nestedFields.length>0?A.nestedFields:["_id"];return{relationName:A.propertyName,type:H?.type,targetTable:A.targetTable,fields:bs,isInverse:H?.isInverse,mappedBy:H?.mappedBy,junctionTableName:H?.junctionTableName,junctionSourceColumn:H?.junctionSourceColumn,junctionTargetColumn:H?.junctionTargetColumn,localField:A.localField,foreignField:A.foreignField,injectedParentFields:A.type==="one"&&A.localField&&A.localField!==A.propertyName&&!O.includes(A.localField)?[A.localField]:void 0,userFilter:Q?.filter,userSort:Q?.sort,userLimit:U,userPage:Fe,nestedDeep:Q?.deep}}),L=ko(i);if(!L)throw new Error("MongoDB relation hydration requires metadata");await bn(o,$,F,L,3,0,e.table,i,e.debugTrace,t.mongoPhysicalMigrationService)}return{results:Rn($),pipeline:r}}function ko(n){let e=n;return e?async t=>{let r=e.tables?.get(t);return r?{name:r.name,columns:(r.columns||[]).map(o=>({name:o.name,type:o.type})),relations:r.relations||[]}:null}:null}function Qi(n){if(n===null||typeof n!="object")return!1;let e=new WeakSet,t=[n];for(;t.length>0;){let r=t.pop();if(!e.has(r)){if(e.add(r),Array.isArray(r)){for(let o of r)o&&typeof o=="object"&&t.push(o);continue}for(let[o,i]of Object.entries(r)){if(i===null){if(o==="_eq"||o==="$eq")return!0;continue}if(!(!i||typeof i!="object")){if(Object.prototype.hasOwnProperty.call(i,"_is_null")&&(i._is_null===!0||i._is_null==="true")||Object.prototype.hasOwnProperty.call(i,"_eq")&&i._eq===null||Object.prototype.hasOwnProperty.call(i,"$eq")&&i.$eq===null)return!0;t.push(i)}}}}return!1}function Rn(n){return n.map(se)}function zi(n,e){let t=[],r=[],o=e?.tables?.get(n.rootTable);if(!o)return{scalarFields:t,relations:r};for(let i of n.nodes)if(i.kind==="wildcard")for(let s of o.columns||[])t.includes(s.name)||t.push(s.name);else i.kind==="scalar"?o.columns?.some(a=>a.name===i.name)&&!t.includes(i.name)&&t.push(i.name):i.kind==="relation"&&r.push(La(i,o,e));return{scalarFields:t,relations:r}}function La(n,e,t){let r=e.relations?.find(u=>u.propertyName===n.propertyName),o,i,s=!1;n.relationType==="many-to-one"||n.relationType==="one-to-one"?r&&ge(r)?(o="_id",i=V(r)||n.propertyName,s=!0):(o=r&&X(r)||n.propertyName,i="_id",s=!1):n.relationType==="one-to-many"?(o="_id",i=r&&V(r)||n.propertyName,s=!0):r?.mappedBy?(o="_id",i=r.mappedBy,s=!0):(o=n.propertyName,i="_id",s=!1);let a=n.relationType==="one-to-many"||n.relationType==="many-to-many",c=Ji(n.children);return{propertyName:n.propertyName,targetTable:n.targetTable,localField:o,foreignField:i,type:a?"many":"one",isInverse:s,nestedFields:c}}function Ji(n){let e=[];for(let t of n)if(t.kind==="wildcard")e.push("*");else if(t.kind==="scalar")e.push(t.name);else if(t.kind==="relation"){let r=Ji(t.children);if(r.length===0)e.push(`${t.propertyName}.id`);else for(let o of r)e.push(`${t.propertyName}.${o}`)}return e}qe();re();var qa=new Set(["int","integer","bigint","smallint","tinyint","float","double","decimal","numeric","real","number"]),Wa=new Set(["date","datetime","timestamp","timestamptz","timestamp with time zone","timestamp without time zone"]),Ka=new Set(["hour","day","week","month","year"]),Ua=new Set(["count","countDistinct","sum","avg","min","max"]);function D(n,e){throw new w(e,{path:n})}function Mt(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}function Qa(n,e){let t=n?.tables?.get(e);return t||D("aggregate",`Table "${e}" metadata is not available`),t}function Hi(n,e,t){let r=n.columns?.find(o=>o.name===e);return r||D(t,`Unknown aggregate field "${e}"`),r.isEncrypted===!0&&D(t,`Encrypted field "${e}" cannot be used in aggregate queries`),r}function za(n,e){let t=n===void 0?"UTC":n;(typeof t!="string"||t.length===0)&&D(e,"Aggregate timezone must be a non-empty IANA timezone");try{new Intl.DateTimeFormat("en-US",{timeZone:t}).format()}catch{D(e,`Invalid aggregate timezone "${t}"`)}return t}function Ja(n,e){return n==null?{}:(Mt(n)||D(e,"Aggregate filter must be an object"),n)}function Vi(n,e,t){let r;return typeof n=="number"?r=n:typeof n=="string"&&/^\d+$/.test(n)?r=Number(n):D(e,t),Number.isSafeInteger(r)||D(e,t),r}function At(n,e,t){Mt(n)||D("aggregate","Aggregate options must be an object");let r=Qa(t,e),o=n.dimensions===void 0?[]:n.dimensions,i=n.measures;Array.isArray(o)||D("aggregate.dimensions","Aggregate dimensions must be an array"),(!Mt(i)||Object.keys(i).length===0)&&D("aggregate.measures","Aggregate requires at least one measure");let s=new Set,a=o.map((m,b)=>{let _=`aggregate.dimensions[${b}]`;(!Mt(m)||typeof m.field!="string"||m.field.length===0)&&D(_,"Aggregate dimension requires a field");let S=Hi(r,m.field,`${_}.field`);return s.has(m.field)&&D(`${_}.field`,`Duplicate aggregate dimension "${m.field}"`),s.add(m.field),m.bucket===void 0?(m.timezone!==void 0&&D(`${_}.timezone`,"Aggregate timezone requires a bucket"),{field:m.field,outputKey:m.field,column:S}):((typeof m.bucket!="string"||!Ka.has(m.bucket))&&D(`${_}.bucket`,"Aggregate bucket must be hour, day, week, month, or year"),Wa.has(String(S.type).toLowerCase())||D(`${_}.bucket`,`Aggregate bucket requires a date field, but "${m.field}" is "${S.type}"`),{field:m.field,outputKey:m.field,bucket:m.bucket,timezone:za(m.timezone,`${_}.timezone`),column:S})}),c=new Set,u=Object.entries(i).map(([m,b])=>{let _=`aggregate.measures.${m}`;(!m||!Mt(b))&&D(_,"Aggregate measure must be an object");let S=Object.entries(b);S.length!==1&&D(_,"Aggregate measure must define exactly one operation");let[E,C]=S[0];Ua.has(E)||D(_,`Unsupported aggregate measure "${E}"`),(typeof C!="string"||C.length===0)&&D(_,"Aggregate measure field must be a non-empty string");let x=Hi(r,C,`${_}.${E}`);return(c.has(m)||s.has(m))&&D(_,`Aggregate output key "${m}" is duplicated`),c.add(m),["sum","avg","min","max"].includes(E)&&!qa.has(String(x.type).toLowerCase())&&D(_,`Aggregate ${E} requires a numeric field, but "${C}" is "${x.type}"`),{outputKey:m,operation:E,field:C,column:x}}),l=n.sort===void 0?[]:n.sort;Array.isArray(l)||D("aggregate.sort","Aggregate sort must be an array");let f=new Set([...s,...c]),d=l.map((m,b)=>{let _=`aggregate.sort[${b}]`;return(!Mt(m)||typeof m.field!="string"||!f.has(m.field))&&D(_,"Aggregate sort field must reference a dimension or measure output"),m.direction!=="asc"&&m.direction!=="desc"&&D(`${_}.direction`,"Aggregate sort direction must be asc or desc"),{field:m.field,direction:m.direction}}),p="Aggregate limit must be an integer between 1 and 10000",g="Aggregate page must be a positive integer",h=n.limit===void 0?void 0:Vi(n.limit,"aggregate.limit",p),y=n.page===void 0?1:Vi(n.page,"aggregate.page",g);return h!==void 0&&(h<=0||h>1e4)&&D("aggregate.limit",p),y<=0&&D("aggregate.page",g),{tableName:e,filter:Ja(n.filter,"aggregate.filter"),dimensions:a,measures:u,sort:d,page:y,limit:h}}var lt=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.db=e.getDb()}async execute(e){let t={metadata:e.metadata,dbType:e.dbType||"mongodb",debugLog:e.debugLog,execute:!e.debugMode};if(!e.plan){let m=new pe;e={...e,plan:m.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"})}}e={...e,fields:e.plan.rawFields};let r=e.plan.rawFields!==void 0&&e.plan.rawFields.length===0&&!Object.keys(e.deep??{}).length;e.deep!==void 0&&rt(e.tableName,e.deep,e.metadata);let o={table:e.tableName,metadata:e.metadata,debugTrace:e.debugTrace};e.pipeline&&(o.pipeline=e.pipeline),r?(o.fields=["_id"],o.mongoFieldsExpanded={scalarFields:["_id"],relations:[]}):e.fields&&(Array.isArray(e.fields)?o.fields=e.fields:typeof e.fields=="string"&&(o.fields=e.fields.split(",").map(m=>m.trim())));let i=e.filter??e.plan?.rawFilter;if(i&&(Le(i,e.tableName,e.metadata),o.mongoRawFilter=i),e.sort){let m=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(b=>b.trim());o.sort=m.map(b=>{let _=b.trim();return _.startsWith("-")?{field:_.substring(1),direction:"desc"}:{field:_,direction:"asc"}})}else o.sort=[{field:"id",direction:"asc"}];let s=this.normalizePaginationValue(e.page,"page",1),a=this.normalizePaginationValue(e.limit,"limit",0);if(s!==void 0&&a===void 0)throw new Error("limit is required when page is provided");s!==void 0&&a!==void 0?(o.offset=(s-1)*a,o.limit=a):a!==void 0&&(o.limit=a);let c=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(m=>m.trim()).filter(Boolean),u=0,l=0;(c.includes("totalCount")||c.includes("*"))&&(u=await this.mongoService.collection(e.tableName).countDocuments({}));let f=t.metadata?.tables?.get(e.tableName),d=new Set((f?.relations??[]).map(m=>m.propertyName)),p=!!o.mongoRawFilter&&ye(o.mongoRawFilter,d);if((c.includes("filterCount")||c.includes("*"))&&!p){let m=this.mongoService.collection(e.tableName),b=e.plan?.filterTree?xt(e.plan.filterTree,{metadata:t.metadata,rootTable:e.tableName}):{};l=await m.countDocuments(b)}o.plan=e.plan,o.deep=e.deep;let g=await this.selectLegacy(o,t),h=r?g.results.map(()=>({})):g.results,y=typeof this.mongoService?.parseResult=="function"?await this.mongoService.parseResult(h,e.tableName):h;if(e.debugMode){let m;try{m=await this.db.collection(e.tableName).aggregate(g.pipeline).explain()}catch(b){m={error:String(b)}}return{pipeline:g.pipeline,explain:m}}if(p&&(c.includes("filterCount")||c.includes("*"))){let m={...o,pipeline:void 0,mongoCountOnly:!0},b=await this.selectLegacy(m,t);l=b.results.length>0?b.results[0].count:0}return{data:y,...c.length>0&&{meta:{...c.includes("totalCount")||c.includes("*")?{totalCount:u}:{},...c.includes("filterCount")||c.includes("*")?{filterCount:l}:{}}}}}async aggregate(e){let t=At(e.aggregate,e.tableName,e.metadata),r=this.db.collection(e.tableName),o=new pe().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:"mongodb"}),i=o.hasRelationFilters?await je(t.filter,e.tableName,e.metadata,this.db):o.filterTree?xt(o.filterTree,{metadata:e.metadata,rootTable:e.tableName}):{},s=[];Object.keys(i).length>0&&s.push({$match:i});let a={_id:{}},c={};for(let l of t.dimensions){let f=`$${l.field}`,d=l.bucket?{$dateTrunc:{date:f,unit:l.bucket,timezone:l.timezone}}:f;a._id[l.outputKey]=d,c[l.outputKey]=`$_id.${l.outputKey}`}for(let l of t.measures){let f=`$${l.field}`;a[l.outputKey]=l.operation==="count"?{$sum:{$cond:[{$ne:[{$ifNull:[f,null]},null]},1,0]}}:l.operation==="countDistinct"?{$addToSet:f}:{[`$${l.operation}`]:f},c[l.outputKey]=l.operation==="countDistinct"?{$size:{$setDifference:[`$${l.outputKey}`,[null]]}}:`$${l.outputKey}`}return s.push({$group:a},{$project:{_id:0,...c}}),t.sort.length>0&&s.push({$sort:Object.fromEntries(t.sort.map(l=>[l.field,l.direction==="asc"?1:-1]))}),t.limit!==void 0&&s.push({$skip:(t.page-1)*t.limit},{$limit:t.limit}),e.debugMode?{pipeline:s,explain:await r.aggregate(s).explain()}:{data:(await r.aggregate(s).toArray()).map(se)}}normalizePaginationValue(e,t,r){if(e==null)return;let o;if(typeof e=="number")o=e;else if(typeof e=="string"&&/^\d+$/.test(e))o=Number(e);else throw new Error(`${t} must be a ${r===1?"positive":"non-negative"} integer`);if(!Number.isSafeInteger(o)||o<r)throw new Error(`${t} must be a ${r===1?"positive":"non-negative"} integer`);return o}async selectLegacy(e,t){let r=[],o=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,i=t.metadata?.tables?.get(e.table),s=i?.relations&&i.relations.length>0;if(!e.mongoFieldsExpanded&&(e.fields&&e.fields.length>0||o||s)){let l=e.plan,f=e.fields&&e.fields.length>0?e.fields:["*"];if(e.fields&&e.fields.length>0&&l?.fieldTree){if(e.mongoFieldsExpanded=zi(l.fieldTree,t.metadata),o){let d=await tt(t.metadata,e.table,[],e.deep),p=new Set(e.mongoFieldsExpanded.relations.map(g=>g.propertyName));e.mongoFieldsExpanded.relations.push(...d.relations.filter(g=>!p.has(g.propertyName)))}}else console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await tt(t.metadata,e.table,f,e.deep);if(this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let d=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:d.scalarFields},r=d.hiddenFields}}e.where&&(e.where=e.where.map(l=>l.field.includes(".")?l:{...l,field:`${e.table}.${l.field}`}));let a=this.db.collection(e.table);if(e.pipeline)return t.debugLog?.push({type:"MongoDB Custom Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(e.pipeline))}),t.execute?{results:(await a.aggregate(e.pipeline).toArray()).map(se),pipeline:e.pipeline}:{results:[],pipeline:e.pipeline};let{results:c,pipeline:u}=await Fn(a,e,{db:this.db,metadata:t.metadata,dbType:t.dbType,debugLog:t.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService,execute:t.execute});return this.mongoPhysicalMigrationService&&t.execute?{results:await this.mongoPhysicalMigrationService.applyReadFallback(e.table,c,r),pipeline:u}:{results:c,pipeline:u}}};qe();var Gi=require("util"),In=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;try{t=typeof e=="string"?e:JSON.stringify(e)}catch{try{t=(0,Gi.inspect)(e,{depth:4,maxArrayLength:100,maxStringLength:4e3,customInspect:!1,getters:!1})}catch{t="[Unserializable]"}}return this.context?`[${this.context}] ${t}`:t}};Se();Se();var Ha=new Set(["_and","_or","_not"]),Va=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]);function ct(n){if(!n||typeof n!="object")return!1;let e=new WeakSet,t=[n];try{for(;t.length>0;){let r=t.pop();if(e.has(r))continue;e.add(r);let o=Object.getOwnPropertyDescriptors(r);for(let[i,s]of Object.entries(o)){if(!s.enumerable)continue;if(s.get||s.set||Ha.has(i))return!0;if(Va.has(i))continue;let a=s.value;a&&typeof a=="object"&&t.push(a)}}}catch{return!0}return!1}var Eo=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"],Ga=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function kr(n){if(typeof n!="string"||!Ga.test(n))throw new Error("Invalid UUID filter value")}function Ya(n){return String(n).replace(/=/g,"==").replace(/%/g,"=%").replace(/_/g,"=_")}function Xa(n){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[n]||n}function vn(n,e,t){if(!t)return!1;let r=n;if(n.includes(".")){let s=n.split(".");r=s[s.length-1]}let o=t.columns.find(s=>s.name===r);if(!o)return!1;let i=o.type?.toLowerCase()||"";return i==="uuid"||i==="uuidv4"||i.includes("uuid")}function Za(n,e,t,r,o){return r!=="postgres"||typeof e!="string"||vn(n,t,o)&&kr(e),e}function Yi(n,e,t,r,o,i,s){let a=o&&!e.includes(".")?`${o}.${e}`:e,c=Je(a,i??"postgres"),u=vn(e,o,s),l=["_eq","_neq","_gt","_gte","_lt","_lte"].includes(t)?Za(e,r,o,i,s):r;switch(t){case"_eq":r===null?n.whereNull(a):u&&i==="postgres"&&typeof r=="string"?n.whereRaw(`${c} = ?::uuid`,[r]):n.where(a,"=",l);break;case"_neq":r===null?n.whereNotNull(a):u&&i==="postgres"&&typeof r=="string"?n.whereRaw(`${c} != ?::uuid`,[r]):n.where(a,"!=",l);break;case"_gt":u&&i==="postgres"&&typeof r=="string"?n.whereRaw(`${c} > ?::uuid`,[r]):n.where(a,">",l);break;case"_gte":u&&i==="postgres"&&typeof r=="string"?n.whereRaw(`${c} >= ?::uuid`,[r]):n.where(a,">=",l);break;case"_lt":u&&i==="postgres"&&typeof r=="string"?n.whereRaw(`${c} < ?::uuid`,[r]):n.where(a,"<",l);break;case"_lte":u&&i==="postgres"&&typeof r=="string"?n.whereRaw(`${c} <= ?::uuid`,[r]):n.where(a,"<=",l);break;case"_in":let f=r;if(Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]),u&&i==="postgres"){for(let p of f)kr(p);n.whereRaw(`${c} = ANY(?::uuid[])`,[f])}else n.whereIn(a,f);break;case"_not_in":case"_nin":let d=r;if(Array.isArray(d)||(d=typeof d=="string"&&d.includes(",")?d.split(",").map(p=>p.trim()):[d]),u&&i==="postgres"){for(let p of d)kr(p);n.whereRaw(`${c} != ALL(?::uuid[])`,[d])}else n.whereNotIn(a,d);break;case"_contains":case"_starts_with":case"_ends_with":{let p=Ya(r),g=t==="_contains"?`%${p}%`:t==="_starts_with"?`${p}%`:`%${p}`;i==="postgres"?n.whereRaw(`lower(unaccent(${c})) ILIKE lower(unaccent(?)) ESCAPE '='`,[g]):i==="sqlite"?n.whereRaw(`lower(${c}) LIKE lower(?) ESCAPE '='`,[g]):n.whereRaw(`lower(${c}) COLLATE utf8mb4_general_ci LIKE lower(?) COLLATE utf8mb4_general_ci ESCAPE '='`,[g]);break}case"_between":if(!Array.isArray(r)||r.length!==2)throw new Error("Invalid SQL _between filter");n.whereBetween(a,[r[0],r[1]]);break;case"_is_null":r===!0?n.whereNull(a):n.whereNotNull(a);break;case"_is_not_null":r===!0?n.whereNotNull(a):n.whereNull(a);break;default:n.where(a,Xa(t),r)}}function el(n,e,t){if(n==="_and"||n==="_or"||n==="_not"||!t)return!0;let r=n.split(".");if(r.length>1&&(!e||r[0]!==e))return!1;let o=r[r.length-1],i=t.columns?.some(a=>a.name===o),s=t.relations?.some(a=>a.propertyName===o);return i||s}function Ot(n,e,t,r="and",o,i){if(!(!e||typeof e!="object")){if(Object.keys(e).length===0){n.whereRaw("1 = 1");return}if(Array.isArray(e)){for(let s of e)r==="and"?n.where(function(){Ot(this,s,t,"and",o,i)}):n.orWhere(function(){Ot(this,s,t,"and",o,i)});return}for(let[s,a]of Object.entries(e)){if(!el(s,t,i))throw new Error(`Invalid SQL filter field: ${s}`);if(s==="_and"){if(Array.isArray(a)){if(a.length===0){n.whereRaw("1 = 1");continue}n.where(function(){for(let c of a)this.where(function(){Ot(this,c,t,"and",o,i)})})}continue}if(s==="_or"){if(Array.isArray(a)){if(a.length===0){n.whereRaw("1 = 0");continue}n.where(function(){for(let c of a)this.orWhere(function(){Ot(this,c,t,"and",o,i)})})}continue}if(s==="_not"){let c=function(){Ot(this,a,t,"and",o,i)};r==="or"?n.orWhereNot(c):n.whereNot(c);continue}if(typeof a=="object"&&a!==null){let c=Object.keys(a),u=c.some(l=>Eo.includes(l));if(u&&c.some(l=>!Eo.includes(l)))throw new Error(`Invalid SQL filter operator for field: ${s}`);if(u)for(let[l,f]of Object.entries(a))Eo.includes(l)&&(r==="and"?n.where(function(){Yi(this,s,l,f,t,o,i)}):n.orWhere(function(){Yi(this,s,l,f,t,o,i)}));else{let l=t&&!s.includes(".")?`${t}.${s}`:s,f=Je(l,o??"postgres");vn(s,t,i)&&o==="postgres"&&typeof a=="string"?(kr(a),r==="and"?n.whereRaw(`${f} = ?::uuid`,[a]):n.orWhereRaw(`${f} = ?::uuid`,[a])):r==="and"?n.where(l,"=",a):n.orWhere(l,"=",a)}}else{let c=t&&!s.includes(".")?`${t}.${s}`:s,u=Je(c,o??"postgres"),l=vn(s,t,i);a===null?r==="and"?n.whereNull(c):n.orWhereNull(c):l&&o==="postgres"&&typeof a=="string"?(kr(a),r==="and"?n.whereRaw(`${u} = ?::uuid`,[a]):n.orWhereRaw(`${u} = ?::uuid`,[a])):r==="and"?n.where(c,"=",a):n.orWhere(c,"=",a)}}}}function ut(n,e,t,r,o){return!e||typeof e!="object"||Ot(n,e,t,"and",r,o),n}function Xi(n){let e=String(n??0);if(!/^\d+$/.test(e))throw new Error("Database count is not a non-negative integer");let t=Number(e);if(!Number.isSafeInteger(t))throw new Error("Database count exceeds JavaScript safe integer range");return t}async function Mn(n,e,t,r,o){let i={};if(r.includes("totalCount")||r.includes("*")){let s=await n(t).count("* as count").first();i.totalCount=Xi(s?.count)}if(r.includes("filterCount")||r.includes("*")){let s=e.clone().clearOrder().clear("limit").clear("offset"),a=await n.from(s.as("enfyra_count_source")).count("* as count").first();i.filterCount=Xi(a?.count)}return i}function Er(n,e,t){if(!n||!t)return n;let r=t.tables?.get(e);if(!r)return n;if(Array.isArray(n))return n.map(i=>Er(i,e,t));if(typeof n!="object"||Buffer.isBuffer(n))return n;let o={...n};for(let i of r.columns)if(i.type==="simple-json"&&o[i.name]&&typeof o[i.name]=="string")try{o[i.name]=JSON.parse(o[i.name])}catch{}for(let i of r.relations??[]){let s=i.propertyName;if(!Object.prototype.hasOwnProperty.call(o,s))continue;let a=i.targetTableName||i.targetTable;a&&(o[s]=Er(o[s],a,t))}return o}var ns=require("crypto");ft();Se();var tl=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);function Zi(n,e){if(!e)return!1;let t=e.columns.find(o=>o.name===n);if(!t)return!1;let r=t.type?.toLowerCase()||"";return r==="uuid"||r==="uuidv4"||r.includes("uuid")}function es(n){return n===!0||n==="true"?!0:n===!1||n==="false"?!1:null}function ts(n){return n&&ee(n)?.name||"id"}function An(n,e,t,r,o,i,s){let a=Zi(e,o),c=Zi(r,i),u=`${I(n,s)}.${I(e,s)}`,l=`${I(t,s)}.${I(r,s)}`;if(s==="postgres"){if(a&&!c)return`${u} = ${l}::uuid`;if(!a&&c)return`${u}::uuid = ${l}`}return`${u} = ${l}`}function rl(n){if(!n||typeof n!="object"||Array.isArray(n))return!1;let e=n;return Object.keys(e).length!==1||!e.id||typeof e.id!="object"||Array.isArray(e.id)?!1:Object.keys(e.id).every(t=>tl.has(t))}function nl(n,e,t){return`__enfyra_relation_${(0,ns.createHash)("sha256").update(JSON.stringify([t,n,e])).digest("hex").slice(0,16)}`}function rs(n,e,t){return n(e===t?e:{[t]:e})}async function os(n,e,t,r,o,i,s){let a=o.relations.find(g=>g.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${o.name}"`);let c=a.targetTableName||a.targetTable;if(!c)throw new Error(`Relation "${t}" in table "${o.name}" is missing target metadata`);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn&&rl(r))return null;let u=s?await s(c):null,l=nl(t,c,e),f=ts(o),d=ts(u),p;switch(a.type){case"one-to-many":{if(!a.foreignKeyColumn)throw new Error(`Relation "${t}" is missing a foreign key`);p=rs(n,c,l).select(n.raw("1")).whereRaw(An(l,a.foreignKeyColumn,e,f,u,o,i));break}case"many-to-many":{if(!a.junctionTableName||!a.junctionSourceColumn||!a.junctionTargetColumn)throw new Error(`Relation "${t}" is missing junction metadata`);let g=s?await s(a.junctionTableName):null;p=n(a.junctionTableName).select(n.raw("1")).join({[l]:c},n.raw(An(a.junctionTableName,a.junctionTargetColumn,l,d,g,u,i))).whereRaw(An(a.junctionTableName,a.junctionSourceColumn,e,f,g,o,i));break}case"many-to-one":case"one-to-one":{if(!a.foreignKeyColumn)throw new Error(`Relation "${t}" is missing a foreign key`);p=rs(n,c,l).select(n.raw("1")).whereRaw(An(l,d,e,a.foreignKeyColumn,u,o,i));break}default:throw new Error(`Unsupported relation type: ${a.type}`)}return u?await ss(n,p,r,l,u,i,s,c):ut(p,r,l,i),{query:p}}async function is(n,e,t,r,o,i,s){let a=await os(n,e,t,r,o,i,s);return a?a.query.toString():null}function ol(n,e,t){for(let[r,o]of Object.entries(t))switch(r){case"_is_null":{let i=es(o);i===!0?n.whereNull(e):i===!1&&n.whereNotNull(e);break}case"_is_not_null":{let i=es(o);i===!0?n.whereNotNull(e):i===!1&&n.whereNull(e);break}case"_eq":o===null?n.whereNull(e):n.where(e,"=",o);break;case"_neq":o===null?n.whereNotNull(e):n.where(e,"!=",o);break;case"_in":{let i=(Array.isArray(o)?o:[o]).filter(s=>s!==null);i.length===0?n.whereRaw("1 = 0"):n.whereIn(e,i);break}case"_not_in":case"_nin":{let i=Array.isArray(o)?o:[o];i.some(s=>s===null)?n.whereRaw("1 = 0"):i.length===0?n.whereRaw("1 = 1"):n.whereNotIn(e,i);break}case"_gt":n.where(e,">",o);break;case"_gte":n.where(e,">=",o);break;case"_lt":n.where(e,"<",o);break;case"_lte":n.where(e,"<=",o);break;default:throw new Error(`Unsupported direct relation operator: ${r}`)}}function dt(n){return{constant:n,apply(e){e.whereRaw(n?"1 = 1":"1 = 0")}}}function xo(n){if(n.some(t=>t.constant===!1))return dt(!1);let e=n.filter(t=>t.constant!==!0);return e.length===0?dt(!0):{apply(t){for(let r of e)r.apply(t)}}}function il(n){if(n.some(t=>t.constant===!0))return dt(!0);let e=n.filter(t=>t.constant!==!1);return e.length===0?dt(!1):{apply(t){t.where(function(){e.forEach((r,o)=>{let i=function(){r.apply(this)};o===0?this.where(i):this.orWhere(i)})})}}}function sl(n){return n.constant!==void 0?dt(!n.constant):{apply(e){e.whereNot(function(){n.apply(this)})}}}async function al(n,e,t,r,o,i){let{fieldFilters:s,relationFilters:a}=Ae(e,r),c=[];for(let[u,l]of Object.entries(a)){let f=r.relations.find(g=>g.propertyName===u),d=await os(n,t,u,l,r,o,i);if(d){c.push(d);continue}if(!f?.foreignKeyColumn)throw new Error(`Relation "${u}" has no direct foreign key`);let p=l?.id;if(!p||typeof p!="object"||Array.isArray(p))throw new Error(`Relation "${u}" has an invalid ID filter`);c.push({field:`${t}.${f.foreignKeyColumn}`,idFilter:p})}return Object.keys(s).length===0&&c.length===0?dt(!0):{apply(u){Object.keys(s).length>0&&ut(u,s,t,o,r);for(let l of c)"query"in l?u.whereExists(l.query):ol(u,l.field,l.idFilter)}}}async function xr(n,e,t,r,o,i){if(!e||typeof e!="object")return dt(!0);if(Array.isArray(e))return xo(await Promise.all(e.map(c=>xr(n,c,t,r,o,i))));let s=[],a=Object.entries(e).filter(([c])=>c!=="_and"&&c!=="_or"&&c!=="_not");return a.length>0&&s.push(await al(n,Object.fromEntries(a),t,r,o,i)),Array.isArray(e._and)&&s.push(xo(await Promise.all(e._and.map(c=>xr(n,c,t,r,o,i))))),Array.isArray(e._or)&&s.push(il(await Promise.all(e._or.map(c=>xr(n,c,t,r,o,i))))),Object.prototype.hasOwnProperty.call(e,"_not")&&s.push(sl(await xr(n,e._not,t,r,o,i))),xo(s)}async function ss(n,e,t,r,o,i,s,a=r){(await xr(n,t,r,o,i,s)).apply(e)}async function Nt(n,e,t,r,o,i,s){await ss(n,e,t,r,o,i,s)}re();ft();Se();var Cr=class{constructor(e,t){this.metadata=e;this.dbType=t}buildRelationCountSortSubquery(e,t){let r=t.relationMeta,o=t.relationName||t.field,i=r?.targetTableName||r?.targetTable,s=this.metadata?.tables?.get(e),a=ee(s)?.name||"id",c=I(e,this.dbType),u=I(a,this.dbType);if(!r||!i)throw new w(`Sort relation '${o}' does not exist on '${e}'.`);if(r.type==="one-to-many"){let l=r.foreignKeyColumn||r.mappedBy;if(!l)throw new w(`Sort function '_count(${o})' cannot resolve relation key on '${e}'.`);let f=I(i,this.dbType),d=I(l,this.dbType),p=i===e?I(e==="__relation_sort_target"?"__relation_sort_target_1":"__relation_sort_target",this.dbType):f;return`(SELECT COUNT(*) FROM ${p===f?f:`${f} AS ${p}`} WHERE ${p}.${d} = ${c}.${u})`}if(r.type==="many-to-many"){let l=this.resolveManyToManyContract(r,o,e),f=I(l.tableName,this.dbType),d=I(l.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${f} WHERE ${f}.${d} = ${c}.${u})`}throw new w(`Sort function '_count(${o})' is only supported for list relations on '${e}'.`)}buildRelationAggregateSortSubquery(e,t){let r=t.relationMeta,o=t.relationName||t.field,i=t.aggregateField,s=r?.targetTableName||r?.targetTable,a=this.metadata?.tables?.get(e),c=this.metadata?.tables?.get(s),u=ee(a)?.name||"id",l=ee(c)?.name||"id",f=I(e,this.dbType),d=I(u,this.dbType),p=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!p||!r||!s||!i)throw new w(`Sort function '${t.field}' is not supported on '${e}'.`);let g=I(s,this.dbType),h=I(i,this.dbType),y=s===e?I(e==="__relation_sort_target"?"__relation_sort_target_1":"__relation_sort_target",this.dbType):g,m=y===g?g:`${g} AS ${y}`;if(r.type==="one-to-many"){let b=r.foreignKeyColumn||r.mappedBy;if(!b)throw new w(`Sort function '_${t.function}(${o}.${i})' cannot resolve relation key on '${e}'.`);let _=I(b,this.dbType);return`(SELECT ${p}(${y}.${h}) FROM ${m} WHERE ${y}.${_} = ${f}.${d})`}if(r.type==="many-to-many"){let b=this.resolveManyToManyContract(r,o,e),_=I(b.tableName,this.dbType),S=I(b.sourceColumn,this.dbType),E=I(b.targetColumn,this.dbType),C=I(l,this.dbType);return`(SELECT ${p}(${y}.${h}) FROM ${_} JOIN ${m} ON ${y}.${C} = ${_}.${E} WHERE ${_}.${S} = ${f}.${d})`}throw new w(`Sort function '_${t.function}(${o}.${i})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,r){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new w(`Relation '${t}' on '${r}' is missing physical many-to-many metadata.`)}};Rr();Se();ft();et();async function On(n,e,t,r,o,i,s){if(!r)return{select:t};let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(Fo(),us)),c=await a(e,t,r,o,i,s);return{select:c.select,batchFetchDescriptors:c.batchFetchDescriptors}}function Fr(n){let e=n;return e?async t=>{let r=e.tables?.get(t);return r?{name:r.name,columns:(r.columns||[]).map(o=>({name:o.name,type:o.type,isPrimary:o.isPrimary})),relations:r.relations||[]}:null}:null}function Nn(n,e,t,r,o){let i=n.targetTableName||n.targetTable;if(!i)return null;if(!(n.type==="many-to-one"||n.type==="one-to-one"&&n.isInverse===!1))throw new Error("Relation sorting requires an explicitly parent-owned to-one relation");let a=n.foreignKeyColumn||(n.propertyName?ie(n.propertyName):null);if(!a)throw new Error("Relation sorting requires a parent foreign-key column");let c=p=>I(p,o),u=r?.tables?.get(i);if(!u)throw new Error(`SQL relation sort requires target metadata for '${i}'`);let l=ee(u)?.name;if(!l)throw new Error(`SQL relation sort requires a primary key for '${i}'`);if(!u.columns?.some(p=>p.name===e))throw new Error(`SQL relation sort requires target column '${e}' on '${i}'`);let f=r?.tables?.get(t);if(!f)throw new Error(`SQL relation sort requires parent metadata for '${t}'`);if(!f.columns?.some(p=>p.name===a))throw new Error(`SQL relation sort requires foreign-key column '${a}' on '${t}'`);let d=t==="__relation_sort_target"?"__relation_sort_target_1":"__relation_sort_target";return`(SELECT ${c(d)}.${c(e)} FROM ${c(i)} AS ${c(d)} WHERE ${c(d)}.${c(l)} = ${c(t)}.${c(a)})`}Se();var pl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Io(n){if(typeof n!="string"||!pl.test(n))throw new Error("Invalid UUID filter value")}function Pn(n){return String(n).replace(/=/g,"==").replace(/%/g,"=%").replace(/_/g,"=_")}function Bt(n,e,t,r,o){for(let i of e){let s=i.field.split("."),a=s.length>1?s[0]:t,c=s[s.length-1],l=["=","!=",">","<",">=","<=","like"].includes(i.operator)?Ir(r,a,c,i.value):i.value;switch(i.operator){case"=":n=n.where(i.field,"=",l);break;case"!=":n=n.where(i.field,"!=",l);break;case">":n=n.where(i.field,">",l);break;case"<":n=n.where(i.field,"<",l);break;case">=":n=n.where(i.field,">=",l);break;case"<=":n=n.where(i.field,"<=",l);break;case"like":n=n.where(i.field,"like",l);break;case"in":let f=Array.isArray(i.value)?i.value.map(b=>Ir(r,a,c,b)):[l];n=n.whereIn(i.field,f);break;case"not in":let d=Array.isArray(i.value)?i.value.map(b=>Ir(r,a,c,b)):[l];n=n.whereNotIn(i.field,d);break;case"is null":n=n.whereNull(i.field);break;case"is not null":n=n.whereNotNull(i.field);break;case"_contains":n=n.whereRaw("?? LIKE ? ESCAPE '='",[i.field,`%${Pn(i.value)}%`]);break;case"_starts_with":n=n.whereRaw("?? LIKE ? ESCAPE '='",[i.field,`${Pn(i.value)}%`]);break;case"_ends_with":n=n.whereRaw("?? LIKE ? ESCAPE '='",[i.field,`%${Pn(i.value)}`]);break;case"_between":let p=i.value;if(typeof p=="string"&&(p=p.split(",").map(b=>b.trim())),!Array.isArray(p)||p.length!==2)throw new Error("Invalid _between filter value");let g=Ir(r,a,c,p[0]),h=Ir(r,a,c,p[1]);n=n.whereBetween(i.field,[g,h]);break;case"_is_null":n=l===!0||l==="true"?n.whereNull(i.field):n.whereNotNull(i.field);break;case"_is_not_null":n=l===!0||l==="true"?n.whereNotNull(i.field):n.whereNull(i.field);break}}return n}function vr(n,e,t,r){let o=[],i=t;if(!n||typeof n!="object")return o;for(let[s,a]of Object.entries(n))if(s==="_and"&&Array.isArray(a)){let c=a.map(u=>{let l=vr(u,e,t,r);return l.length>0?`(${l.join(" AND ")})`:null}).filter(u=>u!==null);c.length>0&&o.push(`(${c.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let c=a.map(u=>{let l=vr(u,e,t,r);return l.length>0?`(${l.join(" AND ")})`:null}).filter(u=>u!==null);c.length>0&&o.push(`(${c.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let c=vr(a,e,t,r);c.length>0&&o.push(`NOT (${c.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[c,u]of Object.entries(a)){let l=`${I(e,r)}.${I(s,r)}`,f=i.columns?.find(h=>h.name===s),d=f&&(f.type?.toLowerCase()==="uuid"||f.type?.toLowerCase().includes("uuid")),p=["_eq","_neq","_gt","_gte","_lt","_lte"].includes(c);d&&r==="postgres"&&u!==null&&p&&Io(u);let g=d&&r==="postgres"&&u!==null&&p?`${we(u,r)}::uuid`:we(u,r);if(c==="_eq")o.push(u===null?`${l} IS NULL`:`${l} = ${g}`);else if(c==="_neq")o.push(u===null?`${l} IS NOT NULL`:`${l} != ${g}`);else if(c==="_gt")o.push(`${l} > ${g}`);else if(c==="_gte")o.push(`${l} >= ${g}`);else if(c==="_lt")o.push(`${l} < ${g}`);else if(c==="_lte")o.push(`${l} <= ${g}`);else if(c==="_is_null")o.push(`${l} IS ${u===!0||u==="true"?"":"NOT "}NULL`);else if(c==="_is_not_null")o.push(`${l} IS ${u===!0||u==="true"?"NOT ":""}NULL`);else if(c==="_in"){let h=Array.isArray(u)?u:[u];if(h.length===0)o.push("FALSE");else{let y=h.map(m=>{d&&r==="postgres"&&m!==null&&Io(m);let b=we(m,r);return d&&r==="postgres"?`${b}::uuid`:b}).join(", ");o.push(`${l} IN (${y})`)}}else if(c==="_not_in"||c==="_nin"){let h=Array.isArray(u)?u:[u];if(h.length===0)o.push("TRUE");else{let y=h.map(m=>{d&&r==="postgres"&&m!==null&&Io(m);let b=we(m,r);return d&&r==="postgres"?`${b}::uuid`:b}).join(", ");o.push(`${l} NOT IN (${y})`)}}else if(c==="_contains"||c==="_starts_with"||c==="_ends_with"){let h=Pn(u).toLowerCase(),y=we(h,r),m=c==="_contains"?r==="mysql"?`CONCAT('%', lower(${y}), '%')`:`'%' || lower(${y}) || '%'`:c==="_starts_with"?r==="mysql"?`CONCAT(lower(${y}), '%')`:`lower(${y}) || '%'`:r==="mysql"?`CONCAT('%', lower(${y}))`:`'%' || lower(${y})`;r==="postgres"?o.push(`lower(unaccent(${l})) ILIKE unaccent(${m}) ESCAPE '='`):r==="mysql"?o.push(`lower(${l}) COLLATE utf8mb4_general_ci LIKE ${m} ESCAPE '='`):o.push(`lower(${l}) LIKE ${m} ESCAPE '='`)}else if(c==="_between"){if(!Array.isArray(u)||u.length!==2)throw new Error("Invalid _between filter value");o.push(`${l} BETWEEN ${we(u[0],r)} AND ${we(u[1],r)}`)}}else{let c=`${I(e,r)}.${I(s,r)}`;o.push(a===null?`${c} IS NULL`:`${c} = ${we(a,r)}`)}return o}function we(n,e="postgres"){if(n==null)return"NULL";if(typeof n=="boolean")return n?"true":"false";if(typeof n=="number"){if(!Number.isFinite(n))throw new Error("Invalid numeric SQL value");return String(n)}if(typeof n=="bigint")return n.toString();let t=Buffer.from(String(n),"utf8").toString("hex");return e==="mysql"?`CONVERT(X'${t}' USING utf8mb4)`:e==="sqlite"?`CAST(X'${t}' AS TEXT)`:`E'${String(n).replace(/\\/g,"\\\\").replace(/'/g,"''")}'`}function Ir(n,e,t,r){if(r==null)return r;let o=n?.tables?.get(e);if(!o?.columns)return r;let i=o.columns.find(s=>s.name===t);if(!i)return r;switch(i.type){case"bigint":{let s=String(r);if(!/^[+-]?\d+$/.test(s))throw new Error("Invalid bigint value");return s}case"int":case"integer":case"smallint":case"tinyint":{let s=String(r);if(!/^[+-]?\d+$/.test(s))throw new Error("Invalid integer value");let a=Number(s);if(!Number.isSafeInteger(a))throw new Error("Integer value exceeds JavaScript safe range");return a}case"decimal":case"numeric":{let s=String(r);if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(s))throw new Error("Invalid decimal value");return s}case"float":case"double":case"real":{let s=Number(r);if(!Number.isFinite(s))throw new Error("Invalid float value");return s}case"boolean":case"bool":if(r===!0||r===!1)return r;if(r==="true"||r==="1"||r===1)return!0;if(r==="false"||r==="0"||r===0)return!1;throw new Error("Invalid boolean value");case"date":case"datetime":case"timestamp":if(typeof r=="string"){let s=new Date(r);if(Number.isNaN(s.getTime()))throw new Error("Invalid date value");return s}return r;default:return r}}re();Se();Rr();var jn=class{constructor(e,t){this.knex=e;this.dbType=t}async aggregate(e){let t=At(e.aggregate,e.tableName,e.metadata),r=this.knex(e.tableName),o=I(e.tableName,this.dbType),i=[],s=[];for(let f of t.dimensions){let d=`${o}.${I(f.field,this.dbType)}`,p=f.bucket?this.buildSqlBucketExpression(d,f.bucket,f.timezone,f.column.type):d;s.push(this.knex.raw(`${p} as ${I(f.outputKey,this.dbType)}`)),i.push(p)}for(let f of t.measures){let d=`${o}.${I(f.field,this.dbType)}`,p=f.operation==="count"?`COUNT(${d})`:f.operation==="countDistinct"?`COUNT(DISTINCT ${d})`:`${f.operation.toUpperCase()}(${d})`;s.push(this.knex.raw(`${p} as ${I(f.outputKey,this.dbType)}`))}let c=new pe().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:this.dbType});c.hasRelationFilters?await Nt(this.knex,r,t.filter,e.tableName,e.metadata?.tables?.get(e.tableName),this.dbType,f=>e.metadata?.tables?.get(f)):c.filterTree&&ue(r,c.filterTree,{dbType:this.dbType,rootTable:e.tableName}),r.select(s),i.length>0&&r.groupByRaw(i.join(", "));for(let f of t.sort)r.orderByRaw(`${I(f.field,this.dbType)} ${f.direction.toUpperCase()}`);return t.limit!==void 0&&r.limit(t.limit).offset((t.page-1)*t.limit),{data:(await r).map(f=>{let d={...f};for(let p of t.measures){let g=d[p.outputKey];if(typeof g=="string"&&/^-?\d+$/.test(g)){let h=Number(g);Number.isSafeInteger(h)&&(d[p.outputKey]=h)}}return d})}}buildSqlBucketExpression(e,t,r,o){let i=we(r,this.dbType);if(this.dbType==="postgres"){let c=`(${["timestamp without time zone","date"].includes(o.toLowerCase())?`(${e}::timestamp AT TIME ZONE 'UTC')`:e} AT TIME ZONE ${i})`;return`DATE_TRUNC(${we(t,this.dbType)}, ${c})`}if(this.dbType==="mysql"){let s=`CONVERT_TZ(${e}, '+00:00', ${i})`;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"?`DATE_SUB(DATE(${s}), INTERVAL WEEKDAY(${s}) DAY)`: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 w(`Aggregate time bucket is not supported on ${this.dbType}`)}};var pt=class n{constructor(e,t,r,o){this.knex=e;this.dbType=t;this.knexService=r;this.maxQueryDepth=o;this.logger=new In(n.name)}async execute(e){let t=performance.now(),r=e.debugLog||[],o=e.debugTrace;if(e.filter&&Le(e.filter,e.tableName,e.metadata),!e.plan){let $=new pe;e={...e,plan:$.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:this.dbType})}}let i=e.plan;e={...e,fields:i.rawFields};let s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,c=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,u=i.rawFields&&i.rawFields.length>0&&!i.rawFields.includes("*");if(i.joins.length===0&&!i.hasRelationFilters&&!i.hasRelationSort&&!c&&!a&&u){o&&o.setQueryPath("simple");let $=await this.executeSimple(e,i);return o&&o.dur("sql_executor",t,{table:e.tableName}),$}let f={table:e.tableName,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?f.fields=e.fields:typeof e.fields=="string"&&(f.fields=e.fields.split(",").map($=>$.trim())));let d=e.filter;if(e.filter&&!ct(e.filter)){f.where=[];for(let[$,T]of Object.entries(e.filter))if(typeof T=="object"&&T!==null)for(let[F,L]of Object.entries(T)){let A;if(F==="_eq")A="=";else if(F==="_neq")A="!=";else if(F==="_in")A="in";else if(F==="_not_in"||F==="_nin")A="not in";else if(F==="_gt")A=">";else if(F==="_gte")A=">=";else if(F==="_lt")A="<";else if(F==="_lte")A="<=";else if(F==="_contains")A="_contains";else if(F==="_starts_with")A="_starts_with";else if(F==="_ends_with")A="_ends_with";else if(F==="_between")A="_between";else if(F==="_is_null")A="_is_null";else if(F==="_is_not_null")A="_is_not_null";else if(F==="_like")A="like";else if(F==="_ilike")A="ilike";else continue;f.where.push({field:$,operator:A,value:L})}else f.where.push({field:$,operator:"=",value:T})}if(e.sort){let $=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(T=>T.trim());f.sort=$.map(T=>{let F=T.trim();return F.startsWith("-")?{field:F.substring(1),direction:"desc"}:{field:F,direction:"asc"}})}else f.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,g=p===void 0||Number.isNaN(p)?void 0:p<0?0:p,h=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,y=h===void 0||Number.isNaN(h)?void 0:h;y&&g!==void 0?(f.offset=(y-1)*g,f.limit=g):g!==void 0&&(f.limit=g);let m=e.plan?.sortItems??(f.sort??[]).map($=>({joinId:null,field:$.field,direction:$.direction,fullPath:$.field})),b=[],_=[];for(let $ of m){if($.function==="count"){let T={sql:this.buildRelationCountSortSubquery(f.table,$,e.metadata),direction:$.direction};_.push(T);continue}if($.function==="max"||$.function==="min"){let T={sql:this.buildRelationAggregateSortSubquery(f.table,$,e.metadata),direction:$.direction};_.push(T);continue}if($.joinId===null){if($.field.includes(".")&&!e.plan){let F=$.field.split(".")[0];if(e.metadata?.tables?.get(f.table)?.relations?.some(Re=>Re.propertyName===F))continue}let T={field:$.field.includes(".")?$.field:`${f.table}.${$.field}`,direction:$.direction};b.push(T),_.push(T)}else{let T=e.plan?.joins.find(F=>F.id===$.joinId);if(T&&(T.relationType==="many-to-one"||T.relationType==="one-to-one")){let F=Nn(T.relationMeta,$.field,f.table,e.metadata,this.dbType);if(F){let L={sql:F,direction:$.direction};_.push(L)}}}}let S=[],E=[];if(f.fields&&f.fields.length>0||c||a){let $=Fr(e.metadata),T=f.fields??["*"],F=await On(this.knex,f.table,T,$,this.dbType,this.maxQueryDepth,e.deep);E=F.select.map(L=>$?this.knex.raw(L):L),S=F.batchFetchDescriptors||[]}f.where&&(f.where=f.where.map($=>$.field.includes(".")?$:{...$,field:`${f.table}.${$.field}`})),f.sort=b;let C=this.knex(f.table),x=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map($=>$.trim()).filter(Boolean),v=x.includes("filterCount")||x.includes("*"),R=x.includes("totalCount")||x.includes("*");if(f.select||E.length>0){let $=(f.select??[]).map(T=>typeof T=="string"&&T.trim().startsWith("(")?this.knex.raw(T):typeof T=="string"&&/ as /i.test(T)?this.knex.raw(T):T);C=C.select([...$,...E])}let M=i.rawFields!==void 0&&i.rawFields.length===0&&!c;if(M&&C.select(this.knex.raw("1 as ??",["__enfyra_empty_selection"])),!M&&!f.select&&E.length===0&&(v||R)&&C.select(`${f.table}.*`),v&&C.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),R){let $=I(f.table,this.dbType);C.select(this.knex.raw(`(SELECT COUNT(*) FROM ${$}) as __total_count__`))}let O=["table_definition","column_definition","relation_definition","method_definition"].includes(f.table);if(d&&(ct(d)||Object.keys(d).length>0)){let $=e.metadata?.tables?.get(f.table);(!O&&$&&$.relations&&$.relations.length>0?Ae(d,$).hasRelations:!1)?await Nt(this.knex,C,d,f.table,$,this.dbType,F=>e.metadata?.tables?.get(F)):e.plan?.filterTree?ue(C,e.plan.filterTree,{dbType:this.dbType,rootTable:f.table}):(this.logger.debug(`buildWhereClause fallback for table=${f.table}`),C=ut(C,d,f.table,this.dbType,$))}else e.plan?.filterTree?ue(C,e.plan.filterTree,{dbType:this.dbType,rootTable:f.table}):f.where&&f.where.length>0&&(C=Bt(C,f.where,f.table,e.metadata,this.dbType));for(let $ of _)if($.field){let T=$.field.includes(".")?$.field:`${f.table}.${$.field}`;C=C.orderBy(T,$.direction)}else $.sql&&(C=C.orderByRaw(`${$.sql} ${$.direction.toUpperCase()}`));f.groupBy&&(C=C.groupBy(f.groupBy)),f.offset&&(C=C.offset(f.offset)),f.limit!==void 0&&f.limit>0&&(C=C.limit(f.limit));let j=0;r&&r.push({type:"SQL Query",table:f.table,sql:C.toSQL().toNative()});let N;if(e.debugMode&&(N=C.toSQL().toNative().sql),e.debugMode&&o){let $=C.toSQL().toNative();o.setSql($.sql);try{let T=$.sql.replace(/\$\d+/g,"?"),F=await this.knex.raw(`EXPLAIN ${T}`,$.bindings);o.setExplain(this.dbType==="postgres"?F.rows:F[0])}catch(T){o.setExplain({error:String(T)})}}let P,Y=performance.now();P=await C,o&&o.dur("db_execute",Y,{table:e.tableName});let te=await this.resolveEmptyPageMeta(C,f.table,x,P.length),k=te.filterCount??0;if(j=te.totalCount??0,v&&P.length>0&&(k=Number(P[0].__filter_count__||0),P.forEach($=>{delete $.__filter_count__})),R&&P.length>0&&P[0].__total_count__!==void 0&&(j=Number(P[0].__total_count__||0),P.forEach($=>{delete $.__total_count__})),S&&S.length>0&&P.length>0){let $=Fr(e.metadata);if($){let{executeBatchFetches:T}=await Promise.resolve().then(()=>(Ao(),ds));await T(this.knex,P,S,$,this.maxQueryDepth??3,0,f.table,this.dbType,e.metadata,o)}}if(this.knexService){let $=performance.now();P=await this.knexService.parseResult(P,f.table),o&&o.dur("db_parseResult",$,{table:e.tableName})}else P=Er(P,f.table,e.metadata);return M&&(P=P.map(()=>({}))),o&&(o.setQueryPath("full"),o.dur("sql_executor",t,{table:e.tableName})),{data:P,...x.length>0&&{meta:{...x.includes("totalCount")||x.includes("*")?{totalCount:j}:{},...x.includes("filterCount")||x.includes("*")?{filterCount:k}:{}}},...N!==void 0&&{sql:N}}}buildRelationCountSortSubquery(e,t,r){return new Cr(r,this.dbType).buildRelationCountSortSubquery(e,t)}buildRelationAggregateSortSubquery(e,t,r){return new Cr(r,this.dbType).buildRelationAggregateSortSubquery(e,t)}async resolveEmptyPageMeta(e,t,r,o){return o>0||r.length===0?{}:Mn(this.knex,e,t,r,!1)}async executeSimple(e,t){let r=e.tableName,o=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],i=this.knex(r).select(o);t.filterTree&&ue(i,t.filterTree,{dbType:this.dbType,rootTable:r});for(let y of t.sortItems){let m=y.field.includes(".")?y.field:`${r}.${y.field}`;i=i.orderBy(m,y.direction)}t.limit!==void 0&&t.limit>0&&(i=i.limit(t.limit)),t.offset!==void 0&&(i=i.offset(t.offset));let s=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(y=>y.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),c=s.includes("totalCount")||s.includes("*");if(a&&i.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),c){let y=I(r,this.dbType);i.select(this.knex.raw(`(SELECT COUNT(*) FROM ${y}) as __total_count__`))}let u=e.debugTrace,l;if(e.debugMode){let y=i.toSQL().toNative();if(l=y.sql,u){u.setSql(y.sql);try{let m=y.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${m}`,y.bindings);u.setExplain(this.dbType==="postgres"?b.rows:b[0])}catch(m){u.setExplain({error:String(m)})}}}let f=performance.now(),d;d=await i,u&&u.dur("db_execute",f,{table:r}),this.knexService?d=await this.knexService.parseResult(d,r):d=Er(d,r,e.metadata);let p=await this.resolveEmptyPageMeta(i,r,s,d.length),g=p.filterCount??0,h=p.totalCount??0;return a&&d.length>0&&(g=Number(d[0].__filter_count__||0),d.forEach(y=>delete y.__filter_count__)),c&&d.length>0&&(h=Number(d[0].__total_count__||0),d.forEach(y=>delete y.__total_count__)),{data:d,...s.length>0&&{meta:{...c?{totalCount:h}:{},...a?{filterCount:g}:{}}},...l!==void 0&&{sql:l}}}async aggregate(e){return new jn(this.knex,this.dbType).aggregate(e)}};var Ln=require("mongodb"),qn=class{constructor(e){this.databaseConfigService=e}safeObjectId(e){if(!Ln.ObjectId)return e;if(typeof e=="string")try{return new Ln.ObjectId(e)}catch{return e}return e}whereToFilter(e){let t={},r=this.databaseConfigService.isMongoDb();for(let[o,i]of Object.entries(e))o==="id"||o==="_id"?r?t._id=this.normalizeWhereFilterValue("_id",i):t.id=this.normalizeWhereFilterValue("id",i):t[o]=this.normalizeWhereFilterValue(o,i);return t}normalizeWhereFilterValue(e,t){return this.isFilterOperatorObject(t)?this.databaseConfigService.isMongoDb()&&e==="_id"?this.normalizeMongoIdOperatorValue(t):t:{_eq:this.databaseConfigService.isMongoDb()&&e==="_id"?this.safeObjectId(t):t}}isFilterOperatorObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof Ln.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[r,o]of Object.entries(e))t[r]=Array.isArray(o)?o.map(i=>this.safeObjectId(i)):this.safeObjectId(o);return t}filterToWhere(e){let t=[];for(let[r,o]of Object.entries(e))if(typeof o=="object"&&o!==null&&!Array.isArray(o))for(let[i,s]of Object.entries(o))t.push({field:r,operator:this.mapFilterOperatorToSql(i),value:s});return t}mapFilterOperatorToSql(e){let t={_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"_contains",_starts_with:"_starts_with",_ends_with:"_ends_with",_is_null:"is null",_is_not_null:"is not null"},r=t[e];if(!Object.prototype.hasOwnProperty.call(t,e))throw new Error(`Unsupported filter operator: ${e}`);return r}};var qt=class{constructor(e){this.debugLog=[];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.conditions=new qn(this.databaseConfigService),this.batchInsertBuffer=new en(this.dbType,this.knexService,this.mongoService,t=>this.runMongoMutationInSaga(t))}async runWithPolicy(e,t){if(this.dbType==="mongodb"){if(typeof this.mongoService?.runWithPolicy!="function")throw new Error("MongoDB policy context is not available");return this.mongoService.runWithPolicy(e,t)}if(typeof this.knexService?.runWithPolicy!="function")throw new Error("SQL policy context is not available");return this.knexService.runWithPolicy(e,t)}async runWithFieldPermissionCheck(e,t){if(this.dbType==="mongodb"){if(typeof this.mongoService?.runWithFieldPermissionCheck!="function")throw new Error("MongoDB field-permission context is not available");return this.mongoService.runWithFieldPermissionCheck(e,t)}if(typeof this.knexService?.runWithFieldPermissionCheck!="function")throw new Error("SQL field-permission context is not available");return this.knexService.runWithFieldPermissionCheck(e,t)}async runWithTelemetryContext(e,t){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.runWithQueryContext(e,t):await t()}getDbType(){return this.dbType}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 r=await this.getMetadataForQuery(),o=It(r,e,t,this.dbType);return o._id!==void 0&&(o._id=this.conditions.safeObjectId(o._id)),o}async applyWhereToKnex(e,t,r){let o=await this.getMetadataForQuery();return{query:Bt(e,t,r??"",o,this.dbType)}}async runMongoMutationInSaga(e){return!this.mongoService?.runInSaga||this.mongoService.isInSaga?.()?e():(await this.mongoService.runInSaga(e)).data}async insertWithOptions(e){if(e.batch)return await this.batchInsertBuffer.enqueue(e.table,e.data);if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{if(Array.isArray(e.data)){let t=[];for(let r of e.data){let o=await this.mongoService.insertOne(e.table,r);t.push(se(o))}return t}return this.mongoService.insertOne(e.table,e.data)});if(Array.isArray(e.data)){let t=[];for(let r of e.data){let o=await this.knexService.insertWithCascade(e.table,r);t.push(o)}return t}else return await this.knexService.insertWithCascade(e.table,e.data)}async select(e){let t=performance.now(),r=await this.getMetadataForQuery(),o=performance.now(),s=new pe().plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:r,dbType:this.dbType}),a=e.debugTrace;if(a&&(a.dur("qb_planner",o,{table:e.tableName}),a.setPlan(this.sanitizePlan(s))),this.dbType==="mongodb"){let f=await new lt(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:r,dbType:this.dbType,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),f}let u=await new pt(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:r,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),u}sanitizePlan(e){return{rawFields:e.rawFields,hasRelationFilters:e.hasRelationFilters,hasRelationSort:e.hasRelationSort,joins:e.joins?.length??0,sortItems:e.sortItems,limit:e.limit,offset:e.offset,page:e.page,isSimpleQuery:e.joins?.length===0&&!e.hasRelationFilters&&!e.hasRelationSort}}async updateWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let i=await this.buildMongoFilter(e.where,e.table),s=this.mongoService.collection(e.table),a=this.mongoService.ioSignalPublic?.()??{},c=await s.find(i,a).toArray(),u=[];for(let l of c){let f=await this.mongoService.updateOne(e.table,l._id,e.data);u.push(f)}return u});let t=this.knexService.getKnex(),r=t(e.table);e.where.length>0&&({query:r}=await this.applyWhereToKnex(r,e.where,e.table));let o=await r;for(let i of o)await this.knexService.updateWithCascade(e.table,i.id,e.data);return e.returning?o.length===0?[]:await t(e.table).whereIn("id",o.map(i=>i.id)).select(e.returning):{affected:o.length}}async deleteWithOptions(e){if(!Array.isArray(e.where))throw new TypeError("Delete conditions must be an array");if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),i=this.mongoService.collection(e.table),s=this.mongoService.ioSignalPublic?.()??{},a=await i.find(o,s).toArray(),c=0;for(let u of a)await this.mongoService.deleteOne(e.table,u._id)&&c++;return c});let r=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:r}=await this.applyWhereToKnex(r,e.where,e.table)),await r.delete()}async count(e){if(this.dbType==="mongodb"){let i=e.where?await this.buildMongoFilter(e.where,e.table):{};return this.mongoService.count(e.table,i)}let r=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:r}=await this.applyWhereToKnex(r,e.where,e.table));let o=await r.count("* as count").first();return Number(o?.count||0)}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.conditions.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 lt(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 pt(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,r){return r?.batch?await this.batchInsertBuffer.enqueue(e,t):this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let a=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return se(a)}let o=await this.knexService.insertWithCascade(e,t),i=this.knexService.getKnex(),s=o||t.id;return await i(e).where("id",s).first()})}async createMany(e,t){return t.length===0?[]:this.trackQueryMetric("insert_many",e,async()=>this.dbType==="mongodb"?(await this.runMongoMutationInSaga(async()=>{if(typeof this.mongoService.insertManyWithCascade=="function")return this.mongoService.insertManyWithCascade(e,t);let o=[];for(let i of t)o.push(await this.mongoService.insertOne(e,i));return o})).map(o=>se(o)):this.knexService.insertManyWithCascade(e,t))}async insertMany(e,t){return this.createMany(e,t)}async flushBatchInserts(){await this.batchInsertBuffer.flush()}async update(e,t,r){return this.trackQueryMetric("update",e,async()=>{if(t&&typeof t=="object"&&"where"in t)return await this.updateWithOptions({table:e,where:t.where,data:r});if(this.dbType==="mongodb"){let i=await this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,r));return se(i)}return await this.knexService.updateWithCascade(e,t,r),await this.knexService.getKnex()(e).where("id",t).first()})}async updateMany(e,t,r,o=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),c=this.mongoService.ioSignalPublic?.()??{},u=o==="_id"?t.map(f=>this.conditions.safeObjectId(f)):t;return(await a.updateMany({[o]:{$in:u}},{$set:r},c)).modifiedCount});let s=await this.knexService.getKnex()(e).whereIn(o,t).update(r);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,r=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?.()??{},c=r==="_id"?t.map(f=>this.conditions.safeObjectId(f)):t,u=await s.find({[r]:{$in:c}},a).toArray(),l=0;for(let f of u)await this.mongoService.deleteOne(e,f._id)&&l++;return l});let i=await this.knexService.getKnex()(e).whereIn(r,t).delete();return typeof i=="number"?i:0})}async countRecords(e,t){if(this.dbType==="mongodb")return this.mongoService.count(e,t||{});let o=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.conditions.filterToWhere(t);({query:o}=await this.applyWhereToKnex(o,s,e))}let i=await o.count("* as count").first();return Number(i?.count||0)}async transaction(e){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>e(this.mongoService)):this.knexService.transaction(e)}async findById(e,t){if(this.dbType==="mongodb"){let o=this.conditions.safeObjectId(t);return this.mongoService.findOne(e,{_id:o})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let o={};for(let[i,s]of Object.entries(t))i==="id"||i==="_id"?o._id=this.conditions.safeObjectId(s):o[i]=s;return this.mongoService.findOne(e,o)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let o={};for(let[c,u]of Object.entries(t))c==="id"||c==="_id"?o._id=this.conditions.safeObjectId(u):o[c]=u;let i=this.mongoService.collection(e),s=this.mongoService.ioSignalPublic?.()??{};return await i.find(o,s).toArray()}return await this.knexService.getKnex()(e).where(t)}async insertAndGet(e,t){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));let r=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),i=r||t.id;return await o(e).where("id",i).first()}async updateById(e,t,r){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,r)):(await this.knexService.updateWithCascade(e,t,r),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 r=this.dbType==="mongodb"?"mongodb":"sql";return this.trackQueryMetric("raw",r,async()=>{if(this.dbType==="mongodb"){let i=this.mongoService.getDb();if(typeof e=="string"){if(/^\s*select\s+1\s*;?\s*$/i.test(e))return await i.command({ping:1});throw new Error("String queries not supported for MongoDB. Use db.command() object instead.")}return await i.command(e)}return await this.knexService.getKnex().raw(e,t)})}async trackQueryMetric(e,t,r){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.trackQuery({op:e,table:t},r):await r()}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}};Ao();vo();Fo();function ps(n){return n?(Array.isArray(n)?n:n.split(",")).flatMap(t=>{let r=typeof t=="string"?t.trim():"",o=r.startsWith("-"),i=o?r.substring(1).trim():r;return i?[{field:i,direction:o?"DESC":"ASC"}]:[]}):[]}Rr();Se();ft();Oe();on();re();qe();wt();function gs(n,e,t){if(!(!n||typeof n!="object")){if(e>ne)throw new w(`Filter nesting depth exceeds maximum of ${ne}`);if(t.has(n))throw new w("Filter contains a circular reference");t.add(n);try{for(let r of Object.values(n))gs(r,e+1,t)}finally{t.delete(n)}}}function hs(n,e,t,r){if(!n||typeof n!="object"||Array.isArray(n))throw new w("Filter must be an object");return Wn(n,e,t,r,0,new Set)}function Wn(n,e,t,r,o,i){if(!n||typeof n!="object"||Array.isArray(n))throw new w("Filter operand must be an object");if(o>ne)throw new w(`Filter nesting depth exceeds maximum of ${ne}`);if(i.has(n))throw new w("Filter contains a circular reference");let s=t?.tables?.get(e);if(!s)throw new w(`Filter validation requires metadata for table '${e}'`);i.add(n);let a=Object.create(null);try{for(let[c,u]of Object.entries(n)){if(de.has(c))throw new w(`Filter operator '${c}' is not valid at table scope`);if(c==="_and"||c==="_or"){if(!Array.isArray(u))throw new w(`Filter '${c}' value must be an array`);a[c]=u.map(d=>Wn(d,e,t,r,o+1,i));continue}if(c==="_not"){a[c]=Wn(u,e,t,r,o+1,i);continue}let l=s.relations?.find(d=>d.propertyName===c);if(l){if(!r(e,c,"relation"))throw new w(`Filtering by relation '${c}' on '${e}' is not allowed`);let d=l.targetTableName||l.targetTable;if(typeof d!="string"||!d)throw new w(`Relation '${c}' on '${e}' has no target table metadata`);a[c]=Wn(u,d,t,r,o+1,i);continue}if(s.columns?.find(d=>d.name===c)){if(!r(e,c,"column"))throw new w(`Filtering by field '${c}' on '${e}' is not allowed`);gs(u,o+1,i),a[c]=u;continue}throw new w(`Unknown filter field '${c}' on table '${e}'`)}return a}finally{i.delete(n)}}function ms(n,e,t,r){if(n===void 0)return n;if(typeof n!="string"&&!Array.isArray(n))throw new w("Sort must be a string or string array");let o=Array.isArray(n)?n:n.split(",");if(o.some(a=>typeof a!="string"))throw new w("Sort entries must be strings");let i=o.map(a=>a.trim()).filter(Boolean),s=[];for(let a of i){let l=(a.startsWith("-")?a.slice(1):a).split("."),f=!0,d=e;for(let p=0;p<l.length;p++){let g=l[p],h=p===l.length-1,y=t?.tables?.get(d);if(!y)throw new w(`Sort validation requires metadata for table '${d}'`);if(h)if(y.columns?.find(b=>b.name===g))r(d,g,"column")||(f=!1);else throw new w(`Unknown sort field '${g}' on table '${d}'`);else{let m=y.relations?.find(_=>_.propertyName===g);if(!m)throw new w(`Unknown sort relation '${g}' on table '${d}'`);if(!r(d,g,"relation")){f=!1;break}let b=m.targetTableName||m.targetTable;if(typeof b!="string"||!b||!t?.tables?.has(b))throw new w(`Sort relation '${g}' on '${d}' has no resolvable target table metadata`);d=b}}f&&s.push(a)}if(s.length!==0)return Array.isArray(n)?s:s.join(",")}cr();qe();sr();async function ys(n,e,t){if(!Number.isInteger(t)||t<1)throw new Error("Per-parent concurrency must be a positive integer");let r=new Map,o=[];for(let d of n){let p=String(d);if(r.has(p)){if(!Object.is(r.get(p),d))throw new Error(`Per-parent identity collision for key: ${p}`);continue}r.set(p,d),o.push({id:d,key:p})}let i=new Array(o.length),s=0,a=!1,c=!1,u;async function l(){for(;!a;){let d=s;if(d>=o.length)return;s+=1;let p=o[d];try{i[d]=await e(p.id)}catch(g){c||(c=!0,u=g),a=!0}}}let f=Math.min(t,o.length);if(f===0)return new Map;if(await Promise.all(Array.from({length:f},()=>l())),c)throw u;return new Map(o.map((d,p)=>[d.key,i[p]]))}wt();et();re();function hl(n){let e=new qt({knexService:n.knexService,mongoService:n.mongoService,databaseConfigService:n.databaseConfigService,runtimeMetricsCollectorService:n.runtimeMetricsCollectorService,lazyRef:n.lazyRef}),t,r,o=!1,i,s=()=>{if(o)throw new Error("Enfyra kernel has been destroyed")},a=()=>{if(s(),!t){let u=n.getPackageCacheService?.()??n.packageCacheService,l=n.getPackageCdnLoaderService?.()??n.packageCdnLoaderService;if(!u||!l)throw new Error("Executor dependencies packageCacheService and packageCdnLoaderService are required");t=new bt({packageCacheService:u,packageCdnLoaderService:l,onExecutorWorkerCrash:n.onExecutorWorkerCrash,onExecutionFinished:n.onExecutionFinished})}return t},c=()=>(s(),r||(r=new gt({isolatedExecutorService:a()})),r);return{queryBuilderService:e,get isolatedExecutorService(){return a()},get executorEngineService(){return c()},onDestroy(){return i||(o=!0,i=Promise.resolve().then(async()=>{try{await e.flushBatchInserts()}finally{await t?.onDestroy?.()}}),i)}}}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,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,applyOperatorToMatch,applyRelationFilters,applyWhereToKnex,assertFieldOperatorValueIsClean,buildMongoCharFoldMapJson,buildMongoFoldTextSearchJs,buildMongoSortSpec,buildMongoSortSpecFromPlan,buildRelationSortSubquery,buildRelationSubquery,buildSqlWherePartsFromFieldAst,buildWhereClause,camelToSnake,checkIfFilterContainsIsNull,chunkedFetch,compileScriptSource,computeEngineTuning,createEnfyraKernel,dslOpToCompareOp,encodeMainThreadToIsolate,escapeSqlValue,executeAggregationPipeline,executeBatchFetches,executeCountQueries,executeMongoBatchFetches,expandFieldsMongo,expandFieldsToJoinsAndSelect,expandFieldsToSelect,getEffectiveCpuCount,getEffectiveMemoryBytes,getEngineTuning,getExecutableScript,getForeignKeyColumnName,getIoAbortSignal,getJunctionColumnNames,getJunctionTableName,getMetadataGetter,getMongoInverseRelationForeignField,getMongoMetadataGetter,getMongoStoredRelationField,getPrimaryKeyColumn,getScriptLegacyField,getShortFkConstraintName,getShortFkName,getShortIndexName,getShortPkName,hasLogicalOperators,isExecutableJavaScript,isMongoInverseRelation,isScriptTable,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeMongoDocument,normalizeMongoResults,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,parseSortInput,perParentRun,quoteIdentifier,quoteQualifiedIdentifier,renderFilterToKnex,resolveExecutableScript,resolveMongoJunctionInfo,rewriteFilterDenyingFields,rewriteSortDroppingDenied,runWithIoAbortSignal,scriptContractService,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,validateDeepOptions,validateFilterShape,whereToMongoFilter});