@enfyra/kernel 1.1.51 → 1.1.53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -0
- package/dist/execution/worker.js +1 -1
- package/dist/index.js +6 -6
- package/dist/package-metadata.json +1 -1
- package/package.json +3 -1
package/README.md
CHANGED
|
@@ -27,3 +27,18 @@ container.register({
|
|
|
27
27
|
executorEngineService: asValue(kernel.executorEngineService),
|
|
28
28
|
});
|
|
29
29
|
```
|
|
30
|
+
|
|
31
|
+
## Executor lane tuning
|
|
32
|
+
|
|
33
|
+
The executor selects up to two runner processes and sizes isolate lanes from the
|
|
34
|
+
effective CPU and memory limits. CPU establishes a baseline of two lanes per
|
|
35
|
+
effective CPU and a flexible ceiling of four lanes per effective CPU. Available
|
|
36
|
+
RAM can raise the target from the baseline toward that ceiling. The memory bound
|
|
37
|
+
uses its raw safe lane count, reserving at most 25% of effective memory for
|
|
38
|
+
isolate limits, with an absolute ceiling of 128 lanes per runner.
|
|
39
|
+
|
|
40
|
+
Run `yarn bench:executor-lanes` on the target hardware to sweep candidate lane
|
|
41
|
+
counts using I/O-bound and CPU-bound scripts, while also verifying that
|
|
42
|
+
cancelling one task does not interrupt a sibling lane. Use the smallest count
|
|
43
|
+
whose I/O p95 has plateaued and whose CPU p95, runner RSS, and heap ratio remain
|
|
44
|
+
within the deployment budget.
|
package/dist/execution/worker.js
CHANGED
|
@@ -949,7 +949,7 @@ function __cleanupTask() {
|
|
|
949
949
|
__pendingRuntimeTasks = [];
|
|
950
950
|
return true;
|
|
951
951
|
}
|
|
952
|
-
`;function Ce(e){return Se.replace("%%PKG_SETUP%%",e)}re.exports={buildSetupCode:Ce}});var{parentPort:Re}=require("worker_threads"),C=Re||{on(e,t){e==="message"&&process.on("message",t)},postMessage(e){process.send?.(e)}},se=require("fs"),{fileURLToPath:$e}=require("url"),{createPackageRuntimeBridge:Me}=ne(),{buildSetupCode:Te}=ae(),V;try{V=require("isolated-vm")}catch(e){C.postMessage({type:"error",message:"isolated-vm not available: "+e.message}),process.exit(1)}var q=new Map,de=0,D=new Map,H=new Map,L=new Map,F=Me({workerDir:__dirname,activeTaskContexts:D}),Ae=500,Ne=5e3,Ee=1,oe=new WeakMap,fe=new WeakMap,pe=new WeakMap,K={created:0,reused:0,released:0,evicted:0,scrubFailed:0};function B(e){let t=L.get(e);return Math.max(1,Math.ceil((t??Date.now()+3e4)-Date.now()))}var M=null,ie=0,ce=0,le=0;async function Oe(){let e=Date.now();if(e-ce<Ne)return le;if(ce=e,!M)return 0;let t=0;for(let a of M){let r=a?.isolate;if(!(!r||r.isDisposed))try{let n=await r.getHeapStatistics(),l=n.heap_size_limit||1,s=n.used_heap_size/l;s>t&&(t=s)}catch{}}return le=t,t}async function U(e){e.heapRatio=await Oe(),e.contextStats=Je(),C.postMessage(e)}function Je(){let e=0;if(M)for(let t of M)e+=t?.idleContexts?.length||0;return{...K,idle:e}}function _e(e,t){if(!M){let a=Math.max(1,Math.trunc(Number(t)||8));M=new Array(a).fill(null)}for(let a=0;a<M.length;a++){let r=(ie+a)%M.length,n=M[r];if((!n||!n.isolate||n.isolate.isDisposed)&&(n={isolate:new V.Isolate({memoryLimit:e}),idleContexts:[],taskId:null},M[r]=n),n.taskId==null)return ie=(r+1)%M.length,n}throw new Error("No isolate lane is available")}function Ie(e){F.cancelTask(e);let t=H.get(e);if(!t){C.postMessage({type:"taskCancelled",id:e});return}H.delete(e),D.delete(e),L.delete(e),t.taskId=null,t.idleContexts.length=0;try{t.isolate.dispose()}catch{}X(e),C.postMessage({type:"taskCancelled",id:e})}function ge(e,t){D.delete(e),H.delete(e),L.delete(e),t.taskId=null,X(e),C.postMessage({type:"taskReleased",id:e})}async function A(e,t,a){let r=oe.get(e);r||(r=new Map,oe.set(e,r));let n=r.get(t);if(n)return n;let l;try{l=await e.compileScript(t,{filename:a})}catch(s){throw s&&typeof s=="object"&&(s.executionStage="compile"),s}if(r.set(t,l),r.size>Ae){let s=r.keys().next().value;r.delete(s)}return l}C.on("message",async e=>{if(e.type==="execute")ze(e).catch(async t=>{await U({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="executeBatch")Xe(e).catch(async t=>{await U({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="invokeRuntimeCallback")je(e).catch(t=>{C.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:t?.message||String(t)})});else if(e.type==="callResult"){let t=q.get(e.callId);t&&(q.delete(e.callId),t.resolve(e.result))}else if(e.type==="callError"){let t=q.get(e.callId);t&&(q.delete(e.callId),t.reject(new Error(e.error)))}else e.type==="cancelTask"&&Ie(e.id)});async function je(e){let t=D.get(e.id);if(!t){C.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:`Runtime callback context not found: ${e.id}`});return}let a=await t.evalClosure(`return __invokeRuntimeCallback(${JSON.stringify(e.callbackId)}, ${JSON.stringify(e.argsJson||"[]")});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}}),r=JSON.parse(a);C.postMessage({type:"runtimeCallbackResult",callId:e.callId,...r})}function j(e,t,a){return new Promise((r,n)=>{let l=`cb_${++de}`;q.set(l,{resolve:r,reject:n}),C.postMessage({type:t,id:e,callId:l,...a})})}function Ue(e,t,a){C.postMessage({type:t,id:e,callId:`f_${++de}`,...a})}async function He(e,t){if(t?.method!=="stream")return j(e,"resCall",t);let a=JSON.parse(t.argsJson||"[]"),r=a[0],n=a[1]||{},l=r?.__pkgHandleArg;if(!l)return j(e,"resCall",t);let s=n.observer&&typeof n.observer=="object"?n.observer.__fnRef:null,y=n.transform&&typeof n.transform=="object"?n.transform.__fnRef:null,p=s||y?new TextDecoder("utf-8"):null;delete n.observer,delete n.transform;let k={...n};await j(e,"resCall",{method:"streamStart",argsJson:JSON.stringify([null,k])});let w=async(d,v,h)=>{if(!d)return;let b=D.get(e);if(!b)return;let R=await b.evalClosure(`return __invokeRuntimeCallback(${JSON.stringify(d)}, ${JSON.stringify(JSON.stringify([v,h]))});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}}),S=JSON.parse(R);if(S?.error)throw new Error(S.error);if(S?.value?.__e!=="u")return S?.value},P=async(d,v)=>{if(s)try{await w(s,d,v)}catch{}},u=async(d,v,h)=>{let b=d;if(y){let S=await w(y,h,v);if(S===null)return;S!==void 0&&(b=Buffer.from(String(S)))}let R=Buffer.from(b);R.length!==0&&await j(e,"resCall",{method:"streamChunk",chunk:R.toString("base64")})};try{await F.streamPackageHandle(e,l,async v=>{let h="";try{h=p?p.decode(Buffer.from(v),{stream:!0}):""}catch{}await P(h,"chunk"),await u(v,"chunk",h)},[],B(e));let d="";try{d=p?p.decode():""}catch{}await P(d,"end"),await u("","end",d),await j(e,"resCall",{method:"streamEnd"})}catch(d){try{await j(e,"resCall",{method:"streamError",error:{message:d.message,stack:d.stack}})}catch{}throw await P("","error"),d}return JSON.stringify({__e:"u"})}function Le(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=$e(e.fileUrl)),!t||!se.existsSync(t)?null:se.readFileSync(t,"utf8")}async function Fe(e,t,a){try{let r=Le(a);if(!r)return null;let n=await e.compileModule(r,{filename:`pkg:${a.safeName}`});await n.instantiate(t,s=>{throw new Error(`Unresolved import in package ${a.safeName}: ${s}`)}),await n.evaluate({timeout:1e4});let l=await n.namespace.get("default");return l!==void 0&&l.typeof!=="undefined"?l.derefInto({release:!1}):n.namespace.derefInto({release:!1})}catch{return null}}function ye(e,t){let a=n=>{let l=2166136261;for(let s=0;s<n.length;s++)l^=n.charCodeAt(s),l=Math.imul(l,16777619);return(l>>>0).toString(36)},r=new Set(t||[]);return e.map(n=>{let l=n.cacheKey||`${n.filePath||""}:${n.fileUrl||""}:${n.mtimeMs||""}:${n.size||""}:${a(n.sourceCode||"")}`,s=r.has(n.name)?"isolate":"proxy";return`${n.name}:${n.version||""}:${l}:${s}`}).join("|")}function he(e,t){let a=new Set(t.map(p=>p.name)),r=new Set,n=String(e||""),l=/\b(?:\$ctx\.)?\$pkgs\s*\[\s*(['"`])([^'"`]+)\1\s*\]/g,s=/\brequire\s*\(\s*(['"`])([^'"`]+)\1\s*\)/g,y=/\b(?:\$ctx\.)?\$pkgs\.([A-Za-z_$][\w$]*)/g;for(let p of[l,s])for(let k of n.matchAll(p)){let w=k[2];a.has(w)&&r.add(w)}for(let p of n.matchAll(y)){let k=p[1];a.has(k)&&r.add(k)}return r}async function De(e,t,a,r){let n=await e.createContext(),l=n.global;await l.set("global",l.derefInto());let s=[],y=[],p=new Map;for(let u of a){p.set(u.name,u);let d=r.has(u.name)?await Fe(e,n,u):null;d!==null?(await l.set(`__pkg_${u.safeName}`,d),s.push(u)):y.push(u)}F.setTaskPackages(t,p),await l.set("__callRef",new V.Reference(async(u,d,v)=>{let h=JSON.parse(v);if(d==="pkgCall")try{return JSON.stringify(await F.executePackageRuntimeCall(u,h))}catch(b){throw new Error(JSON.stringify({__userThrow:!0,message:b.message,code:b.code,details:b.details}))}return d==="resCall"?He(u,h):j(u,d,h)})),await l.set("__fireRef",new V.Reference((u,d,v)=>{let h=JSON.parse(v);Ue(u,d,h)}));let k=s.map(u=>`$pkgs[${JSON.stringify(u.name)}] = __pkg_${u.safeName};`).concat(y.map(u=>`$pkgs[${JSON.stringify(u.name)}] = __createPkgProxy(${JSON.stringify(u.name)}, []);`)).join(`
|
|
952
|
+
`;function Ce(e){return Se.replace("%%PKG_SETUP%%",e)}re.exports={buildSetupCode:Ce}});var{parentPort:Re}=require("worker_threads"),C=Re||{on(e,t){e==="message"&&process.on("message",t)},postMessage(e){process.send?.(e)}},se=require("fs"),{fileURLToPath:$e}=require("url"),{createPackageRuntimeBridge:Me}=ne(),{buildSetupCode:Te}=ae(),V;try{V=require("isolated-vm")}catch(e){C.postMessage({type:"error",message:"isolated-vm not available: "+e.message}),process.exit(1)}var q=new Map,de=0,D=new Map,H=new Map,L=new Map,F=Me({workerDir:__dirname,activeTaskContexts:D}),Ae=500,Ne=5e3,Ee=1,oe=new WeakMap,fe=new WeakMap,pe=new WeakMap,K={created:0,reused:0,released:0,evicted:0,scrubFailed:0};function B(e){let t=L.get(e);return Math.max(1,Math.ceil((t??Date.now()+3e4)-Date.now()))}var M=null,ie=0,ce=0,le=0;async function Oe(){let e=Date.now();if(e-ce<Ne)return le;if(ce=e,!M)return 0;let t=0;for(let a of M){let r=a?.isolate;if(!(!r||r.isDisposed))try{let n=await r.getHeapStatistics(),l=n.heap_size_limit||1,s=n.used_heap_size/l;s>t&&(t=s)}catch{}}return le=t,t}async function U(e){e.heapRatio=await Oe(),e.runnerRssBytes=process.memoryUsage().rss,e.contextStats=Je(),C.postMessage(e)}function Je(){let e=0;if(M)for(let t of M)e+=t?.idleContexts?.length||0;return{...K,idle:e}}function _e(e,t){if(!M){let a=Math.max(1,Math.trunc(Number(t)||8));M=new Array(a).fill(null)}for(let a=0;a<M.length;a++){let r=(ie+a)%M.length,n=M[r];if((!n||!n.isolate||n.isolate.isDisposed)&&(n={isolate:new V.Isolate({memoryLimit:e}),idleContexts:[],taskId:null},M[r]=n),n.taskId==null)return ie=(r+1)%M.length,n}throw new Error("No isolate lane is available")}function Ie(e){F.cancelTask(e);let t=H.get(e);if(!t){C.postMessage({type:"taskCancelled",id:e});return}H.delete(e),D.delete(e),L.delete(e),t.taskId=null,t.idleContexts.length=0;try{t.isolate.dispose()}catch{}X(e),C.postMessage({type:"taskCancelled",id:e})}function ge(e,t){D.delete(e),H.delete(e),L.delete(e),t.taskId=null,X(e),C.postMessage({type:"taskReleased",id:e})}async function A(e,t,a){let r=oe.get(e);r||(r=new Map,oe.set(e,r));let n=r.get(t);if(n)return n;let l;try{l=await e.compileScript(t,{filename:a})}catch(s){throw s&&typeof s=="object"&&(s.executionStage="compile"),s}if(r.set(t,l),r.size>Ae){let s=r.keys().next().value;r.delete(s)}return l}C.on("message",async e=>{if(e.type==="execute")ze(e).catch(async t=>{await U({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="executeBatch")Xe(e).catch(async t=>{await U({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="invokeRuntimeCallback")je(e).catch(t=>{C.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:t?.message||String(t)})});else if(e.type==="callResult"){let t=q.get(e.callId);t&&(q.delete(e.callId),t.resolve(e.result))}else if(e.type==="callError"){let t=q.get(e.callId);t&&(q.delete(e.callId),t.reject(new Error(e.error)))}else e.type==="cancelTask"&&Ie(e.id)});async function je(e){let t=D.get(e.id);if(!t){C.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:`Runtime callback context not found: ${e.id}`});return}let a=await t.evalClosure(`return __invokeRuntimeCallback(${JSON.stringify(e.callbackId)}, ${JSON.stringify(e.argsJson||"[]")});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}}),r=JSON.parse(a);C.postMessage({type:"runtimeCallbackResult",callId:e.callId,...r})}function j(e,t,a){return new Promise((r,n)=>{let l=`cb_${++de}`;q.set(l,{resolve:r,reject:n}),C.postMessage({type:t,id:e,callId:l,...a})})}function Ue(e,t,a){C.postMessage({type:t,id:e,callId:`f_${++de}`,...a})}async function He(e,t){if(t?.method!=="stream")return j(e,"resCall",t);let a=JSON.parse(t.argsJson||"[]"),r=a[0],n=a[1]||{},l=r?.__pkgHandleArg;if(!l)return j(e,"resCall",t);let s=n.observer&&typeof n.observer=="object"?n.observer.__fnRef:null,y=n.transform&&typeof n.transform=="object"?n.transform.__fnRef:null,p=s||y?new TextDecoder("utf-8"):null;delete n.observer,delete n.transform;let k={...n};await j(e,"resCall",{method:"streamStart",argsJson:JSON.stringify([null,k])});let w=async(d,v,h)=>{if(!d)return;let b=D.get(e);if(!b)return;let R=await b.evalClosure(`return __invokeRuntimeCallback(${JSON.stringify(d)}, ${JSON.stringify(JSON.stringify([v,h]))});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}}),S=JSON.parse(R);if(S?.error)throw new Error(S.error);if(S?.value?.__e!=="u")return S?.value},P=async(d,v)=>{if(s)try{await w(s,d,v)}catch{}},u=async(d,v,h)=>{let b=d;if(y){let S=await w(y,h,v);if(S===null)return;S!==void 0&&(b=Buffer.from(String(S)))}let R=Buffer.from(b);R.length!==0&&await j(e,"resCall",{method:"streamChunk",chunk:R.toString("base64")})};try{await F.streamPackageHandle(e,l,async v=>{let h="";try{h=p?p.decode(Buffer.from(v),{stream:!0}):""}catch{}await P(h,"chunk"),await u(v,"chunk",h)},[],B(e));let d="";try{d=p?p.decode():""}catch{}await P(d,"end"),await u("","end",d),await j(e,"resCall",{method:"streamEnd"})}catch(d){try{await j(e,"resCall",{method:"streamError",error:{message:d.message,stack:d.stack}})}catch{}throw await P("","error"),d}return JSON.stringify({__e:"u"})}function Le(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=$e(e.fileUrl)),!t||!se.existsSync(t)?null:se.readFileSync(t,"utf8")}async function Fe(e,t,a){try{let r=Le(a);if(!r)return null;let n=await e.compileModule(r,{filename:`pkg:${a.safeName}`});await n.instantiate(t,s=>{throw new Error(`Unresolved import in package ${a.safeName}: ${s}`)}),await n.evaluate({timeout:1e4});let l=await n.namespace.get("default");return l!==void 0&&l.typeof!=="undefined"?l.derefInto({release:!1}):n.namespace.derefInto({release:!1})}catch{return null}}function ye(e,t){let a=n=>{let l=2166136261;for(let s=0;s<n.length;s++)l^=n.charCodeAt(s),l=Math.imul(l,16777619);return(l>>>0).toString(36)},r=new Set(t||[]);return e.map(n=>{let l=n.cacheKey||`${n.filePath||""}:${n.fileUrl||""}:${n.mtimeMs||""}:${n.size||""}:${a(n.sourceCode||"")}`,s=r.has(n.name)?"isolate":"proxy";return`${n.name}:${n.version||""}:${l}:${s}`}).join("|")}function he(e,t){let a=new Set(t.map(p=>p.name)),r=new Set,n=String(e||""),l=/\b(?:\$ctx\.)?\$pkgs\s*\[\s*(['"`])([^'"`]+)\1\s*\]/g,s=/\brequire\s*\(\s*(['"`])([^'"`]+)\1\s*\)/g,y=/\b(?:\$ctx\.)?\$pkgs\.([A-Za-z_$][\w$]*)/g;for(let p of[l,s])for(let k of n.matchAll(p)){let w=k[2];a.has(w)&&r.add(w)}for(let p of n.matchAll(y)){let k=p[1];a.has(k)&&r.add(k)}return r}async function De(e,t,a,r){let n=await e.createContext(),l=n.global;await l.set("global",l.derefInto());let s=[],y=[],p=new Map;for(let u of a){p.set(u.name,u);let d=r.has(u.name)?await Fe(e,n,u):null;d!==null?(await l.set(`__pkg_${u.safeName}`,d),s.push(u)):y.push(u)}F.setTaskPackages(t,p),await l.set("__callRef",new V.Reference(async(u,d,v)=>{let h=JSON.parse(v);if(d==="pkgCall")try{return JSON.stringify(await F.executePackageRuntimeCall(u,h))}catch(b){throw new Error(JSON.stringify({__userThrow:!0,message:b.message,code:b.code,details:b.details}))}return d==="resCall"?He(u,h):j(u,d,h)})),await l.set("__fireRef",new V.Reference((u,d,v)=>{let h=JSON.parse(v);Ue(u,d,h)}));let k=s.map(u=>`$pkgs[${JSON.stringify(u.name)}] = __pkg_${u.safeName};`).concat(y.map(u=>`$pkgs[${JSON.stringify(u.name)}] = __createPkgProxy(${JSON.stringify(u.name)}, []);`)).join(`
|
|
953
953
|
`),w=Te(k);return await(await A(e,w,"setup.js")).run(n,{timeout:B(t)}),fe.set(n,ye(a,r)),pe.set(n,p),n}async function me(e,t,a,r,n,l,s){let y=e.isolate,p=ye(a,n),k=null;for(let u=e.idleContexts.length-1;u>=0;u--){let d=e.idleContexts[u];if(e.idleContexts.splice(u,1),fe.get(d)===p){k=d,K.reused++;break}try{d.release()}catch{}}k||(k=await De(y,t,a,n),K.created++),F.setTaskPackages(t,pe.get(k)||new Map);let w=k.global;return await w.set("__snapshot",new V.ExternalCopy(r).copyInto()),await w.set("__nextTaskId",t),await w.set("__nextTaskTimeoutMs",l),await w.set("__nextTaskDeadlineMs",s),await(await A(y,"__resetTask(__snapshot, __nextTaskId, __nextTaskTimeoutMs, __nextTaskDeadlineMs);","reset-task.js")).run(k,{timeout:B(t)}),k}async function ke(e,t){if(!(!t||e.isolate.isDisposed)){try{await(await A(e.isolate,"__cleanupTask();","cleanup-task.js")).run(t,{timeout:5e3})}catch{K.scrubFailed++;try{t.release()}catch{}return}if(e.idleContexts.length>=Ee){try{t.release()}catch{}K.evicted++;return}e.idleContexts.push(t),K.released++}}function Ke(e){try{let t=JSON.parse(e.message);if(t&&t.__userThrow)return{...t,message:t.message??e.message}}catch{}return null}var Be=3,qe=["setup.js","extract.js","extract-error-ctx.js","set-status.js","populate-error.js"];function Ve(e){if(!e)return null;let t=e.split(`
|
|
954
954
|
`);for(let a of t){let r=a.match(/at\s+(.+\.js):(\d+):(\d+)/);if(!r)continue;let n=r[1].trim();if(qe.includes(n)||n!=="handler.js"&&!n.startsWith("preHook #")&&!n.startsWith("postHook #"))continue;let s=parseInt(r[2])-Be;if(!(s<=0))return{line:s,column:parseInt(r[3]),phase:n.replace(".js","")}}return null}function Ge(e,t,a){if(!e||!t)return;let r=String(e).split(/\r?\n/),n=Math.max(1,t-1),l=Math.min(r.length,t+1),s=String(l).length,y=[];for(let p=n;p<=l;p++){let k=p===t?">":" ";y.push(`${k} ${String(p).padStart(s," ")}. ${r[p-1]??""}`),p===t&&a&&a>0&&y.push(` ${" ".repeat(s)} ${" ".repeat(Math.max(0,a-1))}^`)}return y.join(`
|
|
955
955
|
`)}function We(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 Q(e,t){let a=Ke(e);if(a)return{message:a.message,statusCode:a.statusCode,errorPath:a.errorPath,code:a.code,details:a.details};let r=Ve(e.stack),n=e.message||"Unknown error",l=r?`${n} (${r.phase}, line ${r.line})`:n,s=We(r,t),y=r?Ge(s,r.line,r.column):void 0;return{message:l,statusCode:e.statusCode||null,details:{errorName:e.name||null,executionStage:e.executionStage||"runtime",...r?{...r,codeFrame:y}:{}}}}function W(e){return e?.message==="Script execution timed out."}function we(e){return e?.message==="Isolate was disposed during execution due to memory limit"}function ve(e){W(e)&&e?.code==null&&(e.code="ERR_SCRIPT_EXECUTION_TIMEOUT"),we(e)&&e?.code==null&&(e.code="ERR_ISOLATE_MEMORY_LIMIT",e.details={outcome:"unknown_outcome",retryable:!1})}async function z(e,t,a){ve(t);let r=Q(t,a);t.details&&(r.details={...r.details,...t.details}),await U({type:"result",id:e,success:!1,error:{...r,stack:t.stack,code:r.code??t.code}})}async function ze(e){let{id:t,code:a,pkgSources:r,snapshot:n,memoryLimitMb:l,isolatePoolSize:s}=e,y={handler:e.sourceCode||a||""},p=r||[],k=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),w=Date.now()+k;L.set(t,w);let P=he(a,p),u=_e(l,s);u.taskId=t,H.set(t,u);let d=u.isolate,v;try{v=await me(u,t,p,n,P,k,w)}catch(h){L.delete(t),H.delete(t),u.taskId=null,X(t),await z(t,h,y),C.postMessage({type:"taskReleased",id:t});return}D.set(t,v);try{let h=`
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var pi=Object.create;var zt=Object.defineProperty;var gi=Object.getOwnPropertyDescriptor;var hi=Object.getOwnPropertyNames;var mi=Object.getPrototypeOf,yi=Object.prototype.hasOwnProperty;var q=(r,e)=>()=>(r&&(e=r(r=0)),e);var Mn=(r,e)=>{for(var t in e)zt(r,t,{get:e[t],enumerable:!0})},yr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of hi(e))!yi.call(r,i)&&i!==t&&zt(r,i,{get:()=>e[i],enumerable:!(n=gi(e,i))||n.enumerable});return r};var ue=(r,e,t)=>(t=r!=null?pi(mi(r)):{},yr(e||!r||!r.__esModule?zt(t,"default",{value:r,enumerable:!0}):t,r)),bi=r=>yr(zt({},"__esModule",{value:!0}),r);function Fr(r){return Bn.createHash("md5").update(r).digest("hex").substring(0,8)}function vr(r){return r.length<=Rr-3?`${r}_pk`:`j_${Fr(r)}_pk`}function xr(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=Rr?n:`j_${Fr(r)}_${t}_fk`}function vt(r,e,t){let n=`${r}:${e}:${t}`;return`j_${Bn.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function J(r){return`${r}Id`}function xt(r,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function Ir(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function Nr(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function Er(r,e,t){return`${r}_${e}_${t}_fk`}function Mr(r,e,t){return`${r}_${e}_${t}_idx`}var Bn,Rr,Ke=q(()=>{"use strict";Bn=ue(require("crypto")),Rr=63});function ln(r){return eo[r]??null}var we,Kn,Nt,eo,cn=q(()=>{"use strict";we=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),Kn=new Set(["_and","_or","_not"]),Nt=[...Array.from(Kn),...Array.from(we)],eo={_eq:"eq",_neq:"neq",_gt:"gt",_gte:"gte",_lt:"lt",_lte:"lte",_in:"in",_not_in:"not_in",_nin:"not_in",_contains:"contains",_starts_with:"starts_with",_ends_with:"ends_with",_between:"between"}});var I,de=q(()=>{"use strict";I=class extends Error{constructor(t="Bad Request",n){let i=Array.isArray(t),o=i?t.join("; ")||"Bad Request":typeof t=="string"?t:JSON.stringify(t);super(o);this.statusCode=400;this.errorCode="BAD_REQUEST";this.name="BadRequestException",this.details=n,i&&(this.messages=t)}}});function jr(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var Br=q(()=>{"use strict"});function Ee(r,e,t){throw new I({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${Nt.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:Nt})}function un(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=jr();for(let i of Object.keys(e))if(i.startsWith("_")&&!we.has(i)){if(n&&i==="_id")continue;Ee(i,r,t)}}function re(r,e,t){if(!r||typeof r!="object")return;let n=t?.tables?.get(e),i=new Set((n?.columns??[]).map(s=>s.name)),o=new Map((n?.relations??[]).map(s=>[s.propertyName,s]));for(let[s,a]of Object.entries(r)){if(to.has(s)){if(Array.isArray(a))for(let c of a)re(c,e,t);else a&&typeof a=="object"&&re(a,e,t);continue}let u=o.get(s);if(u){if(a&&typeof a=="object"&&!Array.isArray(a)){un(s,a,e);let c=u.targetTableName||u.targetTable;if(c){let d=Object.keys(a).filter(l=>!l.startsWith("_"));if(d.length>0){let l={};for(let f of d)l[f]=a[f];re(l,c,t)}}}continue}s.startsWith("_")&&!i.has(s)&&s!=="_id"&&Ee(s,s,e),a&&typeof a=="object"&&!Array.isArray(a)&&un(s,a,e)}}var to,Je=q(()=>{"use strict";de();cn();Br();to=new Set(["_and","_or","_not"])});function fe(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:dn(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function dn(r,e){if(!r||typeof r!="object")return{node:null,hasRelationFilters:!1};let t=[],n=!1;for(let[i,o]of Object.entries(r)){let s=no(i,o,e);s.hasRelationFilters&&(n=!0),s.node&&t.push(s.node)}return t.length===0?{node:null,hasRelationFilters:n}:t.length===1?{node:t[0],hasRelationFilters:n}:{node:{kind:"and",children:t},hasRelationFilters:n}}function no(r,e,t){if(r==="_and")return Lr("and",e,t);if(r==="_or")return Lr("or",e,t);if(r==="_not"){let c=dn(e,t);return c.node?{node:{kind:"not",child:c.node},hasRelationFilters:c.hasRelationFilters}:{node:null,hasRelationFilters:c.hasRelationFilters}}let n=t.metadata?.tables?.get(t.currentTable),i=n?.columns?.some(c=>c.name==="_id"&&c.isPrimary),o=n?.columns?.some(c=>c.name==="id"),a=r==="id"?i&&!o?"_id":"id":r,u=n?.relations?.find(c=>c.propertyName===a);return u?ro(a,e,u,t):n&&!n.columns?.find(d=>d.name===a)?(r.startsWith("_")&&r!=="_id"&&Ee(r,r,t.currentTable),console.warn(`[filter-parser] Unknown field "${r}" on table "${t.currentTable}" \u2014 skipped (not a column or relation in metadata).`),{node:null,hasRelationFilters:!1}):io(a,e,t)}function Lr(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],i=!1;for(let o of e){let s=dn(o,t);s.hasRelationFilters&&(i=!0),s.node&&n.push(s.node)}return n.length===0?{node:null,hasRelationFilters:i}:n.length===1?{node:n[0],hasRelationFilters:i}:{node:{kind:r,children:n},hasRelationFilters:i}}function ro(r,e,t,n){if(typeof e!="object"||e===null)return{node:null,hasRelationFilters:!0};let i=Object.keys(e),o=i.length===1&&(i[0]==="_is_null"||i[0]==="_is_not_null"||i[0]==="_eq"||i[0]==="_neq"||i[0]==="_in"||i[0]==="_not_in"||i[0]==="_nin"),s=n.registry.registerWithParent(n.currentTable,r,n.metadata,"left",n.currentJoinId,"filter");if(o&&i[0]==="_is_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_null===!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(o&&i[0]==="_is_not_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_not_null!==!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(o&&(i[0]==="_eq"||i[0]==="_neq")&&e[i[0]]===null)return s?{node:{kind:"relation_exists",joinId:s,negate:i[0]==="_eq"},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(!s)return{node:null,hasRelationFilters:!0};let a=t.targetTableName||t.targetTable,u={...n,parentJoinId:n.currentJoinId,currentJoinId:s,currentTable:a},c=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]),l=i.length>0&&i.every(p=>c.has(p))?{id:e}:e;return{node:dn(l,u).node,hasRelationFilters:!0}}function io(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:so(r,t)};if(e===null)return{node:{kind:"compare",field:n,op:"is_null",value:!0},hasRelationFilters:!1};if(typeof e!="object")return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};for(let s of Object.keys(e))s.startsWith("_")&&!we.has(s)&&Ee(s,r,t.tableName);let i=Object.entries(e).filter(([s])=>we.has(s));if(i.length===0)return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};let o=[];for(let[s,a]of i){let u=oo(n,s,a);u&&o.push(u)}return o.length===0?{node:null,hasRelationFilters:!1}:o.length===1?{node:o[0],hasRelationFilters:!1}:{node:{kind:"and",children:o},hasRelationFilters:!1}}function oo(r,e,t){if(e==="_is_null")return{kind:"compare",field:r,op:"is_null",value:t===!0};if(e==="_is_not_null")return{kind:"compare",field:r,op:"is_null",value:t!==!0};let n=ln(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function so(r,e){let t=e.metadata?.tables?.get(e.currentTable);if(!t)return!1;let n=r.includes(".")?r.split(".").pop():r,i=t.columns?.find(s=>s.name===n);if(!i)return!1;let o=(i.type||"").toLowerCase();return o==="uuid"||o==="uuidv4"||o.includes("uuid")}var Et=q(()=>{"use strict";cn();Je()});var ie,Mt=q(()=>{"use strict";ie=class{constructor(){this.map=new Map}size(){return this.map.size}has(e){return this.map.has(e)}get(e){return this.map.get(e)}getAll(){return Array.from(this.map.values())}registerWithParent(e,t,n,i="left",o=null,s="data"){let a=o?`${o}.${t}`:t;if(this.map.has(a)){let f=this.map.get(a);return i==="inner"&&(f.joinType="inner"),f.purposes.includes(s)||f.purposes.push(s),a}let u=n?.tables?.get(e);if(!u)return null;let c=u.relations?.find(f=>f.propertyName===t);if(!c)return null;let d=c.targetTableName||c.targetTable;if(!d)return null;let l={id:a,propertyName:t,parentTable:e,targetTable:d,relationType:c.type,parentJoinId:o,joinType:i,relationMeta:c,purposes:[s]};return this.map.set(a,l),a}}});async function W(r,e,t=oe){if(!Number.isInteger(t)||t<1)throw new Error("Batch fetch chunk size must be a positive integer");if(r.length<=t)return e(r);let n=[];for(let u=0;u<r.length;u+=t)n.push(r.slice(u,u+t));let i=[],o=0;async function s(){for(;o<n.length;){let u=o++;i[u]=await e(n[u])}}let a=Math.min(Gn,n.length);return await Promise.all(Array.from({length:a},s)),i.flat()}function He(r){let e=[],t=new Map;for(let n of r)if(n==="*"||!n.includes("."))e.push(n);else{let i=n.split("."),o=i[0],s=i.slice(1).join(".");t.has(o)||t.set(o,[]),t.get(o).push(s)}return{rootFields:e,subRelations:t}}var Me,oe,Gn,Yn,Se,Ge=q(()=>{"use strict";de();Me=16,oe=5e3,Gn=4,Yn=10;Se=class{constructor(e,t,n){this.adapter=e;this.metadataGetter=t;this.trace=n}enrichNestedDescs(e,t,n){if(!t||Object.keys(t).length===0)return e;let i=e.map(s=>{let a=t[s.relationName];if(!a)return s;let u=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(c=>c.trim()).filter(Boolean):["*"];return{...s,fields:u,userFilter:a.filter??s.userFilter,userSort:a.sort??s.userSort,userLimit:a.limit!==void 0?Number(a.limit):s.userLimit,userPage:a.page!==void 0?Number(a.page):s.userPage,nestedDeep:a.deep??s.nestedDeep}}),o=new Set(i.map(s=>s.relationName));for(let[s,a]of Object.entries(t)){if(o.has(s))continue;let u=n?.relations?.find(d=>d.propertyName===s);if(!u)continue;let c=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(d=>d.trim()).filter(Boolean):["*"];i.push({relationName:s,type:u.type,targetTable:u.targetTableName||u.targetTable,fields:c,isInverse:u.isInverse,fkColumn:u.foreignKeyColumn,mappedBy:u.mappedBy,junctionTableName:u.junctionTableName,junctionSourceColumn:u.junctionSourceColumn,junctionTargetColumn:u.junctionTargetColumn,userFilter:a.filter,userSort:a.sort,userLimit:a.limit!==void 0?Number(a.limit):void 0,userPage:a.page!==void 0?Number(a.page):void 0,nestedDeep:a.deep})}return i}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:Yn}:e}fieldsForNestedResolution(e,t){if(!t||Object.keys(t).length===0)return e;let n=new Set(e.filter(o=>o!=="*").map(o=>o.split(".")[0])),i=[...e];for(let o of Object.keys(t))n.has(o)||i.push(o);return i}uniqueValues(e){let t=new Set,n=[];for(let i of e){if(i==null)continue;let o=this.adapter.keyOf(i);t.has(o)||(t.add(o),n.push(i))}return n}assertLocalSortFields(e,t){if(!e.userSort)return;let n=Array.isArray(e.userSort)?e.userSort:String(e.userSort).split(",").map(i=>i.trim()).filter(Boolean);for(let i of n){let o=i.startsWith("-")?i.slice(1):i;if(o.includes("."))throw new I(`Sort field '${o}' is not supported on deep relation '${e.relationName}'. Sort only by local fields defined on '${e.targetTable}'.`);let s=t.columns?.some(u=>u.name===o),a=o==="id"&&t.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new I(`Sort field '${o}' does not exist on '${e.targetTable}'. Sort only by fields defined on the table metadata.`)}}async execute(e,t,n=3,i=0,o){if(e.length===0||t.length===0||i>=n)return;let s;o&&(s=await this.metadataGetter(o)??void 0),await Promise.all(t.map(a=>{let u=this.withDefaultToManyLimit(a);return u.type==="many-to-one"||u.type==="one-to-one"&&!u.isInverse?this.fetchOwnerRelation(e,u,n,i):u.type==="one-to-many"||u.type==="one-to-one"&&u.isInverse?this.fetchInverseRelation(e,u,n,i,s):u.type==="many-to-many"?this.fetchM2MRelation(e,u,n,i,s):Promise.resolve()}))}async fetchOwnerRelation(e,t,n,i){let o=this.adapter.resolveOwnerFkKey(t),s=new Set,a=[];for(let $ of e){let C=$[o];if(C==null)continue;let T=this.adapter.keyOf(C);s.has(T)||(s.add(T),a.push(C))}if(a.length===0){for(let $ of e)$[t.relationName]=null,o!==t.relationName&&delete $[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete $[t.fkColumn];return}let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{isPkOnly:c,nestedDescs:d,fetchSpec:l}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),f=this.adapter.getTargetPkField(u);if(c){for(let $ of e){let C=$[o];$[t.relationName]=C!=null?this.adapter.buildScalarRef(C,f):null,o!==t.relationName&&delete $[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete $[t.fkColumn]}return}let p=performance.now(),h=await this.adapter.fetchOwner(t.targetTable,a,l,t),g=Array.isArray(h)?h:h.docs,m=Array.isArray(h)?void 0:h.stats;this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:m?.strategy??"batch-in",roundtrips:m?.roundtrips??(Math.ceil(a.length/oe)||1),concurrencyWaves:m?.concurrencyWaves,ioConcurrency:m?.ioConcurrency,rowsTransferred:m?.rowsTransferred??g.length,rowsReturned:g.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let y=this.enrichNestedDescs(d,t.nestedDeep,u);y.length>0&&await this.execute(g,y,n,i+1,t.targetTable);let b=new Map;for(let $ of g)b.set(this.adapter.keyOf($[f]),$);for(let $ of e){let C=$[o];$[t.relationName]=C!=null&&b.get(this.adapter.keyOf(C))||null,o!==t.relationName&&delete $[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete $[t.fkColumn]}}async fetchInverseRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=this.uniqueValues(e.map(M=>M[s]));if(a.length===0)return;let u=this.adapter.resolveInverseFkField(t),c=await this.metadataGetter(t.targetTable);if(!c)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,c);let{nestedDescs:d,fetchSpec:l}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),c),f=performance.now(),{docs:p,groupKeyField:h,stats:g}=await this.adapter.fetchInverse(t.targetTable,u,a,l,t),m=new Map,y=t.fields.includes(u)||t.fields.includes("*");for(let M of p){let B=M[h],S=this.adapter.keyOf(B);m.has(S)||m.set(S,[]),m.get(S).push(M)}let b=t.userLimit!==void 0&&t.userLimit>0,$=b?"per-parent-c16":"batch-in",C=b?a.length:Math.ceil(a.length/oe)||1,T=b?Math.ceil(a.length/Me):void 0,k=Array.from(m.values()).reduce((M,B)=>M+B.length,0);if(this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,f,{relationType:t.type,targetTable:t.targetTable,strategy:g?.strategy??$,roundtrips:g?.roundtrips??C,concurrencyWaves:g?.concurrencyWaves??T,ioConcurrency:g?.ioConcurrency,rowsTransferred:g?.rowsTransferred??p.length,rowsReturned:k,rowsDiscarded:Math.max(0,(g?.rowsTransferred??p.length)-k),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let M of p)this.adapter.postProcessInverseChild(M,u,y);let _=this.enrichNestedDescs(d,t.nestedDeep,c);_.length>0&&await this.execute(p,_,n,i+1,t.targetTable);let F=t.type==="one-to-one";for(let M of e){let B=this.adapter.keyOf(M[s]),S=m.get(B)||[];M[t.relationName]=F?S[0]||null:S}}async fetchM2MRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=this.uniqueValues(e.map(T=>T[s]));if(a.length===0)return;let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{nestedDescs:c,fetchSpec:d}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),l=performance.now(),{grouped:f,docs:p,stats:h}=await this.adapter.fetchM2M(e,t,o,u,d),g=t.userLimit!==void 0&&t.userLimit>0,m=g?"m2m-per-parent-c16":"m2m-batch",y=g?a.length:Math.ceil(a.length/oe)||1,b=g?Math.ceil(a.length/Me):void 0,$=Array.from(f.values()).reduce((T,k)=>T+k.length,0);this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,l,{relationType:t.type,targetTable:t.targetTable,strategy:h?.strategy??m,roundtrips:h?.roundtrips??y,concurrencyWaves:h?.concurrencyWaves??b,ioConcurrency:h?.ioConcurrency,rowsTransferred:h?.rowsTransferred??p.length,rowsReturned:$,rowsDiscarded:h?.rowsDiscarded??Math.max(0,(h?.rowsTransferred??p.length)-$),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort});let C=this.enrichNestedDescs(c,t.nestedDeep,u);C.length>0&&p.length>0&&await this.execute(p,C,n,i+1,t.targetTable);for(let T of e){let k=this.adapter.keyOf(T[s]);T[t.relationName]=f.get(k)||[]}}}});var zr,Ce,bn=q(()=>{"use strict";zr=2,Ce=class{constructor(e=2){this.concurrency=e;this.active=0;this.waiters=[];if(!Number.isInteger(e)||e<1)throw new Error("Batch execution concurrency must be a positive integer")}async run(e){await this.acquire();try{return await e()}catch(t){throw this.cancel(t),t}finally{this.release()}}async acquire(){if(this.failure!==void 0)throw this.failure;if(this.active<this.concurrency){this.active+=1;return}if(await new Promise(e=>this.waiters.push(e)),this.failure!==void 0)throw this.failure;this.active+=1}release(){this.active-=1,this.failure===void 0&&this.waiters.shift()?.()}cancel(e){if(this.failure===void 0){this.failure=e;for(let t of this.waiters.splice(0))t()}}}});function x(r,e){let t=e==="mysql"?r.replace(/`/g,"``"):r.replace(/"/g,'""');switch(e){case"mysql":return`\`${t}\``;case"postgres":case"pg":case"sqlite":return`"${t}"`;case"mongodb":return r;default:return`\`${t}\``}}function Re(r,e){return r.split(".").map(t=>t==="*"||t.startsWith('"')&&t.endsWith('"')||t.startsWith("`")&&t.endsWith("`")?t:x(t,e)).join(".")}var ae=q(()=>{"use strict"});function ce(r,e,t){e&&Rn(r,e,t,"and")}function Rn(r,e,t,n){switch(e.kind){case"true":return;case"false":n==="or"?r.orWhereRaw("1 = 0"):r.whereRaw("1 = 0");return;case"and":{let i=function(){for(let o of e.children)this.where(function(){Rn(this,o,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"or":{let i=function(){for(let o of e.children)this.orWhere(function(){Rn(this,o,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"not":{let i=function(){this.whereNot(function(){Rn(this,e.child,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"compare":jo(r,e,t,n);return;case"relation_exists":console.warn(`[sql-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${e.joinId}) \u2014 expected to be handled by applyRelationFilters. Filter silently skipped.`);return}}function jo(r,e,t,n){if(e.field.joinId!==null){console.warn(`[sql-render-filter] compare node has joinId=${e.field.joinId} (field=${e.field.fieldName}) but reached renderer \u2014 expected join path to handle it. Filter silently skipped.`);return}let i=Bo(e.field,t),o=Re(i,t.dbType),s=!!e.field.isUuid,a=t.dbType==="postgres",u=n==="or"?"orWhere":"where",c=n==="or"?"orWhereRaw":"whereRaw",d=n==="or"?"orWhereIn":"whereIn",l=n==="or"?"orWhereNotIn":"whereNotIn",f=n==="or"?"orWhereBetween":"whereBetween",p=n==="or"?"orWhereNull":"whereNull",h=n==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":s&&a&&typeof e.value=="string"?r[c](`${o} = ?::uuid`,[e.value]):r[u](i,"=",e.value);return;case"neq":s&&a&&typeof e.value=="string"?r[c](`${o} != ?::uuid`,[e.value]):r[u](i,"!=",e.value);return;case"gt":s&&a&&typeof e.value=="string"?r[c](`${o} > ?::uuid`,[e.value]):r[u](i,">",e.value);return;case"gte":s&&a&&typeof e.value=="string"?r[c](`${o} >= ?::uuid`,[e.value]):r[u](i,">=",e.value);return;case"lt":s&&a&&typeof e.value=="string"?r[c](`${o} < ?::uuid`,[e.value]):r[u](i,"<",e.value);return;case"lte":s&&a&&typeof e.value=="string"?r[c](`${o} <= ?::uuid`,[e.value]):r[u](i,"<=",e.value);return;case"in":{let g=ii(e.value);s&&a&&g.every(m=>typeof m=="string")?r[c](`${o} = ANY(?::uuid[])`,[g]):r[d](i,g);return}case"not_in":{let g=ii(e.value);s&&a&&g.every(m=>typeof m=="string")?r[c](`${o} != ALL(?::uuid[])`,[g]):r[l](i,g);return}case"contains":lr(r,o,e.value,"contains",t,n);return;case"starts_with":lr(r,o,e.value,"starts_with",t,n);return;case"ends_with":lr(r,o,e.value,"ends_with",t,n);return;case"between":Array.isArray(e.value)&&e.value.length===2&&r[f](i,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?r[p](i):r[h](i);return}}function lr(r,e,t,n,i,o){let s=o==="or"?"orWhereRaw":"whereRaw";if(i.dbType==="postgres"){let u=n==="contains"?`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?)) || '%'`:n==="starts_with"?`lower(unaccent(${e})) ILIKE lower(unaccent(?)) || '%'`:`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?))`;r[s](u,[t]);return}if(i.dbType==="sqlite"){let u=n==="contains"?`lower(${e}) LIKE '%' || lower(?) || '%'`:n==="starts_with"?`lower(${e}) LIKE lower(?) || '%'`:`lower(${e}) LIKE '%' || lower(?)`;r[s](u,[t]);return}let a=n==="contains"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:n==="starts_with"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`;r[s](a,[t])}function Bo(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function ii(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var cr=q(()=>{"use strict";ae()});function H(r){return r.columns.find(e=>e.isPrimary)||null}var qt=q(()=>{"use strict"});var oi={};Mn(oi,{expandFieldsToJoinsAndSelect:()=>ur});async function ur(r,e,t,n,i,o){let s=[],a=[],u=await t(r);if(!u)return{select:[],batchFetchDescriptors:[]};let c=new Map;for(let l of e)if(l==="*"||!l.includes("."))c.has("")||c.set("",[]),c.get("").push(l);else{let f=l.split("."),p=f[0],h=f.slice(1).join(".");c.has(p)||c.set(p,[]),c.get(p).push(h)}if(o&&typeof o=="object")for(let[l,f]of Object.entries(o)){if(c.has(l))continue;let p=f&&typeof f=="object"&&f.fields!=null?Array.isArray(f.fields)?f.fields:String(f.fields).split(",").map(h=>h.trim()).filter(Boolean):["*"];c.set(l,p)}let d=c.get("")||[];for(let l of d){if(l==="*"){let h=new Set;for(let m of u.relations||[])if(m.type==="many-to-one"||m.type==="one-to-one"&&!m.isInverse){let y=m.foreignKeyColumn||J(m.propertyName);y&&h.add(y)}let g=new Set;for(let m of u.columns)h.has(m.name)||(s.push(`${r}.${m.name}`),g.add(m.name));for(let m of u.relations||[])!c.has(m.propertyName)&&!g.has(m.propertyName)&&c.set(m.propertyName,["id"]);continue}if(l.includes(".")){s.push(`${r}.${l}`);continue}if(u.columns?.find(h=>h.name===l)){s.push(`${r}.${l}`);continue}if(u.relations?.find(h=>h.propertyName===l)){c.has(l)||c.set(l,["id"]);continue}}return c.forEach((l,f)=>{if(f==="")return;let p=u.relations?.find(b=>b.propertyName===f);if(!p)return;if(p.type==="many-to-one"||p.type==="one-to-one"&&!p.isInverse){let b=p.foreignKeyColumn||J(p.propertyName),$=x(r,n),C=x(b,n),T=x(f,n);s.push(`${$}.${C} as ${T}`)}let g=p.targetTableName||p.targetTable,m=o?.[f],y=m?.fields!=null?Array.isArray(m.fields)?m.fields:String(m.fields).split(",").map(b=>b.trim()).filter(Boolean):l;a.push({relationName:f,type:p.type,targetTable:g,fields:y,isInverse:p.isInverse,fkColumn:p.foreignKeyColumn,mappedBy:p.mappedBy,junctionTableName:p.junctionTableName,junctionSourceColumn:p.junctionSourceColumn,junctionTargetColumn:p.junctionTargetColumn,userFilter:m?.filter,userSort:m?.sort,userLimit:m?.limit!==void 0?Number(m.limit):void 0,userPage:m?.page!==void 0?Number(m.page):void 0,nestedDeep:m?.deep})}),{select:s,batchFetchDescriptors:a}}var dr=q(()=>{"use strict";Ke();ae()});var Ut,Qt,Fn,ot,Lo,st,pr=q(()=>{"use strict";Ke();ae();qt();Ge();bn();cr();Mt();Et();Ut="__enfyra_row_number__",Qt="__sourceId__",Fn="__targetId__",ot="__enfyra_partitioned__",Lo=5e4,st=class{constructor(e,t="postgres",n,i=new Ce){this.knex=e;this.dbType=t;this.metadata=n;this.executionBudget=i;this.pkField="id"}chunkCount(e,t=oe){return Math.ceil(e.length/t)||1}m2mTargetChunkSize(){return this.dbType==="postgres"?Lo:oe}uniqueValues(e){return Array.from(new Map(e.filter(t=>t!=null).map(t=>[this.keyOf(t),t])).values())}runQuery(e){return this.executionBudget.run(()=>e)}buildPartitionRowNumber(e,t,n){let i=[...t];i.some(s=>s.column===n)||i.push({column:n,order:"asc"});let o=i.map(s=>`?? ${s.order.toUpperCase()}`).join(", ");return this.knex.raw(`ROW_NUMBER() OVER (PARTITION BY ?? ORDER BY ${o}) as ??`,[e,...i.map(s=>s.column),Ut])}buildPartitionSlice(e,t,n,i){return this.knex.from(e.as(ot)).select(`${ot}.*`).where(`${ot}.${Ut}`,">",n).andWhere(`${ot}.${Ut}`,"<=",n+i).orderBy(`${ot}.${t}`,"asc").orderBy(`${ot}.${Ut}`,"asc")}removePartitionFields(e){for(let t of e)delete t[Ut]}buildFilterTree(e,t){if(!e||!this.metadata)return null;let n=new ie,i=this.metadata?.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))},{node:o}=fe(e,t,i,n);return o}parseSortTokens(e,t,n){return e?(Array.isArray(e)?e:e.split(",").map(o=>o.trim()).filter(Boolean)).map(o=>{let s=o.startsWith("-"),u=(s?o.slice(1):o).split(".");if(u.length===1)return{column:n?`${n}.${u[0]}`:`${t}.${u[0]}`,order:s?"desc":"asc"};let c=u[u.length-1];return{column:`${`__sort_${u.slice(0,-1).join("_")}`}.${c}`,order:s?"desc":"asc"}}):[]}applySortJoins(e,t,n,i){if(!t||!this.metadata)return;let o=Array.isArray(t)?t:t.split(",").map(a=>a.trim()).filter(Boolean),s=new Set;for(let a of o){let c=(a.startsWith("-")?a.slice(1):a).split(".");if(c.length<=1)continue;let d=n,l=i||n;for(let f=0;f<c.length-1;f++){let p=c[f],h=this.metadata?.tables?.get(d);if(!h)break;let g=h.relations?.find(b=>b.propertyName===p);if(!g)break;let m=g.targetTableName||g.targetTable,y=`__sort_${c.slice(0,f+1).join("_")}`;if(!s.has(y)){s.add(y);let b=g.foreignKeyColumn||J(g.propertyName),$=this.metadata?.tables?.get(m),C=$&&H($)?.name||"id";e.leftJoin(`${m} as ${y}`,`${y}.${C}`,`${l}.${b}`)}d=m,l=y}}}toKnexSelect(e,t){let n=e.indexOf(" as ");if(n!==-1){let i=e.substring(0,n),o=e.substring(n+4),s=x(o,this.dbType),a=t?`${t}.${x(i,this.dbType)}`:x(i,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${t}.${x(e,this.dbType)} as ${x(e,this.dbType)}`):e}keyOf(e){return e==null?"":String(e)}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return H(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;return!t&&e.mappedBy&&(t=J(e.mappedBy)),t||(t=J(e.targetTable)),t}resolveParentPk(e){return e&&H(e)?.name||"id"}resolveFields(e,t){let{rootFields:n,subRelations:i}=He(e),o=[];if(n.includes("*")){let c=new Set;for(let d of t.relations||[])if(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse){let l=d.foreignKeyColumn||J(d.propertyName);l&&c.add(l)}for(let d of t.columns)c.has(d.name)||o.push(d.name);for(let d of t.relations||[])i.has(d.propertyName)||i.set(d.propertyName,["id"])}else for(let c of n){let d=t.columns.find(l=>l.name===c);d?o.push(d.name):t.relations?.find(f=>f.propertyName===c)&&!i.has(c)&&i.set(c,["id"])}let s=H(t)?.name||"id";o.includes(s)||o.push(s),i.forEach((c,d)=>{let l=t.relations?.find(f=>f.propertyName===d);if(l&&(l.type==="many-to-one"||l.type==="one-to-one"&&!l.isInverse)){let f=l.foreignKeyColumn||J(l.propertyName);f&&o.push(`${f} as ${d}`)}});let a=[];return i.forEach((c,d)=>{let l=t.relations?.find(p=>p.propertyName===d);if(!l)return;let f=l.targetTableName||l.targetTable;f&&a.push({relationName:d,type:l.type,targetTable:f,fields:c,isInverse:l.isInverse,fkColumn:l.foreignKeyColumn,mappedBy:l.mappedBy,junctionTableName:l.junctionTableName,junctionSourceColumn:l.junctionSourceColumn,junctionTargetColumn:l.junctionTargetColumn})}),{isPkOnly:o.length===1&&o[0]===s&&a.length===0,nestedDescs:a,fetchSpec:{selectCols:o,pkCol:s}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?this.buildFilterTree(i.userFilter,e):null,s=i?.userSort?this.parseSortTokens(i.userSort,e):[],a=n.selectCols.map(c=>this.toKnexSelect(c)),u=await W(t,c=>{let d=this.knex(e).select(a).whereIn(n.pkCol,c);if(o&&ce(d,o,{dbType:this.dbType,rootTable:e}),s.length>0){this.applySortJoins(d,i.userSort,e);for(let l of s)d.orderBy(l.column,l.order)}return this.runQuery(d)});return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(t),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,n,i,o){let s=t,a=i.selectCols.find(h=>h.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():i.selectCols.includes(t)||i.selectCols.push(t);let u=o?.userFilter?this.buildFilterTree(o.userFilter,e):null,c=o?.userSort?this.parseSortTokens(o.userSort,e):[],d=o?.userLimit,l=o?.userPage;if(d!==void 0&&d>0){let h=l?(l-1)*d:0,g=i.selectCols.map(y=>this.toKnexSelect(y)),m=await W(n,async y=>{let b=this.knex(e).select(g).select(this.buildPartitionRowNumber(`${e}.${t}`,c,`${e}.${i.pkCol}`)).whereIn(`${e}.${t}`,y);u&&ce(b,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(b,o.userSort,e);let $=await this.runQuery(this.buildPartitionSlice(b,s,h,d));return this.removePartitionFields($),$});return{docs:m,groupKeyField:s,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(n),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.length}}}let f=i.selectCols.map(h=>this.toKnexSelect(h)),p=await W(n,h=>{let g=this.knex(e).select(f).whereIn(t,h);if(u&&ce(g,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(g,o?.userSort,e),c.length>0)for(let m of c)g.orderBy(m.column,m.order);else g.orderBy(i.pkCol,"asc");return this.runQuery(g)});return{docs:p,groupKeyField:s,stats:{strategy:"batch-in",roundtrips:this.chunkCount(n),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length}}}postProcessInverseChild(e,t,n){n||delete e[t]}async selectM2MEdges(e,t,n,i,o,s,a,u){let c=`t.${s}`,d=!!a||u.some(g=>g.column!==c),l=d?u:u.map(g=>({...g,column:`${n}.${o}`})),f=t.userLimit,p=t.userPage;if(f!==void 0&&f>0){let g=p?(p-1)*f:0;return(await W(e,async y=>{let b=this.knex(n).select({[Qt]:`${n}.${i}`,[Fn]:`${n}.${o}`}).whereIn(`${n}.${i}`,y);d&&(b=b.join(`${t.targetTable} as t`,`${n}.${o}`,`t.${s}`),a&&ce(b,a,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(b,t.userSort,t.targetTable,"t")),b.select(this.buildPartitionRowNumber(`${n}.${i}`,l,d?c:`${n}.${o}`));let $=await this.runQuery(this.buildPartitionSlice(b,Qt,g,f));return this.removePartitionFields($),$})).map(y=>({sourceId:y[Qt],targetId:y[Fn]}))}return(await W(e,g=>{let m=this.knex(n).select({[Qt]:`${n}.${i}`,[Fn]:`${n}.${o}`}).whereIn(`${n}.${i}`,g);if(d&&(m=m.join(`${t.targetTable} as t`,`${n}.${o}`,`t.${s}`),a&&ce(m,a,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(m,t.userSort,t.targetTable,"t")),m.orderBy(`${n}.${i}`,"asc"),l.length>0){for(let y of l)m.orderBy(y.column,y.order);d&&!l.some(y=>y.column===c)&&m.orderBy(c,"asc")}else m.orderBy(`${n}.${o}`,"asc");return this.runQuery(m)})).map(g=>({sourceId:g[Qt],targetId:g[Fn]}))}async loadM2MTargets(e,t,n){if(t.length===0)return[];let i=n.selectCols.map(o=>this.toKnexSelect(o));return W(t,o=>this.runQuery(this.knex(e).select(i).whereIn(n.pkCol,o)),this.m2mTargetChunkSize())}async fetchM2M(e,t,n,i,o){let s=this.resolveParentPk(n),a=this.uniqueValues(e.map(_=>_[s]));if(a.length===0)return{grouped:new Map,docs:[]};let u=t.junctionTableName,c=t.junctionSourceColumn,d=t.junctionTargetColumn;if(!u||!c||!d)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let l=t.userFilter?this.buildFilterTree(t.userFilter,t.targetTable):null,f=t.userSort?this.parseSortTokens(t.userSort,t.targetTable,"t"):[],p=await this.selectM2MEdges(a,t,u,c,d,o.pkCol,l,f),h=new Map;for(let _ of a)h.set(this.keyOf(_),[]);let g=o.selectCols.length===1&&o.selectCols[0]===o.pkCol,m=t.userLimit!==void 0&&t.userLimit>0,y=this.chunkCount(a),b=`t.${o.pkCol}`,$=!l&&f.every(_=>_.column===b);if(g){let _=new Map;for(let F of p){let M=this.keyOf(F.targetId);_.has(M)||_.set(M,{[o.pkCol]:F.targetId}),h.get(this.keyOf(F.sourceId))?.push(_.get(M))}return{grouped:h,docs:[],stats:{strategy:$?m?"m2m-junction-partitioned-top-k":"m2m-junction-batch":m?"m2m-filtered-edge-top-k":"m2m-filtered-edge-batch",roundtrips:y,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let C=this.uniqueValues(p.map(_=>_.targetId)),T=await this.loadM2MTargets(t.targetTable,C,o),k=new Map(T.map(_=>[this.keyOf(_[o.pkCol]),_]));for(let _ of p){let F=k.get(this.keyOf(_.targetId));F&&h.get(this.keyOf(_.sourceId))?.push(F)}return{grouped:h,docs:T,stats:{strategy:m?"m2m-partitioned-edge-loader":"m2m-edge-loader",roundtrips:y+(C.length>0?this.chunkCount(C,this.m2mTargetChunkSize()):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+T.length,rowsDiscarded:0}}}}});var li={};Mn(li,{executeBatchFetches:()=>gr});async function gr(r,e,t,n,i=3,o=0,s,a="postgres",u,c){let d=new st(r,a,u);await new Se(d,n,c).execute(e,t,i,o,s)}var hr=q(()=>{"use strict";Ge();pr()});var qo={};Mn(qo,{ALL_SUPPORTED_OPERATORS:()=>Nt,AuthenticationException:()=>gt,AuthorizationException:()=>ht,BadRequestException:()=>I,BatchExecutionBudget:()=>Ce,BatchFetchEngine:()=>Se,BusinessLogicException:()=>ut,CHUNKED_FETCH_CONCURRENCY:()=>Gn,ConfigurationException:()=>$t,DEEP_TO_MANY_DEFAULT_LIMIT:()=>Yn,DEFAULT_BATCH_FETCH_IO_CONCURRENCY:()=>zr,DEFAULT_TIMEOUT_MS:()=>Vt,DOTTED_PATH_MAX_HOPS:()=>Nn,DatabaseException:()=>Le,DuplicateResourceException:()=>pt,ErrorHandler:()=>ve,ExecutorEngineService:()=>Be,ExternalServiceException:()=>bt,FIELD_OPERATORS:()=>we,FileNotFoundException:()=>St,FileSizeExceededException:()=>Ct,FileUploadException:()=>Tt,HttpException:()=>P,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>Yt,InvalidTokenException:()=>yt,IsolatedExecutorService:()=>We,JoinRegistry:()=>ie,LOGICAL_OPERATORS:()=>Kn,MongoBatchAdapter:()=>Xe,MongoQueryExecutor:()=>Ae,PER_PARENT_CONCURRENCY:()=>Me,QueryBuilderService:()=>at,QueryPlanner:()=>Z,ResourceNotFoundException:()=>ft,SchemaException:()=>wt,ScriptContractService:()=>tn,ScriptExecutionException:()=>ye,ScriptTimeoutException:()=>me,ServiceUnavailableException:()=>_t,SqlBatchAdapter:()=>st,SqlQueryExecutor:()=>je,TokenExpiredException:()=>mt,ValidationException:()=>dt,WHERE_IN_CHUNK_SIZE:()=>oe,WorkerPool:()=>Rt,appendIsolatedExecutorRuntimeLog:()=>Q,applyOperatorToMatch:()=>an,applyRelationFilters:()=>Lt,applyWhereToKnex:()=>it,assertFieldOperatorValueIsClean:()=>un,buildMongoCharFoldMapJson:()=>Dn,buildMongoFoldTextSearchJs:()=>nn,buildRelationSubquery:()=>Bt,buildSqlWherePartsFromFieldAst:()=>Wt,buildWhereClause:()=>le,camelToSnake:()=>Nr,chunkedFetch:()=>W,compileScriptSource:()=>qi,computeEngineTuning:()=>An,createEnfyraKernel:()=>Ko,dslOpToCompareOp:()=>ln,encodeMainThreadToIsolate:()=>jn,escapeSqlValue:()=>Kt,executeBatchFetches:()=>gr,executeMongoBatchFetches:()=>wn,expandFieldsToJoinsAndSelect:()=>ur,getEffectiveCpuCount:()=>On,getEffectiveMemoryBytes:()=>kt,getEngineTuning:()=>en,getExecutableScript:()=>zi,getForeignKeyColumnName:()=>J,getIoAbortSignal:()=>Cr,getJunctionColumnNames:()=>xt,getJunctionTableName:()=>vt,getPrimaryKeyColumn:()=>H,getScriptLegacyField:()=>Di,getShortFkConstraintName:()=>xr,getShortFkName:()=>Er,getShortIndexName:()=>Mr,getShortPkName:()=>vr,hasLogicalOperators:()=>he,isExecutableJavaScript:()=>Ui,isScriptTable:()=>Wi,normalizeAggregateQuery:()=>tt,normalizeFlowStepScriptConfig:()=>Hi,normalizeScriptLanguage:()=>Ki,normalizeScriptPatch:()=>Ji,normalizeScriptRecord:()=>Qi,parseBatchFields:()=>He,parseFields:()=>$n,parseFilter:()=>fe,perParentRun:()=>_n,quoteIdentifier:()=>x,quoteQualifiedIdentifier:()=>Re,resolveExecutableScript:()=>Vi,rewriteFilterDenyingFields:()=>di,rewriteSortDroppingDenied:()=>fi,runWithIoAbortSignal:()=>kr,scriptContractService:()=>te,separateFilters:()=>V,snakeToCamel:()=>Ir,throwUnsupportedFieldOperator:()=>Ee,validateDeepOptions:()=>mr,validateFilterShape:()=>re,whereToMongoFilter:()=>Qe});module.exports=bi(qo);var Vt=3e4,Be=class{constructor(e){this.isolatedExecutorService=e.isolatedExecutorService}register(e,t){e.routeData.__codeBlocks||(e.routeData.__codeBlocks=[]),e.routeData.__codeBlocks.push(t)}async runBatch(e,t,n={}){let i=e.routeData.__codeBlocks||[];return i.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(i,e.routeData.context,t??Vt,n)}async run(e,t,n=Vt,i={}){return this.isolatedExecutorService.run(e,t,n,i)}};var Ht=class{constructor(e){this.context=e}log(e){console.log(this.format(e))}warn(e){console.warn(this.format(e))}error(e,t){console.error(this.format(e)),t&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};var $r=require("async_hooks"),Tr=ue(require("path")),Sr=require("stream");var br=require("child_process"),_i=["PATH","HOME","NODE_ENV","TMPDIR","LANG"];function wi(){let r={};for(let e of _i){let t=process.env[e];t!==void 0&&(r[e]=t)}return r}var Gt=class{constructor(e){this.terminated=!1;this.child=(0,br.fork)(e,[],{stdio:["ignore","ignore","ignore","ipc"],env:wi(),serialization:"advanced"})}get pid(){return this.child.pid}on(e,t){return this.child.on(e,t),this}off(e,t){return this.child.off(e,t),this}postMessage(e){if(!this.child.connected)throw new Error("Executor runner IPC is closed");this.child.send(e)}terminate(){if(this.terminated)return;this.terminated=!0;try{this.child.disconnect()}catch{}try{this.child.kill("SIGTERM")}catch{}setTimeout(()=>{if(!(this.child.exitCode!==null||this.child.signalCode!==null))try{this.child.kill("SIGKILL")}catch{}},250).unref?.()}};var me=class extends Error{constructor(t=0,n,i){let o=typeof t=="number"&&t>0?`${t}ms`:String(t||"configured timeout");super(`Script execution timed out after ${o}`);this.statusCode=408;this.errorCode="SCRIPT_TIMEOUT";this.name="ScriptTimeoutException",this.details={timeoutMs:t,scriptId:n,...i}}},ye=class extends Error{constructor(t,n,i){super(`Script execution failed: ${t}`);this.statusCode=400;this.errorCode="SCRIPT_EXECUTION_ERROR";this.name="ScriptExecutionException",this.details={scriptId:n,...i}}},j=class extends Error{constructor(t,n,i,o){super(t);this.statusCode=n;this.errorCode=i;this.name=this.constructor.name,this.details=o}},P=class extends j{constructor(e,t,n){super(e,t,`HTTP_${t}`,n)}},ut=class extends j{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},dt=class extends j{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},ft=class extends j{constructor(e,t){super(t?`${e} with identifier '${t}' not found`:`${e} not found`,404,"RESOURCE_NOT_FOUND",{resource:e,identifier:t})}},pt=class extends j{constructor(e,t,n){super(`${e} with ${t} '${n}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:n})}},gt=class extends j{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},ht=class extends j{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},mt=class extends j{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},yt=class extends j{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},Le=class extends j{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},bt=class extends j{constructor(e,t,n){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:n})}},_t=class extends j{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},wt=class extends j{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},$t=class extends j{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},Tt=class extends j{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},St=class extends j{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},Ct=class extends j{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var ve=class{static createException(e,t,n,i,o){if(e?.includes("$throw"))switch(e){case"$throw.http":return new P(n||"Error",t||500,o);case"$throw.businessLogic":return new ut(n||"Bad request",o);case"$throw.validation":return new dt(n||"Validation failed",o);case"$throw.notFound":return new ft(o?.resource||n||"Resource",o?.identifier);case"$throw.duplicate":return new pt(o?.resource||n||"Resource",o?.field||"field",o?.value||"value");case"$throw.unauthorized":return new gt(n||"Unauthorized");case"$throw.forbidden":return new ht(n||"Forbidden");case"$throw.tokenExpired":return new mt;case"$throw.invalidToken":return new yt;case"$throw.database":return new Le(n||"Database error",o);case"$throw.dbQuery":return new Le(n||"Query error",o);case"$throw.externalService":return new bt(n||"Service",n||"Error",o);case"$throw.serviceUnavailable":return new _t(n||"Service");case"$throw.rateLimit":return new P(n||"Rate limit exceeded",429);case"$throw.scriptError":return new ye(n||"Script error",i,o);case"$throw.scriptTimeout":return new me(o?.timeout||5e3,i);case"$throw.schema":return new wt(n||"Schema error",o);case"$throw.config":return new $t(n||"Configuration error",o);case"$throw.fileUpload":return new Tt(n||"File upload error",o);case"$throw.fileNotFound":return new St(n||"File not found");case"$throw.fileSizeExceeded":return new Ct(o?.maxSize||"unknown",o?.actualSize||"unknown");case"$throw.400":return new P(n||"Bad request",400,o);case"$throw.401":return new P(n||"Authentication required",401,o);case"$throw.403":return new P(n||"Insufficient permissions",403,o);case"$throw.404":return new P(n||"Not found",404,o);case"$throw.409":return new P(n||"Conflict",409,o);case"$throw.422":return new P(n||"Validation failed",422,o);case"$throw.429":return new P(n||"Rate limit exceeded",429,o);case"$throw.500":return new P(n||"Internal server error",500,o);case"$throw.503":return new P(n||"Service unavailable",503,o);default:return new ye(n||"Unknown error",i)}if(t)switch(t){case 400:return new P(n||"Bad request",400,o);case 401:return new P(n||"Authentication required",401,o);case 403:return new P(n||"Insufficient permissions",403,o);case 404:return new P(n||"Not found",404,o);case 409:return new P(n||"Conflict",409,o);case 422:return new P(n||"Validation failed",422,o);case 429:return new P(n||"Rate limit exceeded",429,o);case 500:return new P(n||"Internal server error",500,o);case 503:return new P(n||"Service unavailable",503,o);default:return new ye(n||"Unknown error",i,o)}return new ye(n||"Unknown error",i,o)}};var Xt=ue(require("fs")),Zt=ue(require("path")),Yt=Zt.join(process.cwd(),"test","logs","isolated-executor-runtime.log");function $i(){return process.env.ISOLATED_EXECUTOR_FILE_LOG==="0"?!1:process.env.ISOLATED_EXECUTOR_FILE_LOG==="1"?!0:process.env.JEST_WORKER_ID!==void 0}var Ti=$i();function Q(r){if(Ti)try{let e=Zt.dirname(Yt);Xt.mkdirSync(e,{recursive:!0});let t=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...r})+`
|
|
2
|
-
`;Xt.appendFileSync(Yt,t)}catch{}}var be=ue(require("os")),De=ue(require("fs"));function kt(){try{let r=De.readFileSync("/sys/fs/cgroup/memory.max","utf8").trim();if(r!=="max"){let e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<be.totalmem())return e}}catch{}try{let r=De.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes","utf8").trim(),e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<be.totalmem())return e}catch{}return be.totalmem()}function On(){let r=be.availableParallelism?.()||be.cpus()?.length||1;try{let e=De.readFileSync("/sys/fs/cgroup/cpu.max","utf8").trim(),[t,n]=e.split(/\s+/);if(t!=="max"){let i=parseInt(t,10),o=parseInt(n,10);if(i>0&&o>0)return Math.max(1,Math.ceil(i/o))}}catch{}try{let e=parseInt(De.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8").trim(),10),t=parseInt(De.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_period_us","utf8").trim(),10);if(e>0&&t>0)return Math.max(1,Math.ceil(e/t))}catch{}return r}var Si=.25,Ci=16,ki=2048,Ri=40,Fi=128,vi=32;function An(r){let e=Math.max(1,Math.trunc(r.logicalCpuCount)||1),t=Math.max(1,r.totalMemoryBytes/(1024*1024)),n=Math.min(Fi,Math.max(Ri,Math.round(t/vi))),i=t*Si,o=Math.max(1,Math.floor(i/n)),s=Math.max(1,Math.min(e,2,o)),a=t<ki?1:Ci,u=Math.max(1,Math.min(a,Math.floor(i/(s*n))));return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:u,isolatePoolSize:u}}function en(){return An({logicalCpuCount:On(),totalMemoryBytes:kt()})}var Bi=Tr.join(__dirname,"execution/worker.js"),Li=1e3,Pn=new $r.AsyncLocalStorage;function Cr(){return Pn.getStore()}function kr(r,e){return Pn.run(r,e)}var Rt=class{constructor(e,t,n,i,o,s,a,u=6e4){this.scriptPath=o;this.onCrash=s;this.onRotate=a;this.entries=[];this.waiting=[];this.cachedMemoryOk=!0;this.lastMemoryCheckMs=0;this.memorySampleIntervalMs=200;this.destroying=!1;this.entryCounter=0;this.max=e,this.effectiveMemory=t,this.rssCeiling=n,this.tasksCap=i,this.drainTimeoutMs=u;for(let c=0;c<e;c++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new Gt(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,reservations:0,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let i=t.tasks.get(n.id);i&&(n.type==="taskReleased"?i.onRelease?.():n.type==="result"||n.type==="taskCancelled"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),n.contextStats&&(t.contextStats=n.contextStats),i.onResult(n.type==="taskCancelled"?{type:"result",id:n.id,success:!1,taskCancelled:!0,error:{message:"Task cancelled",code:"ERR_TASK_CANCELLED"}}:n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):i.onIoCall(n))}),e.on("exit",()=>{let n=t.draining,i=this.destroying;t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,s]of t.tasks)s.abortController.abort(),s.onResult({type:"result",success:!1,error:{message:i?"Worker terminated":t.lastError?`Worker crashed: ${t.lastError}`:"Worker crashed",code:i?void 0:"ERR_EXECUTOR_RUNNER_LOST",details:i?void 0:{outcome:"unknown_outcome",retryable:!1}}});t.tasks.clear();let o=this.entries.indexOf(t);o!==-1&&this.entries.splice(o,1),!n&&!i&&(this.onCrash&&this.onCrash(),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),e.on("error",n=>{t.lastError=n.message}),this.entries.push(t),t}rotateEntry(e,t){if(e.draining)return;e.draining=!0;let n=Date.now()-e.spawnedAt;if(this.onRotate&&this.onRotate({reason:t,ageMs:n}),this.spawnEntry(),e.tasks.size===0){e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,e.worker.terminate()},this.drainTimeoutMs)}isMemoryAvailable(){let e=Date.now();return e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs&&(this.cachedMemoryOk=process.memoryUsage().rss/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e),this.cachedMemoryOk}findLeastBusy(){let e=null;for(let t of this.entries){if(t.draining)continue;let n=t.tasks.size+t.reservations;n<this.tasksCap&&(!e||n<e.tasks.size+e.reservations)&&(e=t)}return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size+e.reservations===0||this.isMemoryAvailable())?(e.reservations++,Promise.resolve(e)):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.reservations=Math.max(0,e.reservations-1),e.tasks.set(t,n)}releaseReservation(e){e.reservations=Math.max(0,e.reservations-1),this.drainWaiting()}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&(e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(e&&(e.tasks.size+e.reservations===0||this.isMemoryAvailable()))e.reservations++,this.waiting.shift()(e);else break}}terminateEntry(e){e.worker.terminate()}resize(e){for(this.max=Math.max(1,e);this.entries.length<this.max;)this.spawnEntry()}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,pid:e.worker.pid,activeTasks:e.tasks.size,reservations:e.reservations,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}},wr=new Set(["$helpers","$cache","$transaction","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$debug"]);function jn(r){if(r===void 0)return JSON.stringify({__e:"u"});try{return JSON.stringify({__e:"v",d:r},(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return JSON.stringify({__e:"v",d:{__serializationError:!0,message:"Result is not JSON-serializable"}})}}var We=class r{constructor(e){this.logger=new Ht(r.name);this.effectiveMemory=kt();this.isolationTuning=en();this.pool=new Rt(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Bi,()=>{this.crashesTotal++,this.logger.warn("Worker crashed, replacement spawned")},({reason:e,ageMs:t})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${e} age=${Math.round(t/1e3)}s`)});this.ceiling=this.isolationTuning.maxConcurrentWorkers;this.prevCpuUsage=process.cpuUsage();this.prevCpuTime=process.hrtime.bigint();this.pressureTicks=0;this.recoveryTicks=0;this.taskCounter=0;this.taskDoneTotal=0;this.taskErrorTotal=0;this.taskTimeoutTotal=0;this.rotationsTotal=0;this.crashesTotal=0;this.responseStreams=new Map;this.taskCancellers=new Map;this.taskDurationsMs=[];this.runtimeCallbackCounter=0;this.packageCacheService=e.packageCacheService,this.packageCdnLoaderService=e.packageCdnLoaderService,this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let t=process.memoryUsage().rss/this.effectiveMemory,n=process.hrtime.bigint(),i=process.cpuUsage(this.prevCpuUsage),o=Number(n-this.prevCpuTime)/1e3,s=o>0?(i.user+i.system)/o:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let a=this.pool.getMax(),u=this.pool.getWaitingCount(),c=t>.85||s>.7,d=t<.7&&s<.5,l=u>0,f=a;c?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(f=Math.max(1,a-1))):d&&l?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(f=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),f!==a&&(this.pool.resize(f),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${f} (rss=${Math.round(t*100)}% cpu=${Math.round(s*100)}% queue=${u})`))}createSnapshot(e){let t={$body:e.$body,$query:e.$query,$params:e.$params,$user:e.$user,$share:e.$share,$data:e.$data,$api:{request:e.$api?.request},$uploadedFile:e.$uploadedFile,$req:this.cloneSnapshotValue(e.$req)};for(let i of Object.keys(e)){if(!i.startsWith("$")||i in t||wr.has(i))continue;let o=this.cloneSnapshotValue(e[i]);o!==void 0&&(t[i]=o)}let n=e.$flow;if(n!=null)try{t.$flow=this.cloneSnapshotValue(n)??{}}catch{t.$flow={}}return t}cloneSnapshotValue(e){if(typeof e!="function")try{return JSON.parse(JSON.stringify(e,(t,n)=>{if(typeof n=="bigint")return String(n);if(typeof n!="function")return n}))}catch{return}}mergeCtxChanges(e,t){if(t){t.$body!==void 0&&(e.$body=t.$body),t.$query!==void 0&&(e.$query=t.$query),t.$params!==void 0&&(e.$params=t.$params),t.$data!==void 0&&(e.$data=t.$data),t.$error!==void 0&&(e.$error=t.$error),t.$statusCode!==void 0&&(e.$statusCode=t.$statusCode),t.$share!==void 0&&(e.$share=t.$share),t.$api!==void 0&&e.$api&&(t.$api.error&&(e.$api.error=t.$api.error),t.$api.response&&(e.$api.response=t.$api.response)),t.$flow!==void 0&&t.$flow!==null&&typeof t.$flow=="object"&&e.$flow!=null&&typeof e.$flow=="object"&&Object.assign(e.$flow,t.$flow);for(let[n,i]of Object.entries(t))n.startsWith("$")&&(n==="$body"||n==="$query"||n==="$params"||n==="$data"||n==="$error"||n==="$statusCode"||n==="$share"||n==="$api"||n==="$flow"||wr.has(n)||n==="$env"||(e[n]=i));delete e.$pkgs}}spawnAndExecute(e,t,n,i,o){return(async()=>{let s=await this.pool.dispatch();if(o?.aborted){this.pool.releaseReservation(s);let c=new Error("Execution aborted after client disconnect");return c.code="ERR_EXECUTION_ABORTED",c.isAbort=!0,Promise.reject(c)}let a=`t_${++this.taskCounter}`,u=Date.now();return new Promise((c,d)=>{let l=!1,f=new AbortController,p=!1,h,g=()=>{let _=new Error("Execution aborted after client disconnect");return _.code="ERR_EXECUTION_ABORTED",_.isAbort=!0,_},m=()=>{let _=new Error(`Script execution timed out after ${i}ms`);return _.code="ERR_SCRIPT_EXECUTION_TIMEOUT",_.isTimeout=!0,_},y,b=_=>{if(!(l||p)){p=!0,h=_,f.abort(),this.cleanupResponseStream(a,_);try{s.worker.postMessage({type:"cancelTask",id:a})}catch{}y=setTimeout(()=>{l||(l=!0,clearTimeout(k),T(),this.taskCancellers.delete(a),this.pool.unregisterTask(s,a),this.taskErrorTotal++,Q({event:"task_cancel_grace_terminate",id:a}),this.pool.terminateEntry(s),_.details={..._.details??{},outcome:"unknown_outcome",retryable:!1,escalation:"runner_terminated_after_cancel_grace"},d(_))},Li),y.unref?.()}},$=()=>b(g());this.taskCancellers.set(a,$);let C=()=>$(),T=()=>{o?.removeEventListener("abort",C)};o&&o.addEventListener("abort",C,{once:!0});let k=setTimeout(()=>{l||(this.taskTimeoutTotal++,Q({event:"task_timeout",id:a,timeoutMs:i}),b(m()))},i);this.pool.registerTask(s,a,{abortController:f,onResult:_=>{if(!l){if(_.taskCancelled===!0&&this.pool.unregisterTask(s,a),l=!0,clearTimeout(k),y&&clearTimeout(y),this.taskCancellers.delete(a),T(),this.cleanupResponseStream(a),this.recordTaskDuration(Date.now()-u),p){f.abort(),this.taskErrorTotal++,d(h??g());return}if(_.success){this.taskDoneTotal++,Q({event:"task_done",id:a,ok:!0});let F={value:_.value,valueAbsent:_.valueAbsent===!0,ctxChanges:_.ctxChanges};_.shortCircuit&&(F.shortCircuit=!0),c(F)}else{this.taskErrorTotal++,Q({event:"task_done",id:a,ok:!1,message:_.error?.message});let F=new Error(_.error?.message||"Handler execution failed");F.statusCode=_.error?.statusCode,F.code=_.error?.code,F.details=_.error?.details,_.error?.stack&&(F.stack=_.error.stack),_.ctxChanges&&(F.ctxChanges=_.ctxChanges),this.cleanupResponseStream(a,F),d(F)}}},onRelease:()=>{this.pool.unregisterTask(s,a)},onIoCall:_=>{if(l)return;let F=f.signal;_.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(_,n),s.worker,_.callId,F):_.type==="transactionCall"?this.handleIoCall(()=>this.execTransactionCall(_,n,s.worker),s.worker,_.callId,F):_.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(_,n),s.worker,_.callId,F):_.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(_,n),s.worker,_.callId,F):_.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(_,n),s.worker,_.callId,F):_.type==="storageCall"?this.handleIoCall(()=>this.execStorageCall(_,n,s.worker),s.worker,_.callId,F):_.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall(_,n),s.worker,_.callId,F):_.type==="resCall"&&this.handleIoCall(()=>this.execResCall(_,n),s.worker,_.callId,F)}}),s.worker.postMessage({type:e,id:a,...t}),o?.aborted&&$()})})()}postAbortedCallError(e,t){try{e.postMessage({type:"callError",callId:t,error:JSON.stringify({__userThrow:!0,message:"Execution aborted after client disconnect",code:"ERR_EXECUTION_ABORTED"})})}catch{}}async handleIoCall(e,t,n,i){if(i?.aborted){this.postAbortedCallError(t,n);return}try{let o=await(i?Pn.run(i,e):e());if(i?.aborted){this.postAbortedCallError(t,n);return}try{t.postMessage({type:"callResult",callId:n,result:jn(o)})}catch{}}catch(o){if(i?.aborted){this.postAbortedCallError(t,n);return}try{let s={__userThrow:!0,message:o.message,statusCode:o.statusCode,code:o.errorCode??o.code,details:o.details,messages:o.messages};t.postMessage({type:"callError",callId:n,error:JSON.stringify(s)})}catch{}}}async execRepoCall(e,t){let n=JSON.parse(e.argsJson),i=e.access==="secure"?t?.$repos?.secure?.[e.table]:t?.$repos?.[e.table];if(!i||typeof i[e.method]!="function"){let o=e.access==="secure"?"secure.":"";throw new Error(`Repo method not found: ${o}${e.table}.${e.method}`)}return i[e.method](...n)}async execTransactionCall(e,t,n){let o=JSON.parse(e.argsJson||"[]").map(a=>a?.__fnRef&&typeof a.__fnRef=="string"?(...u)=>this.invokeRuntimeCallback(n,e.id,a.__fnRef,u):a)[0];if(typeof o!="function")throw new Error("$transaction.run requires a callback");let s=t?.$transaction?.run;if(typeof s!="function")throw new Error("$transaction is not available");return await s.call(t.$transaction,o)}async execHelpersCall(e,t){let n=JSON.parse(e.argsJson),i=e.name.split("."),o=t?.$helpers;for(let s of i)o=o?.[s];if(typeof o!="function")throw new Error(`Helper not found: ${e.name}`);return o(...n)}async execSocketCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$socket?.[e.method];if(typeof i!="function")throw new Error(`Socket method not found: ${e.method}`);return i(...n)}async execCacheCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$cache?.[e.method];if(typeof i!="function")throw new Error(`Cache method not found: ${e.method}`);return i(...n)}async execStorageCall(e,t,n){let i=this.parseStorageArgs(e.argsJson,n,e.id),o=t?.$storage?.[e.method];if(typeof o!="function")throw new Error(`Storage method not found: ${e.method}`);return o(...i)}parseStorageArgs(e,t,n){return JSON.parse(e,(i,o)=>{if(o?.__fnRef&&typeof o.__fnRef=="string"){let s=o.__fnRef;return(...a)=>this.invokeRuntimeCallback(t,n,s,a)}return o})}invokeRuntimeCallback(e,t,n,i){let o=`rtcb_${++this.runtimeCallbackCounter}`;return new Promise((s,a)=>{let u=setTimeout(()=>{d(),a(new Error(`Runtime callback timed out: ${n}`))},3e4),c=l=>{if(!(l?.type!=="runtimeCallbackResult"||l.callId!==o)){if(d(),l.error){a(new Error(l.error));return}s(l.value)}},d=()=>{clearTimeout(u),e.off("message",c)};e.on("message",c),e.postMessage({type:"invokeRuntimeCallback",id:t,callId:o,callbackId:n,argsJson:JSON.stringify(i)})})}async execDispatchCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$trigger;if(typeof i!="function")throw new Error("$trigger is not available");return i(...n)}cancelTask(e){this.taskCancellers.get(e)?.()}async execResCall(e,t){if(e.method==="streamStart"){let s=JSON.parse(e.argsJson||"[]")[1]||{},a=t?.$res?.stream;if(typeof a!="function")throw new Error("Response method not found: stream");let u=new Sr.PassThrough,c={stream:u};this.responseStreams.set(e.id,c);let d=t?.$res;if(d&&typeof d.once=="function"){let f=()=>{d.writableEnded!==!0&&this.cancelTask(e.id)};d.once("close",f),c.closeCleanup=()=>{typeof d.off=="function"?d.off("close",f):typeof d.removeListener=="function"&&d.removeListener("close",f)}}let l=a.call(t.$res,u,s);return l&&typeof l.catch=="function"&&l.catch(()=>{}),!0}if(e.method==="streamChunk"){let o=this.responseStreams.get(e.id);if(!o)throw new Error(`Response stream not found: ${e.id}`);let s=Buffer.from(e.chunk||"","base64");return o.stream.write(s)||await new Promise((a,u)=>{let c=()=>{l(),a()},d=f=>{l(),u(f)},l=()=>{o.stream.off("drain",c),o.stream.off("error",d)};o.stream.once("drain",c),o.stream.once("error",d)}),!0}if(e.method==="streamEnd"){let o=this.responseStreams.get(e.id);return o&&(o.closeCleanup?.(),o.stream.end(),this.responseStreams.delete(e.id)),!0}if(e.method==="streamError"){let o=this.responseStreams.get(e.id);if(o){o.closeCleanup?.();let s=e.error?.message||"Response stream failed";o.stream.destroy(new Error(s)),this.responseStreams.delete(e.id)}return!0}let n=JSON.parse(e.argsJson||"[]"),i=t?.$res?.[e.method];if(typeof i!="function")throw new Error(`Response method not found: ${e.method}`);return i.apply(t.$res,n)}cleanupResponseStream(e,t){let n=this.responseStreams.get(e);n&&(this.responseStreams.delete(e),n.closeCleanup?.(),t?n.stream.destroy(t):n.stream.end())}toWorkerCodeBlock(e){return{code:e.code,sourceCode:e.sourceCode,scriptLanguage:e.scriptLanguage,type:e.type}}async run(e,t,n,i={}){let o=Math.max(1,Math.trunc(Number(n)||3e4)),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),u=this.createSnapshot(t);Q({event:"isolated_run_start",timeoutMs:o,codeLen:e?.length??0});let c;try{let d={code:e,sourceCode:i.sourceCode??e,pkgSources:a,snapshot:u,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};c=await this.spawnAndExecute("execute",d,t,o)}catch(d){let l=d;if(Q({event:"isolated_run_error",message:l.message,code:l.code,isTimeout:!!l.isTimeout}),l.code==="ERR_EXECUTION_ABORTED"||l.isAbort)throw l;if(l.isTimeout||l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new me(o,e,l.details);l.code&&l.details&&(l.details.executorCode=l.code);let f=l.statusCode??(typeof l.status=="number"?l.status:void 0);throw ve.createException(l.errorPath,f,l.message||"Unknown error",e,l.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),Q({event:"isolated_run_ok"}),c.valueAbsent?void 0:c.value}async runBatch(e,t,n,i={}){let o=Math.max(1,Math.trunc(Number(n)||3e4)),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),u=this.createSnapshot(t);Q({event:"isolated_batch_start",timeoutMs:o,blocks:e.length});let c;try{let l={codeBlocks:e.map(f=>this.toWorkerCodeBlock(f)),pkgSources:a,snapshot:u,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};c=await this.spawnAndExecute("executeBatch",l,t,o,i.signal)}catch(d){let l=d;if(Q({event:"isolated_batch_error",message:l.message,code:l.code,isTimeout:!!l.isTimeout}),l.ctxChanges&&this.mergeCtxChanges(t,l.ctxChanges),l.code==="ERR_EXECUTION_ABORTED"||l.isAbort)throw l;if(l.isTimeout||l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new me(o,"(batch execution)",l.details);l.code&&l.details&&(l.details.executorCode=l.code);let f=l.statusCode??(typeof l.status=="number"?l.status:void 0);throw ve.createException(l.errorPath,f,l.message||"Unknown error","(batch execution)",l.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),Q({event:"isolated_batch_ok"}),{value:c.valueAbsent?void 0:c.value,shortCircuit:c.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,s)=>o-s),i=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[i]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((i,o)=>i+o,0)/t.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),maxHeapRatio:Math.max(0,...e.workers.map(i=>i.lastHeapRatio||0))}}};var xe=ue(require("typescript")),Ft={oauth_config_definition:"",route_handler_definition:"logic",pre_hook_definition:"code",post_hook_definition:"code",bootstrap_script_definition:"logic",websocket_definition:"connectionHandlerScript",websocket_event_definition:"handlerScript"};function Di(r){return te.getLegacyField(r)}function Wi(r){return te.isScriptTable(r)}function Ki(r){return te.normalizeLanguage(r)}var tn=class{getLegacyField(e){return Ft[e]}isScriptTable(e){return e in Ft}normalizeLanguage(e){return e==="javascript"?"javascript":"typescript"}compileSource(e,t){if(e==null||e==="")return null;let n=String(e),o=this.normalizeLanguage(t)==="javascript"?n:this.transpileTypeScript(n);return this.assertExecutableJavaScript(o),o}isExecutableJavaScript(e){if(!e)return!1;try{return this.assertExecutableJavaScript(e),!0}catch{return!1}}normalizeRecord(e,t){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let n={...t},i=this.getLegacyField(e);return i&&(n.sourceCode===void 0||n.sourceCode===null||n.sourceCode==="")&&n[i]!==void 0&&(n.sourceCode=n[i]),n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage),i&&i in n&&delete n[i],n}normalizePatch(e,t,n){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let i=this.getLegacyField(e),o=Object.prototype.hasOwnProperty.call(t,"sourceCode")||(i?Object.prototype.hasOwnProperty.call(t,i):!1),s=Object.prototype.hasOwnProperty.call(t,"scriptLanguage");if(!o&&!s)return t;let a=o?t.sourceCode??(i?t[i]:void 0):n?.sourceCode??(i&&n?n[i]:void 0),u=s?t.scriptLanguage:n?.scriptLanguage,c={...t};return o&&(c.sourceCode=a??null),c.scriptLanguage=this.normalizeLanguage(u),c.compiledCode=this.compileSource(a,c.scriptLanguage),i&&i in c&&delete c[i],c}getExecutableScript(e){return this.resolveExecutableScript(e).code}resolveExecutableScript(e){if(!e||typeof e!="object")return{code:null,compiledCode:null,shouldPersistCompiledCode:!1};if(typeof e.sourceCode=="string"&&e.sourceCode!==""){let n=this.compileSource(e.sourceCode,e.scriptLanguage);return{code:n,compiledCode:n,shouldPersistCompiledCode:n!==e.compiledCode}}let t=Object.keys(Ft).find(n=>Ft[n]in e);if(t){let n=e[Ft[t]];if(typeof n=="string"&&n!==""){let i=this.compileSource(n,e.scriptLanguage);return{code:i,compiledCode:i,shouldPersistCompiledCode:i!==e.compiledCode}}}return typeof e.compiledCode=="string"&&e.compiledCode!==""&&this.isExecutableJavaScript(e.compiledCode)?{code:e.compiledCode,compiledCode:e.compiledCode,shouldPersistCompiledCode:!1}:{code:null,compiledCode:null,shouldPersistCompiledCode:!1}}normalizeFlowStepScriptConfig(e){if(!e||typeof e!="object")return e;let t=e.type;if(t!=="script"&&t!=="condition")return e;let n={...e},i=e.config;if(typeof i=="string")try{i=JSON.parse(i)}catch{return e}let o=i&&typeof i=="object"?i:{};n.sourceCode=n.sourceCode??o.sourceCode??o.code??null,n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage??o.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage);let s={...o};return delete s.sourceCode,delete s.scriptLanguage,delete s.compiledCode,delete s.code,{...n,config:typeof e.config=="string"?JSON.stringify(s):s}}repairContract(e){let t=this.normalizeLanguage(e?.scriptLanguage),n=e?.sourceCode??null,i=this.compileSource(n,t);return{sourceCode:n,scriptLanguage:t,code:i,compiledCode:i,shouldPersistCompiledCode:i!==e?.compiledCode}}transpileTypeScript(e){let t=xe.default.transpileModule(e,{compilerOptions:{target:xe.default.ScriptTarget.ES2022,module:xe.default.ModuleKind.CommonJS,importsNotUsedAsValues:xe.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),n=t.diagnostics?.find(i=>i.category===xe.default.DiagnosticCategory.Error);if(n)throw new Error(xe.default.flattenDiagnosticMessageText(n.messageText,`
|
|
1
|
+
"use strict";var hi=Object.create;var zt=Object.defineProperty;var mi=Object.getOwnPropertyDescriptor;var yi=Object.getOwnPropertyNames;var bi=Object.getPrototypeOf,_i=Object.prototype.hasOwnProperty;var q=(r,e)=>()=>(r&&(e=r(r=0)),e);var En=(r,e)=>{for(var t in e)zt(r,t,{get:e[t],enumerable:!0})},br=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of yi(e))!_i.call(r,i)&&i!==t&&zt(r,i,{get:()=>e[i],enumerable:!(n=mi(e,i))||n.enumerable});return r};var ue=(r,e,t)=>(t=r!=null?hi(bi(r)):{},br(e||!r||!r.__esModule?zt(t,"default",{value:r,enumerable:!0}):t,r)),wi=r=>br(zt({},"__esModule",{value:!0}),r);function vr(r){return Ln.createHash("md5").update(r).digest("hex").substring(0,8)}function Ir(r){return r.length<=xr-3?`${r}_pk`:`j_${vr(r)}_pk`}function Nr(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=xr?n:`j_${vr(r)}_${t}_fk`}function xt(r,e,t){let n=`${r}:${e}:${t}`;return`j_${Ln.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function J(r){return`${r}Id`}function vt(r,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function Mr(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function Er(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function Or(r,e,t){return`${r}_${e}_${t}_fk`}function Ar(r,e,t){return`${r}_${e}_${t}_idx`}var Ln,xr,Ke=q(()=>{"use strict";Ln=ue(require("crypto")),xr=63});function ln(r){return io[r]??null}var we,qn,Nt,io,cn=q(()=>{"use strict";we=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),qn=new Set(["_and","_or","_not"]),Nt=[...Array.from(qn),...Array.from(we)],io={_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 N,de=q(()=>{"use strict";N=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 Lr(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var Dr=q(()=>{"use strict"});function Me(r,e,t){throw new N({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${Nt.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:Nt})}function un(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=Lr();for(let i of Object.keys(e))if(i.startsWith("_")&&!we.has(i)){if(n&&i==="_id")continue;Me(i,r,t)}}function re(r,e,t){if(!r||typeof r!="object")return;let n=t?.tables?.get(e),i=new Set((n?.columns??[]).map(s=>s.name)),o=new Map((n?.relations??[]).map(s=>[s.propertyName,s]));for(let[s,a]of Object.entries(r)){if(oo.has(s)){if(Array.isArray(a))for(let c of a)re(c,e,t);else a&&typeof a=="object"&&re(a,e,t);continue}let u=o.get(s);if(u){if(a&&typeof a=="object"&&!Array.isArray(a)){un(s,a,e);let c=u.targetTableName||u.targetTable;if(c){let d=Object.keys(a).filter(l=>!l.startsWith("_"));if(d.length>0){let l={};for(let f of d)l[f]=a[f];re(l,c,t)}}}continue}s.startsWith("_")&&!i.has(s)&&s!=="_id"&&Me(s,s,e),a&&typeof a=="object"&&!Array.isArray(a)&&un(s,a,e)}}var oo,Je=q(()=>{"use strict";de();cn();Dr();oo=new Set(["_and","_or","_not"])});function fe(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:dn(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function dn(r,e){if(!r||typeof r!="object")return{node:null,hasRelationFilters:!1};let t=[],n=!1;for(let[i,o]of Object.entries(r)){let s=so(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 so(r,e,t){if(r==="_and")return Wr("and",e,t);if(r==="_or")return Wr("or",e,t);if(r==="_not"){let c=dn(e,t);return c.node?{node:{kind:"not",child:c.node},hasRelationFilters:c.hasRelationFilters}:{node:null,hasRelationFilters:c.hasRelationFilters}}let n=t.metadata?.tables?.get(t.currentTable),i=n?.columns?.some(c=>c.name==="_id"&&c.isPrimary),o=n?.columns?.some(c=>c.name==="id"),a=r==="id"?i&&!o?"_id":"id":r,u=n?.relations?.find(c=>c.propertyName===a);return u?ao(a,e,u,t):n&&!n.columns?.find(d=>d.name===a)?(r.startsWith("_")&&r!=="_id"&&Me(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}):lo(a,e,t)}function Wr(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],i=!1;for(let o of e){let s=dn(o,t);s.hasRelationFilters&&(i=!0),s.node&&n.push(s.node)}return n.length===0?{node:null,hasRelationFilters:i}:n.length===1?{node:n[0],hasRelationFilters:i}:{node:{kind:r,children:n},hasRelationFilters:i}}function ao(r,e,t,n){if(typeof e!="object"||e===null)return{node:null,hasRelationFilters:!0};let i=Object.keys(e),o=i.length===1&&(i[0]==="_is_null"||i[0]==="_is_not_null"||i[0]==="_eq"||i[0]==="_neq"||i[0]==="_in"||i[0]==="_not_in"||i[0]==="_nin"),s=n.registry.registerWithParent(n.currentTable,r,n.metadata,"left",n.currentJoinId,"filter");if(o&&i[0]==="_is_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_null===!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(o&&i[0]==="_is_not_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_not_null!==!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(o&&(i[0]==="_eq"||i[0]==="_neq")&&e[i[0]]===null)return s?{node:{kind:"relation_exists",joinId:s,negate:i[0]==="_eq"},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(!s)return{node:null,hasRelationFilters:!0};let a=t.targetTableName||t.targetTable,u={...n,parentJoinId:n.currentJoinId,currentJoinId:s,currentTable:a},c=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]),l=i.length>0&&i.every(p=>c.has(p))?{id:e}:e;return{node:dn(l,u).node,hasRelationFilters:!0}}function lo(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:uo(r,t)};if(e===null)return{node:{kind:"compare",field:n,op:"is_null",value:!0},hasRelationFilters:!1};if(typeof e!="object")return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};for(let s of Object.keys(e))s.startsWith("_")&&!we.has(s)&&Me(s,r,t.tableName);let i=Object.entries(e).filter(([s])=>we.has(s));if(i.length===0)return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};let o=[];for(let[s,a]of i){let u=co(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 co(r,e,t){if(e==="_is_null")return{kind:"compare",field:r,op:"is_null",value:t===!0};if(e==="_is_not_null")return{kind:"compare",field:r,op:"is_null",value:t!==!0};let n=ln(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function uo(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 Mt=q(()=>{"use strict";cn();Je()});var ie,Et=q(()=>{"use strict";ie=class{constructor(){this.map=new Map}size(){return this.map.size}has(e){return this.map.has(e)}get(e){return this.map.get(e)}getAll(){return Array.from(this.map.values())}registerWithParent(e,t,n,i="left",o=null,s="data"){let a=o?`${o}.${t}`:t;if(this.map.has(a)){let f=this.map.get(a);return i==="inner"&&(f.joinType="inner"),f.purposes.includes(s)||f.purposes.push(s),a}let u=n?.tables?.get(e);if(!u)return null;let c=u.relations?.find(f=>f.propertyName===t);if(!c)return null;let d=c.targetTableName||c.targetTable;if(!d)return null;let l={id:a,propertyName:t,parentTable:e,targetTable:d,relationType:c.type,parentJoinId:o,joinType:i,relationMeta:c,purposes:[s]};return this.map.set(a,l),a}}});async function W(r,e,t=oe){if(!Number.isInteger(t)||t<1)throw new Error("Batch fetch chunk size must be a positive integer");if(r.length<=t)return e(r);let n=[];for(let u=0;u<r.length;u+=t)n.push(r.slice(u,u+t));let i=[],o=0;async function s(){for(;o<n.length;){let u=o++;i[u]=await e(n[u])}}let a=Math.min(Yn,n.length);return await Promise.all(Array.from({length:a},s)),i.flat()}function He(r){let e=[],t=new Map;for(let n of r)if(n==="*"||!n.includes("."))e.push(n);else{let i=n.split("."),o=i[0],s=i.slice(1).join(".");t.has(o)||t.set(o,[]),t.get(o).push(s)}return{rootFields:e,subRelations:t}}var Ee,oe,Yn,Xn,Se,Ge=q(()=>{"use strict";de();Ee=16,oe=5e3,Yn=4,Xn=10;Se=class{constructor(e,t,n){this.adapter=e;this.metadataGetter=t;this.trace=n}enrichNestedDescs(e,t,n){if(!t||Object.keys(t).length===0)return e;let i=e.map(s=>{let a=t[s.relationName];if(!a)return s;let u=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(c=>c.trim()).filter(Boolean):["*"];return{...s,fields:u,userFilter:a.filter??s.userFilter,userSort:a.sort??s.userSort,userLimit:a.limit!==void 0?Number(a.limit):s.userLimit,userPage:a.page!==void 0?Number(a.page):s.userPage,nestedDeep:a.deep??s.nestedDeep}}),o=new Set(i.map(s=>s.relationName));for(let[s,a]of Object.entries(t)){if(o.has(s))continue;let u=n?.relations?.find(d=>d.propertyName===s);if(!u)continue;let c=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(d=>d.trim()).filter(Boolean):["*"];i.push({relationName:s,type:u.type,targetTable:u.targetTableName||u.targetTable,fields:c,isInverse:u.isInverse,fkColumn:u.foreignKeyColumn,mappedBy:u.mappedBy,junctionTableName:u.junctionTableName,junctionSourceColumn:u.junctionSourceColumn,junctionTargetColumn:u.junctionTargetColumn,userFilter:a.filter,userSort:a.sort,userLimit:a.limit!==void 0?Number(a.limit):void 0,userPage:a.page!==void 0?Number(a.page):void 0,nestedDeep:a.deep})}return i}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:Xn}:e}fieldsForNestedResolution(e,t){if(!t||Object.keys(t).length===0)return e;let n=new Set(e.filter(o=>o!=="*").map(o=>o.split(".")[0])),i=[...e];for(let o of Object.keys(t))n.has(o)||i.push(o);return i}uniqueValues(e){let t=new Set,n=[];for(let i of e){if(i==null)continue;let o=this.adapter.keyOf(i);t.has(o)||(t.add(o),n.push(i))}return n}assertLocalSortFields(e,t){if(!e.userSort)return;let n=Array.isArray(e.userSort)?e.userSort:String(e.userSort).split(",").map(i=>i.trim()).filter(Boolean);for(let i of n){let o=i.startsWith("-")?i.slice(1):i;if(o.includes("."))throw new N(`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 N(`Sort field '${o}' does not exist on '${e.targetTable}'. Sort only by fields defined on the table metadata.`)}}async execute(e,t,n=3,i=0,o){if(e.length===0||t.length===0||i>=n)return;let s;o&&(s=await this.metadataGetter(o)??void 0),await Promise.all(t.map(a=>{let u=this.withDefaultToManyLimit(a);return u.type==="many-to-one"||u.type==="one-to-one"&&!u.isInverse?this.fetchOwnerRelation(e,u,n,i):u.type==="one-to-many"||u.type==="one-to-one"&&u.isInverse?this.fetchInverseRelation(e,u,n,i,s):u.type==="many-to-many"?this.fetchM2MRelation(e,u,n,i,s):Promise.resolve()}))}async fetchOwnerRelation(e,t,n,i){let o=this.adapter.resolveOwnerFkKey(t),s=new Set,a=[];for(let w of e){let C=w[o];if(C==null)continue;let T=this.adapter.keyOf(C);s.has(T)||(s.add(T),a.push(C))}if(a.length===0){for(let w of e)w[t.relationName]=null,o!==t.relationName&&delete w[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete w[t.fkColumn];return}let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{isPkOnly:c,nestedDescs:d,fetchSpec:l}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),f=this.adapter.getTargetPkField(u);if(c){for(let w of e){let C=w[o];w[t.relationName]=C!=null?this.adapter.buildScalarRef(C,f):null,o!==t.relationName&&delete w[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete w[t.fkColumn]}return}let p=performance.now(),h=await this.adapter.fetchOwner(t.targetTable,a,l,t),g=Array.isArray(h)?h:h.docs,m=Array.isArray(h)?void 0:h.stats;this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:m?.strategy??"batch-in",roundtrips:m?.roundtrips??(Math.ceil(a.length/oe)||1),concurrencyWaves:m?.concurrencyWaves,ioConcurrency:m?.ioConcurrency,rowsTransferred:m?.rowsTransferred??g.length,rowsReturned:g.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let y=this.enrichNestedDescs(d,t.nestedDeep,u);y.length>0&&await this.execute(g,y,n,i+1,t.targetTable);let b=new Map;for(let w of g)b.set(this.adapter.keyOf(w[f]),w);for(let w of e){let C=w[o];w[t.relationName]=C!=null&&b.get(this.adapter.keyOf(C))||null,o!==t.relationName&&delete w[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete w[t.fkColumn]}}async fetchInverseRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=this.uniqueValues(e.map(I=>I[s]));if(a.length===0)return;let u=this.adapter.resolveInverseFkField(t),c=await this.metadataGetter(t.targetTable);if(!c)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,c);let{nestedDescs:d,fetchSpec:l}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),c),f=performance.now(),{docs:p,groupKeyField:h,stats:g}=await this.adapter.fetchInverse(t.targetTable,u,a,l,t),m=new Map,y=t.fields.includes(u)||t.fields.includes("*");for(let I of p){let B=I[h],S=this.adapter.keyOf(B);m.has(S)||m.set(S,[]),m.get(S).push(I)}let b=t.userLimit!==void 0&&t.userLimit>0,w=b?"per-parent-c16":"batch-in",C=b?a.length:Math.ceil(a.length/oe)||1,T=b?Math.ceil(a.length/Ee):void 0,k=Array.from(m.values()).reduce((I,B)=>I+B.length,0);if(this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,f,{relationType:t.type,targetTable:t.targetTable,strategy:g?.strategy??w,roundtrips:g?.roundtrips??C,concurrencyWaves:g?.concurrencyWaves??T,ioConcurrency:g?.ioConcurrency,rowsTransferred:g?.rowsTransferred??p.length,rowsReturned:k,rowsDiscarded:Math.max(0,(g?.rowsTransferred??p.length)-k),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let I of p)this.adapter.postProcessInverseChild(I,u,y);let x=this.enrichNestedDescs(d,t.nestedDeep,c);x.length>0&&await this.execute(p,x,n,i+1,t.targetTable);let $=t.type==="one-to-one";for(let I of e){let B=this.adapter.keyOf(I[s]),S=m.get(B)||[];I[t.relationName]=$?S[0]||null:S}}async fetchM2MRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=this.uniqueValues(e.map(T=>T[s]));if(a.length===0)return;let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{nestedDescs:c,fetchSpec:d}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),l=performance.now(),{grouped:f,docs:p,stats:h}=await this.adapter.fetchM2M(e,t,o,u,d),g=t.userLimit!==void 0&&t.userLimit>0,m=g?"m2m-per-parent-c16":"m2m-batch",y=g?a.length:Math.ceil(a.length/oe)||1,b=g?Math.ceil(a.length/Ee):void 0,w=Array.from(f.values()).reduce((T,k)=>T+k.length,0);this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,l,{relationType:t.type,targetTable:t.targetTable,strategy:h?.strategy??m,roundtrips:h?.roundtrips??y,concurrencyWaves:h?.concurrencyWaves??b,ioConcurrency:h?.ioConcurrency,rowsTransferred:h?.rowsTransferred??p.length,rowsReturned:w,rowsDiscarded:h?.rowsDiscarded??Math.max(0,(h?.rowsTransferred??p.length)-w),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort});let C=this.enrichNestedDescs(c,t.nestedDeep,u);C.length>0&&p.length>0&&await this.execute(p,C,n,i+1,t.targetTable);for(let T of e){let k=this.adapter.keyOf(T[s]);T[t.relationName]=f.get(k)||[]}}}});var Hr,Ce,bn=q(()=>{"use strict";Hr=2,Ce=class{constructor(e=2){this.concurrency=e;this.active=0;this.waiters=[];if(!Number.isInteger(e)||e<1)throw new Error("Batch execution concurrency must be a positive integer")}async run(e){await this.acquire();try{return await e()}catch(t){throw this.cancel(t),t}finally{this.release()}}async acquire(){if(this.failure!==void 0)throw this.failure;if(this.active<this.concurrency){this.active+=1;return}if(await new Promise(e=>this.waiters.push(e)),this.failure!==void 0)throw this.failure;this.active+=1}release(){this.active-=1,this.failure===void 0&&this.waiters.shift()?.()}cancel(e){if(this.failure===void 0){this.failure=e;for(let t of this.waiters.splice(0))t()}}}});function v(r,e){let t=e==="mysql"?r.replace(/`/g,"``"):r.replace(/"/g,'""');switch(e){case"mysql":return`\`${t}\``;case"postgres":case"pg":case"sqlite":return`"${t}"`;case"mongodb":return r;default:return`\`${t}\``}}function Re(r,e){return r.split(".").map(t=>t==="*"||t.startsWith('"')&&t.endsWith('"')||t.startsWith("`")&&t.endsWith("`")?t:v(t,e)).join(".")}var ae=q(()=>{"use strict"});function ce(r,e,t){e&&Rn(r,e,t,"and")}function Rn(r,e,t,n){switch(e.kind){case"true":return;case"false":n==="or"?r.orWhereRaw("1 = 0"):r.whereRaw("1 = 0");return;case"and":{let i=function(){for(let o of e.children)this.where(function(){Rn(this,o,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"or":{let i=function(){for(let o of e.children)this.orWhere(function(){Rn(this,o,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"not":{let i=function(){this.whereNot(function(){Rn(this,e.child,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"compare":Wo(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 Wo(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=Ko(e.field,t),o=Re(i,t.dbType),s=!!e.field.isUuid,a=t.dbType==="postgres",u=n==="or"?"orWhere":"where",c=n==="or"?"orWhereRaw":"whereRaw",d=n==="or"?"orWhereIn":"whereIn",l=n==="or"?"orWhereNotIn":"whereNotIn",f=n==="or"?"orWhereBetween":"whereBetween",p=n==="or"?"orWhereNull":"whereNull",h=n==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":s&&a&&typeof e.value=="string"?r[c](`${o} = ?::uuid`,[e.value]):r[u](i,"=",e.value);return;case"neq":s&&a&&typeof e.value=="string"?r[c](`${o} != ?::uuid`,[e.value]):r[u](i,"!=",e.value);return;case"gt":s&&a&&typeof e.value=="string"?r[c](`${o} > ?::uuid`,[e.value]):r[u](i,">",e.value);return;case"gte":s&&a&&typeof e.value=="string"?r[c](`${o} >= ?::uuid`,[e.value]):r[u](i,">=",e.value);return;case"lt":s&&a&&typeof e.value=="string"?r[c](`${o} < ?::uuid`,[e.value]):r[u](i,"<",e.value);return;case"lte":s&&a&&typeof e.value=="string"?r[c](`${o} <= ?::uuid`,[e.value]):r[u](i,"<=",e.value);return;case"in":{let g=si(e.value);s&&a&&g.every(m=>typeof m=="string")?r[c](`${o} = ANY(?::uuid[])`,[g]):r[d](i,g);return}case"not_in":{let g=si(e.value);s&&a&&g.every(m=>typeof m=="string")?r[c](`${o} != ALL(?::uuid[])`,[g]):r[l](i,g);return}case"contains":cr(r,o,e.value,"contains",t,n);return;case"starts_with":cr(r,o,e.value,"starts_with",t,n);return;case"ends_with":cr(r,o,e.value,"ends_with",t,n);return;case"between":Array.isArray(e.value)&&e.value.length===2&&r[f](i,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?r[p](i):r[h](i);return}}function cr(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 Ko(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function si(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var ur=q(()=>{"use strict";ae()});function H(r){return r.columns.find(e=>e.isPrimary)||null}var qt=q(()=>{"use strict"});var ai={};En(ai,{expandFieldsToJoinsAndSelect:()=>dr});async function dr(r,e,t,n,i,o){let s=[],a=[],u=await t(r);if(!u)return{select:[],batchFetchDescriptors:[]};let c=new Map;for(let l of e)if(l==="*"||!l.includes("."))c.has("")||c.set("",[]),c.get("").push(l);else{let f=l.split("."),p=f[0],h=f.slice(1).join(".");c.has(p)||c.set(p,[]),c.get(p).push(h)}if(o&&typeof o=="object")for(let[l,f]of Object.entries(o)){if(c.has(l))continue;let p=f&&typeof f=="object"&&f.fields!=null?Array.isArray(f.fields)?f.fields:String(f.fields).split(",").map(h=>h.trim()).filter(Boolean):["*"];c.set(l,p)}let d=c.get("")||[];for(let l of d){if(l==="*"){let h=new Set;for(let m of u.relations||[])if(m.type==="many-to-one"||m.type==="one-to-one"&&!m.isInverse){let y=m.foreignKeyColumn||J(m.propertyName);y&&h.add(y)}let g=new Set;for(let m of u.columns)h.has(m.name)||(s.push(`${r}.${m.name}`),g.add(m.name));for(let m of u.relations||[])!c.has(m.propertyName)&&!g.has(m.propertyName)&&c.set(m.propertyName,["id"]);continue}if(l.includes(".")){s.push(`${r}.${l}`);continue}if(u.columns?.find(h=>h.name===l)){s.push(`${r}.${l}`);continue}if(u.relations?.find(h=>h.propertyName===l)){c.has(l)||c.set(l,["id"]);continue}}return c.forEach((l,f)=>{if(f==="")return;let p=u.relations?.find(b=>b.propertyName===f);if(!p)return;if(p.type==="many-to-one"||p.type==="one-to-one"&&!p.isInverse){let b=p.foreignKeyColumn||J(p.propertyName),w=v(r,n),C=v(b,n),T=v(f,n);s.push(`${w}.${C} as ${T}`)}let g=p.targetTableName||p.targetTable,m=o?.[f],y=m?.fields!=null?Array.isArray(m.fields)?m.fields:String(m.fields).split(",").map(b=>b.trim()).filter(Boolean):l;a.push({relationName:f,type:p.type,targetTable:g,fields:y,isInverse:p.isInverse,fkColumn:p.foreignKeyColumn,mappedBy:p.mappedBy,junctionTableName:p.junctionTableName,junctionSourceColumn:p.junctionSourceColumn,junctionTargetColumn:p.junctionTargetColumn,userFilter:m?.filter,userSort:m?.sort,userLimit:m?.limit!==void 0?Number(m.limit):void 0,userPage:m?.page!==void 0?Number(m.page):void 0,nestedDeep:m?.deep})}),{select:s,batchFetchDescriptors:a}}var fr=q(()=>{"use strict";Ke();ae()});var Ut,Qt,Fn,ot,qo,st,gr=q(()=>{"use strict";Ke();ae();qt();Ge();bn();ur();Et();Mt();Ut="__enfyra_row_number__",Qt="__sourceId__",Fn="__targetId__",ot="__enfyra_partitioned__",qo=5e4,st=class{constructor(e,t="postgres",n,i=new Ce){this.knex=e;this.dbType=t;this.metadata=n;this.executionBudget=i;this.pkField="id"}chunkCount(e,t=oe){return Math.ceil(e.length/t)||1}m2mTargetChunkSize(){return this.dbType==="postgres"?qo:oe}uniqueValues(e){return Array.from(new Map(e.filter(t=>t!=null).map(t=>[this.keyOf(t),t])).values())}runQuery(e){return this.executionBudget.run(()=>e)}buildPartitionRowNumber(e,t,n){let i=[...t];i.some(s=>s.column===n)||i.push({column:n,order:"asc"});let o=i.map(s=>`?? ${s.order.toUpperCase()}`).join(", ");return this.knex.raw(`ROW_NUMBER() OVER (PARTITION BY ?? ORDER BY ${o}) as ??`,[e,...i.map(s=>s.column),Ut])}buildPartitionSlice(e,t,n,i){return this.knex.from(e.as(ot)).select(`${ot}.*`).where(`${ot}.${Ut}`,">",n).andWhere(`${ot}.${Ut}`,"<=",n+i).orderBy(`${ot}.${t}`,"asc").orderBy(`${ot}.${Ut}`,"asc")}removePartitionFields(e){for(let t of e)delete t[Ut]}buildFilterTree(e,t){if(!e||!this.metadata)return null;let n=new ie,i=this.metadata?.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))},{node:o}=fe(e,t,i,n);return o}parseSortTokens(e,t,n){return e?(Array.isArray(e)?e:e.split(",").map(o=>o.trim()).filter(Boolean)).map(o=>{let s=o.startsWith("-"),u=(s?o.slice(1):o).split(".");if(u.length===1)return{column:n?`${n}.${u[0]}`:`${t}.${u[0]}`,order:s?"desc":"asc"};let c=u[u.length-1];return{column:`${`__sort_${u.slice(0,-1).join("_")}`}.${c}`,order:s?"desc":"asc"}}):[]}applySortJoins(e,t,n,i){if(!t||!this.metadata)return;let o=Array.isArray(t)?t:t.split(",").map(a=>a.trim()).filter(Boolean),s=new Set;for(let a of o){let c=(a.startsWith("-")?a.slice(1):a).split(".");if(c.length<=1)continue;let d=n,l=i||n;for(let f=0;f<c.length-1;f++){let p=c[f],h=this.metadata?.tables?.get(d);if(!h)break;let g=h.relations?.find(b=>b.propertyName===p);if(!g)break;let m=g.targetTableName||g.targetTable,y=`__sort_${c.slice(0,f+1).join("_")}`;if(!s.has(y)){s.add(y);let b=g.foreignKeyColumn||J(g.propertyName),w=this.metadata?.tables?.get(m),C=w&&H(w)?.name||"id";e.leftJoin(`${m} as ${y}`,`${y}.${C}`,`${l}.${b}`)}d=m,l=y}}}toKnexSelect(e,t){let n=e.indexOf(" as ");if(n!==-1){let i=e.substring(0,n),o=e.substring(n+4),s=v(o,this.dbType),a=t?`${t}.${v(i,this.dbType)}`:v(i,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${t}.${v(e,this.dbType)} as ${v(e,this.dbType)}`):e}keyOf(e){return e==null?"":String(e)}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return H(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;return!t&&e.mappedBy&&(t=J(e.mappedBy)),t||(t=J(e.targetTable)),t}resolveParentPk(e){return e&&H(e)?.name||"id"}resolveFields(e,t){let{rootFields:n,subRelations:i}=He(e),o=[];if(n.includes("*")){let c=new Set;for(let d of t.relations||[])if(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse){let l=d.foreignKeyColumn||J(d.propertyName);l&&c.add(l)}for(let d of t.columns)c.has(d.name)||o.push(d.name);for(let d of t.relations||[])i.has(d.propertyName)||i.set(d.propertyName,["id"])}else for(let c of n){let d=t.columns.find(l=>l.name===c);d?o.push(d.name):t.relations?.find(f=>f.propertyName===c)&&!i.has(c)&&i.set(c,["id"])}let s=H(t)?.name||"id";o.includes(s)||o.push(s),i.forEach((c,d)=>{let l=t.relations?.find(f=>f.propertyName===d);if(l&&(l.type==="many-to-one"||l.type==="one-to-one"&&!l.isInverse)){let f=l.foreignKeyColumn||J(l.propertyName);f&&o.push(`${f} as ${d}`)}});let a=[];return i.forEach((c,d)=>{let l=t.relations?.find(p=>p.propertyName===d);if(!l)return;let f=l.targetTableName||l.targetTable;f&&a.push({relationName:d,type:l.type,targetTable:f,fields:c,isInverse:l.isInverse,fkColumn:l.foreignKeyColumn,mappedBy:l.mappedBy,junctionTableName:l.junctionTableName,junctionSourceColumn:l.junctionSourceColumn,junctionTargetColumn:l.junctionTargetColumn})}),{isPkOnly:o.length===1&&o[0]===s&&a.length===0,nestedDescs:a,fetchSpec:{selectCols:o,pkCol:s}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?this.buildFilterTree(i.userFilter,e):null,s=i?.userSort?this.parseSortTokens(i.userSort,e):[],a=n.selectCols.map(c=>this.toKnexSelect(c)),u=await W(t,c=>{let d=this.knex(e).select(a).whereIn(n.pkCol,c);if(o&&ce(d,o,{dbType:this.dbType,rootTable:e}),s.length>0){this.applySortJoins(d,i.userSort,e);for(let l of s)d.orderBy(l.column,l.order)}return this.runQuery(d)});return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(t),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,n,i,o){let s=t,a=i.selectCols.find(h=>h.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():i.selectCols.includes(t)||i.selectCols.push(t);let u=o?.userFilter?this.buildFilterTree(o.userFilter,e):null,c=o?.userSort?this.parseSortTokens(o.userSort,e):[],d=o?.userLimit,l=o?.userPage;if(d!==void 0&&d>0){let h=l?(l-1)*d:0,g=i.selectCols.map(y=>this.toKnexSelect(y)),m=await W(n,async y=>{let b=this.knex(e).select(g).select(this.buildPartitionRowNumber(`${e}.${t}`,c,`${e}.${i.pkCol}`)).whereIn(`${e}.${t}`,y);u&&ce(b,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(b,o.userSort,e);let w=await this.runQuery(this.buildPartitionSlice(b,s,h,d));return this.removePartitionFields(w),w});return{docs:m,groupKeyField:s,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(n),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.length}}}let f=i.selectCols.map(h=>this.toKnexSelect(h)),p=await W(n,h=>{let g=this.knex(e).select(f).whereIn(t,h);if(u&&ce(g,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(g,o?.userSort,e),c.length>0)for(let m of c)g.orderBy(m.column,m.order);else g.orderBy(i.pkCol,"asc");return this.runQuery(g)});return{docs:p,groupKeyField:s,stats:{strategy:"batch-in",roundtrips:this.chunkCount(n),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length}}}postProcessInverseChild(e,t,n){n||delete e[t]}async selectM2MEdges(e,t,n,i,o,s,a,u){let c=`t.${s}`,d=!!a||u.some(g=>g.column!==c),l=d?u:u.map(g=>({...g,column:`${n}.${o}`})),f=t.userLimit,p=t.userPage;if(f!==void 0&&f>0){let g=p?(p-1)*f:0;return(await W(e,async y=>{let b=this.knex(n).select({[Qt]:`${n}.${i}`,[Fn]:`${n}.${o}`}).whereIn(`${n}.${i}`,y);d&&(b=b.join(`${t.targetTable} as t`,`${n}.${o}`,`t.${s}`),a&&ce(b,a,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(b,t.userSort,t.targetTable,"t")),b.select(this.buildPartitionRowNumber(`${n}.${i}`,l,d?c:`${n}.${o}`));let w=await this.runQuery(this.buildPartitionSlice(b,Qt,g,f));return this.removePartitionFields(w),w})).map(y=>({sourceId:y[Qt],targetId:y[Fn]}))}return(await W(e,g=>{let m=this.knex(n).select({[Qt]:`${n}.${i}`,[Fn]:`${n}.${o}`}).whereIn(`${n}.${i}`,g);if(d&&(m=m.join(`${t.targetTable} as t`,`${n}.${o}`,`t.${s}`),a&&ce(m,a,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(m,t.userSort,t.targetTable,"t")),m.orderBy(`${n}.${i}`,"asc"),l.length>0){for(let y of l)m.orderBy(y.column,y.order);d&&!l.some(y=>y.column===c)&&m.orderBy(c,"asc")}else m.orderBy(`${n}.${o}`,"asc");return this.runQuery(m)})).map(g=>({sourceId:g[Qt],targetId:g[Fn]}))}async loadM2MTargets(e,t,n){if(t.length===0)return[];let i=n.selectCols.map(o=>this.toKnexSelect(o));return W(t,o=>this.runQuery(this.knex(e).select(i).whereIn(n.pkCol,o)),this.m2mTargetChunkSize())}async fetchM2M(e,t,n,i,o){let s=this.resolveParentPk(n),a=this.uniqueValues(e.map(x=>x[s]));if(a.length===0)return{grouped:new Map,docs:[]};let u=t.junctionTableName,c=t.junctionSourceColumn,d=t.junctionTargetColumn;if(!u||!c||!d)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let l=t.userFilter?this.buildFilterTree(t.userFilter,t.targetTable):null,f=t.userSort?this.parseSortTokens(t.userSort,t.targetTable,"t"):[],p=await this.selectM2MEdges(a,t,u,c,d,o.pkCol,l,f),h=new Map;for(let x of a)h.set(this.keyOf(x),[]);let g=o.selectCols.length===1&&o.selectCols[0]===o.pkCol,m=t.userLimit!==void 0&&t.userLimit>0,y=this.chunkCount(a),b=`t.${o.pkCol}`,w=!l&&f.every(x=>x.column===b);if(g){let x=new Map;for(let $ of p){let I=this.keyOf($.targetId);x.has(I)||x.set(I,{[o.pkCol]:$.targetId}),h.get(this.keyOf($.sourceId))?.push(x.get(I))}return{grouped:h,docs:[],stats:{strategy:w?m?"m2m-junction-partitioned-top-k":"m2m-junction-batch":m?"m2m-filtered-edge-top-k":"m2m-filtered-edge-batch",roundtrips:y,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let C=this.uniqueValues(p.map(x=>x.targetId)),T=await this.loadM2MTargets(t.targetTable,C,o),k=new Map(T.map(x=>[this.keyOf(x[o.pkCol]),x]));for(let x of p){let $=k.get(this.keyOf(x.targetId));$&&h.get(this.keyOf(x.sourceId))?.push($)}return{grouped:h,docs:T,stats:{strategy:m?"m2m-partitioned-edge-loader":"m2m-edge-loader",roundtrips:y+(C.length>0?this.chunkCount(C,this.m2mTargetChunkSize()):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+T.length,rowsDiscarded:0}}}}});var ui={};En(ui,{executeBatchFetches:()=>hr});async function hr(r,e,t,n,i=3,o=0,s,a="postgres",u,c){let d=new st(r,a,u);await new Se(d,n,c).execute(e,t,i,o,s)}var mr=q(()=>{"use strict";Ge();gr()});var zo={};En(zo,{ALL_SUPPORTED_OPERATORS:()=>Nt,AuthenticationException:()=>gt,AuthorizationException:()=>ht,BadRequestException:()=>N,BatchExecutionBudget:()=>Ce,BatchFetchEngine:()=>Se,BusinessLogicException:()=>ut,CHUNKED_FETCH_CONCURRENCY:()=>Yn,ConfigurationException:()=>$t,DEEP_TO_MANY_DEFAULT_LIMIT:()=>Xn,DEFAULT_BATCH_FETCH_IO_CONCURRENCY:()=>Hr,DEFAULT_TIMEOUT_MS:()=>Vt,DOTTED_PATH_MAX_HOPS:()=>Nn,DatabaseException:()=>Le,DuplicateResourceException:()=>pt,ErrorHandler:()=>xe,ExecutorEngineService:()=>Be,ExternalServiceException:()=>bt,FIELD_OPERATORS:()=>we,FileNotFoundException:()=>St,FileSizeExceededException:()=>Ct,FileUploadException:()=>Tt,HttpException:()=>P,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>Yt,InvalidTokenException:()=>yt,IsolatedExecutorService:()=>We,JoinRegistry:()=>ie,LOGICAL_OPERATORS:()=>qn,MongoBatchAdapter:()=>Xe,MongoQueryExecutor:()=>Ae,PER_PARENT_CONCURRENCY:()=>Ee,QueryBuilderService:()=>at,QueryPlanner:()=>Z,ResourceNotFoundException:()=>ft,SchemaException:()=>wt,ScriptContractService:()=>tn,ScriptExecutionException:()=>ye,ScriptTimeoutException:()=>me,ServiceUnavailableException:()=>_t,SqlBatchAdapter:()=>st,SqlQueryExecutor:()=>je,TokenExpiredException:()=>mt,ValidationException:()=>dt,WHERE_IN_CHUNK_SIZE:()=>oe,WorkerPool:()=>Rt,appendIsolatedExecutorRuntimeLog:()=>Q,applyOperatorToMatch:()=>an,applyRelationFilters:()=>Lt,applyWhereToKnex:()=>it,assertFieldOperatorValueIsClean:()=>un,buildMongoCharFoldMapJson:()=>Wn,buildMongoFoldTextSearchJs:()=>nn,buildRelationSubquery:()=>Bt,buildSqlWherePartsFromFieldAst:()=>Wt,buildWhereClause:()=>le,camelToSnake:()=>Er,chunkedFetch:()=>W,compileScriptSource:()=>zi,computeEngineTuning:()=>Pn,createEnfyraKernel:()=>Jo,dslOpToCompareOp:()=>ln,encodeMainThreadToIsolate:()=>Bn,escapeSqlValue:()=>Kt,executeBatchFetches:()=>hr,executeMongoBatchFetches:()=>wn,expandFieldsToJoinsAndSelect:()=>dr,getEffectiveCpuCount:()=>An,getEffectiveMemoryBytes:()=>kt,getEngineTuning:()=>en,getExecutableScript:()=>Yi,getForeignKeyColumnName:()=>J,getIoAbortSignal:()=>Rr,getJunctionColumnNames:()=>vt,getJunctionTableName:()=>xt,getPrimaryKeyColumn:()=>H,getScriptLegacyField:()=>Ui,getShortFkConstraintName:()=>Nr,getShortFkName:()=>Or,getShortIndexName:()=>Ar,getShortPkName:()=>Ir,hasLogicalOperators:()=>he,isExecutableJavaScript:()=>Vi,isScriptTable:()=>Qi,normalizeAggregateQuery:()=>tt,normalizeFlowStepScriptConfig:()=>Zi,normalizeScriptLanguage:()=>Ji,normalizeScriptPatch:()=>Gi,normalizeScriptRecord:()=>Hi,parseBatchFields:()=>He,parseFields:()=>$n,parseFilter:()=>fe,perParentRun:()=>_n,quoteIdentifier:()=>v,quoteQualifiedIdentifier:()=>Re,resolveExecutableScript:()=>Xi,rewriteFilterDenyingFields:()=>pi,rewriteSortDroppingDenied:()=>gi,runWithIoAbortSignal:()=>Fr,scriptContractService:()=>te,separateFilters:()=>V,snakeToCamel:()=>Mr,throwUnsupportedFieldOperator:()=>Me,validateDeepOptions:()=>yr,validateFilterShape:()=>re,whereToMongoFilter:()=>Qe});module.exports=wi(zo);var Vt=3e4,Be=class{constructor(e){this.isolatedExecutorService=e.isolatedExecutorService}register(e,t){e.routeData.__codeBlocks||(e.routeData.__codeBlocks=[]),e.routeData.__codeBlocks.push(t)}async runBatch(e,t,n={}){let i=e.routeData.__codeBlocks||[];return i.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(i,e.routeData.context,t??Vt,n)}async run(e,t,n=Vt,i={}){return this.isolatedExecutorService.run(e,t,n,i)}};var Ht=class{constructor(e){this.context=e}log(e){console.log(this.format(e))}warn(e){console.warn(this.format(e))}error(e,t){console.error(this.format(e)),t&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};var Sr=require("async_hooks"),Cr=ue(require("path")),kr=require("stream");var _r=require("child_process"),$i=["PATH","HOME","NODE_ENV","TMPDIR","LANG"];function Ti(){let r={};for(let e of $i){let t=process.env[e];t!==void 0&&(r[e]=t)}return r}var Gt=class{constructor(e){this.terminated=!1;this.child=(0,_r.fork)(e,[],{stdio:["ignore","ignore","ignore","ipc"],env:Ti(),serialization:"advanced"})}get pid(){return this.child.pid}on(e,t){return this.child.on(e,t),this}off(e,t){return this.child.off(e,t),this}postMessage(e){if(!this.child.connected)throw new Error("Executor runner IPC is closed");this.child.send(e)}terminate(){if(this.terminated)return;this.terminated=!0;try{this.child.disconnect()}catch{}try{this.child.kill("SIGTERM")}catch{}setTimeout(()=>{if(!(this.child.exitCode!==null||this.child.signalCode!==null))try{this.child.kill("SIGKILL")}catch{}},250).unref?.()}};var me=class extends Error{constructor(t=0,n,i){let o=typeof t=="number"&&t>0?`${t}ms`:String(t||"configured timeout");super(`Script execution timed out after ${o}`);this.statusCode=408;this.errorCode="SCRIPT_TIMEOUT";this.name="ScriptTimeoutException",this.details={timeoutMs:t,scriptId:n,...i}}},ye=class extends Error{constructor(t,n,i){super(`Script execution failed: ${t}`);this.statusCode=400;this.errorCode="SCRIPT_EXECUTION_ERROR";this.name="ScriptExecutionException",this.details={scriptId:n,...i}}},j=class extends Error{constructor(t,n,i,o){super(t);this.statusCode=n;this.errorCode=i;this.name=this.constructor.name,this.details=o}},P=class extends j{constructor(e,t,n){super(e,t,`HTTP_${t}`,n)}},ut=class extends j{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},dt=class extends j{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},ft=class extends j{constructor(e,t){super(t?`${e} with identifier '${t}' not found`:`${e} not found`,404,"RESOURCE_NOT_FOUND",{resource:e,identifier:t})}},pt=class extends j{constructor(e,t,n){super(`${e} with ${t} '${n}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:n})}},gt=class extends j{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},ht=class extends j{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},mt=class extends j{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},yt=class extends j{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},Le=class extends j{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},bt=class extends j{constructor(e,t,n){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:n})}},_t=class extends j{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},wt=class extends j{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},$t=class extends j{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},Tt=class extends j{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},St=class extends j{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},Ct=class extends j{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var xe=class{static createException(e,t,n,i,o){if(e?.includes("$throw"))switch(e){case"$throw.http":return new P(n||"Error",t||500,o);case"$throw.businessLogic":return new ut(n||"Bad request",o);case"$throw.validation":return new dt(n||"Validation failed",o);case"$throw.notFound":return new ft(o?.resource||n||"Resource",o?.identifier);case"$throw.duplicate":return new pt(o?.resource||n||"Resource",o?.field||"field",o?.value||"value");case"$throw.unauthorized":return new gt(n||"Unauthorized");case"$throw.forbidden":return new ht(n||"Forbidden");case"$throw.tokenExpired":return new mt;case"$throw.invalidToken":return new yt;case"$throw.database":return new Le(n||"Database error",o);case"$throw.dbQuery":return new Le(n||"Query error",o);case"$throw.externalService":return new bt(n||"Service",n||"Error",o);case"$throw.serviceUnavailable":return new _t(n||"Service");case"$throw.rateLimit":return new P(n||"Rate limit exceeded",429);case"$throw.scriptError":return new ye(n||"Script error",i,o);case"$throw.scriptTimeout":return new me(o?.timeout||5e3,i);case"$throw.schema":return new wt(n||"Schema error",o);case"$throw.config":return new $t(n||"Configuration error",o);case"$throw.fileUpload":return new Tt(n||"File upload error",o);case"$throw.fileNotFound":return new St(n||"File not found");case"$throw.fileSizeExceeded":return new Ct(o?.maxSize||"unknown",o?.actualSize||"unknown");case"$throw.400":return new P(n||"Bad request",400,o);case"$throw.401":return new P(n||"Authentication required",401,o);case"$throw.403":return new P(n||"Insufficient permissions",403,o);case"$throw.404":return new P(n||"Not found",404,o);case"$throw.409":return new P(n||"Conflict",409,o);case"$throw.422":return new P(n||"Validation failed",422,o);case"$throw.429":return new P(n||"Rate limit exceeded",429,o);case"$throw.500":return new P(n||"Internal server error",500,o);case"$throw.503":return new P(n||"Service unavailable",503,o);default:return new ye(n||"Unknown error",i)}if(t)switch(t){case 400:return new P(n||"Bad request",400,o);case 401:return new P(n||"Authentication required",401,o);case 403:return new P(n||"Insufficient permissions",403,o);case 404:return new P(n||"Not found",404,o);case 409:return new P(n||"Conflict",409,o);case 422:return new P(n||"Validation failed",422,o);case 429:return new P(n||"Rate limit exceeded",429,o);case 500:return new P(n||"Internal server error",500,o);case 503:return new P(n||"Service unavailable",503,o);default:return new ye(n||"Unknown error",i,o)}return new ye(n||"Unknown error",i,o)}};var Xt=ue(require("fs")),Zt=ue(require("path")),Yt=Zt.join(process.cwd(),"test","logs","isolated-executor-runtime.log");function Si(){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 Ci=Si();function Q(r){if(Ci)try{let e=Zt.dirname(Yt);Xt.mkdirSync(e,{recursive:!0});let t=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...r})+`
|
|
2
|
+
`;Xt.appendFileSync(Yt,t)}catch{}}var be=ue(require("os")),De=ue(require("fs"));function kt(){try{let r=De.readFileSync("/sys/fs/cgroup/memory.max","utf8").trim();if(r!=="max"){let e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<be.totalmem())return e}}catch{}try{let r=De.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes","utf8").trim(),e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<be.totalmem())return e}catch{}return be.totalmem()}function An(){let r=be.availableParallelism?.()||be.cpus()?.length||1;try{let e=De.readFileSync("/sys/fs/cgroup/cpu.max","utf8").trim(),[t,n]=e.split(/\s+/);if(t!=="max"){let i=parseInt(t,10),o=parseInt(n,10);if(i>0&&o>0)return Math.max(1,Math.ceil(i/o))}}catch{}try{let e=parseInt(De.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8").trim(),10),t=parseInt(De.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_period_us","utf8").trim(),10);if(e>0&&t>0)return Math.max(1,Math.ceil(e/t))}catch{}return r}var ki=.25,On=128,Ri=2,Fi=4,xi=2048,vi=40,Ii=128,Ni=32;function Mi(r){let e=Math.trunc(Number(r));if(!(!Number.isFinite(e)||e<1))return Math.min(On,e)}function wr(r){return 2**Math.ceil(Math.log2(Math.max(1,r)))}function Pn(r){let e=Math.max(1,Math.trunc(r.logicalCpuCount)||1),t=Math.max(1,r.totalMemoryBytes/(1024*1024)),n=Math.min(Ii,Math.max(vi,Math.round(t/Ni))),i=t*ki,o=Math.max(1,Math.floor(i/n)),s=Math.max(1,Math.min(e,2,o)),a=Math.max(1,Math.floor(i/(s*n))),u=Math.min(On,wr(e*Ri)),c=Math.min(On,wr(e*Fi)),d=Math.max(u,Math.min(c,a)),l=Mi(r.maxLanesPerRunner)??d,f=t<xi?1:l,p=Math.max(1,Math.min(f,a));return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:p,isolatePoolSize:p}}function en(){return Pn({logicalCpuCount:An(),totalMemoryBytes:kt()})}var Ki=Cr.join(__dirname,"execution/worker.js"),qi=1e3,jn=new Sr.AsyncLocalStorage;function Rr(){return jn.getStore()}function Fr(r,e){return jn.run(r,e)}var Rt=class{constructor(e,t,n,i,o,s,a,u=6e4){this.scriptPath=o;this.onCrash=s;this.onRotate=a;this.entries=[];this.waiting=[];this.cachedMemoryOk=!0;this.lastMemoryCheckMs=0;this.memorySampleIntervalMs=200;this.destroying=!1;this.entryCounter=0;this.max=e,this.effectiveMemory=t,this.rssCeiling=n,this.tasksCap=i,this.drainTimeoutMs=u;for(let c=0;c<e;c++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new Gt(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,reservations:0,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let i=t.tasks.get(n.id);i&&(n.type==="taskReleased"?i.onRelease?.():n.type==="result"||n.type==="taskCancelled"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),typeof n.runnerRssBytes=="number"&&(t.lastRssBytes=n.runnerRssBytes),n.contextStats&&(t.contextStats=n.contextStats),i.onResult(n.type==="taskCancelled"?{type:"result",id:n.id,success:!1,taskCancelled:!0,error:{message:"Task cancelled",code:"ERR_TASK_CANCELLED"}}:n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):i.onIoCall(n))}),e.on("exit",()=>{let n=t.draining,i=this.destroying;t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,s]of t.tasks)s.abortController.abort(),s.onResult({type:"result",success:!1,error:{message:i?"Worker terminated":t.lastError?`Worker crashed: ${t.lastError}`:"Worker crashed",code:i?void 0:"ERR_EXECUTOR_RUNNER_LOST",details:i?void 0:{outcome:"unknown_outcome",retryable:!1}}});t.tasks.clear();let o=this.entries.indexOf(t);o!==-1&&this.entries.splice(o,1),!n&&!i&&(this.onCrash&&this.onCrash(),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),e.on("error",n=>{t.lastError=n.message}),this.entries.push(t),t}rotateEntry(e,t){if(e.draining)return;e.draining=!0;let n=Date.now()-e.spawnedAt;if(this.onRotate&&this.onRotate({reason:t,ageMs:n}),this.spawnEntry(),e.tasks.size===0){e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,e.worker.terminate()},this.drainTimeoutMs)}isMemoryAvailable(){let e=Date.now();return e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs&&(this.cachedMemoryOk=process.memoryUsage().rss/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e),this.cachedMemoryOk}findLeastBusy(){let e=null;for(let t of this.entries){if(t.draining)continue;let n=t.tasks.size+t.reservations;n<this.tasksCap&&(!e||n<e.tasks.size+e.reservations)&&(e=t)}return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size+e.reservations===0||this.isMemoryAvailable())?(e.reservations++,Promise.resolve(e)):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.reservations=Math.max(0,e.reservations-1),e.tasks.set(t,n)}releaseReservation(e){e.reservations=Math.max(0,e.reservations-1),this.drainWaiting()}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&(e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(e&&(e.tasks.size+e.reservations===0||this.isMemoryAvailable()))e.reservations++,this.waiting.shift()(e);else break}}terminateEntry(e){e.worker.terminate()}resize(e){for(this.max=Math.max(1,e);this.entries.length<this.max;)this.spawnEntry()}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,pid:e.worker.pid,activeTasks:e.tasks.size,reservations:e.reservations,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,lastRssBytes:e.lastRssBytes??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}},Tr=new Set(["$helpers","$cache","$transaction","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$debug"]);function Bn(r){if(r===void 0)return JSON.stringify({__e:"u"});try{return JSON.stringify({__e:"v",d:r},(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return JSON.stringify({__e:"v",d:{__serializationError:!0,message:"Result is not JSON-serializable"}})}}var We=class r{constructor(e){this.logger=new Ht(r.name);this.effectiveMemory=kt();this.prevCpuUsage=process.cpuUsage();this.prevCpuTime=process.hrtime.bigint();this.pressureTicks=0;this.recoveryTicks=0;this.taskCounter=0;this.taskDoneTotal=0;this.taskErrorTotal=0;this.taskTimeoutTotal=0;this.rotationsTotal=0;this.crashesTotal=0;this.responseStreams=new Map;this.taskCancellers=new Map;this.taskDurationsMs=[];this.queueWaitDurationsMs=[];this.runtimeCallbackCounter=0;this.packageCacheService=e.packageCacheService,this.packageCdnLoaderService=e.packageCdnLoaderService,this.isolationTuning=e.tuning??en(),this.ceiling=this.isolationTuning.maxConcurrentWorkers,this.pool=new Rt(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Ki,()=>{this.crashesTotal++,this.logger.warn("Worker crashed, replacement spawned")},({reason:t,ageMs:n})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${t} age=${Math.round(n/1e3)}s`)}),this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let t=process.memoryUsage().rss/this.effectiveMemory,n=process.hrtime.bigint(),i=process.cpuUsage(this.prevCpuUsage),o=Number(n-this.prevCpuTime)/1e3,s=o>0?(i.user+i.system)/o:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let a=this.pool.getMax(),u=this.pool.getWaitingCount(),c=t>.85||s>.7,d=t<.7&&s<.5,l=u>0,f=a;c?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(f=Math.max(1,a-1))):d&&l?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(f=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),f!==a&&(this.pool.resize(f),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${f} (rss=${Math.round(t*100)}% cpu=${Math.round(s*100)}% queue=${u})`))}createSnapshot(e){let t={$body:e.$body,$query:e.$query,$params:e.$params,$user:e.$user,$share:e.$share,$data:e.$data,$api:{request:e.$api?.request},$uploadedFile:e.$uploadedFile,$req:this.cloneSnapshotValue(e.$req)};for(let i of Object.keys(e)){if(!i.startsWith("$")||i in t||Tr.has(i))continue;let o=this.cloneSnapshotValue(e[i]);o!==void 0&&(t[i]=o)}let n=e.$flow;if(n!=null)try{t.$flow=this.cloneSnapshotValue(n)??{}}catch{t.$flow={}}return t}cloneSnapshotValue(e){if(typeof e!="function")try{return JSON.parse(JSON.stringify(e,(t,n)=>{if(typeof n=="bigint")return String(n);if(typeof n!="function")return n}))}catch{return}}mergeCtxChanges(e,t){if(t){t.$body!==void 0&&(e.$body=t.$body),t.$query!==void 0&&(e.$query=t.$query),t.$params!==void 0&&(e.$params=t.$params),t.$data!==void 0&&(e.$data=t.$data),t.$error!==void 0&&(e.$error=t.$error),t.$statusCode!==void 0&&(e.$statusCode=t.$statusCode),t.$share!==void 0&&(e.$share=t.$share),t.$api!==void 0&&e.$api&&(t.$api.error&&(e.$api.error=t.$api.error),t.$api.response&&(e.$api.response=t.$api.response)),t.$flow!==void 0&&t.$flow!==null&&typeof t.$flow=="object"&&e.$flow!=null&&typeof e.$flow=="object"&&Object.assign(e.$flow,t.$flow);for(let[n,i]of Object.entries(t))n.startsWith("$")&&(n==="$body"||n==="$query"||n==="$params"||n==="$data"||n==="$error"||n==="$statusCode"||n==="$share"||n==="$api"||n==="$flow"||Tr.has(n)||n==="$env"||(e[n]=i));delete e.$pkgs}}spawnAndExecute(e,t,n,i,o){return(async()=>{let s=Date.now(),a=await this.pool.dispatch();if(this.recordQueueWait(Date.now()-s),o?.aborted){this.pool.releaseReservation(a);let d=new Error("Execution aborted after client disconnect");return d.code="ERR_EXECUTION_ABORTED",d.isAbort=!0,Promise.reject(d)}let u=`t_${++this.taskCounter}`,c=Date.now();return new Promise((d,l)=>{let f=!1,p=new AbortController,h=!1,g,m=()=>{let $=new Error("Execution aborted after client disconnect");return $.code="ERR_EXECUTION_ABORTED",$.isAbort=!0,$},y=()=>{let $=new Error(`Script execution timed out after ${i}ms`);return $.code="ERR_SCRIPT_EXECUTION_TIMEOUT",$.isTimeout=!0,$},b,w=$=>{if(!(f||h)){h=!0,g=$,p.abort(),this.cleanupResponseStream(u,$);try{a.worker.postMessage({type:"cancelTask",id:u})}catch{}b=setTimeout(()=>{f||(f=!0,clearTimeout(x),k(),this.taskCancellers.delete(u),this.pool.unregisterTask(a,u),this.taskErrorTotal++,Q({event:"task_cancel_grace_terminate",id:u}),this.pool.terminateEntry(a),$.details={...$.details??{},outcome:"unknown_outcome",retryable:!1,escalation:"runner_terminated_after_cancel_grace"},l($))},qi),b.unref?.()}},C=()=>w(m());this.taskCancellers.set(u,C);let T=()=>C(),k=()=>{o?.removeEventListener("abort",T)};o&&o.addEventListener("abort",T,{once:!0});let x=setTimeout(()=>{f||(this.taskTimeoutTotal++,Q({event:"task_timeout",id:u,timeoutMs:i}),w(y()))},i);this.pool.registerTask(a,u,{abortController:p,onResult:$=>{if(!f){if($.taskCancelled===!0&&this.pool.unregisterTask(a,u),f=!0,clearTimeout(x),b&&clearTimeout(b),this.taskCancellers.delete(u),k(),this.cleanupResponseStream(u),this.recordTaskDuration(Date.now()-c),h){p.abort(),this.taskErrorTotal++,l(g??m());return}if($.success){this.taskDoneTotal++,Q({event:"task_done",id:u,ok:!0});let I={value:$.value,valueAbsent:$.valueAbsent===!0,ctxChanges:$.ctxChanges};$.shortCircuit&&(I.shortCircuit=!0),d(I)}else{this.taskErrorTotal++,Q({event:"task_done",id:u,ok:!1,message:$.error?.message});let I=new Error($.error?.message||"Handler execution failed");I.statusCode=$.error?.statusCode,I.code=$.error?.code,I.details=$.error?.details,$.error?.stack&&(I.stack=$.error.stack),$.ctxChanges&&(I.ctxChanges=$.ctxChanges),this.cleanupResponseStream(u,I),l(I)}}},onRelease:()=>{this.pool.unregisterTask(a,u)},onIoCall:$=>{if(f)return;let I=p.signal;$.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall($,n),a.worker,$.callId,I):$.type==="transactionCall"?this.handleIoCall(()=>this.execTransactionCall($,n,a.worker),a.worker,$.callId,I):$.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall($,n),a.worker,$.callId,I):$.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall($,n),a.worker,$.callId,I):$.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall($,n),a.worker,$.callId,I):$.type==="storageCall"?this.handleIoCall(()=>this.execStorageCall($,n,a.worker),a.worker,$.callId,I):$.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall($,n),a.worker,$.callId,I):$.type==="resCall"&&this.handleIoCall(()=>this.execResCall($,n),a.worker,$.callId,I)}}),a.worker.postMessage({type:e,id:u,...t}),o?.aborted&&C()})})()}postAbortedCallError(e,t){try{e.postMessage({type:"callError",callId:t,error:JSON.stringify({__userThrow:!0,message:"Execution aborted after client disconnect",code:"ERR_EXECUTION_ABORTED"})})}catch{}}async handleIoCall(e,t,n,i){if(i?.aborted){this.postAbortedCallError(t,n);return}try{let o=await(i?jn.run(i,e):e());if(i?.aborted){this.postAbortedCallError(t,n);return}try{t.postMessage({type:"callResult",callId:n,result:Bn(o)})}catch{}}catch(o){if(i?.aborted){this.postAbortedCallError(t,n);return}try{let s={__userThrow:!0,message:o.message,statusCode:o.statusCode,code:o.errorCode??o.code,details:o.details,messages:o.messages};t.postMessage({type:"callError",callId:n,error:JSON.stringify(s)})}catch{}}}async execRepoCall(e,t){let n=JSON.parse(e.argsJson),i=e.access==="secure"?t?.$repos?.secure?.[e.table]:t?.$repos?.[e.table];if(!i||typeof i[e.method]!="function"){let o=e.access==="secure"?"secure.":"";throw new Error(`Repo method not found: ${o}${e.table}.${e.method}`)}return i[e.method](...n)}async execTransactionCall(e,t,n){let o=JSON.parse(e.argsJson||"[]").map(a=>a?.__fnRef&&typeof a.__fnRef=="string"?(...u)=>this.invokeRuntimeCallback(n,e.id,a.__fnRef,u):a)[0];if(typeof o!="function")throw new Error("$transaction.run requires a callback");let s=t?.$transaction?.run;if(typeof s!="function")throw new Error("$transaction is not available");return await s.call(t.$transaction,o)}async execHelpersCall(e,t){let n=JSON.parse(e.argsJson),i=e.name.split("."),o=t?.$helpers;for(let s of i)o=o?.[s];if(typeof o!="function")throw new Error(`Helper not found: ${e.name}`);return o(...n)}async execSocketCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$socket?.[e.method];if(typeof i!="function")throw new Error(`Socket method not found: ${e.method}`);return i(...n)}async execCacheCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$cache?.[e.method];if(typeof i!="function")throw new Error(`Cache method not found: ${e.method}`);return i(...n)}async execStorageCall(e,t,n){let i=this.parseStorageArgs(e.argsJson,n,e.id),o=t?.$storage?.[e.method];if(typeof o!="function")throw new Error(`Storage method not found: ${e.method}`);return o(...i)}parseStorageArgs(e,t,n){return JSON.parse(e,(i,o)=>{if(o?.__fnRef&&typeof o.__fnRef=="string"){let s=o.__fnRef;return(...a)=>this.invokeRuntimeCallback(t,n,s,a)}return o})}invokeRuntimeCallback(e,t,n,i){let o=`rtcb_${++this.runtimeCallbackCounter}`;return new Promise((s,a)=>{let u=setTimeout(()=>{d(),a(new Error(`Runtime callback timed out: ${n}`))},3e4),c=l=>{if(!(l?.type!=="runtimeCallbackResult"||l.callId!==o)){if(d(),l.error){a(new Error(l.error));return}s(l.value)}},d=()=>{clearTimeout(u),e.off("message",c)};e.on("message",c),e.postMessage({type:"invokeRuntimeCallback",id:t,callId:o,callbackId:n,argsJson:JSON.stringify(i)})})}async execDispatchCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$trigger;if(typeof i!="function")throw new Error("$trigger is not available");return i(...n)}cancelTask(e){this.taskCancellers.get(e)?.()}async execResCall(e,t){if(e.method==="streamStart"){let s=JSON.parse(e.argsJson||"[]")[1]||{},a=t?.$res?.stream;if(typeof a!="function")throw new Error("Response method not found: stream");let u=new kr.PassThrough,c={stream:u};this.responseStreams.set(e.id,c);let d=t?.$res;if(d&&typeof d.once=="function"){let f=()=>{d.writableEnded!==!0&&this.cancelTask(e.id)};d.once("close",f),c.closeCleanup=()=>{typeof d.off=="function"?d.off("close",f):typeof d.removeListener=="function"&&d.removeListener("close",f)}}let l=a.call(t.$res,u,s);return l&&typeof l.catch=="function"&&l.catch(()=>{}),!0}if(e.method==="streamChunk"){let o=this.responseStreams.get(e.id);if(!o)throw new Error(`Response stream not found: ${e.id}`);let s=Buffer.from(e.chunk||"","base64");return o.stream.write(s)||await new Promise((a,u)=>{let c=()=>{l(),a()},d=f=>{l(),u(f)},l=()=>{o.stream.off("drain",c),o.stream.off("error",d)};o.stream.once("drain",c),o.stream.once("error",d)}),!0}if(e.method==="streamEnd"){let o=this.responseStreams.get(e.id);return o&&(o.closeCleanup?.(),o.stream.end(),this.responseStreams.delete(e.id)),!0}if(e.method==="streamError"){let o=this.responseStreams.get(e.id);if(o){o.closeCleanup?.();let s=e.error?.message||"Response stream failed";o.stream.destroy(new Error(s)),this.responseStreams.delete(e.id)}return!0}let n=JSON.parse(e.argsJson||"[]"),i=t?.$res?.[e.method];if(typeof i!="function")throw new Error(`Response method not found: ${e.method}`);return i.apply(t.$res,n)}cleanupResponseStream(e,t){let n=this.responseStreams.get(e);n&&(this.responseStreams.delete(e),n.closeCleanup?.(),t?n.stream.destroy(t):n.stream.end())}toWorkerCodeBlock(e){return{code:e.code,sourceCode:e.sourceCode,scriptLanguage:e.scriptLanguage,type:e.type}}async run(e,t,n,i={}){let o=Math.max(1,Math.trunc(Number(n)||3e4)),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),u=this.createSnapshot(t);Q({event:"isolated_run_start",timeoutMs:o,codeLen:e?.length??0});let c;try{let d={code:e,sourceCode:i.sourceCode??e,pkgSources:a,snapshot:u,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};c=await this.spawnAndExecute("execute",d,t,o)}catch(d){let l=d;if(Q({event:"isolated_run_error",message:l.message,code:l.code,isTimeout:!!l.isTimeout}),l.code==="ERR_EXECUTION_ABORTED"||l.isAbort)throw l;if(l.isTimeout||l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new me(o,e,l.details);l.code&&l.details&&(l.details.executorCode=l.code);let f=l.statusCode??(typeof l.status=="number"?l.status:void 0);throw xe.createException(l.errorPath,f,l.message||"Unknown error",e,l.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),Q({event:"isolated_run_ok"}),c.valueAbsent?void 0:c.value}async runBatch(e,t,n,i={}){let o=Math.max(1,Math.trunc(Number(n)||3e4)),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),u=this.createSnapshot(t);Q({event:"isolated_batch_start",timeoutMs:o,blocks:e.length});let c;try{let l={codeBlocks:e.map(f=>this.toWorkerCodeBlock(f)),pkgSources:a,snapshot:u,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};c=await this.spawnAndExecute("executeBatch",l,t,o,i.signal)}catch(d){let l=d;if(Q({event:"isolated_batch_error",message:l.message,code:l.code,isTimeout:!!l.isTimeout}),l.ctxChanges&&this.mergeCtxChanges(t,l.ctxChanges),l.code==="ERR_EXECUTION_ABORTED"||l.isAbort)throw l;if(l.isTimeout||l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new me(o,"(batch execution)",l.details);l.code&&l.details&&(l.details.executorCode=l.code);let f=l.statusCode??(typeof l.status=="number"?l.status:void 0);throw xe.createException(l.errorPath,f,l.message||"Unknown error","(batch execution)",l.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),Q({event:"isolated_batch_ok"}),{value:c.valueAbsent?void 0:c.value,shortCircuit:c.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}recordQueueWait(e){this.queueWaitDurationsMs.push(e),this.queueWaitDurationsMs.length>512&&this.queueWaitDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,s)=>o-s),i=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[i]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((s,a)=>s+a,0)/t.length,i=this.queueWaitDurationsMs,o=i.length===0?0:i.reduce((s,a)=>s+a,0)/i.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),avgQueueWaitMs:o,p95QueueWaitMs:this.percentile(i,95),p99QueueWaitMs:this.percentile(i,99),maxHeapRatio:Math.max(0,...e.workers.map(s=>s.lastHeapRatio||0)),runnerRssBytes:e.workers.reduce((s,a)=>s+(a.lastRssBytes||0),0)}}};var ve=ue(require("typescript")),Ft={oauth_config_definition:"",route_handler_definition:"logic",pre_hook_definition:"code",post_hook_definition:"code",bootstrap_script_definition:"logic",websocket_definition:"connectionHandlerScript",websocket_event_definition:"handlerScript"};function Ui(r){return te.getLegacyField(r)}function Qi(r){return te.isScriptTable(r)}function Ji(r){return te.normalizeLanguage(r)}var tn=class{getLegacyField(e){return Ft[e]}isScriptTable(e){return e in Ft}normalizeLanguage(e){return e==="javascript"?"javascript":"typescript"}compileSource(e,t){if(e==null||e==="")return null;let n=String(e),o=this.normalizeLanguage(t)==="javascript"?n:this.transpileTypeScript(n);return this.assertExecutableJavaScript(o),o}isExecutableJavaScript(e){if(!e)return!1;try{return this.assertExecutableJavaScript(e),!0}catch{return!1}}normalizeRecord(e,t){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let n={...t},i=this.getLegacyField(e);return i&&(n.sourceCode===void 0||n.sourceCode===null||n.sourceCode==="")&&n[i]!==void 0&&(n.sourceCode=n[i]),n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage),i&&i in n&&delete n[i],n}normalizePatch(e,t,n){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let i=this.getLegacyField(e),o=Object.prototype.hasOwnProperty.call(t,"sourceCode")||(i?Object.prototype.hasOwnProperty.call(t,i):!1),s=Object.prototype.hasOwnProperty.call(t,"scriptLanguage");if(!o&&!s)return t;let a=o?t.sourceCode??(i?t[i]:void 0):n?.sourceCode??(i&&n?n[i]:void 0),u=s?t.scriptLanguage:n?.scriptLanguage,c={...t};return o&&(c.sourceCode=a??null),c.scriptLanguage=this.normalizeLanguage(u),c.compiledCode=this.compileSource(a,c.scriptLanguage),i&&i in c&&delete c[i],c}getExecutableScript(e){return this.resolveExecutableScript(e).code}resolveExecutableScript(e){if(!e||typeof e!="object")return{code:null,compiledCode:null,shouldPersistCompiledCode:!1};if(typeof e.sourceCode=="string"&&e.sourceCode!==""){let n=this.compileSource(e.sourceCode,e.scriptLanguage);return{code:n,compiledCode:n,shouldPersistCompiledCode:n!==e.compiledCode}}let t=Object.keys(Ft).find(n=>Ft[n]in e);if(t){let n=e[Ft[t]];if(typeof n=="string"&&n!==""){let i=this.compileSource(n,e.scriptLanguage);return{code:i,compiledCode:i,shouldPersistCompiledCode:i!==e.compiledCode}}}return typeof e.compiledCode=="string"&&e.compiledCode!==""&&this.isExecutableJavaScript(e.compiledCode)?{code:e.compiledCode,compiledCode:e.compiledCode,shouldPersistCompiledCode:!1}:{code:null,compiledCode:null,shouldPersistCompiledCode:!1}}normalizeFlowStepScriptConfig(e){if(!e||typeof e!="object")return e;let t=e.type;if(t!=="script"&&t!=="condition")return e;let n={...e},i=e.config;if(typeof i=="string")try{i=JSON.parse(i)}catch{return e}let o=i&&typeof i=="object"?i:{};n.sourceCode=n.sourceCode??o.sourceCode??o.code??null,n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage??o.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage);let s={...o};return delete s.sourceCode,delete s.scriptLanguage,delete s.compiledCode,delete s.code,{...n,config:typeof e.config=="string"?JSON.stringify(s):s}}repairContract(e){let t=this.normalizeLanguage(e?.scriptLanguage),n=e?.sourceCode??null,i=this.compileSource(n,t);return{sourceCode:n,scriptLanguage:t,code:i,compiledCode:i,shouldPersistCompiledCode:i!==e?.compiledCode}}transpileTypeScript(e){let t=ve.default.transpileModule(e,{compilerOptions:{target:ve.default.ScriptTarget.ES2022,module:ve.default.ModuleKind.CommonJS,importsNotUsedAsValues:ve.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),n=t.diagnostics?.find(i=>i.category===ve.default.DiagnosticCategory.Error);if(n)throw new Error(ve.default.flattenDiagnosticMessageText(n.messageText,`
|
|
3
3
|
`));return t.outputText.trimEnd()}assertExecutableJavaScript(e){e&&new Function(`return (async () => {
|
|
4
4
|
"use strict";
|
|
5
5
|
${e}
|
|
6
|
-
});`)}},te=new tn;function
|
|
7
|
-
var M = ${
|
|
6
|
+
});`)}},te=new tn;function zi(r,e){return te.compileSource(r,e)}function Vi(r){return te.isExecutableJavaScript(r)}function Hi(r,e){return te.normalizeRecord(r,e)}function Gi(r,e,t){return te.normalizePatch(r,e,t)}function Yi(r){return te.getExecutableScript(r)}function Xi(r){return te.resolveExecutableScript(r)}function Zi(r){return te.normalizeFlowStepScriptConfig(r)}var vn=require("node:fs"),di=require("node:path");var Dn=require("mongodb");Ke();function Ie(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function z(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!Ie(r)&&(r.foreignKeyColumn||r.propertyName)||null}function K(r){return r.foreignKeyColumn||r.mappedBy||r.propertyName||null}function Y(r){if(!r||typeof r!="object")return r;if(r instanceof Dn.ObjectId)return r.toString();if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return r.map(t=>Y(t));if("buffer"in r&&r.buffer&&typeof r.buffer=="object"&&Object.keys(r.buffer).length===12)try{let t=r.buffer,n=Object.keys(t).sort((i,o)=>parseInt(i)-parseInt(o)).map(i=>t[i]);return new Dn.ObjectId(Buffer.from(n)).toString()}catch{}let e={};for(let[t,n]of Object.entries(r))e[t]=n&&typeof n=="object"&&!(n instanceof Buffer)?Y(n):n;return e}function Ne(r,e){if(e.type!=="many-to-many")return null;let t=e.targetTableName||e.targetTable;if(!t)return null;if(e.mappedBy){let a=t,u=e.mappedBy,c=r,d=e.junctionTableName||xt(a,u,c);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:d,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:c};let l=vt(a,u,c);return{junctionName:d,selfColumn:l.targetColumn,otherColumn:l.sourceColumn,owningTable:a,inverseTable:c}}let n=r,i=t,o=e.junctionTableName||xt(n,e.propertyName,i);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:o,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:i};let s=vt(n,e.propertyName,i);return{junctionName:o,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:i}}async function It(r,e,t,n){if(!r)return{scalarFields:[],relations:[]};let i=r.tables?.get(e);if(!i)return{scalarFields:[],relations:[]};let o=new Map;for(let c of t)if(c==="*")o.has("")||o.set("",[]),o.get("").push(c);else if(c.includes(".")){let d=c.split("."),l=d[0],f=d.slice(1).join(".");o.has(l)||o.set(l,[]),o.get(l).push(f)}else i.relations?.some(l=>l.propertyName===c)?o.has(c)||o.set(c,["_id"]):(o.has("")||o.set("",[]),o.get("").push(c));if(n&&typeof n=="object")for(let[c,d]of Object.entries(n)){if(o.has(c))continue;let l=d&&typeof d=="object"&&d.fields!=null?Array.isArray(d.fields)?d.fields:String(d.fields).split(",").map(f=>f.trim()).filter(Boolean):["*"];o.set(c,l)}let s=[],a=[],u=o.get("")||[];for(let c of u)if(c==="*"){if(i.columns)for(let d of i.columns)s.includes(d.name)||s.push(d.name);if(i.relations)for(let d of i.relations)o.has(d.propertyName)||o.set(d.propertyName,["_id"])}else i.columns?.some(l=>l.name===c)&&!s.includes(c)&&s.push(c);for(let[c,d]of o.entries()){if(c==="")continue;let l=i.relations?.find(m=>m.propertyName===c);if(!l)continue;let f="",p="",h=!1;l.type==="many-to-one"||l.type==="one-to-one"?Ie(l)?(f="_id",p=K(l)||l.propertyName,h=!0):(f=z(l)||l.propertyName,p="_id",h=!1):l.type==="one-to-many"?(f="_id",p=K(l)||l.propertyName,h=!0):l.type==="many-to-many"&&(l.mappedBy?(f="_id",p=l.mappedBy,h=!0):(f=l.propertyName,p="_id",h=!1));let g=l.type==="one-to-many"||l.type==="many-to-many";a.push({propertyName:c,targetTable:l.targetTableName,localField:f,foreignField:p,type:g?"many":"one",isInverse:h,nestedFields:d})}return{scalarFields:s,relations:a}}var rn=ue(require("fs")),Kn=ue(require("path"));var eo=new RegExp("\\p{Mark}","gu");function Pr(r){return r==null?"":String(r).normalize("NFKD").replace(eo,"").toLowerCase()}function Wn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=Pr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function nn(){return`function() {
|
|
7
|
+
var M = ${Wn()};
|
|
8
8
|
function foldStr(s) {
|
|
9
9
|
if (s == null) return '';
|
|
10
10
|
s = String(s);
|
|
@@ -49,5 +49,5 @@ ${e}
|
|
|
49
49
|
}
|
|
50
50
|
}
|
|
51
51
|
return true;
|
|
52
|
-
}`}var Ar="mongo-fold-text-search.body.txt",qe=null;function Yi(){let r=[Wn.join(__dirname,Ar),Wn.join(process.cwd(),"dist","kernel","query","utils",Ar)];for(let e of r)try{if(rn.existsSync(e))return rn.readFileSync(e,"utf8")}catch{}return null}function on(){if(qe!==null)return qe;let r=Yi();return r?(qe=r,qe):(qe=nn(),qe)}var _e=require("mongodb");function D(r,e,t,n){if(t==="_id"){if(n instanceof _e.ObjectId)return n;if(typeof n=="string")try{return new _e.ObjectId(n)}catch{return n}return n}let i=r?.tables?.get(e);if(!i){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new _e.ObjectId(n)}catch{return n}return n}if(!i.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new _e.ObjectId(n)}catch{return n}return n}let o=i.columns.find(s=>s.name===t);if(!o){if(i.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof n=="string"&&n.length===24)try{return new _e.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new _e.ObjectId(n)}catch{return n}return n}if(n==null)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;case"uuid":if(typeof n=="string")try{return new _e.ObjectId(n)}catch{return n}return n;default:return n}}var sn="__mongoFoldTextTriples";function Xi(r){return r==="_id"?"$_id":`$${r}`}function Ue(r,e,t,n){let i=Xi(e),o=r[sn]??[];o.push({ref:i,needle:t,mode:n}),r[sn]=o}function Zi(r){let e=r[sn];if(delete r[sn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:on(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}function Qe(r,e,t,n){let i={},o=n==="mongodb"||!n;for(let s of e){let a=s.field.includes(".")?s.field.split(".").pop()??s.field:s.field,u=t||s.field.split(".")[0]||"";o&&a==="id"&&(a="_id");let c=D(r,u,a,s.value);switch(s.operator){case"=":i[a]=c;break;case"!=":i[a]={$ne:c};break;case">":i[a]={$gt:c};break;case"<":i[a]={$lt:c};break;case">=":i[a]={$gte:c};break;case"<=":i[a]={$lte:c};break;case"like":i[a]={$regex:c.replace(/%/g,".*"),$options:"i"};break;case"in":let d=s.value;Array.isArray(d)||(d=typeof d=="string"&&d.includes(",")?d.split(",").map(y=>y.trim()):[d]);let l=d.map(y=>D(r,u,a,y));i[a]={$in:l};break;case"not in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(y=>y.trim()):[f]);let p=f.map(y=>D(r,u,a,y));i[a]={$nin:p};break;case"is null":i[a]=null;break;case"is not null":i[a]={$ne:null};break;case"_contains":Ue(i,a,String(c),"contains");break;case"_starts_with":Ue(i,a,String(c),"starts");break;case"_ends_with":Ue(i,a,String(c),"ends");break;case"_between":let h=s.value;if(typeof h=="string"&&(h=h.split(",").map(y=>y.trim())),Array.isArray(h)&&h.length===2){let y=D(r,u,a,h[0]),b=D(r,u,a,h[1]);i[a]={$gte:y,$lte:b}}break;case"_is_null":let g=c===!0||c==="true";i[a]=g?{$eq:null}:{$ne:null};break;case"_is_not_null":let m=c===!0||c==="true";i[a]=m?{$ne:null}:{$eq:null};break}}return Zi(i),i}function Pr(r,e,t){let i=r?.tables?.get?.(e)?.columns?.find(o=>o.name===t);return i?i.isNullable!==!1:!0}function an(r,e,t,n,i,o){switch(i){case"_contains":Ue(e,n,String(o),"contains");break;case"_starts_with":Ue(e,n,String(o),"starts");break;case"_ends_with":Ue(e,n,String(o),"ends");break;case"_eq":e[n]=D(r,t,n,o);break;case"_neq":{let l=D(r,t,n,o);Pr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:l}})):e[n]={$ne:l};break}case"_in":{let l=o;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(p=>p.trim()):[l]);let f=l.map(p=>D(r,t,n,p));e[n]={$in:f};break}case"_not_in":case"_nin":let s=o;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(l=>l.trim()):[s]);let a=s.map(l=>D(r,t,n,l));Pr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$nin:a}})):e[n]={$nin:a};break;case"_gt":e[n]={$gt:D(r,t,n,o)};break;case"_gte":e[n]={$gte:D(r,t,n,o)};break;case"_lt":e[n]={$lt:D(r,t,n,o)};break;case"_lte":e[n]={$lte:D(r,t,n,o)};break;case"_is_null":let u=o===!0||o==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let c=o===!0||o==="true";e[n]=c?{$ne:null}:{$eq:null};break;case"_between":let d=o;if(typeof d=="string"&&(d=d.split(",").map(l=>l.trim())),Array.isArray(d)&&d.length===2){let l=D(r,t,n,d[0]),f=D(r,t,n,d[1]);e[n]={$gte:l,$lte:f}}break}}var Vn=require("mongodb");function ne(r,e){if(!r||typeof r!="object")return!1;for(let[t,n]of Object.entries(r))if(t==="_and"||t==="_or"){if(Array.isArray(n)){for(let i of n)if(ne(i,e))return!0}}else if(t==="_not"){if(ne(n,e))return!0}else if(e.has(t))return!0;return!1}function V(r,e){if(!r||typeof r!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},n={},i=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(r)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(i.has(s))if(typeof a=="object"&&a!==null){let u=Object.keys(a);if(u.some(d=>d.startsWith("_"))){let d=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&d.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let o=ne(r,i);return{fieldFilters:t,relationFilters:n,hasRelations:o}}Et();Mt();var fn="__mongoFoldTextTriples";function ze(r,e){if(!r)return{};let t={};return Ot(r,t,e),$e(t),t}function ao(r,e){if(!r)return{};let t={};return Un(r,t,e),$e(t),t}function ge(r,e,t){if(!e)return{};let n=new ie,{node:i}=fe(e,t,r,n);return ze(i,{metadata:r,rootTable:t})}function pn(r,e,t){if(!e)return{};let n=new ie,{node:i}=fe(e,t,r,n);return ao(i,{metadata:r,rootTable:t})}function Ot(r,e,t){switch(r.kind){case"true":return;case"false":pe(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let i=r.children.map(o=>{let s={};return Ot(o,s,t),$e(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}pe(e,...i);return}case"or":{let i=r.children.map(s=>{let a={};return Ot(s,a,t),$e(a),a}).filter(s=>Object.keys(s).length>0);if(i.length===0)return;let o=e.$or;e.$or=o?[...o,...i]:i;return}case"not":{let n={};Ot(r.child,n,t),$e(n);let i=e.$nor;e.$nor=i?[...i,n]:[n];return}case"compare":Wr(r,e,t);return;case"relation_exists":{console.warn(`[mongo-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${r.joinId}) \u2014 expected applyRelationFilters or null-only short-circuit to handle it. Filter silently skipped.`);return}}}function Wr(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let i=o=>D(t.metadata,t.rootTable,n,o);switch(r.op){case"eq":X(e,n,i(r.value));return;case"neq":{let o=i(r.value);Qn(t,n)?pe(e,{[n]:{$ne:null}},{[n]:{$ne:o}}):X(e,n,{$ne:o});return}case"gt":X(e,n,{$gt:i(r.value)});return;case"gte":X(e,n,{$gte:i(r.value)});return;case"lt":X(e,n,{$lt:i(r.value)});return;case"lte":X(e,n,{$lte:i(r.value)});return;case"in":{let o=Dr(r.value).map(i);X(e,n,{$in:o});return}case"not_in":{let o=Dr(r.value).map(i);Qn(t,n)?pe(e,{[n]:{$ne:null}},{[n]:{$nin:o}}):X(e,n,{$nin:o});return}case"between":{let o=Array.isArray(r.value)?r.value:typeof r.value=="string"?r.value.split(",").map(s=>s.trim()):null;Array.isArray(o)&&o.length===2&&X(e,n,{$gte:i(o[0]),$lte:i(o[1])});return}case"is_null":X(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":qn(e,n,String(r.value),"contains");return;case"starts_with":qn(e,n,String(r.value),"starts");return;case"ends_with":qn(e,n,String(r.value),"ends");return}}function Un(r,e,t){switch(r.kind){case"true":pe(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let i=r.children.map(s=>{let a={};return Un(s,a,t),$e(a),a}).filter(s=>Object.keys(s).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}let o=e.$or;e.$or=o?[...o,...i]:i;return}case"or":{let i=r.children.map(o=>{let s={};return Un(o,s,t),$e(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}pe(e,...i);return}case"not":Ot(r.child,e,t);return;case"compare":lo(r,e,t);return;case"relation_exists":{X(e,r.joinId,r.negate?{$ne:null}:{$eq:null});return}}}function lo(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached false renderer \u2014 expected relation resolver to handle it. Filter silently skipped.`);return}if(r.op==="is_null"){X(e,n,r.value===!0?{$ne:null}:{$eq:null});return}let i={};Wr(r,i,t),$e(i);let o={$nor:[i]};Qn(t,n)?pe(e,o,{[n]:{$ne:null}}):pe(e,o)}function X(r,e,t){r[e]===void 0?r[e]=t:(pe(r,{[e]:r[e]},{[e]:t}),delete r[e])}function pe(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function Qn(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(i=>i.name===e);return n?n.isNullable!==!1:!0}function Dr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function co(r){return r==="_id"?"$_id":`$${r}`}function qn(r,e,t,n){let i=co(e),o=r[fn]??[];o.push({ref:i,needle:t,mode:n}),r[fn]=o}function $e(r){let e=r[fn];if(delete r[fn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:on(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}async function Te(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return ge(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!ne(r,o))return ge(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>Te(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._or&&Array.isArray(r._or)){let d=(await Promise.all(r._or.map(l=>Te(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:{$or:d}}if(r._not)return await zn(r._not,e,t,n)||{};let{fieldFilters:s,relationFilters:a}=V(r,i),u=[];if(s&&Object.keys(s).length>0){let c=ge(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(a&&Object.keys(a).length>0)for(let[c,d]of Object.entries(a)){let l=await uo(c,d,e,i,t,n);l&&Object.keys(l).length>0&&u.push(l)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function zn(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return pn(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!ne(r,o))return pn(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>zn(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$or:d}}if(r._or&&Array.isArray(r._or)){let d=(await Promise.all(r._or.map(l=>zn(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._not)return Te(r._not,e,t,n);let{fieldFilters:s,relationFilters:a}=V(r,i),u=[];if(s&&Object.keys(s).length>0){let c=pn(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(a&&Object.keys(a).length>0)for(let[c,d]of Object.entries(a)){let l=await po(c,d,e,i,t,n);l&&Object.keys(l).length>0&&u.push(l)}return u.length===0?{}:u.length===1?u[0]:{$or:u}}async function uo(r,e,t,n,i,o){let s=(n.relations||[]).find(c=>c.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=i?.tables?.get(a);return!a||!u?{}:s.type==="many-to-one"||s.type==="one-to-one"?fo(e,s,r,a,u,i,o):s.type==="one-to-many"?Ur(e,s,t,a,u,i,o):s.type==="many-to-many"?Qr(e,s,t,a,u,i,o):{}}async function fo(r,e,t,n,i,o,s){let a=z(e)||t,u=hn(r),c=mn(u);if(c!==null)return c?{[a]:null}:{[a]:{$ne:null}};let d=Hn(u);if(d!==null){let h=yn(d.value);if(d.op==="eq")return{[a]:h};if(d.op==="neq")return{[a]:{$ne:h}};if(d.op==="in")return{[a]:{$in:h}};if(d.op==="not_in")return{$and:[{[a]:{$nin:h}},{[a]:{$ne:null}}]}}let l=await gn(u,n,i,o,s);if(!l||Object.keys(l).length===0)return{};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(h=>h._id).filter(Boolean);return p.length===0?{__impossible__:!0}:{[a]:{$in:p}}}async function po(r,e,t,n,i,o){let s=(n.relations||[]).find(c=>c.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=i?.tables?.get(a);if(!a||!u)return{};if(s.type==="many-to-one"||s.type==="one-to-one")return go(e,s,r,a,u,i,o);if(s.type==="one-to-many"){let c=await Ur(e,s,t,a,u,i,o);return qr(c)}if(s.type==="many-to-many"){let c=await Qr(e,s,t,a,u,i,o);return qr(c)}return{}}async function go(r,e,t,n,i,o,s){let a=z(e)||t,u=hn(r),c=mn(u);if(c!==null)return c?{[a]:{$ne:null}}:{[a]:null};let d=Hn(u);if(d!==null){let h=yn(d.value);if(d.op==="eq")return{$and:[{[a]:{$ne:h}},{[a]:{$ne:null}}]};if(d.op==="neq")return{[a]:h};if(d.op==="in")return{$and:[{[a]:{$nin:h}},{[a]:{$ne:null}}]};if(d.op==="not_in")return{[a]:{$in:h}}}let l=await gn(u,n,i,o,s);if(!l||Object.keys(l).length===0)return{[a]:null};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(h=>h._id).filter(Boolean);return p.length===0?{[a]:{$ne:null}}:{$and:[{[a]:{$nin:p}},{[a]:{$ne:null}}]}}async function Ur(r,e,t,n,i,o,s){let a=K(e)||t,u=hn(r),c=mn(u);if(c!==null){let f=await Kr(s,n,a,{});return c?f.length===0?{}:{_id:{$nin:f}}:f.length===0?{__impossible__:!0}:{_id:{$in:f}}}let d=await gn(u,n,i,o,s);if(!d||Object.keys(d).length===0)return{};let l=await Kr(s,n,a,d);return l.length===0?{__impossible__:!0}:{_id:{$in:l}}}async function Qr(r,e,t,n,i,o,s){let a=Ne(t,e);if(!a)return{};let u=hn(r),c=mn(u);if(c!==null){let g=await Jn(s,a,n,null);return c?g.length===0?{}:{_id:{$nin:g}}:g.length===0?{__impossible__:!0}:{_id:{$in:g}}}let d=Hn(u);if(d!==null){let g=yn(d.value),m=Array.isArray(g)?g:[g],y=await Jn(s,a,n,{_id:{$in:m}});return y.length===0?{__impossible__:!0}:{_id:{$in:y}}}let l=await gn(u,n,i,o,s);if(!l||Object.keys(l).length===0)return{};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);if(p.length===0)return{__impossible__:!0};let h=await Jn(s,a,n,{_id:{$in:p}});return h.length===0?{__impossible__:!0}:{_id:{$in:h}}}async function gn(r,e,t,n,i){let o=new Set((t?.relations??[]).map(s=>s.propertyName));return ne(r,o)?Te(r,e,n,i):ge(n,r,e)}async function Kr(r,e,t,n){let i=await r.collection(e).find(n,{projection:{[t]:1}}).toArray(),o=new Set,s=[];for(let a of i){let u=a[t];if(u==null)continue;let c=String(u);o.has(c)||(o.add(c),s.push(u))}return s}function qr(r){if(!r||Object.keys(r).length===0)return{};if(r.__impossible__===!0)return{};let e=r._id;if(e&&typeof e=="object"&&!Array.isArray(e)){if(Array.isArray(e.$in))return{_id:{$nin:e.$in}};if(Array.isArray(e.$nin))return{_id:{$in:e.$nin}}}return{$nor:[r]}}async function Jn(r,e,t,n){let i=null;n&&t&&(i=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(d=>d._id).filter(Boolean));let o=i?{[e.otherColumn]:{$in:i}}:{},s=await r.collection(e.junctionName).find(o,{projection:{[e.selfColumn]:1}}).toArray(),a=new Set,u=[];for(let c of s){let d=c[e.selfColumn];if(d==null)continue;let l=String(d);a.has(l)||(a.add(l),u.push(d))}return u}function hn(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function mn(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0],n=r[t];return t==="_is_null"?n===!0:t==="_is_not_null"?n!==!0:t==="_eq"?n===null?!0:null:t==="_neq"&&n===null?!1:null}function yn(r){if(Array.isArray(r))return r.map(e=>yn(e));if(typeof r!="string")return r;try{return new Vn.ObjectId(r)}catch{return r}}function Hn(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof Vn.ObjectId)return{op:"eq",value:r};if(r==null)return null;if(typeof r!="object")return{op:"eq",value:r};if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0];return t==="_eq"?{op:"eq",value:r._eq}:t==="_neq"?{op:"neq",value:r._neq}:t==="_in"&&Array.isArray(r._in)?{op:"in",value:r._in}:t==="_not_in"&&Array.isArray(r._not_in)?{op:"not_in",value:r._not_in}:null}async function At(r,e,t,n){let i=await It(r,e,t),o=[],s={},a={};if(n&&typeof n=="object")for(let[p,h]of Object.entries(n))if(typeof h=="object"&&h!==null){let g=Object.keys(h)[0];g&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(g)?s[p]=h:a[p]=h}else s[p]=h;if(Object.keys(s).length>0){let p={};for(let[h,g]of Object.entries(s))if(typeof g=="object"&&g!==null)for(let[m,y]of Object.entries(g))an(r,p,e,h,m,y);else p[h]=g;Object.keys(p).length>0&&o.push({$match:p})}let c=r?.tables?.get(e)?.relations||[],d=[];for(let[p,h]of Object.entries(a))if(!i.relations.some(m=>m.propertyName===p)){let m=c.find(y=>y.propertyName===p);if(m){let y="",b="";if(m.type==="many-to-one"||m.type==="one-to-one")y=z(m)||m.propertyName,b="_id";else if(m.type==="one-to-many")y="_id",b=K(m)||m.propertyName;else if(m.type==="many-to-many")continue;let $=m.type==="one-to-many"||m.type==="many-to-many";d.push({propertyName:p,targetTable:m.targetTableName,localField:y,foreignField:b,type:$?"many":"one",nestedFields:[]})}}let l=[...i.relations,...d];for(let p of l){let h=a[p.propertyName],g=p.nestedFields&&p.nestedFields.length>0?await At(r,p.targetTable,p.nestedFields,h):h?await At(r,p.targetTable,["_id"],h):[];p.type==="one"&&g.length>0&&g.push({$limit:1}),o.push({$lookup:{from:p.targetTable,localField:p.localField,foreignField:p.foreignField,as:p.propertyName,pipeline:g.length>0?g:void 0}}),p.type==="one"&&(o.push({$unwind:{path:`$${p.propertyName}`,preserveNullAndEmptyArrays:!0}}),h&&(Ve(h)||o.push({$match:{[p.propertyName]:{$ne:null}}})))}let f=c.filter(p=>!l.some(h=>h.propertyName===p.propertyName));if(i.scalarFields.length>0||i.relations.length>0||f.length>0){let p={_id:1};for(let g of i.scalarFields)p[g]=1;for(let g of l)p[g.propertyName]=1,g.type==="one"&&g.localField&&g.localField!==g.propertyName&&(p[g.localField]=1);if(t.includes("*"))for(let g of f){if(g.type==="one-to-many"||g.type==="many-to-many")continue;g.type==="many-to-many"?p[g.propertyName]={$map:{input:`$${g.propertyName}`,as:"item",in:{_id:"$$item"}}}:p[g.propertyName]={$cond:{if:{$ne:[`$${g.propertyName}`,null]},then:{_id:`$${g.propertyName}`},else:null}}}o.push({$project:p})}return o}async function Jr(r,e,t,n,i){let o=r?.tables?.get(t),s=o?.relations||[],a=o?.columns||[],u=s.filter(d=>!i.some(l=>l.propertyName===d.propertyName)),c=n.length===a.length||n.length===0&&i.length===0;if(u.length>0||!c){let d={_id:1};for(let l of n)d[l]=1;for(let l of i)d[l.propertyName]=1,l.type==="one"&&l.localField&&l.localField!==l.propertyName&&(d[l.localField]=1);for(let l of u){if(l.type==="one-to-many"||l.type==="many-to-many")continue;l.type==="many-to-many"?d[l.propertyName]={$map:{input:`$${l.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[l.propertyName]={$cond:{if:{$ne:[`$${l.propertyName}`,null]},then:{_id:`$${l.propertyName}`},else:null}}}e.push({$project:d})}}function Ve(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ve(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ve(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ve(e));if("_not"in r)return Ve(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Ve(t)))return!0}return!1}Ge();var jt=require("mongodb");Ge();bn();async function _n(r,e,t){let n=new Map,i=0;async function o(){for(;i<r.length;){let u=i++,c=r[u];n.set(String(c),await e(c))}}let s=Math.min(t,r.length);if(s===0)return n;let a=Array.from({length:s},o);return await Promise.all(a),n}var se="__sourceId__",ke="__targetId__",Ye="__enfyra_target__",Pt="__enfyra_top_n_documents__",Xe=class{constructor(e,t,n,i=new Ce){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.executionBudget=i;this.pkField="_id"}chunkCount(e){return Math.ceil(e.length/oe)||1}runQuery(e){return this.executionBudget.run(e)}uniqueValues(e){return Array.from(new Map(e.filter(t=>t!=null).map(t=>[this.keyOf(t),t])).values())}buildStableSort(e,t="_id"){let n=this.buildSortFromTokens(e)||{};return n[t]===void 0&&(n[t]=1),n}appendPartitionProjection(e,t,n){if(t){let i={...t};for(let o of n)i[o]=1;e.push({$project:i})}}appendTopNStages(e,t,n,i,o){e.push({$group:{_id:`$${t}`,[Pt]:{$topN:{sortBy:n,output:"$$ROOT",n:i+o}}}},{$project:{[Pt]:{$slice:[`$${Pt}`,i,o]}}},{$unwind:`$${Pt}`},{$replaceRoot:{newRoot:`$${Pt}`}})}normalizeMetadata(){return this.metadata?this.metadata.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortFromTokens(e){let t={};for(let n of this.parseSortTokens(e)){let i=n.field.split(".");if(i.length===1)t[i[0]]=n.order;else{let o=`__sort_${i.slice(0,-1).join("_")}`;t[`${o}.${i[i.length-1]}`]=n.order}}return Object.keys(t).length>0?t:void 0}parseSortTokens(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).map(n=>{let i=n.startsWith("-"),o=i?n.slice(1):n;return{field:o==="id"?"_id":o,order:i?-1:1}}):[]}hasDottedSort(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).some(n=>(n.startsWith("-")?n.slice(1):n).includes(".")):!1}buildSortAggregatePipeline(e,t,n){let i=Array.isArray(n)?n:n.split(",").map(c=>c.trim()).filter(Boolean),o=[{$match:t}],s=new Set;for(let c of i){let l=(c.startsWith("-")?c.slice(1):c).split(".");if(l.length<=1)continue;let f=e;for(let p=0;p<l.length-1;p++){let h=l[p],g=this.normalizeMetadata()?.tables?.get(f);if(!g)break;let m=g.relations?.find($=>$.propertyName===h);if(!m)break;let y=m.targetTableName||m.targetTable,b=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(b)){s.add(b);let $=z(m)||m.propertyName,C=p===0?null:`__sort_${l.slice(0,p).join("_")}`,T=C?`${C}.${$}`:$;o.push({$lookup:{from:y,localField:T,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}f=y}}let a=this.buildSortFromTokens(n);a&&o.push({$sort:a});let u={};for(let c of s)u[c]=0;return Object.keys(u).length>0&&o.push({$project:u}),o}toObjectId(e){try{return typeof e=="string"?new jt.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof jt.ObjectId||t instanceof jt.ObjectId?this.keyOf(e).localeCompare(this.keyOf(t)):typeof e=="number"&&typeof t=="number"?e-t:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="string"&&typeof t=="string"?e.localeCompare(t):e<t?-1:e>t?1:0}sortDocsInMemory(e,t){let n=this.parseSortTokens(t).filter(i=>!i.field.includes("."));n.length!==0&&e.sort((i,o)=>{for(let s of n){let a=this.compareSortValues(i[s.field],o[s.field]);if(a!==0)return a*s.order}return this.compareSortValues(i._id,o._id)})}sortDocsByPk(e){e.sort((t,n)=>this.compareSortValues(t._id,n._id))}projectionWithSortFields(e,t){if(!e)return{projection:e,hiddenFields:[]};let n={...e},i=[];for(let o of this.parseSortTokens(t))o.field.includes(".")||n[o.field]===void 0&&(n[o.field]=1,i.push(o.field));return{projection:n,hiddenFields:i}}removeHiddenFields(e,t){if(t.length!==0)for(let n of e)for(let i of t)delete n[i]}keyOf(e){return e==null?"":e instanceof jt.ObjectId||typeof e=="object"&&typeof e.toHexString=="function"?e.toHexString():String(e)}buildScalarRef(e){return{[this.pkField]:e}}getTargetPkField(e){return this.pkField}resolveOwnerFkKey(e){return e.localField||e.fkColumn||e.relationName}resolveInverseFkField(e){return e.foreignField?e.foreignField:e.mappedBy?e.mappedBy:e.relationName}resolveParentPk(e){return this.pkField}resolveFields(e,t){let{rootFields:n,subRelations:i}=He(e),o={},s=!1;if(n.includes("*")){s=!0;for(let f of t.relations||[])i.has(f.propertyName)||i.set(f.propertyName,["_id"])}else for(let f of n){let p=t.columns.find(h=>h.name===f);p?o[p.name]=1:t.relations?.find(g=>g.propertyName===f)&&!i.has(f)&&i.set(f,["_id"])}i.forEach((f,p)=>{let h=t.relations?.find(g=>g.propertyName===p);h&&(h.type==="many-to-one"||h.type==="one-to-one"&&!h.isInverse)&&(s||(o[z(h)||h.propertyName]=1))}),s||(o._id=1);let a=[];i.forEach((f,p)=>{let h=t.relations?.find(b=>b.propertyName===p);if(!h)return;let g=h.targetTableName||h.targetTable;if(!g)return;let m,y;h.type==="many-to-one"||h.type==="one-to-one"?Ie(h)?(m="_id",y=K(h)||h.propertyName):(m=z(h)||h.propertyName,y="_id"):h.type==="one-to-many"?(m="_id",y=K(h)||h.propertyName):h.type==="many-to-many"&&(h.isInverse?(m="_id",y=h.mappedBy):(m=h.propertyName,y="_id")),a.push({relationName:p,type:h.type,targetTable:g,fields:f,isInverse:h.isInverse,fkColumn:h.foreignKeyColumn,mappedBy:h.mappedBy,junctionTableName:h.junctionTableName,junctionSourceColumn:h.junctionSourceColumn,junctionTargetColumn:h.junctionTargetColumn,localField:m,foreignField:y})});let u=!s&&Object.keys(o).length===1&&o._id===1&&a.length===0,c=this.fieldRenamesByTable?.get(t.name)??[],d=[];if(!s&&c.length>0)for(let f of c)o[f.newName]===1&&o[f.oldName]!==1&&(o[f.oldName]=1,d.push(f.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:o,pendingRenames:c,hiddenFields:d}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?ge(this.normalizeMetadata(),i.userFilter,e):null,s=this.buildSortFromTokens(i?.userSort),a=await W(t,c=>{let d={_id:{$in:c}};o&&Object.keys(o).length>0&&Object.assign(d,o);let l={projection:n.projection};return s&&(l.sort=s),this.runQuery(()=>this.db.collection(e).find(d,l).toArray())}),u=this.applyReadFallback(a,n);return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(t),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,n,i,o){let s=i.projection?{...i.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let a=this.uniqueValues(n.map(y=>this.toObjectId(y))),u=o?.userFilter?ge(this.normalizeMetadata(),o.userFilter,e):null,c=o?.userLimit,d=o?.userPage,l=this.hasDottedSort(o?.userSort);if(c!==void 0&&c>0){let y=d?(d-1)*c:0;if(l)throw new Error(`Dotted sort is not supported for batch relation '${o?.relationName}'`);let b=this.buildStableSort(o?.userSort),$=await W(a,async C=>{let T={[t]:{$in:C}};u&&Object.keys(u).length>0&&Object.assign(T,u);let k=[{$match:T}];this.appendTopNStages(k,t,b,y,c),k.push({$sort:{[t]:1,...b}}),this.appendPartitionProjection(k,s,[t]);let _=await this.runQuery(()=>this.db.collection(e).aggregate(k).toArray());return this.applyReadFallback(_,i)});return{docs:$,groupKeyField:t,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:$.length}}}if(s&&(s[t]=1),l){let y=[],b=await _n(a,async $=>{let C={[t]:$};u&&Object.keys(u).length>0&&Object.assign(C,u);let T=this.buildSortAggregatePipeline(e,C,o.userSort);s&&T.push({$project:s});let k=await this.runQuery(()=>this.db.collection(e).aggregate(T).toArray());return this.applyReadFallback(k,i)},Me);for(let $ of b.values())for(let C of $)y.push(C);return{docs:y,groupKeyField:t,stats:{strategy:"per-parent-dotted-sort",roundtrips:a.length,concurrencyWaves:Math.ceil(a.length/Me),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:y.length}}}let f={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(f,u);let p=this.buildSortFromTokens(o?.userSort)||{_id:1},h={projection:s,sort:p},g=await W(a,y=>this.runQuery(()=>this.db.collection(e).find({[t]:{$in:y},...u||{}},h).toArray())),m=this.applyReadFallback(g,i);return{docs:m,groupKeyField:t,stats:{strategy:"batch-in",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.length}}}postProcessInverseChild(e,t,n){n||delete e[t]}m2mSortCanUseJunction(e){return this.parseSortTokens(e).every(t=>t.field==="_id")}async loadM2MTargets(e,t,n){if(t.length===0)return[];let i=n.projection?{projection:n.projection}:void 0,o=await W(t,s=>this.runQuery(()=>this.db.collection(e).find({_id:{$in:s}},i).toArray()));return this.applyReadFallback(o,n)}async fetchM2MTopK(e,t,n,i,o,s,a){if(this.hasDottedSort(t.userSort))throw new Error(`Dotted sort is not supported for batch relation '${t.relationName}'`);let u=new Map;for(let y of e)u.set(this.keyOf(y),[]);let c=i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1,d=!o&&this.m2mSortCanUseJunction(t.userSort),l=this.parseSortTokens(t.userSort).find(y=>y.field==="_id")?.order??1,f=this.buildStableSort(t.userSort),p=await W(e,async y=>{if(d){let C=[{$match:{[n.selfColumn]:{$in:y}}}];return this.appendTopNStages(C,n.selfColumn,{[n.otherColumn]:l},s,a),C.push({$sort:{[n.selfColumn]:1,[n.otherColumn]:l}},{$project:{_id:0,[se]:`$${n.selfColumn}`,[ke]:`$${n.otherColumn}`}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(C).toArray())).map(k=>({sourceId:k[se],targetId:k[ke]}))}let b=[{$match:{[n.selfColumn]:{$in:y}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ye}},{$unwind:`$${Ye}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ye}`,{[se]:`$${n.selfColumn}`,[ke]:`$${n.otherColumn}`}]}}}];return o&&Object.keys(o).length>0&&b.push({$match:o}),this.appendTopNStages(b,se,f,s,a),b.push({$sort:{[se]:1,...f}}),b.push({$project:{_id:0,[se]:1,[ke]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(b).toArray())).map(C=>({sourceId:C[se],targetId:C[ke]}))});if(c){let y=new Map;for(let b of p){let $=this.keyOf(b.targetId);y.has($)||y.set($,{_id:b.targetId}),u.get(this.keyOf(b.sourceId))?.push(y.get($))}return{grouped:u,docs:[],stats:{strategy:d?"m2m-junction-partitioned-top-k":"m2m-filtered-edge-top-k",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let h=this.uniqueValues(p.map(y=>y.targetId)),g=await this.loadM2MTargets(t.targetTable,h,i),m=new Map(g.map(y=>[this.keyOf(y._id),y]));for(let y of p){let b=m.get(this.keyOf(y.targetId));b&&u.get(this.keyOf(y.sourceId))?.push(b)}return{grouped:u,docs:g,stats:{strategy:"m2m-partitioned-edge-loader",roundtrips:this.chunkCount(e)+(h.length>0?this.chunkCount(h):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+g.length,rowsDiscarded:0}}}async fetchM2MEdgeBatch(e,t,n,i,o){let s=new Map;for(let g of e)s.set(this.keyOf(g),[]);let a=!o&&this.m2mSortCanUseJunction(t.userSort),u=this.parseSortTokens(t.userSort).find(g=>g.field==="_id")?.order??1,c=this.buildStableSort(t.userSort),d=await W(e,async g=>{if(a)return(await this.runQuery(()=>this.db.collection(n.junctionName).find({[n.selfColumn]:{$in:g}},{projection:{_id:0,[n.selfColumn]:1,[n.otherColumn]:1},sort:{[n.selfColumn]:1,[n.otherColumn]:u}}).toArray())).map($=>({sourceId:$[n.selfColumn],targetId:$[n.otherColumn]}));let m=[{$match:{[n.selfColumn]:{$in:g}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ye}},{$unwind:`$${Ye}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ye}`,{[se]:`$${n.selfColumn}`,[ke]:`$${n.otherColumn}`}]}}}];return o&&Object.keys(o).length>0&&m.push({$match:o}),m.push({$sort:{[se]:1,...c}},{$project:{_id:0,[se]:1,[ke]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(m).toArray())).map(b=>({sourceId:b[se],targetId:b[ke]}))});if(i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1){let g=new Map;for(let m of d){let y=this.keyOf(m.targetId);g.has(y)||g.set(y,{_id:m.targetId}),s.get(this.keyOf(m.sourceId))?.push(g.get(y))}return{grouped:s,docs:[],stats:{strategy:a?"m2m-junction-batch":"m2m-filtered-edge-batch",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length,rowsDiscarded:0}}}let f=this.uniqueValues(d.map(g=>g.targetId)),p=await this.loadM2MTargets(t.targetTable,f,i),h=new Map(p.map(g=>[this.keyOf(g._id),g]));for(let g of d){let m=h.get(this.keyOf(g.targetId));m&&s.get(this.keyOf(g.sourceId))?.push(m)}return{grouped:s,docs:p,stats:{strategy:"m2m-edge-loader",roundtrips:this.chunkCount(e)+(f.length>0?this.chunkCount(f):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length+p.length,rowsDiscarded:0}}}async fetchM2M(e,t,n,i,o){let s=n?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=Ne(s,{type:"many-to-many",propertyName:t.relationName,targetTable:t.targetTable,mappedBy:t.isInverse?t.mappedBy:void 0,junctionTableName:t.junctionTableName,junctionSourceColumn:t.junctionSourceColumn,junctionTargetColumn:t.junctionTargetColumn});if(!a)throw new Error(`Failed to resolve junction info for ${s}.${t.relationName}`);let u=this.uniqueValues(e.map(k=>k._id)),c=new Map;for(let k of e)c.set(this.keyOf(k._id),[]);if(u.length===0)return{grouped:c,docs:[]};let d=t.userFilter?ge(this.normalizeMetadata(),t.userFilter,t.targetTable):null,l=t.userLimit,f=t.userPage;if(l!==void 0&&l>0){let k=f?(f-1)*l:0;return this.fetchM2MTopK(u,t,a,o,d,k,l)}let p=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1&&!d,h=this.hasDottedSort(t.userSort);if(!h)return this.fetchM2MEdgeBatch(u,t,a,o,d);let g=await W(u,k=>this.runQuery(()=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:k}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray()));if(g.length===0)return{grouped:c,docs:[],stats:{strategy:"m2m-batch",roundtrips:this.chunkCount(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:0}};let m=new Set,y=[];for(let k of g){let _=k[a.otherColumn];if(_==null)continue;let F=this.keyOf(_);m.has(F)||(m.add(F),y.push(_))}let b=[],$=new Map;if(p)b=y.map(k=>({_id:k})),this.sortDocsByPk(b);else{let k={_id:{$in:y}};d&&Object.keys(d).length>0&&Object.assign(k,d);let _;if(h){let F=this.buildSortAggregatePipeline(t.targetTable,k,t.userSort);o.projection&&F.push({$project:o.projection}),_=await this.runQuery(()=>this.db.collection(t.targetTable).aggregate(F).toArray())}else{let F=this.buildSortFromTokens(t.userSort)||{_id:1},M=this.projectionWithSortFields(o.projection,t.userSort),B={sort:F};M.projection&&(B.projection=M.projection),_=await W(y,S=>this.runQuery(()=>this.db.collection(t.targetTable).find({_id:{$in:S},...d||{}},B).toArray())),t.userSort?this.sortDocsInMemory(_,t.userSort):this.sortDocsByPk(_),this.removeHiddenFields(_,M.hiddenFields)}b=this.applyReadFallback(_,o)}for(let k of b)$.set(this.keyOf(k._id),k);let C=new Map;for(let k of g){let _=this.keyOf(k[a.selfColumn]),F=this.keyOf(k[a.otherColumn]);$.has(F)&&(C.has(F)||C.set(F,[]),C.get(F).push(_))}for(let k of b){let _=C.get(this.keyOf(k._id))||[];for(let F of _)c.get(F)?.push(k)}let T=p||y.length===0?0:this.chunkCount(y);return{grouped:c,docs:b,stats:{strategy:p?"m2m-junction-batch":"m2m-batch",roundtrips:this.chunkCount(u)+T,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length+b.length}}}applyReadFallback(e,t){let n=t.pendingRenames??[];if(e.length===0||n.length===0)return e;let i=new Set(t.hiddenFields??[]);for(let o of e)for(let s of n)o[s.newName]===void 0&&o[s.oldName]!==void 0&&(o[s.newName]=o[s.oldName]),(i.has(s.oldName)||o[s.newName]!==void 0)&&delete o[s.oldName];return e}};async function wn(r,e,t,n,i=3,o=0,s,a,u,c){let d=await c?.getActiveFieldRenamesByTable?.(),l=new Xe(r,a,d);await new Se(l,n,u).execute(e,t,i,o,s)}async function Xn(r,e,t){let n=[],{db:i,metadata:o,dbType:s,debugLog:a}=t,u=o?.tables?.get(e.table),c=new Set((u?.relations??[]).map(S=>S.propertyName)),d=!!e.mongoRawFilter&&!!o&&ne(e.mongoRawFilter,c),l=e.plan,f=l?.filterTree&&!l.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&o&&d){let S=await Te(e.mongoRawFilter,e.table,o,i);S&&Object.keys(S).length>0&&n.push({$match:S})}else if(f){let S=ze(l.filterTree,{metadata:o,rootTable:e.table});Object.keys(S).length>0&&n.push({$match:S})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let S=Qe(o,e.where,e.table,s);n.push({$match:S})}let p=e.plan,g=p?p.hasRelationSort:e.sort?.some(S=>{if(!S.field.includes("."))return!1;let E=S.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(A=>A.propertyName===E)??!1})??!1,m=()=>p?.sortItems?$o(p.sortItems):e.sort?wo(e.sort):null,y=p?.sortItems?ho(p.sortItems):[],b=p?.sortItems?mo(p.sortItems):[],$=()=>{!p||y.length===0||yo(n,e.table,p.sortItems,o)},C=()=>{!p||b.length===0||bo(n,e.table,p.sortItems,o)},T=()=>{let S=[...y,...b];S.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(S.map(E=>[E,0]))})};if(!e.mongoFieldsExpanded){$(),C();let S=m();if(S&&n.push({$sort:S}),e.mongoCountOnly?n.push({$count:"count"}):(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit})),T(),e.select){let A={};for(let L of e.select)A[L]=1;n.push({$project:A})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let E=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:E,pipeline:n}:{results:Vr(E),pipeline:n}}let{scalarFields:k,relations:_}=e.mongoFieldsExpanded;if(!g){$(),C();let S=m();S&&n.push({$sort:S}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}let F=[];for(let S of _)if(e.sort?.some(A=>A.field.startsWith(`${S.propertyName}.`))){let A=e.mongoRawFilter?.[S.propertyName];if(S.nestedFields&&S.nestedFields.length>0){let w=await At(o,S.targetTable,S.nestedFields??[],A);S.type==="one"&&w.length>0&&w.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:w.length>0?w:void 0}})}else if(A){let w=await At(o,S.targetTable,["_id"],A);S.type==="one"&&w.length>0&&w.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:w.length>0?w:void 0}})}else n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName}});S.type==="one"&&(n.push({$unwind:{path:`$${S.propertyName}`,preserveNullAndEmptyArrays:!0}}),A&&(Ze(A)||n.push({$match:{[S.propertyName]:{$ne:null}}})))}else F.push(S);if(g){$(),C();let S=m();S&&n.push({$sort:S}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}T(),await Jr(o,n,e.table,k,[..._]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let M=performance.now(),B=await r.aggregate(n).toArray();if(e.debugTrace?.dur("db_execute",M,{table:e.table}),e.mongoCountOnly)return{results:B,pipeline:n};if(F.length>0&&B.length>0){let S=e.deep||{},E=F.map(L=>{let R=o?.tables?.get(e.table)?.relations?.find(N=>N.propertyName===L.propertyName),v=S[L.propertyName],ee=v?.fields!=null?Array.isArray(v.fields)?v.fields:String(v.fields).split(",").map(N=>N.trim()).filter(Boolean):L.nestedFields&&L.nestedFields.length>0?L.nestedFields:["_id"];return{relationName:L.propertyName,type:R?.type,targetTable:L.targetTable,fields:ee,isInverse:R?.isInverse,mappedBy:R?.mappedBy,junctionTableName:R?.junctionTableName,junctionSourceColumn:R?.junctionSourceColumn,junctionTargetColumn:R?.junctionTargetColumn,localField:L.localField,foreignField:L.foreignField,userFilter:v?.filter,userSort:v?.sort,userLimit:v?.limit!==void 0?Number(v.limit):void 0,userPage:v?.page!==void 0?Number(v.page):void 0,nestedDeep:v?.deep}}),A=_o(o);A&&await wn(i,B,E,A,3,0,e.table,o,e.debugTrace,t.mongoPhysicalMigrationService)}return{results:Vr(B),pipeline:n}}function Zn(r){return`__sort_count_${r.relationName||r.field}`}function er(r){return`__sort_${r.function}_${r.relationName||r.field}_${r.aggregateField||"value"}`}function ho(r){return r.filter(e=>e.function==="count").map(Zn)}function mo(r){return r.filter(e=>e.function==="max"||e.function==="min").map(er)}function yo(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="count")continue;let a=s.relationMeta,u=s.relationName||s.field,c=a?.targetTableName||a?.targetTable,d=Zn(s);if(!(!a||!c)){if(a.type==="one-to-many"){let l=K(a)||u;r.push({$lookup:{from:c,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${l}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let l=Ne(e,a);if(!l)continue;r.push({$lookup:{from:l.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${l.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}})}}}}function bo(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="max"&&s.function!=="min")continue;let a=s.relationMeta,u=s.relationName||s.field,c=a?.targetTableName||a?.targetTable,d=n?.tables?.get(c),l=d?.columns?.find(m=>m.isPrimary)?.name||(d?.columns?.some(m=>m.name==="_id")?"_id":"id"),f=s.aggregateField,p=f==="id"&&d?.columns?.some(m=>m.name==="_id")?"_id":f,h=er(s),g=s.function==="min"?"$min":"$max";if(!(!a||!c||!f)){if(a.type==="one-to-many"){let m=K(a)||u;r.push({$lookup:{from:c,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${m}`,"$$localId"]}}},{$group:{_id:null,value:{[g]:`$${p}`}}}],as:h}}),r.push({$addFields:{[h]:{$arrayElemAt:[`$${h}.value`,0]}}});continue}if(a.type==="many-to-many"){let m=Ne(e,a);if(!m)continue;let y=`${h}_junction`;r.push({$lookup:{from:m.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${m.selfColumn}`,"$$localId"]}}},{$project:{_id:0,targetId:`$${m.otherColumn}`}}],as:y}}),r.push({$lookup:{from:c,let:{targetIds:`$${y}.targetId`},pipeline:[{$match:{$expr:{$in:[`$${l}`,"$$targetIds"]}}},{$group:{_id:null,value:{[g]:`$${p}`}}}],as:h}}),r.push({$addFields:{[h]:{$arrayElemAt:[`$${h}.value`,0]}}}),r.push({$project:{[y]:0}})}}}}function _o(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(i=>({name:i.name,type:i.type})),relations:n.relations||[]}:null}:null}function wo(r){let e={};for(let t of r){let n=t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function $o(r){let e={};for(let t of r){let n=t.function==="count"?Zn(t):t.function==="max"||t.function==="min"?er(t):t.joinId!==null?t.fullPath:t.field;e[n]=t.direction==="asc"?1:-1}return e}function Ze(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ze(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ze(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ze(e));if("_not"in r)return Ze(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Ze(t)))return!0}return!1}function Vr(r){return r.map(Y)}function Hr(r,e){let t=[],n=[],i=e?.tables?.get(r.rootTable);if(!i)return{scalarFields:t,relations:n};for(let o of r.nodes)if(o.kind==="wildcard")for(let s of i.columns||[])t.includes(s.name)||t.push(s.name);else o.kind==="scalar"?i.columns?.some(a=>a.name===o.name)&&!t.includes(o.name)&&t.push(o.name):o.kind==="relation"&&n.push(To(o,i,e));return{scalarFields:t,relations:n}}function To(r,e,t){let n=e.relations?.find(c=>c.propertyName===r.propertyName),i,o,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&Ie(n)?(i="_id",o=K(n)||r.propertyName,s=!0):(i=n&&z(n)||r.propertyName,o="_id",s=!1):r.relationType==="one-to-many"?(i="_id",o=n&&K(n)||r.propertyName,s=!0):n?.mappedBy?(i="_id",o=n.mappedBy,s=!0):(i=r.propertyName,o="_id",s=!1);let a=r.relationType==="one-to-many"||r.relationType==="many-to-many",u=Gr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:i,foreignField:o,type:a?"many":"one",isInverse:s,nestedFields:u}}function Gr(r){let e=[];for(let t of r)if(t.kind==="wildcard")e.push("*");else if(t.kind==="scalar")e.push(t.name);else if(t.kind==="relation"){let n=Gr(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let i of n)e.push(`${t.propertyName}.${i}`)}return e}Je();Mt();Et();function $n(r,e,t,n){let i={rootTable:e,nodes:[]};if(!r||r.length===0)return i;let o=t?.tables?.get(e);if(!o)return i;let s=o.columns?.some(l=>l.name==="_id"&&l.isPrimary),a=o.columns?.some(l=>l.name==="id"),u=s&&!a?"_id":"id",c=new Map,d=[];for(let l of r){let f=l==="id"?u:l;if(f==="*")d.push("*");else if(f.includes(".")){let p=f.indexOf("."),h=f.substring(0,p),g=f.substring(p+1);if(!o.relations?.some(y=>y.propertyName===h))continue;c.has(h)||c.set(h,[]),c.get(h).push(g)}else if(o.relations?.some(h=>h.propertyName===f))c.has(f)||c.set(f,[u]);else{if(!o.columns?.some(g=>g.name===f))continue;d.push(f)}}if(d.includes("*")){i.nodes.push({kind:"wildcard"});for(let l of o.relations||[])c.has(l.propertyName)||c.set(l.propertyName,[u])}else for(let l of d)i.nodes.push({kind:"scalar",name:l});for(let[l,f]of c.entries()){let p=o.relations?.find(m=>m.propertyName===l);if(!p)continue;let h=p.targetTableName||p.targetTable,g={kind:"relation",propertyName:l,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:h,children:Yr(f,h,t)};if(p.type==="many-to-one"||p.type==="one-to-one"){let m=n.registerWithParent(e,l,t,"left",null,"data");g.joinId=m}i.nodes.push(g)}return i}function Yr(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let i=n.columns?.some(d=>d.name==="_id"&&d.isPrimary),o=n.columns?.some(d=>d.name==="id"),s=i&&!o?"_id":"id",a=new Map,u=[];for(let d of r){let l=d==="id"?s:d;if(l==="*")u.push("*");else if(l.includes(".")){let f=l.indexOf("."),p=l.substring(0,f),h=l.substring(f+1);if(!n.relations?.some(m=>m.propertyName===p))continue;a.has(p)||a.set(p,[]),a.get(p).push(h)}else if(n.relations?.some(p=>p.propertyName===l))a.has(l)||a.set(l,[s]);else{if(!n.columns?.some(h=>h.name===l))continue;u.push(l)}}let c=[];if(u.includes("*")){c.push({kind:"wildcard"});for(let d of n.relations||[])a.has(d.propertyName)||a.set(d.propertyName,[s])}else for(let d of u)c.push({kind:"scalar",name:d});for(let[d,l]of a.entries()){let f=n.relations?.find(h=>h.propertyName===d);if(!f)continue;let p=f.targetTableName||f.targetTable;c.push({kind:"relation",propertyName:d,joinId:null,relationType:f.type,isInverse:!!f.isInverse,targetTable:p,children:Yr(l,p,t)})}return c}de();de();var So=new Set(["_and","_or","_not"]);function Xr(r,e){return r?.tables?.get(e)??null}function Co(r,e,t){return Xr(r,e)?.columns?.find(n=>n.name===t)}function tr(r,e,t){return Xr(r,e)?.relations?.find(n=>n.propertyName===t)}function ko(r){let e=r.match(/^_(count|max|min)\(([^)]+)\)$/);if(!e)return null;let t=e[1],n=e[2].trim();if(t==="count")return{functionName:t,relationName:n};let i=n.indexOf(".");return i<=0||i!==n.lastIndexOf(".")?null:{functionName:t,relationName:n.slice(0,i).trim(),fieldName:n.slice(i+1).trim()}}function nr(r,e,t,n){if(Co(r,e,t)?.isEncrypted===!0)throw new I(`Encrypted field '${t}' on '${e}' cannot be used for ${n}.`)}function Oe(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){for(let n of r)Oe(n,e,t);return}for(let[n,i]of Object.entries(r)){if(So.has(n)){Oe(i,e,t);continue}if(n.startsWith("_"))continue;let o=tr(t,e,n);if(o){let s=o.targetTableName||o.targetTable;s&&Oe(i,s,t);continue}nr(t,e,n,"filter")}}}function Tn(r,e,t){if(!r)return;let n=Array.isArray(r)?r:r.split(",").map(i=>i.trim()).filter(Boolean);for(let i of n){let o=i.startsWith("-")?i.slice(1):i;if(!o)continue;let s=ko(o);if(s){if(s.functionName==="count")continue;let c=tr(t,e,s.relationName),d=c?.targetTableName||c?.targetTable;d&&nr(t,d,s.fieldName,"sort");continue}let a=o.split("."),u=e;for(let c=0;c<a.length;c++){let d=a[c];if(c===a.length-1){nr(t,u,d,"sort");break}let f=tr(t,u,d);if(!f)break;u=f.targetTableName||f.targetTable||u}}}var Z=class{plan(e){let{tableName:t,fields:n,filter:i,sort:o,page:s,limit:a,meta:u,metadata:c,dbType:d}=e,l=c?.tables?.get(t),f=new ie,p=this.parseFields(n),h=null;p&&l&&(h=$n(p,t,c,f));let g=!1,m=null;if(i&&l){Oe(i,t,c);let S=fe(i,t,c,f);m=S.node,g=S.hasRelationFilters}let y=this.parseSort(o);l&&Tn(y,t,c);let b=[],$=!1;for(let S of y){let E=S.startsWith("-"),A=E?S.substring(1):S,L=E?"desc":"asc";if(l){let w=this.parseRelationAggregateSort(t,l,A,c);if(w){b.push({joinId:null,field:A,direction:L,fullPath:A,function:w.functionName,relationName:w.relationName,aggregateField:w.aggregateField,relationMeta:w.relationMeta});continue}this.assertLocalSortField(t,l,A)}b.push({joinId:null,field:A,direction:L,fullPath:A})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let C=this.parseLimit(a),T=this.parsePage(s),k=T!==void 0&&C!==void 0?(T-1)*C:void 0,_=this.parseMeta(u),F=_.includes("totalCount")||_.includes("*"),M=_.includes("filterCount")||_.includes("*"),B=f.getAll();return{table:t,dbType:d,rawFields:p,rawFilter:i??null,joins:B,sortItems:b,limit:C,offset:k,needsTotalCount:F,needsFilterCount:M,hasRelationFilters:g,hasRelationSort:$,filterTree:m,fieldTree:h}}parseFields(e){if(e)return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):e.split(",").map(t=>t.trim()).filter(Boolean)}parseSort(e){return e?(Array.isArray(e)?e:e.split(",")).map(n=>n.trim()).filter(Boolean):[]}parseLimit(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;if(!Number.isNaN(t))return t<0?0:t}parsePage(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;return Number.isNaN(t)?void 0:t}parseMeta(e){return e?Array.isArray(e)?e:e.split(",").map(t=>t.trim()).filter(Boolean):[]}assertLocalSortField(e,t,n){if(n.includes("."))throw new I(`Sort field '${n}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let i=t.columns?.some(s=>s.name===n),o=n==="id"&&t.columns?.some(s=>s.name==="_id");if(!i&&!o)throw new I(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationAggregateSort(e,t,n,i){let o=n.match(/^_(count|max|min)\(([^)]+)\)$/);if(!o){if(/^_(count|max|min)\(/.test(n))throw new I(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName), _max(relationName.fieldName), or _min(relationName.fieldName).`);return null}let s=o[1],a=o[2].trim();if(s==="count"){let m=a;if(!m||m.includes("."))throw new I(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let y=t.relations?.find(b=>b.propertyName===m);if(!y)throw new I(`Sort relation '${m}' does not exist on '${e}'.`);if(y.type!=="one-to-many"&&y.type!=="many-to-many")throw new I(`Sort function '_count(${m})' is only supported for list relations on '${e}'.`);return{functionName:s,relationName:m,relationMeta:y}}let u=a.indexOf(".");if(u<=0||u!==a.lastIndexOf("."))throw new I(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let c=a.slice(0,u).trim(),d=a.slice(u+1).trim();if(!c||!d)throw new I(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let l=t.relations?.find(m=>m.propertyName===c);if(!l)throw new I(`Sort relation '${c}' does not exist on '${e}'.`);if(l.type!=="one-to-many"&&l.type!=="many-to-many")throw new I(`Sort function '_${s}(${c}.${d})' is only supported for list relations on '${e}'.`);let f=l.targetTableName||l.targetTable,p=i?.tables?.get(f);if(!p)throw new I(`Sort function '${n}' references unknown target table '${f}' on '${e}'.`);let h=p.columns?.find(m=>m.name===d),g=d==="id"&&p.columns?.some(m=>m.name==="_id");if(!h&&!g)throw new I(`Sort field '${d}' does not exist on '${f}' for function '_${s}(${c}.${d})'.`);if(h?.isEncrypted===!0)throw new I(`Encrypted field '${d}' on '${f}' cannot be used for sort.`);return{functionName:s,relationName:c,aggregateField:d,relationMeta:l}}registerSortJoinChain(e,t,n,i,o){let s=e.indexOf(".");if(s===-1)return null;let a=e.slice(0,s),u=e.slice(s+1),c=n?.tables?.get(t);if(!c)return null;let d=c.relations?.find(p=>p.propertyName===a);if(!d||d.type!=="many-to-one"&&d.type!=="one-to-one")return null;let l=i.registerWithParent(t,a,n,"left",o,"sort");if(!l)return null;if(!u.includes("."))return{lastJoinId:l,field:u};let f=d.targetTableName||d.targetTable;return this.registerSortJoinChain(u,f,n,i,l)}};de();var Ro=new Set(["int","integer","bigint","smallint","tinyint","float","double","decimal","numeric","real","number"]),Fo=new Set(["date","datetime","timestamp","timestamptz","timestamp with time zone","timestamp without time zone"]),vo=new Set(["hour","day","week","month","year"]),xo=new Set(["count","countDistinct","sum","avg","min","max"]);function O(r,e){throw new I(e,{path:r})}function et(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Io(r,e){let t=r?.tables?.get(e);return t||O("aggregate",`Table "${e}" metadata is not available`),t}function Zr(r,e,t){let n=r.columns?.find(i=>i.name===e);return n||O(t,`Unknown aggregate field "${e}"`),n.isEncrypted===!0&&O(t,`Encrypted field "${e}" cannot be used in aggregate queries`),n}function No(r,e){let t=r===void 0?"UTC":r;(typeof t!="string"||t.length===0)&&O(e,"Aggregate timezone must be a non-empty IANA timezone");try{new Intl.DateTimeFormat("en-US",{timeZone:t}).format()}catch{O(e,`Invalid aggregate timezone "${t}"`)}return t}function Eo(r,e){return r==null?{}:(et(r)||O(e,"Aggregate filter must be an object"),r)}function tt(r,e,t){et(r)||O("aggregate","Aggregate options must be an object");let n=Io(t,e),i=r.dimensions===void 0?[]:r.dimensions,o=r.measures;Array.isArray(i)||O("aggregate.dimensions","Aggregate dimensions must be an array"),(!et(o)||Object.keys(o).length===0)&&O("aggregate.measures","Aggregate requires at least one measure");let s=new Set,a=i.map((g,m)=>{let y=`aggregate.dimensions[${m}]`;(!et(g)||typeof g.field!="string"||g.field.length===0)&&O(y,"Aggregate dimension requires a field");let b=Zr(n,g.field,`${y}.field`);return s.has(g.field)&&O(`${y}.field`,`Duplicate aggregate dimension "${g.field}"`),s.add(g.field),g.bucket===void 0?(g.timezone!==void 0&&O(`${y}.timezone`,"Aggregate timezone requires a bucket"),{field:g.field,outputKey:g.field,column:b}):((typeof g.bucket!="string"||!vo.has(g.bucket))&&O(`${y}.bucket`,"Aggregate bucket must be hour, day, week, month, or year"),Fo.has(String(b.type).toLowerCase())||O(`${y}.bucket`,`Aggregate bucket requires a date field, but "${g.field}" is "${b.type}"`),{field:g.field,outputKey:g.field,bucket:g.bucket,timezone:No(g.timezone,`${y}.timezone`),column:b})}),u=new Set,c=Object.entries(o).map(([g,m])=>{let y=`aggregate.measures.${g}`;(!g||!et(m))&&O(y,"Aggregate measure must be an object");let b=Object.entries(m).filter(([k])=>k!=="as");b.length!==1&&O(y,"Aggregate measure must define exactly one operation");let[$,C]=b[0];xo.has($)||O(y,`Unsupported aggregate measure "${$}"`),(typeof C!="string"||C.length===0)&&O(y,"Aggregate measure field must be a non-empty string");let T=Zr(n,C,`${y}.${$}`);return(u.has(g)||s.has(g))&&O(y,`Aggregate output key "${g}" is duplicated`),u.add(g),["sum","avg","min","max"].includes($)&&!Ro.has(String(T.type).toLowerCase())&&O(y,`Aggregate ${$} requires a numeric field, but "${C}" is "${T.type}"`),{outputKey:g,operation:$,field:C,column:T}}),d=r.sort===void 0?[]:r.sort;Array.isArray(d)||O("aggregate.sort","Aggregate sort must be an array");let l=new Set([...s,...u]),f=d.map((g,m)=>{let y=`aggregate.sort[${m}]`;return(!et(g)||typeof g.field!="string"||!l.has(g.field))&&O(y,"Aggregate sort field must reference a dimension or measure output"),g.direction!=="asc"&&g.direction!=="desc"&&O(`${y}.direction`,"Aggregate sort direction must be asc or desc"),{field:g.field,direction:g.direction}}),p=r.limit===void 0?void 0:Number(r.limit),h=r.page===void 0?1:Number(r.page);return p!==void 0&&(!Number.isInteger(p)||p<=0||p>1e4)&&O("aggregate.limit","Aggregate limit must be an integer between 1 and 10000"),(!Number.isInteger(h)||h<=0)&&O("aggregate.page","Aggregate page must be a positive integer"),{tableName:e,filter:Eo(r.filter,"aggregate.filter"),dimensions:a,measures:c,sort:f,page:h,limit:p}}var Ae=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.debugLog=[];this.lastBuiltPipeline=null;this.db=e.getDb()}async execute(e){if(this.metadata=e.metadata,this.dbType=e.dbType||"mongodb",!e.plan){let l=new Z;e={...e,plan:l.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:"mongodb"})}}let t=e.debugLog||[];this.debugLog=t;let n={table:e.tableName,metadata:e.metadata,debugTrace:e.debugTrace};if(e.pipeline&&(n.pipeline=e.pipeline),e.fields&&(Array.isArray(e.fields)?n.fields=e.fields:typeof e.fields=="string"&&(n.fields=e.fields.split(",").map(l=>l.trim()))),e.filter&&(re(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let l=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(f=>f.trim());n.sort=l.map(f=>{let p=f.trim();return p.startsWith("-")?{field:p.substring(1),direction:"desc"}:{field:p,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let l=typeof e.page=="string"?parseInt(e.page,10):e.page,f=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(l-1)*f,n.limit=f}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let i=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(l=>l.trim()).filter(Boolean),o=0,s=0;(i.includes("totalCount")||i.includes("*"))&&(o=await this.mongoService.collection(e.tableName).countDocuments({}));let a=this.metadata?.tables?.get(e.tableName),u=new Set((a?.relations??[]).map(l=>l.propertyName)),c=!!n.mongoRawFilter&&ne(n.mongoRawFilter,u);if((i.includes("filterCount")||i.includes("*"))&&!c){let l=this.mongoService.collection(e.tableName),f=e.plan?.filterTree?ze(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await l.countDocuments(f)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let d=await this.selectLegacy(n);if(e.debugMode){let l=this.lastBuiltPipeline??[],f;try{f=await this.db.collection(e.tableName).aggregate(l).explain()}catch(p){f={error:String(p)}}return{pipeline:l,explain:f}}if(c&&(i.includes("filterCount")||i.includes("*"))){let l={...n,mongoCountOnly:!0},f=await this.selectLegacy(l);s=f.length>0?f[0].count:0}return{data:d,...i.length>0&&{meta:{...i.includes("totalCount")||i.includes("*")?{totalCount:o}:{},...i.includes("filterCount")||i.includes("*")?{filterCount:s}:{}}}}}async aggregate(e){this.metadata=e.metadata,this.dbType=e.dbType||"mongodb";let t=tt(e.aggregate,e.tableName,e.metadata),n=this.db.collection(e.tableName),i=new Z().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:"mongodb"}),o=i.hasRelationFilters?await Te(t.filter,e.tableName,e.metadata,this.db):i.filterTree?ze(i.filterTree,{metadata:e.metadata,rootTable:e.tableName}):{},s=[];Object.keys(o).length>0&&s.push({$match:o});let a={_id:{}},u={};for(let d of t.dimensions){let l=`$${d.field}`,f=d.bucket?{$dateTrunc:{date:l,unit:d.bucket,timezone:d.timezone}}:l;a._id[d.outputKey]=f,u[d.outputKey]=`$_id.${d.outputKey}`}for(let d of t.measures){let l=`$${d.field}`;a[d.outputKey]=d.operation==="count"?{$sum:{$cond:[{$ne:[l,null]},1,0]}}:d.operation==="countDistinct"?{$addToSet:l}:{[`$${d.operation}`]:l},u[d.outputKey]=d.operation==="countDistinct"?{$size:{$setDifference:[`$${d.outputKey}`,[null]]}}:`$${d.outputKey}`}return s.push({$group:a},{$project:{_id:0,...u}}),t.sort.length>0&&s.push({$sort:Object.fromEntries(t.sort.map(d=>[d.field,d.direction==="asc"?1:-1]))}),t.limit!==void 0&&s.push({$skip:(t.page-1)*t.limit},{$limit:t.limit}),this.lastBuiltPipeline=s,e.debugMode?{pipeline:s,explain:await n.aggregate(s).explain()}:{data:(await n.aggregate(s).toArray()).map(Y)}}async selectLegacy(e){let t=[],n=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,i=this.metadata?.tables?.get(e.table),o=i?.relations&&i.relations.length>0;if(e.fields&&e.fields.length>0||n||o){let c=e.plan,d=e.fields&&e.fields.length>0?e.fields:["*"];if(e.fields&&e.fields.length>0&&c?.fieldTree){if(e.mongoFieldsExpanded=Hr(c.fieldTree,this.metadata),n){let l=await It(this.metadata,e.table,[],e.deep),f=new Set(e.mongoFieldsExpanded.relations.map(p=>p.propertyName));e.mongoFieldsExpanded.relations.push(...l.relations.filter(p=>!f.has(p.propertyName)))}}else console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await It(this.metadata,e.table,d,e.deep);if(this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let l=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:l.scalarFields},t=l.hiddenFields}}e.where&&(e.where=e.where.map(c=>c.field.includes(".")?c:{...c,field:`${e.table}.${c.field}`}));let s=this.db.collection(e.table);if(e.pipeline)return this.debugLog&&this.debugLog.push({type:"MongoDB Custom Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(e.pipeline))}),(await s.aggregate(e.pipeline).toArray()).map(Y);let{results:a,pipeline:u}=await Xn(s,e,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=u,this.mongoPhysicalMigrationService?await this.mongoPhysicalMigrationService.applyReadFallback(e.table,a,t):a}async executeAggregationPipeline(e,t){let{results:n,pipeline:i}=await Xn(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=i,n}};var Sn=class{constructor(e){this.context=e}log(e){console.log(this.format(e))}warn(e){console.warn(this.format(e))}error(e,t){console.error(this.format(e)),t&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}fatal(e,t){this.error(e,t)}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};de();ae();var Mo=["_and","_or","_not"];function he(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>he(e));for(let e of Object.keys(r))if(Mo.includes(e)||typeof r[e]=="object"&&r[e]!==null&&he(r[e]))return!0;return!1}var ei=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function Oo(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function Cn(r,e,t){if(!t)return!1;let n=r;if(r.includes(".")){let s=r.split(".");n=s[s.length-1]}let i=t.columns.find(s=>s.name===n);if(!i)return!1;let o=i.type?.toLowerCase()||"";return o==="uuid"||o==="uuidv4"||o.includes("uuid")}function Ao(r,e,t,n,i){return n!=="postgres"||typeof e!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||Cn(r,t,i),e}function ti(r,e,t,n,i,o,s){let a=i&&!e.includes(".")?`${i}.${e}`:e,u=Re(a,o??"postgres"),c=Cn(e,i,s),d=Ao(e,n,i,o,s);switch(t){case"_eq":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} = ?::uuid`,[n]):r.where(a,"=",d);break;case"_neq":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} != ?::uuid`,[n]):r.where(a,"!=",d);break;case"_gt":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} > ?::uuid`,[n]):r.where(a,">",d);break;case"_gte":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} >= ?::uuid`,[n]):r.where(a,">=",d);break;case"_lt":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} < ?::uuid`,[n]):r.where(a,"<",d);break;case"_lte":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} <= ?::uuid`,[n]):r.where(a,"<=",d);break;case"_in":let l=n;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(p=>p.trim()):[l]),c&&o==="postgres"&&l.every(p=>typeof p=="string")?r.whereRaw(`${u} = ANY(?::uuid[])`,[l]):r.whereIn(a,l);break;case"_not_in":case"_nin":let f=n;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]),c&&o==="postgres"&&f.every(p=>typeof p=="string")?r.whereRaw(`${u} != ALL(?::uuid[])`,[f]):r.whereNotIn(a,f);break;case"_contains":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_starts_with":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${u}) LIKE lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_ends_with":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?))`,[n]):o==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?)`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`,[n]);break;case"_between":Array.isArray(n)&&n.length===2&&r.whereBetween(a,[n[0],n[1]]);break;case"_is_null":n===!0?r.whereNull(a):r.whereNotNull(a);break;case"_is_not_null":n===!0?r.whereNotNull(a):r.whereNull(a);break;default:r.where(a,Oo(t),n)}}function Po(r,e,t){if(!t||!e||r.startsWith("_"))return!0;let n=r.includes(".")?r.split(".").pop():r,i=t.columns?.some(s=>s.name===n),o=t.relations?.some(s=>s.propertyName===n);return i||o}function nt(r,e,t,n="and",i,o){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let s of e)n==="and"?r.where(function(){nt(this,s,t,"and",i,o)}):r.orWhere(function(){nt(this,s,t,"and",i,o)});return}for(let[s,a]of Object.entries(e))if(Po(s,t,o)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){nt(this,u,t,"and",i,o)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){nt(this,u,t,"and",i,o)})});continue}if(s==="_not"){r.whereNot(function(){nt(this,a,t,"and",i,o)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(c=>ei.includes(c)))for(let[c,d]of Object.entries(a))ei.includes(c)&&(n==="and"?r.where(function(){ti(this,s,c,d,t,i,o)}):r.orWhere(function(){ti(this,s,c,d,t,i,o)}));else{let c=t&&!s.includes(".")?`${t}.${s}`:s,d=Re(c,i??"postgres");Cn(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${d} = ?::uuid`,[a]):r.orWhereRaw(`${d} = ?::uuid`,[a]):n==="and"?r.where(c,"=",a):r.orWhere(c,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s,c=Re(u,i??"postgres");Cn(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${c} = ?::uuid`,[a]):r.orWhereRaw(`${c} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function le(r,e,t,n,i){return!e||typeof e!="object"||nt(r,e,t,"and",n,i),r}ae();function or(r,e,t){return`${x(r,t)}.${x(e,t)}`}function Fe(r,e){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function ni(r,e){if(!e)return!1;let t=e.columns.find(i=>i.name===r);if(!t)return!1;let n=t.type?.toLowerCase()||"";return n==="uuid"||n==="uuidv4"||n.includes("uuid")}function rt(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function sr(r,e,t,n,i,o){let s=[];for(let[a,u]of Object.entries(o)){let c=await Bt(r,e,a,u,t,n,i);if(c!==null)s.push(`EXISTS (${c})`);else{let d=t.relations.find(l=>l.propertyName===a);if(d&&d.foreignKeyColumn){let l=or(e,d.foreignKeyColumn,n),p=u.id;if(p&&typeof p=="object"){let h=rt(p._is_null),g=rt(p._is_not_null);if(h===!0)s.push(`${l} IS NULL`);else if(h===!1)s.push(`${l} IS NOT NULL`);else if(g===!0)s.push(`${l} IS NOT NULL`);else if(g===!1)s.push(`${l} IS NULL`);else if(p._eq!==void 0){let m=Fe(p._eq,n);s.push(`${l} = ${m}`)}else if(p._neq!==void 0){let m=Fe(p._neq,n);s.push(`${l} != ${m}`)}else if(p._in!==void 0){let y=(Array.isArray(p._in)?p._in:[p._in]).map(b=>Fe(b,n)).join(", ");s.push(`${l} IN (${y})`)}else if(p._not_in!==void 0||p._nin!==void 0){let m=p._not_in??p._nin,b=(Array.isArray(m)?m:[m]).map($=>Fe($,n)).join(", ");s.push(`${l} NOT IN (${b})`)}else if(p._gt!==void 0){let m=Fe(p._gt,n);s.push(`${l} > ${m}`)}else if(p._gte!==void 0){let m=Fe(p._gte,n);s.push(`${l} >= ${m}`)}else if(p._lt!==void 0){let m=Fe(p._lt,n);s.push(`${l} < ${m}`)}else if(p._lte!==void 0){let m=Fe(p._lte,n);s.push(`${l} <= ${m}`)}}}}}return s}function ar(r){return!r||typeof r!="object"||Array.isArray(r)?!1:!!(r._and&&Array.isArray(r._and)||r._or&&Array.isArray(r._or)||r._not!==void 0&&r._not!==null)}async function rr(r,e,t,n,i,o){let s=[];for(let a of r)if(a._and&&Array.isArray(a._and)&&a._and.length>0){let u=[];for(let c of a._and)if(ar(c)){let d=e(t).select(`${t}.id`);await Pe(e,d,c,t,n,i,o),u.push({idSubquery:d})}else{let{fieldFilters:d,relationFilters:l}=V(c,n),f=await sr(e,t,n,i,o,l);u.push({fieldFilters:d,subqueries:f})}s.push(u)}else if(ar(a)){let u=e(t).select(`${t}.id`);await Pe(e,u,a,t,n,i,o),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:c}=V(a,n),d=await sr(e,t,n,i,o,c);s.push([{fieldFilters:u,subqueries:d}])}return s}function ri(r,e,t,n,i){if("idSubquery"in e&&e.idSubquery){r.whereIn(`${t}.id`,e.idSubquery);return}let o=e;Object.keys(o.fieldFilters).length===0&&o.subqueries.length===0||r.where(function(){Object.keys(o.fieldFilters).length>0&&le(this,o.fieldFilters,t,i,n);for(let s of o.subqueries)this.whereRaw(s)})}function ir(r,e,t,n,i){let o=!0;for(let s of e){let a=function(){for(let u of s)ri(this,u,t,n,i)};o?(r.where(a),o=!1):r.orWhere(a)}}function kn(r,e,t,n,i,o,s){let a=ni(e,i),u=ni(n,o),c=`${x(r,s)}.${x(e,s)}`,d=`${x(t,s)}.${x(n,s)}`;if(s==="postgres"){if(a&&!u)return`${c} = ${d}::uuid`;if(!a&&u)return`${c}::uuid = ${d}`}return`${c} = ${d}`}async function Bt(r,e,t,n,i,o,s){let a=i.relations.find(f=>f.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${e}"`);let u=a.targetTableName||a.targetTable;if(!u)throw new Error(`Relation "${t}" in table "${e}" is missing targetTable/targetTableName. Relation metadata: ${JSON.stringify(a,null,2)}`);let c=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn){let f=Object.keys(n||{});if(f.length===1&&f[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(h=>c.has(h)))return null}let d=s?await s(u):null,l;switch(a.type){case"one-to-many":l=r(u).select(r.raw("1")).whereRaw(kn(u,a.foreignKeyColumn,e,"id",d,i,o));break;case"many-to-many":let f=s?await s(a.junctionTableName):null;l=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw(kn(a.junctionTableName,a.junctionTargetColumn,u,"id",f,d,o))).whereRaw(kn(a.junctionTableName,a.junctionSourceColumn,e,"id",f,i,o));break;case"many-to-one":case"one-to-one":l=r(u).select(r.raw("1")).whereRaw(kn(u,"id",e,a.foreignKeyColumn,d,i,o));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?d?await Pe(r,l,n,u,d,o,s):l=le(l,n,u,o,d||void 0):l=le(l,n,u,o),l.toString()}async function Pe(r,e,t,n,i,o,s){if(!t||typeof t!="object")return;if(t._and&&Array.isArray(t._and)){for(let c of t._and)if(c._or&&Array.isArray(c._or)&&c._or.length>0){let d=await rr(c._or,r,n,i,o,s);e.where(function(){ir(this,d,n,i,o)})}else if(c._and&&Array.isArray(c._and)&&c._and.length>0)for(let d of c._and)await Pe(r,e,d,n,i,o,s);else await Pe(r,e,c,n,i,o,s);return}if(t._or&&Array.isArray(t._or)){let c=await rr(t._or,r,n,i,o,s);e.where(function(){ir(this,c,n,i,o)});return}if(t._not){let c=t._not;if(c._and&&Array.isArray(c._and)&&c._and.length>0){let f=[];for(let p of c._and)if(ar(p)){let h=r(n).select(`${n}.id`);await Pe(r,h,p,n,i,o,s),f.push({idSubquery:h})}else{let{fieldFilters:h,relationFilters:g}=V(p,i),m=await sr(r,n,i,o,s,g);f.push({fieldFilters:h,subqueries:m})}e.whereNot(function(){for(let p of f)ri(this,p,n,i,o)});return}if(c._or&&Array.isArray(c._or)&&c._or.length>0){let f=await rr(c._or,r,n,i,o,s);e.whereNot(function(){ir(this,f,n,i,o)});return}let{fieldFilters:d,relationFilters:l}=V(c,i);e.whereNot(function(){Object.keys(d).length>0&&le(this,d,n,o,i)});for(let[f,p]of Object.entries(l)){let h=await Bt(r,n,f,p,i,o,s);if(h===null){let g=i.relations.find(m=>m.propertyName===f);if(g&&g.foreignKeyColumn){let m=or(n,g.foreignKeyColumn,o),b=p.id;if(b&&typeof b=="object"){let $=rt(b._is_null),C=rt(b._is_not_null);if($===!0)e.whereRaw(`${m} IS NOT NULL`);else if($===!1)e.whereRaw(`${m} IS NULL`);else if(C===!0)e.whereRaw(`${m} IS NULL`);else if(C===!1)e.whereRaw(`${m} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${m} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${m} = ?`,[b._neq]);else if(b._in!==void 0){let T=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${m} NOT IN (${T.map(()=>"?").join(", ")})`,T)}else if(b._not_in!==void 0||b._nin!==void 0){let T=b._not_in??b._nin,k=Array.isArray(T)?T:[T];e.whereRaw(`${m} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${h})`)}return}let{fieldFilters:a,relationFilters:u}=V(t,i);Object.keys(a).length>0&&le(e,a,n,o,i);for(let[c,d]of Object.entries(u)){let l=await Bt(r,n,c,d,i,o,s);if(l===null){let f=i.relations.find(p=>p.propertyName===c);if(f&&f.foreignKeyColumn){let p=or(n,f.foreignKeyColumn,o),g=d.id;if(g&&typeof g=="object"){let m=rt(g._is_null),y=rt(g._is_not_null);if(m===!0)e.whereRaw(`${p} IS NULL`);else if(m===!1)e.whereRaw(`${p} IS NOT NULL`);else if(y===!0)e.whereRaw(`${p} IS NOT NULL`);else if(y===!1)e.whereRaw(`${p} IS NULL`);else if(g._eq!==void 0)e.whereRaw(`${p} = ?`,[g._eq]);else if(g._neq!==void 0)e.whereRaw(`${p} != ?`,[g._neq]);else if(g._in!==void 0){let b=Array.isArray(g._in)?g._in:[g._in];e.whereRaw(`${p} IN (${b.map(()=>"?").join(", ")})`,b)}else if(g._not_in!==void 0||g._nin!==void 0){let b=g._not_in??g._nin,$=Array.isArray(b)?b:[b];e.whereRaw(`${p} NOT IN (${$.map(()=>"?").join(", ")})`,$)}}}}else e.whereRaw(`EXISTS (${l})`)}}async function Lt(r,e,t,n,i,o,s){await Pe(r,e,t,n,i,o,s)}ae();ae();function it(r,e,t,n,i){for(let o of e){let s=o.field.split("."),a=t||s[0],u=s[s.length-1],c=Dt(n,a,u,o.value);switch(o.operator){case"=":r=r.where(o.field,"=",c);break;case"!=":r=r.where(o.field,"!=",c);break;case">":r=r.where(o.field,">",c);break;case"<":r=r.where(o.field,"<",c);break;case">=":r=r.where(o.field,">=",c);break;case"<=":r=r.where(o.field,"<=",c);break;case"like":r=r.where(o.field,"like",c);break;case"in":let d=Array.isArray(o.value)?o.value.map(g=>Dt(n,a,u,g)):[c];r=r.whereIn(o.field,d);break;case"not in":let l=Array.isArray(o.value)?o.value.map(g=>Dt(n,a,u,g)):[c];r=r.whereNotIn(o.field,l);break;case"is null":r=r.whereNull(o.field);break;case"is not null":r=r.whereNotNull(o.field);break;case"_contains":r=r.where(o.field,"like",`%${o.value}%`);break;case"_starts_with":r=r.where(o.field,"like",`${o.value}%`);break;case"_ends_with":r=r.where(o.field,"like",`%${o.value}`);break;case"_between":let f=o.value;if(typeof f=="string"&&(f=f.split(",").map(g=>g.trim())),Array.isArray(f)&&f.length===2){let g=Dt(n,a,u,f[0]),m=Dt(n,a,u,f[1]);r=r.whereBetween(o.field,[g,m])}break;case"_is_null":r=c===!0||c==="true"?r.whereNull(o.field):r.whereNotNull(o.field);break;case"_is_not_null":r=c===!0||c==="true"?r.whereNotNull(o.field):r.whereNull(o.field);break}}return r}function Wt(r,e,t,n){let i=[],o=t;if(!r||typeof r!="object")return i;for(let[s,a]of Object.entries(r))if(s==="_and"&&Array.isArray(a)){let u=a.map(c=>{let d=Wt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&i.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(c=>{let d=Wt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&i.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=Wt(a,e,t,n);u.length>0&&i.push(`NOT (${u.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[u,c]of Object.entries(a)){let d=`${x(e,n)}.${x(s,n)}`,l;if(c===null)l="NULL";else if(typeof c=="string"){let f=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,p=o.columns?.find(g=>g.name===s);p&&(p.type?.toLowerCase()==="uuid"||p.type?.toLowerCase().includes("uuid"))&&f.test(c)&&n==="postgres"?l=`'${c}'::uuid`:l=`'${c.replace(/'/g,"''")}'`}else typeof c=="boolean"?l=c?"true":"false":typeof c=="number"?l=String(c):l=`'${String(c).replace(/'/g,"''")}'`;if(u==="_eq")i.push(`${d} = ${l}`);else if(u==="_neq")i.push(`${d} != ${l}`);else if(u==="_gt")i.push(`${d} > ${l}`);else if(u==="_gte")i.push(`${d} >= ${l}`);else if(u==="_lt")i.push(`${d} < ${l}`);else if(u==="_lte")i.push(`${d} <= ${l}`);else if(u==="_is_null")i.push(`${d} IS NULL`);else if(u==="_is_not_null")i.push(`${d} IS NOT NULL`);else if(u==="_in"){let p=(Array.isArray(c)?c:[c]).map(h=>typeof h=="string"?`'${h.replace(/'/g,"''")}'`:String(h)).join(", ");i.push(`${d} IN (${p})`)}else if(u==="_not_in"||u==="_nin"){let p=(Array.isArray(c)?c:[c]).map(h=>typeof h=="string"?`'${h.replace(/'/g,"''")}'`:String(h)).join(", ");i.push(`${d} NOT IN (${p})`)}else if(u==="_contains"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${d}) LIKE '%${f.toLowerCase()}%'`)}else if(u==="_starts_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE lower(unaccent('${f}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${d}) LIKE '${f.toLowerCase()}%'`)}else if(u==="_ends_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}'))`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci)`):i.push(`lower(${d}) LIKE '%${f.toLowerCase()}'`)}else if(u==="_between"&&Array.isArray(c)&&c.length===2){let f=typeof c[0]=="string"?`'${c[0].replace(/'/g,"''")}'`:String(c[0]),p=typeof c[1]=="string"?`'${c[1].replace(/'/g,"''")}'`:String(c[1]);i.push(`${d} BETWEEN ${f} AND ${p}`)}}else{let u=`${x(e,n)}.${x(s,n)}`,c;a===null?c="NULL":typeof a=="string"?c=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?c=a?"true":"false":c=String(a),i.push(`${u} = ${c}`)}return i}function Kt(r){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Dt(r,e,t,n){if(n==null)return n;let i=r?.tables?.get(e);if(!i?.columns)return n;let o=i.columns.find(s=>s.name===t);if(!o)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;default:return n}}cr();Je();ae();qt();Ke();async function si(r,e,t,n,i,o,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(dr(),oi)),u=await a(e,t,n,i,o,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function fr(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(i=>({name:i.name,type:i.type})),relations:n.relations||[]}:null}:null}function ai(r,e,t,n,i){let o=r.targetTableName||r.targetTable;if(!o)return null;let s=r.foreignKeyColumn||J(r.propertyName);if(!s)return null;let a=l=>x(l,i),u=n?.tables?.get(o),d=(u?H(u):null)?.name||"id";return`(SELECT ${a(o)}.${a(e)} FROM ${a(o)} WHERE ${a(o)}.${a(d)} = ${a(t)}.${a(s)})`}qt();var je=class r{constructor(e,t,n,i){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=i;this.logger=new Sn(r.name);this.debugLog=[]}async execute(e){let t=performance.now();this.metadata=e.metadata;let n=e.debugLog||[];this.debugLog=n;let i=e.debugTrace;if(e.filter&&re(e.filter,e.tableName,e.metadata),!e.plan){let w=new Z;e={...e,plan:w.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:this.dbType})}}let o=e.plan,s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,u=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,c=o.rawFields&&o.rawFields.length>0&&!o.rawFields.includes("*");if(o.joins.length===0&&!o.hasRelationFilters&&!o.hasRelationSort&&!u&&!a&&c){i&&i.setQueryPath("simple");let w=await this.executeSimple(e,o);return i&&i.dur("sql_executor",t,{table:e.tableName}),w}let l={table:e.tableName,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?l.fields=e.fields:typeof e.fields=="string"&&(l.fields=e.fields.split(",").map(w=>w.trim())));let f=e.filter;if(e.filter&&!he(e.filter)){l.where=[];for(let[w,R]of Object.entries(e.filter))if(typeof R=="object"&&R!==null)for(let[v,ee]of Object.entries(R)){let N;if(v==="_eq")N="=";else if(v==="_neq")N="!=";else if(v==="_in")N="in";else if(v==="_not_in"||v==="_nin")N="not in";else if(v==="_gt")N=">";else if(v==="_gte")N=">=";else if(v==="_lt")N="<";else if(v==="_lte")N="<=";else if(v==="_contains")N="_contains";else if(v==="_starts_with")N="_starts_with";else if(v==="_ends_with")N="_ends_with";else if(v==="_between")N="_between";else if(v==="_is_null")N="_is_null";else if(v==="_is_not_null")N="_is_not_null";else if(v==="_like")N="like";else if(v==="_ilike")N="ilike";else continue;l.where.push({field:w,operator:N,value:ee})}else l.where.push({field:w,operator:"=",value:R})}if(e.sort){let w=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(R=>R.trim());l.sort=w.map(R=>{let v=R.trim();return v.startsWith("-")?{field:v.substring(1),direction:"desc"}:{field:v,direction:"asc"}})}else l.sort=[{field:"id",direction:"asc"}];let p=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,h=p===void 0||Number.isNaN(p)?void 0:p<0?0:p,g=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,m=g===void 0||Number.isNaN(g)?void 0:g;m&&h!==void 0?(l.offset=(m-1)*h,l.limit=h):h!==void 0&&(l.limit=h);let y=e.plan?.sortItems??(l.sort??[]).map(w=>({joinId:null,field:w.field,direction:w.direction,fullPath:w.field})),b=[],$=[];for(let w of y){if(w.function==="count"){let R={sql:this.buildRelationCountSortSubquery(l.table,w),direction:w.direction};$.push(R);continue}if(w.function==="max"||w.function==="min"){let R={sql:this.buildRelationAggregateSortSubquery(l.table,w),direction:w.direction};$.push(R);continue}if(w.joinId===null){if(w.field.includes(".")&&!e.plan){let v=w.field.split(".")[0];if(this.metadata?.tables?.get(l.table)?.relations?.some(U=>U.propertyName===v))continue}let R={field:w.field.includes(".")?w.field:`${l.table}.${w.field}`,direction:w.direction};b.push(R),$.push(R)}else{let R=e.plan?.joins.find(v=>v.id===w.joinId);if(R&&(R.relationType==="many-to-one"||R.relationType==="one-to-one")){let v=ai(R.relationMeta,w.field,l.table,this.metadata,this.dbType);if(v){let ee={sql:v,direction:w.direction};$.push(ee)}}}}let C=[];if(l.fields&&l.fields.length>0||u||a){let w=fr(this.metadata),R=l.fields&&l.fields.length>0?l.fields:["*"],v=await si(this.knex,l.table,R,w,this.dbType,this.maxQueryDepth,e.deep);v.select.length>0&&(l.select=[...l.select||[],...v.select]),C=v.batchFetchDescriptors||[]}l.where&&(l.where=l.where.map(w=>w.field.includes(".")?w:{...w,field:`${l.table}.${w.field}`})),l.sort=b;let T=this.knex(l.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(w=>w.trim()).filter(Boolean),_=k.includes("filterCount")||k.includes("*"),F=k.includes("totalCount")||k.includes("*");if(l.select){let w=l.select.map(R=>typeof R=="string"&&R.trim().startsWith("(")?this.knex.raw(R):typeof R=="string"&&/ as /i.test(R)?this.knex.raw(R):R);T=T.select(w)}if(_&&T.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),F){let w=x(l.table,this.dbType);T.select(this.knex.raw(`(SELECT COUNT(*) FROM ${w}) as __total_count__`))}let M=["table_definition","column_definition","relation_definition","method_definition"].includes(l.table);if(f&&(he(f)||Object.keys(f).length>0)){let w=this.metadata?.tables?.get(l.table);(!M&&w&&w.relations&&w.relations.length>0?V(f,w).hasRelations:!1)?await Lt(this.knex,T,f,l.table,w,this.dbType,v=>this.metadata?.tables?.get(v)):e.plan?.filterTree?ce(T,e.plan.filterTree,{dbType:this.dbType,rootTable:l.table}):(this.logger.debug(`buildWhereClause fallback for table=${l.table}`),T=le(T,f,l.table,this.dbType,w))}else l.where&&l.where.length>0&&(T=it(T,l.where,l.table,this.metadata,this.dbType));for(let w of $)if(w.field){let R=w.field.includes(".")?w.field:`${l.table}.${w.field}`;T=T.orderBy(R,w.direction)}else w.sql&&(T=T.orderByRaw(`${w.sql} ${w.direction.toUpperCase()}`));l.groupBy&&(T=T.groupBy(l.groupBy)),l.offset&&(T=T.offset(l.offset)),l.limit!==void 0&&l.limit!==null&&l.limit>0&&(T=T.limit(l.limit));let B=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:l.table,sql:T.toSQL().toNative()});let S;if(e.debugMode&&(S=T.toSQL().toNative().sql),e.debugMode&&i){let w=T.toSQL().toNative();i.setSql(w.sql);try{let R=w.sql.replace(/\$\d+/g,"?"),v=await this.knex.raw(`EXPLAIN ${R}`,w.bindings);i.setExplain(this.dbType==="postgres"?v.rows:v[0])}catch(R){i.setExplain({error:String(R)})}}let E,A=performance.now();E=await T,i&&i.dur("db_execute",A,{table:e.tableName});let L=0;if(_&&E.length>0&&(L=Number(E[0].__filter_count__||0),E.forEach(w=>{delete w.__filter_count__})),F&&E.length>0&&E[0].__total_count__!==void 0&&(B=Number(E[0].__total_count__||0),E.forEach(w=>{delete w.__total_count__})),C&&C.length>0&&E.length>0){let w=fr(this.metadata);if(w){let{executeBatchFetches:R}=await Promise.resolve().then(()=>(hr(),li));await R(this.knex,E,C,w,this.maxQueryDepth??3,0,l.table,this.dbType,this.metadata,i)}}if(this.knexService){let w=performance.now();E=await this.knexService.parseResult(E,l.table),i&&i.dur("db_parseResult",w,{table:e.tableName})}else{let w=(R,v)=>{if(!R||!this.metadata)return R;let ee=this.metadata.tables?.get(v);if(!ee)return R;if(Array.isArray(R))return R.map(U=>w(U,v));if(typeof R!="object"||Buffer.isBuffer(R))return R;let N={...R};for(let U of ee.columns)if(U.type==="simple-json"&&N[U.name]&&typeof N[U.name]=="string")try{N[U.name]=JSON.parse(N[U.name])}catch{}for(let[U,G]of Object.entries(N))if(G&&typeof G=="object"&&!Array.isArray(G)&&!Buffer.isBuffer(G)){let En=G;if(En.id!==void 0||En.createdAt!==void 0){let lt=ee.relations?.find(ct=>ct.propertyName===U);lt&&(N[U]=w(G,lt.targetTableName))}}else if(Array.isArray(G)&&G.length>0&&typeof G[0]=="object"&&G[0].id!==void 0){let lt=ee.relations?.find(ct=>ct.propertyName===U);lt&&(N[U]=G.map(ct=>w(ct,lt.targetTableName)))}return N};E=w(E,l.table)}return i&&(i.setQueryPath("full"),i.dur("sql_executor",t,{table:e.tableName})),{data:E,...k.length>0&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:B}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:L}:{}}},...S!==void 0&&{sql:S}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=H(s)?.name||"id",u=x(e,this.dbType),c=x(a,this.dbType);if(!n||!o)throw new I(`Sort relation '${i}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let d=n.foreignKeyColumn||n.mappedBy;if(!d)throw new I(`Sort function '_count(${i})' cannot resolve relation key on '${e}'.`);let l=x(o,this.dbType),f=x(d,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}if(n.type==="many-to-many"){let d=this.resolveManyToManyContract(n,i,e),l=x(d.tableName,this.dbType),f=x(d.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}throw new I(`Sort function '_count(${i})' is only supported for list relations on '${e}'.`)}buildRelationAggregateSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=t.aggregateField,s=n?.targetTableName||n?.targetTable,a=this.metadata?.tables?.get(e),u=this.metadata?.tables?.get(s),c=H(a)?.name||"id",d=H(u)?.name||"id",l=x(e,this.dbType),f=x(c,this.dbType),p=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!p||!n||!s||!o)throw new I(`Sort function '${t.field}' is not supported on '${e}'.`);let h=x(s,this.dbType),g=x(o,this.dbType);if(n.type==="one-to-many"){let m=n.foreignKeyColumn||n.mappedBy;if(!m)throw new I(`Sort function '_${t.function}(${i}.${o})' cannot resolve relation key on '${e}'.`);let y=x(m,this.dbType);return`(SELECT ${p}(${h}.${g}) FROM ${h} WHERE ${h}.${y} = ${l}.${f})`}if(n.type==="many-to-many"){let m=this.resolveManyToManyContract(n,i,e),y=x(m.tableName,this.dbType),b=x(m.sourceColumn,this.dbType),$=x(m.targetColumn,this.dbType),C=x(d,this.dbType);return`(SELECT ${p}(${h}.${g}) FROM ${y} JOIN ${h} ON ${h}.${C} = ${y}.${$} WHERE ${y}.${b} = ${l}.${f})`}throw new I(`Sort function '_${t.function}(${i}.${o})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,n){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new I(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async executeSimple(e,t){let n=e.tableName,i=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],o=this.knex(n).select(i);t.filterTree&&ce(o,t.filterTree,{dbType:this.dbType,rootTable:n});for(let g of t.sortItems){let m=g.field.includes(".")?g.field:`${n}.${g.field}`;o=o.orderBy(m,g.direction)}t.limit!==void 0&&t.limit!==null&&t.limit>0&&(o=o.limit(t.limit)),t.offset!==void 0&&(o=o.offset(t.offset));let s=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(g=>g.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),u=s.includes("totalCount")||s.includes("*");if(a&&o.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),u){let g=x(n,this.dbType);o.select(this.knex.raw(`(SELECT COUNT(*) FROM ${g}) as __total_count__`))}let c=e.debugTrace,d;if(e.debugMode){let g=o.toSQL().toNative();if(d=g.sql,c){c.setSql(g.sql);try{let m=g.sql.replace(/\$\d+/g,"?"),y=await this.knex.raw(`EXPLAIN ${m}`,g.bindings);c.setExplain(this.dbType==="postgres"?y.rows:y[0])}catch(m){c.setExplain({error:String(m)})}}}let l=performance.now(),f;f=await o,c&&c.dur("db_execute",l,{table:n}),this.knexService&&(f=await this.knexService.parseResult(f,n));let p=0,h=0;return a&&f.length>0&&(p=Number(f[0].__filter_count__||0),f.forEach(g=>delete g.__filter_count__)),u&&f.length>0&&(h=Number(f[0].__total_count__||0),f.forEach(g=>delete g.__total_count__)),{data:f,...s.length>0&&{meta:{...u?{totalCount:h}:{},...a?{filterCount:p}:{}}},...d!==void 0&&{sql:d}}}async aggregate(e){let t=tt(e.aggregate,e.tableName,e.metadata),n=this.knex(e.tableName),i=x(e.tableName,this.dbType),o=[],s=[];for(let l of t.dimensions){let f=`${i}.${x(l.field,this.dbType)}`,p=l.bucket?this.buildSqlBucketExpression(f,l.bucket,l.timezone,l.column.type):f;s.push(this.knex.raw(`${p} as ${x(l.outputKey,this.dbType)}`)),o.push(p)}for(let l of t.measures){let f=`${i}.${x(l.field,this.dbType)}`,p=l.operation==="count"?`COUNT(${f})`:l.operation==="countDistinct"?`COUNT(DISTINCT ${f})`:`${l.operation.toUpperCase()}(${f})`;s.push(this.knex.raw(`${p} as ${x(l.outputKey,this.dbType)}`))}let u=new Z().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:this.dbType});u.hasRelationFilters?await Lt(this.knex,n,t.filter,e.tableName,e.metadata?.tables?.get(e.tableName),this.dbType,l=>e.metadata?.tables?.get(l)):u.filterTree&&ce(n,u.filterTree,{dbType:this.dbType,rootTable:e.tableName}),n.select(s),o.length>0&&n.groupByRaw(o.join(", "));for(let l of t.sort)n.orderByRaw(`${x(l.field,this.dbType)} ${l.direction.toUpperCase()}`);return t.limit!==void 0&&n.limit(t.limit).offset((t.page-1)*t.limit),{data:(await n).map(l=>{let f={...l};for(let p of t.measures){let h=f[p.outputKey];h!=null&&typeof h=="string"&&/^-?\d+(\.\d+)?$/.test(h)&&(f[p.outputKey]=Number(h))}return f})}}buildSqlBucketExpression(e,t,n,i){let o=Kt(n);if(this.dbType==="postgres"){let s=`(${e} AT TIME ZONE ${o})`;return`DATE_TRUNC(${Kt(t)}, ${s})`}if(this.dbType==="mysql"){let s=`CONVERT_TZ(${e}, '+00:00', ${o})`;return t==="year"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-01-01'), '%Y-%m-%d')`:t==="month"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-01'), '%Y-%m-%d')`:t==="week"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%u-1'), '%Y-%u-%d')`:t==="day"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-%d'), '%Y-%m-%d')`:`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-%d %H:00:00'), '%Y-%m-%d %H:%i:%s')`}throw new I(`Aggregate time bucket is not supported on ${this.dbType}`)}};var vn=require("mongodb"),at=class{constructor(e){this.debugLog=[];this.batchInserts={items:[],flushing:!1};this.knexService=e.knexService,this.mongoService=e.mongoService,this.databaseConfigService=e.databaseConfigService,this.runtimeMetricsCollectorService=e.runtimeMetricsCollectorService,this.lazyRef=e.lazyRef,this.dbType=this.databaseConfigService.getDbType(),this.batchInsertMaxSize=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_SIZE",100),this.batchInsertMaxWaitMs=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_WAIT_MS",100),this.batchInsertConcurrency=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_CONCURRENCY",5),this.batchInsertTraceFile=process.env.QUERY_BUILDER_BATCH_TRACE_FILE||process.env.DYNAMIC_CREATE_BATCH_TRACE_FILE,this.batchInsertTraceFile&&(0,xn.mkdirSync)((0,ci.dirname)(this.batchInsertTraceFile),{recursive:!0})}async runWithPolicy(e,t){return this.knexService?this.knexService.runWithPolicy(e,t):this.mongoService?this.mongoService.runWithPolicy(e,t):t()}async runWithFieldPermissionCheck(e,t){return this.knexService?this.knexService.runWithFieldPermissionCheck(e,t):this.mongoService?this.mongoService.runWithFieldPermissionCheck(e,t):t()}async runWithTelemetryContext(e,t){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.runWithQueryContext(e,t):await t()}getDbType(){return this.dbType}safeObjectId(e){if(!vn.ObjectId)return e;if(typeof e=="string")try{return new vn.ObjectId(e)}catch{return e}return e}async getMetadataForQuery(){let e={tables:new Map,tablesList:[]},t=this.lazyRef.metadataCacheService;return t?t.isLoaded?.()?await t.getMetadata?.()??e:t.getDirectMetadata?.()??e:e}async buildMongoFilter(e,t){let n=await this.getMetadataForQuery(),i=Qe(n,e,t,this.dbType);return i._id!==void 0&&(i._id=this.safeObjectId(i._id)),i}async applyWhereToKnex(e,t,n){let i=await this.getMetadataForQuery();return{query:it(e,t,n??"",i,this.dbType)}}async runMongoMutationInSaga(e){return!this.mongoService?.runInSaga||this.mongoService.isInSaga?.()?e():(await this.mongoService.runInSaga(e)).data}async insertWithOptions(e){if(e.batch)return await this.insertManyBatch(e.table,e.data);if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{if(Array.isArray(e.data)){let t=[];for(let n of e.data){let i=await this.mongoService.insertOne(e.table,n);t.push(Y(i))}return t}return this.mongoService.insertOne(e.table,e.data)});if(Array.isArray(e.data)){let t=[];for(let n of e.data){let i=await this.knexService.insertWithCascade(e.table,n);t.push(i)}return t}else return await this.knexService.insertWithCascade(e.table,e.data)}async select(e){let t=performance.now(),n=await this.getMetadataForQuery(),i=performance.now(),s=new Z().plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:n,dbType:this.dbType}),a=e.debugTrace;if(a&&(a.dur("qb_planner",i,{table:e.tableName}),a.setPlan(this.sanitizePlan(s))),this.dbType==="mongodb"){let l=await new Ae(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}let c=await new je(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:n,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),c}sanitizePlan(e){return{rawFields:e.rawFields,hasRelationFilters:e.hasRelationFilters,hasRelationSort:e.hasRelationSort,joins:e.joins?.length??0,sortItems:e.sortItems,limit:e.limit,offset:e.offset,page:e.page,isSimpleQuery:e.joins?.length===0&&!e.hasRelationFilters&&!e.hasRelationSort}}async updateWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),s=this.mongoService.collection(e.table),a=this.mongoService.ioSignalPublic?.()??{},u=await s.find(o,a).toArray(),c=[];for(let d of u){let l=await this.mongoService.updateOne(e.table,d._id,e.data);c.push(l)}return c});let t=this.knexService.getKnex(),n=t(e.table);e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n;for(let o of i)await this.knexService.updateWithCascade(e.table,o.id,e.data);if(e.returning){let o=t(e.table);return e.where.length>0&&await this.applyWhereToKnex(o,e.where,e.table),await o.select(e.returning)}return{affected:i.length}}async deleteWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let i=await this.buildMongoFilter(e.where,e.table),o=this.mongoService.collection(e.table),s=this.mongoService.ioSignalPublic?.()??{},a=await o.find(i,s).toArray(),u=0;for(let c of a)await this.mongoService.deleteOne(e.table,c._id)&&u++;return u});let n=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table)),await n.delete()}async count(e){if(this.dbType==="mongodb"){let o=e.where?await this.buildMongoFilter(e.where,e.table):{};return this.mongoService.count(e.table,o)}let n=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n.count("* as count").first();return Number(i?.count||0)}whereToFilter(e){let t={},n=this.databaseConfigService.isMongoDb();for(let[i,o]of Object.entries(e))i==="id"||i==="_id"?n?t._id=this.normalizeWhereFilterValue("_id",o):t.id=this.normalizeWhereFilterValue("id",o):t[i]=this.normalizeWhereFilterValue(i,o);return t}normalizeWhereFilterValue(e,t){return this.isFilterOperatorObject(t)?this.databaseConfigService.isMongoDb()&&e==="_id"?this.normalizeMongoIdOperatorValue(t):t:{_eq:this.databaseConfigService.isMongoDb()&&e==="_id"?this.safeObjectId(t):t}}isFilterOperatorObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof vn.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[n,i]of Object.entries(e))t[n]=Array.isArray(i)?i.map(o=>this.safeObjectId(o)):this.safeObjectId(i);return t}filterToWhere(e){let t=[];for(let[n,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let o=Object.entries(i)[0];if(o){let[s,a]=o,u=this.mapFilterOperatorToSql(s);t.push({field:n,operator:u,value:a})}}return t}mapFilterOperatorToSql(e){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"like",_starts_with:"like",_ends_with:"like",_is_null:"is null",_is_not_null:"is not null"}[e]||"="}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,maxQueryDepth:e.maxQueryDepth})})}async aggregate(e){return this.trackQueryMetric("aggregate",e.table,async()=>{let t=await this.getMetadataForQuery();return this.dbType==="mongodb"?new Ae(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).aggregate({tableName:e.table,aggregate:e.aggregate,metadata:t,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,dbType:this.dbType}):new je(this.knexService.getKnex(),this.dbType,this.knexService).aggregate({tableName:e.table,aggregate:e.aggregate,metadata:t,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t,n){return n?.batch?await this.insertManyBatch(e,t):this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let a=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return Y(a)}let i=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),s=i||t.id;return await o(e).where("id",s).first()})}async insertMany(e,t){return t.length===0?[]:this.trackQueryMetric("insert_many",e,async()=>this.dbType==="mongodb"?(await this.runMongoMutationInSaga(async()=>typeof this.mongoService.insertManyWithCascade=="function"?this.mongoService.insertManyWithCascade(e,t):Promise.all(t.map(i=>this.mongoService.insertOne(e,i))))).map(i=>Y(i)):this.knexService.insertManyWithCascade(e,t))}async flushBatchInserts(){for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)await this.flushBatchInsertBuffer()}async insertManyBatch(e,t){let n=Array.isArray(t)?t:[t];for(let i of n)this.batchInserts.items.push({table:e,data:i});return this.traceBatchInsert("enqueue",{tableName:e,count:n.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i)),{accepted:!0,batch:!0,count:n.length}}async flushBatchInsertBuffer(){if(this.batchInserts.flushing){await this.batchInserts.flushPromise;return}let e=this.batchInserts.items.splice(0,this.batchInserts.items.length);if(this.batchInserts.timer&&(clearTimeout(this.batchInserts.timer),this.batchInserts.timer=void 0),e.length===0)return;this.batchInserts.flushing=!0;let t=this.executeBatchInsertFlush(e);this.batchInserts.flushPromise=t,await t}async executeBatchInsertFlush(e){let t=Date.now();try{let n=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...n.entries()].map(([i,o])=>({tableName:i,count:o.length}))}),await this.runLimited([...n.entries()],([i,o])=>this.flushBatchInsertTable(i,o)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}finally{this.batchInserts.flushing=!1,this.batchInserts.flushPromise=void 0,this.batchInserts.items.length>0&&(this.batchInserts.timer&&clearTimeout(this.batchInserts.timer),this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(n=>this.logBatchInsertError("QueryBuilder batch insert flush failed",n))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let n=Date.now();await this.runBatchInsertWithIsolation(e,t),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-n})}async runBatchInsertWithIsolation(e,t){if(t.length!==0)try{await(async()=>{if(this.dbType==="mongodb"){await this.runMongoMutationInSaga(async()=>{if(typeof this.mongoService?.insertManyWithCascade=="function"){await this.mongoService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.mongoService.insertOne(e,i.data)))});return}if(typeof this.knexService?.insertManyWithCascade=="function"){await this.knexService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.knexService.insertWithCascade(e,i.data)))})()}catch(n){if(t.length===1){this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,n);return}let i=Math.ceil(t.length/2);await Promise.all([this.runBatchInsertWithIsolation(e,t.slice(0,i)),this.runBatchInsertWithIsolation(e,t.slice(i))])}}groupBatchInsertsByTable(e){let t=new Map;for(let n of e){let i=t.get(n.table);i?i.push(n):t.set(n.table,[n])}return t}async runLimited(e,t){let n=0,i=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;n<e.length;){let o=e[n++];await t(o)}});await Promise.all(i)}readPositiveEnv(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.trunc(n):t}traceBatchInsert(e,t){this.batchInsertTraceFile&&(0,xn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
|
|
53
|
-
`)}logBatchInsertError(e,t){let n=t?.message||String(t);this.traceBatchInsert("error",{message:e,error:n,code:t?.code,detail:t?.detail}),console.error(`${e}: ${n}`)}async update(e,t,n){return this.trackQueryMetric("update",e,async()=>{if(t&&typeof t=="object"&&"where"in t)return await this.updateWithOptions({table:e,where:t.where,data:n});if(this.dbType==="mongodb"){let o=await this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n));return Y(o)}return await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first()})}async updateMany(e,t,n,i=this.getPkField()){return t.length===0?0:this.trackQueryMetric("update_many",e,async()=>{if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let a=this.mongoService.collection(e),u=this.mongoService.ioSignalPublic?.()??{};return(await a.updateMany({[i]:{$in:t}},{$set:n},u)).modifiedCount});let s=await this.knexService.getKnex()(e).whereIn(i,t).update(n);return typeof s=="number"?s:0})}async delete(e,t){return this.trackQueryMetric("delete",e,async()=>t&&typeof t=="object"&&"where"in t?await this.deleteWithOptions({table:e,where:t.where})>0:this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t)):await this.knexService.getKnex()(e).where("id",t).delete()>0)}async deleteMany(e,t,n=this.getPkField()){return t.length===0?0:this.trackQueryMetric("delete_many",e,async()=>{if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let s=this.mongoService.collection(e),a=this.mongoService.ioSignalPublic?.()??{},u=await s.find({[n]:{$in:t}},a).toArray(),c=0;for(let d of u)await this.mongoService.deleteOne(e,d._id)&&c++;return c});let o=await this.knexService.getKnex()(e).whereIn(n,t).delete();return typeof o=="number"?o:0})}async countRecords(e,t){if(this.dbType==="mongodb")return this.mongoService.count(e,t||{});let i=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.filterToWhere(t);({query:i}=await this.applyWhereToKnex(i,s,e))}let o=await i.count("* as count").first();return Number(o?.count||0)}async transaction(e){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>e(this.mongoService)):this.knexService.transaction(e)}async findById(e,t){if(this.dbType==="mongodb"){let i=this.safeObjectId(t);return this.mongoService.findOne(e,{_id:i})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[o,s]of Object.entries(t))o==="id"||o==="_id"?i._id=this.safeObjectId(s):i[o]=s;return this.mongoService.findOne(e,i)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[u,c]of Object.entries(t))u==="id"||u==="_id"?i._id=this.safeObjectId(c):i[u]=c;let o=this.mongoService.collection(e),s=this.mongoService.ioSignalPublic?.()??{};return await o.find(i,s).toArray()}return await this.knexService.getKnex()(e).where(t)}async insertAndGet(e,t){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));let n=await this.knexService.insertWithCascade(e,t),i=this.knexService.getKnex(),o=n||t.id;return await i(e).where("id",o).first()}async updateById(e,t,n){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n)):(await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first())}async deleteById(e,t){return this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t))?1:0:this.knexService.getKnex()(e).where("id",t).delete()}async raw(e,t){let n=this.dbType==="mongodb"?"mongodb":"sql";return this.trackQueryMetric("raw",n,async()=>{if(this.dbType==="mongodb"){let o=this.mongoService.getDb();if(typeof e=="string"){if(e.toLowerCase().includes("select 1"))return await o.command({ping:1});throw new Error("String queries not supported for MongoDB. Use db.command() object instead.")}return await o.command(e)}return await this.knexService.getKnex().raw(e,t)})}async trackQueryMetric(e,t,n){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.trackQuery({op:e,table:t},n):await n()}getConnection(){return this.dbType==="mongodb"?this.mongoService.getDb():this.knexService.getKnex()}getKnex(){if(this.dbType==="mongodb")throw new Error("getKnex() is not available for MongoDB. Use getConnection() or unified methods.");return this.knexService.getKnex()}getMongoDb(){if(this.dbType!=="mongodb")throw new Error("getMongoDb() is not available for SQL. Use getConnection() or unified methods.");return this.mongoService.getDb()}getDatabaseType(){return this.dbType}isMongoDb(){return this.dbType==="mongodb"}isSql(){return["mysql","postgres","mariadb","sqlite"].includes(this.dbType)}getPkField(){return this.isMongoDb()?"_id":"id"}getRecordId(e){return this.isMongoDb()?e._id:e.id}};hr();pr();dr();ae();qt();Ge();bn();de();Je();var ui=new Set(["fields","filter","sort","limit","page","deep"]),Nn=3;function mr(r,e,t,n=0,i=3){if(!e||typeof e!="object")return;if(n>=i)throw new I(`deep option exceeds maximum query depth of ${i}`);let o=t?.tables?.get(r),s=new Map((o?.relations??[]).map(a=>[a.propertyName,a]));for(let[a,u]of Object.entries(e)){let c=s.get(a);if(!c)throw new I(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let f of Object.keys(u))if(!ui.has(f))throw new I(`Unknown deep option key '${f}' for relation '${a}'. Allowed: ${[...ui].join(", ")}`);let d=c.type;if(u.limit!==void 0&&(d==="many-to-one"||d==="one-to-one"))throw new I(`'limit' not supported on many-to-one/one-to-one relations (relation '${a}' on '${r}')`);if(u.page!==void 0&&u.limit===void 0)throw new I(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let l=c.targetTableName||c.targetTable;if(l){if(u.filter&&(re(u.filter,l,t),Oe(u.filter,l,t),In(u.filter,0,a,r)),u.sort){Tn(u.sort,l,t);let f=Array.isArray(u.sort)?u.sort:String(u.sort).split(",").map(p=>p.trim()).filter(Boolean);for(let p of f){let h=p.startsWith("-")?p.slice(1):p;Do(h,l,t,a,r)}}u.deep&&mr(l,u.deep,t,n+1,i)}}}function Do(r,e,t,n,i){if(r.includes("."))throw new I(`Sort field '${r}' is not supported for relation '${n}' on '${i}'. Sort only by local fields defined on '${e}'.`);let o=t?.tables?.get(e);if(!o)throw new I(`Sort field '${r}' references unknown table '${e}' (relation '${n}' on '${i}')`);let s=o.columns?.some(u=>u.name===r),a=r==="id"&&o.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new I(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${i}')`)}var Wo=new Set(["_and","_or","_not"]);function In(r,e,t,n){if(!(!r||typeof r!="object"))for(let[i,o]of Object.entries(r)){if(Wo.has(i)){if(Array.isArray(o))for(let c of o)In(c,e,t,n);else o&&typeof o=="object"&&In(o,e,t,n);continue}if(i.startsWith("_")||!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).some(c=>!c.startsWith("_")))continue;let a=e+1;if(a>Nn)throw new I(`Filter path exceeds max dotted hops of ${Nn} at '${i}' (relation '${t}' on '${n}')`);let u={};for(let c of Object.keys(o))c.startsWith("_")||(u[c]=o[c]);In(u,a,t,n)}}function di(r,e,t,n){return!r||typeof r!="object"?r:Jt(r,e,t,n)}function Jt(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let o=r.map(s=>Jt(s,e,t,n)).filter(s=>s!=null);return o.length>0?o:null}let i={};for(let[o,s]of Object.entries(r)){if(o==="_and"||o==="_or"){let l=(Array.isArray(s)?s:[s]).map(f=>Jt(f,e,t,n)).filter(f=>f!=null&&Object.keys(f).length>0);l.length>0&&(i[o]=l);continue}if(o==="_not"){let d=Jt(s,e,t,n);d!=null&&Object.keys(d).length>0&&(i[o]=d);continue}let a=t?.tables?.get(e),u=a?.relations?.find(d=>d.propertyName===o);if(u){if(!n(e,o,"relation"))continue;let d=u.targetTableName||u.targetTable;if(!d)continue;let l=Jt(s,d,t,n);l!=null&&Object.keys(l).length>0&&(i[o]=l);continue}if(a?.columns?.find(d=>d.name===o)){if(!n(e,o,"column"))continue;i[o]=s;continue}i[o]=s}return i}function fi(r,e,t,n){if(!r)return r;let i=Array.isArray(r)?r:r.split(",").map(s=>s.trim()).filter(Boolean),o=[];for(let s of i){let c=(s.startsWith("-")?s.slice(1):s).split("."),d=!0,l=e;for(let f=0;f<c.length;f++){let p=c[f],h=f===c.length-1,g=t?.tables?.get(l);if(!g){d=!1;break}if(h)g.columns?.find(y=>y.name===p)?n(l,p,"column")||(d=!1):g.relations?.find(b=>b.propertyName===p)&&(n(l,p,"relation")||(d=!1));else{let m=g.relations?.find(y=>y.propertyName===p);if(!m){d=!1;break}if(!n(l,p,"relation")){d=!1;break}l=m.targetTableName||m.targetTable||l}}d&&o.push(s)}if(o.length!==0)return Array.isArray(r)?o:o.join(",")}Et();Je();Mt();cn();Ke();de();function Ko(r){let e=new at({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,i=()=>(t||(t=new We({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),o=()=>(n||(n=new Be({isolatedExecutorService:i()})),n);return{queryBuilderService:e,get isolatedExecutorService(){return i()},get executorEngineService(){return o()},async onDestroy(){await t?.onDestroy?.()}}}0&&(module.exports={ALL_SUPPORTED_OPERATORS,AuthenticationException,AuthorizationException,BadRequestException,BatchExecutionBudget,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,DEEP_TO_MANY_DEFAULT_LIMIT,DEFAULT_BATCH_FETCH_IO_CONCURRENCY,DEFAULT_TIMEOUT_MS,DOTTED_PATH_MAX_HOPS,DatabaseException,DuplicateResourceException,ErrorHandler,ExecutorEngineService,ExternalServiceException,FIELD_OPERATORS,FileNotFoundException,FileSizeExceededException,FileUploadException,HttpException,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH,InvalidTokenException,IsolatedExecutorService,JoinRegistry,LOGICAL_OPERATORS,MongoBatchAdapter,MongoQueryExecutor,PER_PARENT_CONCURRENCY,QueryBuilderService,QueryPlanner,ResourceNotFoundException,SchemaException,ScriptContractService,ScriptExecutionException,ScriptTimeoutException,ServiceUnavailableException,SqlBatchAdapter,SqlQueryExecutor,TokenExpiredException,ValidationException,WHERE_IN_CHUNK_SIZE,WorkerPool,appendIsolatedExecutorRuntimeLog,applyOperatorToMatch,applyRelationFilters,applyWhereToKnex,assertFieldOperatorValueIsClean,buildMongoCharFoldMapJson,buildMongoFoldTextSearchJs,buildRelationSubquery,buildSqlWherePartsFromFieldAst,buildWhereClause,camelToSnake,chunkedFetch,compileScriptSource,computeEngineTuning,createEnfyraKernel,dslOpToCompareOp,encodeMainThreadToIsolate,escapeSqlValue,executeBatchFetches,executeMongoBatchFetches,expandFieldsToJoinsAndSelect,getEffectiveCpuCount,getEffectiveMemoryBytes,getEngineTuning,getExecutableScript,getForeignKeyColumnName,getIoAbortSignal,getJunctionColumnNames,getJunctionTableName,getPrimaryKeyColumn,getScriptLegacyField,getShortFkConstraintName,getShortFkName,getShortIndexName,getShortPkName,hasLogicalOperators,isExecutableJavaScript,isScriptTable,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,perParentRun,quoteIdentifier,quoteQualifiedIdentifier,resolveExecutableScript,rewriteFilterDenyingFields,rewriteSortDroppingDenied,runWithIoAbortSignal,scriptContractService,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,validateDeepOptions,validateFilterShape,whereToMongoFilter});
|
|
52
|
+
}`}var jr="mongo-fold-text-search.body.txt",qe=null;function to(){let r=[Kn.join(__dirname,jr),Kn.join(process.cwd(),"dist","kernel","query","utils",jr)];for(let e of r)try{if(rn.existsSync(e))return rn.readFileSync(e,"utf8")}catch{}return null}function on(){if(qe!==null)return qe;let r=to();return r?(qe=r,qe):(qe=nn(),qe)}var _e=require("mongodb");function D(r,e,t,n){if(t==="_id"){if(n instanceof _e.ObjectId)return n;if(typeof n=="string")try{return new _e.ObjectId(n)}catch{return n}return n}let i=r?.tables?.get(e);if(!i){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new _e.ObjectId(n)}catch{return n}return n}if(!i.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new _e.ObjectId(n)}catch{return n}return n}let o=i.columns.find(s=>s.name===t);if(!o){if(i.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof n=="string"&&n.length===24)try{return new _e.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new _e.ObjectId(n)}catch{return n}return n}if(n==null)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;case"uuid":if(typeof n=="string")try{return new _e.ObjectId(n)}catch{return n}return n;default:return n}}var sn="__mongoFoldTextTriples";function no(r){return r==="_id"?"$_id":`$${r}`}function Ue(r,e,t,n){let i=no(e),o=r[sn]??[];o.push({ref:i,needle:t,mode:n}),r[sn]=o}function ro(r){let e=r[sn];if(delete r[sn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:on(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}function Qe(r,e,t,n){let i={},o=n==="mongodb"||!n;for(let s of e){let a=s.field.includes(".")?s.field.split(".").pop()??s.field:s.field,u=t||s.field.split(".")[0]||"";o&&a==="id"&&(a="_id");let c=D(r,u,a,s.value);switch(s.operator){case"=":i[a]=c;break;case"!=":i[a]={$ne:c};break;case">":i[a]={$gt:c};break;case"<":i[a]={$lt:c};break;case">=":i[a]={$gte:c};break;case"<=":i[a]={$lte:c};break;case"like":i[a]={$regex:c.replace(/%/g,".*"),$options:"i"};break;case"in":let d=s.value;Array.isArray(d)||(d=typeof d=="string"&&d.includes(",")?d.split(",").map(y=>y.trim()):[d]);let l=d.map(y=>D(r,u,a,y));i[a]={$in:l};break;case"not in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(y=>y.trim()):[f]);let p=f.map(y=>D(r,u,a,y));i[a]={$nin:p};break;case"is null":i[a]=null;break;case"is not null":i[a]={$ne:null};break;case"_contains":Ue(i,a,String(c),"contains");break;case"_starts_with":Ue(i,a,String(c),"starts");break;case"_ends_with":Ue(i,a,String(c),"ends");break;case"_between":let h=s.value;if(typeof h=="string"&&(h=h.split(",").map(y=>y.trim())),Array.isArray(h)&&h.length===2){let y=D(r,u,a,h[0]),b=D(r,u,a,h[1]);i[a]={$gte:y,$lte:b}}break;case"_is_null":let g=c===!0||c==="true";i[a]=g?{$eq:null}:{$ne:null};break;case"_is_not_null":let m=c===!0||c==="true";i[a]=m?{$ne:null}:{$eq:null};break}}return ro(i),i}function Br(r,e,t){let i=r?.tables?.get?.(e)?.columns?.find(o=>o.name===t);return i?i.isNullable!==!1:!0}function an(r,e,t,n,i,o){switch(i){case"_contains":Ue(e,n,String(o),"contains");break;case"_starts_with":Ue(e,n,String(o),"starts");break;case"_ends_with":Ue(e,n,String(o),"ends");break;case"_eq":e[n]=D(r,t,n,o);break;case"_neq":{let l=D(r,t,n,o);Br(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:l}})):e[n]={$ne:l};break}case"_in":{let l=o;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(p=>p.trim()):[l]);let f=l.map(p=>D(r,t,n,p));e[n]={$in:f};break}case"_not_in":case"_nin":let s=o;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(l=>l.trim()):[s]);let a=s.map(l=>D(r,t,n,l));Br(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$nin:a}})):e[n]={$nin:a};break;case"_gt":e[n]={$gt:D(r,t,n,o)};break;case"_gte":e[n]={$gte:D(r,t,n,o)};break;case"_lt":e[n]={$lt:D(r,t,n,o)};break;case"_lte":e[n]={$lte:D(r,t,n,o)};break;case"_is_null":let u=o===!0||o==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let c=o===!0||o==="true";e[n]=c?{$ne:null}:{$eq:null};break;case"_between":let d=o;if(typeof d=="string"&&(d=d.split(",").map(l=>l.trim())),Array.isArray(d)&&d.length===2){let l=D(r,t,n,d[0]),f=D(r,t,n,d[1]);e[n]={$gte:l,$lte:f}}break}}var Hn=require("mongodb");function ne(r,e){if(!r||typeof r!="object")return!1;for(let[t,n]of Object.entries(r))if(t==="_and"||t==="_or"){if(Array.isArray(n)){for(let i of n)if(ne(i,e))return!0}}else if(t==="_not"){if(ne(n,e))return!0}else if(e.has(t))return!0;return!1}function V(r,e){if(!r||typeof r!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},n={},i=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(r)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(i.has(s))if(typeof a=="object"&&a!==null){let u=Object.keys(a);if(u.some(d=>d.startsWith("_"))){let d=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&d.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let o=ne(r,i);return{fieldFilters:t,relationFilters:n,hasRelations:o}}Mt();Et();var fn="__mongoFoldTextTriples";function ze(r,e){if(!r)return{};let t={};return Ot(r,t,e),$e(t),t}function fo(r,e){if(!r)return{};let t={};return Qn(r,t,e),$e(t),t}function ge(r,e,t){if(!e)return{};let n=new ie,{node:i}=fe(e,t,r,n);return ze(i,{metadata:r,rootTable:t})}function pn(r,e,t){if(!e)return{};let n=new ie,{node:i}=fe(e,t,r,n);return fo(i,{metadata:r,rootTable:t})}function Ot(r,e,t){switch(r.kind){case"true":return;case"false":pe(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let i=r.children.map(o=>{let s={};return Ot(o,s,t),$e(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}pe(e,...i);return}case"or":{let i=r.children.map(s=>{let a={};return Ot(s,a,t),$e(a),a}).filter(s=>Object.keys(s).length>0);if(i.length===0)return;let o=e.$or;e.$or=o?[...o,...i]:i;return}case"not":{let n={};Ot(r.child,n,t),$e(n);let i=e.$nor;e.$nor=i?[...i,n]:[n];return}case"compare":qr(r,e,t);return;case"relation_exists":{console.warn(`[mongo-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${r.joinId}) \u2014 expected applyRelationFilters or null-only short-circuit to handle it. Filter silently skipped.`);return}}}function qr(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let i=o=>D(t.metadata,t.rootTable,n,o);switch(r.op){case"eq":X(e,n,i(r.value));return;case"neq":{let o=i(r.value);Jn(t,n)?pe(e,{[n]:{$ne:null}},{[n]:{$ne:o}}):X(e,n,{$ne:o});return}case"gt":X(e,n,{$gt:i(r.value)});return;case"gte":X(e,n,{$gte:i(r.value)});return;case"lt":X(e,n,{$lt:i(r.value)});return;case"lte":X(e,n,{$lte:i(r.value)});return;case"in":{let o=Kr(r.value).map(i);X(e,n,{$in:o});return}case"not_in":{let o=Kr(r.value).map(i);Jn(t,n)?pe(e,{[n]:{$ne:null}},{[n]:{$nin:o}}):X(e,n,{$nin:o});return}case"between":{let o=Array.isArray(r.value)?r.value:typeof r.value=="string"?r.value.split(",").map(s=>s.trim()):null;Array.isArray(o)&&o.length===2&&X(e,n,{$gte:i(o[0]),$lte:i(o[1])});return}case"is_null":X(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":Un(e,n,String(r.value),"contains");return;case"starts_with":Un(e,n,String(r.value),"starts");return;case"ends_with":Un(e,n,String(r.value),"ends");return}}function Qn(r,e,t){switch(r.kind){case"true":pe(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let i=r.children.map(s=>{let a={};return Qn(s,a,t),$e(a),a}).filter(s=>Object.keys(s).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}let o=e.$or;e.$or=o?[...o,...i]:i;return}case"or":{let i=r.children.map(o=>{let s={};return Qn(o,s,t),$e(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}pe(e,...i);return}case"not":Ot(r.child,e,t);return;case"compare":po(r,e,t);return;case"relation_exists":{X(e,r.joinId,r.negate?{$ne:null}:{$eq:null});return}}}function po(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached false renderer \u2014 expected relation resolver to handle it. Filter silently skipped.`);return}if(r.op==="is_null"){X(e,n,r.value===!0?{$ne:null}:{$eq:null});return}let i={};qr(r,i,t),$e(i);let o={$nor:[i]};Jn(t,n)?pe(e,o,{[n]:{$ne:null}}):pe(e,o)}function X(r,e,t){r[e]===void 0?r[e]=t:(pe(r,{[e]:r[e]},{[e]:t}),delete r[e])}function pe(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function Jn(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(i=>i.name===e);return n?n.isNullable!==!1:!0}function Kr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function go(r){return r==="_id"?"$_id":`$${r}`}function Un(r,e,t,n){let i=go(e),o=r[fn]??[];o.push({ref:i,needle:t,mode:n}),r[fn]=o}function $e(r){let e=r[fn];if(delete r[fn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:on(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}async function Te(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return ge(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!ne(r,o))return ge(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>Te(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._or&&Array.isArray(r._or)){let d=(await Promise.all(r._or.map(l=>Te(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:{$or:d}}if(r._not)return await Vn(r._not,e,t,n)||{};let{fieldFilters:s,relationFilters:a}=V(r,i),u=[];if(s&&Object.keys(s).length>0){let c=ge(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(a&&Object.keys(a).length>0)for(let[c,d]of Object.entries(a)){let l=await ho(c,d,e,i,t,n);l&&Object.keys(l).length>0&&u.push(l)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function Vn(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return pn(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!ne(r,o))return pn(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>Vn(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$or:d}}if(r._or&&Array.isArray(r._or)){let d=(await Promise.all(r._or.map(l=>Vn(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._not)return Te(r._not,e,t,n);let{fieldFilters:s,relationFilters:a}=V(r,i),u=[];if(s&&Object.keys(s).length>0){let c=pn(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(a&&Object.keys(a).length>0)for(let[c,d]of Object.entries(a)){let l=await yo(c,d,e,i,t,n);l&&Object.keys(l).length>0&&u.push(l)}return u.length===0?{}:u.length===1?u[0]:{$or:u}}async function ho(r,e,t,n,i,o){let s=(n.relations||[]).find(c=>c.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=i?.tables?.get(a);return!a||!u?{}:s.type==="many-to-one"||s.type==="one-to-one"?mo(e,s,r,a,u,i,o):s.type==="one-to-many"?Jr(e,s,t,a,u,i,o):s.type==="many-to-many"?zr(e,s,t,a,u,i,o):{}}async function mo(r,e,t,n,i,o,s){let a=z(e)||t,u=hn(r),c=mn(u);if(c!==null)return c?{[a]:null}:{[a]:{$ne:null}};let d=Gn(u);if(d!==null){let h=yn(d.value);if(d.op==="eq")return{[a]:h};if(d.op==="neq")return{[a]:{$ne:h}};if(d.op==="in")return{[a]:{$in:h}};if(d.op==="not_in")return{$and:[{[a]:{$nin:h}},{[a]:{$ne:null}}]}}let l=await gn(u,n,i,o,s);if(!l||Object.keys(l).length===0)return{};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(h=>h._id).filter(Boolean);return p.length===0?{__impossible__:!0}:{[a]:{$in:p}}}async function yo(r,e,t,n,i,o){let s=(n.relations||[]).find(c=>c.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=i?.tables?.get(a);if(!a||!u)return{};if(s.type==="many-to-one"||s.type==="one-to-one")return bo(e,s,r,a,u,i,o);if(s.type==="one-to-many"){let c=await Jr(e,s,t,a,u,i,o);return Qr(c)}if(s.type==="many-to-many"){let c=await zr(e,s,t,a,u,i,o);return Qr(c)}return{}}async function bo(r,e,t,n,i,o,s){let a=z(e)||t,u=hn(r),c=mn(u);if(c!==null)return c?{[a]:{$ne:null}}:{[a]:null};let d=Gn(u);if(d!==null){let h=yn(d.value);if(d.op==="eq")return{$and:[{[a]:{$ne:h}},{[a]:{$ne:null}}]};if(d.op==="neq")return{[a]:h};if(d.op==="in")return{$and:[{[a]:{$nin:h}},{[a]:{$ne:null}}]};if(d.op==="not_in")return{[a]:{$in:h}}}let l=await gn(u,n,i,o,s);if(!l||Object.keys(l).length===0)return{[a]:null};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(h=>h._id).filter(Boolean);return p.length===0?{[a]:{$ne:null}}:{$and:[{[a]:{$nin:p}},{[a]:{$ne:null}}]}}async function Jr(r,e,t,n,i,o,s){let a=K(e)||t,u=hn(r),c=mn(u);if(c!==null){let f=await Ur(s,n,a,{});return c?f.length===0?{}:{_id:{$nin:f}}:f.length===0?{__impossible__:!0}:{_id:{$in:f}}}let d=await gn(u,n,i,o,s);if(!d||Object.keys(d).length===0)return{};let l=await Ur(s,n,a,d);return l.length===0?{__impossible__:!0}:{_id:{$in:l}}}async function zr(r,e,t,n,i,o,s){let a=Ne(t,e);if(!a)return{};let u=hn(r),c=mn(u);if(c!==null){let g=await zn(s,a,n,null);return c?g.length===0?{}:{_id:{$nin:g}}:g.length===0?{__impossible__:!0}:{_id:{$in:g}}}let d=Gn(u);if(d!==null){let g=yn(d.value),m=Array.isArray(g)?g:[g],y=await zn(s,a,n,{_id:{$in:m}});return y.length===0?{__impossible__:!0}:{_id:{$in:y}}}let l=await gn(u,n,i,o,s);if(!l||Object.keys(l).length===0)return{};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);if(p.length===0)return{__impossible__:!0};let h=await zn(s,a,n,{_id:{$in:p}});return h.length===0?{__impossible__:!0}:{_id:{$in:h}}}async function gn(r,e,t,n,i){let o=new Set((t?.relations??[]).map(s=>s.propertyName));return ne(r,o)?Te(r,e,n,i):ge(n,r,e)}async function Ur(r,e,t,n){let i=await r.collection(e).find(n,{projection:{[t]:1}}).toArray(),o=new Set,s=[];for(let a of i){let u=a[t];if(u==null)continue;let c=String(u);o.has(c)||(o.add(c),s.push(u))}return s}function Qr(r){if(!r||Object.keys(r).length===0)return{};if(r.__impossible__===!0)return{};let e=r._id;if(e&&typeof e=="object"&&!Array.isArray(e)){if(Array.isArray(e.$in))return{_id:{$nin:e.$in}};if(Array.isArray(e.$nin))return{_id:{$in:e.$nin}}}return{$nor:[r]}}async function zn(r,e,t,n){let i=null;n&&t&&(i=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(d=>d._id).filter(Boolean));let o=i?{[e.otherColumn]:{$in:i}}:{},s=await r.collection(e.junctionName).find(o,{projection:{[e.selfColumn]:1}}).toArray(),a=new Set,u=[];for(let c of s){let d=c[e.selfColumn];if(d==null)continue;let l=String(d);a.has(l)||(a.add(l),u.push(d))}return u}function hn(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function mn(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0],n=r[t];return t==="_is_null"?n===!0:t==="_is_not_null"?n!==!0:t==="_eq"?n===null?!0:null:t==="_neq"&&n===null?!1:null}function yn(r){if(Array.isArray(r))return r.map(e=>yn(e));if(typeof r!="string")return r;try{return new Hn.ObjectId(r)}catch{return r}}function Gn(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof Hn.ObjectId)return{op:"eq",value:r};if(r==null)return null;if(typeof r!="object")return{op:"eq",value:r};if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0];return t==="_eq"?{op:"eq",value:r._eq}:t==="_neq"?{op:"neq",value:r._neq}:t==="_in"&&Array.isArray(r._in)?{op:"in",value:r._in}:t==="_not_in"&&Array.isArray(r._not_in)?{op:"not_in",value:r._not_in}:null}async function At(r,e,t,n){let i=await It(r,e,t),o=[],s={},a={};if(n&&typeof n=="object")for(let[p,h]of Object.entries(n))if(typeof h=="object"&&h!==null){let g=Object.keys(h)[0];g&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(g)?s[p]=h:a[p]=h}else s[p]=h;if(Object.keys(s).length>0){let p={};for(let[h,g]of Object.entries(s))if(typeof g=="object"&&g!==null)for(let[m,y]of Object.entries(g))an(r,p,e,h,m,y);else p[h]=g;Object.keys(p).length>0&&o.push({$match:p})}let c=r?.tables?.get(e)?.relations||[],d=[];for(let[p,h]of Object.entries(a))if(!i.relations.some(m=>m.propertyName===p)){let m=c.find(y=>y.propertyName===p);if(m){let y="",b="";if(m.type==="many-to-one"||m.type==="one-to-one")y=z(m)||m.propertyName,b="_id";else if(m.type==="one-to-many")y="_id",b=K(m)||m.propertyName;else if(m.type==="many-to-many")continue;let w=m.type==="one-to-many"||m.type==="many-to-many";d.push({propertyName:p,targetTable:m.targetTableName,localField:y,foreignField:b,type:w?"many":"one",nestedFields:[]})}}let l=[...i.relations,...d];for(let p of l){let h=a[p.propertyName],g=p.nestedFields&&p.nestedFields.length>0?await At(r,p.targetTable,p.nestedFields,h):h?await At(r,p.targetTable,["_id"],h):[];p.type==="one"&&g.length>0&&g.push({$limit:1}),o.push({$lookup:{from:p.targetTable,localField:p.localField,foreignField:p.foreignField,as:p.propertyName,pipeline:g.length>0?g:void 0}}),p.type==="one"&&(o.push({$unwind:{path:`$${p.propertyName}`,preserveNullAndEmptyArrays:!0}}),h&&(Ve(h)||o.push({$match:{[p.propertyName]:{$ne:null}}})))}let f=c.filter(p=>!l.some(h=>h.propertyName===p.propertyName));if(i.scalarFields.length>0||i.relations.length>0||f.length>0){let p={_id:1};for(let g of i.scalarFields)p[g]=1;for(let g of l)p[g.propertyName]=1,g.type==="one"&&g.localField&&g.localField!==g.propertyName&&(p[g.localField]=1);if(t.includes("*"))for(let g of f){if(g.type==="one-to-many"||g.type==="many-to-many")continue;g.type==="many-to-many"?p[g.propertyName]={$map:{input:`$${g.propertyName}`,as:"item",in:{_id:"$$item"}}}:p[g.propertyName]={$cond:{if:{$ne:[`$${g.propertyName}`,null]},then:{_id:`$${g.propertyName}`},else:null}}}o.push({$project:p})}return o}async function Vr(r,e,t,n,i){let o=r?.tables?.get(t),s=o?.relations||[],a=o?.columns||[],u=s.filter(d=>!i.some(l=>l.propertyName===d.propertyName)),c=n.length===a.length||n.length===0&&i.length===0;if(u.length>0||!c){let d={_id:1};for(let l of n)d[l]=1;for(let l of i)d[l.propertyName]=1,l.type==="one"&&l.localField&&l.localField!==l.propertyName&&(d[l.localField]=1);for(let l of u){if(l.type==="one-to-many"||l.type==="many-to-many")continue;l.type==="many-to-many"?d[l.propertyName]={$map:{input:`$${l.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[l.propertyName]={$cond:{if:{$ne:[`$${l.propertyName}`,null]},then:{_id:`$${l.propertyName}`},else:null}}}e.push({$project:d})}}function Ve(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ve(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ve(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ve(e));if("_not"in r)return Ve(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Ve(t)))return!0}return!1}Ge();var jt=require("mongodb");Ge();bn();async function _n(r,e,t){let n=new Map,i=0;async function o(){for(;i<r.length;){let u=i++,c=r[u];n.set(String(c),await e(c))}}let s=Math.min(t,r.length);if(s===0)return n;let a=Array.from({length:s},o);return await Promise.all(a),n}var se="__sourceId__",ke="__targetId__",Ye="__enfyra_target__",Pt="__enfyra_top_n_documents__",Xe=class{constructor(e,t,n,i=new Ce){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.executionBudget=i;this.pkField="_id"}chunkCount(e){return Math.ceil(e.length/oe)||1}runQuery(e){return this.executionBudget.run(e)}uniqueValues(e){return Array.from(new Map(e.filter(t=>t!=null).map(t=>[this.keyOf(t),t])).values())}buildStableSort(e,t="_id"){let n=this.buildSortFromTokens(e)||{};return n[t]===void 0&&(n[t]=1),n}appendPartitionProjection(e,t,n){if(t){let i={...t};for(let o of n)i[o]=1;e.push({$project:i})}}appendTopNStages(e,t,n,i,o){e.push({$group:{_id:`$${t}`,[Pt]:{$topN:{sortBy:n,output:"$$ROOT",n:i+o}}}},{$project:{[Pt]:{$slice:[`$${Pt}`,i,o]}}},{$unwind:`$${Pt}`},{$replaceRoot:{newRoot:`$${Pt}`}})}normalizeMetadata(){return this.metadata?this.metadata.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortFromTokens(e){let t={};for(let n of this.parseSortTokens(e)){let i=n.field.split(".");if(i.length===1)t[i[0]]=n.order;else{let o=`__sort_${i.slice(0,-1).join("_")}`;t[`${o}.${i[i.length-1]}`]=n.order}}return Object.keys(t).length>0?t:void 0}parseSortTokens(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).map(n=>{let i=n.startsWith("-"),o=i?n.slice(1):n;return{field:o==="id"?"_id":o,order:i?-1:1}}):[]}hasDottedSort(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).some(n=>(n.startsWith("-")?n.slice(1):n).includes(".")):!1}buildSortAggregatePipeline(e,t,n){let i=Array.isArray(n)?n:n.split(",").map(c=>c.trim()).filter(Boolean),o=[{$match:t}],s=new Set;for(let c of i){let l=(c.startsWith("-")?c.slice(1):c).split(".");if(l.length<=1)continue;let f=e;for(let p=0;p<l.length-1;p++){let h=l[p],g=this.normalizeMetadata()?.tables?.get(f);if(!g)break;let m=g.relations?.find(w=>w.propertyName===h);if(!m)break;let y=m.targetTableName||m.targetTable,b=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(b)){s.add(b);let w=z(m)||m.propertyName,C=p===0?null:`__sort_${l.slice(0,p).join("_")}`,T=C?`${C}.${w}`:w;o.push({$lookup:{from:y,localField:T,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}f=y}}let a=this.buildSortFromTokens(n);a&&o.push({$sort:a});let u={};for(let c of s)u[c]=0;return Object.keys(u).length>0&&o.push({$project:u}),o}toObjectId(e){try{return typeof e=="string"?new jt.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof jt.ObjectId||t instanceof jt.ObjectId?this.keyOf(e).localeCompare(this.keyOf(t)):typeof e=="number"&&typeof t=="number"?e-t:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="string"&&typeof t=="string"?e.localeCompare(t):e<t?-1:e>t?1:0}sortDocsInMemory(e,t){let n=this.parseSortTokens(t).filter(i=>!i.field.includes("."));n.length!==0&&e.sort((i,o)=>{for(let s of n){let a=this.compareSortValues(i[s.field],o[s.field]);if(a!==0)return a*s.order}return this.compareSortValues(i._id,o._id)})}sortDocsByPk(e){e.sort((t,n)=>this.compareSortValues(t._id,n._id))}projectionWithSortFields(e,t){if(!e)return{projection:e,hiddenFields:[]};let n={...e},i=[];for(let o of this.parseSortTokens(t))o.field.includes(".")||n[o.field]===void 0&&(n[o.field]=1,i.push(o.field));return{projection:n,hiddenFields:i}}removeHiddenFields(e,t){if(t.length!==0)for(let n of e)for(let i of t)delete n[i]}keyOf(e){return e==null?"":e instanceof jt.ObjectId||typeof e=="object"&&typeof e.toHexString=="function"?e.toHexString():String(e)}buildScalarRef(e){return{[this.pkField]:e}}getTargetPkField(e){return this.pkField}resolveOwnerFkKey(e){return e.localField||e.fkColumn||e.relationName}resolveInverseFkField(e){return e.foreignField?e.foreignField:e.mappedBy?e.mappedBy:e.relationName}resolveParentPk(e){return this.pkField}resolveFields(e,t){let{rootFields:n,subRelations:i}=He(e),o={},s=!1;if(n.includes("*")){s=!0;for(let f of t.relations||[])i.has(f.propertyName)||i.set(f.propertyName,["_id"])}else for(let f of n){let p=t.columns.find(h=>h.name===f);p?o[p.name]=1:t.relations?.find(g=>g.propertyName===f)&&!i.has(f)&&i.set(f,["_id"])}i.forEach((f,p)=>{let h=t.relations?.find(g=>g.propertyName===p);h&&(h.type==="many-to-one"||h.type==="one-to-one"&&!h.isInverse)&&(s||(o[z(h)||h.propertyName]=1))}),s||(o._id=1);let a=[];i.forEach((f,p)=>{let h=t.relations?.find(b=>b.propertyName===p);if(!h)return;let g=h.targetTableName||h.targetTable;if(!g)return;let m,y;h.type==="many-to-one"||h.type==="one-to-one"?Ie(h)?(m="_id",y=K(h)||h.propertyName):(m=z(h)||h.propertyName,y="_id"):h.type==="one-to-many"?(m="_id",y=K(h)||h.propertyName):h.type==="many-to-many"&&(h.isInverse?(m="_id",y=h.mappedBy):(m=h.propertyName,y="_id")),a.push({relationName:p,type:h.type,targetTable:g,fields:f,isInverse:h.isInverse,fkColumn:h.foreignKeyColumn,mappedBy:h.mappedBy,junctionTableName:h.junctionTableName,junctionSourceColumn:h.junctionSourceColumn,junctionTargetColumn:h.junctionTargetColumn,localField:m,foreignField:y})});let u=!s&&Object.keys(o).length===1&&o._id===1&&a.length===0,c=this.fieldRenamesByTable?.get(t.name)??[],d=[];if(!s&&c.length>0)for(let f of c)o[f.newName]===1&&o[f.oldName]!==1&&(o[f.oldName]=1,d.push(f.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:o,pendingRenames:c,hiddenFields:d}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?ge(this.normalizeMetadata(),i.userFilter,e):null,s=this.buildSortFromTokens(i?.userSort),a=await W(t,c=>{let d={_id:{$in:c}};o&&Object.keys(o).length>0&&Object.assign(d,o);let l={projection:n.projection};return s&&(l.sort=s),this.runQuery(()=>this.db.collection(e).find(d,l).toArray())}),u=this.applyReadFallback(a,n);return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(t),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,n,i,o){let s=i.projection?{...i.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let a=this.uniqueValues(n.map(y=>this.toObjectId(y))),u=o?.userFilter?ge(this.normalizeMetadata(),o.userFilter,e):null,c=o?.userLimit,d=o?.userPage,l=this.hasDottedSort(o?.userSort);if(c!==void 0&&c>0){let y=d?(d-1)*c:0;if(l)throw new Error(`Dotted sort is not supported for batch relation '${o?.relationName}'`);let b=this.buildStableSort(o?.userSort),w=await W(a,async C=>{let T={[t]:{$in:C}};u&&Object.keys(u).length>0&&Object.assign(T,u);let k=[{$match:T}];this.appendTopNStages(k,t,b,y,c),k.push({$sort:{[t]:1,...b}}),this.appendPartitionProjection(k,s,[t]);let x=await this.runQuery(()=>this.db.collection(e).aggregate(k).toArray());return this.applyReadFallback(x,i)});return{docs:w,groupKeyField:t,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:w.length}}}if(s&&(s[t]=1),l){let y=[],b=await _n(a,async w=>{let C={[t]:w};u&&Object.keys(u).length>0&&Object.assign(C,u);let T=this.buildSortAggregatePipeline(e,C,o.userSort);s&&T.push({$project:s});let k=await this.runQuery(()=>this.db.collection(e).aggregate(T).toArray());return this.applyReadFallback(k,i)},Ee);for(let w of b.values())for(let C of w)y.push(C);return{docs:y,groupKeyField:t,stats:{strategy:"per-parent-dotted-sort",roundtrips:a.length,concurrencyWaves:Math.ceil(a.length/Ee),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:y.length}}}let f={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(f,u);let p=this.buildSortFromTokens(o?.userSort)||{_id:1},h={projection:s,sort:p},g=await W(a,y=>this.runQuery(()=>this.db.collection(e).find({[t]:{$in:y},...u||{}},h).toArray())),m=this.applyReadFallback(g,i);return{docs:m,groupKeyField:t,stats:{strategy:"batch-in",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.length}}}postProcessInverseChild(e,t,n){n||delete e[t]}m2mSortCanUseJunction(e){return this.parseSortTokens(e).every(t=>t.field==="_id")}async loadM2MTargets(e,t,n){if(t.length===0)return[];let i=n.projection?{projection:n.projection}:void 0,o=await W(t,s=>this.runQuery(()=>this.db.collection(e).find({_id:{$in:s}},i).toArray()));return this.applyReadFallback(o,n)}async fetchM2MTopK(e,t,n,i,o,s,a){if(this.hasDottedSort(t.userSort))throw new Error(`Dotted sort is not supported for batch relation '${t.relationName}'`);let u=new Map;for(let y of e)u.set(this.keyOf(y),[]);let c=i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1,d=!o&&this.m2mSortCanUseJunction(t.userSort),l=this.parseSortTokens(t.userSort).find(y=>y.field==="_id")?.order??1,f=this.buildStableSort(t.userSort),p=await W(e,async y=>{if(d){let C=[{$match:{[n.selfColumn]:{$in:y}}}];return this.appendTopNStages(C,n.selfColumn,{[n.otherColumn]:l},s,a),C.push({$sort:{[n.selfColumn]:1,[n.otherColumn]:l}},{$project:{_id:0,[se]:`$${n.selfColumn}`,[ke]:`$${n.otherColumn}`}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(C).toArray())).map(k=>({sourceId:k[se],targetId:k[ke]}))}let b=[{$match:{[n.selfColumn]:{$in:y}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ye}},{$unwind:`$${Ye}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ye}`,{[se]:`$${n.selfColumn}`,[ke]:`$${n.otherColumn}`}]}}}];return o&&Object.keys(o).length>0&&b.push({$match:o}),this.appendTopNStages(b,se,f,s,a),b.push({$sort:{[se]:1,...f}}),b.push({$project:{_id:0,[se]:1,[ke]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(b).toArray())).map(C=>({sourceId:C[se],targetId:C[ke]}))});if(c){let y=new Map;for(let b of p){let w=this.keyOf(b.targetId);y.has(w)||y.set(w,{_id:b.targetId}),u.get(this.keyOf(b.sourceId))?.push(y.get(w))}return{grouped:u,docs:[],stats:{strategy:d?"m2m-junction-partitioned-top-k":"m2m-filtered-edge-top-k",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let h=this.uniqueValues(p.map(y=>y.targetId)),g=await this.loadM2MTargets(t.targetTable,h,i),m=new Map(g.map(y=>[this.keyOf(y._id),y]));for(let y of p){let b=m.get(this.keyOf(y.targetId));b&&u.get(this.keyOf(y.sourceId))?.push(b)}return{grouped:u,docs:g,stats:{strategy:"m2m-partitioned-edge-loader",roundtrips:this.chunkCount(e)+(h.length>0?this.chunkCount(h):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+g.length,rowsDiscarded:0}}}async fetchM2MEdgeBatch(e,t,n,i,o){let s=new Map;for(let g of e)s.set(this.keyOf(g),[]);let a=!o&&this.m2mSortCanUseJunction(t.userSort),u=this.parseSortTokens(t.userSort).find(g=>g.field==="_id")?.order??1,c=this.buildStableSort(t.userSort),d=await W(e,async g=>{if(a)return(await this.runQuery(()=>this.db.collection(n.junctionName).find({[n.selfColumn]:{$in:g}},{projection:{_id:0,[n.selfColumn]:1,[n.otherColumn]:1},sort:{[n.selfColumn]:1,[n.otherColumn]:u}}).toArray())).map(w=>({sourceId:w[n.selfColumn],targetId:w[n.otherColumn]}));let m=[{$match:{[n.selfColumn]:{$in:g}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ye}},{$unwind:`$${Ye}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ye}`,{[se]:`$${n.selfColumn}`,[ke]:`$${n.otherColumn}`}]}}}];return o&&Object.keys(o).length>0&&m.push({$match:o}),m.push({$sort:{[se]:1,...c}},{$project:{_id:0,[se]:1,[ke]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(m).toArray())).map(b=>({sourceId:b[se],targetId:b[ke]}))});if(i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1){let g=new Map;for(let m of d){let y=this.keyOf(m.targetId);g.has(y)||g.set(y,{_id:m.targetId}),s.get(this.keyOf(m.sourceId))?.push(g.get(y))}return{grouped:s,docs:[],stats:{strategy:a?"m2m-junction-batch":"m2m-filtered-edge-batch",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length,rowsDiscarded:0}}}let f=this.uniqueValues(d.map(g=>g.targetId)),p=await this.loadM2MTargets(t.targetTable,f,i),h=new Map(p.map(g=>[this.keyOf(g._id),g]));for(let g of d){let m=h.get(this.keyOf(g.targetId));m&&s.get(this.keyOf(g.sourceId))?.push(m)}return{grouped:s,docs:p,stats:{strategy:"m2m-edge-loader",roundtrips:this.chunkCount(e)+(f.length>0?this.chunkCount(f):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length+p.length,rowsDiscarded:0}}}async fetchM2M(e,t,n,i,o){let s=n?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=Ne(s,{type:"many-to-many",propertyName:t.relationName,targetTable:t.targetTable,mappedBy:t.isInverse?t.mappedBy:void 0,junctionTableName:t.junctionTableName,junctionSourceColumn:t.junctionSourceColumn,junctionTargetColumn:t.junctionTargetColumn});if(!a)throw new Error(`Failed to resolve junction info for ${s}.${t.relationName}`);let u=this.uniqueValues(e.map(k=>k._id)),c=new Map;for(let k of e)c.set(this.keyOf(k._id),[]);if(u.length===0)return{grouped:c,docs:[]};let d=t.userFilter?ge(this.normalizeMetadata(),t.userFilter,t.targetTable):null,l=t.userLimit,f=t.userPage;if(l!==void 0&&l>0){let k=f?(f-1)*l:0;return this.fetchM2MTopK(u,t,a,o,d,k,l)}let p=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1&&!d,h=this.hasDottedSort(t.userSort);if(!h)return this.fetchM2MEdgeBatch(u,t,a,o,d);let g=await W(u,k=>this.runQuery(()=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:k}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray()));if(g.length===0)return{grouped:c,docs:[],stats:{strategy:"m2m-batch",roundtrips:this.chunkCount(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:0}};let m=new Set,y=[];for(let k of g){let x=k[a.otherColumn];if(x==null)continue;let $=this.keyOf(x);m.has($)||(m.add($),y.push(x))}let b=[],w=new Map;if(p)b=y.map(k=>({_id:k})),this.sortDocsByPk(b);else{let k={_id:{$in:y}};d&&Object.keys(d).length>0&&Object.assign(k,d);let x;if(h){let $=this.buildSortAggregatePipeline(t.targetTable,k,t.userSort);o.projection&&$.push({$project:o.projection}),x=await this.runQuery(()=>this.db.collection(t.targetTable).aggregate($).toArray())}else{let $=this.buildSortFromTokens(t.userSort)||{_id:1},I=this.projectionWithSortFields(o.projection,t.userSort),B={sort:$};I.projection&&(B.projection=I.projection),x=await W(y,S=>this.runQuery(()=>this.db.collection(t.targetTable).find({_id:{$in:S},...d||{}},B).toArray())),t.userSort?this.sortDocsInMemory(x,t.userSort):this.sortDocsByPk(x),this.removeHiddenFields(x,I.hiddenFields)}b=this.applyReadFallback(x,o)}for(let k of b)w.set(this.keyOf(k._id),k);let C=new Map;for(let k of g){let x=this.keyOf(k[a.selfColumn]),$=this.keyOf(k[a.otherColumn]);w.has($)&&(C.has($)||C.set($,[]),C.get($).push(x))}for(let k of b){let x=C.get(this.keyOf(k._id))||[];for(let $ of x)c.get($)?.push(k)}let T=p||y.length===0?0:this.chunkCount(y);return{grouped:c,docs:b,stats:{strategy:p?"m2m-junction-batch":"m2m-batch",roundtrips:this.chunkCount(u)+T,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length+b.length}}}applyReadFallback(e,t){let n=t.pendingRenames??[];if(e.length===0||n.length===0)return e;let i=new Set(t.hiddenFields??[]);for(let o of e)for(let s of n)o[s.newName]===void 0&&o[s.oldName]!==void 0&&(o[s.newName]=o[s.oldName]),(i.has(s.oldName)||o[s.newName]!==void 0)&&delete o[s.oldName];return e}};async function wn(r,e,t,n,i=3,o=0,s,a,u,c){let d=await c?.getActiveFieldRenamesByTable?.(),l=new Xe(r,a,d);await new Se(l,n,u).execute(e,t,i,o,s)}async function Zn(r,e,t){let n=[],{db:i,metadata:o,dbType:s,debugLog:a}=t,u=o?.tables?.get(e.table),c=new Set((u?.relations??[]).map(S=>S.propertyName)),d=!!e.mongoRawFilter&&!!o&&ne(e.mongoRawFilter,c),l=e.plan,f=l?.filterTree&&!l.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&o&&d){let S=await Te(e.mongoRawFilter,e.table,o,i);S&&Object.keys(S).length>0&&n.push({$match:S})}else if(f){let S=ze(l.filterTree,{metadata:o,rootTable:e.table});Object.keys(S).length>0&&n.push({$match:S})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let S=Qe(o,e.where,e.table,s);n.push({$match:S})}let p=e.plan,g=p?p.hasRelationSort:e.sort?.some(S=>{if(!S.field.includes("."))return!1;let E=S.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(A=>A.propertyName===E)??!1})??!1,m=()=>p?.sortItems?ko(p.sortItems):e.sort?Co(e.sort):null,y=p?.sortItems?_o(p.sortItems):[],b=p?.sortItems?wo(p.sortItems):[],w=()=>{!p||y.length===0||$o(n,e.table,p.sortItems,o)},C=()=>{!p||b.length===0||To(n,e.table,p.sortItems,o)},T=()=>{let S=[...y,...b];S.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(S.map(E=>[E,0]))})};if(!e.mongoFieldsExpanded){w(),C();let S=m();if(S&&n.push({$sort:S}),e.mongoCountOnly?n.push({$count:"count"}):(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit})),T(),e.select){let A={};for(let L of e.select)A[L]=1;n.push({$project:A})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let E=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:E,pipeline:n}:{results:Gr(E),pipeline:n}}let{scalarFields:k,relations:x}=e.mongoFieldsExpanded;if(!g){w(),C();let S=m();S&&n.push({$sort:S}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}let $=[];for(let S of x)if(e.sort?.some(A=>A.field.startsWith(`${S.propertyName}.`))){let A=e.mongoRawFilter?.[S.propertyName];if(S.nestedFields&&S.nestedFields.length>0){let _=await At(o,S.targetTable,S.nestedFields??[],A);S.type==="one"&&_.length>0&&_.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:_.length>0?_:void 0}})}else if(A){let _=await At(o,S.targetTable,["_id"],A);S.type==="one"&&_.length>0&&_.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:_.length>0?_:void 0}})}else n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName}});S.type==="one"&&(n.push({$unwind:{path:`$${S.propertyName}`,preserveNullAndEmptyArrays:!0}}),A&&(Ze(A)||n.push({$match:{[S.propertyName]:{$ne:null}}})))}else $.push(S);if(g){w(),C();let S=m();S&&n.push({$sort:S}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}T(),await Vr(o,n,e.table,k,[...x]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let I=performance.now(),B=await r.aggregate(n).toArray();if(e.debugTrace?.dur("db_execute",I,{table:e.table}),e.mongoCountOnly)return{results:B,pipeline:n};if($.length>0&&B.length>0){let S=e.deep||{},E=$.map(L=>{let R=o?.tables?.get(e.table)?.relations?.find(M=>M.propertyName===L.propertyName),F=S[L.propertyName],ee=F?.fields!=null?Array.isArray(F.fields)?F.fields:String(F.fields).split(",").map(M=>M.trim()).filter(Boolean):L.nestedFields&&L.nestedFields.length>0?L.nestedFields:["_id"];return{relationName:L.propertyName,type:R?.type,targetTable:L.targetTable,fields:ee,isInverse:R?.isInverse,mappedBy:R?.mappedBy,junctionTableName:R?.junctionTableName,junctionSourceColumn:R?.junctionSourceColumn,junctionTargetColumn:R?.junctionTargetColumn,localField:L.localField,foreignField:L.foreignField,userFilter:F?.filter,userSort:F?.sort,userLimit:F?.limit!==void 0?Number(F.limit):void 0,userPage:F?.page!==void 0?Number(F.page):void 0,nestedDeep:F?.deep}}),A=So(o);A&&await wn(i,B,E,A,3,0,e.table,o,e.debugTrace,t.mongoPhysicalMigrationService)}return{results:Gr(B),pipeline:n}}function er(r){return`__sort_count_${r.relationName||r.field}`}function tr(r){return`__sort_${r.function}_${r.relationName||r.field}_${r.aggregateField||"value"}`}function _o(r){return r.filter(e=>e.function==="count").map(er)}function wo(r){return r.filter(e=>e.function==="max"||e.function==="min").map(tr)}function $o(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="count")continue;let a=s.relationMeta,u=s.relationName||s.field,c=a?.targetTableName||a?.targetTable,d=er(s);if(!(!a||!c)){if(a.type==="one-to-many"){let l=K(a)||u;r.push({$lookup:{from:c,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${l}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let l=Ne(e,a);if(!l)continue;r.push({$lookup:{from:l.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${l.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}})}}}}function To(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="max"&&s.function!=="min")continue;let a=s.relationMeta,u=s.relationName||s.field,c=a?.targetTableName||a?.targetTable,d=n?.tables?.get(c),l=d?.columns?.find(m=>m.isPrimary)?.name||(d?.columns?.some(m=>m.name==="_id")?"_id":"id"),f=s.aggregateField,p=f==="id"&&d?.columns?.some(m=>m.name==="_id")?"_id":f,h=tr(s),g=s.function==="min"?"$min":"$max";if(!(!a||!c||!f)){if(a.type==="one-to-many"){let m=K(a)||u;r.push({$lookup:{from:c,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${m}`,"$$localId"]}}},{$group:{_id:null,value:{[g]:`$${p}`}}}],as:h}}),r.push({$addFields:{[h]:{$arrayElemAt:[`$${h}.value`,0]}}});continue}if(a.type==="many-to-many"){let m=Ne(e,a);if(!m)continue;let y=`${h}_junction`;r.push({$lookup:{from:m.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${m.selfColumn}`,"$$localId"]}}},{$project:{_id:0,targetId:`$${m.otherColumn}`}}],as:y}}),r.push({$lookup:{from:c,let:{targetIds:`$${y}.targetId`},pipeline:[{$match:{$expr:{$in:[`$${l}`,"$$targetIds"]}}},{$group:{_id:null,value:{[g]:`$${p}`}}}],as:h}}),r.push({$addFields:{[h]:{$arrayElemAt:[`$${h}.value`,0]}}}),r.push({$project:{[y]:0}})}}}}function So(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 Co(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 ko(r){let e={};for(let t of r){let n=t.function==="count"?er(t):t.function==="max"||t.function==="min"?tr(t):t.joinId!==null?t.fullPath:t.field;e[n]=t.direction==="asc"?1:-1}return e}function Ze(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ze(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ze(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ze(e));if("_not"in r)return Ze(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Ze(t)))return!0}return!1}function Gr(r){return r.map(Y)}function Yr(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(Ro(o,i,e));return{scalarFields:t,relations:n}}function Ro(r,e,t){let n=e.relations?.find(c=>c.propertyName===r.propertyName),i,o,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&Ie(n)?(i="_id",o=K(n)||r.propertyName,s=!0):(i=n&&z(n)||r.propertyName,o="_id",s=!1):r.relationType==="one-to-many"?(i="_id",o=n&&K(n)||r.propertyName,s=!0):n?.mappedBy?(i="_id",o=n.mappedBy,s=!0):(i=r.propertyName,o="_id",s=!1);let a=r.relationType==="one-to-many"||r.relationType==="many-to-many",u=Xr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:i,foreignField:o,type:a?"many":"one",isInverse:s,nestedFields:u}}function Xr(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=Xr(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let i of n)e.push(`${t.propertyName}.${i}`)}return e}Je();Et();Mt();function $n(r,e,t,n){let i={rootTable:e,nodes:[]};if(!r||r.length===0)return i;let o=t?.tables?.get(e);if(!o)return i;let s=o.columns?.some(l=>l.name==="_id"&&l.isPrimary),a=o.columns?.some(l=>l.name==="id"),u=s&&!a?"_id":"id",c=new Map,d=[];for(let l of r){let f=l==="id"?u:l;if(f==="*")d.push("*");else if(f.includes(".")){let p=f.indexOf("."),h=f.substring(0,p),g=f.substring(p+1);if(!o.relations?.some(y=>y.propertyName===h))continue;c.has(h)||c.set(h,[]),c.get(h).push(g)}else if(o.relations?.some(h=>h.propertyName===f))c.has(f)||c.set(f,[u]);else{if(!o.columns?.some(g=>g.name===f))continue;d.push(f)}}if(d.includes("*")){i.nodes.push({kind:"wildcard"});for(let l of o.relations||[])c.has(l.propertyName)||c.set(l.propertyName,[u])}else for(let l of d)i.nodes.push({kind:"scalar",name:l});for(let[l,f]of c.entries()){let p=o.relations?.find(m=>m.propertyName===l);if(!p)continue;let h=p.targetTableName||p.targetTable,g={kind:"relation",propertyName:l,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:h,children:Zr(f,h,t)};if(p.type==="many-to-one"||p.type==="one-to-one"){let m=n.registerWithParent(e,l,t,"left",null,"data");g.joinId=m}i.nodes.push(g)}return i}function Zr(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let i=n.columns?.some(d=>d.name==="_id"&&d.isPrimary),o=n.columns?.some(d=>d.name==="id"),s=i&&!o?"_id":"id",a=new Map,u=[];for(let d of r){let l=d==="id"?s:d;if(l==="*")u.push("*");else if(l.includes(".")){let f=l.indexOf("."),p=l.substring(0,f),h=l.substring(f+1);if(!n.relations?.some(m=>m.propertyName===p))continue;a.has(p)||a.set(p,[]),a.get(p).push(h)}else if(n.relations?.some(p=>p.propertyName===l))a.has(l)||a.set(l,[s]);else{if(!n.columns?.some(h=>h.name===l))continue;u.push(l)}}let c=[];if(u.includes("*")){c.push({kind:"wildcard"});for(let d of n.relations||[])a.has(d.propertyName)||a.set(d.propertyName,[s])}else for(let d of u)c.push({kind:"scalar",name:d});for(let[d,l]of a.entries()){let f=n.relations?.find(h=>h.propertyName===d);if(!f)continue;let p=f.targetTableName||f.targetTable;c.push({kind:"relation",propertyName:d,joinId:null,relationType:f.type,isInverse:!!f.isInverse,targetTable:p,children:Zr(l,p,t)})}return c}de();de();var Fo=new Set(["_and","_or","_not"]);function ei(r,e){return r?.tables?.get(e)??null}function xo(r,e,t){return ei(r,e)?.columns?.find(n=>n.name===t)}function nr(r,e,t){return ei(r,e)?.relations?.find(n=>n.propertyName===t)}function vo(r){let e=r.match(/^_(count|max|min)\(([^)]+)\)$/);if(!e)return null;let t=e[1],n=e[2].trim();if(t==="count")return{functionName:t,relationName:n};let i=n.indexOf(".");return i<=0||i!==n.lastIndexOf(".")?null:{functionName:t,relationName:n.slice(0,i).trim(),fieldName:n.slice(i+1).trim()}}function rr(r,e,t,n){if(xo(r,e,t)?.isEncrypted===!0)throw new N(`Encrypted field '${t}' on '${e}' cannot be used for ${n}.`)}function Oe(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){for(let n of r)Oe(n,e,t);return}for(let[n,i]of Object.entries(r)){if(Fo.has(n)){Oe(i,e,t);continue}if(n.startsWith("_"))continue;let o=nr(t,e,n);if(o){let s=o.targetTableName||o.targetTable;s&&Oe(i,s,t);continue}rr(t,e,n,"filter")}}}function Tn(r,e,t){if(!r)return;let n=Array.isArray(r)?r:r.split(",").map(i=>i.trim()).filter(Boolean);for(let i of n){let o=i.startsWith("-")?i.slice(1):i;if(!o)continue;let s=vo(o);if(s){if(s.functionName==="count")continue;let c=nr(t,e,s.relationName),d=c?.targetTableName||c?.targetTable;d&&rr(t,d,s.fieldName,"sort");continue}let a=o.split("."),u=e;for(let c=0;c<a.length;c++){let d=a[c];if(c===a.length-1){rr(t,u,d,"sort");break}let f=nr(t,u,d);if(!f)break;u=f.targetTableName||f.targetTable||u}}}var Z=class{plan(e){let{tableName:t,fields:n,filter:i,sort:o,page:s,limit:a,meta:u,metadata:c,dbType:d}=e,l=c?.tables?.get(t),f=new ie,p=this.parseFields(n),h=null;p&&l&&(h=$n(p,t,c,f));let g=!1,m=null;if(i&&l){Oe(i,t,c);let S=fe(i,t,c,f);m=S.node,g=S.hasRelationFilters}let y=this.parseSort(o);l&&Tn(y,t,c);let b=[],w=!1;for(let S of y){let E=S.startsWith("-"),A=E?S.substring(1):S,L=E?"desc":"asc";if(l){let _=this.parseRelationAggregateSort(t,l,A,c);if(_){b.push({joinId:null,field:A,direction:L,fullPath:A,function:_.functionName,relationName:_.relationName,aggregateField:_.aggregateField,relationMeta:_.relationMeta});continue}this.assertLocalSortField(t,l,A)}b.push({joinId:null,field:A,direction:L,fullPath:A})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let C=this.parseLimit(a),T=this.parsePage(s),k=T!==void 0&&C!==void 0?(T-1)*C:void 0,x=this.parseMeta(u),$=x.includes("totalCount")||x.includes("*"),I=x.includes("filterCount")||x.includes("*"),B=f.getAll();return{table:t,dbType:d,rawFields:p,rawFilter:i??null,joins:B,sortItems:b,limit:C,offset:k,needsTotalCount:$,needsFilterCount:I,hasRelationFilters:g,hasRelationSort:w,filterTree:m,fieldTree:h}}parseFields(e){if(e)return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):e.split(",").map(t=>t.trim()).filter(Boolean)}parseSort(e){return e?(Array.isArray(e)?e:e.split(",")).map(n=>n.trim()).filter(Boolean):[]}parseLimit(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;if(!Number.isNaN(t))return t<0?0:t}parsePage(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;return Number.isNaN(t)?void 0:t}parseMeta(e){return e?Array.isArray(e)?e:e.split(",").map(t=>t.trim()).filter(Boolean):[]}assertLocalSortField(e,t,n){if(n.includes("."))throw new N(`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 N(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationAggregateSort(e,t,n,i){let o=n.match(/^_(count|max|min)\(([^)]+)\)$/);if(!o){if(/^_(count|max|min)\(/.test(n))throw new N(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName), _max(relationName.fieldName), or _min(relationName.fieldName).`);return null}let s=o[1],a=o[2].trim();if(s==="count"){let m=a;if(!m||m.includes("."))throw new N(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let y=t.relations?.find(b=>b.propertyName===m);if(!y)throw new N(`Sort relation '${m}' does not exist on '${e}'.`);if(y.type!=="one-to-many"&&y.type!=="many-to-many")throw new N(`Sort function '_count(${m})' is only supported for list relations on '${e}'.`);return{functionName:s,relationName:m,relationMeta:y}}let u=a.indexOf(".");if(u<=0||u!==a.lastIndexOf("."))throw new N(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let c=a.slice(0,u).trim(),d=a.slice(u+1).trim();if(!c||!d)throw new N(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let l=t.relations?.find(m=>m.propertyName===c);if(!l)throw new N(`Sort relation '${c}' does not exist on '${e}'.`);if(l.type!=="one-to-many"&&l.type!=="many-to-many")throw new N(`Sort function '_${s}(${c}.${d})' is only supported for list relations on '${e}'.`);let f=l.targetTableName||l.targetTable,p=i?.tables?.get(f);if(!p)throw new N(`Sort function '${n}' references unknown target table '${f}' on '${e}'.`);let h=p.columns?.find(m=>m.name===d),g=d==="id"&&p.columns?.some(m=>m.name==="_id");if(!h&&!g)throw new N(`Sort field '${d}' does not exist on '${f}' for function '_${s}(${c}.${d})'.`);if(h?.isEncrypted===!0)throw new N(`Encrypted field '${d}' on '${f}' cannot be used for sort.`);return{functionName:s,relationName:c,aggregateField:d,relationMeta:l}}registerSortJoinChain(e,t,n,i,o){let s=e.indexOf(".");if(s===-1)return null;let a=e.slice(0,s),u=e.slice(s+1),c=n?.tables?.get(t);if(!c)return null;let d=c.relations?.find(p=>p.propertyName===a);if(!d||d.type!=="many-to-one"&&d.type!=="one-to-one")return null;let l=i.registerWithParent(t,a,n,"left",o,"sort");if(!l)return null;if(!u.includes("."))return{lastJoinId:l,field:u};let f=d.targetTableName||d.targetTable;return this.registerSortJoinChain(u,f,n,i,l)}};de();var Io=new Set(["int","integer","bigint","smallint","tinyint","float","double","decimal","numeric","real","number"]),No=new Set(["date","datetime","timestamp","timestamptz","timestamp with time zone","timestamp without time zone"]),Mo=new Set(["hour","day","week","month","year"]),Eo=new Set(["count","countDistinct","sum","avg","min","max"]);function O(r,e){throw new N(e,{path:r})}function et(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Oo(r,e){let t=r?.tables?.get(e);return t||O("aggregate",`Table "${e}" metadata is not available`),t}function ti(r,e,t){let n=r.columns?.find(i=>i.name===e);return n||O(t,`Unknown aggregate field "${e}"`),n.isEncrypted===!0&&O(t,`Encrypted field "${e}" cannot be used in aggregate queries`),n}function Ao(r,e){let t=r===void 0?"UTC":r;(typeof t!="string"||t.length===0)&&O(e,"Aggregate timezone must be a non-empty IANA timezone");try{new Intl.DateTimeFormat("en-US",{timeZone:t}).format()}catch{O(e,`Invalid aggregate timezone "${t}"`)}return t}function Po(r,e){return r==null?{}:(et(r)||O(e,"Aggregate filter must be an object"),r)}function tt(r,e,t){et(r)||O("aggregate","Aggregate options must be an object");let n=Oo(t,e),i=r.dimensions===void 0?[]:r.dimensions,o=r.measures;Array.isArray(i)||O("aggregate.dimensions","Aggregate dimensions must be an array"),(!et(o)||Object.keys(o).length===0)&&O("aggregate.measures","Aggregate requires at least one measure");let s=new Set,a=i.map((g,m)=>{let y=`aggregate.dimensions[${m}]`;(!et(g)||typeof g.field!="string"||g.field.length===0)&&O(y,"Aggregate dimension requires a field");let b=ti(n,g.field,`${y}.field`);return s.has(g.field)&&O(`${y}.field`,`Duplicate aggregate dimension "${g.field}"`),s.add(g.field),g.bucket===void 0?(g.timezone!==void 0&&O(`${y}.timezone`,"Aggregate timezone requires a bucket"),{field:g.field,outputKey:g.field,column:b}):((typeof g.bucket!="string"||!Mo.has(g.bucket))&&O(`${y}.bucket`,"Aggregate bucket must be hour, day, week, month, or year"),No.has(String(b.type).toLowerCase())||O(`${y}.bucket`,`Aggregate bucket requires a date field, but "${g.field}" is "${b.type}"`),{field:g.field,outputKey:g.field,bucket:g.bucket,timezone:Ao(g.timezone,`${y}.timezone`),column:b})}),u=new Set,c=Object.entries(o).map(([g,m])=>{let y=`aggregate.measures.${g}`;(!g||!et(m))&&O(y,"Aggregate measure must be an object");let b=Object.entries(m).filter(([k])=>k!=="as");b.length!==1&&O(y,"Aggregate measure must define exactly one operation");let[w,C]=b[0];Eo.has(w)||O(y,`Unsupported aggregate measure "${w}"`),(typeof C!="string"||C.length===0)&&O(y,"Aggregate measure field must be a non-empty string");let T=ti(n,C,`${y}.${w}`);return(u.has(g)||s.has(g))&&O(y,`Aggregate output key "${g}" is duplicated`),u.add(g),["sum","avg","min","max"].includes(w)&&!Io.has(String(T.type).toLowerCase())&&O(y,`Aggregate ${w} requires a numeric field, but "${C}" is "${T.type}"`),{outputKey:g,operation:w,field:C,column:T}}),d=r.sort===void 0?[]:r.sort;Array.isArray(d)||O("aggregate.sort","Aggregate sort must be an array");let l=new Set([...s,...u]),f=d.map((g,m)=>{let y=`aggregate.sort[${m}]`;return(!et(g)||typeof g.field!="string"||!l.has(g.field))&&O(y,"Aggregate sort field must reference a dimension or measure output"),g.direction!=="asc"&&g.direction!=="desc"&&O(`${y}.direction`,"Aggregate sort direction must be asc or desc"),{field:g.field,direction:g.direction}}),p=r.limit===void 0?void 0:Number(r.limit),h=r.page===void 0?1:Number(r.page);return p!==void 0&&(!Number.isInteger(p)||p<=0||p>1e4)&&O("aggregate.limit","Aggregate limit must be an integer between 1 and 10000"),(!Number.isInteger(h)||h<=0)&&O("aggregate.page","Aggregate page must be a positive integer"),{tableName:e,filter:Po(r.filter,"aggregate.filter"),dimensions:a,measures:c,sort:f,page:h,limit:p}}var Ae=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.debugLog=[];this.lastBuiltPipeline=null;this.db=e.getDb()}async execute(e){if(this.metadata=e.metadata,this.dbType=e.dbType||"mongodb",!e.plan){let l=new Z;e={...e,plan:l.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:"mongodb"})}}let t=e.debugLog||[];this.debugLog=t;let n={table:e.tableName,metadata:e.metadata,debugTrace:e.debugTrace};if(e.pipeline&&(n.pipeline=e.pipeline),e.fields&&(Array.isArray(e.fields)?n.fields=e.fields:typeof e.fields=="string"&&(n.fields=e.fields.split(",").map(l=>l.trim()))),e.filter&&(re(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let l=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(f=>f.trim());n.sort=l.map(f=>{let p=f.trim();return p.startsWith("-")?{field:p.substring(1),direction:"desc"}:{field:p,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let l=typeof e.page=="string"?parseInt(e.page,10):e.page,f=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(l-1)*f,n.limit=f}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let i=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(l=>l.trim()).filter(Boolean),o=0,s=0;(i.includes("totalCount")||i.includes("*"))&&(o=await this.mongoService.collection(e.tableName).countDocuments({}));let a=this.metadata?.tables?.get(e.tableName),u=new Set((a?.relations??[]).map(l=>l.propertyName)),c=!!n.mongoRawFilter&&ne(n.mongoRawFilter,u);if((i.includes("filterCount")||i.includes("*"))&&!c){let l=this.mongoService.collection(e.tableName),f=e.plan?.filterTree?ze(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await l.countDocuments(f)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let d=await this.selectLegacy(n);if(e.debugMode){let l=this.lastBuiltPipeline??[],f;try{f=await this.db.collection(e.tableName).aggregate(l).explain()}catch(p){f={error:String(p)}}return{pipeline:l,explain:f}}if(c&&(i.includes("filterCount")||i.includes("*"))){let l={...n,mongoCountOnly:!0},f=await this.selectLegacy(l);s=f.length>0?f[0].count:0}return{data:d,...i.length>0&&{meta:{...i.includes("totalCount")||i.includes("*")?{totalCount:o}:{},...i.includes("filterCount")||i.includes("*")?{filterCount:s}:{}}}}}async aggregate(e){this.metadata=e.metadata,this.dbType=e.dbType||"mongodb";let t=tt(e.aggregate,e.tableName,e.metadata),n=this.db.collection(e.tableName),i=new Z().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:"mongodb"}),o=i.hasRelationFilters?await Te(t.filter,e.tableName,e.metadata,this.db):i.filterTree?ze(i.filterTree,{metadata:e.metadata,rootTable:e.tableName}):{},s=[];Object.keys(o).length>0&&s.push({$match:o});let a={_id:{}},u={};for(let d of t.dimensions){let l=`$${d.field}`,f=d.bucket?{$dateTrunc:{date:l,unit:d.bucket,timezone:d.timezone}}:l;a._id[d.outputKey]=f,u[d.outputKey]=`$_id.${d.outputKey}`}for(let d of t.measures){let l=`$${d.field}`;a[d.outputKey]=d.operation==="count"?{$sum:{$cond:[{$ne:[l,null]},1,0]}}:d.operation==="countDistinct"?{$addToSet:l}:{[`$${d.operation}`]:l},u[d.outputKey]=d.operation==="countDistinct"?{$size:{$setDifference:[`$${d.outputKey}`,[null]]}}:`$${d.outputKey}`}return s.push({$group:a},{$project:{_id:0,...u}}),t.sort.length>0&&s.push({$sort:Object.fromEntries(t.sort.map(d=>[d.field,d.direction==="asc"?1:-1]))}),t.limit!==void 0&&s.push({$skip:(t.page-1)*t.limit},{$limit:t.limit}),this.lastBuiltPipeline=s,e.debugMode?{pipeline:s,explain:await n.aggregate(s).explain()}:{data:(await n.aggregate(s).toArray()).map(Y)}}async selectLegacy(e){let t=[],n=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,i=this.metadata?.tables?.get(e.table),o=i?.relations&&i.relations.length>0;if(e.fields&&e.fields.length>0||n||o){let c=e.plan,d=e.fields&&e.fields.length>0?e.fields:["*"];if(e.fields&&e.fields.length>0&&c?.fieldTree){if(e.mongoFieldsExpanded=Yr(c.fieldTree,this.metadata),n){let l=await It(this.metadata,e.table,[],e.deep),f=new Set(e.mongoFieldsExpanded.relations.map(p=>p.propertyName));e.mongoFieldsExpanded.relations.push(...l.relations.filter(p=>!f.has(p.propertyName)))}}else console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await It(this.metadata,e.table,d,e.deep);if(this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let l=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:l.scalarFields},t=l.hiddenFields}}e.where&&(e.where=e.where.map(c=>c.field.includes(".")?c:{...c,field:`${e.table}.${c.field}`}));let s=this.db.collection(e.table);if(e.pipeline)return this.debugLog&&this.debugLog.push({type:"MongoDB Custom Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(e.pipeline))}),(await s.aggregate(e.pipeline).toArray()).map(Y);let{results:a,pipeline:u}=await Zn(s,e,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=u,this.mongoPhysicalMigrationService?await this.mongoPhysicalMigrationService.applyReadFallback(e.table,a,t):a}async executeAggregationPipeline(e,t){let{results:n,pipeline:i}=await Zn(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=i,n}};var Sn=class{constructor(e){this.context=e}log(e){console.log(this.format(e))}warn(e){console.warn(this.format(e))}error(e,t){console.error(this.format(e)),t&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}fatal(e,t){this.error(e,t)}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};de();ae();var jo=["_and","_or","_not"];function he(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>he(e));for(let e of Object.keys(r))if(jo.includes(e)||typeof r[e]=="object"&&r[e]!==null&&he(r[e]))return!0;return!1}var ni=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function Bo(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function Cn(r,e,t){if(!t)return!1;let n=r;if(r.includes(".")){let s=r.split(".");n=s[s.length-1]}let i=t.columns.find(s=>s.name===n);if(!i)return!1;let o=i.type?.toLowerCase()||"";return o==="uuid"||o==="uuidv4"||o.includes("uuid")}function Lo(r,e,t,n,i){return n!=="postgres"||typeof e!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||Cn(r,t,i),e}function ri(r,e,t,n,i,o,s){let a=i&&!e.includes(".")?`${i}.${e}`:e,u=Re(a,o??"postgres"),c=Cn(e,i,s),d=Lo(e,n,i,o,s);switch(t){case"_eq":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} = ?::uuid`,[n]):r.where(a,"=",d);break;case"_neq":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} != ?::uuid`,[n]):r.where(a,"!=",d);break;case"_gt":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} > ?::uuid`,[n]):r.where(a,">",d);break;case"_gte":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} >= ?::uuid`,[n]):r.where(a,">=",d);break;case"_lt":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} < ?::uuid`,[n]):r.where(a,"<",d);break;case"_lte":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} <= ?::uuid`,[n]):r.where(a,"<=",d);break;case"_in":let l=n;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(p=>p.trim()):[l]),c&&o==="postgres"&&l.every(p=>typeof p=="string")?r.whereRaw(`${u} = ANY(?::uuid[])`,[l]):r.whereIn(a,l);break;case"_not_in":case"_nin":let f=n;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]),c&&o==="postgres"&&f.every(p=>typeof p=="string")?r.whereRaw(`${u} != ALL(?::uuid[])`,[f]):r.whereNotIn(a,f);break;case"_contains":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_starts_with":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${u}) LIKE lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_ends_with":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?))`,[n]):o==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?)`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`,[n]);break;case"_between":Array.isArray(n)&&n.length===2&&r.whereBetween(a,[n[0],n[1]]);break;case"_is_null":n===!0?r.whereNull(a):r.whereNotNull(a);break;case"_is_not_null":n===!0?r.whereNotNull(a):r.whereNull(a);break;default:r.where(a,Bo(t),n)}}function Do(r,e,t){if(!t||!e||r.startsWith("_"))return!0;let n=r.includes(".")?r.split(".").pop():r,i=t.columns?.some(s=>s.name===n),o=t.relations?.some(s=>s.propertyName===n);return i||o}function nt(r,e,t,n="and",i,o){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let s of e)n==="and"?r.where(function(){nt(this,s,t,"and",i,o)}):r.orWhere(function(){nt(this,s,t,"and",i,o)});return}for(let[s,a]of Object.entries(e))if(Do(s,t,o)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){nt(this,u,t,"and",i,o)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){nt(this,u,t,"and",i,o)})});continue}if(s==="_not"){r.whereNot(function(){nt(this,a,t,"and",i,o)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(c=>ni.includes(c)))for(let[c,d]of Object.entries(a))ni.includes(c)&&(n==="and"?r.where(function(){ri(this,s,c,d,t,i,o)}):r.orWhere(function(){ri(this,s,c,d,t,i,o)}));else{let c=t&&!s.includes(".")?`${t}.${s}`:s,d=Re(c,i??"postgres");Cn(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${d} = ?::uuid`,[a]):r.orWhereRaw(`${d} = ?::uuid`,[a]):n==="and"?r.where(c,"=",a):r.orWhere(c,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s,c=Re(u,i??"postgres");Cn(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${c} = ?::uuid`,[a]):r.orWhereRaw(`${c} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function le(r,e,t,n,i){return!e||typeof e!="object"||nt(r,e,t,"and",n,i),r}ae();function sr(r,e,t){return`${v(r,t)}.${v(e,t)}`}function Fe(r,e){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function ii(r,e){if(!e)return!1;let t=e.columns.find(i=>i.name===r);if(!t)return!1;let n=t.type?.toLowerCase()||"";return n==="uuid"||n==="uuidv4"||n.includes("uuid")}function rt(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function ar(r,e,t,n,i,o){let s=[];for(let[a,u]of Object.entries(o)){let c=await Bt(r,e,a,u,t,n,i);if(c!==null)s.push(`EXISTS (${c})`);else{let d=t.relations.find(l=>l.propertyName===a);if(d&&d.foreignKeyColumn){let l=sr(e,d.foreignKeyColumn,n),p=u.id;if(p&&typeof p=="object"){let h=rt(p._is_null),g=rt(p._is_not_null);if(h===!0)s.push(`${l} IS NULL`);else if(h===!1)s.push(`${l} IS NOT NULL`);else if(g===!0)s.push(`${l} IS NOT NULL`);else if(g===!1)s.push(`${l} IS NULL`);else if(p._eq!==void 0){let m=Fe(p._eq,n);s.push(`${l} = ${m}`)}else if(p._neq!==void 0){let m=Fe(p._neq,n);s.push(`${l} != ${m}`)}else if(p._in!==void 0){let y=(Array.isArray(p._in)?p._in:[p._in]).map(b=>Fe(b,n)).join(", ");s.push(`${l} IN (${y})`)}else if(p._not_in!==void 0||p._nin!==void 0){let m=p._not_in??p._nin,b=(Array.isArray(m)?m:[m]).map(w=>Fe(w,n)).join(", ");s.push(`${l} NOT IN (${b})`)}else if(p._gt!==void 0){let m=Fe(p._gt,n);s.push(`${l} > ${m}`)}else if(p._gte!==void 0){let m=Fe(p._gte,n);s.push(`${l} >= ${m}`)}else if(p._lt!==void 0){let m=Fe(p._lt,n);s.push(`${l} < ${m}`)}else if(p._lte!==void 0){let m=Fe(p._lte,n);s.push(`${l} <= ${m}`)}}}}}return s}function lr(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 ir(r,e,t,n,i,o){let s=[];for(let a of r)if(a._and&&Array.isArray(a._and)&&a._and.length>0){let u=[];for(let c of a._and)if(lr(c)){let d=e(t).select(`${t}.id`);await Pe(e,d,c,t,n,i,o),u.push({idSubquery:d})}else{let{fieldFilters:d,relationFilters:l}=V(c,n),f=await ar(e,t,n,i,o,l);u.push({fieldFilters:d,subqueries:f})}s.push(u)}else if(lr(a)){let u=e(t).select(`${t}.id`);await Pe(e,u,a,t,n,i,o),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:c}=V(a,n),d=await ar(e,t,n,i,o,c);s.push([{fieldFilters:u,subqueries:d}])}return s}function oi(r,e,t,n,i){if("idSubquery"in e&&e.idSubquery){r.whereIn(`${t}.id`,e.idSubquery);return}let o=e;Object.keys(o.fieldFilters).length===0&&o.subqueries.length===0||r.where(function(){Object.keys(o.fieldFilters).length>0&&le(this,o.fieldFilters,t,i,n);for(let s of o.subqueries)this.whereRaw(s)})}function or(r,e,t,n,i){let o=!0;for(let s of e){let a=function(){for(let u of s)oi(this,u,t,n,i)};o?(r.where(a),o=!1):r.orWhere(a)}}function kn(r,e,t,n,i,o,s){let a=ii(e,i),u=ii(n,o),c=`${v(r,s)}.${v(e,s)}`,d=`${v(t,s)}.${v(n,s)}`;if(s==="postgres"){if(a&&!u)return`${c} = ${d}::uuid`;if(!a&&u)return`${c}::uuid = ${d}`}return`${c} = ${d}`}async function Bt(r,e,t,n,i,o,s){let a=i.relations.find(f=>f.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${e}"`);let u=a.targetTableName||a.targetTable;if(!u)throw new Error(`Relation "${t}" in table "${e}" is missing targetTable/targetTableName. Relation metadata: ${JSON.stringify(a,null,2)}`);let c=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn){let f=Object.keys(n||{});if(f.length===1&&f[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(h=>c.has(h)))return null}let d=s?await s(u):null,l;switch(a.type){case"one-to-many":l=r(u).select(r.raw("1")).whereRaw(kn(u,a.foreignKeyColumn,e,"id",d,i,o));break;case"many-to-many":let f=s?await s(a.junctionTableName):null;l=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw(kn(a.junctionTableName,a.junctionTargetColumn,u,"id",f,d,o))).whereRaw(kn(a.junctionTableName,a.junctionSourceColumn,e,"id",f,i,o));break;case"many-to-one":case"one-to-one":l=r(u).select(r.raw("1")).whereRaw(kn(u,"id",e,a.foreignKeyColumn,d,i,o));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?d?await Pe(r,l,n,u,d,o,s):l=le(l,n,u,o,d||void 0):l=le(l,n,u,o),l.toString()}async function Pe(r,e,t,n,i,o,s){if(!t||typeof t!="object")return;if(t._and&&Array.isArray(t._and)){for(let c of t._and)if(c._or&&Array.isArray(c._or)&&c._or.length>0){let d=await ir(c._or,r,n,i,o,s);e.where(function(){or(this,d,n,i,o)})}else if(c._and&&Array.isArray(c._and)&&c._and.length>0)for(let d of c._and)await Pe(r,e,d,n,i,o,s);else await Pe(r,e,c,n,i,o,s);return}if(t._or&&Array.isArray(t._or)){let c=await ir(t._or,r,n,i,o,s);e.where(function(){or(this,c,n,i,o)});return}if(t._not){let c=t._not;if(c._and&&Array.isArray(c._and)&&c._and.length>0){let f=[];for(let p of c._and)if(lr(p)){let h=r(n).select(`${n}.id`);await Pe(r,h,p,n,i,o,s),f.push({idSubquery:h})}else{let{fieldFilters:h,relationFilters:g}=V(p,i),m=await ar(r,n,i,o,s,g);f.push({fieldFilters:h,subqueries:m})}e.whereNot(function(){for(let p of f)oi(this,p,n,i,o)});return}if(c._or&&Array.isArray(c._or)&&c._or.length>0){let f=await ir(c._or,r,n,i,o,s);e.whereNot(function(){or(this,f,n,i,o)});return}let{fieldFilters:d,relationFilters:l}=V(c,i);e.whereNot(function(){Object.keys(d).length>0&&le(this,d,n,o,i)});for(let[f,p]of Object.entries(l)){let h=await Bt(r,n,f,p,i,o,s);if(h===null){let g=i.relations.find(m=>m.propertyName===f);if(g&&g.foreignKeyColumn){let m=sr(n,g.foreignKeyColumn,o),b=p.id;if(b&&typeof b=="object"){let w=rt(b._is_null),C=rt(b._is_not_null);if(w===!0)e.whereRaw(`${m} IS NOT NULL`);else if(w===!1)e.whereRaw(`${m} IS NULL`);else if(C===!0)e.whereRaw(`${m} IS NULL`);else if(C===!1)e.whereRaw(`${m} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${m} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${m} = ?`,[b._neq]);else if(b._in!==void 0){let T=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${m} NOT IN (${T.map(()=>"?").join(", ")})`,T)}else if(b._not_in!==void 0||b._nin!==void 0){let T=b._not_in??b._nin,k=Array.isArray(T)?T:[T];e.whereRaw(`${m} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${h})`)}return}let{fieldFilters:a,relationFilters:u}=V(t,i);Object.keys(a).length>0&&le(e,a,n,o,i);for(let[c,d]of Object.entries(u)){let l=await Bt(r,n,c,d,i,o,s);if(l===null){let f=i.relations.find(p=>p.propertyName===c);if(f&&f.foreignKeyColumn){let p=sr(n,f.foreignKeyColumn,o),g=d.id;if(g&&typeof g=="object"){let m=rt(g._is_null),y=rt(g._is_not_null);if(m===!0)e.whereRaw(`${p} IS NULL`);else if(m===!1)e.whereRaw(`${p} IS NOT NULL`);else if(y===!0)e.whereRaw(`${p} IS NOT NULL`);else if(y===!1)e.whereRaw(`${p} IS NULL`);else if(g._eq!==void 0)e.whereRaw(`${p} = ?`,[g._eq]);else if(g._neq!==void 0)e.whereRaw(`${p} != ?`,[g._neq]);else if(g._in!==void 0){let b=Array.isArray(g._in)?g._in:[g._in];e.whereRaw(`${p} IN (${b.map(()=>"?").join(", ")})`,b)}else if(g._not_in!==void 0||g._nin!==void 0){let b=g._not_in??g._nin,w=Array.isArray(b)?b:[b];e.whereRaw(`${p} NOT IN (${w.map(()=>"?").join(", ")})`,w)}}}}else e.whereRaw(`EXISTS (${l})`)}}async function Lt(r,e,t,n,i,o,s){await Pe(r,e,t,n,i,o,s)}ae();ae();function it(r,e,t,n,i){for(let o of e){let s=o.field.split("."),a=t||s[0],u=s[s.length-1],c=Dt(n,a,u,o.value);switch(o.operator){case"=":r=r.where(o.field,"=",c);break;case"!=":r=r.where(o.field,"!=",c);break;case">":r=r.where(o.field,">",c);break;case"<":r=r.where(o.field,"<",c);break;case">=":r=r.where(o.field,">=",c);break;case"<=":r=r.where(o.field,"<=",c);break;case"like":r=r.where(o.field,"like",c);break;case"in":let d=Array.isArray(o.value)?o.value.map(g=>Dt(n,a,u,g)):[c];r=r.whereIn(o.field,d);break;case"not in":let l=Array.isArray(o.value)?o.value.map(g=>Dt(n,a,u,g)):[c];r=r.whereNotIn(o.field,l);break;case"is null":r=r.whereNull(o.field);break;case"is not null":r=r.whereNotNull(o.field);break;case"_contains":r=r.where(o.field,"like",`%${o.value}%`);break;case"_starts_with":r=r.where(o.field,"like",`${o.value}%`);break;case"_ends_with":r=r.where(o.field,"like",`%${o.value}`);break;case"_between":let f=o.value;if(typeof f=="string"&&(f=f.split(",").map(g=>g.trim())),Array.isArray(f)&&f.length===2){let g=Dt(n,a,u,f[0]),m=Dt(n,a,u,f[1]);r=r.whereBetween(o.field,[g,m])}break;case"_is_null":r=c===!0||c==="true"?r.whereNull(o.field):r.whereNotNull(o.field);break;case"_is_not_null":r=c===!0||c==="true"?r.whereNotNull(o.field):r.whereNull(o.field);break}}return r}function Wt(r,e,t,n){let i=[],o=t;if(!r||typeof r!="object")return i;for(let[s,a]of Object.entries(r))if(s==="_and"&&Array.isArray(a)){let u=a.map(c=>{let d=Wt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&i.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(c=>{let d=Wt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&i.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=Wt(a,e,t,n);u.length>0&&i.push(`NOT (${u.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[u,c]of Object.entries(a)){let d=`${v(e,n)}.${v(s,n)}`,l;if(c===null)l="NULL";else if(typeof c=="string"){let f=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,p=o.columns?.find(g=>g.name===s);p&&(p.type?.toLowerCase()==="uuid"||p.type?.toLowerCase().includes("uuid"))&&f.test(c)&&n==="postgres"?l=`'${c}'::uuid`:l=`'${c.replace(/'/g,"''")}'`}else typeof c=="boolean"?l=c?"true":"false":typeof c=="number"?l=String(c):l=`'${String(c).replace(/'/g,"''")}'`;if(u==="_eq")i.push(`${d} = ${l}`);else if(u==="_neq")i.push(`${d} != ${l}`);else if(u==="_gt")i.push(`${d} > ${l}`);else if(u==="_gte")i.push(`${d} >= ${l}`);else if(u==="_lt")i.push(`${d} < ${l}`);else if(u==="_lte")i.push(`${d} <= ${l}`);else if(u==="_is_null")i.push(`${d} IS NULL`);else if(u==="_is_not_null")i.push(`${d} IS NOT NULL`);else if(u==="_in"){let p=(Array.isArray(c)?c:[c]).map(h=>typeof h=="string"?`'${h.replace(/'/g,"''")}'`:String(h)).join(", ");i.push(`${d} IN (${p})`)}else if(u==="_not_in"||u==="_nin"){let p=(Array.isArray(c)?c:[c]).map(h=>typeof h=="string"?`'${h.replace(/'/g,"''")}'`:String(h)).join(", ");i.push(`${d} NOT IN (${p})`)}else if(u==="_contains"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${d}) LIKE '%${f.toLowerCase()}%'`)}else if(u==="_starts_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE lower(unaccent('${f}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${d}) LIKE '${f.toLowerCase()}%'`)}else if(u==="_ends_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}'))`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci)`):i.push(`lower(${d}) LIKE '%${f.toLowerCase()}'`)}else if(u==="_between"&&Array.isArray(c)&&c.length===2){let f=typeof c[0]=="string"?`'${c[0].replace(/'/g,"''")}'`:String(c[0]),p=typeof c[1]=="string"?`'${c[1].replace(/'/g,"''")}'`:String(c[1]);i.push(`${d} BETWEEN ${f} AND ${p}`)}}else{let u=`${v(e,n)}.${v(s,n)}`,c;a===null?c="NULL":typeof a=="string"?c=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?c=a?"true":"false":c=String(a),i.push(`${u} = ${c}`)}return i}function Kt(r){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Dt(r,e,t,n){if(n==null)return n;let i=r?.tables?.get(e);if(!i?.columns)return n;let o=i.columns.find(s=>s.name===t);if(!o)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;default:return n}}ur();Je();ae();qt();Ke();async function li(r,e,t,n,i,o,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(fr(),ai)),u=await a(e,t,n,i,o,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function pr(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 ci(r,e,t,n,i){let o=r.targetTableName||r.targetTable;if(!o)return null;let s=r.foreignKeyColumn||J(r.propertyName);if(!s)return null;let a=l=>v(l,i),u=n?.tables?.get(o),d=(u?H(u):null)?.name||"id";return`(SELECT ${a(o)}.${a(e)} FROM ${a(o)} WHERE ${a(o)}.${a(d)} = ${a(t)}.${a(s)})`}qt();var je=class r{constructor(e,t,n,i){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=i;this.logger=new Sn(r.name);this.debugLog=[]}async execute(e){let t=performance.now();this.metadata=e.metadata;let n=e.debugLog||[];this.debugLog=n;let i=e.debugTrace;if(e.filter&&re(e.filter,e.tableName,e.metadata),!e.plan){let _=new Z;e={...e,plan:_.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:this.dbType})}}let o=e.plan,s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,u=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,c=o.rawFields&&o.rawFields.length>0&&!o.rawFields.includes("*");if(o.joins.length===0&&!o.hasRelationFilters&&!o.hasRelationSort&&!u&&!a&&c){i&&i.setQueryPath("simple");let _=await this.executeSimple(e,o);return i&&i.dur("sql_executor",t,{table:e.tableName}),_}let l={table:e.tableName,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?l.fields=e.fields:typeof e.fields=="string"&&(l.fields=e.fields.split(",").map(_=>_.trim())));let f=e.filter;if(e.filter&&!he(e.filter)){l.where=[];for(let[_,R]of Object.entries(e.filter))if(typeof R=="object"&&R!==null)for(let[F,ee]of Object.entries(R)){let M;if(F==="_eq")M="=";else if(F==="_neq")M="!=";else if(F==="_in")M="in";else if(F==="_not_in"||F==="_nin")M="not in";else if(F==="_gt")M=">";else if(F==="_gte")M=">=";else if(F==="_lt")M="<";else if(F==="_lte")M="<=";else if(F==="_contains")M="_contains";else if(F==="_starts_with")M="_starts_with";else if(F==="_ends_with")M="_ends_with";else if(F==="_between")M="_between";else if(F==="_is_null")M="_is_null";else if(F==="_is_not_null")M="_is_not_null";else if(F==="_like")M="like";else if(F==="_ilike")M="ilike";else continue;l.where.push({field:_,operator:M,value:ee})}else l.where.push({field:_,operator:"=",value:R})}if(e.sort){let _=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(R=>R.trim());l.sort=_.map(R=>{let F=R.trim();return F.startsWith("-")?{field:F.substring(1),direction:"desc"}:{field:F,direction:"asc"}})}else l.sort=[{field:"id",direction:"asc"}];let p=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,h=p===void 0||Number.isNaN(p)?void 0:p<0?0:p,g=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,m=g===void 0||Number.isNaN(g)?void 0:g;m&&h!==void 0?(l.offset=(m-1)*h,l.limit=h):h!==void 0&&(l.limit=h);let y=e.plan?.sortItems??(l.sort??[]).map(_=>({joinId:null,field:_.field,direction:_.direction,fullPath:_.field})),b=[],w=[];for(let _ of y){if(_.function==="count"){let R={sql:this.buildRelationCountSortSubquery(l.table,_),direction:_.direction};w.push(R);continue}if(_.function==="max"||_.function==="min"){let R={sql:this.buildRelationAggregateSortSubquery(l.table,_),direction:_.direction};w.push(R);continue}if(_.joinId===null){if(_.field.includes(".")&&!e.plan){let F=_.field.split(".")[0];if(this.metadata?.tables?.get(l.table)?.relations?.some(U=>U.propertyName===F))continue}let R={field:_.field.includes(".")?_.field:`${l.table}.${_.field}`,direction:_.direction};b.push(R),w.push(R)}else{let R=e.plan?.joins.find(F=>F.id===_.joinId);if(R&&(R.relationType==="many-to-one"||R.relationType==="one-to-one")){let F=ci(R.relationMeta,_.field,l.table,this.metadata,this.dbType);if(F){let ee={sql:F,direction:_.direction};w.push(ee)}}}}let C=[];if(l.fields&&l.fields.length>0||u||a){let _=pr(this.metadata),R=l.fields&&l.fields.length>0?l.fields:["*"],F=await li(this.knex,l.table,R,_,this.dbType,this.maxQueryDepth,e.deep);F.select.length>0&&(l.select=[...l.select||[],...F.select]),C=F.batchFetchDescriptors||[]}l.where&&(l.where=l.where.map(_=>_.field.includes(".")?_:{..._,field:`${l.table}.${_.field}`})),l.sort=b;let T=this.knex(l.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(_=>_.trim()).filter(Boolean),x=k.includes("filterCount")||k.includes("*"),$=k.includes("totalCount")||k.includes("*");if(l.select){let _=l.select.map(R=>typeof R=="string"&&R.trim().startsWith("(")?this.knex.raw(R):typeof R=="string"&&/ as /i.test(R)?this.knex.raw(R):R);T=T.select(_)}if(x&&T.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),$){let _=v(l.table,this.dbType);T.select(this.knex.raw(`(SELECT COUNT(*) FROM ${_}) as __total_count__`))}let I=["table_definition","column_definition","relation_definition","method_definition"].includes(l.table);if(f&&(he(f)||Object.keys(f).length>0)){let _=this.metadata?.tables?.get(l.table);(!I&&_&&_.relations&&_.relations.length>0?V(f,_).hasRelations:!1)?await Lt(this.knex,T,f,l.table,_,this.dbType,F=>this.metadata?.tables?.get(F)):e.plan?.filterTree?ce(T,e.plan.filterTree,{dbType:this.dbType,rootTable:l.table}):(this.logger.debug(`buildWhereClause fallback for table=${l.table}`),T=le(T,f,l.table,this.dbType,_))}else l.where&&l.where.length>0&&(T=it(T,l.where,l.table,this.metadata,this.dbType));for(let _ of w)if(_.field){let R=_.field.includes(".")?_.field:`${l.table}.${_.field}`;T=T.orderBy(R,_.direction)}else _.sql&&(T=T.orderByRaw(`${_.sql} ${_.direction.toUpperCase()}`));l.groupBy&&(T=T.groupBy(l.groupBy)),l.offset&&(T=T.offset(l.offset)),l.limit!==void 0&&l.limit!==null&&l.limit>0&&(T=T.limit(l.limit));let B=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:l.table,sql:T.toSQL().toNative()});let S;if(e.debugMode&&(S=T.toSQL().toNative().sql),e.debugMode&&i){let _=T.toSQL().toNative();i.setSql(_.sql);try{let R=_.sql.replace(/\$\d+/g,"?"),F=await this.knex.raw(`EXPLAIN ${R}`,_.bindings);i.setExplain(this.dbType==="postgres"?F.rows:F[0])}catch(R){i.setExplain({error:String(R)})}}let E,A=performance.now();E=await T,i&&i.dur("db_execute",A,{table:e.tableName});let L=0;if(x&&E.length>0&&(L=Number(E[0].__filter_count__||0),E.forEach(_=>{delete _.__filter_count__})),$&&E.length>0&&E[0].__total_count__!==void 0&&(B=Number(E[0].__total_count__||0),E.forEach(_=>{delete _.__total_count__})),C&&C.length>0&&E.length>0){let _=pr(this.metadata);if(_){let{executeBatchFetches:R}=await Promise.resolve().then(()=>(mr(),ui));await R(this.knex,E,C,_,this.maxQueryDepth??3,0,l.table,this.dbType,this.metadata,i)}}if(this.knexService){let _=performance.now();E=await this.knexService.parseResult(E,l.table),i&&i.dur("db_parseResult",_,{table:e.tableName})}else{let _=(R,F)=>{if(!R||!this.metadata)return R;let ee=this.metadata.tables?.get(F);if(!ee)return R;if(Array.isArray(R))return R.map(U=>_(U,F));if(typeof R!="object"||Buffer.isBuffer(R))return R;let M={...R};for(let U of ee.columns)if(U.type==="simple-json"&&M[U.name]&&typeof M[U.name]=="string")try{M[U.name]=JSON.parse(M[U.name])}catch{}for(let[U,G]of Object.entries(M))if(G&&typeof G=="object"&&!Array.isArray(G)&&!Buffer.isBuffer(G)){let Mn=G;if(Mn.id!==void 0||Mn.createdAt!==void 0){let lt=ee.relations?.find(ct=>ct.propertyName===U);lt&&(M[U]=_(G,lt.targetTableName))}}else if(Array.isArray(G)&&G.length>0&&typeof G[0]=="object"&&G[0].id!==void 0){let lt=ee.relations?.find(ct=>ct.propertyName===U);lt&&(M[U]=G.map(ct=>_(ct,lt.targetTableName)))}return M};E=_(E,l.table)}return i&&(i.setQueryPath("full"),i.dur("sql_executor",t,{table:e.tableName})),{data:E,...k.length>0&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:B}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:L}:{}}},...S!==void 0&&{sql:S}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=H(s)?.name||"id",u=v(e,this.dbType),c=v(a,this.dbType);if(!n||!o)throw new N(`Sort relation '${i}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let d=n.foreignKeyColumn||n.mappedBy;if(!d)throw new N(`Sort function '_count(${i})' cannot resolve relation key on '${e}'.`);let l=v(o,this.dbType),f=v(d,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}if(n.type==="many-to-many"){let d=this.resolveManyToManyContract(n,i,e),l=v(d.tableName,this.dbType),f=v(d.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}throw new N(`Sort function '_count(${i})' is only supported for list relations on '${e}'.`)}buildRelationAggregateSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=t.aggregateField,s=n?.targetTableName||n?.targetTable,a=this.metadata?.tables?.get(e),u=this.metadata?.tables?.get(s),c=H(a)?.name||"id",d=H(u)?.name||"id",l=v(e,this.dbType),f=v(c,this.dbType),p=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!p||!n||!s||!o)throw new N(`Sort function '${t.field}' is not supported on '${e}'.`);let h=v(s,this.dbType),g=v(o,this.dbType);if(n.type==="one-to-many"){let m=n.foreignKeyColumn||n.mappedBy;if(!m)throw new N(`Sort function '_${t.function}(${i}.${o})' cannot resolve relation key on '${e}'.`);let y=v(m,this.dbType);return`(SELECT ${p}(${h}.${g}) FROM ${h} WHERE ${h}.${y} = ${l}.${f})`}if(n.type==="many-to-many"){let m=this.resolveManyToManyContract(n,i,e),y=v(m.tableName,this.dbType),b=v(m.sourceColumn,this.dbType),w=v(m.targetColumn,this.dbType),C=v(d,this.dbType);return`(SELECT ${p}(${h}.${g}) FROM ${y} JOIN ${h} ON ${h}.${C} = ${y}.${w} WHERE ${y}.${b} = ${l}.${f})`}throw new N(`Sort function '_${t.function}(${i}.${o})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,n){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new N(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async executeSimple(e,t){let n=e.tableName,i=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],o=this.knex(n).select(i);t.filterTree&&ce(o,t.filterTree,{dbType:this.dbType,rootTable:n});for(let g of t.sortItems){let m=g.field.includes(".")?g.field:`${n}.${g.field}`;o=o.orderBy(m,g.direction)}t.limit!==void 0&&t.limit!==null&&t.limit>0&&(o=o.limit(t.limit)),t.offset!==void 0&&(o=o.offset(t.offset));let s=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(g=>g.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),u=s.includes("totalCount")||s.includes("*");if(a&&o.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),u){let g=v(n,this.dbType);o.select(this.knex.raw(`(SELECT COUNT(*) FROM ${g}) as __total_count__`))}let c=e.debugTrace,d;if(e.debugMode){let g=o.toSQL().toNative();if(d=g.sql,c){c.setSql(g.sql);try{let m=g.sql.replace(/\$\d+/g,"?"),y=await this.knex.raw(`EXPLAIN ${m}`,g.bindings);c.setExplain(this.dbType==="postgres"?y.rows:y[0])}catch(m){c.setExplain({error:String(m)})}}}let l=performance.now(),f;f=await o,c&&c.dur("db_execute",l,{table:n}),this.knexService&&(f=await this.knexService.parseResult(f,n));let p=0,h=0;return a&&f.length>0&&(p=Number(f[0].__filter_count__||0),f.forEach(g=>delete g.__filter_count__)),u&&f.length>0&&(h=Number(f[0].__total_count__||0),f.forEach(g=>delete g.__total_count__)),{data:f,...s.length>0&&{meta:{...u?{totalCount:h}:{},...a?{filterCount:p}:{}}},...d!==void 0&&{sql:d}}}async aggregate(e){let t=tt(e.aggregate,e.tableName,e.metadata),n=this.knex(e.tableName),i=v(e.tableName,this.dbType),o=[],s=[];for(let l of t.dimensions){let f=`${i}.${v(l.field,this.dbType)}`,p=l.bucket?this.buildSqlBucketExpression(f,l.bucket,l.timezone,l.column.type):f;s.push(this.knex.raw(`${p} as ${v(l.outputKey,this.dbType)}`)),o.push(p)}for(let l of t.measures){let f=`${i}.${v(l.field,this.dbType)}`,p=l.operation==="count"?`COUNT(${f})`:l.operation==="countDistinct"?`COUNT(DISTINCT ${f})`:`${l.operation.toUpperCase()}(${f})`;s.push(this.knex.raw(`${p} as ${v(l.outputKey,this.dbType)}`))}let u=new Z().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:this.dbType});u.hasRelationFilters?await Lt(this.knex,n,t.filter,e.tableName,e.metadata?.tables?.get(e.tableName),this.dbType,l=>e.metadata?.tables?.get(l)):u.filterTree&&ce(n,u.filterTree,{dbType:this.dbType,rootTable:e.tableName}),n.select(s),o.length>0&&n.groupByRaw(o.join(", "));for(let l of t.sort)n.orderByRaw(`${v(l.field,this.dbType)} ${l.direction.toUpperCase()}`);return t.limit!==void 0&&n.limit(t.limit).offset((t.page-1)*t.limit),{data:(await n).map(l=>{let f={...l};for(let p of t.measures){let h=f[p.outputKey];h!=null&&typeof h=="string"&&/^-?\d+(\.\d+)?$/.test(h)&&(f[p.outputKey]=Number(h))}return f})}}buildSqlBucketExpression(e,t,n,i){let o=Kt(n);if(this.dbType==="postgres"){let s=`(${e} AT TIME ZONE ${o})`;return`DATE_TRUNC(${Kt(t)}, ${s})`}if(this.dbType==="mysql"){let s=`CONVERT_TZ(${e}, '+00:00', ${o})`;return t==="year"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-01-01'), '%Y-%m-%d')`:t==="month"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-01'), '%Y-%m-%d')`:t==="week"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%u-1'), '%Y-%u-%d')`:t==="day"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-%d'), '%Y-%m-%d')`:`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-%d %H:00:00'), '%Y-%m-%d %H:%i:%s')`}throw new N(`Aggregate time bucket is not supported on ${this.dbType}`)}};var xn=require("mongodb"),at=class{constructor(e){this.debugLog=[];this.batchInserts={items:[],flushing:!1};this.knexService=e.knexService,this.mongoService=e.mongoService,this.databaseConfigService=e.databaseConfigService,this.runtimeMetricsCollectorService=e.runtimeMetricsCollectorService,this.lazyRef=e.lazyRef,this.dbType=this.databaseConfigService.getDbType(),this.batchInsertMaxSize=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_SIZE",100),this.batchInsertMaxWaitMs=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_WAIT_MS",100),this.batchInsertConcurrency=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_CONCURRENCY",5),this.batchInsertTraceFile=process.env.QUERY_BUILDER_BATCH_TRACE_FILE||process.env.DYNAMIC_CREATE_BATCH_TRACE_FILE,this.batchInsertTraceFile&&(0,vn.mkdirSync)((0,di.dirname)(this.batchInsertTraceFile),{recursive:!0})}async runWithPolicy(e,t){return this.knexService?this.knexService.runWithPolicy(e,t):this.mongoService?this.mongoService.runWithPolicy(e,t):t()}async runWithFieldPermissionCheck(e,t){return this.knexService?this.knexService.runWithFieldPermissionCheck(e,t):this.mongoService?this.mongoService.runWithFieldPermissionCheck(e,t):t()}async runWithTelemetryContext(e,t){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.runWithQueryContext(e,t):await t()}getDbType(){return this.dbType}safeObjectId(e){if(!xn.ObjectId)return e;if(typeof e=="string")try{return new xn.ObjectId(e)}catch{return e}return e}async getMetadataForQuery(){let e={tables:new Map,tablesList:[]},t=this.lazyRef.metadataCacheService;return t?t.isLoaded?.()?await t.getMetadata?.()??e:t.getDirectMetadata?.()??e:e}async buildMongoFilter(e,t){let n=await this.getMetadataForQuery(),i=Qe(n,e,t,this.dbType);return i._id!==void 0&&(i._id=this.safeObjectId(i._id)),i}async applyWhereToKnex(e,t,n){let i=await this.getMetadataForQuery();return{query:it(e,t,n??"",i,this.dbType)}}async runMongoMutationInSaga(e){return!this.mongoService?.runInSaga||this.mongoService.isInSaga?.()?e():(await this.mongoService.runInSaga(e)).data}async insertWithOptions(e){if(e.batch)return await this.insertManyBatch(e.table,e.data);if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{if(Array.isArray(e.data)){let t=[];for(let n of e.data){let i=await this.mongoService.insertOne(e.table,n);t.push(Y(i))}return t}return this.mongoService.insertOne(e.table,e.data)});if(Array.isArray(e.data)){let t=[];for(let n of e.data){let i=await this.knexService.insertWithCascade(e.table,n);t.push(i)}return t}else return await this.knexService.insertWithCascade(e.table,e.data)}async select(e){let t=performance.now(),n=await this.getMetadataForQuery(),i=performance.now(),s=new Z().plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:n,dbType:this.dbType}),a=e.debugTrace;if(a&&(a.dur("qb_planner",i,{table:e.tableName}),a.setPlan(this.sanitizePlan(s))),this.dbType==="mongodb"){let l=await new Ae(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}let c=await new je(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:n,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),c}sanitizePlan(e){return{rawFields:e.rawFields,hasRelationFilters:e.hasRelationFilters,hasRelationSort:e.hasRelationSort,joins:e.joins?.length??0,sortItems:e.sortItems,limit:e.limit,offset:e.offset,page:e.page,isSimpleQuery:e.joins?.length===0&&!e.hasRelationFilters&&!e.hasRelationSort}}async updateWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),s=this.mongoService.collection(e.table),a=this.mongoService.ioSignalPublic?.()??{},u=await s.find(o,a).toArray(),c=[];for(let d of u){let l=await this.mongoService.updateOne(e.table,d._id,e.data);c.push(l)}return c});let t=this.knexService.getKnex(),n=t(e.table);e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n;for(let o of i)await this.knexService.updateWithCascade(e.table,o.id,e.data);if(e.returning){let o=t(e.table);return e.where.length>0&&await this.applyWhereToKnex(o,e.where,e.table),await o.select(e.returning)}return{affected:i.length}}async deleteWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let i=await this.buildMongoFilter(e.where,e.table),o=this.mongoService.collection(e.table),s=this.mongoService.ioSignalPublic?.()??{},a=await o.find(i,s).toArray(),u=0;for(let c of a)await this.mongoService.deleteOne(e.table,c._id)&&u++;return u});let n=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table)),await n.delete()}async count(e){if(this.dbType==="mongodb"){let o=e.where?await this.buildMongoFilter(e.where,e.table):{};return this.mongoService.count(e.table,o)}let n=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n.count("* as count").first();return Number(i?.count||0)}whereToFilter(e){let t={},n=this.databaseConfigService.isMongoDb();for(let[i,o]of Object.entries(e))i==="id"||i==="_id"?n?t._id=this.normalizeWhereFilterValue("_id",o):t.id=this.normalizeWhereFilterValue("id",o):t[i]=this.normalizeWhereFilterValue(i,o);return t}normalizeWhereFilterValue(e,t){return this.isFilterOperatorObject(t)?this.databaseConfigService.isMongoDb()&&e==="_id"?this.normalizeMongoIdOperatorValue(t):t:{_eq:this.databaseConfigService.isMongoDb()&&e==="_id"?this.safeObjectId(t):t}}isFilterOperatorObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof xn.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[n,i]of Object.entries(e))t[n]=Array.isArray(i)?i.map(o=>this.safeObjectId(o)):this.safeObjectId(i);return t}filterToWhere(e){let t=[];for(let[n,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let o=Object.entries(i)[0];if(o){let[s,a]=o,u=this.mapFilterOperatorToSql(s);t.push({field:n,operator:u,value:a})}}return t}mapFilterOperatorToSql(e){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"like",_starts_with:"like",_ends_with:"like",_is_null:"is null",_is_not_null:"is not null"}[e]||"="}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,maxQueryDepth:e.maxQueryDepth})})}async aggregate(e){return this.trackQueryMetric("aggregate",e.table,async()=>{let t=await this.getMetadataForQuery();return this.dbType==="mongodb"?new Ae(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).aggregate({tableName:e.table,aggregate:e.aggregate,metadata:t,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,dbType:this.dbType}):new je(this.knexService.getKnex(),this.dbType,this.knexService).aggregate({tableName:e.table,aggregate:e.aggregate,metadata:t,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t,n){return n?.batch?await this.insertManyBatch(e,t):this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let a=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return Y(a)}let i=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),s=i||t.id;return await o(e).where("id",s).first()})}async insertMany(e,t){return t.length===0?[]:this.trackQueryMetric("insert_many",e,async()=>this.dbType==="mongodb"?(await this.runMongoMutationInSaga(async()=>typeof this.mongoService.insertManyWithCascade=="function"?this.mongoService.insertManyWithCascade(e,t):Promise.all(t.map(i=>this.mongoService.insertOne(e,i))))).map(i=>Y(i)):this.knexService.insertManyWithCascade(e,t))}async flushBatchInserts(){for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)await this.flushBatchInsertBuffer()}async insertManyBatch(e,t){let n=Array.isArray(t)?t:[t];for(let i of n)this.batchInserts.items.push({table:e,data:i});return this.traceBatchInsert("enqueue",{tableName:e,count:n.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i)),{accepted:!0,batch:!0,count:n.length}}async flushBatchInsertBuffer(){if(this.batchInserts.flushing){await this.batchInserts.flushPromise;return}let e=this.batchInserts.items.splice(0,this.batchInserts.items.length);if(this.batchInserts.timer&&(clearTimeout(this.batchInserts.timer),this.batchInserts.timer=void 0),e.length===0)return;this.batchInserts.flushing=!0;let t=this.executeBatchInsertFlush(e);this.batchInserts.flushPromise=t,await t}async executeBatchInsertFlush(e){let t=Date.now();try{let n=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...n.entries()].map(([i,o])=>({tableName:i,count:o.length}))}),await this.runLimited([...n.entries()],([i,o])=>this.flushBatchInsertTable(i,o)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}finally{this.batchInserts.flushing=!1,this.batchInserts.flushPromise=void 0,this.batchInserts.items.length>0&&(this.batchInserts.timer&&clearTimeout(this.batchInserts.timer),this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(n=>this.logBatchInsertError("QueryBuilder batch insert flush failed",n))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let n=Date.now();await this.runBatchInsertWithIsolation(e,t),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-n})}async runBatchInsertWithIsolation(e,t){if(t.length!==0)try{await(async()=>{if(this.dbType==="mongodb"){await this.runMongoMutationInSaga(async()=>{if(typeof this.mongoService?.insertManyWithCascade=="function"){await this.mongoService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.mongoService.insertOne(e,i.data)))});return}if(typeof this.knexService?.insertManyWithCascade=="function"){await this.knexService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.knexService.insertWithCascade(e,i.data)))})()}catch(n){if(t.length===1){this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,n);return}let i=Math.ceil(t.length/2);await Promise.all([this.runBatchInsertWithIsolation(e,t.slice(0,i)),this.runBatchInsertWithIsolation(e,t.slice(i))])}}groupBatchInsertsByTable(e){let t=new Map;for(let n of e){let i=t.get(n.table);i?i.push(n):t.set(n.table,[n])}return t}async runLimited(e,t){let n=0,i=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;n<e.length;){let o=e[n++];await t(o)}});await Promise.all(i)}readPositiveEnv(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.trunc(n):t}traceBatchInsert(e,t){this.batchInsertTraceFile&&(0,vn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
|
|
53
|
+
`)}logBatchInsertError(e,t){let n=t?.message||String(t);this.traceBatchInsert("error",{message:e,error:n,code:t?.code,detail:t?.detail}),console.error(`${e}: ${n}`)}async update(e,t,n){return this.trackQueryMetric("update",e,async()=>{if(t&&typeof t=="object"&&"where"in t)return await this.updateWithOptions({table:e,where:t.where,data:n});if(this.dbType==="mongodb"){let o=await this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n));return Y(o)}return await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first()})}async updateMany(e,t,n,i=this.getPkField()){return t.length===0?0:this.trackQueryMetric("update_many",e,async()=>{if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let a=this.mongoService.collection(e),u=this.mongoService.ioSignalPublic?.()??{};return(await a.updateMany({[i]:{$in:t}},{$set:n},u)).modifiedCount});let s=await this.knexService.getKnex()(e).whereIn(i,t).update(n);return typeof s=="number"?s:0})}async delete(e,t){return this.trackQueryMetric("delete",e,async()=>t&&typeof t=="object"&&"where"in t?await this.deleteWithOptions({table:e,where:t.where})>0:this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t)):await this.knexService.getKnex()(e).where("id",t).delete()>0)}async deleteMany(e,t,n=this.getPkField()){return t.length===0?0:this.trackQueryMetric("delete_many",e,async()=>{if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let s=this.mongoService.collection(e),a=this.mongoService.ioSignalPublic?.()??{},u=await s.find({[n]:{$in:t}},a).toArray(),c=0;for(let d of u)await this.mongoService.deleteOne(e,d._id)&&c++;return c});let o=await this.knexService.getKnex()(e).whereIn(n,t).delete();return typeof o=="number"?o:0})}async countRecords(e,t){if(this.dbType==="mongodb")return this.mongoService.count(e,t||{});let i=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.filterToWhere(t);({query:i}=await this.applyWhereToKnex(i,s,e))}let o=await i.count("* as count").first();return Number(o?.count||0)}async transaction(e){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>e(this.mongoService)):this.knexService.transaction(e)}async findById(e,t){if(this.dbType==="mongodb"){let i=this.safeObjectId(t);return this.mongoService.findOne(e,{_id:i})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[o,s]of Object.entries(t))o==="id"||o==="_id"?i._id=this.safeObjectId(s):i[o]=s;return this.mongoService.findOne(e,i)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[u,c]of Object.entries(t))u==="id"||u==="_id"?i._id=this.safeObjectId(c):i[u]=c;let o=this.mongoService.collection(e),s=this.mongoService.ioSignalPublic?.()??{};return await o.find(i,s).toArray()}return await this.knexService.getKnex()(e).where(t)}async insertAndGet(e,t){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));let n=await this.knexService.insertWithCascade(e,t),i=this.knexService.getKnex(),o=n||t.id;return await i(e).where("id",o).first()}async updateById(e,t,n){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n)):(await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first())}async deleteById(e,t){return this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t))?1:0:this.knexService.getKnex()(e).where("id",t).delete()}async raw(e,t){let n=this.dbType==="mongodb"?"mongodb":"sql";return this.trackQueryMetric("raw",n,async()=>{if(this.dbType==="mongodb"){let o=this.mongoService.getDb();if(typeof e=="string"){if(e.toLowerCase().includes("select 1"))return await o.command({ping:1});throw new Error("String queries not supported for MongoDB. Use db.command() object instead.")}return await o.command(e)}return await this.knexService.getKnex().raw(e,t)})}async trackQueryMetric(e,t,n){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.trackQuery({op:e,table:t},n):await n()}getConnection(){return this.dbType==="mongodb"?this.mongoService.getDb():this.knexService.getKnex()}getKnex(){if(this.dbType==="mongodb")throw new Error("getKnex() is not available for MongoDB. Use getConnection() or unified methods.");return this.knexService.getKnex()}getMongoDb(){if(this.dbType!=="mongodb")throw new Error("getMongoDb() is not available for SQL. Use getConnection() or unified methods.");return this.mongoService.getDb()}getDatabaseType(){return this.dbType}isMongoDb(){return this.dbType==="mongodb"}isSql(){return["mysql","postgres","mariadb","sqlite"].includes(this.dbType)}getPkField(){return this.isMongoDb()?"_id":"id"}getRecordId(e){return this.isMongoDb()?e._id:e.id}};mr();gr();fr();ae();qt();Ge();bn();de();Je();var fi=new Set(["fields","filter","sort","limit","page","deep"]),Nn=3;function yr(r,e,t,n=0,i=3){if(!e||typeof e!="object")return;if(n>=i)throw new N(`deep option exceeds maximum query depth of ${i}`);let o=t?.tables?.get(r),s=new Map((o?.relations??[]).map(a=>[a.propertyName,a]));for(let[a,u]of Object.entries(e)){let c=s.get(a);if(!c)throw new N(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let f of Object.keys(u))if(!fi.has(f))throw new N(`Unknown deep option key '${f}' for relation '${a}'. Allowed: ${[...fi].join(", ")}`);let d=c.type;if(u.limit!==void 0&&(d==="many-to-one"||d==="one-to-one"))throw new N(`'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 N(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let l=c.targetTableName||c.targetTable;if(l){if(u.filter&&(re(u.filter,l,t),Oe(u.filter,l,t),In(u.filter,0,a,r)),u.sort){Tn(u.sort,l,t);let f=Array.isArray(u.sort)?u.sort:String(u.sort).split(",").map(p=>p.trim()).filter(Boolean);for(let p of f){let h=p.startsWith("-")?p.slice(1):p;Uo(h,l,t,a,r)}}u.deep&&yr(l,u.deep,t,n+1,i)}}}function Uo(r,e,t,n,i){if(r.includes("."))throw new N(`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 N(`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 N(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${i}')`)}var Qo=new Set(["_and","_or","_not"]);function In(r,e,t,n){if(!(!r||typeof r!="object"))for(let[i,o]of Object.entries(r)){if(Qo.has(i)){if(Array.isArray(o))for(let c of o)In(c,e,t,n);else o&&typeof o=="object"&&In(o,e,t,n);continue}if(i.startsWith("_")||!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).some(c=>!c.startsWith("_")))continue;let a=e+1;if(a>Nn)throw new N(`Filter path exceeds max dotted hops of ${Nn} at '${i}' (relation '${t}' on '${n}')`);let u={};for(let c of Object.keys(o))c.startsWith("_")||(u[c]=o[c]);In(u,a,t,n)}}function pi(r,e,t,n){return!r||typeof r!="object"?r:Jt(r,e,t,n)}function Jt(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let o=r.map(s=>Jt(s,e,t,n)).filter(s=>s!=null);return o.length>0?o:null}let i={};for(let[o,s]of Object.entries(r)){if(o==="_and"||o==="_or"){let l=(Array.isArray(s)?s:[s]).map(f=>Jt(f,e,t,n)).filter(f=>f!=null&&Object.keys(f).length>0);l.length>0&&(i[o]=l);continue}if(o==="_not"){let d=Jt(s,e,t,n);d!=null&&Object.keys(d).length>0&&(i[o]=d);continue}let a=t?.tables?.get(e),u=a?.relations?.find(d=>d.propertyName===o);if(u){if(!n(e,o,"relation"))continue;let d=u.targetTableName||u.targetTable;if(!d)continue;let l=Jt(s,d,t,n);l!=null&&Object.keys(l).length>0&&(i[o]=l);continue}if(a?.columns?.find(d=>d.name===o)){if(!n(e,o,"column"))continue;i[o]=s;continue}i[o]=s}return i}function gi(r,e,t,n){if(!r)return r;let i=Array.isArray(r)?r:r.split(",").map(s=>s.trim()).filter(Boolean),o=[];for(let s of i){let c=(s.startsWith("-")?s.slice(1):s).split("."),d=!0,l=e;for(let f=0;f<c.length;f++){let p=c[f],h=f===c.length-1,g=t?.tables?.get(l);if(!g){d=!1;break}if(h)g.columns?.find(y=>y.name===p)?n(l,p,"column")||(d=!1):g.relations?.find(b=>b.propertyName===p)&&(n(l,p,"relation")||(d=!1));else{let m=g.relations?.find(y=>y.propertyName===p);if(!m){d=!1;break}if(!n(l,p,"relation")){d=!1;break}l=m.targetTableName||m.targetTable||l}}d&&o.push(s)}if(o.length!==0)return Array.isArray(r)?o:o.join(",")}Mt();Je();Et();cn();Ke();de();function Jo(r){let e=new at({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,i=()=>(t||(t=new We({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),o=()=>(n||(n=new Be({isolatedExecutorService:i()})),n);return{queryBuilderService:e,get isolatedExecutorService(){return i()},get executorEngineService(){return o()},async onDestroy(){await t?.onDestroy?.()}}}0&&(module.exports={ALL_SUPPORTED_OPERATORS,AuthenticationException,AuthorizationException,BadRequestException,BatchExecutionBudget,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,DEEP_TO_MANY_DEFAULT_LIMIT,DEFAULT_BATCH_FETCH_IO_CONCURRENCY,DEFAULT_TIMEOUT_MS,DOTTED_PATH_MAX_HOPS,DatabaseException,DuplicateResourceException,ErrorHandler,ExecutorEngineService,ExternalServiceException,FIELD_OPERATORS,FileNotFoundException,FileSizeExceededException,FileUploadException,HttpException,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH,InvalidTokenException,IsolatedExecutorService,JoinRegistry,LOGICAL_OPERATORS,MongoBatchAdapter,MongoQueryExecutor,PER_PARENT_CONCURRENCY,QueryBuilderService,QueryPlanner,ResourceNotFoundException,SchemaException,ScriptContractService,ScriptExecutionException,ScriptTimeoutException,ServiceUnavailableException,SqlBatchAdapter,SqlQueryExecutor,TokenExpiredException,ValidationException,WHERE_IN_CHUNK_SIZE,WorkerPool,appendIsolatedExecutorRuntimeLog,applyOperatorToMatch,applyRelationFilters,applyWhereToKnex,assertFieldOperatorValueIsClean,buildMongoCharFoldMapJson,buildMongoFoldTextSearchJs,buildRelationSubquery,buildSqlWherePartsFromFieldAst,buildWhereClause,camelToSnake,chunkedFetch,compileScriptSource,computeEngineTuning,createEnfyraKernel,dslOpToCompareOp,encodeMainThreadToIsolate,escapeSqlValue,executeBatchFetches,executeMongoBatchFetches,expandFieldsToJoinsAndSelect,getEffectiveCpuCount,getEffectiveMemoryBytes,getEngineTuning,getExecutableScript,getForeignKeyColumnName,getIoAbortSignal,getJunctionColumnNames,getJunctionTableName,getPrimaryKeyColumn,getScriptLegacyField,getShortFkConstraintName,getShortFkName,getShortIndexName,getShortPkName,hasLogicalOperators,isExecutableJavaScript,isScriptTable,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,perParentRun,quoteIdentifier,quoteQualifiedIdentifier,resolveExecutableScript,rewriteFilterDenyingFields,rewriteSortDroppingDenied,runWithIoAbortSignal,scriptContractService,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,validateDeepOptions,validateFilterShape,whereToMongoFilter});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@enfyra/kernel",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.53",
|
|
4
4
|
"description": "Closed-distribution Enfyra kernel runtime",
|
|
5
5
|
"license": "Elastic-2.0",
|
|
6
6
|
"packageManager": "yarn@4.17.0",
|
|
@@ -29,6 +29,8 @@
|
|
|
29
29
|
"scripts": {
|
|
30
30
|
"build": "node scripts/build.mjs",
|
|
31
31
|
"test:executor-error-metadata": "yarn build && node scripts/test-executor-error-metadata.mjs",
|
|
32
|
+
"test:executor-lanes": "yarn build && node scripts/test-executor-lane-tuning.mjs",
|
|
33
|
+
"bench:executor-lanes": "yarn build && node scripts/benchmark-executor-lanes.mjs",
|
|
32
34
|
"test:sql-identifiers": "yarn build && node scripts/test-sql-identifier-quoting.mjs",
|
|
33
35
|
"test:relation-aggregate-sort": "node scripts/test-relation-aggregate-sort.mjs",
|
|
34
36
|
"verify": "node scripts/verify-no-source-leak.mjs && node -e \"const k=require('./dist'); if (typeof k.createEnfyraKernel !== 'function') process.exit(1)\"",
|