@enfyra/kernel 1.0.10 → 1.1.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.
@@ -1,4 +1,4 @@
1
- "use strict";var T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var I=T((Ae,j)=>{"use strict";var{fork:re}=require("child_process"),ae=require("path");function ne({workerDir:e,activeTaskContexts:t}){let s=new Map,a=new Map,r=null,i=0;function l(u){for(let n of a.values())n.reject(u);a.clear()}function _(u){let n=typeof u=="string"?JSON.parse(u):u;if(n?.error)throw new Error(n.error);return n?.value}async function d(u){let n=t.get(u.taskId);if(!n)throw new Error(`Package callback context not found: ${u.taskId}`);let o=JSON.stringify(u.callbackId),f=JSON.stringify(u.argsJson||"[]"),g=await n.evalClosure(`return __invokeRuntimeCallback(${o}, ${f});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}});return _(g)}function k(){if(r&&r.connected)return r;let u=ae.join(e,"package-runtime.child.js"),n=re(u,[],{stdio:["ignore","ignore","ignore","ipc"]});return r=n,n.on("message",o=>{if(!o||!o.id)return;if(o.type==="pkgCallbackCall"){d(o).then(g=>{try{n.send({type:"pkgCallbackResult",id:o.id,value:g})}catch{}}).catch(g=>{try{n.send({type:"pkgCallbackError",id:o.id,error:{message:g.message,stack:g.stack}})}catch{}});return}let f=a.get(o.id);if(f)if(a.delete(o.id),o.ok)f.resolve(o.value);else{let g=new Error(o.error?.message||"Package runtime call failed");g.stack=o.error?.stack||g.stack,f.reject(g)}}),n.on("exit",(o,f)=>{r===n&&(r=null),l(new Error(`Package runtime exited${f?` with signal ${f}`:` with code ${o}`}`))}),n.on("error",o=>{r===n&&(r=null),l(o)}),n}function y(u){return new Promise((n,o)=>{let f=k(),g=`pkg_${++i}`;a.set(g,{resolve:n,reject:o});try{f.send({...u,id:g},w=>{w&&(a.delete(g),o(w))})}catch(w){a.delete(g),o(w)}})}function m(u){try{if(!r||!r.connected)return;r.send({...u,id:`pkg_${++i}`,fire:!0})}catch{}}async function c(u,n){let o=s.get(u);if(!o)throw new Error("Package context is not available");if(n.handleId)return y({op:n.kind==="get"?"handleGet":"handleCall",taskId:u,handleId:n.handleId,path:n.path||[],argsJson:n.argsJson||"[]"});let f=o.get(n.packageName);if(!f)throw new Error(`Package "${n.packageName}" is not available`);return y({op:n.kind==="construct"?"construct":"call",taskId:u,packageName:n.packageName,package:{name:f.name,fileUrl:f.fileUrl},path:n.path||[],argsJson:n.argsJson||"[]"})}function h(u,n){s.set(u,n)}function v(u){s.delete(u),m({op:"releaseTask",taskId:u})}function p(){if(r){try{r.kill()}catch{}r=null}}return{cleanupTaskPackages:v,executePackageRuntimeCall:c,setTaskPackages:h,shutdownPackageRuntime:p}}j.exports={createPackageRuntimeBridge:ne}});var H=T((Ne,U)=>{"use strict";var se=`
1
+ "use strict";var U=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var F=U((Ee,H)=>{"use strict";var{fork:se}=require("child_process"),oe=require("path");function ie({workerDir:e,activeTaskContexts:t}){let n=new Map,a=new Map,r=null,o=0;function c(p){for(let i of a.values())i.reject(p);a.clear()}function _(p){let i=typeof p=="string"?JSON.parse(p):p;if(i?.error)throw new Error(i.error);return i?.value}async function f(p){let i=t.get(p.taskId);if(!i)throw new Error(`Package callback context not found: ${p.taskId}`);let s=JSON.stringify(p.callbackId),g=JSON.stringify(p.argsJson||"[]"),u=await i.evalClosure(`return __invokeRuntimeCallback(${s}, ${g});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}});return _(u)}function v(){if(r&&r.connected)return r;let p=oe.join(e,"package-runtime.child.js"),i=se(p,[],{stdio:["ignore","ignore","ignore","ipc"]});return r=i,i.on("message",s=>{if(!s||!s.id)return;if(s.type==="pkgCallbackCall"){f(s).then(u=>{try{i.send({type:"pkgCallbackResult",id:s.id,value:u})}catch{}}).catch(u=>{try{i.send({type:"pkgCallbackError",id:s.id,error:{message:u.message,stack:u.stack}})}catch{}});return}let g=a.get(s.id);if(g)if(a.delete(s.id),s.ok)g.resolve(s.value);else{let u=new Error(s.error?.message||"Package runtime call failed");u.stack=s.error?.stack||u.stack,g.reject(u)}}),i.on("exit",(s,g)=>{r===i&&(r=null),c(new Error(`Package runtime exited${g?` with signal ${g}`:` with code ${s}`}`))}),i.on("error",s=>{r===i&&(r=null),c(s)}),i}function d(p){return new Promise((i,s)=>{let g=v(),u=`pkg_${++o}`;a.set(u,{resolve:i,reject:s});try{g.send({...p,id:u},y=>{y&&(a.delete(u),s(y))})}catch(y){a.delete(u),s(y)}})}function m(p){try{if(!r||!r.connected)return;r.send({...p,id:`pkg_${++o}`,fire:!0})}catch{}}async function l(p,i){let s=n.get(p);if(!s)throw new Error("Package context is not available");if(i.handleId)return d({op:i.kind==="get"?"handleGet":"handleCall",taskId:p,handleId:i.handleId,path:i.path||[],argsJson:i.argsJson||"[]"});let g=s.get(i.packageName);if(!g)throw new Error(`Package "${i.packageName}" is not available`);return d({op:i.kind==="construct"?"construct":"call",taskId:p,packageName:i.packageName,package:{name:g.name,fileUrl:g.fileUrl},path:i.path||[],argsJson:i.argsJson||"[]"})}function h(p,i){n.set(p,i)}function w(p){n.delete(p),m({op:"releaseTask",taskId:p})}function k(){if(r){try{r.kill()}catch{}r=null}}return{cleanupTaskPackages:w,executePackageRuntimeCall:l,setTaskPackages:h,shutdownPackageRuntime:k}}H.exports={createPackageRuntimeBridge:ie}});var K=U((Te,L)=>{"use strict";var ce=`
2
2
  "use strict";
3
3
  let $ctx = {};
4
4
  let $pkgs = {};
@@ -626,50 +626,51 @@ function __cleanupTask() {
626
626
  __runtimeCallbacks = new Map();
627
627
  return true;
628
628
  }
629
- `;function oe(e){return se.replace("%%PKG_SETUP%%",e)}U.exports={buildSetupCode:oe}});var{parentPort:N}=require("worker_threads"),F=require("fs"),{fileURLToPath:ie}=require("url"),{createPackageRuntimeBridge:ce}=I(),{buildSetupCode:le}=H(),C;try{C=require("isolated-vm")}catch(e){N.postMessage({type:"error",message:"isolated-vm not available: "+e.message}),process.exit(1)}var S=new Map,B=0,R=new Map,A=ce({workerDir:__dirname,activeTaskContexts:R}),ue=500,pe=5e3,fe=32,L=new WeakMap,V=new WeakMap,z=new WeakMap,b={created:0,reused:0,released:0,evicted:0,scrubFailed:0},P=null,_e=0,K=0,D=0;async function de(){let e=Date.now();if(e-K<pe)return D;if(K=e,!P)return 0;let t=0;for(let s of P){let a=s?.isolate;if(!(!a||a.isDisposed))try{let r=await a.getHeapStatistics(),i=r.heap_size_limit||1,l=r.used_heap_size/i;l>t&&(t=l)}catch{}}return D=t,t}async function $(e){e.heapRatio=await de(),e.contextStats=ge(),N.postMessage(e)}function ge(){let e=0;if(P)for(let t of P)e+=t?.idleContexts?.length||0;return{...b,idle:e}}function W(e,t){if(!P){let r=Math.max(1,Math.trunc(Number(t)||8));P=new Array(r).fill(null)}let s=_e++%P.length,a=P[s];return(!a||!a.isolate||a.isolate.isDisposed)&&(a={isolate:new C.Isolate({memoryLimit:e}),idleContexts:[]},P[s]=a),a}async function x(e,t,s){let a=L.get(e);a||(a=new Map,L.set(e,a));let r=a.get(t);if(r)return r;let i=await e.compileScript(t,{filename:s});if(a.set(t,i),a.size>ue){let l=a.keys().next().value;a.delete(l)}return i}N.on("message",async e=>{if(e.type==="execute")be(e).catch(async t=>{await $({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="executeBatch")Se(e).catch(async t=>{await $({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="callResult"){let t=S.get(e.callId);t&&(S.delete(e.callId),t.resolve(e.result))}else if(e.type==="callError"){let t=S.get(e.callId);t&&(S.delete(e.callId),t.reject(new Error(e.error)))}});function ye(e,t,s){return new Promise((a,r)=>{let i=`cb_${++B}`;S.set(i,{resolve:a,reject:r}),N.postMessage({type:t,id:e,callId:i,...s})})}function he(e,t,s){N.postMessage({type:t,id:e,callId:`f_${++B}`,...s})}function me(e){if(typeof e.sourceCode=="string"&&e.sourceCode.length>0)return e.sourceCode;let t=e.filePath;return!t&&typeof e.fileUrl=="string"&&e.fileUrl.startsWith("file://")&&(t=ie(e.fileUrl)),!t||!F.existsSync(t)?null:F.readFileSync(t,"utf8")}async function ke(e,t,s){try{let a=me(s);if(!a)return null;let r=await e.compileModule(a,{filename:`pkg:${s.safeName}`});await r.instantiate(t,l=>{throw new Error(`Unresolved import in package ${s.safeName}: ${l}`)}),await r.evaluate({timeout:1e4});let i=await r.namespace.get("default");return i!==void 0&&i.typeof!=="undefined"?i.derefInto({release:!1}):r.namespace.derefInto({release:!1})}catch{return null}}function G(e,t){let s=r=>{let i=2166136261;for(let l=0;l<r.length;l++)i^=r.charCodeAt(l),i=Math.imul(i,16777619);return(i>>>0).toString(36)},a=new Set(t||[]);return e.map(r=>{let i=r.cacheKey||`${r.filePath||""}:${r.fileUrl||""}:${r.mtimeMs||""}:${r.size||""}:${s(r.sourceCode||"")}`,l=a.has(r.name)?"isolate":"proxy";return`${r.name}:${r.version||""}:${i}:${l}`}).join("|")}function X(e,t){let s=new Set(t.map(d=>d.name)),a=new Set,r=String(e||""),i=/\b(?:\$ctx\.)?\$pkgs\s*\[\s*(['"`])([^'"`]+)\1\s*\]/g,l=/\brequire\s*\(\s*(['"`])([^'"`]+)\1\s*\)/g,_=/\b(?:\$ctx\.)?\$pkgs\.([A-Za-z_$][\w$]*)/g;for(let d of[i,l])for(let k of r.matchAll(d)){let y=k[2];s.has(y)&&a.add(y)}for(let d of r.matchAll(_)){let k=d[1];s.has(k)&&a.add(k)}return a}async function ve(e,t,s,a){let r=await e.createContext(),i=r.global;await i.set("global",i.derefInto());let l=[],_=[],d=new Map;for(let c of s){d.set(c.name,c);let h=a.has(c.name)?await ke(e,r,c):null;h!==null?(await i.set(`__pkg_${c.safeName}`,h),l.push(c)):_.push(c)}A.setTaskPackages(t,d),await i.set("__callRef",new C.Reference(async(c,h,v)=>{let p=JSON.parse(v);return h==="pkgCall"?JSON.stringify(await A.executePackageRuntimeCall(c,p)):ye(c,h,p)})),await i.set("__fireRef",new C.Reference((c,h,v)=>{let p=JSON.parse(v);he(c,h,p)}));let k=l.map(c=>`$pkgs[${JSON.stringify(c.name)}] = __pkg_${c.safeName};`).concat(_.map(c=>`$pkgs[${JSON.stringify(c.name)}] = __createPkgProxy(${JSON.stringify(c.name)}, []);`)).join(`
630
- `),y=le(k);return await(await x(e,y,"setup.js")).run(r,{timeout:5e3}),V.set(r,G(s,a)),z.set(r,d),r}async function Z(e,t,s,a,r){let i=e.isolate,l=G(s,r),_=null;for(let y=e.idleContexts.length-1;y>=0;y--){let m=e.idleContexts[y];if(e.idleContexts.splice(y,1),V.get(m)===l){_=m,b.reused++;break}try{m.release()}catch{}}_||(_=await ve(i,t,s,r),b.created++),A.setTaskPackages(t,z.get(_)||new Map);let d=_.global;return await d.set("__snapshot",new C.ExternalCopy(a).copyInto()),await d.set("__nextTaskId",t),await(await x(i,"__resetTask(__snapshot, __nextTaskId);","reset-task.js")).run(_,{timeout:5e3}),_}async function Q(e,t){if(!(!t||e.isolate.isDisposed)){try{await(await x(e.isolate,"__cleanupTask();","cleanup-task.js")).run(t,{timeout:5e3})}catch{b.scrubFailed++;try{t.release()}catch{}return}if(e.idleContexts.length>=fe){try{t.release()}catch{}b.evicted++;return}e.idleContexts.push(t),b.released++}}function we(e){try{let t=JSON.parse(e.message);if(t&&t.__userThrow)return{...t,message:t.message??e.message}}catch{}return null}var Pe=3,xe=["setup.js","extract.js","extract-error-ctx.js","set-status.js","populate-error.js"];function $e(e){if(!e)return null;let t=e.split(`
631
- `);for(let s of t){let a=s.match(/at\s+(.+\.js):(\d+):(\d+)/);if(!a)continue;let r=a[1].trim();if(xe.includes(r))continue;let l=parseInt(a[2])-Pe;if(!(l<=0))return{line:l,column:parseInt(a[3]),phase:r.replace(".js","")}}return null}function J(e){let t=we(e);if(t)return{message:t.message,statusCode:t.statusCode,details:t.details};let s=$e(e.stack),a=e.message||"Unknown error";return{message:s?`${a} (${s.phase}, line ${s.line})`:a,statusCode:e.statusCode||null,details:s||void 0}}async function Y(e,t){let s=J(t);await $({type:"result",id:e,success:!1,error:{...s,stack:t.stack,code:t.code}})}async function be(e){let{id:t,code:s,pkgSources:a,snapshot:r,memoryLimitMb:i,isolatePoolSize:l}=e,_=a||[],d=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),k=X(s,_),y=W(i,l),m=y.isolate,c=await Z(y,t,_,r,k);R.set(t,c);try{let h=`
629
+ `;function le(e){return ce.replace("%%PKG_SETUP%%",e)}L.exports={buildSetupCode:le}});var{parentPort:O}=require("worker_threads"),D=require("fs"),{fileURLToPath:ue}=require("url"),{createPackageRuntimeBridge:pe}=F(),{buildSetupCode:fe}=K(),N;try{N=require("isolated-vm")}catch(e){O.postMessage({type:"error",message:"isolated-vm not available: "+e.message}),process.exit(1)}var A=new Map,W=0,J=new Map,M=pe({workerDir:__dirname,activeTaskContexts:J}),_e=500,de=5e3,ge=32,q=new WeakMap,G=new WeakMap,X=new WeakMap,C={created:0,reused:0,released:0,evicted:0,scrubFailed:0},x=null,ye=0,B=0,V=0;async function he(){let e=Date.now();if(e-B<de)return V;if(B=e,!x)return 0;let t=0;for(let n of x){let a=n?.isolate;if(!(!a||a.isDisposed))try{let r=await a.getHeapStatistics(),o=r.heap_size_limit||1,c=r.used_heap_size/o;c>t&&(t=c)}catch{}}return V=t,t}async function b(e){e.heapRatio=await he(),e.contextStats=me(),O.postMessage(e)}function me(){let e=0;if(x)for(let t of x)e+=t?.idleContexts?.length||0;return{...C,idle:e}}function Z(e,t){if(!x){let r=Math.max(1,Math.trunc(Number(t)||8));x=new Array(r).fill(null)}let n=ye++%x.length,a=x[n];return(!a||!a.isolate||a.isolate.isDisposed)&&(a={isolate:new N.Isolate({memoryLimit:e}),idleContexts:[]},x[n]=a),a}async function $(e,t,n){let a=q.get(e);a||(a=new Map,q.set(e,a));let r=a.get(t);if(r)return r;let o=await e.compileScript(t,{filename:n});if(a.set(t,o),a.size>_e){let c=a.keys().next().value;a.delete(c)}return o}O.on("message",async e=>{if(e.type==="execute")Ne(e).catch(async t=>{await b({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="executeBatch")Je(e).catch(async t=>{await b({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="callResult"){let t=A.get(e.callId);t&&(A.delete(e.callId),t.resolve(e.result))}else if(e.type==="callError"){let t=A.get(e.callId);t&&(A.delete(e.callId),t.reject(new Error(e.error)))}});function ke(e,t,n){return new Promise((a,r)=>{let o=`cb_${++W}`;A.set(o,{resolve:a,reject:r}),O.postMessage({type:t,id:e,callId:o,...n})})}function ve(e,t,n){O.postMessage({type:t,id:e,callId:`f_${++W}`,...n})}function we(e){if(typeof e.sourceCode=="string"&&e.sourceCode.length>0)return e.sourceCode;let t=e.filePath;return!t&&typeof e.fileUrl=="string"&&e.fileUrl.startsWith("file://")&&(t=ue(e.fileUrl)),!t||!D.existsSync(t)?null:D.readFileSync(t,"utf8")}async function Pe(e,t,n){try{let a=we(n);if(!a)return null;let r=await e.compileModule(a,{filename:`pkg:${n.safeName}`});await r.instantiate(t,c=>{throw new Error(`Unresolved import in package ${n.safeName}: ${c}`)}),await r.evaluate({timeout:1e4});let o=await r.namespace.get("default");return o!==void 0&&o.typeof!=="undefined"?o.derefInto({release:!1}):r.namespace.derefInto({release:!1})}catch{return null}}function Q(e,t){let n=r=>{let o=2166136261;for(let c=0;c<r.length;c++)o^=r.charCodeAt(c),o=Math.imul(o,16777619);return(o>>>0).toString(36)},a=new Set(t||[]);return e.map(r=>{let o=r.cacheKey||`${r.filePath||""}:${r.fileUrl||""}:${r.mtimeMs||""}:${r.size||""}:${n(r.sourceCode||"")}`,c=a.has(r.name)?"isolate":"proxy";return`${r.name}:${r.version||""}:${o}:${c}`}).join("|")}function Y(e,t){let n=new Set(t.map(f=>f.name)),a=new Set,r=String(e||""),o=/\b(?:\$ctx\.)?\$pkgs\s*\[\s*(['"`])([^'"`]+)\1\s*\]/g,c=/\brequire\s*\(\s*(['"`])([^'"`]+)\1\s*\)/g,_=/\b(?:\$ctx\.)?\$pkgs\.([A-Za-z_$][\w$]*)/g;for(let f of[o,c])for(let v of r.matchAll(f)){let d=v[2];n.has(d)&&a.add(d)}for(let f of r.matchAll(_)){let v=f[1];n.has(v)&&a.add(v)}return a}async function xe(e,t,n,a){let r=await e.createContext(),o=r.global;await o.set("global",o.derefInto());let c=[],_=[],f=new Map;for(let l of n){f.set(l.name,l);let h=a.has(l.name)?await Pe(e,r,l):null;h!==null?(await o.set(`__pkg_${l.safeName}`,h),c.push(l)):_.push(l)}M.setTaskPackages(t,f),await o.set("__callRef",new N.Reference(async(l,h,w)=>{let k=JSON.parse(w);return h==="pkgCall"?JSON.stringify(await M.executePackageRuntimeCall(l,k)):ke(l,h,k)})),await o.set("__fireRef",new N.Reference((l,h,w)=>{let k=JSON.parse(w);ve(l,h,k)}));let v=c.map(l=>`$pkgs[${JSON.stringify(l.name)}] = __pkg_${l.safeName};`).concat(_.map(l=>`$pkgs[${JSON.stringify(l.name)}] = __createPkgProxy(${JSON.stringify(l.name)}, []);`)).join(`
630
+ `),d=fe(v);return await(await $(e,d,"setup.js")).run(r,{timeout:5e3}),G.set(r,Q(n,a)),X.set(r,f),r}async function ee(e,t,n,a,r){let o=e.isolate,c=Q(n,r),_=null;for(let d=e.idleContexts.length-1;d>=0;d--){let m=e.idleContexts[d];if(e.idleContexts.splice(d,1),G.get(m)===c){_=m,C.reused++;break}try{m.release()}catch{}}_||(_=await xe(o,t,n,r),C.created++),M.setTaskPackages(t,X.get(_)||new Map);let f=_.global;return await f.set("__snapshot",new N.ExternalCopy(a).copyInto()),await f.set("__nextTaskId",t),await(await $(o,"__resetTask(__snapshot, __nextTaskId);","reset-task.js")).run(_,{timeout:5e3}),_}async function te(e,t){if(!(!t||e.isolate.isDisposed)){try{await(await $(e.isolate,"__cleanupTask();","cleanup-task.js")).run(t,{timeout:5e3})}catch{C.scrubFailed++;try{t.release()}catch{}return}if(e.idleContexts.length>=ge){try{t.release()}catch{}C.evicted++;return}e.idleContexts.push(t),C.released++}}function $e(e){try{let t=JSON.parse(e.message);if(t&&t.__userThrow)return{...t,message:t.message??e.message}}catch{}return null}var Se=3,be=["setup.js","extract.js","extract-error-ctx.js","set-status.js","populate-error.js"];function Ce(e){if(!e)return null;let t=e.split(`
631
+ `);for(let n of t){let a=n.match(/at\s+(.+\.js):(\d+):(\d+)/);if(!a)continue;let r=a[1].trim();if(be.includes(r))continue;let c=parseInt(a[2])-Se;if(!(c<=0))return{line:c,column:parseInt(a[3]),phase:r.replace(".js","")}}return null}function Re(e,t,n){if(!e||!t)return;let a=String(e).split(/\r?\n/),r=Math.max(1,t-1),o=Math.min(a.length,t+1),c=String(o).length,_=[];for(let f=r;f<=o;f++){let v=f===t?">":" ";_.push(`${v} ${String(f).padStart(c," ")}. ${a[f-1]??""}`),f===t&&n&&n>0&&_.push(` ${" ".repeat(c)} ${" ".repeat(Math.max(0,n-1))}^`)}return _.join(`
632
+ `)}function Ae(e,t){if(!(!e||!t)){if(t[e.phase])return t[e.phase];if(e.phase?.startsWith("preHook"))return t.preHook;if(e.phase?.startsWith("postHook"))return t.postHook}}function E(e,t){let n=$e(e);if(n)return{message:n.message,statusCode:n.statusCode,details:n.details};let a=Ce(e.stack),r=e.message||"Unknown error",o=a?`${r} (${a.phase}, line ${a.line})`:r,c=Ae(a,t),_=a?Re(c,a.line,a.column):void 0;return{message:o,statusCode:e.statusCode||null,details:a?{...a,codeFrame:_}:void 0}}async function re(e,t){let n=E(t);await b({type:"result",id:e,success:!1,error:{...n,stack:t.stack,code:t.code}})}async function Ne(e){let{id:t,code:n,pkgSources:a,snapshot:r,memoryLimitMb:o,isolatePoolSize:c}=e,_=a||[],f=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),v=Y(n,_),d=Z(o,c),m=d.isolate,l=await ee(d,t,_,r,v);J.set(t,l);try{let h=`
632
633
  (async () => {
633
634
  "use strict";
634
- ${s}
635
+ ${n}
635
636
  })().then((__result) => __extractResult(__result, __result === undefined));
636
- `,p=await(await x(m,h,"handler.js")).run(c,{timeout:d,promise:!0}),u=JSON.parse(p);await $({type:"result",id:t,success:!0,...u})}catch(h){await Y(t,h)}finally{R.delete(t),await Q(y,c),ee(t)}}async function Se(e){let{id:t,codeBlocks:s,pkgSources:a,snapshot:r,memoryLimitMb:i,isolatePoolSize:l}=e,_=a||[],d=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),k=X((s||[]).map(p=>p.code||"").join(`
637
- `),_),y=W(i,l),m=y.isolate,c=await Z(y,t,_,r,k);R.set(t,c);let h=[],v=[];for(let p of s)(p.type||"handler")==="postHook"?v.push(p):h.push(p);try{let p=null;for(let n=0;n<h.length;n++){let o=h[n],f=o.type||"handler",g=f==="handler"?"handler":`${f} #${n+1}`,w;f==="preHook"?w=`
637
+ `,k=await(await $(m,h,"handler.js")).run(l,{timeout:f,promise:!0}),p=JSON.parse(k);await b({type:"result",id:t,success:!0,...p})}catch(h){await re(t,h)}finally{J.delete(t),await te(d,l),ae(t)}}async function Je(e){let{id:t,codeBlocks:n,pkgSources:a,snapshot:r,memoryLimitMb:o,isolatePoolSize:c}=e,_=a||[],f=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),v=Y((n||[]).map(s=>s.code||"").join(`
638
+ `),_),d=Z(o,c),m=d.isolate,l=await ee(d,t,_,r,v);J.set(t,l);let h=[],w=[],k={},p=0,i=0;for(let s of n){let g=s.type||"handler";g==="postHook"?(i++,k[`postHook #${i}`]=s.code||"",k.postHook=s.code||"",w.push(s)):(g==="handler"?k.handler=s.code||"":(p++,k[`${g} #${p}`]=s.code||"",k.preHook=s.code||""),h.push(s))}try{let s=null;for(let u=0;u<h.length;u++){let y=h[u],P=y.type||"handler",R=P==="handler"?"handler":`${P} #${u+1}`,S;P==="preHook"?S=`
638
639
  (async () => {
639
640
  "use strict";
640
- ${o.code}
641
+ ${y.code}
641
642
  })().then((__r) => {
642
643
  if (__r !== undefined) return JSON.stringify({ __shortCircuit: true, value: __r });
643
644
  return JSON.stringify({ __shortCircuit: false });
644
- });`:w=`
645
+ });`:S=`
645
646
  (async () => {
646
647
  "use strict";
647
- ${o.code}
648
+ ${y.code}
648
649
  })().then((__r) => {
649
650
  $ctx.$data = __r;
650
651
  return "__handler_done__";
651
- });`;try{let M=await(await x(m,w,`${g}.js`)).run(c,{timeout:d,promise:!0});if(f==="preHook"&&typeof M=="string"){let E=JSON.parse(M);if(E.__shortCircuit){let te=await q(m,c,E.value);await $({type:"result",id:t,success:!0,...te,shortCircuit:!0});return}}}catch(O){p=O;break}}if(!p&&v.length>0&&await(await x(m,'$ctx.$statusCode = 200; "__status_set__";',"set-status.js")).run(c,{timeout:5e3}),p&&v.length>0){let n=J(p),o={message:n.message||"Unknown error",name:p.constructor?.name||"Error",stack:p.stack||"",statusCode:n.statusCode||500,details:n.details||{},timestamp:new Date().toISOString()},f=`
652
- $ctx.$error = ${JSON.stringify(o)};
652
+ });`;try{let j=await(await $(m,S,`${R}.js`)).run(l,{timeout:f,promise:!0});if(P==="preHook"&&typeof j=="string"){let I=JSON.parse(j);if(I.__shortCircuit){let ne=await z(m,l,I.value);await b({type:"result",id:t,success:!0,...ne,shortCircuit:!0});return}}}catch(T){s=T;break}}if(!s&&w.length>0&&await(await $(m,'$ctx.$statusCode = 200; "__status_set__";',"set-status.js")).run(l,{timeout:5e3}),s&&w.length>0){let u=E(s,k),y={message:u.message||"Unknown error",name:s.constructor?.name||"Error",stack:s.stack||"",statusCode:u.statusCode||500,details:u.details||{},timestamp:new Date().toISOString()},P=`
653
+ $ctx.$error = ${JSON.stringify(y)};
653
654
  $ctx.$data = null;
654
- $ctx.$statusCode = ${o.statusCode};
655
+ $ctx.$statusCode = ${y.statusCode};
655
656
  if ($ctx.$api) {
656
- $ctx.$api.error = ${JSON.stringify(o)};
657
+ $ctx.$api.error = ${JSON.stringify(y)};
657
658
  $ctx.$api.response = {
658
- statusCode: ${o.statusCode},
659
+ statusCode: ${y.statusCode},
659
660
  responseTime: $ctx.$api.request && $ctx.$api.request.timestamp
660
661
  ? Date.now() - new Date($ctx.$api.request.timestamp).getTime()
661
662
  : 0,
662
- timestamp: ${JSON.stringify(o.timestamp)},
663
+ timestamp: ${JSON.stringify(y.timestamp)},
663
664
  };
664
665
  }
665
- "__error_populated__";`;await(await m.compileScript(f,{filename:"populate-error.js"})).run(c,{timeout:5e3})}for(let n=0;n<v.length;n++){let o=v[n],f=`postHook #${n+1}`,g=`
666
+ "__error_populated__";`;await(await m.compileScript(P,{filename:"populate-error.js"})).run(l,{timeout:5e3})}for(let u=0;u<w.length;u++){let y=w[u],P=`postHook #${u+1}`,R=`
666
667
  (async () => {
667
668
  "use strict";
668
- ${o.code}
669
+ ${y.code}
669
670
  })().then((__r) => {
670
671
  if (__r !== undefined) $ctx.$data = __r;
671
672
  return "__posthook_done__";
672
- });`;try{await(await x(m,g,`${f}.js`)).run(c,{timeout:d,promise:!0})}catch{}}if(p){let n=J(p),o;try{let w=await(await x(m,`JSON.stringify({
673
+ });`;try{await(await $(m,R,`${P}.js`)).run(l,{timeout:f,promise:!0})}catch{}}if(s){let u=E(s,k),y;try{let S=await(await $(m,`JSON.stringify({
673
674
  $body: __safeClone($ctx.$body),
674
675
  $query: __safeClone($ctx.$query),
675
676
  $params: __safeClone($ctx.$params),
@@ -679,4 +680,4 @@ if ($ctx.$api) {
679
680
  $error: __safeClone($ctx.$error),
680
681
  $api: __safeClone($ctx.$api),
681
682
  $statusCode: $ctx.$statusCode,
682
- })`,"extract-error-ctx.js")).run(c,{timeout:5e3});o=JSON.parse(w)}catch{}await $({type:"result",id:t,success:!1,error:{message:n.message,statusCode:n.statusCode,stack:p.stack,code:p.code,details:n.details},ctxChanges:o});return}let u=await q(m,c);await $({type:"result",id:t,success:!0,...u})}catch(p){await Y(t,p)}finally{R.delete(t),await Q(y,c),ee(t)}}function ee(e){A.cleanupTaskPackages(e)}function Ce(){A.shutdownPackageRuntime()}process.on("exit",Ce);async function q(e,t,s){if(s!==void 0){let l=`__extractResult(${JSON.stringify(s)}, false)`,d=await(await e.compileScript(l,{filename:"extract.js"})).run(t,{timeout:5e3});return JSON.parse(d)}let i=await(await x(e,"__extractResult($ctx.$data, $ctx.$data === undefined)","extract.js")).run(t,{timeout:5e3});return JSON.parse(i)}
683
+ })`,"extract-error-ctx.js")).run(l,{timeout:5e3});y=JSON.parse(S)}catch{}await b({type:"result",id:t,success:!1,error:{message:u.message,statusCode:u.statusCode,stack:s.stack,code:s.code,details:u.details},ctxChanges:y});return}let g=await z(m,l);await b({type:"result",id:t,success:!0,...g})}catch(s){await re(t,s)}finally{J.delete(t),await te(d,l),ae(t)}}function ae(e){M.cleanupTaskPackages(e)}function Me(){M.shutdownPackageRuntime()}process.on("exit",Me);async function z(e,t,n){if(n!==void 0){let c=`__extractResult(${JSON.stringify(n)}, false)`,f=await(await e.compileScript(c,{filename:"extract.js"})).run(t,{timeout:5e3});return JSON.parse(f)}let o=await(await $(e,"__extractResult($ctx.$data, $ctx.$data === undefined)","extract.js")).run(t,{timeout:5e3});return JSON.parse(o)}
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var ei=Object.create;var Bt=Object.defineProperty;var ti=Object.getOwnPropertyDescriptor;var ni=Object.getOwnPropertyNames;var ri=Object.getPrototypeOf,ii=Object.prototype.hasOwnProperty;var W=(r,e)=>()=>(r&&(e=r(r=0)),e);var bn=(r,e)=>{for(var t in e)Bt(r,t,{get:e[t],enumerable:!0})},ir=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ni(e))!ii.call(r,o)&&o!==t&&Bt(r,o,{get:()=>e[o],enumerable:!(n=ti(e,o))||n.enumerable});return r};var le=(r,e,t)=>(t=r!=null?ei(ri(r)):{},ir(e||!r||!r.__esModule?Bt(t,"default",{value:r,enumerable:!0}):t,r)),oi=r=>ir(Bt({},"__esModule",{value:!0}),r);function Fn(r){return hr.createHash("md5").update(r).digest("hex").substring(0,8)}function br(r){return r.length<=Cn-3?`${r}_pk`:`j_${Fn(r)}_pk`}function _r(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=Cn?n:`j_${Fn(r)}_${t}_fk`}function ue(r,e,t){let n=`${r}_${e}_${t}`;if(n.length<=Cn)return n;let o=Fn(n),i=r.replace(/_definition/g,"").substring(0,10),s=e.substring(0,10),a=t.replace(/_definition/g,"").substring(0,10);return`j_${o}_${i}_${s}_${a}`}function K(r){return`${r}Id`}function fe(r,e,t){let n=K(r);if(r===t){let i=K(e);return{sourceColumn:n,targetColumn:i}}let o=K(t);return{sourceColumn:n,targetColumn:o}}function wr(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function $r(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function Tr(r,e,t){return`${r}_${e}_${t}_fk`}function Sr(r,e,t){return`${r}_${e}_${t}_idx`}var hr,Cn,Ke=W(()=>{"use strict";hr=le(require("crypto")),Cn=63});function Zt(r){return Ii[r]??null}var Z,Mn,Rt,Ii,vt=W(()=>{"use strict";Z=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),Mn=new Set(["_and","_or","_not"]),Rt=[...Array.from(Mn),...Array.from(Z)],Ii={_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 A,Se=W(()=>{"use strict";A=class extends Error{constructor(t="Bad Request",n){let o=Array.isArray(t),i=o?t.join("; ")||"Bad Request":typeof t=="string"?t:JSON.stringify(t);super(i);this.statusCode=400;this.errorCode="BAD_REQUEST";this.name="BadRequestException",this.details=n,o&&(this.messages=t)}}});function Fr(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var Rr=W(()=>{"use strict"});function Ue(r,e,t){throw new A({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${Rt.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:Rt})}function en(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=Fr();for(let o of Object.keys(e))if(o.startsWith("_")&&!Z.has(o)){if(n&&o==="_id")continue;Ue(o,r,t)}}function Q(r,e,t){if(!r||typeof r!="object")return;let n=t?.tables?.get(e),o=new Set((n?.columns??[]).map(s=>s.name)),i=new Map((n?.relations??[]).map(s=>[s.propertyName,s]));for(let[s,a]of Object.entries(r)){if(Ei.has(s)){if(Array.isArray(a))for(let l of a)Q(l,e,t);else a&&typeof a=="object"&&Q(a,e,t);continue}let u=i.get(s);if(u){if(a&&typeof a=="object"&&!Array.isArray(a)){en(s,a,e);let l=u.targetTableName||u.targetTable;if(l){let f=Object.keys(a).filter(c=>!c.startsWith("_"));if(f.length>0){let c={};for(let p of f)c[p]=a[p];Q(c,l,t)}}}continue}s.startsWith("_")&&!o.has(s)&&s!=="_id"&&Ue(s,s,e),a&&typeof a=="object"&&!Array.isArray(a)&&en(s,a,e)}}var Ei,Ze=W(()=>{"use strict";Se();vt();Rr();Ei=new Set(["_and","_or","_not"])});function ke(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:tn(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function tn(r,e){if(!r||typeof r!="object")return{node:null,hasRelationFilters:!1};let t=[],n=!1;for(let[o,i]of Object.entries(r)){let s=Pi(o,i,e);s.hasRelationFilters&&(n=!0),s.node&&t.push(s.node)}return t.length===0?{node:null,hasRelationFilters:n}:t.length===1?{node:t[0],hasRelationFilters:n}:{node:{kind:"and",children:t},hasRelationFilters:n}}function Pi(r,e,t){if(r==="_and")return vr("and",e,t);if(r==="_or")return vr("or",e,t);if(r==="_not"){let l=tn(e,t);return l.node?{node:{kind:"not",child:l.node},hasRelationFilters:l.hasRelationFilters}:{node:null,hasRelationFilters:l.hasRelationFilters}}let n=t.metadata?.tables?.get(t.currentTable),o=n?.columns?.some(l=>l.name==="_id"&&l.isPrimary),i=n?.columns?.some(l=>l.name==="id"),a=r==="id"?o&&!i?"_id":"id":r,u=n?.relations?.find(l=>l.propertyName===a);return u?ji(a,e,u,t):n&&!n.columns?.find(f=>f.name===a)?(r.startsWith("_")&&r!=="_id"&&Ue(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}):Li(a,e,t)}function vr(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],o=!1;for(let i of e){let s=tn(i,t);s.hasRelationFilters&&(o=!0),s.node&&n.push(s.node)}return n.length===0?{node:null,hasRelationFilters:o}:n.length===1?{node:n[0],hasRelationFilters:o}:{node:{kind:r,children:n},hasRelationFilters:o}}function ji(r,e,t,n){if(typeof e!="object"||e===null)return{node:null,hasRelationFilters:!0};let o=Object.keys(e),i=o.length===1&&(o[0]==="_is_null"||o[0]==="_is_not_null"||o[0]==="_eq"||o[0]==="_neq"||o[0]==="_in"||o[0]==="_not_in"||o[0]==="_nin"),s=n.registry.registerWithParent(n.currentTable,r,n.metadata,"left",n.currentJoinId,"filter");if(i&&o[0]==="_is_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_null===!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(i&&o[0]==="_is_not_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_not_null!==!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(i&&(o[0]==="_eq"||o[0]==="_neq")&&e[o[0]]===null)return s?{node:{kind:"relation_exists",joinId:s,negate:o[0]==="_eq"},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(!s)return{node:null,hasRelationFilters:!0};let a=t.targetTableName||t.targetTable,u={...n,parentJoinId:n.currentJoinId,currentJoinId:s,currentTable:a},l=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]),c=o.length>0&&o.every(d=>l.has(d))?{id:e}:e;return{node:tn(c,u).node,hasRelationFilters:!0}}function Li(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:Bi(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("_")&&!Z.has(s)&&Ue(s,r,t.tableName);let o=Object.entries(e).filter(([s])=>Z.has(s));if(o.length===0)return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};let i=[];for(let[s,a]of o){let u=Di(n,s,a);u&&i.push(u)}return i.length===0?{node:null,hasRelationFilters:!1}:i.length===1?{node:i[0],hasRelationFilters:!1}:{node:{kind:"and",children:i},hasRelationFilters:!1}}function Di(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=Zt(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function Bi(r,e){let t=e.metadata?.tables?.get(e.currentTable);if(!t)return!1;let n=r.includes(".")?r.split(".").pop():r,o=t.columns?.find(s=>s.name===n);if(!o)return!1;let i=(o.type||"").toLowerCase();return i==="uuid"||i==="uuidv4"||i.includes("uuid")}var Nt=W(()=>{"use strict";vt();Ze()});var ie,Mt=W(()=>{"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,o="left",i=null,s="data"){let a=i?`${i}.${t}`:t;if(this.map.has(a)){let p=this.map.get(a);return o==="inner"&&(p.joinType="inner"),p.purposes.includes(s)||p.purposes.push(s),a}let u=n?.tables?.get(e);if(!u)return null;let l=u.relations?.find(p=>p.propertyName===t);if(!l)return null;let f=l.targetTableName||l.targetTable;if(!f)return null;let c={id:a,propertyName:t,parentTable:e,targetTable:f,relationType:l.type,parentJoinId:i,joinType:o,relationMeta:l,purposes:[s]};return this.map.set(a,c),a}}});async function G(r,e){if(r.length<=xe)return e(r);let t=[];for(let a=0;a<r.length;a+=xe)t.push(r.slice(a,a+xe));let n=[],o=0;async function i(){for(;o<t.length;){let a=o++;n[a]=await e(t[a])}}let s=Math.min(Dn,t.length);return await Promise.all(Array.from({length:s},i)),n.flat()}function tt(r){let e=[],t=new Map;for(let n of r)if(n==="*"||!n.includes("."))e.push(n);else{let o=n.split("."),i=o[0],s=o.slice(1).join(".");t.has(i)||t.set(i,[]),t.get(i).push(s)}return{rootFields:e,subRelations:t}}var ee,xe,Dn,Bn,Ce,nt=W(()=>{"use strict";Se();ee=16,xe=5e3,Dn=4,Bn=10;Ce=class{constructor(e,t,n){this.adapter=e;this.metadataGetter=t;this.trace=n}enrichNestedDescs(e,t){return!t||Object.keys(t).length===0?e:e.map(n=>{let o=t[n.relationName];if(!o)return n;let i=o.fields!=null?Array.isArray(o.fields)?o.fields:String(o.fields).split(",").map(s=>s.trim()).filter(Boolean):n.fields;return{...n,fields:i,userFilter:o.filter??n.userFilter,userSort:o.sort??n.userSort,userLimit:o.limit!==void 0?Number(o.limit):n.userLimit,userPage:o.page!==void 0?Number(o.page):n.userPage,nestedDeep:o.deep??n.nestedDeep}})}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:Bn}:e}assertLocalSortFields(e,t){if(!e.userSort)return;let n=Array.isArray(e.userSort)?e.userSort:String(e.userSort).split(",").map(o=>o.trim()).filter(Boolean);for(let o of n){let i=o.startsWith("-")?o.slice(1):o;if(i.includes("."))throw new A(`Sort field '${i}' is not supported on deep relation '${e.relationName}'. Sort only by local fields defined on '${e.targetTable}'.`);let s=t.columns?.some(u=>u.name===i),a=i==="id"&&t.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new A(`Sort field '${i}' does not exist on '${e.targetTable}'. Sort only by fields defined on the table metadata.`)}}async execute(e,t,n=3,o=0,i){if(e.length===0||t.length===0||o>=n)return;let s;i&&(s=await this.metadataGetter(i)??void 0),await Promise.all(t.map(a=>{let u=this.withDefaultToManyLimit(a);return u.type==="many-to-one"||u.type==="one-to-one"&&!u.isInverse?this.fetchOwnerRelation(e,u,n,o):u.type==="one-to-many"||u.type==="one-to-one"&&u.isInverse?this.fetchInverseRelation(e,u,n,o,s):u.type==="many-to-many"?this.fetchM2MRelation(e,u,n,o,s):Promise.resolve()}))}async fetchOwnerRelation(e,t,n,o){let i=this.adapter.resolveOwnerFkKey(t),s=new Set,a=[];for(let h of e){let b=h[i];if(b==null)continue;let S=this.adapter.keyOf(b);s.has(S)||(s.add(S),a.push(b))}if(a.length===0){for(let h of e)h[i]=null,t.fkColumn&&t.fkColumn!==i&&delete h[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:l,nestedDescs:f,fetchSpec:c}=this.adapter.resolveFields(t.fields,u),p=this.adapter.getTargetPkField(u);if(l){for(let h of e){let b=h[i];h[i]=b!=null?this.adapter.buildScalarRef(b,p):null,t.fkColumn&&t.fkColumn!==i&&delete h[t.fkColumn]}return}let d=performance.now(),g=await this.adapter.fetchOwner(t.targetTable,a,c,t);this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,d,{relationType:t.type,targetTable:t.targetTable,strategy:"batch-in",roundtrips:Math.ceil(a.length/xe)||1,rowsTransferred:g.length,rowsReturned:g.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let m=this.enrichNestedDescs(f,t.nestedDeep);m.length>0&&await this.execute(g,m,n,o+1,t.targetTable);let y=new Map;for(let h of g)y.set(this.adapter.keyOf(h[p]),h);for(let h of e){let b=h[i];h[i]=b!=null&&y.get(this.adapter.keyOf(b))||null,t.fkColumn&&t.fkColumn!==i&&delete h[t.fkColumn]}}async fetchInverseRelation(e,t,n,o,i){let s=this.adapter.resolveParentPk(i),a=e.map(_=>_[s]).filter(_=>_!=null);if(a.length===0)return;let u=this.adapter.resolveInverseFkField(t),l=await this.metadataGetter(t.targetTable);if(!l)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,l);let{nestedDescs:f,fetchSpec:c}=this.adapter.resolveFields(t.fields,l),p=performance.now(),{docs:d,groupKeyField:g}=await this.adapter.fetchInverse(t.targetTable,u,a,c,t),m=new Map,y=t.fields.includes(u)||t.fields.includes("*");for(let _ of d){let N=_[g],v=this.adapter.keyOf(N);m.has(v)||m.set(v,[]),m.get(v).push(_)}let h=t.userLimit!==void 0&&t.userLimit>0,b=h?"per-parent-c16":"batch-in",S=h?a.length:Math.ceil(a.length/xe)||1,w=h?Math.ceil(a.length/ee):void 0,$=Array.from(m.values()).reduce((_,N)=>_+N.length,0);if(this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:b,roundtrips:S,concurrencyWaves:w,rowsTransferred:d.length,rowsReturned:$,rowsDiscarded:d.length-$,userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let _ of d)this.adapter.postProcessInverseChild(_,u,y);let k=this.enrichNestedDescs(f,t.nestedDeep);k.length>0&&await this.execute(d,k,n,o+1,t.targetTable);let R=t.type==="one-to-one";for(let _ of e){let N=this.adapter.keyOf(_[s]),v=m.get(N)||[];_[t.relationName]=R?v[0]||null:v}}async fetchM2MRelation(e,t,n,o,i){let s=this.adapter.resolveParentPk(i),a=e.map(w=>w[s]).filter(w=>w!=null);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:l,fetchSpec:f}=this.adapter.resolveFields(t.fields,u),c=performance.now(),{grouped:p,docs:d}=await this.adapter.fetchM2M(e,t,i,u,f),g=t.userLimit!==void 0&&t.userLimit>0,m=g?"m2m-per-parent-c16":"m2m-batch",y=g?a.length:Math.ceil(a.length/xe)||1,h=g?Math.ceil(a.length/ee):void 0,b=Array.from(p.values()).reduce((w,$)=>w+$.length,0);this.trace?.dur(`batch_fetch_L${o}_${t.relationName}`,c,{relationType:t.type,targetTable:t.targetTable,strategy:m,roundtrips:y,concurrencyWaves:h,rowsTransferred:d.length,rowsReturned:b,rowsDiscarded:d.length-b,userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort});let S=this.enrichNestedDescs(l,t.nestedDeep);S.length>0&&d.length>0&&await this.execute(d,S,n,o+1,t.targetTable);for(let w of e){let $=this.adapter.keyOf(w[s]);w[t.relationName]=p.get($)||[]}}}});async function ge(r,e,t){let n=new Map,o=0;async function i(){for(;o<r.length;){let u=o++,l=r[u];n.set(String(l),await e(l))}}let s=Math.min(t,r.length);if(s===0)return n;let a=Array.from({length:s},i);return await Promise.all(a),n}var sn=W(()=>{"use strict"});function C(r,e){switch(e){case"mysql":return`\`${r}\``;case"postgres":case"pg":case"sqlite":return`"${r}"`;case"mongodb":return r;default:return`\`${r}\``}}var ve=W(()=>{"use strict"});function Y(r,e,t){e&&pn(r,e,t,"and")}function pn(r,e,t,n){switch(e.kind){case"true":return;case"false":n==="or"?r.orWhereRaw("1 = 0"):r.whereRaw("1 = 0");return;case"and":{let o=function(){for(let i of e.children)this.where(function(){pn(this,i,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"or":{let o=function(){for(let i of e.children)this.orWhere(function(){pn(this,i,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"not":{let o=function(){this.whereNot(function(){pn(this,e.child,t,"and")})};n==="or"?r.orWhere(o):r.where(o);return}case"compare":co(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 co(r,e,t,n){if(e.field.joinId!==null){console.warn(`[sql-render-filter] compare node has joinId=${e.field.joinId} (field=${e.field.fieldName}) but reached renderer \u2014 expected join path to handle it. Filter silently skipped.`);return}let o=uo(e.field,t),i=!!e.field.isUuid,s=t.dbType==="postgres",a=n==="or"?"orWhere":"where",u=n==="or"?"orWhereRaw":"whereRaw",l=n==="or"?"orWhereIn":"whereIn",f=n==="or"?"orWhereNotIn":"whereNotIn",c=n==="or"?"orWhereBetween":"whereBetween",p=n==="or"?"orWhereNull":"whereNull",d=n==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":i&&s&&typeof e.value=="string"?r[u](`${o} = ?::uuid`,[e.value]):r[a](o,"=",e.value);return;case"neq":i&&s&&typeof e.value=="string"?r[u](`${o} != ?::uuid`,[e.value]):r[a](o,"!=",e.value);return;case"gt":i&&s&&typeof e.value=="string"?r[u](`${o} > ?::uuid`,[e.value]):r[a](o,">",e.value);return;case"gte":i&&s&&typeof e.value=="string"?r[u](`${o} >= ?::uuid`,[e.value]):r[a](o,">=",e.value);return;case"lt":i&&s&&typeof e.value=="string"?r[u](`${o} < ?::uuid`,[e.value]):r[a](o,"<",e.value);return;case"lte":i&&s&&typeof e.value=="string"?r[u](`${o} <= ?::uuid`,[e.value]):r[a](o,"<=",e.value);return;case"in":{let g=Jr(e.value);i&&s&&g.every(m=>typeof m=="string")?r[u](`${o} = ANY(?::uuid[])`,[g]):r[l](o,g);return}case"not_in":{let g=Jr(e.value);i&&s&&g.every(m=>typeof m=="string")?r[u](`${o} != ALL(?::uuid[])`,[g]):r[f](o,g);return}case"contains":Hn(r,o,e.value,"contains",t,n);return;case"starts_with":Hn(r,o,e.value,"starts_with",t,n);return;case"ends_with":Hn(r,o,e.value,"ends_with",t,n);return;case"between":Array.isArray(e.value)&&e.value.length===2&&r[c](o,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?r[p](o):r[d](o);return}}function Hn(r,e,t,n,o,i){let s=i==="or"?"orWhereRaw":"whereRaw";if(o.dbType==="postgres"){let u=n==="contains"?`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?)) || '%'`:n==="starts_with"?`lower(unaccent(${e})) ILIKE lower(unaccent(?)) || '%'`:`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?))`;r[s](u,[t]);return}if(o.dbType==="sqlite"){let u=n==="contains"?`lower(${e}) LIKE '%' || lower(?) || '%'`:n==="starts_with"?`lower(${e}) LIKE lower(?) || '%'`:`lower(${e}) LIKE '%' || lower(?)`;r[s](u,[t]);return}let a=n==="contains"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:n==="starts_with"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`;r[s](a,[t])}function uo(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function Jr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var Gn=W(()=>{"use strict"});function te(r){return r.columns.find(e=>e.isPrimary)||null}var Lt=W(()=>{"use strict"});var zr={};bn(zr,{expandFieldsToJoinsAndSelect:()=>Yn});async function Yn(r,e,t,n,o,i){let s=[],a=[],u=await t(r);if(!u)return{select:[],batchFetchDescriptors:[]};let l=new Map;for(let c of e)if(c==="*"||!c.includes("."))l.has("")||l.set("",[]),l.get("").push(c);else{let p=c.split("."),d=p[0],g=p.slice(1).join(".");l.has(d)||l.set(d,[]),l.get(d).push(g)}let f=l.get("")||[];for(let c of f){if(c==="*"){let g=new Set;for(let y of u.relations||[])if(y.type==="many-to-one"||y.type==="one-to-one"&&!y.isInverse){let h=y.foreignKeyColumn||K(y.targetTableName);h&&g.add(h)}let m=new Set;for(let y of u.columns)g.has(y.name)||(s.push(`${r}.${y.name}`),m.add(y.name));for(let y of u.relations||[])!l.has(y.propertyName)&&!m.has(y.propertyName)&&l.set(y.propertyName,["id"]);continue}if(c.includes(".")){s.push(`${r}.${c}`);continue}if(u.columns?.find(g=>g.name===c)){s.push(`${r}.${c}`);continue}if(u.relations?.find(g=>g.propertyName===c)){l.has(c)||l.set(c,["id"]);continue}}return l.forEach((c,p)=>{if(p==="")return;let d=u.relations?.find(b=>b.propertyName===p);if(!d)return;if(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse){let b=d.foreignKeyColumn||K(d.targetTableName||d.targetTable),S=C(r,n),w=C(b,n),$=C(p,n);s.push(`${S}.${w} as ${$}`)}let m=d.targetTableName||d.targetTable,y=i?.[p],h=y?.fields!=null?Array.isArray(y.fields)?y.fields:String(y.fields).split(",").map(b=>b.trim()).filter(Boolean):c;a.push({relationName:p,type:d.type,targetTable:m,fields:h,isInverse:d.isInverse,fkColumn:d.foreignKeyColumn,mappedBy:d.mappedBy,junctionTableName:d.junctionTableName,junctionSourceColumn:d.junctionSourceColumn,junctionTargetColumn:d.junctionTargetColumn,userFilter:y?.filter,userSort:y?.sort,userLimit:y?.limit!==void 0?Number(y.limit):void 0,userPage:y?.page!==void 0?Number(y.page):void 0,nestedDeep:y?.deep})}),{select:s,batchFetchDescriptors:a}}var Xn=W(()=>{"use strict";Ke();ve()});var ft,er=W(()=>{"use strict";Ke();ve();Lt();nt();Gn();Mt();Nt();sn();ft=class{constructor(e,t="postgres",n){this.knex=e;this.dbType=t;this.metadata=n;this.pkField="id"}buildFilterTree(e,t){if(!e||!this.metadata)return null;let n=new ie,o=this.metadata?.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))},{node:i}=ke(e,t,o,n);return i}parseSortTokens(e,t,n){return e?(Array.isArray(e)?e:e.split(",").map(i=>i.trim()).filter(Boolean)).map(i=>{let s=i.startsWith("-"),u=(s?i.slice(1):i).split(".");if(u.length===1)return{column:n?`${n}.${u[0]}`:`${t}.${u[0]}`,order:s?"desc":"asc"};let l=u[u.length-1];return{column:`${`__sort_${u.slice(0,-1).join("_")}`}.${l}`,order:s?"desc":"asc"}}):[]}applySortJoins(e,t,n,o){if(!t||!this.metadata)return;let i=Array.isArray(t)?t:t.split(",").map(a=>a.trim()).filter(Boolean),s=new Set;for(let a of i){let l=(a.startsWith("-")?a.slice(1):a).split(".");if(l.length<=1)continue;let f=n,c=o||n;for(let p=0;p<l.length-1;p++){let d=l[p],g=this.metadata?.tables?.get(f);if(!g)break;let m=g.relations?.find(b=>b.propertyName===d);if(!m)break;let y=m.targetTableName||m.targetTable,h=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(h)){s.add(h);let b=m.foreignKeyColumn||K(m.propertyName),S=this.metadata?.tables?.get(y),w=S&&te(S)?.name||"id";e.leftJoin(`${y} as ${h}`,`${h}.${w}`,`${c}.${b}`)}f=y,c=h}}}toKnexSelect(e,t){let n=e.indexOf(" as ");if(n!==-1){let o=e.substring(0,n),i=e.substring(n+4),s=C(i,this.dbType),a=t?`${t}.${C(o,this.dbType)}`:C(o,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${t}.${C(e,this.dbType)} as ${C(e,this.dbType)}`):e}keyOf(e){return e==null?"":String(e)}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return te(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;return!t&&e.mappedBy&&(t=K(e.mappedBy)),t||(t=K(e.targetTable)),t}resolveParentPk(e){return e&&te(e)?.name||"id"}resolveFields(e,t){let{rootFields:n,subRelations:o}=tt(e),i=[];if(n.includes("*")){let l=new Set;for(let f of t.relations||[])if(f.type==="many-to-one"||f.type==="one-to-one"&&!f.isInverse){let c=f.foreignKeyColumn||K(f.propertyName);c&&l.add(c)}for(let f of t.columns)l.has(f.name)||i.push(f.name);for(let f of t.relations||[])o.has(f.propertyName)||o.set(f.propertyName,["id"])}else for(let l of n){let f=t.columns.find(c=>c.name===l);f?i.push(f.name):t.relations?.find(p=>p.propertyName===l)&&!o.has(l)&&o.set(l,["id"])}let s=te(t)?.name||"id";i.includes(s)||i.push(s),o.forEach((l,f)=>{let c=t.relations?.find(p=>p.propertyName===f);if(c&&(c.type==="many-to-one"||c.type==="one-to-one"&&!c.isInverse)){let p=c.foreignKeyColumn||K(c.propertyName);p&&i.push(`${p} as ${f}`)}});let a=[];return o.forEach((l,f)=>{let c=t.relations?.find(d=>d.propertyName===f);if(!c)return;let p=c.targetTableName||c.targetTable;p&&a.push({relationName:f,type:c.type,targetTable:p,fields:l,isInverse:c.isInverse,fkColumn:c.foreignKeyColumn,mappedBy:c.mappedBy,junctionTableName:c.junctionTableName,junctionSourceColumn:c.junctionSourceColumn,junctionTargetColumn:c.junctionTargetColumn})}),{isPkOnly:i.length===1&&i[0]===s&&a.length===0,nestedDescs:a,fetchSpec:{selectCols:i,pkCol:s}}}async fetchOwner(e,t,n,o){let i=o?.userFilter?this.buildFilterTree(o.userFilter,e):null,s=o?.userSort?this.parseSortTokens(o.userSort,e):[],a=n.selectCols.map(u=>this.toKnexSelect(u));return G(t,u=>{let l=this.knex(e).select(a).whereIn(n.pkCol,u);if(i&&Y(l,i,{dbType:this.dbType,rootTable:e}),s.length>0){this.applySortJoins(l,o.userSort,e);for(let f of s)l.orderBy(f.column,f.order)}return l})}async fetchInverse(e,t,n,o,i){let s=t,a=o.selectCols.find(g=>g.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():o.selectCols.includes(t)||o.selectCols.push(t);let u=i?.userFilter?this.buildFilterTree(i.userFilter,e):null,l=i?.userSort?this.parseSortTokens(i.userSort,e):[],f=i?.userLimit,c=i?.userPage;if(f!==void 0&&f>0){let g=c?(c-1)*f:0,m=o.selectCols.map(b=>this.toKnexSelect(b)),y=await ge(n,async b=>{let S=this.knex(e).select(m).where(t,b);if(u&&Y(S,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(S,i.userSort,e),l.length>0)for(let w of l)S.orderBy(w.column,w.order);else S.orderBy(o.pkCol,"asc");return g>0&&S.offset(g),S.limit(f),S},ee),h=[];for(let[b,S]of y.entries()){let w=n.find($=>String($)===b);for(let $ of S)$[t]||($[t]=w??b),h.push($)}return{docs:h,groupKeyField:s}}let p=o.selectCols.map(g=>this.toKnexSelect(g));return{docs:await G(n,g=>{let m=this.knex(e).select(p).whereIn(t,g);if(u&&Y(m,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(m,i?.userSort,e),l.length>0)for(let y of l)m.orderBy(y.column,y.order);else m.orderBy(o.pkCol,"asc");return m}),groupKeyField:s}}postProcessInverseChild(e,t,n){n||delete e[t]}async fetchM2M(e,t,n,o,i){let s=this.resolveParentPk(n),a=e.map(S=>S[s]).filter(S=>S!=null);if(a.length===0)return{grouped:new Map,docs:[]};let u=t.junctionTableName,l=t.junctionSourceColumn,f=t.junctionTargetColumn;if(!u||!l||!f)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let c=t.userFilter?this.buildFilterTree(t.userFilter,t.targetTable):null,p=t.userSort?this.parseSortTokens(t.userSort,t.targetTable,"t"):[],d=t.userLimit,g=t.userPage;if(i.selectCols.length===1&&i.selectCols[0]===i.pkCol&&!c&&!d){let S=await G(a,$=>this.knex(u).select([`${l} as __sourceId__`,`${f} as __targetId__`]).whereIn(l,$).orderBy(f,"asc")),w=new Map;for(let $ of S){let k=this.keyOf($.__sourceId__);w.has(k)||w.set(k,[]),w.get(k).push({[i.pkCol]:$.__targetId__})}return{grouped:w,docs:[]}}let y=i.selectCols.map(S=>this.toKnexSelect(S,"t"));if(d!==void 0&&d>0){let S=g?(g-1)*d:0,w=new Map;for(let R of a)w.set(this.keyOf(R),[]);let $=await ge(a,async R=>{let _=this.knex(u).join(`${t.targetTable} as t`,`${u}.${f}`,`t.${i.pkCol}`).select(y).where(`${u}.${l}`,R);if(c&&Y(_,c,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(_,t.userSort,t.targetTable,"t"),p.length>0)for(let N of p)_.orderBy(N.column,N.order);else _.orderBy(`t.${i.pkCol}`,"asc");return S>0&&_.offset(S),_.limit(d),_},ee),k=[];for(let[R,_]of $.entries()){w.set(R,_);for(let N of _)k.push(N)}return{grouped:w,docs:k}}let h=await G(a,S=>{let w=this.knex(u).join(`${t.targetTable} as t`,`${u}.${f}`,`t.${i.pkCol}`).select([`${u}.${l} as __sourceId__`,...y]).whereIn(`${u}.${l}`,S);if(c&&Y(w,c,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(w,t.userSort,t.targetTable,"t"),p.length>0)for(let $ of p)w.orderBy($.column,$.order);else w.orderBy(`t.${i.pkCol}`,"asc");return w}),b=new Map;for(let S of h){let w=S.__sourceId__;delete S.__sourceId__;let $=this.keyOf(w);b.has($)||b.set($,[]),b.get($).push(S)}return{grouped:b,docs:h}}}});var Gr={};bn(Gr,{executeBatchFetches:()=>tr});async function tr(r,e,t,n,o=3,i=0,s,a="postgres",u,l){let f=new ft(r,a,u);await new Ce(f,n,l).execute(e,t,o,i,s)}var nr=W(()=>{"use strict";nt();er()});var yo={};bn(yo,{ALL_SUPPORTED_OPERATORS:()=>Rt,AuthenticationException:()=>Pe,AuthorizationException:()=>je,BadRequestException:()=>A,BatchFetchEngine:()=>Ce,BusinessLogicException:()=>Ae,CHUNKED_FETCH_CONCURRENCY:()=>Dn,ConfigurationException:()=>wt,DEEP_TO_MANY_DEFAULT_LIMIT:()=>Bn,DEFAULT_TIMEOUT_MS:()=>Kt,DOTTED_PATH_MAX_HOPS:()=>mn,DatabaseException:()=>_e,DuplicateResourceException:()=>Ee,ErrorHandler:()=>De,ExecutorEngineService:()=>ze,ExternalServiceException:()=>bt,FIELD_OPERATORS:()=>Z,FileNotFoundException:()=>Tt,FileSizeExceededException:()=>St,FileUploadException:()=>$t,HttpException:()=>Me,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>Ut,InvalidTokenException:()=>ht,IsolatedExecutorService:()=>He,JoinRegistry:()=>ie,LOGICAL_OPERATORS:()=>Mn,MongoBatchAdapter:()=>rt,MongoQueryExecutor:()=>at,PER_PARENT_CONCURRENCY:()=>ee,QueryBuilderService:()=>pt,QueryPlanner:()=>J,ResourceNotFoundException:()=>Ie,SchemaException:()=>_t,ScriptExecutionException:()=>be,ScriptTimeoutException:()=>he,ServiceUnavailableException:()=>Le,SqlBatchAdapter:()=>ft,SqlQueryExecutor:()=>dt,TokenExpiredException:()=>mt,ValidationException:()=>Oe,WHERE_IN_CHUNK_SIZE:()=>xe,WorkerPool:()=>Ft,appendIsolatedExecutorRuntimeLog:()=>z,applyOperatorToMatch:()=>Xt,applyRelationFilters:()=>Ve,applyWhereToKnex:()=>ut,assertFieldOperatorValueIsClean:()=>en,buildAggregateFilter:()=>st,buildMongoCharFoldMapJson:()=>vn,buildMongoFoldTextSearchJs:()=>qt,buildRelationSubquery:()=>Et,buildSqlWherePartsFromFieldAst:()=>jt,buildWhereClause:()=>se,camelToSnake:()=>$r,chunkedFetch:()=>G,compileScriptSource:()=>ce,computeEngineTuning:()=>Tn,createEnfyraKernel:()=>go,dslOpToCompareOp:()=>Zt,encodeMainThreadToIsolate:()=>xn,escapeSqlValue:()=>Vr,executeBatchFetches:()=>tr,executeMongoBatchFetches:()=>an,expandFieldsToJoinsAndSelect:()=>Yn,getEffectiveCpuCount:()=>$n,getEffectiveMemoryBytes:()=>kt,getEngineTuning:()=>Vt,getExecutableScript:()=>hi,getForeignKeyColumnName:()=>K,getIoAbortSignal:()=>mr,getJunctionColumnNames:()=>fe,getJunctionTableName:()=>ue,getPrimaryKeyColumn:()=>te,getScriptLegacyField:()=>Sn,getShortFkConstraintName:()=>_r,getShortFkName:()=>Tr,getShortIndexName:()=>Sr,getShortPkName:()=>br,hasAggregateQuery:()=>Un,hasLogicalOperators:()=>ye,isExecutableJavaScript:()=>cr,isScriptTable:()=>kn,mergeAggregateValue:()=>Re,normalizeAggregateQuery:()=>ot,normalizeFlowStepScriptConfig:()=>bi,normalizeScriptLanguage:()=>Ct,normalizeScriptPatch:()=>mi,normalizeScriptRecord:()=>yi,parseBatchFields:()=>tt,parseFields:()=>ln,parseFilter:()=>ke,perParentRun:()=>ge,quoteIdentifier:()=>C,resolveExecutableScript:()=>ur,rewriteFilterDenyingFields:()=>Xr,rewriteSortDroppingDenied:()=>Zr,separateFilters:()=>H,snakeToCamel:()=>wr,throwUnsupportedFieldOperator:()=>Ue,transformCode:()=>wn,validateDeepOptions:()=>rr,validateFilterShape:()=>Q,whereToMongoFilter:()=>Xe});module.exports=oi(yo);var si={"@CACHE":"$ctx.$cache","@REPOS":"$ctx.$repos","@HELPERS":"$ctx.$helpers","@FETCH":"$ctx.$helpers.$fetch","@LOGS":"$ctx.$logs","@BODY":"$ctx.$body","@DATA":"$ctx.$data","@PARAMS":"$ctx.$params","@QUERY":"$ctx.$query","@USER":"$ctx.$user","@REQ":"$ctx.$req","@RES":"$ctx.$res","@SHARE":"$ctx.$share","@API":"$ctx.$api","@UPLOADED_FILE":"$ctx.$uploadedFile","@PKGS":"$ctx.$pkgs","@SOCKET":"$ctx.$socket","@TRIGGER":"$ctx.$trigger","@FLOW":"$ctx.$flow","@FLOW_PAYLOAD":"$ctx.$flow.$payload","@FLOW_LAST":"$ctx.$flow.$last","@FLOW_META":"$ctx.$flow.$meta","@THROW400":"$ctx.$throw['400']","@THROW401":"$ctx.$throw['401']","@THROW403":"$ctx.$throw['403']","@THROW404":"$ctx.$throw['404']","@THROW409":"$ctx.$throw['409']","@THROW422":"$ctx.$throw['422']","@THROW429":"$ctx.$throw['429']","@THROW500":"$ctx.$throw['500']","@THROW503":"$ctx.$throw['503']","@THROW":"$ctx.$throw","@ERROR":"$ctx.$error","@STATUS":"$ctx.$statusCode"},me=0,or=1,sr=2,_n=3,ar=4,lr=5;function wn(r){let e=r.length,t="",n=0,o=me,i=0,s=0;for(;n<e;){let a=r[n],u=r[n+1];switch(o){case me:if(a==='"')o=or,t+=a,n++;else if(a==="'")o=sr,t+=a,n++;else if(a==="`")o=_n,t+=a,n++;else if(a==="/"&&u==="/")o=ar,t+=a+u,n+=2;else if(a==="/"&&u==="*")o=lr,t+=a+u,n+=2;else if(a==="@"||a==="#"||a==="%"){let l=n,f=a;for(n++;n<e;){let p=r[n];if(p>="A"&&p<="Z"||p>="0"&&p<="9"||p==="_")n++;else break}let c=r.substring(l,n);if(f==="@"){let p=si[c];t+=p||c}else f==="#"?t+="$ctx.$repos."+c.substring(1):t+="$ctx.$pkgs."+c.substring(1)}else a==="{"?(i>0&&s++,t+=a,n++):a==="}"&&i>0?s>0?(s--,t+=a,n++):(i--,t+=a,n++,o=_n):(t+=a,n++);break;case or:t+=a,a==="\\"?(n++,n<e&&(t+=r[n],n++)):(a==='"'&&(o=me),n++);break;case sr:t+=a,a==="\\"?(n++,n<e&&(t+=r[n],n++)):(a==="'"&&(o=me),n++);break;case _n:t+=a,a==="\\"?(n++,n<e&&(t+=r[n],n++)):a==="`"?(o=me,n++):a==="$"&&n+1<e&&r[n+1]==="{"?(t+="{",n+=2,i++,o=me):n++;break;case ar:t+=a,a===`
2
- `&&(o=me),n++;break;case lr:t+=a,a==="*"&&u==="/"?(t+=u,n+=2,o=me):n++;break}}return t}var Kt=3e4,ze=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){let n=e.routeData.__codeBlocks||[];return n.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(n,e.routeData.context,t??Kt)}async run(e,t,n=Kt){return this.isolatedExecutorService.run(e,t,n)}};var Wt=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 dr=require("async_hooks"),pr=le(require("path")),gr=require("worker_threads");var he=class extends Error{constructor(t=0,n){let o=typeof t=="number"&&t>0?`${t}ms`:String(t||"configured timeout");super(`Script execution timed out after ${o}`);this.statusCode=408;this.errorCode="SCRIPT_TIMEOUT";this.name="ScriptTimeoutException",this.details={timeoutMs:t,scriptId:n}}},be=class extends Error{constructor(t,n,o){super(`Script execution failed: ${t}`);this.statusCode=400;this.errorCode="SCRIPT_EXECUTION_ERROR";this.name="ScriptExecutionException",this.details={scriptId:n,...o}}},j=class extends Error{constructor(t,n,o,i){super(t);this.statusCode=n;this.errorCode=o;this.name=this.constructor.name,this.details=i}},Me=class extends j{constructor(e,t,n){super(e,t,`HTTP_${t}`,n)}},Ae=class extends j{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},Oe=class extends j{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},Ie=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})}},Ee=class extends j{constructor(e,t,n){super(`${e} with ${t} '${n}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:n})}},Pe=class extends j{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},je=class extends j{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},mt=class extends j{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},ht=class extends j{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},_e=class extends j{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},bt=class extends j{constructor(e,t,n){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:n})}},Le=class extends j{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},_t=class extends j{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},wt=class extends j{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},$t=class extends j{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},Tt=class extends j{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},St=class extends j{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var De=class{static createException(e,t,n,o,i){if(e?.includes("$throw"))switch(e){case"$throw.businessLogic":return new Ae(n||"Bad request",i);case"$throw.validation":return new Oe(n||"Validation failed",i);case"$throw.notFound":return new Ie(n||"Resource");case"$throw.duplicate":return new Ee(n||"Resource","field","value");case"$throw.unauthorized":return new Pe(n||"Unauthorized");case"$throw.forbidden":return new je(n||"Forbidden");case"$throw.tokenExpired":return new mt;case"$throw.invalidToken":return new ht;case"$throw.database":return new _e(n||"Database error",i);case"$throw.dbQuery":return new _e(n||"Query error",i);case"$throw.externalService":return new bt(n||"Service",n||"Error",i);case"$throw.serviceUnavailable":return new Le(n||"Service");case"$throw.rateLimit":return new Me(n||"Rate limit exceeded",429);case"$throw.scriptError":return new be(n||"Script error",o,i);case"$throw.scriptTimeout":return new he(i?.timeout||5e3,o);case"$throw.schema":return new _t(n||"Schema error",i);case"$throw.config":return new wt(n||"Configuration error",i);case"$throw.fileUpload":return new $t(n||"File upload error",i);case"$throw.fileNotFound":return new Tt(n||"File not found");case"$throw.fileSizeExceeded":return new St(i?.maxSize||"unknown",i?.actualSize||"unknown");case"$throw.400":return new Ae(n||"Bad request");case"$throw.401":return new Pe(n||"Authentication required");case"$throw.403":return new je(n||"Insufficient permissions");case"$throw.404":return new Ie(n||"Resource");case"$throw.409":return new Ee(n||"Resource","field","value");case"$throw.422":return new Oe(n||"Validation failed");case"$throw.429":return new Me(n||"Rate limit exceeded",429);case"$throw.500":return new _e(n||"Internal server error",i);case"$throw.503":return new Le(n||"Service");default:return new be(n||"Unknown error",o)}if(t)switch(t){case 400:return new Ae(n||"Bad request");case 401:return new Pe(n||"Authentication required");case 403:return new je(n||"Insufficient permissions");case 404:return new Ie(n||"Resource");case 409:return new Ee(n||"Resource","field","value");case 422:return new Oe(n||"Validation failed");case 429:return new Me(n||"Rate limit exceeded",429);case 500:return new _e(n||"Internal server error",i);case 503:return new Le(n||"Service");default:return new be(n||"Unknown error",o,i)}return new be(n||"Unknown error",o,i)}};var Qt=le(require("fs")),Jt=le(require("path")),Ut=Jt.join(process.cwd(),"test","logs","isolated-executor-runtime.log");function ai(){return process.env.ISOLATED_EXECUTOR_FILE_LOG==="0"?!1:process.env.ISOLATED_EXECUTOR_FILE_LOG==="1"?!0:process.env.JEST_WORKER_ID!==void 0}var li=ai();function z(r){if(li)try{let e=Jt.dirname(Ut);Qt.mkdirSync(e,{recursive:!0});let t=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...r})+`
3
- `;Qt.appendFileSync(Ut,t)}catch{}}var we=le(require("os")),qe=le(require("fs"));function kt(){try{let r=qe.readFileSync("/sys/fs/cgroup/memory.max","utf8").trim();if(r!=="max"){let e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<we.totalmem())return e}}catch{}try{let r=qe.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes","utf8").trim(),e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<we.totalmem())return e}catch{}return we.totalmem()}function $n(){let r=we.availableParallelism?.()||we.cpus()?.length||1;try{let e=qe.readFileSync("/sys/fs/cgroup/cpu.max","utf8").trim(),[t,n]=e.split(/\s+/);if(t!=="max"){let o=parseInt(t,10),i=parseInt(n,10);if(o>0&&i>0)return Math.max(1,Math.ceil(o/i))}}catch{}try{let e=parseInt(qe.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8").trim(),10),t=parseInt(qe.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 ci=.25,ui=2,fi=2048,di=40,pi=128,gi=32;function Tn(r){let e=Math.max(1,Math.trunc(r.logicalCpuCount)||1),t=Math.max(1,r.totalMemoryBytes/(1024*1024)),n=Math.min(pi,Math.max(di,Math.round(t/gi))),o=t*ci,i=Math.max(1,Math.floor(o/n)),s=Math.max(1,Math.min(e,2,i)),a=Math.min(256,Math.max(16,Math.floor(t/n/s))),u=t<fi?1:ui,l=Math.max(1,Math.min(u,Math.floor(o/(s*n))));return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:a,isolatePoolSize:l}}function Vt(){return Tn({logicalCpuCount:$n(),totalMemoryBytes:kt()})}var Be=le(require("typescript"));var 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 Sn(r){return xt[r]}function kn(r){return r in xt}function Ct(r){return r==="javascript"?"javascript":"typescript"}function ce(r,e){if(r==null||r==="")return null;let t=wn(String(r));if(Ct(e)==="javascript")return t;let n=Be.default.transpileModule(t,{compilerOptions:{target:Be.default.ScriptTarget.ES2022,module:Be.default.ModuleKind.CommonJS,importsNotUsedAsValues:Be.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),o=n.diagnostics?.find(i=>i.category===Be.default.DiagnosticCategory.Error);if(o)throw new Error(Be.default.flattenDiagnosticMessageText(o.messageText,`
1
+ "use strict";var ei=Object.create;var Bt=Object.defineProperty;var ti=Object.getOwnPropertyDescriptor;var ni=Object.getOwnPropertyNames;var ri=Object.getPrototypeOf,ii=Object.prototype.hasOwnProperty;var W=(r,e)=>()=>(r&&(e=r(r=0)),e);var bn=(r,e)=>{for(var t in e)Bt(r,t,{get:e[t],enumerable:!0})},ir=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ni(e))!ii.call(r,i)&&i!==t&&Bt(r,i,{get:()=>e[i],enumerable:!(n=ti(e,i))||n.enumerable});return r};var le=(r,e,t)=>(t=r!=null?ei(ri(r)):{},ir(e||!r||!r.__esModule?Bt(t,"default",{value:r,enumerable:!0}):t,r)),oi=r=>ir(Bt({},"__esModule",{value:!0}),r);function xn(r){return hr.createHash("md5").update(r).digest("hex").substring(0,8)}function br(r){return r.length<=Fn-3?`${r}_pk`:`j_${xn(r)}_pk`}function _r(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=Fn?n:`j_${xn(r)}_${t}_fk`}function Ft(r,e,t){let n=`${r}_${e}_${t}`;if(n.length<=Fn)return n;let i=xn(n),o=r.replace(/_definition/g,"").substring(0,10),s=e.substring(0,10),a=t.replace(/_definition/g,"").substring(0,10);return`j_${i}_${o}_${s}_${a}`}function K(r){return`${r}Id`}function xt(r,e,t){let n=K(r);if(r===t){let o=K(e);return{sourceColumn:n,targetColumn:o}}let i=K(t);return{sourceColumn:n,targetColumn:i}}function wr(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function $r(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function Tr(r,e,t){return`${r}_${e}_${t}_fk`}function Sr(r,e,t){return`${r}_${e}_${t}_idx`}var hr,Fn,ze=W(()=>{"use strict";hr=le(require("crypto")),Fn=63});function Zt(r){return Ii[r]??null}var Z,Mn,Rt,Ii,vt=W(()=>{"use strict";Z=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),Mn=new Set(["_and","_or","_not"]),Rt=[...Array.from(Mn),...Array.from(Z)],Ii={_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 M,$e=W(()=>{"use strict";M=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 xr(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var Rr=W(()=>{"use strict"});function Be(r,e,t){throw new M({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${Rt.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:Rt})}function en(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=xr();for(let i of Object.keys(e))if(i.startsWith("_")&&!Z.has(i)){if(n&&i==="_id")continue;Be(i,r,t)}}function Q(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(Ei.has(s)){if(Array.isArray(a))for(let l of a)Q(l,e,t);else a&&typeof a=="object"&&Q(a,e,t);continue}let u=o.get(s);if(u){if(a&&typeof a=="object"&&!Array.isArray(a)){en(s,a,e);let l=u.targetTableName||u.targetTable;if(l){let f=Object.keys(a).filter(c=>!c.startsWith("_"));if(f.length>0){let c={};for(let p of f)c[p]=a[p];Q(c,l,t)}}}continue}s.startsWith("_")&&!i.has(s)&&s!=="_id"&&Be(s,s,e),a&&typeof a=="object"&&!Array.isArray(a)&&en(s,a,e)}}var Ei,Ye=W(()=>{"use strict";$e();vt();Rr();Ei=new Set(["_and","_or","_not"])});function Te(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:tn(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function tn(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=Pi(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 Pi(r,e,t){if(r==="_and")return vr("and",e,t);if(r==="_or")return vr("or",e,t);if(r==="_not"){let l=tn(e,t);return l.node?{node:{kind:"not",child:l.node},hasRelationFilters:l.hasRelationFilters}:{node:null,hasRelationFilters:l.hasRelationFilters}}let n=t.metadata?.tables?.get(t.currentTable),i=n?.columns?.some(l=>l.name==="_id"&&l.isPrimary),o=n?.columns?.some(l=>l.name==="id"),a=r==="id"?i&&!o?"_id":"id":r,u=n?.relations?.find(l=>l.propertyName===a);return u?ji(a,e,u,t):n&&!n.columns?.find(f=>f.name===a)?(r.startsWith("_")&&r!=="_id"&&Be(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}):Li(a,e,t)}function vr(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],i=!1;for(let o of e){let s=tn(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 ji(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},l=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]),c=i.length>0&&i.every(d=>l.has(d))?{id:e}:e;return{node:tn(c,u).node,hasRelationFilters:!0}}function Li(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:Bi(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("_")&&!Z.has(s)&&Be(s,r,t.tableName);let i=Object.entries(e).filter(([s])=>Z.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=Di(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 Di(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=Zt(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function Bi(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 Nt=W(()=>{"use strict";vt();Ye()});var ie,Mt=W(()=>{"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 p=this.map.get(a);return i==="inner"&&(p.joinType="inner"),p.purposes.includes(s)||p.purposes.push(s),a}let u=n?.tables?.get(e);if(!u)return null;let l=u.relations?.find(p=>p.propertyName===t);if(!l)return null;let f=l.targetTableName||l.targetTable;if(!f)return null;let c={id:a,propertyName:t,parentTable:e,targetTable:f,relationType:l.type,parentJoinId:o,joinType:i,relationMeta:l,purposes:[s]};return this.map.set(a,c),a}}});async function Y(r,e){if(r.length<=Se)return e(r);let t=[];for(let a=0;a<r.length;a+=Se)t.push(r.slice(a,a+Se));let n=[],i=0;async function o(){for(;i<t.length;){let a=i++;n[a]=await e(t[a])}}let s=Math.min(Dn,t.length);return await Promise.all(Array.from({length:s},o)),n.flat()}function Ze(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 ee,Se,Dn,Bn,ke,et=W(()=>{"use strict";$e();ee=16,Se=5e3,Dn=4,Bn=10;ke=class{constructor(e,t,n){this.adapter=e;this.metadataGetter=t;this.trace=n}enrichNestedDescs(e,t){return!t||Object.keys(t).length===0?e:e.map(n=>{let i=t[n.relationName];if(!i)return n;let o=i.fields!=null?Array.isArray(i.fields)?i.fields:String(i.fields).split(",").map(s=>s.trim()).filter(Boolean):n.fields;return{...n,fields:o,userFilter:i.filter??n.userFilter,userSort:i.sort??n.userSort,userLimit:i.limit!==void 0?Number(i.limit):n.userLimit,userPage:i.page!==void 0?Number(i.page):n.userPage,nestedDeep:i.deep??n.nestedDeep}})}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:Bn}:e}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 M(`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 M(`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 h of e){let b=h[o];if(b==null)continue;let S=this.adapter.keyOf(b);s.has(S)||(s.add(S),a.push(b))}if(a.length===0){for(let h of e)h[t.relationName]=null,o!==t.relationName&&delete h[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete h[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:l,nestedDescs:f,fetchSpec:c}=this.adapter.resolveFields(t.fields,u),p=this.adapter.getTargetPkField(u);if(l){for(let h of e){let b=h[o];h[t.relationName]=b!=null?this.adapter.buildScalarRef(b,p):null,o!==t.relationName&&delete h[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete h[t.fkColumn]}return}let d=performance.now(),g=await this.adapter.fetchOwner(t.targetTable,a,c,t);this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,d,{relationType:t.type,targetTable:t.targetTable,strategy:"batch-in",roundtrips:Math.ceil(a.length/Se)||1,rowsTransferred:g.length,rowsReturned:g.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let m=this.enrichNestedDescs(f,t.nestedDeep);m.length>0&&await this.execute(g,m,n,i+1,t.targetTable);let y=new Map;for(let h of g)y.set(this.adapter.keyOf(h[p]),h);for(let h of e){let b=h[o];h[t.relationName]=b!=null&&y.get(this.adapter.keyOf(b))||null,o!==t.relationName&&delete h[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete h[t.fkColumn]}}async fetchInverseRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=e.map(_=>_[s]).filter(_=>_!=null);if(a.length===0)return;let u=this.adapter.resolveInverseFkField(t),l=await this.metadataGetter(t.targetTable);if(!l)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,l);let{nestedDescs:f,fetchSpec:c}=this.adapter.resolveFields(t.fields,l),p=performance.now(),{docs:d,groupKeyField:g}=await this.adapter.fetchInverse(t.targetTable,u,a,c,t),m=new Map,y=t.fields.includes(u)||t.fields.includes("*");for(let _ of d){let N=_[g],v=this.adapter.keyOf(N);m.has(v)||m.set(v,[]),m.get(v).push(_)}let h=t.userLimit!==void 0&&t.userLimit>0,b=h?"per-parent-c16":"batch-in",S=h?a.length:Math.ceil(a.length/Se)||1,w=h?Math.ceil(a.length/ee):void 0,$=Array.from(m.values()).reduce((_,N)=>_+N.length,0);if(this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:b,roundtrips:S,concurrencyWaves:w,rowsTransferred:d.length,rowsReturned:$,rowsDiscarded:d.length-$,userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let _ of d)this.adapter.postProcessInverseChild(_,u,y);let k=this.enrichNestedDescs(f,t.nestedDeep);k.length>0&&await this.execute(d,k,n,i+1,t.targetTable);let R=t.type==="one-to-one";for(let _ of e){let N=this.adapter.keyOf(_[s]),v=m.get(N)||[];_[t.relationName]=R?v[0]||null:v}}async fetchM2MRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=e.map(w=>w[s]).filter(w=>w!=null);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:l,fetchSpec:f}=this.adapter.resolveFields(t.fields,u),c=performance.now(),{grouped:p,docs:d}=await this.adapter.fetchM2M(e,t,o,u,f),g=t.userLimit!==void 0&&t.userLimit>0,m=g?"m2m-per-parent-c16":"m2m-batch",y=g?a.length:Math.ceil(a.length/Se)||1,h=g?Math.ceil(a.length/ee):void 0,b=Array.from(p.values()).reduce((w,$)=>w+$.length,0);this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,c,{relationType:t.type,targetTable:t.targetTable,strategy:m,roundtrips:y,concurrencyWaves:h,rowsTransferred:d.length,rowsReturned:b,rowsDiscarded:d.length-b,userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort});let S=this.enrichNestedDescs(l,t.nestedDeep);S.length>0&&d.length>0&&await this.execute(d,S,n,i+1,t.targetTable);for(let w of e){let $=this.adapter.keyOf(w[s]);w[t.relationName]=p.get($)||[]}}}});async function de(r,e,t){let n=new Map,i=0;async function o(){for(;i<r.length;){let u=i++,l=r[u];n.set(String(l),await e(l))}}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 sn=W(()=>{"use strict"});function F(r,e){switch(e){case"mysql":return`\`${r}\``;case"postgres":case"pg":case"sqlite":return`"${r}"`;case"mongodb":return r;default:return`\`${r}\``}}var xe=W(()=>{"use strict"});function X(r,e,t){e&&pn(r,e,t,"and")}function pn(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(){pn(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(){pn(this,o,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"not":{let i=function(){this.whereNot(function(){pn(this,e.child,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"compare":co(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 co(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=uo(e.field,t),o=!!e.field.isUuid,s=t.dbType==="postgres",a=n==="or"?"orWhere":"where",u=n==="or"?"orWhereRaw":"whereRaw",l=n==="or"?"orWhereIn":"whereIn",f=n==="or"?"orWhereNotIn":"whereNotIn",c=n==="or"?"orWhereBetween":"whereBetween",p=n==="or"?"orWhereNull":"whereNull",d=n==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":o&&s&&typeof e.value=="string"?r[u](`${i} = ?::uuid`,[e.value]):r[a](i,"=",e.value);return;case"neq":o&&s&&typeof e.value=="string"?r[u](`${i} != ?::uuid`,[e.value]):r[a](i,"!=",e.value);return;case"gt":o&&s&&typeof e.value=="string"?r[u](`${i} > ?::uuid`,[e.value]):r[a](i,">",e.value);return;case"gte":o&&s&&typeof e.value=="string"?r[u](`${i} >= ?::uuid`,[e.value]):r[a](i,">=",e.value);return;case"lt":o&&s&&typeof e.value=="string"?r[u](`${i} < ?::uuid`,[e.value]):r[a](i,"<",e.value);return;case"lte":o&&s&&typeof e.value=="string"?r[u](`${i} <= ?::uuid`,[e.value]):r[a](i,"<=",e.value);return;case"in":{let g=Jr(e.value);o&&s&&g.every(m=>typeof m=="string")?r[u](`${i} = ANY(?::uuid[])`,[g]):r[l](i,g);return}case"not_in":{let g=Jr(e.value);o&&s&&g.every(m=>typeof m=="string")?r[u](`${i} != ALL(?::uuid[])`,[g]):r[f](i,g);return}case"contains":Hn(r,i,e.value,"contains",t,n);return;case"starts_with":Hn(r,i,e.value,"starts_with",t,n);return;case"ends_with":Hn(r,i,e.value,"ends_with",t,n);return;case"between":Array.isArray(e.value)&&e.value.length===2&&r[c](i,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?r[p](i):r[d](i);return}}function Hn(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 uo(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function Jr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var Gn=W(()=>{"use strict"});function te(r){return r.columns.find(e=>e.isPrimary)||null}var Lt=W(()=>{"use strict"});var zr={};bn(zr,{expandFieldsToJoinsAndSelect:()=>Yn});async function Yn(r,e,t,n,i,o){let s=[],a=[],u=await t(r);if(!u)return{select:[],batchFetchDescriptors:[]};let l=new Map;for(let c of e)if(c==="*"||!c.includes("."))l.has("")||l.set("",[]),l.get("").push(c);else{let p=c.split("."),d=p[0],g=p.slice(1).join(".");l.has(d)||l.set(d,[]),l.get(d).push(g)}let f=l.get("")||[];for(let c of f){if(c==="*"){let g=new Set;for(let y of u.relations||[])if(y.type==="many-to-one"||y.type==="one-to-one"&&!y.isInverse){let h=y.foreignKeyColumn||K(y.propertyName);h&&g.add(h)}let m=new Set;for(let y of u.columns)g.has(y.name)||(s.push(`${r}.${y.name}`),m.add(y.name));for(let y of u.relations||[])!l.has(y.propertyName)&&!m.has(y.propertyName)&&l.set(y.propertyName,["id"]);continue}if(c.includes(".")){s.push(`${r}.${c}`);continue}if(u.columns?.find(g=>g.name===c)){s.push(`${r}.${c}`);continue}if(u.relations?.find(g=>g.propertyName===c)){l.has(c)||l.set(c,["id"]);continue}}return l.forEach((c,p)=>{if(p==="")return;let d=u.relations?.find(b=>b.propertyName===p);if(!d)return;if(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse){let b=d.foreignKeyColumn||K(d.propertyName),S=F(r,n),w=F(b,n),$=F(p,n);s.push(`${S}.${w} as ${$}`)}let m=d.targetTableName||d.targetTable,y=o?.[p],h=y?.fields!=null?Array.isArray(y.fields)?y.fields:String(y.fields).split(",").map(b=>b.trim()).filter(Boolean):c;a.push({relationName:p,type:d.type,targetTable:m,fields:h,isInverse:d.isInverse,fkColumn:d.foreignKeyColumn,mappedBy:d.mappedBy,junctionTableName:d.junctionTableName,junctionSourceColumn:d.junctionSourceColumn,junctionTargetColumn:d.junctionTargetColumn,userFilter:y?.filter,userSort:y?.sort,userLimit:y?.limit!==void 0?Number(y.limit):void 0,userPage:y?.page!==void 0?Number(y.page):void 0,nestedDeep:y?.deep})}),{select:s,batchFetchDescriptors:a}}var Xn=W(()=>{"use strict";ze();xe()});var ct,er=W(()=>{"use strict";ze();xe();Lt();et();Gn();Mt();Nt();sn();ct=class{constructor(e,t="postgres",n){this.knex=e;this.dbType=t;this.metadata=n;this.pkField="id"}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}=Te(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 l=u[u.length-1];return{column:`${`__sort_${u.slice(0,-1).join("_")}`}.${l}`,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 l=(a.startsWith("-")?a.slice(1):a).split(".");if(l.length<=1)continue;let f=n,c=i||n;for(let p=0;p<l.length-1;p++){let d=l[p],g=this.metadata?.tables?.get(f);if(!g)break;let m=g.relations?.find(b=>b.propertyName===d);if(!m)break;let y=m.targetTableName||m.targetTable,h=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(h)){s.add(h);let b=m.foreignKeyColumn||K(m.propertyName),S=this.metadata?.tables?.get(y),w=S&&te(S)?.name||"id";e.leftJoin(`${y} as ${h}`,`${h}.${w}`,`${c}.${b}`)}f=y,c=h}}}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 te(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;return!t&&e.mappedBy&&(t=K(e.mappedBy)),t||(t=K(e.targetTable)),t}resolveParentPk(e){return e&&te(e)?.name||"id"}resolveFields(e,t){let{rootFields:n,subRelations:i}=Ze(e),o=[];if(n.includes("*")){let l=new Set;for(let f of t.relations||[])if(f.type==="many-to-one"||f.type==="one-to-one"&&!f.isInverse){let c=f.foreignKeyColumn||K(f.propertyName);c&&l.add(c)}for(let f of t.columns)l.has(f.name)||o.push(f.name);for(let f of t.relations||[])i.has(f.propertyName)||i.set(f.propertyName,["id"])}else for(let l of n){let f=t.columns.find(c=>c.name===l);f?o.push(f.name):t.relations?.find(p=>p.propertyName===l)&&!i.has(l)&&i.set(l,["id"])}let s=te(t)?.name||"id";o.includes(s)||o.push(s),i.forEach((l,f)=>{let c=t.relations?.find(p=>p.propertyName===f);if(c&&(c.type==="many-to-one"||c.type==="one-to-one"&&!c.isInverse)){let p=c.foreignKeyColumn||K(c.propertyName);p&&o.push(`${p} as ${f}`)}});let a=[];return i.forEach((l,f)=>{let c=t.relations?.find(d=>d.propertyName===f);if(!c)return;let p=c.targetTableName||c.targetTable;p&&a.push({relationName:f,type:c.type,targetTable:p,fields:l,isInverse:c.isInverse,fkColumn:c.foreignKeyColumn,mappedBy:c.mappedBy,junctionTableName:c.junctionTableName,junctionSourceColumn:c.junctionSourceColumn,junctionTargetColumn:c.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(u=>this.toKnexSelect(u));return Y(t,u=>{let l=this.knex(e).select(a).whereIn(n.pkCol,u);if(o&&X(l,o,{dbType:this.dbType,rootTable:e}),s.length>0){this.applySortJoins(l,i.userSort,e);for(let f of s)l.orderBy(f.column,f.order)}return l})}async fetchInverse(e,t,n,i,o){let s=t,a=i.selectCols.find(g=>g.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,l=o?.userSort?this.parseSortTokens(o.userSort,e):[],f=o?.userLimit,c=o?.userPage;if(f!==void 0&&f>0){let g=c?(c-1)*f:0,m=i.selectCols.map(b=>this.toKnexSelect(b)),y=await de(n,async b=>{let S=this.knex(e).select(m).where(t,b);if(u&&X(S,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(S,o.userSort,e),l.length>0)for(let w of l)S.orderBy(w.column,w.order);else S.orderBy(i.pkCol,"asc");return g>0&&S.offset(g),S.limit(f),S},ee),h=[];for(let[b,S]of y.entries()){let w=n.find($=>String($)===b);for(let $ of S)$[t]||($[t]=w??b),h.push($)}return{docs:h,groupKeyField:s}}let p=i.selectCols.map(g=>this.toKnexSelect(g));return{docs:await Y(n,g=>{let m=this.knex(e).select(p).whereIn(t,g);if(u&&X(m,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(m,o?.userSort,e),l.length>0)for(let y of l)m.orderBy(y.column,y.order);else m.orderBy(i.pkCol,"asc");return m}),groupKeyField:s}}postProcessInverseChild(e,t,n){n||delete e[t]}async fetchM2M(e,t,n,i,o){let s=this.resolveParentPk(n),a=e.map(S=>S[s]).filter(S=>S!=null);if(a.length===0)return{grouped:new Map,docs:[]};let u=t.junctionTableName,l=t.junctionSourceColumn,f=t.junctionTargetColumn;if(!u||!l||!f)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let c=t.userFilter?this.buildFilterTree(t.userFilter,t.targetTable):null,p=t.userSort?this.parseSortTokens(t.userSort,t.targetTable,"t"):[],d=t.userLimit,g=t.userPage;if(o.selectCols.length===1&&o.selectCols[0]===o.pkCol&&!c&&!d){let S=await Y(a,$=>this.knex(u).select([`${l} as __sourceId__`,`${f} as __targetId__`]).whereIn(l,$).orderBy(f,"asc")),w=new Map;for(let $ of S){let k=this.keyOf($.__sourceId__);w.has(k)||w.set(k,[]),w.get(k).push({[o.pkCol]:$.__targetId__})}return{grouped:w,docs:[]}}let y=o.selectCols.map(S=>this.toKnexSelect(S,"t"));if(d!==void 0&&d>0){let S=g?(g-1)*d:0,w=new Map;for(let R of a)w.set(this.keyOf(R),[]);let $=await de(a,async R=>{let _=this.knex(u).join(`${t.targetTable} as t`,`${u}.${f}`,`t.${o.pkCol}`).select(y).where(`${u}.${l}`,R);if(c&&X(_,c,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(_,t.userSort,t.targetTable,"t"),p.length>0)for(let N of p)_.orderBy(N.column,N.order);else _.orderBy(`t.${o.pkCol}`,"asc");return S>0&&_.offset(S),_.limit(d),_},ee),k=[];for(let[R,_]of $.entries()){w.set(R,_);for(let N of _)k.push(N)}return{grouped:w,docs:k}}let h=await Y(a,S=>{let w=this.knex(u).join(`${t.targetTable} as t`,`${u}.${f}`,`t.${o.pkCol}`).select([`${u}.${l} as __sourceId__`,...y]).whereIn(`${u}.${l}`,S);if(c&&X(w,c,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(w,t.userSort,t.targetTable,"t"),p.length>0)for(let $ of p)w.orderBy($.column,$.order);else w.orderBy(`t.${o.pkCol}`,"asc");return w}),b=new Map;for(let S of h){let w=S.__sourceId__;delete S.__sourceId__;let $=this.keyOf(w);b.has($)||b.set($,[]),b.get($).push(S)}return{grouped:b,docs:h}}}});var Gr={};bn(Gr,{executeBatchFetches:()=>tr});async function tr(r,e,t,n,i=3,o=0,s,a="postgres",u,l){let f=new ct(r,a,u);await new ke(f,n,l).execute(e,t,i,o,s)}var nr=W(()=>{"use strict";et();er()});var yo={};bn(yo,{ALL_SUPPORTED_OPERATORS:()=>Rt,AuthenticationException:()=>Ie,AuthorizationException:()=>Ee,BadRequestException:()=>M,BatchFetchEngine:()=>ke,BusinessLogicException:()=>Ne,CHUNKED_FETCH_CONCURRENCY:()=>Dn,ConfigurationException:()=>bt,DEEP_TO_MANY_DEFAULT_LIMIT:()=>Bn,DEFAULT_TIMEOUT_MS:()=>Kt,DOTTED_PATH_MAX_HOPS:()=>mn,DatabaseException:()=>he,DuplicateResourceException:()=>Oe,ErrorHandler:()=>je,ExecutorEngineService:()=>Qe,ExternalServiceException:()=>mt,FIELD_OPERATORS:()=>Z,FileNotFoundException:()=>wt,FileSizeExceededException:()=>$t,FileUploadException:()=>_t,HttpException:()=>ve,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>Ut,InvalidTokenException:()=>yt,IsolatedExecutorService:()=>Ve,JoinRegistry:()=>ie,LOGICAL_OPERATORS:()=>Mn,MongoBatchAdapter:()=>tt,MongoQueryExecutor:()=>ot,PER_PARENT_CONCURRENCY:()=>ee,QueryBuilderService:()=>ft,QueryPlanner:()=>J,ResourceNotFoundException:()=>Ae,SchemaException:()=>ht,ScriptExecutionException:()=>me,ScriptTimeoutException:()=>ye,ServiceUnavailableException:()=>Pe,SqlBatchAdapter:()=>ct,SqlQueryExecutor:()=>ut,TokenExpiredException:()=>gt,ValidationException:()=>Me,WHERE_IN_CHUNK_SIZE:()=>Se,WorkerPool:()=>Ct,appendIsolatedExecutorRuntimeLog:()=>z,applyOperatorToMatch:()=>Xt,applyRelationFilters:()=>Ue,applyWhereToKnex:()=>lt,assertFieldOperatorValueIsClean:()=>en,buildAggregateFilter:()=>it,buildMongoCharFoldMapJson:()=>vn,buildMongoFoldTextSearchJs:()=>qt,buildRelationSubquery:()=>Et,buildSqlWherePartsFromFieldAst:()=>jt,buildWhereClause:()=>se,camelToSnake:()=>$r,chunkedFetch:()=>Y,compileScriptSource:()=>ce,computeEngineTuning:()=>Tn,createEnfyraKernel:()=>go,dslOpToCompareOp:()=>Zt,encodeMainThreadToIsolate:()=>Cn,escapeSqlValue:()=>Vr,executeBatchFetches:()=>tr,executeMongoBatchFetches:()=>an,expandFieldsToJoinsAndSelect:()=>Yn,getEffectiveCpuCount:()=>$n,getEffectiveMemoryBytes:()=>Tt,getEngineTuning:()=>Vt,getExecutableScript:()=>hi,getForeignKeyColumnName:()=>K,getIoAbortSignal:()=>mr,getJunctionColumnNames:()=>xt,getJunctionTableName:()=>Ft,getPrimaryKeyColumn:()=>te,getScriptLegacyField:()=>Sn,getShortFkConstraintName:()=>_r,getShortFkName:()=>Tr,getShortIndexName:()=>Sr,getShortPkName:()=>br,hasAggregateQuery:()=>Un,hasLogicalOperators:()=>pe,isExecutableJavaScript:()=>cr,isScriptTable:()=>kn,mergeAggregateValue:()=>Fe,normalizeAggregateQuery:()=>rt,normalizeFlowStepScriptConfig:()=>bi,normalizeScriptLanguage:()=>kt,normalizeScriptPatch:()=>mi,normalizeScriptRecord:()=>yi,parseBatchFields:()=>Ze,parseFields:()=>ln,parseFilter:()=>Te,perParentRun:()=>de,quoteIdentifier:()=>F,resolveExecutableScript:()=>ur,rewriteFilterDenyingFields:()=>Xr,rewriteSortDroppingDenied:()=>Zr,separateFilters:()=>G,snakeToCamel:()=>wr,throwUnsupportedFieldOperator:()=>Be,transformCode:()=>wn,validateDeepOptions:()=>rr,validateFilterShape:()=>Q,whereToMongoFilter:()=>Ge});module.exports=oi(yo);var si={"@CACHE":"$ctx.$cache","@REPOS":"$ctx.$repos","@HELPERS":"$ctx.$helpers","@FETCH":"$ctx.$helpers.$fetch","@LOGS":"$ctx.$logs","@BODY":"$ctx.$body","@DATA":"$ctx.$data","@PARAMS":"$ctx.$params","@QUERY":"$ctx.$query","@USER":"$ctx.$user","@REQ":"$ctx.$req","@RES":"$ctx.$res","@SHARE":"$ctx.$share","@API":"$ctx.$api","@UPLOADED_FILE":"$ctx.$uploadedFile","@PKGS":"$ctx.$pkgs","@SOCKET":"$ctx.$socket","@TRIGGER":"$ctx.$trigger","@FLOW":"$ctx.$flow","@FLOW_PAYLOAD":"$ctx.$flow.$payload","@FLOW_LAST":"$ctx.$flow.$last","@FLOW_META":"$ctx.$flow.$meta","@THROW400":"$ctx.$throw['400']","@THROW401":"$ctx.$throw['401']","@THROW403":"$ctx.$throw['403']","@THROW404":"$ctx.$throw['404']","@THROW409":"$ctx.$throw['409']","@THROW422":"$ctx.$throw['422']","@THROW429":"$ctx.$throw['429']","@THROW500":"$ctx.$throw['500']","@THROW503":"$ctx.$throw['503']","@THROW":"$ctx.$throw","@ERROR":"$ctx.$error","@STATUS":"$ctx.$statusCode"},ge=0,or=1,sr=2,_n=3,ar=4,lr=5;function wn(r){let e=r.length,t="",n=0,i=ge,o=0,s=0;for(;n<e;){let a=r[n],u=r[n+1];switch(i){case ge:if(a==='"')i=or,t+=a,n++;else if(a==="'")i=sr,t+=a,n++;else if(a==="`")i=_n,t+=a,n++;else if(a==="/"&&u==="/")i=ar,t+=a+u,n+=2;else if(a==="/"&&u==="*")i=lr,t+=a+u,n+=2;else if(a==="@"||a==="#"||a==="%"){let l=n,f=a;for(n++;n<e;){let p=r[n];if(p>="A"&&p<="Z"||p>="0"&&p<="9"||p==="_")n++;else break}let c=r.substring(l,n);if(f==="@"){let p=si[c];t+=p||c}else f==="#"?t+="$ctx.$repos."+c.substring(1):t+="$ctx.$pkgs."+c.substring(1)}else a==="{"?(o>0&&s++,t+=a,n++):a==="}"&&o>0?s>0?(s--,t+=a,n++):(o--,t+=a,n++,i=_n):(t+=a,n++);break;case or:t+=a,a==="\\"?(n++,n<e&&(t+=r[n],n++)):(a==='"'&&(i=ge),n++);break;case sr:t+=a,a==="\\"?(n++,n<e&&(t+=r[n],n++)):(a==="'"&&(i=ge),n++);break;case _n:t+=a,a==="\\"?(n++,n<e&&(t+=r[n],n++)):a==="`"?(i=ge,n++):a==="$"&&n+1<e&&r[n+1]==="{"?(t+="{",n+=2,o++,i=ge):n++;break;case ar:t+=a,a===`
2
+ `&&(i=ge),n++;break;case lr:t+=a,a==="*"&&u==="/"?(t+=u,n+=2,i=ge):n++;break}}return t}var Kt=3e4,Qe=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){let n=e.routeData.__codeBlocks||[];return n.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(n,e.routeData.context,t??Kt)}async run(e,t,n=Kt){return this.isolatedExecutorService.run(e,t,n)}};var Wt=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 dr=require("async_hooks"),pr=le(require("path")),gr=require("worker_threads");var ye=class extends Error{constructor(t=0,n){let i=typeof t=="number"&&t>0?`${t}ms`:String(t||"configured timeout");super(`Script execution timed out after ${i}`);this.statusCode=408;this.errorCode="SCRIPT_TIMEOUT";this.name="ScriptTimeoutException",this.details={timeoutMs:t,scriptId:n}}},me=class extends Error{constructor(t,n,i){super(`Script execution failed: ${t}`);this.statusCode=400;this.errorCode="SCRIPT_EXECUTION_ERROR";this.name="ScriptExecutionException",this.details={scriptId:n,...i}}},j=class extends Error{constructor(t,n,i,o){super(t);this.statusCode=n;this.errorCode=i;this.name=this.constructor.name,this.details=o}},ve=class extends j{constructor(e,t,n){super(e,t,`HTTP_${t}`,n)}},Ne=class extends j{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},Me=class extends j{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},Ae=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})}},Oe=class extends j{constructor(e,t,n){super(`${e} with ${t} '${n}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:n})}},Ie=class extends j{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},Ee=class extends j{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},gt=class extends j{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},yt=class extends j{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},he=class extends j{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},mt=class extends j{constructor(e,t,n){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:n})}},Pe=class extends j{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},ht=class extends j{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},bt=class extends j{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},_t=class extends j{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},wt=class extends j{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},$t=class extends j{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var je=class{static createException(e,t,n,i,o){if(e?.includes("$throw"))switch(e){case"$throw.businessLogic":return new Ne(n||"Bad request",o);case"$throw.validation":return new Me(n||"Validation failed",o);case"$throw.notFound":return new Ae(n||"Resource");case"$throw.duplicate":return new Oe(n||"Resource","field","value");case"$throw.unauthorized":return new Ie(n||"Unauthorized");case"$throw.forbidden":return new Ee(n||"Forbidden");case"$throw.tokenExpired":return new gt;case"$throw.invalidToken":return new yt;case"$throw.database":return new he(n||"Database error",o);case"$throw.dbQuery":return new he(n||"Query error",o);case"$throw.externalService":return new mt(n||"Service",n||"Error",o);case"$throw.serviceUnavailable":return new Pe(n||"Service");case"$throw.rateLimit":return new ve(n||"Rate limit exceeded",429);case"$throw.scriptError":return new me(n||"Script error",i,o);case"$throw.scriptTimeout":return new ye(o?.timeout||5e3,i);case"$throw.schema":return new ht(n||"Schema error",o);case"$throw.config":return new bt(n||"Configuration error",o);case"$throw.fileUpload":return new _t(n||"File upload error",o);case"$throw.fileNotFound":return new wt(n||"File not found");case"$throw.fileSizeExceeded":return new $t(o?.maxSize||"unknown",o?.actualSize||"unknown");case"$throw.400":return new Ne(n||"Bad request",o);case"$throw.401":return new Ie(n||"Authentication required");case"$throw.403":return new Ee(n||"Insufficient permissions");case"$throw.404":return new Ae(n||"Resource");case"$throw.409":return new Oe(n||"Resource","field","value");case"$throw.422":return new Me(n||"Validation failed",o);case"$throw.429":return new ve(n||"Rate limit exceeded",429);case"$throw.500":return new he(n||"Internal server error",o);case"$throw.503":return new Pe(n||"Service");default:return new me(n||"Unknown error",i)}if(t)switch(t){case 400:return new Ne(n||"Bad request",o);case 401:return new Ie(n||"Authentication required");case 403:return new Ee(n||"Insufficient permissions");case 404:return new Ae(n||"Resource");case 409:return new Oe(n||"Resource","field","value");case 422:return new Me(n||"Validation failed",o);case 429:return new ve(n||"Rate limit exceeded",429);case 500:return new he(n||"Internal server error",o);case 503:return new Pe(n||"Service");default:return new me(n||"Unknown error",i,o)}return new me(n||"Unknown error",i,o)}};var Qt=le(require("fs")),Jt=le(require("path")),Ut=Jt.join(process.cwd(),"test","logs","isolated-executor-runtime.log");function ai(){return process.env.ISOLATED_EXECUTOR_FILE_LOG==="0"?!1:process.env.ISOLATED_EXECUTOR_FILE_LOG==="1"?!0:process.env.JEST_WORKER_ID!==void 0}var li=ai();function z(r){if(li)try{let e=Jt.dirname(Ut);Qt.mkdirSync(e,{recursive:!0});let t=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...r})+`
3
+ `;Qt.appendFileSync(Ut,t)}catch{}}var be=le(require("os")),Je=le(require("fs"));function Tt(){try{let r=Je.readFileSync("/sys/fs/cgroup/memory.max","utf8").trim();if(r!=="max"){let e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<be.totalmem())return e}}catch{}try{let r=Je.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes","utf8").trim(),e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<be.totalmem())return e}catch{}return be.totalmem()}function $n(){let r=be.availableParallelism?.()||be.cpus()?.length||1;try{let e=Je.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(Je.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8").trim(),10),t=parseInt(Je.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 ci=.25,ui=2,fi=2048,di=40,pi=128,gi=32;function Tn(r){let e=Math.max(1,Math.trunc(r.logicalCpuCount)||1),t=Math.max(1,r.totalMemoryBytes/(1024*1024)),n=Math.min(pi,Math.max(di,Math.round(t/gi))),i=t*ci,o=Math.max(1,Math.floor(i/n)),s=Math.max(1,Math.min(e,2,o)),a=Math.min(256,Math.max(16,Math.floor(t/n/s))),u=t<fi?1:ui,l=Math.max(1,Math.min(u,Math.floor(i/(s*n))));return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:a,isolatePoolSize:l}}function Vt(){return Tn({logicalCpuCount:$n(),totalMemoryBytes:Tt()})}var Le=le(require("typescript"));var St={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 Sn(r){return St[r]}function kn(r){return r in St}function kt(r){return r==="javascript"?"javascript":"typescript"}function ce(r,e){if(r==null||r==="")return null;let t=wn(String(r));if(kt(e)==="javascript")return t;let n=Le.default.transpileModule(t,{compilerOptions:{target:Le.default.ScriptTarget.ES2022,module:Le.default.ModuleKind.CommonJS,importsNotUsedAsValues:Le.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),i=n.diagnostics?.find(o=>o.category===Le.default.DiagnosticCategory.Error);if(i)throw new Error(Le.default.flattenDiagnosticMessageText(i.messageText,`
4
4
  `));return n.outputText.trimEnd()}function cr(r){if(!r)return!1;try{return new Function(`return (async () => {
5
5
  "use strict";
6
6
  ${r}
7
- });`),!0}catch{return!1}}function yi(r,e){if(!kn(r)||!e||typeof e!="object")return e;let t={...e},n=Sn(r);return n&&(t.sourceCode===void 0||t.sourceCode===null||t.sourceCode==="")&&t[n]!==void 0&&(t.sourceCode=t[n]),t.scriptLanguage=Ct(t.scriptLanguage),(t.compiledCode===void 0||t.compiledCode===null||t.compiledCode==="")&&(t.compiledCode=ce(t.sourceCode,t.scriptLanguage)),n&&n in t&&delete t[n],t}function mi(r,e,t){if(!kn(r)||!e||typeof e!="object")return e;let n=Sn(r),o=Object.prototype.hasOwnProperty.call(e,"sourceCode")||(n?Object.prototype.hasOwnProperty.call(e,n):!1),i=Object.prototype.hasOwnProperty.call(e,"scriptLanguage");if(!o&&!i)return e;let s=o?e.sourceCode??(n?e[n]:void 0):t?.sourceCode??(n&&t?t[n]:void 0),a=i?e.scriptLanguage:t?.scriptLanguage,u=ce(s,a),l={...e};return o&&(l.sourceCode=s??null),l.scriptLanguage=Ct(a),l.compiledCode=u,n&&n in l&&delete l[n],l}function hi(r){return ur(r).code}function ur(r){if(!r||typeof r!="object")return{code:null,compiledCode:null,shouldPersistCompiledCode:!1};if(typeof r.compiledCode=="string"&&r.compiledCode!==""&&cr(r.compiledCode))return{code:r.compiledCode,compiledCode:r.compiledCode,shouldPersistCompiledCode:!1};if(typeof r.sourceCode=="string"&&r.sourceCode!==""){let t=ce(r.sourceCode,r.scriptLanguage);return{code:t,compiledCode:t,shouldPersistCompiledCode:t!==r.compiledCode}}let e=Object.keys(xt).find(t=>xt[t]in r);if(e){let t=r[xt[e]];if(typeof t=="string"&&t!==""){let n=ce(t,r.scriptLanguage);return{code:n,compiledCode:n,shouldPersistCompiledCode:n!==r.compiledCode}}}return typeof r.compiledCode=="string"&&r.compiledCode!==""?{code:r.compiledCode,compiledCode:r.compiledCode,shouldPersistCompiledCode:!1}:{code:null,compiledCode:null,shouldPersistCompiledCode:!1}}function bi(r){if(!r||typeof r!="object")return r;let e=r.type;if(e!=="script"&&e!=="condition")return r;let t=r.config;if(typeof t=="string")try{t=JSON.parse(t)}catch{return r}if(!t||typeof t!="object")return r;let n={...t};return n.sourceCode=n.sourceCode??n.code??null,n.scriptLanguage=Ct(n.scriptLanguage),n.compiledCode=ce(n.sourceCode,n.scriptLanguage),delete n.code,{...r,config:typeof r.config=="string"?JSON.stringify(n):n}}var Ri=pr.join(__dirname,"execution/worker.js"),vi=["Invalid or unexpected token","Unexpected identifier","Unexpected token","Missing initializer in const declaration","await is only valid"],yr=new dr.AsyncLocalStorage;function mr(){return yr.getStore()}var Ft=class{constructor(e,t,n,o,i,s,a,u=6e4){this.scriptPath=i;this.onCrash=s;this.onRotate=a;this.entries=[];this.waiting=[];this.cachedMemoryOk=!0;this.lastMemoryCheckMs=0;this.memorySampleIntervalMs=200;this.destroying=!1;this.entryCounter=0;this.max=e,this.effectiveMemory=t,this.rssCeiling=n,this.tasksCap=o,this.drainTimeoutMs=u;for(let l=0;l<e;l++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new gr.Worker(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let o=t.tasks.get(n.id);o&&(n.type==="result"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),n.contextStats&&(t.contextStats=n.contextStats),o.onResult(n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):o.onIoCall(n))}),e.on("exit",()=>{let n=t.draining,o=this.destroying;t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,s]of t.tasks)s.abortController.abort(),s.onResult({type:"result",success:!1,error:{message:o?"Worker terminated":"Worker crashed"}});t.tasks.clear();let i=this.entries.indexOf(t);i!==-1&&this.entries.splice(i,1),!n&&!o&&(this.onCrash&&this.onCrash(),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),this.entries.push(t),t}rotateEntry(e,t){if(e.draining)return;e.draining=!0;let n=Date.now()-e.spawnedAt;if(this.onRotate&&this.onRotate({reason:t,ageMs:n}),this.spawnEntry(),e.tasks.size===0){e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,e.worker.terminate()},this.drainTimeoutMs)}isMemoryAvailable(){let e=Date.now();return e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs&&(this.cachedMemoryOk=process.memoryUsage().rss/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e),this.cachedMemoryOk}findLeastBusy(){let e=null;for(let t of this.entries)t.draining||t.tasks.size<this.tasksCap&&(!e||t.tasks.size<e.tasks.size)&&(e=t);return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size===0||this.isMemoryAvailable())?Promise.resolve(e):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.tasks.set(t,n)}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&(e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(e&&(e.tasks.size===0||this.isMemoryAvailable()))this.waiting.shift()(e);else break}}terminateEntry(e){e.worker.terminate()}resize(e){for(this.max=Math.max(1,e);this.entries.length<this.max;)this.spawnEntry()}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,activeTasks:e.tasks.size,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}};function xn(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 He=class r{constructor(e){this.logger=new Wt(r.name);this.effectiveMemory=kt();this.isolationTuning=Vt();this.pool=new Ft(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Ri,()=>{this.crashesTotal++,this.logger.warn("Worker crashed, replacement spawned")},({reason:e,ageMs:t})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${e} age=${Math.round(t/1e3)}s`)});this.ceiling=this.isolationTuning.maxConcurrentWorkers;this.prevCpuUsage=process.cpuUsage();this.prevCpuTime=process.hrtime.bigint();this.pressureTicks=0;this.recoveryTicks=0;this.taskCounter=0;this.taskDoneTotal=0;this.taskErrorTotal=0;this.taskTimeoutTotal=0;this.rotationsTotal=0;this.crashesTotal=0;this.taskDurationsMs=[];this.packageCacheService=e.packageCacheService,this.packageCdnLoaderService=e.packageCdnLoaderService,this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let t=process.memoryUsage().rss/this.effectiveMemory,n=process.hrtime.bigint(),o=process.cpuUsage(this.prevCpuUsage),i=Number(n-this.prevCpuTime)/1e3,s=i>0?(o.user+o.system)/i:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let a=this.pool.getMax(),u=this.pool.getWaitingCount(),l=t>.85||s>.7,f=t<.7&&s<.5,c=u>0,p=a;l?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(p=Math.max(1,a-1))):f&&c?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(p=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),p!==a&&(this.pool.resize(p),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${p} (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},n=e.$flow;if(n!=null)try{t.$flow=JSON.parse(JSON.stringify(n,(o,i)=>typeof i=="bigint"?String(i):i))}catch{t.$flow={}}return t}mergeCtxChanges(e,t){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),delete e.$pkgs)}spawnAndExecute(e,t,n,o){return(async()=>{let i=await this.pool.dispatch(),s=`t_${++this.taskCounter}`,a=Date.now();return new Promise((u,l)=>{let f=!1,c=new AbortController,p=setTimeout(()=>{if(f)return;f=!0,c.abort(),this.pool.unregisterTask(i,s),this.taskTimeoutTotal++,z({event:"task_timeout",id:s,timeoutMs:o}),this.pool.terminateEntry(i);let d=new Error(`Script execution timed out after ${o}ms`);d.code="ERR_SCRIPT_EXECUTION_TIMEOUT",d.isTimeout=!0,l(d)},o+5e3);this.pool.registerTask(i,s,{abortController:c,onResult:d=>{if(!f)if(f=!0,clearTimeout(p),this.pool.unregisterTask(i,s),this.recordTaskDuration(Date.now()-a),d.success){this.taskDoneTotal++,z({event:"task_done",id:s,ok:!0});let g={value:d.value,valueAbsent:d.valueAbsent===!0,ctxChanges:d.ctxChanges};d.shortCircuit&&(g.shortCircuit=!0),u(g)}else{this.taskErrorTotal++,z({event:"task_done",id:s,ok:!1,message:d.error?.message});let g=new Error(d.error?.message||"Handler execution failed");g.statusCode=d.error?.statusCode,g.code=d.error?.code,g.details=d.error?.details,d.error?.stack&&(g.stack=d.error.stack),d.ctxChanges&&(g.ctxChanges=d.ctxChanges),l(g)}},onIoCall:d=>{if(f)return;let g=c.signal;d.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(d,n),i.worker,d.callId,g):d.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(d,n),i.worker,d.callId,g):d.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(d,n),i.worker,d.callId,g):d.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(d,n),i.worker,d.callId,g):d.type==="dispatchCall"&&this.handleIoCall(()=>this.execDispatchCall(d,n),i.worker,d.callId,g)}}),i.worker.postMessage({type:e,id:s,...t})})})()}async handleIoCall(e,t,n,o){if(!o?.aborted)try{let i=await(o?yr.run(o,e):e());if(o?.aborted)return;try{t.postMessage({type:"callResult",callId:n,result:xn(i)})}catch{}}catch(i){if(o?.aborted)return;try{let s={__userThrow:!0,message:i.message,statusCode:i.statusCode,code:i.errorCode??i.code,details:i.details,messages:i.messages};t.postMessage({type:"callError",callId:n,error:JSON.stringify(s)})}catch{}}}async execRepoCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$repos?.[e.table];if(!o||typeof o[e.method]!="function")throw new Error(`Repo method not found: ${e.table}.${e.method}`);return o[e.method](...n)}async execHelpersCall(e,t){let n=JSON.parse(e.argsJson),o=e.name.split("."),i=t?.$helpers;for(let s of o)i=i?.[s];if(typeof i!="function")throw new Error(`Helper not found: ${e.name}`);return i(...n)}async execSocketCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$socket?.[e.method];if(typeof o!="function")throw new Error(`Socket method not found: ${e.method}`);return o(...n)}async execCacheCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$cache?.[e.method];if(typeof o!="function")throw new Error(`Cache method not found: ${e.method}`);return o(...n)}async execDispatchCall(e,t){let n=JSON.parse(e.argsJson),o=t?.$trigger;if(typeof o!="function")throw new Error("$trigger is not available");return o(...n)}isScriptParseFailure(e){let t=e.message||"";return vi.some(n=>t.includes(n))}async run(e,t,n){let o=Math.max(1,Math.trunc(Number(n)||3e4)),i=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(i),a=this.createSnapshot(t);z({event:"isolated_run_start",timeoutMs:o,codeLen:e?.length??0});let u;try{let l={code:e,pkgSources:s,snapshot:a,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{u=await this.spawnAndExecute("execute",l,t,o)}catch(f){let c=f,p=ce(e,"typescript")||"";if(!this.isScriptParseFailure(c)||p===e)throw f;z({event:"isolated_run_ts_retry",message:c.message}),u=await this.spawnAndExecute("execute",{...l,code:p},t,o)}}catch(l){let f=l;if(z({event:"isolated_run_error",message:f.message,code:f.code,isTimeout:!!f.isTimeout}),f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new he(o,e);let c=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw De.createException(void 0,c,f.message||"Unknown error",e,f.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),z({event:"isolated_run_ok"}),u.valueAbsent?void 0:u.value}async runBatch(e,t,n){let o=Math.max(1,Math.trunc(Number(n)||3e4)),i=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(i),a=this.createSnapshot(t);z({event:"isolated_batch_start",timeoutMs:o,blocks:e.length});let u;try{let l={codeBlocks:e,pkgSources:s,snapshot:a,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{u=await this.spawnAndExecute("executeBatch",l,t,o)}catch(f){let c=f,p=e.map(g=>({...g,code:ce(g.code,"typescript")||""})),d=p.some((g,m)=>g.code!==e[m]?.code);if(!this.isScriptParseFailure(c)||!d)throw f;z({event:"isolated_batch_ts_retry",message:c.message}),u=await this.spawnAndExecute("executeBatch",{...l,codeBlocks:p},t,o)}}catch(l){let f=l;if(z({event:"isolated_batch_error",message:f.message,code:f.code,isTimeout:!!f.isTimeout}),f.ctxChanges&&this.mergeCtxChanges(t,f.ctxChanges),f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new he(o,"(batch execution)");let c=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw De.createException(void 0,c,f.message||"Unknown error","(batch execution)",f.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),z({event:"isolated_batch_ok"}),{value:u.valueAbsent?void 0:u.value,shortCircuit:u.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let n=[...e].sort((i,s)=>i-s),o=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[o]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((o,i)=>o+i,0)/t.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),maxHeapRatio:Math.max(0,...e.workers.map(o=>o.lastHeapRatio||0))}}};var Rn=require("mongodb");Ke();function We(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function X(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!We(r)&&(r.foreignKeyColumn||r.propertyName)||null}function U(r){return r.mappedBy||r.foreignKeyColumn||r.propertyName||null}function ne(r){if(!r||typeof r!="object")return r;if(r instanceof Rn.ObjectId)return r.toString();if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return r.map(t=>ne(t));if("buffer"in r&&r.buffer&&typeof r.buffer=="object"&&Object.keys(r.buffer).length===12)try{let t=r.buffer,n=Object.keys(t).sort((o,i)=>parseInt(o)-parseInt(i)).map(o=>t[o]);return new Rn.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)?ne(n):n;return e}function $e(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,l=r,f=e.junctionTableName||ue(a,u,l);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:f,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:l};let c=fe(a,u,l);return{junctionName:f,selfColumn:c.targetColumn,otherColumn:c.sourceColumn,owningTable:a,inverseTable:l}}let n=r,o=t,i=e.junctionTableName||ue(n,e.propertyName,o);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:i,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:o};let s=fe(n,e.propertyName,o);return{junctionName:i,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:o}}async function zt(r,e,t){if(!r)return{scalarFields:[],relations:[]};let n=r.tables?.get(e);if(!n)return{scalarFields:[],relations:[]};let o=new Map;for(let u of t)if(u==="*")o.has("")||o.set("",[]),o.get("").push(u);else if(u.includes(".")){let l=u.split("."),f=l[0],c=l.slice(1).join(".");o.has(f)||o.set(f,[]),o.get(f).push(c)}else n.relations?.some(f=>f.propertyName===u)?o.has(u)||o.set(u,["_id"]):(o.has("")||o.set("",[]),o.get("").push(u));let i=[],s=[],a=o.get("")||[];for(let u of a)if(u==="*"){if(n.columns)for(let l of n.columns)i.includes(l.name)||i.push(l.name);if(n.relations)for(let l of n.relations)o.has(l.propertyName)||o.set(l.propertyName,["_id"])}else n.columns?.some(f=>f.name===u)&&!i.includes(u)&&i.push(u);for(let[u,l]of o.entries()){if(u==="")continue;let f=n.relations?.find(m=>m.propertyName===u);if(!f)continue;let c="",p="",d=!1;f.type==="many-to-one"||f.type==="one-to-one"?We(f)?(c="_id",p=U(f)||f.propertyName,d=!0):(c=X(f)||f.propertyName,p="_id",d=!1):f.type==="one-to-many"?(c="_id",p=U(f)||f.propertyName,d=!0):f.type==="many-to-many"&&(f.mappedBy?(c="_id",p=f.mappedBy,d=!0):(c=f.propertyName,p="_id",d=!1));let g=f.type==="one-to-many"||f.type==="many-to-many";s.push({propertyName:u,targetTable:f.targetTableName,localField:c,foreignField:p,type:g?"many":"one",isInverse:d,nestedFields:l})}return{scalarFields:i,relations:s}}var Ht=le(require("fs")),Nn=le(require("path"));var Ni=new RegExp("\\p{Mark}","gu");function kr(r){return r==null?"":String(r).normalize("NFKD").replace(Ni,"").toLowerCase()}function vn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=kr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function qt(){return`function() {
7
+ });`),!0}catch{return!1}}function yi(r,e){if(!kn(r)||!e||typeof e!="object")return e;let t={...e},n=Sn(r);return n&&(t.sourceCode===void 0||t.sourceCode===null||t.sourceCode==="")&&t[n]!==void 0&&(t.sourceCode=t[n]),t.scriptLanguage=kt(t.scriptLanguage),(t.compiledCode===void 0||t.compiledCode===null||t.compiledCode==="")&&(t.compiledCode=ce(t.sourceCode,t.scriptLanguage)),n&&n in t&&delete t[n],t}function mi(r,e,t){if(!kn(r)||!e||typeof e!="object")return e;let n=Sn(r),i=Object.prototype.hasOwnProperty.call(e,"sourceCode")||(n?Object.prototype.hasOwnProperty.call(e,n):!1),o=Object.prototype.hasOwnProperty.call(e,"scriptLanguage");if(!i&&!o)return e;let s=i?e.sourceCode??(n?e[n]:void 0):t?.sourceCode??(n&&t?t[n]:void 0),a=o?e.scriptLanguage:t?.scriptLanguage,u=ce(s,a),l={...e};return i&&(l.sourceCode=s??null),l.scriptLanguage=kt(a),l.compiledCode=u,n&&n in l&&delete l[n],l}function hi(r){return ur(r).code}function ur(r){if(!r||typeof r!="object")return{code:null,compiledCode:null,shouldPersistCompiledCode:!1};if(typeof r.compiledCode=="string"&&r.compiledCode!==""&&cr(r.compiledCode))return{code:r.compiledCode,compiledCode:r.compiledCode,shouldPersistCompiledCode:!1};if(typeof r.sourceCode=="string"&&r.sourceCode!==""){let t=ce(r.sourceCode,r.scriptLanguage);return{code:t,compiledCode:t,shouldPersistCompiledCode:t!==r.compiledCode}}let e=Object.keys(St).find(t=>St[t]in r);if(e){let t=r[St[e]];if(typeof t=="string"&&t!==""){let n=ce(t,r.scriptLanguage);return{code:n,compiledCode:n,shouldPersistCompiledCode:n!==r.compiledCode}}}return typeof r.compiledCode=="string"&&r.compiledCode!==""?{code:r.compiledCode,compiledCode:r.compiledCode,shouldPersistCompiledCode:!1}:{code:null,compiledCode:null,shouldPersistCompiledCode:!1}}function bi(r){if(!r||typeof r!="object")return r;let e=r.type;if(e!=="script"&&e!=="condition")return r;let t=r.config;if(typeof t=="string")try{t=JSON.parse(t)}catch{return r}if(!t||typeof t!="object")return r;let n={...t};return n.sourceCode=n.sourceCode??n.code??null,n.scriptLanguage=kt(n.scriptLanguage),n.compiledCode=ce(n.sourceCode,n.scriptLanguage),delete n.code,{...r,config:typeof r.config=="string"?JSON.stringify(n):n}}var Ri=pr.join(__dirname,"execution/worker.js"),vi=["Invalid or unexpected token","Unexpected identifier","Unexpected token","Missing initializer in const declaration","await is only valid"],yr=new dr.AsyncLocalStorage;function mr(){return yr.getStore()}var Ct=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 l=0;l<e;l++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new gr.Worker(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let i=t.tasks.get(n.id);i&&(n.type==="result"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),n.contextStats&&(t.contextStats=n.contextStats),i.onResult(n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):i.onIoCall(n))}),e.on("exit",()=>{let n=t.draining,i=this.destroying;t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,s]of t.tasks)s.abortController.abort(),s.onResult({type:"result",success:!1,error:{message:i?"Worker terminated":"Worker crashed"}});t.tasks.clear();let o=this.entries.indexOf(t);o!==-1&&this.entries.splice(o,1),!n&&!i&&(this.onCrash&&this.onCrash(),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),this.entries.push(t),t}rotateEntry(e,t){if(e.draining)return;e.draining=!0;let n=Date.now()-e.spawnedAt;if(this.onRotate&&this.onRotate({reason:t,ageMs:n}),this.spawnEntry(),e.tasks.size===0){e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,e.worker.terminate()},this.drainTimeoutMs)}isMemoryAvailable(){let e=Date.now();return e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs&&(this.cachedMemoryOk=process.memoryUsage().rss/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e),this.cachedMemoryOk}findLeastBusy(){let e=null;for(let t of this.entries)t.draining||t.tasks.size<this.tasksCap&&(!e||t.tasks.size<e.tasks.size)&&(e=t);return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size===0||this.isMemoryAvailable())?Promise.resolve(e):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.tasks.set(t,n)}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&(e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(e&&(e.tasks.size===0||this.isMemoryAvailable()))this.waiting.shift()(e);else break}}terminateEntry(e){e.worker.terminate()}resize(e){for(this.max=Math.max(1,e);this.entries.length<this.max;)this.spawnEntry()}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,activeTasks:e.tasks.size,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}};function Cn(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 Ve=class r{constructor(e){this.logger=new Wt(r.name);this.effectiveMemory=Tt();this.isolationTuning=Vt();this.pool=new Ct(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Ri,()=>{this.crashesTotal++,this.logger.warn("Worker crashed, replacement spawned")},({reason:e,ageMs:t})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${e} age=${Math.round(t/1e3)}s`)});this.ceiling=this.isolationTuning.maxConcurrentWorkers;this.prevCpuUsage=process.cpuUsage();this.prevCpuTime=process.hrtime.bigint();this.pressureTicks=0;this.recoveryTicks=0;this.taskCounter=0;this.taskDoneTotal=0;this.taskErrorTotal=0;this.taskTimeoutTotal=0;this.rotationsTotal=0;this.crashesTotal=0;this.taskDurationsMs=[];this.packageCacheService=e.packageCacheService,this.packageCdnLoaderService=e.packageCdnLoaderService,this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let t=process.memoryUsage().rss/this.effectiveMemory,n=process.hrtime.bigint(),i=process.cpuUsage(this.prevCpuUsage),o=Number(n-this.prevCpuTime)/1e3,s=o>0?(i.user+i.system)/o:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let a=this.pool.getMax(),u=this.pool.getWaitingCount(),l=t>.85||s>.7,f=t<.7&&s<.5,c=u>0,p=a;l?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(p=Math.max(1,a-1))):f&&c?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(p=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),p!==a&&(this.pool.resize(p),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${p} (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},n=e.$flow;if(n!=null)try{t.$flow=JSON.parse(JSON.stringify(n,(i,o)=>typeof o=="bigint"?String(o):o))}catch{t.$flow={}}return t}mergeCtxChanges(e,t){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),delete e.$pkgs)}spawnAndExecute(e,t,n,i){return(async()=>{let o=await this.pool.dispatch(),s=`t_${++this.taskCounter}`,a=Date.now();return new Promise((u,l)=>{let f=!1,c=new AbortController,p=setTimeout(()=>{if(f)return;f=!0,c.abort(),this.pool.unregisterTask(o,s),this.taskTimeoutTotal++,z({event:"task_timeout",id:s,timeoutMs:i}),this.pool.terminateEntry(o);let d=new Error(`Script execution timed out after ${i}ms`);d.code="ERR_SCRIPT_EXECUTION_TIMEOUT",d.isTimeout=!0,l(d)},i+5e3);this.pool.registerTask(o,s,{abortController:c,onResult:d=>{if(!f)if(f=!0,clearTimeout(p),this.pool.unregisterTask(o,s),this.recordTaskDuration(Date.now()-a),d.success){this.taskDoneTotal++,z({event:"task_done",id:s,ok:!0});let g={value:d.value,valueAbsent:d.valueAbsent===!0,ctxChanges:d.ctxChanges};d.shortCircuit&&(g.shortCircuit=!0),u(g)}else{this.taskErrorTotal++,z({event:"task_done",id:s,ok:!1,message:d.error?.message});let g=new Error(d.error?.message||"Handler execution failed");g.statusCode=d.error?.statusCode,g.code=d.error?.code,g.details=d.error?.details,d.error?.stack&&(g.stack=d.error.stack),d.ctxChanges&&(g.ctxChanges=d.ctxChanges),l(g)}},onIoCall:d=>{if(f)return;let g=c.signal;d.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(d,n),o.worker,d.callId,g):d.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(d,n),o.worker,d.callId,g):d.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(d,n),o.worker,d.callId,g):d.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(d,n),o.worker,d.callId,g):d.type==="dispatchCall"&&this.handleIoCall(()=>this.execDispatchCall(d,n),o.worker,d.callId,g)}}),o.worker.postMessage({type:e,id:s,...t})})})()}async handleIoCall(e,t,n,i){if(!i?.aborted)try{let o=await(i?yr.run(i,e):e());if(i?.aborted)return;try{t.postMessage({type:"callResult",callId:n,result:Cn(o)})}catch{}}catch(o){if(i?.aborted)return;try{let s={__userThrow:!0,message:o.message,statusCode:o.statusCode,code:o.errorCode??o.code,details:o.details,messages:o.messages};t.postMessage({type:"callError",callId:n,error:JSON.stringify(s)})}catch{}}}async execRepoCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$repos?.[e.table];if(!i||typeof i[e.method]!="function")throw new Error(`Repo method not found: ${e.table}.${e.method}`);return i[e.method](...n)}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 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)}isScriptParseFailure(e){let t=e.message||"";return vi.some(n=>t.includes(n))}async run(e,t,n){let i=Math.max(1,Math.trunc(Number(n)||3e4)),o=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(o),a=this.createSnapshot(t);z({event:"isolated_run_start",timeoutMs:i,codeLen:e?.length??0});let u;try{let l={code:e,pkgSources:s,snapshot:a,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{u=await this.spawnAndExecute("execute",l,t,i)}catch(f){let c=f,p=ce(e,"typescript")||"";if(!this.isScriptParseFailure(c)||p===e)throw f;z({event:"isolated_run_ts_retry",message:c.message}),u=await this.spawnAndExecute("execute",{...l,code:p},t,i)}}catch(l){let f=l;if(z({event:"isolated_run_error",message:f.message,code:f.code,isTimeout:!!f.isTimeout}),f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new ye(i,e);let c=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw je.createException(void 0,c,f.message||"Unknown error",e,f.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),z({event:"isolated_run_ok"}),u.valueAbsent?void 0:u.value}async runBatch(e,t,n){let i=Math.max(1,Math.trunc(Number(n)||3e4)),o=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(o),a=this.createSnapshot(t);z({event:"isolated_batch_start",timeoutMs:i,blocks:e.length});let u;try{let l={codeBlocks:e,pkgSources:s,snapshot:a,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{u=await this.spawnAndExecute("executeBatch",l,t,i)}catch(f){let c=f,p=e.map(g=>({...g,code:ce(g.code,"typescript")||""})),d=p.some((g,m)=>g.code!==e[m]?.code);if(!this.isScriptParseFailure(c)||!d)throw f;z({event:"isolated_batch_ts_retry",message:c.message}),u=await this.spawnAndExecute("executeBatch",{...l,codeBlocks:p},t,i)}}catch(l){let f=l;if(z({event:"isolated_batch_error",message:f.message,code:f.code,isTimeout:!!f.isTimeout}),f.ctxChanges&&this.mergeCtxChanges(t,f.ctxChanges),f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new ye(i,"(batch execution)");let c=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw je.createException(void 0,c,f.message||"Unknown error","(batch execution)",f.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),z({event:"isolated_batch_ok"}),{value:u.valueAbsent?void 0:u.value,shortCircuit:u.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,s)=>o-s),i=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[i]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((i,o)=>i+o,0)/t.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),maxHeapRatio:Math.max(0,...e.workers.map(i=>i.lastHeapRatio||0))}}};var Rn=require("mongodb");ze();function De(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function H(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!De(r)&&(r.foreignKeyColumn||r.propertyName)||null}function U(r){return r.foreignKeyColumn||r.mappedBy||r.propertyName||null}function ne(r){if(!r||typeof r!="object")return r;if(r instanceof Rn.ObjectId)return r.toString();if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return r.map(t=>ne(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 Rn.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)?ne(n):n;return e}function _e(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,l=r,f=e.junctionTableName||Ft(a,u,l);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:f,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:l};let c=xt(a,u,l);return{junctionName:f,selfColumn:c.targetColumn,otherColumn:c.sourceColumn,owningTable:a,inverseTable:l}}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=xt(n,e.propertyName,i);return{junctionName:o,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:i}}async function zt(r,e,t){if(!r)return{scalarFields:[],relations:[]};let n=r.tables?.get(e);if(!n)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(".")){let l=u.split("."),f=l[0],c=l.slice(1).join(".");i.has(f)||i.set(f,[]),i.get(f).push(c)}else n.relations?.some(f=>f.propertyName===u)?i.has(u)||i.set(u,["_id"]):(i.has("")||i.set("",[]),i.get("").push(u));let o=[],s=[],a=i.get("")||[];for(let u of a)if(u==="*"){if(n.columns)for(let l of n.columns)o.includes(l.name)||o.push(l.name);if(n.relations)for(let l of n.relations)i.has(l.propertyName)||i.set(l.propertyName,["_id"])}else n.columns?.some(f=>f.name===u)&&!o.includes(u)&&o.push(u);for(let[u,l]of i.entries()){if(u==="")continue;let f=n.relations?.find(m=>m.propertyName===u);if(!f)continue;let c="",p="",d=!1;f.type==="many-to-one"||f.type==="one-to-one"?De(f)?(c="_id",p=U(f)||f.propertyName,d=!0):(c=H(f)||f.propertyName,p="_id",d=!1):f.type==="one-to-many"?(c="_id",p=U(f)||f.propertyName,d=!0):f.type==="many-to-many"&&(f.mappedBy?(c="_id",p=f.mappedBy,d=!0):(c=f.propertyName,p="_id",d=!1));let g=f.type==="one-to-many"||f.type==="many-to-many";s.push({propertyName:u,targetTable:f.targetTableName,localField:c,foreignField:p,type:g?"many":"one",isInverse:d,nestedFields:l})}return{scalarFields:o,relations:s}}var Ht=le(require("fs")),Nn=le(require("path"));var Ni=new RegExp("\\p{Mark}","gu");function kr(r){return r==null?"":String(r).normalize("NFKD").replace(Ni,"").toLowerCase()}function vn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=kr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function qt(){return`function() {
8
8
  var M = ${vn()};
9
9
  function foldStr(s) {
10
10
  if (s == null) return '';
@@ -50,4 +50,4 @@ ${r}
50
50
  }
51
51
  }
52
52
  return true;
53
- }`}var xr="mongo-fold-text-search.body.txt",Ge=null;function Mi(){let r=[Nn.join(__dirname,xr),Nn.join(process.cwd(),"dist","kernel","query","utils",xr)];for(let e of r)try{if(Ht.existsSync(e))return Ht.readFileSync(e,"utf8")}catch{}return null}function Gt(){if(Ge!==null)return Ge;let r=Mi();return r?(Ge=r,Ge):(Ge=qt(),Ge)}var Te=require("mongodb");function D(r,e,t,n){if(t==="_id"){if(n instanceof Te.ObjectId)return n;if(typeof n=="string")try{return new Te.ObjectId(n)}catch{return n}return n}let o=r?.tables?.get(e);if(!o){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new Te.ObjectId(n)}catch{return n}return n}if(!o.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new Te.ObjectId(n)}catch{return n}return n}let i=o.columns.find(s=>s.name===t);if(!i){if(o.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof n=="string"&&n.length===24)try{return new Te.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new Te.ObjectId(n)}catch{return n}return n}if(n==null)return n;switch(i.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;case"uuid":if(typeof n=="string")try{return new Te.ObjectId(n)}catch{return n}return n;default:return n}}var Yt="__mongoFoldTextTriples";function Ai(r){return r==="_id"?"$_id":`$${r}`}function Ye(r,e,t,n){let o=Ai(e),i=r[Yt]??[];i.push({ref:o,needle:t,mode:n}),r[Yt]=i}function Oi(r){let e=r[Yt];if(delete r[Yt],!e?.length)return;let t=[];for(let i of e)t.push(i.ref,i.needle,i.mode);let n={$eq:[{$function:{body:Gt(),args:t,lang:"js"}},!0]},o=r.$expr;o?r.$expr={$and:[o,n]}:r.$expr=n}function Xe(r,e,t,n){let o={},i=n==="mongodb"||!n;for(let s of e){let a=s.field.includes(".")?s.field.split(".").pop()??s.field:s.field,u=t||s.field.split(".")[0]||"";i&&a==="id"&&(a="_id");let l=D(r,u,a,s.value);switch(s.operator){case"=":o[a]=l;break;case"!=":o[a]={$ne:l};break;case">":o[a]={$gt:l};break;case"<":o[a]={$lt:l};break;case">=":o[a]={$gte:l};break;case"<=":o[a]={$lte:l};break;case"like":o[a]={$regex:l.replace(/%/g,".*"),$options:"i"};break;case"in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(h=>h.trim()):[f]);let c=f.map(h=>D(r,u,a,h));o[a]={$in:c};break;case"not in":let p=s.value;Array.isArray(p)||(p=typeof p=="string"&&p.includes(",")?p.split(",").map(h=>h.trim()):[p]);let d=p.map(h=>D(r,u,a,h));o[a]={$nin:d};break;case"is null":o[a]=null;break;case"is not null":o[a]={$ne:null};break;case"_contains":Ye(o,a,String(l),"contains");break;case"_starts_with":Ye(o,a,String(l),"starts");break;case"_ends_with":Ye(o,a,String(l),"ends");break;case"_between":let g=s.value;if(typeof g=="string"&&(g=g.split(",").map(h=>h.trim())),Array.isArray(g)&&g.length===2){let h=D(r,u,a,g[0]),b=D(r,u,a,g[1]);o[a]={$gte:h,$lte:b}}break;case"_is_null":let m=l===!0||l==="true";o[a]=m?{$eq:null}:{$ne:null};break;case"_is_not_null":let y=l===!0||l==="true";o[a]=y?{$ne:null}:{$eq:null};break}}return Oi(o),o}function Cr(r,e,t){let o=r?.tables?.get?.(e)?.columns?.find(i=>i.name===t);return o?o.isNullable!==!1:!0}function Xt(r,e,t,n,o,i){switch(o){case"_contains":Ye(e,n,String(i),"contains");break;case"_starts_with":Ye(e,n,String(i),"starts");break;case"_ends_with":Ye(e,n,String(i),"ends");break;case"_eq":e[n]=D(r,t,n,i);break;case"_neq":{let c=D(r,t,n,i);Cr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:c}})):e[n]={$ne:c};break}case"_in":{let c=i;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(d=>d.trim()):[c]);let p=c.map(d=>D(r,t,n,d));e[n]={$in:p};break}case"_not_in":case"_nin":let s=i;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(c=>c.trim()):[s]);let a=s.map(c=>D(r,t,n,c));Cr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$nin:a}})):e[n]={$nin:a};break;case"_gt":e[n]={$gt:D(r,t,n,i)};break;case"_gte":e[n]={$gte:D(r,t,n,i)};break;case"_lt":e[n]={$lt:D(r,t,n,i)};break;case"_lte":e[n]={$lte:D(r,t,n,i)};break;case"_is_null":let u=i===!0||i==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let l=i===!0||i==="true";e[n]=l?{$ne:null}:{$eq:null};break;case"_between":let f=i;if(typeof f=="string"&&(f=f.split(",").map(c=>c.trim())),Array.isArray(f)&&f.length===2){let c=D(r,t,n,f[0]),p=D(r,t,n,f[1]);e[n]={$gte:c,$lte:p}}break}}var In=require("mongodb");function re(r,e){if(!r||typeof r!="object")return!1;for(let[t,n]of Object.entries(r))if(t==="_and"||t==="_or"){if(Array.isArray(n)){for(let o of n)if(re(o,e))return!0}}else if(t==="_not"){if(re(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={},o=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(r)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(o.has(s))if(typeof a=="object"&&a!==null){let u=Object.keys(a);if(u.some(f=>f.startsWith("_"))){let f=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&f.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let i=re(r,o);return{fieldFilters:t,relationFilters:n,hasRelations:i}}Nt();Mt();var on="__mongoFoldTextTriples";function Qe(r,e){if(!r)return{};let t={};return nn(r,t,e),rn(t),t}function de(r,e,t){if(!e)return{};let n=new ie,{node:o}=ke(e,t,r,n);return Qe(o,{metadata:r,rootTable:t})}function nn(r,e,t){switch(r.kind){case"true":return;case"false":At(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let o=r.children.map(i=>{let s={};return nn(i,s,t),rn(s),s}).filter(i=>Object.keys(i).length>0);if(o.length===0)return;if(o.length===1){Object.assign(e,o[0]);return}At(e,...o);return}case"or":{let o=r.children.map(s=>{let a={};return nn(s,a,t),rn(a),a}).filter(s=>Object.keys(s).length>0);if(o.length===0)return;let i=e.$or;e.$or=i?[...i,...o]:o;return}case"not":{let n={};nn(r.child,n,t),rn(n);let o=e.$nor;e.$nor=o?[...o,n]:[n];return}case"compare":Ki(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 Ki(r,e,t){let n=r.field.fieldName;if(n==="id"&&(n="_id"),r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let o=i=>D(t.metadata,t.rootTable,n,i);switch(r.op){case"eq":oe(e,n,o(r.value));return;case"neq":{let i=o(r.value);Nr(t,n)?At(e,{[n]:{$ne:null}},{[n]:{$ne:i}}):oe(e,n,{$ne:i});return}case"gt":oe(e,n,{$gt:o(r.value)});return;case"gte":oe(e,n,{$gte:o(r.value)});return;case"lt":oe(e,n,{$lt:o(r.value)});return;case"lte":oe(e,n,{$lte:o(r.value)});return;case"in":{let i=Mr(r.value).map(o);oe(e,n,{$in:i});return}case"not_in":{let i=Mr(r.value).map(o);Nr(t,n)?At(e,{[n]:{$ne:null}},{[n]:{$nin:i}}):oe(e,n,{$nin:i});return}case"between":{let i=Array.isArray(r.value)?r.value:typeof r.value=="string"?r.value.split(",").map(s=>s.trim()):null;Array.isArray(i)&&i.length===2&&oe(e,n,{$gte:o(i[0]),$lte:o(i[1])});return}case"is_null":oe(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":An(e,n,String(r.value),"contains");return;case"starts_with":An(e,n,String(r.value),"starts");return;case"ends_with":An(e,n,String(r.value),"ends");return}}function oe(r,e,t){r[e]===void 0?r[e]=t:(At(r,{[e]:r[e]},{[e]:t}),delete r[e])}function At(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function Nr(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(o=>o.name===e);return n?n.isNullable!==!1:!0}function Mr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function Wi(r){return r==="_id"?"$_id":`$${r}`}function An(r,e,t,n){let o=Wi(e),i=r[on]??[];i.push({ref:o,needle:t,mode:n}),r[on]=i}function rn(r){let e=r[on];if(delete r[on],!e?.length)return;let t=[];for(let i of e)t.push(i.ref,i.needle,i.mode);let n={$eq:[{$function:{body:Gt(),args:t,lang:"js"}},!0]},o=r.$expr;o?r.$expr={$and:[o,n]}:r.$expr=n}async function pe(r,e,t,n){if(!r||typeof r!="object")return{};let o=t?.tables?.get(e);if(!o)return de(t,r,e);let i=new Set((o.relations||[]).map(l=>l.propertyName));if(!re(r,i))return de(t,r,e);if(r._and&&Array.isArray(r._and)){let f=(await Promise.all(r._and.map(c=>pe(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:f.length===1?f[0]:{$and:f}}if(r._or&&Array.isArray(r._or)){let f=(await Promise.all(r._or.map(c=>pe(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:{$or:f}}if(r._not){let l=await pe(r._not,e,t,n);return!l||Object.keys(l).length===0?{}:{$nor:[l]}}let{fieldFilters:s,relationFilters:a}=H(r,o),u=[];if(s&&Object.keys(s).length>0){let l=de(t,s,e);l&&Object.keys(l).length>0&&u.push(l)}if(a&&Object.keys(a).length>0)for(let[l,f]of Object.entries(a)){let c=await Ui(l,f,e,o,t,n);c&&Object.keys(c).length>0&&u.push(c)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function Ui(r,e,t,n,o,i){let s=(n.relations||[]).find(l=>l.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=o?.tables?.get(a);return!a||!u?{}:s.type==="many-to-one"||s.type==="one-to-one"?Qi(e,s,r,a,u,o,i):s.type==="one-to-many"?Ji(e,s,t,a,u,o,i):s.type==="many-to-many"?Vi(e,s,t,a,u,o,i):{}}async function Qi(r,e,t,n,o,i,s){let a=X(e)||t,u=Pn(r),l=jn(u);if(l!==null)return l?{[a]:null}:{[a]:{$ne:null}};let f=Or(u);if(f!==null){let g=Ln(f.value);if(f.op==="eq")return{[a]:g};if(f.op==="neq")return{[a]:{$ne:g}};if(f.op==="in")return{[a]:{$in:g}};if(f.op==="not_in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]}}let c=await En(u,n,o,i,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);return d.length===0?{[a]:null}:{[a]:{$in:d}}}async function Ji(r,e,t,n,o,i,s){let a=U(e)||t,u=Pn(r),l=jn(u);if(l!==null){let p=await Ar(s,n,a,{});return l?p.length===0?{}:{_id:{$nin:p}}:p.length===0?{__impossible__:!0}:{_id:{$in:p}}}let f=await En(u,n,o,i,s);if(!f||Object.keys(f).length===0)return{};let c=await Ar(s,n,a,f);return c.length===0?{__impossible__:!0}:{_id:{$in:c}}}async function Vi(r,e,t,n,o,i,s){let a=$e(t,e);if(!a)return{};let u=Pn(r),l=jn(u);if(l!==null){let m=await On(s,a,n,null);return l?m.length===0?{}:{_id:{$nin:m}}:m.length===0?{__impossible__:!0}:{_id:{$in:m}}}let f=Or(u);if(f!==null){let m=Ln(f.value),y=Array.isArray(m)?m:[m],h=await On(s,a,n,{_id:{$in:y}});return h.length===0?{__impossible__:!0}:{_id:{$in:h}}}let c=await En(u,n,o,i,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(m=>m._id).filter(Boolean);if(d.length===0)return{__impossible__:!0};let g=await On(s,a,n,{_id:{$in:d}});return g.length===0?{__impossible__:!0}:{_id:{$in:g}}}async function En(r,e,t,n,o){let i=new Set((t?.relations??[]).map(s=>s.propertyName));return re(r,i)?pe(r,e,n,o):de(n,r,e)}async function Ar(r,e,t,n){let o=await r.collection(e).find(n,{projection:{[t]:1}}).toArray(),i=new Set,s=[];for(let a of o){let u=a[t];if(u==null)continue;let l=String(u);i.has(l)||(i.add(l),s.push(u))}return s}async function On(r,e,t,n){let o=null;n&&t&&(o=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(f=>f._id).filter(Boolean));let i=o?{[e.otherColumn]:{$in:o}}:{},s=await r.collection(e.junctionName).find(i,{projection:{[e.selfColumn]:1}}).toArray(),a=new Set,u=[];for(let l of s){let f=l[e.selfColumn];if(f==null)continue;let c=String(f);a.has(c)||(a.add(c),u.push(f))}return u}function Pn(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function jn(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 Ln(r){if(Array.isArray(r))return r.map(e=>Ln(e));if(typeof r!="string")return r;try{return new In.ObjectId(r)}catch{return r}}function Or(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof In.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 Ot(r,e,t,n){let o=await zt(r,e,t),i=[],s={},a={};if(n&&typeof n=="object")for(let[d,g]of Object.entries(n))if(typeof g=="object"&&g!==null){let m=Object.keys(g)[0];m&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(m)?s[d]=g:a[d]=g}else s[d]=g;if(Object.keys(s).length>0){let d={};for(let[g,m]of Object.entries(s))if(typeof m=="object"&&m!==null)for(let[y,h]of Object.entries(m))Xt(r,d,e,g,y,h);else d[g]=m;Object.keys(d).length>0&&i.push({$match:d})}let l=r?.tables?.get(e)?.relations||[],f=[];for(let[d,g]of Object.entries(a))if(!o.relations.some(y=>y.propertyName===d)){let y=l.find(h=>h.propertyName===d);if(y){let h="",b="";if(y.type==="many-to-one"||y.type==="one-to-one")h=X(y)||y.propertyName,b="_id";else if(y.type==="one-to-many")h="_id",b=U(y)||y.propertyName;else if(y.type==="many-to-many")continue;let S=y.type==="one-to-many"||y.type==="many-to-many";f.push({propertyName:d,targetTable:y.targetTableName,localField:h,foreignField:b,type:S?"many":"one",nestedFields:[]})}}let c=[...o.relations,...f];for(let d of c){let g=a[d.propertyName],m=d.nestedFields&&d.nestedFields.length>0?await Ot(r,d.targetTable,d.nestedFields,g):g?await Ot(r,d.targetTable,["_id"],g):[];d.type==="one"&&m.length>0&&m.push({$limit:1}),i.push({$lookup:{from:d.targetTable,localField:d.localField,foreignField:d.foreignField,as:d.propertyName,pipeline:m.length>0?m:void 0}}),d.type==="one"&&(i.push({$unwind:{path:`$${d.propertyName}`,preserveNullAndEmptyArrays:!0}}),g&&(et(g)||i.push({$match:{[d.propertyName]:{$ne:null}}})))}let p=l.filter(d=>!c.some(g=>g.propertyName===d.propertyName));if(o.scalarFields.length>0||o.relations.length>0||p.length>0){let d={_id:1};for(let m of o.scalarFields)d[m]=1;for(let m of c)d[m.propertyName]=1;if(t.includes("*"))for(let m of p){if(m.type==="one-to-many"||m.type==="many-to-many")continue;m.type==="many-to-many"?d[m.propertyName]={$map:{input:`$${m.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[m.propertyName]={$cond:{if:{$ne:[`$${m.propertyName}`,null]},then:{_id:`$${m.propertyName}`},else:null}}}i.push({$project:d})}return i}async function Ir(r,e,t,n,o){let i=r?.tables?.get(t),s=i?.relations||[],a=i?.columns||[],u=s.filter(f=>!o.some(c=>c.propertyName===f.propertyName)),l=n.length===a.length||n.length===0&&o.length===0;if(u.length>0||!l){let f={_id:1};for(let c of n)f[c]=1;for(let c of o)f[c.propertyName]=1;for(let c of u){if(c.type==="one-to-many"||c.type==="many-to-many")continue;c.type==="many-to-many"?f[c.propertyName]={$map:{input:`$${c.propertyName}`,as:"item",in:{_id:"$$item"}}}:f[c.propertyName]={$cond:{if:{$ne:[`$${c.propertyName}`,null]},then:{_id:`$${c.propertyName}`},else:null}}}e.push({$project:f})}}function et(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>et(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>et(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>et(e));if("_not"in r)return et(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||et(t)))return!0}return!1}nt();var It=require("mongodb");nt();sn();var rt=class{constructor(e,t,n){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.pkField="_id"}normalizeMetadata(){return this.metadata?this.metadata.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortFromTokens(e){let t={};for(let n of this.parseSortTokens(e)){let o=n.field.split(".");if(o.length===1)t[o[0]]=n.order;else{let i=`__sort_${o.slice(0,-1).join("_")}`;t[`${i}.${o[o.length-1]}`]=n.order}}return Object.keys(t).length>0?t:void 0}parseSortTokens(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).map(n=>{let o=n.startsWith("-");return{field:o?n.slice(1):n,order:o?-1:1}}):[]}hasDottedSort(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).some(n=>(n.startsWith("-")?n.slice(1):n).includes(".")):!1}buildSortAggregatePipeline(e,t,n){let o=Array.isArray(n)?n:n.split(",").map(l=>l.trim()).filter(Boolean),i=[{$match:t}],s=new Set;for(let l of o){let c=(l.startsWith("-")?l.slice(1):l).split(".");if(c.length<=1)continue;let p=e;for(let d=0;d<c.length-1;d++){let g=c[d],m=this.normalizeMetadata()?.tables?.get(p);if(!m)break;let y=m.relations?.find(S=>S.propertyName===g);if(!y)break;let h=y.targetTableName||y.targetTable,b=`__sort_${c.slice(0,d+1).join("_")}`;if(!s.has(b)){s.add(b);let S=X(y)||y.propertyName,w=d===0?null:`__sort_${c.slice(0,d).join("_")}`,$=w?`${w}.${S}`:S;i.push({$lookup:{from:h,localField:$,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}p=h}}let a=this.buildSortFromTokens(n);a&&i.push({$sort:a});let u={};for(let l of s)u[l]=0;return Object.keys(u).length>0&&i.push({$project:u}),i}toObjectId(e){try{return typeof e=="string"?new It.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof It.ObjectId||t instanceof It.ObjectId?this.keyOf(e).localeCompare(this.keyOf(t)):typeof e=="number"&&typeof t=="number"?e-t:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="string"&&typeof t=="string"?e.localeCompare(t):e<t?-1:e>t?1:0}sortDocsInMemory(e,t){let n=this.parseSortTokens(t).filter(o=>!o.field.includes("."));n.length!==0&&e.sort((o,i)=>{for(let s of n){let a=this.compareSortValues(o[s.field],i[s.field]);if(a!==0)return a*s.order}return this.compareSortValues(o._id,i._id)})}sortDocsByPk(e){e.sort((t,n)=>this.compareSortValues(t._id,n._id))}projectionWithSortFields(e,t){if(!e)return{projection:e,hiddenFields:[]};let n={...e},o=[];for(let i of this.parseSortTokens(t))i.field.includes(".")||n[i.field]===void 0&&(n[i.field]=1,o.push(i.field));return{projection:n,hiddenFields:o}}removeHiddenFields(e,t){if(t.length!==0)for(let n of e)for(let o of t)delete n[o]}keyOf(e){return e==null?"":e instanceof It.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.relationName}resolveInverseFkField(e){return e.foreignField?e.foreignField:e.mappedBy?e.mappedBy:e.relationName}resolveParentPk(e){return this.pkField}resolveFields(e,t){let{rootFields:n,subRelations:o}=tt(e),i={},s=!1;if(n.includes("*")){s=!0;for(let p of t.relations||[])o.has(p.propertyName)||o.set(p.propertyName,["_id"])}else for(let p of n){let d=t.columns.find(g=>g.name===p);d?i[d.name]=1:t.relations?.find(m=>m.propertyName===p)&&!o.has(p)&&o.set(p,["_id"])}o.forEach((p,d)=>{let g=t.relations?.find(m=>m.propertyName===d);g&&(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse)&&(s||(i[g.propertyName]=1))}),s||(i._id=1);let a=[];o.forEach((p,d)=>{let g=t.relations?.find(b=>b.propertyName===d);if(!g)return;let m=g.targetTableName||g.targetTable;if(!m)return;let y,h;g.type==="many-to-one"||g.type==="one-to-one"?We(g)?(y="_id",h=U(g)||g.propertyName):(y=X(g)||g.propertyName,h="_id"):g.type==="one-to-many"?(y="_id",h=U(g)||g.propertyName):g.type==="many-to-many"&&(g.isInverse?(y="_id",h=g.mappedBy):(y=g.propertyName,h="_id")),a.push({relationName:d,type:g.type,targetTable:m,fields:p,isInverse:g.isInverse,fkColumn:g.foreignKeyColumn,mappedBy:g.mappedBy,junctionTableName:g.junctionTableName,junctionSourceColumn:g.junctionSourceColumn,junctionTargetColumn:g.junctionTargetColumn,localField:y,foreignField:h})});let u=!s&&Object.keys(i).length===1&&i._id===1&&a.length===0,l=this.fieldRenamesByTable?.get(t.name)??[],f=[];if(!s&&l.length>0)for(let p of l)i[p.newName]===1&&i[p.oldName]!==1&&(i[p.oldName]=1,f.push(p.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:i,pendingRenames:l,hiddenFields:f}}}async fetchOwner(e,t,n,o){let i=o?.userFilter?de(this.normalizeMetadata(),o.userFilter,e):null,s=this.buildSortFromTokens(o?.userSort),a=await G(t,u=>{let l={_id:{$in:u}};i&&Object.keys(i).length>0&&Object.assign(l,i);let f={projection:n.projection};return s&&(f.sort=s),this.db.collection(e).find(l,f).toArray()});return this.applyReadFallback(a,n)}async fetchInverse(e,t,n,o,i){let s=o.projection?{...o.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let a=n.filter(y=>y!=null).map(y=>this.toObjectId(y)),u=i?.userFilter?de(this.normalizeMetadata(),i.userFilter,e):null,l=i?.userLimit,f=i?.userPage,c=this.hasDottedSort(i?.userSort);if(l!==void 0&&l>0){let y=f?(f-1)*l:0,h=await ge(a,async S=>{let w={[t]:S};if(u&&Object.keys(u).length>0&&Object.assign(w,u),c){let _=this.buildSortAggregatePipeline(e,w,i.userSort);y>0&&_.push({$skip:y}),_.push({$limit:l}),s&&_.push({$project:s});let N=await this.db.collection(e).aggregate(_).toArray();return this.applyReadFallback(N,o)}let k={sort:this.buildSortFromTokens(i?.userSort)||{_id:1}};s&&(k.projection=s);let R=this.db.collection(e).find(w,k);return y>0&&R.skip(y),R.limit(l),this.applyReadFallback(await R.toArray(),o)},ee),b=[];for(let[S,w]of h.entries()){let $=a.find(k=>this.keyOf(k)===S);for(let k of w)k[t]||(k[t]=$??S),b.push(k)}return{docs:b,groupKeyField:t}}if(c){let y=[],h=await ge(a,async b=>{let S={[t]:b};u&&Object.keys(u).length>0&&Object.assign(S,u);let w=this.buildSortAggregatePipeline(e,S,i.userSort);s&&w.push({$project:s});let $=await this.db.collection(e).aggregate(w).toArray();return this.applyReadFallback($,o)},ee);for(let b of h.values())for(let S of b)y.push(S);return{docs:y,groupKeyField:t}}let p={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(p,u);let d=this.buildSortFromTokens(i?.userSort)||{_id:1},g={projection:s,sort:d},m=await G(a,y=>this.db.collection(e).find({[t]:{$in:y},...u||{}},g).toArray());return{docs:this.applyReadFallback(m,o),groupKeyField:t}}postProcessInverseChild(e,t,n){n||delete e[t]}async fetchM2M(e,t,n,o,i){let s=n?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=$e(s,{type:"many-to-many",propertyName:t.relationName,targetTable:t.targetTable,mappedBy:t.isInverse?t.mappedBy:void 0});if(!a)throw new Error(`Failed to resolve junction info for ${s}.${t.relationName}`);let u=e.map(w=>w._id).filter(w=>w!=null),l=new Map;for(let w of e)l.set(this.keyOf(w._id),[]);if(u.length===0)return{grouped:l,docs:[]};let f=await G(u,w=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:w}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray());if(f.length===0)return{grouped:l,docs:[]};let c=t.userFilter?de(this.normalizeMetadata(),t.userFilter,t.targetTable):null,p=t.userLimit,d=t.userPage;if(p!==void 0&&p>0){let w=d?(d-1)*p:0,$=await ge(u,async R=>{let N=(await this.db.collection(a.junctionName).find({[a.selfColumn]:R},{projection:{_id:0,[a.otherColumn]:1}}).toArray()).map(L=>L[a.otherColumn]).filter(L=>L!=null);if(N.length===0)return[];let v={_id:{$in:N}};if(c&&Object.keys(c).length>0&&Object.assign(v,c),this.hasDottedSort(t.userSort)){let L=this.buildSortAggregatePipeline(t.targetTable,v,t.userSort);w>0&&L.push({$skip:w}),L.push({$limit:p}),i.projection&&L.push({$project:i.projection});let T=await this.db.collection(t.targetTable).aggregate(L).toArray();return this.applyReadFallback(T,i)}let B={sort:this.buildSortFromTokens(t.userSort)||{_id:1}};i.projection&&(B.projection=i.projection);let P=this.db.collection(t.targetTable).find(v,B);return w>0&&P.skip(w),P.limit(p),this.applyReadFallback(await P.toArray(),i)},ee),k=[];for(let[R,_]of $.entries()){l.set(R,_);for(let N of _)k.push(N)}return{grouped:l,docs:k}}let g=new Set,m=[];for(let w of f){let $=w[a.otherColumn];if($==null)continue;let k=this.keyOf($);g.has(k)||(g.add(k),m.push($))}let y=i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1&&!c,h=[],b=new Map;if(y)h=m.map(w=>({_id:w})),this.sortDocsByPk(h);else{let w={_id:{$in:m}};c&&Object.keys(c).length>0&&Object.assign(w,c);let $=this.hasDottedSort(t.userSort),k;if($){let R=this.buildSortAggregatePipeline(t.targetTable,w,t.userSort);i.projection&&R.push({$project:i.projection}),k=await this.db.collection(t.targetTable).aggregate(R).toArray()}else{let R=this.buildSortFromTokens(t.userSort)||{_id:1},_=this.projectionWithSortFields(i.projection,t.userSort),N={sort:R};_.projection&&(N.projection=_.projection),k=await G(m,v=>this.db.collection(t.targetTable).find({_id:{$in:v},...c||{}},N).toArray()),t.userSort?this.sortDocsInMemory(k,t.userSort):this.sortDocsByPk(k),this.removeHiddenFields(k,_.hiddenFields)}h=this.applyReadFallback(k,i)}for(let w of h)b.set(this.keyOf(w._id),w);let S=new Map;for(let w of f){let $=this.keyOf(w[a.selfColumn]),k=this.keyOf(w[a.otherColumn]);b.has(k)&&(S.has(k)||S.set(k,[]),S.get(k).push($))}for(let w of h){let $=S.get(this.keyOf(w._id))||[];for(let k of $)l.get(k)?.push(w)}return{grouped:l,docs:h}}applyReadFallback(e,t){let n=t.pendingRenames??[];if(e.length===0||n.length===0)return e;let o=new Set(t.hiddenFields??[]);for(let i of e)for(let s of n)i[s.newName]===void 0&&i[s.oldName]!==void 0&&(i[s.newName]=i[s.oldName]),(o.has(s.oldName)||i[s.newName]!==void 0)&&delete i[s.oldName];return e}};async function an(r,e,t,n,o=3,i=0,s,a,u,l){let f=await l?.getActiveFieldRenamesByTable?.(),c=new rt(r,a,f);await new Ce(c,n,u).execute(e,t,o,i,s)}async function Kn(r,e,t){let n=[],{db:o,metadata:i,dbType:s,debugLog:a}=t,u=i?.tables?.get(e.table),l=new Set((u?.relations??[]).map(_=>_.propertyName)),f=!!e.mongoRawFilter&&!!i&&re(e.mongoRawFilter,l),c=e.plan,p=c?.filterTree&&!c.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&i&&f){let _=await pe(e.mongoRawFilter,e.table,i,o);_&&Object.keys(_).length>0&&n.push({$match:_})}else if(p){let _=Qe(c.filterTree,{metadata:i,rootTable:e.table});Object.keys(_).length>0&&n.push({$match:_})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let _=Xe(i,e.where,e.table,s);n.push({$match:_})}let d=e.plan,m=d?d.hasRelationSort:e.sort?.some(_=>{if(!_.field.includes("."))return!1;let N=_.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(v=>v.propertyName===N)??!1})??!1,y=()=>d?.sortItems?Yi(d.sortItems):e.sort?Gi(e.sort):null,h=d?.sortItems?zi(d.sortItems):[],b=()=>{!d||h.length===0||qi(n,e.table,d.sortItems,i)},S=()=>{h.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(h.map(_=>[_,0]))})};if(!e.mongoFieldsExpanded){b();let _=y();if(_&&n.push({$sort:_}),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})),S(),e.select){let v={};for(let I of e.select)v[I]=1;n.push({$project:v})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let N=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:N,pipeline:n}:{results:Er(N),pipeline:n}}let{scalarFields:w,relations:$}=e.mongoFieldsExpanded;if(!m){b();let _=y();_&&n.push({$sort:_}),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 k=[];for(let _ of $)if(e.sort?.some(v=>v.field.startsWith(`${_.propertyName}.`))){let v=e.mongoRawFilter?.[_.propertyName];if(_.nestedFields&&_.nestedFields.length>0){let M=await Ot(i,_.targetTable,_.nestedFields??[],v);_.type==="one"&&M.length>0&&M.push({$limit:1}),n.push({$lookup:{from:_.targetTable,localField:_.localField,foreignField:_.foreignField,as:_.propertyName,pipeline:M.length>0?M:void 0}})}else if(v){let M=await Ot(i,_.targetTable,["_id"],v);_.type==="one"&&M.length>0&&M.push({$limit:1}),n.push({$lookup:{from:_.targetTable,localField:_.localField,foreignField:_.foreignField,as:_.propertyName,pipeline:M.length>0?M:void 0}})}else n.push({$lookup:{from:_.targetTable,localField:_.localField,foreignField:_.foreignField,as:_.propertyName}});_.type==="one"&&(n.push({$unwind:{path:`$${_.propertyName}`,preserveNullAndEmptyArrays:!0}}),v&&(it(v)||n.push({$match:{[_.propertyName]:{$ne:null}}})))}else k.push(_);if(m){b();let _=y();_&&n.push({$sort:_}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}await Ir(i,n,e.table,w,[...$]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let R=await r.aggregate(n).toArray();if(e.mongoCountOnly)return{results:R,pipeline:n};if(k.length>0&&R.length>0){let _=e.deep||{},N=k.map(I=>{let B=i?.tables?.get(e.table)?.relations?.find(T=>T.propertyName===I.propertyName),P=_[I.propertyName],L=P?.fields!=null?Array.isArray(P.fields)?P.fields:String(P.fields).split(",").map(T=>T.trim()).filter(Boolean):I.nestedFields&&I.nestedFields.length>0?I.nestedFields:["_id"];return{relationName:I.propertyName,type:B?.type,targetTable:I.targetTable,fields:L,isInverse:B?.isInverse,mappedBy:B?.mappedBy,junctionTableName:B?.junctionTableName,localField:I.localField,foreignField:I.foreignField,userFilter:P?.filter,userSort:P?.sort,userLimit:P?.limit!==void 0?Number(P.limit):void 0,userPage:P?.page!==void 0?Number(P.page):void 0,nestedDeep:P?.deep}}),v=Hi(i);v&&await an(o,R,N,v,3,0,e.table,i,void 0,t.mongoPhysicalMigrationService)}return{results:Er(R),pipeline:n}}function Wn(r){return`__sort_count_${r.relationName||r.field}`}function zi(r){return r.filter(e=>e.function==="count").map(Wn)}function qi(r,e,t,n){let o=n?.tables?.get(e),i=o?.columns?.find(s=>s.isPrimary)?.name||(o?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="count")continue;let a=s.relationMeta,u=s.relationName||s.field,l=a?.targetTableName||a?.targetTable,f=Wn(s);if(!(!a||!l)){if(a.type==="one-to-many"){let c=U(a)||u;r.push({$lookup:{from:l,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${c}`,"$$localId"]}}},{$count:"value"}],as:f}}),r.push({$addFields:{[f]:{$ifNull:[{$arrayElemAt:[`$${f}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let c=$e(e,a);if(!c)continue;r.push({$lookup:{from:c.junctionName,let:{localId:`$${i}`},pipeline:[{$match:{$expr:{$eq:[`$${c.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:f}}),r.push({$addFields:{[f]:{$ifNull:[{$arrayElemAt:[`$${f}.value`,0]},0]}}})}}}}function Hi(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(o=>({name:o.name,type:o.type})),relations:n.relations||[]}:null}:null}function Gi(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 Yi(r){let e={};for(let t of r){let n=t.function==="count"?Wn(t):t.joinId!==null?t.fullPath:t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function it(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>it(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>it(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>it(e));if("_not"in r)return it(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||it(t)))return!0}return!1}function Er(r){return r.map(ne)}function Pr(r,e){let t=[],n=[],o=e?.tables?.get(r.rootTable);if(!o)return{scalarFields:t,relations:n};for(let i of r.nodes)if(i.kind==="wildcard")for(let s of o.columns||[])t.includes(s.name)||t.push(s.name);else i.kind==="scalar"?o.columns?.some(a=>a.name===i.name)&&!t.includes(i.name)&&t.push(i.name):i.kind==="relation"&&n.push(Xi(i,o,e));return{scalarFields:t,relations:n}}function Xi(r,e,t){let n=e.relations?.find(l=>l.propertyName===r.propertyName),o,i,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&We(n)?(o="_id",i=U(n)||r.propertyName,s=!0):(o=n&&X(n)||r.propertyName,i="_id",s=!1):r.relationType==="one-to-many"?(o="_id",i=n&&U(n)||r.propertyName,s=!0):n?.mappedBy?(o="_id",i=n.mappedBy,s=!0):(o=r.propertyName,i="_id",s=!1);let a=r.relationType==="one-to-many"||r.relationType==="many-to-many",u=jr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:o,foreignField:i,type:a?"many":"one",isInverse:s,nestedFields:u}}function jr(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=jr(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let o of n)e.push(`${t.propertyName}.${o}`)}return e}Ze();Mt();Nt();function ln(r,e,t,n){let o={rootTable:e,nodes:[]};if(!r||r.length===0)return o;let i=t?.tables?.get(e);if(!i)return o;let s=i.columns?.some(c=>c.name==="_id"&&c.isPrimary),a=i.columns?.some(c=>c.name==="id"),u=s&&!a?"_id":"id",l=new Map,f=[];for(let c of r){let p=c==="id"?u:c;if(p==="*")f.push("*");else if(p.includes(".")){let d=p.indexOf("."),g=p.substring(0,d),m=p.substring(d+1);if(!i.relations?.some(h=>h.propertyName===g))continue;l.has(g)||l.set(g,[]),l.get(g).push(m)}else if(i.relations?.some(g=>g.propertyName===p))l.has(p)||l.set(p,[u]);else{if(!i.columns?.some(m=>m.name===p))continue;f.push(p)}}if(f.includes("*")){o.nodes.push({kind:"wildcard"});for(let c of i.relations||[])l.has(c.propertyName)||l.set(c.propertyName,[u])}else for(let c of f)o.nodes.push({kind:"scalar",name:c});for(let[c,p]of l.entries()){let d=i.relations?.find(y=>y.propertyName===c);if(!d)continue;let g=d.targetTableName||d.targetTable,m={kind:"relation",propertyName:c,joinId:null,relationType:d.type,isInverse:!!d.isInverse,targetTable:g,children:Lr(p,g,t)};if(d.type==="many-to-one"||d.type==="one-to-one"){let y=n.registerWithParent(e,c,t,"left",null,"data");m.joinId=y}o.nodes.push(m)}return o}function Lr(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let o=n.columns?.some(f=>f.name==="_id"&&f.isPrimary),i=n.columns?.some(f=>f.name==="id"),s=o&&!i?"_id":"id",a=new Map,u=[];for(let f of r){let c=f==="id"?s:f;if(c==="*")u.push("*");else if(c.includes(".")){let p=c.indexOf("."),d=c.substring(0,p),g=c.substring(p+1);if(!n.relations?.some(y=>y.propertyName===d))continue;a.has(d)||a.set(d,[]),a.get(d).push(g)}else if(n.relations?.some(d=>d.propertyName===c))a.has(c)||a.set(c,[s]);else{if(!n.columns?.some(g=>g.name===c))continue;u.push(c)}}let l=[];if(u.includes("*")){l.push({kind:"wildcard"});for(let f of n.relations||[])a.has(f.propertyName)||a.set(f.propertyName,[s])}else for(let f of u)l.push({kind:"scalar",name:f});for(let[f,c]of a.entries()){let p=n.relations?.find(g=>g.propertyName===f);if(!p)continue;let d=p.targetTableName||p.targetTable;l.push({kind:"relation",propertyName:f,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:d,children:Lr(c,d,t)})}return l}Se();var J=class{plan(e){let{tableName:t,fields:n,filter:o,sort:i,page:s,limit:a,meta:u,metadata:l,dbType:f}=e,c=l?.tables?.get(t),p=new ie,d=this.parseFields(n),g=null;d&&c&&(g=ln(d,t,l,p));let m=!1,y=null;if(o&&c){let I=ke(o,t,l,p);y=I.node,m=I.hasRelationFilters}let h=this.parseSort(i),b=[],S=!1;for(let I of h){let M=I.startsWith("-"),B=M?I.substring(1):I,P=M?"desc":"asc";if(c){let L=this.parseRelationCountSort(t,c,B);if(L){b.push({joinId:null,field:B,direction:P,fullPath:B,function:"count",relationName:L.relationName,relationMeta:L.relationMeta});continue}this.assertLocalSortField(t,c,B)}b.push({joinId:null,field:B,direction:P,fullPath:B})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let w=this.parseLimit(a),$=this.parsePage(s),k=$!==void 0&&w!==void 0?($-1)*w:void 0,R=this.parseMeta(u),_=R.includes("totalCount")||R.includes("*"),N=R.includes("filterCount")||R.includes("*"),v=p.getAll();return{table:t,dbType:f,rawFields:d,rawFilter:o??null,joins:v,sortItems:b,limit:w,offset:k,needsTotalCount:_,needsFilterCount:N,hasRelationFilters:m,hasRelationSort:S,filterTree:y,fieldTree:g}}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 A(`Sort field '${n}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let o=t.columns?.some(s=>s.name===n),i=n==="id"&&t.columns?.some(s=>s.name==="_id");if(!o&&!i)throw new A(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationCountSort(e,t,n){if(!n.startsWith("_count"))return null;let o=n.match(/^_count\(([^)]+)\)$/);if(!o)throw new A(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName).`);let i=o[1].trim();if(!i||i.includes("."))throw new A(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let s=t.relations?.find(a=>a.propertyName===i);if(!s)throw new A(`Sort relation '${i}' does not exist on '${e}'.`);if(s.type!=="one-to-many"&&s.type!=="many-to-many")throw new A(`Sort function '_count(${i})' is only supported for list relations on '${e}'.`);return{relationName:i,relationMeta:s}}registerSortJoinChain(e,t,n,o,i){let s=e.indexOf(".");if(s===-1)return null;let a=e.slice(0,s),u=e.slice(s+1),l=n?.tables?.get(t);if(!l)return null;let f=l.relations?.find(d=>d.propertyName===a);if(!f||f.type!=="many-to-one"&&f.type!=="one-to-one")return null;let c=o.registerWithParent(t,a,n,"left",i,"sort");if(!c)return null;if(!u.includes("."))return{lastJoinId:c,field:u};let p=f.targetTableName||f.targetTable;return this.registerSortJoinChain(u,p,n,o,c)}};Se();vt();var Zi=new Set(["count","sum","avg","min","max","countRecords"]),eo=new Set(["int","integer","bigint","float","double","decimal","numeric","real","number"]),to=new Set(["_and","_or","_not"]);function Fe(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function E(r,e){let t=r.replace(/^aggregate\./,"");throw new A(e,{path:r,aggregate:{[t]:e}})}function no(r){return typeof r!="string"?!1:eo.has(r.toLowerCase())}function Dr(r){return Object.keys(r).length===0}function ro(r,e,t){return r===!0?{}:(r==null&&E(t,`aggregate.${e} condition must be true or an object`),Fe(r)||E(t,`aggregate.${e} condition must be true or an object`),r)}function io(r,e,t){let n=r?.tables?.get(e);return n||E(t,`Table "${e}" metadata is not available`),n}function Br(r,e){let t=r?.targetTableName??r?.targetTable;return(typeof t!="string"||t.length===0)&&E(e,"aggregate.countRecords relation target is not available"),t}function cn(r,e,t,n){let o=io(t,e,n);for(let[i,s]of Object.entries(r)){if(i==="_and"||i==="_or"){Array.isArray(s)||E(n,`aggregate.countRecords ${i} condition must be an array`);for(let f of s)Fe(f)||E(n,`aggregate.countRecords ${i} items must be objects`),cn(f,e,t,n);continue}if(i==="_not"){Fe(s)||E(n,"aggregate.countRecords _not condition must be an object"),cn(s,e,t,n);continue}(i.startsWith("_")||to.has(i))&&E(n,`Unsupported aggregate.countRecords condition key "${i}"`);let a=o.columns?.find(f=>f.name===i),u=o.relations?.find(f=>f.propertyName===i);if(!a&&!u&&E(n,`Unknown aggregate.countRecords field or relation "${i}" on table "${e}"`),Fe(s)||E(n,`aggregate.countRecords condition for "${i}" must be an object`),a){for(let f of Object.keys(s))Z.has(f)||E(n,`aggregate.countRecords condition for "${i}" only supports field operators`);continue}let l=Br(u,n);cn(s,l,t,n)}}function Un(r){return Fe(r)&&Object.keys(r).length>0}function ot(r,e,t){if(!Un(r))return[];Fe(r)||E("aggregate","aggregate must be an object");let n=t?.tables?.get(e);n||E("aggregate",`Table "${e}" metadata is not available`);let o=[];for(let[i,s]of Object.entries(r)){let a=`aggregate.${i}`;(!i||typeof i!="string")&&E("aggregate","aggregate field name must be a non-empty string"),Fe(s)||E(a,"aggregate field config must be an object");let u=i,l=a,f=n.columns?.find(d=>d.name===i),c=n.relations?.find(d=>d.propertyName===i);!f&&!c&&E(l,`Unknown aggregate field or relation "${i}" on table "${e}"`);let p=Object.entries(s).filter(([d])=>d!=="as");p.length===0&&E(l,"aggregate field must define at least one operation");for(let[d,g]of p){Zi.has(d)||E(l,`Unsupported aggregate operation "${d}"`);let m=ro(g,d,l);if(c&&d!=="countRecords"&&E(l,`aggregate.${d} is not supported on relation "${i}"; use countRecords`),f&&d==="countRecords"&&E(l,`aggregate.countRecords requires a relation, but "${i}" is a field`),f&&(d==="sum"||d==="avg")&&!no(f.type)&&E(l,`aggregate.${d} requires a numeric field, but "${i}" is "${f.type}"`),f)for(let y of Object.keys(m))Z.has(y)||E(l,`aggregate.${d} condition for "${i}" only supports field operators`);if(c&&d==="countRecords"){let y=Br(c,l);cn(m,y,t,l)}o.push({field:i,outputKey:u,path:l,op:d,condition:m})}}return o}function st(r,e){let t=[];return Fe(r)&&!Dr(r)&&t.push(r),Dr(e.condition)||t.push({[e.field]:e.condition}),t.length===0?{}:t.length===1?t[0]:{_and:t}}function Re(r,e,t){r[e.outputKey]??={},r[e.outputKey][e.op]=t}var at=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 p=new J;e={...e,plan:p.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:"mongodb"})}}let t=e.debugLog||[];this.debugLog=t;let n={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};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(p=>p.trim()))),e.filter&&(Q(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let p=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(d=>d.trim());n.sort=p.map(d=>{let g=d.trim();return g.startsWith("-")?{field:g.substring(1),direction:"desc"}:{field:g,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let p=typeof e.page=="string"?parseInt(e.page,10):e.page,d=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(p-1)*d,n.limit=d}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let o=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(p=>p.trim()).filter(Boolean),i=0,s=0;(o.includes("totalCount")||o.includes("*"))&&(i=await this.mongoService.collection(e.tableName).countDocuments({}));let a=this.metadata?.tables?.get(e.tableName),u=new Set((a?.relations??[]).map(p=>p.propertyName)),l=!!n.mongoRawFilter&&re(n.mongoRawFilter,u);if((o.includes("filterCount")||o.includes("*"))&&!l){let p=this.mongoService.collection(e.tableName),d=e.plan?.filterTree?Qe(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await p.countDocuments(d)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let f=await this.selectLegacy(n);if(e.debugMode){let p=this.lastBuiltPipeline??[],d;try{d=await this.db.collection(e.tableName).aggregate(p).explain()}catch(g){d={error:String(g)}}return{pipeline:p,explain:d}}if(l&&(o.includes("filterCount")||o.includes("*"))){let p={...n,mongoCountOnly:!0},d=await this.selectLegacy(p);s=d.length>0?d[0].count:0}let c=await this.executeAggregate(n,e.filter);return{data:f,...(o.length>0||c)&&{meta:{...o.includes("totalCount")||o.includes("*")?{totalCount:i}:{},...o.includes("filterCount")||o.includes("*")?{filterCount:s}:{},...c?{aggregate:c}:{}}}}}async selectLegacy(e){let t=[];if(e.fields&&e.fields.length>0){let s=e.plan;if(s?.fieldTree?e.mongoFieldsExpanded=Pr(s.fieldTree,this.metadata):(console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await zt(this.metadata,e.table,e.fields)),this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let a=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:a.scalarFields},t=a.hiddenFields}}e.where&&(e.where=e.where.map(s=>s.field.includes(".")?s:{...s,field:`${e.table}.${s.field}`}));let n=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 n.aggregate(e.pipeline).toArray()).map(ne);let{results:o,pipeline:i}=await Kn(n,e,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=i,this.mongoPhysicalMigrationService?await this.mongoPhysicalMigrationService.applyReadFallback(e.table,o,t):o}async executeAggregationPipeline(e,t){let{results:n,pipeline:o}=await Kn(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=o,n}async executeAggregate(e,t){let n=ot(e.aggregate,e.table,e.metadata);if(n.length===0)return;let o={},i=this.db.collection(e.table);for(let s of n){let a=st(t,s);Q(a,e.table,e.metadata);let l=new J().plan({tableName:e.table,filter:a,metadata:e.metadata,dbType:"mongodb"});if(s.op==="countRecords"){let p=await this.executeRelationCountRecords(e,t,s);Re(o,s,p);continue}let f=l.hasRelationFilters?await pe(a,e.table,e.metadata,this.db):l.filterTree?Qe(l.filterTree,{metadata:e.metadata,rootTable:e.table}):{},c;if(s.op==="count")c=await i.countDocuments(f);else{let[{value:p}={value:null}]=await i.aggregate([{$match:f},{$group:{_id:null,value:{[`$${s.op}`]:`$${s.field}`}}}]).toArray();c=p??0}Re(o,s,c)}return o}async executeRelationCountRecords(e,t,n){let i=e.metadata?.tables?.get(e.table)?.relations?.find(f=>f.propertyName===n.field),s=i?.targetTableName||i?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!i||!s||!a)return 0;let u=await this.resolveMatchFilter(e.table,t,e.metadata),l=await this.resolveMatchFilter(s,n.condition,e.metadata);if(i.type==="one-to-many"){let c=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(p=>p._id).filter(p=>p!=null);return c.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{[i.foreignKeyColumn]:{$in:c}}]})}if(i.type==="many-to-many"){let f=$e(e.table,i);if(!f)return 0;let p=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(m=>m._id).filter(m=>m!=null);if(p.length===0)return 0;let g=(await this.db.collection(f.junctionName).find({[f.selfColumn]:{$in:p}},{projection:{[f.otherColumn]:1}}).toArray()).map(m=>m[f.otherColumn]).filter(m=>m!=null);return g.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:g}}]})}if(i.type==="many-to-one"||i.type==="one-to-one"){let f=i.foreignKeyColumn||`${n.field}Id`,p=(await this.db.collection(e.table).find(u,{projection:{[f]:1}}).toArray()).map(d=>d[f]).filter(d=>d!=null);return p.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:p}}]})}return 0}async resolveMatchFilter(e,t,n){if(!t||Object.keys(t).length===0)return{};Q(t,e,n);let i=new J().plan({tableName:e,filter:t,metadata:n,dbType:"mongodb"});return i.hasRelationFilters?await pe(t,e,n,this.db):i.filterTree?Qe(i.filterTree,{metadata:n,rootTable:e}):{}}};var un=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}};Se();var oo=["_and","_or","_not"];function ye(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>ye(e));for(let e of Object.keys(r))if(oo.includes(e)||typeof r[e]=="object"&&r[e]!==null&&ye(r[e]))return!0;return!1}var Kr=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function so(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function fn(r,e,t){if(!t)return!1;let n=r;if(r.includes(".")){let s=r.split(".");n=s[s.length-1]}let o=t.columns.find(s=>s.name===n);if(!o)return!1;let i=o.type?.toLowerCase()||"";return i==="uuid"||i==="uuidv4"||i.includes("uuid")}function ao(r,e,t,n,o){return n!=="postgres"||typeof e!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||fn(r,t,o),e}function Wr(r,e,t,n,o,i,s){let a=o&&!e.includes(".")?`${o}.${e}`:e,u=fn(e,o,s),l=ao(e,n,o,i,s);switch(t){case"_eq":u&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${a} = ?::uuid`,[n]):r.where(a,"=",l);break;case"_neq":u&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${a} != ?::uuid`,[n]):r.where(a,"!=",l);break;case"_gt":u&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${a} > ?::uuid`,[n]):r.where(a,">",l);break;case"_gte":u&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${a} >= ?::uuid`,[n]):r.where(a,">=",l);break;case"_lt":u&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${a} < ?::uuid`,[n]):r.where(a,"<",l);break;case"_lte":u&&i==="postgres"&&typeof n=="string"?r.whereRaw(`${a} <= ?::uuid`,[n]):r.where(a,"<=",l);break;case"_in":let f=n;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]),u&&i==="postgres"&&f.every(p=>typeof p=="string")?r.whereRaw(`${a} = ANY(?::uuid[])`,[f]):r.whereIn(a,f);break;case"_not_in":case"_nin":let c=n;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(p=>p.trim()):[c]),u&&i==="postgres"&&c.every(p=>typeof p=="string")?r.whereRaw(`${a} != ALL(?::uuid[])`,[c]):r.whereNotIn(a,c);break;case"_contains":i==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):i==="sqlite"?r.whereRaw(`lower(${a}) LIKE '%' || lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${a})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_starts_with":i==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE lower(unaccent(?)) || '%'`,[n]):i==="sqlite"?r.whereRaw(`lower(${a}) LIKE lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${a})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_ends_with":i==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE '%' || lower(unaccent(?))`,[n]):i==="sqlite"?r.whereRaw(`lower(${a}) LIKE '%' || lower(?)`,[n]):r.whereRaw(`lower(unaccent(${a})) 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,so(t),n)}}function lo(r,e,t){if(!t||!e||r.startsWith("_"))return!0;let n=r.includes(".")?r.split(".").pop():r,o=t.columns?.some(s=>s.name===n),i=t.relations?.some(s=>s.propertyName===n);return o||i}function lt(r,e,t,n="and",o,i){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let s of e)n==="and"?r.where(function(){lt(this,s,t,"and",o,i)}):r.orWhere(function(){lt(this,s,t,"and",o,i)});return}for(let[s,a]of Object.entries(e))if(lo(s,t,i)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){lt(this,u,t,"and",o,i)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){lt(this,u,t,"and",o,i)})});continue}if(s==="_not"){r.whereNot(function(){lt(this,a,t,"and",o,i)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(l=>Kr.includes(l)))for(let[l,f]of Object.entries(a))Kr.includes(l)&&(n==="and"?r.where(function(){Wr(this,s,l,f,t,o,i)}):r.orWhere(function(){Wr(this,s,l,f,t,o,i)}));else{let l=t&&!s.includes(".")?`${t}.${s}`:s;fn(s,t,i)&&o==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${l} = ?::uuid`,[a]):r.orWhereRaw(`${l} = ?::uuid`,[a]):n==="and"?r.where(l,"=",a):r.orWhere(l,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s;fn(s,t,i)&&o==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${u} = ?::uuid`,[a]):r.orWhereRaw(`${u} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function se(r,e,t,n,o){return!e||typeof e!="object"||lt(r,e,t,"and",n,o),r}ve();function Vn(r,e,t){return`${C(r,t)}.${C(e,t)}`}function Ne(r,e){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Ur(r,e){if(!e)return!1;let t=e.columns.find(o=>o.name===r);if(!t)return!1;let n=t.type?.toLowerCase()||"";return n==="uuid"||n==="uuidv4"||n.includes("uuid")}function ct(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function zn(r,e,t,n,o,i){let s=[];for(let[a,u]of Object.entries(i)){let l=await Et(r,e,a,u,t,n,o);if(l!==null)s.push(`EXISTS (${l})`);else{let f=t.relations.find(c=>c.propertyName===a);if(f&&f.foreignKeyColumn){let c=Vn(e,f.foreignKeyColumn,n),d=u.id;if(d&&typeof d=="object"){let g=ct(d._is_null),m=ct(d._is_not_null);if(g===!0)s.push(`${c} IS NULL`);else if(g===!1)s.push(`${c} IS NOT NULL`);else if(m===!0)s.push(`${c} IS NOT NULL`);else if(m===!1)s.push(`${c} IS NULL`);else if(d._eq!==void 0){let y=Ne(d._eq,n);s.push(`${c} = ${y}`)}else if(d._neq!==void 0){let y=Ne(d._neq,n);s.push(`${c} != ${y}`)}else if(d._in!==void 0){let h=(Array.isArray(d._in)?d._in:[d._in]).map(b=>Ne(b,n)).join(", ");s.push(`${c} IN (${h})`)}else if(d._not_in!==void 0||d._nin!==void 0){let y=d._not_in??d._nin,b=(Array.isArray(y)?y:[y]).map(S=>Ne(S,n)).join(", ");s.push(`${c} NOT IN (${b})`)}else if(d._gt!==void 0){let y=Ne(d._gt,n);s.push(`${c} > ${y}`)}else if(d._gte!==void 0){let y=Ne(d._gte,n);s.push(`${c} >= ${y}`)}else if(d._lt!==void 0){let y=Ne(d._lt,n);s.push(`${c} < ${y}`)}else if(d._lte!==void 0){let y=Ne(d._lte,n);s.push(`${c} <= ${y}`)}}}}}return s}function qn(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 Qn(r,e,t,n,o,i){let s=[];for(let a of r)if(a._and&&Array.isArray(a._and)&&a._and.length>0){let u=[];for(let l of a._and)if(qn(l)){let f=e(t).select(`${t}.id`);await Je(e,f,l,t,n,o,i),u.push({idSubquery:f})}else{let{fieldFilters:f,relationFilters:c}=H(l,n),p=await zn(e,t,n,o,i,c);u.push({fieldFilters:f,subqueries:p})}s.push(u)}else if(qn(a)){let u=e(t).select(`${t}.id`);await Je(e,u,a,t,n,o,i),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:l}=H(a,n),f=await zn(e,t,n,o,i,l);s.push([{fieldFilters:u,subqueries:f}])}return s}function Qr(r,e,t,n,o){if("idSubquery"in e&&e.idSubquery){r.whereIn(`${t}.id`,e.idSubquery);return}let i=e;Object.keys(i.fieldFilters).length===0&&i.subqueries.length===0||r.where(function(){Object.keys(i.fieldFilters).length>0&&se(this,i.fieldFilters,t,o,n);for(let s of i.subqueries)this.whereRaw(s)})}function Jn(r,e,t,n,o){let i=!0;for(let s of e){let a=function(){for(let u of s)Qr(this,u,t,n,o)};i?(r.where(a),i=!1):r.orWhere(a)}}function dn(r,e,t,n,o,i,s){let a=Ur(e,o),u=Ur(n,i),l=`${C(r,s)}.${C(e,s)}`,f=`${C(t,s)}.${C(n,s)}`;if(s==="postgres"){if(a&&!u)return`${l} = ${f}::uuid`;if(!a&&u)return`${l}::uuid = ${f}`}return`${l} = ${f}`}async function Et(r,e,t,n,o,i,s){let a=o.relations.find(p=>p.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 l=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 p=Object.keys(n||{});if(p.length===1&&p[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(g=>l.has(g)))return null}let f=s?await s(u):null,c;switch(a.type){case"one-to-many":c=r(u).select(r.raw("1")).whereRaw(dn(u,a.foreignKeyColumn,e,"id",f,o,i));break;case"many-to-many":let p=s?await s(a.junctionTableName):null;c=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw(dn(a.junctionTableName,a.junctionTargetColumn,u,"id",p,f,i))).whereRaw(dn(a.junctionTableName,a.junctionSourceColumn,e,"id",p,o,i));break;case"many-to-one":case"one-to-one":c=r(u).select(r.raw("1")).whereRaw(dn(u,"id",e,a.foreignKeyColumn,f,o,i));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?f?await Je(r,c,n,u,f,i,s):c=se(c,n,u,i,f||void 0):c=se(c,n,u,i),c.toString()}async function Je(r,e,t,n,o,i,s){if(!t||typeof t!="object")return;if(t._and&&Array.isArray(t._and)){for(let l of t._and)if(l._or&&Array.isArray(l._or)&&l._or.length>0){let f=await Qn(l._or,r,n,o,i,s);e.where(function(){Jn(this,f,n,o,i)})}else if(l._and&&Array.isArray(l._and)&&l._and.length>0)for(let f of l._and)await Je(r,e,f,n,o,i,s);else await Je(r,e,l,n,o,i,s);return}if(t._or&&Array.isArray(t._or)){let l=await Qn(t._or,r,n,o,i,s);e.where(function(){Jn(this,l,n,o,i)});return}if(t._not){let l=t._not;if(l._and&&Array.isArray(l._and)&&l._and.length>0){let p=[];for(let d of l._and)if(qn(d)){let g=r(n).select(`${n}.id`);await Je(r,g,d,n,o,i,s),p.push({idSubquery:g})}else{let{fieldFilters:g,relationFilters:m}=H(d,o),y=await zn(r,n,o,i,s,m);p.push({fieldFilters:g,subqueries:y})}e.whereNot(function(){for(let d of p)Qr(this,d,n,o,i)});return}if(l._or&&Array.isArray(l._or)&&l._or.length>0){let p=await Qn(l._or,r,n,o,i,s);e.whereNot(function(){Jn(this,p,n,o,i)});return}let{fieldFilters:f,relationFilters:c}=H(l,o);e.whereNot(function(){Object.keys(f).length>0&&se(this,f,n,i,o)});for(let[p,d]of Object.entries(c)){let g=await Et(r,n,p,d,o,i,s);if(g===null){let m=o.relations.find(y=>y.propertyName===p);if(m&&m.foreignKeyColumn){let y=Vn(n,m.foreignKeyColumn,i),b=d.id;if(b&&typeof b=="object"){let S=ct(b._is_null),w=ct(b._is_not_null);if(S===!0)e.whereRaw(`${y} IS NOT NULL`);else if(S===!1)e.whereRaw(`${y} IS NULL`);else if(w===!0)e.whereRaw(`${y} IS NULL`);else if(w===!1)e.whereRaw(`${y} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${y} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${y} = ?`,[b._neq]);else if(b._in!==void 0){let $=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${y} NOT IN (${$.map(()=>"?").join(", ")})`,$)}else if(b._not_in!==void 0||b._nin!==void 0){let $=b._not_in??b._nin,k=Array.isArray($)?$:[$];e.whereRaw(`${y} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${g})`)}return}let{fieldFilters:a,relationFilters:u}=H(t,o);Object.keys(a).length>0&&se(e,a,n,i,o);for(let[l,f]of Object.entries(u)){let c=await Et(r,n,l,f,o,i,s);if(c===null){let p=o.relations.find(d=>d.propertyName===l);if(p&&p.foreignKeyColumn){let d=Vn(n,p.foreignKeyColumn,i),m=f.id;if(m&&typeof m=="object"){let y=ct(m._is_null),h=ct(m._is_not_null);if(y===!0)e.whereRaw(`${d} IS NULL`);else if(y===!1)e.whereRaw(`${d} IS NOT NULL`);else if(h===!0)e.whereRaw(`${d} IS NOT NULL`);else if(h===!1)e.whereRaw(`${d} IS NULL`);else if(m._eq!==void 0)e.whereRaw(`${d} = ?`,[m._eq]);else if(m._neq!==void 0)e.whereRaw(`${d} != ?`,[m._neq]);else if(m._in!==void 0){let b=Array.isArray(m._in)?m._in:[m._in];e.whereRaw(`${d} IN (${b.map(()=>"?").join(", ")})`,b)}else if(m._not_in!==void 0||m._nin!==void 0){let b=m._not_in??m._nin,S=Array.isArray(b)?b:[b];e.whereRaw(`${d} NOT IN (${S.map(()=>"?").join(", ")})`,S)}}}}else e.whereRaw(`EXISTS (${c})`)}}async function Ve(r,e,t,n,o,i,s){await Je(r,e,t,n,o,i,s)}ve();Gn();Ze();Ke();ve();function ut(r,e,t,n,o){for(let i of e){let s=i.field.split("."),a=t||s[0],u=s[s.length-1],l=Pt(n,a,u,i.value);switch(i.operator){case"=":r=r.where(i.field,"=",l);break;case"!=":r=r.where(i.field,"!=",l);break;case">":r=r.where(i.field,">",l);break;case"<":r=r.where(i.field,"<",l);break;case">=":r=r.where(i.field,">=",l);break;case"<=":r=r.where(i.field,"<=",l);break;case"like":r=r.where(i.field,"like",l);break;case"in":let f=Array.isArray(i.value)?i.value.map(m=>Pt(n,a,u,m)):[l];r=r.whereIn(i.field,f);break;case"not in":let c=Array.isArray(i.value)?i.value.map(m=>Pt(n,a,u,m)):[l];r=r.whereNotIn(i.field,c);break;case"is null":r=r.whereNull(i.field);break;case"is not null":r=r.whereNotNull(i.field);break;case"_contains":r=r.where(i.field,"like",`%${i.value}%`);break;case"_starts_with":r=r.where(i.field,"like",`${i.value}%`);break;case"_ends_with":r=r.where(i.field,"like",`%${i.value}`);break;case"_between":let p=i.value;if(typeof p=="string"&&(p=p.split(",").map(m=>m.trim())),Array.isArray(p)&&p.length===2){let m=Pt(n,a,u,p[0]),y=Pt(n,a,u,p[1]);r=r.whereBetween(i.field,[m,y])}break;case"_is_null":r=l===!0||l==="true"?r.whereNull(i.field):r.whereNotNull(i.field);break;case"_is_not_null":r=l===!0||l==="true"?r.whereNotNull(i.field):r.whereNull(i.field);break}}return r}function jt(r,e,t,n){let o=[],i=t;if(!r||typeof r!="object")return o;for(let[s,a]of Object.entries(r))if(s==="_and"&&Array.isArray(a)){let u=a.map(l=>{let f=jt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&o.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(l=>{let f=jt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&o.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=jt(a,e,t,n);u.length>0&&o.push(`NOT (${u.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[u,l]of Object.entries(a)){let f=`${C(e,n)}.${C(s,n)}`,c;if(l===null)c="NULL";else if(typeof l=="string"){let p=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,d=i.columns?.find(m=>m.name===s);d&&(d.type?.toLowerCase()==="uuid"||d.type?.toLowerCase().includes("uuid"))&&p.test(l)&&n==="postgres"?c=`'${l}'::uuid`:c=`'${l.replace(/'/g,"''")}'`}else typeof l=="boolean"?c=l?"true":"false":typeof l=="number"?c=String(l):c=`'${String(l).replace(/'/g,"''")}'`;if(u==="_eq")o.push(`${f} = ${c}`);else if(u==="_neq")o.push(`${f} != ${c}`);else if(u==="_gt")o.push(`${f} > ${c}`);else if(u==="_gte")o.push(`${f} >= ${c}`);else if(u==="_lt")o.push(`${f} < ${c}`);else if(u==="_lte")o.push(`${f} <= ${c}`);else if(u==="_is_null")o.push(`${f} IS NULL`);else if(u==="_is_not_null")o.push(`${f} IS NOT NULL`);else if(u==="_in"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");o.push(`${f} IN (${d})`)}else if(u==="_not_in"||u==="_nin"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");o.push(`${f} NOT IN (${d})`)}else if(u==="_contains"){let p=String(l).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}')) || '%'`):n==="mysql"?o.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):o.push(`lower(${f}) LIKE '%${p.toLowerCase()}%'`)}else if(u==="_starts_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${f})) ILIKE lower(unaccent('${p}')) || '%'`):n==="mysql"?o.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):o.push(`lower(${f}) LIKE '${p.toLowerCase()}%'`)}else if(u==="_ends_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?o.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}'))`):n==="mysql"?o.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci)`):o.push(`lower(${f}) LIKE '%${p.toLowerCase()}'`)}else if(u==="_between"&&Array.isArray(l)&&l.length===2){let p=typeof l[0]=="string"?`'${l[0].replace(/'/g,"''")}'`:String(l[0]),d=typeof l[1]=="string"?`'${l[1].replace(/'/g,"''")}'`:String(l[1]);o.push(`${f} BETWEEN ${p} AND ${d}`)}}else{let u=`${C(e,n)}.${C(s,n)}`,l;a===null?l="NULL":typeof a=="string"?l=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?l=a?"true":"false":l=String(a),o.push(`${u} = ${l}`)}return o}function Vr(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 Pt(r,e,t,n){if(n==null)return n;let o=r?.tables?.get(e);if(!o?.columns)return n;let i=o.columns.find(s=>s.name===t);if(!i)return n;switch(i.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;default:return n}}ve();Lt();Ke();async function qr(r,e,t,n,o,i,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(Xn(),zr)),u=await a(e,t,n,o,i,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function Zn(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(o=>({name:o.name,type:o.type})),relations:n.relations||[]}:null}:null}function Hr(r,e,t,n,o){let i=r.targetTableName||r.targetTable;if(!i)return null;let s=r.foreignKeyColumn||K(i);if(!s)return null;let a=c=>C(c,o),u=n?.tables?.get(i),f=(u?te(u):null)?.name||"id";return`(SELECT ${a(i)}.${a(e)} FROM ${a(i)} WHERE ${a(i)}.${a(f)} = ${a(t)}.${a(s)})`}Lt();var dt=class r{constructor(e,t,n,o){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=o;this.logger=new un(r.name);this.debugLog=[]}async execute(e){let t=performance.now();this.metadata=e.metadata;let n=e.debugLog||[];this.debugLog=n;let o=e.debugTrace;if(e.filter&&Q(e.filter,e.tableName,e.metadata),!e.plan){let T=new J;e={...e,plan:T.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:this.dbType})}}let i=e.plan,s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,u=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,l=i.rawFields&&i.rawFields.length>0&&!i.rawFields.includes("*");if(i.joins.length===0&&!i.hasRelationFilters&&!i.hasRelationSort&&!u&&!a&&l){o&&o.setQueryPath("simple");let T=await this.executeSimple(e,i);return o&&o.dur("sql_executor",t,{table:e.tableName}),T}let c={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?c.fields=e.fields:typeof e.fields=="string"&&(c.fields=e.fields.split(",").map(T=>T.trim())));let p=e.filter;if(e.filter&&!ye(e.filter)){c.where=[];for(let[T,x]of Object.entries(e.filter))if(typeof x=="object"&&x!==null)for(let[F,ae]of Object.entries(x)){let O;if(F==="_eq")O="=";else if(F==="_neq")O="!=";else if(F==="_in")O="in";else if(F==="_not_in"||F==="_nin")O="not in";else if(F==="_gt")O=">";else if(F==="_gte")O=">=";else if(F==="_lt")O="<";else if(F==="_lte")O="<=";else if(F==="_contains")O="_contains";else if(F==="_starts_with")O="_starts_with";else if(F==="_ends_with")O="_ends_with";else if(F==="_between")O="_between";else if(F==="_is_null")O="_is_null";else if(F==="_is_not_null")O="_is_not_null";else if(F==="_like")O="like";else if(F==="_ilike")O="ilike";else continue;c.where.push({field:T,operator:O,value:ae})}else c.where.push({field:T,operator:"=",value:x})}if(e.sort){let T=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(x=>x.trim());c.sort=T.map(x=>{let F=x.trim();return F.startsWith("-")?{field:F.substring(1),direction:"desc"}:{field:F,direction:"asc"}})}else c.sort=[{field:"id",direction:"asc"}];let d=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,g=d===void 0||Number.isNaN(d)?void 0:d<0?0:d,m=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,y=m===void 0||Number.isNaN(m)?void 0:m;y&&g!==void 0?(c.offset=(y-1)*g,c.limit=g):g!==void 0&&(c.limit=g);let h=e.plan?.sortItems??(c.sort??[]).map(T=>({joinId:null,field:T.field,direction:T.direction,fullPath:T.field})),b=[],S=[];for(let T of h){if(T.function==="count"){let x={sql:this.buildRelationCountSortSubquery(c.table,T),direction:T.direction};S.push(x);continue}if(T.joinId===null){if(T.field.includes(".")&&!e.plan){let F=T.field.split(".")[0];if(this.metadata?.tables?.get(c.table)?.relations?.some(V=>V.propertyName===F))continue}let x={field:T.field.includes(".")?T.field:`${c.table}.${T.field}`,direction:T.direction};b.push(x),S.push(x)}else{let x=e.plan?.joins.find(F=>F.id===T.joinId);if(x&&(x.relationType==="many-to-one"||x.relationType==="one-to-one")){let F=Hr(x.relationMeta,T.field,c.table,this.metadata,this.dbType);if(F){let ae={sql:F,direction:T.direction};S.push(ae)}}}}let w=[];if(c.fields&&c.fields.length>0){let T=Zn(this.metadata),x=await qr(this.knex,c.table,c.fields,T,this.dbType,this.maxQueryDepth,e.deep);c.select=[...c.select||[],...x.select],w=x.batchFetchDescriptors||[]}c.where&&(c.where=c.where.map(T=>T.field.includes(".")?T:{...T,field:`${c.table}.${T.field}`})),c.sort=b;let $=this.knex(c.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(T=>T.trim()).filter(Boolean),R=k.includes("filterCount")||k.includes("*"),_=k.includes("totalCount")||k.includes("*");if(c.select){let T=c.select.map(x=>typeof x=="string"&&x.trim().startsWith("(")?this.knex.raw(x):typeof x=="string"&&/ as /i.test(x)?this.knex.raw(x):x);$=$.select(T)}if(R&&$.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),_){let T=C(c.table,this.dbType);$.select(this.knex.raw(`(SELECT COUNT(*) FROM ${T}) as __total_count__`))}let N=["table_definition","column_definition","relation_definition","method_definition"].includes(c.table);if(p&&(ye(p)||Object.keys(p).length>0)){let T=this.metadata?.tables?.get(c.table);(!N&&T&&T.relations&&T.relations.length>0?H(p,T).hasRelations:!1)?await Ve(this.knex,$,p,c.table,T,this.dbType,F=>this.metadata?.tables?.get(F)):e.plan?.filterTree?Y($,e.plan.filterTree,{dbType:this.dbType,rootTable:c.table}):(this.logger.debug(`buildWhereClause fallback for table=${c.table}`),$=se($,p,c.table,this.dbType,T))}else c.where&&c.where.length>0&&($=ut($,c.where,c.table,this.metadata,this.dbType));for(let T of S)if(T.field){let x=T.field.includes(".")?T.field:`${c.table}.${T.field}`;$=$.orderBy(x,T.direction)}else T.sql&&($=$.orderByRaw(`${T.sql} ${T.direction.toUpperCase()}`));c.groupBy&&($=$.groupBy(c.groupBy)),c.offset&&($=$.offset(c.offset)),c.limit!==void 0&&c.limit!==null&&c.limit>0&&($=$.limit(c.limit));let v=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:c.table,sql:$.toSQL().toNative()});let I;if(e.debugMode&&(I=$.toSQL().toNative().sql),e.debugMode&&o){let T=$.toSQL().toNative();o.setSql(T.sql);try{let x=T.sql.replace(/\$\d+/g,"?"),F=await this.knex.raw(`EXPLAIN ${x}`,T.bindings);o.setExplain(this.dbType==="postgres"?F.rows:F[0])}catch(x){o.setExplain({error:String(x)})}}let M,B=performance.now();M=await $,o&&o.dur("db_execute",B,{table:e.tableName});let P=0;if(R&&M.length>0&&(P=Number(M[0].__filter_count__||0),M.forEach(T=>{delete T.__filter_count__})),_&&M.length>0&&M[0].__total_count__!==void 0&&(v=Number(M[0].__total_count__||0),M.forEach(T=>{delete T.__total_count__})),w&&w.length>0&&M.length>0){let T=Zn(this.metadata);if(T){let{executeBatchFetches:x}=await Promise.resolve().then(()=>(nr(),Gr));await x(this.knex,M,w,T,this.maxQueryDepth??3,0,c.table,this.dbType,this.metadata,o)}}if(this.knexService){let T=performance.now();M=await this.knexService.parseResult(M,c.table),o&&o.dur("db_parseResult",T,{table:e.tableName})}else{let T=(x,F)=>{if(!x||!this.metadata)return x;let ae=this.metadata.tables?.get(F);if(!ae)return x;if(Array.isArray(x))return x.map(V=>T(V,F));if(typeof x!="object"||Buffer.isBuffer(x))return x;let O={...x};for(let V of ae.columns)if(V.type==="simple-json"&&O[V.name]&&typeof O[V.name]=="string")try{O[V.name]=JSON.parse(O[V.name])}catch{}for(let[V,q]of Object.entries(O))if(q&&typeof q=="object"&&!Array.isArray(q)&&!Buffer.isBuffer(q)){let hn=q;if(hn.id!==void 0||hn.createdAt!==void 0){let gt=ae.relations?.find(yt=>yt.propertyName===V);gt&&(O[V]=T(q,gt.targetTableName))}}else if(Array.isArray(q)&&q.length>0&&typeof q[0]=="object"&&q[0].id!==void 0){let gt=ae.relations?.find(yt=>yt.propertyName===V);gt&&(O[V]=q.map(yt=>T(yt,gt.targetTableName)))}return O};M=T(M,c.table)}o&&(o.setQueryPath("full"),o.dur("sql_executor",t,{table:e.tableName}));let L=await this.executeAggregate(c,p);return{data:M,...(k.length>0||L)&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:v}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:P}:{},...L?{aggregate:L}:{}}},...I!==void 0&&{sql:I}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,o=t.relationName||t.field,i=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=te(s)?.name||"id",u=C(e,this.dbType),l=C(a,this.dbType);if(!n||!i)throw new A(`Sort relation '${o}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let f=n.foreignKeyColumn||n.mappedBy;if(!f)throw new A(`Sort function '_count(${o})' cannot resolve relation key on '${e}'.`);let c=C(i,this.dbType),p=C(f,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}if(n.type==="many-to-many"){let f=n.junctionTableName||(n.mappedBy?ue(i,n.mappedBy,e):ue(e,n.propertyName,i)),c=n.mappedBy?fe(i,n.mappedBy,e):fe(e,n.propertyName,i),p=n.junctionSourceColumn||(n.mappedBy?c.targetColumn:c.sourceColumn),d=C(f,this.dbType),g=C(p,this.dbType);return`(SELECT COUNT(*) FROM ${d} WHERE ${d}.${g} = ${u}.${l})`}throw new A(`Sort function '_count(${o})' is only supported for list relations on '${e}'.`)}async executeSimple(e,t){let n=e.tableName,o=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],i=this.knex(n).select(o);t.filterTree&&Y(i,t.filterTree,{dbType:this.dbType,rootTable:n});for(let y of t.sortItems){let h=y.field.includes(".")?y.field:`${n}.${y.field}`;i=i.orderBy(h,y.direction)}t.limit!==void 0&&t.limit!==null&&t.limit>0&&(i=i.limit(t.limit)),t.offset!==void 0&&(i=i.offset(t.offset));let s=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(y=>y.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),u=s.includes("totalCount")||s.includes("*");if(a&&i.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),u){let y=C(n,this.dbType);i.select(this.knex.raw(`(SELECT COUNT(*) FROM ${y}) as __total_count__`))}let l=e.debugTrace,f;if(e.debugMode){let y=i.toSQL().toNative();if(f=y.sql,l){l.setSql(y.sql);try{let h=y.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${h}`,y.bindings);l.setExplain(this.dbType==="postgres"?b.rows:b[0])}catch(h){l.setExplain({error:String(h)})}}}let c=performance.now(),p;p=await i,l&&l.dur("db_execute",c,{table:n}),this.knexService&&(p=await this.knexService.parseResult(p,n));let d=0,g=0;a&&p.length>0&&(d=Number(p[0].__filter_count__||0),p.forEach(y=>delete y.__filter_count__)),u&&p.length>0&&(g=Number(p[0].__total_count__||0),p.forEach(y=>delete y.__total_count__));let m=await this.executeAggregate({table:n,aggregate:e.aggregate,metadata:e.metadata},e.filter);return{data:p,...(s.length>0||m)&&{meta:{...u?{totalCount:g}:{},...a?{filterCount:d}:{},...m?{aggregate:m}:{}}},...f!==void 0&&{sql:f}}}async executeAggregate(e,t){let n=ot(e.aggregate,e.table,e.metadata);if(n.length===0)return;let o={};for(let i of n){let s=st(t,i);Q(s,e.table,e.metadata);let u=new J().plan({tableName:e.table,filter:s,metadata:e.metadata,dbType:this.dbType});if(i.op==="countRecords"){let d=await this.executeRelationCountRecords(e,t,i);Re(o,i,d);continue}let l=this.knex(e.table);if(u.hasRelationFilters){let d=e.metadata?.tables?.get(e.table);await Ve(this.knex,l,s,e.table,d,this.dbType,g=>e.metadata?.tables?.get(g))}else u.filterTree&&Y(l,u.filterTree,{dbType:this.dbType,rootTable:e.table});let f=`${C(e.table,this.dbType)}.${C(i.field,this.dbType)}`,c=i.op==="count"?this.knex.raw("COUNT(*) as value"):this.knex.raw(`${i.op.toUpperCase()}(${f}) as value`),p=await l.clearSelect().select(c).first();Re(o,i,p?.value??0)}return o}async executeRelationCountRecords(e,t,n){let o=e.metadata?.tables?.get(e.table),i=o?.relations?.find(c=>c.propertyName===n.field),s=i?.targetTableName||i?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!i||!s||!a)return 0;let u=this.knex(e.table).select(`${e.table}.id`);if(t&&Object.keys(t).length>0){let p=new J().plan({tableName:e.table,filter:t,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Ve(this.knex,u,t,e.table,o,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&Y(u,p.filterTree,{dbType:this.dbType,rootTable:e.table})}let l=this.knex(s).count("* as value");if(n.condition&&Object.keys(n.condition).length>0){Q(n.condition,s,e.metadata);let p=new J().plan({tableName:s,filter:n.condition,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Ve(this.knex,l,n.condition,s,a,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&Y(l,p.filterTree,{dbType:this.dbType,rootTable:s})}if(i.type==="one-to-many")l.whereIn(`${s}.${i.foreignKeyColumn}`,u);else if(i.type==="many-to-many"){let c=i.junctionTableName||ue(e.table,i.propertyName,s),p=fe(e.table,i.propertyName,s),d=i.junctionSourceColumn||p.sourceColumn,g=i.junctionTargetColumn||p.targetColumn;l.whereIn(`${s}.id`,this.knex(c).select(`${c}.${g}`).whereIn(`${c}.${d}`,u))}else(i.type==="many-to-one"||i.type==="one-to-one")&&l.whereIn(`${s}.id`,function(){this.select(`${e.table}.${i.foreignKeyColumn}`).from(e.table),t&&Object.keys(t).length>0&&this.whereIn(`${e.table}.id`,u),this.whereNotNull(`${e.table}.${i.foreignKeyColumn}`)});let f=await l.first();return Number(f?.value??0)}};var gn=require("mongodb"),pt=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()}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(!gn.ObjectId)return e;if(typeof e=="string")try{return new gn.ObjectId(e)}catch{return e}return e}async getMetadataForQuery(){let e={tables:new Map,tablesList:[]},t=this.lazyRef.metadataCacheService;return t?t.isLoaded?.()?await t.getMetadata?.()??e:t.getDirectMetadata?.()??e:e}async buildMongoFilter(e,t){let n=await this.getMetadataForQuery(),o=Xe(n,e,t,this.dbType);return o._id!==void 0&&(o._id=this.safeObjectId(o._id)),o}async applyWhereToKnex(e,t,n){let o=await this.getMetadataForQuery();return{query:ut(e,t,n??"",o,this.dbType)}}async runMongoMutationInSaga(e){return!this.mongoService?.runInSaga||this.mongoService.isInSaga?.()?e():(await this.mongoService.runInSaga(e)).data}async insertWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{if(Array.isArray(e.data)){let t=[];for(let n of e.data){let o=await this.mongoService.insertOne(e.table,n);t.push(ne(o))}return t}return this.mongoService.insertOne(e.table,e.data)});if(Array.isArray(e.data)){let t=[];for(let n of e.data){let o=await this.knexService.insertWithCascade(e.table,n);t.push(o)}return t}else return await this.knexService.insertWithCascade(e.table,e.data)}async select(e){let t=performance.now(),n=await this.getMetadataForQuery(),o=performance.now(),s=new J().plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:n,dbType:this.dbType}),a=e.debugTrace;if(a&&(a.dur("qb_planner",o,{table:e.tableName}),a.setPlan(this.sanitizePlan(s))),this.dbType==="mongodb")return new at(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s,aggregate:e.aggregate});let l=await new dt(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}),l}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),a=await this.mongoService.collection(e.table).find(i).toArray(),u=[];for(let l of a){let f=await this.mongoService.updateOne(e.table,l._id,e.data);u.push(f)}return u});let t=this.knexService.getKnex(),n=t(e.table);e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let o=await n;for(let i of o)await this.knexService.updateWithCascade(e.table,i.id,e.data);if(e.returning){let i=t(e.table);return e.where.length>0&&await this.applyWhereToKnex(i,e.where,e.table),await i.select(e.returning)}return{affected:o.length}}async deleteWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),s=await this.mongoService.collection(e.table).find(o).toArray(),a=0;for(let u of s)await this.mongoService.deleteOne(e.table,u._id)&&a++;return a});let n=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table)),await n.delete()}async count(e){if(this.dbType==="mongodb"){let i=e.where?await this.buildMongoFilter(e.where,e.table):{};return this.mongoService.count(e.table,i)}let n=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let o=await n.count("* as count").first();return Number(o?.count||0)}whereToFilter(e){let t={},n=this.databaseConfigService.isMongoDb();for(let[o,i]of Object.entries(e))o==="id"||o==="_id"?n?t._id=this.normalizeWhereFilterValue("_id",i):t.id=this.normalizeWhereFilterValue("id",i):t[o]=this.normalizeWhereFilterValue(o,i);return t}normalizeWhereFilterValue(e,t){return this.isFilterOperatorObject(t)?this.databaseConfigService.isMongoDb()&&e==="_id"?this.normalizeMongoIdOperatorValue(t):t:{_eq:this.databaseConfigService.isMongoDb()&&e==="_id"?this.safeObjectId(t):t}}isFilterOperatorObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof gn.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[n,o]of Object.entries(e))t[n]=Array.isArray(o)?o.map(i=>this.safeObjectId(i)):this.safeObjectId(o);return t}filterToWhere(e){let t=[];for(let[n,o]of Object.entries(e))if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let i=Object.entries(o)[0];if(i){let[s,a]=i,u=this.mapFilterOperatorToSql(s);t.push({field:n,operator:u,value:a})}}return t}mapFilterOperatorToSql(e){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"like",_starts_with:"like",_ends_with:"like",_is_null:"is null",_is_not_null:"is not null"}[e]||"="}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,aggregate:e.aggregate,maxQueryDepth:e.maxQueryDepth})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t){return this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let s=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return ne(s)}let n=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),i=n||t.id;return await o(e).where("id",i).first()})}async update(e,t,n){return this.trackQueryMetric("update",e,async()=>{if(t&&typeof t=="object"&&"where"in t)return await this.updateWithOptions({table:e,where:t.where,data:n});if(this.dbType==="mongodb"){let i=await this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n));return ne(i)}return await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first()})}async delete(e,t){return this.trackQueryMetric("delete",e,async()=>t&&typeof t=="object"&&"where"in t?await this.deleteWithOptions({table:e,where:t.where})>0:this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t)):await this.knexService.getKnex()(e).where("id",t).delete()>0)}async countRecords(e,t){if(this.dbType==="mongodb")return this.mongoService.count(e,t||{});let o=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.filterToWhere(t);({query:o}=await this.applyWhereToKnex(o,s,e))}let i=await o.count("* as count").first();return Number(i?.count||0)}async transaction(e){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>e(this.mongoService)):this.knexService.transaction(e)}async findById(e,t){if(this.dbType==="mongodb"){let o=this.safeObjectId(t);return this.mongoService.findOne(e,{_id:o})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let o={};for(let[i,s]of Object.entries(t))i==="id"||i==="_id"?o._id=this.safeObjectId(s):o[i]=s;return this.mongoService.findOne(e,o)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let o={};for(let[a,u]of Object.entries(t))a==="id"||a==="_id"?o._id=this.safeObjectId(u):o[a]=u;return await this.mongoService.collection(e).find(o).toArray()}return await this.knexService.getKnex()(e).where(t)}async insertAndGet(e,t){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));let n=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),i=n||t.id;return await o(e).where("id",i).first()}async updateById(e,t,n){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n)):(await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first())}async deleteById(e,t){return this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t))?1:0:this.knexService.getKnex()(e).where("id",t).delete()}async raw(e,t){let n=this.dbType==="mongodb"?"mongodb":"sql";return this.trackQueryMetric("raw",n,async()=>{if(this.dbType==="mongodb"){let i=this.mongoService.getDb();if(typeof e=="string"){if(e.toLowerCase().includes("select 1"))return await i.command({ping:1});throw new Error("String queries not supported for MongoDB. Use db.command() object instead.")}return await i.command(e)}return await this.knexService.getKnex().raw(e,t)})}async trackQueryMetric(e,t,n){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.trackQuery({op:e,table:t},n):await n()}getConnection(){return this.dbType==="mongodb"?this.mongoService.getDb():this.knexService.getKnex()}getKnex(){if(this.dbType==="mongodb")throw new Error("getKnex() is not available for MongoDB. Use getConnection() or unified methods.");return this.knexService.getKnex()}getMongoDb(){if(this.dbType!=="mongodb")throw new Error("getMongoDb() is not available for SQL. Use getConnection() or unified methods.");return this.mongoService.getDb()}getDatabaseType(){return this.dbType}isMongoDb(){return this.dbType==="mongodb"}isSql(){return["mysql","postgres","mariadb","sqlite"].includes(this.dbType)}getPkField(){return this.isMongoDb()?"_id":"id"}getRecordId(e){return this.isMongoDb()?e._id:e.id}};nr();er();Xn();ve();Lt();nt();Se();Ze();var Yr=new Set(["fields","filter","sort","limit","page","deep"]),mn=3;function rr(r,e,t,n=0,o=3){if(!e||typeof e!="object")return;if(n>=o)throw new A(`deep option exceeds maximum query depth of ${o}`);let i=t?.tables?.get(r),s=new Map((i?.relations??[]).map(a=>[a.propertyName,a]));for(let[a,u]of Object.entries(e)){let l=s.get(a);if(!l)throw new A(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let p of Object.keys(u))if(!Yr.has(p))throw new A(`Unknown deep option key '${p}' for relation '${a}'. Allowed: ${[...Yr].join(", ")}`);let f=l.type;if(u.limit!==void 0&&(f==="many-to-one"||f==="one-to-one"))throw new A(`'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 A(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let c=l.targetTableName||l.targetTable;if(c){if(u.filter&&(Q(u.filter,c,t),yn(u.filter,0,a,r)),u.sort){let p=Array.isArray(u.sort)?u.sort:String(u.sort).split(",").map(d=>d.trim()).filter(Boolean);for(let d of p){let g=d.startsWith("-")?d.slice(1):d;fo(g,c,t,a,r)}}u.deep&&rr(c,u.deep,t,n+1,o)}}}function fo(r,e,t,n,o){if(r.includes("."))throw new A(`Sort field '${r}' is not supported for relation '${n}' on '${o}'. Sort only by local fields defined on '${e}'.`);let i=t?.tables?.get(e);if(!i)throw new A(`Sort field '${r}' references unknown table '${e}' (relation '${n}' on '${o}')`);let s=i.columns?.some(u=>u.name===r),a=r==="id"&&i.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new A(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${o}')`)}var po=new Set(["_and","_or","_not"]);function yn(r,e,t,n){if(!(!r||typeof r!="object"))for(let[o,i]of Object.entries(r)){if(po.has(o)){if(Array.isArray(i))for(let l of i)yn(l,e,t,n);else i&&typeof i=="object"&&yn(i,e,t,n);continue}if(o.startsWith("_")||!i||typeof i!="object"||Array.isArray(i)||!Object.keys(i).some(l=>!l.startsWith("_")))continue;let a=e+1;if(a>mn)throw new A(`Filter path exceeds max dotted hops of ${mn} at '${o}' (relation '${t}' on '${n}')`);let u={};for(let l of Object.keys(i))l.startsWith("_")||(u[l]=i[l]);yn(u,a,t,n)}}function Xr(r,e,t,n){return!r||typeof r!="object"?r:Dt(r,e,t,n)}function Dt(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let i=r.map(s=>Dt(s,e,t,n)).filter(s=>s!=null);return i.length>0?i:null}let o={};for(let[i,s]of Object.entries(r)){if(i==="_and"||i==="_or"){let c=(Array.isArray(s)?s:[s]).map(p=>Dt(p,e,t,n)).filter(p=>p!=null&&Object.keys(p).length>0);c.length>0&&(o[i]=c);continue}if(i==="_not"){let f=Dt(s,e,t,n);f!=null&&Object.keys(f).length>0&&(o[i]=f);continue}let a=t?.tables?.get(e),u=a?.relations?.find(f=>f.propertyName===i);if(u){if(!n(e,i,"relation"))continue;let f=u.targetTableName||u.targetTable;if(!f)continue;let c=Dt(s,f,t,n);c!=null&&Object.keys(c).length>0&&(o[i]=c);continue}if(a?.columns?.find(f=>f.name===i)){if(!n(e,i,"column"))continue;o[i]=s;continue}o[i]=s}return o}function Zr(r,e,t,n){if(!r)return r;let o=Array.isArray(r)?r:r.split(",").map(s=>s.trim()).filter(Boolean),i=[];for(let s of o){let l=(s.startsWith("-")?s.slice(1):s).split("."),f=!0,c=e;for(let p=0;p<l.length;p++){let d=l[p],g=p===l.length-1,m=t?.tables?.get(c);if(!m){f=!1;break}if(g)m.columns?.find(h=>h.name===d)?n(c,d,"column")||(f=!1):m.relations?.find(b=>b.propertyName===d)&&(n(c,d,"relation")||(f=!1));else{let y=m.relations?.find(h=>h.propertyName===d);if(!y){f=!1;break}if(!n(c,d,"relation")){f=!1;break}c=y.targetTableName||y.targetTable||c}}f&&i.push(s)}if(i.length!==0)return Array.isArray(r)?i:i.join(",")}Nt();Ze();Mt();sn();vt();Ke();Se();function go(r){let e=new pt({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,o=()=>(t||(t=new He({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),i=()=>(n||(n=new ze({isolatedExecutorService:o()})),n);return{queryBuilderService:e,get isolatedExecutorService(){return o()},get executorEngineService(){return i()},async onDestroy(){await t?.onDestroy?.()}}}0&&(module.exports={ALL_SUPPORTED_OPERATORS,AuthenticationException,AuthorizationException,BadRequestException,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,DEEP_TO_MANY_DEFAULT_LIMIT,DEFAULT_TIMEOUT_MS,DOTTED_PATH_MAX_HOPS,DatabaseException,DuplicateResourceException,ErrorHandler,ExecutorEngineService,ExternalServiceException,FIELD_OPERATORS,FileNotFoundException,FileSizeExceededException,FileUploadException,HttpException,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH,InvalidTokenException,IsolatedExecutorService,JoinRegistry,LOGICAL_OPERATORS,MongoBatchAdapter,MongoQueryExecutor,PER_PARENT_CONCURRENCY,QueryBuilderService,QueryPlanner,ResourceNotFoundException,SchemaException,ScriptExecutionException,ScriptTimeoutException,ServiceUnavailableException,SqlBatchAdapter,SqlQueryExecutor,TokenExpiredException,ValidationException,WHERE_IN_CHUNK_SIZE,WorkerPool,appendIsolatedExecutorRuntimeLog,applyOperatorToMatch,applyRelationFilters,applyWhereToKnex,assertFieldOperatorValueIsClean,buildAggregateFilter,buildMongoCharFoldMapJson,buildMongoFoldTextSearchJs,buildRelationSubquery,buildSqlWherePartsFromFieldAst,buildWhereClause,camelToSnake,chunkedFetch,compileScriptSource,computeEngineTuning,createEnfyraKernel,dslOpToCompareOp,encodeMainThreadToIsolate,escapeSqlValue,executeBatchFetches,executeMongoBatchFetches,expandFieldsToJoinsAndSelect,getEffectiveCpuCount,getEffectiveMemoryBytes,getEngineTuning,getExecutableScript,getForeignKeyColumnName,getIoAbortSignal,getJunctionColumnNames,getJunctionTableName,getPrimaryKeyColumn,getScriptLegacyField,getShortFkConstraintName,getShortFkName,getShortIndexName,getShortPkName,hasAggregateQuery,hasLogicalOperators,isExecutableJavaScript,isScriptTable,mergeAggregateValue,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,perParentRun,quoteIdentifier,resolveExecutableScript,rewriteFilterDenyingFields,rewriteSortDroppingDenied,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,transformCode,validateDeepOptions,validateFilterShape,whereToMongoFilter});
53
+ }`}var Cr="mongo-fold-text-search.body.txt",qe=null;function Mi(){let r=[Nn.join(__dirname,Cr),Nn.join(process.cwd(),"dist","kernel","query","utils",Cr)];for(let e of r)try{if(Ht.existsSync(e))return Ht.readFileSync(e,"utf8")}catch{}return null}function Gt(){if(qe!==null)return qe;let r=Mi();return r?(qe=r,qe):(qe=qt(),qe)}var we=require("mongodb");function D(r,e,t,n){if(t==="_id"){if(n instanceof we.ObjectId)return n;if(typeof n=="string")try{return new we.ObjectId(n)}catch{return n}return n}let i=r?.tables?.get(e);if(!i){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}return n}if(!i.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}return n}let o=i.columns.find(s=>s.name===t);if(!o){if(i.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}return n}if(n==null)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;case"uuid":if(typeof n=="string")try{return new we.ObjectId(n)}catch{return n}return n;default:return n}}var Yt="__mongoFoldTextTriples";function Ai(r){return r==="_id"?"$_id":`$${r}`}function He(r,e,t,n){let i=Ai(e),o=r[Yt]??[];o.push({ref:i,needle:t,mode:n}),r[Yt]=o}function Oi(r){let e=r[Yt];if(delete r[Yt],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:Gt(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}function Ge(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 l=D(r,u,a,s.value);switch(s.operator){case"=":i[a]=l;break;case"!=":i[a]={$ne:l};break;case">":i[a]={$gt:l};break;case"<":i[a]={$lt:l};break;case">=":i[a]={$gte:l};break;case"<=":i[a]={$lte:l};break;case"like":i[a]={$regex:l.replace(/%/g,".*"),$options:"i"};break;case"in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(h=>h.trim()):[f]);let c=f.map(h=>D(r,u,a,h));i[a]={$in:c};break;case"not in":let p=s.value;Array.isArray(p)||(p=typeof p=="string"&&p.includes(",")?p.split(",").map(h=>h.trim()):[p]);let d=p.map(h=>D(r,u,a,h));i[a]={$nin:d};break;case"is null":i[a]=null;break;case"is not null":i[a]={$ne:null};break;case"_contains":He(i,a,String(l),"contains");break;case"_starts_with":He(i,a,String(l),"starts");break;case"_ends_with":He(i,a,String(l),"ends");break;case"_between":let g=s.value;if(typeof g=="string"&&(g=g.split(",").map(h=>h.trim())),Array.isArray(g)&&g.length===2){let h=D(r,u,a,g[0]),b=D(r,u,a,g[1]);i[a]={$gte:h,$lte:b}}break;case"_is_null":let m=l===!0||l==="true";i[a]=m?{$eq:null}:{$ne:null};break;case"_is_not_null":let y=l===!0||l==="true";i[a]=y?{$ne:null}:{$eq:null};break}}return Oi(i),i}function Fr(r,e,t){let i=r?.tables?.get?.(e)?.columns?.find(o=>o.name===t);return i?i.isNullable!==!1:!0}function Xt(r,e,t,n,i,o){switch(i){case"_contains":He(e,n,String(o),"contains");break;case"_starts_with":He(e,n,String(o),"starts");break;case"_ends_with":He(e,n,String(o),"ends");break;case"_eq":e[n]=D(r,t,n,o);break;case"_neq":{let c=D(r,t,n,o);Fr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:c}})):e[n]={$ne:c};break}case"_in":{let c=o;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(d=>d.trim()):[c]);let p=c.map(d=>D(r,t,n,d));e[n]={$in:p};break}case"_not_in":case"_nin":let s=o;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(c=>c.trim()):[s]);let a=s.map(c=>D(r,t,n,c));Fr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$nin:a}})):e[n]={$nin:a};break;case"_gt":e[n]={$gt:D(r,t,n,o)};break;case"_gte":e[n]={$gte:D(r,t,n,o)};break;case"_lt":e[n]={$lt:D(r,t,n,o)};break;case"_lte":e[n]={$lte:D(r,t,n,o)};break;case"_is_null":let u=o===!0||o==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let l=o===!0||o==="true";e[n]=l?{$ne:null}:{$eq:null};break;case"_between":let f=o;if(typeof f=="string"&&(f=f.split(",").map(c=>c.trim())),Array.isArray(f)&&f.length===2){let c=D(r,t,n,f[0]),p=D(r,t,n,f[1]);e[n]={$gte:c,$lte:p}}break}}var In=require("mongodb");function re(r,e){if(!r||typeof r!="object")return!1;for(let[t,n]of Object.entries(r))if(t==="_and"||t==="_or"){if(Array.isArray(n)){for(let i of n)if(re(i,e))return!0}}else if(t==="_not"){if(re(n,e))return!0}else if(e.has(t))return!0;return!1}function G(r,e){if(!r||typeof r!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},n={},i=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(r)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(i.has(s))if(typeof a=="object"&&a!==null){let u=Object.keys(a);if(u.some(f=>f.startsWith("_"))){let f=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&f.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let o=re(r,i);return{fieldFilters:t,relationFilters:n,hasRelations:o}}Nt();Mt();var on="__mongoFoldTextTriples";function Ke(r,e){if(!r)return{};let t={};return nn(r,t,e),rn(t),t}function ue(r,e,t){if(!e)return{};let n=new ie,{node:i}=Te(e,t,r,n);return Ke(i,{metadata:r,rootTable:t})}function nn(r,e,t){switch(r.kind){case"true":return;case"false":At(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let i=r.children.map(o=>{let s={};return nn(o,s,t),rn(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}At(e,...i);return}case"or":{let i=r.children.map(s=>{let a={};return nn(s,a,t),rn(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={};nn(r.child,n,t),rn(n);let i=e.$nor;e.$nor=i?[...i,n]:[n];return}case"compare":Ki(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 Ki(r,e,t){let n=r.field.fieldName;if(n==="id"&&(n="_id"),r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let i=o=>D(t.metadata,t.rootTable,n,o);switch(r.op){case"eq":oe(e,n,i(r.value));return;case"neq":{let o=i(r.value);Nr(t,n)?At(e,{[n]:{$ne:null}},{[n]:{$ne:o}}):oe(e,n,{$ne:o});return}case"gt":oe(e,n,{$gt:i(r.value)});return;case"gte":oe(e,n,{$gte:i(r.value)});return;case"lt":oe(e,n,{$lt:i(r.value)});return;case"lte":oe(e,n,{$lte:i(r.value)});return;case"in":{let o=Mr(r.value).map(i);oe(e,n,{$in:o});return}case"not_in":{let o=Mr(r.value).map(i);Nr(t,n)?At(e,{[n]:{$ne:null}},{[n]:{$nin:o}}):oe(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&&oe(e,n,{$gte:i(o[0]),$lte:i(o[1])});return}case"is_null":oe(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":An(e,n,String(r.value),"contains");return;case"starts_with":An(e,n,String(r.value),"starts");return;case"ends_with":An(e,n,String(r.value),"ends");return}}function oe(r,e,t){r[e]===void 0?r[e]=t:(At(r,{[e]:r[e]},{[e]:t}),delete r[e])}function At(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function Nr(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(i=>i.name===e);return n?n.isNullable!==!1:!0}function Mr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function Wi(r){return r==="_id"?"$_id":`$${r}`}function An(r,e,t,n){let i=Wi(e),o=r[on]??[];o.push({ref:i,needle:t,mode:n}),r[on]=o}function rn(r){let e=r[on];if(delete r[on],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:Gt(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}async function fe(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return ue(t,r,e);let o=new Set((i.relations||[]).map(l=>l.propertyName));if(!re(r,o))return ue(t,r,e);if(r._and&&Array.isArray(r._and)){let f=(await Promise.all(r._and.map(c=>fe(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:f.length===1?f[0]:{$and:f}}if(r._or&&Array.isArray(r._or)){let f=(await Promise.all(r._or.map(c=>fe(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:{$or:f}}if(r._not){let l=await fe(r._not,e,t,n);return!l||Object.keys(l).length===0?{}:{$nor:[l]}}let{fieldFilters:s,relationFilters:a}=G(r,i),u=[];if(s&&Object.keys(s).length>0){let l=ue(t,s,e);l&&Object.keys(l).length>0&&u.push(l)}if(a&&Object.keys(a).length>0)for(let[l,f]of Object.entries(a)){let c=await Ui(l,f,e,i,t,n);c&&Object.keys(c).length>0&&u.push(c)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function Ui(r,e,t,n,i,o){let s=(n.relations||[]).find(l=>l.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"?Qi(e,s,r,a,u,i,o):s.type==="one-to-many"?Ji(e,s,t,a,u,i,o):s.type==="many-to-many"?Vi(e,s,t,a,u,i,o):{}}async function Qi(r,e,t,n,i,o,s){let a=H(e)||t,u=Pn(r),l=jn(u);if(l!==null)return l?{[a]:null}:{[a]:{$ne:null}};let f=Or(u);if(f!==null){let g=Ln(f.value);if(f.op==="eq")return{[a]:g};if(f.op==="neq")return{[a]:{$ne:g}};if(f.op==="in")return{[a]:{$in:g}};if(f.op==="not_in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]}}let c=await En(u,n,i,o,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);return d.length===0?{[a]:null}:{[a]:{$in:d}}}async function Ji(r,e,t,n,i,o,s){let a=U(e)||t,u=Pn(r),l=jn(u);if(l!==null){let p=await Ar(s,n,a,{});return l?p.length===0?{}:{_id:{$nin:p}}:p.length===0?{__impossible__:!0}:{_id:{$in:p}}}let f=await En(u,n,i,o,s);if(!f||Object.keys(f).length===0)return{};let c=await Ar(s,n,a,f);return c.length===0?{__impossible__:!0}:{_id:{$in:c}}}async function Vi(r,e,t,n,i,o,s){let a=_e(t,e);if(!a)return{};let u=Pn(r),l=jn(u);if(l!==null){let m=await On(s,a,n,null);return l?m.length===0?{}:{_id:{$nin:m}}:m.length===0?{__impossible__:!0}:{_id:{$in:m}}}let f=Or(u);if(f!==null){let m=Ln(f.value),y=Array.isArray(m)?m:[m],h=await On(s,a,n,{_id:{$in:y}});return h.length===0?{__impossible__:!0}:{_id:{$in:h}}}let c=await En(u,n,i,o,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(m=>m._id).filter(Boolean);if(d.length===0)return{__impossible__:!0};let g=await On(s,a,n,{_id:{$in:d}});return g.length===0?{__impossible__:!0}:{_id:{$in:g}}}async function En(r,e,t,n,i){let o=new Set((t?.relations??[]).map(s=>s.propertyName));return re(r,o)?fe(r,e,n,i):ue(n,r,e)}async function Ar(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 l=String(u);o.has(l)||(o.add(l),s.push(u))}return s}async function On(r,e,t,n){let i=null;n&&t&&(i=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(f=>f._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 l of s){let f=l[e.selfColumn];if(f==null)continue;let c=String(f);a.has(c)||(a.add(c),u.push(f))}return u}function Pn(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function jn(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 Ln(r){if(Array.isArray(r))return r.map(e=>Ln(e));if(typeof r!="string")return r;try{return new In.ObjectId(r)}catch{return r}}function Or(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof In.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 Ot(r,e,t,n){let i=await zt(r,e,t),o=[],s={},a={};if(n&&typeof n=="object")for(let[d,g]of Object.entries(n))if(typeof g=="object"&&g!==null){let m=Object.keys(g)[0];m&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(m)?s[d]=g:a[d]=g}else s[d]=g;if(Object.keys(s).length>0){let d={};for(let[g,m]of Object.entries(s))if(typeof m=="object"&&m!==null)for(let[y,h]of Object.entries(m))Xt(r,d,e,g,y,h);else d[g]=m;Object.keys(d).length>0&&o.push({$match:d})}let l=r?.tables?.get(e)?.relations||[],f=[];for(let[d,g]of Object.entries(a))if(!i.relations.some(y=>y.propertyName===d)){let y=l.find(h=>h.propertyName===d);if(y){let h="",b="";if(y.type==="many-to-one"||y.type==="one-to-one")h=H(y)||y.propertyName,b="_id";else if(y.type==="one-to-many")h="_id",b=U(y)||y.propertyName;else if(y.type==="many-to-many")continue;let S=y.type==="one-to-many"||y.type==="many-to-many";f.push({propertyName:d,targetTable:y.targetTableName,localField:h,foreignField:b,type:S?"many":"one",nestedFields:[]})}}let c=[...i.relations,...f];for(let d of c){let g=a[d.propertyName],m=d.nestedFields&&d.nestedFields.length>0?await Ot(r,d.targetTable,d.nestedFields,g):g?await Ot(r,d.targetTable,["_id"],g):[];d.type==="one"&&m.length>0&&m.push({$limit:1}),o.push({$lookup:{from:d.targetTable,localField:d.localField,foreignField:d.foreignField,as:d.propertyName,pipeline:m.length>0?m:void 0}}),d.type==="one"&&(o.push({$unwind:{path:`$${d.propertyName}`,preserveNullAndEmptyArrays:!0}}),g&&(Xe(g)||o.push({$match:{[d.propertyName]:{$ne:null}}})))}let p=l.filter(d=>!c.some(g=>g.propertyName===d.propertyName));if(i.scalarFields.length>0||i.relations.length>0||p.length>0){let d={_id:1};for(let m of i.scalarFields)d[m]=1;for(let m of c)d[m.propertyName]=1,m.type==="one"&&m.localField&&m.localField!==m.propertyName&&(d[m.localField]=1);if(t.includes("*"))for(let m of p){if(m.type==="one-to-many"||m.type==="many-to-many")continue;m.type==="many-to-many"?d[m.propertyName]={$map:{input:`$${m.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[m.propertyName]={$cond:{if:{$ne:[`$${m.propertyName}`,null]},then:{_id:`$${m.propertyName}`},else:null}}}o.push({$project:d})}return o}async function Ir(r,e,t,n,i){let o=r?.tables?.get(t),s=o?.relations||[],a=o?.columns||[],u=s.filter(f=>!i.some(c=>c.propertyName===f.propertyName)),l=n.length===a.length||n.length===0&&i.length===0;if(u.length>0||!l){let f={_id:1};for(let c of n)f[c]=1;for(let c of i)f[c.propertyName]=1,c.type==="one"&&c.localField&&c.localField!==c.propertyName&&(f[c.localField]=1);for(let c of u){if(c.type==="one-to-many"||c.type==="many-to-many")continue;c.type==="many-to-many"?f[c.propertyName]={$map:{input:`$${c.propertyName}`,as:"item",in:{_id:"$$item"}}}:f[c.propertyName]={$cond:{if:{$ne:[`$${c.propertyName}`,null]},then:{_id:`$${c.propertyName}`},else:null}}}e.push({$project:f})}}function Xe(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Xe(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Xe(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Xe(e));if("_not"in r)return Xe(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||Xe(t)))return!0}return!1}et();var It=require("mongodb");et();sn();var tt=class{constructor(e,t,n){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.pkField="_id"}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("-");return{field:i?n.slice(1):n,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(l=>l.trim()).filter(Boolean),o=[{$match:t}],s=new Set;for(let l of i){let c=(l.startsWith("-")?l.slice(1):l).split(".");if(c.length<=1)continue;let p=e;for(let d=0;d<c.length-1;d++){let g=c[d],m=this.normalizeMetadata()?.tables?.get(p);if(!m)break;let y=m.relations?.find(S=>S.propertyName===g);if(!y)break;let h=y.targetTableName||y.targetTable,b=`__sort_${c.slice(0,d+1).join("_")}`;if(!s.has(b)){s.add(b);let S=H(y)||y.propertyName,w=d===0?null:`__sort_${c.slice(0,d).join("_")}`,$=w?`${w}.${S}`:S;o.push({$lookup:{from:h,localField:$,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}p=h}}let a=this.buildSortFromTokens(n);a&&o.push({$sort:a});let u={};for(let l of s)u[l]=0;return Object.keys(u).length>0&&o.push({$project:u}),o}toObjectId(e){try{return typeof e=="string"?new It.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof It.ObjectId||t instanceof It.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 It.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}=Ze(e),o={},s=!1;if(n.includes("*")){s=!0;for(let p of t.relations||[])i.has(p.propertyName)||i.set(p.propertyName,["_id"])}else for(let p of n){let d=t.columns.find(g=>g.name===p);d?o[d.name]=1:t.relations?.find(m=>m.propertyName===p)&&!i.has(p)&&i.set(p,["_id"])}i.forEach((p,d)=>{let g=t.relations?.find(m=>m.propertyName===d);g&&(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse)&&(s||(o[H(g)||g.propertyName]=1))}),s||(o._id=1);let a=[];i.forEach((p,d)=>{let g=t.relations?.find(b=>b.propertyName===d);if(!g)return;let m=g.targetTableName||g.targetTable;if(!m)return;let y,h;g.type==="many-to-one"||g.type==="one-to-one"?De(g)?(y="_id",h=U(g)||g.propertyName):(y=H(g)||g.propertyName,h="_id"):g.type==="one-to-many"?(y="_id",h=U(g)||g.propertyName):g.type==="many-to-many"&&(g.isInverse?(y="_id",h=g.mappedBy):(y=g.propertyName,h="_id")),a.push({relationName:d,type:g.type,targetTable:m,fields:p,isInverse:g.isInverse,fkColumn:g.foreignKeyColumn,mappedBy:g.mappedBy,junctionTableName:g.junctionTableName,junctionSourceColumn:g.junctionSourceColumn,junctionTargetColumn:g.junctionTargetColumn,localField:y,foreignField:h})});let u=!s&&Object.keys(o).length===1&&o._id===1&&a.length===0,l=this.fieldRenamesByTable?.get(t.name)??[],f=[];if(!s&&l.length>0)for(let p of l)o[p.newName]===1&&o[p.oldName]!==1&&(o[p.oldName]=1,f.push(p.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:o,pendingRenames:l,hiddenFields:f}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?ue(this.normalizeMetadata(),i.userFilter,e):null,s=this.buildSortFromTokens(i?.userSort),a=await Y(t,u=>{let l={_id:{$in:u}};o&&Object.keys(o).length>0&&Object.assign(l,o);let f={projection:n.projection};return s&&(f.sort=s),this.db.collection(e).find(l,f).toArray()});return this.applyReadFallback(a,n)}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=n.filter(y=>y!=null).map(y=>this.toObjectId(y)),u=o?.userFilter?ue(this.normalizeMetadata(),o.userFilter,e):null,l=o?.userLimit,f=o?.userPage,c=this.hasDottedSort(o?.userSort);if(l!==void 0&&l>0){let y=f?(f-1)*l:0,h=await de(a,async S=>{let w={[t]:S};if(u&&Object.keys(u).length>0&&Object.assign(w,u),c){let _=this.buildSortAggregatePipeline(e,w,o.userSort);y>0&&_.push({$skip:y}),_.push({$limit:l}),s&&_.push({$project:s});let N=await this.db.collection(e).aggregate(_).toArray();return this.applyReadFallback(N,i)}let k={sort:this.buildSortFromTokens(o?.userSort)||{_id:1}};s&&(k.projection=s);let R=this.db.collection(e).find(w,k);return y>0&&R.skip(y),R.limit(l),this.applyReadFallback(await R.toArray(),i)},ee),b=[];for(let[S,w]of h.entries()){let $=a.find(k=>this.keyOf(k)===S);for(let k of w)k[t]||(k[t]=$??S),b.push(k)}return{docs:b,groupKeyField:t}}if(s&&(s[t]=1),c){let y=[],h=await de(a,async b=>{let S={[t]:b};u&&Object.keys(u).length>0&&Object.assign(S,u);let w=this.buildSortAggregatePipeline(e,S,o.userSort);s&&w.push({$project:s});let $=await this.db.collection(e).aggregate(w).toArray();return this.applyReadFallback($,i)},ee);for(let b of h.values())for(let S of b)y.push(S);return{docs:y,groupKeyField:t}}let p={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(p,u);let d=this.buildSortFromTokens(o?.userSort)||{_id:1},g={projection:s,sort:d},m=await Y(a,y=>this.db.collection(e).find({[t]:{$in:y},...u||{}},g).toArray());return{docs:this.applyReadFallback(m,i),groupKeyField:t}}postProcessInverseChild(e,t,n){n||delete e[t]}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=_e(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=e.map(w=>w._id).filter(w=>w!=null),l=new Map;for(let w of e)l.set(this.keyOf(w._id),[]);if(u.length===0)return{grouped:l,docs:[]};let f=await Y(u,w=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:w}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray());if(f.length===0)return{grouped:l,docs:[]};let c=t.userFilter?ue(this.normalizeMetadata(),t.userFilter,t.targetTable):null,p=t.userLimit,d=t.userPage;if(p!==void 0&&p>0){let w=d?(d-1)*p:0,$=await de(u,async R=>{let N=(await this.db.collection(a.junctionName).find({[a.selfColumn]:R},{projection:{_id:0,[a.otherColumn]:1}}).toArray()).map(L=>L[a.otherColumn]).filter(L=>L!=null);if(N.length===0)return[];let v={_id:{$in:N}};if(c&&Object.keys(c).length>0&&Object.assign(v,c),this.hasDottedSort(t.userSort)){let L=this.buildSortAggregatePipeline(t.targetTable,v,t.userSort);w>0&&L.push({$skip:w}),L.push({$limit:p}),o.projection&&L.push({$project:o.projection});let T=await this.db.collection(t.targetTable).aggregate(L).toArray();return this.applyReadFallback(T,o)}let B={sort:this.buildSortFromTokens(t.userSort)||{_id:1}};o.projection&&(B.projection=o.projection);let P=this.db.collection(t.targetTable).find(v,B);return w>0&&P.skip(w),P.limit(p),this.applyReadFallback(await P.toArray(),o)},ee),k=[];for(let[R,_]of $.entries()){l.set(R,_);for(let N of _)k.push(N)}return{grouped:l,docs:k}}let g=new Set,m=[];for(let w of f){let $=w[a.otherColumn];if($==null)continue;let k=this.keyOf($);g.has(k)||(g.add(k),m.push($))}let y=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1&&!c,h=[],b=new Map;if(y)h=m.map(w=>({_id:w})),this.sortDocsByPk(h);else{let w={_id:{$in:m}};c&&Object.keys(c).length>0&&Object.assign(w,c);let $=this.hasDottedSort(t.userSort),k;if($){let R=this.buildSortAggregatePipeline(t.targetTable,w,t.userSort);o.projection&&R.push({$project:o.projection}),k=await this.db.collection(t.targetTable).aggregate(R).toArray()}else{let R=this.buildSortFromTokens(t.userSort)||{_id:1},_=this.projectionWithSortFields(o.projection,t.userSort),N={sort:R};_.projection&&(N.projection=_.projection),k=await Y(m,v=>this.db.collection(t.targetTable).find({_id:{$in:v},...c||{}},N).toArray()),t.userSort?this.sortDocsInMemory(k,t.userSort):this.sortDocsByPk(k),this.removeHiddenFields(k,_.hiddenFields)}h=this.applyReadFallback(k,o)}for(let w of h)b.set(this.keyOf(w._id),w);let S=new Map;for(let w of f){let $=this.keyOf(w[a.selfColumn]),k=this.keyOf(w[a.otherColumn]);b.has(k)&&(S.has(k)||S.set(k,[]),S.get(k).push($))}for(let w of h){let $=S.get(this.keyOf(w._id))||[];for(let k of $)l.get(k)?.push(w)}return{grouped:l,docs:h}}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 an(r,e,t,n,i=3,o=0,s,a,u,l){let f=await l?.getActiveFieldRenamesByTable?.(),c=new tt(r,a,f);await new ke(c,n,u).execute(e,t,i,o,s)}async function Kn(r,e,t){let n=[],{db:i,metadata:o,dbType:s,debugLog:a}=t,u=o?.tables?.get(e.table),l=new Set((u?.relations??[]).map(_=>_.propertyName)),f=!!e.mongoRawFilter&&!!o&&re(e.mongoRawFilter,l),c=e.plan,p=c?.filterTree&&!c.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&o&&f){let _=await fe(e.mongoRawFilter,e.table,o,i);_&&Object.keys(_).length>0&&n.push({$match:_})}else if(p){let _=Ke(c.filterTree,{metadata:o,rootTable:e.table});Object.keys(_).length>0&&n.push({$match:_})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let _=Ge(o,e.where,e.table,s);n.push({$match:_})}let d=e.plan,m=d?d.hasRelationSort:e.sort?.some(_=>{if(!_.field.includes("."))return!1;let N=_.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(v=>v.propertyName===N)??!1})??!1,y=()=>d?.sortItems?Yi(d.sortItems):e.sort?Gi(e.sort):null,h=d?.sortItems?zi(d.sortItems):[],b=()=>{!d||h.length===0||qi(n,e.table,d.sortItems,o)},S=()=>{h.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(h.map(_=>[_,0]))})};if(!e.mongoFieldsExpanded){b();let _=y();if(_&&n.push({$sort:_}),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})),S(),e.select){let v={};for(let I of e.select)v[I]=1;n.push({$project:v})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let N=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:N,pipeline:n}:{results:Er(N),pipeline:n}}let{scalarFields:w,relations:$}=e.mongoFieldsExpanded;if(!m){b();let _=y();_&&n.push({$sort:_}),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 k=[];for(let _ of $)if(e.sort?.some(v=>v.field.startsWith(`${_.propertyName}.`))){let v=e.mongoRawFilter?.[_.propertyName];if(_.nestedFields&&_.nestedFields.length>0){let A=await Ot(o,_.targetTable,_.nestedFields??[],v);_.type==="one"&&A.length>0&&A.push({$limit:1}),n.push({$lookup:{from:_.targetTable,localField:_.localField,foreignField:_.foreignField,as:_.propertyName,pipeline:A.length>0?A:void 0}})}else if(v){let A=await Ot(o,_.targetTable,["_id"],v);_.type==="one"&&A.length>0&&A.push({$limit:1}),n.push({$lookup:{from:_.targetTable,localField:_.localField,foreignField:_.foreignField,as:_.propertyName,pipeline:A.length>0?A:void 0}})}else n.push({$lookup:{from:_.targetTable,localField:_.localField,foreignField:_.foreignField,as:_.propertyName}});_.type==="one"&&(n.push({$unwind:{path:`$${_.propertyName}`,preserveNullAndEmptyArrays:!0}}),v&&(nt(v)||n.push({$match:{[_.propertyName]:{$ne:null}}})))}else k.push(_);if(m){b();let _=y();_&&n.push({$sort:_}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}await Ir(o,n,e.table,w,[...$]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let R=await r.aggregate(n).toArray();if(e.mongoCountOnly)return{results:R,pipeline:n};if(k.length>0&&R.length>0){let _=e.deep||{},N=k.map(I=>{let B=o?.tables?.get(e.table)?.relations?.find(T=>T.propertyName===I.propertyName),P=_[I.propertyName],L=P?.fields!=null?Array.isArray(P.fields)?P.fields:String(P.fields).split(",").map(T=>T.trim()).filter(Boolean):I.nestedFields&&I.nestedFields.length>0?I.nestedFields:["_id"];return{relationName:I.propertyName,type:B?.type,targetTable:I.targetTable,fields:L,isInverse:B?.isInverse,mappedBy:B?.mappedBy,junctionTableName:B?.junctionTableName,localField:I.localField,foreignField:I.foreignField,userFilter:P?.filter,userSort:P?.sort,userLimit:P?.limit!==void 0?Number(P.limit):void 0,userPage:P?.page!==void 0?Number(P.page):void 0,nestedDeep:P?.deep}}),v=Hi(o);v&&await an(i,R,N,v,3,0,e.table,o,void 0,t.mongoPhysicalMigrationService)}return{results:Er(R),pipeline:n}}function Wn(r){return`__sort_count_${r.relationName||r.field}`}function zi(r){return r.filter(e=>e.function==="count").map(Wn)}function qi(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,l=a?.targetTableName||a?.targetTable,f=Wn(s);if(!(!a||!l)){if(a.type==="one-to-many"){let c=U(a)||u;r.push({$lookup:{from:l,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${c}`,"$$localId"]}}},{$count:"value"}],as:f}}),r.push({$addFields:{[f]:{$ifNull:[{$arrayElemAt:[`$${f}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let c=_e(e,a);if(!c)continue;r.push({$lookup:{from:c.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${c.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:f}}),r.push({$addFields:{[f]:{$ifNull:[{$arrayElemAt:[`$${f}.value`,0]},0]}}})}}}}function Hi(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 Gi(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 Yi(r){let e={};for(let t of r){let n=t.function==="count"?Wn(t):t.joinId!==null?t.fullPath:t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function nt(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>nt(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>nt(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>nt(e));if("_not"in r)return nt(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||nt(t)))return!0}return!1}function Er(r){return r.map(ne)}function Pr(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(Xi(o,i,e));return{scalarFields:t,relations:n}}function Xi(r,e,t){let n=e.relations?.find(l=>l.propertyName===r.propertyName),i,o,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&De(n)?(i="_id",o=U(n)||r.propertyName,s=!0):(i=n&&H(n)||r.propertyName,o="_id",s=!1):r.relationType==="one-to-many"?(i="_id",o=n&&U(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=jr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:i,foreignField:o,type:a?"many":"one",isInverse:s,nestedFields:u}}function jr(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=jr(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let i of n)e.push(`${t.propertyName}.${i}`)}return e}Ye();Mt();Nt();function ln(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(c=>c.name==="_id"&&c.isPrimary),a=o.columns?.some(c=>c.name==="id"),u=s&&!a?"_id":"id",l=new Map,f=[];for(let c of r){let p=c==="id"?u:c;if(p==="*")f.push("*");else if(p.includes(".")){let d=p.indexOf("."),g=p.substring(0,d),m=p.substring(d+1);if(!o.relations?.some(h=>h.propertyName===g))continue;l.has(g)||l.set(g,[]),l.get(g).push(m)}else if(o.relations?.some(g=>g.propertyName===p))l.has(p)||l.set(p,[u]);else{if(!o.columns?.some(m=>m.name===p))continue;f.push(p)}}if(f.includes("*")){i.nodes.push({kind:"wildcard"});for(let c of o.relations||[])l.has(c.propertyName)||l.set(c.propertyName,[u])}else for(let c of f)i.nodes.push({kind:"scalar",name:c});for(let[c,p]of l.entries()){let d=o.relations?.find(y=>y.propertyName===c);if(!d)continue;let g=d.targetTableName||d.targetTable,m={kind:"relation",propertyName:c,joinId:null,relationType:d.type,isInverse:!!d.isInverse,targetTable:g,children:Lr(p,g,t)};if(d.type==="many-to-one"||d.type==="one-to-one"){let y=n.registerWithParent(e,c,t,"left",null,"data");m.joinId=y}i.nodes.push(m)}return i}function Lr(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let i=n.columns?.some(f=>f.name==="_id"&&f.isPrimary),o=n.columns?.some(f=>f.name==="id"),s=i&&!o?"_id":"id",a=new Map,u=[];for(let f of r){let c=f==="id"?s:f;if(c==="*")u.push("*");else if(c.includes(".")){let p=c.indexOf("."),d=c.substring(0,p),g=c.substring(p+1);if(!n.relations?.some(y=>y.propertyName===d))continue;a.has(d)||a.set(d,[]),a.get(d).push(g)}else if(n.relations?.some(d=>d.propertyName===c))a.has(c)||a.set(c,[s]);else{if(!n.columns?.some(g=>g.name===c))continue;u.push(c)}}let l=[];if(u.includes("*")){l.push({kind:"wildcard"});for(let f of n.relations||[])a.has(f.propertyName)||a.set(f.propertyName,[s])}else for(let f of u)l.push({kind:"scalar",name:f});for(let[f,c]of a.entries()){let p=n.relations?.find(g=>g.propertyName===f);if(!p)continue;let d=p.targetTableName||p.targetTable;l.push({kind:"relation",propertyName:f,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:d,children:Lr(c,d,t)})}return l}$e();var J=class{plan(e){let{tableName:t,fields:n,filter:i,sort:o,page:s,limit:a,meta:u,metadata:l,dbType:f}=e,c=l?.tables?.get(t),p=new ie,d=this.parseFields(n),g=null;d&&c&&(g=ln(d,t,l,p));let m=!1,y=null;if(i&&c){let I=Te(i,t,l,p);y=I.node,m=I.hasRelationFilters}let h=this.parseSort(o),b=[],S=!1;for(let I of h){let A=I.startsWith("-"),B=A?I.substring(1):I,P=A?"desc":"asc";if(c){let L=this.parseRelationCountSort(t,c,B);if(L){b.push({joinId:null,field:B,direction:P,fullPath:B,function:"count",relationName:L.relationName,relationMeta:L.relationMeta});continue}this.assertLocalSortField(t,c,B)}b.push({joinId:null,field:B,direction:P,fullPath:B})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let w=this.parseLimit(a),$=this.parsePage(s),k=$!==void 0&&w!==void 0?($-1)*w:void 0,R=this.parseMeta(u),_=R.includes("totalCount")||R.includes("*"),N=R.includes("filterCount")||R.includes("*"),v=p.getAll();return{table:t,dbType:f,rawFields:d,rawFilter:i??null,joins:v,sortItems:b,limit:w,offset:k,needsTotalCount:_,needsFilterCount:N,hasRelationFilters:m,hasRelationSort:S,filterTree:y,fieldTree:g}}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 M(`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 M(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationCountSort(e,t,n){if(!n.startsWith("_count"))return null;let i=n.match(/^_count\(([^)]+)\)$/);if(!i)throw new M(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName).`);let o=i[1].trim();if(!o||o.includes("."))throw new M(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let s=t.relations?.find(a=>a.propertyName===o);if(!s)throw new M(`Sort relation '${o}' does not exist on '${e}'.`);if(s.type!=="one-to-many"&&s.type!=="many-to-many")throw new M(`Sort function '_count(${o})' is only supported for list relations on '${e}'.`);return{relationName:o,relationMeta:s}}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),l=n?.tables?.get(t);if(!l)return null;let f=l.relations?.find(d=>d.propertyName===a);if(!f||f.type!=="many-to-one"&&f.type!=="one-to-one")return null;let c=i.registerWithParent(t,a,n,"left",o,"sort");if(!c)return null;if(!u.includes("."))return{lastJoinId:c,field:u};let p=f.targetTableName||f.targetTable;return this.registerSortJoinChain(u,p,n,i,c)}};$e();vt();var Zi=new Set(["count","sum","avg","min","max","countRecords"]),eo=new Set(["int","integer","bigint","float","double","decimal","numeric","real","number"]),to=new Set(["_and","_or","_not"]);function Ce(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function E(r,e){let t=r.replace(/^aggregate\./,"");throw new M(e,{path:r,aggregate:{[t]:e}})}function no(r){return typeof r!="string"?!1:eo.has(r.toLowerCase())}function Dr(r){return Object.keys(r).length===0}function ro(r,e,t){return r===!0?{}:(r==null&&E(t,`aggregate.${e} condition must be true or an object`),Ce(r)||E(t,`aggregate.${e} condition must be true or an object`),r)}function io(r,e,t){let n=r?.tables?.get(e);return n||E(t,`Table "${e}" metadata is not available`),n}function Br(r,e){let t=r?.targetTableName??r?.targetTable;return(typeof t!="string"||t.length===0)&&E(e,"aggregate.countRecords relation target is not available"),t}function cn(r,e,t,n){let i=io(t,e,n);for(let[o,s]of Object.entries(r)){if(o==="_and"||o==="_or"){Array.isArray(s)||E(n,`aggregate.countRecords ${o} condition must be an array`);for(let f of s)Ce(f)||E(n,`aggregate.countRecords ${o} items must be objects`),cn(f,e,t,n);continue}if(o==="_not"){Ce(s)||E(n,"aggregate.countRecords _not condition must be an object"),cn(s,e,t,n);continue}(o.startsWith("_")||to.has(o))&&E(n,`Unsupported aggregate.countRecords condition key "${o}"`);let a=i.columns?.find(f=>f.name===o),u=i.relations?.find(f=>f.propertyName===o);if(!a&&!u&&E(n,`Unknown aggregate.countRecords field or relation "${o}" on table "${e}"`),Ce(s)||E(n,`aggregate.countRecords condition for "${o}" must be an object`),a){for(let f of Object.keys(s))Z.has(f)||E(n,`aggregate.countRecords condition for "${o}" only supports field operators`);continue}let l=Br(u,n);cn(s,l,t,n)}}function Un(r){return Ce(r)&&Object.keys(r).length>0}function rt(r,e,t){if(!Un(r))return[];Ce(r)||E("aggregate","aggregate must be an object");let n=t?.tables?.get(e);n||E("aggregate",`Table "${e}" metadata is not available`);let i=[];for(let[o,s]of Object.entries(r)){let a=`aggregate.${o}`;(!o||typeof o!="string")&&E("aggregate","aggregate field name must be a non-empty string"),Ce(s)||E(a,"aggregate field config must be an object");let u=o,l=a,f=n.columns?.find(d=>d.name===o),c=n.relations?.find(d=>d.propertyName===o);!f&&!c&&E(l,`Unknown aggregate field or relation "${o}" on table "${e}"`);let p=Object.entries(s).filter(([d])=>d!=="as");p.length===0&&E(l,"aggregate field must define at least one operation");for(let[d,g]of p){Zi.has(d)||E(l,`Unsupported aggregate operation "${d}"`);let m=ro(g,d,l);if(c&&d!=="countRecords"&&E(l,`aggregate.${d} is not supported on relation "${o}"; use countRecords`),f&&d==="countRecords"&&E(l,`aggregate.countRecords requires a relation, but "${o}" is a field`),f&&(d==="sum"||d==="avg")&&!no(f.type)&&E(l,`aggregate.${d} requires a numeric field, but "${o}" is "${f.type}"`),f)for(let y of Object.keys(m))Z.has(y)||E(l,`aggregate.${d} condition for "${o}" only supports field operators`);if(c&&d==="countRecords"){let y=Br(c,l);cn(m,y,t,l)}i.push({field:o,outputKey:u,path:l,op:d,condition:m})}}return i}function it(r,e){let t=[];return Ce(r)&&!Dr(r)&&t.push(r),Dr(e.condition)||t.push({[e.field]:e.condition}),t.length===0?{}:t.length===1?t[0]:{_and:t}}function Fe(r,e,t){r[e.outputKey]??={},r[e.outputKey][e.op]=t}var ot=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 p=new J;e={...e,plan:p.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:"mongodb"})}}let t=e.debugLog||[];this.debugLog=t;let n={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};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(p=>p.trim()))),e.filter&&(Q(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let p=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(d=>d.trim());n.sort=p.map(d=>{let g=d.trim();return g.startsWith("-")?{field:g.substring(1),direction:"desc"}:{field:g,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let p=typeof e.page=="string"?parseInt(e.page,10):e.page,d=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(p-1)*d,n.limit=d}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(p=>p.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(p=>p.propertyName)),l=!!n.mongoRawFilter&&re(n.mongoRawFilter,u);if((i.includes("filterCount")||i.includes("*"))&&!l){let p=this.mongoService.collection(e.tableName),d=e.plan?.filterTree?Ke(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await p.countDocuments(d)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let f=await this.selectLegacy(n);if(e.debugMode){let p=this.lastBuiltPipeline??[],d;try{d=await this.db.collection(e.tableName).aggregate(p).explain()}catch(g){d={error:String(g)}}return{pipeline:p,explain:d}}if(l&&(i.includes("filterCount")||i.includes("*"))){let p={...n,mongoCountOnly:!0},d=await this.selectLegacy(p);s=d.length>0?d[0].count:0}let c=await this.executeAggregate(n,e.filter);return{data:f,...(i.length>0||c)&&{meta:{...i.includes("totalCount")||i.includes("*")?{totalCount:o}:{},...i.includes("filterCount")||i.includes("*")?{filterCount:s}:{},...c?{aggregate:c}:{}}}}}async selectLegacy(e){let t=[];if(e.fields&&e.fields.length>0){let s=e.plan;if(s?.fieldTree?e.mongoFieldsExpanded=Pr(s.fieldTree,this.metadata):(console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await zt(this.metadata,e.table,e.fields)),this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let a=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:a.scalarFields},t=a.hiddenFields}}e.where&&(e.where=e.where.map(s=>s.field.includes(".")?s:{...s,field:`${e.table}.${s.field}`}));let n=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 n.aggregate(e.pipeline).toArray()).map(ne);let{results:i,pipeline:o}=await Kn(n,e,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=o,this.mongoPhysicalMigrationService?await this.mongoPhysicalMigrationService.applyReadFallback(e.table,i,t):i}async executeAggregationPipeline(e,t){let{results:n,pipeline:i}=await Kn(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=i,n}async executeAggregate(e,t){let n=rt(e.aggregate,e.table,e.metadata);if(n.length===0)return;let i={},o=this.db.collection(e.table);for(let s of n){let a=it(t,s);Q(a,e.table,e.metadata);let l=new J().plan({tableName:e.table,filter:a,metadata:e.metadata,dbType:"mongodb"});if(s.op==="countRecords"){let p=await this.executeRelationCountRecords(e,t,s);Fe(i,s,p);continue}let f=l.hasRelationFilters?await fe(a,e.table,e.metadata,this.db):l.filterTree?Ke(l.filterTree,{metadata:e.metadata,rootTable:e.table}):{},c;if(s.op==="count")c=await o.countDocuments(f);else{let[{value:p}={value:null}]=await o.aggregate([{$match:f},{$group:{_id:null,value:{[`$${s.op}`]:`$${s.field}`}}}]).toArray();c=p??0}Fe(i,s,c)}return i}async executeRelationCountRecords(e,t,n){let o=e.metadata?.tables?.get(e.table)?.relations?.find(f=>f.propertyName===n.field),s=o?.targetTableName||o?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!o||!s||!a)return 0;let u=await this.resolveMatchFilter(e.table,t,e.metadata),l=await this.resolveMatchFilter(s,n.condition,e.metadata);if(o.type==="one-to-many"){let c=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(p=>p._id).filter(p=>p!=null);return c.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{[o.foreignKeyColumn]:{$in:c}}]})}if(o.type==="many-to-many"){let f=_e(e.table,o);if(!f)return 0;let p=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(m=>m._id).filter(m=>m!=null);if(p.length===0)return 0;let g=(await this.db.collection(f.junctionName).find({[f.selfColumn]:{$in:p}},{projection:{[f.otherColumn]:1}}).toArray()).map(m=>m[f.otherColumn]).filter(m=>m!=null);return g.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:g}}]})}if(o.type==="many-to-one"||o.type==="one-to-one"){let f=o.foreignKeyColumn||`${n.field}Id`,p=(await this.db.collection(e.table).find(u,{projection:{[f]:1}}).toArray()).map(d=>d[f]).filter(d=>d!=null);return p.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:p}}]})}return 0}async resolveMatchFilter(e,t,n){if(!t||Object.keys(t).length===0)return{};Q(t,e,n);let o=new J().plan({tableName:e,filter:t,metadata:n,dbType:"mongodb"});return o.hasRelationFilters?await fe(t,e,n,this.db):o.filterTree?Ke(o.filterTree,{metadata:n,rootTable:e}):{}}};var un=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}};$e();var oo=["_and","_or","_not"];function pe(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>pe(e));for(let e of Object.keys(r))if(oo.includes(e)||typeof r[e]=="object"&&r[e]!==null&&pe(r[e]))return!0;return!1}var Kr=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function so(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function fn(r,e,t){if(!t)return!1;let n=r;if(r.includes(".")){let s=r.split(".");n=s[s.length-1]}let i=t.columns.find(s=>s.name===n);if(!i)return!1;let o=i.type?.toLowerCase()||"";return o==="uuid"||o==="uuidv4"||o.includes("uuid")}function ao(r,e,t,n,i){return n!=="postgres"||typeof e!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||fn(r,t,i),e}function Wr(r,e,t,n,i,o,s){let a=i&&!e.includes(".")?`${i}.${e}`:e,u=fn(e,i,s),l=ao(e,n,i,o,s);switch(t){case"_eq":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} = ?::uuid`,[n]):r.where(a,"=",l);break;case"_neq":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} != ?::uuid`,[n]):r.where(a,"!=",l);break;case"_gt":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} > ?::uuid`,[n]):r.where(a,">",l);break;case"_gte":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} >= ?::uuid`,[n]):r.where(a,">=",l);break;case"_lt":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} < ?::uuid`,[n]):r.where(a,"<",l);break;case"_lte":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} <= ?::uuid`,[n]):r.where(a,"<=",l);break;case"_in":let f=n;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]),u&&o==="postgres"&&f.every(p=>typeof p=="string")?r.whereRaw(`${a} = ANY(?::uuid[])`,[f]):r.whereIn(a,f);break;case"_not_in":case"_nin":let c=n;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(p=>p.trim()):[c]),u&&o==="postgres"&&c.every(p=>typeof p=="string")?r.whereRaw(`${a} != ALL(?::uuid[])`,[c]):r.whereNotIn(a,c);break;case"_contains":o==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${a}) LIKE '%' || lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${a})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_starts_with":o==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${a}) LIKE lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${a})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_ends_with":o==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE '%' || lower(unaccent(?))`,[n]):o==="sqlite"?r.whereRaw(`lower(${a}) LIKE '%' || lower(?)`,[n]):r.whereRaw(`lower(unaccent(${a})) 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,so(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 st(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(){st(this,s,t,"and",i,o)}):r.orWhere(function(){st(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(){st(this,u,t,"and",i,o)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){st(this,u,t,"and",i,o)})});continue}if(s==="_not"){r.whereNot(function(){st(this,a,t,"and",i,o)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(l=>Kr.includes(l)))for(let[l,f]of Object.entries(a))Kr.includes(l)&&(n==="and"?r.where(function(){Wr(this,s,l,f,t,i,o)}):r.orWhere(function(){Wr(this,s,l,f,t,i,o)}));else{let l=t&&!s.includes(".")?`${t}.${s}`:s;fn(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(`${l} = ?::uuid`,[a]):r.orWhereRaw(`${l} = ?::uuid`,[a]):n==="and"?r.where(l,"=",a):r.orWhere(l,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s;fn(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(`${u} = ?::uuid`,[a]):r.orWhereRaw(`${u} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function se(r,e,t,n,i){return!e||typeof e!="object"||st(r,e,t,"and",n,i),r}xe();function Vn(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 Ur(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 at(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function zn(r,e,t,n,i,o){let s=[];for(let[a,u]of Object.entries(o)){let l=await Et(r,e,a,u,t,n,i);if(l!==null)s.push(`EXISTS (${l})`);else{let f=t.relations.find(c=>c.propertyName===a);if(f&&f.foreignKeyColumn){let c=Vn(e,f.foreignKeyColumn,n),d=u.id;if(d&&typeof d=="object"){let g=at(d._is_null),m=at(d._is_not_null);if(g===!0)s.push(`${c} IS NULL`);else if(g===!1)s.push(`${c} IS NOT NULL`);else if(m===!0)s.push(`${c} IS NOT NULL`);else if(m===!1)s.push(`${c} IS NULL`);else if(d._eq!==void 0){let y=Re(d._eq,n);s.push(`${c} = ${y}`)}else if(d._neq!==void 0){let y=Re(d._neq,n);s.push(`${c} != ${y}`)}else if(d._in!==void 0){let h=(Array.isArray(d._in)?d._in:[d._in]).map(b=>Re(b,n)).join(", ");s.push(`${c} IN (${h})`)}else if(d._not_in!==void 0||d._nin!==void 0){let y=d._not_in??d._nin,b=(Array.isArray(y)?y:[y]).map(S=>Re(S,n)).join(", ");s.push(`${c} NOT IN (${b})`)}else if(d._gt!==void 0){let y=Re(d._gt,n);s.push(`${c} > ${y}`)}else if(d._gte!==void 0){let y=Re(d._gte,n);s.push(`${c} >= ${y}`)}else if(d._lt!==void 0){let y=Re(d._lt,n);s.push(`${c} < ${y}`)}else if(d._lte!==void 0){let y=Re(d._lte,n);s.push(`${c} <= ${y}`)}}}}}return s}function qn(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 Qn(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 l of a._and)if(qn(l)){let f=e(t).select(`${t}.id`);await We(e,f,l,t,n,i,o),u.push({idSubquery:f})}else{let{fieldFilters:f,relationFilters:c}=G(l,n),p=await zn(e,t,n,i,o,c);u.push({fieldFilters:f,subqueries:p})}s.push(u)}else if(qn(a)){let u=e(t).select(`${t}.id`);await We(e,u,a,t,n,i,o),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:l}=G(a,n),f=await zn(e,t,n,i,o,l);s.push([{fieldFilters:u,subqueries:f}])}return s}function Qr(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&&se(this,o.fieldFilters,t,i,n);for(let s of o.subqueries)this.whereRaw(s)})}function Jn(r,e,t,n,i){let o=!0;for(let s of e){let a=function(){for(let u of s)Qr(this,u,t,n,i)};o?(r.where(a),o=!1):r.orWhere(a)}}function dn(r,e,t,n,i,o,s){let a=Ur(e,i),u=Ur(n,o),l=`${F(r,s)}.${F(e,s)}`,f=`${F(t,s)}.${F(n,s)}`;if(s==="postgres"){if(a&&!u)return`${l} = ${f}::uuid`;if(!a&&u)return`${l}::uuid = ${f}`}return`${l} = ${f}`}async function Et(r,e,t,n,i,o,s){let a=i.relations.find(p=>p.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 l=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 p=Object.keys(n||{});if(p.length===1&&p[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(g=>l.has(g)))return null}let f=s?await s(u):null,c;switch(a.type){case"one-to-many":c=r(u).select(r.raw("1")).whereRaw(dn(u,a.foreignKeyColumn,e,"id",f,i,o));break;case"many-to-many":let p=s?await s(a.junctionTableName):null;c=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw(dn(a.junctionTableName,a.junctionTargetColumn,u,"id",p,f,o))).whereRaw(dn(a.junctionTableName,a.junctionSourceColumn,e,"id",p,i,o));break;case"many-to-one":case"one-to-one":c=r(u).select(r.raw("1")).whereRaw(dn(u,"id",e,a.foreignKeyColumn,f,i,o));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?f?await We(r,c,n,u,f,o,s):c=se(c,n,u,o,f||void 0):c=se(c,n,u,o),c.toString()}async function We(r,e,t,n,i,o,s){if(!t||typeof t!="object")return;if(t._and&&Array.isArray(t._and)){for(let l of t._and)if(l._or&&Array.isArray(l._or)&&l._or.length>0){let f=await Qn(l._or,r,n,i,o,s);e.where(function(){Jn(this,f,n,i,o)})}else if(l._and&&Array.isArray(l._and)&&l._and.length>0)for(let f of l._and)await We(r,e,f,n,i,o,s);else await We(r,e,l,n,i,o,s);return}if(t._or&&Array.isArray(t._or)){let l=await Qn(t._or,r,n,i,o,s);e.where(function(){Jn(this,l,n,i,o)});return}if(t._not){let l=t._not;if(l._and&&Array.isArray(l._and)&&l._and.length>0){let p=[];for(let d of l._and)if(qn(d)){let g=r(n).select(`${n}.id`);await We(r,g,d,n,i,o,s),p.push({idSubquery:g})}else{let{fieldFilters:g,relationFilters:m}=G(d,i),y=await zn(r,n,i,o,s,m);p.push({fieldFilters:g,subqueries:y})}e.whereNot(function(){for(let d of p)Qr(this,d,n,i,o)});return}if(l._or&&Array.isArray(l._or)&&l._or.length>0){let p=await Qn(l._or,r,n,i,o,s);e.whereNot(function(){Jn(this,p,n,i,o)});return}let{fieldFilters:f,relationFilters:c}=G(l,i);e.whereNot(function(){Object.keys(f).length>0&&se(this,f,n,o,i)});for(let[p,d]of Object.entries(c)){let g=await Et(r,n,p,d,i,o,s);if(g===null){let m=i.relations.find(y=>y.propertyName===p);if(m&&m.foreignKeyColumn){let y=Vn(n,m.foreignKeyColumn,o),b=d.id;if(b&&typeof b=="object"){let S=at(b._is_null),w=at(b._is_not_null);if(S===!0)e.whereRaw(`${y} IS NOT NULL`);else if(S===!1)e.whereRaw(`${y} IS NULL`);else if(w===!0)e.whereRaw(`${y} IS NULL`);else if(w===!1)e.whereRaw(`${y} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${y} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${y} = ?`,[b._neq]);else if(b._in!==void 0){let $=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${y} NOT IN (${$.map(()=>"?").join(", ")})`,$)}else if(b._not_in!==void 0||b._nin!==void 0){let $=b._not_in??b._nin,k=Array.isArray($)?$:[$];e.whereRaw(`${y} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${g})`)}return}let{fieldFilters:a,relationFilters:u}=G(t,i);Object.keys(a).length>0&&se(e,a,n,o,i);for(let[l,f]of Object.entries(u)){let c=await Et(r,n,l,f,i,o,s);if(c===null){let p=i.relations.find(d=>d.propertyName===l);if(p&&p.foreignKeyColumn){let d=Vn(n,p.foreignKeyColumn,o),m=f.id;if(m&&typeof m=="object"){let y=at(m._is_null),h=at(m._is_not_null);if(y===!0)e.whereRaw(`${d} IS NULL`);else if(y===!1)e.whereRaw(`${d} IS NOT NULL`);else if(h===!0)e.whereRaw(`${d} IS NOT NULL`);else if(h===!1)e.whereRaw(`${d} IS NULL`);else if(m._eq!==void 0)e.whereRaw(`${d} = ?`,[m._eq]);else if(m._neq!==void 0)e.whereRaw(`${d} != ?`,[m._neq]);else if(m._in!==void 0){let b=Array.isArray(m._in)?m._in:[m._in];e.whereRaw(`${d} IN (${b.map(()=>"?").join(", ")})`,b)}else if(m._not_in!==void 0||m._nin!==void 0){let b=m._not_in??m._nin,S=Array.isArray(b)?b:[b];e.whereRaw(`${d} NOT IN (${S.map(()=>"?").join(", ")})`,S)}}}}else e.whereRaw(`EXISTS (${c})`)}}async function Ue(r,e,t,n,i,o,s){await We(r,e,t,n,i,o,s)}xe();Gn();Ye();xe();function lt(r,e,t,n,i){for(let o of e){let s=o.field.split("."),a=t||s[0],u=s[s.length-1],l=Pt(n,a,u,o.value);switch(o.operator){case"=":r=r.where(o.field,"=",l);break;case"!=":r=r.where(o.field,"!=",l);break;case">":r=r.where(o.field,">",l);break;case"<":r=r.where(o.field,"<",l);break;case">=":r=r.where(o.field,">=",l);break;case"<=":r=r.where(o.field,"<=",l);break;case"like":r=r.where(o.field,"like",l);break;case"in":let f=Array.isArray(o.value)?o.value.map(m=>Pt(n,a,u,m)):[l];r=r.whereIn(o.field,f);break;case"not in":let c=Array.isArray(o.value)?o.value.map(m=>Pt(n,a,u,m)):[l];r=r.whereNotIn(o.field,c);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 p=o.value;if(typeof p=="string"&&(p=p.split(",").map(m=>m.trim())),Array.isArray(p)&&p.length===2){let m=Pt(n,a,u,p[0]),y=Pt(n,a,u,p[1]);r=r.whereBetween(o.field,[m,y])}break;case"_is_null":r=l===!0||l==="true"?r.whereNull(o.field):r.whereNotNull(o.field);break;case"_is_not_null":r=l===!0||l==="true"?r.whereNotNull(o.field):r.whereNull(o.field);break}}return r}function jt(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(l=>{let f=jt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&i.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(l=>{let f=jt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&i.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=jt(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,l]of Object.entries(a)){let f=`${F(e,n)}.${F(s,n)}`,c;if(l===null)c="NULL";else if(typeof l=="string"){let p=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,d=o.columns?.find(m=>m.name===s);d&&(d.type?.toLowerCase()==="uuid"||d.type?.toLowerCase().includes("uuid"))&&p.test(l)&&n==="postgres"?c=`'${l}'::uuid`:c=`'${l.replace(/'/g,"''")}'`}else typeof l=="boolean"?c=l?"true":"false":typeof l=="number"?c=String(l):c=`'${String(l).replace(/'/g,"''")}'`;if(u==="_eq")i.push(`${f} = ${c}`);else if(u==="_neq")i.push(`${f} != ${c}`);else if(u==="_gt")i.push(`${f} > ${c}`);else if(u==="_gte")i.push(`${f} >= ${c}`);else if(u==="_lt")i.push(`${f} < ${c}`);else if(u==="_lte")i.push(`${f} <= ${c}`);else if(u==="_is_null")i.push(`${f} IS NULL`);else if(u==="_is_not_null")i.push(`${f} IS NOT NULL`);else if(u==="_in"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");i.push(`${f} IN (${d})`)}else if(u==="_not_in"||u==="_nin"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");i.push(`${f} NOT IN (${d})`)}else if(u==="_contains"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${f}) LIKE '%${p.toLowerCase()}%'`)}else if(u==="_starts_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${f})) ILIKE lower(unaccent('${p}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${f}) LIKE '${p.toLowerCase()}%'`)}else if(u==="_ends_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}'))`):n==="mysql"?i.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci)`):i.push(`lower(${f}) LIKE '%${p.toLowerCase()}'`)}else if(u==="_between"&&Array.isArray(l)&&l.length===2){let p=typeof l[0]=="string"?`'${l[0].replace(/'/g,"''")}'`:String(l[0]),d=typeof l[1]=="string"?`'${l[1].replace(/'/g,"''")}'`:String(l[1]);i.push(`${f} BETWEEN ${p} AND ${d}`)}}else{let u=`${F(e,n)}.${F(s,n)}`,l;a===null?l="NULL":typeof a=="string"?l=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?l=a?"true":"false":l=String(a),i.push(`${u} = ${l}`)}return i}function Vr(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 Pt(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}}xe();Lt();ze();async function qr(r,e,t,n,i,o,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(Xn(),zr)),u=await a(e,t,n,i,o,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function Zn(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 Hr(r,e,t,n,i){let o=r.targetTableName||r.targetTable;if(!o)return null;let s=r.foreignKeyColumn||K(r.propertyName);if(!s)return null;let a=c=>F(c,i),u=n?.tables?.get(o),f=(u?te(u):null)?.name||"id";return`(SELECT ${a(o)}.${a(e)} FROM ${a(o)} WHERE ${a(o)}.${a(f)} = ${a(t)}.${a(s)})`}Lt();var ut=class r{constructor(e,t,n,i){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=i;this.logger=new un(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&&Q(e.filter,e.tableName,e.metadata),!e.plan){let T=new J;e={...e,plan:T.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,l=o.rawFields&&o.rawFields.length>0&&!o.rawFields.includes("*");if(o.joins.length===0&&!o.hasRelationFilters&&!o.hasRelationSort&&!u&&!a&&l){i&&i.setQueryPath("simple");let T=await this.executeSimple(e,o);return i&&i.dur("sql_executor",t,{table:e.tableName}),T}let c={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?c.fields=e.fields:typeof e.fields=="string"&&(c.fields=e.fields.split(",").map(T=>T.trim())));let p=e.filter;if(e.filter&&!pe(e.filter)){c.where=[];for(let[T,C]of Object.entries(e.filter))if(typeof C=="object"&&C!==null)for(let[x,ae]of Object.entries(C)){let O;if(x==="_eq")O="=";else if(x==="_neq")O="!=";else if(x==="_in")O="in";else if(x==="_not_in"||x==="_nin")O="not in";else if(x==="_gt")O=">";else if(x==="_gte")O=">=";else if(x==="_lt")O="<";else if(x==="_lte")O="<=";else if(x==="_contains")O="_contains";else if(x==="_starts_with")O="_starts_with";else if(x==="_ends_with")O="_ends_with";else if(x==="_between")O="_between";else if(x==="_is_null")O="_is_null";else if(x==="_is_not_null")O="_is_not_null";else if(x==="_like")O="like";else if(x==="_ilike")O="ilike";else continue;c.where.push({field:T,operator:O,value:ae})}else c.where.push({field:T,operator:"=",value:C})}if(e.sort){let T=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(C=>C.trim());c.sort=T.map(C=>{let x=C.trim();return x.startsWith("-")?{field:x.substring(1),direction:"desc"}:{field:x,direction:"asc"}})}else c.sort=[{field:"id",direction:"asc"}];let d=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,g=d===void 0||Number.isNaN(d)?void 0:d<0?0:d,m=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,y=m===void 0||Number.isNaN(m)?void 0:m;y&&g!==void 0?(c.offset=(y-1)*g,c.limit=g):g!==void 0&&(c.limit=g);let h=e.plan?.sortItems??(c.sort??[]).map(T=>({joinId:null,field:T.field,direction:T.direction,fullPath:T.field})),b=[],S=[];for(let T of h){if(T.function==="count"){let C={sql:this.buildRelationCountSortSubquery(c.table,T),direction:T.direction};S.push(C);continue}if(T.joinId===null){if(T.field.includes(".")&&!e.plan){let x=T.field.split(".")[0];if(this.metadata?.tables?.get(c.table)?.relations?.some(V=>V.propertyName===x))continue}let C={field:T.field.includes(".")?T.field:`${c.table}.${T.field}`,direction:T.direction};b.push(C),S.push(C)}else{let C=e.plan?.joins.find(x=>x.id===T.joinId);if(C&&(C.relationType==="many-to-one"||C.relationType==="one-to-one")){let x=Hr(C.relationMeta,T.field,c.table,this.metadata,this.dbType);if(x){let ae={sql:x,direction:T.direction};S.push(ae)}}}}let w=[];if(c.fields&&c.fields.length>0){let T=Zn(this.metadata),C=await qr(this.knex,c.table,c.fields,T,this.dbType,this.maxQueryDepth,e.deep);c.select=[...c.select||[],...C.select],w=C.batchFetchDescriptors||[]}c.where&&(c.where=c.where.map(T=>T.field.includes(".")?T:{...T,field:`${c.table}.${T.field}`})),c.sort=b;let $=this.knex(c.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(T=>T.trim()).filter(Boolean),R=k.includes("filterCount")||k.includes("*"),_=k.includes("totalCount")||k.includes("*");if(c.select){let T=c.select.map(C=>typeof C=="string"&&C.trim().startsWith("(")?this.knex.raw(C):typeof C=="string"&&/ as /i.test(C)?this.knex.raw(C):C);$=$.select(T)}if(R&&$.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),_){let T=F(c.table,this.dbType);$.select(this.knex.raw(`(SELECT COUNT(*) FROM ${T}) as __total_count__`))}let N=["table_definition","column_definition","relation_definition","method_definition"].includes(c.table);if(p&&(pe(p)||Object.keys(p).length>0)){let T=this.metadata?.tables?.get(c.table);(!N&&T&&T.relations&&T.relations.length>0?G(p,T).hasRelations:!1)?await Ue(this.knex,$,p,c.table,T,this.dbType,x=>this.metadata?.tables?.get(x)):e.plan?.filterTree?X($,e.plan.filterTree,{dbType:this.dbType,rootTable:c.table}):(this.logger.debug(`buildWhereClause fallback for table=${c.table}`),$=se($,p,c.table,this.dbType,T))}else c.where&&c.where.length>0&&($=lt($,c.where,c.table,this.metadata,this.dbType));for(let T of S)if(T.field){let C=T.field.includes(".")?T.field:`${c.table}.${T.field}`;$=$.orderBy(C,T.direction)}else T.sql&&($=$.orderByRaw(`${T.sql} ${T.direction.toUpperCase()}`));c.groupBy&&($=$.groupBy(c.groupBy)),c.offset&&($=$.offset(c.offset)),c.limit!==void 0&&c.limit!==null&&c.limit>0&&($=$.limit(c.limit));let v=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:c.table,sql:$.toSQL().toNative()});let I;if(e.debugMode&&(I=$.toSQL().toNative().sql),e.debugMode&&i){let T=$.toSQL().toNative();i.setSql(T.sql);try{let C=T.sql.replace(/\$\d+/g,"?"),x=await this.knex.raw(`EXPLAIN ${C}`,T.bindings);i.setExplain(this.dbType==="postgres"?x.rows:x[0])}catch(C){i.setExplain({error:String(C)})}}let A,B=performance.now();A=await $,i&&i.dur("db_execute",B,{table:e.tableName});let P=0;if(R&&A.length>0&&(P=Number(A[0].__filter_count__||0),A.forEach(T=>{delete T.__filter_count__})),_&&A.length>0&&A[0].__total_count__!==void 0&&(v=Number(A[0].__total_count__||0),A.forEach(T=>{delete T.__total_count__})),w&&w.length>0&&A.length>0){let T=Zn(this.metadata);if(T){let{executeBatchFetches:C}=await Promise.resolve().then(()=>(nr(),Gr));await C(this.knex,A,w,T,this.maxQueryDepth??3,0,c.table,this.dbType,this.metadata,i)}}if(this.knexService){let T=performance.now();A=await this.knexService.parseResult(A,c.table),i&&i.dur("db_parseResult",T,{table:e.tableName})}else{let T=(C,x)=>{if(!C||!this.metadata)return C;let ae=this.metadata.tables?.get(x);if(!ae)return C;if(Array.isArray(C))return C.map(V=>T(V,x));if(typeof C!="object"||Buffer.isBuffer(C))return C;let O={...C};for(let V of ae.columns)if(V.type==="simple-json"&&O[V.name]&&typeof O[V.name]=="string")try{O[V.name]=JSON.parse(O[V.name])}catch{}for(let[V,q]of Object.entries(O))if(q&&typeof q=="object"&&!Array.isArray(q)&&!Buffer.isBuffer(q)){let hn=q;if(hn.id!==void 0||hn.createdAt!==void 0){let dt=ae.relations?.find(pt=>pt.propertyName===V);dt&&(O[V]=T(q,dt.targetTableName))}}else if(Array.isArray(q)&&q.length>0&&typeof q[0]=="object"&&q[0].id!==void 0){let dt=ae.relations?.find(pt=>pt.propertyName===V);dt&&(O[V]=q.map(pt=>T(pt,dt.targetTableName)))}return O};A=T(A,c.table)}i&&(i.setQueryPath("full"),i.dur("sql_executor",t,{table:e.tableName}));let L=await this.executeAggregate(c,p);return{data:A,...(k.length>0||L)&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:v}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:P}:{},...L?{aggregate:L}:{}}},...I!==void 0&&{sql:I}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=te(s)?.name||"id",u=F(e,this.dbType),l=F(a,this.dbType);if(!n||!o)throw new M(`Sort relation '${i}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let f=n.foreignKeyColumn||n.mappedBy;if(!f)throw new M(`Sort function '_count(${i})' cannot resolve relation key on '${e}'.`);let c=F(o,this.dbType),p=F(f,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}if(n.type==="many-to-many"){let f=this.resolveManyToManyContract(n,i,e),c=F(f.tableName,this.dbType),p=F(f.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}throw new M(`Sort function '_count(${i})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,n){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new M(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async executeSimple(e,t){let n=e.tableName,i=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],o=this.knex(n).select(i);t.filterTree&&X(o,t.filterTree,{dbType:this.dbType,rootTable:n});for(let y of t.sortItems){let h=y.field.includes(".")?y.field:`${n}.${y.field}`;o=o.orderBy(h,y.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(y=>y.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 y=F(n,this.dbType);o.select(this.knex.raw(`(SELECT COUNT(*) FROM ${y}) as __total_count__`))}let l=e.debugTrace,f;if(e.debugMode){let y=o.toSQL().toNative();if(f=y.sql,l){l.setSql(y.sql);try{let h=y.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${h}`,y.bindings);l.setExplain(this.dbType==="postgres"?b.rows:b[0])}catch(h){l.setExplain({error:String(h)})}}}let c=performance.now(),p;p=await o,l&&l.dur("db_execute",c,{table:n}),this.knexService&&(p=await this.knexService.parseResult(p,n));let d=0,g=0;a&&p.length>0&&(d=Number(p[0].__filter_count__||0),p.forEach(y=>delete y.__filter_count__)),u&&p.length>0&&(g=Number(p[0].__total_count__||0),p.forEach(y=>delete y.__total_count__));let m=await this.executeAggregate({table:n,aggregate:e.aggregate,metadata:e.metadata},e.filter);return{data:p,...(s.length>0||m)&&{meta:{...u?{totalCount:g}:{},...a?{filterCount:d}:{},...m?{aggregate:m}:{}}},...f!==void 0&&{sql:f}}}async executeAggregate(e,t){let n=rt(e.aggregate,e.table,e.metadata);if(n.length===0)return;let i={};for(let o of n){let s=it(t,o);Q(s,e.table,e.metadata);let u=new J().plan({tableName:e.table,filter:s,metadata:e.metadata,dbType:this.dbType});if(o.op==="countRecords"){let d=await this.executeRelationCountRecords(e,t,o);Fe(i,o,d);continue}let l=this.knex(e.table);if(u.hasRelationFilters){let d=e.metadata?.tables?.get(e.table);await Ue(this.knex,l,s,e.table,d,this.dbType,g=>e.metadata?.tables?.get(g))}else u.filterTree&&X(l,u.filterTree,{dbType:this.dbType,rootTable:e.table});let f=`${F(e.table,this.dbType)}.${F(o.field,this.dbType)}`,c=o.op==="count"?this.knex.raw("COUNT(*) as value"):this.knex.raw(`${o.op.toUpperCase()}(${f}) as value`),p=await l.clearSelect().select(c).first();Fe(i,o,p?.value??0)}return i}async executeRelationCountRecords(e,t,n){let i=e.metadata?.tables?.get(e.table),o=i?.relations?.find(c=>c.propertyName===n.field),s=o?.targetTableName||o?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!o||!s||!a)return 0;let u=this.knex(e.table).select(`${e.table}.id`);if(t&&Object.keys(t).length>0){let p=new J().plan({tableName:e.table,filter:t,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Ue(this.knex,u,t,e.table,i,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&X(u,p.filterTree,{dbType:this.dbType,rootTable:e.table})}let l=this.knex(s).count("* as value");if(n.condition&&Object.keys(n.condition).length>0){Q(n.condition,s,e.metadata);let p=new J().plan({tableName:s,filter:n.condition,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Ue(this.knex,l,n.condition,s,a,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&X(l,p.filterTree,{dbType:this.dbType,rootTable:s})}if(o.type==="one-to-many")l.whereIn(`${s}.${o.foreignKeyColumn}`,u);else if(o.type==="many-to-many"){let c=this.resolveManyToManyContract(o,n.field,e.table);l.whereIn(`${s}.id`,this.knex(c.tableName).select(`${c.tableName}.${c.targetColumn}`).whereIn(`${c.tableName}.${c.sourceColumn}`,u))}else(o.type==="many-to-one"||o.type==="one-to-one")&&l.whereIn(`${s}.id`,function(){this.select(`${e.table}.${o.foreignKeyColumn}`).from(e.table),t&&Object.keys(t).length>0&&this.whereIn(`${e.table}.id`,u),this.whereNotNull(`${e.table}.${o.foreignKeyColumn}`)});let f=await l.first();return Number(f?.value??0)}};var gn=require("mongodb"),ft=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()}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(!gn.ObjectId)return e;if(typeof e=="string")try{return new gn.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=Ge(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:lt(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(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(ne(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 J().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")return new ot(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s,aggregate:e.aggregate});let l=await new ut(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:n,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}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),a=await this.mongoService.collection(e.table).find(o).toArray(),u=[];for(let l of a){let f=await this.mongoService.updateOne(e.table,l._id,e.data);u.push(f)}return u});let t=this.knexService.getKnex(),n=t(e.table);e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n;for(let o of i)await this.knexService.updateWithCascade(e.table,o.id,e.data);if(e.returning){let o=t(e.table);return e.where.length>0&&await this.applyWhereToKnex(o,e.where,e.table),await o.select(e.returning)}return{affected:i.length}}async deleteWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let i=await this.buildMongoFilter(e.where,e.table),s=await this.mongoService.collection(e.table).find(i).toArray(),a=0;for(let u of s)await this.mongoService.deleteOne(e.table,u._id)&&a++;return a});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 gn.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,aggregate:e.aggregate,maxQueryDepth:e.maxQueryDepth})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t){return this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let s=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return ne(s)}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 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 ne(o)}return await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first()})}async delete(e,t){return this.trackQueryMetric("delete",e,async()=>t&&typeof t=="object"&&"where"in t?await this.deleteWithOptions({table:e,where:t.where})>0:this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t)):await this.knexService.getKnex()(e).where("id",t).delete()>0)}async countRecords(e,t){if(this.dbType==="mongodb")return this.mongoService.count(e,t||{});let i=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.filterToWhere(t);({query:i}=await this.applyWhereToKnex(i,s,e))}let o=await i.count("* as count").first();return Number(o?.count||0)}async transaction(e){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>e(this.mongoService)):this.knexService.transaction(e)}async findById(e,t){if(this.dbType==="mongodb"){let i=this.safeObjectId(t);return this.mongoService.findOne(e,{_id:i})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[o,s]of Object.entries(t))o==="id"||o==="_id"?i._id=this.safeObjectId(s):i[o]=s;return this.mongoService.findOne(e,i)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[a,u]of Object.entries(t))a==="id"||a==="_id"?i._id=this.safeObjectId(u):i[a]=u;return await this.mongoService.collection(e).find(i).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}};nr();er();Xn();xe();Lt();et();$e();Ye();var Yr=new Set(["fields","filter","sort","limit","page","deep"]),mn=3;function rr(r,e,t,n=0,i=3){if(!e||typeof e!="object")return;if(n>=i)throw new M(`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 l=s.get(a);if(!l)throw new M(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let p of Object.keys(u))if(!Yr.has(p))throw new M(`Unknown deep option key '${p}' for relation '${a}'. Allowed: ${[...Yr].join(", ")}`);let f=l.type;if(u.limit!==void 0&&(f==="many-to-one"||f==="one-to-one"))throw new M(`'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 M(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let c=l.targetTableName||l.targetTable;if(c){if(u.filter&&(Q(u.filter,c,t),yn(u.filter,0,a,r)),u.sort){let p=Array.isArray(u.sort)?u.sort:String(u.sort).split(",").map(d=>d.trim()).filter(Boolean);for(let d of p){let g=d.startsWith("-")?d.slice(1):d;fo(g,c,t,a,r)}}u.deep&&rr(c,u.deep,t,n+1,i)}}}function fo(r,e,t,n,i){if(r.includes("."))throw new M(`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 M(`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 M(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${i}')`)}var po=new Set(["_and","_or","_not"]);function yn(r,e,t,n){if(!(!r||typeof r!="object"))for(let[i,o]of Object.entries(r)){if(po.has(i)){if(Array.isArray(o))for(let l of o)yn(l,e,t,n);else o&&typeof o=="object"&&yn(o,e,t,n);continue}if(i.startsWith("_")||!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).some(l=>!l.startsWith("_")))continue;let a=e+1;if(a>mn)throw new M(`Filter path exceeds max dotted hops of ${mn} at '${i}' (relation '${t}' on '${n}')`);let u={};for(let l of Object.keys(o))l.startsWith("_")||(u[l]=o[l]);yn(u,a,t,n)}}function Xr(r,e,t,n){return!r||typeof r!="object"?r:Dt(r,e,t,n)}function Dt(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let o=r.map(s=>Dt(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 c=(Array.isArray(s)?s:[s]).map(p=>Dt(p,e,t,n)).filter(p=>p!=null&&Object.keys(p).length>0);c.length>0&&(i[o]=c);continue}if(o==="_not"){let f=Dt(s,e,t,n);f!=null&&Object.keys(f).length>0&&(i[o]=f);continue}let a=t?.tables?.get(e),u=a?.relations?.find(f=>f.propertyName===o);if(u){if(!n(e,o,"relation"))continue;let f=u.targetTableName||u.targetTable;if(!f)continue;let c=Dt(s,f,t,n);c!=null&&Object.keys(c).length>0&&(i[o]=c);continue}if(a?.columns?.find(f=>f.name===o)){if(!n(e,o,"column"))continue;i[o]=s;continue}i[o]=s}return i}function Zr(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 l=(s.startsWith("-")?s.slice(1):s).split("."),f=!0,c=e;for(let p=0;p<l.length;p++){let d=l[p],g=p===l.length-1,m=t?.tables?.get(c);if(!m){f=!1;break}if(g)m.columns?.find(h=>h.name===d)?n(c,d,"column")||(f=!1):m.relations?.find(b=>b.propertyName===d)&&(n(c,d,"relation")||(f=!1));else{let y=m.relations?.find(h=>h.propertyName===d);if(!y){f=!1;break}if(!n(c,d,"relation")){f=!1;break}c=y.targetTableName||y.targetTable||c}}f&&o.push(s)}if(o.length!==0)return Array.isArray(r)?o:o.join(",")}Nt();Ye();Mt();sn();vt();ze();$e();function go(r){let e=new ft({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,i=()=>(t||(t=new Ve({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),o=()=>(n||(n=new Qe({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,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,DEEP_TO_MANY_DEFAULT_LIMIT,DEFAULT_TIMEOUT_MS,DOTTED_PATH_MAX_HOPS,DatabaseException,DuplicateResourceException,ErrorHandler,ExecutorEngineService,ExternalServiceException,FIELD_OPERATORS,FileNotFoundException,FileSizeExceededException,FileUploadException,HttpException,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH,InvalidTokenException,IsolatedExecutorService,JoinRegistry,LOGICAL_OPERATORS,MongoBatchAdapter,MongoQueryExecutor,PER_PARENT_CONCURRENCY,QueryBuilderService,QueryPlanner,ResourceNotFoundException,SchemaException,ScriptExecutionException,ScriptTimeoutException,ServiceUnavailableException,SqlBatchAdapter,SqlQueryExecutor,TokenExpiredException,ValidationException,WHERE_IN_CHUNK_SIZE,WorkerPool,appendIsolatedExecutorRuntimeLog,applyOperatorToMatch,applyRelationFilters,applyWhereToKnex,assertFieldOperatorValueIsClean,buildAggregateFilter,buildMongoCharFoldMapJson,buildMongoFoldTextSearchJs,buildRelationSubquery,buildSqlWherePartsFromFieldAst,buildWhereClause,camelToSnake,chunkedFetch,compileScriptSource,computeEngineTuning,createEnfyraKernel,dslOpToCompareOp,encodeMainThreadToIsolate,escapeSqlValue,executeBatchFetches,executeMongoBatchFetches,expandFieldsToJoinsAndSelect,getEffectiveCpuCount,getEffectiveMemoryBytes,getEngineTuning,getExecutableScript,getForeignKeyColumnName,getIoAbortSignal,getJunctionColumnNames,getJunctionTableName,getPrimaryKeyColumn,getScriptLegacyField,getShortFkConstraintName,getShortFkName,getShortIndexName,getShortPkName,hasAggregateQuery,hasLogicalOperators,isExecutableJavaScript,isScriptTable,mergeAggregateValue,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,perParentRun,quoteIdentifier,resolveExecutableScript,rewriteFilterDenyingFields,rewriteSortDroppingDenied,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,transformCode,validateDeepOptions,validateFilterShape,whereToMongoFilter});
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "@enfyra/kernel",
3
- "version": "1.0.10",
3
+ "version": "1.1.0",
4
4
  "source": "bundled-compiled-kernel"
5
5
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enfyra/kernel",
3
- "version": "1.0.10",
3
+ "version": "1.1.0",
4
4
  "description": "Closed-distribution Enfyra kernel runtime",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "private": false,