@enfyra/kernel 1.1.33 → 1.1.35

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/LICENSE CHANGED
@@ -1 +1,55 @@
1
- SEE LICENSE IN LICENSE
1
+ Elastic License 2.0
2
+
3
+ URL: https://www.elastic.co/licensing/elastic-license
4
+
5
+ ## Acceptance
6
+
7
+ By using the software, you agree to all of the terms and conditions below.
8
+
9
+ ## Copyright License
10
+
11
+ The licensor grants you a non-exclusive, royalty-free, worldwide, non-sublicensable, non-transferable license to use, copy, distribute, make available, and prepare derivative works of the software, in each case subject to the limitations and conditions below.
12
+
13
+ ## Limitations
14
+
15
+ You may not provide the software to third parties as a hosted or managed service, where the service provides users with access to any substantial set of the features or functionality of the software.
16
+
17
+ You may not move, change, disable, or circumvent the license key functionality in the software, and you may not remove or obscure any functionality in the software that is protected by the license key.
18
+
19
+ You may not alter, remove, or obscure any licensing, copyright, or other notices of the licensor in the software. Any use of the licensor's trademarks is subject to applicable law.
20
+
21
+ ## Patents
22
+
23
+ The licensor grants you a license, under any patent claims the licensor can license, or becomes able to license, to make, have made, use, sell, offer for sale, import and have imported the software, in each case subject to the limitations and conditions in this license. This license does not cover any patent claims that you cause to be infringed by modifications or additions to the software. If you or your company make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
24
+
25
+ ## Notices
26
+
27
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms.
28
+
29
+ If you modify the software, you must include in any modified copies of the software prominent notices stating that you have modified the software.
30
+
31
+ ## No Other Rights
32
+
33
+ These terms do not imply any licenses other than those expressly granted in these terms.
34
+
35
+ ## Termination
36
+
37
+ If you use the software in violation of these terms, such use is not licensed, and your licenses will automatically terminate. If the licensor provides you with a notice of your violation, and you cease all violation of this license no later than 30 days after you receive that notice, your licenses will be reinstated retroactively. However, if you violate these terms after such reinstatement, any additional violation of these terms will cause your licenses to terminate automatically and permanently.
38
+
39
+ ## No Liability
40
+
41
+ *As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.*
42
+
43
+ ## Definitions
44
+
45
+ The **licensor** is the entity offering these terms, and the **software** is the software the licensor makes available under these terms, including any portion of it.
46
+
47
+ **you** refers to the individual or entity agreeing to these terms.
48
+
49
+ **your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
50
+
51
+ **your licenses** are all the licenses granted to you for the software under these terms.
52
+
53
+ **use** means anything you do with the software requiring one of your licenses.
54
+
55
+ **trademark** means trademarks, service marks, and similar rights.
@@ -1,4 +1,4 @@
1
- "use strict";var D=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var B=D((Fe,K)=>{"use strict";var{fork:ce}=require("child_process"),le=require("path");function ue({workerDir:e,activeTaskContexts:t}){let s=new Map,r=new Map,a=new Map,o=null,c=0;function g(f){return Math.max(1,Math.trunc(Number(f)||3e4))}function u(f){for(let n of r.values())clearTimeout(n.timer),n.reject(f);r.clear()}function y(f){let n=typeof f=="string"?JSON.parse(f):f;if(n?.error)throw new Error(n.error);return n?.value}async function P(f){let n=t.get(f.taskId);if(!n)throw new Error(`Package callback context not found: ${f.taskId}`);let i=JSON.stringify(f.callbackId),d=JSON.stringify(f.argsJson||"[]"),_=await n.evalClosure(`return __invokeRuntimeCallback(${i}, ${d});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}});return y(_)}function h(){if(o&&o.connected)return o;let f=le.join(e,"package-runtime.child.js"),n=ce(f,[],{stdio:["ignore","ignore","ignore","ipc"],env:{PATH:process.env.PATH||"",HOME:process.env.HOME||"",NODE_ENV:process.env.NODE_ENV||"production",TMPDIR:process.env.TMPDIR||"",LANG:process.env.LANG||""}});return o=n,n.on("message",i=>{if(!i||!i.id)return;if(i.type==="pkgStreamChunk"){let _=a.get(i.id);if(!_)return;_.onChunk(Buffer.from(i.chunk||"","base64")).then(()=>{try{n.send({type:"pkgStreamAck",ackId:i.ackId})}catch{}}).catch(v=>{try{n.send({type:"pkgStreamError",ackId:i.ackId,error:{message:v.message,stack:v.stack}})}catch{}});return}if(i.type==="pkgCallbackCall"){P(i).then(_=>{try{n.send({type:"pkgCallbackResult",id:i.id,value:_})}catch{}}).catch(_=>{try{n.send({type:"pkgCallbackError",id:i.id,error:{message:_.message,stack:_.stack}})}catch{}});return}let d=r.get(i.id);if(d)if(clearTimeout(d.timer),r.delete(i.id),a.delete(i.id),i.ok)d.resolve(i.value);else{let _=new Error(i.error?.message||"Package runtime call failed");_.stack=i.error?.stack||_.stack,d.reject(_)}}),n.on("exit",(i,d)=>{o===n&&(o=null),u(new Error(`Package runtime exited${d?` with signal ${d}`:` with code ${i}`}`))}),n.on("error",i=>{o===n&&(o=null),u(i)}),n}function l(f){return new Promise((n,i)=>{let d=h(),_=`pkg_${++c}`,v=g(f.timeoutMs),S=setTimeout(()=>{r.delete(_),a.delete(_);try{d.kill()}catch{}i(new Error(`Package runtime call timed out after ${v}ms`))},v);r.set(_,{resolve:n,reject:i,timer:S});try{d.send({...f,id:_},x=>{x&&(clearTimeout(S),r.delete(_),i(x))})}catch(x){clearTimeout(S),r.delete(_),i(x)}})}function m(f,n,i,d=[],_=3e4){return new Promise((v,S)=>{let x=h(),b=`pkg_${++c}`,F=g(_),U=setTimeout(()=>{r.delete(b),a.delete(b);try{x.kill()}catch{}S(new Error(`Package runtime stream timed out after ${F}ms`))},F);r.set(b,{resolve:v,reject:S,timer:U}),a.set(b,{onChunk:i});try{x.send({op:"streamHandle",taskId:f,handleId:n,path:d,id:b},H=>{H&&(clearTimeout(U),r.delete(b),a.delete(b),S(H))})}catch(H){clearTimeout(U),r.delete(b),a.delete(b),S(H)}})}function w(f){try{if(!o||!o.connected)return;o.send({...f,id:`pkg_${++c}`,fire:!0})}catch{}}async function k(f,n){let i=s.get(f);if(!i)throw new Error("Package context is not available");if(n.handleId)return l({op:n.kind==="get"?"handleGet":"handleCall",taskId:f,handleId:n.handleId,path:n.path||[],argsJson:n.argsJson||"[]",timeoutMs:n.timeoutMs});let d=i.get(n.packageName);if(!d)throw new Error(`Package "${n.packageName}" is not available`);return l({op:n.kind==="construct"?"construct":"call",taskId:f,packageName:n.packageName,package:{name:d.name,fileUrl:d.fileUrl},path:n.path||[],argsJson:n.argsJson||"[]",timeoutMs:n.timeoutMs})}function N(f,n){s.set(f,n)}function T(f){s.delete(f),w({op:"releaseTask",taskId:f})}function p(){if(o){try{o.kill()}catch{}o=null}}return{cleanupTaskPackages:T,executePackageRuntimeCall:k,setTaskPackages:N,streamPackageHandle:m,shutdownPackageRuntime:p}}K.exports={createPackageRuntimeBridge:ue}});var V=D((He,q)=>{"use strict";var fe=`
1
+ "use strict";var K=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var q=K((Fe,B)=>{"use strict";var{fork:le}=require("child_process"),ue=require("path");function fe({workerDir:e,activeTaskContexts:t}){let s=new Map,r=new Map,a=new Map,o=null,l=0;function g(f){return Math.max(1,Math.trunc(Number(f)||3e4))}function u(f){for(let n of r.values())clearTimeout(n.timer),n.reject(f);r.clear()}function d(f){let n=typeof f=="string"?JSON.parse(f):f;if(n?.error)throw new Error(n.error);return n?.value}async function v(f){let n=t.get(f.taskId);if(!n)throw new Error(`Package callback context not found: ${f.taskId}`);let i=JSON.stringify(f.callbackId),_=JSON.stringify(f.argsJson||"[]"),p=await n.evalClosure(`return __invokeRuntimeCallback(${i}, ${_});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}});return d(p)}function y(){if(o&&o.connected)return o;let f=ue.join(e,"package-runtime.child.js"),n=le(f,[],{stdio:["ignore","ignore","ignore","ipc"],env:{PATH:process.env.PATH||"",HOME:process.env.HOME||"",NODE_ENV:process.env.NODE_ENV||"production",TMPDIR:process.env.TMPDIR||"",LANG:process.env.LANG||""}});return o=n,n.on("message",i=>{if(!i||!i.id)return;if(i.type==="pkgStreamChunk"){let p=a.get(i.id);if(!p)return;p.onChunk(Buffer.from(i.chunk||"","base64")).then(()=>{try{n.send({type:"pkgStreamAck",ackId:i.ackId})}catch{}}).catch(P=>{try{n.send({type:"pkgStreamError",ackId:i.ackId,error:{message:P.message,stack:P.stack}})}catch{}});return}if(i.type==="pkgCallbackCall"){v(i).then(p=>{try{n.send({type:"pkgCallbackResult",id:i.id,value:p})}catch{}}).catch(p=>{try{n.send({type:"pkgCallbackError",id:i.id,error:{message:p.message,stack:p.stack}})}catch{}});return}let _=r.get(i.id);if(_)if(clearTimeout(_.timer),r.delete(i.id),a.delete(i.id),i.ok)_.resolve(i.value);else{let p=new Error(i.error?.message||"Package runtime call failed");p.stack=i.error?.stack||p.stack,_.reject(p)}}),n.on("exit",(i,_)=>{o===n&&(o=null),u(new Error(`Package runtime exited${_?` with signal ${_}`:` with code ${i}`}`))}),n.on("error",i=>{o===n&&(o=null),u(i)}),n}function c(f){return new Promise((n,i)=>{let _=y(),p=`pkg_${++l}`,P=g(f.timeoutMs),S=setTimeout(()=>{r.delete(p),a.delete(p);try{_.kill()}catch{}i(new Error(`Package runtime call timed out after ${P}ms`))},P);r.set(p,{resolve:n,reject:i,timer:S});try{_.send({...f,id:p},x=>{x&&(clearTimeout(S),r.delete(p),i(x))})}catch(x){clearTimeout(S),r.delete(p),i(x)}})}function m(f,n,i,_=[],p=3e4){return new Promise((P,S)=>{let x=y(),b=`pkg_${++l}`,F=g(p),L=setTimeout(()=>{r.delete(b),a.delete(b);try{x.kill()}catch{}S(new Error(`Package runtime stream timed out after ${F}ms`))},F);r.set(b,{resolve:P,reject:S,timer:L}),a.set(b,{onChunk:i});try{x.send({op:"streamHandle",taskId:f,handleId:n,path:_,id:b},U=>{U&&(clearTimeout(L),r.delete(b),a.delete(b),S(U))})}catch(U){clearTimeout(L),r.delete(b),a.delete(b),S(U)}})}function w(f){try{if(!o||!o.connected)return;o.send({...f,id:`pkg_${++l}`,fire:!0})}catch{}}async function k(f,n){let i=s.get(f);if(!i)throw new Error("Package context is not available");if(n.handleId)return c({op:n.kind==="get"?"handleGet":"handleCall",taskId:f,handleId:n.handleId,path:n.path||[],argsJson:n.argsJson||"[]",timeoutMs:n.timeoutMs});let _=i.get(n.packageName);if(!_)throw new Error(`Package "${n.packageName}" is not available`);return c({op:n.kind==="construct"?"construct":"call",taskId:f,packageName:n.packageName,package:{name:_.name,fileUrl:_.fileUrl},path:n.path||[],argsJson:n.argsJson||"[]",timeoutMs:n.timeoutMs})}function T(f,n){s.set(f,n)}function J(f){s.delete(f),w({op:"releaseTask",taskId:f})}function h(){if(o){try{o.kill()}catch{}o=null}}return{cleanupTaskPackages:J,executePackageRuntimeCall:k,setTaskPackages:T,streamPackageHandle:m,shutdownPackageRuntime:h}}B.exports={createPackageRuntimeBridge:fe}});var W=K((Ue,V)=>{"use strict";var de=`
2
2
  "use strict";
3
3
  let $ctx = {};
4
4
  let $pkgs = {};
@@ -500,9 +500,11 @@ function __createPkgHandleProxy(handlePromise, path) {
500
500
  };
501
501
  return new Proxy(fn, {
502
502
  get: (_, prop) => {
503
+ if (typeof prop === 'symbol') return undefined;
503
504
  if (prop === 'then') return undefined;
504
505
  if (prop === '__pkgHandle') return undefined;
505
506
  if (prop === '__pkgHandlePromise') return handlePromise;
507
+ if (prop === '__enfyraLocalReadable') return undefined;
506
508
  return __createAsyncPkgResultProxy(
507
509
  handlePromise.then((handleId) =>
508
510
  __call('pkgCall', __encodePkgCallPayload({
@@ -560,8 +562,20 @@ function __createAsyncPkgResultProxy(valuePromise, path) {
560
562
 
561
563
  return new Proxy(fn, {
562
564
  get: (_target, prop) => {
565
+ if (typeof prop === 'symbol') return undefined;
563
566
  if (prop === '__pkgHandle') return undefined;
564
- if (prop === '__pkgHandlePromise') return undefined;
567
+ if (prop === '__enfyraLocalReadable') return undefined;
568
+ if (prop === '__pkgHandlePromise') {
569
+ return promiseForPath().then((value) => {
570
+ if (value && typeof value === 'object' && value.__pkgHandle) {
571
+ return value.__pkgHandle;
572
+ }
573
+ if (typeof value === 'function' && value.__pkgHandlePromise) {
574
+ return value.__pkgHandlePromise;
575
+ }
576
+ return undefined;
577
+ });
578
+ }
565
579
  if (prop === 'then') {
566
580
  const promise = promiseForPath();
567
581
  return promise.then.bind(promise);
@@ -879,30 +893,30 @@ function __cleanupTask() {
879
893
  __pendingRuntimeTasks = [];
880
894
  return true;
881
895
  }
882
- `;function de(e){return fe.replace("%%PKG_SETUP%%",e)}q.exports={buildSetupCode:de}});var{parentPort:R}=require("worker_threads"),W=require("fs"),{fileURLToPath:_e}=require("url"),{createPackageRuntimeBridge:pe}=B(),{buildSetupCode:ge}=V(),j;try{j=require("isolated-vm")}catch(e){R.postMessage({type:"error",message:"isolated-vm not available: "+e.message}),process.exit(1)}var I=new Map,Q=0,O=new Map,E=pe({workerDir:__dirname,activeTaskContexts:O}),he=500,ye=5e3,me=32,z=new WeakMap,Y=new WeakMap,ee=new WeakMap,J={created:0,reused:0,released:0,evicted:0,scrubFailed:0},C=null,ke=0,G=0,X=0;async function we(){let e=Date.now();if(e-G<ye)return X;if(G=e,!C)return 0;let t=0;for(let s of C){let r=s?.isolate;if(!(!r||r.isDisposed))try{let a=await r.getHeapStatistics(),o=a.heap_size_limit||1,c=a.used_heap_size/o;c>t&&(t=c)}catch{}}return X=t,t}async function A(e){e.heapRatio=await we(),e.contextStats=ve(),R.postMessage(e)}function ve(){let e=0;if(C)for(let t of C)e+=t?.idleContexts?.length||0;return{...J,idle:e}}function te(e,t){if(!C){let a=Math.max(1,Math.trunc(Number(t)||8));C=new Array(a).fill(null)}let s=ke++%C.length,r=C[s];return(!r||!r.isolate||r.isolate.isDisposed)&&(r={isolate:new j.Isolate({memoryLimit:e}),idleContexts:[]},C[s]=r),r}async function $(e,t,s){let r=z.get(e);r||(r=new Map,z.set(e,r));let a=r.get(t);if(a)return a;let o=await e.compileScript(t,{filename:s});if(r.set(t,o),r.size>he){let c=r.keys().next().value;r.delete(c)}return o}R.on("message",async e=>{if(e.type==="execute")Oe(e).catch(async t=>{await A({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="executeBatch")Ee(e).catch(async t=>{await A({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="invokeRuntimeCallback")Pe(e).catch(t=>{R.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:t?.message||String(t)})});else if(e.type==="callResult"){let t=I.get(e.callId);t&&(I.delete(e.callId),t.resolve(e.result))}else if(e.type==="callError"){let t=I.get(e.callId);t&&(I.delete(e.callId),t.reject(new Error(e.error)))}});async function Pe(e){let t=O.get(e.id);if(!t){R.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:`Runtime callback context not found: ${e.id}`});return}let s=await t.evalClosure(`return __invokeRuntimeCallback(${JSON.stringify(e.callbackId)}, ${JSON.stringify(e.argsJson||"[]")});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}}),r=JSON.parse(s);R.postMessage({type:"runtimeCallbackResult",callId:e.callId,...r})}function M(e,t,s){return new Promise((r,a)=>{let o=`cb_${++Q}`;I.set(o,{resolve:r,reject:a}),R.postMessage({type:t,id:e,callId:o,...s})})}function be(e,t,s){R.postMessage({type:t,id:e,callId:`f_${++Q}`,...s})}async function Se(e,t){if(t?.method!=="stream")return M(e,"resCall",t);let s=JSON.parse(t.argsJson||"[]"),r=s[0],a=s[1]||{},o=r?.__pkgHandleArg;if(!o)return M(e,"resCall",t);await M(e,"resCall",{method:"streamStart",argsJson:JSON.stringify([null,a])});try{await E.streamPackageHandle(e,o,c=>M(e,"resCall",{method:"streamChunk",chunk:Buffer.from(c).toString("base64")})),await M(e,"resCall",{method:"streamEnd"})}catch(c){try{await M(e,"resCall",{method:"streamError",error:{message:c.message,stack:c.stack}})}catch{}throw c}return JSON.stringify({__e:"u"})}function xe(e){if(typeof e.sourceCode=="string"&&e.sourceCode.length>0)return e.sourceCode;let t=e.filePath;return!t&&typeof e.fileUrl=="string"&&e.fileUrl.startsWith("file://")&&(t=_e(e.fileUrl)),!t||!W.existsSync(t)?null:W.readFileSync(t,"utf8")}async function Ce(e,t,s){try{let r=xe(s);if(!r)return null;let a=await e.compileModule(r,{filename:`pkg:${s.safeName}`});await a.instantiate(t,c=>{throw new Error(`Unresolved import in package ${s.safeName}: ${c}`)}),await a.evaluate({timeout:1e4});let o=await a.namespace.get("default");return o!==void 0&&o.typeof!=="undefined"?o.derefInto({release:!1}):a.namespace.derefInto({release:!1})}catch{return null}}function re(e,t){let s=a=>{let o=2166136261;for(let c=0;c<a.length;c++)o^=a.charCodeAt(c),o=Math.imul(o,16777619);return(o>>>0).toString(36)},r=new Set(t||[]);return e.map(a=>{let o=a.cacheKey||`${a.filePath||""}:${a.fileUrl||""}:${a.mtimeMs||""}:${a.size||""}:${s(a.sourceCode||"")}`,c=r.has(a.name)?"isolate":"proxy";return`${a.name}:${a.version||""}:${o}:${c}`}).join("|")}function ne(e,t){let s=new Set(t.map(u=>u.name)),r=new Set,a=String(e||""),o=/\b(?:\$ctx\.)?\$pkgs\s*\[\s*(['"`])([^'"`]+)\1\s*\]/g,c=/\brequire\s*\(\s*(['"`])([^'"`]+)\1\s*\)/g,g=/\b(?:\$ctx\.)?\$pkgs\.([A-Za-z_$][\w$]*)/g;for(let u of[o,c])for(let y of a.matchAll(u)){let P=y[2];s.has(P)&&r.add(P)}for(let u of a.matchAll(g)){let y=u[1];s.has(y)&&r.add(y)}return r}async function $e(e,t,s,r){let a=await e.createContext(),o=a.global;await o.set("global",o.derefInto());let c=[],g=[],u=new Map;for(let l of s){u.set(l.name,l);let m=r.has(l.name)?await Ce(e,a,l):null;m!==null?(await o.set(`__pkg_${l.safeName}`,m),c.push(l)):g.push(l)}E.setTaskPackages(t,u),await o.set("__callRef",new j.Reference(async(l,m,w)=>{let k=JSON.parse(w);return m==="pkgCall"?JSON.stringify(await E.executePackageRuntimeCall(l,k)):m==="resCall"?Se(l,k):M(l,m,k)})),await o.set("__fireRef",new j.Reference((l,m,w)=>{let k=JSON.parse(w);be(l,m,k)}));let y=c.map(l=>`$pkgs[${JSON.stringify(l.name)}] = __pkg_${l.safeName};`).concat(g.map(l=>`$pkgs[${JSON.stringify(l.name)}] = __createPkgProxy(${JSON.stringify(l.name)}, []);`)).join(`
883
- `),P=ge(y);return await(await $(e,P,"setup.js")).run(a,{timeout:5e3}),Y.set(a,re(s,r)),ee.set(a,u),a}async function ae(e,t,s,r,a,o){let c=e.isolate,g=re(s,a),u=null;for(let h=e.idleContexts.length-1;h>=0;h--){let l=e.idleContexts[h];if(e.idleContexts.splice(h,1),Y.get(l)===g){u=l,J.reused++;break}try{l.release()}catch{}}u||(u=await $e(c,t,s,a),J.created++),E.setTaskPackages(t,ee.get(u)||new Map);let y=u.global;return await y.set("__snapshot",new j.ExternalCopy(r).copyInto()),await y.set("__nextTaskId",t),await y.set("__nextTaskTimeoutMs",o),await(await $(c,"__resetTask(__snapshot, __nextTaskId, __nextTaskTimeoutMs);","reset-task.js")).run(u,{timeout:5e3}),u}async function se(e,t){if(!(!t||e.isolate.isDisposed)){try{await(await $(e.isolate,"__cleanupTask();","cleanup-task.js")).run(t,{timeout:5e3})}catch{J.scrubFailed++;try{t.release()}catch{}return}if(e.idleContexts.length>=me){try{t.release()}catch{}J.evicted++;return}e.idleContexts.push(t),J.released++}}function Re(e){try{let t=JSON.parse(e.message);if(t&&t.__userThrow)return{...t,message:t.message??e.message}}catch{}return null}var Me=3,Ae=["setup.js","extract.js","extract-error-ctx.js","set-status.js","populate-error.js"];function Ne(e){if(!e)return null;let t=e.split(`
884
- `);for(let s of t){let r=s.match(/at\s+(.+\.js):(\d+):(\d+)/);if(!r)continue;let a=r[1].trim();if(Ae.includes(a))continue;let c=parseInt(r[2])-Me;if(!(c<=0))return{line:c,column:parseInt(r[3]),phase:a.replace(".js","")}}return null}function Te(e,t,s){if(!e||!t)return;let r=String(e).split(/\r?\n/),a=Math.max(1,t-1),o=Math.min(r.length,t+1),c=String(o).length,g=[];for(let u=a;u<=o;u++){let y=u===t?">":" ";g.push(`${y} ${String(u).padStart(c," ")}. ${r[u-1]??""}`),u===t&&s&&s>0&&g.push(` ${" ".repeat(c)} ${" ".repeat(Math.max(0,s-1))}^`)}return g.join(`
885
- `)}function Je(e,t){if(!(!e||!t)){if(t[e.phase])return t[e.phase];if(e.phase?.startsWith("preHook"))return t.preHook;if(e.phase?.startsWith("postHook"))return t.postHook}}function L(e,t){let s=Re(e);if(s)return{message:s.message,statusCode:s.statusCode,errorPath:s.errorPath,details:s.details};let r=Ne(e.stack),a=e.message||"Unknown error",o=r?`${a} (${r.phase}, line ${r.line})`:a,c=Je(r,t),g=r?Te(c,r.line,r.column):void 0;return{message:o,statusCode:e.statusCode||null,details:{errorName:e.name||null,...r?{...r,codeFrame:g}:{}}}}async function oe(e,t,s){let r=L(t,s);await A({type:"result",id:e,success:!1,error:{...r,stack:t.stack,code:t.code}})}async function Oe(e){let{id:t,code:s,pkgSources:r,snapshot:a,memoryLimitMb:o,isolatePoolSize:c}=e,g={handler:e.sourceCode||s||""},u=r||[],y=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),P=ne(s,u),h=te(o,c),l=h.isolate,m=await ae(h,t,u,a,P,y);O.set(t,m);try{let w=`
896
+ `;function _e(e){return de.replace("%%PKG_SETUP%%",e)}V.exports={buildSetupCode:_e}});var{parentPort:R}=require("worker_threads"),z=require("fs"),{fileURLToPath:pe}=require("url"),{createPackageRuntimeBridge:ge}=q(),{buildSetupCode:ye}=W(),j;try{j=require("isolated-vm")}catch(e){R.postMessage({type:"error",message:"isolated-vm not available: "+e.message}),process.exit(1)}var I=new Map,Y=0,A=new Map,H=new Map,E=ge({workerDir:__dirname,activeTaskContexts:A}),he=500,me=5e3,ke=32,G=new WeakMap,ee=new WeakMap,te=new WeakMap,O={created:0,reused:0,released:0,evicted:0,scrubFailed:0},C=null,ve=0,X=0,Z=0;async function we(){let e=Date.now();if(e-X<me)return Z;if(X=e,!C)return 0;let t=0;for(let s of C){let r=s?.isolate;if(!(!r||r.isDisposed))try{let a=await r.getHeapStatistics(),o=a.heap_size_limit||1,l=a.used_heap_size/o;l>t&&(t=l)}catch{}}return Z=t,t}async function N(e){e.heapRatio=await we(),e.contextStats=Pe(),R.postMessage(e)}function Pe(){let e=0;if(C)for(let t of C)e+=t?.idleContexts?.length||0;return{...O,idle:e}}function re(e,t){if(!C){let a=Math.max(1,Math.trunc(Number(t)||8));C=new Array(a).fill(null)}let s=ve++%C.length,r=C[s];return(!r||!r.isolate||r.isolate.isDisposed)&&(r={isolate:new j.Isolate({memoryLimit:e}),idleContexts:[]},C[s]=r),r}async function $(e,t,s){let r=G.get(e);r||(r=new Map,G.set(e,r));let a=r.get(t);if(a)return a;let o=await e.compileScript(t,{filename:s});if(r.set(t,o),r.size>he){let l=r.keys().next().value;r.delete(l)}return o}R.on("message",async e=>{if(e.type==="execute")Ee(e).catch(async t=>{await N({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="executeBatch")Ie(e).catch(async t=>{await N({type:"result",id:e.id,success:!1,error:{message:t.message,stack:t.stack}})});else if(e.type==="invokeRuntimeCallback")be(e).catch(t=>{R.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:t?.message||String(t)})});else if(e.type==="callResult"){let t=I.get(e.callId);t&&(I.delete(e.callId),t.resolve(e.result))}else if(e.type==="callError"){let t=I.get(e.callId);t&&(I.delete(e.callId),t.reject(new Error(e.error)))}});async function be(e){let t=A.get(e.id);if(!t){R.postMessage({type:"runtimeCallbackResult",callId:e.callId,error:`Runtime callback context not found: ${e.id}`});return}let s=await t.evalClosure(`return __invokeRuntimeCallback(${JSON.stringify(e.callbackId)}, ${JSON.stringify(e.argsJson||"[]")});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}}),r=JSON.parse(s);R.postMessage({type:"runtimeCallbackResult",callId:e.callId,...r})}function M(e,t,s){return new Promise((r,a)=>{let o=`cb_${++Y}`;I.set(o,{resolve:r,reject:a}),R.postMessage({type:t,id:e,callId:o,...s})})}function Se(e,t,s){R.postMessage({type:t,id:e,callId:`f_${++Y}`,...s})}async function xe(e,t){if(t?.method!=="stream")return M(e,"resCall",t);let s=JSON.parse(t.argsJson||"[]"),r=s[0],a=s[1]||{},o=r?.__pkgHandleArg;if(!o)return M(e,"resCall",t);let l=a.observer&&typeof a.observer=="object"?a.observer.__fnRef:null;delete a.observer;let g={...a};await M(e,"resCall",{method:"streamStart",argsJson:JSON.stringify([null,g])});let u=async(d,v)=>{if(!l)return;let y=A.get(e);if(!y)return;let c;try{c=Buffer.from(d).toString("utf8")}catch{c=""}try{await y.evalClosure(`return __invokeRuntimeCallback(${JSON.stringify(l)}, ${JSON.stringify(JSON.stringify([c,v]))});`,[],{arguments:{copy:!0},result:{promise:!0,copy:!0}})}catch{}};try{await E.streamPackageHandle(e,o,async d=>{await u(d,"chunk"),await M(e,"resCall",{method:"streamChunk",chunk:Buffer.from(d).toString("base64")})},[],Math.trunc(H.get(e)||3e4)),await M(e,"resCall",{method:"streamEnd"}),await u("","end")}catch(d){try{await M(e,"resCall",{method:"streamError",error:{message:d.message,stack:d.stack}})}catch{}throw await u("","error"),d}return JSON.stringify({__e:"u"})}function Ce(e){if(typeof e.sourceCode=="string"&&e.sourceCode.length>0)return e.sourceCode;let t=e.filePath;return!t&&typeof e.fileUrl=="string"&&e.fileUrl.startsWith("file://")&&(t=pe(e.fileUrl)),!t||!z.existsSync(t)?null:z.readFileSync(t,"utf8")}async function $e(e,t,s){try{let r=Ce(s);if(!r)return null;let a=await e.compileModule(r,{filename:`pkg:${s.safeName}`});await a.instantiate(t,l=>{throw new Error(`Unresolved import in package ${s.safeName}: ${l}`)}),await a.evaluate({timeout:1e4});let o=await a.namespace.get("default");return o!==void 0&&o.typeof!=="undefined"?o.derefInto({release:!1}):a.namespace.derefInto({release:!1})}catch{return null}}function ne(e,t){let s=a=>{let o=2166136261;for(let l=0;l<a.length;l++)o^=a.charCodeAt(l),o=Math.imul(o,16777619);return(o>>>0).toString(36)},r=new Set(t||[]);return e.map(a=>{let o=a.cacheKey||`${a.filePath||""}:${a.fileUrl||""}:${a.mtimeMs||""}:${a.size||""}:${s(a.sourceCode||"")}`,l=r.has(a.name)?"isolate":"proxy";return`${a.name}:${a.version||""}:${o}:${l}`}).join("|")}function ae(e,t){let s=new Set(t.map(u=>u.name)),r=new Set,a=String(e||""),o=/\b(?:\$ctx\.)?\$pkgs\s*\[\s*(['"`])([^'"`]+)\1\s*\]/g,l=/\brequire\s*\(\s*(['"`])([^'"`]+)\1\s*\)/g,g=/\b(?:\$ctx\.)?\$pkgs\.([A-Za-z_$][\w$]*)/g;for(let u of[o,l])for(let d of a.matchAll(u)){let v=d[2];s.has(v)&&r.add(v)}for(let u of a.matchAll(g)){let d=u[1];s.has(d)&&r.add(d)}return r}async function Re(e,t,s,r){let a=await e.createContext(),o=a.global;await o.set("global",o.derefInto());let l=[],g=[],u=new Map;for(let c of s){u.set(c.name,c);let m=r.has(c.name)?await $e(e,a,c):null;m!==null?(await o.set(`__pkg_${c.safeName}`,m),l.push(c)):g.push(c)}E.setTaskPackages(t,u),await o.set("__callRef",new j.Reference(async(c,m,w)=>{let k=JSON.parse(w);return m==="pkgCall"?JSON.stringify(await E.executePackageRuntimeCall(c,k)):m==="resCall"?xe(c,k):M(c,m,k)})),await o.set("__fireRef",new j.Reference((c,m,w)=>{let k=JSON.parse(w);Se(c,m,k)}));let d=l.map(c=>`$pkgs[${JSON.stringify(c.name)}] = __pkg_${c.safeName};`).concat(g.map(c=>`$pkgs[${JSON.stringify(c.name)}] = __createPkgProxy(${JSON.stringify(c.name)}, []);`)).join(`
897
+ `),v=ye(d);return await(await $(e,v,"setup.js")).run(a,{timeout:5e3}),ee.set(a,ne(s,r)),te.set(a,u),a}async function se(e,t,s,r,a,o){let l=e.isolate,g=ne(s,a),u=null;for(let y=e.idleContexts.length-1;y>=0;y--){let c=e.idleContexts[y];if(e.idleContexts.splice(y,1),ee.get(c)===g){u=c,O.reused++;break}try{c.release()}catch{}}u||(u=await Re(l,t,s,a),O.created++),E.setTaskPackages(t,te.get(u)||new Map);let d=u.global;return await d.set("__snapshot",new j.ExternalCopy(r).copyInto()),await d.set("__nextTaskId",t),await d.set("__nextTaskTimeoutMs",o),await(await $(l,"__resetTask(__snapshot, __nextTaskId, __nextTaskTimeoutMs);","reset-task.js")).run(u,{timeout:5e3}),u}async function oe(e,t){if(!(!t||e.isolate.isDisposed)){try{await(await $(e.isolate,"__cleanupTask();","cleanup-task.js")).run(t,{timeout:5e3})}catch{O.scrubFailed++;try{t.release()}catch{}return}if(e.idleContexts.length>=ke){try{t.release()}catch{}O.evicted++;return}e.idleContexts.push(t),O.released++}}function Me(e){try{let t=JSON.parse(e.message);if(t&&t.__userThrow)return{...t,message:t.message??e.message}}catch{}return null}var Ne=3,Ae=["setup.js","extract.js","extract-error-ctx.js","set-status.js","populate-error.js"];function Te(e){if(!e)return null;let t=e.split(`
898
+ `);for(let s of t){let r=s.match(/at\s+(.+\.js):(\d+):(\d+)/);if(!r)continue;let a=r[1].trim();if(Ae.includes(a))continue;let l=parseInt(r[2])-Ne;if(!(l<=0))return{line:l,column:parseInt(r[3]),phase:a.replace(".js","")}}return null}function Je(e,t,s){if(!e||!t)return;let r=String(e).split(/\r?\n/),a=Math.max(1,t-1),o=Math.min(r.length,t+1),l=String(o).length,g=[];for(let u=a;u<=o;u++){let d=u===t?">":" ";g.push(`${d} ${String(u).padStart(l," ")}. ${r[u-1]??""}`),u===t&&s&&s>0&&g.push(` ${" ".repeat(l)} ${" ".repeat(Math.max(0,s-1))}^`)}return g.join(`
899
+ `)}function Oe(e,t){if(!(!e||!t)){if(t[e.phase])return t[e.phase];if(e.phase?.startsWith("preHook"))return t.preHook;if(e.phase?.startsWith("postHook"))return t.postHook}}function D(e,t){let s=Me(e);if(s)return{message:s.message,statusCode:s.statusCode,errorPath:s.errorPath,details:s.details};let r=Te(e.stack),a=e.message||"Unknown error",o=r?`${a} (${r.phase}, line ${r.line})`:a,l=Oe(r,t),g=r?Je(l,r.line,r.column):void 0;return{message:o,statusCode:e.statusCode||null,details:{errorName:e.name||null,...r?{...r,codeFrame:g}:{}}}}async function ie(e,t,s){let r=D(t,s);await N({type:"result",id:e,success:!1,error:{...r,stack:t.stack,code:t.code}})}async function Ee(e){let{id:t,code:s,pkgSources:r,snapshot:a,memoryLimitMb:o,isolatePoolSize:l}=e,g={handler:e.sourceCode||s||""},u=r||[],d=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),v=ae(s,u),y=re(o,l),c=y.isolate,m=await se(y,t,u,a,v,d);A.set(t,m),H.set(t,d);try{let w=`
886
900
  (async () => {
887
901
  "use strict";
888
902
  ${s}
889
903
  })().then((__result) => __extractResult(__result, __result === undefined));
890
- `,N=await(await $(l,w,"handler.js")).run(m,{timeout:y,promise:!0}),T=JSON.parse(N);await A({type:"result",id:t,success:!0,...T})}catch(w){await oe(t,w,g)}finally{O.delete(t),await se(h,m),ie(t)}}async function Ee(e){let{id:t,codeBlocks:s,pkgSources:r,snapshot:a,memoryLimitMb:o,isolatePoolSize:c}=e,g=r||[],u=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),y=ne((s||[]).map(p=>p.code||"").join(`
891
- `),g),P=te(o,c),h=P.isolate,l=await ae(P,t,g,a,y,u);O.set(t,l);let m=[],w=[],k={},N=0,T=0;for(let p of s){let f=p.type||"handler",n=p.sourceCode||p.code||"";f==="postHook"?(T++,k[`postHook #${T}`]=n,k.postHook=n,w.push(p)):(f==="handler"?k.handler=n:(N++,k[`${f} #${N}`]=n,k.preHook=n),m.push(p))}try{let p=null;for(let n=0;n<m.length;n++){let i=m[n],d=i.type||"handler",_=d==="handler"?"handler":`${d} #${n+1}`,v;d==="preHook"?v=`
904
+ `,T=await(await $(c,w,"handler.js")).run(m,{timeout:d,promise:!0}),J=JSON.parse(T);await N({type:"result",id:t,success:!0,...J})}catch(w){await ie(t,w,g)}finally{A.delete(t),H.delete(t),await oe(y,m),ce(t)}}async function Ie(e){let{id:t,codeBlocks:s,pkgSources:r,snapshot:a,memoryLimitMb:o,isolatePoolSize:l}=e,g=r||[],u=Math.max(1,Math.trunc(Number(e.timeoutMs)||3e4)),d=ae((s||[]).map(h=>h.code||"").join(`
905
+ `),g),v=re(o,l),y=v.isolate,c=await se(v,t,g,a,d,u);A.set(t,c),H.set(t,u);let m=[],w=[],k={},T=0,J=0;for(let h of s){let f=h.type||"handler",n=h.sourceCode||h.code||"";f==="postHook"?(J++,k[`postHook #${J}`]=n,k.postHook=n,w.push(h)):(f==="handler"?k.handler=n:(T++,k[`${f} #${T}`]=n,k.preHook=n),m.push(h))}try{let h=null;for(let n=0;n<m.length;n++){let i=m[n],_=i.type||"handler",p=_==="handler"?"handler":`${_} #${n+1}`,P;_==="preHook"?P=`
892
906
  (async () => {
893
907
  "use strict";
894
908
  ${i.code}
895
909
  })().then((__r) => {
896
910
  if (__r !== undefined) return JSON.stringify({ __shortCircuit: true, value: __r });
897
911
  return JSON.stringify({ __shortCircuit: false });
898
- });`:v=`
912
+ });`:P=`
899
913
  (async () => {
900
914
  "use strict";
901
915
  ${i.code}
902
916
  })().then((__r) => {
903
917
  $ctx.$data = __r;
904
918
  return "__handler_done__";
905
- });`;try{let x=await(await $(h,v,`${_}.js`)).run(l,{timeout:u,promise:!0});if(d==="preHook"&&typeof x=="string"){let b=JSON.parse(x);if(b.__shortCircuit){let F=await Z(h,l,b.value);await A({type:"result",id:t,success:!0,...F,shortCircuit:!0});return}}}catch(S){p=S;break}}if(!p&&w.length>0&&await(await $(h,'$ctx.$statusCode = 200; "__status_set__";',"set-status.js")).run(l,{timeout:5e3}),p&&w.length>0){let n=L(p,k),i={message:n.message||"Unknown error",name:p.constructor?.name||"Error",stack:p.stack||"",statusCode:n.statusCode||500,details:n.details||{},timestamp:new Date().toISOString()},d=`
919
+ });`;try{let x=await(await $(y,P,`${p}.js`)).run(c,{timeout:u,promise:!0});if(_==="preHook"&&typeof x=="string"){let b=JSON.parse(x);if(b.__shortCircuit){let F=await Q(y,c,b.value);await N({type:"result",id:t,success:!0,...F,shortCircuit:!0});return}}}catch(S){h=S;break}}if(!h&&w.length>0&&await(await $(y,'$ctx.$statusCode = 200; "__status_set__";',"set-status.js")).run(c,{timeout:5e3}),h&&w.length>0){let n=D(h,k),i={message:n.message||"Unknown error",name:h.constructor?.name||"Error",stack:h.stack||"",statusCode:n.statusCode||500,details:n.details||{},timestamp:new Date().toISOString()},_=`
906
920
  $ctx.$error = ${JSON.stringify(i)};
907
921
  $ctx.$data = null;
908
922
  $ctx.$statusCode = ${i.statusCode};
@@ -916,11 +930,11 @@ if ($ctx.$api) {
916
930
  timestamp: ${JSON.stringify(i.timestamp)},
917
931
  };
918
932
  }
919
- "__error_populated__";`;await(await h.compileScript(d,{filename:"populate-error.js"})).run(l,{timeout:5e3})}for(let n=0;n<w.length;n++){let i=w[n],d=`postHook #${n+1}`,_=`
933
+ "__error_populated__";`;await(await y.compileScript(_,{filename:"populate-error.js"})).run(c,{timeout:5e3})}for(let n=0;n<w.length;n++){let i=w[n],_=`postHook #${n+1}`,p=`
920
934
  (async () => {
921
935
  "use strict";
922
936
  ${i.code}
923
937
  })().then((__r) => {
924
938
  if (__r !== undefined) $ctx.$data = __r;
925
939
  return "__posthook_done__";
926
- });`;try{await(await $(h,_,`${d}.js`)).run(l,{timeout:u,promise:!0})}catch{}}if(p){let n=L(p,k),i;try{let v=await(await $(h,"(async () => JSON.stringify(await __extractCtxChanges()))()","extract-error-ctx.js")).run(l,{timeout:5e3,promise:!0});i=JSON.parse(v)}catch{}await A({type:"result",id:t,success:!1,error:{message:n.message,statusCode:n.statusCode,errorPath:n.errorPath,stack:p.stack,code:p.code,details:n.details},ctxChanges:i});return}let f=await Z(h,l);await A({type:"result",id:t,success:!0,...f})}catch(p){await oe(t,p)}finally{O.delete(t),await se(P,l),ie(t)}}function ie(e){E.cleanupTaskPackages(e)}function Ie(){E.shutdownPackageRuntime()}process.on("exit",Ie);async function Z(e,t,s){if(s!==void 0){let c=`__extractResult(${JSON.stringify(s)}, false)`,u=await(await e.compileScript(c,{filename:"extract.js"})).run(t,{timeout:5e3,promise:!0});return JSON.parse(u)}let o=await(await $(e,"__extractResult($ctx.$data, $ctx.$data === undefined)","extract.js")).run(t,{timeout:5e3,promise:!0});return JSON.parse(o)}
940
+ });`;try{await(await $(y,p,`${_}.js`)).run(c,{timeout:u,promise:!0})}catch{}}if(h){let n=D(h,k),i;try{let P=await(await $(y,"(async () => JSON.stringify(await __extractCtxChanges()))()","extract-error-ctx.js")).run(c,{timeout:5e3,promise:!0});i=JSON.parse(P)}catch{}await N({type:"result",id:t,success:!1,error:{message:n.message,statusCode:n.statusCode,errorPath:n.errorPath,stack:h.stack,code:h.code,details:n.details},ctxChanges:i});return}let f=await Q(y,c);await N({type:"result",id:t,success:!0,...f})}catch(h){await ie(t,h)}finally{A.delete(t),H.delete(t),await oe(v,c),ce(t)}}function ce(e){E.cleanupTaskPackages(e)}function je(){E.shutdownPackageRuntime()}process.on("exit",je);async function Q(e,t,s){if(s!==void 0){let l=`__extractResult(${JSON.stringify(s)}, false)`,u=await(await e.compileScript(l,{filename:"extract.js"})).run(t,{timeout:5e3,promise:!0});return JSON.parse(u)}let o=await(await $(e,"__extractResult($ctx.$data, $ctx.$data === undefined)","extract.js")).run(t,{timeout:5e3,promise:!0});return JSON.parse(o)}
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "@enfyra/kernel",
3
- "version": "1.1.32",
3
+ "version": "1.1.34",
4
4
  "source": "bundled-compiled-kernel"
5
5
  }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@enfyra/kernel",
3
- "version": "1.1.33",
3
+ "version": "1.1.35",
4
4
  "description": "Closed-distribution Enfyra kernel runtime",
5
- "license": "SEE LICENSE IN LICENSE",
5
+ "license": "Elastic-2.0",
6
6
  "packageManager": "yarn@4.17.0",
7
7
  "main": "./dist/index.js",
8
8
  "types": "./dist/index.d.ts",