@enfyra/kernel 1.1.58 → 1.1.59
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
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use strict";var yi=Object.create;var Vt=Object.defineProperty;var bi=Object.getOwnPropertyDescriptor;var _i=Object.getOwnPropertyNames;var wi=Object.getPrototypeOf,$i=Object.prototype.hasOwnProperty;var U=(r,e)=>()=>(r&&(e=r(r=0)),e);var On=(r,e)=>{for(var t in e)Vt(r,t,{get:e[t],enumerable:!0})},_r=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of _i(e))!$i.call(r,i)&&i!==t&&Vt(r,i,{get:()=>e[i],enumerable:!(n=bi(e,i))||n.enumerable});return r};var de=(r,e,t)=>(t=r!=null?yi(wi(r)):{},_r(e||!r||!r.__esModule?Vt(t,"default",{value:r,enumerable:!0}):t,r)),Ti=r=>_r(Vt({},"__esModule",{value:!0}),r);function Ir(r){return Dn.createHash("md5").update(r).digest("hex").substring(0,8)}function Nr(r){return r.length<=vr-3?`${r}_pk`:`j_${Ir(r)}_pk`}function Mr(r,e,t){let n=`${r}_${e}_foreign`;return n.length<=vr?n:`j_${Ir(r)}_${t}_fk`}function vt(r,e,t){let n=`${r}:${e}:${t}`;return`j_${Dn.createHash("sha1").update(n).digest("hex").slice(0,12)}`}function V(r){return`${r}Id`}function It(r,e,t){return{sourceColumn:"sourceId",targetColumn:"targetId"}}function Er(r){return r.replace(/_([a-z])/g,e=>e[1].toUpperCase())}function Or(r){return r.replace(/([A-Z])/g,"_$1").toLowerCase()}function Ar(r,e,t){return`${r}_${e}_${t}_fk`}function Pr(r,e,t){return`${r}_${e}_${t}_idx`}var Dn,vr,qe=U(()=>{"use strict";Dn=de(require("crypto")),vr=63});function cn(r){return co[r]??null}var $e,Un,Mt,co,un=U(()=>{"use strict";$e=new Set(["_eq","_neq","_gt","_gte","_lt","_lte","_in","_not_in","_nin","_contains","_starts_with","_ends_with","_between","_is_null","_is_not_null"]),Un=new Set(["_and","_or","_not"]),Mt=[...Array.from(Un),...Array.from($e)],co={_eq:"eq",_neq:"neq",_gt:"gt",_gte:"gte",_lt:"lt",_lte:"lte",_in:"in",_not_in:"not_in",_nin:"not_in",_contains:"contains",_starts_with:"starts_with",_ends_with:"ends_with",_between:"between"}});var I,fe=U(()=>{"use strict";I=class extends Error{constructor(t="Bad Request",n){let i=Array.isArray(t),o=i?t.join("; ")||"Bad Request":typeof t=="string"?t:JSON.stringify(t);super(o);this.statusCode=400;this.errorCode="BAD_REQUEST";this.name="BadRequestException",this.details=n,i&&(this.messages=t)}}});function Dr(){let r=process.env.DB_URI||"";return r.startsWith("mongodb://")||r.startsWith("mongodb+srv://")}var Wr=U(()=>{"use strict"});function Ee(r,e,t){throw new I({message:`Unsupported filter operator "${r}" on field "${e}"${t?` (table "${t}")`:""}. Supported operators: ${Mt.join(", ")}.`,error:"UnsupportedFilterOperator",operator:r,field:e,supportedOperators:Mt})}function dn(r,e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=Dr();for(let i of Object.keys(e))if(i.startsWith("_")&&!$e.has(i)){if(n&&i==="_id")continue;Ee(i,r,t)}}function ie(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(uo.has(s)){if(Array.isArray(a))for(let c of a)ie(c,e,t);else a&&typeof a=="object"&&ie(a,e,t);continue}let u=o.get(s);if(u){if(a&&typeof a=="object"&&!Array.isArray(a)){dn(s,a,e);let c=u.targetTableName||u.targetTable;if(c){let d=Object.keys(a).filter(l=>!l.startsWith("_"));if(d.length>0){let l={};for(let f of d)l[f]=a[f];ie(l,c,t)}}}continue}s.startsWith("_")&&!i.has(s)&&s!=="_id"&&Ee(s,s,e),a&&typeof a=="object"&&!Array.isArray(a)&&dn(s,a,e)}}var uo,ze=U(()=>{"use strict";fe();un();Wr();uo=new Set(["_and","_or","_not"])});function pe(r,e,t,n){return!r||typeof r!="object"?{node:null,hasRelationFilters:!1}:fn(r,{tableName:e,metadata:t,registry:n,parentJoinId:null,currentJoinId:null,currentTable:e})}function fn(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=fo(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 fo(r,e,t){if(r==="_and")return Kr("and",e,t);if(r==="_or")return Kr("or",e,t);if(r==="_not"){let c=fn(e,t);return c.node?{node:{kind:"not",child:c.node},hasRelationFilters:c.hasRelationFilters}:{node:null,hasRelationFilters:c.hasRelationFilters}}let n=t.metadata?.tables?.get(t.currentTable),i=n?.columns?.some(c=>c.name==="_id"&&c.isPrimary),o=n?.columns?.some(c=>c.name==="id"),a=r==="id"?i&&!o?"_id":"id":r,u=n?.relations?.find(c=>c.propertyName===a);return u?po(a,e,u,t):n&&!n.columns?.find(d=>d.name===a)?(r.startsWith("_")&&r!=="_id"&&Ee(r,r,t.currentTable),console.warn(`[filter-parser] Unknown field "${r}" on table "${t.currentTable}" \u2014 skipped (not a column or relation in metadata).`),{node:null,hasRelationFilters:!1}):go(a,e,t)}function Kr(r,e,t){if(!Array.isArray(e))return{node:null,hasRelationFilters:!1};let n=[],i=!1;for(let o of e){let s=fn(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 po(r,e,t,n){if(typeof e!="object"||e===null)return{node:null,hasRelationFilters:!0};let i=Object.keys(e),o=i.length===1&&(i[0]==="_is_null"||i[0]==="_is_not_null"||i[0]==="_eq"||i[0]==="_neq"||i[0]==="_in"||i[0]==="_not_in"||i[0]==="_nin"),s=n.registry.registerWithParent(n.currentTable,r,n.metadata,"left",n.currentJoinId,"filter");if(o&&i[0]==="_is_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_null===!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(o&&i[0]==="_is_not_null")return s?{node:{kind:"relation_exists",joinId:s,negate:e._is_not_null!==!0},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(o&&(i[0]==="_eq"||i[0]==="_neq")&&e[i[0]]===null)return s?{node:{kind:"relation_exists",joinId:s,negate:i[0]==="_eq"},hasRelationFilters:!0}:{node:null,hasRelationFilters:!0};if(!s)return{node:null,hasRelationFilters:!0};let a=t.targetTableName||t.targetTable,u={...n,parentJoinId:n.currentJoinId,currentJoinId:s,currentTable:a},c=new Set(["_eq","_neq","_in","_not_in","_nin","_gt","_gte","_lt","_lte"]),l=i.length>0&&i.every(p=>c.has(p))?{id:e}:e;return{node:fn(l,u).node,hasRelationFilters:!0}}function go(r,e,t){let n={joinId:t.currentJoinId,fieldName:r,isUuid:mo(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("_")&&!$e.has(s)&&Ee(s,r,t.tableName);let i=Object.entries(e).filter(([s])=>$e.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=ho(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 ho(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=cn(e);return n?{kind:"compare",field:r,op:n,value:t}:null}function mo(r,e){let t=e.metadata?.tables?.get(e.currentTable);if(!t)return!1;let n=r.includes(".")?r.split(".").pop():r,i=t.columns?.find(s=>s.name===n);if(!i)return!1;let o=(i.type||"").toLowerCase();return o==="uuid"||o==="uuidv4"||o.includes("uuid")}var Et=U(()=>{"use strict";un();ze()});var oe,Ot=U(()=>{"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 f=this.map.get(a);return i==="inner"&&(f.joinType="inner"),f.purposes.includes(s)||f.purposes.push(s),a}let u=n?.tables?.get(e);if(!u)return null;let c=u.relations?.find(f=>f.propertyName===t);if(!c)return null;let d=c.targetTableName||c.targetTable;if(!d)return null;let l={id:a,propertyName:t,parentTable:e,targetTable:d,relationType:c.type,parentJoinId:o,joinType:i,relationMeta:c,purposes:[s]};return this.map.set(a,l),a}}});async function K(r,e,t=se){if(!Number.isInteger(t)||t<1)throw new Error("Batch fetch chunk size must be a positive integer");if(r.length<=t)return e(r);let n=[];for(let u=0;u<r.length;u+=t)n.push(r.slice(u,u+t));let i=[],o=0;async function s(){for(;o<n.length;){let u=o++;i[u]=await e(n[u])}}let a=Math.min(Xn,n.length);return await Promise.all(Array.from({length:a},s)),i.flat()}function Ge(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 Oe,se,Xn,Zn,Ce,Ye=U(()=>{"use strict";fe();Oe=16,se=5e3,Xn=4,Zn=10;Ce=class{constructor(e,t,n){this.adapter=e;this.metadataGetter=t;this.trace=n}enrichNestedDescs(e,t,n){if(!t||Object.keys(t).length===0)return e;let i=e.map(s=>{let a=t[s.relationName];if(!a)return s;let u=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(c=>c.trim()).filter(Boolean):["*"];return{...s,fields:u,userFilter:a.filter??s.userFilter,userSort:a.sort??s.userSort,userLimit:a.limit!==void 0?Number(a.limit):s.userLimit,userPage:a.page!==void 0?Number(a.page):s.userPage,nestedDeep:a.deep??s.nestedDeep}}),o=new Set(i.map(s=>s.relationName));for(let[s,a]of Object.entries(t)){if(o.has(s))continue;let u=n?.relations?.find(d=>d.propertyName===s);if(!u)continue;let c=a.fields!=null?Array.isArray(a.fields)?a.fields:String(a.fields).split(",").map(d=>d.trim()).filter(Boolean):["*"];i.push({relationName:s,type:u.type,targetTable:u.targetTableName||u.targetTable,fields:c,isInverse:u.isInverse,fkColumn:u.foreignKeyColumn,mappedBy:u.mappedBy,junctionTableName:u.junctionTableName,junctionSourceColumn:u.junctionSourceColumn,junctionTargetColumn:u.junctionTargetColumn,userFilter:a.filter,userSort:a.sort,userLimit:a.limit!==void 0?Number(a.limit):void 0,userPage:a.page!==void 0?Number(a.page):void 0,nestedDeep:a.deep})}return i}withDefaultToManyLimit(e){return e.userLimit===void 0&&(e.type==="one-to-many"||e.type==="many-to-many")?{...e,userLimit:Zn}:e}fieldsForNestedResolution(e,t){if(!t||Object.keys(t).length===0)return e;let n=new Set(e.filter(o=>o!=="*").map(o=>o.split(".")[0])),i=[...e];for(let o of Object.keys(t))n.has(o)||i.push(o);return i}uniqueValues(e){let t=new Set,n=[];for(let i of e){if(i==null)continue;let o=this.adapter.keyOf(i);t.has(o)||(t.add(o),n.push(i))}return n}assertLocalSortFields(e,t){if(!e.userSort)return;let n=Array.isArray(e.userSort)?e.userSort:String(e.userSort).split(",").map(i=>i.trim()).filter(Boolean);for(let i of n){let o=i.startsWith("-")?i.slice(1):i;if(o.includes("."))throw new I(`Sort field '${o}' is not supported on deep relation '${e.relationName}'. Sort only by local fields defined on '${e.targetTable}'.`);let s=t.columns?.some(u=>u.name===o),a=o==="id"&&t.columns?.some(u=>u.name==="_id");if(!s&&!a)throw new I(`Sort field '${o}' does not exist on '${e.targetTable}'. Sort only by fields defined on the table metadata.`)}}async execute(e,t,n=3,i=0,o){if(e.length===0||t.length===0||i>=n)return;let s;o&&(s=await this.metadataGetter(o)??void 0),await Promise.all(t.map(a=>{let u=this.withDefaultToManyLimit(a);return u.type==="many-to-one"||u.type==="one-to-one"&&!u.isInverse?this.fetchOwnerRelation(e,u,n,i):u.type==="one-to-many"||u.type==="one-to-one"&&u.isInverse?this.fetchInverseRelation(e,u,n,i,s):u.type==="many-to-many"?this.fetchM2MRelation(e,u,n,i,s):Promise.resolve()}))}async fetchOwnerRelation(e,t,n,i){let o=this.adapter.resolveOwnerFkKey(t),s=new Set,a=[];for(let _ of e){let C=_[o];if(C==null)continue;let T=this.adapter.keyOf(C);s.has(T)||(s.add(T),a.push(C))}if(a.length===0){for(let _ of e)_[t.relationName]=null,o!==t.relationName&&delete _[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete _[t.fkColumn];return}let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{isPkOnly:c,nestedDescs:d,fetchSpec:l}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),f=this.adapter.getTargetPkField(u);if(c){for(let _ of e){let C=_[o];_[t.relationName]=C!=null?this.adapter.buildScalarRef(C,f):null,o!==t.relationName&&delete _[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete _[t.fkColumn]}return}let p=performance.now(),m=await this.adapter.fetchOwner(t.targetTable,a,l,t),g=Array.isArray(m)?m:m.docs,h=Array.isArray(m)?void 0:m.stats;this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,p,{relationType:t.type,targetTable:t.targetTable,strategy:h?.strategy??"batch-in",roundtrips:h?.roundtrips??(Math.ceil(a.length/se)||1),concurrencyWaves:h?.concurrencyWaves,ioConcurrency:h?.ioConcurrency,rowsTransferred:h?.rowsTransferred??g.length,rowsReturned:g.length,rowsDiscarded:0,userFilter:!!t.userFilter,userSort:!!t.userSort});let y=this.enrichNestedDescs(d,t.nestedDeep,u);y.length>0&&await this.execute(g,y,n,i+1,t.targetTable);let b=new Map;for(let _ of g)b.set(this.adapter.keyOf(_[f]),_);for(let _ of e){let C=_[o];_[t.relationName]=C!=null&&b.get(this.adapter.keyOf(C))||null,o!==t.relationName&&delete _[o],t.fkColumn&&t.fkColumn!==t.relationName&&delete _[t.fkColumn]}}async fetchInverseRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=this.uniqueValues(e.map(v=>v[s]));if(a.length===0)return;let u=this.adapter.resolveInverseFkField(t),c=await this.metadataGetter(t.targetTable);if(!c)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,c);let{nestedDescs:d,fetchSpec:l}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),c),f=performance.now(),{docs:p,groupKeyField:m,stats:g}=await this.adapter.fetchInverse(t.targetTable,u,a,l,t),h=new Map,y=t.fields.includes(u)||t.fields.includes("*");for(let v of p){let B=v[m],S=this.adapter.keyOf(B);h.has(S)||h.set(S,[]),h.get(S).push(v)}let b=t.userLimit!==void 0&&t.userLimit>0,_=b?"per-parent-c16":"batch-in",C=b?a.length:Math.ceil(a.length/se)||1,T=b?Math.ceil(a.length/Oe):void 0,k=Array.from(h.values()).reduce((v,B)=>v+B.length,0);if(this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,f,{relationType:t.type,targetTable:t.targetTable,strategy:g?.strategy??_,roundtrips:g?.roundtrips??C,concurrencyWaves:g?.concurrencyWaves??T,ioConcurrency:g?.ioConcurrency,rowsTransferred:g?.rowsTransferred??p.length,rowsReturned:k,rowsDiscarded:Math.max(0,(g?.rowsTransferred??p.length)-k),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort}),this.adapter.postProcessInverseChild)for(let v of p)this.adapter.postProcessInverseChild(v,u,y);let F=this.enrichNestedDescs(d,t.nestedDeep,c);F.length>0&&await this.execute(p,F,n,i+1,t.targetTable);let w=t.type==="one-to-one";for(let v of e){let B=this.adapter.keyOf(v[s]),S=h.get(B)||[];v[t.relationName]=w?S[0]||null:S}}async fetchM2MRelation(e,t,n,i,o){let s=this.adapter.resolveParentPk(o),a=this.uniqueValues(e.map(T=>T[s]));if(a.length===0)return;let u=await this.metadataGetter(t.targetTable);if(!u)throw new Error(`Metadata not found for target table: ${t.targetTable}`);this.assertLocalSortFields(t,u);let{nestedDescs:c,fetchSpec:d}=this.adapter.resolveFields(this.fieldsForNestedResolution(t.fields,t.nestedDeep),u),l=performance.now(),{grouped:f,docs:p,stats:m}=await this.adapter.fetchM2M(e,t,o,u,d),g=t.userLimit!==void 0&&t.userLimit>0,h=g?"m2m-per-parent-c16":"m2m-batch",y=g?a.length:Math.ceil(a.length/se)||1,b=g?Math.ceil(a.length/Oe):void 0,_=Array.from(f.values()).reduce((T,k)=>T+k.length,0);this.trace?.dur(`batch_fetch_L${i}_${t.relationName}`,l,{relationType:t.type,targetTable:t.targetTable,strategy:m?.strategy??h,roundtrips:m?.roundtrips??y,concurrencyWaves:m?.concurrencyWaves??b,ioConcurrency:m?.ioConcurrency,rowsTransferred:m?.rowsTransferred??p.length,rowsReturned:_,rowsDiscarded:m?.rowsDiscarded??Math.max(0,(m?.rowsTransferred??p.length)-_),userLimit:t.userLimit,userFilter:!!t.userFilter,userSort:!!t.userSort});let C=this.enrichNestedDescs(c,t.nestedDeep,u);C.length>0&&p.length>0&&await this.execute(p,C,n,i+1,t.targetTable);for(let T of e){let k=this.adapter.keyOf(T[s]);T[t.relationName]=f.get(k)||[]}}}});var Gr,ke,_n=U(()=>{"use strict";Gr=2,ke=class{constructor(e=2){this.concurrency=e;this.active=0;this.waiters=[];if(!Number.isInteger(e)||e<1)throw new Error("Batch execution concurrency must be a positive integer")}async run(e){await this.acquire();try{return await e()}catch(t){throw this.cancel(t),t}finally{this.release()}}async acquire(){if(this.failure!==void 0)throw this.failure;if(this.active<this.concurrency){this.active+=1;return}if(await new Promise(e=>this.waiters.push(e)),this.failure!==void 0)throw this.failure;this.active+=1}release(){this.active-=1,this.failure===void 0&&this.waiters.shift()?.()}cancel(e){if(this.failure===void 0){this.failure=e;for(let t of this.waiters.splice(0))t()}}}});function x(r,e){let t=e==="mysql"?r.replace(/`/g,"``"):r.replace(/"/g,'""');switch(e){case"mysql":return`\`${t}\``;case"postgres":case"pg":case"sqlite":return`"${t}"`;case"mongodb":return r;default:return`\`${t}\``}}function Fe(r,e){return r.split(".").map(t=>t==="*"||t.startsWith('"')&&t.endsWith('"')||t.startsWith("`")&&t.endsWith("`")?t:x(t,e)).join(".")}var le=U(()=>{"use strict"});function ue(r,e,t){e&&Fn(r,e,t,"and")}function Fn(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(){Fn(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(){Fn(this,o,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"not":{let i=function(){this.whereNot(function(){Fn(this,e.child,t,"and")})};n==="or"?r.orWhere(i):r.where(i);return}case"compare":Jo(r,e,t,n);return;case"relation_exists":console.warn(`[sql-render-filter] relation_exists node reached renderer directly (rootTable=${t.rootTable}, joinId=${e.joinId}) \u2014 expected to be handled by applyRelationFilters. Filter silently skipped.`);return}}function Jo(r,e,t,n){if(e.field.joinId!==null){console.warn(`[sql-render-filter] compare node has joinId=${e.field.joinId} (field=${e.field.fieldName}) but reached renderer \u2014 expected join path to handle it. Filter silently skipped.`);return}let i=zo(e.field,t),o=Fe(i,t.dbType),s=!!e.field.isUuid,a=t.dbType==="postgres",u=n==="or"?"orWhere":"where",c=n==="or"?"orWhereRaw":"whereRaw",d=n==="or"?"orWhereIn":"whereIn",l=n==="or"?"orWhereNotIn":"whereNotIn",f=n==="or"?"orWhereBetween":"whereBetween",p=n==="or"?"orWhereNull":"whereNull",m=n==="or"?"orWhereNotNull":"whereNotNull";switch(e.op){case"eq":s&&a&&typeof e.value=="string"?r[c](`${o} = ?::uuid`,[e.value]):r[u](i,"=",e.value);return;case"neq":s&&a&&typeof e.value=="string"?r[c](`${o} != ?::uuid`,[e.value]):r[u](i,"!=",e.value);return;case"gt":s&&a&&typeof e.value=="string"?r[c](`${o} > ?::uuid`,[e.value]):r[u](i,">",e.value);return;case"gte":s&&a&&typeof e.value=="string"?r[c](`${o} >= ?::uuid`,[e.value]):r[u](i,">=",e.value);return;case"lt":s&&a&&typeof e.value=="string"?r[c](`${o} < ?::uuid`,[e.value]):r[u](i,"<",e.value);return;case"lte":s&&a&&typeof e.value=="string"?r[c](`${o} <= ?::uuid`,[e.value]):r[u](i,"<=",e.value);return;case"in":{let g=ai(e.value);s&&a&&g.every(h=>typeof h=="string")?r[c](`${o} = ANY(?::uuid[])`,[g]):r[d](i,g);return}case"not_in":{let g=ai(e.value);s&&a&&g.every(h=>typeof h=="string")?r[c](`${o} != ALL(?::uuid[])`,[g]):r[l](i,g);return}case"contains":ur(r,o,e.value,"contains",t,n);return;case"starts_with":ur(r,o,e.value,"starts_with",t,n);return;case"ends_with":ur(r,o,e.value,"ends_with",t,n);return;case"between":Array.isArray(e.value)&&e.value.length===2&&r[f](i,[e.value[0],e.value[1]]);return;case"is_null":e.value===!0?r[p](i):r[m](i);return}}function ur(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 zo(r,e){return r.fieldName.includes(".")?r.fieldName:`${e.rootTable}.${r.fieldName}`}function ai(r){return Array.isArray(r)?r:typeof r=="string"&&r.includes(",")?r.split(",").map(e=>e.trim()):[r]}var dr=U(()=>{"use strict";le()});function Y(r){return r.columns.find(e=>e.isPrimary)||null}var Ut=U(()=>{"use strict"});var li={};On(li,{expandFieldsToJoinsAndSelect:()=>fr});async function fr(r,e,t,n,i,o){let s=[],a=[],u=await t(r);if(!u)return{select:[],batchFetchDescriptors:[]};let c=new Map;for(let l of e)if(l==="*"||!l.includes("."))c.has("")||c.set("",[]),c.get("").push(l);else{let f=l.split("."),p=f[0],m=f.slice(1).join(".");c.has(p)||c.set(p,[]),c.get(p).push(m)}if(o&&typeof o=="object")for(let[l,f]of Object.entries(o)){if(c.has(l))continue;let p=f&&typeof f=="object"&&f.fields!=null?Array.isArray(f.fields)?f.fields:String(f.fields).split(",").map(m=>m.trim()).filter(Boolean):["*"];c.set(l,p)}let d=c.get("")||[];for(let l of d){if(l==="*"){let m=new Set;for(let h of u.relations||[])if(h.type==="many-to-one"||h.type==="one-to-one"&&!h.isInverse){let y=h.foreignKeyColumn||V(h.propertyName);y&&m.add(y)}let g=new Set;for(let h of u.columns)m.has(h.name)||(s.push(`${r}.${h.name}`),g.add(h.name));for(let h of u.relations||[])!c.has(h.propertyName)&&!g.has(h.propertyName)&&c.set(h.propertyName,["id"]);continue}if(l.includes(".")){s.push(`${r}.${l}`);continue}if(u.columns?.find(m=>m.name===l)){s.push(`${r}.${l}`);continue}if(u.relations?.find(m=>m.propertyName===l)){c.has(l)||c.set(l,["id"]);continue}}return c.forEach((l,f)=>{if(f==="")return;let p=u.relations?.find(b=>b.propertyName===f);if(!p)return;if(p.type==="many-to-one"||p.type==="one-to-one"&&!p.isInverse){let b=p.foreignKeyColumn||V(p.propertyName),_=x(r,n),C=x(b,n),T=x(f,n);s.push(`${_}.${C} as ${T}`)}let g=p.targetTableName||p.targetTable,h=o?.[f],y=h?.fields!=null?Array.isArray(h.fields)?h.fields:String(h.fields).split(",").map(b=>b.trim()).filter(Boolean):l;a.push({relationName:f,type:p.type,targetTable:g,fields:y,isInverse:p.isInverse,fkColumn:p.foreignKeyColumn,mappedBy:p.mappedBy,junctionTableName:p.junctionTableName,junctionSourceColumn:p.junctionSourceColumn,junctionTargetColumn:p.junctionTargetColumn,userFilter: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 pr=U(()=>{"use strict";qe();le()});var Qt,Jt,xn,st,Vo,at,hr=U(()=>{"use strict";qe();le();Ut();Ye();_n();dr();Ot();Et();Qt="__enfyra_row_number__",Jt="__sourceId__",xn="__targetId__",st="__enfyra_partitioned__",Vo=5e4,at=class{constructor(e,t="postgres",n,i=new ke){this.knex=e;this.dbType=t;this.metadata=n;this.executionBudget=i;this.pkField="id"}chunkCount(e,t=se){return Math.ceil(e.length/t)||1}m2mTargetChunkSize(){return this.dbType==="postgres"?Vo:se}uniqueValues(e){return Array.from(new Map(e.filter(t=>t!=null).map(t=>[this.keyOf(t),t])).values())}runQuery(e){return this.executionBudget.run(()=>e)}buildPartitionRowNumber(e,t,n){let i=[...t];i.some(s=>s.column===n)||i.push({column:n,order:"asc"});let o=i.map(s=>`?? ${s.order.toUpperCase()}`).join(", ");return this.knex.raw(`ROW_NUMBER() OVER (PARTITION BY ?? ORDER BY ${o}) as ??`,[e,...i.map(s=>s.column),Qt])}buildPartitionSlice(e,t,n,i){return this.knex.from(e.as(st)).select(`${st}.*`).where(`${st}.${Qt}`,">",n).andWhere(`${st}.${Qt}`,"<=",n+i).orderBy(`${st}.${t}`,"asc").orderBy(`${st}.${Qt}`,"asc")}removePartitionFields(e){for(let t of e)delete t[Qt]}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}=pe(e,t,i,n);return o}parseSortTokens(e,t,n){return e?(Array.isArray(e)?e:e.split(",").map(o=>o.trim()).filter(Boolean)).map(o=>{let s=o.startsWith("-"),u=(s?o.slice(1):o).split(".");if(u.length===1)return{column:n?`${n}.${u[0]}`:`${t}.${u[0]}`,order:s?"desc":"asc"};let c=u[u.length-1];return{column:`${`__sort_${u.slice(0,-1).join("_")}`}.${c}`,order:s?"desc":"asc"}}):[]}applySortJoins(e,t,n,i){if(!t||!this.metadata)return;let o=Array.isArray(t)?t:t.split(",").map(a=>a.trim()).filter(Boolean),s=new Set;for(let a of o){let c=(a.startsWith("-")?a.slice(1):a).split(".");if(c.length<=1)continue;let d=n,l=i||n;for(let f=0;f<c.length-1;f++){let p=c[f],m=this.metadata?.tables?.get(d);if(!m)break;let g=m.relations?.find(b=>b.propertyName===p);if(!g)break;let h=g.targetTableName||g.targetTable,y=`__sort_${c.slice(0,f+1).join("_")}`;if(!s.has(y)){s.add(y);let b=g.foreignKeyColumn||V(g.propertyName),_=this.metadata?.tables?.get(h),C=_&&Y(_)?.name||"id";e.leftJoin(`${h} as ${y}`,`${y}.${C}`,`${l}.${b}`)}d=h,l=y}}}toKnexSelect(e,t){let n=e.indexOf(" as ");if(n!==-1){let i=e.substring(0,n),o=e.substring(n+4),s=x(o,this.dbType),a=t?`${t}.${x(i,this.dbType)}`:x(i,this.dbType);return this.knex.raw(`${a} as ${s}`)}return t?this.knex.raw(`${t}.${x(e,this.dbType)} as ${x(e,this.dbType)}`):e}keyOf(e){return e==null?"":String(e)}buildScalarRef(e,t){return{[t||this.pkField]:e}}getTargetPkField(e){return Y(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&&Y(e)?.name||"id"}resolveFields(e,t){let{rootFields:n,subRelations:i}=Ge(e),o=[];if(n.includes("*")){let c=new Set;for(let d of t.relations||[])if(d.type==="many-to-one"||d.type==="one-to-one"&&!d.isInverse){let l=d.foreignKeyColumn||V(d.propertyName);l&&c.add(l)}for(let d of t.columns)c.has(d.name)||o.push(d.name);for(let d of t.relations||[])i.has(d.propertyName)||i.set(d.propertyName,["id"])}else for(let c of n){let d=t.columns.find(l=>l.name===c);d?o.push(d.name):t.relations?.find(f=>f.propertyName===c)&&!i.has(c)&&i.set(c,["id"])}let s=Y(t)?.name||"id";o.includes(s)||o.push(s),i.forEach((c,d)=>{let l=t.relations?.find(f=>f.propertyName===d);if(l&&(l.type==="many-to-one"||l.type==="one-to-one"&&!l.isInverse)){let f=l.foreignKeyColumn||V(l.propertyName);f&&o.push(`${f} as ${d}`)}});let a=[];return i.forEach((c,d)=>{let l=t.relations?.find(p=>p.propertyName===d);if(!l)return;let f=l.targetTableName||l.targetTable;f&&a.push({relationName:d,type:l.type,targetTable:f,fields:c,isInverse:l.isInverse,fkColumn:l.foreignKeyColumn,mappedBy:l.mappedBy,junctionTableName:l.junctionTableName,junctionSourceColumn:l.junctionSourceColumn,junctionTargetColumn:l.junctionTargetColumn})}),{isPkOnly:o.length===1&&o[0]===s&&a.length===0,nestedDescs:a,fetchSpec:{selectCols:o,pkCol:s}}}async fetchOwner(e,t,n,i){let o=i?.userFilter?this.buildFilterTree(i.userFilter,e):null,s=i?.userSort?this.parseSortTokens(i.userSort,e):[],a=n.selectCols.map(c=>this.toKnexSelect(c)),u=await K(t,c=>{let d=this.knex(e).select(a).whereIn(n.pkCol,c);if(o&&ue(d,o,{dbType:this.dbType,rootTable:e}),s.length>0){this.applySortJoins(d,i.userSort,e);for(let l of s)d.orderBy(l.column,l.order)}return this.runQuery(d)});return{docs:u,stats:{strategy:"batch-in",roundtrips:this.chunkCount(t),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:u.length}}}async fetchInverse(e,t,n,i,o){let s=t,a=i.selectCols.find(m=>m.startsWith(`${t} as `));a?s=a.split(" as ")[1].trim():i.selectCols.includes(t)||i.selectCols.push(t);let u=o?.userFilter?this.buildFilterTree(o.userFilter,e):null,c=o?.userSort?this.parseSortTokens(o.userSort,e):[],d=o?.userLimit,l=o?.userPage;if(d!==void 0&&d>0){let m=l?(l-1)*d:0,g=i.selectCols.map(y=>this.toKnexSelect(y)),h=await K(n,async y=>{let b=this.knex(e).select(g).select(this.buildPartitionRowNumber(`${e}.${t}`,c,`${e}.${i.pkCol}`)).whereIn(`${e}.${t}`,y);u&&ue(b,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(b,o.userSort,e);let _=await this.runQuery(this.buildPartitionSlice(b,s,m,d));return this.removePartitionFields(_),_});return{docs:h,groupKeyField:s,stats:{strategy:"partitioned-top-k",roundtrips:this.chunkCount(n),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:h.length}}}let f=i.selectCols.map(m=>this.toKnexSelect(m)),p=await K(n,m=>{let g=this.knex(e).select(f).whereIn(t,m);if(u&&ue(g,u,{dbType:this.dbType,rootTable:e}),this.applySortJoins(g,o?.userSort,e),c.length>0)for(let h of c)g.orderBy(h.column,h.order);else g.orderBy(i.pkCol,"asc");return this.runQuery(g)});return{docs:p,groupKeyField:s,stats:{strategy:"batch-in",roundtrips:this.chunkCount(n),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length}}}postProcessInverseChild(e,t,n){n||delete e[t]}async selectM2MEdges(e,t,n,i,o,s,a,u){let c=`t.${s}`,d=!!a||u.some(g=>g.column!==c),l=d?u:u.map(g=>({...g,column:`${n}.${o}`})),f=t.userLimit,p=t.userPage;if(f!==void 0&&f>0){let g=p?(p-1)*f:0;return(await K(e,async y=>{let b=this.knex(n).select({[Jt]:`${n}.${i}`,[xn]:`${n}.${o}`}).whereIn(`${n}.${i}`,y);d&&(b=b.join(`${t.targetTable} as t`,`${n}.${o}`,`t.${s}`),a&&ue(b,a,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(b,t.userSort,t.targetTable,"t")),b.select(this.buildPartitionRowNumber(`${n}.${i}`,l,d?c:`${n}.${o}`));let _=await this.runQuery(this.buildPartitionSlice(b,Jt,g,f));return this.removePartitionFields(_),_})).map(y=>({sourceId:y[Jt],targetId:y[xn]}))}return(await K(e,g=>{let h=this.knex(n).select({[Jt]:`${n}.${i}`,[xn]:`${n}.${o}`}).whereIn(`${n}.${i}`,g);if(d&&(h=h.join(`${t.targetTable} as t`,`${n}.${o}`,`t.${s}`),a&&ue(h,a,{dbType:this.dbType,rootTable:"t"}),this.applySortJoins(h,t.userSort,t.targetTable,"t")),h.orderBy(`${n}.${i}`,"asc"),l.length>0){for(let y of l)h.orderBy(y.column,y.order);d&&!l.some(y=>y.column===c)&&h.orderBy(c,"asc")}else h.orderBy(`${n}.${o}`,"asc");return this.runQuery(h)})).map(g=>({sourceId:g[Jt],targetId:g[xn]}))}async loadM2MTargets(e,t,n){if(t.length===0)return[];let i=n.selectCols.map(o=>this.toKnexSelect(o));return K(t,o=>this.runQuery(this.knex(e).select(i).whereIn(n.pkCol,o)),this.m2mTargetChunkSize())}async fetchM2M(e,t,n,i,o){let s=this.resolveParentPk(n),a=this.uniqueValues(e.map(F=>F[s]));if(a.length===0)return{grouped:new Map,docs:[]};let u=t.junctionTableName,c=t.junctionSourceColumn,d=t.junctionTargetColumn;if(!u||!c||!d)throw new Error(`Missing junction table config for relation: ${t.relationName}`);let l=t.userFilter?this.buildFilterTree(t.userFilter,t.targetTable):null,f=t.userSort?this.parseSortTokens(t.userSort,t.targetTable,"t"):[],p=await this.selectM2MEdges(a,t,u,c,d,o.pkCol,l,f),m=new Map;for(let F of a)m.set(this.keyOf(F),[]);let g=o.selectCols.length===1&&o.selectCols[0]===o.pkCol,h=t.userLimit!==void 0&&t.userLimit>0,y=this.chunkCount(a),b=`t.${o.pkCol}`,_=!l&&f.every(F=>F.column===b);if(g){let F=new Map;for(let w of p){let v=this.keyOf(w.targetId);F.has(v)||F.set(v,{[o.pkCol]:w.targetId}),m.get(this.keyOf(w.sourceId))?.push(F.get(v))}return{grouped:m,docs:[],stats:{strategy:_?h?"m2m-junction-partitioned-top-k":"m2m-junction-batch":h?"m2m-filtered-edge-top-k":"m2m-filtered-edge-batch",roundtrips:y,ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length,rowsDiscarded:0}}}let C=this.uniqueValues(p.map(F=>F.targetId)),T=await this.loadM2MTargets(t.targetTable,C,o),k=new Map(T.map(F=>[this.keyOf(F[o.pkCol]),F]));for(let F of p){let w=k.get(this.keyOf(F.targetId));w&&m.get(this.keyOf(F.sourceId))?.push(w)}return{grouped:m,docs:T,stats:{strategy:h?"m2m-partitioned-edge-loader":"m2m-edge-loader",roundtrips:y+(C.length>0?this.chunkCount(C,this.m2mTargetChunkSize()):0),ioConcurrency:this.executionBudget.concurrency,rowsTransferred:p.length+T.length,rowsDiscarded:0}}}}});var fi={};On(fi,{executeBatchFetches:()=>mr});async function mr(r,e,t,n,i=3,o=0,s,a="postgres",u,c){let d=new at(r,a,u);await new Ce(d,n,c).execute(e,t,i,o,s)}var yr=U(()=>{"use strict";Ye();hr()});var Xo={};On(Xo,{ALL_SUPPORTED_OPERATORS:()=>Mt,AuthenticationException:()=>ht,AuthorizationException:()=>mt,BadRequestException:()=>I,BatchExecutionBudget:()=>ke,BatchFetchEngine:()=>Ce,BusinessLogicException:()=>dt,CHUNKED_FETCH_CONCURRENCY:()=>Xn,ConfigurationException:()=>Tt,DEEP_TO_MANY_DEFAULT_LIMIT:()=>Zn,DEFAULT_BATCH_FETCH_IO_CONCURRENCY:()=>Gr,DEFAULT_TIMEOUT_MS:()=>Ht,DOTTED_PATH_MAX_HOPS:()=>Mn,DatabaseException:()=>De,DuplicateResourceException:()=>gt,ErrorHandler:()=>ve,ExecutorEngineService:()=>Le,ExternalServiceException:()=>_t,FIELD_OPERATORS:()=>$e,FileNotFoundException:()=>Ct,FileSizeExceededException:()=>kt,FileUploadException:()=>St,HttpException:()=>P,ISOLATED_EXECUTOR_RUNTIME_LOG_PATH:()=>Xt,InvalidTokenException:()=>bt,IsolatedExecutorService:()=>Ke,JoinRegistry:()=>oe,LOGICAL_OPERATORS:()=>Un,MongoBatchAdapter:()=>Ze,MongoQueryExecutor:()=>Pe,PER_PARENT_CONCURRENCY:()=>Oe,QueryBuilderService:()=>lt,QueryPlanner:()=>te,ResourceNotFoundException:()=>pt,SchemaException:()=>$t,ScriptContractService:()=>nn,ScriptExecutionException:()=>be,ScriptTimeoutException:()=>ye,ServiceUnavailableException:()=>wt,SqlBatchAdapter:()=>at,SqlQueryExecutor:()=>Be,TokenExpiredException:()=>yt,ValidationException:()=>ft,WHERE_IN_CHUNK_SIZE:()=>se,WorkerPool:()=>Ft,appendIsolatedExecutorRuntimeLog:()=>J,applyOperatorToMatch:()=>ln,applyRelationFilters:()=>Dt,applyWhereToKnex:()=>ot,assertFieldOperatorValueIsClean:()=>dn,buildMongoCharFoldMapJson:()=>Kn,buildMongoFoldTextSearchJs:()=>rn,buildRelationSubquery:()=>Lt,buildSqlWherePartsFromFieldAst:()=>Kt,buildWhereClause:()=>ce,camelToSnake:()=>Or,chunkedFetch:()=>K,compileScriptSource:()=>Xi,computeEngineTuning:()=>jn,createEnfyraKernel:()=>Yo,dslOpToCompareOp:()=>cn,encodeMainThreadToIsolate:()=>Ln,escapeSqlValue:()=>qt,executeBatchFetches:()=>mr,executeMongoBatchFetches:()=>$n,expandFieldsToJoinsAndSelect:()=>fr,getEffectiveCpuCount:()=>Pn,getEffectiveMemoryBytes:()=>Rt,getEngineTuning:()=>tn,getExecutableScript:()=>no,getForeignKeyColumnName:()=>V,getIoAbortSignal:()=>Fr,getJunctionColumnNames:()=>It,getJunctionTableName:()=>vt,getPrimaryKeyColumn:()=>Y,getScriptLegacyField:()=>Hi,getShortFkConstraintName:()=>Mr,getShortFkName:()=>Ar,getShortIndexName:()=>Pr,getShortPkName:()=>Nr,hasLogicalOperators:()=>me,isExecutableJavaScript:()=>Zi,isScriptTable:()=>Gi,normalizeAggregateQuery:()=>nt,normalizeFlowStepScriptConfig:()=>io,normalizeScriptLanguage:()=>Yi,normalizeScriptPatch:()=>to,normalizeScriptRecord:()=>eo,parseBatchFields:()=>Ge,parseFields:()=>Tn,parseFilter:()=>pe,perParentRun:()=>wn,quoteIdentifier:()=>x,quoteQualifiedIdentifier:()=>Fe,resolveExecutableScript:()=>ro,rewriteFilterDenyingFields:()=>hi,rewriteSortDroppingDenied:()=>mi,runWithIoAbortSignal:()=>xr,scriptContractService:()=>ne,separateFilters:()=>G,snakeToCamel:()=>Er,throwUnsupportedFieldOperator:()=>Ee,validateDeepOptions:()=>br,validateFilterShape:()=>ie,whereToMongoFilter:()=>Je});module.exports=Ti(Xo);var Ht=3e4,Le=class{constructor(e){this.isolatedExecutorService=e.isolatedExecutorService}register(e,t){e.routeData.__codeBlocks||(e.routeData.__codeBlocks=[]),e.routeData.__codeBlocks.push(t)}async runBatch(e,t,n={}){let i=e.routeData.__codeBlocks||[];return i.length===0?{value:void 0,shortCircuit:!1}:this.isolatedExecutorService.runBatch(i,e.routeData.context,t??Ht,n)}async run(e,t,n=Ht,i={}){return this.isolatedExecutorService.run(e,t,n,i)}};var Gt=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 Cr=require("async_hooks"),kr=de(require("path")),Rr=require("stream");var wr=require("child_process"),Si=["PATH","HOME","NODE_ENV","TMPDIR","LANG"];function Ci(){let r={};for(let e of Si){let t=process.env[e];t!==void 0&&(r[e]=t)}return r}var Yt=class{constructor(e){this.terminated=!1;this.child=(0,wr.fork)(e,[],{stdio:["ignore","ignore","ignore","ipc"],env:Ci(),serialization:"advanced"})}get pid(){return this.child.pid}on(e,t){return this.child.on(e,t),this}off(e,t){return this.child.off(e,t),this}postMessage(e){if(!this.child.connected)throw new Error("Executor runner IPC is closed");this.child.send(e)}terminate(){if(this.terminated)return;this.terminated=!0;try{this.child.disconnect()}catch{}try{this.child.kill("SIGTERM")}catch{}setTimeout(()=>{if(!(this.child.exitCode!==null||this.child.signalCode!==null))try{this.child.kill("SIGKILL")}catch{}},250).unref?.()}};var ye=class extends Error{constructor(t=0,n,i){let o=typeof t=="number"&&t>0?`${t}ms`:String(t||"configured timeout");super(`Script execution timed out after ${o}`);this.statusCode=408;this.errorCode="SCRIPT_TIMEOUT";this.name="ScriptTimeoutException",this.details={timeoutMs:t,scriptId:n,...i}}},be=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}}},L=class extends Error{constructor(t,n,i,o){super(t);this.statusCode=n;this.errorCode=i;this.name=this.constructor.name,this.details=o}},P=class extends L{constructor(e,t,n){super(e,t,`HTTP_${t}`,n)}},dt=class extends L{constructor(e,t){super(e,400,"BUSINESS_LOGIC_ERROR",t)}},ft=class extends L{constructor(e,t){super(e,422,"VALIDATION_ERROR",t)}},pt=class extends L{constructor(e,t){super(t?`${e} with identifier '${t}' not found`:`${e} not found`,404,"RESOURCE_NOT_FOUND",{resource:e,identifier:t})}},gt=class extends L{constructor(e,t,n){super(`${e} with ${t} '${n}' already exists`,409,"DUPLICATE_RESOURCE",{resource:e,field:t,value:n})}},ht=class extends L{constructor(e="Authentication failed",t){super(e,401,"AUTHENTICATION_ERROR",t)}},mt=class extends L{constructor(e="Insufficient permissions",t){super(e,403,"AUTHORIZATION_ERROR",t)}},yt=class extends L{constructor(){super("Token has expired",401,"TOKEN_EXPIRED")}},bt=class extends L{constructor(){super("Invalid token provided",401,"INVALID_TOKEN")}},De=class extends L{constructor(e,t){super(e,500,"DATABASE_ERROR",t)}},_t=class extends L{constructor(e,t,n){super(`External service '${e}' error: ${t}`,502,"EXTERNAL_SERVICE_ERROR",{service:e,details:n})}},wt=class extends L{constructor(e){super(`Service '${e}' is currently unavailable`,503,"SERVICE_UNAVAILABLE",{service:e})}},$t=class extends L{constructor(e,t){super(e,400,"SCHEMA_ERROR",t)}},Tt=class extends L{constructor(e,t){super(e,500,"CONFIGURATION_ERROR",t)}},St=class extends L{constructor(e,t){super(e,400,"FILE_UPLOAD_ERROR",t)}},Ct=class extends L{constructor(e="File not found"){super(e,404,"FILE_NOT_FOUND")}},kt=class extends L{constructor(e,t){super("File size exceeded",413,"FILE_SIZE_EXCEEDED",{maxSize:e,actualSize:t})}};var ve=class{static createException(e,t,n,i,o){if(e?.includes("$throw"))switch(e){case"$throw.http":return new P(n||"Error",t||500,o);case"$throw.businessLogic":return new dt(n||"Bad request",o);case"$throw.validation":return new ft(n||"Validation failed",o);case"$throw.notFound":return new pt(o?.resource||n||"Resource",o?.identifier);case"$throw.duplicate":return new gt(o?.resource||n||"Resource",o?.field||"field",o?.value||"value");case"$throw.unauthorized":return new ht(n||"Unauthorized");case"$throw.forbidden":return new mt(n||"Forbidden");case"$throw.tokenExpired":return new yt;case"$throw.invalidToken":return new bt;case"$throw.database":return new De(n||"Database error",o);case"$throw.dbQuery":return new De(n||"Query error",o);case"$throw.externalService":return new _t(n||"Service",n||"Error",o);case"$throw.serviceUnavailable":return new wt(n||"Service");case"$throw.rateLimit":return new P(n||"Rate limit exceeded",429);case"$throw.scriptError":return new be(n||"Script error",i,o);case"$throw.scriptTimeout":return new ye(o?.timeout||5e3,i);case"$throw.schema":return new $t(n||"Schema error",o);case"$throw.config":return new Tt(n||"Configuration error",o);case"$throw.fileUpload":return new St(n||"File upload error",o);case"$throw.fileNotFound":return new Ct(n||"File not found");case"$throw.fileSizeExceeded":return new kt(o?.maxSize||"unknown",o?.actualSize||"unknown");case"$throw.400":return new P(n||"Bad request",400,o);case"$throw.401":return new P(n||"Authentication required",401,o);case"$throw.403":return new P(n||"Insufficient permissions",403,o);case"$throw.404":return new P(n||"Not found",404,o);case"$throw.409":return new P(n||"Conflict",409,o);case"$throw.422":return new P(n||"Validation failed",422,o);case"$throw.429":return new P(n||"Rate limit exceeded",429,o);case"$throw.500":return new P(n||"Internal server error",500,o);case"$throw.503":return new P(n||"Service unavailable",503,o);default:return new be(n||"Unknown error",i)}if(t)switch(t){case 400:return new P(n||"Bad request",400,o);case 401:return new P(n||"Authentication required",401,o);case 403:return new P(n||"Insufficient permissions",403,o);case 404:return new P(n||"Not found",404,o);case 409:return new P(n||"Conflict",409,o);case 422:return new P(n||"Validation failed",422,o);case 429:return new P(n||"Rate limit exceeded",429,o);case 500:return new P(n||"Internal server error",500,o);case 503:return new P(n||"Service unavailable",503,o);default:return new be(n||"Unknown error",i,o)}return new be(n||"Unknown error",i,o)}};var Zt=de(require("fs")),en=de(require("path")),Xt=en.join(process.cwd(),"test","logs","isolated-executor-runtime.log");function ki(){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 Ri=ki();function J(r){if(Ri)try{let e=en.dirname(Xt);Zt.mkdirSync(e,{recursive:!0});let t=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...r})+`
|
|
2
|
-
`;Zt.appendFileSync(Xt,t)}catch{}}var _e=de(require("os")),We=de(require("fs"));function Rt(){try{let r=We.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=We.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 Pn(){let r=_e.availableParallelism?.()||_e.cpus()?.length||1;try{let e=We.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(We.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8").trim(),10),t=parseInt(We.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 Fi=.25,An=128,xi=2,vi=4,Ii=6,Ni=8,Mi=2048,Ei=40,Oi=128,Ai=32;function Pi(r){let e=Math.trunc(Number(r));if(!(!Number.isFinite(e)||e<1))return Math.min(An,e)}function ji(r){let e=Math.trunc(Number(r));return!Number.isFinite(e)||e<1?Ii:Math.min(Ni,e)}function $r(r){return 2**Math.ceil(Math.log2(Math.max(1,r)))}function jn(r){let e=Math.max(1,Math.trunc(r.logicalCpuCount)||1),t=Math.max(1,r.totalMemoryBytes/(1024*1024)),n=Math.min(Oi,Math.max(Ei,Math.round(t/Ai))),i=t*Fi,o=Math.max(1,Math.floor(i/n)),s=Math.max(1,Math.min(e,2,o)),a=Math.max(1,Math.floor(i/(s*n))),u=Math.min(An,$r(e*xi)),c=Math.min(An,$r(e*vi)),d=Math.max(u,Math.min(c,a)),l=Pi(r.maxLanesPerRunner)??d,f=t<Mi?1:l,p=Math.max(1,Math.min(f,a)),m=ji(r.tasksPerIsolate),g=p*m;return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:g,isolatePoolSize:p,tasksPerIsolate:m}}function tn(){return jn({logicalCpuCount:Pn(),totalMemoryBytes:Rt()})}var zi=kr.join(__dirname,"execution/worker.js"),Vi=1e3,Bn=new Cr.AsyncLocalStorage;function Fr(){return Bn.getStore()}function xr(r,e){return Bn.run(r,e)}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 c=0;c<e;c++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new Yt(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,reservations:0,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let i=t.tasks.get(n.id);i&&(n.type==="taskReleased"?i.onRelease?.():n.type==="result"||n.type==="taskCancelled"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),typeof n.runnerRssBytes=="number"&&(t.lastRssBytes=n.runnerRssBytes),n.contextStats&&(t.contextStats=n.contextStats),i.onResult(n.type==="taskCancelled"?{type:"result",id:n.id,success:!1,taskCancelled:!0,error:{message:"Task cancelled",code:"ERR_TASK_CANCELLED"}}:n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):i.onIoCall(n))}),e.on("exit",(n,i)=>{let o=t.draining,s=this.destroying,a={entryId:t.id,pid:t.worker.pid,exitCode:n,exitSignal:i??null,lastError:t.lastError,lastHeapRatio:t.lastHeapRatio,lastRssBytes:t.lastRssBytes,activeTasks:[...t.tasks.values()].map(c=>c.diagnostics)};t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,c]of t.tasks)c.abortController.abort(),c.onResult({type:"result",success:!1,error:{message:s?"Worker terminated":t.lastError?`Worker crashed: ${t.lastError}`:"Worker crashed",code:s?void 0:"ERR_EXECUTOR_RUNNER_LOST",details:s?void 0:{outcome:"unknown_outcome",retryable:!1}}});t.tasks.clear();let u=this.entries.indexOf(t);u!==-1&&this.entries.splice(u,1),!o&&!s&&(this.onCrash?.(a),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),e.on("error",n=>{t.lastError=n.message}),this.entries.push(t),t}rotateEntry(e,t){if(e.draining)return;e.draining=!0;let n=Date.now()-e.spawnedAt;if(this.onRotate&&this.onRotate({reason:t,ageMs:n}),this.spawnEntry(),e.tasks.size===0){e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,e.worker.terminate()},this.drainTimeoutMs)}isMemoryAvailable(){let e=Date.now();return e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs&&(this.cachedMemoryOk=process.memoryUsage().rss/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e),this.cachedMemoryOk}findLeastBusy(){let e=null;for(let t of this.entries){if(t.draining)continue;let n=t.tasks.size+t.reservations;n<this.tasksCap&&(!e||n<e.tasks.size+e.reservations)&&(e=t)}return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size+e.reservations===0||this.isMemoryAvailable())?(e.reservations++,Promise.resolve(e)):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.reservations=Math.max(0,e.reservations-1),e.tasks.set(t,n)}releaseReservation(e){e.reservations=Math.max(0,e.reservations-1),this.drainWaiting()}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&(e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(e&&(e.tasks.size+e.reservations===0||this.isMemoryAvailable()))e.reservations++,this.waiting.shift()(e);else break}}terminateEntry(e){e.worker.terminate()}resize(e){for(this.max=Math.max(1,e);this.entries.length<this.max;)this.spawnEntry()}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,pid:e.worker.pid,activeTasks:e.tasks.size,reservations:e.reservations,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,lastRssBytes:e.lastRssBytes??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}},Sr=new Set(["$helpers","$cache","$transaction","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$debug"]);function Ln(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 Ke=class r{constructor(e){this.logger=new Gt(r.name);this.effectiveMemory=Rt();this.prevCpuUsage=process.cpuUsage();this.prevCpuTime=process.hrtime.bigint();this.pressureTicks=0;this.recoveryTicks=0;this.taskCounter=0;this.taskDoneTotal=0;this.taskErrorTotal=0;this.taskTimeoutTotal=0;this.rotationsTotal=0;this.crashesTotal=0;this.responseStreams=new Map;this.taskCancellers=new Map;this.taskDurationsMs=[];this.queueWaitDurationsMs=[];this.runtimeCallbackCounter=0;this.packageCacheService=e.packageCacheService,this.packageCdnLoaderService=e.packageCdnLoaderService,this.isolationTuning=e.tuning??tn(),this.ceiling=this.isolationTuning.maxConcurrentWorkers,this.pool=new Ft(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,zi,t=>{this.crashesTotal++;let n={event:"executor_worker_crashed",...t};this.logger.warn(n),J(n)},({reason:t,ageMs:n})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${t} age=${Math.round(n/1e3)}s`)}),this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerIsolate} tasks/isolate, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let t=process.memoryUsage().rss/this.effectiveMemory,n=process.hrtime.bigint(),i=process.cpuUsage(this.prevCpuUsage),o=Number(n-this.prevCpuTime)/1e3,s=o>0?(i.user+i.system)/o:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let a=this.pool.getMax(),u=this.pool.getWaitingCount(),c=t>.85||s>.7,d=t<.7&&s<.5,l=u>0,f=a;c?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(f=Math.max(1,a-1))):d&&l?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(f=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),f!==a&&(this.pool.resize(f),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${f} (rss=${Math.round(t*100)}% cpu=${Math.round(s*100)}% queue=${u})`))}createSnapshot(e){let t={$body:e.$body,$query:e.$query,$params:e.$params,$user:e.$user,$share:e.$share,$data:e.$data,$api:{request:e.$api?.request},$uploadedFile:e.$uploadedFile,$req:this.cloneSnapshotValue(e.$req)};for(let i of Object.keys(e)){if(!i.startsWith("$")||i in t||Sr.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"||Sr.has(n)||n==="$env"||(e[n]=i));delete e.$pkgs}}spawnAndExecute(e,t,n,i,o){return(async()=>{let s=Date.now(),a=await this.pool.dispatch();if(this.recordQueueWait(Date.now()-s),o?.aborted){this.pool.releaseReservation(a);let d=new Error("Execution aborted after client disconnect");return d.code="ERR_EXECUTION_ABORTED",d.isAbort=!0,Promise.reject(d)}let u=`t_${++this.taskCounter}`,c=Date.now();return new Promise((d,l)=>{let f=!1,p=new AbortController,m=!1,g,h=()=>{let w=new Error("Execution aborted after client disconnect");return w.code="ERR_EXECUTION_ABORTED",w.isAbort=!0,w},y=()=>{let w=new Error(`Script execution timed out after ${i}ms`);return w.code="ERR_SCRIPT_EXECUTION_TIMEOUT",w.isTimeout=!0,w},b,_=w=>{if(!(f||m)){m=!0,g=w,p.abort(),this.cleanupResponseStream(u,w);try{a.worker.postMessage({type:"cancelTask",id:u})}catch{}b=setTimeout(()=>{f||(f=!0,clearTimeout(F),k(),this.taskCancellers.delete(u),this.pool.unregisterTask(a,u),this.taskErrorTotal++,J({event:"task_cancel_grace_terminate",id:u}),this.pool.terminateEntry(a),w.details={...w.details??{},outcome:"unknown_outcome",retryable:!1,escalation:"runner_terminated_after_cancel_grace"},l(w))},Vi),b.unref?.()}},C=()=>_(h());this.taskCancellers.set(u,C);let T=()=>C(),k=()=>{o?.removeEventListener("abort",T)};o&&o.addEventListener("abort",T,{once:!0});let F=setTimeout(()=>{f||(this.taskTimeoutTotal++,J({event:"task_timeout",id:u,timeoutMs:i}),_(y()))},i);this.pool.registerTask(a,u,{abortController:p,diagnostics:this.createWorkerTaskDiagnostics(e,t,n,i),onResult:w=>{if(!f){if(w.taskCancelled===!0&&this.pool.unregisterTask(a,u),f=!0,clearTimeout(F),b&&clearTimeout(b),this.taskCancellers.delete(u),k(),this.cleanupResponseStream(u),this.recordTaskDuration(Date.now()-c),m){p.abort(),this.taskErrorTotal++,l(g??h());return}if(w.success){this.taskDoneTotal++,J({event:"task_done",id:u,ok:!0});let v={value:w.value,valueAbsent:w.valueAbsent===!0,ctxChanges:w.ctxChanges};w.shortCircuit&&(v.shortCircuit=!0),d(v)}else{this.taskErrorTotal++,J({event:"task_done",id:u,ok:!1,message:w.error?.message});let v=new Error(w.error?.message||"Handler execution failed");v.statusCode=w.error?.statusCode,v.code=w.error?.code,v.errorCode=w.error?.code,v.details=w.error?.details,w.error?.stack&&(v.stack=w.error.stack),w.ctxChanges&&(v.ctxChanges=w.ctxChanges),this.cleanupResponseStream(u,v),l(v)}}},onRelease:()=>{this.pool.unregisterTask(a,u)},onIoCall:w=>{if(f)return;let v=p.signal;w.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(w,n),a.worker,w.callId,v):w.type==="transactionCall"?this.handleIoCall(()=>this.execTransactionCall(w,n,a.worker),a.worker,w.callId,v):w.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(w,n),a.worker,w.callId,v):w.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(w,n),a.worker,w.callId,v):w.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(w,n),a.worker,w.callId,v):w.type==="storageCall"?this.handleIoCall(()=>this.execStorageCall(w,n,a.worker),a.worker,w.callId,v):w.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall(w,n),a.worker,w.callId,v):w.type==="resCall"&&this.handleIoCall(()=>this.execResCall(w,n),a.worker,w.callId,v)}}),a.worker.postMessage({type:e,id:u,...t}),o?.aborted&&C()})})()}postAbortedCallError(e,t){try{e.postMessage({type:"callError",callId:t,error:JSON.stringify({__userThrow:!0,message:"Execution aborted after client disconnect",code:"ERR_EXECUTION_ABORTED"})})}catch{}}async handleIoCall(e,t,n,i){if(i?.aborted){this.postAbortedCallError(t,n);return}try{let o=await(i?Bn.run(i,e):e());if(i?.aborted){this.postAbortedCallError(t,n);return}try{t.postMessage({type:"callResult",callId:n,result:Ln(o)})}catch{}}catch(o){if(i?.aborted){this.postAbortedCallError(t,n);return}try{let s={__userThrow:!0,message:o.message,statusCode:o.statusCode,code:o.errorCode??o.code,details:o.details,messages:o.messages};t.postMessage({type:"callError",callId:n,error:JSON.stringify(s)})}catch{}}}async execRepoCall(e,t){let n=JSON.parse(e.argsJson),i=e.access==="secure"?t?.$repos?.secure?.[e.table]:t?.$repos?.[e.table];if(!i||typeof i[e.method]!="function"){let o=e.access==="secure"?"secure.":"";throw new Error(`Repo method not found: ${o}${e.table}.${e.method}`)}return i[e.method](...n)}async execTransactionCall(e,t,n){let o=JSON.parse(e.argsJson||"[]").map(a=>a?.__fnRef&&typeof a.__fnRef=="string"?(...u)=>this.invokeRuntimeCallback(n,e.id,a.__fnRef,u):a)[0];if(typeof o!="function")throw new Error("$transaction.run requires a callback");let s=t?.$transaction?.run;if(typeof s!="function")throw new Error("$transaction is not available");return await s.call(t.$transaction,o)}async execHelpersCall(e,t){let n=JSON.parse(e.argsJson),i=e.name.split("."),o=t?.$helpers;for(let s of i)o=o?.[s];if(typeof o!="function")throw new Error(`Helper not found: ${e.name}`);return o(...n)}async execSocketCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$socket?.[e.method];if(typeof i!="function")throw new Error(`Socket method not found: ${e.method}`);return i(...n)}async execCacheCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$cache?.[e.method];if(typeof i!="function")throw new Error(`Cache method not found: ${e.method}`);return i(...n)}async execStorageCall(e,t,n){let i=this.parseStorageArgs(e.argsJson,n,e.id),o=t?.$storage?.[e.method];if(typeof o!="function")throw new Error(`Storage method not found: ${e.method}`);return o(...i)}parseStorageArgs(e,t,n){return JSON.parse(e,(i,o)=>{if(o?.__fnRef&&typeof o.__fnRef=="string"){let s=o.__fnRef;return(...a)=>this.invokeRuntimeCallback(t,n,s,a)}return o})}invokeRuntimeCallback(e,t,n,i){let o=`rtcb_${++this.runtimeCallbackCounter}`;return new Promise((s,a)=>{let u=setTimeout(()=>{d(),a(new Error(`Runtime callback timed out: ${n}`))},3e4),c=l=>{if(!(l?.type!=="runtimeCallbackResult"||l.callId!==o)){if(d(),l.error){a(new Error(l.error));return}s(l.value)}},d=()=>{clearTimeout(u),e.off("message",c)};e.on("message",c),e.postMessage({type:"invokeRuntimeCallback",id:t,callId:o,callbackId:n,argsJson:JSON.stringify(i)})})}async execDispatchCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$trigger;if(typeof i!="function")throw new Error("$trigger is not available");return i(...n)}cancelTask(e){this.taskCancellers.get(e)?.()}async execResCall(e,t){if(e.method==="streamStart"){let s=JSON.parse(e.argsJson||"[]")[1]||{},a=t?.$res?.stream;if(typeof a!="function")throw new Error("Response method not found: stream");let u=new Rr.PassThrough,c={stream:u};this.responseStreams.set(e.id,c);let d=t?.$res;if(d&&typeof d.once=="function"){let f=()=>{d.writableEnded!==!0&&this.cancelTask(e.id)};d.once("close",f),c.closeCleanup=()=>{typeof d.off=="function"?d.off("close",f):typeof d.removeListener=="function"&&d.removeListener("close",f)}}let l=a.call(t.$res,u,s);return l&&typeof l.catch=="function"&&l.catch(()=>{}),!0}if(e.method==="streamChunk"){let o=this.responseStreams.get(e.id);if(!o)throw new Error(`Response stream not found: ${e.id}`);let s=Buffer.from(e.chunk||"","base64");return o.stream.write(s)||await new Promise((a,u)=>{let c=()=>{l(),a()},d=f=>{l(),u(f)},l=()=>{o.stream.off("drain",c),o.stream.off("error",d)};o.stream.once("drain",c),o.stream.once("error",d)}),!0}if(e.method==="streamEnd"){let o=this.responseStreams.get(e.id);return o&&(o.closeCleanup?.(),o.stream.end(),this.responseStreams.delete(e.id)),!0}if(e.method==="streamError"){let o=this.responseStreams.get(e.id);if(o){o.closeCleanup?.();let s=e.error?.message||"Response stream failed";o.stream.destroy(new Error(s)),this.responseStreams.delete(e.id)}return!0}let n=JSON.parse(e.argsJson||"[]"),i=t?.$res?.[e.method];if(typeof i!="function")throw new Error(`Response method not found: ${e.method}`);return i.apply(t.$res,n)}cleanupResponseStream(e,t){let n=this.responseStreams.get(e);n&&(this.responseStreams.delete(e),n.closeCleanup?.(),t?n.stream.destroy(t):n.stream.end())}toWorkerCodeBlock(e){return{code:e.code,sourceCode:e.sourceCode,scriptLanguage:e.scriptLanguage,scriptId:e.scriptId,type:e.type}}createWorkerTaskDiagnostics(e,t,n,i){let o=n?.$api?.request?.correlationId,s=Array.isArray(t.codeBlocks)?t.codeBlocks.map(a=>({type:a?.type==="preHook"||a?.type==="postHook"||a?.type==="handler"?a.type:"run",...a?.scriptId!==void 0&&a?.scriptId!==null?{scriptId:String(a.scriptId)}:{}})):[{type:"run"}];return{...typeof o=="string"&&o?{correlationId:o}:{},timeoutMs:i,isolateMemoryLimitMb:Number(t.memoryLimitMb||0),isolatePoolSize:Number(t.isolatePoolSize||0),tasksPerIsolate:Number(t.tasksPerIsolate||0),scriptBlocks:s}}async run(e,t,n,i={}){let o=Math.max(1,Math.trunc(Number(n)||3e4)),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),u=this.createSnapshot(t);J({event:"isolated_run_start",timeoutMs:o,codeLen:e?.length??0});let c;try{let d={code:e,sourceCode:i.sourceCode??e,pkgSources:a,snapshot:u,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize,tasksPerIsolate:this.isolationTuning.tasksPerIsolate};c=await this.spawnAndExecute("execute",d,t,o)}catch(d){let l=d;if(J({event:"isolated_run_error",message:l.message,code:l.code,isTimeout:!!l.isTimeout}),l.code==="ERR_EXECUTION_ABORTED"||l.isAbort)throw l;if(l.isTimeout||l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new ye(o,e,l.details);l.code&&l.details&&(l.details.executorCode=l.code);let f=l.statusCode??(typeof l.status=="number"?l.status:void 0);throw ve.createException(l.errorPath,f,l.message||"Unknown error",e,l.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),J({event:"isolated_run_ok"}),c.valueAbsent?void 0:c.value}async runBatch(e,t,n,i={}){let o=Math.max(1,Math.trunc(Number(n)||3e4)),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),u=this.createSnapshot(t);J({event:"isolated_batch_start",timeoutMs:o,blocks:e.length});let c;try{let l={codeBlocks:e.map(f=>this.toWorkerCodeBlock(f)),pkgSources:a,snapshot:u,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize,tasksPerIsolate:this.isolationTuning.tasksPerIsolate};c=await this.spawnAndExecute("executeBatch",l,t,o,i.signal)}catch(d){let l=d;if(J({event:"isolated_batch_error",message:l.message,code:l.code,isTimeout:!!l.isTimeout}),l.ctxChanges&&this.mergeCtxChanges(t,l.ctxChanges),l.code==="ERR_EXECUTION_ABORTED"||l.isAbort)throw l;if(l.isTimeout||l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new ye(o,"(batch execution)",l.details);l.code&&l.details&&(l.details.executorCode=l.code);let f=l.statusCode??(typeof l.status=="number"?l.status:void 0);throw ve.createException(l.errorPath,f,l.message||"Unknown error","(batch execution)",l.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),J({event:"isolated_batch_ok"}),{value:c.valueAbsent?void 0:c.value,shortCircuit:c.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}recordQueueWait(e){this.queueWaitDurationsMs.push(e),this.queueWaitDurationsMs.length>512&&this.queueWaitDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,s)=>o-s),i=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[i]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((s,a)=>s+a,0)/t.length,i=this.queueWaitDurationsMs,o=i.length===0?0:i.reduce((s,a)=>s+a,0)/i.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),avgQueueWaitMs:o,p95QueueWaitMs:this.percentile(i,95),p99QueueWaitMs:this.percentile(i,99),maxHeapRatio:Math.max(0,...e.workers.map(s=>s.lastHeapRatio||0)),runnerRssBytes:e.workers.reduce((s,a)=>s+(a.lastRssBytes||0),0)}}};var Ie=de(require("typescript")),xt={oauth_config_definition:"",route_handler_definition:"logic",pre_hook_definition:"code",post_hook_definition:"code",bootstrap_script_definition:"logic",websocket_definition:"connectionHandlerScript",websocket_event_definition:"handlerScript"};function Hi(r){return ne.getLegacyField(r)}function Gi(r){return ne.isScriptTable(r)}function Yi(r){return ne.normalizeLanguage(r)}var nn=class{getLegacyField(e){return xt[e]}isScriptTable(e){return e in xt}normalizeLanguage(e){return e==="javascript"?"javascript":"typescript"}compileSource(e,t){if(e==null||e==="")return null;let n=String(e),o=this.normalizeLanguage(t)==="javascript"?n:this.transpileTypeScript(n);return this.assertExecutableJavaScript(o),o}isExecutableJavaScript(e){if(!e)return!1;try{return this.assertExecutableJavaScript(e),!0}catch{return!1}}normalizeRecord(e,t){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let n={...t},i=this.getLegacyField(e);return i&&(n.sourceCode===void 0||n.sourceCode===null||n.sourceCode==="")&&n[i]!==void 0&&(n.sourceCode=n[i]),n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage),i&&i in n&&delete n[i],n}normalizePatch(e,t,n){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let i=this.getLegacyField(e),o=Object.prototype.hasOwnProperty.call(t,"sourceCode")||(i?Object.prototype.hasOwnProperty.call(t,i):!1),s=Object.prototype.hasOwnProperty.call(t,"scriptLanguage");if(!o&&!s)return t;let a=o?t.sourceCode??(i?t[i]:void 0):n?.sourceCode??(i&&n?n[i]:void 0),u=s?t.scriptLanguage:n?.scriptLanguage,c={...t};return o&&(c.sourceCode=a??null),c.scriptLanguage=this.normalizeLanguage(u),c.compiledCode=this.compileSource(a,c.scriptLanguage),i&&i in c&&delete c[i],c}getExecutableScript(e){return this.resolveExecutableScript(e).code}resolveExecutableScript(e){if(!e||typeof e!="object")return{code:null,compiledCode:null,shouldPersistCompiledCode:!1};if(typeof e.sourceCode=="string"&&e.sourceCode!==""){let n=this.compileSource(e.sourceCode,e.scriptLanguage);return{code:n,compiledCode:n,shouldPersistCompiledCode:n!==e.compiledCode}}let t=Object.keys(xt).find(n=>xt[n]in e);if(t){let n=e[xt[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=Ie.default.transpileModule(e,{compilerOptions:{target:Ie.default.ScriptTarget.ES2022,module:Ie.default.ModuleKind.CommonJS,importsNotUsedAsValues:Ie.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),n=t.diagnostics?.find(i=>i.category===Ie.default.DiagnosticCategory.Error);if(n)throw new Error(Ie.default.flattenDiagnosticMessageText(n.messageText,`
|
|
2
|
+
`;Zt.appendFileSync(Xt,t)}catch{}}var _e=de(require("os")),We=de(require("fs"));function Rt(){try{let r=We.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=We.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 Pn(){let r=_e.availableParallelism?.()||_e.cpus()?.length||1;try{let e=We.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(We.readFileSync("/sys/fs/cgroup/cpu/cpu.cfs_quota_us","utf8").trim(),10),t=parseInt(We.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 Fi=.25,An=128,xi=2,vi=4,Ii=6,Ni=8,Mi=2048,Ei=40,Oi=128,Ai=32;function Pi(r){let e=Math.trunc(Number(r));if(!(!Number.isFinite(e)||e<1))return Math.min(An,e)}function ji(r){let e=Math.trunc(Number(r));return!Number.isFinite(e)||e<1?Ii:Math.min(Ni,e)}function $r(r){return 2**Math.ceil(Math.log2(Math.max(1,r)))}function jn(r){let e=Math.max(1,Math.trunc(r.logicalCpuCount)||1),t=Math.max(1,r.totalMemoryBytes/(1024*1024)),n=Math.min(Oi,Math.max(Ei,Math.round(t/Ai))),i=t*Fi,o=Math.max(1,Math.floor(i/n)),s=Math.max(1,Math.min(e,2,o)),a=Math.max(1,Math.floor(i/(s*n))),u=Math.min(An,$r(e*xi)),c=Math.min(An,$r(e*vi)),d=Math.max(u,Math.min(c,a)),l=Pi(r.maxLanesPerRunner)??d,f=t<Mi?1:l,p=Math.max(1,Math.min(f,a)),m=ji(r.tasksPerIsolate),g=p*m;return{maxConcurrentWorkers:s,isolateMemoryLimitMb:n,tasksPerWorkerCap:g,isolatePoolSize:p,tasksPerIsolate:m}}function tn(){return jn({logicalCpuCount:Pn(),totalMemoryBytes:Rt()})}var zi=kr.join(__dirname,"execution/worker.js"),Vi=1e3,Bn=new Cr.AsyncLocalStorage;function Fr(){return Bn.getStore()}function xr(r,e){return Bn.run(r,e)}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 c=0;c<e;c++)this.spawnEntry()}getEntries(){return this.entries}spawnEntry(){let e=new Yt(this.scriptPath),t={id:++this.entryCounter,worker:e,tasks:new Map,reservations:0,draining:!1,spawnedAt:Date.now()};return e.on("message",n=>{let i=t.tasks.get(n.id);i&&(n.type==="taskReleased"?i.onRelease?.():n.type==="result"||n.type==="taskCancelled"?(typeof n.heapRatio=="number"&&(t.lastHeapRatio=n.heapRatio),typeof n.runnerRssBytes=="number"&&(t.lastRssBytes=n.runnerRssBytes),n.contextStats&&(t.contextStats=n.contextStats),i.onResult(n.type==="taskCancelled"?{type:"result",id:n.id,success:!1,taskCancelled:!0,error:{message:"Task cancelled",code:"ERR_TASK_CANCELLED"}}:n),!t.draining&&typeof n.heapRatio=="number"&&n.heapRatio>=.8&&this.rotateEntry(t,`heap=${Math.round(n.heapRatio*100)}%`)):i.onIoCall(n))}),e.on("exit",(n,i)=>{let o=t.draining,s=this.destroying,a={entryId:t.id,pid:t.worker.pid,exitCode:n,exitSignal:i??null,lastError:t.lastError,lastHeapRatio:t.lastHeapRatio,lastRssBytes:t.lastRssBytes,activeTasks:[...t.tasks.values()].map(c=>c.diagnostics)};t.drainTimeout&&(clearTimeout(t.drainTimeout),t.drainTimeout=void 0);for(let[,c]of t.tasks)c.abortController.abort(),c.onResult({type:"result",success:!1,error:{message:s?"Worker terminated":t.lastError?`Worker crashed: ${t.lastError}`:"Worker crashed",code:s?void 0:"ERR_EXECUTOR_RUNNER_LOST",details:s?void 0:{outcome:"unknown_outcome",retryable:!1}}});t.tasks.clear();let u=this.entries.indexOf(t);u!==-1&&this.entries.splice(u,1),!o&&!s&&(this.onCrash?.(a),this.entries.length<this.max&&this.spawnEntry()),this.drainWaiting()}),e.on("error",n=>{t.lastError=n.message}),this.entries.push(t),t}rotateEntry(e,t){if(e.draining)return;e.draining=!0;let n=Date.now()-e.spawnedAt;if(this.onRotate&&this.onRotate({reason:t,ageMs:n}),this.spawnEntry(),e.tasks.size===0){e.worker.terminate();return}e.drainTimeout=setTimeout(()=>{e.drainTimeout=void 0,e.worker.terminate()},this.drainTimeoutMs)}isMemoryAvailable(){let e=Date.now();return e-this.lastMemoryCheckMs>=this.memorySampleIntervalMs&&(this.cachedMemoryOk=process.memoryUsage().rss/this.effectiveMemory<this.rssCeiling,this.lastMemoryCheckMs=e),this.cachedMemoryOk}findLeastBusy(){let e=null;for(let t of this.entries){if(t.draining)continue;let n=t.tasks.size+t.reservations;n<this.tasksCap&&(!e||n<e.tasks.size+e.reservations)&&(e=t)}return e}dispatch(){let e=this.findLeastBusy();return e&&(e.tasks.size+e.reservations===0||this.isMemoryAvailable())?(e.reservations++,Promise.resolve(e)):new Promise(t=>this.waiting.push(t))}registerTask(e,t,n){e.reservations=Math.max(0,e.reservations-1),e.tasks.set(t,n)}releaseReservation(e){e.reservations=Math.max(0,e.reservations-1),this.drainWaiting()}unregisterTask(e,t){e.tasks.delete(t),e.draining&&e.tasks.size===0&&(e.drainTimeout&&(clearTimeout(e.drainTimeout),e.drainTimeout=void 0),e.worker.terminate()),this.drainWaiting()}drainWaiting(){for(;this.waiting.length>0;){let e=this.findLeastBusy();if(e&&(e.tasks.size+e.reservations===0||this.isMemoryAvailable()))e.reservations++,this.waiting.shift()(e);else break}}terminateEntry(e){e.worker.terminate()}resize(e){for(this.max=Math.max(1,e);this.entries.length<this.max;)this.spawnEntry()}getMax(){return this.max}getWaitingCount(){return this.waiting.length}getTotalActiveTasks(){let e=0;for(let t of this.entries)e+=t.tasks.size;return e}getMetrics(){return{max:this.max,activeTasks:this.getTotalActiveTasks(),waitingTasks:this.waiting.length,workers:this.entries.map(e=>({id:e.id,pid:e.worker.pid,activeTasks:e.tasks.size,reservations:e.reservations,draining:e.draining,ageMs:Date.now()-e.spawnedAt,lastHeapRatio:e.lastHeapRatio??0,lastRssBytes:e.lastRssBytes??0,contextStats:e.contextStats??{}}))}}destroyAll(){this.destroying=!0;for(let e of this.entries)e.worker.terminate();this.entries.length=0,this.waiting.length=0}},Sr=new Set(["$helpers","$cache","$transaction","$repos","$req","$res","$socket","$storage","$logs","$throw","$trigger","$pkgs","$debug"]);function Ln(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 Ke=class r{constructor(e){this.logger=new Gt(r.name);this.effectiveMemory=Rt();this.prevCpuUsage=process.cpuUsage();this.prevCpuTime=process.hrtime.bigint();this.pressureTicks=0;this.recoveryTicks=0;this.taskCounter=0;this.taskDoneTotal=0;this.taskErrorTotal=0;this.taskTimeoutTotal=0;this.rotationsTotal=0;this.crashesTotal=0;this.responseStreams=new Map;this.taskCancellers=new Map;this.taskDurationsMs=[];this.queueWaitDurationsMs=[];this.runtimeCallbackCounter=0;this.packageCacheService=e.packageCacheService,this.packageCdnLoaderService=e.packageCdnLoaderService,this.isolationTuning=e.tuning??tn(),this.ceiling=this.isolationTuning.maxConcurrentWorkers,this.pool=new Ft(this.isolationTuning.maxConcurrentWorkers,this.effectiveMemory,.9,this.isolationTuning.tasksPerWorkerCap,zi,t=>{this.crashesTotal++;let n={event:"executor_worker_crashed",...t};this.logger.warn(n),J(n)},({reason:t,ageMs:n})=>{this.rotationsTotal++,this.logger.log(`Worker rotation: reason=${t} age=${Math.round(n/1e3)}s`)}),this.logger.log(`Worker pool started: ${this.isolationTuning.maxConcurrentWorkers} workers, ${this.isolationTuning.isolateMemoryLimitMb}MB per isolate, ${this.isolationTuning.isolatePoolSize} isolates/worker, ${this.isolationTuning.tasksPerIsolate} tasks/isolate, ${this.isolationTuning.tasksPerWorkerCap} tasks/worker cap`),this.tuneTimer=setInterval(()=>this.autoTune(),3e4)}onDestroy(){this.tuneTimer&&clearInterval(this.tuneTimer),this.pool.destroyAll()}autoTune(){let t=process.memoryUsage().rss/this.effectiveMemory,n=process.hrtime.bigint(),i=process.cpuUsage(this.prevCpuUsage),o=Number(n-this.prevCpuTime)/1e3,s=o>0?(i.user+i.system)/o:0;this.prevCpuUsage=process.cpuUsage(),this.prevCpuTime=n;let a=this.pool.getMax(),u=this.pool.getWaitingCount(),c=t>.85||s>.7,d=t<.7&&s<.5,l=u>0,f=a;c?(this.recoveryTicks=0,this.pressureTicks++,this.pressureTicks>=3&&(f=Math.max(1,a-1))):d&&l?(this.pressureTicks=0,this.recoveryTicks++,this.recoveryTicks>=3&&(f=Math.min(this.ceiling,a+2))):(this.pressureTicks=0,this.recoveryTicks=0),f!==a&&(this.pool.resize(f),this.pressureTicks=0,this.recoveryTicks=0,this.logger.log(`Worker pool adjusted: ${a} -> ${f} (rss=${Math.round(t*100)}% cpu=${Math.round(s*100)}% queue=${u})`))}createSnapshot(e){let t={$body:e.$body,$query:e.$query,$params:e.$params,$user:e.$user,$share:e.$share,$data:e.$data,$api:{request:e.$api?.request},$uploadedFile:e.$uploadedFile,$req:this.cloneSnapshotValue(e.$req)};for(let i of Object.keys(e)){if(!i.startsWith("$")||i in t||Sr.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"||Sr.has(n)||n==="$env"||(e[n]=i));delete e.$pkgs}}spawnAndExecute(e,t,n,i,o){return(async()=>{let s=Date.now(),a=await this.pool.dispatch();if(this.recordQueueWait(Date.now()-s),o?.aborted){this.pool.releaseReservation(a);let d=new Error("Execution aborted after client disconnect");return d.code="ERR_EXECUTION_ABORTED",d.isAbort=!0,Promise.reject(d)}let u=`t_${++this.taskCounter}`,c=Date.now();return new Promise((d,l)=>{let f=!1,p=new AbortController,m=!1,g,h=()=>{let w=new Error("Execution aborted after client disconnect");return w.code="ERR_EXECUTION_ABORTED",w.isAbort=!0,w},y=()=>{let w=new Error(`Script execution timed out after ${i}ms`);return w.code="ERR_SCRIPT_EXECUTION_TIMEOUT",w.isTimeout=!0,w},b,_=w=>{if(!(f||m)){m=!0,g=w,p.abort(),this.cleanupResponseStream(u,w);try{a.worker.postMessage({type:"cancelTask",id:u})}catch{}b=setTimeout(()=>{f||(f=!0,clearTimeout(F),k(),this.taskCancellers.delete(u),this.pool.unregisterTask(a,u),this.taskErrorTotal++,J({event:"task_cancel_grace_terminate",id:u}),this.pool.terminateEntry(a),w.details={...w.details??{},outcome:"unknown_outcome",retryable:!1,escalation:"runner_terminated_after_cancel_grace"},l(w))},Vi),b.unref?.()}},C=()=>_(h());this.taskCancellers.set(u,C);let T=()=>C(),k=()=>{o?.removeEventListener("abort",T)};o&&o.addEventListener("abort",T,{once:!0});let F=setTimeout(()=>{f||(this.taskTimeoutTotal++,J({event:"task_timeout",id:u,timeoutMs:i}),_(y()))},i);this.pool.registerTask(a,u,{abortController:p,diagnostics:this.createWorkerTaskDiagnostics(e,t,n,i),onResult:w=>{if(!f){if(w.taskCancelled===!0&&this.pool.unregisterTask(a,u),f=!0,clearTimeout(F),b&&clearTimeout(b),this.taskCancellers.delete(u),k(),this.cleanupResponseStream(u),this.recordTaskDuration(Date.now()-c),m){p.abort(),this.taskErrorTotal++,l(g??h());return}if(w.success){this.taskDoneTotal++,J({event:"task_done",id:u,ok:!0});let v={value:w.value,valueAbsent:w.valueAbsent===!0,ctxChanges:w.ctxChanges};w.shortCircuit&&(v.shortCircuit=!0),d(v)}else{this.taskErrorTotal++,J({event:"task_done",id:u,ok:!1,message:w.error?.message});let v=new Error(w.error?.message||"Handler execution failed");v.statusCode=w.error?.statusCode,v.code=w.error?.code,v.errorCode=w.error?.code,v.details=w.error?.details,w.error?.stack&&(v.stack=w.error.stack),w.ctxChanges&&(v.ctxChanges=w.ctxChanges),this.cleanupResponseStream(u,v),l(v)}}},onRelease:()=>{this.pool.unregisterTask(a,u)},onIoCall:w=>{if(f)return;let v=p.signal;w.type==="repoCall"?this.handleIoCall(()=>this.execRepoCall(w,n),a.worker,w.callId,v):w.type==="transactionCall"?this.handleIoCall(()=>this.execTransactionCall(w,n,a.worker),a.worker,w.callId,v):w.type==="helpersCall"?this.handleIoCall(()=>this.execHelpersCall(w,n),a.worker,w.callId,v):w.type==="socketCall"?this.handleIoCall(()=>this.execSocketCall(w,n),a.worker,w.callId,v):w.type==="cacheCall"?this.handleIoCall(()=>this.execCacheCall(w,n),a.worker,w.callId,v):w.type==="storageCall"?this.handleIoCall(()=>this.execStorageCall(w,n,a.worker),a.worker,w.callId,v):w.type==="dispatchCall"?this.handleIoCall(()=>this.execDispatchCall(w,n),a.worker,w.callId,v):w.type==="resCall"&&this.handleIoCall(()=>this.execResCall(w,n),a.worker,w.callId,v)}}),a.worker.postMessage({type:e,id:u,...t}),o?.aborted&&C()})})()}postAbortedCallError(e,t){try{e.postMessage({type:"callError",callId:t,error:JSON.stringify({__userThrow:!0,message:"Execution aborted after client disconnect",code:"ERR_EXECUTION_ABORTED"})})}catch{}}async handleIoCall(e,t,n,i){if(i?.aborted){this.postAbortedCallError(t,n);return}try{let o=await(i?Bn.run(i,e):e());if(i?.aborted){this.postAbortedCallError(t,n);return}try{t.postMessage({type:"callResult",callId:n,result:Ln(o)})}catch{}}catch(o){if(i?.aborted){this.postAbortedCallError(t,n);return}try{let s={__userThrow:!0,message:o.message,statusCode:o.statusCode,code:o.errorCode??o.code,errorPath:o.errorPath,details:o.details,messages:o.messages};t.postMessage({type:"callError",callId:n,error:JSON.stringify(s)})}catch{}}}async execRepoCall(e,t){let n=JSON.parse(e.argsJson),i=e.access==="secure"?t?.$repos?.secure?.[e.table]:t?.$repos?.[e.table];if(!i||typeof i[e.method]!="function"){let o=e.access==="secure"?"secure.":"";throw new Error(`Repo method not found: ${o}${e.table}.${e.method}`)}return i[e.method](...n)}async execTransactionCall(e,t,n){let o=JSON.parse(e.argsJson||"[]").map(a=>a?.__fnRef&&typeof a.__fnRef=="string"?(...u)=>this.invokeRuntimeCallback(n,e.id,a.__fnRef,u):a)[0];if(typeof o!="function")throw new Error("$transaction.run requires a callback");let s=t?.$transaction?.run;if(typeof s!="function")throw new Error("$transaction is not available");return await s.call(t.$transaction,o)}async execHelpersCall(e,t){let n=JSON.parse(e.argsJson),i=e.name.split("."),o=t?.$helpers;for(let s of i)o=o?.[s];if(typeof o!="function")throw new Error(`Helper not found: ${e.name}`);return o(...n)}async execSocketCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$socket?.[e.method];if(typeof i!="function")throw new Error(`Socket method not found: ${e.method}`);return i(...n)}async execCacheCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$cache?.[e.method];if(typeof i!="function")throw new Error(`Cache method not found: ${e.method}`);return i(...n)}async execStorageCall(e,t,n){let i=this.parseStorageArgs(e.argsJson,n,e.id),o=t?.$storage?.[e.method];if(typeof o!="function")throw new Error(`Storage method not found: ${e.method}`);return o(...i)}parseStorageArgs(e,t,n){return JSON.parse(e,(i,o)=>{if(o?.__fnRef&&typeof o.__fnRef=="string"){let s=o.__fnRef;return(...a)=>this.invokeRuntimeCallback(t,n,s,a)}return o})}invokeRuntimeCallback(e,t,n,i){let o=`rtcb_${++this.runtimeCallbackCounter}`;return new Promise((s,a)=>{let u=setTimeout(()=>{d(),a(new Error(`Runtime callback timed out: ${n}`))},3e4),c=l=>{if(!(l?.type!=="runtimeCallbackResult"||l.callId!==o)){if(d(),l.error){let f=new Error(String(l.error));try{let p=JSON.parse(String(l.error));p?.__userThrow&&(f.message=String(p.message??f.message),f.statusCode=p.statusCode,f.code=p.code??(Number.isInteger(p.statusCode)?`HTTP_${p.statusCode}`:void 0),f.errorCode=f.code,f.errorPath=p.errorPath,f.details=p.details,f.messages=p.messages)}catch{}a(f);return}s(l.value)}},d=()=>{clearTimeout(u),e.off("message",c)};e.on("message",c),e.postMessage({type:"invokeRuntimeCallback",id:t,callId:o,callbackId:n,argsJson:JSON.stringify(i)})})}async execDispatchCall(e,t){let n=JSON.parse(e.argsJson),i=t?.$trigger;if(typeof i!="function")throw new Error("$trigger is not available");return i(...n)}cancelTask(e){this.taskCancellers.get(e)?.()}async execResCall(e,t){if(e.method==="streamStart"){let s=JSON.parse(e.argsJson||"[]")[1]||{},a=t?.$res?.stream;if(typeof a!="function")throw new Error("Response method not found: stream");let u=new Rr.PassThrough,c={stream:u};this.responseStreams.set(e.id,c);let d=t?.$res;if(d&&typeof d.once=="function"){let f=()=>{d.writableEnded!==!0&&this.cancelTask(e.id)};d.once("close",f),c.closeCleanup=()=>{typeof d.off=="function"?d.off("close",f):typeof d.removeListener=="function"&&d.removeListener("close",f)}}let l=a.call(t.$res,u,s);return l&&typeof l.catch=="function"&&l.catch(()=>{}),!0}if(e.method==="streamChunk"){let o=this.responseStreams.get(e.id);if(!o)throw new Error(`Response stream not found: ${e.id}`);let s=Buffer.from(e.chunk||"","base64");return o.stream.write(s)||await new Promise((a,u)=>{let c=()=>{l(),a()},d=f=>{l(),u(f)},l=()=>{o.stream.off("drain",c),o.stream.off("error",d)};o.stream.once("drain",c),o.stream.once("error",d)}),!0}if(e.method==="streamEnd"){let o=this.responseStreams.get(e.id);return o&&(o.closeCleanup?.(),o.stream.end(),this.responseStreams.delete(e.id)),!0}if(e.method==="streamError"){let o=this.responseStreams.get(e.id);if(o){o.closeCleanup?.();let s=e.error?.message||"Response stream failed";o.stream.destroy(new Error(s)),this.responseStreams.delete(e.id)}return!0}let n=JSON.parse(e.argsJson||"[]"),i=t?.$res?.[e.method];if(typeof i!="function")throw new Error(`Response method not found: ${e.method}`);return i.apply(t.$res,n)}cleanupResponseStream(e,t){let n=this.responseStreams.get(e);n&&(this.responseStreams.delete(e),n.closeCleanup?.(),t?n.stream.destroy(t):n.stream.end())}toWorkerCodeBlock(e){return{code:e.code,sourceCode:e.sourceCode,scriptLanguage:e.scriptLanguage,scriptId:e.scriptId,type:e.type}}createWorkerTaskDiagnostics(e,t,n,i){let o=n?.$api?.request?.correlationId,s=Array.isArray(t.codeBlocks)?t.codeBlocks.map(a=>({type:a?.type==="preHook"||a?.type==="postHook"||a?.type==="handler"?a.type:"run",...a?.scriptId!==void 0&&a?.scriptId!==null?{scriptId:String(a.scriptId)}:{}})):[{type:"run"}];return{...typeof o=="string"&&o?{correlationId:o}:{},timeoutMs:i,isolateMemoryLimitMb:Number(t.memoryLimitMb||0),isolatePoolSize:Number(t.isolatePoolSize||0),tasksPerIsolate:Number(t.tasksPerIsolate||0),scriptBlocks:s}}async run(e,t,n,i={}){let o=Math.max(1,Math.trunc(Number(n)||3e4)),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),u=this.createSnapshot(t);J({event:"isolated_run_start",timeoutMs:o,codeLen:e?.length??0});let c;try{let d={code:e,sourceCode:i.sourceCode??e,pkgSources:a,snapshot:u,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize,tasksPerIsolate:this.isolationTuning.tasksPerIsolate};c=await this.spawnAndExecute("execute",d,t,o)}catch(d){let l=d;if(J({event:"isolated_run_error",message:l.message,code:l.code,isTimeout:!!l.isTimeout}),l.code==="ERR_EXECUTION_ABORTED"||l.isAbort)throw l;if(l.isTimeout||l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new ye(o,e,l.details);l.code&&l.details&&(l.details.executorCode=l.code);let f=l.statusCode??(typeof l.status=="number"?l.status:void 0);throw ve.createException(l.errorPath,f,l.message||"Unknown error",e,l.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),J({event:"isolated_run_ok"}),c.valueAbsent?void 0:c.value}async runBatch(e,t,n,i={}){let o=Math.max(1,Math.trunc(Number(n)||3e4)),s=await this.packageCacheService.getPackages(),a=this.packageCdnLoaderService.getPackageSources(s),u=this.createSnapshot(t);J({event:"isolated_batch_start",timeoutMs:o,blocks:e.length});let c;try{let l={codeBlocks:e.map(f=>this.toWorkerCodeBlock(f)),pkgSources:a,snapshot:u,timeoutMs:o,memoryLimitMb:this.isolationTuning.isolateMemoryLimitMb,isolatePoolSize:this.isolationTuning.isolatePoolSize,tasksPerIsolate:this.isolationTuning.tasksPerIsolate};c=await this.spawnAndExecute("executeBatch",l,t,o,i.signal)}catch(d){let l=d;if(J({event:"isolated_batch_error",message:l.message,code:l.code,isTimeout:!!l.isTimeout}),l.ctxChanges&&this.mergeCtxChanges(t,l.ctxChanges),l.code==="ERR_EXECUTION_ABORTED"||l.isAbort)throw l;if(l.isTimeout||l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT")throw new ye(o,"(batch execution)",l.details);l.code&&l.details&&(l.details.executorCode=l.code);let f=l.statusCode??(typeof l.status=="number"?l.status:void 0);throw ve.createException(l.errorPath,f,l.message||"Unknown error","(batch execution)",l.details||{})}return this.mergeCtxChanges(t,c.ctxChanges||{}),J({event:"isolated_batch_ok"}),{value:c.valueAbsent?void 0:c.value,shortCircuit:c.shortCircuit===!0}}recordTaskDuration(e){this.taskDurationsMs.push(e),this.taskDurationsMs.length>512&&this.taskDurationsMs.shift()}recordQueueWait(e){this.queueWaitDurationsMs.push(e),this.queueWaitDurationsMs.length>512&&this.queueWaitDurationsMs.shift()}percentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,s)=>o-s),i=Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1));return n[i]}getMetrics(){let e=this.pool.getMetrics(),t=this.taskDurationsMs,n=t.length===0?0:t.reduce((s,a)=>s+a,0)/t.length,i=this.queueWaitDurationsMs,o=i.length===0?0:i.reduce((s,a)=>s+a,0)/i.length;return{tuning:this.isolationTuning,pool:e,taskDoneTotal:this.taskDoneTotal,taskErrorTotal:this.taskErrorTotal,taskTimeoutTotal:this.taskTimeoutTotal,rotationsTotal:this.rotationsTotal,crashesTotal:this.crashesTotal,avgTaskMs:n,p95TaskMs:this.percentile(t,95),p99TaskMs:this.percentile(t,99),avgQueueWaitMs:o,p95QueueWaitMs:this.percentile(i,95),p99QueueWaitMs:this.percentile(i,99),maxHeapRatio:Math.max(0,...e.workers.map(s=>s.lastHeapRatio||0)),runnerRssBytes:e.workers.reduce((s,a)=>s+(a.lastRssBytes||0),0)}}};var Ie=de(require("typescript")),xt={oauth_config_definition:"",route_handler_definition:"logic",pre_hook_definition:"code",post_hook_definition:"code",bootstrap_script_definition:"logic",websocket_definition:"connectionHandlerScript",websocket_event_definition:"handlerScript"};function Hi(r){return ne.getLegacyField(r)}function Gi(r){return ne.isScriptTable(r)}function Yi(r){return ne.normalizeLanguage(r)}var nn=class{getLegacyField(e){return xt[e]}isScriptTable(e){return e in xt}normalizeLanguage(e){return e==="javascript"?"javascript":"typescript"}compileSource(e,t){if(e==null||e==="")return null;let n=String(e),o=this.normalizeLanguage(t)==="javascript"?n:this.transpileTypeScript(n);return this.assertExecutableJavaScript(o),o}isExecutableJavaScript(e){if(!e)return!1;try{return this.assertExecutableJavaScript(e),!0}catch{return!1}}normalizeRecord(e,t){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let n={...t},i=this.getLegacyField(e);return i&&(n.sourceCode===void 0||n.sourceCode===null||n.sourceCode==="")&&n[i]!==void 0&&(n.sourceCode=n[i]),n.scriptLanguage=this.normalizeLanguage(n.scriptLanguage),n.compiledCode=this.compileSource(n.sourceCode,n.scriptLanguage),i&&i in n&&delete n[i],n}normalizePatch(e,t,n){if(!this.isScriptTable(e)||!t||typeof t!="object")return t;let i=this.getLegacyField(e),o=Object.prototype.hasOwnProperty.call(t,"sourceCode")||(i?Object.prototype.hasOwnProperty.call(t,i):!1),s=Object.prototype.hasOwnProperty.call(t,"scriptLanguage");if(!o&&!s)return t;let a=o?t.sourceCode??(i?t[i]:void 0):n?.sourceCode??(i&&n?n[i]:void 0),u=s?t.scriptLanguage:n?.scriptLanguage,c={...t};return o&&(c.sourceCode=a??null),c.scriptLanguage=this.normalizeLanguage(u),c.compiledCode=this.compileSource(a,c.scriptLanguage),i&&i in c&&delete c[i],c}getExecutableScript(e){return this.resolveExecutableScript(e).code}resolveExecutableScript(e){if(!e||typeof e!="object")return{code:null,compiledCode:null,shouldPersistCompiledCode:!1};if(typeof e.sourceCode=="string"&&e.sourceCode!==""){let n=this.compileSource(e.sourceCode,e.scriptLanguage);return{code:n,compiledCode:n,shouldPersistCompiledCode:n!==e.compiledCode}}let t=Object.keys(xt).find(n=>xt[n]in e);if(t){let n=e[xt[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=Ie.default.transpileModule(e,{compilerOptions:{target:Ie.default.ScriptTarget.ES2022,module:Ie.default.ModuleKind.CommonJS,importsNotUsedAsValues:Ie.default.ImportsNotUsedAsValues.Remove,sourceMap:!1,inlineSourceMap:!1,inlineSources:!1},reportDiagnostics:!0}),n=t.diagnostics?.find(i=>i.category===Ie.default.DiagnosticCategory.Error);if(n)throw new Error(Ie.default.flattenDiagnosticMessageText(n.messageText,`
|
|
3
3
|
`));return t.outputText.trimEnd()}assertExecutableJavaScript(e){e&&new Function(`return (async () => {
|
|
4
4
|
"use strict";
|
|
5
5
|
${e}
|