@enfyra/kernel 1.1.15 → 1.1.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/package-metadata.json +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
`));return t.outputText.trimEnd()}assertExecutableJavaScript(e){e&&new Function(`return (async () => {
|
|
4
4
|
"use strict";
|
|
5
5
|
${e}
|
|
6
|
-
});`)}},ee=new zt;function Vt(r,e){return ee.compileSource(r,e)}function bi(r){return ee.isExecutableJavaScript(r)}function _i(r,e){return ee.normalizeRecord(r,e)}function wi(r,e,t){return ee.normalizePatch(r,e,t)}function $i(r){return ee.getExecutableScript(r)}function Si(r){return ee.resolveExecutableScript(r)}function Ti(r){return ee.normalizeFlowStepScriptConfig(r)}var Ai=ur.join(__dirname,"execution/worker.js"),Oi=["Invalid or unexpected token","Unexpected identifier","Unexpected token","Missing initializer in const declaration","await is only valid"],pr=new cr.AsyncLocalStorage;function gr(){return pr.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 dr.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}},lr=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 ze=class r{constructor(e){this.logger=new Wt(r.name);this.effectiveMemory=Tt();this.isolationTuning=qt();this.pool=new Ft(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Ai,()=>{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,$req:this.cloneSnapshotValue(e.$req)};for(let i of Object.keys(e)){if(!i.startsWith("$")||i in t||lr.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"||lr.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++,q({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++,q({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++,q({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?pr.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 fr.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 Oi.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);q({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;q({event:"isolated_run_ts_retry",message:c.message}),u=await this.spawnAndExecute("execute",{...l,code:p},t,i)}}catch(l){let f=l;if(q({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||{}),q({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);q({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,m)=>g.code!==e[m]?.code);if(!this.isScriptParseFailure(c)||!d)throw f;q({event:"isolated_batch_ts_retry",message:c.message}),u=await this.spawnAndExecute("executeBatch",{...l,codeBlocks:p},t,i)}}catch(l){let f=l;if(q({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||{}),q({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"),Yr=require("node:path");var Rn=require("mongodb");Ve();function Be(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function G(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!Be(r)&&(r.foreignKeyColumn||r.propertyName)||null}function K(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 fe(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(m=>m.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=K(f)||f.propertyName,d=!0):(c=G(f)||f.propertyName,p="_id",d=!1):f.type==="one-to-many"?(c="_id",p=K(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 Ei=new RegExp("\\p{Mark}","gu");function Tr(r){return r==null?"":String(r).normalize("NFKD").replace(Ei,"").toLowerCase()}function xn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=Tr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function Gt(){return`function() {
|
|
6
|
+
});`)}},ee=new zt;function Vt(r,e){return ee.compileSource(r,e)}function bi(r){return ee.isExecutableJavaScript(r)}function _i(r,e){return ee.normalizeRecord(r,e)}function wi(r,e,t){return ee.normalizePatch(r,e,t)}function $i(r){return ee.getExecutableScript(r)}function Si(r){return ee.resolveExecutableScript(r)}function Ti(r){return ee.normalizeFlowStepScriptConfig(r)}var Ai=ur.join(__dirname,"execution/worker.js"),Oi=["Invalid or unexpected token","Unexpected identifier","Unexpected token","Missing initializer in const declaration","await is only valid"],pr=new cr.AsyncLocalStorage;function gr(){return pr.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 dr.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}},lr=new Set(["$helpers","$cache","$repos","$req","$res","$socket","$logs","$throw","$trigger","$pkgs","$debug"]);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 ze=class r{constructor(e){this.logger=new Wt(r.name);this.effectiveMemory=Tt();this.isolationTuning=qt();this.pool=new Ft(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,Ai,()=>{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,$req:this.cloneSnapshotValue(e.$req)};for(let i of Object.keys(e)){if(!i.startsWith("$")||i in t||lr.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"||lr.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++,q({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++,q({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++,q({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?pr.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 fr.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 Oi.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);q({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;q({event:"isolated_run_ts_retry",message:c.message}),u=await this.spawnAndExecute("execute",{...l,code:p},t,i)}}catch(l){let f=l;if(q({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||{}),q({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);q({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,m)=>g.code!==e[m]?.code);if(!this.isScriptParseFailure(c)||!d)throw f;q({event:"isolated_batch_ts_retry",message:c.message}),u=await this.spawnAndExecute("executeBatch",{...l,codeBlocks:p},t,i)}}catch(l){let f=l;if(q({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||{}),q({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"),Yr=require("node:path");var Rn=require("mongodb");Ve();function Be(r){return r.type==="one-to-many"||r.isInverse===!0||r.type==="one-to-one"&&!!r.mappedBy}function G(r){return(r.type==="many-to-one"||r.type==="one-to-one")&&!Be(r)&&(r.foreignKeyColumn||r.propertyName)||null}function K(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 fe(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(m=>m.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=K(f)||f.propertyName,d=!0):(c=G(f)||f.propertyName,p="_id",d=!1):f.type==="one-to-many"?(c="_id",p=K(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 Ei=new RegExp("\\p{Mark}","gu");function Tr(r){return r==null?"":String(r).normalize("NFKD").replace(Ei,"").toLowerCase()}function xn(){let r={};for(let e=128;e<=1114111;e++)try{let t=String.fromCodePoint(e),n=Tr(t);n!==t&&(r[t]=n)}catch{}return JSON.stringify(r)}function Gt(){return`function() {
|
|
7
7
|
var M = ${xn()};
|
|
8
8
|
function foldStr(s) {
|
|
9
9
|
if (s == null) return '';
|