@enfyra/kernel 1.1.61 → 1.1.63
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/execution/worker.js +31 -27
- package/dist/index.js +1 -1
- package/dist/package-metadata.json +1 -1
- package/package.json +1 -1
package/dist/execution/worker.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var ne=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ae=ne((Ye,re)=>{"use strict";var{fork:ve}=require("child_process"),be=require("path");function xe({workerDir:e,activeTaskContexts:t}){let s=new Map,n=new Map,r=new Map,i=new Map,o=null,y=0,f=1e3;function w(l){return Math.max(1,Math.trunc(Number(l)||3e4))}function b(l,a,c){let
|
|
1
|
+
"use strict";var ne=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ae=ne((Ye,re)=>{"use strict";var{fork:ve}=require("child_process"),be=require("path");function xe({workerDir:e,activeTaskContexts:t}){let s=new Map,n=new Map,r=new Map,i=new Map,o=null,y=0,f=1e3;function w(l){return Math.max(1,Math.trunc(Number(l)||3e4))}function b(l,a,c){let p=new Error(l);return p.code=a,p.details=c,p}function R(l,a){for(let[c,p]of n)p.child===l&&(clearTimeout(p.timer),n.delete(c),r.delete(c),p.reject(a))}function d(l){for(let[a,c]of i)c.child===l&&(clearTimeout(c.timer),i.delete(a))}function u(l,a){if(!l.connected)return;let c=`cancel_${++y}`,p=setTimeout(()=>{i.delete(c);try{l.kill()}catch{}},f);p.unref?.(),i.set(c,{child:l,timer:p});try{l.send({op:"cancelTask",taskId:a,id:c})}catch{clearTimeout(p),i.delete(c);try{l.kill()}catch{}}}function m(l){let a=typeof l=="string"?JSON.parse(l):l;if(a?.error)throw new Error(a.error);return a?.value}async function v(l){let a=t.get(l.taskId);if(!a)throw new Error(`Package callback context not found: ${l.taskId}`);let c=JSON.stringify(l.callbackId),p=JSON.stringify(l.argsJson||"[]"),h=await a.evalClosure(`return __invokeRuntimeCallback(${c}, ${p});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}});return m(h)}function k(){if(o&&o.connected)return o;let l=be.join(e,"package-runtime.child.js"),a=ve(l,[],{stdio:["ignore","ignore","ignore","ipc"],env:{PATH:process.env.PATH||"",HOME:process.env.HOME||"",NODE_ENV:process.env.NODE_ENV||"production",TMPDIR:process.env.TMPDIR||"",LANG:process.env.LANG||""}});return o=a,a.on("message",c=>{if(!c||!c.id)return;if(c.type==="pkgStreamChunk"){let h=r.get(c.id);if(!h)return;h.onChunk(Buffer.from(c.chunk||"","base64")).then(()=>{try{a.send({type:"pkgStreamAck",ackId:c.ackId})}catch{}}).catch(M=>{try{a.send({type:"pkgStreamError",ackId:c.ackId,error:{message:M.message,stack:M.stack}})}catch{}});return}if(c.type==="taskCancelled"){let h=i.get(c.id);if(!h||h.child!==a)return;clearTimeout(h.timer),i.delete(c.id);return}if(c.type==="pkgCallbackCall"){v(c).then(h=>{try{a.send({type:"pkgCallbackResult",id:c.id,value:h})}catch{}}).catch(h=>{try{a.send({type:"pkgCallbackError",id:c.id,error:{message:h.message,stack:h.stack}})}catch{}});return}let p=n.get(c.id);if(p)if(clearTimeout(p.timer),n.delete(c.id),r.delete(c.id),c.ok)p.resolve(c.value);else{c.error?.code==="ERR_PACKAGE_RUNTIME_TIMEOUT"&&u(a,p.taskId);let h=b(c.error?.message||"Package runtime call failed",c.error?.code,c.error?.details);h.stack=c.error?.stack||h.stack,p.reject(h)}}),a.on("exit",(c,p)=>{o===a&&(o=null),d(a),R(a,b(`Package runtime exited${p?` with signal ${p}`:` with code ${c}`}`,"ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}),a.on("error",c=>{o===a&&(o=null),d(a),R(a,b(c.message,"ERR_PACKAGE_RUNTIME_LOST",{outcome:"unknown_outcome",retryable:!1}))}),a}function P(l){return new Promise((a,c)=>{let p=k(),h=`pkg_${++y}`,M=w(l.timeoutMs),J=setTimeout(()=>{n.delete(h),r.delete(h),u(p,l.taskId),c(b(`Package runtime call timed out after ${M}ms`,"ERR_PACKAGE_RUNTIME_TIMEOUT",{outcome:"unknown_outcome",retryable:!1}))},M);n.set(h,{child:p,taskId:l.taskId,resolve:a,reject:c,timer:J});try{p.send({...l,id:h},I=>{I&&(clearTimeout(J),n.delete(h),c(I))})}catch(I){clearTimeout(J),n.delete(h),c(I)}})}function C(l,a,c,p=[],h=3e4){return new Promise((M,J)=>{let I=k(),N=`pkg_${++y}`,Q=w(h),ee=setTimeout(()=>{n.delete(N),r.delete(N),u(I,l),J(b(`Package runtime stream timed out after ${Q}ms`,"ERR_PACKAGE_RUNTIME_TIMEOUT",{outcome:"unknown_outcome",retryable:!1}))},Q);n.set(N,{child:I,taskId:l,resolve:M,reject:J,timer:ee}),r.set(N,{onChunk:c});try{I.send({op:"streamHandle",taskId:l,handleId:a,path:p,id:N,timeoutMs:Q},G=>{G&&(clearTimeout(ee),n.delete(N),r.delete(N),J(G))})}catch(G){clearTimeout(ee),n.delete(N),r.delete(N),J(G)}})}function D(l){try{if(!o||!o.connected)return;o.send({...l,id:`pkg_${++y}`,fire:!0})}catch{}}function _(l){try{if(!o||!o.connected)return;u(o,l)}catch{}}async function H(l,a){let c=s.get(l);if(!c)throw new Error("Package context is not available");if(a.handleId)return P({op:a.kind==="get"?"handleGet":"handleCall",taskId:l,handleId:a.handleId,path:a.path||[],argsJson:a.argsJson||"[]",timeoutMs:a.timeoutMs});let p=c.get(a.packageName);if(!p)throw new Error(`Package "${a.packageName}" is not available`);return P({op:a.kind==="construct"?"construct":"call",taskId:l,packageName:a.packageName,package:{name:p.name,fileUrl:p.fileUrl},path:a.path||[],argsJson:a.argsJson||"[]",timeoutMs:a.timeoutMs})}function g(l,a){s.set(l,a)}function x(l){s.delete(l),D({op:"releaseTask",taskId:l})}function $(){if(o){try{o.kill()}catch{}o=null}}return{cleanupTaskPackages:x,cancelTask:_,executePackageRuntimeCall:H,setTaskPackages:g,streamPackageHandle:C,shutdownPackageRuntime:$}}re.exports={createPackageRuntimeBridge:xe}});var oe=ne((Ze,se)=>{"use strict";var Pe=`
|
|
2
2
|
"use strict";
|
|
3
3
|
let $ctx = {};
|
|
4
4
|
let $pkgs = {};
|
|
@@ -311,56 +311,57 @@ async function __invokeRuntimeCallback(id, argsJson) {
|
|
|
311
311
|
|
|
312
312
|
const __safeCloneFailed = Symbol('__safeCloneFailed');
|
|
313
313
|
|
|
314
|
-
async function __safeClone(v, seen) {
|
|
314
|
+
async function __safeClone(v, seen, cyclic) {
|
|
315
315
|
if (!seen) {
|
|
316
|
-
const cloned = await __safeClone(v, new WeakSet());
|
|
316
|
+
const cloned = await __safeClone(v, new WeakSet(), new WeakSet());
|
|
317
317
|
return cloned === __safeCloneFailed ? null : cloned;
|
|
318
318
|
}
|
|
319
319
|
if (v === undefined) return undefined;
|
|
320
|
+
let tracked = false;
|
|
320
321
|
try {
|
|
321
322
|
if (v && typeof v.then === 'function') {
|
|
322
|
-
return await __safeClone(await v, seen);
|
|
323
|
+
return await __safeClone(await v, seen, cyclic);
|
|
323
324
|
}
|
|
324
325
|
if (v && typeof v === 'object') {
|
|
325
|
-
if (seen.has(v))
|
|
326
|
+
if (seen.has(v)) {
|
|
327
|
+
cyclic.add(v);
|
|
328
|
+
return null;
|
|
329
|
+
}
|
|
326
330
|
seen.add(v);
|
|
331
|
+
tracked = true;
|
|
327
332
|
}
|
|
328
333
|
if (v instanceof Date) return v.toISOString();
|
|
329
334
|
if (v instanceof Set) {
|
|
330
335
|
const out = [];
|
|
331
336
|
for (const item of v.values()) {
|
|
332
|
-
const cloned = await __safeClone(item, seen);
|
|
333
|
-
|
|
334
|
-
out.push(cloned);
|
|
337
|
+
const cloned = await __safeClone(item, seen, cyclic);
|
|
338
|
+
out.push(cloned === __safeCloneFailed ? null : cloned);
|
|
335
339
|
}
|
|
336
|
-
return out;
|
|
340
|
+
return cyclic.has(v) ? __safeCloneFailed : out;
|
|
337
341
|
}
|
|
338
342
|
if (v instanceof Map) {
|
|
339
343
|
const out = {};
|
|
340
344
|
for (const [key, item] of v.entries()) {
|
|
341
|
-
const cloned = await __safeClone(item, seen);
|
|
342
|
-
|
|
343
|
-
out[String(key)] = cloned;
|
|
345
|
+
const cloned = await __safeClone(item, seen, cyclic);
|
|
346
|
+
out[String(key)] = cloned === __safeCloneFailed ? null : cloned;
|
|
344
347
|
}
|
|
345
|
-
return out;
|
|
348
|
+
return cyclic.has(v) ? __safeCloneFailed : out;
|
|
346
349
|
}
|
|
347
350
|
if (Array.isArray(v)) {
|
|
348
351
|
const out = [];
|
|
349
352
|
for (const item of v) {
|
|
350
|
-
const cloned = await __safeClone(item, seen);
|
|
351
|
-
|
|
352
|
-
out.push(cloned);
|
|
353
|
+
const cloned = await __safeClone(item, seen, cyclic);
|
|
354
|
+
out.push(cloned === __safeCloneFailed ? null : cloned);
|
|
353
355
|
}
|
|
354
|
-
return out;
|
|
356
|
+
return cyclic.has(v) ? __safeCloneFailed : out;
|
|
355
357
|
}
|
|
356
358
|
if (v && typeof v === 'object') {
|
|
357
359
|
const out = {};
|
|
358
360
|
for (const key of Object.keys(v)) {
|
|
359
|
-
const cloned = await __safeClone(v[key], seen);
|
|
360
|
-
|
|
361
|
-
out[key] = cloned;
|
|
361
|
+
const cloned = await __safeClone(v[key], seen, cyclic);
|
|
362
|
+
out[key] = cloned === __safeCloneFailed ? null : cloned;
|
|
362
363
|
}
|
|
363
|
-
return out;
|
|
364
|
+
return cyclic.has(v) ? __safeCloneFailed : out;
|
|
364
365
|
}
|
|
365
366
|
if (typeof v === 'function' && v.__pkgHandlePromise) {
|
|
366
367
|
return undefined;
|
|
@@ -368,6 +369,9 @@ async function __safeClone(v, seen) {
|
|
|
368
369
|
return JSON.parse(JSON.stringify(v));
|
|
369
370
|
}
|
|
370
371
|
catch { return null; }
|
|
372
|
+
finally {
|
|
373
|
+
if (tracked) seen.delete(v);
|
|
374
|
+
}
|
|
371
375
|
}
|
|
372
376
|
|
|
373
377
|
const __ctxChangeProtectedKeys = new Set([
|
|
@@ -956,16 +960,16 @@ function __cleanupTask() {
|
|
|
956
960
|
__pendingRuntimeTasks = [];
|
|
957
961
|
return true;
|
|
958
962
|
}
|
|
959
|
-
`;function Se(e){return Pe.replace("%%PKG_SETUP%%",e)}se.exports={buildSetupCode:Se}});var{parentPort:Ce}=require("worker_threads"),S=Ce||{on(e,t){e==="message"&&process.on("message",t)},postMessage(e){process.send?.(e)}},ie=require("fs"),{fileURLToPath:Re}=require("url"),{createPackageRuntimeBridge:$e}=ae(),{buildSetupCode:Te}=oe(),q;try{q=require("isolated-vm")}catch(e){S.postMessage({type:"error",message:"isolated-vm not available: "+e.message}),process.exit(1)}var K=new Map,
|
|
960
|
-
`),b=Te(w);return await(await T(e,b,"setup.js")).run(r,{timeout:B(t)}),
|
|
963
|
+
`;function Se(e){return Pe.replace("%%PKG_SETUP%%",e)}se.exports={buildSetupCode:Se}});var{parentPort:Ce}=require("worker_threads"),S=Ce||{on(e,t){e==="message"&&process.on("message",t)},postMessage(e){process.send?.(e)}},ie=require("fs"),{fileURLToPath:Re}=require("url"),{createPackageRuntimeBridge:$e}=ae(),{buildSetupCode:Te}=oe(),q;try{q=require("isolated-vm")}catch(e){S.postMessage({type:"error",message:"isolated-vm not available: "+e.message}),process.exit(1)}var K=new Map,pe=0,O=new Map,E=new Map,j=new Map,U=$e({workerDir:__dirname,activeTaskContexts:O}),Me=500,Ne=5e3,ce=new WeakMap,_e=new WeakMap,W={created:0,reused:0,released:0,evicted:0,scrubFailed:0};function B(e){let t=j.get(e);return Math.max(1,Math.ceil((t??Date.now()+3e4)-Date.now()))}var A=null,le=0,ue=0,de=0;async function Ae(){let e=Date.now();if(e-ue<Ne)return de;if(ue=e,!A)return 0;let t=0;for(let s of A){let n=s?.isolate;if(!(!n||n.isDisposed))try{let r=await n.getHeapStatistics(),i=r.heap_size_limit||1,o=r.used_heap_size/i;o>t&&(t=o)}catch{}}return de=t,t}async function F(e){e.heapRatio=await Ae(),e.runnerRssBytes=process.memoryUsage().rss,e.contextStats=Ee(),S.postMessage(e)}function Ee(){return{...W,idle:0}}function ge(e,t,s){if(!A){let n=Math.max(1,Math.trunc(Number(t)||8));A=new Array(n).fill(null)}for(let n=0;n<A.length;n++){let r=(le+n)%A.length,i=A[r];if((!i||!i.isolate||i.isolate.isDisposed)&&(i={isolate:new q.Isolate({memoryLimit:e}),taskIds:new Set},A[r]=i),i.taskIds.size<s)return le=(r+1)%A.length,i}throw new Error("No isolate lane is available")}function z(e,t,s){for(let n of[...e.taskIds])n!==t&&(e.taskIds.delete(n),E.delete(n),O.delete(n),j.delete(n),U.cancelTask(n),V(n),S.postMessage({type:"result",id:n,success:!1,error:{message:"Isolate was disposed because a sibling task could not continue",code:"ERR_EXECUTOR_ISOLATE_LOST",details:{outcome:"unknown_outcome",retryable:!1,reason:s}}}),S.postMessage({type:"taskReleased",id:n}));try{e.isolate.dispose()}catch{}}function Oe(e){let t=E.get(e);if(!t){S.postMessage({type:"taskCancelled",id:e});return}z(t,e,"sibling_cancelled"),U.cancelTask(e),E.delete(e),O.delete(e),j.delete(e),t.taskIds.delete(e),V(e),S.postMessage({type:"taskCancelled",id:e})}function ye(e,t){t.taskIds.delete(e)&&(O.delete(e),E.delete(e),j.delete(e),V(e),S.postMessage({type:"taskReleased",id:e}))}async function T(e,t,s){let n=ce.get(e);n||(n=new Map,ce.set(e,n));let r=n.get(t);if(r)return r;let i;try{i=await e.compileScript(t,{filename:s})}catch(o){throw o&&typeof o=="object"&&(o.executionStage="compile"),o}if(n.set(t,i),n.size>Me){let o=n.keys().next().value;n.delete(o)}return i}S.on("message",async e=>{if(e.type==="execute")Ge(e).catch(async t=>{await F({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="executeBatch")We(e).catch(async t=>{await F({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="invokeRuntimeCallback")Je(e).catch(t=>{S.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:t?.message||String(t)})});else if(e.type==="callResult"){let t=K.get(e.callId);t&&(K.delete(e.callId),t.resolve(e.result))}else if(e.type==="callError"){let t=K.get(e.callId);t&&(K.delete(e.callId),t.reject(new Error(e.error)))}else e.type==="cancelTask"&&Oe(e.id)});async function Je(e){let t=O.get(e.id);if(!t){S.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:`Runtime callback context not found: ${e.id}`});return}let s=await t.evalClosure(`return __invokeRuntimeCallback(${JSON.stringify(e.callbackId)}, ${JSON.stringify(e.argsJson||"[]")});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}}),n=JSON.parse(s);S.postMessage({type:"runtimeCallbackResult",callId:e.callId,...n})}function L(e,t,s){return new Promise((n,r)=>{let i=`cb_${++pe}`;K.set(i,{resolve:n,reject:r}),S.postMessage({type:t,id:e,callId:i,...s})})}function Ie(e,t,s){S.postMessage({type:t,id:e,callId:`f_${++pe}`,...s})}async function je(e,t){if(t?.method!=="stream")return L(e,"resCall",t);let s=JSON.parse(t.argsJson||"[]"),n=s[0],r=s[1]||{},i=n?.__pkgHandleArg;if(!i)return L(e,"resCall",t);let o=r.observer&&typeof r.observer=="object"?r.observer.__fnRef:null,y=r.transform&&typeof r.transform=="object"?r.transform.__fnRef:null,f=o||y?new TextDecoder("utf-8"):null;delete r.observer,delete r.transform;let w={...r};await L(e,"resCall",{method:"streamStart",argsJson:JSON.stringify([null,w])});let b=async(u,m,v)=>{if(!u)return;let k=O.get(e);if(!k)return;let P=await k.evalClosure(`return __invokeRuntimeCallback(${JSON.stringify(u)}, ${JSON.stringify(JSON.stringify([m,v]))});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}}),C=JSON.parse(P);if(C?.error)throw new Error(C.error);if(C?.value?.__e!=="u")return C?.value},R=async(u,m)=>{if(o)try{await b(o,u,m)}catch{}},d=async(u,m,v)=>{let k=u;if(y){let C=await b(y,v,m);if(C===null)return;C!==void 0&&(k=Buffer.from(String(C)))}let P=Buffer.from(k);P.length!==0&&await L(e,"resCall",{method:"streamChunk",chunk:P.toString("base64")})};try{await U.streamPackageHandle(e,i,async m=>{let v="";try{v=f?f.decode(Buffer.from(m),{stream:!0}):""}catch{}await R(v,"chunk"),await d(m,"chunk",v)},[],B(e));let u="";try{u=f?f.decode():""}catch{}await R(u,"end"),await d("","end",u),await L(e,"resCall",{method:"streamEnd"})}catch(u){try{await L(e,"resCall",{method:"streamError",error:{message:u.message,stack:u.stack}})}catch{}throw await R("","error"),u}return JSON.stringify({__e:"u"})}function Ue(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=Re(e.fileUrl)),!t||!ie.existsSync(t)?null:ie.readFileSync(t,"utf8")}async function He(e,t,s){try{let n=Ue(s);if(!n)return null;let r=await e.compileModule(n,{filename:`pkg:${s.safeName}`});await r.instantiate(t,o=>{throw new Error(`Unresolved import in package ${s.safeName}: ${o}`)}),await r.evaluate({timeout:1e4});let i=await r.namespace.get("default");return i!==void 0&&i.typeof!=="undefined"?i.derefInto({release:!1}):r.namespace.derefInto({release:!1})}catch{return null}}function he(e,t){let s=new Set(t.map(f=>f.name)),n=new Set,r=String(e||""),i=/\b(?:\$ctx\.)?\$pkgs\s*\[\s*(['"`])([^'"`]+)\1\s*\]/g,o=/\brequire\s*\(\s*(['"`])([^'"`]+)\1\s*\)/g,y=/\b(?:\$ctx\.)?\$pkgs\.([A-Za-z_$][\w$]*)/g;for(let f of[i,o])for(let w of r.matchAll(f)){let b=w[2];s.has(b)&&n.add(b)}for(let f of r.matchAll(y)){let w=f[1];s.has(w)&&n.add(w)}return n}async function Le(e,t,s,n){let r=await e.createContext(),i=r.global;await i.set("global",i.derefInto());let o=[],y=[],f=new Map;for(let d of s){f.set(d.name,d);let u=n.has(d.name)?await He(e,r,d):null;u!==null?(await i.set(`__pkg_${d.safeName}`,u),o.push(d)):y.push(d)}U.setTaskPackages(t,f),await i.set("__callRef",new q.Reference(async(d,u,m)=>{let v=JSON.parse(m);if(u==="pkgCall")try{return JSON.stringify(await U.executePackageRuntimeCall(d,v))}catch(k){throw new Error(JSON.stringify({__userThrow:!0,message:k.message,code:k.code,details:k.details}))}return u==="resCall"?je(d,v):L(d,u,v)})),await i.set("__fireRef",new q.Reference((d,u,m)=>{let v=JSON.parse(m);Ie(d,u,v)}));let w=o.map(d=>`$pkgs[${JSON.stringify(d.name)}] = __pkg_${d.safeName};`).concat(y.map(d=>`$pkgs[${JSON.stringify(d.name)}] = __createPkgProxy(${JSON.stringify(d.name)}, []);`)).join(`
|
|
964
|
+
`),b=Te(w);return await(await T(e,b,"setup.js")).run(r,{timeout:B(t)}),_e.set(r,f),r}async function me(e,t,s,n,r,i,o){let y=e.isolate,f=await Le(y,t,s,r);W.created++,U.setTaskPackages(t,_e.get(f)||new Map);let w=f.global;return await w.set("__snapshot",new q.ExternalCopy(n).copyInto()),await w.set("__nextTaskId",t),await w.set("__nextTaskTimeoutMs",i),await w.set("__nextTaskDeadlineMs",o),await(await T(y,"__resetTask(__snapshot, __nextTaskId, __nextTaskTimeoutMs, __nextTaskDeadlineMs);","reset-task.js")).run(f,{timeout:B(t)}),f}async function ke(e,t){if(!(!t||e.isolate.isDisposed)){try{await(await T(e.isolate,"__cleanupTask();","cleanup-task.js")).run(t,{timeout:5e3})}catch{W.scrubFailed++;try{t.release()}catch{}return}try{t.release()}catch{}W.released++}}function Fe(e){try{let t=JSON.parse(e.message);if(t&&t.__userThrow)return{...t,message:t.message??e.message}}catch{}return null}var De=3,Be=["setup.js","extract.js","extract-error-ctx.js","set-status.js","populate-error.js"];function Ke(e){if(!e)return null;let t=e.split(`
|
|
961
965
|
`);for(let s of t){let n=s.match(/at\s+(.+\.js):(\d+):(\d+)/);if(!n)continue;let r=n[1].trim();if(Be.includes(r)||r!=="handler.js"&&!r.startsWith("preHook #")&&!r.startsWith("postHook #"))continue;let o=parseInt(n[2])-De;if(!(o<=0))return{line:o,column:parseInt(n[3]),phase:r.replace(".js","")}}return null}function qe(e,t,s){if(!e||!t)return;let n=String(e).split(/\r?\n/),r=Math.max(1,t-1),i=Math.min(n.length,t+1),o=String(i).length,y=[];for(let f=r;f<=i;f++){let w=f===t?">":" ";y.push(`${w} ${String(f).padStart(o," ")}. ${n[f-1]??""}`),f===t&&s&&s>0&&y.push(` ${" ".repeat(o)} ${" ".repeat(Math.max(0,s-1))}^`)}return y.join(`
|
|
962
966
|
`)}function Ve(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 te(e,t){let s=Fe(e);if(s)return{message:s.message,statusCode:s.statusCode,errorPath:s.errorPath,code:s.code??(Number.isInteger(s.statusCode)?`HTTP_${s.statusCode}`:void 0),details:s.details};let n=Ke(e.stack),r=e.message||"Unknown error",i=n?`${r} (${n.phase}, line ${n.line})`:r,o=Ve(n,t),y=n?qe(o,n.line,n.column):void 0;return{message:i,statusCode:e.statusCode||null,details:{errorName:e.name||null,executionStage:e.executionStage||"runtime",...n?{...n,codeFrame:y}:{}}}}function X(e){return e?.message==="Script execution timed out."}function Y(e){return e?.message==="Isolate was disposed during execution due to memory limit"}function we(e){X(e)&&e?.code==null&&(e.code="ERR_SCRIPT_EXECUTION_TIMEOUT"),Y(e)&&e?.code==null&&(e.code="ERR_ISOLATE_MEMORY_LIMIT",e.details={outcome:"unknown_outcome",retryable:!1})}async function Z(e,t,s){we(t);let n=te(t,s);t.details&&(n.details={...n.details,...t.details});let r,i=O.get(e),o=E.get(e);if(i&&o&&!o.isolate.isDisposed)try{let y=await T(o.isolate,"JSON.stringify({logs: __logs, truncated: $ctx.$share.$logsTruncated === true})","extract-diagnostic-logs.js");r=JSON.parse(await y.run(i,{timeout:100}))}catch{}await F({type:"result",id:e,success:!1,diagnosticLogs:r,error:{...n,stack:t.stack,code:n.code??t.code}})}async function Ge(e){let{id:t,code:s,pkgSources:n,snapshot:r,memoryLimitMb:i,isolatePoolSize:o,tasksPerIsolate:y}=e,f={handler:e.sourceCode||s||""},w=n||[],b=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),R=Date.now()+b;j.set(t,R);let d=he(s,w),u=ge(i,o,Math.max(1,Math.trunc(Number(y)||1)));u.taskIds.add(t),E.set(t,u);let m=u.isolate,v;try{v=await me(u,t,w,r,d,b,R)}catch(k){j.delete(t),E.delete(t),u.taskIds.delete(t),V(t),await Z(t,k,f),S.postMessage({type:"taskReleased",id:t});return}O.set(t,v);try{let k=`
|
|
963
967
|
(async () => {
|
|
964
968
|
"use strict";
|
|
965
969
|
${s}
|
|
966
970
|
})().then((__result) => __extractResult(__result, __result === undefined));
|
|
967
|
-
`,C=await(await T(m,k,"handler.js")).run(v,{timeout:B(t),promise:!0}),D=JSON.parse(C);await F({type:"result",id:t,success:!0,...D})}catch(k){u.taskIds.has(t)&&(await Z(t,k,f),(X(k)||Y(k))&&z(u,t,"sibling_execution_failure"))}finally{await ke(u,v),ye(t,u)}}async function We(e){let{id:t,codeBlocks:s,pkgSources:n,snapshot:r,memoryLimitMb:i,isolatePoolSize:o,tasksPerIsolate:y}=e,f=n||[],w=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),b=Date.now()+w;j.set(t,b);let R=he((s||[]).map(
|
|
968
|
-
`),f),d=ge(i,o,Math.max(1,Math.trunc(Number(y)||1)));d.taskIds.add(t),E.set(t,d);let u=d.isolate,m;try{m=await me(d,t,f,r,R,w,b)}catch(
|
|
971
|
+
`,C=await(await T(m,k,"handler.js")).run(v,{timeout:B(t),promise:!0}),D=JSON.parse(C);await F({type:"result",id:t,success:!0,...D})}catch(k){u.taskIds.has(t)&&(await Z(t,k,f),(X(k)||Y(k))&&z(u,t,"sibling_execution_failure"))}finally{await ke(u,v),ye(t,u)}}async function We(e){let{id:t,codeBlocks:s,pkgSources:n,snapshot:r,memoryLimitMb:i,isolatePoolSize:o,tasksPerIsolate:y}=e,f=n||[],w=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),b=Date.now()+w;j.set(t,b);let R=he((s||[]).map(_=>_.code||"").join(`
|
|
972
|
+
`),f),d=ge(i,o,Math.max(1,Math.trunc(Number(y)||1)));d.taskIds.add(t),E.set(t,d);let u=d.isolate,m;try{m=await me(d,t,f,r,R,w,b)}catch(_){j.delete(t),E.delete(t),d.taskIds.delete(t),V(t),await Z(t,_),S.postMessage({type:"taskReleased",id:t});return}O.set(t,m);let v=[],k=[],P={},C=0,D=0;for(let _ of s){let H=_.type||"handler",g=_.sourceCode||_.code||"";H==="postHook"?(D++,P[`postHook #${D}`]=g,P.postHook=g,k.push(_)):(H==="handler"?P.handler=g:(C++,P[`${H} #${C}`]=g,P.preHook=g),v.push(_))}try{let _=null;for(let g=0;g<v.length;g++){let x=v[g],$=x.type||"handler",l=$==="handler"?"handler":`${$} #${g+1}`,a;$==="preHook"?a=`
|
|
969
973
|
(async () => {
|
|
970
974
|
"use strict";
|
|
971
975
|
${x.code}
|
|
@@ -979,7 +983,7 @@ function __cleanupTask() {
|
|
|
979
983
|
})().then((__r) => {
|
|
980
984
|
$ctx.$data = __r;
|
|
981
985
|
return "__handler_done__";
|
|
982
|
-
});`;try{let
|
|
986
|
+
});`;try{let p=await(await T(u,a,`${l}.js`)).run(m,{timeout:B(t),promise:!0});if($==="preHook"&&typeof p=="string"){let h=JSON.parse(p);if(h.__shortCircuit){let M=await fe(u,m,h.value);await F({type:"result",id:t,success:!0,...M,shortCircuit:!0});return}}}catch(c){_=c;break}}if(!_&&k.length>0&&await(await T(u,'$ctx.$statusCode = 200; "__status_set__";',"set-status.js")).run(m,{timeout:5e3}),_&&k.length>0){let g=te(_,P),x={message:g.message||"Unknown error",name:_.constructor?.name||"Error",stack:_.stack||"",statusCode:g.statusCode||500,details:g.details||{},timestamp:new Date().toISOString()},$=`
|
|
983
987
|
$ctx.$error = ${JSON.stringify(x)};
|
|
984
988
|
$ctx.$data = null;
|
|
985
989
|
$ctx.$statusCode = ${x.statusCode};
|
|
@@ -1000,4 +1004,4 @@ if ($ctx.$api) {
|
|
|
1000
1004
|
})().then((__r) => {
|
|
1001
1005
|
if (__r !== undefined) $ctx.$data = __r;
|
|
1002
1006
|
return "__posthook_done__";
|
|
1003
|
-
});`;try{await(await T(u,l,`${$}.js`)).run(m,{timeout:B(t),promise:!0})}catch(a){S.postMessage({type:"executionError",id:t,sourceKind:"postHook",scriptId:x.scriptId,error:{message:a.message,stack:a.stack,code:a.code}})}}if(
|
|
1007
|
+
});`;try{await(await T(u,l,`${$}.js`)).run(m,{timeout:B(t),promise:!0})}catch(a){S.postMessage({type:"executionError",id:t,sourceKind:"postHook",scriptId:x.scriptId,error:{message:a.message,stack:a.stack,code:a.code}})}}if(_){we(_);let g=te(_,P);_.details&&(g.details={...g.details,..._.details});let x;try{let a=await(await T(u,"(async () => JSON.stringify(await __extractCtxChanges()))()","extract-error-ctx.js")).run(m,{timeout:5e3,promise:!0});x=JSON.parse(a)}catch{}await F({type:"result",id:t,success:!1,error:{message:g.message,statusCode:g.statusCode,errorPath:g.errorPath,stack:_.stack,code:g.code??_.code,details:g.details},ctxChanges:x}),(X(_)||Y(_))&&z(d,t,"sibling_execution_failure");return}let H=await fe(u,m);await F({type:"result",id:t,success:!0,...H})}catch(_){d.taskIds.has(t)&&(await Z(t,_),(X(_)||Y(_))&&z(d,t,"sibling_execution_failure"))}finally{await ke(d,m),ye(t,d)}}function V(e){U.cleanupTaskPackages(e)}function ze(){U.shutdownPackageRuntime()}process.on("exit",ze);async function fe(e,t,s){if(s!==void 0){let o=`__extractResult(${JSON.stringify(s)}, false)`,f=await(await e.compileScript(o,{filename:"extract.js"})).run(t,{timeout:5e3,promise:!0});return JSON.parse(f)}let i=await(await T(e,"__extractResult($ctx.$data, $ctx.$data === undefined)","extract.js")).run(t,{timeout:5e3,promise:!0});return JSON.parse(i)}
|
package/dist/index.js
CHANGED
|
@@ -48,5 +48,5 @@ ${e}
|
|
|
48
48
|
}
|
|
49
49
|
}
|
|
50
50
|
return true;
|
|
51
|
-
}`}var Or="mongo-fold-text-search.body.txt",qe=null;function eo(){let r=[Ln.join(__dirname,Or),Ln.join(process.cwd(),"dist","kernel","query","utils",Or)];for(let e of r)try{if(en.existsSync(e))return en.readFileSync(e,"utf8")}catch{}return null}function tn(){if(qe!==null)return qe;let r=eo();return r?(qe=r,qe):(qe=Zt(),qe)}var be=require("mongodb");function W(r,e,t,n){if(t==="_id"){if(n instanceof be.ObjectId)return n;if(typeof n=="string")try{return new be.ObjectId(n)}catch{return n}return n}let i=r?.tables?.get(e);if(!i){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new be.ObjectId(n)}catch{return n}return n}if(!i.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new be.ObjectId(n)}catch{return n}return n}let o=i.columns.find(s=>s.name===t);if(!o){if(i.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof n=="string"&&n.length===24)try{return new be.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new be.ObjectId(n)}catch{return n}return n}if(n==null)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;case"uuid":if(typeof n=="string")try{return new be.ObjectId(n)}catch{return n}return n;default:return n}}var nn="__mongoFoldTextTriples";function to(r){return r==="_id"?"$_id":`$${r}`}function Ue(r,e,t,n){let i=to(e),o=r[nn]??[];o.push({ref:i,needle:t,mode:n}),r[nn]=o}function no(r){let e=r[nn];if(delete r[nn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:tn(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}function Qe(r,e,t,n){let i={},o=n==="mongodb"||!n;for(let s of e){let a=s.field.includes(".")?s.field.split(".").pop()??s.field:s.field,u=t||s.field.split(".")[0]||"";o&&a==="id"&&(a="_id");let c=W(r,u,a,s.value);switch(s.operator){case"=":i[a]=c;break;case"!=":i[a]={$ne:c};break;case">":i[a]={$gt:c};break;case"<":i[a]={$lt:c};break;case">=":i[a]={$gte:c};break;case"<=":i[a]={$lte:c};break;case"like":i[a]={$regex:c.replace(/%/g,".*"),$options:"i"};break;case"in":let d=s.value;Array.isArray(d)||(d=typeof d=="string"&&d.includes(",")?d.split(",").map(m=>m.trim()):[d]);let l=d.map(m=>W(r,u,a,m));i[a]={$in:l};break;case"not in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(m=>m.trim()):[f]);let p=f.map(m=>W(r,u,a,m));i[a]={$nin:p};break;case"is null":i[a]=null;break;case"is not null":i[a]={$ne:null};break;case"_contains":Ue(i,a,String(c),"contains");break;case"_starts_with":Ue(i,a,String(c),"starts");break;case"_ends_with":Ue(i,a,String(c),"ends");break;case"_between":let y=s.value;if(typeof y=="string"&&(y=y.split(",").map(m=>m.trim())),Array.isArray(y)&&y.length===2){let m=W(r,u,a,y[0]),b=W(r,u,a,y[1]);i[a]={$gte:m,$lte:b}}break;case"_is_null":let g=c===!0||c==="true";i[a]=g?{$eq:null}:{$ne:null};break;case"_is_not_null":let h=c===!0||c==="true";i[a]=h?{$ne:null}:{$eq:null};break}}return no(i),i}function Ar(r,e,t){let i=r?.tables?.get?.(e)?.columns?.find(o=>o.name===t);return i?i.isNullable!==!1:!0}function rn(r,e,t,n,i,o){switch(i){case"_contains":Ue(e,n,String(o),"contains");break;case"_starts_with":Ue(e,n,String(o),"starts");break;case"_ends_with":Ue(e,n,String(o),"ends");break;case"_eq":e[n]=W(r,t,n,o);break;case"_neq":{let l=W(r,t,n,o);Ar(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:l}})):e[n]={$ne:l};break}case"_in":{let l=o;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(p=>p.trim()):[l]);let f=l.map(p=>W(r,t,n,p));e[n]={$in:f};break}case"_not_in":case"_nin":let s=o;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(l=>l.trim()):[s]);let a=s.map(l=>W(r,t,n,l));Ar(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$nin:a}})):e[n]={$nin:a};break;case"_gt":e[n]={$gt:W(r,t,n,o)};break;case"_gte":e[n]={$gte:W(r,t,n,o)};break;case"_lt":e[n]={$lt:W(r,t,n,o)};break;case"_lte":e[n]={$lte:W(r,t,n,o)};break;case"_is_null":let u=o===!0||o==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let c=o===!0||o==="true";e[n]=c?{$ne:null}:{$eq:null};break;case"_between":let d=o;if(typeof d=="string"&&(d=d.split(",").map(l=>l.trim())),Array.isArray(d)&&d.length===2){let l=W(r,t,n,d[0]),f=W(r,t,n,d[1]);e[n]={$gte:l,$lte:f}}break}}var Jn=require("mongodb");function ne(r,e){if(!r||typeof r!="object")return!1;for(let[t,n]of Object.entries(r))if(t==="_and"||t==="_or"){if(Array.isArray(n)){for(let i of n)if(ne(i,e))return!0}}else if(t==="_not"){if(ne(n,e))return!0}else if(e.has(t))return!0;return!1}function H(r,e){if(!r||typeof r!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},n={},i=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(r)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(i.has(s))if(typeof a=="object"&&a!==null){let u=Object.keys(a);if(u.some(d=>d.startsWith("_"))){let d=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&d.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let o=ne(r,i);return{fieldFilters:t,relationFilters:n,hasRelations:o}}Et();Mt();var cn="__mongoFoldTextTriples";function ze(r,e){if(!r)return{};let t={};return Ot(r,t,e),we(t),t}function uo(r,e){if(!r)return{};let t={};return Kn(r,t,e),we(t),t}function pe(r,e,t){if(!e)return{};let n=new ie,{node:i}=de(e,t,r,n);return ze(i,{metadata:r,rootTable:t})}function un(r,e,t){if(!e)return{};let n=new ie,{node:i}=de(e,t,r,n);return uo(i,{metadata:r,rootTable:t})}function Ot(r,e,t){switch(r.kind){case"true":return;case"false":fe(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let i=r.children.map(o=>{let s={};return Ot(o,s,t),we(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}fe(e,...i);return}case"or":{let i=r.children.map(s=>{let a={};return Ot(s,a,t),we(a),a}).filter(s=>Object.keys(s).length>0);if(i.length===0)return;let o=e.$or;e.$or=o?[...o,...i]:i;return}case"not":{let n={};Ot(r.child,n,t),we(n);let i=e.$nor;e.$nor=i?[...i,n]:[n];return}case"compare":Dr(r,e,t);return;case"relation_exists":{console.warn(`[mongo-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${r.joinId}) \u2014 expected applyRelationFilters or null-only short-circuit to handle it. Filter silently skipped.`);return}}}function Dr(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let i=o=>W(t.metadata,t.rootTable,n,o);switch(r.op){case"eq":Z(e,n,i(r.value));return;case"neq":{let o=i(r.value);qn(t,n)?fe(e,{[n]:{$ne:null}},{[n]:{$ne:o}}):Z(e,n,{$ne:o});return}case"gt":Z(e,n,{$gt:i(r.value)});return;case"gte":Z(e,n,{$gte:i(r.value)});return;case"lt":Z(e,n,{$lt:i(r.value)});return;case"lte":Z(e,n,{$lte:i(r.value)});return;case"in":{let o=Lr(r.value).map(i);Z(e,n,{$in:o});return}case"not_in":{let o=Lr(r.value).map(i);qn(t,n)?fe(e,{[n]:{$ne:null}},{[n]:{$nin:o}}):Z(e,n,{$nin:o});return}case"between":{let o=Array.isArray(r.value)?r.value:typeof r.value=="string"?r.value.split(",").map(s=>s.trim()):null;Array.isArray(o)&&o.length===2&&Z(e,n,{$gte:i(o[0]),$lte:i(o[1])});return}case"is_null":Z(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":Wn(e,n,String(r.value),"contains");return;case"starts_with":Wn(e,n,String(r.value),"starts");return;case"ends_with":Wn(e,n,String(r.value),"ends");return}}function Kn(r,e,t){switch(r.kind){case"true":fe(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let i=r.children.map(s=>{let a={};return Kn(s,a,t),we(a),a}).filter(s=>Object.keys(s).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}let o=e.$or;e.$or=o?[...o,...i]:i;return}case"or":{let i=r.children.map(o=>{let s={};return Kn(o,s,t),we(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}fe(e,...i);return}case"not":Ot(r.child,e,t);return;case"compare":fo(r,e,t);return;case"relation_exists":{Z(e,r.joinId,r.negate?{$ne:null}:{$eq:null});return}}}function fo(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached false renderer \u2014 expected relation resolver to handle it. Filter silently skipped.`);return}if(r.op==="is_null"){Z(e,n,r.value===!0?{$ne:null}:{$eq:null});return}let i={};Dr(r,i,t),we(i);let o={$nor:[i]};qn(t,n)?fe(e,o,{[n]:{$ne:null}}):fe(e,o)}function Z(r,e,t){r[e]===void 0?r[e]=t:(fe(r,{[e]:r[e]},{[e]:t}),delete r[e])}function fe(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function qn(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(i=>i.name===e);return n?n.isNullable!==!1:!0}function Lr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function po(r){return r==="_id"?"$_id":`$${r}`}function Wn(r,e,t,n){let i=po(e),o=r[cn]??[];o.push({ref:i,needle:t,mode:n}),r[cn]=o}function we(r){let e=r[cn];if(delete r[cn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:tn(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}async function $e(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return pe(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!ne(r,o))return pe(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>$e(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._or&&Array.isArray(r._or)){let d=(await Promise.all(r._or.map(l=>$e(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:{$or:d}}if(r._not)return await Qn(r._not,e,t,n)||{};let{fieldFilters:s,relationFilters:a}=H(r,i),u=[];if(s&&Object.keys(s).length>0){let c=pe(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(a&&Object.keys(a).length>0)for(let[c,d]of Object.entries(a)){let l=await go(c,d,e,i,t,n);l&&Object.keys(l).length>0&&u.push(l)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function Qn(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return un(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!ne(r,o))return un(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>Qn(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$or:d}}if(r._or&&Array.isArray(r._or)){let d=(await Promise.all(r._or.map(l=>Qn(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._not)return $e(r._not,e,t,n);let{fieldFilters:s,relationFilters:a}=H(r,i),u=[];if(s&&Object.keys(s).length>0){let c=un(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(a&&Object.keys(a).length>0)for(let[c,d]of Object.entries(a)){let l=await yo(c,d,e,i,t,n);l&&Object.keys(l).length>0&&u.push(l)}return u.length===0?{}:u.length===1?u[0]:{$or:u}}async function go(r,e,t,n,i,o){let s=(n.relations||[]).find(c=>c.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=i?.tables?.get(a);return!a||!u?{}:s.type==="many-to-one"||s.type==="one-to-one"?ho(e,s,r,a,u,i,o):s.type==="one-to-many"?qr(e,s,t,a,u,i,o):s.type==="many-to-many"?Ur(e,s,t,a,u,i,o):{}}async function ho(r,e,t,n,i,o,s){let a=V(e)||t,u=fn(r),c=pn(u);if(c!==null)return c?{[a]:null}:{[a]:{$ne:null}};let d=zn(u);if(d!==null){let y=gn(d.value);if(d.op==="eq")return{[a]:y};if(d.op==="neq")return{[a]:{$ne:y}};if(d.op==="in")return{[a]:{$in:y}};if(d.op==="not_in")return{$and:[{[a]:{$nin:y}},{[a]:{$ne:null}}]}}let l=await dn(u,n,i,o,s);if(!l||Object.keys(l).length===0)return{};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(Boolean);return p.length===0?{__impossible__:!0}:{[a]:{$in:p}}}async function yo(r,e,t,n,i,o){let s=(n.relations||[]).find(c=>c.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=i?.tables?.get(a);if(!a||!u)return{};if(s.type==="many-to-one"||s.type==="one-to-one")return mo(e,s,r,a,u,i,o);if(s.type==="one-to-many"){let c=await qr(e,s,t,a,u,i,o);return Kr(c)}if(s.type==="many-to-many"){let c=await Ur(e,s,t,a,u,i,o);return Kr(c)}return{}}async function mo(r,e,t,n,i,o,s){let a=V(e)||t,u=fn(r),c=pn(u);if(c!==null)return c?{[a]:{$ne:null}}:{[a]:null};let d=zn(u);if(d!==null){let y=gn(d.value);if(d.op==="eq")return{$and:[{[a]:{$ne:y}},{[a]:{$ne:null}}]};if(d.op==="neq")return{[a]:y};if(d.op==="in")return{$and:[{[a]:{$nin:y}},{[a]:{$ne:null}}]};if(d.op==="not_in")return{[a]:{$in:y}}}let l=await dn(u,n,i,o,s);if(!l||Object.keys(l).length===0)return{[a]:null};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(Boolean);return p.length===0?{[a]:{$ne:null}}:{$and:[{[a]:{$nin:p}},{[a]:{$ne:null}}]}}async function qr(r,e,t,n,i,o,s){let a=q(e)||t,u=fn(r),c=pn(u);if(c!==null){let f=await Wr(s,n,a,{});return c?f.length===0?{}:{_id:{$nin:f}}:f.length===0?{__impossible__:!0}:{_id:{$in:f}}}let d=await dn(u,n,i,o,s);if(!d||Object.keys(d).length===0)return{};let l=await Wr(s,n,a,d);return l.length===0?{__impossible__:!0}:{_id:{$in:l}}}async function Ur(r,e,t,n,i,o,s){let a=Ne(t,e);if(!a)return{};let u=fn(r),c=pn(u);if(c!==null){let g=await Un(s,a,n,null);return c?g.length===0?{}:{_id:{$nin:g}}:g.length===0?{__impossible__:!0}:{_id:{$in:g}}}let d=zn(u);if(d!==null){let g=gn(d.value),h=Array.isArray(g)?g:[g],m=await Un(s,a,n,{_id:{$in:h}});return m.length===0?{__impossible__:!0}:{_id:{$in:m}}}let l=await dn(u,n,i,o,s);if(!l||Object.keys(l).length===0)return{};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);if(p.length===0)return{__impossible__:!0};let y=await Un(s,a,n,{_id:{$in:p}});return y.length===0?{__impossible__:!0}:{_id:{$in:y}}}async function dn(r,e,t,n,i){let o=new Set((t?.relations??[]).map(s=>s.propertyName));return ne(r,o)?$e(r,e,n,i):pe(n,r,e)}async function Wr(r,e,t,n){let i=await r.collection(e).find(n,{projection:{[t]:1}}).toArray(),o=new Set,s=[];for(let a of i){let u=a[t];if(u==null)continue;let c=String(u);o.has(c)||(o.add(c),s.push(u))}return s}function Kr(r){if(!r||Object.keys(r).length===0)return{};if(r.__impossible__===!0)return{};let e=r._id;if(e&&typeof e=="object"&&!Array.isArray(e)){if(Array.isArray(e.$in))return{_id:{$nin:e.$in}};if(Array.isArray(e.$nin))return{_id:{$in:e.$nin}}}return{$nor:[r]}}async function Un(r,e,t,n){let i=null;n&&t&&(i=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(d=>d._id).filter(Boolean));let o=i?{[e.otherColumn]:{$in:i}}:{},s=await r.collection(e.junctionName).find(o,{projection:{[e.selfColumn]:1}}).toArray(),a=new Set,u=[];for(let c of s){let d=c[e.selfColumn];if(d==null)continue;let l=String(d);a.has(l)||(a.add(l),u.push(d))}return u}function fn(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function pn(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0],n=r[t];return t==="_is_null"?n===!0:t==="_is_not_null"?n!==!0:t==="_eq"?n===null?!0:null:t==="_neq"&&n===null?!1:null}function gn(r){if(Array.isArray(r))return r.map(e=>gn(e));if(typeof r!="string")return r;try{return new Jn.ObjectId(r)}catch{return r}}function zn(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof Jn.ObjectId)return{op:"eq",value:r};if(r==null)return null;if(typeof r!="object")return{op:"eq",value:r};if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0];return t==="_eq"?{op:"eq",value:r._eq}:t==="_neq"?{op:"neq",value:r._neq}:t==="_in"&&Array.isArray(r._in)?{op:"in",value:r._in}:t==="_not_in"&&Array.isArray(r._not_in)?{op:"not_in",value:r._not_in}:null}async function At(r,e,t,n){let i=await It(r,e,t),o=[],s={},a={};if(n&&typeof n=="object")for(let[p,y]of Object.entries(n))if(typeof y=="object"&&y!==null){let g=Object.keys(y)[0];g&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(g)?s[p]=y:a[p]=y}else s[p]=y;if(Object.keys(s).length>0){let p={};for(let[y,g]of Object.entries(s))if(typeof g=="object"&&g!==null)for(let[h,m]of Object.entries(g))rn(r,p,e,y,h,m);else p[y]=g;Object.keys(p).length>0&&o.push({$match:p})}let c=r?.tables?.get(e)?.relations||[],d=[];for(let[p,y]of Object.entries(a))if(!i.relations.some(h=>h.propertyName===p)){let h=c.find(m=>m.propertyName===p);if(h){let m="",b="";if(h.type==="many-to-one"||h.type==="one-to-one")m=V(h)||h.propertyName,b="_id";else if(h.type==="one-to-many")m="_id",b=q(h)||h.propertyName;else if(h.type==="many-to-many")continue;let w=h.type==="one-to-many"||h.type==="many-to-many";d.push({propertyName:p,targetTable:h.targetTableName,localField:m,foreignField:b,type:w?"many":"one",nestedFields:[]})}}let l=[...i.relations,...d];for(let p of l){let y=a[p.propertyName],g=p.nestedFields&&p.nestedFields.length>0?await At(r,p.targetTable,p.nestedFields,y):y?await At(r,p.targetTable,["_id"],y):[];p.type==="one"&&g.length>0&&g.push({$limit:1}),o.push({$lookup:{from:p.targetTable,localField:p.localField,foreignField:p.foreignField,as:p.propertyName,pipeline:g.length>0?g:void 0}}),p.type==="one"&&(o.push({$unwind:{path:`$${p.propertyName}`,preserveNullAndEmptyArrays:!0}}),y&&(Ve(y)||o.push({$match:{[p.propertyName]:{$ne:null}}})))}let f=c.filter(p=>!l.some(y=>y.propertyName===p.propertyName));if(i.scalarFields.length>0||i.relations.length>0||f.length>0){let p={_id:1};for(let g of i.scalarFields)p[g]=1;for(let g of l)p[g.propertyName]=1,g.type==="one"&&g.localField&&g.localField!==g.propertyName&&(p[g.localField]=1);if(t.includes("*"))for(let g of f){if(g.type==="one-to-many"||g.type==="many-to-many")continue;g.type==="many-to-many"?p[g.propertyName]={$map:{input:`$${g.propertyName}`,as:"item",in:{_id:"$$item"}}}:p[g.propertyName]={$cond:{if:{$ne:[`$${g.propertyName}`,null]},then:{_id:`$${g.propertyName}`},else:null}}}o.push({$project:p})}return o}async function Qr(r,e,t,n,i){let o=r?.tables?.get(t),s=o?.relations||[],a=o?.columns||[],u=s.filter(d=>!i.some(l=>l.propertyName===d.propertyName)),c=n.length===a.length||n.length===0&&i.length===0;if(u.length>0||!c){let d={_id:1};for(let l of n)d[l]=1;for(let l of i)d[l.propertyName]=1,l.type==="one"&&l.localField&&l.localField!==l.propertyName&&(d[l.localField]=1);for(let l of u){if(l.type==="one-to-many"||l.type==="many-to-many")continue;l.type==="many-to-many"?d[l.propertyName]={$map:{input:`$${l.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[l.propertyName]={$cond:{if:{$ne:[`$${l.propertyName}`,null]},then:{_id:`$${l.propertyName}`},else:null}}}e.push({$project:d})}}function Ve(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ve(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ve(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ve(e));if("_not"in r)return Ve(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Ve(t)))return!0}return!1}Ge();var jt=require("mongodb");Ge();hn();async function yn(r,e,t){let n=new Map,i=0;async function o(){for(;i<r.length;){let u=i++,c=r[u];n.set(String(c),await e(c))}}let s=Math.min(t,r.length);if(s===0)return n;let a=Array.from({length:s},o);return await Promise.all(a),n}var se="__sourceId__",Ce="__targetId__",Ye="__enfyra_target__",Pt="__enfyra_top_n_documents__",Xe=class{constructor(e,t,n,i=new Se){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.executionBudget=i;this.pkField="_id"}chunkCount(e){return Math.ceil(e.length/oe)||1}runQuery(e){return this.executionBudget.run(e)}uniqueValues(e){return Array.from(new Map(e.filter(t=>t!=null).map(t=>[this.keyOf(t),t])).values())}buildStableSort(e,t="_id"){let n=this.buildSortFromTokens(e)||{};return n[t]===void 0&&(n[t]=1),n}appendPartitionProjection(e,t,n){if(t){let i={...t};for(let o of n)i[o]=1;e.push({$project:i})}}appendTopNStages(e,t,n,i,o){e.push({$group:{_id:`$${t}`,[Pt]:{$topN:{sortBy:n,output:"$$ROOT",n:i+o}}}},{$project:{[Pt]:{$slice:[`$${Pt}`,i,o]}}},{$unwind:`$${Pt}`},{$replaceRoot:{newRoot:`$${Pt}`}})}normalizeMetadata(){return this.metadata?this.metadata.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortFromTokens(e){let t={};for(let n of this.parseSortTokens(e)){let i=n.field.split(".");if(i.length===1)t[i[0]]=n.order;else{let o=`__sort_${i.slice(0,-1).join("_")}`;t[`${o}.${i[i.length-1]}`]=n.order}}return Object.keys(t).length>0?t:void 0}parseSortTokens(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).map(n=>{let i=n.startsWith("-"),o=i?n.slice(1):n;return{field:o==="id"?"_id":o,order:i?-1:1}}):[]}hasDottedSort(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).some(n=>(n.startsWith("-")?n.slice(1):n).includes(".")):!1}buildSortAggregatePipeline(e,t,n){let i=Array.isArray(n)?n:n.split(",").map(c=>c.trim()).filter(Boolean),o=[{$match:t}],s=new Set;for(let c of i){let l=(c.startsWith("-")?c.slice(1):c).split(".");if(l.length<=1)continue;let f=e;for(let p=0;p<l.length-1;p++){let y=l[p],g=this.normalizeMetadata()?.tables?.get(f);if(!g)break;let h=g.relations?.find(w=>w.propertyName===y);if(!h)break;let m=h.targetTableName||h.targetTable,b=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(b)){s.add(b);let w=V(h)||h.propertyName,C=p===0?null:`__sort_${l.slice(0,p).join("_")}`,T=C?`${C}.${w}`:w;o.push({$lookup:{from:m,localField:T,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}f=m}}let a=this.buildSortFromTokens(n);a&&o.push({$sort:a});let u={};for(let c of s)u[c]=0;return Object.keys(u).length>0&&o.push({$project:u}),o}toObjectId(e){try{return typeof e=="string"?new jt.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof jt.ObjectId||t instanceof jt.ObjectId?this.keyOf(e).localeCompare(this.keyOf(t)):typeof e=="number"&&typeof t=="number"?e-t:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="string"&&typeof t=="string"?e.localeCompare(t):e<t?-1:e>t?1:0}sortDocsInMemory(e,t){let n=this.parseSortTokens(t).filter(i=>!i.field.includes("."));n.length!==0&&e.sort((i,o)=>{for(let s of n){let a=this.compareSortValues(i[s.field],o[s.field]);if(a!==0)return a*s.order}return this.compareSortValues(i._id,o._id)})}sortDocsByPk(e){e.sort((t,n)=>this.compareSortValues(t._id,n._id))}projectionWithSortFields(e,t){if(!e)return{projection:e,hiddenFields:[]};let n={...e},i=[];for(let o of this.parseSortTokens(t))o.field.includes(".")||n[o.field]===void 0&&(n[o.field]=1,i.push(o.field));return{projection:n,hiddenFields:i}}removeHiddenFields(e,t){if(t.length!==0)for(let n of e)for(let i of t)delete n[i]}keyOf(e){return e==null?"":e instanceof jt.ObjectId||typeof e=="object"&&typeof e.toHexString=="function"?e.toHexString():String(e)}buildScalarRef(e){return{[this.pkField]:e}}getTargetPkField(e){return this.pkField}resolveOwnerFkKey(e){return e.localField||e.fkColumn||e.relationName}resolveInverseFkField(e){return e.foreignField?e.foreignField:e.mappedBy?e.mappedBy:e.relationName}resolveParentPk(e){return this.pkField}resolveFields(e,t){let{rootFields:n,subRelations:i}=He(e),o={},s=!1;if(n.includes("*")){s=!0;for(let f of t.relations||[])i.has(f.propertyName)||i.set(f.propertyName,["_id"])}else for(let f of n){let p=t.columns.find(y=>y.name===f);p?o[p.name]=1:t.relations?.find(g=>g.propertyName===f)&&!i.has(f)&&i.set(f,["_id"])}i.forEach((f,p)=>{let y=t.relations?.find(g=>g.propertyName===p);y&&(y.type==="many-to-one"||y.type==="one-to-one"&&!y.isInverse)&&(s||(o[V(y)||y.propertyName]=1))}),s||(o._id=1);let a=[];i.forEach((f,p)=>{let y=t.relations?.find(b=>b.propertyName===p);if(!y)return;let g=y.targetTableName||y.targetTable;if(!g)return;let h,m;y.type==="many-to-one"||y.type==="one-to-one"?Ie(y)?(h="_id",m=q(y)||y.propertyName):(h=V(y)||y.propertyName,m="_id"):y.type==="one-to-many"?(h="_id",m=q(y)||y.propertyName):y.type==="many-to-many"&&(y.isInverse?(h="_id",m=y.mappedBy):(h=y.propertyName,m="_id")),a.push({relationName:p,type:y.type,targetTable:g,fields:f,isInverse:y.isInverse,fkColumn:y.foreignKeyColumn,mappedBy:y.mappedBy,junctionTableName:y.junctionTableName,junctionSourceColumn:y.junctionSourceColumn,junctionTargetColumn:y.junctionTargetColumn,localField:h,foreignField:m})});let u=!s&&Object.keys(o).length===1&&o._id===1&&a.length===0,c=this.fieldRenamesByTable?.get(t.name)??[],d=[];if(!s&&c.length>0)for(let f of c)o[f.newName]===1&&o[f.oldName]!==1&&(o[f.oldName]=1,d.push(f.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:o,pendingRenames:c,hiddenFields:d}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?pe(this.normalizeMetadata(),i.userFilter,e):null,s=this.buildSortFromTokens(i?.userSort),a=await K(t,c=>{let d={_id:{$in:c}};o&&Object.keys(o).length>0&&Object.assign(d,o);let l={projection:n.projection};return s&&(l.sort=s),this.runQuery(()=>this.db.collection(e).find(d,l).toArray())}),u=this.applyReadFallback(a,n);return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(t),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,n,i,o){let s=i.projection?{...i.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let a=this.uniqueValues(n.map(m=>this.toObjectId(m))),u=o?.userFilter?pe(this.normalizeMetadata(),o.userFilter,e):null,c=o?.userLimit,d=o?.userPage,l=this.hasDottedSort(o?.userSort);if(c!==void 0&&c>0){let m=d?(d-1)*c:0;if(l)throw new Error(`Dotted sort is not supported for batch relation '${o?.relationName}'`);let b=this.buildStableSort(o?.userSort),w=await K(a,async C=>{let T={[t]:{$in:C}};u&&Object.keys(u).length>0&&Object.assign(T,u);let k=[{$match:T}];this.appendTopNStages(k,t,b,m,c),k.push({$sort:{[t]:1,...b}}),this.appendPartitionProjection(k,s,[t]);let x=await this.runQuery(()=>this.db.collection(e).aggregate(k).toArray());return this.applyReadFallback(x,i)});return{docs:w,groupKeyField:t,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:w.length}}}if(s&&(s[t]=1),l){let m=[],b=await yn(a,async w=>{let C={[t]:w};u&&Object.keys(u).length>0&&Object.assign(C,u);let T=this.buildSortAggregatePipeline(e,C,o.userSort);s&&T.push({$project:s});let k=await this.runQuery(()=>this.db.collection(e).aggregate(T).toArray());return this.applyReadFallback(k,i)},Me);for(let w of b.values())for(let C of w)m.push(C);return{docs:m,groupKeyField:t,stats:{strategy:"per-parent-dotted-sort",roundtrips:a.length,concurrencyWaves:Math.ceil(a.length/Me),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.length}}}let f={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(f,u);let p=this.buildSortFromTokens(o?.userSort)||{_id:1},y={projection:s,sort:p},g=await K(a,m=>this.runQuery(()=>this.db.collection(e).find({[t]:{$in:m},...u||{}},y).toArray())),h=this.applyReadFallback(g,i);return{docs:h,groupKeyField:t,stats:{strategy:"batch-in",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:h.length}}}postProcessInverseChild(e,t,n){n||delete e[t]}m2mSortCanUseJunction(e){return this.parseSortTokens(e).every(t=>t.field==="_id")}async loadM2MTargets(e,t,n){if(t.length===0)return[];let i=n.projection?{projection:n.projection}:void 0,o=await K(t,s=>this.runQuery(()=>this.db.collection(e).find({_id:{$in:s}},i).toArray()));return this.applyReadFallback(o,n)}async fetchM2MTopK(e,t,n,i,o,s,a){if(this.hasDottedSort(t.userSort))throw new Error(`Dotted sort is not supported for batch relation '${t.relationName}'`);let u=new Map;for(let m of e)u.set(this.keyOf(m),[]);let c=i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1,d=!o&&this.m2mSortCanUseJunction(t.userSort),l=this.parseSortTokens(t.userSort).find(m=>m.field==="_id")?.order??1,f=this.buildStableSort(t.userSort),p=await K(e,async m=>{if(d){let C=[{$match:{[n.selfColumn]:{$in:m}}}];return this.appendTopNStages(C,n.selfColumn,{[n.otherColumn]:l},s,a),C.push({$sort:{[n.selfColumn]:1,[n.otherColumn]:l}},{$project:{_id:0,[se]:`$${n.selfColumn}`,[Ce]:`$${n.otherColumn}`}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(C).toArray())).map(k=>({sourceId:k[se],targetId:k[Ce]}))}let b=[{$match:{[n.selfColumn]:{$in:m}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ye}},{$unwind:`$${Ye}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ye}`,{[se]:`$${n.selfColumn}`,[Ce]:`$${n.otherColumn}`}]}}}];return o&&Object.keys(o).length>0&&b.push({$match:o}),this.appendTopNStages(b,se,f,s,a),b.push({$sort:{[se]:1,...f}}),b.push({$project:{_id:0,[se]:1,[Ce]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(b).toArray())).map(C=>({sourceId:C[se],targetId:C[Ce]}))});if(c){let m=new Map;for(let b of p){let w=this.keyOf(b.targetId);m.has(w)||m.set(w,{_id:b.targetId}),u.get(this.keyOf(b.sourceId))?.push(m.get(w))}return{grouped:u,docs:[],stats:{strategy:d?"m2m-junction-partitioned-top-k":"m2m-filtered-edge-top-k",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let y=this.uniqueValues(p.map(m=>m.targetId)),g=await this.loadM2MTargets(t.targetTable,y,i),h=new Map(g.map(m=>[this.keyOf(m._id),m]));for(let m of p){let b=h.get(this.keyOf(m.targetId));b&&u.get(this.keyOf(m.sourceId))?.push(b)}return{grouped:u,docs:g,stats:{strategy:"m2m-partitioned-edge-loader",roundtrips:this.chunkCount(e)+(y.length>0?this.chunkCount(y):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+g.length,rowsDiscarded:0}}}async fetchM2MEdgeBatch(e,t,n,i,o){let s=new Map;for(let g of e)s.set(this.keyOf(g),[]);let a=!o&&this.m2mSortCanUseJunction(t.userSort),u=this.parseSortTokens(t.userSort).find(g=>g.field==="_id")?.order??1,c=this.buildStableSort(t.userSort),d=await K(e,async g=>{if(a)return(await this.runQuery(()=>this.db.collection(n.junctionName).find({[n.selfColumn]:{$in:g}},{projection:{_id:0,[n.selfColumn]:1,[n.otherColumn]:1},sort:{[n.selfColumn]:1,[n.otherColumn]:u}}).toArray())).map(w=>({sourceId:w[n.selfColumn],targetId:w[n.otherColumn]}));let h=[{$match:{[n.selfColumn]:{$in:g}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ye}},{$unwind:`$${Ye}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ye}`,{[se]:`$${n.selfColumn}`,[Ce]:`$${n.otherColumn}`}]}}}];return o&&Object.keys(o).length>0&&h.push({$match:o}),h.push({$sort:{[se]:1,...c}},{$project:{_id:0,[se]:1,[Ce]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(h).toArray())).map(b=>({sourceId:b[se],targetId:b[Ce]}))});if(i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1){let g=new Map;for(let h of d){let m=this.keyOf(h.targetId);g.has(m)||g.set(m,{_id:h.targetId}),s.get(this.keyOf(h.sourceId))?.push(g.get(m))}return{grouped:s,docs:[],stats:{strategy:a?"m2m-junction-batch":"m2m-filtered-edge-batch",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length,rowsDiscarded:0}}}let f=this.uniqueValues(d.map(g=>g.targetId)),p=await this.loadM2MTargets(t.targetTable,f,i),y=new Map(p.map(g=>[this.keyOf(g._id),g]));for(let g of d){let h=y.get(this.keyOf(g.targetId));h&&s.get(this.keyOf(g.sourceId))?.push(h)}return{grouped:s,docs:p,stats:{strategy:"m2m-edge-loader",roundtrips:this.chunkCount(e)+(f.length>0?this.chunkCount(f):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length+p.length,rowsDiscarded:0}}}async fetchM2M(e,t,n,i,o){let s=n?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=Ne(s,{type:"many-to-many",propertyName:t.relationName,targetTable:t.targetTable,mappedBy:t.isInverse?t.mappedBy:void 0,junctionTableName:t.junctionTableName,junctionSourceColumn:t.junctionSourceColumn,junctionTargetColumn:t.junctionTargetColumn});if(!a)throw new Error(`Failed to resolve junction info for ${s}.${t.relationName}`);let u=this.uniqueValues(e.map(k=>k._id)),c=new Map;for(let k of e)c.set(this.keyOf(k._id),[]);if(u.length===0)return{grouped:c,docs:[]};let d=t.userFilter?pe(this.normalizeMetadata(),t.userFilter,t.targetTable):null,l=t.userLimit,f=t.userPage;if(l!==void 0&&l>0){let k=f?(f-1)*l:0;return this.fetchM2MTopK(u,t,a,o,d,k,l)}let p=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1&&!d,y=this.hasDottedSort(t.userSort);if(!y)return this.fetchM2MEdgeBatch(u,t,a,o,d);let g=await K(u,k=>this.runQuery(()=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:k}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray()));if(g.length===0)return{grouped:c,docs:[],stats:{strategy:"m2m-batch",roundtrips:this.chunkCount(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:0}};let h=new Set,m=[];for(let k of g){let x=k[a.otherColumn];if(x==null)continue;let _=this.keyOf(x);h.has(_)||(h.add(_),m.push(x))}let b=[],w=new Map;if(p)b=m.map(k=>({_id:k})),this.sortDocsByPk(b);else{let k={_id:{$in:m}};d&&Object.keys(d).length>0&&Object.assign(k,d);let x;if(y){let _=this.buildSortAggregatePipeline(t.targetTable,k,t.userSort);o.projection&&_.push({$project:o.projection}),x=await this.runQuery(()=>this.db.collection(t.targetTable).aggregate(_).toArray())}else{let _=this.buildSortFromTokens(t.userSort)||{_id:1},v=this.projectionWithSortFields(o.projection,t.userSort),j={sort:_};v.projection&&(j.projection=v.projection),x=await K(m,S=>this.runQuery(()=>this.db.collection(t.targetTable).find({_id:{$in:S},...d||{}},j).toArray())),t.userSort?this.sortDocsInMemory(x,t.userSort):this.sortDocsByPk(x),this.removeHiddenFields(x,v.hiddenFields)}b=this.applyReadFallback(x,o)}for(let k of b)w.set(this.keyOf(k._id),k);let C=new Map;for(let k of g){let x=this.keyOf(k[a.selfColumn]),_=this.keyOf(k[a.otherColumn]);w.has(_)&&(C.has(_)||C.set(_,[]),C.get(_).push(x))}for(let k of b){let x=C.get(this.keyOf(k._id))||[];for(let _ of x)c.get(_)?.push(k)}let T=p||m.length===0?0:this.chunkCount(m);return{grouped:c,docs:b,stats:{strategy:p?"m2m-junction-batch":"m2m-batch",roundtrips:this.chunkCount(u)+T,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length+b.length}}}applyReadFallback(e,t){let n=t.pendingRenames??[];if(e.length===0||n.length===0)return e;let i=new Set(t.hiddenFields??[]);for(let o of e)for(let s of n)o[s.newName]===void 0&&o[s.oldName]!==void 0&&(o[s.newName]=o[s.oldName]),(i.has(s.oldName)||o[s.newName]!==void 0)&&delete o[s.oldName];return e}};async function mn(r,e,t,n,i=3,o=0,s,a,u,c){let d=await c?.getActiveFieldRenamesByTable?.(),l=new Xe(r,a,d);await new Te(l,n,u).execute(e,t,i,o,s)}async function Gn(r,e,t){let n=[],{db:i,metadata:o,dbType:s,debugLog:a}=t,u=o?.tables?.get(e.table),c=new Set((u?.relations??[]).map(S=>S.propertyName)),d=!!e.mongoRawFilter&&!!o&&ne(e.mongoRawFilter,c),l=e.plan,f=l?.filterTree&&!l.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&o&&d){let S=await $e(e.mongoRawFilter,e.table,o,i);S&&Object.keys(S).length>0&&n.push({$match:S})}else if(f){let S=ze(l.filterTree,{metadata:o,rootTable:e.table});Object.keys(S).length>0&&n.push({$match:S})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let S=Qe(o,e.where,e.table,s);n.push({$match:S})}let p=e.plan,g=p?p.hasRelationSort:e.sort?.some(S=>{if(!S.field.includes("."))return!1;let E=S.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(A=>A.propertyName===E)??!1})??!1,h=()=>p?.sortItems?Co(p.sortItems):e.sort?So(e.sort):null,m=p?.sortItems?bo(p.sortItems):[],b=p?.sortItems?_o(p.sortItems):[],w=()=>{!p||m.length===0||wo(n,e.table,p.sortItems,o)},C=()=>{!p||b.length===0||$o(n,e.table,p.sortItems,o)},T=()=>{let S=[...m,...b];S.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(S.map(E=>[E,0]))})};if(!e.mongoFieldsExpanded){w(),C();let S=h();if(S&&n.push({$sort:S}),e.mongoCountOnly?n.push({$count:"count"}):(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit})),T(),e.select){let A={};for(let D of e.select)A[D]=1;n.push({$project:A})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let E=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:E,pipeline:n}:{results:zr(E),pipeline:n}}let{scalarFields:k,relations:x}=e.mongoFieldsExpanded;if(!g){w(),C();let S=h();S&&n.push({$sort:S}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}let _=[];for(let S of x)if(e.sort?.some(A=>A.field.startsWith(`${S.propertyName}.`))){let A=e.mongoRawFilter?.[S.propertyName];if(S.nestedFields&&S.nestedFields.length>0){let B=await At(o,S.targetTable,S.nestedFields??[],A);S.type==="one"&&B.length>0&&B.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:B.length>0?B:void 0}})}else if(A){let B=await At(o,S.targetTable,["_id"],A);S.type==="one"&&B.length>0&&B.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:B.length>0?B:void 0}})}else n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName}});S.type==="one"&&(n.push({$unwind:{path:`$${S.propertyName}`,preserveNullAndEmptyArrays:!0}}),A&&(Ze(A)||n.push({$match:{[S.propertyName]:{$ne:null}}})))}else _.push(S);if(g){w(),C();let S=h();S&&n.push({$sort:S}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}T(),await Qr(o,n,e.table,k,[...x]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let v=performance.now(),j=await r.aggregate(n).toArray();if(e.debugTrace?.dur("db_execute",v,{table:e.table}),e.mongoCountOnly)return{results:j,pipeline:n};if(_.length>0&&j.length>0){let S=e.deep||{},E=_.map(D=>{let $=o?.tables?.get(e.table)?.relations?.find(J=>J.propertyName===D.propertyName),R=S[D.propertyName],N=R?.fields!=null?Array.isArray(R.fields)?R.fields:String(R.fields).split(",").map(J=>J.trim()).filter(Boolean):D.nestedFields&&D.nestedFields.length>0?D.nestedFields:["_id"];return{relationName:D.propertyName,type:$?.type,targetTable:D.targetTable,fields:N,isInverse:$?.isInverse,mappedBy:$?.mappedBy,junctionTableName:$?.junctionTableName,junctionSourceColumn:$?.junctionSourceColumn,junctionTargetColumn:$?.junctionTargetColumn,localField:D.localField,foreignField:D.foreignField,userFilter:R?.filter,userSort:R?.sort,userLimit:R?.limit!==void 0?Number(R.limit):void 0,userPage:R?.page!==void 0?Number(R.page):void 0,nestedDeep:R?.deep}}),A=To(o);A&&await mn(i,j,E,A,3,0,e.table,o,e.debugTrace,t.mongoPhysicalMigrationService)}return{results:zr(j),pipeline:n}}function Yn(r){return`__sort_count_${r.relationName||r.field}`}function Xn(r){return`__sort_${r.function}_${r.relationName||r.field}_${r.aggregateField||"value"}`}function bo(r){return r.filter(e=>e.function==="count").map(Yn)}function _o(r){return r.filter(e=>e.function==="max"||e.function==="min").map(Xn)}function wo(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="count")continue;let a=s.relationMeta,u=s.relationName||s.field,c=a?.targetTableName||a?.targetTable,d=Yn(s);if(!(!a||!c)){if(a.type==="one-to-many"){let l=q(a)||u;r.push({$lookup:{from:c,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${l}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let l=Ne(e,a);if(!l)continue;r.push({$lookup:{from:l.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${l.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}})}}}}function $o(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="max"&&s.function!=="min")continue;let a=s.relationMeta,u=s.relationName||s.field,c=a?.targetTableName||a?.targetTable,d=n?.tables?.get(c),l=d?.columns?.find(h=>h.isPrimary)?.name||(d?.columns?.some(h=>h.name==="_id")?"_id":"id"),f=s.aggregateField,p=f==="id"&&d?.columns?.some(h=>h.name==="_id")?"_id":f,y=Xn(s),g=s.function==="min"?"$min":"$max";if(!(!a||!c||!f)){if(a.type==="one-to-many"){let h=q(a)||u;r.push({$lookup:{from:c,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${h}`,"$$localId"]}}},{$group:{_id:null,value:{[g]:`$${p}`}}}],as:y}}),r.push({$addFields:{[y]:{$arrayElemAt:[`$${y}.value`,0]}}});continue}if(a.type==="many-to-many"){let h=Ne(e,a);if(!h)continue;let m=`${y}_junction`;r.push({$lookup:{from:h.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${h.selfColumn}`,"$$localId"]}}},{$project:{_id:0,targetId:`$${h.otherColumn}`}}],as:m}}),r.push({$lookup:{from:c,let:{targetIds:`$${m}.targetId`},pipeline:[{$match:{$expr:{$in:[`$${l}`,"$$targetIds"]}}},{$group:{_id:null,value:{[g]:`$${p}`}}}],as:y}}),r.push({$addFields:{[y]:{$arrayElemAt:[`$${y}.value`,0]}}}),r.push({$project:{[m]:0}})}}}}function To(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(i=>({name:i.name,type:i.type})),relations:n.relations||[]}:null}:null}function So(r){let e={};for(let t of r){let n=t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function Co(r){let e={};for(let t of r){let n=t.function==="count"?Yn(t):t.function==="max"||t.function==="min"?Xn(t):t.joinId!==null?t.fullPath:t.field;e[n]=t.direction==="asc"?1:-1}return e}function Ze(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ze(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ze(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ze(e));if("_not"in r)return Ze(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Ze(t)))return!0}return!1}function zr(r){return r.map(X)}function Vr(r,e){let t=[],n=[],i=e?.tables?.get(r.rootTable);if(!i)return{scalarFields:t,relations:n};for(let o of r.nodes)if(o.kind==="wildcard")for(let s of i.columns||[])t.includes(s.name)||t.push(s.name);else o.kind==="scalar"?i.columns?.some(a=>a.name===o.name)&&!t.includes(o.name)&&t.push(o.name):o.kind==="relation"&&n.push(ko(o,i,e));return{scalarFields:t,relations:n}}function ko(r,e,t){let n=e.relations?.find(c=>c.propertyName===r.propertyName),i,o,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&Ie(n)?(i="_id",o=q(n)||r.propertyName,s=!0):(i=n&&V(n)||r.propertyName,o="_id",s=!1):r.relationType==="one-to-many"?(i="_id",o=n&&q(n)||r.propertyName,s=!0):n?.mappedBy?(i="_id",o=n.mappedBy,s=!0):(i=r.propertyName,o="_id",s=!1);let a=r.relationType==="one-to-many"||r.relationType==="many-to-many",u=Hr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:i,foreignField:o,type:a?"many":"one",isInverse:s,nestedFields:u}}function Hr(r){let e=[];for(let t of r)if(t.kind==="wildcard")e.push("*");else if(t.kind==="scalar")e.push(t.name);else if(t.kind==="relation"){let n=Hr(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let i of n)e.push(`${t.propertyName}.${i}`)}return e}Je();Mt();Et();function bn(r,e,t,n){let i={rootTable:e,nodes:[]};if(!r||r.length===0)return i;let o=t?.tables?.get(e);if(!o)return i;let s=o.columns?.some(l=>l.name==="_id"&&l.isPrimary),a=o.columns?.some(l=>l.name==="id"),u=s&&!a?"_id":"id",c=new Map,d=[];for(let l of r){let f=l==="id"?u:l;if(f==="*")d.push("*");else if(f.includes(".")){let p=f.indexOf("."),y=f.substring(0,p),g=f.substring(p+1);if(!o.relations?.some(m=>m.propertyName===y))continue;c.has(y)||c.set(y,[]),c.get(y).push(g)}else if(o.relations?.some(y=>y.propertyName===f))c.has(f)||c.set(f,[u]);else{if(!o.columns?.some(g=>g.name===f))continue;d.push(f)}}if(d.includes("*")){i.nodes.push({kind:"wildcard"});for(let l of o.relations||[])c.has(l.propertyName)||c.set(l.propertyName,[u])}else for(let l of d)i.nodes.push({kind:"scalar",name:l});for(let[l,f]of c.entries()){let p=o.relations?.find(h=>h.propertyName===l);if(!p)continue;let y=p.targetTableName||p.targetTable,g={kind:"relation",propertyName:l,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:y,children:Gr(f,y,t)};if(p.type==="many-to-one"||p.type==="one-to-one"){let h=n.registerWithParent(e,l,t,"left",null,"data");g.joinId=h}i.nodes.push(g)}return i}function Gr(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let i=n.columns?.some(d=>d.name==="_id"&&d.isPrimary),o=n.columns?.some(d=>d.name==="id"),s=i&&!o?"_id":"id",a=new Map,u=[];for(let d of r){let l=d==="id"?s:d;if(l==="*")u.push("*");else if(l.includes(".")){let f=l.indexOf("."),p=l.substring(0,f),y=l.substring(f+1);if(!n.relations?.some(h=>h.propertyName===p))continue;a.has(p)||a.set(p,[]),a.get(p).push(y)}else if(n.relations?.some(p=>p.propertyName===l))a.has(l)||a.set(l,[s]);else{if(!n.columns?.some(y=>y.name===l))continue;u.push(l)}}let c=[];if(u.includes("*")){c.push({kind:"wildcard"});for(let d of n.relations||[])a.has(d.propertyName)||a.set(d.propertyName,[s])}else for(let d of u)c.push({kind:"scalar",name:d});for(let[d,l]of a.entries()){let f=n.relations?.find(y=>y.propertyName===d);if(!f)continue;let p=f.targetTableName||f.targetTable;c.push({kind:"relation",propertyName:d,joinId:null,relationType:f.type,isInverse:!!f.isInverse,targetTable:p,children:Gr(l,p,t)})}return c}ue();ue();var Ro=new Set(["_and","_or","_not"]);function Yr(r,e){return r?.tables?.get(e)??null}function xo(r,e,t){return Yr(r,e)?.columns?.find(n=>n.name===t)}function Zn(r,e,t){return Yr(r,e)?.relations?.find(n=>n.propertyName===t)}function Fo(r){let e=r.match(/^_(count|max|min)\(([^)]+)\)$/);if(!e)return null;let t=e[1],n=e[2].trim();if(t==="count")return{functionName:t,relationName:n};let i=n.indexOf(".");return i<=0||i!==n.lastIndexOf(".")?null:{functionName:t,relationName:n.slice(0,i).trim(),fieldName:n.slice(i+1).trim()}}function er(r,e,t,n){if(xo(r,e,t)?.isEncrypted===!0)throw new I(`Encrypted field '${t}' on '${e}' cannot be used for ${n}.`)}function Oe(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){for(let n of r)Oe(n,e,t);return}for(let[n,i]of Object.entries(r)){if(Ro.has(n)){Oe(i,e,t);continue}if(n.startsWith("_"))continue;let o=Zn(t,e,n);if(o){let s=o.targetTableName||o.targetTable;s&&Oe(i,s,t);continue}er(t,e,n,"filter")}}}function _n(r,e,t){if(!r)return;let n=Array.isArray(r)?r:r.split(",").map(i=>i.trim()).filter(Boolean);for(let i of n){let o=i.startsWith("-")?i.slice(1):i;if(!o)continue;let s=Fo(o);if(s){if(s.functionName==="count")continue;let c=Zn(t,e,s.relationName),d=c?.targetTableName||c?.targetTable;d&&er(t,d,s.fieldName,"sort");continue}let a=o.split("."),u=e;for(let c=0;c<a.length;c++){let d=a[c];if(c===a.length-1){er(t,u,d,"sort");break}let f=Zn(t,u,d);if(!f)break;u=f.targetTableName||f.targetTable||u}}}var ee=class{plan(e){let{tableName:t,fields:n,filter:i,sort:o,page:s,limit:a,meta:u,metadata:c,dbType:d}=e,l=c?.tables?.get(t),f=new ie,p=this.parseFields(n),y=null;p&&l&&(y=bn(p,t,c,f));let g=!1,h=null;if(i&&l){Oe(i,t,c);let S=de(i,t,c,f);h=S.node,g=S.hasRelationFilters}let m=this.parseSort(o);l&&_n(m,t,c);let b=[],w=!1;for(let S of m){let E=S.startsWith("-"),A=E?S.substring(1):S,D=E?"desc":"asc";if(l){let B=this.parseRelationAggregateSort(t,l,A,c);if(B){b.push({joinId:null,field:A,direction:D,fullPath:A,function:B.functionName,relationName:B.relationName,aggregateField:B.aggregateField,relationMeta:B.relationMeta});continue}this.assertLocalSortField(t,l,A)}b.push({joinId:null,field:A,direction:D,fullPath:A})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let C=this.parseLimit(a),T=this.parsePage(s),k=T!==void 0&&C!==void 0?(T-1)*C:void 0,x=this.parseMeta(u),_=x.includes("totalCount")||x.includes("*"),v=x.includes("filterCount")||x.includes("*"),j=f.getAll();return{table:t,dbType:d,rawFields:p,rawFilter:i??null,joins:j,sortItems:b,limit:C,offset:k,needsTotalCount:_,needsFilterCount:v,hasRelationFilters:g,hasRelationSort:w,filterTree:h,fieldTree:y}}parseFields(e){if(e)return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):e.split(",").map(t=>t.trim()).filter(Boolean)}parseSort(e){return e?(Array.isArray(e)?e:e.split(",")).map(n=>n.trim()).filter(Boolean):[]}parseLimit(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;if(!Number.isNaN(t))return t<0?0:t}parsePage(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;return Number.isNaN(t)?void 0:t}parseMeta(e){return e?Array.isArray(e)?e:e.split(",").map(t=>t.trim()).filter(Boolean):[]}assertLocalSortField(e,t,n){if(n.includes("."))throw new I(`Sort field '${n}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let i=t.columns?.some(s=>s.name===n),o=n==="id"&&t.columns?.some(s=>s.name==="_id");if(!i&&!o)throw new I(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationAggregateSort(e,t,n,i){let o=n.match(/^_(count|max|min)\(([^)]+)\)$/);if(!o){if(/^_(count|max|min)\(/.test(n))throw new I(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName), _max(relationName.fieldName), or _min(relationName.fieldName).`);return null}let s=o[1],a=o[2].trim();if(s==="count"){let h=a;if(!h||h.includes("."))throw new I(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let m=t.relations?.find(b=>b.propertyName===h);if(!m)throw new I(`Sort relation '${h}' does not exist on '${e}'.`);if(m.type!=="one-to-many"&&m.type!=="many-to-many")throw new I(`Sort function '_count(${h})' is only supported for list relations on '${e}'.`);return{functionName:s,relationName:h,relationMeta:m}}let u=a.indexOf(".");if(u<=0||u!==a.lastIndexOf("."))throw new I(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let c=a.slice(0,u).trim(),d=a.slice(u+1).trim();if(!c||!d)throw new I(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let l=t.relations?.find(h=>h.propertyName===c);if(!l)throw new I(`Sort relation '${c}' does not exist on '${e}'.`);if(l.type!=="one-to-many"&&l.type!=="many-to-many")throw new I(`Sort function '_${s}(${c}.${d})' is only supported for list relations on '${e}'.`);let f=l.targetTableName||l.targetTable,p=i?.tables?.get(f);if(!p)throw new I(`Sort function '${n}' references unknown target table '${f}' on '${e}'.`);let y=p.columns?.find(h=>h.name===d),g=d==="id"&&p.columns?.some(h=>h.name==="_id");if(!y&&!g)throw new I(`Sort field '${d}' does not exist on '${f}' for function '_${s}(${c}.${d})'.`);if(y?.isEncrypted===!0)throw new I(`Encrypted field '${d}' on '${f}' cannot be used for sort.`);return{functionName:s,relationName:c,aggregateField:d,relationMeta:l}}registerSortJoinChain(e,t,n,i,o){let s=e.indexOf(".");if(s===-1)return null;let a=e.slice(0,s),u=e.slice(s+1),c=n?.tables?.get(t);if(!c)return null;let d=c.relations?.find(p=>p.propertyName===a);if(!d||d.type!=="many-to-one"&&d.type!=="one-to-one")return null;let l=i.registerWithParent(t,a,n,"left",o,"sort");if(!l)return null;if(!u.includes("."))return{lastJoinId:l,field:u};let f=d.targetTableName||d.targetTable;return this.registerSortJoinChain(u,f,n,i,l)}};ue();var vo=new Set(["int","integer","bigint","smallint","tinyint","float","double","decimal","numeric","real","number"]),Io=new Set(["date","datetime","timestamp","timestamptz","timestamp with time zone","timestamp without time zone"]),No=new Set(["hour","day","week","month","year"]),Eo=new Set(["count","countDistinct","sum","avg","min","max"]);function O(r,e){throw new I(e,{path:r})}function et(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Mo(r,e){let t=r?.tables?.get(e);return t||O("aggregate",`Table "${e}" metadata is not available`),t}function Xr(r,e,t){let n=r.columns?.find(i=>i.name===e);return n||O(t,`Unknown aggregate field "${e}"`),n.isEncrypted===!0&&O(t,`Encrypted field "${e}" cannot be used in aggregate queries`),n}function Oo(r,e){let t=r===void 0?"UTC":r;(typeof t!="string"||t.length===0)&&O(e,"Aggregate timezone must be a non-empty IANA timezone");try{new Intl.DateTimeFormat("en-US",{timeZone:t}).format()}catch{O(e,`Invalid aggregate timezone "${t}"`)}return t}function Ao(r,e){return r==null?{}:(et(r)||O(e,"Aggregate filter must be an object"),r)}function tt(r,e,t){et(r)||O("aggregate","Aggregate options must be an object");let n=Mo(t,e),i=r.dimensions===void 0?[]:r.dimensions,o=r.measures;Array.isArray(i)||O("aggregate.dimensions","Aggregate dimensions must be an array"),(!et(o)||Object.keys(o).length===0)&&O("aggregate.measures","Aggregate requires at least one measure");let s=new Set,a=i.map((g,h)=>{let m=`aggregate.dimensions[${h}]`;(!et(g)||typeof g.field!="string"||g.field.length===0)&&O(m,"Aggregate dimension requires a field");let b=Xr(n,g.field,`${m}.field`);return s.has(g.field)&&O(`${m}.field`,`Duplicate aggregate dimension "${g.field}"`),s.add(g.field),g.bucket===void 0?(g.timezone!==void 0&&O(`${m}.timezone`,"Aggregate timezone requires a bucket"),{field:g.field,outputKey:g.field,column:b}):((typeof g.bucket!="string"||!No.has(g.bucket))&&O(`${m}.bucket`,"Aggregate bucket must be hour, day, week, month, or year"),Io.has(String(b.type).toLowerCase())||O(`${m}.bucket`,`Aggregate bucket requires a date field, but "${g.field}" is "${b.type}"`),{field:g.field,outputKey:g.field,bucket:g.bucket,timezone:Oo(g.timezone,`${m}.timezone`),column:b})}),u=new Set,c=Object.entries(o).map(([g,h])=>{let m=`aggregate.measures.${g}`;(!g||!et(h))&&O(m,"Aggregate measure must be an object");let b=Object.entries(h).filter(([k])=>k!=="as");b.length!==1&&O(m,"Aggregate measure must define exactly one operation");let[w,C]=b[0];Eo.has(w)||O(m,`Unsupported aggregate measure "${w}"`),(typeof C!="string"||C.length===0)&&O(m,"Aggregate measure field must be a non-empty string");let T=Xr(n,C,`${m}.${w}`);return(u.has(g)||s.has(g))&&O(m,`Aggregate output key "${g}" is duplicated`),u.add(g),["sum","avg","min","max"].includes(w)&&!vo.has(String(T.type).toLowerCase())&&O(m,`Aggregate ${w} requires a numeric field, but "${C}" is "${T.type}"`),{outputKey:g,operation:w,field:C,column:T}}),d=r.sort===void 0?[]:r.sort;Array.isArray(d)||O("aggregate.sort","Aggregate sort must be an array");let l=new Set([...s,...u]),f=d.map((g,h)=>{let m=`aggregate.sort[${h}]`;return(!et(g)||typeof g.field!="string"||!l.has(g.field))&&O(m,"Aggregate sort field must reference a dimension or measure output"),g.direction!=="asc"&&g.direction!=="desc"&&O(`${m}.direction`,"Aggregate sort direction must be asc or desc"),{field:g.field,direction:g.direction}}),p=r.limit===void 0?void 0:Number(r.limit),y=r.page===void 0?1:Number(r.page);return p!==void 0&&(!Number.isInteger(p)||p<=0||p>1e4)&&O("aggregate.limit","Aggregate limit must be an integer between 1 and 10000"),(!Number.isInteger(y)||y<=0)&&O("aggregate.page","Aggregate page must be a positive integer"),{tableName:e,filter:Ao(r.filter,"aggregate.filter"),dimensions:a,measures:c,sort:f,page:y,limit:p}}var Ae=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.debugLog=[];this.lastBuiltPipeline=null;this.db=e.getDb()}async execute(e){if(this.metadata=e.metadata,this.dbType=e.dbType||"mongodb",!e.plan){let l=new ee;e={...e,plan:l.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:"mongodb"})}}let t=e.debugLog||[];this.debugLog=t;let n={table:e.tableName,metadata:e.metadata,debugTrace:e.debugTrace};if(e.pipeline&&(n.pipeline=e.pipeline),e.fields&&(Array.isArray(e.fields)?n.fields=e.fields:typeof e.fields=="string"&&(n.fields=e.fields.split(",").map(l=>l.trim()))),e.filter&&(re(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let l=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(f=>f.trim());n.sort=l.map(f=>{let p=f.trim();return p.startsWith("-")?{field:p.substring(1),direction:"desc"}:{field:p,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let l=typeof e.page=="string"?parseInt(e.page,10):e.page,f=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(l-1)*f,n.limit=f}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let i=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(l=>l.trim()).filter(Boolean),o=0,s=0;(i.includes("totalCount")||i.includes("*"))&&(o=await this.mongoService.collection(e.tableName).countDocuments({}));let a=this.metadata?.tables?.get(e.tableName),u=new Set((a?.relations??[]).map(l=>l.propertyName)),c=!!n.mongoRawFilter&&ne(n.mongoRawFilter,u);if((i.includes("filterCount")||i.includes("*"))&&!c){let l=this.mongoService.collection(e.tableName),f=e.plan?.filterTree?ze(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await l.countDocuments(f)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let d=await this.selectLegacy(n);if(e.debugMode){let l=this.lastBuiltPipeline??[],f;try{f=await this.db.collection(e.tableName).aggregate(l).explain()}catch(p){f={error:String(p)}}return{pipeline:l,explain:f}}if(c&&(i.includes("filterCount")||i.includes("*"))){let l={...n,mongoCountOnly:!0},f=await this.selectLegacy(l);s=f.length>0?f[0].count:0}return{data:d,...i.length>0&&{meta:{...i.includes("totalCount")||i.includes("*")?{totalCount:o}:{},...i.includes("filterCount")||i.includes("*")?{filterCount:s}:{}}}}}async aggregate(e){this.metadata=e.metadata,this.dbType=e.dbType||"mongodb";let t=tt(e.aggregate,e.tableName,e.metadata),n=this.db.collection(e.tableName),i=new ee().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:"mongodb"}),o=i.hasRelationFilters?await $e(t.filter,e.tableName,e.metadata,this.db):i.filterTree?ze(i.filterTree,{metadata:e.metadata,rootTable:e.tableName}):{},s=[];Object.keys(o).length>0&&s.push({$match:o});let a={_id:{}},u={};for(let d of t.dimensions){let l=`$${d.field}`,f=d.bucket?{$dateTrunc:{date:l,unit:d.bucket,timezone:d.timezone}}:l;a._id[d.outputKey]=f,u[d.outputKey]=`$_id.${d.outputKey}`}for(let d of t.measures){let l=`$${d.field}`;a[d.outputKey]=d.operation==="count"?{$sum:{$cond:[{$ne:[l,null]},1,0]}}:d.operation==="countDistinct"?{$addToSet:l}:{[`$${d.operation}`]:l},u[d.outputKey]=d.operation==="countDistinct"?{$size:{$setDifference:[`$${d.outputKey}`,[null]]}}:`$${d.outputKey}`}return s.push({$group:a},{$project:{_id:0,...u}}),t.sort.length>0&&s.push({$sort:Object.fromEntries(t.sort.map(d=>[d.field,d.direction==="asc"?1:-1]))}),t.limit!==void 0&&s.push({$skip:(t.page-1)*t.limit},{$limit:t.limit}),this.lastBuiltPipeline=s,e.debugMode?{pipeline:s,explain:await n.aggregate(s).explain()}:{data:(await n.aggregate(s).toArray()).map(X)}}async selectLegacy(e){let t=[],n=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,i=this.metadata?.tables?.get(e.table),o=i?.relations&&i.relations.length>0;if(e.fields&&e.fields.length>0||n||o){let c=e.plan,d=e.fields&&e.fields.length>0?e.fields:["*"];if(e.fields&&e.fields.length>0&&c?.fieldTree){if(e.mongoFieldsExpanded=Vr(c.fieldTree,this.metadata),n){let l=await It(this.metadata,e.table,[],e.deep),f=new Set(e.mongoFieldsExpanded.relations.map(p=>p.propertyName));e.mongoFieldsExpanded.relations.push(...l.relations.filter(p=>!f.has(p.propertyName)))}}else console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await It(this.metadata,e.table,d,e.deep);if(this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let l=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:l.scalarFields},t=l.hiddenFields}}e.where&&(e.where=e.where.map(c=>c.field.includes(".")?c:{...c,field:`${e.table}.${c.field}`}));let s=this.db.collection(e.table);if(e.pipeline)return this.debugLog&&this.debugLog.push({type:"MongoDB Custom Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(e.pipeline))}),(await s.aggregate(e.pipeline).toArray()).map(X);let{results:a,pipeline:u}=await Gn(s,e,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=u,this.mongoPhysicalMigrationService?await this.mongoPhysicalMigrationService.applyReadFallback(e.table,a,t):a}async executeAggregationPipeline(e,t){let{results:n,pipeline:i}=await Gn(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=i,n}};var wn=class{constructor(e){this.context=e}log(e){console.log(this.format(e))}warn(e){console.warn(this.format(e))}error(e,t){console.error(this.format(e)),t&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}fatal(e,t){this.error(e,t)}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};ue();ae();var Po=["_and","_or","_not"];function ge(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>ge(e));for(let e of Object.keys(r))if(Po.includes(e)||typeof r[e]=="object"&&r[e]!==null&&ge(r[e]))return!0;return!1}var Zr=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function jo(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function $n(r,e,t){if(!t)return!1;let n=r;if(r.includes(".")){let s=r.split(".");n=s[s.length-1]}let i=t.columns.find(s=>s.name===n);if(!i)return!1;let o=i.type?.toLowerCase()||"";return o==="uuid"||o==="uuidv4"||o.includes("uuid")}function Bo(r,e,t,n,i){return n!=="postgres"||typeof e!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||$n(r,t,i),e}function ei(r,e,t,n,i,o,s){let a=i&&!e.includes(".")?`${i}.${e}`:e,u=ke(a,o??"postgres"),c=$n(e,i,s),d=Bo(e,n,i,o,s);switch(t){case"_eq":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} = ?::uuid`,[n]):r.where(a,"=",d);break;case"_neq":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} != ?::uuid`,[n]):r.where(a,"!=",d);break;case"_gt":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} > ?::uuid`,[n]):r.where(a,">",d);break;case"_gte":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} >= ?::uuid`,[n]):r.where(a,">=",d);break;case"_lt":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} < ?::uuid`,[n]):r.where(a,"<",d);break;case"_lte":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} <= ?::uuid`,[n]):r.where(a,"<=",d);break;case"_in":let l=n;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(p=>p.trim()):[l]),c&&o==="postgres"&&l.every(p=>typeof p=="string")?r.whereRaw(`${u} = ANY(?::uuid[])`,[l]):r.whereIn(a,l);break;case"_not_in":case"_nin":let f=n;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]),c&&o==="postgres"&&f.every(p=>typeof p=="string")?r.whereRaw(`${u} != ALL(?::uuid[])`,[f]):r.whereNotIn(a,f);break;case"_contains":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_starts_with":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${u}) LIKE lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_ends_with":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?))`,[n]):o==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?)`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`,[n]);break;case"_between":Array.isArray(n)&&n.length===2&&r.whereBetween(a,[n[0],n[1]]);break;case"_is_null":n===!0?r.whereNull(a):r.whereNotNull(a);break;case"_is_not_null":n===!0?r.whereNotNull(a):r.whereNull(a);break;default:r.where(a,jo(t),n)}}function Lo(r,e,t){if(!t||!e||r.startsWith("_"))return!0;let n=r.includes(".")?r.split(".").pop():r,i=t.columns?.some(s=>s.name===n),o=t.relations?.some(s=>s.propertyName===n);return i||o}function nt(r,e,t,n="and",i,o){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let s of e)n==="and"?r.where(function(){nt(this,s,t,"and",i,o)}):r.orWhere(function(){nt(this,s,t,"and",i,o)});return}for(let[s,a]of Object.entries(e))if(Lo(s,t,o)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){nt(this,u,t,"and",i,o)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){nt(this,u,t,"and",i,o)})});continue}if(s==="_not"){r.whereNot(function(){nt(this,a,t,"and",i,o)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(c=>Zr.includes(c)))for(let[c,d]of Object.entries(a))Zr.includes(c)&&(n==="and"?r.where(function(){ei(this,s,c,d,t,i,o)}):r.orWhere(function(){ei(this,s,c,d,t,i,o)}));else{let c=t&&!s.includes(".")?`${t}.${s}`:s,d=ke(c,i??"postgres");$n(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${d} = ?::uuid`,[a]):r.orWhereRaw(`${d} = ?::uuid`,[a]):n==="and"?r.where(c,"=",a):r.orWhere(c,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s,c=ke(u,i??"postgres");$n(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${c} = ?::uuid`,[a]):r.orWhereRaw(`${c} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function le(r,e,t,n,i){return!e||typeof e!="object"||nt(r,e,t,"and",n,i),r}ae();function rr(r,e,t){return`${F(r,t)}.${F(e,t)}`}function Re(r,e){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function ti(r,e){if(!e)return!1;let t=e.columns.find(i=>i.name===r);if(!t)return!1;let n=t.type?.toLowerCase()||"";return n==="uuid"||n==="uuidv4"||n.includes("uuid")}function rt(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function ir(r,e,t,n,i,o){let s=[];for(let[a,u]of Object.entries(o)){let c=await Bt(r,e,a,u,t,n,i);if(c!==null)s.push(`EXISTS (${c})`);else{let d=t.relations.find(l=>l.propertyName===a);if(d&&d.foreignKeyColumn){let l=rr(e,d.foreignKeyColumn,n),p=u.id;if(p&&typeof p=="object"){let y=rt(p._is_null),g=rt(p._is_not_null);if(y===!0)s.push(`${l} IS NULL`);else if(y===!1)s.push(`${l} IS NOT NULL`);else if(g===!0)s.push(`${l} IS NOT NULL`);else if(g===!1)s.push(`${l} IS NULL`);else if(p._eq!==void 0){let h=Re(p._eq,n);s.push(`${l} = ${h}`)}else if(p._neq!==void 0){let h=Re(p._neq,n);s.push(`${l} != ${h}`)}else if(p._in!==void 0){let m=(Array.isArray(p._in)?p._in:[p._in]).map(b=>Re(b,n)).join(", ");s.push(`${l} IN (${m})`)}else if(p._not_in!==void 0||p._nin!==void 0){let h=p._not_in??p._nin,b=(Array.isArray(h)?h:[h]).map(w=>Re(w,n)).join(", ");s.push(`${l} NOT IN (${b})`)}else if(p._gt!==void 0){let h=Re(p._gt,n);s.push(`${l} > ${h}`)}else if(p._gte!==void 0){let h=Re(p._gte,n);s.push(`${l} >= ${h}`)}else if(p._lt!==void 0){let h=Re(p._lt,n);s.push(`${l} < ${h}`)}else if(p._lte!==void 0){let h=Re(p._lte,n);s.push(`${l} <= ${h}`)}}}}}return s}function or(r){return!r||typeof r!="object"||Array.isArray(r)?!1:!!(r._and&&Array.isArray(r._and)||r._or&&Array.isArray(r._or)||r._not!==void 0&&r._not!==null)}async function tr(r,e,t,n,i,o){let s=[];for(let a of r)if(a._and&&Array.isArray(a._and)&&a._and.length>0){let u=[];for(let c of a._and)if(or(c)){let d=e(t).select(`${t}.id`);await Pe(e,d,c,t,n,i,o),u.push({idSubquery:d})}else{let{fieldFilters:d,relationFilters:l}=H(c,n),f=await ir(e,t,n,i,o,l);u.push({fieldFilters:d,subqueries:f})}s.push(u)}else if(or(a)){let u=e(t).select(`${t}.id`);await Pe(e,u,a,t,n,i,o),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:c}=H(a,n),d=await ir(e,t,n,i,o,c);s.push([{fieldFilters:u,subqueries:d}])}return s}function ni(r,e,t,n,i){if("idSubquery"in e&&e.idSubquery){r.whereIn(`${t}.id`,e.idSubquery);return}let o=e;Object.keys(o.fieldFilters).length===0&&o.subqueries.length===0||r.where(function(){Object.keys(o.fieldFilters).length>0&&le(this,o.fieldFilters,t,i,n);for(let s of o.subqueries)this.whereRaw(s)})}function nr(r,e,t,n,i){let o=!0;for(let s of e){let a=function(){for(let u of s)ni(this,u,t,n,i)};o?(r.where(a),o=!1):r.orWhere(a)}}function Tn(r,e,t,n,i,o,s){let a=ti(e,i),u=ti(n,o),c=`${F(r,s)}.${F(e,s)}`,d=`${F(t,s)}.${F(n,s)}`;if(s==="postgres"){if(a&&!u)return`${c} = ${d}::uuid`;if(!a&&u)return`${c}::uuid = ${d}`}return`${c} = ${d}`}async function Bt(r,e,t,n,i,o,s){let a=i.relations.find(f=>f.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${e}"`);let u=a.targetTableName||a.targetTable;if(!u)throw new Error(`Relation "${t}" in table "${e}" is missing targetTable/targetTableName. Relation metadata: ${JSON.stringify(a,null,2)}`);let c=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn){let f=Object.keys(n||{});if(f.length===1&&f[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(y=>c.has(y)))return null}let d=s?await s(u):null,l;switch(a.type){case"one-to-many":l=r(u).select(r.raw("1")).whereRaw(Tn(u,a.foreignKeyColumn,e,"id",d,i,o));break;case"many-to-many":let f=s?await s(a.junctionTableName):null;l=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw(Tn(a.junctionTableName,a.junctionTargetColumn,u,"id",f,d,o))).whereRaw(Tn(a.junctionTableName,a.junctionSourceColumn,e,"id",f,i,o));break;case"many-to-one":case"one-to-one":l=r(u).select(r.raw("1")).whereRaw(Tn(u,"id",e,a.foreignKeyColumn,d,i,o));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?d?await Pe(r,l,n,u,d,o,s):l=le(l,n,u,o,d||void 0):l=le(l,n,u,o),l.toString()}async function Pe(r,e,t,n,i,o,s){if(!t||typeof t!="object")return;if(t._and&&Array.isArray(t._and)){for(let c of t._and)if(c._or&&Array.isArray(c._or)&&c._or.length>0){let d=await tr(c._or,r,n,i,o,s);e.where(function(){nr(this,d,n,i,o)})}else if(c._and&&Array.isArray(c._and)&&c._and.length>0)for(let d of c._and)await Pe(r,e,d,n,i,o,s);else await Pe(r,e,c,n,i,o,s);return}if(t._or&&Array.isArray(t._or)){let c=await tr(t._or,r,n,i,o,s);e.where(function(){nr(this,c,n,i,o)});return}if(t._not){let c=t._not;if(c._and&&Array.isArray(c._and)&&c._and.length>0){let f=[];for(let p of c._and)if(or(p)){let y=r(n).select(`${n}.id`);await Pe(r,y,p,n,i,o,s),f.push({idSubquery:y})}else{let{fieldFilters:y,relationFilters:g}=H(p,i),h=await ir(r,n,i,o,s,g);f.push({fieldFilters:y,subqueries:h})}e.whereNot(function(){for(let p of f)ni(this,p,n,i,o)});return}if(c._or&&Array.isArray(c._or)&&c._or.length>0){let f=await tr(c._or,r,n,i,o,s);e.whereNot(function(){nr(this,f,n,i,o)});return}let{fieldFilters:d,relationFilters:l}=H(c,i);e.whereNot(function(){Object.keys(d).length>0&&le(this,d,n,o,i)});for(let[f,p]of Object.entries(l)){let y=await Bt(r,n,f,p,i,o,s);if(y===null){let g=i.relations.find(h=>h.propertyName===f);if(g&&g.foreignKeyColumn){let h=rr(n,g.foreignKeyColumn,o),b=p.id;if(b&&typeof b=="object"){let w=rt(b._is_null),C=rt(b._is_not_null);if(w===!0)e.whereRaw(`${h} IS NOT NULL`);else if(w===!1)e.whereRaw(`${h} IS NULL`);else if(C===!0)e.whereRaw(`${h} IS NULL`);else if(C===!1)e.whereRaw(`${h} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${h} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${h} = ?`,[b._neq]);else if(b._in!==void 0){let T=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${h} NOT IN (${T.map(()=>"?").join(", ")})`,T)}else if(b._not_in!==void 0||b._nin!==void 0){let T=b._not_in??b._nin,k=Array.isArray(T)?T:[T];e.whereRaw(`${h} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${y})`)}return}let{fieldFilters:a,relationFilters:u}=H(t,i);Object.keys(a).length>0&&le(e,a,n,o,i);for(let[c,d]of Object.entries(u)){let l=await Bt(r,n,c,d,i,o,s);if(l===null){let f=i.relations.find(p=>p.propertyName===c);if(f&&f.foreignKeyColumn){let p=rr(n,f.foreignKeyColumn,o),g=d.id;if(g&&typeof g=="object"){let h=rt(g._is_null),m=rt(g._is_not_null);if(h===!0)e.whereRaw(`${p} IS NULL`);else if(h===!1)e.whereRaw(`${p} IS NOT NULL`);else if(m===!0)e.whereRaw(`${p} IS NOT NULL`);else if(m===!1)e.whereRaw(`${p} IS NULL`);else if(g._eq!==void 0)e.whereRaw(`${p} = ?`,[g._eq]);else if(g._neq!==void 0)e.whereRaw(`${p} != ?`,[g._neq]);else if(g._in!==void 0){let b=Array.isArray(g._in)?g._in:[g._in];e.whereRaw(`${p} IN (${b.map(()=>"?").join(", ")})`,b)}else if(g._not_in!==void 0||g._nin!==void 0){let b=g._not_in??g._nin,w=Array.isArray(b)?b:[b];e.whereRaw(`${p} NOT IN (${w.map(()=>"?").join(", ")})`,w)}}}}else e.whereRaw(`EXISTS (${l})`)}}async function Lt(r,e,t,n,i,o,s){await Pe(r,e,t,n,i,o,s)}ae();ae();function it(r,e,t,n,i){for(let o of e){let s=o.field.split("."),a=t||s[0],u=s[s.length-1],c=Dt(n,a,u,o.value);switch(o.operator){case"=":r=r.where(o.field,"=",c);break;case"!=":r=r.where(o.field,"!=",c);break;case">":r=r.where(o.field,">",c);break;case"<":r=r.where(o.field,"<",c);break;case">=":r=r.where(o.field,">=",c);break;case"<=":r=r.where(o.field,"<=",c);break;case"like":r=r.where(o.field,"like",c);break;case"in":let d=Array.isArray(o.value)?o.value.map(g=>Dt(n,a,u,g)):[c];r=r.whereIn(o.field,d);break;case"not in":let l=Array.isArray(o.value)?o.value.map(g=>Dt(n,a,u,g)):[c];r=r.whereNotIn(o.field,l);break;case"is null":r=r.whereNull(o.field);break;case"is not null":r=r.whereNotNull(o.field);break;case"_contains":r=r.where(o.field,"like",`%${o.value}%`);break;case"_starts_with":r=r.where(o.field,"like",`${o.value}%`);break;case"_ends_with":r=r.where(o.field,"like",`%${o.value}`);break;case"_between":let f=o.value;if(typeof f=="string"&&(f=f.split(",").map(g=>g.trim())),Array.isArray(f)&&f.length===2){let g=Dt(n,a,u,f[0]),h=Dt(n,a,u,f[1]);r=r.whereBetween(o.field,[g,h])}break;case"_is_null":r=c===!0||c==="true"?r.whereNull(o.field):r.whereNotNull(o.field);break;case"_is_not_null":r=c===!0||c==="true"?r.whereNotNull(o.field):r.whereNull(o.field);break}}return r}function Wt(r,e,t,n){let i=[],o=t;if(!r||typeof r!="object")return i;for(let[s,a]of Object.entries(r))if(s==="_and"&&Array.isArray(a)){let u=a.map(c=>{let d=Wt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&i.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(c=>{let d=Wt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&i.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=Wt(a,e,t,n);u.length>0&&i.push(`NOT (${u.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[u,c]of Object.entries(a)){let d=`${F(e,n)}.${F(s,n)}`,l;if(c===null)l="NULL";else if(typeof c=="string"){let f=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,p=o.columns?.find(g=>g.name===s);p&&(p.type?.toLowerCase()==="uuid"||p.type?.toLowerCase().includes("uuid"))&&f.test(c)&&n==="postgres"?l=`'${c}'::uuid`:l=`'${c.replace(/'/g,"''")}'`}else typeof c=="boolean"?l=c?"true":"false":typeof c=="number"?l=String(c):l=`'${String(c).replace(/'/g,"''")}'`;if(u==="_eq")i.push(`${d} = ${l}`);else if(u==="_neq")i.push(`${d} != ${l}`);else if(u==="_gt")i.push(`${d} > ${l}`);else if(u==="_gte")i.push(`${d} >= ${l}`);else if(u==="_lt")i.push(`${d} < ${l}`);else if(u==="_lte")i.push(`${d} <= ${l}`);else if(u==="_is_null")i.push(`${d} IS NULL`);else if(u==="_is_not_null")i.push(`${d} IS NOT NULL`);else if(u==="_in"){let p=(Array.isArray(c)?c:[c]).map(y=>typeof y=="string"?`'${y.replace(/'/g,"''")}'`:String(y)).join(", ");i.push(`${d} IN (${p})`)}else if(u==="_not_in"||u==="_nin"){let p=(Array.isArray(c)?c:[c]).map(y=>typeof y=="string"?`'${y.replace(/'/g,"''")}'`:String(y)).join(", ");i.push(`${d} NOT IN (${p})`)}else if(u==="_contains"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${d}) LIKE '%${f.toLowerCase()}%'`)}else if(u==="_starts_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE lower(unaccent('${f}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${d}) LIKE '${f.toLowerCase()}%'`)}else if(u==="_ends_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}'))`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci)`):i.push(`lower(${d}) LIKE '%${f.toLowerCase()}'`)}else if(u==="_between"&&Array.isArray(c)&&c.length===2){let f=typeof c[0]=="string"?`'${c[0].replace(/'/g,"''")}'`:String(c[0]),p=typeof c[1]=="string"?`'${c[1].replace(/'/g,"''")}'`:String(c[1]);i.push(`${d} BETWEEN ${f} AND ${p}`)}}else{let u=`${F(e,n)}.${F(s,n)}`,c;a===null?c="NULL":typeof a=="string"?c=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?c=a?"true":"false":c=String(a),i.push(`${u} = ${c}`)}return i}function Kt(r){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Dt(r,e,t,n){if(n==null)return n;let i=r?.tables?.get(e);if(!i?.columns)return n;let o=i.columns.find(s=>s.name===t);if(!o)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;default:return n}}ar();Je();ae();qt();Ke();async function oi(r,e,t,n,i,o,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(cr(),ii)),u=await a(e,t,n,i,o,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function ur(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(i=>({name:i.name,type:i.type})),relations:n.relations||[]}:null}:null}function si(r,e,t,n,i){let o=r.targetTableName||r.targetTable;if(!o)return null;let s=r.foreignKeyColumn||z(r.propertyName);if(!s)return null;let a=l=>F(l,i),u=n?.tables?.get(o),d=(u?G(u):null)?.name||"id";return`(SELECT ${a(o)}.${a(e)} FROM ${a(o)} WHERE ${a(o)}.${a(d)} = ${a(t)}.${a(s)})`}qt();async function ai(r,e,t,n,i){let o={};if(n.includes("totalCount")||n.includes("*")){let s=await r(t).count("* as count").first();o.totalCount=Number(s?.count||0)}if(n.includes("filterCount")||n.includes("*")){let a=await e.clone().clearSelect().clearOrder().clear("limit").clear("offset").countDistinct(`${t}.id as count`).first();o.filterCount=Number(a?.count||0)}return o}var je=class r{constructor(e,t,n,i){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=i;this.logger=new wn(r.name);this.debugLog=[]}async execute(e){let t=performance.now();this.metadata=e.metadata;let n=e.debugLog||[];this.debugLog=n;let i=e.debugTrace;if(e.filter&&re(e.filter,e.tableName,e.metadata),!e.plan){let $=new ee;e={...e,plan:$.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:this.dbType})}}let o=e.plan,s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,u=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,c=o.rawFields&&o.rawFields.length>0&&!o.rawFields.includes("*");if(o.joins.length===0&&!o.hasRelationFilters&&!o.hasRelationSort&&!u&&!a&&c){i&&i.setQueryPath("simple");let $=await this.executeSimple(e,o);return i&&i.dur("sql_executor",t,{table:e.tableName}),$}let l={table:e.tableName,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?l.fields=e.fields:typeof e.fields=="string"&&(l.fields=e.fields.split(",").map($=>$.trim())));let f=e.filter;if(e.filter&&!ge(e.filter)){l.where=[];for(let[$,R]of Object.entries(e.filter))if(typeof R=="object"&&R!==null)for(let[N,J]of Object.entries(R)){let M;if(N==="_eq")M="=";else if(N==="_neq")M="!=";else if(N==="_in")M="in";else if(N==="_not_in"||N==="_nin")M="not in";else if(N==="_gt")M=">";else if(N==="_gte")M=">=";else if(N==="_lt")M="<";else if(N==="_lte")M="<=";else if(N==="_contains")M="_contains";else if(N==="_starts_with")M="_starts_with";else if(N==="_ends_with")M="_ends_with";else if(N==="_between")M="_between";else if(N==="_is_null")M="_is_null";else if(N==="_is_not_null")M="_is_not_null";else if(N==="_like")M="like";else if(N==="_ilike")M="ilike";else continue;l.where.push({field:$,operator:M,value:J})}else l.where.push({field:$,operator:"=",value:R})}if(e.sort){let $=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(R=>R.trim());l.sort=$.map(R=>{let N=R.trim();return N.startsWith("-")?{field:N.substring(1),direction:"desc"}:{field:N,direction:"asc"}})}else l.sort=[{field:"id",direction:"asc"}];let p=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,y=p===void 0||Number.isNaN(p)?void 0:p<0?0:p,g=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,h=g===void 0||Number.isNaN(g)?void 0:g;h&&y!==void 0?(l.offset=(h-1)*y,l.limit=y):y!==void 0&&(l.limit=y);let m=e.plan?.sortItems??(l.sort??[]).map($=>({joinId:null,field:$.field,direction:$.direction,fullPath:$.field})),b=[],w=[];for(let $ of m){if($.function==="count"){let R={sql:this.buildRelationCountSortSubquery(l.table,$),direction:$.direction};w.push(R);continue}if($.function==="max"||$.function==="min"){let R={sql:this.buildRelationAggregateSortSubquery(l.table,$),direction:$.direction};w.push(R);continue}if($.joinId===null){if($.field.includes(".")&&!e.plan){let N=$.field.split(".")[0];if(this.metadata?.tables?.get(l.table)?.relations?.some(Q=>Q.propertyName===N))continue}let R={field:$.field.includes(".")?$.field:`${l.table}.${$.field}`,direction:$.direction};b.push(R),w.push(R)}else{let R=e.plan?.joins.find(N=>N.id===$.joinId);if(R&&(R.relationType==="many-to-one"||R.relationType==="one-to-one")){let N=si(R.relationMeta,$.field,l.table,this.metadata,this.dbType);if(N){let J={sql:N,direction:$.direction};w.push(J)}}}}let C=[];if(l.fields&&l.fields.length>0||u||a){let $=ur(this.metadata),R=l.fields&&l.fields.length>0?l.fields:["*"],N=await oi(this.knex,l.table,R,$,this.dbType,this.maxQueryDepth,e.deep);N.select.length>0&&(l.select=[...l.select||[],...N.select]),C=N.batchFetchDescriptors||[]}l.where&&(l.where=l.where.map($=>$.field.includes(".")?$:{...$,field:`${l.table}.${$.field}`})),l.sort=b;let T=this.knex(l.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map($=>$.trim()).filter(Boolean),x=k.includes("filterCount")||k.includes("*"),_=k.includes("totalCount")||k.includes("*");if(l.select){let $=l.select.map(R=>typeof R=="string"&&R.trim().startsWith("(")?this.knex.raw(R):typeof R=="string"&&/ as /i.test(R)?this.knex.raw(R):R);T=T.select($)}if(x&&T.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),_){let $=F(l.table,this.dbType);T.select(this.knex.raw(`(SELECT COUNT(*) FROM ${$}) as __total_count__`))}let v=["table_definition","column_definition","relation_definition","method_definition"].includes(l.table);if(f&&(ge(f)||Object.keys(f).length>0)){let $=this.metadata?.tables?.get(l.table);(!v&&$&&$.relations&&$.relations.length>0?H(f,$).hasRelations:!1)?await Lt(this.knex,T,f,l.table,$,this.dbType,N=>this.metadata?.tables?.get(N)):e.plan?.filterTree?ce(T,e.plan.filterTree,{dbType:this.dbType,rootTable:l.table}):(this.logger.debug(`buildWhereClause fallback for table=${l.table}`),T=le(T,f,l.table,this.dbType,$))}else l.where&&l.where.length>0&&(T=it(T,l.where,l.table,this.metadata,this.dbType));for(let $ of w)if($.field){let R=$.field.includes(".")?$.field:`${l.table}.${$.field}`;T=T.orderBy(R,$.direction)}else $.sql&&(T=T.orderByRaw(`${$.sql} ${$.direction.toUpperCase()}`));l.groupBy&&(T=T.groupBy(l.groupBy)),l.offset&&(T=T.offset(l.offset)),l.limit!==void 0&&l.limit!==null&&l.limit>0&&(T=T.limit(l.limit));let j=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:l.table,sql:T.toSQL().toNative()});let S;if(e.debugMode&&(S=T.toSQL().toNative().sql),e.debugMode&&i){let $=T.toSQL().toNative();i.setSql($.sql);try{let R=$.sql.replace(/\$\d+/g,"?"),N=await this.knex.raw(`EXPLAIN ${R}`,$.bindings);i.setExplain(this.dbType==="postgres"?N.rows:N[0])}catch(R){i.setExplain({error:String(R)})}}let E,A=performance.now();E=await T,i&&i.dur("db_execute",A,{table:e.tableName});let D=await this.resolveEmptyPageMeta(T,l.table,k,E.length),B=D.filterCount??0;if(j=D.totalCount??0,x&&E.length>0&&(B=Number(E[0].__filter_count__||0),E.forEach($=>{delete $.__filter_count__})),_&&E.length>0&&E[0].__total_count__!==void 0&&(j=Number(E[0].__total_count__||0),E.forEach($=>{delete $.__total_count__})),C&&C.length>0&&E.length>0){let $=ur(this.metadata);if($){let{executeBatchFetches:R}=await Promise.resolve().then(()=>(pr(),li));await R(this.knex,E,C,$,this.maxQueryDepth??3,0,l.table,this.dbType,this.metadata,i)}}if(this.knexService){let $=performance.now();E=await this.knexService.parseResult(E,l.table),i&&i.dur("db_parseResult",$,{table:e.tableName})}else{let $=(R,N)=>{if(!R||!this.metadata)return R;let J=this.metadata.tables?.get(N);if(!J)return R;if(Array.isArray(R))return R.map(Q=>$(Q,N));if(typeof R!="object"||Buffer.isBuffer(R))return R;let M={...R};for(let Q of J.columns)if(Q.type==="simple-json"&&M[Q.name]&&typeof M[Q.name]=="string")try{M[Q.name]=JSON.parse(M[Q.name])}catch{}for(let[Q,Y]of Object.entries(M))if(Y&&typeof Y=="object"&&!Array.isArray(Y)&&!Buffer.isBuffer(Y)){let vn=Y;if(vn.id!==void 0||vn.createdAt!==void 0){let lt=J.relations?.find(ct=>ct.propertyName===Q);lt&&(M[Q]=$(Y,lt.targetTableName))}}else if(Array.isArray(Y)&&Y.length>0&&typeof Y[0]=="object"&&Y[0].id!==void 0){let lt=J.relations?.find(ct=>ct.propertyName===Q);lt&&(M[Q]=Y.map(ct=>$(ct,lt.targetTableName)))}return M};E=$(E,l.table)}return i&&(i.setQueryPath("full"),i.dur("sql_executor",t,{table:e.tableName})),{data:E,...k.length>0&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:j}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:B}:{}}},...S!==void 0&&{sql:S}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=G(s)?.name||"id",u=F(e,this.dbType),c=F(a,this.dbType);if(!n||!o)throw new I(`Sort relation '${i}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let d=n.foreignKeyColumn||n.mappedBy;if(!d)throw new I(`Sort function '_count(${i})' cannot resolve relation key on '${e}'.`);let l=F(o,this.dbType),f=F(d,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}if(n.type==="many-to-many"){let d=this.resolveManyToManyContract(n,i,e),l=F(d.tableName,this.dbType),f=F(d.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}throw new I(`Sort function '_count(${i})' is only supported for list relations on '${e}'.`)}buildRelationAggregateSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=t.aggregateField,s=n?.targetTableName||n?.targetTable,a=this.metadata?.tables?.get(e),u=this.metadata?.tables?.get(s),c=G(a)?.name||"id",d=G(u)?.name||"id",l=F(e,this.dbType),f=F(c,this.dbType),p=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!p||!n||!s||!o)throw new I(`Sort function '${t.field}' is not supported on '${e}'.`);let y=F(s,this.dbType),g=F(o,this.dbType);if(n.type==="one-to-many"){let h=n.foreignKeyColumn||n.mappedBy;if(!h)throw new I(`Sort function '_${t.function}(${i}.${o})' cannot resolve relation key on '${e}'.`);let m=F(h,this.dbType);return`(SELECT ${p}(${y}.${g}) FROM ${y} WHERE ${y}.${m} = ${l}.${f})`}if(n.type==="many-to-many"){let h=this.resolveManyToManyContract(n,i,e),m=F(h.tableName,this.dbType),b=F(h.sourceColumn,this.dbType),w=F(h.targetColumn,this.dbType),C=F(d,this.dbType);return`(SELECT ${p}(${y}.${g}) FROM ${m} JOIN ${y} ON ${y}.${C} = ${m}.${w} WHERE ${m}.${b} = ${l}.${f})`}throw new I(`Sort function '_${t.function}(${i}.${o})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,n){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new I(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async resolveEmptyPageMeta(e,t,n,i){return i>0||n.length===0?{}:ai(this.knex,e,t,n,!1)}async executeSimple(e,t){let n=e.tableName,i=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],o=this.knex(n).select(i);t.filterTree&&ce(o,t.filterTree,{dbType:this.dbType,rootTable:n});for(let h of t.sortItems){let m=h.field.includes(".")?h.field:`${n}.${h.field}`;o=o.orderBy(m,h.direction)}t.limit!==void 0&&t.limit!==null&&t.limit>0&&(o=o.limit(t.limit)),t.offset!==void 0&&(o=o.offset(t.offset));let s=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(h=>h.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),u=s.includes("totalCount")||s.includes("*");if(a&&o.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),u){let h=F(n,this.dbType);o.select(this.knex.raw(`(SELECT COUNT(*) FROM ${h}) as __total_count__`))}let c=e.debugTrace,d;if(e.debugMode){let h=o.toSQL().toNative();if(d=h.sql,c){c.setSql(h.sql);try{let m=h.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${m}`,h.bindings);c.setExplain(this.dbType==="postgres"?b.rows:b[0])}catch(m){c.setExplain({error:String(m)})}}}let l=performance.now(),f;f=await o,c&&c.dur("db_execute",l,{table:n}),this.knexService&&(f=await this.knexService.parseResult(f,n));let p=await this.resolveEmptyPageMeta(o,n,s,f.length),y=p.filterCount??0,g=p.totalCount??0;return a&&f.length>0&&(y=Number(f[0].__filter_count__||0),f.forEach(h=>delete h.__filter_count__)),u&&f.length>0&&(g=Number(f[0].__total_count__||0),f.forEach(h=>delete h.__total_count__)),{data:f,...s.length>0&&{meta:{...u?{totalCount:g}:{},...a?{filterCount:y}:{}}},...d!==void 0&&{sql:d}}}async aggregate(e){let t=tt(e.aggregate,e.tableName,e.metadata),n=this.knex(e.tableName),i=F(e.tableName,this.dbType),o=[],s=[];for(let l of t.dimensions){let f=`${i}.${F(l.field,this.dbType)}`,p=l.bucket?this.buildSqlBucketExpression(f,l.bucket,l.timezone,l.column.type):f;s.push(this.knex.raw(`${p} as ${F(l.outputKey,this.dbType)}`)),o.push(p)}for(let l of t.measures){let f=`${i}.${F(l.field,this.dbType)}`,p=l.operation==="count"?`COUNT(${f})`:l.operation==="countDistinct"?`COUNT(DISTINCT ${f})`:`${l.operation.toUpperCase()}(${f})`;s.push(this.knex.raw(`${p} as ${F(l.outputKey,this.dbType)}`))}let u=new ee().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:this.dbType});u.hasRelationFilters?await Lt(this.knex,n,t.filter,e.tableName,e.metadata?.tables?.get(e.tableName),this.dbType,l=>e.metadata?.tables?.get(l)):u.filterTree&&ce(n,u.filterTree,{dbType:this.dbType,rootTable:e.tableName}),n.select(s),o.length>0&&n.groupByRaw(o.join(", "));for(let l of t.sort)n.orderByRaw(`${F(l.field,this.dbType)} ${l.direction.toUpperCase()}`);return t.limit!==void 0&&n.limit(t.limit).offset((t.page-1)*t.limit),{data:(await n).map(l=>{let f={...l};for(let p of t.measures){let y=f[p.outputKey];y!=null&&typeof y=="string"&&/^-?\d+(\.\d+)?$/.test(y)&&(f[p.outputKey]=Number(y))}return f})}}buildSqlBucketExpression(e,t,n,i){let o=Kt(n);if(this.dbType==="postgres"){let s=`(${e} AT TIME ZONE ${o})`;return`DATE_TRUNC(${Kt(t)}, ${s})`}if(this.dbType==="mysql"){let s=`CONVERT_TZ(${e}, '+00:00', ${o})`;return t==="year"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-01-01'), '%Y-%m-%d')`:t==="month"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-01'), '%Y-%m-%d')`:t==="week"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%u-1'), '%Y-%u-%d')`:t==="day"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-%d'), '%Y-%m-%d')`:`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-%d %H:00:00'), '%Y-%m-%d %H:%i:%s')`}throw new I(`Aggregate time bucket is not supported on ${this.dbType}`)}};var kn=require("mongodb"),at=class{constructor(e){this.debugLog=[];this.batchInserts={items:[],flushing:!1};this.knexService=e.knexService,this.mongoService=e.mongoService,this.databaseConfigService=e.databaseConfigService,this.runtimeMetricsCollectorService=e.runtimeMetricsCollectorService,this.lazyRef=e.lazyRef,this.dbType=this.databaseConfigService.getDbType(),this.batchInsertMaxSize=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_SIZE",100),this.batchInsertMaxWaitMs=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_WAIT_MS",100),this.batchInsertConcurrency=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_CONCURRENCY",5),this.batchInsertTraceFile=process.env.QUERY_BUILDER_BATCH_TRACE_FILE||process.env.DYNAMIC_CREATE_BATCH_TRACE_FILE,this.batchInsertTraceFile&&(0,Rn.mkdirSync)((0,ci.dirname)(this.batchInsertTraceFile),{recursive:!0})}async runWithPolicy(e,t){return this.knexService?this.knexService.runWithPolicy(e,t):this.mongoService?this.mongoService.runWithPolicy(e,t):t()}async runWithFieldPermissionCheck(e,t){return this.knexService?this.knexService.runWithFieldPermissionCheck(e,t):this.mongoService?this.mongoService.runWithFieldPermissionCheck(e,t):t()}async runWithTelemetryContext(e,t){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.runWithQueryContext(e,t):await t()}getDbType(){return this.dbType}safeObjectId(e){if(!kn.ObjectId)return e;if(typeof e=="string")try{return new kn.ObjectId(e)}catch{return e}return e}async getMetadataForQuery(){let e={tables:new Map,tablesList:[]},t=this.lazyRef.metadataCacheService;return t?t.isLoaded?.()?await t.getMetadata?.()??e:t.getDirectMetadata?.()??e:e}async buildMongoFilter(e,t){let n=await this.getMetadataForQuery(),i=Qe(n,e,t,this.dbType);return i._id!==void 0&&(i._id=this.safeObjectId(i._id)),i}async applyWhereToKnex(e,t,n){let i=await this.getMetadataForQuery();return{query:it(e,t,n??"",i,this.dbType)}}async runMongoMutationInSaga(e){return!this.mongoService?.runInSaga||this.mongoService.isInSaga?.()?e():(await this.mongoService.runInSaga(e)).data}async insertWithOptions(e){if(e.batch)return await this.insertManyBatch(e.table,e.data);if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{if(Array.isArray(e.data)){let t=[];for(let n of e.data){let i=await this.mongoService.insertOne(e.table,n);t.push(X(i))}return t}return this.mongoService.insertOne(e.table,e.data)});if(Array.isArray(e.data)){let t=[];for(let n of e.data){let i=await this.knexService.insertWithCascade(e.table,n);t.push(i)}return t}else return await this.knexService.insertWithCascade(e.table,e.data)}async select(e){let t=performance.now(),n=await this.getMetadataForQuery(),i=performance.now(),s=new ee().plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:n,dbType:this.dbType}),a=e.debugTrace;if(a&&(a.dur("qb_planner",i,{table:e.tableName}),a.setPlan(this.sanitizePlan(s))),this.dbType==="mongodb"){let l=await new Ae(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}let c=await new je(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:n,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),c}sanitizePlan(e){return{rawFields:e.rawFields,hasRelationFilters:e.hasRelationFilters,hasRelationSort:e.hasRelationSort,joins:e.joins?.length??0,sortItems:e.sortItems,limit:e.limit,offset:e.offset,page:e.page,isSimpleQuery:e.joins?.length===0&&!e.hasRelationFilters&&!e.hasRelationSort}}async updateWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),s=this.mongoService.collection(e.table),a=this.mongoService.ioSignalPublic?.()??{},u=await s.find(o,a).toArray(),c=[];for(let d of u){let l=await this.mongoService.updateOne(e.table,d._id,e.data);c.push(l)}return c});let t=this.knexService.getKnex(),n=t(e.table);e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n;for(let o of i)await this.knexService.updateWithCascade(e.table,o.id,e.data);if(e.returning){let o=t(e.table);return e.where.length>0&&await this.applyWhereToKnex(o,e.where,e.table),await o.select(e.returning)}return{affected:i.length}}async deleteWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let i=await this.buildMongoFilter(e.where,e.table),o=this.mongoService.collection(e.table),s=this.mongoService.ioSignalPublic?.()??{},a=await o.find(i,s).toArray(),u=0;for(let c of a)await this.mongoService.deleteOne(e.table,c._id)&&u++;return u});let n=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table)),await n.delete()}async count(e){if(this.dbType==="mongodb"){let o=e.where?await this.buildMongoFilter(e.where,e.table):{};return this.mongoService.count(e.table,o)}let n=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n.count("* as count").first();return Number(i?.count||0)}whereToFilter(e){let t={},n=this.databaseConfigService.isMongoDb();for(let[i,o]of Object.entries(e))i==="id"||i==="_id"?n?t._id=this.normalizeWhereFilterValue("_id",o):t.id=this.normalizeWhereFilterValue("id",o):t[i]=this.normalizeWhereFilterValue(i,o);return t}normalizeWhereFilterValue(e,t){return this.isFilterOperatorObject(t)?this.databaseConfigService.isMongoDb()&&e==="_id"?this.normalizeMongoIdOperatorValue(t):t:{_eq:this.databaseConfigService.isMongoDb()&&e==="_id"?this.safeObjectId(t):t}}isFilterOperatorObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof kn.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[n,i]of Object.entries(e))t[n]=Array.isArray(i)?i.map(o=>this.safeObjectId(o)):this.safeObjectId(i);return t}filterToWhere(e){let t=[];for(let[n,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let o=Object.entries(i)[0];if(o){let[s,a]=o,u=this.mapFilterOperatorToSql(s);t.push({field:n,operator:u,value:a})}}return t}mapFilterOperatorToSql(e){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"like",_starts_with:"like",_ends_with:"like",_is_null:"is null",_is_not_null:"is not null"}[e]||"="}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,maxQueryDepth:e.maxQueryDepth})})}async aggregate(e){return this.trackQueryMetric("aggregate",e.table,async()=>{let t=await this.getMetadataForQuery();return this.dbType==="mongodb"?new Ae(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).aggregate({tableName:e.table,aggregate:e.aggregate,metadata:t,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,dbType:this.dbType}):new je(this.knexService.getKnex(),this.dbType,this.knexService).aggregate({tableName:e.table,aggregate:e.aggregate,metadata:t,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t,n){return n?.batch?await this.insertManyBatch(e,t):this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let a=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return X(a)}let i=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),s=i||t.id;return await o(e).where("id",s).first()})}async createMany(e,t){return t.length===0?[]:this.trackQueryMetric("insert_many",e,async()=>this.dbType==="mongodb"?(await this.runMongoMutationInSaga(async()=>typeof this.mongoService.insertManyWithCascade=="function"?this.mongoService.insertManyWithCascade(e,t):Promise.all(t.map(i=>this.mongoService.insertOne(e,i))))).map(i=>X(i)):this.knexService.insertManyWithCascade(e,t))}async insertMany(e,t){return this.createMany(e,t)}async flushBatchInserts(){for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)await this.flushBatchInsertBuffer()}async insertManyBatch(e,t){let n=Array.isArray(t)?t:[t];for(let i of n)this.batchInserts.items.push({table:e,data:i});return this.traceBatchInsert("enqueue",{tableName:e,count:n.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i)),{accepted:!0,batch:!0,count:n.length}}async flushBatchInsertBuffer(){if(this.batchInserts.flushing){await this.batchInserts.flushPromise;return}let e=this.batchInserts.items.splice(0,this.batchInserts.items.length);if(this.batchInserts.timer&&(clearTimeout(this.batchInserts.timer),this.batchInserts.timer=void 0),e.length===0)return;this.batchInserts.flushing=!0;let t=this.executeBatchInsertFlush(e);this.batchInserts.flushPromise=t,await t}async executeBatchInsertFlush(e){let t=Date.now();try{let n=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...n.entries()].map(([i,o])=>({tableName:i,count:o.length}))}),await this.runLimited([...n.entries()],([i,o])=>this.flushBatchInsertTable(i,o)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}finally{this.batchInserts.flushing=!1,this.batchInserts.flushPromise=void 0,this.batchInserts.items.length>0&&(this.batchInserts.timer&&clearTimeout(this.batchInserts.timer),this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(n=>this.logBatchInsertError("QueryBuilder batch insert flush failed",n))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let n=Date.now();await this.runBatchInsertWithIsolation(e,t),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-n})}async runBatchInsertWithIsolation(e,t){if(t.length!==0)try{await(async()=>{if(this.dbType==="mongodb"){await this.runMongoMutationInSaga(async()=>{if(typeof this.mongoService?.insertManyWithCascade=="function"){await this.mongoService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.mongoService.insertOne(e,i.data)))});return}if(typeof this.knexService?.insertManyWithCascade=="function"){await this.knexService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.knexService.insertWithCascade(e,i.data)))})()}catch(n){if(t.length===1){this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,n);return}let i=Math.ceil(t.length/2);await Promise.all([this.runBatchInsertWithIsolation(e,t.slice(0,i)),this.runBatchInsertWithIsolation(e,t.slice(i))])}}groupBatchInsertsByTable(e){let t=new Map;for(let n of e){let i=t.get(n.table);i?i.push(n):t.set(n.table,[n])}return t}async runLimited(e,t){let n=0,i=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;n<e.length;){let o=e[n++];await t(o)}});await Promise.all(i)}readPositiveEnv(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.trunc(n):t}traceBatchInsert(e,t){this.batchInsertTraceFile&&(0,Rn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
|
|
51
|
+
}`}var Or="mongo-fold-text-search.body.txt",qe=null;function eo(){let r=[Ln.join(__dirname,Or),Ln.join(process.cwd(),"dist","kernel","query","utils",Or)];for(let e of r)try{if(en.existsSync(e))return en.readFileSync(e,"utf8")}catch{}return null}function tn(){if(qe!==null)return qe;let r=eo();return r?(qe=r,qe):(qe=Zt(),qe)}var be=require("mongodb");function W(r,e,t,n){if(t==="_id"){if(n instanceof be.ObjectId)return n;if(typeof n=="string")try{return new be.ObjectId(n)}catch{return n}return n}let i=r?.tables?.get(e);if(!i){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new be.ObjectId(n)}catch{return n}return n}if(!i.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new be.ObjectId(n)}catch{return n}return n}let o=i.columns.find(s=>s.name===t);if(!o){if(i.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof n=="string"&&n.length===24)try{return new be.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new be.ObjectId(n)}catch{return n}return n}if(n==null)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;case"uuid":if(typeof n=="string")try{return new be.ObjectId(n)}catch{return n}return n;default:return n}}var nn="__mongoFoldTextTriples";function to(r){return r==="_id"?"$_id":`$${r}`}function Ue(r,e,t,n){let i=to(e),o=r[nn]??[];o.push({ref:i,needle:t,mode:n}),r[nn]=o}function no(r){let e=r[nn];if(delete r[nn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:tn(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}function Qe(r,e,t,n){let i={},o=n==="mongodb"||!n;for(let s of e){let a=s.field.includes(".")?s.field.split(".").pop()??s.field:s.field,u=t||s.field.split(".")[0]||"";o&&a==="id"&&(a="_id");let c=W(r,u,a,s.value);switch(s.operator){case"=":i[a]=c;break;case"!=":i[a]={$ne:c};break;case">":i[a]={$gt:c};break;case"<":i[a]={$lt:c};break;case">=":i[a]={$gte:c};break;case"<=":i[a]={$lte:c};break;case"like":i[a]={$regex:c.replace(/%/g,".*"),$options:"i"};break;case"in":let d=s.value;Array.isArray(d)||(d=typeof d=="string"&&d.includes(",")?d.split(",").map(m=>m.trim()):[d]);let l=d.map(m=>W(r,u,a,m));i[a]={$in:l};break;case"not in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(m=>m.trim()):[f]);let p=f.map(m=>W(r,u,a,m));i[a]={$nin:p};break;case"is null":i[a]=null;break;case"is not null":i[a]={$ne:null};break;case"_contains":Ue(i,a,String(c),"contains");break;case"_starts_with":Ue(i,a,String(c),"starts");break;case"_ends_with":Ue(i,a,String(c),"ends");break;case"_between":let y=s.value;if(typeof y=="string"&&(y=y.split(",").map(m=>m.trim())),Array.isArray(y)&&y.length===2){let m=W(r,u,a,y[0]),b=W(r,u,a,y[1]);i[a]={$gte:m,$lte:b}}break;case"_is_null":let g=c===!0||c==="true";i[a]=g?{$eq:null}:{$ne:null};break;case"_is_not_null":let h=c===!0||c==="true";i[a]=h?{$ne:null}:{$eq:null};break}}return no(i),i}function Ar(r,e,t){let i=r?.tables?.get?.(e)?.columns?.find(o=>o.name===t);return i?i.isNullable!==!1:!0}function rn(r,e,t,n,i,o){switch(i){case"_contains":Ue(e,n,String(o),"contains");break;case"_starts_with":Ue(e,n,String(o),"starts");break;case"_ends_with":Ue(e,n,String(o),"ends");break;case"_eq":e[n]=W(r,t,n,o);break;case"_neq":{let l=W(r,t,n,o);Ar(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:l}})):e[n]={$ne:l};break}case"_in":{let l=o;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(p=>p.trim()):[l]);let f=l.map(p=>W(r,t,n,p));e[n]={$in:f};break}case"_not_in":case"_nin":let s=o;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(l=>l.trim()):[s]);let a=s.map(l=>W(r,t,n,l));Ar(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$nin:a}})):e[n]={$nin:a};break;case"_gt":e[n]={$gt:W(r,t,n,o)};break;case"_gte":e[n]={$gte:W(r,t,n,o)};break;case"_lt":e[n]={$lt:W(r,t,n,o)};break;case"_lte":e[n]={$lte:W(r,t,n,o)};break;case"_is_null":let u=o===!0||o==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let c=o===!0||o==="true";e[n]=c?{$ne:null}:{$eq:null};break;case"_between":let d=o;if(typeof d=="string"&&(d=d.split(",").map(l=>l.trim())),Array.isArray(d)&&d.length===2){let l=W(r,t,n,d[0]),f=W(r,t,n,d[1]);e[n]={$gte:l,$lte:f}}break}}var Jn=require("mongodb");function ne(r,e){if(!r||typeof r!="object")return!1;for(let[t,n]of Object.entries(r))if(t==="_and"||t==="_or"){if(Array.isArray(n)){for(let i of n)if(ne(i,e))return!0}}else if(t==="_not"){if(ne(n,e))return!0}else if(e.has(t))return!0;return!1}function H(r,e){if(!r||typeof r!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},n={},i=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(r)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(i.has(s))if(typeof a=="object"&&a!==null){let u=Object.keys(a);if(u.some(d=>d.startsWith("_"))){let d=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&d.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let o=ne(r,i);return{fieldFilters:t,relationFilters:n,hasRelations:o}}Et();Mt();var cn="__mongoFoldTextTriples";function ze(r,e){if(!r)return{};let t={};return Ot(r,t,e),we(t),t}function uo(r,e){if(!r)return{};let t={};return Kn(r,t,e),we(t),t}function pe(r,e,t){if(!e)return{};let n=new ie,{node:i}=de(e,t,r,n);return ze(i,{metadata:r,rootTable:t})}function un(r,e,t){if(!e)return{};let n=new ie,{node:i}=de(e,t,r,n);return uo(i,{metadata:r,rootTable:t})}function Ot(r,e,t){switch(r.kind){case"true":return;case"false":fe(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let i=r.children.map(o=>{let s={};return Ot(o,s,t),we(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}fe(e,...i);return}case"or":{let i=r.children.map(s=>{let a={};return Ot(s,a,t),we(a),a}).filter(s=>Object.keys(s).length>0);if(i.length===0)return;let o=e.$or;e.$or=o?[...o,...i]:i;return}case"not":{let n={};Ot(r.child,n,t),we(n);let i=e.$nor;e.$nor=i?[...i,n]:[n];return}case"compare":Dr(r,e,t);return;case"relation_exists":{console.warn(`[mongo-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${r.joinId}) \u2014 expected applyRelationFilters or null-only short-circuit to handle it. Filter silently skipped.`);return}}}function Dr(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let i=o=>W(t.metadata,t.rootTable,n,o);switch(r.op){case"eq":Z(e,n,i(r.value));return;case"neq":{let o=i(r.value);qn(t,n)?fe(e,{[n]:{$ne:null}},{[n]:{$ne:o}}):Z(e,n,{$ne:o});return}case"gt":Z(e,n,{$gt:i(r.value)});return;case"gte":Z(e,n,{$gte:i(r.value)});return;case"lt":Z(e,n,{$lt:i(r.value)});return;case"lte":Z(e,n,{$lte:i(r.value)});return;case"in":{let o=Lr(r.value).map(i);Z(e,n,{$in:o});return}case"not_in":{let o=Lr(r.value).map(i);qn(t,n)?fe(e,{[n]:{$ne:null}},{[n]:{$nin:o}}):Z(e,n,{$nin:o});return}case"between":{let o=Array.isArray(r.value)?r.value:typeof r.value=="string"?r.value.split(",").map(s=>s.trim()):null;Array.isArray(o)&&o.length===2&&Z(e,n,{$gte:i(o[0]),$lte:i(o[1])});return}case"is_null":Z(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":Wn(e,n,String(r.value),"contains");return;case"starts_with":Wn(e,n,String(r.value),"starts");return;case"ends_with":Wn(e,n,String(r.value),"ends");return}}function Kn(r,e,t){switch(r.kind){case"true":fe(e,{_id:{$exists:!1,$type:"null"}});return;case"false":return;case"and":{let i=r.children.map(s=>{let a={};return Kn(s,a,t),we(a),a}).filter(s=>Object.keys(s).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}let o=e.$or;e.$or=o?[...o,...i]:i;return}case"or":{let i=r.children.map(o=>{let s={};return Kn(o,s,t),we(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}fe(e,...i);return}case"not":Ot(r.child,e,t);return;case"compare":fo(r,e,t);return;case"relation_exists":{Z(e,r.joinId,r.negate?{$ne:null}:{$eq:null});return}}}function fo(r,e,t){let n=r.field.fieldName;if(r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached false renderer \u2014 expected relation resolver to handle it. Filter silently skipped.`);return}if(r.op==="is_null"){Z(e,n,r.value===!0?{$ne:null}:{$eq:null});return}let i={};Dr(r,i,t),we(i);let o={$nor:[i]};qn(t,n)?fe(e,o,{[n]:{$ne:null}}):fe(e,o)}function Z(r,e,t){r[e]===void 0?r[e]=t:(fe(r,{[e]:r[e]},{[e]:t}),delete r[e])}function fe(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function qn(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(i=>i.name===e);return n?n.isNullable!==!1:!0}function Lr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function po(r){return r==="_id"?"$_id":`$${r}`}function Wn(r,e,t,n){let i=po(e),o=r[cn]??[];o.push({ref:i,needle:t,mode:n}),r[cn]=o}function we(r){let e=r[cn];if(delete r[cn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:tn(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}async function $e(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return pe(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!ne(r,o))return pe(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>$e(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._or&&Array.isArray(r._or)){let d=(await Promise.all(r._or.map(l=>$e(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:{$or:d}}if(r._not)return await Qn(r._not,e,t,n)||{};let{fieldFilters:s,relationFilters:a}=H(r,i),u=[];if(s&&Object.keys(s).length>0){let c=pe(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(a&&Object.keys(a).length>0)for(let[c,d]of Object.entries(a)){let l=await go(c,d,e,i,t,n);l&&Object.keys(l).length>0&&u.push(l)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function Qn(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return un(t,r,e);let o=new Set((i.relations||[]).map(c=>c.propertyName));if(!ne(r,o))return un(t,r,e);if(r._and&&Array.isArray(r._and)){let d=(await Promise.all(r._and.map(l=>Qn(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$or:d}}if(r._or&&Array.isArray(r._or)){let d=(await Promise.all(r._or.map(l=>Qn(l,e,t,n)))).filter(l=>l&&Object.keys(l).length>0);return d.length===0?{}:d.length===1?d[0]:{$and:d}}if(r._not)return $e(r._not,e,t,n);let{fieldFilters:s,relationFilters:a}=H(r,i),u=[];if(s&&Object.keys(s).length>0){let c=un(t,s,e);c&&Object.keys(c).length>0&&u.push(c)}if(a&&Object.keys(a).length>0)for(let[c,d]of Object.entries(a)){let l=await yo(c,d,e,i,t,n);l&&Object.keys(l).length>0&&u.push(l)}return u.length===0?{}:u.length===1?u[0]:{$or:u}}async function go(r,e,t,n,i,o){let s=(n.relations||[]).find(c=>c.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=i?.tables?.get(a);return!a||!u?{}:s.type==="many-to-one"||s.type==="one-to-one"?ho(e,s,r,a,u,i,o):s.type==="one-to-many"?qr(e,s,t,a,u,i,o):s.type==="many-to-many"?Ur(e,s,t,a,u,i,o):{}}async function ho(r,e,t,n,i,o,s){let a=V(e)||t,u=fn(r),c=pn(u);if(c!==null)return c?{[a]:null}:{[a]:{$ne:null}};let d=zn(u);if(d!==null){let y=gn(d.value);if(d.op==="eq")return{[a]:y};if(d.op==="neq")return{[a]:{$ne:y}};if(d.op==="in")return{[a]:{$in:y}};if(d.op==="not_in")return{$and:[{[a]:{$nin:y}},{[a]:{$ne:null}}]}}let l=await dn(u,n,i,o,s);if(!l||Object.keys(l).length===0)return{};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(Boolean);return p.length===0?{__impossible__:!0}:{[a]:{$in:p}}}async function yo(r,e,t,n,i,o){let s=(n.relations||[]).find(c=>c.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=i?.tables?.get(a);if(!a||!u)return{};if(s.type==="many-to-one"||s.type==="one-to-one")return mo(e,s,r,a,u,i,o);if(s.type==="one-to-many"){let c=await qr(e,s,t,a,u,i,o);return Kr(c)}if(s.type==="many-to-many"){let c=await Ur(e,s,t,a,u,i,o);return Kr(c)}return{}}async function mo(r,e,t,n,i,o,s){let a=V(e)||t,u=fn(r),c=pn(u);if(c!==null)return c?{[a]:{$ne:null}}:{[a]:null};let d=zn(u);if(d!==null){let y=gn(d.value);if(d.op==="eq")return{$and:[{[a]:{$ne:y}},{[a]:{$ne:null}}]};if(d.op==="neq")return{[a]:y};if(d.op==="in")return{$and:[{[a]:{$nin:y}},{[a]:{$ne:null}}]};if(d.op==="not_in")return{[a]:{$in:y}}}let l=await dn(u,n,i,o,s);if(!l||Object.keys(l).length===0)return{[a]:null};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(Boolean);return p.length===0?{[a]:{$ne:null}}:{$and:[{[a]:{$nin:p}},{[a]:{$ne:null}}]}}async function qr(r,e,t,n,i,o,s){let a=q(e)||t,u=fn(r),c=pn(u);if(c!==null){let f=await Wr(s,n,a,{});return c?f.length===0?{}:{_id:{$nin:f}}:f.length===0?{__impossible__:!0}:{_id:{$in:f}}}let d=await dn(u,n,i,o,s);if(!d||Object.keys(d).length===0)return{};let l=await Wr(s,n,a,d);return l.length===0?{__impossible__:!0}:{_id:{$in:l}}}async function Ur(r,e,t,n,i,o,s){let a=Ne(t,e);if(!a)return{};let u=fn(r),c=pn(u);if(c!==null){let g=await Un(s,a,n,null);return c?g.length===0?{}:{_id:{$nin:g}}:g.length===0?{__impossible__:!0}:{_id:{$in:g}}}let d=zn(u);if(d!==null){let g=gn(d.value),h=Array.isArray(g)?g:[g],m=await Un(s,a,n,{_id:{$in:h}});return m.length===0?{__impossible__:!0}:{_id:{$in:m}}}let l=await dn(u,n,i,o,s);if(!l||Object.keys(l).length===0)return{};let p=(await s.collection(n).find(l,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);if(p.length===0)return{__impossible__:!0};let y=await Un(s,a,n,{_id:{$in:p}});return y.length===0?{__impossible__:!0}:{_id:{$in:y}}}async function dn(r,e,t,n,i){let o=new Set((t?.relations??[]).map(s=>s.propertyName));return ne(r,o)?$e(r,e,n,i):pe(n,r,e)}async function Wr(r,e,t,n){let i=await r.collection(e).find(n,{projection:{[t]:1}}).toArray(),o=new Set,s=[];for(let a of i){let u=a[t];if(u==null)continue;let c=String(u);o.has(c)||(o.add(c),s.push(u))}return s}function Kr(r){if(!r||Object.keys(r).length===0)return{};if(r.__impossible__===!0)return{};let e=r._id;if(e&&typeof e=="object"&&!Array.isArray(e)){if(Array.isArray(e.$in))return{_id:{$nin:e.$in}};if(Array.isArray(e.$nin))return{_id:{$in:e.$nin}}}return{$nor:[r]}}async function Un(r,e,t,n){let i=null;n&&t&&(i=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(d=>d._id).filter(Boolean));let o=i?{[e.otherColumn]:{$in:i}}:{},s=await r.collection(e.junctionName).find(o,{projection:{[e.selfColumn]:1}}).toArray(),a=new Set,u=[];for(let c of s){let d=c[e.selfColumn];if(d==null)continue;let l=String(d);a.has(l)||(a.add(l),u.push(d))}return u}function fn(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function pn(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0],n=r[t];return t==="_is_null"?n===!0:t==="_is_not_null"?n!==!0:t==="_eq"?n===null?!0:null:t==="_neq"&&n===null?!1:null}function gn(r){if(Array.isArray(r))return r.map(e=>gn(e));if(typeof r!="string")return r;try{return new Jn.ObjectId(r)}catch{return r}}function zn(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof Jn.ObjectId)return{op:"eq",value:r};if(r==null)return null;if(typeof r!="object")return{op:"eq",value:r};if(!r||typeof r!="object"||Array.isArray(r))return null;let e=Object.keys(r);if(e.length!==1)return null;let t=e[0];return t==="_eq"?{op:"eq",value:r._eq}:t==="_neq"?{op:"neq",value:r._neq}:t==="_in"&&Array.isArray(r._in)?{op:"in",value:r._in}:t==="_not_in"&&Array.isArray(r._not_in)?{op:"not_in",value:r._not_in}:null}async function At(r,e,t,n){let i=await It(r,e,t),o=[],s={},a={};if(n&&typeof n=="object")for(let[p,y]of Object.entries(n))if(typeof y=="object"&&y!==null){let g=Object.keys(y)[0];g&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(g)?s[p]=y:a[p]=y}else s[p]=y;if(Object.keys(s).length>0){let p={};for(let[y,g]of Object.entries(s))if(typeof g=="object"&&g!==null)for(let[h,m]of Object.entries(g))rn(r,p,e,y,h,m);else p[y]=g;Object.keys(p).length>0&&o.push({$match:p})}let c=r?.tables?.get(e)?.relations||[],d=[];for(let[p,y]of Object.entries(a))if(!i.relations.some(h=>h.propertyName===p)){let h=c.find(m=>m.propertyName===p);if(h){let m="",b="";if(h.type==="many-to-one"||h.type==="one-to-one")m=V(h)||h.propertyName,b="_id";else if(h.type==="one-to-many")m="_id",b=q(h)||h.propertyName;else if(h.type==="many-to-many")continue;let w=h.type==="one-to-many"||h.type==="many-to-many";d.push({propertyName:p,targetTable:h.targetTableName,localField:m,foreignField:b,type:w?"many":"one",nestedFields:[]})}}let l=[...i.relations,...d];for(let p of l){let y=a[p.propertyName],g=p.nestedFields&&p.nestedFields.length>0?await At(r,p.targetTable,p.nestedFields,y):y?await At(r,p.targetTable,["_id"],y):[];p.type==="one"&&g.length>0&&g.push({$limit:1}),o.push({$lookup:{from:p.targetTable,localField:p.localField,foreignField:p.foreignField,as:p.propertyName,pipeline:g.length>0?g:void 0}}),p.type==="one"&&(o.push({$unwind:{path:`$${p.propertyName}`,preserveNullAndEmptyArrays:!0}}),y&&(Ve(y)||o.push({$match:{[p.propertyName]:{$ne:null}}})))}let f=c.filter(p=>!l.some(y=>y.propertyName===p.propertyName));if(i.scalarFields.length>0||i.relations.length>0||f.length>0){let p={_id:1};for(let g of i.scalarFields)p[g]=1;for(let g of l)p[g.propertyName]=1,g.type==="one"&&g.localField&&g.localField!==g.propertyName&&(p[g.localField]=1);if(t.includes("*"))for(let g of f){if(g.type==="one-to-many"||g.type==="many-to-many")continue;g.type==="many-to-many"?p[g.propertyName]={$map:{input:`$${g.propertyName}`,as:"item",in:{_id:"$$item"}}}:p[g.propertyName]={$cond:{if:{$ne:[`$${g.propertyName}`,null]},then:{_id:`$${g.propertyName}`},else:null}}}o.push({$project:p})}return o}async function Qr(r,e,t,n,i){let o=r?.tables?.get(t),s=o?.relations||[],a=o?.columns||[],u=s.filter(d=>!i.some(l=>l.propertyName===d.propertyName)),c=n.length===a.length||n.length===0&&i.length===0;if(u.length>0||!c){let d={_id:1};for(let l of n)d[l]=1;for(let l of i)d[l.propertyName]=1,l.type==="one"&&l.localField&&l.localField!==l.propertyName&&(d[l.localField]=1);for(let l of u){if(l.type==="one-to-many"||l.type==="many-to-many")continue;l.type==="many-to-many"?d[l.propertyName]={$map:{input:`$${l.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[l.propertyName]={$cond:{if:{$ne:[`$${l.propertyName}`,null]},then:{_id:`$${l.propertyName}`},else:null}}}e.push({$project:d})}}function Ve(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ve(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ve(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ve(e));if("_not"in r)return Ve(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Ve(t)))return!0}return!1}Ge();var jt=require("mongodb");Ge();hn();async function yn(r,e,t){let n=new Map,i=0;async function o(){for(;i<r.length;){let u=i++,c=r[u];n.set(String(c),await e(c))}}let s=Math.min(t,r.length);if(s===0)return n;let a=Array.from({length:s},o);return await Promise.all(a),n}var se="__sourceId__",Ce="__targetId__",Ye="__enfyra_target__",Pt="__enfyra_top_n_documents__",Xe=class{constructor(e,t,n,i=new Se){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.executionBudget=i;this.pkField="_id"}chunkCount(e){return Math.ceil(e.length/oe)||1}runQuery(e){return this.executionBudget.run(e)}uniqueValues(e){return Array.from(new Map(e.filter(t=>t!=null).map(t=>[this.keyOf(t),t])).values())}buildStableSort(e,t="_id"){let n=this.buildSortFromTokens(e)||{};return n[t]===void 0&&(n[t]=1),n}appendPartitionProjection(e,t,n){if(t){let i={...t};for(let o of n)i[o]=1;e.push({$project:i})}}appendTopNStages(e,t,n,i,o){e.push({$group:{_id:`$${t}`,[Pt]:{$topN:{sortBy:n,output:"$$ROOT",n:i+o}}}},{$project:{[Pt]:{$slice:[`$${Pt}`,i,o]}}},{$unwind:`$${Pt}`},{$replaceRoot:{newRoot:`$${Pt}`}})}normalizeMetadata(){return this.metadata?this.metadata.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortFromTokens(e){let t={};for(let n of this.parseSortTokens(e)){let i=n.field.split(".");if(i.length===1)t[i[0]]=n.order;else{let o=`__sort_${i.slice(0,-1).join("_")}`;t[`${o}.${i[i.length-1]}`]=n.order}}return Object.keys(t).length>0?t:void 0}parseSortTokens(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).map(n=>{let i=n.startsWith("-"),o=i?n.slice(1):n;return{field:o==="id"?"_id":o,order:i?-1:1}}):[]}hasDottedSort(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).some(n=>(n.startsWith("-")?n.slice(1):n).includes(".")):!1}buildSortAggregatePipeline(e,t,n){let i=Array.isArray(n)?n:n.split(",").map(c=>c.trim()).filter(Boolean),o=[{$match:t}],s=new Set;for(let c of i){let l=(c.startsWith("-")?c.slice(1):c).split(".");if(l.length<=1)continue;let f=e;for(let p=0;p<l.length-1;p++){let y=l[p],g=this.normalizeMetadata()?.tables?.get(f);if(!g)break;let h=g.relations?.find(w=>w.propertyName===y);if(!h)break;let m=h.targetTableName||h.targetTable,b=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(b)){s.add(b);let w=V(h)||h.propertyName,C=p===0?null:`__sort_${l.slice(0,p).join("_")}`,T=C?`${C}.${w}`:w;o.push({$lookup:{from:m,localField:T,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}f=m}}let a=this.buildSortFromTokens(n);a&&o.push({$sort:a});let u={};for(let c of s)u[c]=0;return Object.keys(u).length>0&&o.push({$project:u}),o}toObjectId(e){try{return typeof e=="string"?new jt.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof jt.ObjectId||t instanceof jt.ObjectId?this.keyOf(e).localeCompare(this.keyOf(t)):typeof e=="number"&&typeof t=="number"?e-t:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="string"&&typeof t=="string"?e.localeCompare(t):e<t?-1:e>t?1:0}sortDocsInMemory(e,t){let n=this.parseSortTokens(t).filter(i=>!i.field.includes("."));n.length!==0&&e.sort((i,o)=>{for(let s of n){let a=this.compareSortValues(i[s.field],o[s.field]);if(a!==0)return a*s.order}return this.compareSortValues(i._id,o._id)})}sortDocsByPk(e){e.sort((t,n)=>this.compareSortValues(t._id,n._id))}projectionWithSortFields(e,t){if(!e)return{projection:e,hiddenFields:[]};let n={...e},i=[];for(let o of this.parseSortTokens(t))o.field.includes(".")||n[o.field]===void 0&&(n[o.field]=1,i.push(o.field));return{projection:n,hiddenFields:i}}removeHiddenFields(e,t){if(t.length!==0)for(let n of e)for(let i of t)delete n[i]}keyOf(e){return e==null?"":e instanceof jt.ObjectId||typeof e=="object"&&typeof e.toHexString=="function"?e.toHexString():String(e)}buildScalarRef(e){return{[this.pkField]:e}}getTargetPkField(e){return this.pkField}resolveOwnerFkKey(e){return e.localField||e.fkColumn||e.relationName}resolveInverseFkField(e){return e.foreignField?e.foreignField:e.mappedBy?e.mappedBy:e.relationName}resolveParentPk(e){return this.pkField}resolveFields(e,t){let{rootFields:n,subRelations:i}=He(e),o={},s=!1;if(n.includes("*")){s=!0;for(let f of t.relations||[])i.has(f.propertyName)||i.set(f.propertyName,["_id"])}else for(let f of n){let p=t.columns.find(y=>y.name===f);p?o[p.name]=1:t.relations?.find(g=>g.propertyName===f)&&!i.has(f)&&i.set(f,["_id"])}i.forEach((f,p)=>{let y=t.relations?.find(g=>g.propertyName===p);y&&(y.type==="many-to-one"||y.type==="one-to-one"&&!y.isInverse)&&(s||(o[V(y)||y.propertyName]=1))}),s||(o._id=1);let a=[];i.forEach((f,p)=>{let y=t.relations?.find(b=>b.propertyName===p);if(!y)return;let g=y.targetTableName||y.targetTable;if(!g)return;let h,m;y.type==="many-to-one"||y.type==="one-to-one"?Ie(y)?(h="_id",m=q(y)||y.propertyName):(h=V(y)||y.propertyName,m="_id"):y.type==="one-to-many"?(h="_id",m=q(y)||y.propertyName):y.type==="many-to-many"&&(y.isInverse?(h="_id",m=y.mappedBy):(h=y.propertyName,m="_id")),a.push({relationName:p,type:y.type,targetTable:g,fields:f,isInverse:y.isInverse,fkColumn:y.foreignKeyColumn,mappedBy:y.mappedBy,junctionTableName:y.junctionTableName,junctionSourceColumn:y.junctionSourceColumn,junctionTargetColumn:y.junctionTargetColumn,localField:h,foreignField:m})});let u=!s&&Object.keys(o).length===1&&o._id===1&&a.length===0,c=this.fieldRenamesByTable?.get(t.name)??[],d=[];if(!s&&c.length>0)for(let f of c)o[f.newName]===1&&o[f.oldName]!==1&&(o[f.oldName]=1,d.push(f.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:o,pendingRenames:c,hiddenFields:d}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?pe(this.normalizeMetadata(),i.userFilter,e):null,s=this.buildSortFromTokens(i?.userSort),a=await K(t,c=>{let d={_id:{$in:c}};o&&Object.keys(o).length>0&&Object.assign(d,o);let l={projection:n.projection};return s&&(l.sort=s),this.runQuery(()=>this.db.collection(e).find(d,l).toArray())}),u=this.applyReadFallback(a,n);return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(t),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,n,i,o){let s=i.projection?{...i.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let a=this.uniqueValues(n.map(m=>this.toObjectId(m))),u=o?.userFilter?pe(this.normalizeMetadata(),o.userFilter,e):null,c=o?.userLimit,d=o?.userPage,l=this.hasDottedSort(o?.userSort);if(c!==void 0&&c>0){let m=d?(d-1)*c:0;if(l)throw new Error(`Dotted sort is not supported for batch relation '${o?.relationName}'`);let b=this.buildStableSort(o?.userSort),w=await K(a,async C=>{let T={[t]:{$in:C}};u&&Object.keys(u).length>0&&Object.assign(T,u);let k=[{$match:T}];this.appendTopNStages(k,t,b,m,c),k.push({$sort:{[t]:1,...b}}),this.appendPartitionProjection(k,s,[t]);let x=await this.runQuery(()=>this.db.collection(e).aggregate(k).toArray());return this.applyReadFallback(x,i)});return{docs:w,groupKeyField:t,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:w.length}}}if(s&&(s[t]=1),l){let m=[],b=await yn(a,async w=>{let C={[t]:w};u&&Object.keys(u).length>0&&Object.assign(C,u);let T=this.buildSortAggregatePipeline(e,C,o.userSort);s&&T.push({$project:s});let k=await this.runQuery(()=>this.db.collection(e).aggregate(T).toArray());return this.applyReadFallback(k,i)},Me);for(let w of b.values())for(let C of w)m.push(C);return{docs:m,groupKeyField:t,stats:{strategy:"per-parent-dotted-sort",roundtrips:a.length,concurrencyWaves:Math.ceil(a.length/Me),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:m.length}}}let f={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(f,u);let p=this.buildSortFromTokens(o?.userSort)||{_id:1},y={projection:s,sort:p},g=await K(a,m=>this.runQuery(()=>this.db.collection(e).find({[t]:{$in:m},...u||{}},y).toArray())),h=this.applyReadFallback(g,i);return{docs:h,groupKeyField:t,stats:{strategy:"batch-in",roundtrips:this.chunkCount(a),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:h.length}}}postProcessInverseChild(e,t,n){n||delete e[t]}m2mSortCanUseJunction(e){return this.parseSortTokens(e).every(t=>t.field==="_id")}async loadM2MTargets(e,t,n){if(t.length===0)return[];let i=n.projection?{projection:n.projection}:void 0,o=await K(t,s=>this.runQuery(()=>this.db.collection(e).find({_id:{$in:s}},i).toArray()));return this.applyReadFallback(o,n)}async fetchM2MTopK(e,t,n,i,o,s,a){if(this.hasDottedSort(t.userSort))throw new Error(`Dotted sort is not supported for batch relation '${t.relationName}'`);let u=new Map;for(let m of e)u.set(this.keyOf(m),[]);let c=i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1,d=!o&&this.m2mSortCanUseJunction(t.userSort),l=this.parseSortTokens(t.userSort).find(m=>m.field==="_id")?.order??1,f=this.buildStableSort(t.userSort),p=await K(e,async m=>{if(d){let C=[{$match:{[n.selfColumn]:{$in:m}}}];return this.appendTopNStages(C,n.selfColumn,{[n.otherColumn]:l},s,a),C.push({$sort:{[n.selfColumn]:1,[n.otherColumn]:l}},{$project:{_id:0,[se]:`$${n.selfColumn}`,[Ce]:`$${n.otherColumn}`}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(C).toArray())).map(k=>({sourceId:k[se],targetId:k[Ce]}))}let b=[{$match:{[n.selfColumn]:{$in:m}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ye}},{$unwind:`$${Ye}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ye}`,{[se]:`$${n.selfColumn}`,[Ce]:`$${n.otherColumn}`}]}}}];return o&&Object.keys(o).length>0&&b.push({$match:o}),this.appendTopNStages(b,se,f,s,a),b.push({$sort:{[se]:1,...f}}),b.push({$project:{_id:0,[se]:1,[Ce]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(b).toArray())).map(C=>({sourceId:C[se],targetId:C[Ce]}))});if(c){let m=new Map;for(let b of p){let w=this.keyOf(b.targetId);m.has(w)||m.set(w,{_id:b.targetId}),u.get(this.keyOf(b.sourceId))?.push(m.get(w))}return{grouped:u,docs:[],stats:{strategy:d?"m2m-junction-partitioned-top-k":"m2m-filtered-edge-top-k",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let y=this.uniqueValues(p.map(m=>m.targetId)),g=await this.loadM2MTargets(t.targetTable,y,i),h=new Map(g.map(m=>[this.keyOf(m._id),m]));for(let m of p){let b=h.get(this.keyOf(m.targetId));b&&u.get(this.keyOf(m.sourceId))?.push(b)}return{grouped:u,docs:g,stats:{strategy:"m2m-partitioned-edge-loader",roundtrips:this.chunkCount(e)+(y.length>0?this.chunkCount(y):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+g.length,rowsDiscarded:0}}}async fetchM2MEdgeBatch(e,t,n,i,o){let s=new Map;for(let g of e)s.set(this.keyOf(g),[]);let a=!o&&this.m2mSortCanUseJunction(t.userSort),u=this.parseSortTokens(t.userSort).find(g=>g.field==="_id")?.order??1,c=this.buildStableSort(t.userSort),d=await K(e,async g=>{if(a)return(await this.runQuery(()=>this.db.collection(n.junctionName).find({[n.selfColumn]:{$in:g}},{projection:{_id:0,[n.selfColumn]:1,[n.otherColumn]:1},sort:{[n.selfColumn]:1,[n.otherColumn]:u}}).toArray())).map(w=>({sourceId:w[n.selfColumn],targetId:w[n.otherColumn]}));let h=[{$match:{[n.selfColumn]:{$in:g}}},{$lookup:{from:t.targetTable,localField:n.otherColumn,foreignField:"_id",as:Ye}},{$unwind:`$${Ye}`},{$replaceRoot:{newRoot:{$mergeObjects:[`$${Ye}`,{[se]:`$${n.selfColumn}`,[Ce]:`$${n.otherColumn}`}]}}}];return o&&Object.keys(o).length>0&&h.push({$match:o}),h.push({$sort:{[se]:1,...c}},{$project:{_id:0,[se]:1,[Ce]:1}}),(await this.runQuery(()=>this.db.collection(n.junctionName).aggregate(h).toArray())).map(b=>({sourceId:b[se],targetId:b[Ce]}))});if(i.projection&&Object.keys(i.projection).length===1&&i.projection._id===1){let g=new Map;for(let h of d){let m=this.keyOf(h.targetId);g.has(m)||g.set(m,{_id:h.targetId}),s.get(this.keyOf(h.sourceId))?.push(g.get(m))}return{grouped:s,docs:[],stats:{strategy:a?"m2m-junction-batch":"m2m-filtered-edge-batch",roundtrips:this.chunkCount(e),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length,rowsDiscarded:0}}}let f=this.uniqueValues(d.map(g=>g.targetId)),p=await this.loadM2MTargets(t.targetTable,f,i),y=new Map(p.map(g=>[this.keyOf(g._id),g]));for(let g of d){let h=y.get(this.keyOf(g.targetId));h&&s.get(this.keyOf(g.sourceId))?.push(h)}return{grouped:s,docs:p,stats:{strategy:"m2m-edge-loader",roundtrips:this.chunkCount(e)+(f.length>0?this.chunkCount(f):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:d.length+p.length,rowsDiscarded:0}}}async fetchM2M(e,t,n,i,o){let s=n?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=Ne(s,{type:"many-to-many",propertyName:t.relationName,targetTable:t.targetTable,mappedBy:t.isInverse?t.mappedBy:void 0,junctionTableName:t.junctionTableName,junctionSourceColumn:t.junctionSourceColumn,junctionTargetColumn:t.junctionTargetColumn});if(!a)throw new Error(`Failed to resolve junction info for ${s}.${t.relationName}`);let u=this.uniqueValues(e.map(k=>k._id)),c=new Map;for(let k of e)c.set(this.keyOf(k._id),[]);if(u.length===0)return{grouped:c,docs:[]};let d=t.userFilter?pe(this.normalizeMetadata(),t.userFilter,t.targetTable):null,l=t.userLimit,f=t.userPage;if(l!==void 0&&l>0){let k=f?(f-1)*l:0;return this.fetchM2MTopK(u,t,a,o,d,k,l)}let p=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1&&!d,y=this.hasDottedSort(t.userSort);if(!y)return this.fetchM2MEdgeBatch(u,t,a,o,d);let g=await K(u,k=>this.runQuery(()=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:k}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray()));if(g.length===0)return{grouped:c,docs:[],stats:{strategy:"m2m-batch",roundtrips:this.chunkCount(u),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:0}};let h=new Set,m=[];for(let k of g){let x=k[a.otherColumn];if(x==null)continue;let _=this.keyOf(x);h.has(_)||(h.add(_),m.push(x))}let b=[],w=new Map;if(p)b=m.map(k=>({_id:k})),this.sortDocsByPk(b);else{let k={_id:{$in:m}};d&&Object.keys(d).length>0&&Object.assign(k,d);let x;if(y){let _=this.buildSortAggregatePipeline(t.targetTable,k,t.userSort);o.projection&&_.push({$project:o.projection}),x=await this.runQuery(()=>this.db.collection(t.targetTable).aggregate(_).toArray())}else{let _=this.buildSortFromTokens(t.userSort)||{_id:1},v=this.projectionWithSortFields(o.projection,t.userSort),j={sort:_};v.projection&&(j.projection=v.projection),x=await K(m,S=>this.runQuery(()=>this.db.collection(t.targetTable).find({_id:{$in:S},...d||{}},j).toArray())),t.userSort?this.sortDocsInMemory(x,t.userSort):this.sortDocsByPk(x),this.removeHiddenFields(x,v.hiddenFields)}b=this.applyReadFallback(x,o)}for(let k of b)w.set(this.keyOf(k._id),k);let C=new Map;for(let k of g){let x=this.keyOf(k[a.selfColumn]),_=this.keyOf(k[a.otherColumn]);w.has(_)&&(C.has(_)||C.set(_,[]),C.get(_).push(x))}for(let k of b){let x=C.get(this.keyOf(k._id))||[];for(let _ of x)c.get(_)?.push(k)}let T=p||m.length===0?0:this.chunkCount(m);return{grouped:c,docs:b,stats:{strategy:p?"m2m-junction-batch":"m2m-batch",roundtrips:this.chunkCount(u)+T,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:g.length+b.length}}}applyReadFallback(e,t){let n=t.pendingRenames??[];if(e.length===0||n.length===0)return e;let i=new Set(t.hiddenFields??[]);for(let o of e)for(let s of n)o[s.newName]===void 0&&o[s.oldName]!==void 0&&(o[s.newName]=o[s.oldName]),(i.has(s.oldName)||o[s.newName]!==void 0)&&delete o[s.oldName];return e}};async function mn(r,e,t,n,i=3,o=0,s,a,u,c){let d=await c?.getActiveFieldRenamesByTable?.(),l=new Xe(r,a,d);await new Te(l,n,u).execute(e,t,i,o,s)}async function Gn(r,e,t){let n=[],{db:i,metadata:o,dbType:s,debugLog:a}=t,u=o?.tables?.get(e.table),c=new Set((u?.relations??[]).map(S=>S.propertyName)),d=!!e.mongoRawFilter&&!!o&&ne(e.mongoRawFilter,c),l=e.plan,f=l?.filterTree&&!l.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&o&&d){let S=await $e(e.mongoRawFilter,e.table,o,i);S&&Object.keys(S).length>0&&n.push({$match:S})}else if(f){let S=ze(l.filterTree,{metadata:o,rootTable:e.table});Object.keys(S).length>0&&n.push({$match:S})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let S=Qe(o,e.where,e.table,s);n.push({$match:S})}let p=e.plan,g=p?p.hasRelationSort:e.sort?.some(S=>{if(!S.field.includes("."))return!1;let E=S.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(A=>A.propertyName===E)??!1})??!1,h=()=>p?.sortItems?Co(p.sortItems):e.sort?So(e.sort):null,m=p?.sortItems?bo(p.sortItems):[],b=p?.sortItems?_o(p.sortItems):[],w=()=>{!p||m.length===0||wo(n,e.table,p.sortItems,o)},C=()=>{!p||b.length===0||$o(n,e.table,p.sortItems,o)},T=()=>{let S=[...m,...b];S.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(S.map(E=>[E,0]))})};if(!e.mongoFieldsExpanded){w(),C();let S=h();if(S&&n.push({$sort:S}),e.mongoCountOnly?n.push({$count:"count"}):(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit})),T(),e.select){let A={};for(let D of e.select)A[D]=1;n.push({$project:A})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let E=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:E,pipeline:n}:{results:zr(E),pipeline:n}}let{scalarFields:k,relations:x}=e.mongoFieldsExpanded;if(!g){w(),C();let S=h();S&&n.push({$sort:S}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}let _=[];for(let S of x)if(e.sort?.some(A=>A.field.startsWith(`${S.propertyName}.`))){let A=e.mongoRawFilter?.[S.propertyName];if(S.nestedFields&&S.nestedFields.length>0){let B=await At(o,S.targetTable,S.nestedFields??[],A);S.type==="one"&&B.length>0&&B.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:B.length>0?B:void 0}})}else if(A){let B=await At(o,S.targetTable,["_id"],A);S.type==="one"&&B.length>0&&B.push({$limit:1}),n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName,pipeline:B.length>0?B:void 0}})}else n.push({$lookup:{from:S.targetTable,localField:S.localField,foreignField:S.foreignField,as:S.propertyName}});S.type==="one"&&(n.push({$unwind:{path:`$${S.propertyName}`,preserveNullAndEmptyArrays:!0}}),A&&(Ze(A)||n.push({$match:{[S.propertyName]:{$ne:null}}})))}else _.push(S);if(g){w(),C();let S=h();S&&n.push({$sort:S}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}T(),await Qr(o,n,e.table,k,[...x]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let v=performance.now(),j=await r.aggregate(n).toArray();if(e.debugTrace?.dur("db_execute",v,{table:e.table}),e.mongoCountOnly)return{results:j,pipeline:n};if(_.length>0&&j.length>0){let S=e.deep||{},E=_.map(D=>{let $=o?.tables?.get(e.table)?.relations?.find(J=>J.propertyName===D.propertyName),R=S[D.propertyName],N=R?.fields!=null?Array.isArray(R.fields)?R.fields:String(R.fields).split(",").map(J=>J.trim()).filter(Boolean):D.nestedFields&&D.nestedFields.length>0?D.nestedFields:["_id"];return{relationName:D.propertyName,type:$?.type,targetTable:D.targetTable,fields:N,isInverse:$?.isInverse,mappedBy:$?.mappedBy,junctionTableName:$?.junctionTableName,junctionSourceColumn:$?.junctionSourceColumn,junctionTargetColumn:$?.junctionTargetColumn,localField:D.localField,foreignField:D.foreignField,userFilter:R?.filter,userSort:R?.sort,userLimit:R?.limit!==void 0?Number(R.limit):void 0,userPage:R?.page!==void 0?Number(R.page):void 0,nestedDeep:R?.deep}}),A=To(o);A&&await mn(i,j,E,A,3,0,e.table,o,e.debugTrace,t.mongoPhysicalMigrationService)}return{results:zr(j),pipeline:n}}function Yn(r){return`__sort_count_${r.relationName||r.field}`}function Xn(r){return`__sort_${r.function}_${r.relationName||r.field}_${r.aggregateField||"value"}`}function bo(r){return r.filter(e=>e.function==="count").map(Yn)}function _o(r){return r.filter(e=>e.function==="max"||e.function==="min").map(Xn)}function wo(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="count")continue;let a=s.relationMeta,u=s.relationName||s.field,c=a?.targetTableName||a?.targetTable,d=Yn(s);if(!(!a||!c)){if(a.type==="one-to-many"){let l=q(a)||u;r.push({$lookup:{from:c,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${l}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let l=Ne(e,a);if(!l)continue;r.push({$lookup:{from:l.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${l.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:d}}),r.push({$addFields:{[d]:{$ifNull:[{$arrayElemAt:[`$${d}.value`,0]},0]}}})}}}}function $o(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="max"&&s.function!=="min")continue;let a=s.relationMeta,u=s.relationName||s.field,c=a?.targetTableName||a?.targetTable,d=n?.tables?.get(c),l=d?.columns?.find(h=>h.isPrimary)?.name||(d?.columns?.some(h=>h.name==="_id")?"_id":"id"),f=s.aggregateField,p=f==="id"&&d?.columns?.some(h=>h.name==="_id")?"_id":f,y=Xn(s),g=s.function==="min"?"$min":"$max";if(!(!a||!c||!f)){if(a.type==="one-to-many"){let h=q(a)||u;r.push({$lookup:{from:c,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${h}`,"$$localId"]}}},{$group:{_id:null,value:{[g]:`$${p}`}}}],as:y}}),r.push({$addFields:{[y]:{$arrayElemAt:[`$${y}.value`,0]}}});continue}if(a.type==="many-to-many"){let h=Ne(e,a);if(!h)continue;let m=`${y}_junction`;r.push({$lookup:{from:h.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${h.selfColumn}`,"$$localId"]}}},{$project:{_id:0,targetId:`$${h.otherColumn}`}}],as:m}}),r.push({$lookup:{from:c,let:{targetIds:`$${m}.targetId`},pipeline:[{$match:{$expr:{$in:[`$${l}`,"$$targetIds"]}}},{$group:{_id:null,value:{[g]:`$${p}`}}}],as:y}}),r.push({$addFields:{[y]:{$arrayElemAt:[`$${y}.value`,0]}}}),r.push({$project:{[m]:0}})}}}}function To(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(i=>({name:i.name,type:i.type})),relations:n.relations||[]}:null}:null}function So(r){let e={};for(let t of r){let n=t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function Co(r){let e={};for(let t of r){let n=t.function==="count"?Yn(t):t.function==="max"||t.function==="min"?Xn(t):t.joinId!==null?t.fullPath:t.field;e[n]=t.direction==="asc"?1:-1}return e}function Ze(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Ze(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Ze(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Ze(e));if("_not"in r)return Ze(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Ze(t)))return!0}return!1}function zr(r){return r.map(X)}function Vr(r,e){let t=[],n=[],i=e?.tables?.get(r.rootTable);if(!i)return{scalarFields:t,relations:n};for(let o of r.nodes)if(o.kind==="wildcard")for(let s of i.columns||[])t.includes(s.name)||t.push(s.name);else o.kind==="scalar"?i.columns?.some(a=>a.name===o.name)&&!t.includes(o.name)&&t.push(o.name):o.kind==="relation"&&n.push(ko(o,i,e));return{scalarFields:t,relations:n}}function ko(r,e,t){let n=e.relations?.find(c=>c.propertyName===r.propertyName),i,o,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&Ie(n)?(i="_id",o=q(n)||r.propertyName,s=!0):(i=n&&V(n)||r.propertyName,o="_id",s=!1):r.relationType==="one-to-many"?(i="_id",o=n&&q(n)||r.propertyName,s=!0):n?.mappedBy?(i="_id",o=n.mappedBy,s=!0):(i=r.propertyName,o="_id",s=!1);let a=r.relationType==="one-to-many"||r.relationType==="many-to-many",u=Hr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:i,foreignField:o,type:a?"many":"one",isInverse:s,nestedFields:u}}function Hr(r){let e=[];for(let t of r)if(t.kind==="wildcard")e.push("*");else if(t.kind==="scalar")e.push(t.name);else if(t.kind==="relation"){let n=Hr(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let i of n)e.push(`${t.propertyName}.${i}`)}return e}Je();Mt();Et();function bn(r,e,t,n){let i={rootTable:e,nodes:[]};if(!r||r.length===0)return i;let o=t?.tables?.get(e);if(!o)return i;let s=o.columns?.some(l=>l.name==="_id"&&l.isPrimary),a=o.columns?.some(l=>l.name==="id"),u=s&&!a?"_id":"id",c=new Map,d=[];for(let l of r){let f=l==="id"?u:l;if(f==="*")d.push("*");else if(f.includes(".")){let p=f.indexOf("."),y=f.substring(0,p),g=f.substring(p+1);if(!o.relations?.some(m=>m.propertyName===y))continue;c.has(y)||c.set(y,[]),c.get(y).push(g)}else if(o.relations?.some(y=>y.propertyName===f))c.has(f)||c.set(f,[u]);else{if(!o.columns?.some(g=>g.name===f))continue;d.push(f)}}if(d.includes("*")){i.nodes.push({kind:"wildcard"});for(let l of o.relations||[])c.has(l.propertyName)||c.set(l.propertyName,[u])}else for(let l of d)i.nodes.push({kind:"scalar",name:l});for(let[l,f]of c.entries()){let p=o.relations?.find(h=>h.propertyName===l);if(!p)continue;let y=p.targetTableName||p.targetTable,g={kind:"relation",propertyName:l,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:y,children:Gr(f,y,t)};if(p.type==="many-to-one"||p.type==="one-to-one"){let h=n.registerWithParent(e,l,t,"left",null,"data");g.joinId=h}i.nodes.push(g)}return i}function Gr(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let i=n.columns?.some(d=>d.name==="_id"&&d.isPrimary),o=n.columns?.some(d=>d.name==="id"),s=i&&!o?"_id":"id",a=new Map,u=[];for(let d of r){let l=d==="id"?s:d;if(l==="*")u.push("*");else if(l.includes(".")){let f=l.indexOf("."),p=l.substring(0,f),y=l.substring(f+1);if(!n.relations?.some(h=>h.propertyName===p))continue;a.has(p)||a.set(p,[]),a.get(p).push(y)}else if(n.relations?.some(p=>p.propertyName===l))a.has(l)||a.set(l,[s]);else{if(!n.columns?.some(y=>y.name===l))continue;u.push(l)}}let c=[];if(u.includes("*")){c.push({kind:"wildcard"});for(let d of n.relations||[])a.has(d.propertyName)||a.set(d.propertyName,[s])}else for(let d of u)c.push({kind:"scalar",name:d});for(let[d,l]of a.entries()){let f=n.relations?.find(y=>y.propertyName===d);if(!f)continue;let p=f.targetTableName||f.targetTable;c.push({kind:"relation",propertyName:d,joinId:null,relationType:f.type,isInverse:!!f.isInverse,targetTable:p,children:Gr(l,p,t)})}return c}ue();ue();var Ro=new Set(["_and","_or","_not"]);function Yr(r,e){return r?.tables?.get(e)??null}function xo(r,e,t){return Yr(r,e)?.columns?.find(n=>n.name===t)}function Zn(r,e,t){return Yr(r,e)?.relations?.find(n=>n.propertyName===t)}function Fo(r){let e=r.match(/^_(count|max|min)\(([^)]+)\)$/);if(!e)return null;let t=e[1],n=e[2].trim();if(t==="count")return{functionName:t,relationName:n};let i=n.indexOf(".");return i<=0||i!==n.lastIndexOf(".")?null:{functionName:t,relationName:n.slice(0,i).trim(),fieldName:n.slice(i+1).trim()}}function er(r,e,t,n){if(xo(r,e,t)?.isEncrypted===!0)throw new I(`Encrypted field '${t}' on '${e}' cannot be used for ${n}.`)}function Oe(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){for(let n of r)Oe(n,e,t);return}for(let[n,i]of Object.entries(r)){if(Ro.has(n)){Oe(i,e,t);continue}if(n.startsWith("_"))continue;let o=Zn(t,e,n);if(o){let s=o.targetTableName||o.targetTable;s&&Oe(i,s,t);continue}er(t,e,n,"filter")}}}function _n(r,e,t){if(!r)return;let n=Array.isArray(r)?r:r.split(",").map(i=>i.trim()).filter(Boolean);for(let i of n){let o=i.startsWith("-")?i.slice(1):i;if(!o)continue;let s=Fo(o);if(s){if(s.functionName==="count")continue;let c=Zn(t,e,s.relationName),d=c?.targetTableName||c?.targetTable;d&&er(t,d,s.fieldName,"sort");continue}let a=o.split("."),u=e;for(let c=0;c<a.length;c++){let d=a[c];if(c===a.length-1){er(t,u,d,"sort");break}let f=Zn(t,u,d);if(!f)break;u=f.targetTableName||f.targetTable||u}}}var ee=class{plan(e){let{tableName:t,fields:n,filter:i,sort:o,page:s,limit:a,meta:u,metadata:c,dbType:d}=e,l=c?.tables?.get(t),f=new ie,p=this.parseFields(n),y=null;p&&l&&(y=bn(p,t,c,f));let g=!1,h=null;if(i&&l){Oe(i,t,c);let S=de(i,t,c,f);h=S.node,g=S.hasRelationFilters}let m=this.parseSort(o);l&&_n(m,t,c);let b=[],w=!1;for(let S of m){let E=S.startsWith("-"),A=E?S.substring(1):S,D=E?"desc":"asc";if(l){let B=this.parseRelationAggregateSort(t,l,A,c);if(B){b.push({joinId:null,field:A,direction:D,fullPath:A,function:B.functionName,relationName:B.relationName,aggregateField:B.aggregateField,relationMeta:B.relationMeta});continue}this.assertLocalSortField(t,l,A)}b.push({joinId:null,field:A,direction:D,fullPath:A})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let C=this.parseLimit(a),T=this.parsePage(s),k=T!==void 0&&C!==void 0?(T-1)*C:void 0,x=this.parseMeta(u),_=x.includes("totalCount")||x.includes("*"),v=x.includes("filterCount")||x.includes("*"),j=f.getAll();return{table:t,dbType:d,rawFields:p,rawFilter:i??null,joins:j,sortItems:b,limit:C,offset:k,needsTotalCount:_,needsFilterCount:v,hasRelationFilters:g,hasRelationSort:w,filterTree:h,fieldTree:y}}parseFields(e){if(e)return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):e.split(",").map(t=>t.trim()).filter(Boolean)}parseSort(e){return e?(Array.isArray(e)?e:e.split(",")).map(n=>n.trim()).filter(Boolean):[]}parseLimit(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;if(!Number.isNaN(t))return t<0?0:t}parsePage(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;return Number.isNaN(t)?void 0:t}parseMeta(e){return e?Array.isArray(e)?e:e.split(",").map(t=>t.trim()).filter(Boolean):[]}assertLocalSortField(e,t,n){if(n.includes("."))throw new I(`Sort field '${n}' is not supported on '${e}'. Sort only by local fields defined on the table metadata.`);let i=t.columns?.some(s=>s.name===n),o=n==="id"&&t.columns?.some(s=>s.name==="_id");if(!i&&!o)throw new I(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationAggregateSort(e,t,n,i){let o=n.match(/^_(count|max|min)\(([^)]+)\)$/);if(!o){if(/^_(count|max|min)\(/.test(n))throw new I(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName), _max(relationName.fieldName), or _min(relationName.fieldName).`);return null}let s=o[1],a=o[2].trim();if(s==="count"){let h=a;if(!h||h.includes("."))throw new I(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let m=t.relations?.find(b=>b.propertyName===h);if(!m)throw new I(`Sort relation '${h}' does not exist on '${e}'.`);if(m.type!=="one-to-many"&&m.type!=="many-to-many")throw new I(`Sort function '_count(${h})' is only supported for list relations on '${e}'.`);return{functionName:s,relationName:h,relationMeta:m}}let u=a.indexOf(".");if(u<=0||u!==a.lastIndexOf("."))throw new I(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let c=a.slice(0,u).trim(),d=a.slice(u+1).trim();if(!c||!d)throw new I(`Sort function '${n}' is not supported on '${e}'. Use _${s}(relationName.fieldName).`);let l=t.relations?.find(h=>h.propertyName===c);if(!l)throw new I(`Sort relation '${c}' does not exist on '${e}'.`);if(l.type!=="one-to-many"&&l.type!=="many-to-many")throw new I(`Sort function '_${s}(${c}.${d})' is only supported for list relations on '${e}'.`);let f=l.targetTableName||l.targetTable,p=i?.tables?.get(f);if(!p)throw new I(`Sort function '${n}' references unknown target table '${f}' on '${e}'.`);let y=p.columns?.find(h=>h.name===d),g=d==="id"&&p.columns?.some(h=>h.name==="_id");if(!y&&!g)throw new I(`Sort field '${d}' does not exist on '${f}' for function '_${s}(${c}.${d})'.`);if(y?.isEncrypted===!0)throw new I(`Encrypted field '${d}' on '${f}' cannot be used for sort.`);return{functionName:s,relationName:c,aggregateField:d,relationMeta:l}}registerSortJoinChain(e,t,n,i,o){let s=e.indexOf(".");if(s===-1)return null;let a=e.slice(0,s),u=e.slice(s+1),c=n?.tables?.get(t);if(!c)return null;let d=c.relations?.find(p=>p.propertyName===a);if(!d||d.type!=="many-to-one"&&d.type!=="one-to-one")return null;let l=i.registerWithParent(t,a,n,"left",o,"sort");if(!l)return null;if(!u.includes("."))return{lastJoinId:l,field:u};let f=d.targetTableName||d.targetTable;return this.registerSortJoinChain(u,f,n,i,l)}};ue();var vo=new Set(["int","integer","bigint","smallint","tinyint","float","double","decimal","numeric","real","number"]),Io=new Set(["date","datetime","timestamp","timestamptz","timestamp with time zone","timestamp without time zone"]),No=new Set(["hour","day","week","month","year"]),Eo=new Set(["count","countDistinct","sum","avg","min","max"]);function O(r,e){throw new I(e,{path:r})}function et(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Mo(r,e){let t=r?.tables?.get(e);return t||O("aggregate",`Table "${e}" metadata is not available`),t}function Xr(r,e,t){let n=r.columns?.find(i=>i.name===e);return n||O(t,`Unknown aggregate field "${e}"`),n.isEncrypted===!0&&O(t,`Encrypted field "${e}" cannot be used in aggregate queries`),n}function Oo(r,e){let t=r===void 0?"UTC":r;(typeof t!="string"||t.length===0)&&O(e,"Aggregate timezone must be a non-empty IANA timezone");try{new Intl.DateTimeFormat("en-US",{timeZone:t}).format()}catch{O(e,`Invalid aggregate timezone "${t}"`)}return t}function Ao(r,e){return r==null?{}:(et(r)||O(e,"Aggregate filter must be an object"),r)}function tt(r,e,t){et(r)||O("aggregate","Aggregate options must be an object");let n=Mo(t,e),i=r.dimensions===void 0?[]:r.dimensions,o=r.measures;Array.isArray(i)||O("aggregate.dimensions","Aggregate dimensions must be an array"),(!et(o)||Object.keys(o).length===0)&&O("aggregate.measures","Aggregate requires at least one measure");let s=new Set,a=i.map((g,h)=>{let m=`aggregate.dimensions[${h}]`;(!et(g)||typeof g.field!="string"||g.field.length===0)&&O(m,"Aggregate dimension requires a field");let b=Xr(n,g.field,`${m}.field`);return s.has(g.field)&&O(`${m}.field`,`Duplicate aggregate dimension "${g.field}"`),s.add(g.field),g.bucket===void 0?(g.timezone!==void 0&&O(`${m}.timezone`,"Aggregate timezone requires a bucket"),{field:g.field,outputKey:g.field,column:b}):((typeof g.bucket!="string"||!No.has(g.bucket))&&O(`${m}.bucket`,"Aggregate bucket must be hour, day, week, month, or year"),Io.has(String(b.type).toLowerCase())||O(`${m}.bucket`,`Aggregate bucket requires a date field, but "${g.field}" is "${b.type}"`),{field:g.field,outputKey:g.field,bucket:g.bucket,timezone:Oo(g.timezone,`${m}.timezone`),column:b})}),u=new Set,c=Object.entries(o).map(([g,h])=>{let m=`aggregate.measures.${g}`;(!g||!et(h))&&O(m,"Aggregate measure must be an object");let b=Object.entries(h).filter(([k])=>k!=="as");b.length!==1&&O(m,"Aggregate measure must define exactly one operation");let[w,C]=b[0];Eo.has(w)||O(m,`Unsupported aggregate measure "${w}"`),(typeof C!="string"||C.length===0)&&O(m,"Aggregate measure field must be a non-empty string");let T=Xr(n,C,`${m}.${w}`);return(u.has(g)||s.has(g))&&O(m,`Aggregate output key "${g}" is duplicated`),u.add(g),["sum","avg","min","max"].includes(w)&&!vo.has(String(T.type).toLowerCase())&&O(m,`Aggregate ${w} requires a numeric field, but "${C}" is "${T.type}"`),{outputKey:g,operation:w,field:C,column:T}}),d=r.sort===void 0?[]:r.sort;Array.isArray(d)||O("aggregate.sort","Aggregate sort must be an array");let l=new Set([...s,...u]),f=d.map((g,h)=>{let m=`aggregate.sort[${h}]`;return(!et(g)||typeof g.field!="string"||!l.has(g.field))&&O(m,"Aggregate sort field must reference a dimension or measure output"),g.direction!=="asc"&&g.direction!=="desc"&&O(`${m}.direction`,"Aggregate sort direction must be asc or desc"),{field:g.field,direction:g.direction}}),p=r.limit===void 0?void 0:Number(r.limit),y=r.page===void 0?1:Number(r.page);return p!==void 0&&(!Number.isInteger(p)||p<=0||p>1e4)&&O("aggregate.limit","Aggregate limit must be an integer between 1 and 10000"),(!Number.isInteger(y)||y<=0)&&O("aggregate.page","Aggregate page must be a positive integer"),{tableName:e,filter:Ao(r.filter,"aggregate.filter"),dimensions:a,measures:c,sort:f,page:y,limit:p}}var Ae=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.debugLog=[];this.lastBuiltPipeline=null;this.db=e.getDb()}async execute(e){if(this.metadata=e.metadata,this.dbType=e.dbType||"mongodb",!e.plan){let l=new ee;e={...e,plan:l.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:"mongodb"})}}let t=e.debugLog||[];this.debugLog=t;let n={table:e.tableName,metadata:e.metadata,debugTrace:e.debugTrace};if(e.pipeline&&(n.pipeline=e.pipeline),e.fields&&(Array.isArray(e.fields)?n.fields=e.fields:typeof e.fields=="string"&&(n.fields=e.fields.split(",").map(l=>l.trim()))),e.filter&&(re(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let l=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(f=>f.trim());n.sort=l.map(f=>{let p=f.trim();return p.startsWith("-")?{field:p.substring(1),direction:"desc"}:{field:p,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let l=typeof e.page=="string"?parseInt(e.page,10):e.page,f=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(l-1)*f,n.limit=f}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let i=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(l=>l.trim()).filter(Boolean),o=0,s=0;(i.includes("totalCount")||i.includes("*"))&&(o=await this.mongoService.collection(e.tableName).countDocuments({}));let a=this.metadata?.tables?.get(e.tableName),u=new Set((a?.relations??[]).map(l=>l.propertyName)),c=!!n.mongoRawFilter&&ne(n.mongoRawFilter,u);if((i.includes("filterCount")||i.includes("*"))&&!c){let l=this.mongoService.collection(e.tableName),f=e.plan?.filterTree?ze(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await l.countDocuments(f)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let d=await this.selectLegacy(n);if(e.debugMode){let l=this.lastBuiltPipeline??[],f;try{f=await this.db.collection(e.tableName).aggregate(l).explain()}catch(p){f={error:String(p)}}return{pipeline:l,explain:f}}if(c&&(i.includes("filterCount")||i.includes("*"))){let l={...n,mongoCountOnly:!0},f=await this.selectLegacy(l);s=f.length>0?f[0].count:0}return{data:d,...i.length>0&&{meta:{...i.includes("totalCount")||i.includes("*")?{totalCount:o}:{},...i.includes("filterCount")||i.includes("*")?{filterCount:s}:{}}}}}async aggregate(e){this.metadata=e.metadata,this.dbType=e.dbType||"mongodb";let t=tt(e.aggregate,e.tableName,e.metadata),n=this.db.collection(e.tableName),i=new ee().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:"mongodb"}),o=i.hasRelationFilters?await $e(t.filter,e.tableName,e.metadata,this.db):i.filterTree?ze(i.filterTree,{metadata:e.metadata,rootTable:e.tableName}):{},s=[];Object.keys(o).length>0&&s.push({$match:o});let a={_id:{}},u={};for(let d of t.dimensions){let l=`$${d.field}`,f=d.bucket?{$dateTrunc:{date:l,unit:d.bucket,timezone:d.timezone}}:l;a._id[d.outputKey]=f,u[d.outputKey]=`$_id.${d.outputKey}`}for(let d of t.measures){let l=`$${d.field}`;a[d.outputKey]=d.operation==="count"?{$sum:{$cond:[{$ne:[l,null]},1,0]}}:d.operation==="countDistinct"?{$addToSet:l}:{[`$${d.operation}`]:l},u[d.outputKey]=d.operation==="countDistinct"?{$size:{$setDifference:[`$${d.outputKey}`,[null]]}}:`$${d.outputKey}`}return s.push({$group:a},{$project:{_id:0,...u}}),t.sort.length>0&&s.push({$sort:Object.fromEntries(t.sort.map(d=>[d.field,d.direction==="asc"?1:-1]))}),t.limit!==void 0&&s.push({$skip:(t.page-1)*t.limit},{$limit:t.limit}),this.lastBuiltPipeline=s,e.debugMode?{pipeline:s,explain:await n.aggregate(s).explain()}:{data:(await n.aggregate(s).toArray()).map(X)}}async selectLegacy(e){let t=[],n=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,i=this.metadata?.tables?.get(e.table),o=i?.relations&&i.relations.length>0;if(e.fields&&e.fields.length>0||n||o){let c=e.plan,d=e.fields&&e.fields.length>0?e.fields:["*"];if(e.fields&&e.fields.length>0&&c?.fieldTree){if(e.mongoFieldsExpanded=Vr(c.fieldTree,this.metadata),n){let l=await It(this.metadata,e.table,[],e.deep),f=new Set(e.mongoFieldsExpanded.relations.map(p=>p.propertyName));e.mongoFieldsExpanded.relations.push(...l.relations.filter(p=>!f.has(p.propertyName)))}}else console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await It(this.metadata,e.table,d,e.deep);if(this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let l=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:l.scalarFields},t=l.hiddenFields}}e.where&&(e.where=e.where.map(c=>c.field.includes(".")?c:{...c,field:`${e.table}.${c.field}`}));let s=this.db.collection(e.table);if(e.pipeline)return this.debugLog&&this.debugLog.push({type:"MongoDB Custom Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(e.pipeline))}),(await s.aggregate(e.pipeline).toArray()).map(X);let{results:a,pipeline:u}=await Gn(s,e,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=u,this.mongoPhysicalMigrationService?await this.mongoPhysicalMigrationService.applyReadFallback(e.table,a,t):a}async executeAggregationPipeline(e,t){let{results:n,pipeline:i}=await Gn(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=i,n}};var wn=class{constructor(e){this.context=e}log(e){console.log(this.format(e))}warn(e){console.warn(this.format(e))}error(e,t){console.error(this.format(e)),t&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}fatal(e,t){this.error(e,t)}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};ue();ae();var Po=["_and","_or","_not"];function ge(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>ge(e));for(let e of Object.keys(r))if(Po.includes(e)||typeof r[e]=="object"&&r[e]!==null&&ge(r[e]))return!0;return!1}var Zr=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function jo(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function $n(r,e,t){if(!t)return!1;let n=r;if(r.includes(".")){let s=r.split(".");n=s[s.length-1]}let i=t.columns.find(s=>s.name===n);if(!i)return!1;let o=i.type?.toLowerCase()||"";return o==="uuid"||o==="uuidv4"||o.includes("uuid")}function Bo(r,e,t,n,i){return n!=="postgres"||typeof e!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)||$n(r,t,i),e}function ei(r,e,t,n,i,o,s){let a=i&&!e.includes(".")?`${i}.${e}`:e,u=ke(a,o??"postgres"),c=$n(e,i,s),d=Bo(e,n,i,o,s);switch(t){case"_eq":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} = ?::uuid`,[n]):r.where(a,"=",d);break;case"_neq":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} != ?::uuid`,[n]):r.where(a,"!=",d);break;case"_gt":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} > ?::uuid`,[n]):r.where(a,">",d);break;case"_gte":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} >= ?::uuid`,[n]):r.where(a,">=",d);break;case"_lt":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} < ?::uuid`,[n]):r.where(a,"<",d);break;case"_lte":c&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} <= ?::uuid`,[n]):r.where(a,"<=",d);break;case"_in":let l=n;Array.isArray(l)||(l=typeof l=="string"&&l.includes(",")?l.split(",").map(p=>p.trim()):[l]),c&&o==="postgres"&&l.every(p=>typeof p=="string")?r.whereRaw(`${u} = ANY(?::uuid[])`,[l]):r.whereIn(a,l);break;case"_not_in":case"_nin":let f=n;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]),c&&o==="postgres"&&f.every(p=>typeof p=="string")?r.whereRaw(`${u} != ALL(?::uuid[])`,[f]):r.whereNotIn(a,f);break;case"_contains":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_starts_with":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${u}) LIKE lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_ends_with":o==="postgres"?r.whereRaw(`lower(unaccent(${u})) ILIKE '%' || lower(unaccent(?))`,[n]):o==="sqlite"?r.whereRaw(`lower(${u}) LIKE '%' || lower(?)`,[n]):r.whereRaw(`lower(unaccent(${u})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`,[n]);break;case"_between":Array.isArray(n)&&n.length===2&&r.whereBetween(a,[n[0],n[1]]);break;case"_is_null":n===!0?r.whereNull(a):r.whereNotNull(a);break;case"_is_not_null":n===!0?r.whereNotNull(a):r.whereNull(a);break;default:r.where(a,jo(t),n)}}function Lo(r,e,t){if(!t||!e||r.startsWith("_"))return!0;let n=r.includes(".")?r.split(".").pop():r,i=t.columns?.some(s=>s.name===n),o=t.relations?.some(s=>s.propertyName===n);return i||o}function nt(r,e,t,n="and",i,o){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let s of e)n==="and"?r.where(function(){nt(this,s,t,"and",i,o)}):r.orWhere(function(){nt(this,s,t,"and",i,o)});return}for(let[s,a]of Object.entries(e))if(Lo(s,t,o)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){nt(this,u,t,"and",i,o)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){nt(this,u,t,"and",i,o)})});continue}if(s==="_not"){r.whereNot(function(){nt(this,a,t,"and",i,o)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(c=>Zr.includes(c)))for(let[c,d]of Object.entries(a))Zr.includes(c)&&(n==="and"?r.where(function(){ei(this,s,c,d,t,i,o)}):r.orWhere(function(){ei(this,s,c,d,t,i,o)}));else{let c=t&&!s.includes(".")?`${t}.${s}`:s,d=ke(c,i??"postgres");$n(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${d} = ?::uuid`,[a]):r.orWhereRaw(`${d} = ?::uuid`,[a]):n==="and"?r.where(c,"=",a):r.orWhere(c,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s,c=ke(u,i??"postgres");$n(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${c} = ?::uuid`,[a]):r.orWhereRaw(`${c} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function le(r,e,t,n,i){return!e||typeof e!="object"||nt(r,e,t,"and",n,i),r}ae();function rr(r,e,t){return`${F(r,t)}.${F(e,t)}`}function Re(r,e){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function ti(r,e){if(!e)return!1;let t=e.columns.find(i=>i.name===r);if(!t)return!1;let n=t.type?.toLowerCase()||"";return n==="uuid"||n==="uuidv4"||n.includes("uuid")}function rt(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function ir(r,e,t,n,i,o){let s=[];for(let[a,u]of Object.entries(o)){let c=await Bt(r,e,a,u,t,n,i);if(c!==null)s.push(`EXISTS (${c})`);else{let d=t.relations.find(l=>l.propertyName===a);if(d&&d.foreignKeyColumn){let l=rr(e,d.foreignKeyColumn,n),p=u.id;if(p&&typeof p=="object"){let y=rt(p._is_null),g=rt(p._is_not_null);if(y===!0)s.push(`${l} IS NULL`);else if(y===!1)s.push(`${l} IS NOT NULL`);else if(g===!0)s.push(`${l} IS NOT NULL`);else if(g===!1)s.push(`${l} IS NULL`);else if(p._eq!==void 0){let h=Re(p._eq,n);s.push(`${l} = ${h}`)}else if(p._neq!==void 0){let h=Re(p._neq,n);s.push(`${l} != ${h}`)}else if(p._in!==void 0){let m=(Array.isArray(p._in)?p._in:[p._in]).map(b=>Re(b,n)).join(", ");s.push(`${l} IN (${m})`)}else if(p._not_in!==void 0||p._nin!==void 0){let h=p._not_in??p._nin,b=(Array.isArray(h)?h:[h]).map(w=>Re(w,n)).join(", ");s.push(`${l} NOT IN (${b})`)}else if(p._gt!==void 0){let h=Re(p._gt,n);s.push(`${l} > ${h}`)}else if(p._gte!==void 0){let h=Re(p._gte,n);s.push(`${l} >= ${h}`)}else if(p._lt!==void 0){let h=Re(p._lt,n);s.push(`${l} < ${h}`)}else if(p._lte!==void 0){let h=Re(p._lte,n);s.push(`${l} <= ${h}`)}}}}}return s}function or(r){return!r||typeof r!="object"||Array.isArray(r)?!1:!!(r._and&&Array.isArray(r._and)||r._or&&Array.isArray(r._or)||r._not!==void 0&&r._not!==null)}async function tr(r,e,t,n,i,o){let s=[];for(let a of r)if(a._and&&Array.isArray(a._and)&&a._and.length>0){let u=[];for(let c of a._and)if(or(c)){let d=e(t).select(`${t}.id`);await Pe(e,d,c,t,n,i,o),u.push({idSubquery:d})}else{let{fieldFilters:d,relationFilters:l}=H(c,n),f=await ir(e,t,n,i,o,l);u.push({fieldFilters:d,subqueries:f})}s.push(u)}else if(or(a)){let u=e(t).select(`${t}.id`);await Pe(e,u,a,t,n,i,o),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:c}=H(a,n),d=await ir(e,t,n,i,o,c);s.push([{fieldFilters:u,subqueries:d}])}return s}function ni(r,e,t,n,i){if("idSubquery"in e&&e.idSubquery){r.whereIn(`${t}.id`,e.idSubquery);return}let o=e;Object.keys(o.fieldFilters).length===0&&o.subqueries.length===0||r.where(function(){Object.keys(o.fieldFilters).length>0&&le(this,o.fieldFilters,t,i,n);for(let s of o.subqueries)this.whereRaw(s)})}function nr(r,e,t,n,i){let o=!0;for(let s of e){let a=function(){for(let u of s)ni(this,u,t,n,i)};o?(r.where(a),o=!1):r.orWhere(a)}}function Tn(r,e,t,n,i,o,s){let a=ti(e,i),u=ti(n,o),c=`${F(r,s)}.${F(e,s)}`,d=`${F(t,s)}.${F(n,s)}`;if(s==="postgres"){if(a&&!u)return`${c} = ${d}::uuid`;if(!a&&u)return`${c}::uuid = ${d}`}return`${c} = ${d}`}async function Bt(r,e,t,n,i,o,s){let a=i.relations.find(f=>f.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${e}"`);let u=a.targetTableName||a.targetTable;if(!u)throw new Error(`Relation "${t}" in table "${e}" is missing targetTable/targetTableName. Relation metadata: ${JSON.stringify(a,null,2)}`);let c=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn){let f=Object.keys(n||{});if(f.length===1&&f[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(y=>c.has(y)))return null}let d=s?await s(u):null,l;switch(a.type){case"one-to-many":l=r(u).select(r.raw("1")).whereRaw(Tn(u,a.foreignKeyColumn,e,"id",d,i,o));break;case"many-to-many":let f=s?await s(a.junctionTableName):null;l=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw(Tn(a.junctionTableName,a.junctionTargetColumn,u,"id",f,d,o))).whereRaw(Tn(a.junctionTableName,a.junctionSourceColumn,e,"id",f,i,o));break;case"many-to-one":case"one-to-one":l=r(u).select(r.raw("1")).whereRaw(Tn(u,"id",e,a.foreignKeyColumn,d,i,o));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?d?await Pe(r,l,n,u,d,o,s):l=le(l,n,u,o,d||void 0):l=le(l,n,u,o),l.toString()}async function Pe(r,e,t,n,i,o,s){if(!t||typeof t!="object")return;if(t._and&&Array.isArray(t._and)){for(let c of t._and)if(c._or&&Array.isArray(c._or)&&c._or.length>0){let d=await tr(c._or,r,n,i,o,s);e.where(function(){nr(this,d,n,i,o)})}else if(c._and&&Array.isArray(c._and)&&c._and.length>0)for(let d of c._and)await Pe(r,e,d,n,i,o,s);else await Pe(r,e,c,n,i,o,s);return}if(t._or&&Array.isArray(t._or)){let c=await tr(t._or,r,n,i,o,s);e.where(function(){nr(this,c,n,i,o)});return}if(t._not){let c=t._not;if(c._and&&Array.isArray(c._and)&&c._and.length>0){let f=[];for(let p of c._and)if(or(p)){let y=r(n).select(`${n}.id`);await Pe(r,y,p,n,i,o,s),f.push({idSubquery:y})}else{let{fieldFilters:y,relationFilters:g}=H(p,i),h=await ir(r,n,i,o,s,g);f.push({fieldFilters:y,subqueries:h})}e.whereNot(function(){for(let p of f)ni(this,p,n,i,o)});return}if(c._or&&Array.isArray(c._or)&&c._or.length>0){let f=await tr(c._or,r,n,i,o,s);e.whereNot(function(){nr(this,f,n,i,o)});return}let{fieldFilters:d,relationFilters:l}=H(c,i);e.whereNot(function(){Object.keys(d).length>0&&le(this,d,n,o,i)});for(let[f,p]of Object.entries(l)){let y=await Bt(r,n,f,p,i,o,s);if(y===null){let g=i.relations.find(h=>h.propertyName===f);if(g&&g.foreignKeyColumn){let h=rr(n,g.foreignKeyColumn,o),b=p.id;if(b&&typeof b=="object"){let w=rt(b._is_null),C=rt(b._is_not_null);if(w===!0)e.whereRaw(`${h} IS NOT NULL`);else if(w===!1)e.whereRaw(`${h} IS NULL`);else if(C===!0)e.whereRaw(`${h} IS NULL`);else if(C===!1)e.whereRaw(`${h} IS NOT NULL`);else if(b._eq!==void 0)e.whereRaw(`${h} != ?`,[b._eq]);else if(b._neq!==void 0)e.whereRaw(`${h} = ?`,[b._neq]);else if(b._in!==void 0){let T=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${h} NOT IN (${T.map(()=>"?").join(", ")})`,T)}else if(b._not_in!==void 0||b._nin!==void 0){let T=b._not_in??b._nin,k=Array.isArray(T)?T:[T];e.whereRaw(`${h} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${y})`)}return}let{fieldFilters:a,relationFilters:u}=H(t,i);Object.keys(a).length>0&&le(e,a,n,o,i);for(let[c,d]of Object.entries(u)){let l=await Bt(r,n,c,d,i,o,s);if(l===null){let f=i.relations.find(p=>p.propertyName===c);if(f&&f.foreignKeyColumn){let p=rr(n,f.foreignKeyColumn,o),g=d.id;if(g&&typeof g=="object"){let h=rt(g._is_null),m=rt(g._is_not_null);if(h===!0)e.whereRaw(`${p} IS NULL`);else if(h===!1)e.whereRaw(`${p} IS NOT NULL`);else if(m===!0)e.whereRaw(`${p} IS NOT NULL`);else if(m===!1)e.whereRaw(`${p} IS NULL`);else if(g._eq!==void 0)e.whereRaw(`${p} = ?`,[g._eq]);else if(g._neq!==void 0)e.whereRaw(`${p} != ?`,[g._neq]);else if(g._in!==void 0){let b=Array.isArray(g._in)?g._in:[g._in];e.whereRaw(`${p} IN (${b.map(()=>"?").join(", ")})`,b)}else if(g._not_in!==void 0||g._nin!==void 0){let b=g._not_in??g._nin,w=Array.isArray(b)?b:[b];e.whereRaw(`${p} NOT IN (${w.map(()=>"?").join(", ")})`,w)}}}}else e.whereRaw(`EXISTS (${l})`)}}async function Lt(r,e,t,n,i,o,s){await Pe(r,e,t,n,i,o,s)}ae();ae();function it(r,e,t,n,i){for(let o of e){let s=o.field.split("."),a=t||s[0],u=s[s.length-1],c=Dt(n,a,u,o.value);switch(o.operator){case"=":r=r.where(o.field,"=",c);break;case"!=":r=r.where(o.field,"!=",c);break;case">":r=r.where(o.field,">",c);break;case"<":r=r.where(o.field,"<",c);break;case">=":r=r.where(o.field,">=",c);break;case"<=":r=r.where(o.field,"<=",c);break;case"like":r=r.where(o.field,"like",c);break;case"in":let d=Array.isArray(o.value)?o.value.map(g=>Dt(n,a,u,g)):[c];r=r.whereIn(o.field,d);break;case"not in":let l=Array.isArray(o.value)?o.value.map(g=>Dt(n,a,u,g)):[c];r=r.whereNotIn(o.field,l);break;case"is null":r=r.whereNull(o.field);break;case"is not null":r=r.whereNotNull(o.field);break;case"_contains":r=r.where(o.field,"like",`%${o.value}%`);break;case"_starts_with":r=r.where(o.field,"like",`${o.value}%`);break;case"_ends_with":r=r.where(o.field,"like",`%${o.value}`);break;case"_between":let f=o.value;if(typeof f=="string"&&(f=f.split(",").map(g=>g.trim())),Array.isArray(f)&&f.length===2){let g=Dt(n,a,u,f[0]),h=Dt(n,a,u,f[1]);r=r.whereBetween(o.field,[g,h])}break;case"_is_null":r=c===!0||c==="true"?r.whereNull(o.field):r.whereNotNull(o.field);break;case"_is_not_null":r=c===!0||c==="true"?r.whereNotNull(o.field):r.whereNull(o.field);break}}return r}function Wt(r,e,t,n){let i=[],o=t;if(!r||typeof r!="object")return i;for(let[s,a]of Object.entries(r))if(s==="_and"&&Array.isArray(a)){let u=a.map(c=>{let d=Wt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&i.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(c=>{let d=Wt(c,e,t,n);return d.length>0?`(${d.join(" AND ")})`:null}).filter(c=>c!==null);u.length>0&&i.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=Wt(a,e,t,n);u.length>0&&i.push(`NOT (${u.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[u,c]of Object.entries(a)){let d=`${F(e,n)}.${F(s,n)}`,l;if(c===null)l="NULL";else if(typeof c=="string"){let f=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,p=o.columns?.find(g=>g.name===s);p&&(p.type?.toLowerCase()==="uuid"||p.type?.toLowerCase().includes("uuid"))&&f.test(c)&&n==="postgres"?l=`'${c}'::uuid`:l=`'${c.replace(/'/g,"''")}'`}else typeof c=="boolean"?l=c?"true":"false":typeof c=="number"?l=String(c):l=`'${String(c).replace(/'/g,"''")}'`;if(u==="_eq")i.push(`${d} = ${l}`);else if(u==="_neq")i.push(`${d} != ${l}`);else if(u==="_gt")i.push(`${d} > ${l}`);else if(u==="_gte")i.push(`${d} >= ${l}`);else if(u==="_lt")i.push(`${d} < ${l}`);else if(u==="_lte")i.push(`${d} <= ${l}`);else if(u==="_is_null")i.push(`${d} IS NULL`);else if(u==="_is_not_null")i.push(`${d} IS NOT NULL`);else if(u==="_in"){let p=(Array.isArray(c)?c:[c]).map(y=>typeof y=="string"?`'${y.replace(/'/g,"''")}'`:String(y)).join(", ");i.push(`${d} IN (${p})`)}else if(u==="_not_in"||u==="_nin"){let p=(Array.isArray(c)?c:[c]).map(y=>typeof y=="string"?`'${y.replace(/'/g,"''")}'`:String(y)).join(", ");i.push(`${d} NOT IN (${p})`)}else if(u==="_contains"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${d}) LIKE '%${f.toLowerCase()}%'`)}else if(u==="_starts_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE lower(unaccent('${f}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${f}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${d}) LIKE '${f.toLowerCase()}%'`)}else if(u==="_ends_with"){let f=String(c).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${d})) ILIKE '%' || lower(unaccent('${f}'))`):n==="mysql"?i.push(`lower(unaccent(${d})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${f}')) COLLATE utf8mb4_general_ci)`):i.push(`lower(${d}) LIKE '%${f.toLowerCase()}'`)}else if(u==="_between"&&Array.isArray(c)&&c.length===2){let f=typeof c[0]=="string"?`'${c[0].replace(/'/g,"''")}'`:String(c[0]),p=typeof c[1]=="string"?`'${c[1].replace(/'/g,"''")}'`:String(c[1]);i.push(`${d} BETWEEN ${f} AND ${p}`)}}else{let u=`${F(e,n)}.${F(s,n)}`,c;a===null?c="NULL":typeof a=="string"?c=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?c=a?"true":"false":c=String(a),i.push(`${u} = ${c}`)}return i}function Kt(r){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Dt(r,e,t,n){if(n==null)return n;let i=r?.tables?.get(e);if(!i?.columns)return n;let o=i.columns.find(s=>s.name===t);if(!o)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;default:return n}}ar();Je();ae();qt();Ke();async function oi(r,e,t,n,i,o,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(cr(),ii)),u=await a(e,t,n,i,o,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function ur(r){let e=r;return e?async t=>{let n=e.tables?.get(t);return n?{name:n.name,columns:(n.columns||[]).map(i=>({name:i.name,type:i.type})),relations:n.relations||[]}:null}:null}function si(r,e,t,n,i){let o=r.targetTableName||r.targetTable;if(!o)return null;let s=r.foreignKeyColumn||z(r.propertyName);if(!s)return null;let a=l=>F(l,i),u=n?.tables?.get(o),d=(u?G(u):null)?.name||"id";return`(SELECT ${a(o)}.${a(e)} FROM ${a(o)} WHERE ${a(o)}.${a(d)} = ${a(t)}.${a(s)})`}qt();async function ai(r,e,t,n,i){let o={};if(n.includes("totalCount")||n.includes("*")){let s=await r(t).count("* as count").first();o.totalCount=Number(s?.count||0)}if(n.includes("filterCount")||n.includes("*")){let a=await e.clone().clearSelect().clearOrder().clear("limit").clear("offset").countDistinct(`${t}.id as count`).first();o.filterCount=Number(a?.count||0)}return o}var je=class r{constructor(e,t,n,i){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=i;this.logger=new wn(r.name);this.debugLog=[]}async execute(e){let t=performance.now();this.metadata=e.metadata;let n=e.debugLog||[];this.debugLog=n;let i=e.debugTrace;if(e.filter&&re(e.filter,e.tableName,e.metadata),!e.plan){let $=new ee;e={...e,plan:$.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:this.dbType})}}let o=e.plan,s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,u=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,c=o.rawFields&&o.rawFields.length>0&&!o.rawFields.includes("*");if(o.joins.length===0&&!o.hasRelationFilters&&!o.hasRelationSort&&!u&&!a&&c){i&&i.setQueryPath("simple");let $=await this.executeSimple(e,o);return i&&i.dur("sql_executor",t,{table:e.tableName}),$}let l={table:e.tableName,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?l.fields=e.fields:typeof e.fields=="string"&&(l.fields=e.fields.split(",").map($=>$.trim())));let f=e.filter;if(e.filter&&!ge(e.filter)){l.where=[];for(let[$,R]of Object.entries(e.filter))if(typeof R=="object"&&R!==null)for(let[N,J]of Object.entries(R)){let M;if(N==="_eq")M="=";else if(N==="_neq")M="!=";else if(N==="_in")M="in";else if(N==="_not_in"||N==="_nin")M="not in";else if(N==="_gt")M=">";else if(N==="_gte")M=">=";else if(N==="_lt")M="<";else if(N==="_lte")M="<=";else if(N==="_contains")M="_contains";else if(N==="_starts_with")M="_starts_with";else if(N==="_ends_with")M="_ends_with";else if(N==="_between")M="_between";else if(N==="_is_null")M="_is_null";else if(N==="_is_not_null")M="_is_not_null";else if(N==="_like")M="like";else if(N==="_ilike")M="ilike";else continue;l.where.push({field:$,operator:M,value:J})}else l.where.push({field:$,operator:"=",value:R})}if(e.sort){let $=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(R=>R.trim());l.sort=$.map(R=>{let N=R.trim();return N.startsWith("-")?{field:N.substring(1),direction:"desc"}:{field:N,direction:"asc"}})}else l.sort=[{field:"id",direction:"asc"}];let p=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,y=p===void 0||Number.isNaN(p)?void 0:p<0?0:p,g=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,h=g===void 0||Number.isNaN(g)?void 0:g;h&&y!==void 0?(l.offset=(h-1)*y,l.limit=y):y!==void 0&&(l.limit=y);let m=e.plan?.sortItems??(l.sort??[]).map($=>({joinId:null,field:$.field,direction:$.direction,fullPath:$.field})),b=[],w=[];for(let $ of m){if($.function==="count"){let R={sql:this.buildRelationCountSortSubquery(l.table,$),direction:$.direction};w.push(R);continue}if($.function==="max"||$.function==="min"){let R={sql:this.buildRelationAggregateSortSubquery(l.table,$),direction:$.direction};w.push(R);continue}if($.joinId===null){if($.field.includes(".")&&!e.plan){let N=$.field.split(".")[0];if(this.metadata?.tables?.get(l.table)?.relations?.some(Q=>Q.propertyName===N))continue}let R={field:$.field.includes(".")?$.field:`${l.table}.${$.field}`,direction:$.direction};b.push(R),w.push(R)}else{let R=e.plan?.joins.find(N=>N.id===$.joinId);if(R&&(R.relationType==="many-to-one"||R.relationType==="one-to-one")){let N=si(R.relationMeta,$.field,l.table,this.metadata,this.dbType);if(N){let J={sql:N,direction:$.direction};w.push(J)}}}}let C=[];if(l.fields&&l.fields.length>0||u||a){let $=ur(this.metadata),R=l.fields&&l.fields.length>0?l.fields:["*"],N=await oi(this.knex,l.table,R,$,this.dbType,this.maxQueryDepth,e.deep);N.select.length>0&&(l.select=[...l.select||[],...N.select]),C=N.batchFetchDescriptors||[]}l.where&&(l.where=l.where.map($=>$.field.includes(".")?$:{...$,field:`${l.table}.${$.field}`})),l.sort=b;let T=this.knex(l.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map($=>$.trim()).filter(Boolean),x=k.includes("filterCount")||k.includes("*"),_=k.includes("totalCount")||k.includes("*");if(l.select){let $=l.select.map(R=>typeof R=="string"&&R.trim().startsWith("(")?this.knex.raw(R):typeof R=="string"&&/ as /i.test(R)?this.knex.raw(R):R);T=T.select($)}if(x&&T.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),_){let $=F(l.table,this.dbType);T.select(this.knex.raw(`(SELECT COUNT(*) FROM ${$}) as __total_count__`))}let v=["table_definition","column_definition","relation_definition","method_definition"].includes(l.table);if(f&&(ge(f)||Object.keys(f).length>0)){let $=this.metadata?.tables?.get(l.table);(!v&&$&&$.relations&&$.relations.length>0?H(f,$).hasRelations:!1)?await Lt(this.knex,T,f,l.table,$,this.dbType,N=>this.metadata?.tables?.get(N)):e.plan?.filterTree?ce(T,e.plan.filterTree,{dbType:this.dbType,rootTable:l.table}):(this.logger.debug(`buildWhereClause fallback for table=${l.table}`),T=le(T,f,l.table,this.dbType,$))}else l.where&&l.where.length>0&&(T=it(T,l.where,l.table,this.metadata,this.dbType));for(let $ of w)if($.field){let R=$.field.includes(".")?$.field:`${l.table}.${$.field}`;T=T.orderBy(R,$.direction)}else $.sql&&(T=T.orderByRaw(`${$.sql} ${$.direction.toUpperCase()}`));l.groupBy&&(T=T.groupBy(l.groupBy)),l.offset&&(T=T.offset(l.offset)),l.limit!==void 0&&l.limit!==null&&l.limit>0&&(T=T.limit(l.limit));let j=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:l.table,sql:T.toSQL().toNative()});let S;if(e.debugMode&&(S=T.toSQL().toNative().sql),e.debugMode&&i){let $=T.toSQL().toNative();i.setSql($.sql);try{let R=$.sql.replace(/\$\d+/g,"?"),N=await this.knex.raw(`EXPLAIN ${R}`,$.bindings);i.setExplain(this.dbType==="postgres"?N.rows:N[0])}catch(R){i.setExplain({error:String(R)})}}let E,A=performance.now();E=await T,i&&i.dur("db_execute",A,{table:e.tableName});let D=await this.resolveEmptyPageMeta(T,l.table,k,E.length),B=D.filterCount??0;if(j=D.totalCount??0,x&&E.length>0&&(B=Number(E[0].__filter_count__||0),E.forEach($=>{delete $.__filter_count__})),_&&E.length>0&&E[0].__total_count__!==void 0&&(j=Number(E[0].__total_count__||0),E.forEach($=>{delete $.__total_count__})),C&&C.length>0&&E.length>0){let $=ur(this.metadata);if($){let{executeBatchFetches:R}=await Promise.resolve().then(()=>(pr(),li));await R(this.knex,E,C,$,this.maxQueryDepth??3,0,l.table,this.dbType,this.metadata,i)}}if(this.knexService){let $=performance.now();E=await this.knexService.parseResult(E,l.table),i&&i.dur("db_parseResult",$,{table:e.tableName})}else{let $=(R,N)=>{if(!R||!this.metadata)return R;let J=this.metadata.tables?.get(N);if(!J)return R;if(Array.isArray(R))return R.map(Q=>$(Q,N));if(typeof R!="object"||Buffer.isBuffer(R))return R;let M={...R};for(let Q of J.columns)if(Q.type==="simple-json"&&M[Q.name]&&typeof M[Q.name]=="string")try{M[Q.name]=JSON.parse(M[Q.name])}catch{}for(let[Q,Y]of Object.entries(M))if(Y&&typeof Y=="object"&&!Array.isArray(Y)&&!Buffer.isBuffer(Y)){let vn=Y;if(vn.id!==void 0||vn.createdAt!==void 0){let lt=J.relations?.find(ct=>ct.propertyName===Q);lt&&(M[Q]=$(Y,lt.targetTableName))}}else if(Array.isArray(Y)&&Y.length>0&&typeof Y[0]=="object"&&Y[0].id!==void 0){let lt=J.relations?.find(ct=>ct.propertyName===Q);lt&&(M[Q]=Y.map(ct=>$(ct,lt.targetTableName)))}return M};E=$(E,l.table)}return i&&(i.setQueryPath("full"),i.dur("sql_executor",t,{table:e.tableName})),{data:E,...k.length>0&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:j}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:B}:{}}},...S!==void 0&&{sql:S}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=G(s)?.name||"id",u=F(e,this.dbType),c=F(a,this.dbType);if(!n||!o)throw new I(`Sort relation '${i}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let d=n.foreignKeyColumn||n.mappedBy;if(!d)throw new I(`Sort function '_count(${i})' cannot resolve relation key on '${e}'.`);let l=F(o,this.dbType),f=F(d,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}if(n.type==="many-to-many"){let d=this.resolveManyToManyContract(n,i,e),l=F(d.tableName,this.dbType),f=F(d.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${l} WHERE ${l}.${f} = ${u}.${c})`}throw new I(`Sort function '_count(${i})' is only supported for list relations on '${e}'.`)}buildRelationAggregateSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=t.aggregateField,s=n?.targetTableName||n?.targetTable,a=this.metadata?.tables?.get(e),u=this.metadata?.tables?.get(s),c=G(a)?.name||"id",d=G(u)?.name||"id",l=F(e,this.dbType),f=F(c,this.dbType),p=t.function==="min"?"MIN":t.function==="max"?"MAX":null;if(!p||!n||!s||!o)throw new I(`Sort function '${t.field}' is not supported on '${e}'.`);let y=F(s,this.dbType),g=F(o,this.dbType);if(n.type==="one-to-many"){let h=n.foreignKeyColumn||n.mappedBy;if(!h)throw new I(`Sort function '_${t.function}(${i}.${o})' cannot resolve relation key on '${e}'.`);let m=F(h,this.dbType);return`(SELECT ${p}(${y}.${g}) FROM ${y} WHERE ${y}.${m} = ${l}.${f})`}if(n.type==="many-to-many"){let h=this.resolveManyToManyContract(n,i,e),m=F(h.tableName,this.dbType),b=F(h.sourceColumn,this.dbType),w=F(h.targetColumn,this.dbType),C=F(d,this.dbType);return`(SELECT ${p}(${y}.${g}) FROM ${m} JOIN ${y} ON ${y}.${C} = ${m}.${w} WHERE ${m}.${b} = ${l}.${f})`}throw new I(`Sort function '_${t.function}(${i}.${o})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,n){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new I(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async resolveEmptyPageMeta(e,t,n,i){return i>0||n.length===0?{}:ai(this.knex,e,t,n,!1)}async executeSimple(e,t){let n=e.tableName,i=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],o=this.knex(n).select(i);t.filterTree&&ce(o,t.filterTree,{dbType:this.dbType,rootTable:n});for(let h of t.sortItems){let m=h.field.includes(".")?h.field:`${n}.${h.field}`;o=o.orderBy(m,h.direction)}t.limit!==void 0&&t.limit!==null&&t.limit>0&&(o=o.limit(t.limit)),t.offset!==void 0&&(o=o.offset(t.offset));let s=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(h=>h.trim()).filter(Boolean),a=s.includes("filterCount")||s.includes("*"),u=s.includes("totalCount")||s.includes("*");if(a&&o.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),u){let h=F(n,this.dbType);o.select(this.knex.raw(`(SELECT COUNT(*) FROM ${h}) as __total_count__`))}let c=e.debugTrace,d;if(e.debugMode){let h=o.toSQL().toNative();if(d=h.sql,c){c.setSql(h.sql);try{let m=h.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${m}`,h.bindings);c.setExplain(this.dbType==="postgres"?b.rows:b[0])}catch(m){c.setExplain({error:String(m)})}}}let l=performance.now(),f;f=await o,c&&c.dur("db_execute",l,{table:n}),this.knexService&&(f=await this.knexService.parseResult(f,n));let p=await this.resolveEmptyPageMeta(o,n,s,f.length),y=p.filterCount??0,g=p.totalCount??0;return a&&f.length>0&&(y=Number(f[0].__filter_count__||0),f.forEach(h=>delete h.__filter_count__)),u&&f.length>0&&(g=Number(f[0].__total_count__||0),f.forEach(h=>delete h.__total_count__)),{data:f,...s.length>0&&{meta:{...u?{totalCount:g}:{},...a?{filterCount:y}:{}}},...d!==void 0&&{sql:d}}}async aggregate(e){let t=tt(e.aggregate,e.tableName,e.metadata),n=this.knex(e.tableName),i=F(e.tableName,this.dbType),o=[],s=[];for(let l of t.dimensions){let f=`${i}.${F(l.field,this.dbType)}`,p=l.bucket?this.buildSqlBucketExpression(f,l.bucket,l.timezone,l.column.type):f;s.push(this.knex.raw(`${p} as ${F(l.outputKey,this.dbType)}`)),o.push(p)}for(let l of t.measures){let f=`${i}.${F(l.field,this.dbType)}`,p=l.operation==="count"?`COUNT(${f})`:l.operation==="countDistinct"?`COUNT(DISTINCT ${f})`:`${l.operation.toUpperCase()}(${f})`;s.push(this.knex.raw(`${p} as ${F(l.outputKey,this.dbType)}`))}let u=new ee().plan({tableName:e.tableName,filter:t.filter,metadata:e.metadata,dbType:this.dbType});u.hasRelationFilters?await Lt(this.knex,n,t.filter,e.tableName,e.metadata?.tables?.get(e.tableName),this.dbType,l=>e.metadata?.tables?.get(l)):u.filterTree&&ce(n,u.filterTree,{dbType:this.dbType,rootTable:e.tableName}),n.select(s),o.length>0&&n.groupByRaw(o.join(", "));for(let l of t.sort)n.orderByRaw(`${F(l.field,this.dbType)} ${l.direction.toUpperCase()}`);return t.limit!==void 0&&n.limit(t.limit).offset((t.page-1)*t.limit),{data:(await n).map(l=>{let f={...l};for(let p of t.measures){let y=f[p.outputKey];y!=null&&typeof y=="string"&&/^-?\d+(\.\d+)?$/.test(y)&&(f[p.outputKey]=Number(y))}return f})}}buildSqlBucketExpression(e,t,n,i){let o=Kt(n);if(this.dbType==="postgres"){let s=`(${e} AT TIME ZONE ${o})`;return`DATE_TRUNC(${Kt(t)}, ${s})`}if(this.dbType==="mysql"){let s=`CONVERT_TZ(${e}, '+00:00', ${o})`;return t==="year"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-01-01'), '%Y-%m-%d')`:t==="month"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-01'), '%Y-%m-%d')`:t==="week"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%u-1'), '%Y-%u-%d')`:t==="day"?`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-%d'), '%Y-%m-%d')`:`STR_TO_DATE(DATE_FORMAT(${s}, '%Y-%m-%d %H:00:00'), '%Y-%m-%d %H:%i:%s')`}throw new I(`Aggregate time bucket is not supported on ${this.dbType}`)}};var kn=require("mongodb"),at=class{constructor(e){this.debugLog=[];this.batchInserts={items:[],flushing:!1};this.knexService=e.knexService,this.mongoService=e.mongoService,this.databaseConfigService=e.databaseConfigService,this.runtimeMetricsCollectorService=e.runtimeMetricsCollectorService,this.lazyRef=e.lazyRef,this.dbType=this.databaseConfigService.getDbType(),this.batchInsertMaxSize=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_SIZE",100),this.batchInsertMaxWaitMs=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_WAIT_MS",100),this.batchInsertConcurrency=this.readPositiveEnv("DYNAMIC_CREATE_BATCH_CONCURRENCY",5),this.batchInsertTraceFile=process.env.QUERY_BUILDER_BATCH_TRACE_FILE||process.env.DYNAMIC_CREATE_BATCH_TRACE_FILE,this.batchInsertTraceFile&&(0,Rn.mkdirSync)((0,ci.dirname)(this.batchInsertTraceFile),{recursive:!0})}async runWithPolicy(e,t){return this.knexService?this.knexService.runWithPolicy(e,t):this.mongoService?this.mongoService.runWithPolicy(e,t):t()}async runWithFieldPermissionCheck(e,t){return this.knexService?this.knexService.runWithFieldPermissionCheck(e,t):this.mongoService?this.mongoService.runWithFieldPermissionCheck(e,t):t()}async runWithTelemetryContext(e,t){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.runWithQueryContext(e,t):await t()}getDbType(){return this.dbType}safeObjectId(e){if(!kn.ObjectId)return e;if(typeof e=="string")try{return new kn.ObjectId(e)}catch{return e}return e}async getMetadataForQuery(){let e={tables:new Map,tablesList:[]},t=this.lazyRef.metadataCacheService;return t?t.isLoaded?.()?await t.getMetadata?.()??e:t.getDirectMetadata?.()??e:e}async buildMongoFilter(e,t){let n=await this.getMetadataForQuery(),i=Qe(n,e,t,this.dbType);return i._id!==void 0&&(i._id=this.safeObjectId(i._id)),i}async applyWhereToKnex(e,t,n){let i=await this.getMetadataForQuery();return{query:it(e,t,n??"",i,this.dbType)}}async runMongoMutationInSaga(e){return!this.mongoService?.runInSaga||this.mongoService.isInSaga?.()?e():(await this.mongoService.runInSaga(e)).data}async insertWithOptions(e){if(e.batch)return await this.insertManyBatch(e.table,e.data);if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{if(Array.isArray(e.data)){let t=[];for(let n of e.data){let i=await this.mongoService.insertOne(e.table,n);t.push(X(i))}return t}return this.mongoService.insertOne(e.table,e.data)});if(Array.isArray(e.data)){let t=[];for(let n of e.data){let i=await this.knexService.insertWithCascade(e.table,n);t.push(i)}return t}else return await this.knexService.insertWithCascade(e.table,e.data)}async select(e){let t=performance.now(),n=await this.getMetadataForQuery(),i=performance.now(),s=new ee().plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:n,dbType:this.dbType}),a=e.debugTrace;if(a&&(a.dur("qb_planner",i,{table:e.tableName}),a.setPlan(this.sanitizePlan(s))),this.dbType==="mongodb"){let l=await new Ae(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}let c=await new je(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:n,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),c}sanitizePlan(e){return{rawFields:e.rawFields,hasRelationFilters:e.hasRelationFilters,hasRelationSort:e.hasRelationSort,joins:e.joins?.length??0,sortItems:e.sortItems,limit:e.limit,offset:e.offset,page:e.page,isSimpleQuery:e.joins?.length===0&&!e.hasRelationFilters&&!e.hasRelationSort}}async updateWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),s=this.mongoService.collection(e.table),a=this.mongoService.ioSignalPublic?.()??{},u=await s.find(o,a).toArray(),c=[];for(let d of u){let l=await this.mongoService.updateOne(e.table,d._id,e.data);c.push(l)}return c});let t=this.knexService.getKnex(),n=t(e.table);e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n;for(let o of i)await this.knexService.updateWithCascade(e.table,o.id,e.data);if(e.returning){let o=t(e.table);return e.where.length>0&&await this.applyWhereToKnex(o,e.where,e.table),await o.select(e.returning)}return{affected:i.length}}async deleteWithOptions(e){if(!Array.isArray(e.where))throw new TypeError("Delete conditions must be an array");if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let i=await this.buildMongoFilter(e.where,e.table),o=this.mongoService.collection(e.table),s=this.mongoService.ioSignalPublic?.()??{},a=await o.find(i,s).toArray(),u=0;for(let c of a)await this.mongoService.deleteOne(e.table,c._id)&&u++;return u});let n=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table)),await n.delete()}async count(e){if(this.dbType==="mongodb"){let o=e.where?await this.buildMongoFilter(e.where,e.table):{};return this.mongoService.count(e.table,o)}let n=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n.count("* as count").first();return Number(i?.count||0)}whereToFilter(e){let t={},n=this.databaseConfigService.isMongoDb();for(let[i,o]of Object.entries(e))i==="id"||i==="_id"?n?t._id=this.normalizeWhereFilterValue("_id",o):t.id=this.normalizeWhereFilterValue("id",o):t[i]=this.normalizeWhereFilterValue(i,o);return t}normalizeWhereFilterValue(e,t){return this.isFilterOperatorObject(t)?this.databaseConfigService.isMongoDb()&&e==="_id"?this.normalizeMongoIdOperatorValue(t):t:{_eq:this.databaseConfigService.isMongoDb()&&e==="_id"?this.safeObjectId(t):t}}isFilterOperatorObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof kn.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[n,i]of Object.entries(e))t[n]=Array.isArray(i)?i.map(o=>this.safeObjectId(o)):this.safeObjectId(i);return t}filterToWhere(e){let t=[];for(let[n,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let o=Object.entries(i)[0];if(o){let[s,a]=o,u=this.mapFilterOperatorToSql(s);t.push({field:n,operator:u,value:a})}}return t}mapFilterOperatorToSql(e){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"like",_starts_with:"like",_ends_with:"like",_is_null:"is null",_is_not_null:"is not null"}[e]||"="}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,maxQueryDepth:e.maxQueryDepth})})}async aggregate(e){return this.trackQueryMetric("aggregate",e.table,async()=>{let t=await this.getMetadataForQuery();return this.dbType==="mongodb"?new Ae(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).aggregate({tableName:e.table,aggregate:e.aggregate,metadata:t,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,dbType:this.dbType}):new je(this.knexService.getKnex(),this.dbType,this.knexService).aggregate({tableName:e.table,aggregate:e.aggregate,metadata:t,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t,n){return n?.batch?await this.insertManyBatch(e,t):this.trackQueryMetric("insert",e,async()=>{if(this.dbType==="mongodb"){let a=await this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));return X(a)}let i=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),s=i||t.id;return await o(e).where("id",s).first()})}async createMany(e,t){return t.length===0?[]:this.trackQueryMetric("insert_many",e,async()=>this.dbType==="mongodb"?(await this.runMongoMutationInSaga(async()=>typeof this.mongoService.insertManyWithCascade=="function"?this.mongoService.insertManyWithCascade(e,t):Promise.all(t.map(i=>this.mongoService.insertOne(e,i))))).map(i=>X(i)):this.knexService.insertManyWithCascade(e,t))}async insertMany(e,t){return this.createMany(e,t)}async flushBatchInserts(){for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)await this.flushBatchInsertBuffer()}async insertManyBatch(e,t){let n=Array.isArray(t)?t:[t];for(let i of n)this.batchInserts.items.push({table:e,data:i});return this.traceBatchInsert("enqueue",{tableName:e,count:n.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i)),{accepted:!0,batch:!0,count:n.length}}async flushBatchInsertBuffer(){if(this.batchInserts.flushing){await this.batchInserts.flushPromise;return}let e=this.batchInserts.items.splice(0,this.batchInserts.items.length);if(this.batchInserts.timer&&(clearTimeout(this.batchInserts.timer),this.batchInserts.timer=void 0),e.length===0)return;this.batchInserts.flushing=!0;let t=this.executeBatchInsertFlush(e);this.batchInserts.flushPromise=t,await t}async executeBatchInsertFlush(e){let t=Date.now();try{let n=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...n.entries()].map(([i,o])=>({tableName:i,count:o.length}))}),await this.runLimited([...n.entries()],([i,o])=>this.flushBatchInsertTable(i,o)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}finally{this.batchInserts.flushing=!1,this.batchInserts.flushPromise=void 0,this.batchInserts.items.length>0&&(this.batchInserts.timer&&clearTimeout(this.batchInserts.timer),this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(n=>this.logBatchInsertError("QueryBuilder batch insert flush failed",n))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let n=Date.now();await this.runBatchInsertWithIsolation(e,t),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-n})}async runBatchInsertWithIsolation(e,t){if(t.length!==0)try{await(async()=>{if(this.dbType==="mongodb"){await this.runMongoMutationInSaga(async()=>{if(typeof this.mongoService?.insertManyWithCascade=="function"){await this.mongoService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.mongoService.insertOne(e,i.data)))});return}if(typeof this.knexService?.insertManyWithCascade=="function"){await this.knexService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.knexService.insertWithCascade(e,i.data)))})()}catch(n){if(t.length===1){this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,n);return}let i=Math.ceil(t.length/2);await Promise.all([this.runBatchInsertWithIsolation(e,t.slice(0,i)),this.runBatchInsertWithIsolation(e,t.slice(i))])}}groupBatchInsertsByTable(e){let t=new Map;for(let n of e){let i=t.get(n.table);i?i.push(n):t.set(n.table,[n])}return t}async runLimited(e,t){let n=0,i=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;n<e.length;){let o=e[n++];await t(o)}});await Promise.all(i)}readPositiveEnv(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.trunc(n):t}traceBatchInsert(e,t){this.batchInsertTraceFile&&(0,Rn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
|
|
52
52
|
`)}logBatchInsertError(e,t){let n=t?.message||String(t);this.traceBatchInsert("error",{message:e,error:n,code:t?.code,detail:t?.detail}),console.error(`${e}: ${n}`)}async update(e,t,n){return this.trackQueryMetric("update",e,async()=>{if(t&&typeof t=="object"&&"where"in t)return await this.updateWithOptions({table:e,where:t.where,data:n});if(this.dbType==="mongodb"){let o=await this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n));return X(o)}return await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first()})}async updateMany(e,t,n,i=this.getPkField()){return t.length===0?0:this.trackQueryMetric("update_many",e,async()=>{if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let a=this.mongoService.collection(e),u=this.mongoService.ioSignalPublic?.()??{};return(await a.updateMany({[i]:{$in:t}},{$set:n},u)).modifiedCount});let s=await this.knexService.getKnex()(e).whereIn(i,t).update(n);return typeof s=="number"?s:0})}async delete(e,t){return this.trackQueryMetric("delete",e,async()=>t&&typeof t=="object"&&"where"in t?await this.deleteWithOptions({table:e,where:t.where})>0:this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t)):await this.knexService.getKnex()(e).where("id",t).delete()>0)}async deleteMany(e,t,n=this.getPkField()){return t.length===0?0:this.trackQueryMetric("delete_many",e,async()=>{if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let s=this.mongoService.collection(e),a=this.mongoService.ioSignalPublic?.()??{},u=await s.find({[n]:{$in:t}},a).toArray(),c=0;for(let d of u)await this.mongoService.deleteOne(e,d._id)&&c++;return c});let o=await this.knexService.getKnex()(e).whereIn(n,t).delete();return typeof o=="number"?o:0})}async countRecords(e,t){if(this.dbType==="mongodb")return this.mongoService.count(e,t||{});let i=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.filterToWhere(t);({query:i}=await this.applyWhereToKnex(i,s,e))}let o=await i.count("* as count").first();return Number(o?.count||0)}async transaction(e){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>e(this.mongoService)):this.knexService.transaction(e)}async findById(e,t){if(this.dbType==="mongodb"){let i=this.safeObjectId(t);return this.mongoService.findOne(e,{_id:i})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[o,s]of Object.entries(t))o==="id"||o==="_id"?i._id=this.safeObjectId(s):i[o]=s;return this.mongoService.findOne(e,i)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[u,c]of Object.entries(t))u==="id"||u==="_id"?i._id=this.safeObjectId(c):i[u]=c;let o=this.mongoService.collection(e),s=this.mongoService.ioSignalPublic?.()??{};return await o.find(i,s).toArray()}return await this.knexService.getKnex()(e).where(t)}async insertAndGet(e,t){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));let n=await this.knexService.insertWithCascade(e,t),i=this.knexService.getKnex(),o=n||t.id;return await i(e).where("id",o).first()}async updateById(e,t,n){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n)):(await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first())}async deleteById(e,t){return this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t))?1:0:this.knexService.getKnex()(e).where("id",t).delete()}async raw(e,t){let n=this.dbType==="mongodb"?"mongodb":"sql";return this.trackQueryMetric("raw",n,async()=>{if(this.dbType==="mongodb"){let o=this.mongoService.getDb();if(typeof e=="string"){if(e.toLowerCase().includes("select 1"))return await o.command({ping:1});throw new Error("String queries not supported for MongoDB. Use db.command() object instead.")}return await o.command(e)}return await this.knexService.getKnex().raw(e,t)})}async trackQueryMetric(e,t,n){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.trackQuery({op:e,table:t},n):await n()}getConnection(){return this.dbType==="mongodb"?this.mongoService.getDb():this.knexService.getKnex()}getKnex(){if(this.dbType==="mongodb")throw new Error("getKnex() is not available for MongoDB. Use getConnection() or unified methods.");return this.knexService.getKnex()}getMongoDb(){if(this.dbType!=="mongodb")throw new Error("getMongoDb() is not available for SQL. Use getConnection() or unified methods.");return this.mongoService.getDb()}getDatabaseType(){return this.dbType}isMongoDb(){return this.dbType==="mongodb"}isSql(){return["mysql","postgres","mariadb","sqlite"].includes(this.dbType)}getPkField(){return this.isMongoDb()?"_id":"id"}getRecordId(e){return this.isMongoDb()?e._id:e.id}};pr();dr();cr();ae();qt();Ge();hn();ue();Je();var ui=new Set(["fields","filter","sort","limit","page","deep"]),Fn=3;function gr(r,e,t,n=0,i=3){if(!e||typeof e!="object")return;if(n>=i)throw new I(`deep option exceeds maximum query depth of ${i}`);let o=t?.tables?.get(r),s=new Map((o?.relations??[]).map(a=>[a.propertyName,a]));for(let[a,u]of Object.entries(e)){let c=s.get(a);if(!c)throw new I(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let f of Object.keys(u))if(!ui.has(f))throw new I(`Unknown deep option key '${f}' for relation '${a}'. Allowed: ${[...ui].join(", ")}`);let d=c.type;if(u.limit!==void 0&&(d==="many-to-one"||d==="one-to-one"))throw new I(`'limit' not supported on many-to-one/one-to-one relations (relation '${a}' on '${r}')`);if(u.page!==void 0&&u.limit===void 0)throw new I(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let l=c.targetTableName||c.targetTable;if(l){if(u.filter&&(re(u.filter,l,t),Oe(u.filter,l,t),xn(u.filter,0,a,r)),u.sort){_n(u.sort,l,t);let f=Array.isArray(u.sort)?u.sort:String(u.sort).split(",").map(p=>p.trim()).filter(Boolean);for(let p of f){let y=p.startsWith("-")?p.slice(1):p;qo(y,l,t,a,r)}}u.deep&&gr(l,u.deep,t,n+1,i)}}}function qo(r,e,t,n,i){if(r.includes("."))throw new I(`Sort field '${r}' is not supported for relation '${n}' on '${i}'. Sort only by local fields defined on '${e}'.`);let o=t?.tables?.get(e);if(!o)throw new I(`Sort field '${r}' references unknown table '${e}' (relation '${n}' on '${i}')`);let s=o.columns?.some(u=>u.name===r),a=r==="id"&&o.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new I(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${i}')`)}var Uo=new Set(["_and","_or","_not"]);function xn(r,e,t,n){if(!(!r||typeof r!="object"))for(let[i,o]of Object.entries(r)){if(Uo.has(i)){if(Array.isArray(o))for(let c of o)xn(c,e,t,n);else o&&typeof o=="object"&&xn(o,e,t,n);continue}if(i.startsWith("_")||!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).some(c=>!c.startsWith("_")))continue;let a=e+1;if(a>Fn)throw new I(`Filter path exceeds max dotted hops of ${Fn} at '${i}' (relation '${t}' on '${n}')`);let u={};for(let c of Object.keys(o))c.startsWith("_")||(u[c]=o[c]);xn(u,a,t,n)}}function di(r,e,t,n){return!r||typeof r!="object"?r:Jt(r,e,t,n)}function Jt(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let o=r.map(s=>Jt(s,e,t,n)).filter(s=>s!=null);return o.length>0?o:null}let i={};for(let[o,s]of Object.entries(r)){if(o==="_and"||o==="_or"){let l=(Array.isArray(s)?s:[s]).map(f=>Jt(f,e,t,n)).filter(f=>f!=null&&Object.keys(f).length>0);l.length>0&&(i[o]=l);continue}if(o==="_not"){let d=Jt(s,e,t,n);d!=null&&Object.keys(d).length>0&&(i[o]=d);continue}let a=t?.tables?.get(e),u=a?.relations?.find(d=>d.propertyName===o);if(u){if(!n(e,o,"relation"))continue;let d=u.targetTableName||u.targetTable;if(!d)continue;let l=Jt(s,d,t,n);l!=null&&Object.keys(l).length>0&&(i[o]=l);continue}if(a?.columns?.find(d=>d.name===o)){if(!n(e,o,"column"))continue;i[o]=s;continue}i[o]=s}return i}function fi(r,e,t,n){if(!r)return r;let i=Array.isArray(r)?r:r.split(",").map(s=>s.trim()).filter(Boolean),o=[];for(let s of i){let c=(s.startsWith("-")?s.slice(1):s).split("."),d=!0,l=e;for(let f=0;f<c.length;f++){let p=c[f],y=f===c.length-1,g=t?.tables?.get(l);if(!g){d=!1;break}if(y)g.columns?.find(m=>m.name===p)?n(l,p,"column")||(d=!1):g.relations?.find(b=>b.propertyName===p)&&(n(l,p,"relation")||(d=!1));else{let h=g.relations?.find(m=>m.propertyName===p);if(!h){d=!1;break}if(!n(l,p,"relation")){d=!1;break}l=h.targetTableName||h.targetTable||l}}d&&o.push(s)}if(o.length!==0)return Array.isArray(r)?o:o.join(",")}Et();Je();Mt();sn();Ke();ue();function Qo(r){let e=new at({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,i=()=>(t||(t=new We({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService,onExecutorWorkerCrash:r.onExecutorWorkerCrash,onExecutionFinished:r.onExecutionFinished})),t),o=()=>(n||(n=new Be({isolatedExecutorService:i()})),n);return{queryBuilderService:e,get isolatedExecutorService(){return i()},get executorEngineService(){return o()},async onDestroy(){await t?.onDestroy?.()}}}0&&(module.exports={ALL_SUPPORTED_OPERATORS,AuthenticationException,AuthorizationException,BadRequestException,BatchExecutionBudget,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,DEEP_TO_MANY_DEFAULT_LIMIT,DEFAULT_BATCH_FETCH_IO_CONCURRENCY,DEFAULT_TIMEOUT_MS,DOTTED_PATH_MAX_HOPS,DatabaseException,DuplicateResourceException,ErrorHandler,ExecutorEngineService,ExternalServiceException,FIELD_OPERATORS,FileNotFoundException,FileSizeExceededException,FileUploadException,HttpException,InvalidTokenException,IsolatedExecutorService,JoinRegistry,LOGICAL_OPERATORS,MongoBatchAdapter,MongoQueryExecutor,PER_PARENT_CONCURRENCY,QueryBuilderService,QueryPlanner,ResourceNotFoundException,SchemaException,ScriptContractService,ScriptExecutionException,ScriptTimeoutException,ServiceUnavailableException,SqlBatchAdapter,SqlQueryExecutor,TokenExpiredException,ValidationException,WHERE_IN_CHUNK_SIZE,WorkerPool,applyOperatorToMatch,applyRelationFilters,applyWhereToKnex,assertFieldOperatorValueIsClean,buildMongoCharFoldMapJson,buildMongoFoldTextSearchJs,buildRelationSubquery,buildSqlWherePartsFromFieldAst,buildWhereClause,camelToSnake,chunkedFetch,compileScriptSource,computeEngineTuning,createEnfyraKernel,dslOpToCompareOp,encodeMainThreadToIsolate,escapeSqlValue,executeBatchFetches,executeMongoBatchFetches,expandFieldsToJoinsAndSelect,getEffectiveCpuCount,getEffectiveMemoryBytes,getEngineTuning,getExecutableScript,getForeignKeyColumnName,getIoAbortSignal,getJunctionColumnNames,getJunctionTableName,getPrimaryKeyColumn,getScriptLegacyField,getShortFkConstraintName,getShortFkName,getShortIndexName,getShortPkName,hasLogicalOperators,isExecutableJavaScript,isScriptTable,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,perParentRun,quoteIdentifier,quoteQualifiedIdentifier,resolveExecutableScript,rewriteFilterDenyingFields,rewriteSortDroppingDenied,runWithIoAbortSignal,scriptContractService,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,validateDeepOptions,validateFilterShape,whereToMongoFilter});
|