@enfyra/kernel 1.1.11 → 1.1.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var P=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var g=P((L,b)=>{"use strict";function A({handles:e,createHandleId:t,callIsolateCallback:a}){function i(f,r){if(r==null)return r;let d=typeof r;if(d==="string"||d==="number"||d==="boolean")return r;if(r instanceof Date)return{__date:r.toISOString()};if(r instanceof Set)return{__set:Array.from(r.values()).map(n=>i(f,n))};if(r instanceof Map)return{__map:Array.from(r.entries()).map(([n,p])=>[i(f,n),i(f,p)])};if(r instanceof RegExp)return{__regexp:{source:r.source,flags:r.flags}};if(r instanceof Error)return{__error:{name:r.name,message:r.message,stack:r.stack}};if(typeof URL<"u"&&r instanceof URL)return{__url:r.href};if(typeof URLSearchParams<"u"&&r instanceof URLSearchParams)return{__urlSearchParams:r.toString()};if(typeof Buffer<"u"&&Buffer.isBuffer(r)||r._isBuffer===!0)return c(f,r);if(ArrayBuffer.isView(r))return{__typedArray:r.constructor?.name||"Uint8Array",data:Array.from(r)};if(r instanceof ArrayBuffer)return{__arrayBuffer:Array.from(new Uint8Array(r))};if(Array.isArray(r))return r.map(n=>i(f,n));if(d==="object"&&m(r)){let n={};for(let[p,h]of Object.entries(r))n[p]=i(f,h);return n}return c(f,r)}function c(f,r){let d=t(f);return e.set(d,r),{__pkgHandle:d}}function o(f,r){if(!r||typeof r!="object")return r;if(r.__fnRef)return(...n)=>a(f,r.__fnRef,n);if(r.__pkgHandleArg){let n=e.get(r.__pkgHandleArg);if(!n)throw new Error(`Package argument handle not found: ${r.__pkgHandleArg}`);return n}if(r.__date)return new Date(r.__date);if(r.__set)return new Set(r.__set.map(n=>o(f,n)));if(r.__map)return new Map(r.__map.map(([n,p])=>[o(f,n),o(f,p)]));if(r.__regexp)return new RegExp(r.__regexp.source,r.__regexp.flags||"");if(r.__error){let n=new Error(r.__error.message||"");return n.name=r.__error.name||"Error",r.__error.stack&&(n.stack=r.__error.stack),n}if(r.__url)return new URL(r.__url);if(r.__urlSearchParams)return new URLSearchParams(r.__urlSearchParams);if(r.__blob)return new Blob([Uint8Array.from(r.__blob.data||[])],{type:r.__blob.type||""});if(r.__file){let n=[Uint8Array.from(r.__file.data||[])],p={type:r.__file.type||"",lastModified:r.__file.lastModified};return typeof File<"u"?new File(n,r.__file.name||"file",p):new Blob(n,p)}if(r.__formData){let n=new FormData;for(let[p,h]of r.__formData)n.append(p,o(f,h));return n}if(r.__typedArray){let n=globalThis[r.__typedArray]||Uint8Array;return new n(r.data||[])}if(r.__arrayBuffer)return Uint8Array.from(r.__arrayBuffer).buffer;if(Array.isArray(r))return r.map(n=>o(f,n));let d={};for(let[n,p]of Object.entries(r))d[n]=o(f,p);return d}function s(f,r){return JSON.parse(r||"[]").map(d=>o(f,d))}return{createPackageHandle:c,deserializePackageArg:o,deserializePackageArgs:s,serializePackageValue:i}}function m(e){if(e===null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:!Object.values(e).some(a=>typeof a=="function")}b.exports={createPackageRuntimeCodec:A}});var{createPackageRuntimeCodec:S}=g(),w=new Map,u=new Map,k=new Map,l=new Map,$=0,C=0,E=0,{createPackageHandle:I,deserializePackageArg:R,deserializePackageArgs:U,serializePackageValue:_}=S({handles:u,createHandleId:e=>`${e}:pkg_${++$}`,callIsolateCallback:j});async function B(e){let t=e.fileUrl||e.name;if(w.has(t))return w.get(t);let a=e.name&&e.name.startsWith("node:")?e.name:e.fileUrl||e.name;if(!a)throw new Error(`Package "${e.name}" cannot be imported by package runtime`);let i=await import(a);return w.set(t,i),i}function y(e,t){if(!t||t.length===0)return{target:e&&e.default!==void 0?e.default:e,receiver:void 0};let a=e,i;for(let c=0;c<t.length;c++){let o=t[c];if(a==null&&c===0&&e.default!==void 0&&(a=e.default),a!=null&&o in a){i=a,a=a[o];continue}if(c===0&&e.default!==void 0&&e.default!==a&&o in e.default){i=e.default,a=e.default[o];continue}throw new Error(`Package export not found: ${t.join(".")}`)}return{target:a,receiver:i}}function j(e,t,a){return new Promise((i,c)=>{let o=`cb_${++C}`;k.set(o,{resolve:i,reject:c,taskId:e});try{process.send?.({type:"pkgCallbackCall",id:o,taskId:e,callbackId:t,argsJson:JSON.stringify(a.map(s=>_(e,s)))})}catch(s){k.delete(o),c(s)}})}async function x(e){let t=U(e.taskId,e.argsJson);if(e.op==="handleCall"){let o=u.get(e.handleId);if(!o)throw new Error(`Package handle not found: ${e.handleId}`);let{target:s,receiver:f}=y(o,e.path||[]);if(typeof s!="function")return _(e.taskId,s);let r=await s.apply(f||o,t);return _(e.taskId,r)}if(e.op==="handleGet"){let o=u.get(e.handleId);if(!o)throw new Error(`Package handle not found: ${e.handleId}`);let{target:s,receiver:f}=y(o,e.path||[]);return _(e.taskId,typeof s=="function"&&f?s.bind(f):s)}let a=await B(e.package),{target:i,receiver:c}=y(a,e.path||[]);if(e.op==="construct"){if(typeof i!="function")throw new Error(`Package export is not constructable: ${e.packageName}.${(e.path||[]).join(".")}`);return I(e.taskId,new i(...t))}return typeof i=="function"?_(e.taskId,await i.apply(c,t)):_(e.taskId,i)}function O(e,t,a){return new Promise((i,c)=>{let o=`stream_${++E}`;l.set(o,{resolve:i,reject:c});try{process.send?.({type:"pkgStreamChunk",id:e,ackId:o,taskId:t,chunk:Buffer.from(a).toString("base64")},s=>{s&&(l.delete(o),c(s))})}catch(s){l.delete(o),c(s)}})}async function H(e){let t=u.get(e.handleId);if(!t)throw new Error(`Package handle not found: ${e.handleId}`);let{target:a}=y(t,e.path||[]),i=a||t;if(!i||typeof i[Symbol.asyncIterator]!="function"&&typeof i.on!="function")throw new Error(`Package handle is not a readable stream: ${e.handleId}`);for await(let c of i)await O(e.id,e.taskId,c)}function M(e){for(let t of u.keys())t.startsWith(`${e}:`)&&u.delete(t)}process.on("message",async e=>{if(e){if(e.type==="pkgStreamAck"||e.type==="pkgStreamError"){let t=l.get(e.ackId);if(!t)return;l.delete(e.ackId),e.type==="pkgStreamAck"?t.resolve(!0):t.reject(new Error(e.error?.message||"Package stream failed"));return}if(e.type==="pkgCallbackResult"||e.type==="pkgCallbackError"){let t=k.get(e.id);if(!t)return;k.delete(e.id),e.type==="pkgCallbackResult"?t.resolve(R(t.taskId,e.value)):t.reject(new Error(e.error?.message||"Package callback failed"));return}if(e.op)try{if(e.op==="releaseTask"){M(e.taskId),e.fire||process.send?.({id:e.id,ok:!0,value:!0});return}let t=e.op==="streamHandle"?await H(e):await x(e);process.send?.({id:e.id,ok:!0,value:t})}catch(t){let a=[e.op?`op=${e.op}`:null,e.packageName?`package=${e.packageName}`:null,e.handleId?`handle=${e.handleId}`:null,Array.isArray(e.path)?`path=${e.path.join(".")||"<root>"}`:null].filter(Boolean).join(" ");process.send?.({id:e.id,ok:!1,error:{message:a?`${t.message} (${a})`:t.message,stack:t.stack}})}}});
|
package/dist/execution/worker.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var F=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var
|
|
1
|
+
"use strict";var F=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var L=F((je,U)=>{"use strict";var{fork:oe}=require("child_process"),ie=require("path");function ce({workerDir:e,activeTaskContexts:t}){let s=new Map,r=new Map,n=new Map,a=null,l=0;function _(i){for(let c of r.values())c.reject(i);r.clear()}function d(i){let c=typeof i=="string"?JSON.parse(i):i;if(c?.error)throw new Error(c.error);return c?.value}async function v(i){let c=t.get(i.taskId);if(!c)throw new Error(`Package callback context not found: ${i.taskId}`);let o=JSON.stringify(i.callbackId),f=JSON.stringify(i.argsJson||"[]"),p=await c.evalClosure(`return __invokeRuntimeCallback(${o}, ${f});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}});return d(p)}function g(){if(a&&a.connected)return a;let i=ie.join(e,"package-runtime.child.js"),c=oe(i,[],{stdio:["ignore","ignore","ignore","ipc"]});return a=c,c.on("message",o=>{if(!o||!o.id)return;if(o.type==="pkgStreamChunk"){let p=n.get(o.id);if(!p)return;p.onChunk(Buffer.from(o.chunk||"","base64")).then(()=>{try{c.send({type:"pkgStreamAck",ackId:o.ackId})}catch{}}).catch(k=>{try{c.send({type:"pkgStreamError",ackId:o.ackId,error:{message:k.message,stack:k.stack}})}catch{}});return}if(o.type==="pkgCallbackCall"){v(o).then(p=>{try{c.send({type:"pkgCallbackResult",id:o.id,value:p})}catch{}}).catch(p=>{try{c.send({type:"pkgCallbackError",id:o.id,error:{message:p.message,stack:p.stack}})}catch{}});return}let f=r.get(o.id);if(f)if(r.delete(o.id),n.delete(o.id),o.ok)f.resolve(o.value);else{let p=new Error(o.error?.message||"Package runtime call failed");p.stack=o.error?.stack||p.stack,f.reject(p)}}),c.on("exit",(o,f)=>{a===c&&(a=null),_(new Error(`Package runtime exited${f?` with signal ${f}`:` with code ${o}`}`))}),c.on("error",o=>{a===c&&(a=null),_(o)}),c}function y(i){return new Promise((c,o)=>{let f=g(),p=`pkg_${++l}`;r.set(p,{resolve:c,reject:o});try{f.send({...i,id:p},k=>{k&&(r.delete(p),o(k))})}catch(k){r.delete(p),o(k)}})}function u(i,c,o,f=[]){return new Promise((p,k)=>{let x=g(),P=`pkg_${++l}`;r.set(P,{resolve:p,reject:k}),n.set(P,{onChunk:o});try{x.send({op:"streamHandle",taskId:i,handleId:c,path:f,id:P},b=>{b&&(r.delete(P),n.delete(P),k(b))})}catch(b){r.delete(P),n.delete(P),k(b)}})}function h(i){try{if(!a||!a.connected)return;a.send({...i,id:`pkg_${++l}`,fire:!0})}catch{}}async function w(i,c){let o=s.get(i);if(!o)throw new Error("Package context is not available");if(c.handleId)return y({op:c.kind==="get"?"handleGet":"handleCall",taskId:i,handleId:c.handleId,path:c.path||[],argsJson:c.argsJson||"[]"});let f=o.get(c.packageName);if(!f)throw new Error(`Package "${c.packageName}" is not available`);return y({op:c.kind==="construct"?"construct":"call",taskId:i,packageName:c.packageName,package:{name:f.name,fileUrl:f.fileUrl},path:c.path||[],argsJson:c.argsJson||"[]"})}function m(i,c){s.set(i,c)}function A(i){s.delete(i),h({op:"releaseTask",taskId:i})}function T(){if(a){try{a.kill()}catch{}a=null}}return{cleanupTaskPackages:A,executePackageRuntimeCall:w,setTaskPackages:m,streamPackageHandle:u,shutdownPackageRuntime:T}}U.exports={createPackageRuntimeBridge:ce}});var D=F((Te,K)=>{"use strict";var le=`
|
|
2
2
|
"use strict";
|
|
3
3
|
let $ctx = {};
|
|
4
4
|
let $pkgs = {};
|
|
@@ -658,6 +658,10 @@ function __resetTask(snapshot, taskId) {
|
|
|
658
658
|
get: (_, method) => async (...args) =>
|
|
659
659
|
__call('cacheCall', JSON.stringify({ method: String(method), argsJson: JSON.stringify(args) }))
|
|
660
660
|
});
|
|
661
|
+
$ctx.$res = new Proxy({}, {
|
|
662
|
+
get: (_, method) => async (...args) =>
|
|
663
|
+
__call('resCall', JSON.stringify({ method: String(method), argsJson: await __stringifyRuntimeArgs(args) }))
|
|
664
|
+
});
|
|
661
665
|
$ctx.$trigger = async (...args) =>
|
|
662
666
|
__call('dispatchCall', JSON.stringify({ method: 'trigger', argsJson: JSON.stringify(args) }));
|
|
663
667
|
$ctx.$throw = new Proxy({}, {
|
|
@@ -701,48 +705,48 @@ function __cleanupTask() {
|
|
|
701
705
|
__runtimeCallbacks = new Map();
|
|
702
706
|
return true;
|
|
703
707
|
}
|
|
704
|
-
`;function
|
|
705
|
-
`),
|
|
706
|
-
`);for(let
|
|
707
|
-
`)}function
|
|
708
|
+
`;function ue(e){return le.replace("%%PKG_SETUP%%",e)}K.exports={buildSetupCode:ue}});var{parentPort:j}=require("worker_threads"),q=require("fs"),{fileURLToPath:fe}=require("url"),{createPackageRuntimeBridge:pe}=L(),{buildSetupCode:_e}=D(),M;try{M=require("isolated-vm")}catch(e){j.postMessage({type:"error",message:"isolated-vm not available: "+e.message}),process.exit(1)}var O=new Map,G=0,E=new Map,J=pe({workerDir:__dirname,activeTaskContexts:E}),de=500,ge=5e3,he=32,B=new WeakMap,X=new WeakMap,Z=new WeakMap,N={created:0,reused:0,released:0,evicted:0,scrubFailed:0},S=null,ye=0,V=0,W=0;async function me(){let e=Date.now();if(e-V<ge)return W;if(V=e,!S)return 0;let t=0;for(let s of S){let r=s?.isolate;if(!(!r||r.isDisposed))try{let n=await r.getHeapStatistics(),a=n.heap_size_limit||1,l=n.used_heap_size/a;l>t&&(t=l)}catch{}}return W=t,t}async function R(e){e.heapRatio=await me(),e.contextStats=ke(),j.postMessage(e)}function ke(){let e=0;if(S)for(let t of S)e+=t?.idleContexts?.length||0;return{...N,idle:e}}function Q(e,t){if(!S){let n=Math.max(1,Math.trunc(Number(t)||8));S=new Array(n).fill(null)}let s=ye++%S.length,r=S[s];return(!r||!r.isolate||r.isolate.isDisposed)&&(r={isolate:new M.Isolate({memoryLimit:e}),idleContexts:[]},S[s]=r),r}async function C(e,t,s){let r=B.get(e);r||(r=new Map,B.set(e,r));let n=r.get(t);if(n)return n;let a=await e.compileScript(t,{filename:s});if(r.set(t,a),r.size>de){let l=r.keys().next().value;r.delete(l)}return a}j.on("message",async e=>{if(e.type==="execute")Je(e).catch(async t=>{await R({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="executeBatch")Oe(e).catch(async t=>{await R({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="callResult"){let t=O.get(e.callId);t&&(O.delete(e.callId),t.resolve(e.result))}else if(e.type==="callError"){let t=O.get(e.callId);t&&(O.delete(e.callId),t.reject(new Error(e.error)))}});function $(e,t,s){return new Promise((r,n)=>{let a=`cb_${++G}`;O.set(a,{resolve:r,reject:n}),j.postMessage({type:t,id:e,callId:a,...s})})}function ve(e,t,s){j.postMessage({type:t,id:e,callId:`f_${++G}`,...s})}async function we(e,t){if(t?.method!=="stream")return $(e,"resCall",t);let s=JSON.parse(t.argsJson||"[]"),r=s[0],n=s[1]||{},a=r?.__pkgHandleArg;if(!a)return $(e,"resCall",t);await $(e,"resCall",{method:"streamStart",argsJson:JSON.stringify([null,n])});try{await J.streamPackageHandle(e,a,l=>$(e,"resCall",{method:"streamChunk",chunk:Buffer.from(l).toString("base64")})),await $(e,"resCall",{method:"streamEnd"})}catch(l){try{await $(e,"resCall",{method:"streamError",error:{message:l.message,stack:l.stack}})}catch{}throw l}return JSON.stringify({__e:"u"})}function Pe(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=fe(e.fileUrl)),!t||!q.existsSync(t)?null:q.readFileSync(t,"utf8")}async function xe(e,t,s){try{let r=Pe(s);if(!r)return null;let n=await e.compileModule(r,{filename:`pkg:${s.safeName}`});await n.instantiate(t,l=>{throw new Error(`Unresolved import in package ${s.safeName}: ${l}`)}),await n.evaluate({timeout:1e4});let a=await n.namespace.get("default");return a!==void 0&&a.typeof!=="undefined"?a.derefInto({release:!1}):n.namespace.derefInto({release:!1})}catch{return null}}function Y(e,t){let s=n=>{let a=2166136261;for(let l=0;l<n.length;l++)a^=n.charCodeAt(l),a=Math.imul(a,16777619);return(a>>>0).toString(36)},r=new Set(t||[]);return e.map(n=>{let a=n.cacheKey||`${n.filePath||""}:${n.fileUrl||""}:${n.mtimeMs||""}:${n.size||""}:${s(n.sourceCode||"")}`,l=r.has(n.name)?"isolate":"proxy";return`${n.name}:${n.version||""}:${a}:${l}`}).join("|")}function ee(e,t){let s=new Set(t.map(d=>d.name)),r=new Set,n=String(e||""),a=/\b(?:\$ctx\.)?\$pkgs\s*\[\s*(['"`])([^'"`]+)\1\s*\]/g,l=/\brequire\s*\(\s*(['"`])([^'"`]+)\1\s*\)/g,_=/\b(?:\$ctx\.)?\$pkgs\.([A-Za-z_$][\w$]*)/g;for(let d of[a,l])for(let v of n.matchAll(d)){let g=v[2];s.has(g)&&r.add(g)}for(let d of n.matchAll(_)){let v=d[1];s.has(v)&&r.add(v)}return r}async function Se(e,t,s,r){let n=await e.createContext(),a=n.global;await a.set("global",a.derefInto());let l=[],_=[],d=new Map;for(let u of s){d.set(u.name,u);let h=r.has(u.name)?await xe(e,n,u):null;h!==null?(await a.set(`__pkg_${u.safeName}`,h),l.push(u)):_.push(u)}J.setTaskPackages(t,d),await a.set("__callRef",new M.Reference(async(u,h,w)=>{let m=JSON.parse(w);return h==="pkgCall"?JSON.stringify(await J.executePackageRuntimeCall(u,m)):h==="resCall"?we(u,m):$(u,h,m)})),await a.set("__fireRef",new M.Reference((u,h,w)=>{let m=JSON.parse(w);ve(u,h,m)}));let v=l.map(u=>`$pkgs[${JSON.stringify(u.name)}] = __pkg_${u.safeName};`).concat(_.map(u=>`$pkgs[${JSON.stringify(u.name)}] = __createPkgProxy(${JSON.stringify(u.name)}, []);`)).join(`
|
|
709
|
+
`),g=_e(v);return await(await C(e,g,"setup.js")).run(n,{timeout:5e3}),X.set(n,Y(s,r)),Z.set(n,d),n}async function te(e,t,s,r,n){let a=e.isolate,l=Y(s,n),_=null;for(let g=e.idleContexts.length-1;g>=0;g--){let y=e.idleContexts[g];if(e.idleContexts.splice(g,1),X.get(y)===l){_=y,N.reused++;break}try{y.release()}catch{}}_||(_=await Se(a,t,s,n),N.created++),J.setTaskPackages(t,Z.get(_)||new Map);let d=_.global;return await d.set("__snapshot",new M.ExternalCopy(r).copyInto()),await d.set("__nextTaskId",t),await(await C(a,"__resetTask(__snapshot, __nextTaskId);","reset-task.js")).run(_,{timeout:5e3}),_}async function re(e,t){if(!(!t||e.isolate.isDisposed)){try{await(await C(e.isolate,"__cleanupTask();","cleanup-task.js")).run(t,{timeout:5e3})}catch{N.scrubFailed++;try{t.release()}catch{}return}if(e.idleContexts.length>=he){try{t.release()}catch{}N.evicted++;return}e.idleContexts.push(t),N.released++}}function Ce(e){try{let t=JSON.parse(e.message);if(t&&t.__userThrow)return{...t,message:t.message??e.message}}catch{}return null}var be=3,$e=["setup.js","extract.js","extract-error-ctx.js","set-status.js","populate-error.js"];function Re(e){if(!e)return null;let t=e.split(`
|
|
710
|
+
`);for(let s of t){let r=s.match(/at\s+(.+\.js):(\d+):(\d+)/);if(!r)continue;let n=r[1].trim();if($e.includes(n))continue;let l=parseInt(r[2])-be;if(!(l<=0))return{line:l,column:parseInt(r[3]),phase:n.replace(".js","")}}return null}function Ae(e,t,s){if(!e||!t)return;let r=String(e).split(/\r?\n/),n=Math.max(1,t-1),a=Math.min(r.length,t+1),l=String(a).length,_=[];for(let d=n;d<=a;d++){let v=d===t?">":" ";_.push(`${v} ${String(d).padStart(l," ")}. ${r[d-1]??""}`),d===t&&s&&s>0&&_.push(` ${" ".repeat(l)} ${" ".repeat(Math.max(0,s-1))}^`)}return _.join(`
|
|
711
|
+
`)}function Ne(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 I(e,t){let s=Ce(e);if(s)return{message:s.message,statusCode:s.statusCode,details:s.details};let r=Re(e.stack),n=e.message||"Unknown error",a=r?`${n} (${r.phase}, line ${r.line})`:n,l=Ne(r,t),_=r?Ae(l,r.line,r.column):void 0;return{message:a,statusCode:e.statusCode||null,details:r?{...r,codeFrame:_}:void 0}}async function ne(e,t){let s=I(t);await R({type:"result",id:e,success:!1,error:{...s,stack:t.stack,code:t.code}})}async function Je(e){let{id:t,code:s,pkgSources:r,snapshot:n,memoryLimitMb:a,isolatePoolSize:l}=e,_=r||[],d=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),v=ee(s,_),g=Q(a,l),y=g.isolate,u=await te(g,t,_,n,v);E.set(t,u);try{let h=`
|
|
708
712
|
(async () => {
|
|
709
713
|
"use strict";
|
|
710
|
-
${
|
|
714
|
+
${s}
|
|
711
715
|
})().then((__result) => __extractResult(__result, __result === undefined));
|
|
712
|
-
`,
|
|
713
|
-
`),_),
|
|
716
|
+
`,m=await(await C(y,h,"handler.js")).run(u,{timeout:d,promise:!0}),A=JSON.parse(m);await R({type:"result",id:t,success:!0,...A})}catch(h){await ne(t,h)}finally{E.delete(t),await re(g,u),ae(t)}}async function Oe(e){let{id:t,codeBlocks:s,pkgSources:r,snapshot:n,memoryLimitMb:a,isolatePoolSize:l}=e,_=r||[],d=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),v=ee((s||[]).map(i=>i.code||"").join(`
|
|
717
|
+
`),_),g=Q(a,l),y=g.isolate,u=await te(g,t,_,n,v);E.set(t,u);let h=[],w=[],m={},A=0,T=0;for(let i of s){let c=i.type||"handler";c==="postHook"?(T++,m[`postHook #${T}`]=i.code||"",m.postHook=i.code||"",w.push(i)):(c==="handler"?m.handler=i.code||"":(A++,m[`${c} #${A}`]=i.code||"",m.preHook=i.code||""),h.push(i))}try{let i=null;for(let o=0;o<h.length;o++){let f=h[o],p=f.type||"handler",k=p==="handler"?"handler":`${p} #${o+1}`,x;p==="preHook"?x=`
|
|
714
718
|
(async () => {
|
|
715
719
|
"use strict";
|
|
716
|
-
${
|
|
720
|
+
${f.code}
|
|
717
721
|
})().then((__r) => {
|
|
718
722
|
if (__r !== undefined) return JSON.stringify({ __shortCircuit: true, value: __r });
|
|
719
723
|
return JSON.stringify({ __shortCircuit: false });
|
|
720
|
-
});`:
|
|
724
|
+
});`:x=`
|
|
721
725
|
(async () => {
|
|
722
726
|
"use strict";
|
|
723
|
-
${
|
|
727
|
+
${f.code}
|
|
724
728
|
})().then((__r) => {
|
|
725
729
|
$ctx.$data = __r;
|
|
726
730
|
return "__handler_done__";
|
|
727
|
-
});`;try{let
|
|
728
|
-
$ctx.$error = ${JSON.stringify(
|
|
731
|
+
});`;try{let b=await(await C(y,x,`${k}.js`)).run(u,{timeout:d,promise:!0});if(p==="preHook"&&typeof b=="string"){let H=JSON.parse(b);if(H.__shortCircuit){let se=await z(y,u,H.value);await R({type:"result",id:t,success:!0,...se,shortCircuit:!0});return}}}catch(P){i=P;break}}if(!i&&w.length>0&&await(await C(y,'$ctx.$statusCode = 200; "__status_set__";',"set-status.js")).run(u,{timeout:5e3}),i&&w.length>0){let o=I(i,m),f={message:o.message||"Unknown error",name:i.constructor?.name||"Error",stack:i.stack||"",statusCode:o.statusCode||500,details:o.details||{},timestamp:new Date().toISOString()},p=`
|
|
732
|
+
$ctx.$error = ${JSON.stringify(f)};
|
|
729
733
|
$ctx.$data = null;
|
|
730
|
-
$ctx.$statusCode = ${
|
|
734
|
+
$ctx.$statusCode = ${f.statusCode};
|
|
731
735
|
if ($ctx.$api) {
|
|
732
|
-
$ctx.$api.error = ${JSON.stringify(
|
|
736
|
+
$ctx.$api.error = ${JSON.stringify(f)};
|
|
733
737
|
$ctx.$api.response = {
|
|
734
|
-
statusCode: ${
|
|
738
|
+
statusCode: ${f.statusCode},
|
|
735
739
|
responseTime: $ctx.$api.request && $ctx.$api.request.timestamp
|
|
736
740
|
? Date.now() - new Date($ctx.$api.request.timestamp).getTime()
|
|
737
741
|
: 0,
|
|
738
|
-
timestamp: ${JSON.stringify(
|
|
742
|
+
timestamp: ${JSON.stringify(f.timestamp)},
|
|
739
743
|
};
|
|
740
744
|
}
|
|
741
|
-
"__error_populated__";`;await(await
|
|
745
|
+
"__error_populated__";`;await(await y.compileScript(p,{filename:"populate-error.js"})).run(u,{timeout:5e3})}for(let o=0;o<w.length;o++){let f=w[o],p=`postHook #${o+1}`,k=`
|
|
742
746
|
(async () => {
|
|
743
747
|
"use strict";
|
|
744
|
-
${
|
|
748
|
+
${f.code}
|
|
745
749
|
})().then((__r) => {
|
|
746
750
|
if (__r !== undefined) $ctx.$data = __r;
|
|
747
751
|
return "__posthook_done__";
|
|
748
|
-
});`;try{await(await
|
|
752
|
+
});`;try{await(await C(y,k,`${p}.js`)).run(u,{timeout:d,promise:!0})}catch{}}if(i){let o=I(i,m),f;try{let x=await(await C(y,"(async () => JSON.stringify(await __extractCtxChanges()))()","extract-error-ctx.js")).run(u,{timeout:5e3,promise:!0});f=JSON.parse(x)}catch{}await R({type:"result",id:t,success:!1,error:{message:o.message,statusCode:o.statusCode,stack:i.stack,code:i.code,details:o.details},ctxChanges:f});return}let c=await z(y,u);await R({type:"result",id:t,success:!0,...c})}catch(i){await ne(t,i)}finally{E.delete(t),await re(g,u),ae(t)}}function ae(e){J.cleanupTaskPackages(e)}function Me(){J.shutdownPackageRuntime()}process.on("exit",Me);async function z(e,t,s){if(s!==void 0){let l=`__extractResult(${JSON.stringify(s)}, false)`,d=await(await e.compileScript(l,{filename:"extract.js"})).run(t,{timeout:5e3,promise:!0});return JSON.parse(d)}let a=await(await C(e,"__extractResult($ctx.$data, $ctx.$data === undefined)","extract.js")).run(t,{timeout:5e3,promise:!0});return JSON.parse(a)}
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var Xr=Object.create;var Bt=Object.defineProperty;var Zr=Object.getOwnPropertyDescriptor;var ei=Object.getOwnPropertyNames;var ti=Object.getPrototypeOf,ni=Object.prototype.hasOwnProperty;var K=(r,e)=>()=>(r&&(e=r(r=0)),e);var Tn=(r,e)=>{for(var t in e)Bt(r,t,{get:e[t],enumerable:!0})},nr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ei(e))!ni.call(r,i)&&i!==t&&Bt(r,i,{get:()=>e[i],enumerable:!(n=Zr(e,i))||n.enumerable});return r};var ce=(r,e,t)=>(t=r!=null?Xr(ti(r)):{},nr(e||!r||!r.__esModule?Bt(t,"default",{value:r,enumerable:!0}):t,r)),ri=r=>nr(Bt({},"__esModule",{value:!0}),r);function fr(r){return Fn.createHash("md5").update(r).digest("hex").substring(0,8)}function dr(r){return r.length<=ur-3?`${r}_pk`:`j_${fr(r)}_pk`}function pr(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=ur?n:`j_${fr(r)}_${t}_fk`}function Ft(r,e,t){let n=`${r}:${e}:${t}`;return`j_${Fn.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function V(r){return`${r}Id`}function Ct(r,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function gr(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function hr(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function yr(r,e,t){return`${r}_${e}_${t}_fk`}function mr(r,e,t){return`${r}_${e}_${t}_idx`}var Fn,ur,Ve=K(()=>{"use strict";Fn=ce(require("crypto")),ur=63});function en(r){return Pi[r]??null}var ee,vn,Rt,Pi,xt=K(()=>{"use strict";ee=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),vn=new Set(["_and","_or","_not"]),Rt=[...Array.from(vn),...Array.from(ee)],Pi={_eq:"eq",_neq:"neq",_gt:"gt",_gte:"gte",_lt:"lt",_lte:"lte",_in:"in",_not_in:"not_in",_nin:"not_in",_contains:"contains",_starts_with:"starts_with",_ends_with:"ends_with",_between:"between"}});var x,ue=K(()=>{"use strict";x=class extends Error{constructor(t="Bad Request",n){let i=Array.isArray(t),o=i?t.join("; ")||"Bad Request":typeof t=="string"?t:JSON.stringify(t);super(o);this.statusCode=400;this.errorCode="BAD_REQUEST";this.name="BadRequestException",this.details=n,i&&(this.messages=t)}}});function Tr(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var Sr=K(()=>{"use strict"});function Be(r,e,t){throw new x({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${Rt.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:Rt})}function tn(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=Tr();for(let i of Object.keys(e))if(i.startsWith("_")&&!ee.has(i)){if(n&&i==="_id")continue;Be(i,r,t)}}function U(r,e,t){if(!r||typeof r!="object")return;let n=t?.tables?.get(e),i=new Set((n?.columns??[]).map(s=>s.name)),o=new Map((n?.relations??[]).map(s=>[s.propertyName,s]));for(let[s,a]of Object.entries(r)){if(ji.has(s)){if(Array.isArray(a))for(let l of a)U(l,e,t);else a&&typeof a=="object"&&U(a,e,t);continue}let u=o.get(s);if(u){if(a&&typeof a=="object"&&!Array.isArray(a)){tn(s,a,e);let l=u.targetTableName||u.targetTable;if(l){let f=Object.keys(a).filter(c=>!c.startsWith("_"));if(f.length>0){let c={};for(let p of f)c[p]=a[p];U(c,l,t)}}}continue}s.startsWith("_")&&!i.has(s)&&s!=="_id"&&Be(s,s,e),a&&typeof a=="object"&&!Array.isArray(a)&&tn(s,a,e)}}var ji,Ye=K(()=>{"use strict";ue();xt();Sr();ji=new Set(["_and","_or","_not"])});function Te(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:nn(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function nn(r,e){if(!r||typeof r!="object")return{node:null,hasRelationFilters:!1};let t=[],n=!1;for(let[i,o]of Object.entries(r)){let s=Li(i,o,e);s.hasRelationFilters&&(n=!0),s.node&&t.push(s.node)}return t.length===0?{node:null,hasRelationFilters:n}:t.length===1?{node:t[0],hasRelationFilters:n}:{node:{kind:"and",children:t},hasRelationFilters:n}}function Li(r,e,t){if(r==="_and")return $r("and",e,t);if(r==="_or")return $r("or",e,t);if(r==="_not"){let l=nn(e,t);return l.node?{node:{kind:"not",child:l.node},hasRelationFilters:l.hasRelationFilters}:{node:null,hasRelationFilters:l.hasRelationFilters}}let n=t.metadata?.tables?.get(t.currentTable),i=n?.columns?.some(l=>l.name==="_id"&&l.isPrimary),o=n?.columns?.some(l=>l.name==="id"),a=r==="id"?i&&!o?"_id":"id":r,u=n?.relations?.find(l=>l.propertyName===a);return u?Bi(a,e,u,t):n&&!n.columns?.find(f=>f.name===a)?(r.startsWith("_")&&r!=="_id"&&Be(r,r,t.currentTable),console.warn(`[filter-parser] Unknown field "${r}" on table "${t.currentTable}" \u2014 skipped (not a column or relation in metadata).`),{node:null,hasRelationFilters:!1}):Di(a,e,t)}function $r(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],i=!1;for(let o of e){let s=nn(o,t);s.hasRelationFilters&&(i=!0),s.node&&n.push(s.node)}return n.length===0?{node:null,hasRelationFilters:i}:n.length===1?{node:n[0],hasRelationFilters:i}:{node:{kind:r,children:n},hasRelationFilters:i}}function Bi(r,e,t,n){if(typeof e!="object"||e===null)return{node:null,hasRelationFilters:!0};let i=Object.keys(e),o=i.length===1&&(i[0]==="_is_null"||i[0]==="_is_not_null"||i[0]==="_eq"||i[0]==="_neq"||i[0]==="_in"||i[0]==="_not_in"||i[0]==="_nin"),s=n.registry.registerWithParent(n.currentTable,r,n.metadata,"left",n.currentJoinId,"filter");if(o&&i[0]==="_is_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_null===!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(o&&i[0]==="_is_not_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_not_null!==!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(o&&(i[0]==="_eq"||i[0]==="_neq")&&e[i[0]]===null)return s?{node:{kind:"relation_exists",joinId:s,negate:i[0]==="_eq"},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(!s)return{node:null,hasRelationFilters:!0};let a=t.targetTableName||t.targetTable,u={...n,parentJoinId:n.currentJoinId,currentJoinId:s,currentTable:a},l=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]),c=i.length>0&&i.every(d=>l.has(d))?{id:e}:e;return{node:nn(c,u).node,hasRelationFilters:!0}}function Di(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:Wi(r,t)};if(e===null)return{node:{kind:"compare",field:n,op:"is_null",value:!0},hasRelationFilters:!1};if(typeof e!="object")return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};for(let s of Object.keys(e))s.startsWith("_")&&!ee.has(s)&&Be(s,r,t.tableName);let i=Object.entries(e).filter(([s])=>ee.has(s));if(i.length===0)return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};let o=[];for(let[s,a]of i){let u=Ki(n,s,a);u&&o.push(u)}return o.length===0?{node:null,hasRelationFilters:!1}:o.length===1?{node:o[0],hasRelationFilters:!1}:{node:{kind:"and",children:o},hasRelationFilters:!1}}function Ki(r,e,t){if(e==="_is_null")return{kind:"compare",field:r,op:"is_null",value:t===!0};if(e==="_is_not_null")return{kind:"compare",field:r,op:"is_null",value:t!==!0};let n=en(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function Wi(r,e){let t=e.metadata?.tables?.get(e.currentTable);if(!t)return!1;let n=r.includes(".")?r.split(".").pop():r,i=t.columns?.find(s=>s.name===n);if(!i)return!1;let o=(i.type||"").toLowerCase();return o==="uuid"||o==="uuidv4"||o.includes("uuid")}var vt=K(()=>{"use strict";xt();Ye()});var oe,It=K(()=>{"use strict";oe=class{constructor(){this.map=new Map}size(){return this.map.size}has(e){return this.map.has(e)}get(e){return this.map.get(e)}getAll(){return Array.from(this.map.values())}registerWithParent(e,t,n,i="left",o=null,s="data"){let a=o?`${o}.${t}`:t;if(this.map.has(a)){let p=this.map.get(a);return i==="inner"&&(p.joinType="inner"),p.purposes.includes(s)||p.purposes.push(s),a}let u=n?.tables?.get(e);if(!u)return null;let l=u.relations?.find(p=>p.propertyName===t);if(!l)return null;let f=l.targetTableName||l.targetTable;if(!f)return null;let c={id:a,propertyName:t,parentTable:e,targetTable:f,relationType:l.type,parentJoinId:o,joinType:i,relationMeta:l,purposes:[s]};return this.map.set(a,c),a}}});async function Y(r,e){if(r.length<=Se)return e(r);let t=[];for(let a=0;a<r.length;a+=Se)t.push(r.slice(a,a+Se));let n=[],i=0;async function o(){for(;i<t.length;){let a=i++;n[a]=await e(t[a])}}let s=Math.min(jn,t.length);return await Promise.all(Array.from({length:s},o)),n.flat()}function Ze(r){let e=[],t=new Map;for(let n of r)if(n==="*"||!n.includes("."))e.push(n);else{let i=n.split("."),o=i[0],s=i.slice(1).join(".");t.has(o)||t.set(o,[]),t.get(o).push(s)}return{rootFields:e,subRelations:t}}var te,Se,jn,Ln,$e,et=K(()=>{"use strict";ue();te=16,Se=5e3,jn=4,Ln=10;$e=class{constructor(e,t,n){this.adapter=e;this.metadataGetter=t;this.trace=n}enrichNestedDescs(e,t){return!t||Object.keys(t).length===0?e:e.map(n=>{let i=t[n.relationName];if(!i)return n;let o=i.fields!=null?Array.isArray(i.fields)?i.fields:String(i.fields).split(",").map(s=>s.trim()).filter(Boolean):n.fields;return{...n,fields:o,userFilter:i.filter??n.userFilter,userSort:i.sort??n.userSort,userLimit:i.limit!==void 0?Number(i.limit):n.userLimit,userPage:i.page!==void 0?Number(i.page):n.userPage,nestedDeep:i.deep??n.nestedDeep}})}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:Ln}:e}assertLocalSortFields(e,t){if(!e.userSort)return;let n=Array.isArray(e.userSort)?e.userSort:String(e.userSort).split(",").map(i=>i.trim()).filter(Boolean);for(let i of n){let o=i.startsWith("-")?i.slice(1):i;if(o.includes("."))throw new x(`Sort field '${o}' is not supported on deep relation '${e.relationName}'. Sort only by local fields defined on '${e.targetTable}'.`);let s=t.columns?.some(u=>u.name===o),a=o==="id"&&t.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new x(`Sort field '${o}' does not exist on '${e.targetTable}'. Sort only by fields defined on the table metadata.`)}}async execute(e,t,n=3,i=0,o){if(e.length===0||t.length===0||i>=n)return;let s;o&&(s=await this.metadataGetter(o)??void 0),await Promise.all(t.map(a=>{let u=this.withDefaultToManyLimit(a);return u.type==="many-to-one"||u.type==="one-to-one"&&!u.isInverse?this.fetchOwnerRelation(e,u,n,i):u.type==="one-to-many"||u.type==="one-to-one"&&u.isInverse?this.fetchInverseRelation(e,u,n,i,s):u.type==="many-to-many"?this.fetchM2MRelation(e,u,n,i,s):Promise.resolve()}))}async fetchOwnerRelation(e,t,n,i){let o=this.adapter.resolveOwnerFkKey(t),s=new Set,a=[];for(let m of e){let b=m[o];if(b==null)continue;let $=this.adapter.keyOf(b);s.has($)||(s.add($),a.push(b))}if(a.length===0){for(let m of e)m[t.relationName]=null,o!==t.relationName&&delete m[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete m[t.fkColumn];return}let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{isPkOnly:l,nestedDescs:f,fetchSpec:c}=this.adapter.resolveFields(t.fields,u),p=this.adapter.getTargetPkField(u);if(l){for(let m of e){let b=m[o];m[t.relationName]=b!=null?this.adapter.buildScalarRef(b,p):null,o!==t.relationName&&delete m[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete m[t.fkColumn]}return}let d=performance.now(),g=await this.adapter.fetchOwner(t.targetTable,a,c,t);this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,d,{relationType:t.type,targetTable:t.targetTable,strategy:"batch-in",roundtrips:Math.ceil(a.length/Se)||1,rowsTransferred:g.length,rowsReturned:g.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let y=this.enrichNestedDescs(f,t.nestedDeep);y.length>0&&await this.execute(g,y,n,i+1,t.targetTable);let h=new Map;for(let m of g)h.set(this.adapter.keyOf(m[p]),m);for(let m of e){let b=m[o];m[t.relationName]=b!=null&&h.get(this.adapter.keyOf(b))||null,o!==t.relationName&&delete m[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete m[t.fkColumn]}}async fetchInverseRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=e.map(_=>_[s]).filter(_=>_!=null);if(a.length===0)return;let u=this.adapter.resolveInverseFkField(t),l=await this.metadataGetter(t.targetTable);if(!l)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,l);let{nestedDescs:f,fetchSpec:c}=this.adapter.resolveFields(t.fields,l),p=performance.now(),{docs:d,groupKeyField:g}=await this.adapter.fetchInverse(t.targetTable,u,a,c,t),y=new Map,h=t.fields.includes(u)||t.fields.includes("*");for(let _ of d){let N=_[g],I=this.adapter.keyOf(N);y.has(I)||y.set(I,[]),y.get(I).push(_)}let m=t.userLimit!==void 0&&t.userLimit>0,b=m?"per-parent-c16":"batch-in",$=m?a.length:Math.ceil(a.length/Se)||1,w=m?Math.ceil(a.length/te):void 0,T=Array.from(y.values()).reduce((_,N)=>_+N.length,0);if(this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:b,roundtrips:$,concurrencyWaves:w,rowsTransferred:d.length,rowsReturned:T,rowsDiscarded:d.length-T,userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let _ of d)this.adapter.postProcessInverseChild(_,u,h);let k=this.enrichNestedDescs(f,t.nestedDeep);k.length>0&&await this.execute(d,k,n,i+1,t.targetTable);let v=t.type==="one-to-one";for(let _ of e){let N=this.adapter.keyOf(_[s]),I=y.get(N)||[];_[t.relationName]=v?I[0]||null:I}}async fetchM2MRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=e.map(w=>w[s]).filter(w=>w!=null);if(a.length===0)return;let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{nestedDescs:l,fetchSpec:f}=this.adapter.resolveFields(t.fields,u),c=performance.now(),{grouped:p,docs:d}=await this.adapter.fetchM2M(e,t,o,u,f),g=t.userLimit!==void 0&&t.userLimit>0,y=g?"m2m-per-parent-c16":"m2m-batch",h=g?a.length:Math.ceil(a.length/Se)||1,m=g?Math.ceil(a.length/te):void 0,b=Array.from(p.values()).reduce((w,T)=>w+T.length,0);this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,c,{relationType:t.type,targetTable:t.targetTable,strategy:y,roundtrips:h,concurrencyWaves:m,rowsTransferred:d.length,rowsReturned:b,rowsDiscarded:d.length-b,userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort});let $=this.enrichNestedDescs(l,t.nestedDeep);$.length>0&&d.length>0&&await this.execute(d,$,n,i+1,t.targetTable);for(let w of e){let T=this.adapter.keyOf(w[s]);w[t.relationName]=p.get(T)||[]}}}});async function pe(r,e,t){let n=new Map,i=0;async function o(){for(;i<r.length;){let u=i++,l=r[u];n.set(String(l),await e(l))}}let s=Math.min(t,r.length);if(s===0)return n;let a=Array.from({length:s},o);return await Promise.all(a),n}var an=K(()=>{"use strict"});function C(r,e){switch(e){case"mysql":return`\`${r}\``;case"postgres":case"pg":case"sqlite":return`"${r}"`;case"mongodb":return r;default:return`\`${r}\``}}var Ce=K(()=>{"use strict"});function X(r,e,t){e&&hn(r,e,t,"and")}function hn(r,e,t,n){switch(e.kind){case"true":return;case"false":n==="or"?r.orWhereRaw("1 = 0"):r.whereRaw("1 = 0");return;case"and":{let i=function(){for(let o of e.children)this.where(function(){hn(this,o,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"or":{let i=function(){for(let o of e.children)this.orWhere(function(){hn(this,o,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"not":{let i=function(){this.whereNot(function(){hn(this,e.child,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"compare":go(r,e,t,n);return;case"relation_exists":console.warn(`[sql-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${e.joinId}) \u2014 expected to be handled by applyRelationFilters. Filter silently skipped.`);return}}function go(r,e,t,n){if(e.field.joinId!==null){console.warn(`[sql-render-filter] compare node has joinId=${e.field.joinId} (field=${e.field.fieldName}) but reached renderer \u2014 expected join path to handle it. Filter silently skipped.`);return}let i=ho(e.field,t),o=!!e.field.isUuid,s=t.dbType==="postgres",a=n==="or"?"orWhere":"where",u=n==="or"?"orWhereRaw":"whereRaw",l=n==="or"?"orWhereIn":"whereIn",f=n==="or"?"orWhereNotIn":"whereNotIn",c=n==="or"?"orWhereBetween":"whereBetween",p=n==="or"?"orWhereNull":"whereNull",d=n==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":o&&s&&typeof e.value=="string"?r[u](`${i} = ?::uuid`,[e.value]):r[a](i,"=",e.value);return;case"neq":o&&s&&typeof e.value=="string"?r[u](`${i} != ?::uuid`,[e.value]):r[a](i,"!=",e.value);return;case"gt":o&&s&&typeof e.value=="string"?r[u](`${i} > ?::uuid`,[e.value]):r[a](i,">",e.value);return;case"gte":o&&s&&typeof e.value=="string"?r[u](`${i} >= ?::uuid`,[e.value]):r[a](i,">=",e.value);return;case"lt":o&&s&&typeof e.value=="string"?r[u](`${i} < ?::uuid`,[e.value]):r[a](i,"<",e.value);return;case"lte":o&&s&&typeof e.value=="string"?r[u](`${i} <= ?::uuid`,[e.value]):r[a](i,"<=",e.value);return;case"in":{let g=Wr(e.value);o&&s&&g.every(y=>typeof y=="string")?r[u](`${i} = ANY(?::uuid[])`,[g]):r[l](i,g);return}case"not_in":{let g=Wr(e.value);o&&s&&g.every(y=>typeof y=="string")?r[u](`${i} != ALL(?::uuid[])`,[g]):r[f](i,g);return}case"contains":Vn(r,i,e.value,"contains",t,n);return;case"starts_with":Vn(r,i,e.value,"starts_with",t,n);return;case"ends_with":Vn(r,i,e.value,"ends_with",t,n);return;case"between":Array.isArray(e.value)&&e.value.length===2&&r[c](i,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?r[p](i):r[d](i);return}}function Vn(r,e,t,n,i,o){let s=o==="or"?"orWhereRaw":"whereRaw";if(i.dbType==="postgres"){let u=n==="contains"?`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?)) || '%'`:n==="starts_with"?`lower(unaccent(${e})) ILIKE lower(unaccent(?)) || '%'`:`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?))`;r[s](u,[t]);return}if(i.dbType==="sqlite"){let u=n==="contains"?`lower(${e}) LIKE '%' || lower(?) || '%'`:n==="starts_with"?`lower(${e}) LIKE lower(?) || '%'`:`lower(${e}) LIKE '%' || lower(?)`;r[s](u,[t]);return}let a=n==="contains"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:n==="starts_with"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`;r[s](a,[t])}function ho(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function Wr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var qn=K(()=>{"use strict"});function ne(r){return r.columns.find(e=>e.isPrimary)||null}var jt=K(()=>{"use strict"});var Qr={};Tn(Qr,{expandFieldsToJoinsAndSelect:()=>Hn});async function Hn(r,e,t,n,i,o){let s=[],a=[],u=await t(r);if(!u)return{select:[],batchFetchDescriptors:[]};let l=new Map;for(let c of e)if(c==="*"||!c.includes("."))l.has("")||l.set("",[]),l.get("").push(c);else{let p=c.split("."),d=p[0],g=p.slice(1).join(".");l.has(d)||l.set(d,[]),l.get(d).push(g)}let f=l.get("")||[];for(let c of f){if(c==="*"){let g=new Set;for(let h of u.relations||[])if(h.type==="many-to-one"||h.type==="one-to-one"&&!h.isInverse){let m=h.foreignKeyColumn||V(h.propertyName);m&&g.add(m)}let y=new Set;for(let h of u.columns)g.has(h.name)||(s.push(`${r}.${h.name}`),y.add(h.name));for(let h of u.relations||[])!l.has(h.propertyName)&&!y.has(h.propertyName)&&l.set(h.propertyName,["id"]);continue}if(c.includes(".")){s.push(`${r}.${c}`);continue}if(u.columns?.find(g=>g.name===c)){s.push(`${r}.${c}`);continue}if(u.relations?.find(g=>g.propertyName===c)){l.has(c)||l.set(c,["id"]);continue}}return l.forEach((c,p)=>{if(p==="")return;let d=u.relations?.find(b=>b.propertyName===p);if(!d)return;if(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse){let b=d.foreignKeyColumn||V(d.propertyName),$=C(r,n),w=C(b,n),T=C(p,n);s.push(`${$}.${w} as ${T}`)}let y=d.targetTableName||d.targetTable,h=o?.[p],m=h?.fields!=null?Array.isArray(h.fields)?h.fields:String(h.fields).split(",").map(b=>b.trim()).filter(Boolean):c;a.push({relationName:p,type:d.type,targetTable:y,fields:m,isInverse:d.isInverse,fkColumn:d.foreignKeyColumn,mappedBy:d.mappedBy,junctionTableName:d.junctionTableName,junctionSourceColumn:d.junctionSourceColumn,junctionTargetColumn:d.junctionTargetColumn,userFilter:h?.filter,userSort:h?.sort,userLimit:h?.limit!==void 0?Number(h.limit):void 0,userPage:h?.page!==void 0?Number(h.page):void 0,nestedDeep:h?.deep})}),{select:s,batchFetchDescriptors:a}}var Gn=K(()=>{"use strict";Ve();Ce()});var ct,Xn=K(()=>{"use strict";Ve();Ce();jt();et();qn();It();vt();an();ct=class{constructor(e,t="postgres",n){this.knex=e;this.dbType=t;this.metadata=n;this.pkField="id"}buildFilterTree(e,t){if(!e||!this.metadata)return null;let n=new oe,i=this.metadata?.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))},{node:o}=Te(e,t,i,n);return o}parseSortTokens(e,t,n){return e?(Array.isArray(e)?e:e.split(",").map(o=>o.trim()).filter(Boolean)).map(o=>{let s=o.startsWith("-"),u=(s?o.slice(1):o).split(".");if(u.length===1)return{column:n?`${n}.${u[0]}`:`${t}.${u[0]}`,order:s?"desc":"asc"};let l=u[u.length-1];return{column:`${`__sort_${u.slice(0,-1).join("_")}`}.${l}`,order:s?"desc":"asc"}}):[]}applySortJoins(e,t,n,i){if(!t||!this.metadata)return;let o=Array.isArray(t)?t:t.split(",").map(a=>a.trim()).filter(Boolean),s=new Set;for(let a of o){let l=(a.startsWith("-")?a.slice(1):a).split(".");if(l.length<=1)continue;let f=n,c=i||n;for(let p=0;p<l.length-1;p++){let d=l[p],g=this.metadata?.tables?.get(f);if(!g)break;let y=g.relations?.find(b=>b.propertyName===d);if(!y)break;let h=y.targetTableName||y.targetTable,m=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(m)){s.add(m);let b=y.foreignKeyColumn||V(y.propertyName),$=this.metadata?.tables?.get(h),w=$&&ne($)?.name||"id";e.leftJoin(`${h} as ${m}`,`${m}.${w}`,`${c}.${b}`)}f=h,c=m}}}toKnexSelect(e,t){let n=e.indexOf(" as ");if(n!==-1){let i=e.substring(0,n),o=e.substring(n+4),s=C(o,this.dbType),a=t?`${t}.${C(i,this.dbType)}`:C(i,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${t}.${C(e,this.dbType)} as ${C(e,this.dbType)}`):e}keyOf(e){return e==null?"":String(e)}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return ne(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;return!t&&e.mappedBy&&(t=V(e.mappedBy)),t||(t=V(e.targetTable)),t}resolveParentPk(e){return e&&ne(e)?.name||"id"}resolveFields(e,t){let{rootFields:n,subRelations:i}=Ze(e),o=[];if(n.includes("*")){let l=new Set;for(let f of t.relations||[])if(f.type==="many-to-one"||f.type==="one-to-one"&&!f.isInverse){let c=f.foreignKeyColumn||V(f.propertyName);c&&l.add(c)}for(let f of t.columns)l.has(f.name)||o.push(f.name);for(let f of t.relations||[])i.has(f.propertyName)||i.set(f.propertyName,["id"])}else for(let l of n){let f=t.columns.find(c=>c.name===l);f?o.push(f.name):t.relations?.find(p=>p.propertyName===l)&&!i.has(l)&&i.set(l,["id"])}let s=ne(t)?.name||"id";o.includes(s)||o.push(s),i.forEach((l,f)=>{let c=t.relations?.find(p=>p.propertyName===f);if(c&&(c.type==="many-to-one"||c.type==="one-to-one"&&!c.isInverse)){let p=c.foreignKeyColumn||V(c.propertyName);p&&o.push(`${p} as ${f}`)}});let a=[];return i.forEach((l,f)=>{let c=t.relations?.find(d=>d.propertyName===f);if(!c)return;let p=c.targetTableName||c.targetTable;p&&a.push({relationName:f,type:c.type,targetTable:p,fields:l,isInverse:c.isInverse,fkColumn:c.foreignKeyColumn,mappedBy:c.mappedBy,junctionTableName:c.junctionTableName,junctionSourceColumn:c.junctionSourceColumn,junctionTargetColumn:c.junctionTargetColumn})}),{isPkOnly:o.length===1&&o[0]===s&&a.length===0,nestedDescs:a,fetchSpec:{selectCols:o,pkCol:s}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?this.buildFilterTree(i.userFilter,e):null,s=i?.userSort?this.parseSortTokens(i.userSort,e):[],a=n.selectCols.map(u=>this.toKnexSelect(u));return Y(t,u=>{let l=this.knex(e).select(a).whereIn(n.pkCol,u);if(o&&X(l,o,{dbType:this.dbType,rootTable:e}),s.length>0){this.applySortJoins(l,i.userSort,e);for(let f of s)l.orderBy(f.column,f.order)}return l})}async fetchInverse(e,t,n,i,o){let s=t,a=i.selectCols.find(g=>g.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():i.selectCols.includes(t)||i.selectCols.push(t);let u=o?.userFilter?this.buildFilterTree(o.userFilter,e):null,l=o?.userSort?this.parseSortTokens(o.userSort,e):[],f=o?.userLimit,c=o?.userPage;if(f!==void 0&&f>0){let g=c?(c-1)*f:0,y=i.selectCols.map(b=>this.toKnexSelect(b)),h=await pe(n,async b=>{let $=this.knex(e).select(y).where(t,b);if(u&&X($,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins($,o.userSort,e),l.length>0)for(let w of l)$.orderBy(w.column,w.order);else $.orderBy(i.pkCol,"asc");return g>0&&$.offset(g),$.limit(f),$},te),m=[];for(let[b,$]of h.entries()){let w=n.find(T=>String(T)===b);for(let T of $)T[t]||(T[t]=w??b),m.push(T)}return{docs:m,groupKeyField:s}}let p=i.selectCols.map(g=>this.toKnexSelect(g));return{docs:await Y(n,g=>{let y=this.knex(e).select(p).whereIn(t,g);if(u&&X(y,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(y,o?.userSort,e),l.length>0)for(let h of l)y.orderBy(h.column,h.order);else y.orderBy(i.pkCol,"asc");return y}),groupKeyField:s}}postProcessInverseChild(e,t,n){n||delete e[t]}async fetchM2M(e,t,n,i,o){let s=this.resolveParentPk(n),a=e.map($=>$[s]).filter($=>$!=null);if(a.length===0)return{grouped:new Map,docs:[]};let u=t.junctionTableName,l=t.junctionSourceColumn,f=t.junctionTargetColumn;if(!u||!l||!f)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let c=t.userFilter?this.buildFilterTree(t.userFilter,t.targetTable):null,p=t.userSort?this.parseSortTokens(t.userSort,t.targetTable,"t"):[],d=t.userLimit,g=t.userPage;if(o.selectCols.length===1&&o.selectCols[0]===o.pkCol&&!c&&!d){let $=await Y(a,T=>this.knex(u).select([`${l} as __sourceId__`,`${f} as __targetId__`]).whereIn(l,T).orderBy(f,"asc")),w=new Map;for(let T of $){let k=this.keyOf(T.__sourceId__);w.has(k)||w.set(k,[]),w.get(k).push({[o.pkCol]:T.__targetId__})}return{grouped:w,docs:[]}}let h=o.selectCols.map($=>this.toKnexSelect($,"t"));if(d!==void 0&&d>0){let $=g?(g-1)*d:0,w=new Map;for(let v of a)w.set(this.keyOf(v),[]);let T=await pe(a,async v=>{let _=this.knex(u).join(`${t.targetTable} as t`,`${u}.${f}`,`t.${o.pkCol}`).select(h).where(`${u}.${l}`,v);if(c&&X(_,c,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(_,t.userSort,t.targetTable,"t"),p.length>0)for(let N of p)_.orderBy(N.column,N.order);else _.orderBy(`t.${o.pkCol}`,"asc");return $>0&&_.offset($),_.limit(d),_},te),k=[];for(let[v,_]of T.entries()){w.set(v,_);for(let N of _)k.push(N)}return{grouped:w,docs:k}}let m=await Y(a,$=>{let w=this.knex(u).join(`${t.targetTable} as t`,`${u}.${f}`,`t.${o.pkCol}`).select([`${u}.${l} as __sourceId__`,...h]).whereIn(`${u}.${l}`,$);if(c&&X(w,c,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(w,t.userSort,t.targetTable,"t"),p.length>0)for(let T of p)w.orderBy(T.column,T.order);else w.orderBy(`t.${o.pkCol}`,"asc");return w}),b=new Map;for(let $ of m){let w=$.__sourceId__;delete $.__sourceId__;let T=this.keyOf(w);b.has(T)||b.set(T,[]),b.get(T).push($)}return{grouped:b,docs:m}}}});var Vr={};Tn(Vr,{executeBatchFetches:()=>Zn});async function Zn(r,e,t,n,i=3,o=0,s,a="postgres",u,l){let f=new ct(r,a,u);await new $e(f,n,l).execute(e,t,i,o,s)}var er=K(()=>{"use strict";et();Xn()});var _o={};Tn(_o,{ALL_SUPPORTED_OPERATORS:()=>Rt,AuthenticationException:()=>Ae,AuthorizationException:()=>Oe,BadRequestException:()=>x,BatchFetchEngine:()=>$e,BusinessLogicException:()=>ve,CHUNKED_FETCH_CONCURRENCY:()=>jn,ConfigurationException:()=>bt,DEEP_TO_MANY_DEFAULT_LIMIT:()=>Ln,DEFAULT_TIMEOUT_MS:()=>Dt,DOTTED_PATH_MAX_HOPS:()=>_n,DatabaseException:()=>me,DuplicateResourceException:()=>Me,ErrorHandler:()=>Pe,ExecutorEngineService:()=>Qe,ExternalServiceException:()=>yt,FIELD_OPERATORS:()=>ee,FileNotFoundException:()=>wt,FileSizeExceededException:()=>Tt,FileUploadException:()=>_t,HttpException:()=>xe,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>Wt,InvalidTokenException:()=>ht,IsolatedExecutorService:()=>ze,JoinRegistry:()=>oe,LOGICAL_OPERATORS:()=>vn,MongoBatchAdapter:()=>tt,MongoQueryExecutor:()=>ot,PER_PARENT_CONCURRENCY:()=>te,QueryBuilderService:()=>ft,QueryPlanner:()=>Q,ResourceNotFoundException:()=>Ne,SchemaException:()=>mt,ScriptContractService:()=>zt,ScriptExecutionException:()=>ye,ScriptTimeoutException:()=>he,ServiceUnavailableException:()=>Ee,SqlBatchAdapter:()=>ct,SqlQueryExecutor:()=>ut,TokenExpiredException:()=>gt,ValidationException:()=>Ie,WHERE_IN_CHUNK_SIZE:()=>Se,WorkerPool:()=>kt,appendIsolatedExecutorRuntimeLog:()=>z,applyOperatorToMatch:()=>Zt,applyRelationFilters:()=>Ue,applyWhereToKnex:()=>lt,assertFieldOperatorValueIsClean:()=>tn,buildAggregateFilter:()=>it,buildMongoCharFoldMapJson:()=>Rn,buildMongoFoldTextSearchJs:()=>Ht,buildRelationSubquery:()=>Ot,buildSqlWherePartsFromFieldAst:()=>Pt,buildWhereClause:()=>ae,camelToSnake:()=>hr,chunkedFetch:()=>Y,compileScriptSource:()=>Vt,computeEngineTuning:()=>$n,createEnfyraKernel:()=>bo,dslOpToCompareOp:()=>en,encodeMainThreadToIsolate:()=>kn,escapeSqlValue:()=>Ur,executeBatchFetches:()=>Zn,executeMongoBatchFetches:()=>ln,expandFieldsToJoinsAndSelect:()=>Hn,getEffectiveCpuCount:()=>Sn,getEffectiveMemoryBytes:()=>St,getEngineTuning:()=>Jt,getExecutableScript:()=>bi,getForeignKeyColumnName:()=>V,getIoAbortSignal:()=>cr,getJunctionColumnNames:()=>Ct,getJunctionTableName:()=>Ft,getPrimaryKeyColumn:()=>ne,getScriptLegacyField:()=>di,getShortFkConstraintName:()=>pr,getShortFkName:()=>yr,getShortIndexName:()=>mr,getShortPkName:()=>dr,hasAggregateQuery:()=>Kn,hasLogicalOperators:()=>ge,isExecutableJavaScript:()=>hi,isScriptTable:()=>pi,mergeAggregateValue:()=>Fe,normalizeAggregateQuery:()=>rt,normalizeFlowStepScriptConfig:()=>wi,normalizeScriptLanguage:()=>gi,normalizeScriptPatch:()=>mi,normalizeScriptRecord:()=>yi,parseBatchFields:()=>Ze,parseFields:()=>cn,parseFilter:()=>Te,perParentRun:()=>pe,quoteIdentifier:()=>C,resolveExecutableScript:()=>_i,rewriteFilterDenyingFields:()=>Gr,rewriteSortDroppingDenied:()=>Yr,scriptContractService:()=>Z,separateFilters:()=>G,snakeToCamel:()=>gr,throwUnsupportedFieldOperator:()=>Be,validateDeepOptions:()=>tr,validateFilterShape:()=>U,whereToMongoFilter:()=>Ge});module.exports=ri(_o);var Dt=3e4,Qe=class{constructor(e){this.isolatedExecutorService=e.isolatedExecutorService}register(e,t){e.routeData.__codeBlocks||(e.routeData.__codeBlocks=[]),e.routeData.__codeBlocks.push(t)}async runBatch(e,t){let n=e.routeData.__codeBlocks||[];return n.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(n,e.routeData.context,t??Dt)}async run(e,t,n=Dt){return this.isolatedExecutorService.run(e,t,n)}};var Kt=class{constructor(e){this.context=e}log(e){console.log(this.format(e))}warn(e){console.warn(this.format(e))}error(e,t){console.error(this.format(e)),t&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};var or=require("async_hooks"),sr=ce(require("path")),ar=require("worker_threads");var he=class extends Error{constructor(t=0,n){let i=typeof t=="number"&&t>0?`${t}ms`:String(t||"configured timeout");super(`Script execution timed out after ${i}`);this.statusCode=408;this.errorCode="SCRIPT_TIMEOUT";this.name="ScriptTimeoutException",this.details={timeoutMs:t,scriptId:n}}},ye=class extends Error{constructor(t,n,i){super(`Script execution failed: ${t}`);this.statusCode=400;this.errorCode="SCRIPT_EXECUTION_ERROR";this.name="ScriptExecutionException",this.details={scriptId:n,...i}}},j=class extends Error{constructor(t,n,i,o){super(t);this.statusCode=n;this.errorCode=i;this.name=this.constructor.name,this.details=o}},xe=class extends j{constructor(e,t,n){super(e,t,`HTTP_${t}`,n)}},ve=class extends j{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},Ie=class extends j{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},Ne=class extends j{constructor(e,t){super(t?`${e} with identifier '${t}' not found`:`${e} not found`,404,"RESOURCE_NOT_FOUND",{resource:e,identifier:t})}},Me=class extends j{constructor(e,t,n){super(`${e} with ${t} '${n}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:n})}},Ae=class extends j{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},Oe=class extends j{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},gt=class extends j{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},ht=class extends j{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},me=class extends j{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},yt=class extends j{constructor(e,t,n){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:n})}},Ee=class extends j{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},mt=class extends j{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},bt=class extends j{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},_t=class extends j{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},wt=class extends j{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},Tt=class extends j{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var Pe=class{static createException(e,t,n,i,o){if(e?.includes("$throw"))switch(e){case"$throw.businessLogic":return new ve(n||"Bad request",o);case"$throw.validation":return new Ie(n||"Validation failed",o);case"$throw.notFound":return new Ne(n||"Resource");case"$throw.duplicate":return new Me(n||"Resource","field","value");case"$throw.unauthorized":return new Ae(n||"Unauthorized");case"$throw.forbidden":return new Oe(n||"Forbidden");case"$throw.tokenExpired":return new gt;case"$throw.invalidToken":return new ht;case"$throw.database":return new me(n||"Database error",o);case"$throw.dbQuery":return new me(n||"Query error",o);case"$throw.externalService":return new yt(n||"Service",n||"Error",o);case"$throw.serviceUnavailable":return new Ee(n||"Service");case"$throw.rateLimit":return new xe(n||"Rate limit exceeded",429);case"$throw.scriptError":return new ye(n||"Script error",i,o);case"$throw.scriptTimeout":return new he(o?.timeout||5e3,i);case"$throw.schema":return new mt(n||"Schema error",o);case"$throw.config":return new bt(n||"Configuration error",o);case"$throw.fileUpload":return new _t(n||"File upload error",o);case"$throw.fileNotFound":return new wt(n||"File not found");case"$throw.fileSizeExceeded":return new Tt(o?.maxSize||"unknown",o?.actualSize||"unknown");case"$throw.400":return new ve(n||"Bad request",o);case"$throw.401":return new Ae(n||"Authentication required");case"$throw.403":return new Oe(n||"Insufficient permissions");case"$throw.404":return new Ne(n||"Resource");case"$throw.409":return new Me(n||"Resource","field","value");case"$throw.422":return new Ie(n||"Validation failed",o);case"$throw.429":return new xe(n||"Rate limit exceeded",429);case"$throw.500":return new me(n||"Internal server error",o);case"$throw.503":return new Ee(n||"Service");default:return new ye(n||"Unknown error",i)}if(t)switch(t){case 400:return new ve(n||"Bad request",o);case 401:return new Ae(n||"Authentication required");case 403:return new Oe(n||"Insufficient permissions");case 404:return new Ne(n||"Resource");case 409:return new Me(n||"Resource","field","value");case 422:return new Ie(n||"Validation failed",o);case 429:return new xe(n||"Rate limit exceeded",429);case 500:return new me(n||"Internal server error",o);case 503:return new Ee(n||"Service");default:return new ye(n||"Unknown error",i,o)}return new ye(n||"Unknown error",i,o)}};var Ut=ce(require("fs")),Qt=ce(require("path")),Wt=Qt.join(process.cwd(),"test","logs","isolated-executor-runtime.log");function ii(){return process.env.ISOLATED_EXECUTOR_FILE_LOG==="0"?!1:process.env.ISOLATED_EXECUTOR_FILE_LOG==="1"?!0:process.env.JEST_WORKER_ID!==void 0}var oi=ii();function z(r){if(oi)try{let e=Qt.dirname(Wt);Ut.mkdirSync(e,{recursive:!0});let t=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...r})+`
|
|
2
|
-
`;
|
|
1
|
+
"use strict";var ei=Object.create;var Dt=Object.defineProperty;var ti=Object.getOwnPropertyDescriptor;var ni=Object.getOwnPropertyNames;var ri=Object.getPrototypeOf,ii=Object.prototype.hasOwnProperty;var K=(r,e)=>()=>(r&&(e=r(r=0)),e);var Tn=(r,e)=>{for(var t in e)Dt(r,t,{get:e[t],enumerable:!0})},rr=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ni(e))!ii.call(r,i)&&i!==t&&Dt(r,i,{get:()=>e[i],enumerable:!(n=ti(e,i))||n.enumerable});return r};var ue=(r,e,t)=>(t=r!=null?ei(ri(r)):{},rr(e||!r||!r.__esModule?Dt(t,"default",{value:r,enumerable:!0}):t,r)),oi=r=>rr(Dt({},"__esModule",{value:!0}),r);function pr(r){return Cn.createHash("md5").update(r).digest("hex").substring(0,8)}function gr(r){return r.length<=dr-3?`${r}_pk`:`j_${pr(r)}_pk`}function hr(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=dr?n:`j_${pr(r)}_${t}_fk`}function Ct(r,e,t){let n=`${r}:${e}:${t}`;return`j_${Cn.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function V(r){return`${r}Id`}function Rt(r,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function yr(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function mr(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function br(r,e,t){return`${r}_${e}_${t}_fk`}function _r(r,e,t){return`${r}_${e}_${t}_idx`}var Cn,dr,qe=K(()=>{"use strict";Cn=ue(require("crypto")),dr=63});function tn(r){return Li[r]??null}var ee,In,xt,Li,vt=K(()=>{"use strict";ee=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),In=new Set(["_and","_or","_not"]),xt=[...Array.from(In),...Array.from(ee)],Li={_eq:"eq",_neq:"neq",_gt:"gt",_gte:"gte",_lt:"lt",_lte:"lte",_in:"in",_not_in:"not_in",_nin:"not_in",_contains:"contains",_starts_with:"starts_with",_ends_with:"ends_with",_between:"between"}});var x,fe=K(()=>{"use strict";x=class extends Error{constructor(t="Bad Request",n){let i=Array.isArray(t),o=i?t.join("; ")||"Bad Request":typeof t=="string"?t:JSON.stringify(t);super(o);this.statusCode=400;this.errorCode="BAD_REQUEST";this.name="BadRequestException",this.details=n,i&&(this.messages=t)}}});function $r(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var kr=K(()=>{"use strict"});function De(r,e,t){throw new x({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${xt.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:xt})}function nn(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=$r();for(let i of Object.keys(e))if(i.startsWith("_")&&!ee.has(i)){if(n&&i==="_id")continue;De(i,r,t)}}function U(r,e,t){if(!r||typeof r!="object")return;let n=t?.tables?.get(e),i=new Set((n?.columns??[]).map(s=>s.name)),o=new Map((n?.relations??[]).map(s=>[s.propertyName,s]));for(let[s,a]of Object.entries(r)){if(Bi.has(s)){if(Array.isArray(a))for(let l of a)U(l,e,t);else a&&typeof a=="object"&&U(a,e,t);continue}let u=o.get(s);if(u){if(a&&typeof a=="object"&&!Array.isArray(a)){nn(s,a,e);let l=u.targetTableName||u.targetTable;if(l){let f=Object.keys(a).filter(c=>!c.startsWith("_"));if(f.length>0){let c={};for(let p of f)c[p]=a[p];U(c,l,t)}}}continue}s.startsWith("_")&&!i.has(s)&&s!=="_id"&&De(s,s,e),a&&typeof a=="object"&&!Array.isArray(a)&&nn(s,a,e)}}var Bi,Xe=K(()=>{"use strict";fe();vt();kr();Bi=new Set(["_and","_or","_not"])});function Te(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:rn(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function rn(r,e){if(!r||typeof r!="object")return{node:null,hasRelationFilters:!1};let t=[],n=!1;for(let[i,o]of Object.entries(r)){let s=Di(i,o,e);s.hasRelationFilters&&(n=!0),s.node&&t.push(s.node)}return t.length===0?{node:null,hasRelationFilters:n}:t.length===1?{node:t[0],hasRelationFilters:n}:{node:{kind:"and",children:t},hasRelationFilters:n}}function Di(r,e,t){if(r==="_and")return Fr("and",e,t);if(r==="_or")return Fr("or",e,t);if(r==="_not"){let l=rn(e,t);return l.node?{node:{kind:"not",child:l.node},hasRelationFilters:l.hasRelationFilters}:{node:null,hasRelationFilters:l.hasRelationFilters}}let n=t.metadata?.tables?.get(t.currentTable),i=n?.columns?.some(l=>l.name==="_id"&&l.isPrimary),o=n?.columns?.some(l=>l.name==="id"),a=r==="id"?i&&!o?"_id":"id":r,u=n?.relations?.find(l=>l.propertyName===a);return u?Ki(a,e,u,t):n&&!n.columns?.find(f=>f.name===a)?(r.startsWith("_")&&r!=="_id"&&De(r,r,t.currentTable),console.warn(`[filter-parser] Unknown field "${r}" on table "${t.currentTable}" \u2014 skipped (not a column or relation in metadata).`),{node:null,hasRelationFilters:!1}):Wi(a,e,t)}function Fr(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],i=!1;for(let o of e){let s=rn(o,t);s.hasRelationFilters&&(i=!0),s.node&&n.push(s.node)}return n.length===0?{node:null,hasRelationFilters:i}:n.length===1?{node:n[0],hasRelationFilters:i}:{node:{kind:r,children:n},hasRelationFilters:i}}function Ki(r,e,t,n){if(typeof e!="object"||e===null)return{node:null,hasRelationFilters:!0};let i=Object.keys(e),o=i.length===1&&(i[0]==="_is_null"||i[0]==="_is_not_null"||i[0]==="_eq"||i[0]==="_neq"||i[0]==="_in"||i[0]==="_not_in"||i[0]==="_nin"),s=n.registry.registerWithParent(n.currentTable,r,n.metadata,"left",n.currentJoinId,"filter");if(o&&i[0]==="_is_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_null===!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(o&&i[0]==="_is_not_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_not_null!==!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(o&&(i[0]==="_eq"||i[0]==="_neq")&&e[i[0]]===null)return s?{node:{kind:"relation_exists",joinId:s,negate:i[0]==="_eq"},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(!s)return{node:null,hasRelationFilters:!0};let a=t.targetTableName||t.targetTable,u={...n,parentJoinId:n.currentJoinId,currentJoinId:s,currentTable:a},l=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]),c=i.length>0&&i.every(d=>l.has(d))?{id:e}:e;return{node:rn(c,u).node,hasRelationFilters:!0}}function Wi(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:Qi(r,t)};if(e===null)return{node:{kind:"compare",field:n,op:"is_null",value:!0},hasRelationFilters:!1};if(typeof e!="object")return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};for(let s of Object.keys(e))s.startsWith("_")&&!ee.has(s)&&De(s,r,t.tableName);let i=Object.entries(e).filter(([s])=>ee.has(s));if(i.length===0)return{node:{kind:"compare",field:n,op:"eq",value:e},hasRelationFilters:!1};let o=[];for(let[s,a]of i){let u=Ui(n,s,a);u&&o.push(u)}return o.length===0?{node:null,hasRelationFilters:!1}:o.length===1?{node:o[0],hasRelationFilters:!1}:{node:{kind:"and",children:o},hasRelationFilters:!1}}function Ui(r,e,t){if(e==="_is_null")return{kind:"compare",field:r,op:"is_null",value:t===!0};if(e==="_is_not_null")return{kind:"compare",field:r,op:"is_null",value:t!==!0};let n=tn(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function Qi(r,e){let t=e.metadata?.tables?.get(e.currentTable);if(!t)return!1;let n=r.includes(".")?r.split(".").pop():r,i=t.columns?.find(s=>s.name===n);if(!i)return!1;let o=(i.type||"").toLowerCase();return o==="uuid"||o==="uuidv4"||o.includes("uuid")}var It=K(()=>{"use strict";vt();Xe()});var oe,Nt=K(()=>{"use strict";oe=class{constructor(){this.map=new Map}size(){return this.map.size}has(e){return this.map.has(e)}get(e){return this.map.get(e)}getAll(){return Array.from(this.map.values())}registerWithParent(e,t,n,i="left",o=null,s="data"){let a=o?`${o}.${t}`:t;if(this.map.has(a)){let p=this.map.get(a);return i==="inner"&&(p.joinType="inner"),p.purposes.includes(s)||p.purposes.push(s),a}let u=n?.tables?.get(e);if(!u)return null;let l=u.relations?.find(p=>p.propertyName===t);if(!l)return null;let f=l.targetTableName||l.targetTable;if(!f)return null;let c={id:a,propertyName:t,parentTable:e,targetTable:f,relationType:l.type,parentJoinId:o,joinType:i,relationMeta:l,purposes:[s]};return this.map.set(a,c),a}}});async function Y(r,e){if(r.length<=$e)return e(r);let t=[];for(let a=0;a<r.length;a+=$e)t.push(r.slice(a,a+$e));let n=[],i=0;async function o(){for(;i<t.length;){let a=i++;n[a]=await e(t[a])}}let s=Math.min(Ln,t.length);return await Promise.all(Array.from({length:s},o)),n.flat()}function et(r){let e=[],t=new Map;for(let n of r)if(n==="*"||!n.includes("."))e.push(n);else{let i=n.split("."),o=i[0],s=i.slice(1).join(".");t.has(o)||t.set(o,[]),t.get(o).push(s)}return{rootFields:e,subRelations:t}}var te,$e,Ln,Bn,ke,tt=K(()=>{"use strict";fe();te=16,$e=5e3,Ln=4,Bn=10;ke=class{constructor(e,t,n){this.adapter=e;this.metadataGetter=t;this.trace=n}enrichNestedDescs(e,t){return!t||Object.keys(t).length===0?e:e.map(n=>{let i=t[n.relationName];if(!i)return n;let o=i.fields!=null?Array.isArray(i.fields)?i.fields:String(i.fields).split(",").map(s=>s.trim()).filter(Boolean):n.fields;return{...n,fields:o,userFilter:i.filter??n.userFilter,userSort:i.sort??n.userSort,userLimit:i.limit!==void 0?Number(i.limit):n.userLimit,userPage:i.page!==void 0?Number(i.page):n.userPage,nestedDeep:i.deep??n.nestedDeep}})}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:Bn}:e}assertLocalSortFields(e,t){if(!e.userSort)return;let n=Array.isArray(e.userSort)?e.userSort:String(e.userSort).split(",").map(i=>i.trim()).filter(Boolean);for(let i of n){let o=i.startsWith("-")?i.slice(1):i;if(o.includes("."))throw new x(`Sort field '${o}' is not supported on deep relation '${e.relationName}'. Sort only by local fields defined on '${e.targetTable}'.`);let s=t.columns?.some(u=>u.name===o),a=o==="id"&&t.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new x(`Sort field '${o}' does not exist on '${e.targetTable}'. Sort only by fields defined on the table metadata.`)}}async execute(e,t,n=3,i=0,o){if(e.length===0||t.length===0||i>=n)return;let s;o&&(s=await this.metadataGetter(o)??void 0),await Promise.all(t.map(a=>{let u=this.withDefaultToManyLimit(a);return u.type==="many-to-one"||u.type==="one-to-one"&&!u.isInverse?this.fetchOwnerRelation(e,u,n,i):u.type==="one-to-many"||u.type==="one-to-one"&&u.isInverse?this.fetchInverseRelation(e,u,n,i,s):u.type==="many-to-many"?this.fetchM2MRelation(e,u,n,i,s):Promise.resolve()}))}async fetchOwnerRelation(e,t,n,i){let o=this.adapter.resolveOwnerFkKey(t),s=new Set,a=[];for(let m of e){let b=m[o];if(b==null)continue;let $=this.adapter.keyOf(b);s.has($)||(s.add($),a.push(b))}if(a.length===0){for(let m of e)m[t.relationName]=null,o!==t.relationName&&delete m[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete m[t.fkColumn];return}let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{isPkOnly:l,nestedDescs:f,fetchSpec:c}=this.adapter.resolveFields(t.fields,u),p=this.adapter.getTargetPkField(u);if(l){for(let m of e){let b=m[o];m[t.relationName]=b!=null?this.adapter.buildScalarRef(b,p):null,o!==t.relationName&&delete m[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete m[t.fkColumn]}return}let d=performance.now(),g=await this.adapter.fetchOwner(t.targetTable,a,c,t);this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,d,{relationType:t.type,targetTable:t.targetTable,strategy:"batch-in",roundtrips:Math.ceil(a.length/$e)||1,rowsTransferred:g.length,rowsReturned:g.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let y=this.enrichNestedDescs(f,t.nestedDeep);y.length>0&&await this.execute(g,y,n,i+1,t.targetTable);let h=new Map;for(let m of g)h.set(this.adapter.keyOf(m[p]),m);for(let m of e){let b=m[o];m[t.relationName]=b!=null&&h.get(this.adapter.keyOf(b))||null,o!==t.relationName&&delete m[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete m[t.fkColumn]}}async fetchInverseRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=e.map(_=>_[s]).filter(_=>_!=null);if(a.length===0)return;let u=this.adapter.resolveInverseFkField(t),l=await this.metadataGetter(t.targetTable);if(!l)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,l);let{nestedDescs:f,fetchSpec:c}=this.adapter.resolveFields(t.fields,l),p=performance.now(),{docs:d,groupKeyField:g}=await this.adapter.fetchInverse(t.targetTable,u,a,c,t),y=new Map,h=t.fields.includes(u)||t.fields.includes("*");for(let _ of d){let N=_[g],I=this.adapter.keyOf(N);y.has(I)||y.set(I,[]),y.get(I).push(_)}let m=t.userLimit!==void 0&&t.userLimit>0,b=m?"per-parent-c16":"batch-in",$=m?a.length:Math.ceil(a.length/$e)||1,w=m?Math.ceil(a.length/te):void 0,S=Array.from(y.values()).reduce((_,N)=>_+N.length,0);if(this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:b,roundtrips:$,concurrencyWaves:w,rowsTransferred:d.length,rowsReturned:S,rowsDiscarded:d.length-S,userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let _ of d)this.adapter.postProcessInverseChild(_,u,h);let k=this.enrichNestedDescs(f,t.nestedDeep);k.length>0&&await this.execute(d,k,n,i+1,t.targetTable);let v=t.type==="one-to-one";for(let _ of e){let N=this.adapter.keyOf(_[s]),I=y.get(N)||[];_[t.relationName]=v?I[0]||null:I}}async fetchM2MRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=e.map(w=>w[s]).filter(w=>w!=null);if(a.length===0)return;let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{nestedDescs:l,fetchSpec:f}=this.adapter.resolveFields(t.fields,u),c=performance.now(),{grouped:p,docs:d}=await this.adapter.fetchM2M(e,t,o,u,f),g=t.userLimit!==void 0&&t.userLimit>0,y=g?"m2m-per-parent-c16":"m2m-batch",h=g?a.length:Math.ceil(a.length/$e)||1,m=g?Math.ceil(a.length/te):void 0,b=Array.from(p.values()).reduce((w,S)=>w+S.length,0);this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,c,{relationType:t.type,targetTable:t.targetTable,strategy:y,roundtrips:h,concurrencyWaves:m,rowsTransferred:d.length,rowsReturned:b,rowsDiscarded:d.length-b,userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort});let $=this.enrichNestedDescs(l,t.nestedDeep);$.length>0&&d.length>0&&await this.execute(d,$,n,i+1,t.targetTable);for(let w of e){let S=this.adapter.keyOf(w[s]);w[t.relationName]=p.get(S)||[]}}}});async function ge(r,e,t){let n=new Map,i=0;async function o(){for(;i<r.length;){let u=i++,l=r[u];n.set(String(l),await e(l))}}let s=Math.min(t,r.length);if(s===0)return n;let a=Array.from({length:s},o);return await Promise.all(a),n}var ln=K(()=>{"use strict"});function C(r,e){let t=e==="mysql"?r.replace(/`/g,"``"):r.replace(/"/g,'""');switch(e){case"mysql":return`\`${t}\``;case"postgres":case"pg":case"sqlite":return`"${t}"`;case"mongodb":return r;default:return`\`${t}\``}}function Re(r,e){return r.split(".").map(t=>t==="*"||t.startsWith('"')&&t.endsWith('"')||t.startsWith("`")&&t.endsWith("`")?t:C(t,e)).join(".")}var ae=K(()=>{"use strict"});function X(r,e,t){e&&yn(r,e,t,"and")}function yn(r,e,t,n){switch(e.kind){case"true":return;case"false":n==="or"?r.orWhereRaw("1 = 0"):r.whereRaw("1 = 0");return;case"and":{let i=function(){for(let o of e.children)this.where(function(){yn(this,o,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"or":{let i=function(){for(let o of e.children)this.orWhere(function(){yn(this,o,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"not":{let i=function(){this.whereNot(function(){yn(this,e.child,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"compare":yo(r,e,t,n);return;case"relation_exists":console.warn(`[sql-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${e.joinId}) \u2014 expected to be handled by applyRelationFilters. Filter silently skipped.`);return}}function yo(r,e,t,n){if(e.field.joinId!==null){console.warn(`[sql-render-filter] compare node has joinId=${e.field.joinId} (field=${e.field.fieldName}) but reached renderer \u2014 expected join path to handle it. Filter silently skipped.`);return}let i=mo(e.field,t),o=Re(i,t.dbType),s=!!e.field.isUuid,a=t.dbType==="postgres",u=n==="or"?"orWhere":"where",l=n==="or"?"orWhereRaw":"whereRaw",f=n==="or"?"orWhereIn":"whereIn",c=n==="or"?"orWhereNotIn":"whereNotIn",p=n==="or"?"orWhereBetween":"whereBetween",d=n==="or"?"orWhereNull":"whereNull",g=n==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":s&&a&&typeof e.value=="string"?r[l](`${o} = ?::uuid`,[e.value]):r[u](i,"=",e.value);return;case"neq":s&&a&&typeof e.value=="string"?r[l](`${o} != ?::uuid`,[e.value]):r[u](i,"!=",e.value);return;case"gt":s&&a&&typeof e.value=="string"?r[l](`${o} > ?::uuid`,[e.value]):r[u](i,">",e.value);return;case"gte":s&&a&&typeof e.value=="string"?r[l](`${o} >= ?::uuid`,[e.value]):r[u](i,">=",e.value);return;case"lt":s&&a&&typeof e.value=="string"?r[l](`${o} < ?::uuid`,[e.value]):r[u](i,"<",e.value);return;case"lte":s&&a&&typeof e.value=="string"?r[l](`${o} <= ?::uuid`,[e.value]):r[u](i,"<=",e.value);return;case"in":{let y=Qr(e.value);s&&a&&y.every(h=>typeof h=="string")?r[l](`${o} = ANY(?::uuid[])`,[y]):r[f](i,y);return}case"not_in":{let y=Qr(e.value);s&&a&&y.every(h=>typeof h=="string")?r[l](`${o} != ALL(?::uuid[])`,[y]):r[c](i,y);return}case"contains":qn(r,o,e.value,"contains",t,n);return;case"starts_with":qn(r,o,e.value,"starts_with",t,n);return;case"ends_with":qn(r,o,e.value,"ends_with",t,n);return;case"between":Array.isArray(e.value)&&e.value.length===2&&r[p](i,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?r[d](i):r[g](i);return}}function qn(r,e,t,n,i,o){let s=o==="or"?"orWhereRaw":"whereRaw";if(i.dbType==="postgres"){let u=n==="contains"?`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?)) || '%'`:n==="starts_with"?`lower(unaccent(${e})) ILIKE lower(unaccent(?)) || '%'`:`lower(unaccent(${e})) ILIKE '%' || lower(unaccent(?))`;r[s](u,[t]);return}if(i.dbType==="sqlite"){let u=n==="contains"?`lower(${e}) LIKE '%' || lower(?) || '%'`:n==="starts_with"?`lower(${e}) LIKE lower(?) || '%'`:`lower(${e}) LIKE '%' || lower(?)`;r[s](u,[t]);return}let a=n==="contains"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:n==="starts_with"?`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`:`lower(unaccent(${e})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`;r[s](a,[t])}function mo(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function Qr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var Hn=K(()=>{"use strict";ae()});function ne(r){return r.columns.find(e=>e.isPrimary)||null}var Lt=K(()=>{"use strict"});var zr={};Tn(zr,{expandFieldsToJoinsAndSelect:()=>Gn});async function Gn(r,e,t,n,i,o){let s=[],a=[],u=await t(r);if(!u)return{select:[],batchFetchDescriptors:[]};let l=new Map;for(let c of e)if(c==="*"||!c.includes("."))l.has("")||l.set("",[]),l.get("").push(c);else{let p=c.split("."),d=p[0],g=p.slice(1).join(".");l.has(d)||l.set(d,[]),l.get(d).push(g)}let f=l.get("")||[];for(let c of f){if(c==="*"){let g=new Set;for(let h of u.relations||[])if(h.type==="many-to-one"||h.type==="one-to-one"&&!h.isInverse){let m=h.foreignKeyColumn||V(h.propertyName);m&&g.add(m)}let y=new Set;for(let h of u.columns)g.has(h.name)||(s.push(`${r}.${h.name}`),y.add(h.name));for(let h of u.relations||[])!l.has(h.propertyName)&&!y.has(h.propertyName)&&l.set(h.propertyName,["id"]);continue}if(c.includes(".")){s.push(`${r}.${c}`);continue}if(u.columns?.find(g=>g.name===c)){s.push(`${r}.${c}`);continue}if(u.relations?.find(g=>g.propertyName===c)){l.has(c)||l.set(c,["id"]);continue}}return l.forEach((c,p)=>{if(p==="")return;let d=u.relations?.find(b=>b.propertyName===p);if(!d)return;if(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse){let b=d.foreignKeyColumn||V(d.propertyName),$=C(r,n),w=C(b,n),S=C(p,n);s.push(`${$}.${w} as ${S}`)}let y=d.targetTableName||d.targetTable,h=o?.[p],m=h?.fields!=null?Array.isArray(h.fields)?h.fields:String(h.fields).split(",").map(b=>b.trim()).filter(Boolean):c;a.push({relationName:p,type:d.type,targetTable:y,fields:m,isInverse:d.isInverse,fkColumn:d.foreignKeyColumn,mappedBy:d.mappedBy,junctionTableName:d.junctionTableName,junctionSourceColumn:d.junctionSourceColumn,junctionTargetColumn:d.junctionTargetColumn,userFilter:h?.filter,userSort:h?.sort,userLimit:h?.limit!==void 0?Number(h.limit):void 0,userPage:h?.page!==void 0?Number(h.page):void 0,nestedDeep:h?.deep})}),{select:s,batchFetchDescriptors:a}}var Yn=K(()=>{"use strict";qe();ae()});var ut,Zn=K(()=>{"use strict";qe();ae();Lt();tt();Hn();Nt();It();ln();ut=class{constructor(e,t="postgres",n){this.knex=e;this.dbType=t;this.metadata=n;this.pkField="id"}buildFilterTree(e,t){if(!e||!this.metadata)return null;let n=new oe,i=this.metadata?.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))},{node:o}=Te(e,t,i,n);return o}parseSortTokens(e,t,n){return e?(Array.isArray(e)?e:e.split(",").map(o=>o.trim()).filter(Boolean)).map(o=>{let s=o.startsWith("-"),u=(s?o.slice(1):o).split(".");if(u.length===1)return{column:n?`${n}.${u[0]}`:`${t}.${u[0]}`,order:s?"desc":"asc"};let l=u[u.length-1];return{column:`${`__sort_${u.slice(0,-1).join("_")}`}.${l}`,order:s?"desc":"asc"}}):[]}applySortJoins(e,t,n,i){if(!t||!this.metadata)return;let o=Array.isArray(t)?t:t.split(",").map(a=>a.trim()).filter(Boolean),s=new Set;for(let a of o){let l=(a.startsWith("-")?a.slice(1):a).split(".");if(l.length<=1)continue;let f=n,c=i||n;for(let p=0;p<l.length-1;p++){let d=l[p],g=this.metadata?.tables?.get(f);if(!g)break;let y=g.relations?.find(b=>b.propertyName===d);if(!y)break;let h=y.targetTableName||y.targetTable,m=`__sort_${l.slice(0,p+1).join("_")}`;if(!s.has(m)){s.add(m);let b=y.foreignKeyColumn||V(y.propertyName),$=this.metadata?.tables?.get(h),w=$&&ne($)?.name||"id";e.leftJoin(`${h} as ${m}`,`${m}.${w}`,`${c}.${b}`)}f=h,c=m}}}toKnexSelect(e,t){let n=e.indexOf(" as ");if(n!==-1){let i=e.substring(0,n),o=e.substring(n+4),s=C(o,this.dbType),a=t?`${t}.${C(i,this.dbType)}`:C(i,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${t}.${C(e,this.dbType)} as ${C(e,this.dbType)}`):e}keyOf(e){return e==null?"":String(e)}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return ne(e)?.name||"id"}resolveOwnerFkKey(e){return e.relationName}resolveInverseFkField(e){let t=e.fkColumn;return!t&&e.mappedBy&&(t=V(e.mappedBy)),t||(t=V(e.targetTable)),t}resolveParentPk(e){return e&&ne(e)?.name||"id"}resolveFields(e,t){let{rootFields:n,subRelations:i}=et(e),o=[];if(n.includes("*")){let l=new Set;for(let f of t.relations||[])if(f.type==="many-to-one"||f.type==="one-to-one"&&!f.isInverse){let c=f.foreignKeyColumn||V(f.propertyName);c&&l.add(c)}for(let f of t.columns)l.has(f.name)||o.push(f.name);for(let f of t.relations||[])i.has(f.propertyName)||i.set(f.propertyName,["id"])}else for(let l of n){let f=t.columns.find(c=>c.name===l);f?o.push(f.name):t.relations?.find(p=>p.propertyName===l)&&!i.has(l)&&i.set(l,["id"])}let s=ne(t)?.name||"id";o.includes(s)||o.push(s),i.forEach((l,f)=>{let c=t.relations?.find(p=>p.propertyName===f);if(c&&(c.type==="many-to-one"||c.type==="one-to-one"&&!c.isInverse)){let p=c.foreignKeyColumn||V(c.propertyName);p&&o.push(`${p} as ${f}`)}});let a=[];return i.forEach((l,f)=>{let c=t.relations?.find(d=>d.propertyName===f);if(!c)return;let p=c.targetTableName||c.targetTable;p&&a.push({relationName:f,type:c.type,targetTable:p,fields:l,isInverse:c.isInverse,fkColumn:c.foreignKeyColumn,mappedBy:c.mappedBy,junctionTableName:c.junctionTableName,junctionSourceColumn:c.junctionSourceColumn,junctionTargetColumn:c.junctionTargetColumn})}),{isPkOnly:o.length===1&&o[0]===s&&a.length===0,nestedDescs:a,fetchSpec:{selectCols:o,pkCol:s}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?this.buildFilterTree(i.userFilter,e):null,s=i?.userSort?this.parseSortTokens(i.userSort,e):[],a=n.selectCols.map(u=>this.toKnexSelect(u));return Y(t,u=>{let l=this.knex(e).select(a).whereIn(n.pkCol,u);if(o&&X(l,o,{dbType:this.dbType,rootTable:e}),s.length>0){this.applySortJoins(l,i.userSort,e);for(let f of s)l.orderBy(f.column,f.order)}return l})}async fetchInverse(e,t,n,i,o){let s=t,a=i.selectCols.find(g=>g.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():i.selectCols.includes(t)||i.selectCols.push(t);let u=o?.userFilter?this.buildFilterTree(o.userFilter,e):null,l=o?.userSort?this.parseSortTokens(o.userSort,e):[],f=o?.userLimit,c=o?.userPage;if(f!==void 0&&f>0){let g=c?(c-1)*f:0,y=i.selectCols.map(b=>this.toKnexSelect(b)),h=await ge(n,async b=>{let $=this.knex(e).select(y).where(t,b);if(u&&X($,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins($,o.userSort,e),l.length>0)for(let w of l)$.orderBy(w.column,w.order);else $.orderBy(i.pkCol,"asc");return g>0&&$.offset(g),$.limit(f),$},te),m=[];for(let[b,$]of h.entries()){let w=n.find(S=>String(S)===b);for(let S of $)S[t]||(S[t]=w??b),m.push(S)}return{docs:m,groupKeyField:s}}let p=i.selectCols.map(g=>this.toKnexSelect(g));return{docs:await Y(n,g=>{let y=this.knex(e).select(p).whereIn(t,g);if(u&&X(y,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(y,o?.userSort,e),l.length>0)for(let h of l)y.orderBy(h.column,h.order);else y.orderBy(i.pkCol,"asc");return y}),groupKeyField:s}}postProcessInverseChild(e,t,n){n||delete e[t]}async fetchM2M(e,t,n,i,o){let s=this.resolveParentPk(n),a=e.map($=>$[s]).filter($=>$!=null);if(a.length===0)return{grouped:new Map,docs:[]};let u=t.junctionTableName,l=t.junctionSourceColumn,f=t.junctionTargetColumn;if(!u||!l||!f)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let c=t.userFilter?this.buildFilterTree(t.userFilter,t.targetTable):null,p=t.userSort?this.parseSortTokens(t.userSort,t.targetTable,"t"):[],d=t.userLimit,g=t.userPage;if(o.selectCols.length===1&&o.selectCols[0]===o.pkCol&&!c&&!d){let $=await Y(a,S=>this.knex(u).select([`${l} as __sourceId__`,`${f} as __targetId__`]).whereIn(l,S).orderBy(f,"asc")),w=new Map;for(let S of $){let k=this.keyOf(S.__sourceId__);w.has(k)||w.set(k,[]),w.get(k).push({[o.pkCol]:S.__targetId__})}return{grouped:w,docs:[]}}let h=o.selectCols.map($=>this.toKnexSelect($,"t"));if(d!==void 0&&d>0){let $=g?(g-1)*d:0,w=new Map;for(let v of a)w.set(this.keyOf(v),[]);let S=await ge(a,async v=>{let _=this.knex(u).join(`${t.targetTable} as t`,`${u}.${f}`,`t.${o.pkCol}`).select(h).where(`${u}.${l}`,v);if(c&&X(_,c,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(_,t.userSort,t.targetTable,"t"),p.length>0)for(let N of p)_.orderBy(N.column,N.order);else _.orderBy(`t.${o.pkCol}`,"asc");return $>0&&_.offset($),_.limit(d),_},te),k=[];for(let[v,_]of S.entries()){w.set(v,_);for(let N of _)k.push(N)}return{grouped:w,docs:k}}let m=await Y(a,$=>{let w=this.knex(u).join(`${t.targetTable} as t`,`${u}.${f}`,`t.${o.pkCol}`).select([`${u}.${l} as __sourceId__`,...h]).whereIn(`${u}.${l}`,$);if(c&&X(w,c,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(w,t.userSort,t.targetTable,"t"),p.length>0)for(let S of p)w.orderBy(S.column,S.order);else w.orderBy(`t.${o.pkCol}`,"asc");return w}),b=new Map;for(let $ of m){let w=$.__sourceId__;delete $.__sourceId__;let S=this.keyOf(w);b.has(S)||b.set(S,[]),b.get(S).push($)}return{grouped:b,docs:m}}}});var Hr={};Tn(Hr,{executeBatchFetches:()=>er});async function er(r,e,t,n,i=3,o=0,s,a="postgres",u,l){let f=new ut(r,a,u);await new ke(f,n,l).execute(e,t,i,o,s)}var tr=K(()=>{"use strict";tt();Zn()});var So={};Tn(So,{ALL_SUPPORTED_OPERATORS:()=>xt,AuthenticationException:()=>Oe,AuthorizationException:()=>Ee,BadRequestException:()=>x,BatchFetchEngine:()=>ke,BusinessLogicException:()=>Ie,CHUNKED_FETCH_CONCURRENCY:()=>Ln,ConfigurationException:()=>_t,DEEP_TO_MANY_DEFAULT_LIMIT:()=>Bn,DEFAULT_TIMEOUT_MS:()=>Kt,DOTTED_PATH_MAX_HOPS:()=>wn,DatabaseException:()=>be,DuplicateResourceException:()=>Ae,ErrorHandler:()=>je,ExecutorEngineService:()=>Je,ExternalServiceException:()=>mt,FIELD_OPERATORS:()=>ee,FileNotFoundException:()=>St,FileSizeExceededException:()=>Tt,FileUploadException:()=>wt,HttpException:()=>ve,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>Ut,InvalidTokenException:()=>yt,IsolatedExecutorService:()=>Ve,JoinRegistry:()=>oe,LOGICAL_OPERATORS:()=>In,MongoBatchAdapter:()=>nt,MongoQueryExecutor:()=>st,PER_PARENT_CONCURRENCY:()=>te,QueryBuilderService:()=>dt,QueryPlanner:()=>Q,ResourceNotFoundException:()=>Me,SchemaException:()=>bt,ScriptContractService:()=>Vt,ScriptExecutionException:()=>me,ScriptTimeoutException:()=>ye,ServiceUnavailableException:()=>Pe,SqlBatchAdapter:()=>ut,SqlQueryExecutor:()=>ft,TokenExpiredException:()=>ht,ValidationException:()=>Ne,WHERE_IN_CHUNK_SIZE:()=>$e,WorkerPool:()=>Ft,appendIsolatedExecutorRuntimeLog:()=>z,applyOperatorToMatch:()=>en,applyRelationFilters:()=>Qe,applyWhereToKnex:()=>ct,assertFieldOperatorValueIsClean:()=>nn,buildAggregateFilter:()=>ot,buildMongoCharFoldMapJson:()=>xn,buildMongoFoldTextSearchJs:()=>Gt,buildRelationSubquery:()=>Et,buildSqlWherePartsFromFieldAst:()=>jt,buildWhereClause:()=>le,camelToSnake:()=>mr,chunkedFetch:()=>Y,compileScriptSource:()=>qt,computeEngineTuning:()=>kn,createEnfyraKernel:()=>wo,dslOpToCompareOp:()=>tn,encodeMainThreadToIsolate:()=>Fn,escapeSqlValue:()=>Jr,executeBatchFetches:()=>er,executeMongoBatchFetches:()=>cn,expandFieldsToJoinsAndSelect:()=>Gn,getEffectiveCpuCount:()=>$n,getEffectiveMemoryBytes:()=>$t,getEngineTuning:()=>zt,getExecutableScript:()=>wi,getForeignKeyColumnName:()=>V,getIoAbortSignal:()=>fr,getJunctionColumnNames:()=>Rt,getJunctionTableName:()=>Ct,getPrimaryKeyColumn:()=>ne,getScriptLegacyField:()=>gi,getShortFkConstraintName:()=>hr,getShortFkName:()=>br,getShortIndexName:()=>_r,getShortPkName:()=>gr,hasAggregateQuery:()=>Wn,hasLogicalOperators:()=>he,isExecutableJavaScript:()=>mi,isScriptTable:()=>hi,mergeAggregateValue:()=>Ce,normalizeAggregateQuery:()=>it,normalizeFlowStepScriptConfig:()=>Ti,normalizeScriptLanguage:()=>yi,normalizeScriptPatch:()=>_i,normalizeScriptRecord:()=>bi,parseBatchFields:()=>et,parseFields:()=>un,parseFilter:()=>Te,perParentRun:()=>ge,quoteIdentifier:()=>C,quoteQualifiedIdentifier:()=>Re,resolveExecutableScript:()=>Si,rewriteFilterDenyingFields:()=>Xr,rewriteSortDroppingDenied:()=>Zr,scriptContractService:()=>Z,separateFilters:()=>G,snakeToCamel:()=>yr,throwUnsupportedFieldOperator:()=>De,validateDeepOptions:()=>nr,validateFilterShape:()=>U,whereToMongoFilter:()=>Ye});module.exports=oi(So);var Kt=3e4,Je=class{constructor(e){this.isolatedExecutorService=e.isolatedExecutorService}register(e,t){e.routeData.__codeBlocks||(e.routeData.__codeBlocks=[]),e.routeData.__codeBlocks.push(t)}async runBatch(e,t){let n=e.routeData.__codeBlocks||[];return n.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(n,e.routeData.context,t??Kt)}async run(e,t,n=Kt){return this.isolatedExecutorService.run(e,t,n)}};var Wt=class{constructor(e){this.context=e}log(e){console.log(this.format(e))}warn(e){console.warn(this.format(e))}error(e,t){console.error(this.format(e)),t&&console.error(t)}debug(e){process.env.DEBUG&&console.debug(this.format(e))}verbose(e){process.env.DEBUG&&console.debug(this.format(e))}format(e){let t=typeof e=="string"?e:JSON.stringify(e);return this.context?`[${this.context}] ${t}`:t}};var sr=require("async_hooks"),ar=ue(require("path")),lr=require("stream"),cr=require("worker_threads");var ye=class extends Error{constructor(t=0,n){let i=typeof t=="number"&&t>0?`${t}ms`:String(t||"configured timeout");super(`Script execution timed out after ${i}`);this.statusCode=408;this.errorCode="SCRIPT_TIMEOUT";this.name="ScriptTimeoutException",this.details={timeoutMs:t,scriptId:n}}},me=class extends Error{constructor(t,n,i){super(`Script execution failed: ${t}`);this.statusCode=400;this.errorCode="SCRIPT_EXECUTION_ERROR";this.name="ScriptExecutionException",this.details={scriptId:n,...i}}},j=class extends Error{constructor(t,n,i,o){super(t);this.statusCode=n;this.errorCode=i;this.name=this.constructor.name,this.details=o}},ve=class extends j{constructor(e,t,n){super(e,t,`HTTP_${t}`,n)}},Ie=class extends j{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},Ne=class extends j{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},Me=class extends j{constructor(e,t){super(t?`${e} with identifier '${t}' not found`:`${e} not found`,404,"RESOURCE_NOT_FOUND",{resource:e,identifier:t})}},Ae=class extends j{constructor(e,t,n){super(`${e} with ${t} '${n}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:n})}},Oe=class extends j{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},Ee=class extends j{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},ht=class extends j{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},yt=class extends j{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},be=class extends j{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},mt=class extends j{constructor(e,t,n){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:n})}},Pe=class extends j{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},bt=class extends j{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},_t=class extends j{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},wt=class extends j{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},St=class extends j{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},Tt=class extends j{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var je=class{static createException(e,t,n,i,o){if(e?.includes("$throw"))switch(e){case"$throw.businessLogic":return new Ie(n||"Bad request",o);case"$throw.validation":return new Ne(n||"Validation failed",o);case"$throw.notFound":return new Me(n||"Resource");case"$throw.duplicate":return new Ae(n||"Resource","field","value");case"$throw.unauthorized":return new Oe(n||"Unauthorized");case"$throw.forbidden":return new Ee(n||"Forbidden");case"$throw.tokenExpired":return new ht;case"$throw.invalidToken":return new yt;case"$throw.database":return new be(n||"Database error",o);case"$throw.dbQuery":return new be(n||"Query error",o);case"$throw.externalService":return new mt(n||"Service",n||"Error",o);case"$throw.serviceUnavailable":return new Pe(n||"Service");case"$throw.rateLimit":return new ve(n||"Rate limit exceeded",429);case"$throw.scriptError":return new me(n||"Script error",i,o);case"$throw.scriptTimeout":return new ye(o?.timeout||5e3,i);case"$throw.schema":return new bt(n||"Schema error",o);case"$throw.config":return new _t(n||"Configuration error",o);case"$throw.fileUpload":return new wt(n||"File upload error",o);case"$throw.fileNotFound":return new St(n||"File not found");case"$throw.fileSizeExceeded":return new Tt(o?.maxSize||"unknown",o?.actualSize||"unknown");case"$throw.400":return new Ie(n||"Bad request",o);case"$throw.401":return new Oe(n||"Authentication required");case"$throw.403":return new Ee(n||"Insufficient permissions");case"$throw.404":return new Me(n||"Resource");case"$throw.409":return new Ae(n||"Resource","field","value");case"$throw.422":return new Ne(n||"Validation failed",o);case"$throw.429":return new ve(n||"Rate limit exceeded",429);case"$throw.500":return new be(n||"Internal server error",o);case"$throw.503":return new Pe(n||"Service");default:return new me(n||"Unknown error",i)}if(t)switch(t){case 400:return new Ie(n||"Bad request",o);case 401:return new Oe(n||"Authentication required");case 403:return new Ee(n||"Insufficient permissions");case 404:return new Me(n||"Resource");case 409:return new Ae(n||"Resource","field","value");case 422:return new Ne(n||"Validation failed",o);case 429:return new ve(n||"Rate limit exceeded",429);case 500:return new be(n||"Internal server error",o);case 503:return new Pe(n||"Service");default:return new me(n||"Unknown error",i,o)}return new me(n||"Unknown error",i,o)}};var Qt=ue(require("fs")),Jt=ue(require("path")),Ut=Jt.join(process.cwd(),"test","logs","isolated-executor-runtime.log");function si(){return process.env.ISOLATED_EXECUTOR_FILE_LOG==="0"?!1:process.env.ISOLATED_EXECUTOR_FILE_LOG==="1"?!0:process.env.JEST_WORKER_ID!==void 0}var ai=si();function z(r){if(ai)try{let e=Jt.dirname(Ut);Qt.mkdirSync(e,{recursive:!0});let t=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...r})+`
|
|
2
|
+
`;Qt.appendFileSync(Ut,t)}catch{}}var _e=ue(require("os")),ze=ue(require("fs"));function $t(){try{let r=ze.readFileSync("/sys/fs/cgroup/memory.max","utf8").trim();if(r!=="max"){let e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<_e.totalmem())return e}}catch{}try{let r=ze.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes","utf8").trim(),e=parseInt(r,10);if(Number.isFinite(e)&&e>0&&e<_e.totalmem())return e}catch{}return _e.totalmem()}function $n(){let r=_e.availableParallelism?.()||_e.cpus()?.length||1;try{let e=ze.readFileSync("/sys/fs/cgroup/cpu.max","utf8").trim(),[t,n]=e.split(/\s+/);if(t!=="max"){let i=parseInt(t,10),o=parseInt(n,10);if(i>0&&o>0)return Math.max(1,Math.ceil(i/o))}}catch{}try{let e=parseInt(ze.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8").trim(),10),t=parseInt(ze.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_period_us","utf8").trim(),10);if(e>0&&t>0)return Math.max(1,Math.ceil(e/t))}catch{}return r}var li=.25,ci=2,ui=2048,fi=40,di=128,pi=32;function kn(r){let e=Math.max(1,Math.trunc(r.logicalCpuCount)||1),t=Math.max(1,r.totalMemoryBytes/(1024*1024)),n=Math.min(di,Math.max(fi,Math.round(t/pi))),i=t*li,o=Math.max(1,Math.floor(i/n)),s=Math.max(1,Math.min(e,2,o)),a=Math.min(256,Math.max(16,Math.floor(t/n/s))),u=t<ui?1:ci,l=Math.max(1,Math.min(u,Math.floor(i/(s*n))));return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:a,isolatePoolSize:l}}function zt(){return kn({logicalCpuCount:$n(),totalMemoryBytes:$t()})}var Le=ue(require("typescript")),kt={oauth_config_definition:"",route_handler_definition:"logic",pre_hook_definition:"code",post_hook_definition:"code",bootstrap_script_definition:"logic",websocket_definition:"connectionHandlerScript",websocket_event_definition:"handlerScript"};function gi(r){return Z.getLegacyField(r)}function hi(r){return Z.isScriptTable(r)}function yi(r){return Z.normalizeLanguage(r)}var Vt=class{getLegacyField(e){return kt[e]}isScriptTable(e){return e in kt}normalizeLanguage(e){return e==="javascript"?"javascript":"typescript"}compileSource(e,t){if(e==null||e==="")return null;let n=String(e),o=this.normalizeLanguage(t)==="javascript"?n:this.transpileTypeScript(n);return this.assertExecutableJavaScript(o),o}isExecutableJavaScript(e){if(!e)return!1;try{return this.assertExecutableJavaScript(e),!0}catch{return!1}}normalizeRecord(e,t){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let n={...t},i=this.getLegacyField(e);return i&&(n.sourceCode===void 0||n.sourceCode===null||n.sourceCode==="")&&n[i]!==void 0&&(n.sourceCode=n[i]),n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage),i&&i in n&&delete n[i],n}normalizePatch(e,t,n){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let i=this.getLegacyField(e),o=Object.prototype.hasOwnProperty.call(t,"sourceCode")||(i?Object.prototype.hasOwnProperty.call(t,i):!1),s=Object.prototype.hasOwnProperty.call(t,"scriptLanguage");if(!o&&!s)return t;let a=o?t.sourceCode??(i?t[i]:void 0):n?.sourceCode??(i&&n?n[i]:void 0),u=s?t.scriptLanguage:n?.scriptLanguage,l={...t};return o&&(l.sourceCode=a??null),l.scriptLanguage=this.normalizeLanguage(u),l.compiledCode=this.compileSource(a,l.scriptLanguage),i&&i in l&&delete l[i],l}getExecutableScript(e){return this.resolveExecutableScript(e).code}resolveExecutableScript(e){if(!e||typeof e!="object")return{code:null,compiledCode:null,shouldPersistCompiledCode:!1};if(typeof e.sourceCode=="string"&&e.sourceCode!==""){let n=this.compileSource(e.sourceCode,e.scriptLanguage);return{code:n,compiledCode:n,shouldPersistCompiledCode:n!==e.compiledCode}}let t=Object.keys(kt).find(n=>kt[n]in e);if(t){let n=e[kt[t]];if(typeof n=="string"&&n!==""){let i=this.compileSource(n,e.scriptLanguage);return{code:i,compiledCode:i,shouldPersistCompiledCode:i!==e.compiledCode}}}return typeof e.compiledCode=="string"&&e.compiledCode!==""&&this.isExecutableJavaScript(e.compiledCode)?{code:e.compiledCode,compiledCode:e.compiledCode,shouldPersistCompiledCode:!1}:{code:null,compiledCode:null,shouldPersistCompiledCode:!1}}normalizeFlowStepScriptConfig(e){if(!e||typeof e!="object")return e;let t=e.type;if(t!=="script"&&t!=="condition")return e;let n={...e},i=e.config;if(typeof i=="string")try{i=JSON.parse(i)}catch{return e}let o=i&&typeof i=="object"?i:{};n.sourceCode=n.sourceCode??o.sourceCode??o.code??null,n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage??o.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage);let s={...o};return delete s.sourceCode,delete s.scriptLanguage,delete s.compiledCode,delete s.code,{...n,config:typeof e.config=="string"?JSON.stringify(s):s}}repairContract(e){let t=this.normalizeLanguage(e?.scriptLanguage),n=e?.sourceCode??null,i=this.compileSource(n,t);return{sourceCode:n,scriptLanguage:t,code:i,compiledCode:i,shouldPersistCompiledCode:i!==e?.compiledCode}}transpileTypeScript(e){let t=Le.default.transpileModule(e,{compilerOptions:{target:Le.default.ScriptTarget.ES2022,module:Le.default.ModuleKind.CommonJS,importsNotUsedAsValues:Le.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),n=t.diagnostics?.find(i=>i.category===Le.default.DiagnosticCategory.Error);if(n)throw new Error(Le.default.flattenDiagnosticMessageText(n.messageText,`
|
|
3
3
|
`));return t.outputText.trimEnd()}assertExecutableJavaScript(e){e&&new Function(`return (async () => {
|
|
4
4
|
"use strict";
|
|
5
5
|
${e}
|
|
6
|
-
});`)}},Z=new zt;function Vt(r,e){return Z.compileSource(r,e)}function hi(r){return Z.isExecutableJavaScript(r)}function yi(r,e){return Z.normalizeRecord(r,e)}function mi(r,e,t){return Z.normalizePatch(r,e,t)}function bi(r){return Z.getExecutableScript(r)}function _i(r){return Z.resolveExecutableScript(r)}function wi(r){return Z.normalizeFlowStepScriptConfig(r)}var Ii=sr.join(__dirname,"execution/worker.js"),Ni=["Invalid or unexpected token","Unexpected identifier","Unexpected token","Missing initializer in const declaration","await is only valid"],lr=new or.AsyncLocalStorage;function cr(){return lr.getStore()}var kt=class{constructor(e,t,n,i,o,s,a,u=6e4){this.scriptPath=o;this.onCrash=s;this.onRotate=a;this.entries=[];this.waiting=[];this.cachedMemoryOk=!0;this.lastMemoryCheckMs=0;this.memorySampleIntervalMs=200;this.destroying=!1;this.entryCounter=0;this.max=e,this.effectiveMemory=t,this.rssCeiling=n,this.tasksCap=i,this.drainTimeoutMs=u;for(let l=0;l<e;l++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new ar.Worker(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let i=t.tasks.get(n.id);i&&(n.type==="result"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),n.contextStats&&(t.contextStats=n.contextStats),i.onResult(n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):i.onIoCall(n))}),e.on("exit",()=>{let n=t.draining,i=this.destroying;t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,s]of t.tasks)s.abortController.abort(),s.onResult({type:"result",success:!1,error:{message:i?"Worker terminated":"Worker crashed"}});t.tasks.clear();let o=this.entries.indexOf(t);o!==-1&&this.entries.splice(o,1),!n&&!i&&(this.onCrash&&this.onCrash(),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),this.entries.push(t),t}rotateEntry(e,t){if(e.draining)return;e.draining=!0;let n=Date.now()-e.spawnedAt;if(this.onRotate&&this.onRotate({reason:t,ageMs:n}),this.spawnEntry(),e.tasks.size===0){e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,e.worker.terminate()},this.drainTimeoutMs)}isMemoryAvailable(){let e=Date.now();return e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs&&(this.cachedMemoryOk=process.memoryUsage().rss/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e),this.cachedMemoryOk}findLeastBusy(){let e=null;for(let t of this.entries)t.draining||t.tasks.size<this.tasksCap&&(!e||t.tasks.size<e.tasks.size)&&(e=t);return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size===0||this.isMemoryAvailable())?Promise.resolve(e):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.tasks.set(t,n)}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&(e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(e&&(e.tasks.size===0||this.isMemoryAvailable()))this.waiting.shift()(e);else break}}terminateEntry(e){e.worker.terminate()}resize(e){for(this.max=Math.max(1,e);this.entries.length<this.max;)this.spawnEntry()}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,activeTasks:e.tasks.size,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}},ir=new Set(["$helpers","$cache","$repos","$req","$res","$socket","$logs","$throw","$trigger","$pkgs"]);function kn(r){if(r===void 0)return JSON.stringify({__e:"u"});try{return JSON.stringify({__e:"v",d:r},(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return JSON.stringify({__e:"v",d:{__serializationError:!0,message:"Result is not JSON-serializable"}})}}var ze=class r{constructor(e){this.logger=new Kt(r.name);this.effectiveMemory=St();this.isolationTuning=Jt();this.pool=new kt(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Ii,()=>{this.crashesTotal++,this.logger.warn("Worker crashed, replacement spawned")},({reason:e,ageMs:t})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${e} age=${Math.round(t/1e3)}s`)});this.ceiling=this.isolationTuning.maxConcurrentWorkers;this.prevCpuUsage=process.cpuUsage();this.prevCpuTime=process.hrtime.bigint();this.pressureTicks=0;this.recoveryTicks=0;this.taskCounter=0;this.taskDoneTotal=0;this.taskErrorTotal=0;this.taskTimeoutTotal=0;this.rotationsTotal=0;this.crashesTotal=0;this.taskDurationsMs=[];this.packageCacheService=e.packageCacheService,this.packageCdnLoaderService=e.packageCdnLoaderService,this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let t=process.memoryUsage().rss/this.effectiveMemory,n=process.hrtime.bigint(),i=process.cpuUsage(this.prevCpuUsage),o=Number(n-this.prevCpuTime)/1e3,s=o>0?(i.user+i.system)/o:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let a=this.pool.getMax(),u=this.pool.getWaitingCount(),l=t>.85||s>.7,f=t<.7&&s<.5,c=u>0,p=a;l?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(p=Math.max(1,a-1))):f&&c?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(p=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),p!==a&&(this.pool.resize(p),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${p} (rss=${Math.round(t*100)}% cpu=${Math.round(s*100)}% queue=${u})`))}createSnapshot(e){let t={$body:e.$body,$query:e.$query,$params:e.$params,$user:e.$user,$share:e.$share,$data:e.$data,$api:{request:e.$api?.request},$uploadedFile:e.$uploadedFile};for(let i of Object.keys(e)){if(!i.startsWith("$")||i in t||ir.has(i))continue;let o=this.cloneSnapshotValue(e[i]);o!==void 0&&(t[i]=o)}let n=e.$flow;if(n!=null)try{t.$flow=this.cloneSnapshotValue(n)??{}}catch{t.$flow={}}return t}cloneSnapshotValue(e){if(typeof e!="function")try{return JSON.parse(JSON.stringify(e,(t,n)=>{if(typeof n=="bigint")return String(n);if(typeof n!="function")return n}))}catch{return}}mergeCtxChanges(e,t){if(t){t.$body!==void 0&&(e.$body=t.$body),t.$query!==void 0&&(e.$query=t.$query),t.$params!==void 0&&(e.$params=t.$params),t.$data!==void 0&&(e.$data=t.$data),t.$error!==void 0&&(e.$error=t.$error),t.$statusCode!==void 0&&(e.$statusCode=t.$statusCode),t.$share!==void 0&&(e.$share=t.$share),t.$api!==void 0&&e.$api&&(t.$api.error&&(e.$api.error=t.$api.error),t.$api.response&&(e.$api.response=t.$api.response)),t.$flow!==void 0&&t.$flow!==null&&typeof t.$flow=="object"&&e.$flow!=null&&typeof e.$flow=="object"&&Object.assign(e.$flow,t.$flow);for(let[n,i]of Object.entries(t))n.startsWith("$")&&(n==="$body"||n==="$query"||n==="$params"||n==="$data"||n==="$error"||n==="$statusCode"||n==="$share"||n==="$api"||n==="$flow"||ir.has(n)||n==="$env"||(e[n]=i));delete e.$pkgs}}spawnAndExecute(e,t,n,i){return(async()=>{let o=await this.pool.dispatch(),s=`t_${++this.taskCounter}`,a=Date.now();return new Promise((u,l)=>{let f=!1,c=new AbortController,p=setTimeout(()=>{if(f)return;f=!0,c.abort(),this.pool.unregisterTask(o,s),this.taskTimeoutTotal++,z({event:"task_timeout",id:s,timeoutMs:i}),this.pool.terminateEntry(o);let d=new Error(`Script execution timed out after ${i}ms`);d.code="ERR_SCRIPT_EXECUTION_TIMEOUT",d.isTimeout=!0,l(d)},i+5e3);this.pool.registerTask(o,s,{abortController:c,onResult:d=>{if(!f)if(f=!0,clearTimeout(p),this.pool.unregisterTask(o,s),this.recordTaskDuration(Date.now()-a),d.success){this.taskDoneTotal++,z({event:"task_done",id:s,ok:!0});let g={value:d.value,valueAbsent:d.valueAbsent===!0,ctxChanges:d.ctxChanges};d.shortCircuit&&(g.shortCircuit=!0),u(g)}else{this.taskErrorTotal++,z({event:"task_done",id:s,ok:!1,message:d.error?.message});let g=new Error(d.error?.message||"Handler execution failed");g.statusCode=d.error?.statusCode,g.code=d.error?.code,g.details=d.error?.details,d.error?.stack&&(g.stack=d.error.stack),d.ctxChanges&&(g.ctxChanges=d.ctxChanges),l(g)}},onIoCall:d=>{if(f)return;let g=c.signal;d.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(d,n),o.worker,d.callId,g):d.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(d,n),o.worker,d.callId,g):d.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(d,n),o.worker,d.callId,g):d.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(d,n),o.worker,d.callId,g):d.type==="dispatchCall"&&this.handleIoCall(()=>this.execDispatchCall(d,n),o.worker,d.callId,g)}}),o.worker.postMessage({type:e,id:s,...t})})})()}async handleIoCall(e,t,n,i){if(!i?.aborted)try{let o=await(i?lr.run(i,e):e());if(i?.aborted)return;try{t.postMessage({type:"callResult",callId:n,result:kn(o)})}catch{}}catch(o){if(i?.aborted)return;try{let s={__userThrow:!0,message:o.message,statusCode:o.statusCode,code:o.errorCode??o.code,details:o.details,messages:o.messages};t.postMessage({type:"callError",callId:n,error:JSON.stringify(s)})}catch{}}}async execRepoCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$repos?.[e.table];if(!i||typeof i[e.method]!="function")throw new Error(`Repo method not found: ${e.table}.${e.method}`);return i[e.method](...n)}async execHelpersCall(e,t){let n=JSON.parse(e.argsJson),i=e.name.split("."),o=t?.$helpers;for(let s of i)o=o?.[s];if(typeof o!="function")throw new Error(`Helper not found: ${e.name}`);return o(...n)}async execSocketCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$socket?.[e.method];if(typeof i!="function")throw new Error(`Socket method not found: ${e.method}`);return i(...n)}async execCacheCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$cache?.[e.method];if(typeof i!="function")throw new Error(`Cache method not found: ${e.method}`);return i(...n)}async execDispatchCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$trigger;if(typeof i!="function")throw new Error("$trigger is not available");return i(...n)}isScriptParseFailure(e){let t=e.message||"";return Ni.some(n=>t.includes(n))}async run(e,t,n){let i=Math.max(1,Math.trunc(Number(n)||3e4)),o=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(o),a=this.createSnapshot(t);z({event:"isolated_run_start",timeoutMs:i,codeLen:e?.length??0});let u;try{let l={code:e,pkgSources:s,snapshot:a,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{u=await this.spawnAndExecute("execute",l,t,i)}catch(f){let c=f,p=Vt(e,"typescript")||"";if(!this.isScriptParseFailure(c)||p===e)throw f;z({event:"isolated_run_ts_retry",message:c.message}),u=await this.spawnAndExecute("execute",{...l,code:p},t,i)}}catch(l){let f=l;if(z({event:"isolated_run_error",message:f.message,code:f.code,isTimeout:!!f.isTimeout}),f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new he(i,e);let c=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw Pe.createException(void 0,c,f.message||"Unknown error",e,f.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),z({event:"isolated_run_ok"}),u.valueAbsent?void 0:u.value}async runBatch(e,t,n){let i=Math.max(1,Math.trunc(Number(n)||3e4)),o=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(o),a=this.createSnapshot(t);z({event:"isolated_batch_start",timeoutMs:i,blocks:e.length});let u;try{let l={codeBlocks:e,pkgSources:s,snapshot:a,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{u=await this.spawnAndExecute("executeBatch",l,t,i)}catch(f){let c=f,p=e.map(g=>({...g,code:Vt(g.code,"typescript")||""})),d=p.some((g,y)=>g.code!==e[y]?.code);if(!this.isScriptParseFailure(c)||!d)throw f;z({event:"isolated_batch_ts_retry",message:c.message}),u=await this.spawnAndExecute("executeBatch",{...l,codeBlocks:p},t,i)}}catch(l){let f=l;if(z({event:"isolated_batch_error",message:f.message,code:f.code,isTimeout:!!f.isTimeout}),f.ctxChanges&&this.mergeCtxChanges(t,f.ctxChanges),f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new he(i,"(batch execution)");let c=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw Pe.createException(void 0,c,f.message||"Unknown error","(batch execution)",f.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),z({event:"isolated_batch_ok"}),{value:u.valueAbsent?void 0:u.value,shortCircuit:u.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,s)=>o-s),i=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[i]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((i,o)=>i+o,0)/t.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),maxHeapRatio:Math.max(0,...e.workers.map(i=>i.lastHeapRatio||0))}}};var mn=require("node:fs"),qr=require("node:path");var Cn=require("mongodb");Ve();function Le(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function H(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!Le(r)&&(r.foreignKeyColumn||r.propertyName)||null}function W(r){return r.foreignKeyColumn||r.mappedBy||r.propertyName||null}function re(r){if(!r||typeof r!="object")return r;if(r instanceof Cn.ObjectId)return r.toString();if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return r.map(t=>re(t));if("buffer"in r&&r.buffer&&typeof r.buffer=="object"&&Object.keys(r.buffer).length===12)try{let t=r.buffer,n=Object.keys(t).sort((i,o)=>parseInt(i)-parseInt(o)).map(i=>t[i]);return new Cn.ObjectId(Buffer.from(n)).toString()}catch{}let e={};for(let[t,n]of Object.entries(r))e[t]=n&&typeof n=="object"&&!(n instanceof Buffer)?re(n):n;return e}function _e(r,e){if(e.type!=="many-to-many")return null;let t=e.targetTableName||e.targetTable;if(!t)return null;if(e.mappedBy){let a=t,u=e.mappedBy,l=r,f=e.junctionTableName||Ft(a,u,l);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:f,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:l};let c=Ct(a,u,l);return{junctionName:f,selfColumn:c.targetColumn,otherColumn:c.sourceColumn,owningTable:a,inverseTable:l}}let n=r,i=t,o=e.junctionTableName||Ft(n,e.propertyName,i);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:o,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:i};let s=Ct(n,e.propertyName,i);return{junctionName:o,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:i}}async function qt(r,e,t){if(!r)return{scalarFields:[],relations:[]};let n=r.tables?.get(e);if(!n)return{scalarFields:[],relations:[]};let i=new Map;for(let u of t)if(u==="*")i.has("")||i.set("",[]),i.get("").push(u);else if(u.includes(".")){let l=u.split("."),f=l[0],c=l.slice(1).join(".");i.has(f)||i.set(f,[]),i.get(f).push(c)}else n.relations?.some(f=>f.propertyName===u)?i.has(u)||i.set(u,["_id"]):(i.has("")||i.set("",[]),i.get("").push(u));let o=[],s=[],a=i.get("")||[];for(let u of a)if(u==="*"){if(n.columns)for(let l of n.columns)o.includes(l.name)||o.push(l.name);if(n.relations)for(let l of n.relations)i.has(l.propertyName)||i.set(l.propertyName,["_id"])}else n.columns?.some(f=>f.name===u)&&!o.includes(u)&&o.push(u);for(let[u,l]of i.entries()){if(u==="")continue;let f=n.relations?.find(y=>y.propertyName===u);if(!f)continue;let c="",p="",d=!1;f.type==="many-to-one"||f.type==="one-to-one"?Le(f)?(c="_id",p=W(f)||f.propertyName,d=!0):(c=H(f)||f.propertyName,p="_id",d=!1):f.type==="one-to-many"?(c="_id",p=W(f)||f.propertyName,d=!0):f.type==="many-to-many"&&(f.mappedBy?(c="_id",p=f.mappedBy,d=!0):(c=f.propertyName,p="_id",d=!1));let g=f.type==="one-to-many"||f.type==="many-to-many";s.push({propertyName:u,targetTable:f.targetTableName,localField:c,foreignField:p,type:g?"many":"one",isInverse:d,nestedFields:l})}return{scalarFields:o,relations:s}}var Gt=ce(require("fs")),xn=ce(require("path"));var Mi=new RegExp("\\p{Mark}","gu");function br(r){return r==null?"":String(r).normalize("NFKD").replace(Mi,"").toLowerCase()}function Rn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=br(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function Ht(){return`function() {
|
|
7
|
-
var M = ${
|
|
6
|
+
});`)}},Z=new Vt;function qt(r,e){return Z.compileSource(r,e)}function mi(r){return Z.isExecutableJavaScript(r)}function bi(r,e){return Z.normalizeRecord(r,e)}function _i(r,e,t){return Z.normalizePatch(r,e,t)}function wi(r){return Z.getExecutableScript(r)}function Si(r){return Z.resolveExecutableScript(r)}function Ti(r){return Z.normalizeFlowStepScriptConfig(r)}var Mi=ar.join(__dirname,"execution/worker.js"),Ai=["Invalid or unexpected token","Unexpected identifier","Unexpected token","Missing initializer in const declaration","await is only valid"],ur=new sr.AsyncLocalStorage;function fr(){return ur.getStore()}var Ft=class{constructor(e,t,n,i,o,s,a,u=6e4){this.scriptPath=o;this.onCrash=s;this.onRotate=a;this.entries=[];this.waiting=[];this.cachedMemoryOk=!0;this.lastMemoryCheckMs=0;this.memorySampleIntervalMs=200;this.destroying=!1;this.entryCounter=0;this.max=e,this.effectiveMemory=t,this.rssCeiling=n,this.tasksCap=i,this.drainTimeoutMs=u;for(let l=0;l<e;l++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new cr.Worker(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let i=t.tasks.get(n.id);i&&(n.type==="result"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),n.contextStats&&(t.contextStats=n.contextStats),i.onResult(n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):i.onIoCall(n))}),e.on("exit",()=>{let n=t.draining,i=this.destroying;t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,s]of t.tasks)s.abortController.abort(),s.onResult({type:"result",success:!1,error:{message:i?"Worker terminated":"Worker crashed"}});t.tasks.clear();let o=this.entries.indexOf(t);o!==-1&&this.entries.splice(o,1),!n&&!i&&(this.onCrash&&this.onCrash(),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),this.entries.push(t),t}rotateEntry(e,t){if(e.draining)return;e.draining=!0;let n=Date.now()-e.spawnedAt;if(this.onRotate&&this.onRotate({reason:t,ageMs:n}),this.spawnEntry(),e.tasks.size===0){e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,e.worker.terminate()},this.drainTimeoutMs)}isMemoryAvailable(){let e=Date.now();return e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs&&(this.cachedMemoryOk=process.memoryUsage().rss/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e),this.cachedMemoryOk}findLeastBusy(){let e=null;for(let t of this.entries)t.draining||t.tasks.size<this.tasksCap&&(!e||t.tasks.size<e.tasks.size)&&(e=t);return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size===0||this.isMemoryAvailable())?Promise.resolve(e):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.tasks.set(t,n)}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&(e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(e&&(e.tasks.size===0||this.isMemoryAvailable()))this.waiting.shift()(e);else break}}terminateEntry(e){e.worker.terminate()}resize(e){for(this.max=Math.max(1,e);this.entries.length<this.max;)this.spawnEntry()}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,activeTasks:e.tasks.size,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}},or=new Set(["$helpers","$cache","$repos","$req","$res","$socket","$logs","$throw","$trigger","$pkgs"]);function Fn(r){if(r===void 0)return JSON.stringify({__e:"u"});try{return JSON.stringify({__e:"v",d:r},(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return JSON.stringify({__e:"v",d:{__serializationError:!0,message:"Result is not JSON-serializable"}})}}var Ve=class r{constructor(e){this.logger=new Wt(r.name);this.effectiveMemory=$t();this.isolationTuning=zt();this.pool=new Ft(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Mi,()=>{this.crashesTotal++,this.logger.warn("Worker crashed, replacement spawned")},({reason:e,ageMs:t})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${e} age=${Math.round(t/1e3)}s`)});this.ceiling=this.isolationTuning.maxConcurrentWorkers;this.prevCpuUsage=process.cpuUsage();this.prevCpuTime=process.hrtime.bigint();this.pressureTicks=0;this.recoveryTicks=0;this.taskCounter=0;this.taskDoneTotal=0;this.taskErrorTotal=0;this.taskTimeoutTotal=0;this.rotationsTotal=0;this.crashesTotal=0;this.responseStreams=new Map;this.taskDurationsMs=[];this.packageCacheService=e.packageCacheService,this.packageCdnLoaderService=e.packageCdnLoaderService,this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let t=process.memoryUsage().rss/this.effectiveMemory,n=process.hrtime.bigint(),i=process.cpuUsage(this.prevCpuUsage),o=Number(n-this.prevCpuTime)/1e3,s=o>0?(i.user+i.system)/o:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let a=this.pool.getMax(),u=this.pool.getWaitingCount(),l=t>.85||s>.7,f=t<.7&&s<.5,c=u>0,p=a;l?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(p=Math.max(1,a-1))):f&&c?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(p=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),p!==a&&(this.pool.resize(p),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${p} (rss=${Math.round(t*100)}% cpu=${Math.round(s*100)}% queue=${u})`))}createSnapshot(e){let t={$body:e.$body,$query:e.$query,$params:e.$params,$user:e.$user,$share:e.$share,$data:e.$data,$api:{request:e.$api?.request},$uploadedFile:e.$uploadedFile};for(let i of Object.keys(e)){if(!i.startsWith("$")||i in t||or.has(i))continue;let o=this.cloneSnapshotValue(e[i]);o!==void 0&&(t[i]=o)}let n=e.$flow;if(n!=null)try{t.$flow=this.cloneSnapshotValue(n)??{}}catch{t.$flow={}}return t}cloneSnapshotValue(e){if(typeof e!="function")try{return JSON.parse(JSON.stringify(e,(t,n)=>{if(typeof n=="bigint")return String(n);if(typeof n!="function")return n}))}catch{return}}mergeCtxChanges(e,t){if(t){t.$body!==void 0&&(e.$body=t.$body),t.$query!==void 0&&(e.$query=t.$query),t.$params!==void 0&&(e.$params=t.$params),t.$data!==void 0&&(e.$data=t.$data),t.$error!==void 0&&(e.$error=t.$error),t.$statusCode!==void 0&&(e.$statusCode=t.$statusCode),t.$share!==void 0&&(e.$share=t.$share),t.$api!==void 0&&e.$api&&(t.$api.error&&(e.$api.error=t.$api.error),t.$api.response&&(e.$api.response=t.$api.response)),t.$flow!==void 0&&t.$flow!==null&&typeof t.$flow=="object"&&e.$flow!=null&&typeof e.$flow=="object"&&Object.assign(e.$flow,t.$flow);for(let[n,i]of Object.entries(t))n.startsWith("$")&&(n==="$body"||n==="$query"||n==="$params"||n==="$data"||n==="$error"||n==="$statusCode"||n==="$share"||n==="$api"||n==="$flow"||or.has(n)||n==="$env"||(e[n]=i));delete e.$pkgs}}spawnAndExecute(e,t,n,i){return(async()=>{let o=await this.pool.dispatch(),s=`t_${++this.taskCounter}`,a=Date.now();return new Promise((u,l)=>{let f=!1,c=new AbortController,p=setTimeout(()=>{if(f)return;f=!0,c.abort();let d=new Error(`Script execution timed out after ${i}ms`);this.cleanupResponseStream(s,d),this.pool.unregisterTask(o,s),this.taskTimeoutTotal++,z({event:"task_timeout",id:s,timeoutMs:i}),this.pool.terminateEntry(o),d.code="ERR_SCRIPT_EXECUTION_TIMEOUT",d.isTimeout=!0,l(d)},i+5e3);this.pool.registerTask(o,s,{abortController:c,onResult:d=>{if(!f)if(f=!0,clearTimeout(p),this.cleanupResponseStream(s),this.pool.unregisterTask(o,s),this.recordTaskDuration(Date.now()-a),d.success){this.taskDoneTotal++,z({event:"task_done",id:s,ok:!0});let g={value:d.value,valueAbsent:d.valueAbsent===!0,ctxChanges:d.ctxChanges};d.shortCircuit&&(g.shortCircuit=!0),u(g)}else{this.taskErrorTotal++,z({event:"task_done",id:s,ok:!1,message:d.error?.message});let g=new Error(d.error?.message||"Handler execution failed");g.statusCode=d.error?.statusCode,g.code=d.error?.code,g.details=d.error?.details,d.error?.stack&&(g.stack=d.error.stack),d.ctxChanges&&(g.ctxChanges=d.ctxChanges),this.cleanupResponseStream(s,g),l(g)}},onIoCall:d=>{if(f)return;let g=c.signal;d.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(d,n),o.worker,d.callId,g):d.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(d,n),o.worker,d.callId,g):d.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(d,n),o.worker,d.callId,g):d.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(d,n),o.worker,d.callId,g):d.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall(d,n),o.worker,d.callId,g):d.type==="resCall"&&this.handleIoCall(()=>this.execResCall(d,n),o.worker,d.callId,g)}}),o.worker.postMessage({type:e,id:s,...t})})})()}async handleIoCall(e,t,n,i){if(!i?.aborted)try{let o=await(i?ur.run(i,e):e());if(i?.aborted)return;try{t.postMessage({type:"callResult",callId:n,result:Fn(o)})}catch{}}catch(o){if(i?.aborted)return;try{let s={__userThrow:!0,message:o.message,statusCode:o.statusCode,code:o.errorCode??o.code,details:o.details,messages:o.messages};t.postMessage({type:"callError",callId:n,error:JSON.stringify(s)})}catch{}}}async execRepoCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$repos?.[e.table];if(!i||typeof i[e.method]!="function")throw new Error(`Repo method not found: ${e.table}.${e.method}`);return i[e.method](...n)}async execHelpersCall(e,t){let n=JSON.parse(e.argsJson),i=e.name.split("."),o=t?.$helpers;for(let s of i)o=o?.[s];if(typeof o!="function")throw new Error(`Helper not found: ${e.name}`);return o(...n)}async execSocketCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$socket?.[e.method];if(typeof i!="function")throw new Error(`Socket method not found: ${e.method}`);return i(...n)}async execCacheCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$cache?.[e.method];if(typeof i!="function")throw new Error(`Cache method not found: ${e.method}`);return i(...n)}async execDispatchCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$trigger;if(typeof i!="function")throw new Error("$trigger is not available");return i(...n)}async execResCall(e,t){if(e.method==="streamStart"){let s=JSON.parse(e.argsJson||"[]")[1]||{},a=t?.$res?.stream;if(typeof a!="function")throw new Error("Response method not found: stream");let u=new lr.PassThrough;return this.responseStreams.set(e.id,{stream:u}),a.call(t.$res,u,s),!0}if(e.method==="streamChunk"){let o=this.responseStreams.get(e.id);if(!o)throw new Error(`Response stream not found: ${e.id}`);let s=Buffer.from(e.chunk||"","base64");return o.stream.write(s)||await new Promise((a,u)=>{let l=()=>{c(),a()},f=p=>{c(),u(p)},c=()=>{o.stream.off("drain",l),o.stream.off("error",f)};o.stream.once("drain",l),o.stream.once("error",f)}),!0}if(e.method==="streamEnd"){let o=this.responseStreams.get(e.id);return o&&(o.stream.end(),this.responseStreams.delete(e.id)),!0}if(e.method==="streamError"){let o=this.responseStreams.get(e.id);if(o){let s=e.error?.message||"Response stream failed";o.stream.destroy(new Error(s)),this.responseStreams.delete(e.id)}return!0}let n=JSON.parse(e.argsJson||"[]"),i=t?.$res?.[e.method];if(typeof i!="function")throw new Error(`Response method not found: ${e.method}`);return i.apply(t.$res,n)}cleanupResponseStream(e,t){let n=this.responseStreams.get(e);n&&(this.responseStreams.delete(e),t?n.stream.destroy(t):n.stream.end())}isScriptParseFailure(e){let t=e.message||"";return Ai.some(n=>t.includes(n))}async run(e,t,n){let i=Math.max(1,Math.trunc(Number(n)||3e4)),o=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(o),a=this.createSnapshot(t);z({event:"isolated_run_start",timeoutMs:i,codeLen:e?.length??0});let u;try{let l={code:e,pkgSources:s,snapshot:a,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{u=await this.spawnAndExecute("execute",l,t,i)}catch(f){let c=f,p=qt(e,"typescript")||"";if(!this.isScriptParseFailure(c)||p===e)throw f;z({event:"isolated_run_ts_retry",message:c.message}),u=await this.spawnAndExecute("execute",{...l,code:p},t,i)}}catch(l){let f=l;if(z({event:"isolated_run_error",message:f.message,code:f.code,isTimeout:!!f.isTimeout}),f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new ye(i,e);let c=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw je.createException(void 0,c,f.message||"Unknown error",e,f.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),z({event:"isolated_run_ok"}),u.valueAbsent?void 0:u.value}async runBatch(e,t,n){let i=Math.max(1,Math.trunc(Number(n)||3e4)),o=await this.packageCacheService.getPackages(),s=this.packageCdnLoaderService.getPackageSources(o),a=this.createSnapshot(t);z({event:"isolated_batch_start",timeoutMs:i,blocks:e.length});let u;try{let l={codeBlocks:e,pkgSources:s,snapshot:a,timeoutMs:i,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize};try{u=await this.spawnAndExecute("executeBatch",l,t,i)}catch(f){let c=f,p=e.map(g=>({...g,code:qt(g.code,"typescript")||""})),d=p.some((g,y)=>g.code!==e[y]?.code);if(!this.isScriptParseFailure(c)||!d)throw f;z({event:"isolated_batch_ts_retry",message:c.message}),u=await this.spawnAndExecute("executeBatch",{...l,codeBlocks:p},t,i)}}catch(l){let f=l;if(z({event:"isolated_batch_error",message:f.message,code:f.code,isTimeout:!!f.isTimeout}),f.ctxChanges&&this.mergeCtxChanges(t,f.ctxChanges),f.isTimeout||f.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new ye(i,"(batch execution)");let c=f.statusCode??(typeof f.status=="number"?f.status:void 0);throw je.createException(void 0,c,f.message||"Unknown error","(batch execution)",f.details||{})}return this.mergeCtxChanges(t,u.ctxChanges||{}),z({event:"isolated_batch_ok"}),{value:u.valueAbsent?void 0:u.value,shortCircuit:u.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,s)=>o-s),i=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[i]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((i,o)=>i+o,0)/t.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),maxHeapRatio:Math.max(0,...e.workers.map(i=>i.lastHeapRatio||0))}}};var bn=require("node:fs"),Gr=require("node:path");var Rn=require("mongodb");qe();function Be(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function H(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!Be(r)&&(r.foreignKeyColumn||r.propertyName)||null}function W(r){return r.foreignKeyColumn||r.mappedBy||r.propertyName||null}function re(r){if(!r||typeof r!="object")return r;if(r instanceof Rn.ObjectId)return r.toString();if(r instanceof Date)return r.toISOString();if(Array.isArray(r))return r.map(t=>re(t));if("buffer"in r&&r.buffer&&typeof r.buffer=="object"&&Object.keys(r.buffer).length===12)try{let t=r.buffer,n=Object.keys(t).sort((i,o)=>parseInt(i)-parseInt(o)).map(i=>t[i]);return new Rn.ObjectId(Buffer.from(n)).toString()}catch{}let e={};for(let[t,n]of Object.entries(r))e[t]=n&&typeof n=="object"&&!(n instanceof Buffer)?re(n):n;return e}function we(r,e){if(e.type!=="many-to-many")return null;let t=e.targetTableName||e.targetTable;if(!t)return null;if(e.mappedBy){let a=t,u=e.mappedBy,l=r,f=e.junctionTableName||Ct(a,u,l);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:f,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:a,inverseTable:l};let c=Rt(a,u,l);return{junctionName:f,selfColumn:c.targetColumn,otherColumn:c.sourceColumn,owningTable:a,inverseTable:l}}let n=r,i=t,o=e.junctionTableName||Ct(n,e.propertyName,i);if(e.junctionSourceColumn&&e.junctionTargetColumn)return{junctionName:o,selfColumn:e.junctionSourceColumn,otherColumn:e.junctionTargetColumn,owningTable:n,inverseTable:i};let s=Rt(n,e.propertyName,i);return{junctionName:o,selfColumn:s.sourceColumn,otherColumn:s.targetColumn,owningTable:n,inverseTable:i}}async function Ht(r,e,t){if(!r)return{scalarFields:[],relations:[]};let n=r.tables?.get(e);if(!n)return{scalarFields:[],relations:[]};let i=new Map;for(let u of t)if(u==="*")i.has("")||i.set("",[]),i.get("").push(u);else if(u.includes(".")){let l=u.split("."),f=l[0],c=l.slice(1).join(".");i.has(f)||i.set(f,[]),i.get(f).push(c)}else n.relations?.some(f=>f.propertyName===u)?i.has(u)||i.set(u,["_id"]):(i.has("")||i.set("",[]),i.get("").push(u));let o=[],s=[],a=i.get("")||[];for(let u of a)if(u==="*"){if(n.columns)for(let l of n.columns)o.includes(l.name)||o.push(l.name);if(n.relations)for(let l of n.relations)i.has(l.propertyName)||i.set(l.propertyName,["_id"])}else n.columns?.some(f=>f.name===u)&&!o.includes(u)&&o.push(u);for(let[u,l]of i.entries()){if(u==="")continue;let f=n.relations?.find(y=>y.propertyName===u);if(!f)continue;let c="",p="",d=!1;f.type==="many-to-one"||f.type==="one-to-one"?Be(f)?(c="_id",p=W(f)||f.propertyName,d=!0):(c=H(f)||f.propertyName,p="_id",d=!1):f.type==="one-to-many"?(c="_id",p=W(f)||f.propertyName,d=!0):f.type==="many-to-many"&&(f.mappedBy?(c="_id",p=f.mappedBy,d=!0):(c=f.propertyName,p="_id",d=!1));let g=f.type==="one-to-many"||f.type==="many-to-many";s.push({propertyName:u,targetTable:f.targetTableName,localField:c,foreignField:p,type:g?"many":"one",isInverse:d,nestedFields:l})}return{scalarFields:o,relations:s}}var Yt=ue(require("fs")),vn=ue(require("path"));var Oi=new RegExp("\\p{Mark}","gu");function wr(r){return r==null?"":String(r).normalize("NFKD").replace(Oi,"").toLowerCase()}function xn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=wr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function Gt(){return`function() {
|
|
7
|
+
var M = ${xn()};
|
|
8
8
|
function foldStr(s) {
|
|
9
9
|
if (s == null) return '';
|
|
10
10
|
s = String(s);
|
|
@@ -49,5 +49,5 @@ ${e}
|
|
|
49
49
|
}
|
|
50
50
|
}
|
|
51
51
|
return true;
|
|
52
|
-
}`}var _r="mongo-fold-text-search.body.txt",qe=null;function Ai(){let r=[xn.join(__dirname,_r),xn.join(process.cwd(),"dist","kernel","query","utils",_r)];for(let e of r)try{if(Gt.existsSync(e))return Gt.readFileSync(e,"utf8")}catch{}return null}function Yt(){if(qe!==null)return qe;let r=Ai();return r?(qe=r,qe):(qe=Ht(),qe)}var we=require("mongodb");function B(r,e,t,n){if(t==="_id"){if(n instanceof we.ObjectId)return n;if(typeof n=="string")try{return new we.ObjectId(n)}catch{return n}return n}let i=r?.tables?.get(e);if(!i){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}return n}if(!i.columns){if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}return n}let o=i.columns.find(s=>s.name===t);if(!o){if(i.relations?.find(a=>a.propertyName===t||a.foreignKeyColumn===t)&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new we.ObjectId(n)}catch{return n}return n}if(n==null)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;case"uuid":if(typeof n=="string")try{return new we.ObjectId(n)}catch{return n}return n;default:return n}}var Xt="__mongoFoldTextTriples";function Oi(r){return r==="_id"?"$_id":`$${r}`}function He(r,e,t,n){let i=Oi(e),o=r[Xt]??[];o.push({ref:i,needle:t,mode:n}),r[Xt]=o}function Ei(r){let e=r[Xt];if(delete r[Xt],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:Yt(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}function Ge(r,e,t,n){let i={},o=n==="mongodb"||!n;for(let s of e){let a=s.field.includes(".")?s.field.split(".").pop()??s.field:s.field,u=t||s.field.split(".")[0]||"";o&&a==="id"&&(a="_id");let l=B(r,u,a,s.value);switch(s.operator){case"=":i[a]=l;break;case"!=":i[a]={$ne:l};break;case">":i[a]={$gt:l};break;case"<":i[a]={$lt:l};break;case">=":i[a]={$gte:l};break;case"<=":i[a]={$lte:l};break;case"like":i[a]={$regex:l.replace(/%/g,".*"),$options:"i"};break;case"in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(m=>m.trim()):[f]);let c=f.map(m=>B(r,u,a,m));i[a]={$in:c};break;case"not in":let p=s.value;Array.isArray(p)||(p=typeof p=="string"&&p.includes(",")?p.split(",").map(m=>m.trim()):[p]);let d=p.map(m=>B(r,u,a,m));i[a]={$nin:d};break;case"is null":i[a]=null;break;case"is not null":i[a]={$ne:null};break;case"_contains":He(i,a,String(l),"contains");break;case"_starts_with":He(i,a,String(l),"starts");break;case"_ends_with":He(i,a,String(l),"ends");break;case"_between":let g=s.value;if(typeof g=="string"&&(g=g.split(",").map(m=>m.trim())),Array.isArray(g)&&g.length===2){let m=B(r,u,a,g[0]),b=B(r,u,a,g[1]);i[a]={$gte:m,$lte:b}}break;case"_is_null":let y=l===!0||l==="true";i[a]=y?{$eq:null}:{$ne:null};break;case"_is_not_null":let h=l===!0||l==="true";i[a]=h?{$ne:null}:{$eq:null};break}}return Ei(i),i}function wr(r,e,t){let i=r?.tables?.get?.(e)?.columns?.find(o=>o.name===t);return i?i.isNullable!==!1:!0}function Zt(r,e,t,n,i,o){switch(i){case"_contains":He(e,n,String(o),"contains");break;case"_starts_with":He(e,n,String(o),"starts");break;case"_ends_with":He(e,n,String(o),"ends");break;case"_eq":e[n]=B(r,t,n,o);break;case"_neq":{let c=B(r,t,n,o);wr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:c}})):e[n]={$ne:c};break}case"_in":{let c=o;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(d=>d.trim()):[c]);let p=c.map(d=>B(r,t,n,d));e[n]={$in:p};break}case"_not_in":case"_nin":let s=o;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(c=>c.trim()):[s]);let a=s.map(c=>B(r,t,n,c));wr(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:B(r,t,n,o)};break;case"_gte":e[n]={$gte:B(r,t,n,o)};break;case"_lt":e[n]={$lt:B(r,t,n,o)};break;case"_lte":e[n]={$lte:B(r,t,n,o)};break;case"_is_null":let u=o===!0||o==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let l=o===!0||o==="true";e[n]=l?{$ne:null}:{$eq:null};break;case"_between":let f=o;if(typeof f=="string"&&(f=f.split(",").map(c=>c.trim())),Array.isArray(f)&&f.length===2){let c=B(r,t,n,f[0]),p=B(r,t,n,f[1]);e[n]={$gte:c,$lte:p}}break}}var Mn=require("mongodb");function ie(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(ie(i,e))return!0}}else if(t==="_not"){if(ie(n,e))return!0}else if(e.has(t))return!0;return!1}function G(r,e){if(!r||typeof r!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},n={},i=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(r)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(i.has(s))if(typeof a=="object"&&a!==null){let u=Object.keys(a);if(u.some(f=>f.startsWith("_"))){let f=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&f.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let o=ie(r,i);return{fieldFilters:t,relationFilters:n,hasRelations:o}}vt();It();var sn="__mongoFoldTextTriples";function De(r,e){if(!r)return{};let t={};return rn(r,t,e),on(t),t}function fe(r,e,t){if(!e)return{};let n=new oe,{node:i}=Te(e,t,r,n);return De(i,{metadata:r,rootTable:t})}function rn(r,e,t){switch(r.kind){case"true":return;case"false":Nt(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let i=r.children.map(o=>{let s={};return rn(o,s,t),on(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}Nt(e,...i);return}case"or":{let i=r.children.map(s=>{let a={};return rn(s,a,t),on(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={};rn(r.child,n,t),on(n);let i=e.$nor;e.$nor=i?[...i,n]:[n];return}case"compare":Ui(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 Ui(r,e,t){let n=r.field.fieldName;if(n==="id"&&(n="_id"),r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let i=o=>B(t.metadata,t.rootTable,n,o);switch(r.op){case"eq":se(e,n,i(r.value));return;case"neq":{let o=i(r.value);kr(t,n)?Nt(e,{[n]:{$ne:null}},{[n]:{$ne:o}}):se(e,n,{$ne:o});return}case"gt":se(e,n,{$gt:i(r.value)});return;case"gte":se(e,n,{$gte:i(r.value)});return;case"lt":se(e,n,{$lt:i(r.value)});return;case"lte":se(e,n,{$lte:i(r.value)});return;case"in":{let o=Fr(r.value).map(i);se(e,n,{$in:o});return}case"not_in":{let o=Fr(r.value).map(i);kr(t,n)?Nt(e,{[n]:{$ne:null}},{[n]:{$nin:o}}):se(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&&se(e,n,{$gte:i(o[0]),$lte:i(o[1])});return}case"is_null":se(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":In(e,n,String(r.value),"contains");return;case"starts_with":In(e,n,String(r.value),"starts");return;case"ends_with":In(e,n,String(r.value),"ends");return}}function se(r,e,t){r[e]===void 0?r[e]=t:(Nt(r,{[e]:r[e]},{[e]:t}),delete r[e])}function Nt(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function kr(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(i=>i.name===e);return n?n.isNullable!==!1:!0}function Fr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function Qi(r){return r==="_id"?"$_id":`$${r}`}function In(r,e,t,n){let i=Qi(e),o=r[sn]??[];o.push({ref:i,needle:t,mode:n}),r[sn]=o}function on(r){let e=r[sn];if(delete r[sn],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:Yt(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}async function de(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return fe(t,r,e);let o=new Set((i.relations||[]).map(l=>l.propertyName));if(!ie(r,o))return fe(t,r,e);if(r._and&&Array.isArray(r._and)){let f=(await Promise.all(r._and.map(c=>de(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:f.length===1?f[0]:{$and:f}}if(r._or&&Array.isArray(r._or)){let f=(await Promise.all(r._or.map(c=>de(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:{$or:f}}if(r._not){let l=await de(r._not,e,t,n);return!l||Object.keys(l).length===0?{}:{$nor:[l]}}let{fieldFilters:s,relationFilters:a}=G(r,i),u=[];if(s&&Object.keys(s).length>0){let l=fe(t,s,e);l&&Object.keys(l).length>0&&u.push(l)}if(a&&Object.keys(a).length>0)for(let[l,f]of Object.entries(a)){let c=await Ji(l,f,e,i,t,n);c&&Object.keys(c).length>0&&u.push(c)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function Ji(r,e,t,n,i,o){let s=(n.relations||[]).find(l=>l.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=i?.tables?.get(a);return!a||!u?{}:s.type==="many-to-one"||s.type==="one-to-one"?zi(e,s,r,a,u,i,o):s.type==="one-to-many"?Vi(e,s,t,a,u,i,o):s.type==="many-to-many"?qi(e,s,t,a,u,i,o):{}}async function zi(r,e,t,n,i,o,s){let a=H(e)||t,u=On(r),l=En(u);if(l!==null)return l?{[a]:null}:{[a]:{$ne:null}};let f=Rr(u);if(f!==null){let g=Pn(f.value);if(f.op==="eq")return{[a]:g};if(f.op==="neq")return{[a]:{$ne:g}};if(f.op==="in")return{[a]:{$in:g}};if(f.op==="not_in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]}}let c=await An(u,n,i,o,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);return d.length===0?{[a]:null}:{[a]:{$in:d}}}async function Vi(r,e,t,n,i,o,s){let a=W(e)||t,u=On(r),l=En(u);if(l!==null){let p=await Cr(s,n,a,{});return l?p.length===0?{}:{_id:{$nin:p}}:p.length===0?{__impossible__:!0}:{_id:{$in:p}}}let f=await An(u,n,i,o,s);if(!f||Object.keys(f).length===0)return{};let c=await Cr(s,n,a,f);return c.length===0?{__impossible__:!0}:{_id:{$in:c}}}async function qi(r,e,t,n,i,o,s){let a=_e(t,e);if(!a)return{};let u=On(r),l=En(u);if(l!==null){let y=await Nn(s,a,n,null);return l?y.length===0?{}:{_id:{$nin:y}}:y.length===0?{__impossible__:!0}:{_id:{$in:y}}}let f=Rr(u);if(f!==null){let y=Pn(f.value),h=Array.isArray(y)?y:[y],m=await Nn(s,a,n,{_id:{$in:h}});return m.length===0?{__impossible__:!0}:{_id:{$in:m}}}let c=await An(u,n,i,o,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(Boolean);if(d.length===0)return{__impossible__:!0};let g=await Nn(s,a,n,{_id:{$in:d}});return g.length===0?{__impossible__:!0}:{_id:{$in:g}}}async function An(r,e,t,n,i){let o=new Set((t?.relations??[]).map(s=>s.propertyName));return ie(r,o)?de(r,e,n,i):fe(n,r,e)}async function Cr(r,e,t,n){let i=await r.collection(e).find(n,{projection:{[t]:1}}).toArray(),o=new Set,s=[];for(let a of i){let u=a[t];if(u==null)continue;let l=String(u);o.has(l)||(o.add(l),s.push(u))}return s}async function Nn(r,e,t,n){let i=null;n&&t&&(i=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(f=>f._id).filter(Boolean));let o=i?{[e.otherColumn]:{$in:i}}:{},s=await r.collection(e.junctionName).find(o,{projection:{[e.selfColumn]:1}}).toArray(),a=new Set,u=[];for(let l of s){let f=l[e.selfColumn];if(f==null)continue;let c=String(f);a.has(c)||(a.add(c),u.push(f))}return u}function On(r){return r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===1&&r.id&&typeof r.id=="object"?r.id:r}function En(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 Pn(r){if(Array.isArray(r))return r.map(e=>Pn(e));if(typeof r!="string")return r;try{return new Mn.ObjectId(r)}catch{return r}}function Rr(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof Mn.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 Mt(r,e,t,n){let i=await qt(r,e,t),o=[],s={},a={};if(n&&typeof n=="object")for(let[d,g]of Object.entries(n))if(typeof g=="object"&&g!==null){let y=Object.keys(g)[0];y&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(y)?s[d]=g:a[d]=g}else s[d]=g;if(Object.keys(s).length>0){let d={};for(let[g,y]of Object.entries(s))if(typeof y=="object"&&y!==null)for(let[h,m]of Object.entries(y))Zt(r,d,e,g,h,m);else d[g]=y;Object.keys(d).length>0&&o.push({$match:d})}let l=r?.tables?.get(e)?.relations||[],f=[];for(let[d,g]of Object.entries(a))if(!i.relations.some(h=>h.propertyName===d)){let h=l.find(m=>m.propertyName===d);if(h){let m="",b="";if(h.type==="many-to-one"||h.type==="one-to-one")m=H(h)||h.propertyName,b="_id";else if(h.type==="one-to-many")m="_id",b=W(h)||h.propertyName;else if(h.type==="many-to-many")continue;let $=h.type==="one-to-many"||h.type==="many-to-many";f.push({propertyName:d,targetTable:h.targetTableName,localField:m,foreignField:b,type:$?"many":"one",nestedFields:[]})}}let c=[...i.relations,...f];for(let d of c){let g=a[d.propertyName],y=d.nestedFields&&d.nestedFields.length>0?await Mt(r,d.targetTable,d.nestedFields,g):g?await Mt(r,d.targetTable,["_id"],g):[];d.type==="one"&&y.length>0&&y.push({$limit:1}),o.push({$lookup:{from:d.targetTable,localField:d.localField,foreignField:d.foreignField,as:d.propertyName,pipeline:y.length>0?y:void 0}}),d.type==="one"&&(o.push({$unwind:{path:`$${d.propertyName}`,preserveNullAndEmptyArrays:!0}}),g&&(Xe(g)||o.push({$match:{[d.propertyName]:{$ne:null}}})))}let p=l.filter(d=>!c.some(g=>g.propertyName===d.propertyName));if(i.scalarFields.length>0||i.relations.length>0||p.length>0){let d={_id:1};for(let y of i.scalarFields)d[y]=1;for(let y of c)d[y.propertyName]=1,y.type==="one"&&y.localField&&y.localField!==y.propertyName&&(d[y.localField]=1);if(t.includes("*"))for(let y of p){if(y.type==="one-to-many"||y.type==="many-to-many")continue;y.type==="many-to-many"?d[y.propertyName]={$map:{input:`$${y.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[y.propertyName]={$cond:{if:{$ne:[`$${y.propertyName}`,null]},then:{_id:`$${y.propertyName}`},else:null}}}o.push({$project:d})}return o}async function xr(r,e,t,n,i){let o=r?.tables?.get(t),s=o?.relations||[],a=o?.columns||[],u=s.filter(f=>!i.some(c=>c.propertyName===f.propertyName)),l=n.length===a.length||n.length===0&&i.length===0;if(u.length>0||!l){let f={_id:1};for(let c of n)f[c]=1;for(let c of i)f[c.propertyName]=1,c.type==="one"&&c.localField&&c.localField!==c.propertyName&&(f[c.localField]=1);for(let c of u){if(c.type==="one-to-many"||c.type==="many-to-many")continue;c.type==="many-to-many"?f[c.propertyName]={$map:{input:`$${c.propertyName}`,as:"item",in:{_id:"$$item"}}}:f[c.propertyName]={$cond:{if:{$ne:[`$${c.propertyName}`,null]},then:{_id:`$${c.propertyName}`},else:null}}}e.push({$project:f})}}function Xe(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>Xe(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>Xe(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>Xe(e));if("_not"in r)return Xe(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||Xe(t)))return!0}return!1}et();var At=require("mongodb");et();an();var tt=class{constructor(e,t,n){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.pkField="_id"}normalizeMetadata(){return this.metadata?this.metadata.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortFromTokens(e){let t={};for(let n of this.parseSortTokens(e)){let i=n.field.split(".");if(i.length===1)t[i[0]]=n.order;else{let o=`__sort_${i.slice(0,-1).join("_")}`;t[`${o}.${i[i.length-1]}`]=n.order}}return Object.keys(t).length>0?t:void 0}parseSortTokens(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).map(n=>{let i=n.startsWith("-");return{field:i?n.slice(1):n,order:i?-1:1}}):[]}hasDottedSort(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).some(n=>(n.startsWith("-")?n.slice(1):n).includes(".")):!1}buildSortAggregatePipeline(e,t,n){let i=Array.isArray(n)?n:n.split(",").map(l=>l.trim()).filter(Boolean),o=[{$match:t}],s=new Set;for(let l of i){let c=(l.startsWith("-")?l.slice(1):l).split(".");if(c.length<=1)continue;let p=e;for(let d=0;d<c.length-1;d++){let g=c[d],y=this.normalizeMetadata()?.tables?.get(p);if(!y)break;let h=y.relations?.find($=>$.propertyName===g);if(!h)break;let m=h.targetTableName||h.targetTable,b=`__sort_${c.slice(0,d+1).join("_")}`;if(!s.has(b)){s.add(b);let $=H(h)||h.propertyName,w=d===0?null:`__sort_${c.slice(0,d).join("_")}`,T=w?`${w}.${$}`:$;o.push({$lookup:{from:m,localField:T,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}p=m}}let a=this.buildSortFromTokens(n);a&&o.push({$sort:a});let u={};for(let l of s)u[l]=0;return Object.keys(u).length>0&&o.push({$project:u}),o}toObjectId(e){try{return typeof e=="string"?new At.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof At.ObjectId||t instanceof At.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 At.ObjectId||typeof e=="object"&&typeof e.toHexString=="function"?e.toHexString():String(e)}buildScalarRef(e){return{[this.pkField]:e}}getTargetPkField(e){return this.pkField}resolveOwnerFkKey(e){return e.localField||e.fkColumn||e.relationName}resolveInverseFkField(e){return e.foreignField?e.foreignField:e.mappedBy?e.mappedBy:e.relationName}resolveParentPk(e){return this.pkField}resolveFields(e,t){let{rootFields:n,subRelations:i}=Ze(e),o={},s=!1;if(n.includes("*")){s=!0;for(let p of t.relations||[])i.has(p.propertyName)||i.set(p.propertyName,["_id"])}else for(let p of n){let d=t.columns.find(g=>g.name===p);d?o[d.name]=1:t.relations?.find(y=>y.propertyName===p)&&!i.has(p)&&i.set(p,["_id"])}i.forEach((p,d)=>{let g=t.relations?.find(y=>y.propertyName===d);g&&(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse)&&(s||(o[H(g)||g.propertyName]=1))}),s||(o._id=1);let a=[];i.forEach((p,d)=>{let g=t.relations?.find(b=>b.propertyName===d);if(!g)return;let y=g.targetTableName||g.targetTable;if(!y)return;let h,m;g.type==="many-to-one"||g.type==="one-to-one"?Le(g)?(h="_id",m=W(g)||g.propertyName):(h=H(g)||g.propertyName,m="_id"):g.type==="one-to-many"?(h="_id",m=W(g)||g.propertyName):g.type==="many-to-many"&&(g.isInverse?(h="_id",m=g.mappedBy):(h=g.propertyName,m="_id")),a.push({relationName:d,type:g.type,targetTable:y,fields:p,isInverse:g.isInverse,fkColumn:g.foreignKeyColumn,mappedBy:g.mappedBy,junctionTableName:g.junctionTableName,junctionSourceColumn:g.junctionSourceColumn,junctionTargetColumn:g.junctionTargetColumn,localField:h,foreignField:m})});let u=!s&&Object.keys(o).length===1&&o._id===1&&a.length===0,l=this.fieldRenamesByTable?.get(t.name)??[],f=[];if(!s&&l.length>0)for(let p of l)o[p.newName]===1&&o[p.oldName]!==1&&(o[p.oldName]=1,f.push(p.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:o,pendingRenames:l,hiddenFields:f}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?fe(this.normalizeMetadata(),i.userFilter,e):null,s=this.buildSortFromTokens(i?.userSort),a=await Y(t,u=>{let l={_id:{$in:u}};o&&Object.keys(o).length>0&&Object.assign(l,o);let f={projection:n.projection};return s&&(f.sort=s),this.db.collection(e).find(l,f).toArray()});return this.applyReadFallback(a,n)}async fetchInverse(e,t,n,i,o){let s=i.projection?{...i.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let a=n.filter(h=>h!=null).map(h=>this.toObjectId(h)),u=o?.userFilter?fe(this.normalizeMetadata(),o.userFilter,e):null,l=o?.userLimit,f=o?.userPage,c=this.hasDottedSort(o?.userSort);if(l!==void 0&&l>0){let h=f?(f-1)*l:0,m=await pe(a,async $=>{let w={[t]:$};if(u&&Object.keys(u).length>0&&Object.assign(w,u),c){let _=this.buildSortAggregatePipeline(e,w,o.userSort);h>0&&_.push({$skip:h}),_.push({$limit:l}),s&&_.push({$project:s});let N=await this.db.collection(e).aggregate(_).toArray();return this.applyReadFallback(N,i)}let k={sort:this.buildSortFromTokens(o?.userSort)||{_id:1}};s&&(k.projection=s);let v=this.db.collection(e).find(w,k);return h>0&&v.skip(h),v.limit(l),this.applyReadFallback(await v.toArray(),i)},te),b=[];for(let[$,w]of m.entries()){let T=a.find(k=>this.keyOf(k)===$);for(let k of w)k[t]||(k[t]=T??$),b.push(k)}return{docs:b,groupKeyField:t}}if(s&&(s[t]=1),c){let h=[],m=await pe(a,async b=>{let $={[t]:b};u&&Object.keys(u).length>0&&Object.assign($,u);let w=this.buildSortAggregatePipeline(e,$,o.userSort);s&&w.push({$project:s});let T=await this.db.collection(e).aggregate(w).toArray();return this.applyReadFallback(T,i)},te);for(let b of m.values())for(let $ of b)h.push($);return{docs:h,groupKeyField:t}}let p={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(p,u);let d=this.buildSortFromTokens(o?.userSort)||{_id:1},g={projection:s,sort:d},y=await Y(a,h=>this.db.collection(e).find({[t]:{$in:h},...u||{}},g).toArray());return{docs:this.applyReadFallback(y,i),groupKeyField:t}}postProcessInverseChild(e,t,n){n||delete e[t]}async fetchM2M(e,t,n,i,o){let s=n?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=_e(s,{type:"many-to-many",propertyName:t.relationName,targetTable:t.targetTable,mappedBy:t.isInverse?t.mappedBy:void 0,junctionTableName:t.junctionTableName,junctionSourceColumn:t.junctionSourceColumn,junctionTargetColumn:t.junctionTargetColumn});if(!a)throw new Error(`Failed to resolve junction info for ${s}.${t.relationName}`);let u=e.map(w=>w._id).filter(w=>w!=null),l=new Map;for(let w of e)l.set(this.keyOf(w._id),[]);if(u.length===0)return{grouped:l,docs:[]};let f=await Y(u,w=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:w}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray());if(f.length===0)return{grouped:l,docs:[]};let c=t.userFilter?fe(this.normalizeMetadata(),t.userFilter,t.targetTable):null,p=t.userLimit,d=t.userPage;if(p!==void 0&&p>0){let w=d?(d-1)*p:0,T=await pe(u,async v=>{let N=(await this.db.collection(a.junctionName).find({[a.selfColumn]:v},{projection:{_id:0,[a.otherColumn]:1}}).toArray()).map(L=>L[a.otherColumn]).filter(L=>L!=null);if(N.length===0)return[];let I={_id:{$in:N}};if(c&&Object.keys(c).length>0&&Object.assign(I,c),this.hasDottedSort(t.userSort)){let L=this.buildSortAggregatePipeline(t.targetTable,I,t.userSort);w>0&&L.push({$skip:w}),L.push({$limit:p}),o.projection&&L.push({$project:o.projection});let S=await this.db.collection(t.targetTable).aggregate(L).toArray();return this.applyReadFallback(S,o)}let D={sort:this.buildSortFromTokens(t.userSort)||{_id:1}};o.projection&&(D.projection=o.projection);let P=this.db.collection(t.targetTable).find(I,D);return w>0&&P.skip(w),P.limit(p),this.applyReadFallback(await P.toArray(),o)},te),k=[];for(let[v,_]of T.entries()){l.set(v,_);for(let N of _)k.push(N)}return{grouped:l,docs:k}}let g=new Set,y=[];for(let w of f){let T=w[a.otherColumn];if(T==null)continue;let k=this.keyOf(T);g.has(k)||(g.add(k),y.push(T))}let h=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1&&!c,m=[],b=new Map;if(h)m=y.map(w=>({_id:w})),this.sortDocsByPk(m);else{let w={_id:{$in:y}};c&&Object.keys(c).length>0&&Object.assign(w,c);let T=this.hasDottedSort(t.userSort),k;if(T){let v=this.buildSortAggregatePipeline(t.targetTable,w,t.userSort);o.projection&&v.push({$project:o.projection}),k=await this.db.collection(t.targetTable).aggregate(v).toArray()}else{let v=this.buildSortFromTokens(t.userSort)||{_id:1},_=this.projectionWithSortFields(o.projection,t.userSort),N={sort:v};_.projection&&(N.projection=_.projection),k=await Y(y,I=>this.db.collection(t.targetTable).find({_id:{$in:I},...c||{}},N).toArray()),t.userSort?this.sortDocsInMemory(k,t.userSort):this.sortDocsByPk(k),this.removeHiddenFields(k,_.hiddenFields)}m=this.applyReadFallback(k,o)}for(let w of m)b.set(this.keyOf(w._id),w);let $=new Map;for(let w of f){let T=this.keyOf(w[a.selfColumn]),k=this.keyOf(w[a.otherColumn]);b.has(k)&&($.has(k)||$.set(k,[]),$.get(k).push(T))}for(let w of m){let T=$.get(this.keyOf(w._id))||[];for(let k of T)l.get(k)?.push(w)}return{grouped:l,docs:m}}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 ln(r,e,t,n,i=3,o=0,s,a,u,l){let f=await l?.getActiveFieldRenamesByTable?.(),c=new tt(r,a,f);await new $e(c,n,u).execute(e,t,i,o,s)}async function Bn(r,e,t){let n=[],{db:i,metadata:o,dbType:s,debugLog:a}=t,u=o?.tables?.get(e.table),l=new Set((u?.relations??[]).map(_=>_.propertyName)),f=!!e.mongoRawFilter&&!!o&&ie(e.mongoRawFilter,l),c=e.plan,p=c?.filterTree&&!c.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&o&&f){let _=await de(e.mongoRawFilter,e.table,o,i);_&&Object.keys(_).length>0&&n.push({$match:_})}else if(p){let _=De(c.filterTree,{metadata:o,rootTable:e.table});Object.keys(_).length>0&&n.push({$match:_})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let _=Ge(o,e.where,e.table,s);n.push({$match:_})}let d=e.plan,y=d?d.hasRelationSort:e.sort?.some(_=>{if(!_.field.includes("."))return!1;let N=_.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(I=>I.propertyName===N)??!1})??!1,h=()=>d?.sortItems?Zi(d.sortItems):e.sort?Xi(e.sort):null,m=d?.sortItems?Hi(d.sortItems):[],b=()=>{!d||m.length===0||Gi(n,e.table,d.sortItems,o)},$=()=>{m.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(m.map(_=>[_,0]))})};if(!e.mongoFieldsExpanded){b();let _=h();if(_&&n.push({$sort:_}),e.mongoCountOnly?n.push({$count:"count"}):(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit})),$(),e.select){let I={};for(let O of e.select)I[O]=1;n.push({$project:I})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let N=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:N,pipeline:n}:{results:vr(N),pipeline:n}}let{scalarFields:w,relations:T}=e.mongoFieldsExpanded;if(!y){b();let _=h();_&&n.push({$sort:_}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}let k=[];for(let _ of T)if(e.sort?.some(I=>I.field.startsWith(`${_.propertyName}.`))){let I=e.mongoRawFilter?.[_.propertyName];if(_.nestedFields&&_.nestedFields.length>0){let M=await Mt(o,_.targetTable,_.nestedFields??[],I);_.type==="one"&&M.length>0&&M.push({$limit:1}),n.push({$lookup:{from:_.targetTable,localField:_.localField,foreignField:_.foreignField,as:_.propertyName,pipeline:M.length>0?M:void 0}})}else if(I){let M=await Mt(o,_.targetTable,["_id"],I);_.type==="one"&&M.length>0&&M.push({$limit:1}),n.push({$lookup:{from:_.targetTable,localField:_.localField,foreignField:_.foreignField,as:_.propertyName,pipeline:M.length>0?M:void 0}})}else n.push({$lookup:{from:_.targetTable,localField:_.localField,foreignField:_.foreignField,as:_.propertyName}});_.type==="one"&&(n.push({$unwind:{path:`$${_.propertyName}`,preserveNullAndEmptyArrays:!0}}),I&&(nt(I)||n.push({$match:{[_.propertyName]:{$ne:null}}})))}else k.push(_);if(y){b();let _=h();_&&n.push({$sort:_}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}await xr(o,n,e.table,w,[...T]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let v=await r.aggregate(n).toArray();if(e.mongoCountOnly)return{results:v,pipeline:n};if(k.length>0&&v.length>0){let _=e.deep||{},N=k.map(O=>{let D=o?.tables?.get(e.table)?.relations?.find(S=>S.propertyName===O.propertyName),P=_[O.propertyName],L=P?.fields!=null?Array.isArray(P.fields)?P.fields:String(P.fields).split(",").map(S=>S.trim()).filter(Boolean):O.nestedFields&&O.nestedFields.length>0?O.nestedFields:["_id"];return{relationName:O.propertyName,type:D?.type,targetTable:O.targetTable,fields:L,isInverse:D?.isInverse,mappedBy:D?.mappedBy,junctionTableName:D?.junctionTableName,localField:O.localField,foreignField:O.foreignField,userFilter:P?.filter,userSort:P?.sort,userLimit:P?.limit!==void 0?Number(P.limit):void 0,userPage:P?.page!==void 0?Number(P.page):void 0,nestedDeep:P?.deep}}),I=Yi(o);I&&await ln(i,v,N,I,3,0,e.table,o,void 0,t.mongoPhysicalMigrationService)}return{results:vr(v),pipeline:n}}function Dn(r){return`__sort_count_${r.relationName||r.field}`}function Hi(r){return r.filter(e=>e.function==="count").map(Dn)}function Gi(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="count")continue;let a=s.relationMeta,u=s.relationName||s.field,l=a?.targetTableName||a?.targetTable,f=Dn(s);if(!(!a||!l)){if(a.type==="one-to-many"){let c=W(a)||u;r.push({$lookup:{from:l,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${c}`,"$$localId"]}}},{$count:"value"}],as:f}}),r.push({$addFields:{[f]:{$ifNull:[{$arrayElemAt:[`$${f}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let c=_e(e,a);if(!c)continue;r.push({$lookup:{from:c.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${c.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:f}}),r.push({$addFields:{[f]:{$ifNull:[{$arrayElemAt:[`$${f}.value`,0]},0]}}})}}}}function Yi(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 Xi(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 Zi(r){let e={};for(let t of r){let n=t.function==="count"?Dn(t):t.joinId!==null?t.fullPath:t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function nt(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>nt(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>nt(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>nt(e));if("_not"in r)return nt(r._not);for(let[e,t]of Object.entries(r)){if(t===null){if(e==="_eq"||e==="$eq")return!0;continue}if(typeof t=="object"&&("_is_null"in t&&(t._is_null===!0||t._is_null==="true")||"_eq"in t&&t._eq===null||"$eq"in t&&t.$eq===null||nt(t)))return!0}return!1}function vr(r){return r.map(re)}function Ir(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(eo(o,i,e));return{scalarFields:t,relations:n}}function eo(r,e,t){let n=e.relations?.find(l=>l.propertyName===r.propertyName),i,o,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&Le(n)?(i="_id",o=W(n)||r.propertyName,s=!0):(i=n&&H(n)||r.propertyName,o="_id",s=!1):r.relationType==="one-to-many"?(i="_id",o=n&&W(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=Nr(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:i,foreignField:o,type:a?"many":"one",isInverse:s,nestedFields:u}}function Nr(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=Nr(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let i of n)e.push(`${t.propertyName}.${i}`)}return e}Ye();It();vt();function cn(r,e,t,n){let i={rootTable:e,nodes:[]};if(!r||r.length===0)return i;let o=t?.tables?.get(e);if(!o)return i;let s=o.columns?.some(c=>c.name==="_id"&&c.isPrimary),a=o.columns?.some(c=>c.name==="id"),u=s&&!a?"_id":"id",l=new Map,f=[];for(let c of r){let p=c==="id"?u:c;if(p==="*")f.push("*");else if(p.includes(".")){let d=p.indexOf("."),g=p.substring(0,d),y=p.substring(d+1);if(!o.relations?.some(m=>m.propertyName===g))continue;l.has(g)||l.set(g,[]),l.get(g).push(y)}else if(o.relations?.some(g=>g.propertyName===p))l.has(p)||l.set(p,[u]);else{if(!o.columns?.some(y=>y.name===p))continue;f.push(p)}}if(f.includes("*")){i.nodes.push({kind:"wildcard"});for(let c of o.relations||[])l.has(c.propertyName)||l.set(c.propertyName,[u])}else for(let c of f)i.nodes.push({kind:"scalar",name:c});for(let[c,p]of l.entries()){let d=o.relations?.find(h=>h.propertyName===c);if(!d)continue;let g=d.targetTableName||d.targetTable,y={kind:"relation",propertyName:c,joinId:null,relationType:d.type,isInverse:!!d.isInverse,targetTable:g,children:Mr(p,g,t)};if(d.type==="many-to-one"||d.type==="one-to-one"){let h=n.registerWithParent(e,c,t,"left",null,"data");y.joinId=h}i.nodes.push(y)}return i}function Mr(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let i=n.columns?.some(f=>f.name==="_id"&&f.isPrimary),o=n.columns?.some(f=>f.name==="id"),s=i&&!o?"_id":"id",a=new Map,u=[];for(let f of r){let c=f==="id"?s:f;if(c==="*")u.push("*");else if(c.includes(".")){let p=c.indexOf("."),d=c.substring(0,p),g=c.substring(p+1);if(!n.relations?.some(h=>h.propertyName===d))continue;a.has(d)||a.set(d,[]),a.get(d).push(g)}else if(n.relations?.some(d=>d.propertyName===c))a.has(c)||a.set(c,[s]);else{if(!n.columns?.some(g=>g.name===c))continue;u.push(c)}}let l=[];if(u.includes("*")){l.push({kind:"wildcard"});for(let f of n.relations||[])a.has(f.propertyName)||a.set(f.propertyName,[s])}else for(let f of u)l.push({kind:"scalar",name:f});for(let[f,c]of a.entries()){let p=n.relations?.find(g=>g.propertyName===f);if(!p)continue;let d=p.targetTableName||p.targetTable;l.push({kind:"relation",propertyName:f,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:d,children:Mr(c,d,t)})}return l}ue();ue();var to=new Set(["_and","_or","_not"]);function Ar(r,e){return r?.tables?.get(e)??null}function no(r,e,t){return Ar(r,e)?.columns?.find(n=>n.name===t)}function Or(r,e,t){return Ar(r,e)?.relations?.find(n=>n.propertyName===t)}function Er(r,e,t,n){if(no(r,e,t)?.isEncrypted===!0)throw new x(`Encrypted field '${t}' on '${e}' cannot be used for ${n}.`)}function Ke(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){for(let n of r)Ke(n,e,t);return}for(let[n,i]of Object.entries(r)){if(to.has(n)){Ke(i,e,t);continue}if(n.startsWith("_"))continue;let o=Or(t,e,n);if(o){let s=o.targetTableName||o.targetTable;s&&Ke(i,s,t);continue}Er(t,e,n,"filter")}}}function un(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||o.startsWith("_count("))continue;let s=o.split("."),a=e;for(let u=0;u<s.length;u++){let l=s[u];if(u===s.length-1){Er(t,a,l,"sort");break}let c=Or(t,a,l);if(!c)break;a=c.targetTableName||c.targetTable||a}}}var Q=class{plan(e){let{tableName:t,fields:n,filter:i,sort:o,page:s,limit:a,meta:u,metadata:l,dbType:f}=e,c=l?.tables?.get(t),p=new oe,d=this.parseFields(n),g=null;d&&c&&(g=cn(d,t,l,p));let y=!1,h=null;if(i&&c){Ke(i,t,l);let O=Te(i,t,l,p);h=O.node,y=O.hasRelationFilters}let m=this.parseSort(o);c&&un(m,t,l);let b=[],$=!1;for(let O of m){let M=O.startsWith("-"),D=M?O.substring(1):O,P=M?"desc":"asc";if(c){let L=this.parseRelationCountSort(t,c,D);if(L){b.push({joinId:null,field:D,direction:P,fullPath:D,function:"count",relationName:L.relationName,relationMeta:L.relationMeta});continue}this.assertLocalSortField(t,c,D)}b.push({joinId:null,field:D,direction:P,fullPath:D})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let w=this.parseLimit(a),T=this.parsePage(s),k=T!==void 0&&w!==void 0?(T-1)*w:void 0,v=this.parseMeta(u),_=v.includes("totalCount")||v.includes("*"),N=v.includes("filterCount")||v.includes("*"),I=p.getAll();return{table:t,dbType:f,rawFields:d,rawFilter:i??null,joins:I,sortItems:b,limit:w,offset:k,needsTotalCount:_,needsFilterCount:N,hasRelationFilters:y,hasRelationSort:$,filterTree:h,fieldTree:g}}parseFields(e){if(e)return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):e.split(",").map(t=>t.trim()).filter(Boolean)}parseSort(e){return e?(Array.isArray(e)?e:e.split(",")).map(n=>n.trim()).filter(Boolean):[]}parseLimit(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;if(!Number.isNaN(t))return t<0?0:t}parsePage(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;return Number.isNaN(t)?void 0:t}parseMeta(e){return e?Array.isArray(e)?e:e.split(",").map(t=>t.trim()).filter(Boolean):[]}assertLocalSortField(e,t,n){if(n.includes("."))throw new x(`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 x(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationCountSort(e,t,n){if(!n.startsWith("_count"))return null;let i=n.match(/^_count\(([^)]+)\)$/);if(!i)throw new x(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName).`);let o=i[1].trim();if(!o||o.includes("."))throw new x(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let s=t.relations?.find(a=>a.propertyName===o);if(!s)throw new x(`Sort relation '${o}' does not exist on '${e}'.`);if(s.type!=="one-to-many"&&s.type!=="many-to-many")throw new x(`Sort function '_count(${o})' is only supported for list relations on '${e}'.`);return{relationName:o,relationMeta:s}}registerSortJoinChain(e,t,n,i,o){let s=e.indexOf(".");if(s===-1)return null;let a=e.slice(0,s),u=e.slice(s+1),l=n?.tables?.get(t);if(!l)return null;let f=l.relations?.find(d=>d.propertyName===a);if(!f||f.type!=="many-to-one"&&f.type!=="one-to-one")return null;let c=i.registerWithParent(t,a,n,"left",o,"sort");if(!c)return null;if(!u.includes("."))return{lastJoinId:c,field:u};let p=f.targetTableName||f.targetTable;return this.registerSortJoinChain(u,p,n,i,c)}};ue();xt();var ro=new Set(["count","sum","avg","min","max","countRecords"]),io=new Set(["int","integer","bigint","float","double","decimal","numeric","real","number"]),oo=new Set(["_and","_or","_not"]);function ke(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function E(r,e){let t=r.replace(/^aggregate\./,"");throw new x(e,{path:r,aggregate:{[t]:e}})}function so(r){return typeof r!="string"?!1:io.has(r.toLowerCase())}function Pr(r){return Object.keys(r).length===0}function ao(r,e,t){return r===!0?{}:(r==null&&E(t,`aggregate.${e} condition must be true or an object`),ke(r)||E(t,`aggregate.${e} condition must be true or an object`),r)}function lo(r,e,t){let n=r?.tables?.get(e);return n||E(t,`Table "${e}" metadata is not available`),n}function jr(r,e){let t=r?.targetTableName??r?.targetTable;return(typeof t!="string"||t.length===0)&&E(e,"aggregate.countRecords relation target is not available"),t}function fn(r,e,t,n){let i=lo(t,e,n);for(let[o,s]of Object.entries(r)){if(o==="_and"||o==="_or"){Array.isArray(s)||E(n,`aggregate.countRecords ${o} condition must be an array`);for(let f of s)ke(f)||E(n,`aggregate.countRecords ${o} items must be objects`),fn(f,e,t,n);continue}if(o==="_not"){ke(s)||E(n,"aggregate.countRecords _not condition must be an object"),fn(s,e,t,n);continue}(o.startsWith("_")||oo.has(o))&&E(n,`Unsupported aggregate.countRecords condition key "${o}"`);let a=i.columns?.find(f=>f.name===o),u=i.relations?.find(f=>f.propertyName===o);if(!a&&!u&&E(n,`Unknown aggregate.countRecords field or relation "${o}" on table "${e}"`),ke(s)||E(n,`aggregate.countRecords condition for "${o}" must be an object`),a){for(let f of Object.keys(s))ee.has(f)||E(n,`aggregate.countRecords condition for "${o}" only supports field operators`);continue}let l=jr(u,n);fn(s,l,t,n)}}function Kn(r){return ke(r)&&Object.keys(r).length>0}function rt(r,e,t){if(!Kn(r))return[];ke(r)||E("aggregate","aggregate must be an object");let n=t?.tables?.get(e);n||E("aggregate",`Table "${e}" metadata is not available`);let i=[];for(let[o,s]of Object.entries(r)){let a=`aggregate.${o}`;(!o||typeof o!="string")&&E("aggregate","aggregate field name must be a non-empty string"),ke(s)||E(a,"aggregate field config must be an object");let u=o,l=a,f=n.columns?.find(d=>d.name===o),c=n.relations?.find(d=>d.propertyName===o);!f&&!c&&E(l,`Unknown aggregate field or relation "${o}" on table "${e}"`);let p=Object.entries(s).filter(([d])=>d!=="as");p.length===0&&E(l,"aggregate field must define at least one operation");for(let[d,g]of p){ro.has(d)||E(l,`Unsupported aggregate operation "${d}"`);let y=ao(g,d,l);if(c&&d!=="countRecords"&&E(l,`aggregate.${d} is not supported on relation "${o}"; use countRecords`),f&&d==="countRecords"&&E(l,`aggregate.countRecords requires a relation, but "${o}" is a field`),f&&(d==="sum"||d==="avg")&&!so(f.type)&&E(l,`aggregate.${d} requires a numeric field, but "${o}" is "${f.type}"`),f)for(let h of Object.keys(y))ee.has(h)||E(l,`aggregate.${d} condition for "${o}" only supports field operators`);if(c&&d==="countRecords"){let h=jr(c,l);fn(y,h,t,l)}i.push({field:o,outputKey:u,path:l,op:d,condition:y})}}return i}function it(r,e){let t=[];return ke(r)&&!Pr(r)&&t.push(r),Pr(e.condition)||t.push({[e.field]:e.condition}),t.length===0?{}:t.length===1?t[0]:{_and:t}}function Fe(r,e,t){r[e.outputKey]??={},r[e.outputKey][e.op]=t}var ot=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.debugLog=[];this.lastBuiltPipeline=null;this.db=e.getDb()}async execute(e){if(this.metadata=e.metadata,this.dbType=e.dbType||"mongodb",!e.plan){let p=new Q;e={...e,plan:p.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:"mongodb"})}}let t=e.debugLog||[];this.debugLog=t;let n={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};if(e.pipeline&&(n.pipeline=e.pipeline),e.fields&&(Array.isArray(e.fields)?n.fields=e.fields:typeof e.fields=="string"&&(n.fields=e.fields.split(",").map(p=>p.trim()))),e.filter&&(U(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let p=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(d=>d.trim());n.sort=p.map(d=>{let g=d.trim();return g.startsWith("-")?{field:g.substring(1),direction:"desc"}:{field:g,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let p=typeof e.page=="string"?parseInt(e.page,10):e.page,d=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(p-1)*d,n.limit=d}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let i=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(p=>p.trim()).filter(Boolean),o=0,s=0;(i.includes("totalCount")||i.includes("*"))&&(o=await this.mongoService.collection(e.tableName).countDocuments({}));let a=this.metadata?.tables?.get(e.tableName),u=new Set((a?.relations??[]).map(p=>p.propertyName)),l=!!n.mongoRawFilter&&ie(n.mongoRawFilter,u);if((i.includes("filterCount")||i.includes("*"))&&!l){let p=this.mongoService.collection(e.tableName),d=e.plan?.filterTree?De(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await p.countDocuments(d)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let f=await this.selectLegacy(n);if(e.debugMode){let p=this.lastBuiltPipeline??[],d;try{d=await this.db.collection(e.tableName).aggregate(p).explain()}catch(g){d={error:String(g)}}return{pipeline:p,explain:d}}if(l&&(i.includes("filterCount")||i.includes("*"))){let p={...n,mongoCountOnly:!0},d=await this.selectLegacy(p);s=d.length>0?d[0].count:0}let c=await this.executeAggregate(n,e.filter);return{data:f,...(i.length>0||c)&&{meta:{...i.includes("totalCount")||i.includes("*")?{totalCount:o}:{},...i.includes("filterCount")||i.includes("*")?{filterCount:s}:{},...c?{aggregate:c}:{}}}}}async selectLegacy(e){let t=[];if(e.fields&&e.fields.length>0){let s=e.plan;if(s?.fieldTree?e.mongoFieldsExpanded=Ir(s.fieldTree,this.metadata):(console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await qt(this.metadata,e.table,e.fields)),this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let a=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:a.scalarFields},t=a.hiddenFields}}e.where&&(e.where=e.where.map(s=>s.field.includes(".")?s:{...s,field:`${e.table}.${s.field}`}));let n=this.db.collection(e.table);if(e.pipeline)return this.debugLog&&this.debugLog.push({type:"MongoDB Custom Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(e.pipeline))}),(await n.aggregate(e.pipeline).toArray()).map(re);let{results:i,pipeline:o}=await Bn(n,e,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=o,this.mongoPhysicalMigrationService?await this.mongoPhysicalMigrationService.applyReadFallback(e.table,i,t):i}async executeAggregationPipeline(e,t){let{results:n,pipeline:i}=await Bn(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=i,n}async executeAggregate(e,t){let n=rt(e.aggregate,e.table,e.metadata);if(n.length===0)return;let i={},o=this.db.collection(e.table);for(let s of n){let a=it(t,s);U(a,e.table,e.metadata);let l=new Q().plan({tableName:e.table,filter:a,metadata:e.metadata,dbType:"mongodb"});if(s.op==="countRecords"){let p=await this.executeRelationCountRecords(e,t,s);Fe(i,s,p);continue}let f=l.hasRelationFilters?await de(a,e.table,e.metadata,this.db):l.filterTree?De(l.filterTree,{metadata:e.metadata,rootTable:e.table}):{},c;if(s.op==="count")c=await o.countDocuments(f);else{let[{value:p}={value:null}]=await o.aggregate([{$match:f},{$group:{_id:null,value:{[`$${s.op}`]:`$${s.field}`}}}]).toArray();c=p??0}Fe(i,s,c)}return i}async executeRelationCountRecords(e,t,n){let o=e.metadata?.tables?.get(e.table)?.relations?.find(f=>f.propertyName===n.field),s=o?.targetTableName||o?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!o||!s||!a)return 0;let u=await this.resolveMatchFilter(e.table,t,e.metadata),l=await this.resolveMatchFilter(s,n.condition,e.metadata);if(o.type==="one-to-many"){let c=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(p=>p._id).filter(p=>p!=null);return c.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{[o.foreignKeyColumn]:{$in:c}}]})}if(o.type==="many-to-many"){let f=_e(e.table,o);if(!f)return 0;let p=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(y=>y!=null);if(p.length===0)return 0;let g=(await this.db.collection(f.junctionName).find({[f.selfColumn]:{$in:p}},{projection:{[f.otherColumn]:1}}).toArray()).map(y=>y[f.otherColumn]).filter(y=>y!=null);return g.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:g}}]})}if(o.type==="many-to-one"||o.type==="one-to-one"){let f=o.foreignKeyColumn||`${n.field}Id`,p=(await this.db.collection(e.table).find(u,{projection:{[f]:1}}).toArray()).map(d=>d[f]).filter(d=>d!=null);return p.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:p}}]})}return 0}async resolveMatchFilter(e,t,n){if(!t||Object.keys(t).length===0)return{};U(t,e,n);let o=new Q().plan({tableName:e,filter:t,metadata:n,dbType:"mongodb"});return o.hasRelationFilters?await de(t,e,n,this.db):o.filterTree?De(o.filterTree,{metadata:n,rootTable:e}):{}}};var dn=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();var co=["_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(co.includes(e)||typeof r[e]=="object"&&r[e]!==null&&ge(r[e]))return!0;return!1}var Lr=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function uo(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function pn(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 fo(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)||pn(r,t,i),e}function Br(r,e,t,n,i,o,s){let a=i&&!e.includes(".")?`${i}.${e}`:e,u=pn(e,i,s),l=fo(e,n,i,o,s);switch(t){case"_eq":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} = ?::uuid`,[n]):r.where(a,"=",l);break;case"_neq":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} != ?::uuid`,[n]):r.where(a,"!=",l);break;case"_gt":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} > ?::uuid`,[n]):r.where(a,">",l);break;case"_gte":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} >= ?::uuid`,[n]):r.where(a,">=",l);break;case"_lt":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} < ?::uuid`,[n]):r.where(a,"<",l);break;case"_lte":u&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${a} <= ?::uuid`,[n]):r.where(a,"<=",l);break;case"_in":let f=n;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(p=>p.trim()):[f]),u&&o==="postgres"&&f.every(p=>typeof p=="string")?r.whereRaw(`${a} = ANY(?::uuid[])`,[f]):r.whereIn(a,f);break;case"_not_in":case"_nin":let c=n;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(p=>p.trim()):[c]),u&&o==="postgres"&&c.every(p=>typeof p=="string")?r.whereRaw(`${a} != ALL(?::uuid[])`,[c]):r.whereNotIn(a,c);break;case"_contains":o==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE '%' || lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${a}) LIKE '%' || lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${a})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_starts_with":o==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE lower(unaccent(?)) || '%'`,[n]):o==="sqlite"?r.whereRaw(`lower(${a}) LIKE lower(?) || '%'`,[n]):r.whereRaw(`lower(unaccent(${a})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent(?)) COLLATE utf8mb4_general_ci, '%')`,[n]);break;case"_ends_with":o==="postgres"?r.whereRaw(`lower(unaccent(${a})) ILIKE '%' || lower(unaccent(?))`,[n]):o==="sqlite"?r.whereRaw(`lower(${a}) LIKE '%' || lower(?)`,[n]):r.whereRaw(`lower(unaccent(${a})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent(?)) COLLATE utf8mb4_general_ci)`,[n]);break;case"_between":Array.isArray(n)&&n.length===2&&r.whereBetween(a,[n[0],n[1]]);break;case"_is_null":n===!0?r.whereNull(a):r.whereNotNull(a);break;case"_is_not_null":n===!0?r.whereNotNull(a):r.whereNull(a);break;default:r.where(a,uo(t),n)}}function po(r,e,t){if(!t||!e||r.startsWith("_"))return!0;let n=r.includes(".")?r.split(".").pop():r,i=t.columns?.some(s=>s.name===n),o=t.relations?.some(s=>s.propertyName===n);return i||o}function st(r,e,t,n="and",i,o){if(!(!e||typeof e!="object")){if(Array.isArray(e)){for(let s of e)n==="and"?r.where(function(){st(this,s,t,"and",i,o)}):r.orWhere(function(){st(this,s,t,"and",i,o)});return}for(let[s,a]of Object.entries(e))if(po(s,t,o)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){st(this,u,t,"and",i,o)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){st(this,u,t,"and",i,o)})});continue}if(s==="_not"){r.whereNot(function(){st(this,a,t,"and",i,o)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(l=>Lr.includes(l)))for(let[l,f]of Object.entries(a))Lr.includes(l)&&(n==="and"?r.where(function(){Br(this,s,l,f,t,i,o)}):r.orWhere(function(){Br(this,s,l,f,t,i,o)}));else{let l=t&&!s.includes(".")?`${t}.${s}`:s;pn(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${l} = ?::uuid`,[a]):r.orWhereRaw(`${l} = ?::uuid`,[a]):n==="and"?r.where(l,"=",a):r.orWhere(l,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s;pn(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${u} = ?::uuid`,[a]):r.orWhereRaw(`${u} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function ae(r,e,t,n,i){return!e||typeof e!="object"||st(r,e,t,"and",n,i),r}Ce();function Qn(r,e,t){return`${C(r,t)}.${C(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 Dr(r,e){if(!e)return!1;let t=e.columns.find(i=>i.name===r);if(!t)return!1;let n=t.type?.toLowerCase()||"";return n==="uuid"||n==="uuidv4"||n.includes("uuid")}function at(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function Jn(r,e,t,n,i,o){let s=[];for(let[a,u]of Object.entries(o)){let l=await Ot(r,e,a,u,t,n,i);if(l!==null)s.push(`EXISTS (${l})`);else{let f=t.relations.find(c=>c.propertyName===a);if(f&&f.foreignKeyColumn){let c=Qn(e,f.foreignKeyColumn,n),d=u.id;if(d&&typeof d=="object"){let g=at(d._is_null),y=at(d._is_not_null);if(g===!0)s.push(`${c} IS NULL`);else if(g===!1)s.push(`${c} IS NOT NULL`);else if(y===!0)s.push(`${c} IS NOT NULL`);else if(y===!1)s.push(`${c} IS NULL`);else if(d._eq!==void 0){let h=Re(d._eq,n);s.push(`${c} = ${h}`)}else if(d._neq!==void 0){let h=Re(d._neq,n);s.push(`${c} != ${h}`)}else if(d._in!==void 0){let m=(Array.isArray(d._in)?d._in:[d._in]).map(b=>Re(b,n)).join(", ");s.push(`${c} IN (${m})`)}else if(d._not_in!==void 0||d._nin!==void 0){let h=d._not_in??d._nin,b=(Array.isArray(h)?h:[h]).map($=>Re($,n)).join(", ");s.push(`${c} NOT IN (${b})`)}else if(d._gt!==void 0){let h=Re(d._gt,n);s.push(`${c} > ${h}`)}else if(d._gte!==void 0){let h=Re(d._gte,n);s.push(`${c} >= ${h}`)}else if(d._lt!==void 0){let h=Re(d._lt,n);s.push(`${c} < ${h}`)}else if(d._lte!==void 0){let h=Re(d._lte,n);s.push(`${c} <= ${h}`)}}}}}return s}function zn(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 Wn(r,e,t,n,i,o){let s=[];for(let a of r)if(a._and&&Array.isArray(a._and)&&a._and.length>0){let u=[];for(let l of a._and)if(zn(l)){let f=e(t).select(`${t}.id`);await We(e,f,l,t,n,i,o),u.push({idSubquery:f})}else{let{fieldFilters:f,relationFilters:c}=G(l,n),p=await Jn(e,t,n,i,o,c);u.push({fieldFilters:f,subqueries:p})}s.push(u)}else if(zn(a)){let u=e(t).select(`${t}.id`);await We(e,u,a,t,n,i,o),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:l}=G(a,n),f=await Jn(e,t,n,i,o,l);s.push([{fieldFilters:u,subqueries:f}])}return s}function Kr(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&&ae(this,o.fieldFilters,t,i,n);for(let s of o.subqueries)this.whereRaw(s)})}function Un(r,e,t,n,i){let o=!0;for(let s of e){let a=function(){for(let u of s)Kr(this,u,t,n,i)};o?(r.where(a),o=!1):r.orWhere(a)}}function gn(r,e,t,n,i,o,s){let a=Dr(e,i),u=Dr(n,o),l=`${C(r,s)}.${C(e,s)}`,f=`${C(t,s)}.${C(n,s)}`;if(s==="postgres"){if(a&&!u)return`${l} = ${f}::uuid`;if(!a&&u)return`${l}::uuid = ${f}`}return`${l} = ${f}`}async function Ot(r,e,t,n,i,o,s){let a=i.relations.find(p=>p.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${e}"`);let u=a.targetTableName||a.targetTable;if(!u)throw new Error(`Relation "${t}" in table "${e}" is missing targetTable/targetTableName. Relation metadata: ${JSON.stringify(a,null,2)}`);let l=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn){let p=Object.keys(n||{});if(p.length===1&&p[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(g=>l.has(g)))return null}let f=s?await s(u):null,c;switch(a.type){case"one-to-many":c=r(u).select(r.raw("1")).whereRaw(gn(u,a.foreignKeyColumn,e,"id",f,i,o));break;case"many-to-many":let p=s?await s(a.junctionTableName):null;c=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw(gn(a.junctionTableName,a.junctionTargetColumn,u,"id",p,f,o))).whereRaw(gn(a.junctionTableName,a.junctionSourceColumn,e,"id",p,i,o));break;case"many-to-one":case"one-to-one":c=r(u).select(r.raw("1")).whereRaw(gn(u,"id",e,a.foreignKeyColumn,f,i,o));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?f?await We(r,c,n,u,f,o,s):c=ae(c,n,u,o,f||void 0):c=ae(c,n,u,o),c.toString()}async function We(r,e,t,n,i,o,s){if(!t||typeof t!="object")return;if(t._and&&Array.isArray(t._and)){for(let l of t._and)if(l._or&&Array.isArray(l._or)&&l._or.length>0){let f=await Wn(l._or,r,n,i,o,s);e.where(function(){Un(this,f,n,i,o)})}else if(l._and&&Array.isArray(l._and)&&l._and.length>0)for(let f of l._and)await We(r,e,f,n,i,o,s);else await We(r,e,l,n,i,o,s);return}if(t._or&&Array.isArray(t._or)){let l=await Wn(t._or,r,n,i,o,s);e.where(function(){Un(this,l,n,i,o)});return}if(t._not){let l=t._not;if(l._and&&Array.isArray(l._and)&&l._and.length>0){let p=[];for(let d of l._and)if(zn(d)){let g=r(n).select(`${n}.id`);await We(r,g,d,n,i,o,s),p.push({idSubquery:g})}else{let{fieldFilters:g,relationFilters:y}=G(d,i),h=await Jn(r,n,i,o,s,y);p.push({fieldFilters:g,subqueries:h})}e.whereNot(function(){for(let d of p)Kr(this,d,n,i,o)});return}if(l._or&&Array.isArray(l._or)&&l._or.length>0){let p=await Wn(l._or,r,n,i,o,s);e.whereNot(function(){Un(this,p,n,i,o)});return}let{fieldFilters:f,relationFilters:c}=G(l,i);e.whereNot(function(){Object.keys(f).length>0&&ae(this,f,n,o,i)});for(let[p,d]of Object.entries(c)){let g=await Ot(r,n,p,d,i,o,s);if(g===null){let y=i.relations.find(h=>h.propertyName===p);if(y&&y.foreignKeyColumn){let h=Qn(n,y.foreignKeyColumn,o),b=d.id;if(b&&typeof b=="object"){let $=at(b._is_null),w=at(b._is_not_null);if($===!0)e.whereRaw(`${h} IS NOT NULL`);else if($===!1)e.whereRaw(`${h} IS NULL`);else if(w===!0)e.whereRaw(`${h} IS NULL`);else if(w===!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 (${g})`)}return}let{fieldFilters:a,relationFilters:u}=G(t,i);Object.keys(a).length>0&&ae(e,a,n,o,i);for(let[l,f]of Object.entries(u)){let c=await Ot(r,n,l,f,i,o,s);if(c===null){let p=i.relations.find(d=>d.propertyName===l);if(p&&p.foreignKeyColumn){let d=Qn(n,p.foreignKeyColumn,o),y=f.id;if(y&&typeof y=="object"){let h=at(y._is_null),m=at(y._is_not_null);if(h===!0)e.whereRaw(`${d} IS NULL`);else if(h===!1)e.whereRaw(`${d} IS NOT NULL`);else if(m===!0)e.whereRaw(`${d} IS NOT NULL`);else if(m===!1)e.whereRaw(`${d} IS NULL`);else if(y._eq!==void 0)e.whereRaw(`${d} = ?`,[y._eq]);else if(y._neq!==void 0)e.whereRaw(`${d} != ?`,[y._neq]);else if(y._in!==void 0){let b=Array.isArray(y._in)?y._in:[y._in];e.whereRaw(`${d} IN (${b.map(()=>"?").join(", ")})`,b)}else if(y._not_in!==void 0||y._nin!==void 0){let b=y._not_in??y._nin,$=Array.isArray(b)?b:[b];e.whereRaw(`${d} NOT IN (${$.map(()=>"?").join(", ")})`,$)}}}}else e.whereRaw(`EXISTS (${c})`)}}async function Ue(r,e,t,n,i,o,s){await We(r,e,t,n,i,o,s)}Ce();qn();Ye();Ce();function lt(r,e,t,n,i){for(let o of e){let s=o.field.split("."),a=t||s[0],u=s[s.length-1],l=Et(n,a,u,o.value);switch(o.operator){case"=":r=r.where(o.field,"=",l);break;case"!=":r=r.where(o.field,"!=",l);break;case">":r=r.where(o.field,">",l);break;case"<":r=r.where(o.field,"<",l);break;case">=":r=r.where(o.field,">=",l);break;case"<=":r=r.where(o.field,"<=",l);break;case"like":r=r.where(o.field,"like",l);break;case"in":let f=Array.isArray(o.value)?o.value.map(y=>Et(n,a,u,y)):[l];r=r.whereIn(o.field,f);break;case"not in":let c=Array.isArray(o.value)?o.value.map(y=>Et(n,a,u,y)):[l];r=r.whereNotIn(o.field,c);break;case"is null":r=r.whereNull(o.field);break;case"is not null":r=r.whereNotNull(o.field);break;case"_contains":r=r.where(o.field,"like",`%${o.value}%`);break;case"_starts_with":r=r.where(o.field,"like",`${o.value}%`);break;case"_ends_with":r=r.where(o.field,"like",`%${o.value}`);break;case"_between":let p=o.value;if(typeof p=="string"&&(p=p.split(",").map(y=>y.trim())),Array.isArray(p)&&p.length===2){let y=Et(n,a,u,p[0]),h=Et(n,a,u,p[1]);r=r.whereBetween(o.field,[y,h])}break;case"_is_null":r=l===!0||l==="true"?r.whereNull(o.field):r.whereNotNull(o.field);break;case"_is_not_null":r=l===!0||l==="true"?r.whereNotNull(o.field):r.whereNull(o.field);break}}return r}function Pt(r,e,t,n){let i=[],o=t;if(!r||typeof r!="object")return i;for(let[s,a]of Object.entries(r))if(s==="_and"&&Array.isArray(a)){let u=a.map(l=>{let f=Pt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&i.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(l=>{let f=Pt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&i.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=Pt(a,e,t,n);u.length>0&&i.push(`NOT (${u.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[u,l]of Object.entries(a)){let f=`${C(e,n)}.${C(s,n)}`,c;if(l===null)c="NULL";else if(typeof l=="string"){let p=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,d=o.columns?.find(y=>y.name===s);d&&(d.type?.toLowerCase()==="uuid"||d.type?.toLowerCase().includes("uuid"))&&p.test(l)&&n==="postgres"?c=`'${l}'::uuid`:c=`'${l.replace(/'/g,"''")}'`}else typeof l=="boolean"?c=l?"true":"false":typeof l=="number"?c=String(l):c=`'${String(l).replace(/'/g,"''")}'`;if(u==="_eq")i.push(`${f} = ${c}`);else if(u==="_neq")i.push(`${f} != ${c}`);else if(u==="_gt")i.push(`${f} > ${c}`);else if(u==="_gte")i.push(`${f} >= ${c}`);else if(u==="_lt")i.push(`${f} < ${c}`);else if(u==="_lte")i.push(`${f} <= ${c}`);else if(u==="_is_null")i.push(`${f} IS NULL`);else if(u==="_is_not_null")i.push(`${f} IS NOT NULL`);else if(u==="_in"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");i.push(`${f} IN (${d})`)}else if(u==="_not_in"||u==="_nin"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");i.push(`${f} NOT IN (${d})`)}else if(u==="_contains"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${f}) LIKE '%${p.toLowerCase()}%'`)}else if(u==="_starts_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${f})) ILIKE lower(unaccent('${p}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${f}) LIKE '${p.toLowerCase()}%'`)}else if(u==="_ends_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}'))`):n==="mysql"?i.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci)`):i.push(`lower(${f}) LIKE '%${p.toLowerCase()}'`)}else if(u==="_between"&&Array.isArray(l)&&l.length===2){let p=typeof l[0]=="string"?`'${l[0].replace(/'/g,"''")}'`:String(l[0]),d=typeof l[1]=="string"?`'${l[1].replace(/'/g,"''")}'`:String(l[1]);i.push(`${f} BETWEEN ${p} AND ${d}`)}}else{let u=`${C(e,n)}.${C(s,n)}`,l;a===null?l="NULL":typeof a=="string"?l=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?l=a?"true":"false":l=String(a),i.push(`${u} = ${l}`)}return i}function Ur(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 Et(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}}Ce();jt();Ve();async function Jr(r,e,t,n,i,o,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(Gn(),Qr)),u=await a(e,t,n,i,o,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function Yn(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 zr(r,e,t,n,i){let o=r.targetTableName||r.targetTable;if(!o)return null;let s=r.foreignKeyColumn||V(r.propertyName);if(!s)return null;let a=c=>C(c,i),u=n?.tables?.get(o),f=(u?ne(u):null)?.name||"id";return`(SELECT ${a(o)}.${a(e)} FROM ${a(o)} WHERE ${a(o)}.${a(f)} = ${a(t)}.${a(s)})`}jt();var ut=class r{constructor(e,t,n,i){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=i;this.logger=new dn(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&&U(e.filter,e.tableName,e.metadata),!e.plan){let S=new Q;e={...e,plan:S.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:this.dbType})}}let o=e.plan,s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,u=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,l=o.rawFields&&o.rawFields.length>0&&!o.rawFields.includes("*");if(o.joins.length===0&&!o.hasRelationFilters&&!o.hasRelationSort&&!u&&!a&&l){i&&i.setQueryPath("simple");let S=await this.executeSimple(e,o);return i&&i.dur("sql_executor",t,{table:e.tableName}),S}let c={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?c.fields=e.fields:typeof e.fields=="string"&&(c.fields=e.fields.split(",").map(S=>S.trim())));let p=e.filter;if(e.filter&&!ge(e.filter)){c.where=[];for(let[S,F]of Object.entries(e.filter))if(typeof F=="object"&&F!==null)for(let[R,le]of Object.entries(F)){let A;if(R==="_eq")A="=";else if(R==="_neq")A="!=";else if(R==="_in")A="in";else if(R==="_not_in"||R==="_nin")A="not in";else if(R==="_gt")A=">";else if(R==="_gte")A=">=";else if(R==="_lt")A="<";else if(R==="_lte")A="<=";else if(R==="_contains")A="_contains";else if(R==="_starts_with")A="_starts_with";else if(R==="_ends_with")A="_ends_with";else if(R==="_between")A="_between";else if(R==="_is_null")A="_is_null";else if(R==="_is_not_null")A="_is_not_null";else if(R==="_like")A="like";else if(R==="_ilike")A="ilike";else continue;c.where.push({field:S,operator:A,value:le})}else c.where.push({field:S,operator:"=",value:F})}if(e.sort){let S=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(F=>F.trim());c.sort=S.map(F=>{let R=F.trim();return R.startsWith("-")?{field:R.substring(1),direction:"desc"}:{field:R,direction:"asc"}})}else c.sort=[{field:"id",direction:"asc"}];let d=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,g=d===void 0||Number.isNaN(d)?void 0:d<0?0:d,y=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,h=y===void 0||Number.isNaN(y)?void 0:y;h&&g!==void 0?(c.offset=(h-1)*g,c.limit=g):g!==void 0&&(c.limit=g);let m=e.plan?.sortItems??(c.sort??[]).map(S=>({joinId:null,field:S.field,direction:S.direction,fullPath:S.field})),b=[],$=[];for(let S of m){if(S.function==="count"){let F={sql:this.buildRelationCountSortSubquery(c.table,S),direction:S.direction};$.push(F);continue}if(S.joinId===null){if(S.field.includes(".")&&!e.plan){let R=S.field.split(".")[0];if(this.metadata?.tables?.get(c.table)?.relations?.some(J=>J.propertyName===R))continue}let F={field:S.field.includes(".")?S.field:`${c.table}.${S.field}`,direction:S.direction};b.push(F),$.push(F)}else{let F=e.plan?.joins.find(R=>R.id===S.joinId);if(F&&(F.relationType==="many-to-one"||F.relationType==="one-to-one")){let R=zr(F.relationMeta,S.field,c.table,this.metadata,this.dbType);if(R){let le={sql:R,direction:S.direction};$.push(le)}}}}let w=[];if(c.fields&&c.fields.length>0){let S=Yn(this.metadata),F=await Jr(this.knex,c.table,c.fields,S,this.dbType,this.maxQueryDepth,e.deep);c.select=[...c.select||[],...F.select],w=F.batchFetchDescriptors||[]}c.where&&(c.where=c.where.map(S=>S.field.includes(".")?S:{...S,field:`${c.table}.${S.field}`})),c.sort=b;let T=this.knex(c.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(S=>S.trim()).filter(Boolean),v=k.includes("filterCount")||k.includes("*"),_=k.includes("totalCount")||k.includes("*");if(c.select){let S=c.select.map(F=>typeof F=="string"&&F.trim().startsWith("(")?this.knex.raw(F):typeof F=="string"&&/ as /i.test(F)?this.knex.raw(F):F);T=T.select(S)}if(v&&T.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),_){let S=C(c.table,this.dbType);T.select(this.knex.raw(`(SELECT COUNT(*) FROM ${S}) as __total_count__`))}let N=["table_definition","column_definition","relation_definition","method_definition"].includes(c.table);if(p&&(ge(p)||Object.keys(p).length>0)){let S=this.metadata?.tables?.get(c.table);(!N&&S&&S.relations&&S.relations.length>0?G(p,S).hasRelations:!1)?await Ue(this.knex,T,p,c.table,S,this.dbType,R=>this.metadata?.tables?.get(R)):e.plan?.filterTree?X(T,e.plan.filterTree,{dbType:this.dbType,rootTable:c.table}):(this.logger.debug(`buildWhereClause fallback for table=${c.table}`),T=ae(T,p,c.table,this.dbType,S))}else c.where&&c.where.length>0&&(T=lt(T,c.where,c.table,this.metadata,this.dbType));for(let S of $)if(S.field){let F=S.field.includes(".")?S.field:`${c.table}.${S.field}`;T=T.orderBy(F,S.direction)}else S.sql&&(T=T.orderByRaw(`${S.sql} ${S.direction.toUpperCase()}`));c.groupBy&&(T=T.groupBy(c.groupBy)),c.offset&&(T=T.offset(c.offset)),c.limit!==void 0&&c.limit!==null&&c.limit>0&&(T=T.limit(c.limit));let I=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:c.table,sql:T.toSQL().toNative()});let O;if(e.debugMode&&(O=T.toSQL().toNative().sql),e.debugMode&&i){let S=T.toSQL().toNative();i.setSql(S.sql);try{let F=S.sql.replace(/\$\d+/g,"?"),R=await this.knex.raw(`EXPLAIN ${F}`,S.bindings);i.setExplain(this.dbType==="postgres"?R.rows:R[0])}catch(F){i.setExplain({error:String(F)})}}let M,D=performance.now();M=await T,i&&i.dur("db_execute",D,{table:e.tableName});let P=0;if(v&&M.length>0&&(P=Number(M[0].__filter_count__||0),M.forEach(S=>{delete S.__filter_count__})),_&&M.length>0&&M[0].__total_count__!==void 0&&(I=Number(M[0].__total_count__||0),M.forEach(S=>{delete S.__total_count__})),w&&w.length>0&&M.length>0){let S=Yn(this.metadata);if(S){let{executeBatchFetches:F}=await Promise.resolve().then(()=>(er(),Vr));await F(this.knex,M,w,S,this.maxQueryDepth??3,0,c.table,this.dbType,this.metadata,i)}}if(this.knexService){let S=performance.now();M=await this.knexService.parseResult(M,c.table),i&&i.dur("db_parseResult",S,{table:e.tableName})}else{let S=(F,R)=>{if(!F||!this.metadata)return F;let le=this.metadata.tables?.get(R);if(!le)return F;if(Array.isArray(F))return F.map(J=>S(J,R));if(typeof F!="object"||Buffer.isBuffer(F))return F;let A={...F};for(let J of le.columns)if(J.type==="simple-json"&&A[J.name]&&typeof A[J.name]=="string")try{A[J.name]=JSON.parse(A[J.name])}catch{}for(let[J,q]of Object.entries(A))if(q&&typeof q=="object"&&!Array.isArray(q)&&!Buffer.isBuffer(q)){let wn=q;if(wn.id!==void 0||wn.createdAt!==void 0){let dt=le.relations?.find(pt=>pt.propertyName===J);dt&&(A[J]=S(q,dt.targetTableName))}}else if(Array.isArray(q)&&q.length>0&&typeof q[0]=="object"&&q[0].id!==void 0){let dt=le.relations?.find(pt=>pt.propertyName===J);dt&&(A[J]=q.map(pt=>S(pt,dt.targetTableName)))}return A};M=S(M,c.table)}i&&(i.setQueryPath("full"),i.dur("sql_executor",t,{table:e.tableName}));let L=await this.executeAggregate(c,p);return{data:M,...(k.length>0||L)&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:I}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:P}:{},...L?{aggregate:L}:{}}},...O!==void 0&&{sql:O}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=ne(s)?.name||"id",u=C(e,this.dbType),l=C(a,this.dbType);if(!n||!o)throw new x(`Sort relation '${i}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let f=n.foreignKeyColumn||n.mappedBy;if(!f)throw new x(`Sort function '_count(${i})' cannot resolve relation key on '${e}'.`);let c=C(o,this.dbType),p=C(f,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}if(n.type==="many-to-many"){let f=this.resolveManyToManyContract(n,i,e),c=C(f.tableName,this.dbType),p=C(f.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}throw new x(`Sort function '_count(${i})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,n){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new x(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async executeSimple(e,t){let n=e.tableName,i=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],o=this.knex(n).select(i);t.filterTree&&X(o,t.filterTree,{dbType:this.dbType,rootTable:n});for(let 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=C(n,this.dbType);o.select(this.knex.raw(`(SELECT COUNT(*) FROM ${h}) as __total_count__`))}let l=e.debugTrace,f;if(e.debugMode){let h=o.toSQL().toNative();if(f=h.sql,l){l.setSql(h.sql);try{let m=h.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${m}`,h.bindings);l.setExplain(this.dbType==="postgres"?b.rows:b[0])}catch(m){l.setExplain({error:String(m)})}}}let c=performance.now(),p;p=await o,l&&l.dur("db_execute",c,{table:n}),this.knexService&&(p=await this.knexService.parseResult(p,n));let d=0,g=0;a&&p.length>0&&(d=Number(p[0].__filter_count__||0),p.forEach(h=>delete h.__filter_count__)),u&&p.length>0&&(g=Number(p[0].__total_count__||0),p.forEach(h=>delete h.__total_count__));let y=await this.executeAggregate({table:n,aggregate:e.aggregate,metadata:e.metadata},e.filter);return{data:p,...(s.length>0||y)&&{meta:{...u?{totalCount:g}:{},...a?{filterCount:d}:{},...y?{aggregate:y}:{}}},...f!==void 0&&{sql:f}}}async executeAggregate(e,t){let n=rt(e.aggregate,e.table,e.metadata);if(n.length===0)return;let i={};for(let o of n){let s=it(t,o);U(s,e.table,e.metadata);let u=new Q().plan({tableName:e.table,filter:s,metadata:e.metadata,dbType:this.dbType});if(o.op==="countRecords"){let d=await this.executeRelationCountRecords(e,t,o);Fe(i,o,d);continue}let l=this.knex(e.table);if(u.hasRelationFilters){let d=e.metadata?.tables?.get(e.table);await Ue(this.knex,l,s,e.table,d,this.dbType,g=>e.metadata?.tables?.get(g))}else u.filterTree&&X(l,u.filterTree,{dbType:this.dbType,rootTable:e.table});let f=`${C(e.table,this.dbType)}.${C(o.field,this.dbType)}`,c=o.op==="count"?this.knex.raw("COUNT(*) as value"):this.knex.raw(`${o.op.toUpperCase()}(${f}) as value`),p=await l.clearSelect().select(c).first();Fe(i,o,p?.value??0)}return i}async executeRelationCountRecords(e,t,n){let i=e.metadata?.tables?.get(e.table),o=i?.relations?.find(c=>c.propertyName===n.field),s=o?.targetTableName||o?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!o||!s||!a)return 0;let u=this.knex(e.table).select(`${e.table}.id`);if(t&&Object.keys(t).length>0){let p=new Q().plan({tableName:e.table,filter:t,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Ue(this.knex,u,t,e.table,i,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&X(u,p.filterTree,{dbType:this.dbType,rootTable:e.table})}let l=this.knex(s).count("* as value");if(n.condition&&Object.keys(n.condition).length>0){U(n.condition,s,e.metadata);let p=new Q().plan({tableName:s,filter:n.condition,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Ue(this.knex,l,n.condition,s,a,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&X(l,p.filterTree,{dbType:this.dbType,rootTable:s})}if(o.type==="one-to-many")l.whereIn(`${s}.${o.foreignKeyColumn}`,u);else if(o.type==="many-to-many"){let c=this.resolveManyToManyContract(o,n.field,e.table);l.whereIn(`${s}.id`,this.knex(c.tableName).select(`${c.tableName}.${c.targetColumn}`).whereIn(`${c.tableName}.${c.sourceColumn}`,u))}else(o.type==="many-to-one"||o.type==="one-to-one")&&l.whereIn(`${s}.id`,function(){this.select(`${e.table}.${o.foreignKeyColumn}`).from(e.table),t&&Object.keys(t).length>0&&this.whereIn(`${e.table}.id`,u),this.whereNotNull(`${e.table}.${o.foreignKeyColumn}`)});let f=await l.first();return Number(f?.value??0)}};var yn=require("mongodb"),ft=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,mn.mkdirSync)((0,qr.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(!yn.ObjectId)return e;if(typeof e=="string")try{return new yn.ObjectId(e)}catch{return e}return e}async getMetadataForQuery(){let e={tables:new Map,tablesList:[]},t=this.lazyRef.metadataCacheService;return t?t.isLoaded?.()?await t.getMetadata?.()??e:t.getDirectMetadata?.()??e:e}async buildMongoFilter(e,t){let n=await this.getMetadataForQuery(),i=Ge(n,e,t,this.dbType);return i._id!==void 0&&(i._id=this.safeObjectId(i._id)),i}async applyWhereToKnex(e,t,n){let i=await this.getMetadataForQuery();return{query:lt(e,t,n??"",i,this.dbType)}}async runMongoMutationInSaga(e){return!this.mongoService?.runInSaga||this.mongoService.isInSaga?.()?e():(await this.mongoService.runInSaga(e)).data}async insertWithOptions(e){if(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(re(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 Q().plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:n,dbType:this.dbType}),a=e.debugTrace;if(a&&(a.dur("qb_planner",i,{table:e.tableName}),a.setPlan(this.sanitizePlan(s))),this.dbType==="mongodb")return new ot(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s,aggregate:e.aggregate});let l=await new ut(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:n,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}sanitizePlan(e){return{rawFields:e.rawFields,hasRelationFilters:e.hasRelationFilters,hasRelationSort:e.hasRelationSort,joins:e.joins?.length??0,sortItems:e.sortItems,limit:e.limit,offset:e.offset,page:e.page,isSimpleQuery:e.joins?.length===0&&!e.hasRelationFilters&&!e.hasRelationSort}}async updateWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),a=await this.mongoService.collection(e.table).find(o).toArray(),u=[];for(let l of a){let f=await this.mongoService.updateOne(e.table,l._id,e.data);u.push(f)}return u});let t=this.knexService.getKnex(),n=t(e.table);e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n;for(let o of i)await this.knexService.updateWithCascade(e.table,o.id,e.data);if(e.returning){let o=t(e.table);return e.where.length>0&&await this.applyWhereToKnex(o,e.where,e.table),await o.select(e.returning)}return{affected:i.length}}async deleteWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let i=await this.buildMongoFilter(e.where,e.table),s=await this.mongoService.collection(e.table).find(i).toArray(),a=0;for(let u of s)await this.mongoService.deleteOne(e.table,u._id)&&a++;return a});let n=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table)),await n.delete()}async count(e){if(this.dbType==="mongodb"){let o=e.where?await this.buildMongoFilter(e.where,e.table):{};return this.mongoService.count(e.table,o)}let n=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n.count("* as count").first();return Number(i?.count||0)}whereToFilter(e){let t={},n=this.databaseConfigService.isMongoDb();for(let[i,o]of Object.entries(e))i==="id"||i==="_id"?n?t._id=this.normalizeWhereFilterValue("_id",o):t.id=this.normalizeWhereFilterValue("id",o):t[i]=this.normalizeWhereFilterValue(i,o);return t}normalizeWhereFilterValue(e,t){return this.isFilterOperatorObject(t)?this.databaseConfigService.isMongoDb()&&e==="_id"?this.normalizeMongoIdOperatorValue(t):t:{_eq:this.databaseConfigService.isMongoDb()&&e==="_id"?this.safeObjectId(t):t}}isFilterOperatorObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof yn.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[n,i]of Object.entries(e))t[n]=Array.isArray(i)?i.map(o=>this.safeObjectId(o)):this.safeObjectId(i);return t}filterToWhere(e){let t=[];for(let[n,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let o=Object.entries(i)[0];if(o){let[s,a]=o,u=this.mapFilterOperatorToSql(s);t.push({field:n,operator:u,value:a})}}return t}mapFilterOperatorToSql(e){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"like",_starts_with:"like",_ends_with:"like",_is_null:"is null",_is_not_null:"is not null"}[e]||"="}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,aggregate:e.aggregate,maxQueryDepth:e.maxQueryDepth})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t,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 re(a)}let i=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),s=i||t.id;return await o(e).where("id",s).first()})}async flushBatchInserts(){for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)await this.flushBatchInsertBuffer()}async insertManyBatch(e,t){let n=Array.isArray(t)?t:[t];for(let i of n)this.batchInserts.items.push({table:e,data:i});return this.traceBatchInsert("enqueue",{tableName:e,count:n.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i)),{accepted:!0,batch:!0,count:n.length}}async flushBatchInsertBuffer(){if(this.batchInserts.flushing){await this.batchInserts.flushPromise;return}let e=this.batchInserts.items.splice(0,this.batchInserts.items.length);if(this.batchInserts.timer&&(clearTimeout(this.batchInserts.timer),this.batchInserts.timer=void 0),e.length===0)return;this.batchInserts.flushing=!0;let t=this.executeBatchInsertFlush(e);this.batchInserts.flushPromise=t,await t}async executeBatchInsertFlush(e){let t=Date.now();try{let n=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...n.entries()].map(([i,o])=>({tableName:i,count:o.length}))}),await this.runLimited([...n.entries()],([i,o])=>this.flushBatchInsertTable(i,o)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}finally{this.batchInserts.flushing=!1,this.batchInserts.flushPromise=void 0,this.batchInserts.items.length>0&&(this.batchInserts.timer&&clearTimeout(this.batchInserts.timer),this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(n=>this.logBatchInsertError("QueryBuilder batch insert flush failed",n))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let n=Date.now();await this.runBatchInsertWithIsolation(e,t),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-n})}async runBatchInsertWithIsolation(e,t){if(t.length!==0)try{await(async()=>{if(this.dbType==="mongodb"){await this.runMongoMutationInSaga(async()=>{if(typeof this.mongoService?.insertManyWithCascade=="function"){await this.mongoService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.mongoService.insertOne(e,i.data)))});return}if(typeof this.knexService?.insertManyWithCascade=="function"){await this.knexService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.knexService.insertWithCascade(e,i.data)))})()}catch(n){if(t.length===1){this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,n);return}let i=Math.ceil(t.length/2);await Promise.all([this.runBatchInsertWithIsolation(e,t.slice(0,i)),this.runBatchInsertWithIsolation(e,t.slice(i))])}}groupBatchInsertsByTable(e){let t=new Map;for(let n of e){let i=t.get(n.table);i?i.push(n):t.set(n.table,[n])}return t}async runLimited(e,t){let n=0,i=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;n<e.length;){let o=e[n++];await t(o)}});await Promise.all(i)}readPositiveEnv(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.trunc(n):t}traceBatchInsert(e,t){this.batchInsertTraceFile&&(0,mn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
|
|
53
|
-
`)}logBatchInsertError(e,t){let n=t?.message||String(t);this.traceBatchInsert("error",{message:e,error:n,code:t?.code,detail:t?.detail}),console.error(`${e}: ${n}`)}async update(e,t,n){return this.trackQueryMetric("update",e,async()=>{if(t&&typeof t=="object"&&"where"in t)return await this.updateWithOptions({table:e,where:t.where,data:n});if(this.dbType==="mongodb"){let o=await this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n));return re(o)}return await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first()})}async delete(e,t){return this.trackQueryMetric("delete",e,async()=>t&&typeof t=="object"&&"where"in t?await this.deleteWithOptions({table:e,where:t.where})>0:this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t)):await this.knexService.getKnex()(e).where("id",t).delete()>0)}async countRecords(e,t){if(this.dbType==="mongodb")return this.mongoService.count(e,t||{});let i=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.filterToWhere(t);({query:i}=await this.applyWhereToKnex(i,s,e))}let o=await i.count("* as count").first();return Number(o?.count||0)}async transaction(e){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>e(this.mongoService)):this.knexService.transaction(e)}async findById(e,t){if(this.dbType==="mongodb"){let i=this.safeObjectId(t);return this.mongoService.findOne(e,{_id:i})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[o,s]of Object.entries(t))o==="id"||o==="_id"?i._id=this.safeObjectId(s):i[o]=s;return this.mongoService.findOne(e,i)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[a,u]of Object.entries(t))a==="id"||a==="_id"?i._id=this.safeObjectId(u):i[a]=u;return await this.mongoService.collection(e).find(i).toArray()}return await this.knexService.getKnex()(e).where(t)}async insertAndGet(e,t){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));let n=await this.knexService.insertWithCascade(e,t),i=this.knexService.getKnex(),o=n||t.id;return await i(e).where("id",o).first()}async updateById(e,t,n){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n)):(await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first())}async deleteById(e,t){return this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t))?1:0:this.knexService.getKnex()(e).where("id",t).delete()}async raw(e,t){let n=this.dbType==="mongodb"?"mongodb":"sql";return this.trackQueryMetric("raw",n,async()=>{if(this.dbType==="mongodb"){let o=this.mongoService.getDb();if(typeof e=="string"){if(e.toLowerCase().includes("select 1"))return await o.command({ping:1});throw new Error("String queries not supported for MongoDB. Use db.command() object instead.")}return await o.command(e)}return await this.knexService.getKnex().raw(e,t)})}async trackQueryMetric(e,t,n){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.trackQuery({op:e,table:t},n):await n()}getConnection(){return this.dbType==="mongodb"?this.mongoService.getDb():this.knexService.getKnex()}getKnex(){if(this.dbType==="mongodb")throw new Error("getKnex() is not available for MongoDB. Use getConnection() or unified methods.");return this.knexService.getKnex()}getMongoDb(){if(this.dbType!=="mongodb")throw new Error("getMongoDb() is not available for SQL. Use getConnection() or unified methods.");return this.mongoService.getDb()}getDatabaseType(){return this.dbType}isMongoDb(){return this.dbType==="mongodb"}isSql(){return["mysql","postgres","mariadb","sqlite"].includes(this.dbType)}getPkField(){return this.isMongoDb()?"_id":"id"}getRecordId(e){return this.isMongoDb()?e._id:e.id}};er();Xn();Gn();Ce();jt();et();ue();Ye();var Hr=new Set(["fields","filter","sort","limit","page","deep"]),_n=3;function tr(r,e,t,n=0,i=3){if(!e||typeof e!="object")return;if(n>=i)throw new x(`deep option exceeds maximum query depth of ${i}`);let o=t?.tables?.get(r),s=new Map((o?.relations??[]).map(a=>[a.propertyName,a]));for(let[a,u]of Object.entries(e)){let l=s.get(a);if(!l)throw new x(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let p of Object.keys(u))if(!Hr.has(p))throw new x(`Unknown deep option key '${p}' for relation '${a}'. Allowed: ${[...Hr].join(", ")}`);let f=l.type;if(u.limit!==void 0&&(f==="many-to-one"||f==="one-to-one"))throw new x(`'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 x(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let c=l.targetTableName||l.targetTable;if(c){if(u.filter&&(U(u.filter,c,t),Ke(u.filter,c,t),bn(u.filter,0,a,r)),u.sort){un(u.sort,c,t);let p=Array.isArray(u.sort)?u.sort:String(u.sort).split(",").map(d=>d.trim()).filter(Boolean);for(let d of p){let g=d.startsWith("-")?d.slice(1):d;yo(g,c,t,a,r)}}u.deep&&tr(c,u.deep,t,n+1,i)}}}function yo(r,e,t,n,i){if(r.includes("."))throw new x(`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 x(`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 x(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${i}')`)}var mo=new Set(["_and","_or","_not"]);function bn(r,e,t,n){if(!(!r||typeof r!="object"))for(let[i,o]of Object.entries(r)){if(mo.has(i)){if(Array.isArray(o))for(let l of o)bn(l,e,t,n);else o&&typeof o=="object"&&bn(o,e,t,n);continue}if(i.startsWith("_")||!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).some(l=>!l.startsWith("_")))continue;let a=e+1;if(a>_n)throw new x(`Filter path exceeds max dotted hops of ${_n} at '${i}' (relation '${t}' on '${n}')`);let u={};for(let l of Object.keys(o))l.startsWith("_")||(u[l]=o[l]);bn(u,a,t,n)}}function Gr(r,e,t,n){return!r||typeof r!="object"?r:Lt(r,e,t,n)}function Lt(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let o=r.map(s=>Lt(s,e,t,n)).filter(s=>s!=null);return o.length>0?o:null}let i={};for(let[o,s]of Object.entries(r)){if(o==="_and"||o==="_or"){let c=(Array.isArray(s)?s:[s]).map(p=>Lt(p,e,t,n)).filter(p=>p!=null&&Object.keys(p).length>0);c.length>0&&(i[o]=c);continue}if(o==="_not"){let f=Lt(s,e,t,n);f!=null&&Object.keys(f).length>0&&(i[o]=f);continue}let a=t?.tables?.get(e),u=a?.relations?.find(f=>f.propertyName===o);if(u){if(!n(e,o,"relation"))continue;let f=u.targetTableName||u.targetTable;if(!f)continue;let c=Lt(s,f,t,n);c!=null&&Object.keys(c).length>0&&(i[o]=c);continue}if(a?.columns?.find(f=>f.name===o)){if(!n(e,o,"column"))continue;i[o]=s;continue}i[o]=s}return i}function Yr(r,e,t,n){if(!r)return r;let i=Array.isArray(r)?r:r.split(",").map(s=>s.trim()).filter(Boolean),o=[];for(let s of i){let l=(s.startsWith("-")?s.slice(1):s).split("."),f=!0,c=e;for(let p=0;p<l.length;p++){let d=l[p],g=p===l.length-1,y=t?.tables?.get(c);if(!y){f=!1;break}if(g)y.columns?.find(m=>m.name===d)?n(c,d,"column")||(f=!1):y.relations?.find(b=>b.propertyName===d)&&(n(c,d,"relation")||(f=!1));else{let h=y.relations?.find(m=>m.propertyName===d);if(!h){f=!1;break}if(!n(c,d,"relation")){f=!1;break}c=h.targetTableName||h.targetTable||c}}f&&o.push(s)}if(o.length!==0)return Array.isArray(r)?o:o.join(",")}vt();Ye();It();an();xt();Ve();ue();function bo(r){let e=new ft({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,i=()=>(t||(t=new ze({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),o=()=>(n||(n=new Qe({isolatedExecutorService:i()})),n);return{queryBuilderService:e,get isolatedExecutorService(){return i()},get executorEngineService(){return o()},async onDestroy(){await t?.onDestroy?.()}}}0&&(module.exports={ALL_SUPPORTED_OPERATORS,AuthenticationException,AuthorizationException,BadRequestException,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,DEEP_TO_MANY_DEFAULT_LIMIT,DEFAULT_TIMEOUT_MS,DOTTED_PATH_MAX_HOPS,DatabaseException,DuplicateResourceException,ErrorHandler,ExecutorEngineService,ExternalServiceException,FIELD_OPERATORS,FileNotFoundException,FileSizeExceededException,FileUploadException,HttpException,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH,InvalidTokenException,IsolatedExecutorService,JoinRegistry,LOGICAL_OPERATORS,MongoBatchAdapter,MongoQueryExecutor,PER_PARENT_CONCURRENCY,QueryBuilderService,QueryPlanner,ResourceNotFoundException,SchemaException,ScriptContractService,ScriptExecutionException,ScriptTimeoutException,ServiceUnavailableException,SqlBatchAdapter,SqlQueryExecutor,TokenExpiredException,ValidationException,WHERE_IN_CHUNK_SIZE,WorkerPool,appendIsolatedExecutorRuntimeLog,applyOperatorToMatch,applyRelationFilters,applyWhereToKnex,assertFieldOperatorValueIsClean,buildAggregateFilter,buildMongoCharFoldMapJson,buildMongoFoldTextSearchJs,buildRelationSubquery,buildSqlWherePartsFromFieldAst,buildWhereClause,camelToSnake,chunkedFetch,compileScriptSource,computeEngineTuning,createEnfyraKernel,dslOpToCompareOp,encodeMainThreadToIsolate,escapeSqlValue,executeBatchFetches,executeMongoBatchFetches,expandFieldsToJoinsAndSelect,getEffectiveCpuCount,getEffectiveMemoryBytes,getEngineTuning,getExecutableScript,getForeignKeyColumnName,getIoAbortSignal,getJunctionColumnNames,getJunctionTableName,getPrimaryKeyColumn,getScriptLegacyField,getShortFkConstraintName,getShortFkName,getShortIndexName,getShortPkName,hasAggregateQuery,hasLogicalOperators,isExecutableJavaScript,isScriptTable,mergeAggregateValue,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,perParentRun,quoteIdentifier,resolveExecutableScript,rewriteFilterDenyingFields,rewriteSortDroppingDenied,scriptContractService,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,validateDeepOptions,validateFilterShape,whereToMongoFilter});
|
|
52
|
+
}`}var Sr="mongo-fold-text-search.body.txt",He=null;function Ei(){let r=[vn.join(__dirname,Sr),vn.join(process.cwd(),"dist","kernel","query","utils",Sr)];for(let e of r)try{if(Yt.existsSync(e))return Yt.readFileSync(e,"utf8")}catch{}return null}function Xt(){if(He!==null)return He;let r=Ei();return r?(He=r,He):(He=Gt(),He)}var Se=require("mongodb");function B(r,e,t,n){if(t==="_id"){if(n instanceof Se.ObjectId)return n;if(typeof n=="string")try{return new Se.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 Se.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 Se.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 Se.ObjectId(n)}catch{return n}if((t==="_id"||t==="id"||t.endsWith("Id"))&&typeof n=="string"&&n.length===24)try{return new Se.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 Se.ObjectId(n)}catch{return n}return n;default:return n}}var Zt="__mongoFoldTextTriples";function Pi(r){return r==="_id"?"$_id":`$${r}`}function Ge(r,e,t,n){let i=Pi(e),o=r[Zt]??[];o.push({ref:i,needle:t,mode:n}),r[Zt]=o}function ji(r){let e=r[Zt];if(delete r[Zt],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:Xt(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}function Ye(r,e,t,n){let i={},o=n==="mongodb"||!n;for(let s of e){let a=s.field.includes(".")?s.field.split(".").pop()??s.field:s.field,u=t||s.field.split(".")[0]||"";o&&a==="id"&&(a="_id");let l=B(r,u,a,s.value);switch(s.operator){case"=":i[a]=l;break;case"!=":i[a]={$ne:l};break;case">":i[a]={$gt:l};break;case"<":i[a]={$lt:l};break;case">=":i[a]={$gte:l};break;case"<=":i[a]={$lte:l};break;case"like":i[a]={$regex:l.replace(/%/g,".*"),$options:"i"};break;case"in":let f=s.value;Array.isArray(f)||(f=typeof f=="string"&&f.includes(",")?f.split(",").map(m=>m.trim()):[f]);let c=f.map(m=>B(r,u,a,m));i[a]={$in:c};break;case"not in":let p=s.value;Array.isArray(p)||(p=typeof p=="string"&&p.includes(",")?p.split(",").map(m=>m.trim()):[p]);let d=p.map(m=>B(r,u,a,m));i[a]={$nin:d};break;case"is null":i[a]=null;break;case"is not null":i[a]={$ne:null};break;case"_contains":Ge(i,a,String(l),"contains");break;case"_starts_with":Ge(i,a,String(l),"starts");break;case"_ends_with":Ge(i,a,String(l),"ends");break;case"_between":let g=s.value;if(typeof g=="string"&&(g=g.split(",").map(m=>m.trim())),Array.isArray(g)&&g.length===2){let m=B(r,u,a,g[0]),b=B(r,u,a,g[1]);i[a]={$gte:m,$lte:b}}break;case"_is_null":let y=l===!0||l==="true";i[a]=y?{$eq:null}:{$ne:null};break;case"_is_not_null":let h=l===!0||l==="true";i[a]=h?{$ne:null}:{$eq:null};break}}return ji(i),i}function Tr(r,e,t){let i=r?.tables?.get?.(e)?.columns?.find(o=>o.name===t);return i?i.isNullable!==!1:!0}function en(r,e,t,n,i,o){switch(i){case"_contains":Ge(e,n,String(o),"contains");break;case"_starts_with":Ge(e,n,String(o),"starts");break;case"_ends_with":Ge(e,n,String(o),"ends");break;case"_eq":e[n]=B(r,t,n,o);break;case"_neq":{let c=B(r,t,n,o);Tr(r,t,n)?(e.$and||(e.$and=[]),e.$and.push({[n]:{$ne:null}}),e.$and.push({[n]:{$ne:c}})):e[n]={$ne:c};break}case"_in":{let c=o;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(d=>d.trim()):[c]);let p=c.map(d=>B(r,t,n,d));e[n]={$in:p};break}case"_not_in":case"_nin":let s=o;Array.isArray(s)||(s=typeof s=="string"&&s.includes(",")?s.split(",").map(c=>c.trim()):[s]);let a=s.map(c=>B(r,t,n,c));Tr(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:B(r,t,n,o)};break;case"_gte":e[n]={$gte:B(r,t,n,o)};break;case"_lt":e[n]={$lt:B(r,t,n,o)};break;case"_lte":e[n]={$lte:B(r,t,n,o)};break;case"_is_null":let u=o===!0||o==="true";e[n]=u?{$eq:null}:{$ne:null};break;case"_is_not_null":let l=o===!0||o==="true";e[n]=l?{$ne:null}:{$eq:null};break;case"_between":let f=o;if(typeof f=="string"&&(f=f.split(",").map(c=>c.trim())),Array.isArray(f)&&f.length===2){let c=B(r,t,n,f[0]),p=B(r,t,n,f[1]);e[n]={$gte:c,$lte:p}}break}}var An=require("mongodb");function ie(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(ie(i,e))return!0}}else if(t==="_not"){if(ie(n,e))return!0}else if(e.has(t))return!0;return!1}function G(r,e){if(!r||typeof r!="object")return{fieldFilters:{},relationFilters:{},hasRelations:!1};let t={},n={},i=new Set(e.relations.map(s=>s.propertyName));for(let[s,a]of Object.entries(r)){if(s==="_and"||s==="_or"||s==="_not"){t[s]=a;continue}if(i.has(s))if(typeof a=="object"&&a!==null){let u=Object.keys(a);if(u.some(f=>f.startsWith("_"))){let f=["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"];u.length===1&&f.includes(u[0])?n[s]={id:a}:n[s]=a}else n[s]=a}else n[s]=a;else t[s]=a}let o=ie(r,i);return{fieldFilters:t,relationFilters:n,hasRelations:o}}It();Nt();var an="__mongoFoldTextTriples";function Ke(r,e){if(!r)return{};let t={};return on(r,t,e),sn(t),t}function de(r,e,t){if(!e)return{};let n=new oe,{node:i}=Te(e,t,r,n);return Ke(i,{metadata:r,rootTable:t})}function on(r,e,t){switch(r.kind){case"true":return;case"false":Mt(e,{_id:{$exists:!1,$type:"null"}});return;case"and":{let i=r.children.map(o=>{let s={};return on(o,s,t),sn(s),s}).filter(o=>Object.keys(o).length>0);if(i.length===0)return;if(i.length===1){Object.assign(e,i[0]);return}Mt(e,...i);return}case"or":{let i=r.children.map(s=>{let a={};return on(s,a,t),sn(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={};on(r.child,n,t),sn(n);let i=e.$nor;e.$nor=i?[...i,n]:[n];return}case"compare":Ji(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 Ji(r,e,t){let n=r.field.fieldName;if(n==="id"&&(n="_id"),r.field.joinId!==null){console.warn(`[mongo-render-filter] compare node has joinId=${r.field.joinId} (field=${r.field.fieldName}) but reached renderer \u2014 expected relation pipeline to handle it. Filter silently skipped.`);return}let i=o=>B(t.metadata,t.rootTable,n,o);switch(r.op){case"eq":se(e,n,i(r.value));return;case"neq":{let o=i(r.value);Cr(t,n)?Mt(e,{[n]:{$ne:null}},{[n]:{$ne:o}}):se(e,n,{$ne:o});return}case"gt":se(e,n,{$gt:i(r.value)});return;case"gte":se(e,n,{$gte:i(r.value)});return;case"lt":se(e,n,{$lt:i(r.value)});return;case"lte":se(e,n,{$lte:i(r.value)});return;case"in":{let o=Rr(r.value).map(i);se(e,n,{$in:o});return}case"not_in":{let o=Rr(r.value).map(i);Cr(t,n)?Mt(e,{[n]:{$ne:null}},{[n]:{$nin:o}}):se(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&&se(e,n,{$gte:i(o[0]),$lte:i(o[1])});return}case"is_null":se(e,n,r.value===!0?{$eq:null}:{$ne:null});return;case"contains":Nn(e,n,String(r.value),"contains");return;case"starts_with":Nn(e,n,String(r.value),"starts");return;case"ends_with":Nn(e,n,String(r.value),"ends");return}}function se(r,e,t){r[e]===void 0?r[e]=t:(Mt(r,{[e]:r[e]},{[e]:t}),delete r[e])}function Mt(r,...e){if(e.length===0)return;let t=r.$and;r.$and=t?[...t,...e]:e}function Cr(r,e){let n=r.metadata?.tables?.get?.(r.rootTable)?.columns?.find(i=>i.name===e);return n?n.isNullable!==!1:!0}function Rr(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}function zi(r){return r==="_id"?"$_id":`$${r}`}function Nn(r,e,t,n){let i=zi(e),o=r[an]??[];o.push({ref:i,needle:t,mode:n}),r[an]=o}function sn(r){let e=r[an];if(delete r[an],!e?.length)return;let t=[];for(let o of e)t.push(o.ref,o.needle,o.mode);let n={$eq:[{$function:{body:Xt(),args:t,lang:"js"}},!0]},i=r.$expr;i?r.$expr={$and:[i,n]}:r.$expr=n}async function pe(r,e,t,n){if(!r||typeof r!="object")return{};let i=t?.tables?.get(e);if(!i)return de(t,r,e);let o=new Set((i.relations||[]).map(l=>l.propertyName));if(!ie(r,o))return de(t,r,e);if(r._and&&Array.isArray(r._and)){let f=(await Promise.all(r._and.map(c=>pe(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:f.length===1?f[0]:{$and:f}}if(r._or&&Array.isArray(r._or)){let f=(await Promise.all(r._or.map(c=>pe(c,e,t,n)))).filter(c=>c&&Object.keys(c).length>0);return f.length===0?{}:{$or:f}}if(r._not){let l=await pe(r._not,e,t,n);return!l||Object.keys(l).length===0?{}:{$nor:[l]}}let{fieldFilters:s,relationFilters:a}=G(r,i),u=[];if(s&&Object.keys(s).length>0){let l=de(t,s,e);l&&Object.keys(l).length>0&&u.push(l)}if(a&&Object.keys(a).length>0)for(let[l,f]of Object.entries(a)){let c=await Vi(l,f,e,i,t,n);c&&Object.keys(c).length>0&&u.push(c)}return u.length===0?{}:u.length===1?u[0]:{$and:u}}async function Vi(r,e,t,n,i,o){let s=(n.relations||[]).find(l=>l.propertyName===r);if(!s)return{};let a=s.targetTableName||s.targetTable,u=i?.tables?.get(a);return!a||!u?{}:s.type==="many-to-one"||s.type==="one-to-one"?qi(e,s,r,a,u,i,o):s.type==="one-to-many"?Hi(e,s,t,a,u,i,o):s.type==="many-to-many"?Gi(e,s,t,a,u,i,o):{}}async function qi(r,e,t,n,i,o,s){let a=H(e)||t,u=En(r),l=Pn(u);if(l!==null)return l?{[a]:null}:{[a]:{$ne:null}};let f=vr(u);if(f!==null){let g=jn(f.value);if(f.op==="eq")return{[a]:g};if(f.op==="neq")return{[a]:{$ne:g}};if(f.op==="in")return{[a]:{$in:g}};if(f.op==="not_in")return{$and:[{[a]:{$nin:g}},{[a]:{$ne:null}}]}}let c=await On(u,n,i,o,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(g=>g._id).filter(Boolean);return d.length===0?{[a]:null}:{[a]:{$in:d}}}async function Hi(r,e,t,n,i,o,s){let a=W(e)||t,u=En(r),l=Pn(u);if(l!==null){let p=await xr(s,n,a,{});return l?p.length===0?{}:{_id:{$nin:p}}:p.length===0?{__impossible__:!0}:{_id:{$in:p}}}let f=await On(u,n,i,o,s);if(!f||Object.keys(f).length===0)return{};let c=await xr(s,n,a,f);return c.length===0?{__impossible__:!0}:{_id:{$in:c}}}async function Gi(r,e,t,n,i,o,s){let a=we(t,e);if(!a)return{};let u=En(r),l=Pn(u);if(l!==null){let y=await Mn(s,a,n,null);return l?y.length===0?{}:{_id:{$nin:y}}:y.length===0?{__impossible__:!0}:{_id:{$in:y}}}let f=vr(u);if(f!==null){let y=jn(f.value),h=Array.isArray(y)?y:[y],m=await Mn(s,a,n,{_id:{$in:h}});return m.length===0?{__impossible__:!0}:{_id:{$in:m}}}let c=await On(u,n,i,o,s);if(!c||Object.keys(c).length===0)return{};let d=(await s.collection(n).find(c,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(Boolean);if(d.length===0)return{__impossible__:!0};let g=await Mn(s,a,n,{_id:{$in:d}});return g.length===0?{__impossible__:!0}:{_id:{$in:g}}}async function On(r,e,t,n,i){let o=new Set((t?.relations??[]).map(s=>s.propertyName));return ie(r,o)?pe(r,e,n,i):de(n,r,e)}async function xr(r,e,t,n){let i=await r.collection(e).find(n,{projection:{[t]:1}}).toArray(),o=new Set,s=[];for(let a of i){let u=a[t];if(u==null)continue;let l=String(u);o.has(l)||(o.add(l),s.push(u))}return s}async function Mn(r,e,t,n){let i=null;n&&t&&(i=(await r.collection(t).find(n,{projection:{_id:1}}).toArray()).map(f=>f._id).filter(Boolean));let o=i?{[e.otherColumn]:{$in:i}}:{},s=await r.collection(e.junctionName).find(o,{projection:{[e.selfColumn]:1}}).toArray(),a=new Set,u=[];for(let l of s){let f=l[e.selfColumn];if(f==null)continue;let c=String(f);a.has(c)||(a.add(c),u.push(f))}return u}function En(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 jn(r){if(Array.isArray(r))return r.map(e=>jn(e));if(typeof r!="string")return r;try{return new An.ObjectId(r)}catch{return r}}function vr(r){if(Array.isArray(r))return{op:"in",value:r};if(r instanceof An.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 Ht(r,e,t),o=[],s={},a={};if(n&&typeof n=="object")for(let[d,g]of Object.entries(n))if(typeof g=="object"&&g!==null){let y=Object.keys(g)[0];y&&["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"].includes(y)?s[d]=g:a[d]=g}else s[d]=g;if(Object.keys(s).length>0){let d={};for(let[g,y]of Object.entries(s))if(typeof y=="object"&&y!==null)for(let[h,m]of Object.entries(y))en(r,d,e,g,h,m);else d[g]=y;Object.keys(d).length>0&&o.push({$match:d})}let l=r?.tables?.get(e)?.relations||[],f=[];for(let[d,g]of Object.entries(a))if(!i.relations.some(h=>h.propertyName===d)){let h=l.find(m=>m.propertyName===d);if(h){let m="",b="";if(h.type==="many-to-one"||h.type==="one-to-one")m=H(h)||h.propertyName,b="_id";else if(h.type==="one-to-many")m="_id",b=W(h)||h.propertyName;else if(h.type==="many-to-many")continue;let $=h.type==="one-to-many"||h.type==="many-to-many";f.push({propertyName:d,targetTable:h.targetTableName,localField:m,foreignField:b,type:$?"many":"one",nestedFields:[]})}}let c=[...i.relations,...f];for(let d of c){let g=a[d.propertyName],y=d.nestedFields&&d.nestedFields.length>0?await At(r,d.targetTable,d.nestedFields,g):g?await At(r,d.targetTable,["_id"],g):[];d.type==="one"&&y.length>0&&y.push({$limit:1}),o.push({$lookup:{from:d.targetTable,localField:d.localField,foreignField:d.foreignField,as:d.propertyName,pipeline:y.length>0?y:void 0}}),d.type==="one"&&(o.push({$unwind:{path:`$${d.propertyName}`,preserveNullAndEmptyArrays:!0}}),g&&(Ze(g)||o.push({$match:{[d.propertyName]:{$ne:null}}})))}let p=l.filter(d=>!c.some(g=>g.propertyName===d.propertyName));if(i.scalarFields.length>0||i.relations.length>0||p.length>0){let d={_id:1};for(let y of i.scalarFields)d[y]=1;for(let y of c)d[y.propertyName]=1,y.type==="one"&&y.localField&&y.localField!==y.propertyName&&(d[y.localField]=1);if(t.includes("*"))for(let y of p){if(y.type==="one-to-many"||y.type==="many-to-many")continue;y.type==="many-to-many"?d[y.propertyName]={$map:{input:`$${y.propertyName}`,as:"item",in:{_id:"$$item"}}}:d[y.propertyName]={$cond:{if:{$ne:[`$${y.propertyName}`,null]},then:{_id:`$${y.propertyName}`},else:null}}}o.push({$project:d})}return o}async function Ir(r,e,t,n,i){let o=r?.tables?.get(t),s=o?.relations||[],a=o?.columns||[],u=s.filter(f=>!i.some(c=>c.propertyName===f.propertyName)),l=n.length===a.length||n.length===0&&i.length===0;if(u.length>0||!l){let f={_id:1};for(let c of n)f[c]=1;for(let c of i)f[c.propertyName]=1,c.type==="one"&&c.localField&&c.localField!==c.propertyName&&(f[c.localField]=1);for(let c of u){if(c.type==="one-to-many"||c.type==="many-to-many")continue;c.type==="many-to-many"?f[c.propertyName]={$map:{input:`$${c.propertyName}`,as:"item",in:{_id:"$$item"}}}:f[c.propertyName]={$cond:{if:{$ne:[`$${c.propertyName}`,null]},then:{_id:`$${c.propertyName}`},else:null}}}e.push({$project:f})}}function 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}tt();var Ot=require("mongodb");tt();ln();var nt=class{constructor(e,t,n){this.db=e;this.metadata=t;this.fieldRenamesByTable=n;this.pkField="_id"}normalizeMetadata(){return this.metadata?this.metadata.tables?this.metadata:{tables:new Map(Object.entries(this.metadata))}:this.metadata}buildSortFromTokens(e){let t={};for(let n of this.parseSortTokens(e)){let i=n.field.split(".");if(i.length===1)t[i[0]]=n.order;else{let o=`__sort_${i.slice(0,-1).join("_")}`;t[`${o}.${i[i.length-1]}`]=n.order}}return Object.keys(t).length>0?t:void 0}parseSortTokens(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).map(n=>{let i=n.startsWith("-");return{field:i?n.slice(1):n,order:i?-1:1}}):[]}hasDottedSort(e){return e?(Array.isArray(e)?e:e.split(",").map(n=>n.trim()).filter(Boolean)).some(n=>(n.startsWith("-")?n.slice(1):n).includes(".")):!1}buildSortAggregatePipeline(e,t,n){let i=Array.isArray(n)?n:n.split(",").map(l=>l.trim()).filter(Boolean),o=[{$match:t}],s=new Set;for(let l of i){let c=(l.startsWith("-")?l.slice(1):l).split(".");if(c.length<=1)continue;let p=e;for(let d=0;d<c.length-1;d++){let g=c[d],y=this.normalizeMetadata()?.tables?.get(p);if(!y)break;let h=y.relations?.find($=>$.propertyName===g);if(!h)break;let m=h.targetTableName||h.targetTable,b=`__sort_${c.slice(0,d+1).join("_")}`;if(!s.has(b)){s.add(b);let $=H(h)||h.propertyName,w=d===0?null:`__sort_${c.slice(0,d).join("_")}`,S=w?`${w}.${$}`:$;o.push({$lookup:{from:m,localField:S,foreignField:"_id",as:b}},{$unwind:{path:`$${b}`,preserveNullAndEmptyArrays:!0}})}p=m}}let a=this.buildSortFromTokens(n);a&&o.push({$sort:a});let u={};for(let l of s)u[l]=0;return Object.keys(u).length>0&&o.push({$project:u}),o}toObjectId(e){try{return typeof e=="string"?new Ot.ObjectId(e):e}catch{return e}}compareSortValues(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:e instanceof Ot.ObjectId||t instanceof Ot.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 Ot.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}=et(e),o={},s=!1;if(n.includes("*")){s=!0;for(let p of t.relations||[])i.has(p.propertyName)||i.set(p.propertyName,["_id"])}else for(let p of n){let d=t.columns.find(g=>g.name===p);d?o[d.name]=1:t.relations?.find(y=>y.propertyName===p)&&!i.has(p)&&i.set(p,["_id"])}i.forEach((p,d)=>{let g=t.relations?.find(y=>y.propertyName===d);g&&(g.type==="many-to-one"||g.type==="one-to-one"&&!g.isInverse)&&(s||(o[H(g)||g.propertyName]=1))}),s||(o._id=1);let a=[];i.forEach((p,d)=>{let g=t.relations?.find(b=>b.propertyName===d);if(!g)return;let y=g.targetTableName||g.targetTable;if(!y)return;let h,m;g.type==="many-to-one"||g.type==="one-to-one"?Be(g)?(h="_id",m=W(g)||g.propertyName):(h=H(g)||g.propertyName,m="_id"):g.type==="one-to-many"?(h="_id",m=W(g)||g.propertyName):g.type==="many-to-many"&&(g.isInverse?(h="_id",m=g.mappedBy):(h=g.propertyName,m="_id")),a.push({relationName:d,type:g.type,targetTable:y,fields:p,isInverse:g.isInverse,fkColumn:g.foreignKeyColumn,mappedBy:g.mappedBy,junctionTableName:g.junctionTableName,junctionSourceColumn:g.junctionSourceColumn,junctionTargetColumn:g.junctionTargetColumn,localField:h,foreignField:m})});let u=!s&&Object.keys(o).length===1&&o._id===1&&a.length===0,l=this.fieldRenamesByTable?.get(t.name)??[],f=[];if(!s&&l.length>0)for(let p of l)o[p.newName]===1&&o[p.oldName]!==1&&(o[p.oldName]=1,f.push(p.oldName));return{isPkOnly:u,nestedDescs:a,fetchSpec:{projection:s?void 0:o,pendingRenames:l,hiddenFields:f}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?de(this.normalizeMetadata(),i.userFilter,e):null,s=this.buildSortFromTokens(i?.userSort),a=await Y(t,u=>{let l={_id:{$in:u}};o&&Object.keys(o).length>0&&Object.assign(l,o);let f={projection:n.projection};return s&&(f.sort=s),this.db.collection(e).find(l,f).toArray()});return this.applyReadFallback(a,n)}async fetchInverse(e,t,n,i,o){let s=i.projection?{...i.projection}:void 0;s&&s[t]===void 0&&(s[t]=1);let a=n.filter(h=>h!=null).map(h=>this.toObjectId(h)),u=o?.userFilter?de(this.normalizeMetadata(),o.userFilter,e):null,l=o?.userLimit,f=o?.userPage,c=this.hasDottedSort(o?.userSort);if(l!==void 0&&l>0){let h=f?(f-1)*l:0,m=await ge(a,async $=>{let w={[t]:$};if(u&&Object.keys(u).length>0&&Object.assign(w,u),c){let _=this.buildSortAggregatePipeline(e,w,o.userSort);h>0&&_.push({$skip:h}),_.push({$limit:l}),s&&_.push({$project:s});let N=await this.db.collection(e).aggregate(_).toArray();return this.applyReadFallback(N,i)}let k={sort:this.buildSortFromTokens(o?.userSort)||{_id:1}};s&&(k.projection=s);let v=this.db.collection(e).find(w,k);return h>0&&v.skip(h),v.limit(l),this.applyReadFallback(await v.toArray(),i)},te),b=[];for(let[$,w]of m.entries()){let S=a.find(k=>this.keyOf(k)===$);for(let k of w)k[t]||(k[t]=S??$),b.push(k)}return{docs:b,groupKeyField:t}}if(s&&(s[t]=1),c){let h=[],m=await ge(a,async b=>{let $={[t]:b};u&&Object.keys(u).length>0&&Object.assign($,u);let w=this.buildSortAggregatePipeline(e,$,o.userSort);s&&w.push({$project:s});let S=await this.db.collection(e).aggregate(w).toArray();return this.applyReadFallback(S,i)},te);for(let b of m.values())for(let $ of b)h.push($);return{docs:h,groupKeyField:t}}let p={[t]:{$in:a}};u&&Object.keys(u).length>0&&Object.assign(p,u);let d=this.buildSortFromTokens(o?.userSort)||{_id:1},g={projection:s,sort:d},y=await Y(a,h=>this.db.collection(e).find({[t]:{$in:h},...u||{}},g).toArray());return{docs:this.applyReadFallback(y,i),groupKeyField:t}}postProcessInverseChild(e,t,n){n||delete e[t]}async fetchM2M(e,t,n,i,o){let s=n?.name;if(!s)throw new Error(`Missing parentMeta.name for M2M batch fetch: ${t.relationName}`);let a=we(s,{type:"many-to-many",propertyName:t.relationName,targetTable:t.targetTable,mappedBy:t.isInverse?t.mappedBy:void 0,junctionTableName:t.junctionTableName,junctionSourceColumn:t.junctionSourceColumn,junctionTargetColumn:t.junctionTargetColumn});if(!a)throw new Error(`Failed to resolve junction info for ${s}.${t.relationName}`);let u=e.map(w=>w._id).filter(w=>w!=null),l=new Map;for(let w of e)l.set(this.keyOf(w._id),[]);if(u.length===0)return{grouped:l,docs:[]};let f=await Y(u,w=>this.db.collection(a.junctionName).find({[a.selfColumn]:{$in:w}},{projection:{_id:0,[a.selfColumn]:1,[a.otherColumn]:1}}).toArray());if(f.length===0)return{grouped:l,docs:[]};let c=t.userFilter?de(this.normalizeMetadata(),t.userFilter,t.targetTable):null,p=t.userLimit,d=t.userPage;if(p!==void 0&&p>0){let w=d?(d-1)*p:0,S=await ge(u,async v=>{let N=(await this.db.collection(a.junctionName).find({[a.selfColumn]:v},{projection:{_id:0,[a.otherColumn]:1}}).toArray()).map(L=>L[a.otherColumn]).filter(L=>L!=null);if(N.length===0)return[];let I={_id:{$in:N}};if(c&&Object.keys(c).length>0&&Object.assign(I,c),this.hasDottedSort(t.userSort)){let L=this.buildSortAggregatePipeline(t.targetTable,I,t.userSort);w>0&&L.push({$skip:w}),L.push({$limit:p}),o.projection&&L.push({$project:o.projection});let T=await this.db.collection(t.targetTable).aggregate(L).toArray();return this.applyReadFallback(T,o)}let D={sort:this.buildSortFromTokens(t.userSort)||{_id:1}};o.projection&&(D.projection=o.projection);let P=this.db.collection(t.targetTable).find(I,D);return w>0&&P.skip(w),P.limit(p),this.applyReadFallback(await P.toArray(),o)},te),k=[];for(let[v,_]of S.entries()){l.set(v,_);for(let N of _)k.push(N)}return{grouped:l,docs:k}}let g=new Set,y=[];for(let w of f){let S=w[a.otherColumn];if(S==null)continue;let k=this.keyOf(S);g.has(k)||(g.add(k),y.push(S))}let h=o.projection&&Object.keys(o.projection).length===1&&o.projection._id===1&&!c,m=[],b=new Map;if(h)m=y.map(w=>({_id:w})),this.sortDocsByPk(m);else{let w={_id:{$in:y}};c&&Object.keys(c).length>0&&Object.assign(w,c);let S=this.hasDottedSort(t.userSort),k;if(S){let v=this.buildSortAggregatePipeline(t.targetTable,w,t.userSort);o.projection&&v.push({$project:o.projection}),k=await this.db.collection(t.targetTable).aggregate(v).toArray()}else{let v=this.buildSortFromTokens(t.userSort)||{_id:1},_=this.projectionWithSortFields(o.projection,t.userSort),N={sort:v};_.projection&&(N.projection=_.projection),k=await Y(y,I=>this.db.collection(t.targetTable).find({_id:{$in:I},...c||{}},N).toArray()),t.userSort?this.sortDocsInMemory(k,t.userSort):this.sortDocsByPk(k),this.removeHiddenFields(k,_.hiddenFields)}m=this.applyReadFallback(k,o)}for(let w of m)b.set(this.keyOf(w._id),w);let $=new Map;for(let w of f){let S=this.keyOf(w[a.selfColumn]),k=this.keyOf(w[a.otherColumn]);b.has(k)&&($.has(k)||$.set(k,[]),$.get(k).push(S))}for(let w of m){let S=$.get(this.keyOf(w._id))||[];for(let k of S)l.get(k)?.push(w)}return{grouped:l,docs:m}}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 cn(r,e,t,n,i=3,o=0,s,a,u,l){let f=await l?.getActiveFieldRenamesByTable?.(),c=new nt(r,a,f);await new ke(c,n,u).execute(e,t,i,o,s)}async function Dn(r,e,t){let n=[],{db:i,metadata:o,dbType:s,debugLog:a}=t,u=o?.tables?.get(e.table),l=new Set((u?.relations??[]).map(_=>_.propertyName)),f=!!e.mongoRawFilter&&!!o&&ie(e.mongoRawFilter,l),c=e.plan,p=c?.filterTree&&!c.hasRelationFilters&&!e.where;if(e.mongoRawFilter&&o&&f){let _=await pe(e.mongoRawFilter,e.table,o,i);_&&Object.keys(_).length>0&&n.push({$match:_})}else if(p){let _=Ke(c.filterTree,{metadata:o,rootTable:e.table});Object.keys(_).length>0&&n.push({$match:_})}else if(e.where){console.warn(`[mongo-executor:fallback] whereToMongoFilter path hit for table=${e.table} where=${JSON.stringify(e.where)}`);let _=Ye(o,e.where,e.table,s);n.push({$match:_})}let d=e.plan,y=d?d.hasRelationSort:e.sort?.some(_=>{if(!_.field.includes("."))return!1;let N=_.field.split(".")[0];return e.mongoFieldsExpanded?.relations?.some(I=>I.propertyName===N)??!1})??!1,h=()=>d?.sortItems?to(d.sortItems):e.sort?eo(e.sort):null,m=d?.sortItems?Yi(d.sortItems):[],b=()=>{!d||m.length===0||Xi(n,e.table,d.sortItems,o)},$=()=>{m.length===0||e.mongoCountOnly||n.push({$project:Object.fromEntries(m.map(_=>[_,0]))})};if(!e.mongoFieldsExpanded){b();let _=h();if(_&&n.push({$sort:_}),e.mongoCountOnly?n.push({$count:"count"}):(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit})),$(),e.select){let I={};for(let O of e.select)I[O]=1;n.push({$project:I})}a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let N=await r.aggregate(n).toArray();return e.mongoCountOnly?{results:N,pipeline:n}:{results:Nr(N),pipeline:n}}let{scalarFields:w,relations:S}=e.mongoFieldsExpanded;if(!y){b();let _=h();_&&n.push({$sort:_}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}let k=[];for(let _ of S)if(e.sort?.some(I=>I.field.startsWith(`${_.propertyName}.`))){let I=e.mongoRawFilter?.[_.propertyName];if(_.nestedFields&&_.nestedFields.length>0){let M=await At(o,_.targetTable,_.nestedFields??[],I);_.type==="one"&&M.length>0&&M.push({$limit:1}),n.push({$lookup:{from:_.targetTable,localField:_.localField,foreignField:_.foreignField,as:_.propertyName,pipeline:M.length>0?M:void 0}})}else if(I){let M=await At(o,_.targetTable,["_id"],I);_.type==="one"&&M.length>0&&M.push({$limit:1}),n.push({$lookup:{from:_.targetTable,localField:_.localField,foreignField:_.foreignField,as:_.propertyName,pipeline:M.length>0?M:void 0}})}else n.push({$lookup:{from:_.targetTable,localField:_.localField,foreignField:_.foreignField,as:_.propertyName}});_.type==="one"&&(n.push({$unwind:{path:`$${_.propertyName}`,preserveNullAndEmptyArrays:!0}}),I&&(rt(I)||n.push({$match:{[_.propertyName]:{$ne:null}}})))}else k.push(_);if(y){b();let _=h();_&&n.push({$sort:_}),e.mongoCountOnly||(e.offset&&n.push({$skip:e.offset}),e.limit!==void 0&&e.limit!==null&&e.limit>0&&n.push({$limit:e.limit}))}await Ir(o,n,e.table,w,[...S]),e.mongoCountOnly&&n.push({$count:"count"}),a&&a.push({type:"MongoDB Aggregation Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(n))});let v=await r.aggregate(n).toArray();if(e.mongoCountOnly)return{results:v,pipeline:n};if(k.length>0&&v.length>0){let _=e.deep||{},N=k.map(O=>{let D=o?.tables?.get(e.table)?.relations?.find(T=>T.propertyName===O.propertyName),P=_[O.propertyName],L=P?.fields!=null?Array.isArray(P.fields)?P.fields:String(P.fields).split(",").map(T=>T.trim()).filter(Boolean):O.nestedFields&&O.nestedFields.length>0?O.nestedFields:["_id"];return{relationName:O.propertyName,type:D?.type,targetTable:O.targetTable,fields:L,isInverse:D?.isInverse,mappedBy:D?.mappedBy,junctionTableName:D?.junctionTableName,localField:O.localField,foreignField:O.foreignField,userFilter:P?.filter,userSort:P?.sort,userLimit:P?.limit!==void 0?Number(P.limit):void 0,userPage:P?.page!==void 0?Number(P.page):void 0,nestedDeep:P?.deep}}),I=Zi(o);I&&await cn(i,v,N,I,3,0,e.table,o,void 0,t.mongoPhysicalMigrationService)}return{results:Nr(v),pipeline:n}}function Kn(r){return`__sort_count_${r.relationName||r.field}`}function Yi(r){return r.filter(e=>e.function==="count").map(Kn)}function Xi(r,e,t,n){let i=n?.tables?.get(e),o=i?.columns?.find(s=>s.isPrimary)?.name||(i?.columns?.some(s=>s.name==="_id")?"_id":"id");for(let s of t){if(s.function!=="count")continue;let a=s.relationMeta,u=s.relationName||s.field,l=a?.targetTableName||a?.targetTable,f=Kn(s);if(!(!a||!l)){if(a.type==="one-to-many"){let c=W(a)||u;r.push({$lookup:{from:l,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${c}`,"$$localId"]}}},{$count:"value"}],as:f}}),r.push({$addFields:{[f]:{$ifNull:[{$arrayElemAt:[`$${f}.value`,0]},0]}}});continue}if(a.type==="many-to-many"){let c=we(e,a);if(!c)continue;r.push({$lookup:{from:c.junctionName,let:{localId:`$${o}`},pipeline:[{$match:{$expr:{$eq:[`$${c.selfColumn}`,"$$localId"]}}},{$count:"value"}],as:f}}),r.push({$addFields:{[f]:{$ifNull:[{$arrayElemAt:[`$${f}.value`,0]},0]}}})}}}}function Zi(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 eo(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 to(r){let e={};for(let t of r){let n=t.function==="count"?Kn(t):t.joinId!==null?t.fullPath:t.field;n==="id"&&(n="_id"),e[n]=t.direction==="asc"?1:-1}return e}function rt(r){if(!r||typeof r!="object")return!1;if(r===null)return!0;if(Array.isArray(r))return r.some(e=>rt(e));if("_or"in r&&Array.isArray(r._or))return r._or.some(e=>rt(e));if("_and"in r&&Array.isArray(r._and))return r._and.some(e=>rt(e));if("_not"in r)return rt(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||rt(t)))return!0}return!1}function Nr(r){return r.map(re)}function Mr(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(no(o,i,e));return{scalarFields:t,relations:n}}function no(r,e,t){let n=e.relations?.find(l=>l.propertyName===r.propertyName),i,o,s=!1;r.relationType==="many-to-one"||r.relationType==="one-to-one"?n&&Be(n)?(i="_id",o=W(n)||r.propertyName,s=!0):(i=n&&H(n)||r.propertyName,o="_id",s=!1):r.relationType==="one-to-many"?(i="_id",o=n&&W(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=Ar(r.children);return{propertyName:r.propertyName,targetTable:r.targetTable,localField:i,foreignField:o,type:a?"many":"one",isInverse:s,nestedFields:u}}function Ar(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=Ar(t.children);if(n.length===0)e.push(`${t.propertyName}.id`);else for(let i of n)e.push(`${t.propertyName}.${i}`)}return e}Xe();Nt();It();function un(r,e,t,n){let i={rootTable:e,nodes:[]};if(!r||r.length===0)return i;let o=t?.tables?.get(e);if(!o)return i;let s=o.columns?.some(c=>c.name==="_id"&&c.isPrimary),a=o.columns?.some(c=>c.name==="id"),u=s&&!a?"_id":"id",l=new Map,f=[];for(let c of r){let p=c==="id"?u:c;if(p==="*")f.push("*");else if(p.includes(".")){let d=p.indexOf("."),g=p.substring(0,d),y=p.substring(d+1);if(!o.relations?.some(m=>m.propertyName===g))continue;l.has(g)||l.set(g,[]),l.get(g).push(y)}else if(o.relations?.some(g=>g.propertyName===p))l.has(p)||l.set(p,[u]);else{if(!o.columns?.some(y=>y.name===p))continue;f.push(p)}}if(f.includes("*")){i.nodes.push({kind:"wildcard"});for(let c of o.relations||[])l.has(c.propertyName)||l.set(c.propertyName,[u])}else for(let c of f)i.nodes.push({kind:"scalar",name:c});for(let[c,p]of l.entries()){let d=o.relations?.find(h=>h.propertyName===c);if(!d)continue;let g=d.targetTableName||d.targetTable,y={kind:"relation",propertyName:c,joinId:null,relationType:d.type,isInverse:!!d.isInverse,targetTable:g,children:Or(p,g,t)};if(d.type==="many-to-one"||d.type==="one-to-one"){let h=n.registerWithParent(e,c,t,"left",null,"data");y.joinId=h}i.nodes.push(y)}return i}function Or(r,e,t){let n=t?.tables?.get(e);if(!n)return[];let i=n.columns?.some(f=>f.name==="_id"&&f.isPrimary),o=n.columns?.some(f=>f.name==="id"),s=i&&!o?"_id":"id",a=new Map,u=[];for(let f of r){let c=f==="id"?s:f;if(c==="*")u.push("*");else if(c.includes(".")){let p=c.indexOf("."),d=c.substring(0,p),g=c.substring(p+1);if(!n.relations?.some(h=>h.propertyName===d))continue;a.has(d)||a.set(d,[]),a.get(d).push(g)}else if(n.relations?.some(d=>d.propertyName===c))a.has(c)||a.set(c,[s]);else{if(!n.columns?.some(g=>g.name===c))continue;u.push(c)}}let l=[];if(u.includes("*")){l.push({kind:"wildcard"});for(let f of n.relations||[])a.has(f.propertyName)||a.set(f.propertyName,[s])}else for(let f of u)l.push({kind:"scalar",name:f});for(let[f,c]of a.entries()){let p=n.relations?.find(g=>g.propertyName===f);if(!p)continue;let d=p.targetTableName||p.targetTable;l.push({kind:"relation",propertyName:f,joinId:null,relationType:p.type,isInverse:!!p.isInverse,targetTable:d,children:Or(c,d,t)})}return l}fe();fe();var ro=new Set(["_and","_or","_not"]);function Er(r,e){return r?.tables?.get(e)??null}function io(r,e,t){return Er(r,e)?.columns?.find(n=>n.name===t)}function Pr(r,e,t){return Er(r,e)?.relations?.find(n=>n.propertyName===t)}function jr(r,e,t,n){if(io(r,e,t)?.isEncrypted===!0)throw new x(`Encrypted field '${t}' on '${e}' cannot be used for ${n}.`)}function We(r,e,t){if(!(!r||typeof r!="object")){if(Array.isArray(r)){for(let n of r)We(n,e,t);return}for(let[n,i]of Object.entries(r)){if(ro.has(n)){We(i,e,t);continue}if(n.startsWith("_"))continue;let o=Pr(t,e,n);if(o){let s=o.targetTableName||o.targetTable;s&&We(i,s,t);continue}jr(t,e,n,"filter")}}}function fn(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||o.startsWith("_count("))continue;let s=o.split("."),a=e;for(let u=0;u<s.length;u++){let l=s[u];if(u===s.length-1){jr(t,a,l,"sort");break}let c=Pr(t,a,l);if(!c)break;a=c.targetTableName||c.targetTable||a}}}var Q=class{plan(e){let{tableName:t,fields:n,filter:i,sort:o,page:s,limit:a,meta:u,metadata:l,dbType:f}=e,c=l?.tables?.get(t),p=new oe,d=this.parseFields(n),g=null;d&&c&&(g=un(d,t,l,p));let y=!1,h=null;if(i&&c){We(i,t,l);let O=Te(i,t,l,p);h=O.node,y=O.hasRelationFilters}let m=this.parseSort(o);c&&fn(m,t,l);let b=[],$=!1;for(let O of m){let M=O.startsWith("-"),D=M?O.substring(1):O,P=M?"desc":"asc";if(c){let L=this.parseRelationCountSort(t,c,D);if(L){b.push({joinId:null,field:D,direction:P,fullPath:D,function:"count",relationName:L.relationName,relationMeta:L.relationMeta});continue}this.assertLocalSortField(t,c,D)}b.push({joinId:null,field:D,direction:P,fullPath:D})}b.length===0&&b.push({joinId:null,field:"id",direction:"asc",fullPath:"id"});let w=this.parseLimit(a),S=this.parsePage(s),k=S!==void 0&&w!==void 0?(S-1)*w:void 0,v=this.parseMeta(u),_=v.includes("totalCount")||v.includes("*"),N=v.includes("filterCount")||v.includes("*"),I=p.getAll();return{table:t,dbType:f,rawFields:d,rawFilter:i??null,joins:I,sortItems:b,limit:w,offset:k,needsTotalCount:_,needsFilterCount:N,hasRelationFilters:y,hasRelationSort:$,filterTree:h,fieldTree:g}}parseFields(e){if(e)return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):e.split(",").map(t=>t.trim()).filter(Boolean)}parseSort(e){return e?(Array.isArray(e)?e:e.split(",")).map(n=>n.trim()).filter(Boolean):[]}parseLimit(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;if(!Number.isNaN(t))return t<0?0:t}parsePage(e){if(e==null)return;let t=typeof e=="string"?parseInt(e,10):e;return Number.isNaN(t)?void 0:t}parseMeta(e){return e?Array.isArray(e)?e:e.split(",").map(t=>t.trim()).filter(Boolean):[]}assertLocalSortField(e,t,n){if(n.includes("."))throw new x(`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 x(`Sort field '${n}' does not exist on '${e}'. Sort only by fields defined on the table metadata.`)}parseRelationCountSort(e,t,n){if(!n.startsWith("_count"))return null;let i=n.match(/^_count\(([^)]+)\)$/);if(!i)throw new x(`Sort function '${n}' is not supported on '${e}'. Use _count(relationName).`);let o=i[1].trim();if(!o||o.includes("."))throw new x(`Sort function '${n}' is not supported on '${e}'. Use a direct relation name in _count().`);let s=t.relations?.find(a=>a.propertyName===o);if(!s)throw new x(`Sort relation '${o}' does not exist on '${e}'.`);if(s.type!=="one-to-many"&&s.type!=="many-to-many")throw new x(`Sort function '_count(${o})' is only supported for list relations on '${e}'.`);return{relationName:o,relationMeta:s}}registerSortJoinChain(e,t,n,i,o){let s=e.indexOf(".");if(s===-1)return null;let a=e.slice(0,s),u=e.slice(s+1),l=n?.tables?.get(t);if(!l)return null;let f=l.relations?.find(d=>d.propertyName===a);if(!f||f.type!=="many-to-one"&&f.type!=="one-to-one")return null;let c=i.registerWithParent(t,a,n,"left",o,"sort");if(!c)return null;if(!u.includes("."))return{lastJoinId:c,field:u};let p=f.targetTableName||f.targetTable;return this.registerSortJoinChain(u,p,n,i,c)}};fe();vt();var oo=new Set(["count","sum","avg","min","max","countRecords"]),so=new Set(["int","integer","bigint","float","double","decimal","numeric","real","number"]),ao=new Set(["_and","_or","_not"]);function Fe(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function E(r,e){let t=r.replace(/^aggregate\./,"");throw new x(e,{path:r,aggregate:{[t]:e}})}function lo(r){return typeof r!="string"?!1:so.has(r.toLowerCase())}function Lr(r){return Object.keys(r).length===0}function co(r,e,t){return r===!0?{}:(r==null&&E(t,`aggregate.${e} condition must be true or an object`),Fe(r)||E(t,`aggregate.${e} condition must be true or an object`),r)}function uo(r,e,t){let n=r?.tables?.get(e);return n||E(t,`Table "${e}" metadata is not available`),n}function Br(r,e){let t=r?.targetTableName??r?.targetTable;return(typeof t!="string"||t.length===0)&&E(e,"aggregate.countRecords relation target is not available"),t}function dn(r,e,t,n){let i=uo(t,e,n);for(let[o,s]of Object.entries(r)){if(o==="_and"||o==="_or"){Array.isArray(s)||E(n,`aggregate.countRecords ${o} condition must be an array`);for(let f of s)Fe(f)||E(n,`aggregate.countRecords ${o} items must be objects`),dn(f,e,t,n);continue}if(o==="_not"){Fe(s)||E(n,"aggregate.countRecords _not condition must be an object"),dn(s,e,t,n);continue}(o.startsWith("_")||ao.has(o))&&E(n,`Unsupported aggregate.countRecords condition key "${o}"`);let a=i.columns?.find(f=>f.name===o),u=i.relations?.find(f=>f.propertyName===o);if(!a&&!u&&E(n,`Unknown aggregate.countRecords field or relation "${o}" on table "${e}"`),Fe(s)||E(n,`aggregate.countRecords condition for "${o}" must be an object`),a){for(let f of Object.keys(s))ee.has(f)||E(n,`aggregate.countRecords condition for "${o}" only supports field operators`);continue}let l=Br(u,n);dn(s,l,t,n)}}function Wn(r){return Fe(r)&&Object.keys(r).length>0}function it(r,e,t){if(!Wn(r))return[];Fe(r)||E("aggregate","aggregate must be an object");let n=t?.tables?.get(e);n||E("aggregate",`Table "${e}" metadata is not available`);let i=[];for(let[o,s]of Object.entries(r)){let a=`aggregate.${o}`;(!o||typeof o!="string")&&E("aggregate","aggregate field name must be a non-empty string"),Fe(s)||E(a,"aggregate field config must be an object");let u=o,l=a,f=n.columns?.find(d=>d.name===o),c=n.relations?.find(d=>d.propertyName===o);!f&&!c&&E(l,`Unknown aggregate field or relation "${o}" on table "${e}"`);let p=Object.entries(s).filter(([d])=>d!=="as");p.length===0&&E(l,"aggregate field must define at least one operation");for(let[d,g]of p){oo.has(d)||E(l,`Unsupported aggregate operation "${d}"`);let y=co(g,d,l);if(c&&d!=="countRecords"&&E(l,`aggregate.${d} is not supported on relation "${o}"; use countRecords`),f&&d==="countRecords"&&E(l,`aggregate.countRecords requires a relation, but "${o}" is a field`),f&&(d==="sum"||d==="avg")&&!lo(f.type)&&E(l,`aggregate.${d} requires a numeric field, but "${o}" is "${f.type}"`),f)for(let h of Object.keys(y))ee.has(h)||E(l,`aggregate.${d} condition for "${o}" only supports field operators`);if(c&&d==="countRecords"){let h=Br(c,l);dn(y,h,t,l)}i.push({field:o,outputKey:u,path:l,op:d,condition:y})}}return i}function ot(r,e){let t=[];return Fe(r)&&!Lr(r)&&t.push(r),Lr(e.condition)||t.push({[e.field]:e.condition}),t.length===0?{}:t.length===1?t[0]:{_and:t}}function Ce(r,e,t){r[e.outputKey]??={},r[e.outputKey][e.op]=t}var st=class{constructor(e,t){this.mongoService=e;this.mongoPhysicalMigrationService=t;this.debugLog=[];this.lastBuiltPipeline=null;this.db=e.getDb()}async execute(e){if(this.metadata=e.metadata,this.dbType=e.dbType||"mongodb",!e.plan){let p=new Q;e={...e,plan:p.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:"mongodb"})}}let t=e.debugLog||[];this.debugLog=t;let n={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};if(e.pipeline&&(n.pipeline=e.pipeline),e.fields&&(Array.isArray(e.fields)?n.fields=e.fields:typeof e.fields=="string"&&(n.fields=e.fields.split(",").map(p=>p.trim()))),e.filter&&(U(e.filter,e.tableName,e.metadata),n.mongoRawFilter=e.filter),e.sort){let p=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(d=>d.trim());n.sort=p.map(d=>{let g=d.trim();return g.startsWith("-")?{field:g.substring(1),direction:"desc"}:{field:g,direction:"asc"}})}else n.sort=[{field:"id",direction:"asc"}];if(e.page&&e.limit){let p=typeof e.page=="string"?parseInt(e.page,10):e.page,d=typeof e.limit=="string"?parseInt(e.limit,10):e.limit;n.offset=(p-1)*d,n.limit=d}else e.limit&&(n.limit=typeof e.limit=="string"?parseInt(e.limit,10):e.limit);let i=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(p=>p.trim()).filter(Boolean),o=0,s=0;(i.includes("totalCount")||i.includes("*"))&&(o=await this.mongoService.collection(e.tableName).countDocuments({}));let a=this.metadata?.tables?.get(e.tableName),u=new Set((a?.relations??[]).map(p=>p.propertyName)),l=!!n.mongoRawFilter&&ie(n.mongoRawFilter,u);if((i.includes("filterCount")||i.includes("*"))&&!l){let p=this.mongoService.collection(e.tableName),d=e.plan?.filterTree?Ke(e.plan.filterTree,{metadata:this.metadata,rootTable:e.tableName}):{};s=await p.countDocuments(d)}this.lastBuiltPipeline=null,n.plan=e.plan,n.deep=e.deep;let f=await this.selectLegacy(n);if(e.debugMode){let p=this.lastBuiltPipeline??[],d;try{d=await this.db.collection(e.tableName).aggregate(p).explain()}catch(g){d={error:String(g)}}return{pipeline:p,explain:d}}if(l&&(i.includes("filterCount")||i.includes("*"))){let p={...n,mongoCountOnly:!0},d=await this.selectLegacy(p);s=d.length>0?d[0].count:0}let c=await this.executeAggregate(n,e.filter);return{data:f,...(i.length>0||c)&&{meta:{...i.includes("totalCount")||i.includes("*")?{totalCount:o}:{},...i.includes("filterCount")||i.includes("*")?{filterCount:s}:{},...c?{aggregate:c}:{}}}}}async selectLegacy(e){let t=[];if(e.fields&&e.fields.length>0){let s=e.plan;if(s?.fieldTree?e.mongoFieldsExpanded=Mr(s.fieldTree,this.metadata):(console.warn(`[mongo-executor:fallback] expandFieldsMongo path hit for table=${e.table} fields=${JSON.stringify(e.fields)}`),e.mongoFieldsExpanded=await Ht(this.metadata,e.table,e.fields)),this.mongoPhysicalMigrationService&&e.mongoFieldsExpanded){let a=await this.mongoPhysicalMigrationService.augmentScalarProjection(e.table,e.mongoFieldsExpanded.scalarFields);e.mongoFieldsExpanded={...e.mongoFieldsExpanded,scalarFields:a.scalarFields},t=a.hiddenFields}}e.where&&(e.where=e.where.map(s=>s.field.includes(".")?s:{...s,field:`${e.table}.${s.field}`}));let n=this.db.collection(e.table);if(e.pipeline)return this.debugLog&&this.debugLog.push({type:"MongoDB Custom Pipeline",collection:e.table,pipeline:JSON.parse(JSON.stringify(e.pipeline))}),(await n.aggregate(e.pipeline).toArray()).map(re);let{results:i,pipeline:o}=await Dn(n,e,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=o,this.mongoPhysicalMigrationService?await this.mongoPhysicalMigrationService.applyReadFallback(e.table,i,t):i}async executeAggregationPipeline(e,t){let{results:n,pipeline:i}=await Dn(e,t,{db:this.db,metadata:this.metadata,dbType:this.dbType,debugLog:this.debugLog,mongoPhysicalMigrationService:this.mongoPhysicalMigrationService});return this.lastBuiltPipeline=i,n}async executeAggregate(e,t){let n=it(e.aggregate,e.table,e.metadata);if(n.length===0)return;let i={},o=this.db.collection(e.table);for(let s of n){let a=ot(t,s);U(a,e.table,e.metadata);let l=new Q().plan({tableName:e.table,filter:a,metadata:e.metadata,dbType:"mongodb"});if(s.op==="countRecords"){let p=await this.executeRelationCountRecords(e,t,s);Ce(i,s,p);continue}let f=l.hasRelationFilters?await pe(a,e.table,e.metadata,this.db):l.filterTree?Ke(l.filterTree,{metadata:e.metadata,rootTable:e.table}):{},c;if(s.op==="count")c=await o.countDocuments(f);else{let[{value:p}={value:null}]=await o.aggregate([{$match:f},{$group:{_id:null,value:{[`$${s.op}`]:`$${s.field}`}}}]).toArray();c=p??0}Ce(i,s,c)}return i}async executeRelationCountRecords(e,t,n){let o=e.metadata?.tables?.get(e.table)?.relations?.find(f=>f.propertyName===n.field),s=o?.targetTableName||o?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!o||!s||!a)return 0;let u=await this.resolveMatchFilter(e.table,t,e.metadata),l=await this.resolveMatchFilter(s,n.condition,e.metadata);if(o.type==="one-to-many"){let c=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(p=>p._id).filter(p=>p!=null);return c.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{[o.foreignKeyColumn]:{$in:c}}]})}if(o.type==="many-to-many"){let f=we(e.table,o);if(!f)return 0;let p=(await this.db.collection(e.table).find(u,{projection:{_id:1}}).toArray()).map(y=>y._id).filter(y=>y!=null);if(p.length===0)return 0;let g=(await this.db.collection(f.junctionName).find({[f.selfColumn]:{$in:p}},{projection:{[f.otherColumn]:1}}).toArray()).map(y=>y[f.otherColumn]).filter(y=>y!=null);return g.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:g}}]})}if(o.type==="many-to-one"||o.type==="one-to-one"){let f=o.foreignKeyColumn||`${n.field}Id`,p=(await this.db.collection(e.table).find(u,{projection:{[f]:1}}).toArray()).map(d=>d[f]).filter(d=>d!=null);return p.length===0?0:await this.db.collection(s).countDocuments({$and:[l,{_id:{$in:p}}]})}return 0}async resolveMatchFilter(e,t,n){if(!t||Object.keys(t).length===0)return{};U(t,e,n);let o=new Q().plan({tableName:e,filter:t,metadata:n,dbType:"mongodb"});return o.hasRelationFilters?await pe(t,e,n,this.db):o.filterTree?Ke(o.filterTree,{metadata:n,rootTable:e}):{}}};var pn=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}};fe();ae();var fo=["_and","_or","_not"];function he(r){if(!r||typeof r!="object")return!1;if(Array.isArray(r))return r.some(e=>he(e));for(let e of Object.keys(r))if(fo.includes(e)||typeof r[e]=="object"&&r[e]!==null&&he(r[e]))return!0;return!1}var Dr=["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"];function po(r){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in"}[r]||r}function gn(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 go(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)||gn(r,t,i),e}function Kr(r,e,t,n,i,o,s){let a=i&&!e.includes(".")?`${i}.${e}`:e,u=Re(a,o??"postgres"),l=gn(e,i,s),f=go(e,n,i,o,s);switch(t){case"_eq":l&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} = ?::uuid`,[n]):r.where(a,"=",f);break;case"_neq":l&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} != ?::uuid`,[n]):r.where(a,"!=",f);break;case"_gt":l&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} > ?::uuid`,[n]):r.where(a,">",f);break;case"_gte":l&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} >= ?::uuid`,[n]):r.where(a,">=",f);break;case"_lt":l&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} < ?::uuid`,[n]):r.where(a,"<",f);break;case"_lte":l&&o==="postgres"&&typeof n=="string"?r.whereRaw(`${u} <= ?::uuid`,[n]):r.where(a,"<=",f);break;case"_in":let c=n;Array.isArray(c)||(c=typeof c=="string"&&c.includes(",")?c.split(",").map(d=>d.trim()):[c]),l&&o==="postgres"&&c.every(d=>typeof d=="string")?r.whereRaw(`${u} = ANY(?::uuid[])`,[c]):r.whereIn(a,c);break;case"_not_in":case"_nin":let p=n;Array.isArray(p)||(p=typeof p=="string"&&p.includes(",")?p.split(",").map(d=>d.trim()):[p]),l&&o==="postgres"&&p.every(d=>typeof d=="string")?r.whereRaw(`${u} != ALL(?::uuid[])`,[p]):r.whereNotIn(a,p);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,po(t),n)}}function ho(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 at(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(){at(this,s,t,"and",i,o)}):r.orWhere(function(){at(this,s,t,"and",i,o)});return}for(let[s,a]of Object.entries(e))if(ho(s,t,o)){if(s==="_and"){Array.isArray(a)&&r.where(function(){for(let u of a)this.where(function(){at(this,u,t,"and",i,o)})});continue}if(s==="_or"){Array.isArray(a)&&r.where(function(){for(let u of a)this.orWhere(function(){at(this,u,t,"and",i,o)})});continue}if(s==="_not"){r.whereNot(function(){at(this,a,t,"and",i,o)});continue}if(typeof a=="object"&&a!==null)if(Object.keys(a).some(l=>Dr.includes(l)))for(let[l,f]of Object.entries(a))Dr.includes(l)&&(n==="and"?r.where(function(){Kr(this,s,l,f,t,i,o)}):r.orWhere(function(){Kr(this,s,l,f,t,i,o)}));else{let l=t&&!s.includes(".")?`${t}.${s}`:s,f=Re(l,i??"postgres");gn(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(`${f} = ?::uuid`,[a]):r.orWhereRaw(`${f} = ?::uuid`,[a]):n==="and"?r.where(l,"=",a):r.orWhere(l,"=",a)}else{let u=t&&!s.includes(".")?`${t}.${s}`:s,l=Re(u,i??"postgres");gn(s,t,o)&&i==="postgres"&&typeof a=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a)?n==="and"?r.whereRaw(`${l} = ?::uuid`,[a]):r.orWhereRaw(`${l} = ?::uuid`,[a]):n==="and"?r.where(u,"=",a):r.orWhere(u,"=",a)}}}}function le(r,e,t,n,i){return!e||typeof e!="object"||at(r,e,t,"and",n,i),r}ae();function Jn(r,e,t){return`${C(r,t)}.${C(e,t)}`}function xe(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 Wr(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 lt(r){return r===!0||r==="true"?!0:r===!1||r==="false"?!1:null}async function zn(r,e,t,n,i,o){let s=[];for(let[a,u]of Object.entries(o)){let l=await Et(r,e,a,u,t,n,i);if(l!==null)s.push(`EXISTS (${l})`);else{let f=t.relations.find(c=>c.propertyName===a);if(f&&f.foreignKeyColumn){let c=Jn(e,f.foreignKeyColumn,n),d=u.id;if(d&&typeof d=="object"){let g=lt(d._is_null),y=lt(d._is_not_null);if(g===!0)s.push(`${c} IS NULL`);else if(g===!1)s.push(`${c} IS NOT NULL`);else if(y===!0)s.push(`${c} IS NOT NULL`);else if(y===!1)s.push(`${c} IS NULL`);else if(d._eq!==void 0){let h=xe(d._eq,n);s.push(`${c} = ${h}`)}else if(d._neq!==void 0){let h=xe(d._neq,n);s.push(`${c} != ${h}`)}else if(d._in!==void 0){let m=(Array.isArray(d._in)?d._in:[d._in]).map(b=>xe(b,n)).join(", ");s.push(`${c} IN (${m})`)}else if(d._not_in!==void 0||d._nin!==void 0){let h=d._not_in??d._nin,b=(Array.isArray(h)?h:[h]).map($=>xe($,n)).join(", ");s.push(`${c} NOT IN (${b})`)}else if(d._gt!==void 0){let h=xe(d._gt,n);s.push(`${c} > ${h}`)}else if(d._gte!==void 0){let h=xe(d._gte,n);s.push(`${c} >= ${h}`)}else if(d._lt!==void 0){let h=xe(d._lt,n);s.push(`${c} < ${h}`)}else if(d._lte!==void 0){let h=xe(d._lte,n);s.push(`${c} <= ${h}`)}}}}}return s}function Vn(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 Un(r,e,t,n,i,o){let s=[];for(let a of r)if(a._and&&Array.isArray(a._and)&&a._and.length>0){let u=[];for(let l of a._and)if(Vn(l)){let f=e(t).select(`${t}.id`);await Ue(e,f,l,t,n,i,o),u.push({idSubquery:f})}else{let{fieldFilters:f,relationFilters:c}=G(l,n),p=await zn(e,t,n,i,o,c);u.push({fieldFilters:f,subqueries:p})}s.push(u)}else if(Vn(a)){let u=e(t).select(`${t}.id`);await Ue(e,u,a,t,n,i,o),s.push([{idSubquery:u}])}else{let{fieldFilters:u,relationFilters:l}=G(a,n),f=await zn(e,t,n,i,o,l);s.push([{fieldFilters:u,subqueries:f}])}return s}function Ur(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 Qn(r,e,t,n,i){let o=!0;for(let s of e){let a=function(){for(let u of s)Ur(this,u,t,n,i)};o?(r.where(a),o=!1):r.orWhere(a)}}function hn(r,e,t,n,i,o,s){let a=Wr(e,i),u=Wr(n,o),l=`${C(r,s)}.${C(e,s)}`,f=`${C(t,s)}.${C(n,s)}`;if(s==="postgres"){if(a&&!u)return`${l} = ${f}::uuid`;if(!a&&u)return`${l}::uuid = ${f}`}return`${l} = ${f}`}async function Et(r,e,t,n,i,o,s){let a=i.relations.find(p=>p.propertyName===t);if(!a)throw new Error(`Relation "${t}" not found in table "${e}"`);let u=a.targetTableName||a.targetTable;if(!u)throw new Error(`Relation "${t}" in table "${e}" is missing targetTable/targetTableName. Relation metadata: ${JSON.stringify(a,null,2)}`);let l=new Set(["_is_null","_is_not_null","_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]);if((a.type==="many-to-one"||a.type==="one-to-one")&&a.foreignKeyColumn){let p=Object.keys(n||{});if(p.length===1&&p[0]==="id"&&typeof n.id=="object"&&Object.keys(n.id).every(g=>l.has(g)))return null}let f=s?await s(u):null,c;switch(a.type){case"one-to-many":c=r(u).select(r.raw("1")).whereRaw(hn(u,a.foreignKeyColumn,e,"id",f,i,o));break;case"many-to-many":let p=s?await s(a.junctionTableName):null;c=r(a.junctionTableName).select(r.raw("1")).join(u,r.raw(hn(a.junctionTableName,a.junctionTargetColumn,u,"id",p,f,o))).whereRaw(hn(a.junctionTableName,a.junctionSourceColumn,e,"id",p,i,o));break;case"many-to-one":case"one-to-one":c=r(u).select(r.raw("1")).whereRaw(hn(u,"id",e,a.foreignKeyColumn,f,i,o));break;default:throw new Error(`Unsupported relation type: ${a.type}`)}return s?f?await Ue(r,c,n,u,f,o,s):c=le(c,n,u,o,f||void 0):c=le(c,n,u,o),c.toString()}async function Ue(r,e,t,n,i,o,s){if(!t||typeof t!="object")return;if(t._and&&Array.isArray(t._and)){for(let l of t._and)if(l._or&&Array.isArray(l._or)&&l._or.length>0){let f=await Un(l._or,r,n,i,o,s);e.where(function(){Qn(this,f,n,i,o)})}else if(l._and&&Array.isArray(l._and)&&l._and.length>0)for(let f of l._and)await Ue(r,e,f,n,i,o,s);else await Ue(r,e,l,n,i,o,s);return}if(t._or&&Array.isArray(t._or)){let l=await Un(t._or,r,n,i,o,s);e.where(function(){Qn(this,l,n,i,o)});return}if(t._not){let l=t._not;if(l._and&&Array.isArray(l._and)&&l._and.length>0){let p=[];for(let d of l._and)if(Vn(d)){let g=r(n).select(`${n}.id`);await Ue(r,g,d,n,i,o,s),p.push({idSubquery:g})}else{let{fieldFilters:g,relationFilters:y}=G(d,i),h=await zn(r,n,i,o,s,y);p.push({fieldFilters:g,subqueries:h})}e.whereNot(function(){for(let d of p)Ur(this,d,n,i,o)});return}if(l._or&&Array.isArray(l._or)&&l._or.length>0){let p=await Un(l._or,r,n,i,o,s);e.whereNot(function(){Qn(this,p,n,i,o)});return}let{fieldFilters:f,relationFilters:c}=G(l,i);e.whereNot(function(){Object.keys(f).length>0&&le(this,f,n,o,i)});for(let[p,d]of Object.entries(c)){let g=await Et(r,n,p,d,i,o,s);if(g===null){let y=i.relations.find(h=>h.propertyName===p);if(y&&y.foreignKeyColumn){let h=Jn(n,y.foreignKeyColumn,o),b=d.id;if(b&&typeof b=="object"){let $=lt(b._is_null),w=lt(b._is_not_null);if($===!0)e.whereRaw(`${h} IS NOT NULL`);else if($===!1)e.whereRaw(`${h} IS NULL`);else if(w===!0)e.whereRaw(`${h} IS NULL`);else if(w===!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 S=Array.isArray(b._in)?b._in:[b._in];e.whereRaw(`${h} NOT IN (${S.map(()=>"?").join(", ")})`,S)}else if(b._not_in!==void 0||b._nin!==void 0){let S=b._not_in??b._nin,k=Array.isArray(S)?S:[S];e.whereRaw(`${h} IN (${k.map(()=>"?").join(", ")})`,k)}}}}else e.whereRaw(`NOT EXISTS (${g})`)}return}let{fieldFilters:a,relationFilters:u}=G(t,i);Object.keys(a).length>0&&le(e,a,n,o,i);for(let[l,f]of Object.entries(u)){let c=await Et(r,n,l,f,i,o,s);if(c===null){let p=i.relations.find(d=>d.propertyName===l);if(p&&p.foreignKeyColumn){let d=Jn(n,p.foreignKeyColumn,o),y=f.id;if(y&&typeof y=="object"){let h=lt(y._is_null),m=lt(y._is_not_null);if(h===!0)e.whereRaw(`${d} IS NULL`);else if(h===!1)e.whereRaw(`${d} IS NOT NULL`);else if(m===!0)e.whereRaw(`${d} IS NOT NULL`);else if(m===!1)e.whereRaw(`${d} IS NULL`);else if(y._eq!==void 0)e.whereRaw(`${d} = ?`,[y._eq]);else if(y._neq!==void 0)e.whereRaw(`${d} != ?`,[y._neq]);else if(y._in!==void 0){let b=Array.isArray(y._in)?y._in:[y._in];e.whereRaw(`${d} IN (${b.map(()=>"?").join(", ")})`,b)}else if(y._not_in!==void 0||y._nin!==void 0){let b=y._not_in??y._nin,$=Array.isArray(b)?b:[b];e.whereRaw(`${d} NOT IN (${$.map(()=>"?").join(", ")})`,$)}}}}else e.whereRaw(`EXISTS (${c})`)}}async function Qe(r,e,t,n,i,o,s){await Ue(r,e,t,n,i,o,s)}ae();Hn();Xe();ae();function ct(r,e,t,n,i){for(let o of e){let s=o.field.split("."),a=t||s[0],u=s[s.length-1],l=Pt(n,a,u,o.value);switch(o.operator){case"=":r=r.where(o.field,"=",l);break;case"!=":r=r.where(o.field,"!=",l);break;case">":r=r.where(o.field,">",l);break;case"<":r=r.where(o.field,"<",l);break;case">=":r=r.where(o.field,">=",l);break;case"<=":r=r.where(o.field,"<=",l);break;case"like":r=r.where(o.field,"like",l);break;case"in":let f=Array.isArray(o.value)?o.value.map(y=>Pt(n,a,u,y)):[l];r=r.whereIn(o.field,f);break;case"not in":let c=Array.isArray(o.value)?o.value.map(y=>Pt(n,a,u,y)):[l];r=r.whereNotIn(o.field,c);break;case"is null":r=r.whereNull(o.field);break;case"is not null":r=r.whereNotNull(o.field);break;case"_contains":r=r.where(o.field,"like",`%${o.value}%`);break;case"_starts_with":r=r.where(o.field,"like",`${o.value}%`);break;case"_ends_with":r=r.where(o.field,"like",`%${o.value}`);break;case"_between":let p=o.value;if(typeof p=="string"&&(p=p.split(",").map(y=>y.trim())),Array.isArray(p)&&p.length===2){let y=Pt(n,a,u,p[0]),h=Pt(n,a,u,p[1]);r=r.whereBetween(o.field,[y,h])}break;case"_is_null":r=l===!0||l==="true"?r.whereNull(o.field):r.whereNotNull(o.field);break;case"_is_not_null":r=l===!0||l==="true"?r.whereNotNull(o.field):r.whereNull(o.field);break}}return r}function jt(r,e,t,n){let i=[],o=t;if(!r||typeof r!="object")return i;for(let[s,a]of Object.entries(r))if(s==="_and"&&Array.isArray(a)){let u=a.map(l=>{let f=jt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&i.push(`(${u.join(" AND ")})`)}else if(s==="_or"&&Array.isArray(a)){let u=a.map(l=>{let f=jt(l,e,t,n);return f.length>0?`(${f.join(" AND ")})`:null}).filter(l=>l!==null);u.length>0&&i.push(`(${u.join(" OR ")})`)}else if(s==="_not"&&typeof a=="object"&&a!==null){let u=jt(a,e,t,n);u.length>0&&i.push(`NOT (${u.join(" AND ")})`)}else if(typeof a=="object"&&a!==null&&!Array.isArray(a))for(let[u,l]of Object.entries(a)){let f=`${C(e,n)}.${C(s,n)}`,c;if(l===null)c="NULL";else if(typeof l=="string"){let p=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,d=o.columns?.find(y=>y.name===s);d&&(d.type?.toLowerCase()==="uuid"||d.type?.toLowerCase().includes("uuid"))&&p.test(l)&&n==="postgres"?c=`'${l}'::uuid`:c=`'${l.replace(/'/g,"''")}'`}else typeof l=="boolean"?c=l?"true":"false":typeof l=="number"?c=String(l):c=`'${String(l).replace(/'/g,"''")}'`;if(u==="_eq")i.push(`${f} = ${c}`);else if(u==="_neq")i.push(`${f} != ${c}`);else if(u==="_gt")i.push(`${f} > ${c}`);else if(u==="_gte")i.push(`${f} >= ${c}`);else if(u==="_lt")i.push(`${f} < ${c}`);else if(u==="_lte")i.push(`${f} <= ${c}`);else if(u==="_is_null")i.push(`${f} IS NULL`);else if(u==="_is_not_null")i.push(`${f} IS NOT NULL`);else if(u==="_in"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");i.push(`${f} IN (${d})`)}else if(u==="_not_in"||u==="_nin"){let d=(Array.isArray(l)?l:[l]).map(g=>typeof g=="string"?`'${g.replace(/'/g,"''")}'`:String(g)).join(", ");i.push(`${f} NOT IN (${d})`)}else if(u==="_contains"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${f}) LIKE '%${p.toLowerCase()}%'`)}else if(u==="_starts_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${f})) ILIKE lower(unaccent('${p}')) || '%'`):n==="mysql"?i.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT(lower(unaccent('${p}')) COLLATE utf8mb4_general_ci, '%')`):i.push(`lower(${f}) LIKE '${p.toLowerCase()}%'`)}else if(u==="_ends_with"){let p=String(l).replace(/'/g,"''");n==="postgres"?i.push(`lower(unaccent(${f})) ILIKE '%' || lower(unaccent('${p}'))`):n==="mysql"?i.push(`lower(unaccent(${f})) COLLATE utf8mb4_general_ci LIKE CONCAT('%', lower(unaccent('${p}')) COLLATE utf8mb4_general_ci)`):i.push(`lower(${f}) LIKE '%${p.toLowerCase()}'`)}else if(u==="_between"&&Array.isArray(l)&&l.length===2){let p=typeof l[0]=="string"?`'${l[0].replace(/'/g,"''")}'`:String(l[0]),d=typeof l[1]=="string"?`'${l[1].replace(/'/g,"''")}'`:String(l[1]);i.push(`${f} BETWEEN ${p} AND ${d}`)}}else{let u=`${C(e,n)}.${C(s,n)}`,l;a===null?l="NULL":typeof a=="string"?l=`'${a.replace(/'/g,"''")}'`:typeof a=="boolean"?l=a?"true":"false":l=String(a),i.push(`${u} = ${l}`)}return i}function Jr(r){return r==null?"NULL":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:typeof r=="boolean"?r?"true":"false":typeof r=="number"?String(r):`'${String(r).replace(/'/g,"''")}'`}function Pt(r,e,t,n){if(n==null)return n;let i=r?.tables?.get(e);if(!i?.columns)return n;let o=i.columns.find(s=>s.name===t);if(!o)return n;switch(o.type){case"int":case"integer":case"bigint":case"smallint":case"tinyint":return typeof n=="string"?parseInt(n,10):Number(n);case"float":case"double":case"decimal":case"numeric":case"real":return typeof n=="string"?parseFloat(n):Number(n);case"boolean":case"bool":return typeof n=="string"?n==="true"||n==="1":!!n;case"date":case"datetime":case"timestamp":return typeof n=="string"?new Date(n):n;default:return n}}ae();Lt();qe();async function Vr(r,e,t,n,i,o,s){if(!n)return{select:t};try{let{expandFieldsToJoinsAndSelect:a}=await Promise.resolve().then(()=>(Yn(),zr)),u=await a(e,t,n,i,o,s);return{select:u.select,batchFetchDescriptors:u.batchFetchDescriptors}}catch{return{select:t}}}function Xn(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 qr(r,e,t,n,i){let o=r.targetTableName||r.targetTable;if(!o)return null;let s=r.foreignKeyColumn||V(r.propertyName);if(!s)return null;let a=c=>C(c,i),u=n?.tables?.get(o),f=(u?ne(u):null)?.name||"id";return`(SELECT ${a(o)}.${a(e)} FROM ${a(o)} WHERE ${a(o)}.${a(f)} = ${a(t)}.${a(s)})`}Lt();var ft=class r{constructor(e,t,n,i){this.knex=e;this.dbType=t;this.knexService=n;this.maxQueryDepth=i;this.logger=new pn(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&&U(e.filter,e.tableName,e.metadata),!e.plan){let T=new Q;e={...e,plan:T.plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:e.metadata,dbType:this.dbType})}}let o=e.plan,s=e.metadata?.tables?.get(e.tableName),a=s?.relations&&s.relations.length>0,u=e.deep&&typeof e.deep=="object"&&Object.keys(e.deep).length>0,l=o.rawFields&&o.rawFields.length>0&&!o.rawFields.includes("*");if(o.joins.length===0&&!o.hasRelationFilters&&!o.hasRelationSort&&!u&&!a&&l){i&&i.setQueryPath("simple");let T=await this.executeSimple(e,o);return i&&i.dur("sql_executor",t,{table:e.tableName}),T}let c={table:e.tableName,aggregate:e.aggregate,metadata:e.metadata};e.fields&&(Array.isArray(e.fields)?c.fields=e.fields:typeof e.fields=="string"&&(c.fields=e.fields.split(",").map(T=>T.trim())));let p=e.filter;if(e.filter&&!he(e.filter)){c.where=[];for(let[T,F]of Object.entries(e.filter))if(typeof F=="object"&&F!==null)for(let[R,ce]of Object.entries(F)){let A;if(R==="_eq")A="=";else if(R==="_neq")A="!=";else if(R==="_in")A="in";else if(R==="_not_in"||R==="_nin")A="not in";else if(R==="_gt")A=">";else if(R==="_gte")A=">=";else if(R==="_lt")A="<";else if(R==="_lte")A="<=";else if(R==="_contains")A="_contains";else if(R==="_starts_with")A="_starts_with";else if(R==="_ends_with")A="_ends_with";else if(R==="_between")A="_between";else if(R==="_is_null")A="_is_null";else if(R==="_is_not_null")A="_is_not_null";else if(R==="_like")A="like";else if(R==="_ilike")A="ilike";else continue;c.where.push({field:T,operator:A,value:ce})}else c.where.push({field:T,operator:"=",value:F})}if(e.sort){let T=Array.isArray(e.sort)?e.sort:e.sort.split(",").map(F=>F.trim());c.sort=T.map(F=>{let R=F.trim();return R.startsWith("-")?{field:R.substring(1),direction:"desc"}:{field:R,direction:"asc"}})}else c.sort=[{field:"id",direction:"asc"}];let d=e.limit===void 0||e.limit===null?void 0:typeof e.limit=="string"?parseInt(e.limit,10):e.limit,g=d===void 0||Number.isNaN(d)?void 0:d<0?0:d,y=e.page===void 0||e.page===null?void 0:typeof e.page=="string"?parseInt(e.page,10):e.page,h=y===void 0||Number.isNaN(y)?void 0:y;h&&g!==void 0?(c.offset=(h-1)*g,c.limit=g):g!==void 0&&(c.limit=g);let m=e.plan?.sortItems??(c.sort??[]).map(T=>({joinId:null,field:T.field,direction:T.direction,fullPath:T.field})),b=[],$=[];for(let T of m){if(T.function==="count"){let F={sql:this.buildRelationCountSortSubquery(c.table,T),direction:T.direction};$.push(F);continue}if(T.joinId===null){if(T.field.includes(".")&&!e.plan){let R=T.field.split(".")[0];if(this.metadata?.tables?.get(c.table)?.relations?.some(J=>J.propertyName===R))continue}let F={field:T.field.includes(".")?T.field:`${c.table}.${T.field}`,direction:T.direction};b.push(F),$.push(F)}else{let F=e.plan?.joins.find(R=>R.id===T.joinId);if(F&&(F.relationType==="many-to-one"||F.relationType==="one-to-one")){let R=qr(F.relationMeta,T.field,c.table,this.metadata,this.dbType);if(R){let ce={sql:R,direction:T.direction};$.push(ce)}}}}let w=[];if(c.fields&&c.fields.length>0){let T=Xn(this.metadata),F=await Vr(this.knex,c.table,c.fields,T,this.dbType,this.maxQueryDepth,e.deep);c.select=[...c.select||[],...F.select],w=F.batchFetchDescriptors||[]}c.where&&(c.where=c.where.map(T=>T.field.includes(".")?T:{...T,field:`${c.table}.${T.field}`})),c.sort=b;let S=this.knex(c.table),k=Array.isArray(e.meta)?e.meta:(e.meta||"").split(",").map(T=>T.trim()).filter(Boolean),v=k.includes("filterCount")||k.includes("*"),_=k.includes("totalCount")||k.includes("*");if(c.select){let T=c.select.map(F=>typeof F=="string"&&F.trim().startsWith("(")?this.knex.raw(F):typeof F=="string"&&/ as /i.test(F)?this.knex.raw(F):F);S=S.select(T)}if(v&&S.select(this.knex.raw("COUNT(*) OVER() as __filter_count__")),_){let T=C(c.table,this.dbType);S.select(this.knex.raw(`(SELECT COUNT(*) FROM ${T}) as __total_count__`))}let N=["table_definition","column_definition","relation_definition","method_definition"].includes(c.table);if(p&&(he(p)||Object.keys(p).length>0)){let T=this.metadata?.tables?.get(c.table);(!N&&T&&T.relations&&T.relations.length>0?G(p,T).hasRelations:!1)?await Qe(this.knex,S,p,c.table,T,this.dbType,R=>this.metadata?.tables?.get(R)):e.plan?.filterTree?X(S,e.plan.filterTree,{dbType:this.dbType,rootTable:c.table}):(this.logger.debug(`buildWhereClause fallback for table=${c.table}`),S=le(S,p,c.table,this.dbType,T))}else c.where&&c.where.length>0&&(S=ct(S,c.where,c.table,this.metadata,this.dbType));for(let T of $)if(T.field){let F=T.field.includes(".")?T.field:`${c.table}.${T.field}`;S=S.orderBy(F,T.direction)}else T.sql&&(S=S.orderByRaw(`${T.sql} ${T.direction.toUpperCase()}`));c.groupBy&&(S=S.groupBy(c.groupBy)),c.offset&&(S=S.offset(c.offset)),c.limit!==void 0&&c.limit!==null&&c.limit>0&&(S=S.limit(c.limit));let I=0;this.debugLog&&this.debugLog.push({type:"SQL Query",table:c.table,sql:S.toSQL().toNative()});let O;if(e.debugMode&&(O=S.toSQL().toNative().sql),e.debugMode&&i){let T=S.toSQL().toNative();i.setSql(T.sql);try{let F=T.sql.replace(/\$\d+/g,"?"),R=await this.knex.raw(`EXPLAIN ${F}`,T.bindings);i.setExplain(this.dbType==="postgres"?R.rows:R[0])}catch(F){i.setExplain({error:String(F)})}}let M,D=performance.now();M=await S,i&&i.dur("db_execute",D,{table:e.tableName});let P=0;if(v&&M.length>0&&(P=Number(M[0].__filter_count__||0),M.forEach(T=>{delete T.__filter_count__})),_&&M.length>0&&M[0].__total_count__!==void 0&&(I=Number(M[0].__total_count__||0),M.forEach(T=>{delete T.__total_count__})),w&&w.length>0&&M.length>0){let T=Xn(this.metadata);if(T){let{executeBatchFetches:F}=await Promise.resolve().then(()=>(tr(),Hr));await F(this.knex,M,w,T,this.maxQueryDepth??3,0,c.table,this.dbType,this.metadata,i)}}if(this.knexService){let T=performance.now();M=await this.knexService.parseResult(M,c.table),i&&i.dur("db_parseResult",T,{table:e.tableName})}else{let T=(F,R)=>{if(!F||!this.metadata)return F;let ce=this.metadata.tables?.get(R);if(!ce)return F;if(Array.isArray(F))return F.map(J=>T(J,R));if(typeof F!="object"||Buffer.isBuffer(F))return F;let A={...F};for(let J of ce.columns)if(J.type==="simple-json"&&A[J.name]&&typeof A[J.name]=="string")try{A[J.name]=JSON.parse(A[J.name])}catch{}for(let[J,q]of Object.entries(A))if(q&&typeof q=="object"&&!Array.isArray(q)&&!Buffer.isBuffer(q)){let Sn=q;if(Sn.id!==void 0||Sn.createdAt!==void 0){let pt=ce.relations?.find(gt=>gt.propertyName===J);pt&&(A[J]=T(q,pt.targetTableName))}}else if(Array.isArray(q)&&q.length>0&&typeof q[0]=="object"&&q[0].id!==void 0){let pt=ce.relations?.find(gt=>gt.propertyName===J);pt&&(A[J]=q.map(gt=>T(gt,pt.targetTableName)))}return A};M=T(M,c.table)}i&&(i.setQueryPath("full"),i.dur("sql_executor",t,{table:e.tableName}));let L=await this.executeAggregate(c,p);return{data:M,...(k.length>0||L)&&{meta:{...k.includes("totalCount")||k.includes("*")?{totalCount:I}:{},...k.includes("filterCount")||k.includes("*")?{filterCount:P}:{},...L?{aggregate:L}:{}}},...O!==void 0&&{sql:O}}}buildRelationCountSortSubquery(e,t){let n=t.relationMeta,i=t.relationName||t.field,o=n?.targetTableName||n?.targetTable,s=this.metadata?.tables?.get(e),a=ne(s)?.name||"id",u=C(e,this.dbType),l=C(a,this.dbType);if(!n||!o)throw new x(`Sort relation '${i}' does not exist on '${e}'.`);if(n.type==="one-to-many"){let f=n.foreignKeyColumn||n.mappedBy;if(!f)throw new x(`Sort function '_count(${i})' cannot resolve relation key on '${e}'.`);let c=C(o,this.dbType),p=C(f,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}if(n.type==="many-to-many"){let f=this.resolveManyToManyContract(n,i,e),c=C(f.tableName,this.dbType),p=C(f.sourceColumn,this.dbType);return`(SELECT COUNT(*) FROM ${c} WHERE ${c}.${p} = ${u}.${l})`}throw new x(`Sort function '_count(${i})' is only supported for list relations on '${e}'.`)}resolveManyToManyContract(e,t,n){if(e?.junctionTableName&&e?.junctionSourceColumn&&e?.junctionTargetColumn)return{tableName:e.junctionTableName,sourceColumn:e.junctionSourceColumn,targetColumn:e.junctionTargetColumn};throw new x(`Relation '${t}' on '${n}' is missing physical many-to-many metadata.`)}async executeSimple(e,t){let n=e.tableName,i=t.rawFields&&t.rawFields.length>0?t.rawFields:["*"],o=this.knex(n).select(i);t.filterTree&&X(o,t.filterTree,{dbType:this.dbType,rootTable:n});for(let 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=C(n,this.dbType);o.select(this.knex.raw(`(SELECT COUNT(*) FROM ${h}) as __total_count__`))}let l=e.debugTrace,f;if(e.debugMode){let h=o.toSQL().toNative();if(f=h.sql,l){l.setSql(h.sql);try{let m=h.sql.replace(/\$\d+/g,"?"),b=await this.knex.raw(`EXPLAIN ${m}`,h.bindings);l.setExplain(this.dbType==="postgres"?b.rows:b[0])}catch(m){l.setExplain({error:String(m)})}}}let c=performance.now(),p;p=await o,l&&l.dur("db_execute",c,{table:n}),this.knexService&&(p=await this.knexService.parseResult(p,n));let d=0,g=0;a&&p.length>0&&(d=Number(p[0].__filter_count__||0),p.forEach(h=>delete h.__filter_count__)),u&&p.length>0&&(g=Number(p[0].__total_count__||0),p.forEach(h=>delete h.__total_count__));let y=await this.executeAggregate({table:n,aggregate:e.aggregate,metadata:e.metadata},e.filter);return{data:p,...(s.length>0||y)&&{meta:{...u?{totalCount:g}:{},...a?{filterCount:d}:{},...y?{aggregate:y}:{}}},...f!==void 0&&{sql:f}}}async executeAggregate(e,t){let n=it(e.aggregate,e.table,e.metadata);if(n.length===0)return;let i={};for(let o of n){let s=ot(t,o);U(s,e.table,e.metadata);let u=new Q().plan({tableName:e.table,filter:s,metadata:e.metadata,dbType:this.dbType});if(o.op==="countRecords"){let d=await this.executeRelationCountRecords(e,t,o);Ce(i,o,d);continue}let l=this.knex(e.table);if(u.hasRelationFilters){let d=e.metadata?.tables?.get(e.table);await Qe(this.knex,l,s,e.table,d,this.dbType,g=>e.metadata?.tables?.get(g))}else u.filterTree&&X(l,u.filterTree,{dbType:this.dbType,rootTable:e.table});let f=`${C(e.table,this.dbType)}.${C(o.field,this.dbType)}`,c=o.op==="count"?this.knex.raw("COUNT(*) as value"):this.knex.raw(`${o.op.toUpperCase()}(${f}) as value`),p=await l.clearSelect().select(c).first();Ce(i,o,p?.value??0)}return i}async executeRelationCountRecords(e,t,n){let i=e.metadata?.tables?.get(e.table),o=i?.relations?.find(c=>c.propertyName===n.field),s=o?.targetTableName||o?.targetTable,a=s?e.metadata?.tables?.get(s):null;if(!o||!s||!a)return 0;let u=this.knex(e.table).select(`${e.table}.id`);if(t&&Object.keys(t).length>0){let p=new Q().plan({tableName:e.table,filter:t,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Qe(this.knex,u,t,e.table,i,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&X(u,p.filterTree,{dbType:this.dbType,rootTable:e.table})}let l=this.knex(s).count("* as value");if(n.condition&&Object.keys(n.condition).length>0){U(n.condition,s,e.metadata);let p=new Q().plan({tableName:s,filter:n.condition,metadata:e.metadata,dbType:this.dbType});p.hasRelationFilters?await Qe(this.knex,l,n.condition,s,a,this.dbType,d=>e.metadata?.tables?.get(d)):p.filterTree&&X(l,p.filterTree,{dbType:this.dbType,rootTable:s})}if(o.type==="one-to-many")l.whereIn(`${s}.${o.foreignKeyColumn}`,u);else if(o.type==="many-to-many"){let c=this.resolveManyToManyContract(o,n.field,e.table);l.whereIn(`${s}.id`,this.knex(c.tableName).select(`${c.tableName}.${c.targetColumn}`).whereIn(`${c.tableName}.${c.sourceColumn}`,u))}else(o.type==="many-to-one"||o.type==="one-to-one")&&l.whereIn(`${s}.id`,function(){this.select(`${e.table}.${o.foreignKeyColumn}`).from(e.table),t&&Object.keys(t).length>0&&this.whereIn(`${e.table}.id`,u),this.whereNotNull(`${e.table}.${o.foreignKeyColumn}`)});let f=await l.first();return Number(f?.value??0)}};var mn=require("mongodb"),dt=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,bn.mkdirSync)((0,Gr.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(!mn.ObjectId)return e;if(typeof e=="string")try{return new mn.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=Ye(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:ct(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(re(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 Q().plan({tableName:e.tableName,fields:e.fields,filter:e.filter,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,metadata:n,dbType:this.dbType}),a=e.debugTrace;if(a&&(a.dur("qb_planner",i,{table:e.tableName}),a.setPlan(this.sanitizePlan(s))),this.dbType==="mongodb")return new st(this.mongoService,this.lazyRef.mongoPhysicalMigrationService).execute({...e,metadata:n,dbType:this.dbType,plan:s,aggregate:e.aggregate});let l=await new ft(this.knexService.getKnex(),this.dbType,this.knexService,e.maxQueryDepth).execute({...e,metadata:n,plan:s});return a&&a.dur("qb_total_select",t,{table:e.tableName}),l}sanitizePlan(e){return{rawFields:e.rawFields,hasRelationFilters:e.hasRelationFilters,hasRelationSort:e.hasRelationSort,joins:e.joins?.length??0,sortItems:e.sortItems,limit:e.limit,offset:e.offset,page:e.page,isSimpleQuery:e.joins?.length===0&&!e.hasRelationFilters&&!e.hasRelationSort}}async updateWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let o=await this.buildMongoFilter(e.where,e.table),a=await this.mongoService.collection(e.table).find(o).toArray(),u=[];for(let l of a){let f=await this.mongoService.updateOne(e.table,l._id,e.data);u.push(f)}return u});let t=this.knexService.getKnex(),n=t(e.table);e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n;for(let o of i)await this.knexService.updateWithCascade(e.table,o.id,e.data);if(e.returning){let o=t(e.table);return e.where.length>0&&await this.applyWhereToKnex(o,e.where,e.table),await o.select(e.returning)}return{affected:i.length}}async deleteWithOptions(e){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(async()=>{let i=await this.buildMongoFilter(e.where,e.table),s=await this.mongoService.collection(e.table).find(i).toArray(),a=0;for(let u of s)await this.mongoService.deleteOne(e.table,u._id)&&a++;return a});let n=this.knexService.getKnex()(e.table);return e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table)),await n.delete()}async count(e){if(this.dbType==="mongodb"){let o=e.where?await this.buildMongoFilter(e.where,e.table):{};return this.mongoService.count(e.table,o)}let n=this.knexService.getKnex()(e.table);e.where&&e.where.length>0&&({query:n}=await this.applyWhereToKnex(n,e.where,e.table));let i=await n.count("* as count").first();return Number(i?.count||0)}whereToFilter(e){let t={},n=this.databaseConfigService.isMongoDb();for(let[i,o]of Object.entries(e))i==="id"||i==="_id"?n?t._id=this.normalizeWhereFilterValue("_id",o):t.id=this.normalizeWhereFilterValue("id",o):t[i]=this.normalizeWhereFilterValue(i,o);return t}normalizeWhereFilterValue(e,t){return this.isFilterOperatorObject(t)?this.databaseConfigService.isMongoDb()&&e==="_id"?this.normalizeMongoIdOperatorValue(t):t:{_eq:this.databaseConfigService.isMongoDb()&&e==="_id"?this.safeObjectId(t):t}}isFilterOperatorObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof mn.ObjectId)&&Object.keys(e).length>0&&Object.keys(e).every(t=>t.startsWith("_"))}normalizeMongoIdOperatorValue(e){let t={};for(let[n,i]of Object.entries(e))t[n]=Array.isArray(i)?i.map(o=>this.safeObjectId(o)):this.safeObjectId(i);return t}filterToWhere(e){let t=[];for(let[n,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let o=Object.entries(i)[0];if(o){let[s,a]=o,u=this.mapFilterOperatorToSql(s);t.push({field:n,operator:u,value:a})}}return t}mapFilterOperatorToSql(e){return{_eq:"=",_neq:"!=",_gt:">",_gte:">=",_lt:"<",_lte:"<=",_in:"in",_not_in:"not in",_contains:"like",_starts_with:"like",_ends_with:"like",_is_null:"is null",_is_not_null:"is not null"}[e]||"="}async find(e){return this.trackQueryMetric("find",e.table,async()=>{let t=e.filter||(e.where?this.whereToFilter(e.where):void 0);return await this.select({tableName:e.table,filter:t,fields:e.fields,sort:e.sort,page:e.page,limit:e.limit,meta:e.meta,deep:e.deep,debugMode:e.debugMode,debugLog:e.debugLog,debugTrace:e.debugTrace,pipeline:e.pipeline,aggregate:e.aggregate,maxQueryDepth:e.maxQueryDepth})})}async findOne(e){return(await this.find({...e,limit:1}))?.data?.[0]??null}async insert(e,t,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 re(a)}let i=await this.knexService.insertWithCascade(e,t),o=this.knexService.getKnex(),s=i||t.id;return await o(e).where("id",s).first()})}async flushBatchInserts(){for(;this.batchInserts.items.length>0||this.batchInserts.flushing;)await this.flushBatchInsertBuffer()}async insertManyBatch(e,t){let n=Array.isArray(t)?t:[t];for(let i of n)this.batchInserts.items.push({table:e,data:i});return this.traceBatchInsert("enqueue",{tableName:e,count:n.length,pending:this.batchInserts.items.length,flushing:this.batchInserts.flushing}),this.batchInserts.timer||(this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i))},this.batchInsertMaxWaitMs)),this.batchInserts.items.length>=this.batchInsertMaxSize&&this.flushBatchInsertBuffer().catch(i=>this.logBatchInsertError("QueryBuilder batch insert flush failed",i)),{accepted:!0,batch:!0,count:n.length}}async flushBatchInsertBuffer(){if(this.batchInserts.flushing){await this.batchInserts.flushPromise;return}let e=this.batchInserts.items.splice(0,this.batchInserts.items.length);if(this.batchInserts.timer&&(clearTimeout(this.batchInserts.timer),this.batchInserts.timer=void 0),e.length===0)return;this.batchInserts.flushing=!0;let t=this.executeBatchInsertFlush(e);this.batchInserts.flushPromise=t,await t}async executeBatchInsertFlush(e){let t=Date.now();try{let n=this.groupBatchInsertsByTable(e);this.traceBatchInsert("flush_start",{count:e.length,tables:[...n.entries()].map(([i,o])=>({tableName:i,count:o.length}))}),await this.runLimited([...n.entries()],([i,o])=>this.flushBatchInsertTable(i,o)),this.traceBatchInsert("flush_done",{count:e.length,durationMs:Date.now()-t})}finally{this.batchInserts.flushing=!1,this.batchInserts.flushPromise=void 0,this.batchInserts.items.length>0&&(this.batchInserts.timer&&clearTimeout(this.batchInserts.timer),this.batchInserts.timer=setTimeout(()=>{this.flushBatchInsertBuffer().catch(n=>this.logBatchInsertError("QueryBuilder batch insert flush failed",n))},this.batchInsertMaxWaitMs))}}async flushBatchInsertTable(e,t){let n=Date.now();await this.runBatchInsertWithIsolation(e,t),this.traceBatchInsert("flush_table",{tableName:e,count:t.length,durationMs:Date.now()-n})}async runBatchInsertWithIsolation(e,t){if(t.length!==0)try{await(async()=>{if(this.dbType==="mongodb"){await this.runMongoMutationInSaga(async()=>{if(typeof this.mongoService?.insertManyWithCascade=="function"){await this.mongoService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.mongoService.insertOne(e,i.data)))});return}if(typeof this.knexService?.insertManyWithCascade=="function"){await this.knexService.insertManyWithCascade(e,t.map(i=>i.data));return}await Promise.all(t.map(i=>this.knexService.insertWithCascade(e,i.data)))})()}catch(n){if(t.length===1){this.logBatchInsertError(`QueryBuilder batch insert item failed for ${e}`,n);return}let i=Math.ceil(t.length/2);await Promise.all([this.runBatchInsertWithIsolation(e,t.slice(0,i)),this.runBatchInsertWithIsolation(e,t.slice(i))])}}groupBatchInsertsByTable(e){let t=new Map;for(let n of e){let i=t.get(n.table);i?i.push(n):t.set(n.table,[n])}return t}async runLimited(e,t){let n=0,i=Array.from({length:Math.min(this.batchInsertConcurrency,e.length)},async()=>{for(;n<e.length;){let o=e[n++];await t(o)}});await Promise.all(i)}readPositiveEnv(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?Math.trunc(n):t}traceBatchInsert(e,t){this.batchInsertTraceFile&&(0,bn.appendFileSync)(this.batchInsertTraceFile,JSON.stringify({event:e,ts:Date.now(),...t})+`
|
|
53
|
+
`)}logBatchInsertError(e,t){let n=t?.message||String(t);this.traceBatchInsert("error",{message:e,error:n,code:t?.code,detail:t?.detail}),console.error(`${e}: ${n}`)}async update(e,t,n){return this.trackQueryMetric("update",e,async()=>{if(t&&typeof t=="object"&&"where"in t)return await this.updateWithOptions({table:e,where:t.where,data:n});if(this.dbType==="mongodb"){let o=await this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n));return re(o)}return await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first()})}async delete(e,t){return this.trackQueryMetric("delete",e,async()=>t&&typeof t=="object"&&"where"in t?await this.deleteWithOptions({table:e,where:t.where})>0:this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t)):await this.knexService.getKnex()(e).where("id",t).delete()>0)}async countRecords(e,t){if(this.dbType==="mongodb")return this.mongoService.count(e,t||{});let i=this.knexService.getKnex()(e);if(t&&Object.keys(t).length>0){let s=this.filterToWhere(t);({query:i}=await this.applyWhereToKnex(i,s,e))}let o=await i.count("* as count").first();return Number(o?.count||0)}async transaction(e){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>e(this.mongoService)):this.knexService.transaction(e)}async findById(e,t){if(this.dbType==="mongodb"){let i=this.safeObjectId(t);return this.mongoService.findOne(e,{_id:i})}return await this.knexService.getKnex()(e).where("id",t).first()}async findOneWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[o,s]of Object.entries(t))o==="id"||o==="_id"?i._id=this.safeObjectId(s):i[o]=s;return this.mongoService.findOne(e,i)}return await this.knexService.getKnex()(e).where(t).first()}async findWhere(e,t){if(this.dbType==="mongodb"){let i={};for(let[a,u]of Object.entries(t))a==="id"||a==="_id"?i._id=this.safeObjectId(u):i[a]=u;return await this.mongoService.collection(e).find(i).toArray()}return await this.knexService.getKnex()(e).where(t)}async insertAndGet(e,t){if(this.dbType==="mongodb")return this.runMongoMutationInSaga(()=>this.mongoService.insertOne(e,t));let n=await this.knexService.insertWithCascade(e,t),i=this.knexService.getKnex(),o=n||t.id;return await i(e).where("id",o).first()}async updateById(e,t,n){return this.dbType==="mongodb"?this.runMongoMutationInSaga(()=>this.mongoService.updateOne(e,t,n)):(await this.knexService.updateWithCascade(e,t,n),await this.knexService.getKnex()(e).where("id",t).first())}async deleteById(e,t){return this.dbType==="mongodb"?await this.runMongoMutationInSaga(()=>this.mongoService.deleteOne(e,t))?1:0:this.knexService.getKnex()(e).where("id",t).delete()}async raw(e,t){let n=this.dbType==="mongodb"?"mongodb":"sql";return this.trackQueryMetric("raw",n,async()=>{if(this.dbType==="mongodb"){let o=this.mongoService.getDb();if(typeof e=="string"){if(e.toLowerCase().includes("select 1"))return await o.command({ping:1});throw new Error("String queries not supported for MongoDB. Use db.command() object instead.")}return await o.command(e)}return await this.knexService.getKnex().raw(e,t)})}async trackQueryMetric(e,t,n){return this.runtimeMetricsCollectorService?await this.runtimeMetricsCollectorService.trackQuery({op:e,table:t},n):await n()}getConnection(){return this.dbType==="mongodb"?this.mongoService.getDb():this.knexService.getKnex()}getKnex(){if(this.dbType==="mongodb")throw new Error("getKnex() is not available for MongoDB. Use getConnection() or unified methods.");return this.knexService.getKnex()}getMongoDb(){if(this.dbType!=="mongodb")throw new Error("getMongoDb() is not available for SQL. Use getConnection() or unified methods.");return this.mongoService.getDb()}getDatabaseType(){return this.dbType}isMongoDb(){return this.dbType==="mongodb"}isSql(){return["mysql","postgres","mariadb","sqlite"].includes(this.dbType)}getPkField(){return this.isMongoDb()?"_id":"id"}getRecordId(e){return this.isMongoDb()?e._id:e.id}};tr();Zn();Yn();ae();Lt();tt();fe();Xe();var Yr=new Set(["fields","filter","sort","limit","page","deep"]),wn=3;function nr(r,e,t,n=0,i=3){if(!e||typeof e!="object")return;if(n>=i)throw new x(`deep option exceeds maximum query depth of ${i}`);let o=t?.tables?.get(r),s=new Map((o?.relations??[]).map(a=>[a.propertyName,a]));for(let[a,u]of Object.entries(e)){let l=s.get(a);if(!l)throw new x(`Unknown relation '${a}' on '${r}'`);if(!u||typeof u!="object")continue;for(let p of Object.keys(u))if(!Yr.has(p))throw new x(`Unknown deep option key '${p}' for relation '${a}'. Allowed: ${[...Yr].join(", ")}`);let f=l.type;if(u.limit!==void 0&&(f==="many-to-one"||f==="one-to-one"))throw new x(`'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 x(`'page' requires 'limit' to be present (relation '${a}' on '${r}')`);let c=l.targetTableName||l.targetTable;if(c){if(u.filter&&(U(u.filter,c,t),We(u.filter,c,t),_n(u.filter,0,a,r)),u.sort){fn(u.sort,c,t);let p=Array.isArray(u.sort)?u.sort:String(u.sort).split(",").map(d=>d.trim()).filter(Boolean);for(let d of p){let g=d.startsWith("-")?d.slice(1):d;bo(g,c,t,a,r)}}u.deep&&nr(c,u.deep,t,n+1,i)}}}function bo(r,e,t,n,i){if(r.includes("."))throw new x(`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 x(`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 x(`Sort field '${r}' does not exist on '${e}' (relation '${n}' on '${i}')`)}var _o=new Set(["_and","_or","_not"]);function _n(r,e,t,n){if(!(!r||typeof r!="object"))for(let[i,o]of Object.entries(r)){if(_o.has(i)){if(Array.isArray(o))for(let l of o)_n(l,e,t,n);else o&&typeof o=="object"&&_n(o,e,t,n);continue}if(i.startsWith("_")||!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).some(l=>!l.startsWith("_")))continue;let a=e+1;if(a>wn)throw new x(`Filter path exceeds max dotted hops of ${wn} at '${i}' (relation '${t}' on '${n}')`);let u={};for(let l of Object.keys(o))l.startsWith("_")||(u[l]=o[l]);_n(u,a,t,n)}}function Xr(r,e,t,n){return!r||typeof r!="object"?r:Bt(r,e,t,n)}function Bt(r,e,t,n){if(!r||typeof r!="object")return r;if(Array.isArray(r)){let o=r.map(s=>Bt(s,e,t,n)).filter(s=>s!=null);return o.length>0?o:null}let i={};for(let[o,s]of Object.entries(r)){if(o==="_and"||o==="_or"){let c=(Array.isArray(s)?s:[s]).map(p=>Bt(p,e,t,n)).filter(p=>p!=null&&Object.keys(p).length>0);c.length>0&&(i[o]=c);continue}if(o==="_not"){let f=Bt(s,e,t,n);f!=null&&Object.keys(f).length>0&&(i[o]=f);continue}let a=t?.tables?.get(e),u=a?.relations?.find(f=>f.propertyName===o);if(u){if(!n(e,o,"relation"))continue;let f=u.targetTableName||u.targetTable;if(!f)continue;let c=Bt(s,f,t,n);c!=null&&Object.keys(c).length>0&&(i[o]=c);continue}if(a?.columns?.find(f=>f.name===o)){if(!n(e,o,"column"))continue;i[o]=s;continue}i[o]=s}return i}function Zr(r,e,t,n){if(!r)return r;let i=Array.isArray(r)?r:r.split(",").map(s=>s.trim()).filter(Boolean),o=[];for(let s of i){let l=(s.startsWith("-")?s.slice(1):s).split("."),f=!0,c=e;for(let p=0;p<l.length;p++){let d=l[p],g=p===l.length-1,y=t?.tables?.get(c);if(!y){f=!1;break}if(g)y.columns?.find(m=>m.name===d)?n(c,d,"column")||(f=!1):y.relations?.find(b=>b.propertyName===d)&&(n(c,d,"relation")||(f=!1));else{let h=y.relations?.find(m=>m.propertyName===d);if(!h){f=!1;break}if(!n(c,d,"relation")){f=!1;break}c=h.targetTableName||h.targetTable||c}}f&&o.push(s)}if(o.length!==0)return Array.isArray(r)?o:o.join(",")}It();Xe();Nt();ln();vt();qe();fe();function wo(r){let e=new dt({knexService:r.knexService,mongoService:r.mongoService,databaseConfigService:r.databaseConfigService,runtimeMetricsCollectorService:r.runtimeMetricsCollectorService,lazyRef:r.lazyRef}),t,n,i=()=>(t||(t=new Ve({packageCacheService:r.getPackageCacheService?.()??r.packageCacheService,packageCdnLoaderService:r.getPackageCdnLoaderService?.()??r.packageCdnLoaderService})),t),o=()=>(n||(n=new Je({isolatedExecutorService:i()})),n);return{queryBuilderService:e,get isolatedExecutorService(){return i()},get executorEngineService(){return o()},async onDestroy(){await t?.onDestroy?.()}}}0&&(module.exports={ALL_SUPPORTED_OPERATORS,AuthenticationException,AuthorizationException,BadRequestException,BatchFetchEngine,BusinessLogicException,CHUNKED_FETCH_CONCURRENCY,ConfigurationException,DEEP_TO_MANY_DEFAULT_LIMIT,DEFAULT_TIMEOUT_MS,DOTTED_PATH_MAX_HOPS,DatabaseException,DuplicateResourceException,ErrorHandler,ExecutorEngineService,ExternalServiceException,FIELD_OPERATORS,FileNotFoundException,FileSizeExceededException,FileUploadException,HttpException,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH,InvalidTokenException,IsolatedExecutorService,JoinRegistry,LOGICAL_OPERATORS,MongoBatchAdapter,MongoQueryExecutor,PER_PARENT_CONCURRENCY,QueryBuilderService,QueryPlanner,ResourceNotFoundException,SchemaException,ScriptContractService,ScriptExecutionException,ScriptTimeoutException,ServiceUnavailableException,SqlBatchAdapter,SqlQueryExecutor,TokenExpiredException,ValidationException,WHERE_IN_CHUNK_SIZE,WorkerPool,appendIsolatedExecutorRuntimeLog,applyOperatorToMatch,applyRelationFilters,applyWhereToKnex,assertFieldOperatorValueIsClean,buildAggregateFilter,buildMongoCharFoldMapJson,buildMongoFoldTextSearchJs,buildRelationSubquery,buildSqlWherePartsFromFieldAst,buildWhereClause,camelToSnake,chunkedFetch,compileScriptSource,computeEngineTuning,createEnfyraKernel,dslOpToCompareOp,encodeMainThreadToIsolate,escapeSqlValue,executeBatchFetches,executeMongoBatchFetches,expandFieldsToJoinsAndSelect,getEffectiveCpuCount,getEffectiveMemoryBytes,getEngineTuning,getExecutableScript,getForeignKeyColumnName,getIoAbortSignal,getJunctionColumnNames,getJunctionTableName,getPrimaryKeyColumn,getScriptLegacyField,getShortFkConstraintName,getShortFkName,getShortIndexName,getShortPkName,hasAggregateQuery,hasLogicalOperators,isExecutableJavaScript,isScriptTable,mergeAggregateValue,normalizeAggregateQuery,normalizeFlowStepScriptConfig,normalizeScriptLanguage,normalizeScriptPatch,normalizeScriptRecord,parseBatchFields,parseFields,parseFilter,perParentRun,quoteIdentifier,quoteQualifiedIdentifier,resolveExecutableScript,rewriteFilterDenyingFields,rewriteSortDroppingDenied,scriptContractService,separateFilters,snakeToCamel,throwUnsupportedFieldOperator,validateDeepOptions,validateFilterShape,whereToMongoFilter});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@enfyra/kernel",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.13",
|
|
4
4
|
"description": "Closed-distribution Enfyra kernel runtime",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"private": false,
|
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
},
|
|
29
29
|
"scripts": {
|
|
30
30
|
"build": "node scripts/build.mjs",
|
|
31
|
+
"test:sql-identifiers": "yarn build && node scripts/test-sql-identifier-quoting.mjs",
|
|
31
32
|
"verify": "node scripts/verify-no-source-leak.mjs && node -e \"const k=require('./dist'); if (typeof k.createEnfyraKernel !== 'function') process.exit(1)\"",
|
|
32
33
|
"pack:local": "yarn build && yarn verify && yarn pack --filename enfyra-kernel.tgz"
|
|
33
34
|
},
|