@blue-labs/document-processor 1.33.2 → 1.33.3

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 CHANGED
@@ -1,9 +1,9 @@
1
- "use strict";var be=Object.defineProperty;var Te=(a,e,t)=>e in a?be(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var l=(a,e,t)=>Te(a,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("@blue-repository/core-dev"),m=require("@blue-labs/language"),E=require("@blue-labs/shared-utils"),C=require("@blue-repository/myos-dev"),P=(...a)=>a.map((e,t)=>{if(typeof e!="string")return"";if(t===0&&e==="/")return"/";const n=t>0?e.replace(/^\/+/,""):e;return t<a.length-1?n.replace(/\/+$/,""):n}).filter(Boolean).join("/").replace(/\/{2,}/g,"/");class Z{constructor(e,t,n,o){l(this,"actions",[]);this.getDocument=e,this.taskInfo=t,this.blue=n,this.onFlush=o}get(e){const t=this.getDocument(),n=P(this.taskInfo.nodePath,e);return t.get(n)}addPatch(e){this.actions.push({kind:"patch",patch:{...e,path:P(this.taskInfo.nodePath,e.path)}})}emitEvent(e){const t=this.taskInfo.event,n=t.trace??[],o={...e,source:e.source??"internal",originNodePath:e.originNodePath??this.taskInfo.nodePath,rootEvent:e.rootEvent??t.rootEvent??t,trace:[...n],emissionType:e.emissionType??t.emissionType};this.actions.push({kind:"event",event:o})}async flush(){var t;if(!this.actions.length)return[];const e=[...this.actions];return this.actions.length=0,await((t=this.onFlush)==null?void 0:t.call(this,e)),e}getNodePath(){return this.taskInfo.nodePath}resolvePath(e){return P(this.taskInfo.nodePath,e)}getTaskInfo(){return this.taskInfo}getBlue(){return this.blue}loadExternalModule(){throw new Error("Not implemented")}loadBlueContent(e){const t=this.blue.getNodeProvider().fetchFirstByBlueId(e);if(!t)throw new Error(`Blue node not found for blueId: ${e}`);return Promise.resolve(JSON.stringify(this.blue.nodeToJson(t)))}}class W extends Error{constructor(e,t){super(`Cannot apply patch ${JSON.stringify(e)}`),this.patch=e,this.cause=t,this.name="PatchApplicationError"}}class J extends Error{constructor(e,t,n){super(`Patch ${JSON.stringify(e)} touches "${e.op==="move"||e.op==="copy"?`${e.from} → ${e.path}`:e.path}" which is inside embedded document "${t}" (Process Embedded @ "${n}")`),this.patch=e,this.offendingPath=t,this.contractNodePath=n,this.name="EmbeddedDocumentModificationError"}}class j extends Error{constructor(e,t){super(`Failed to evaluate expression "${e}"`),this.code=e,this.cause=t,this.name="ExpressionEvaluationError"}}class x extends Error{constructor(e,t){super(`Failed to evaluate code block "${e}"`),this.code=e,this.cause=t,this.name="CodeBlockEvaluationError"}}function B(a){return E.deepFreeze(a)}function M(a){return a.clone()}function D(a,e,t="/",n=[]){const o=a.getContracts()??{};for(const[r,s]of Object.entries(o))if(e.isTypeOf(s,h.ProcessEmbeddedSchema)){const d=e.nodeToSchemaOutput(s,h.ProcessEmbeddedSchema).paths??[];for(const u of d)n.push({absPath:P(t,u),contractPath:P(t,`contracts/${r}`)})}for(const[r,s]of Object.entries(a.getProperties()??{}))D(s,e,P(t,r),n);return n}function z(a,e){return a===e||a.startsWith(e.endsWith("/")?e:e+"/")}function R(a,e){if(!e.length)return a;let t=M(a);for(const n of e)try{t=m.applyBlueNodePatch(t,n,!0)}catch(o){throw new W(n,o)}return B(t)}function v(a){return a!=null}function N(a){return a instanceof m.BlueNode}class Se{constructor(e=[],t=(n,o)=>n<o?-1:n>o?1:0){l(this,"data");l(this,"length");l(this,"compare");if(this.data=e,this.length=this.data.length,this.compare=t,this.length>0)for(let n=(this.length>>1)-1;n>=0;n--)this._down(n)}push(e){this.data.push(e),this._up(this.length++)}pop(){if(this.length===0)return;const e=this.data[0],t=this.data.pop();return--this.length>0&&(this.data[0]=t,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:t,compare:n}=this,o=t[e];for(;e>0;){const r=e-1>>1,s=t[r];if(n(o,s)>=0)break;t[e]=s,e=r}t[e]=o}_down(e){const{data:t,compare:n}=this,o=this.length>>1,r=t[e];for(;e<o;){let s=(e<<1)+1;const i=s+1;if(i<this.length&&n(t[i],t[s])<0&&(s=i),n(t[s],r)>=0)break;t[e]=t[s],e=s}t[e]=r}}const Pe=(a,e,t,n,o,r)=>[-a,e,t,n,o,r],Ce=(a,e)=>{for(let t=0;t<a.key.length;t++){const n=a.key[t],o=e.key[t];if(n!==o)return typeof n=="number"&&typeof o=="number"?n-o:typeof n=="string"&&typeof o=="string"?n.localeCompare(o):0}return 0};class Ne{constructor(){l(this,"queue");this.queue=new Se([],Ce)}push(e){this.queue.push(e)}pop(){return this.queue.pop()}get length(){return this.queue.length}}class ke{constructor(e=[]){l(this,"processors",new Map);l(this,"typeOrder",new Map);e.forEach((t,n)=>this.register(t,n))}register(e,t){if(this.processors.has(e.contractBlueId))throw new Error(`Processor for ${e.contractType} already registered`);this.processors.set(e.contractBlueId,e),this.typeOrder.has(e.contractBlueId)||this.typeOrder.set(e.contractBlueId,t??this.typeOrder.size)}get(e){if(!e)return;const t=e.getBlueId();if(t)return this.processors.get(t)}orderOf(e){if(!e)return 0;const t=e.getBlueId();return t?this.typeOrder.get(t)??0:0}values(){return this.processors.values()}}const O=class O{constructor(){l(this,"isEnabled");this.isEnabled=process.env.TRACE_BLUE_ENABLED!=="false"}makeHop(e,t){return`${e}#${t}`}shouldTrace(){return this.isEnabled}addHop(e,t,n){if(!this.shouldTrace())return{...e};const o=e.trace??[],s=[...o.length>=O.MAX_TRACE_LENGTH?o.slice(o.length-(O.MAX_TRACE_LENGTH-1)):o,this.makeHop(t,n)];return{...e,trace:s}}getTrace(e){return e.trace??[]}clearTrace(e){return{...e,trace:[]}}isTracingEnabled(){return this.isEnabled}};l(O,"MAX_TRACE_LENGTH",128);let V=O;function Ie(a){return Object.entries(a.getContracts()??{})}const Be=64;class Oe{constructor(e,t,n,o,r){l(this,"traceManager");this.blue=e,this.registry=t,this.queue=n,this.getNextTaskId=o,this.getNextEventSeq=r,this.traceManager=new V}async route(e,t,n,o,r=0){var c;if(n.seq===void 0&&(n.seq=this.getNextEventSeq()),t.length===0){if(n.dispatchPath){const d=n.dispatchPath.split("/").filter(Boolean),u={...n};return delete u.dispatchPath,this.route(e,d,u,o,r)}if(n.source==="channel"&&n.originNodePath&&n.originNodePath!=="/"){const d=((c=n.originNodePath)==null?void 0:c.split("/").filter(Boolean))??[];return this.route(e,d,n,o,r)}}const s=P("/",t.join("/")),i=e.get(s);N(i)&&await this.traverseContracts({doc:e,node:i,nodePath:s,event:n,afterTaskId:o,pathSegments:t,inlineDepth:r})}async traverseContracts(e){const{doc:t,node:n,nodePath:o,event:r,afterTaskId:s,pathSegments:i,inlineDepth:c}=e;if(!this.shouldSkipForChannel(r,o))for(const[d,u]of Ie(n)){if(!u.getType())continue;const p=this.registry.get(u.getType());if(!p){console.warn(`No processor registered for contract: ${d}`);continue}const f={nodePath:o,contractName:d,contractNode:u,event:r},g=new Z(()=>t,f,this.blue);if(p.supports(r,u,g,d))switch(p.role){case"adapter":await this.processAdapter({cp:p,event:r,contractNode:u,ctx:g,contractName:d,doc:t,afterTaskId:s,inlineDepth:c});break;case"handler":this.scheduleHandler({contractNode:u,contractName:d,nodePath:o,event:r,depth:i.length,afterTaskId:s});break}}}async processAdapter(e){var T;const{cp:t,event:n,contractNode:o,ctx:r,contractName:s,doc:i,afterTaskId:c,inlineDepth:d}=e;if(d>=Be)throw new Error("Adapter recursion limit reached");const u=this.traceManager.addHop(n,((T=r.getTaskInfo())==null?void 0:T.nodePath)??"",s);await t.handle(u,o,r,s);const p=await r.flush();if(p.find(w=>w.kind==="patch"))throw new Error(`Contract "${s}" (adapter) attempted to patch the document`);const g=p.filter(w=>w.kind==="event");for(const w of g)await this.route(i,[],w.event,c,d+1)}scheduleHandler(e){const{contractNode:t,contractName:n,nodePath:o,event:r,depth:s,afterTaskId:i}=e,c=t.getType();if(!c){console.warn(`Contract node type is not defined for: ${n}`);return}const d=this.registry.orderOf(c),u=t.get("/order"),p=m.isBigNumber(u)?u.toNumber():0,f=this.getNextTaskId()+i,g=r.seq;if(g===void 0)throw new Error("Event sequence missing");const T=Pe(s,g,d,p,n,f);{const y=`${o}#${n}`,A=r.trace??[];if(r.source!=="external"&&A.includes(y))throw new Error(`Loop detected: repeated hop ${y} within the same event chain`)}const w=this.traceManager.addHop(r,o,n);this.queue.push({key:T,nodePath:o,contractName:n,contractNode:t,event:w})}shouldSkipForChannel(e,t){return e.source==="channel"&&!!e.originNodePath&&e.originNodePath!==t}}const Me=(a,e,t)=>{(t instanceof W||t instanceof J)&&console.error(`[Blue] Failed to apply patches for contract "${a}" on event ${JSON.stringify(e)}`,t)};function H(a,e){const t=M(a),n=o=>{if(!N(o))return;const r=o.getContracts();(!(r!=null&&r.checkpoint)||!m.BlueNodeTypeSchema.isTypeOf(r.checkpoint,h.ChannelEventCheckpointSchema))&&o.addContract("checkpoint",e.jsonValueToNode({type:{name:"Channel Event Checkpoint",blueId:h.blueIds["Channel Event Checkpoint"]},lastEvents:{}}))};n(t);for(const{absPath:o}of D(t,e)){const r=t.get(o);N(r)&&n(r)}return B(t)}function $e(a,e){const t=M(a);return N(t)&&(ee(t,e)||t.addContract("initialized",e.jsonValueToNode({type:{name:"Initialized Marker",blueId:h.blueIds["Initialized Marker"]}}))),B(t)}function ee(a,e){const t=a.getContracts();return Object.values(t??{}).some(n=>e.isTypeOf(n,h.InitializedMarkerSchema,{checkSchemaExtensions:!0}))}class te{constructor(e){l(this,"contractType","Channel Event Checkpoint");l(this,"contractBlueId",h.blueIds["Channel Event Checkpoint"]);l(this,"role","handler");this.cache=e}supports(e){var t,n;return e.source==="channel"&&((t=e.rootEvent)==null?void 0:t.payload)===e.payload&&((n=e.rootEvent)==null?void 0:n.source)==="external"}async getEventBlueId(e,t){var o;const n=(o=e.rootEvent)==null?void 0:o.payload;if(!n)throw new Error("Cannot calculate blueId for checkpoint: missing root event payload");if(n instanceof m.ResolvedBlueNode){const r=n.getMinimalNode();return await t.getBlue().calculateBlueId(r)}return await t.getBlue().calculateBlueId(n)}async handle(e,t,n){var s;if(!e.channelName||!((s=e.rootEvent)!=null&&s.seq))return;const o=await this.getEventBlueId(e,n),r=n.getNodePath().replace(/\/contracts\/checkpoint$/,"");this.cache.record(r,e,o)}}const X=(a,e)=>a.get(e)!==void 0;class qe{constructor(){l(this,"firstSeen",new Map)}record(e,t,n){const o=e;this.firstSeen.has(o)||this.firstSeen.set(o,{docBase:e,event:t,eventBlueId:n})}flush(e){const t=[];for(const{docBase:n,event:o,eventBlueId:r}of this.firstSeen.values()){if(!o.channelName)continue;const s=P(n,"contracts/checkpoint/lastEvents",o.channelName),i=`${s}/blueId`;X(e,s)?t.push({op:X(e,i)?"replace":"add",path:i,val:r}):t.push({op:"add",path:s,val:{blueId:r}})}return t}clear(){this.firstSeen.clear()}}class ne{constructor(){l(this,"contractType","Composite Timeline Channel");l(this,"contractBlueId",h.blueIds["Composite Timeline Channel"]);l(this,"role","adapter")}supports(e,t,n){const o=n.getBlue().nodeToSchemaOutput(t,h.CompositeTimelineChannelSchema);return!o.channels||!e.channelName?!1:o.channels.includes(e.channelName)}handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}}class k{constructor(){l(this,"role","adapter")}baseSupports(e){return e.source!=="channel"}}class oe extends k{constructor(){super(...arguments);l(this,"contractType","Document Update Channel");l(this,"contractBlueId",h.blueIds["Document Update Channel"])}supports(t,n,o){if(!this.baseSupports(t)||t.emissionType!=="update")return!1;const r=o.getBlue().nodeToSchemaOutput(n,h.DocumentUpdateChannelSchema),s=t.payload.get("/path");if(!s)return!1;const i=r.path;return E.isNonNullable(i)&&s===o.resolvePath(i)}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class re extends k{constructor(){super(...arguments);l(this,"contractType","Embedded Node Channel");l(this,"contractBlueId",h.blueIds["Embedded Node Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;const r=o.getBlue().nodeToSchemaOutput(n,h.EmbeddedNodeChannelSchema);return v(t.originNodePath)&&v(r.path)&&t.originNodePath===o.resolvePath(r.path)}handle(t,n,o,r){const s=o.getBlue().nodeToSchemaOutput(n,h.EmbeddedNodeChannelSchema),{originNodePath:i,payload:c}=t;v(s.path)&&i===o.resolvePath(s.path)&&o.emitEvent({payload:c,channelName:r,source:"channel"})}}class se{constructor(){l(this,"contractType","Initialized Marker");l(this,"contractBlueId",h.blueIds["Initialized Marker"]);l(this,"role","marker")}supports(){return!1}handle(){}}class ae extends k{constructor(){super(...arguments);l(this,"contractType","Lifecycle Event Channel");l(this,"contractBlueId",h.blueIds["Lifecycle Event Channel"])}supports(t,n,o){return!this.baseSupports(t)||t.emissionType!=="lifecycle"||!this.isLifecycleEvent(t,o)?!1:this.isEventPatternMatch(t,n,o)}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel",emissionType:t.emissionType})}isLifecycleEvent(t,n){const o=n.getBlue(),r=t.payload;return o.isTypeOf(r,h.LifecycleEventSchema,{checkSchemaExtensions:!0})}isEventPatternMatch(t,n,o){var s;const r=(s=n.getProperties())==null?void 0:s.event;if(!r)return!0;try{const i=o.getBlue(),c=i.resolve(t.payload);return i.isTypeOfNode(c,r)}catch(i){return console.warn("Error during lifecycle event pattern matching:",i),!1}}}const Q=(a,e)=>{const t=e.getBlue();return t.isTypeOf(a.payload,h.TimelineEntrySchema)||t.isTypeOf(a.payload,C.MyOSTimelineEntrySchema)};class ie extends k{constructor(){super(...arguments);l(this,"contractType","MyOS Timeline Channel");l(this,"contractBlueId",C.blueIds["MyOS Timeline Channel"])}supports(t,n,o){var u;if(!this.baseSupports(t)||!Q(t,o))return!1;const s=o.getBlue().nodeToSchemaOutput(t.payload,C.MyOSTimelineEntrySchema),i=o.getBlue().nodeToSchemaOutput(n,C.MyOSTimelineChannelSchema),c=(u=s.timeline)==null?void 0:u.timelineId;return v(i.timelineId)&&v(c)&&c===i.timelineId}handle(t,n,o,r){Q(t,o)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class ce extends k{constructor(){super(...arguments);l(this,"contractType","MyOS Agent Channel");l(this,"contractBlueId",C.blueIds["MyOS Agent Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;try{const{myosAgentEvent:r,myosAgentChannel:s}=this.parseEventAndChannel(t,n,o);return this.isAgentMatch(r,s)&&this.isEventPatternMatch(r,s,o)}catch(r){return console.warn("Error in MyOSAgentChannelProcessor.supports:",r),!1}}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}parseEventAndChannel(t,n,o){const r=o.getBlue(),s=r.nodeToSchemaOutput(t.payload,C.MyOSAgentEventSchema),i=r.nodeToSchemaOutput(n,C.MyOSAgentChannelSchema);return{myosAgentEvent:s,myosAgentChannel:i}}isAgentMatch(t,n){var s;const o=t.agentId,r=(s=n.agent)==null?void 0:s.agentId;return v(o)&&v(r)&&o===r}isEventPatternMatch(t,n,o){const r=n.event;if(!r)return!0;const s=t.event;if(!s)return!1;try{const i=o.getBlue(),c=i.nodeToJson(s),d=i.nodeToJson(r);return E.deepContains(c,d)}catch(i){return console.warn("Error during event pattern matching:",i),!1}}}class le{constructor(){l(this,"contractType","Operation");l(this,"contractBlueId",h.blueIds.Operation);l(this,"role","adapter")}supports(e,t,n,o){const s=n.getBlue().nodeToSchemaOutput(t,h.OperationSchema),i=this.parseEventPayload(e,n),c=this.isOperationNameMatch(i,o),d=this.isOperationChannelMatch(e,s),u=this.isRequestPatternMatch(i,s,n);return c&&d&&u}async handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}parseEventPayload(e,t){const n=t.getBlue();if(n.isTypeOf(e.payload,h.TimelineEntrySchema,{checkSchemaExtensions:!0})){const o=n.nodeToSchemaOutput(e.payload,h.TimelineEntrySchema);if(o.message)return n.nodeToSchemaOutput(o.message,h.OperationRequestSchema)}return null}isOperationNameMatch(e,t){return v(e==null?void 0:e.operation)&&(e==null?void 0:e.operation)===t}isOperationChannelMatch(e,t){const n=t.channel;return E.isNullable(n)?!0:e.source==="channel"&&e.channelName===n}isRequestPatternMatch(e,t,n){const o=t.request;if(E.isNullable(o))return!0;const r=n.getBlue(),s=e==null?void 0:e.request;if(E.isNullable(s))return!1;const i=r.resolve(s);return r.isTypeOfNode(i,o)}}class ue{constructor(){l(this,"contractType","Process Embedded");l(this,"role","adapter");l(this,"contractBlueId",h.blueIds["Process Embedded"])}supports(e){return e.source!=="channel"}handle(e,t,n){const o=n.getBlue().nodeToSchemaOutput(t,h.ProcessEmbeddedSchema);for(const r of o.paths??[])n.emitEvent({...e,dispatchPath:n.resolvePath(r)})}}const de=!process.env.SKIP_ISOLATED_VM;let b=null;if(de)try{b=require("isolated-vm")}catch{console.warn("isolated-vm not available, using fallback evaluation method")}function K(a){return/\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(a)||/\bexport\s+/.test(a)}class q{static getIvmUnavailableMessage(){const e=typeof process<"u"&&process.version?process.version:"unknown",t=typeof process<"u"&&process.platform?process.platform:"unknown",n=typeof process<"u"&&process.arch?process.arch:"unknown";return["isolated-vm is required for expression evaluation but could not be loaded.","This feature only works in a Node.js environment with the native addon available.","",`Detected environment: Node ${e} on ${t}/${n}.`,"","Common causes:","- Running in a non-Node environment (browser, edge/runtime without Node).","- 'isolated-vm' is not installed, or failed to build its native addon.","- The module was bundled/stripped by a build tool.","","How to fix:","- Ensure 'isolated-vm' is listed in dependencies (not devDependencies) of the executing package.","- Reinstall or rebuild: npm ci && npm rebuild isolated-vm (or equivalent with your package manager).","- Run this code on a supported Node.js runtime (not browser/edge workers)."].join(`
2
- `)}static async evaluate({code:e,ctx:t,bindings:n={},options:o={}}){return!b||!de?this.evaluateSimple(e,n,o):this.evaluateSecure(e,n,t,o)}static async evaluateSimple(e,t,n={}){if(K(e))throw new Error("Static import/export syntax requires isolated-vm – start Node without SKIP_ISOLATED_VM.");try{if(n.isCodeBlock){const o=Object.keys(t);return await(await new Function(...o,`return async function codeBlock(${o.join(", ")}) { ${e} }`)(...o.map(i=>t[i])))(...o.map(i=>t[i]))}else return new Function(...Object.keys(t),`return ${e};`)(...Object.values(t))}catch(o){throw n.isCodeBlock?new x(e,o):new j(e,o)}}static async evaluateSecure(e,t,n,o={}){if(!b)throw new Error(this.getIvmUnavailableMessage());const r=new b.Isolate({memoryLimit:32}),s=await r.createContext(),i=s.global;try{await this.setupIsolateEnvironment(i,t);const c=new Map,d=this.createModuleResolver(r,s,c,n);let u;return K(e)?u=await this.evaluateESModule(r,s,e,o,d):u=await this.evaluateSimpleScript(r,s,e,t,o),this.deepClone(u)}catch(c){throw o.isCodeBlock?new x(e,c):new j(e,c)}finally{s.release(),r.dispose()}}static async setupIsolateEnvironment(e,t){if(!b)throw new Error("isolated-vm not available");const n=new b.Callback((...r)=>console.log(...r)),o=new b.ExternalCopy({log:n}).copyInto();await e.set("console",o);for(const[r,s]of Object.entries(t))typeof s=="function"?await e.set(r,new b.Callback(s)):await e.set(r,new b.ExternalCopy(s).copyInto())}static createModuleResolver(e,t,n,o){return async r=>{if(n.has(r))return n.get(r);if(r.startsWith("blue:")){const s=r.slice(5),i=o.loadBlueContent;if(typeof i!="function")throw new Error(`ProcessingContext is missing a loadBlueContent(blueId) implementation (needed for ${r})`);const c=await i(s),d=await e.compileModule(c);return n.set(r,d),await d.instantiate(t,this.createModuleResolver(e,t,n,o)),d}if(/^https?:\/\//.test(r)){let s;if(typeof o.loadExternalModule=="function")s=await o.loadExternalModule(r);else throw new Error(`ProcessingContext is missing a loadExternalModule(url) implementation (needed for ${r})`);const i=await e.compileModule(s);return n.set(r,i),await i.instantiate(t,this.createModuleResolver(e,t,n,o)),i}throw new Error(`Unsupported module specifier "${r}"`)}}static async evaluateSimpleScript(e,t,n,o,r){const s=Object.keys(o).join(", "),i=Object.keys(o).map(u=>u),c=`(async (${s}) => { ${r.isCodeBlock?n:`return (${n});`} })(${i.join(", ")})`;return await(await e.compileScript(c)).run(t,{timeout:r.timeout??500,promise:!0,copy:!0,release:!0})}static async evaluateESModule(e,t,n,o,r){let s=n;if(o.isCodeBlock){const d=/^\s*(import\s.+?;|export\s.+?;)/gm,u=(n.match(d)||[]).join(`
1
+ "use strict";var be=Object.create;var j=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Se=Object.getPrototypeOf,Ce=Object.prototype.hasOwnProperty;var Ne=(a,e,t)=>e in a?j(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var Ie=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Pe(e))!Ce.call(a,o)&&o!==t&&j(a,o,{get:()=>e[o],enumerable:!(n=Te(e,o))||n.enumerable});return a};var z=(a,e,t)=>(t=a!=null?be(Se(a)):{},Ie(e||!a||!a.__esModule?j(t,"default",{value:a,enumerable:!0}):t,a));var l=(a,e,t)=>Ne(a,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("@blue-repository/core-dev"),m=require("@blue-labs/language"),v=require("@blue-labs/shared-utils"),C=require("@blue-repository/myos-dev"),S=(...a)=>a.map((e,t)=>{if(typeof e!="string")return"";if(t===0&&e==="/")return"/";const n=t>0?e.replace(/^\/+/,""):e;return t<a.length-1?n.replace(/\/+$/,""):n}).filter(Boolean).join("/").replace(/\/{2,}/g,"/");class Y{constructor(e,t,n,o){l(this,"actions",[]);this.getDocument=e,this.taskInfo=t,this.blue=n,this.onFlush=o}get(e){const t=this.getDocument(),n=S(this.taskInfo.nodePath,e);return t.get(n)}addPatch(e){this.actions.push({kind:"patch",patch:{...e,path:S(this.taskInfo.nodePath,e.path)}})}emitEvent(e){const t=this.taskInfo.event,n=t.trace??[],o={...e,source:e.source??"internal",originNodePath:e.originNodePath??this.taskInfo.nodePath,rootEvent:e.rootEvent??t.rootEvent??t,trace:[...n],emissionType:e.emissionType??t.emissionType};this.actions.push({kind:"event",event:o})}async flush(){var t;if(!this.actions.length)return[];const e=[...this.actions];return this.actions.length=0,await((t=this.onFlush)==null?void 0:t.call(this,e)),e}getNodePath(){return this.taskInfo.nodePath}resolvePath(e){return S(this.taskInfo.nodePath,e)}getTaskInfo(){return this.taskInfo}getBlue(){return this.blue}loadExternalModule(){throw new Error("Not implemented")}loadBlueContent(e){const t=this.blue.getNodeProvider().fetchFirstByBlueId(e);if(!t)throw new Error(`Blue node not found for blueId: ${e}`);return Promise.resolve(JSON.stringify(this.blue.nodeToJson(t)))}}class _ extends Error{constructor(e,t){super(`Cannot apply patch ${JSON.stringify(e)}`),this.patch=e,this.cause=t,this.name="PatchApplicationError"}}class W extends Error{constructor(e,t,n){super(`Patch ${JSON.stringify(e)} touches "${e.op==="move"||e.op==="copy"?`${e.from} → ${e.path}`:e.path}" which is inside embedded document "${t}" (Process Embedded @ "${n}")`),this.patch=e,this.offendingPath=t,this.contractNodePath=n,this.name="EmbeddedDocumentModificationError"}}class Z extends Error{constructor(e,t){super(`Failed to evaluate expression "${e}"`),this.code=e,this.cause=t,this.name="ExpressionEvaluationError"}}class ee extends Error{constructor(e,t){super(`Failed to evaluate code block "${e}"`),this.code=e,this.cause=t,this.name="CodeBlockEvaluationError"}}function B(a){return v.deepFreeze(a)}function M(a){return a.clone()}function D(a,e,t="/",n=[]){const o=a.getContracts()??{};for(const[r,s]of Object.entries(o))if(e.isTypeOf(s,h.ProcessEmbeddedSchema)){const d=e.nodeToSchemaOutput(s,h.ProcessEmbeddedSchema).paths??[];for(const u of d)n.push({absPath:S(t,u),contractPath:S(t,`contracts/${r}`)})}for(const[r,s]of Object.entries(a.getProperties()??{}))D(s,e,S(t,r),n);return n}function R(a,e){return a===e||a.startsWith(e.endsWith("/")?e:e+"/")}function H(a,e){if(!e.length)return a;let t=M(a);for(const n of e)try{t=m.applyBlueNodePatch(t,n,!0)}catch(o){throw new _(n,o)}return B(t)}function w(a){return a!=null}function N(a){return a instanceof m.BlueNode}class ke{constructor(e=[],t=(n,o)=>n<o?-1:n>o?1:0){l(this,"data");l(this,"length");l(this,"compare");if(this.data=e,this.length=this.data.length,this.compare=t,this.length>0)for(let n=(this.length>>1)-1;n>=0;n--)this._down(n)}push(e){this.data.push(e),this._up(this.length++)}pop(){if(this.length===0)return;const e=this.data[0],t=this.data.pop();return--this.length>0&&(this.data[0]=t,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:t,compare:n}=this,o=t[e];for(;e>0;){const r=e-1>>1,s=t[r];if(n(o,s)>=0)break;t[e]=s,e=r}t[e]=o}_down(e){const{data:t,compare:n}=this,o=this.length>>1,r=t[e];for(;e<o;){let s=(e<<1)+1;const i=s+1;if(i<this.length&&n(t[i],t[s])<0&&(s=i),n(t[s],r)>=0)break;t[e]=t[s],e=s}t[e]=r}}const Be=(a,e,t,n,o,r)=>[-a,e,t,n,o,r],Oe=(a,e)=>{for(let t=0;t<a.key.length;t++){const n=a.key[t],o=e.key[t];if(n!==o)return typeof n=="number"&&typeof o=="number"?n-o:typeof n=="string"&&typeof o=="string"?n.localeCompare(o):0}return 0};class Me{constructor(){l(this,"queue");this.queue=new ke([],Oe)}push(e){this.queue.push(e)}pop(){return this.queue.pop()}get length(){return this.queue.length}}class qe{constructor(e=[]){l(this,"processors",new Map);l(this,"typeOrder",new Map);e.forEach((t,n)=>this.register(t,n))}register(e,t){if(this.processors.has(e.contractBlueId))throw new Error(`Processor for ${e.contractType} already registered`);this.processors.set(e.contractBlueId,e),this.typeOrder.has(e.contractBlueId)||this.typeOrder.set(e.contractBlueId,t??this.typeOrder.size)}get(e){if(!e)return;const t=e.getBlueId();if(t)return this.processors.get(t)}orderOf(e){if(!e)return 0;const t=e.getBlueId();return t?this.typeOrder.get(t)??0:0}values(){return this.processors.values()}}const O=class O{constructor(){l(this,"isEnabled");this.isEnabled=process.env.TRACE_BLUE_ENABLED!=="false"}makeHop(e,t){return`${e}#${t}`}shouldTrace(){return this.isEnabled}addHop(e,t,n){if(!this.shouldTrace())return{...e};const o=e.trace??[],s=[...o.length>=O.MAX_TRACE_LENGTH?o.slice(o.length-(O.MAX_TRACE_LENGTH-1)):o,this.makeHop(t,n)];return{...e,trace:s}}getTrace(e){return e.trace??[]}clearTrace(e){return{...e,trace:[]}}isTracingEnabled(){return this.isEnabled}};l(O,"MAX_TRACE_LENGTH",128);let x=O;function $e(a){return Object.entries(a.getContracts()??{})}const De=64;class Ae{constructor(e,t,n,o,r){l(this,"traceManager");this.blue=e,this.registry=t,this.queue=n,this.getNextTaskId=o,this.getNextEventSeq=r,this.traceManager=new x}async route(e,t,n,o,r=0){var c;if(n.seq===void 0&&(n.seq=this.getNextEventSeq()),t.length===0){if(n.dispatchPath){const d=n.dispatchPath.split("/").filter(Boolean),u={...n};return delete u.dispatchPath,this.route(e,d,u,o,r)}if(n.source==="channel"&&n.originNodePath&&n.originNodePath!=="/"){const d=((c=n.originNodePath)==null?void 0:c.split("/").filter(Boolean))??[];return this.route(e,d,n,o,r)}}const s=S("/",t.join("/")),i=e.get(s);N(i)&&await this.traverseContracts({doc:e,node:i,nodePath:s,event:n,afterTaskId:o,pathSegments:t,inlineDepth:r})}async traverseContracts(e){const{doc:t,node:n,nodePath:o,event:r,afterTaskId:s,pathSegments:i,inlineDepth:c}=e;if(!this.shouldSkipForChannel(r,o))for(const[d,u]of $e(n)){if(!u.getType())continue;const p=this.registry.get(u.getType());if(!p){console.warn(`No processor registered for contract: ${d}`);continue}const f={nodePath:o,contractName:d,contractNode:u,event:r},g=new Y(()=>t,f,this.blue);if(p.supports(r,u,g,d))switch(p.role){case"adapter":await this.processAdapter({cp:p,event:r,contractNode:u,ctx:g,contractName:d,doc:t,afterTaskId:s,inlineDepth:c});break;case"handler":this.scheduleHandler({contractNode:u,contractName:d,nodePath:o,event:r,depth:i.length,afterTaskId:s});break}}}async processAdapter(e){var T;const{cp:t,event:n,contractNode:o,ctx:r,contractName:s,doc:i,afterTaskId:c,inlineDepth:d}=e;if(d>=De)throw new Error("Adapter recursion limit reached");const u=this.traceManager.addHop(n,((T=r.getTaskInfo())==null?void 0:T.nodePath)??"",s);await t.handle(u,o,r,s);const p=await r.flush();if(p.find(b=>b.kind==="patch"))throw new Error(`Contract "${s}" (adapter) attempted to patch the document`);const g=p.filter(b=>b.kind==="event");for(const b of g)await this.route(i,[],b.event,c,d+1)}scheduleHandler(e){const{contractNode:t,contractName:n,nodePath:o,event:r,depth:s,afterTaskId:i}=e,c=t.getType();if(!c){console.warn(`Contract node type is not defined for: ${n}`);return}const d=this.registry.orderOf(c),u=t.get("/order"),p=m.isBigNumber(u)?u.toNumber():0,f=this.getNextTaskId()+i,g=r.seq;if(g===void 0)throw new Error("Event sequence missing");const T=Be(s,g,d,p,n,f);{const E=`${o}#${n}`,A=r.trace??[];if(r.source!=="external"&&A.includes(E))throw new Error(`Loop detected: repeated hop ${E} within the same event chain`)}const b=this.traceManager.addHop(r,o,n);this.queue.push({key:T,nodePath:o,contractName:n,contractNode:t,event:b})}shouldSkipForChannel(e,t){return e.source==="channel"&&!!e.originNodePath&&e.originNodePath!==t}}const je=(a,e,t)=>{(t instanceof _||t instanceof W)&&console.error(`[Blue] Failed to apply patches for contract "${a}" on event ${JSON.stringify(e)}`,t)};function F(a,e){const t=M(a),n=o=>{if(!N(o))return;const r=o.getContracts();(!(r!=null&&r.checkpoint)||!m.BlueNodeTypeSchema.isTypeOf(r.checkpoint,h.ChannelEventCheckpointSchema))&&o.addContract("checkpoint",e.jsonValueToNode({type:{name:"Channel Event Checkpoint",blueId:h.blueIds["Channel Event Checkpoint"]},lastEvents:{}}))};n(t);for(const{absPath:o}of D(t,e)){const r=t.get(o);N(r)&&n(r)}return B(t)}function xe(a,e){const t=M(a);return N(t)&&(te(t,e)||t.addContract("initialized",e.jsonValueToNode({type:{name:"Initialized Marker",blueId:h.blueIds["Initialized Marker"]}}))),B(t)}function te(a,e){const t=a.getContracts();return Object.values(t??{}).some(n=>e.isTypeOf(n,h.InitializedMarkerSchema,{checkSchemaExtensions:!0}))}class ne{constructor(e){l(this,"contractType","Channel Event Checkpoint");l(this,"contractBlueId",h.blueIds["Channel Event Checkpoint"]);l(this,"role","handler");this.cache=e}supports(e){var t,n;return e.source==="channel"&&((t=e.rootEvent)==null?void 0:t.payload)===e.payload&&((n=e.rootEvent)==null?void 0:n.source)==="external"}async getEventBlueId(e,t){var o;const n=(o=e.rootEvent)==null?void 0:o.payload;if(!n)throw new Error("Cannot calculate blueId for checkpoint: missing root event payload");if(n instanceof m.ResolvedBlueNode){const r=n.getMinimalNode();return await t.getBlue().calculateBlueId(r)}return await t.getBlue().calculateBlueId(n)}async handle(e,t,n){var s;if(!e.channelName||!((s=e.rootEvent)!=null&&s.seq))return;const o=await this.getEventBlueId(e,n),r=n.getNodePath().replace(/\/contracts\/checkpoint$/,"");this.cache.record(r,e,o)}}const X=(a,e)=>a.get(e)!==void 0;class Ve{constructor(){l(this,"firstSeen",new Map)}record(e,t,n){const o=e;this.firstSeen.has(o)||this.firstSeen.set(o,{docBase:e,event:t,eventBlueId:n})}flush(e){const t=[];for(const{docBase:n,event:o,eventBlueId:r}of this.firstSeen.values()){if(!o.channelName)continue;const s=S(n,"contracts/checkpoint/lastEvents",o.channelName),i=`${s}/blueId`;X(e,s)?t.push({op:X(e,i)?"replace":"add",path:i,val:r}):t.push({op:"add",path:s,val:{blueId:r}})}return t}clear(){this.firstSeen.clear()}}class oe{constructor(){l(this,"contractType","Composite Timeline Channel");l(this,"contractBlueId",h.blueIds["Composite Timeline Channel"]);l(this,"role","adapter")}supports(e,t,n){const o=n.getBlue().nodeToSchemaOutput(t,h.CompositeTimelineChannelSchema);return!o.channels||!e.channelName?!1:o.channels.includes(e.channelName)}handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}}class I{constructor(){l(this,"role","adapter")}baseSupports(e){return e.source!=="channel"}}class re extends I{constructor(){super(...arguments);l(this,"contractType","Document Update Channel");l(this,"contractBlueId",h.blueIds["Document Update Channel"])}supports(t,n,o){if(!this.baseSupports(t)||t.emissionType!=="update")return!1;const r=o.getBlue().nodeToSchemaOutput(n,h.DocumentUpdateChannelSchema),s=t.payload.get("/path");if(!s)return!1;const i=r.path;return v.isNonNullable(i)&&s===o.resolvePath(i)}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class se extends I{constructor(){super(...arguments);l(this,"contractType","Embedded Node Channel");l(this,"contractBlueId",h.blueIds["Embedded Node Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;const r=o.getBlue().nodeToSchemaOutput(n,h.EmbeddedNodeChannelSchema);return w(t.originNodePath)&&w(r.path)&&t.originNodePath===o.resolvePath(r.path)}handle(t,n,o,r){const s=o.getBlue().nodeToSchemaOutput(n,h.EmbeddedNodeChannelSchema),{originNodePath:i,payload:c}=t;w(s.path)&&i===o.resolvePath(s.path)&&o.emitEvent({payload:c,channelName:r,source:"channel"})}}class ae{constructor(){l(this,"contractType","Initialized Marker");l(this,"contractBlueId",h.blueIds["Initialized Marker"]);l(this,"role","marker")}supports(){return!1}handle(){}}class ie extends I{constructor(){super(...arguments);l(this,"contractType","Lifecycle Event Channel");l(this,"contractBlueId",h.blueIds["Lifecycle Event Channel"])}supports(t,n,o){return!this.baseSupports(t)||t.emissionType!=="lifecycle"||!this.isLifecycleEvent(t,o)?!1:this.isEventPatternMatch(t,n,o)}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel",emissionType:t.emissionType})}isLifecycleEvent(t,n){const o=n.getBlue(),r=t.payload;return o.isTypeOf(r,h.LifecycleEventSchema,{checkSchemaExtensions:!0})}isEventPatternMatch(t,n,o){var s;const r=(s=n.getProperties())==null?void 0:s.event;if(!r)return!0;try{const i=o.getBlue(),c=i.resolve(t.payload);return i.isTypeOfNode(c,r)}catch(i){return console.warn("Error during lifecycle event pattern matching:",i),!1}}}const Q=(a,e)=>{const t=e.getBlue();return t.isTypeOf(a.payload,h.TimelineEntrySchema)||t.isTypeOf(a.payload,C.MyOSTimelineEntrySchema)};class ce extends I{constructor(){super(...arguments);l(this,"contractType","MyOS Timeline Channel");l(this,"contractBlueId",C.blueIds["MyOS Timeline Channel"])}supports(t,n,o){var u;if(!this.baseSupports(t)||!Q(t,o))return!1;const s=o.getBlue().nodeToSchemaOutput(t.payload,C.MyOSTimelineEntrySchema),i=o.getBlue().nodeToSchemaOutput(n,C.MyOSTimelineChannelSchema),c=(u=s.timeline)==null?void 0:u.timelineId;return w(i.timelineId)&&w(c)&&c===i.timelineId}handle(t,n,o,r){Q(t,o)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class le extends I{constructor(){super(...arguments);l(this,"contractType","MyOS Agent Channel");l(this,"contractBlueId",C.blueIds["MyOS Agent Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;try{const{myosAgentEvent:r,myosAgentChannel:s}=this.parseEventAndChannel(t,n,o);return this.isAgentMatch(r,s)&&this.isEventPatternMatch(r,s,o)}catch(r){return console.warn("Error in MyOSAgentChannelProcessor.supports:",r),!1}}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}parseEventAndChannel(t,n,o){const r=o.getBlue(),s=r.nodeToSchemaOutput(t.payload,C.MyOSAgentEventSchema),i=r.nodeToSchemaOutput(n,C.MyOSAgentChannelSchema);return{myosAgentEvent:s,myosAgentChannel:i}}isAgentMatch(t,n){var s;const o=t.agentId,r=(s=n.agent)==null?void 0:s.agentId;return w(o)&&w(r)&&o===r}isEventPatternMatch(t,n,o){const r=n.event;if(!r)return!0;const s=t.event;if(!s)return!1;try{const i=o.getBlue(),c=i.nodeToJson(s),d=i.nodeToJson(r);return v.deepContains(c,d)}catch(i){return console.warn("Error during event pattern matching:",i),!1}}}class ue{constructor(){l(this,"contractType","Operation");l(this,"contractBlueId",h.blueIds.Operation);l(this,"role","adapter")}supports(e,t,n,o){const s=n.getBlue().nodeToSchemaOutput(t,h.OperationSchema),i=this.parseEventPayload(e,n),c=this.isOperationNameMatch(i,o),d=this.isOperationChannelMatch(e,s),u=this.isRequestPatternMatch(i,s,n);return c&&d&&u}async handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}parseEventPayload(e,t){const n=t.getBlue();if(n.isTypeOf(e.payload,h.TimelineEntrySchema,{checkSchemaExtensions:!0})){const o=n.nodeToSchemaOutput(e.payload,h.TimelineEntrySchema);if(o.message)return n.nodeToSchemaOutput(o.message,h.OperationRequestSchema)}return null}isOperationNameMatch(e,t){return w(e==null?void 0:e.operation)&&(e==null?void 0:e.operation)===t}isOperationChannelMatch(e,t){const n=t.channel;return v.isNullable(n)?!0:e.source==="channel"&&e.channelName===n}isRequestPatternMatch(e,t,n){const o=t.request;if(v.isNullable(o))return!0;const r=n.getBlue(),s=e==null?void 0:e.request;if(v.isNullable(s))return!1;const i=r.resolve(s);return r.isTypeOfNode(i,o)}}class de{constructor(){l(this,"contractType","Process Embedded");l(this,"role","adapter");l(this,"contractBlueId",h.blueIds["Process Embedded"])}supports(e){return e.source!=="channel"}handle(e,t,n){const o=n.getBlue().nodeToSchemaOutput(t,h.ProcessEmbeddedSchema);for(const r of o.paths??[])n.emitEvent({...e,dispatchPath:n.resolvePath(r)})}}const _e=!process.env.SKIP_ISOLATED_VM;let y=null;if(_e)try{y=require("isolated-vm")}catch{console.warn("isolated-vm not available, using fallback evaluation method")}function We(a){return/\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(a)||/\bexport\s+/.test(a)}class ${static getIvmUnavailableMessage(){const e=typeof process<"u"&&process.version?process.version:"unknown",t=typeof process<"u"&&process.platform?process.platform:"unknown",n=typeof process<"u"&&process.arch?process.arch:"unknown";return["isolated-vm is required for expression evaluation but could not be loaded.","This feature only works in a Node.js environment with the native addon available.","",`Detected environment: Node ${e} on ${t}/${n}.`,"","Common causes:","- Running in a non-Node environment (browser, edge/runtime without Node).","- 'isolated-vm' is not installed, or failed to build its native addon.","- The module was bundled/stripped by a build tool.","","How to fix:","- Ensure 'isolated-vm' is listed in dependencies (not devDependencies) of the executing package.","- Reinstall or rebuild: npm ci && npm rebuild isolated-vm (or equivalent with your package manager).","- Run this code on a supported Node.js runtime (not browser/edge workers)."].join(`
2
+ `)}static async ensureIvm(){if(y)return y;try{typeof require=="function"?y=require("isolated-vm"):y=(await import("isolated-vm")).default??await import("isolated-vm")}catch(e){console.error(e),y=null}return y}static async evaluate({code:e,ctx:t,bindings:n={},options:o={}}){if(await this.ensureIvm(),!y)throw new Error(this.getIvmUnavailableMessage());return this.evaluateSecure(e,n,t,o)}static async evaluateSecure(e,t,n,o={}){if(!y)throw new Error(this.getIvmUnavailableMessage());const r=new y.Isolate({memoryLimit:32}),s=await r.createContext(),i=s.global;try{await this.setupIsolateEnvironment(i,t);const c=new Map,d=this.createModuleResolver(r,s,c,n);let u;return We(e)?u=await this.evaluateESModule(r,s,e,o,d):u=await this.evaluateSimpleScript(r,s,e,t,o),this.deepClone(u)}catch(c){throw o.isCodeBlock?new ee(e,c):new Z(e,c)}finally{s.release(),r.dispose()}}static async setupIsolateEnvironment(e,t){if(!y)throw new Error("isolated-vm not available");const n=new y.Callback((...r)=>console.log(...r)),o=new y.ExternalCopy({log:n}).copyInto();await e.set("console",o);for(const[r,s]of Object.entries(t))typeof s=="function"?await e.set(r,new y.Callback(s)):await e.set(r,new y.ExternalCopy(s).copyInto())}static createModuleResolver(e,t,n,o){return async r=>{if(n.has(r))return n.get(r);if(r.startsWith("blue:")){const s=r.slice(5),i=o.loadBlueContent;if(typeof i!="function")throw new Error(`ProcessingContext is missing a loadBlueContent(blueId) implementation (needed for ${r})`);const c=await i(s),d=await e.compileModule(c);return n.set(r,d),await d.instantiate(t,this.createModuleResolver(e,t,n,o)),d}if(/^https?:\/\//.test(r)){let s;if(typeof o.loadExternalModule=="function")s=await o.loadExternalModule(r);else throw new Error(`ProcessingContext is missing a loadExternalModule(url) implementation (needed for ${r})`);const i=await e.compileModule(s);return n.set(r,i),await i.instantiate(t,this.createModuleResolver(e,t,n,o)),i}throw new Error(`Unsupported module specifier "${r}"`)}}static async evaluateSimpleScript(e,t,n,o,r){const s=Object.keys(o).join(", "),i=Object.keys(o).map(u=>u),c=`(async (${s}) => { ${r.isCodeBlock?n:`return (${n});`} })(${i.join(", ")})`;return await(await e.compileScript(c)).run(t,{timeout:r.timeout??500,promise:!0,copy:!0,release:!0})}static async evaluateESModule(e,t,n,o,r){let s=n;if(o.isCodeBlock){const d=/^\s*(import\s.+?;|export\s.+?;)/gm,u=(n.match(d)||[]).join(`
3
3
  `),p=n.replace(d,"").trim();s=`
4
4
  ${u}
5
5
  const run = function() {
6
6
  ${p}
7
7
  };
8
8
  export default run();
9
- `}const i=await e.compileModule(s);return await i.instantiate(t,r),await i.evaluate({timeout:o.timeout??500,promise:!0,reference:!0,release:!0}),await i.namespace.get("default",{timeout:o.timeout??500,promise:!0,copy:!0,release:!0})}static deepClone(e){return typeof e>"u"?e:JSON.parse(JSON.stringify(e))}}class L{static createStandardBindings(e,t,n){const o=e.getBlue(),r=o.nodeToJson(t.payload,"simple"),s=m.isBigNumber(r)?r.toNumber():r;return{document:i=>{const c=e.get(i);return m.isBigNumber(c)?c.toNumber():N(c)?o.nodeToJson(c,"original"):c},event:s,steps:n}}}const De=/^\$\{([\s\S]*)\}$/,Ae=/\$\{([\s\S]*?)\}/,S=a=>typeof a!="string"?!1:De.test(a),_=a=>typeof a!="string"?!1:Ae.test(a),he=a=>{if(!S(a))throw new Error(`Invalid expression: ${a}`);return a.slice(2,-1)};class ${static createBindings(e,t,n){return L.createStandardBindings(e,t,n)}static async evaluate(e,t,n,o){const{coerceToString:r}=o;if(S(e)){const s=he(e),i=await q.evaluate({code:s,ctx:t,bindings:n});return r?String(i??""):i}if(_(e)){const i=`\`${String(e).replace(/`/g,"\\`")}\``,c=await q.evaluate({code:i,ctx:t,bindings:n});return String(c??"")}return r?String(e):e}}function G(a,e){const{op:t,path:n,val:o,from:r}=a;if((t==="move"||t==="copy")&&!r)throw new Error(`${t} operation requires 'from' path`);if((t==="add"||t==="replace")&&o===void 0)throw new Error(`${t} operation requires 'val' property`);const s={type:"Document Update",op:t,path:n};return o!==void 0&&(s.val=o),r!==void 0&&(s.from=r),e.jsonValueToNode(s)}function je(a){return a.jsonValueToNode({type:"Document Processing Initiated"})}class xe{constructor(){l(this,"stepType","Update Document")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,h.UpdateDocumentSchema)}async execute(e,t,n,o,r){const s=n.getBlue();if(!m.BlueNodeTypeSchema.isTypeOf(e,h.UpdateDocumentSchema))return;const i=await this.evaluateChangeset(e.get("/changeset"),n,t,r),c=m.applyBlueNodePatch(e,{op:"replace",path:"/changeset",val:i}),d=n.getBlue().nodeToSchemaOutput(c,h.UpdateDocumentSchema);for(const u of d.changeset??[]){if(!u.path)continue;const p=await this.evaluateChangePath(u.path,n,t,r),f=u.val;if((u.op==="replace"||u.op==="add")&&E.isNonNullable(f)){const g=await this.evaluateChangeValue(f,n,t,r);n.addPatch({op:u.op,path:p,val:g}),n.emitEvent({payload:G({op:u.op,path:n.resolvePath(p),val:s.nodeToJson(g,"original")},s),emissionType:"update"})}u.op==="remove"&&(n.addPatch({op:u.op,path:p}),n.emitEvent({payload:G({op:u.op,path:n.resolvePath(p),val:null},s),emissionType:"update"}))}}async evaluateChangeset(e,t,n,o){const r=t.getBlue();if(S(e)){const s=he(e),i=await q.evaluate({code:s,ctx:t,bindings:L.createStandardBindings(t,n,o)});return r.jsonValueToNode(i??null)}if(N(e))return e;throw new Error("Invalid changeset: expected a string or document node")}async evaluateChangeValue(e,t,n,o){const r=e.getValue(),s=t.getBlue();if(S(r)||typeof r=="string"&&_(r)){const i=$.createBindings(t,n,o),c=await $.evaluate(String(r),t,i,{coerceToString:!S(r)});return s.jsonValueToNode(c??null)}return e}async evaluateChangePath(e,t,n,o){const r=$.createBindings(t,n,o);if(S(e)||_(e)){const s=await $.evaluate(e,t,r,{coerceToString:!0});return String(s??"")}return e}}class Ve{constructor(){l(this,"stepType","Trigger Event")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,h.TriggerEventSchema)}async execute(e,t,n){const o=n.getBlue();if(!m.BlueNodeTypeSchema.isTypeOf(e,h.TriggerEventSchema))return;const r=o.nodeToSchemaOutput(e,h.TriggerEventSchema);r.event&&n.emitEvent({payload:r.event,emissionType:"triggered"})}}class _e{constructor(){l(this,"stepType","JavaScript Code")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,h.JavaScriptCodeSchema)}async execute(e,t,n,o,r){if(!m.BlueNodeTypeSchema.isTypeOf(e,h.JavaScriptCodeSchema))return;const s=n.getBlue(),i=s.nodeToSchemaOutput(e,h.JavaScriptCodeSchema);if(!i.code)throw new Error("JavaScript code is required");const c=await q.evaluate({code:i.code,ctx:n,bindings:L.createStandardBindings(n,t,r),options:{isCodeBlock:!0,timeout:500}});if(c&&typeof c=="object"&&"events"in c){const d=c;if(Array.isArray(d.events))for(const u of d.events)n.emitEvent({payload:s.jsonValueToNode(u),emissionType:"triggered"})}return c}}const We=[new xe,new Ve,new _e];class U{constructor(e=We){l(this,"contractType","Sequential Workflow");l(this,"contractBlueId",h.blueIds["Sequential Workflow"]);l(this,"role","handler");l(this,"executors",[]);this.executors=e}registerExecutor(e){this.executors.push(e)}supports(e,t,n){const r=n.getBlue().nodeToSchemaOutput(t,h.SequentialWorkflowSchema),s=this.isChannelNameMatch(e,r),i=this.isEventPatternMatch(e,t,n);return s&&i}async handle(e,t,n,o){var i;const r={},s=(i=t.getProperties())==null?void 0:i.steps.getItems();for(const[c,d]of(s??[]).entries()){const u=this.executors.find(f=>f.supports(d));if(!u)throw new Error(`Unsupported workflow step type "${d.getType()}"`);const p=await u.execute(d,e,n,o,r);if(p!==void 0){const f=d.getName(),g=typeof f=="string"?f:`Step${c+1}`;r[g]=p}await n.flush()}}isChannelNameMatch(e,t){const n=t.channel;return E.isNonNullable(n)&&e.source==="channel"&&e.channelName===n}isEventPatternMatch(e,t,n){var r;const o=(r=t.getProperties())==null?void 0:r.event;if(!o)return!0;try{const s=n.getBlue(),i=s.resolve(e.payload);return s.isTypeOfNode(i,o)}catch(s){return console.warn("Error during event pattern matching:",s),!1}}}class pe{constructor(e){l(this,"contractType","Sequential Workflow Operation");l(this,"contractBlueId",h.blueIds["Sequential Workflow Operation"]);l(this,"role","handler");l(this,"sequentialWorkflowProcessor");this.sequentialWorkflowProcessor=e||new U}supports(e,t,n){const s=n.getBlue().nodeToSchemaOutput(t,h.SequentialWorkflowOperationSchema).operation,i=e.channelName;return e.source==="channel"&&E.isNonNullable(i)&&E.isNonNullable(s)&&i===s}async handle(e,t,n,o){try{await this.sequentialWorkflowProcessor.handle(e,t,n,o)}catch(r){throw console.error("Error in SequentialWorkflowOperationProcessor.handle:",r),r}}}const Y=a=>m.BlueNodeTypeSchema.isTypeOf(a.payload,h.TimelineEntrySchema);class me extends k{constructor(){super(...arguments);l(this,"contractType","Timeline Channel");l(this,"contractBlueId",h.blueIds["Timeline Channel"])}supports(t,n,o){var u;if(!this.baseSupports(t)||!Y(t))return!1;const s=o.getBlue().nodeToSchemaOutput(t.payload,h.TimelineEntrySchema),i=o.getBlue().nodeToSchemaOutput(n,h.TimelineChannelSchema),c=(u=s.timeline)==null?void 0:u.timelineId;return v(i.timelineId)&&v(c)&&c===i.timelineId}handle(t,n,o,r){Y(t)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class fe extends k{constructor(){super(...arguments);l(this,"contractType","Triggered Event Channel");l(this,"contractBlueId",h.blueIds["Triggered Event Channel"])}supports(t){return this.baseSupports(t)?t.emissionType==="triggered":!1}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}const Je=[new ue,new re,new oe,new me,new ie,new ce,new ne,new ae,new fe,new le,new U,new pe,new se];class Le{constructor(e,t=Je){l(this,"taskCounter",0);l(this,"eventCounter",0);l(this,"registry");l(this,"queue");l(this,"router");l(this,"checkpointCache",new qe);this.blue=e,this.registry=new ke(t),this.queue=new Ne,this.router=new Oe(this.blue,this.registry,this.queue,()=>++this.taskCounter,()=>++this.eventCounter),this.register(new te(this.checkpointCache),9999)}register(e,t){this.registry.register(e,t)}async initialize(e){let t=H(B(e),this.blue);const n={payload:je(this.blue),source:"internal",emissionType:"lifecycle"},o=[n.payload];await this.router.route(t,[],n,0);const r=await this.drainQueue(t);return t=r.state,o.push(...r.emitted),t=$e(t,this.blue),{state:M(t),emitted:o}}async processEvents(e,t){let n=H(B(e),this.blue);const o=[];if(!ee(n,this.blue))throw new Error("Document is not initialized");for(const r of t)try{const s={payload:r,source:"external"};await this.router.route(n,[],s,0);const i=await this.drainQueue(n);n=i.state,o.push(...i.emitted);const c=this.checkpointCache.flush(n);c.length&&(n=R(n,c))}finally{this.checkpointCache.clear()}return{state:M(n),emitted:o}}async drainQueue(e){var s;let t=e;const n=[],o=1e4;let r=0;for(;this.queue.length;){if(++r>o)throw new Error("Possible cycle – too many iterations");const i=this.queue.pop(),{nodePath:c,contractName:d,contractNode:u,event:p}=i,f=t.get(c);if(!N(f)||!((s=f.getContracts())!=null&&s[d])||!u.getType())continue;const g=this.registry.get(u.getType());if(!g){console.warn(`No processor registered for contract: ${d}`);continue}const T=new Z(()=>t,i,this.blue,async w=>{for(const y of w)if(y.kind==="patch"){const A=D(t,this.blue);for(const I of A){const ye=y.patch.op==="move"||y.patch.op==="copy"?[y.patch.from,y.patch.path]:[y.patch.path],F=T.getNodePath(),Ee=ye.some(we=>z(we,I.absPath)),ve=z(F,I.absPath);if(Ee&&!ve)throw new J(y.patch,I.absPath,F)}try{t=R(t,[y.patch])}catch(I){throw Me(d,p,I),I}}else y.kind==="event"&&(n.push(y.event.payload),await this.router.route(t,[],y.event,i.key[5]))});await g.handle(p,u,T,d),await T.flush()}return{state:t,emitted:n}}}class ge{process(e,t){const n=t.getValue();if(S(n)){const o=t.clone();return o.setValue(n),o.setProperties(void 0),o.setItems(void 0),o.setType(void 0),o}return e}postProcess(e,t){const n=t.getValue();if(S(n)&&e.getValue()!==n&&n!==void 0){const o=e.clone();return o.setValue(n),o}return e}}const Ue=Object.freeze(Object.defineProperty({__proto__:null,ExpressionPreserver:ge},Symbol.toStringTag,{value:"Module"}));function Fe(){return new m.MergingProcessors.SequentialMergingProcessor([new m.MergingProcessors.ValuePropagator,new ge,new m.MergingProcessors.TypeAssigner,new m.MergingProcessors.ListProcessor,new m.MergingProcessors.DictionaryProcessor,new m.MergingProcessors.BasicTypesVerifier])}exports.BlueDocumentProcessor=Le;exports.ChannelEventCheckpointProcessor=te;exports.CodeBlockEvaluationError=x;exports.CompositeTimelineChannelProcessor=ne;exports.DocumentUpdateChannelProcessor=oe;exports.EmbeddedDocumentModificationError=J;exports.EmbeddedNodeChannelProcessor=re;exports.ExpressionEvaluationError=j;exports.InitializedMarkerProcessor=se;exports.LifecycleEventChannelProcessor=ae;exports.MergingProcessors=Ue;exports.MyOSAgentChannelProcessor=ce;exports.MyOSTimelineChannelProcessor=ie;exports.OperationProcessor=le;exports.PatchApplicationError=W;exports.ProcessEmbeddedProcessor=ue;exports.SequentialWorkflowOperationProcessor=pe;exports.SequentialWorkflowProcessor=U;exports.TimelineChannelProcessor=me;exports.TriggeredEventChannelProcessor=fe;exports.collectEmbeddedPathSpecs=D;exports.createDefaultMergingProcessor=Fe;
9
+ `}const i=await e.compileModule(s);return await i.instantiate(t,r),await i.evaluate({timeout:o.timeout??500,promise:!0,reference:!0,release:!0}),await i.namespace.get("default",{timeout:o.timeout??500,promise:!0,copy:!0,release:!0})}static deepClone(e){return typeof e>"u"?e:JSON.parse(JSON.stringify(e))}}class J{static createStandardBindings(e,t,n){const o=e.getBlue(),r=o.nodeToJson(t.payload,"simple"),s=m.isBigNumber(r)?r.toNumber():r;return{document:i=>{const c=e.get(i);return m.isBigNumber(c)?c.toNumber():N(c)?o.nodeToJson(c,"original"):c},event:s,steps:n}}}const Je=/^\$\{([\s\S]*)\}$/,Ue=/\$\{([\s\S]*?)\}/,P=a=>typeof a!="string"?!1:Je.test(a),V=a=>typeof a!="string"?!1:Ue.test(a),he=a=>{if(!P(a))throw new Error(`Invalid expression: ${a}`);return a.slice(2,-1)};class q{static createBindings(e,t,n){return J.createStandardBindings(e,t,n)}static async evaluate(e,t,n,o){const{coerceToString:r}=o;if(P(e)){const s=he(e),i=await $.evaluate({code:s,ctx:t,bindings:n});return r?String(i??""):i}if(V(e)){const i=`\`${String(e).replace(/`/g,"\\`")}\``,c=await $.evaluate({code:i,ctx:t,bindings:n});return String(c??"")}return r?String(e):e}}function G(a,e){const{op:t,path:n,val:o,from:r}=a;if((t==="move"||t==="copy")&&!r)throw new Error(`${t} operation requires 'from' path`);if((t==="add"||t==="replace")&&o===void 0)throw new Error(`${t} operation requires 'val' property`);const s={type:"Document Update",op:t,path:n};return o!==void 0&&(s.val=o),r!==void 0&&(s.from=r),e.jsonValueToNode(s)}function Le(a){return a.jsonValueToNode({type:"Document Processing Initiated"})}class ze{constructor(){l(this,"stepType","Update Document")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,h.UpdateDocumentSchema)}async execute(e,t,n,o,r){const s=n.getBlue();if(!m.BlueNodeTypeSchema.isTypeOf(e,h.UpdateDocumentSchema))return;const i=await this.evaluateChangeset(e.get("/changeset"),n,t,r),c=m.applyBlueNodePatch(e,{op:"replace",path:"/changeset",val:i}),d=n.getBlue().nodeToSchemaOutput(c,h.UpdateDocumentSchema);for(const u of d.changeset??[]){if(!u.path)continue;const p=await this.evaluateChangePath(u.path,n,t,r),f=u.val;if((u.op==="replace"||u.op==="add")&&v.isNonNullable(f)){const g=await this.evaluateChangeValue(f,n,t,r);n.addPatch({op:u.op,path:p,val:g}),n.emitEvent({payload:G({op:u.op,path:n.resolvePath(p),val:s.nodeToJson(g,"original")},s),emissionType:"update"})}u.op==="remove"&&(n.addPatch({op:u.op,path:p}),n.emitEvent({payload:G({op:u.op,path:n.resolvePath(p),val:null},s),emissionType:"update"}))}}async evaluateChangeset(e,t,n,o){const r=t.getBlue();if(P(e)){const s=he(e),i=await $.evaluate({code:s,ctx:t,bindings:J.createStandardBindings(t,n,o)});return r.jsonValueToNode(i??null)}if(N(e))return e;throw new Error("Invalid changeset: expected a string or document node")}async evaluateChangeValue(e,t,n,o){const r=e.getValue(),s=t.getBlue();if(P(r)||typeof r=="string"&&V(r)){const i=q.createBindings(t,n,o),c=await q.evaluate(String(r),t,i,{coerceToString:!P(r)});return s.jsonValueToNode(c??null)}return e}async evaluateChangePath(e,t,n,o){const r=q.createBindings(t,n,o);if(P(e)||V(e)){const s=await q.evaluate(e,t,r,{coerceToString:!0});return String(s??"")}return e}}class Re{constructor(){l(this,"stepType","Trigger Event")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,h.TriggerEventSchema)}async execute(e,t,n){const o=n.getBlue();if(!m.BlueNodeTypeSchema.isTypeOf(e,h.TriggerEventSchema))return;const r=o.nodeToSchemaOutput(e,h.TriggerEventSchema);r.event&&n.emitEvent({payload:r.event,emissionType:"triggered"})}}class He{constructor(){l(this,"stepType","JavaScript Code")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,h.JavaScriptCodeSchema)}async execute(e,t,n,o,r){if(!m.BlueNodeTypeSchema.isTypeOf(e,h.JavaScriptCodeSchema))return;const s=n.getBlue(),i=s.nodeToSchemaOutput(e,h.JavaScriptCodeSchema);if(!i.code)throw new Error("JavaScript code is required");const c=await $.evaluate({code:i.code,ctx:n,bindings:J.createStandardBindings(n,t,r),options:{isCodeBlock:!0,timeout:500}});if(c&&typeof c=="object"&&"events"in c){const d=c;if(Array.isArray(d.events))for(const u of d.events)n.emitEvent({payload:s.jsonValueToNode(u),emissionType:"triggered"})}return c}}const Fe=[new ze,new Re,new He];class U{constructor(e=Fe){l(this,"contractType","Sequential Workflow");l(this,"contractBlueId",h.blueIds["Sequential Workflow"]);l(this,"role","handler");l(this,"executors",[]);this.executors=e}registerExecutor(e){this.executors.push(e)}supports(e,t,n){const r=n.getBlue().nodeToSchemaOutput(t,h.SequentialWorkflowSchema),s=this.isChannelNameMatch(e,r),i=this.isEventPatternMatch(e,t,n);return s&&i}async handle(e,t,n,o){var i;const r={},s=(i=t.getProperties())==null?void 0:i.steps.getItems();for(const[c,d]of(s??[]).entries()){const u=this.executors.find(f=>f.supports(d));if(!u)throw new Error(`Unsupported workflow step type "${d.getType()}"`);const p=await u.execute(d,e,n,o,r);if(p!==void 0){const f=d.getName(),g=typeof f=="string"?f:`Step${c+1}`;r[g]=p}await n.flush()}}isChannelNameMatch(e,t){const n=t.channel;return v.isNonNullable(n)&&e.source==="channel"&&e.channelName===n}isEventPatternMatch(e,t,n){var r;const o=(r=t.getProperties())==null?void 0:r.event;if(!o)return!0;try{const s=n.getBlue(),i=s.resolve(e.payload);return s.isTypeOfNode(i,o)}catch(s){return console.warn("Error during event pattern matching:",s),!1}}}class pe{constructor(e){l(this,"contractType","Sequential Workflow Operation");l(this,"contractBlueId",h.blueIds["Sequential Workflow Operation"]);l(this,"role","handler");l(this,"sequentialWorkflowProcessor");this.sequentialWorkflowProcessor=e||new U}supports(e,t,n){const s=n.getBlue().nodeToSchemaOutput(t,h.SequentialWorkflowOperationSchema).operation,i=e.channelName;return e.source==="channel"&&v.isNonNullable(i)&&v.isNonNullable(s)&&i===s}async handle(e,t,n,o){try{await this.sequentialWorkflowProcessor.handle(e,t,n,o)}catch(r){throw console.error("Error in SequentialWorkflowOperationProcessor.handle:",r),r}}}const K=a=>m.BlueNodeTypeSchema.isTypeOf(a.payload,h.TimelineEntrySchema);class me extends I{constructor(){super(...arguments);l(this,"contractType","Timeline Channel");l(this,"contractBlueId",h.blueIds["Timeline Channel"])}supports(t,n,o){var u;if(!this.baseSupports(t)||!K(t))return!1;const s=o.getBlue().nodeToSchemaOutput(t.payload,h.TimelineEntrySchema),i=o.getBlue().nodeToSchemaOutput(n,h.TimelineChannelSchema),c=(u=s.timeline)==null?void 0:u.timelineId;return w(i.timelineId)&&w(c)&&c===i.timelineId}handle(t,n,o,r){K(t)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class fe extends I{constructor(){super(...arguments);l(this,"contractType","Triggered Event Channel");l(this,"contractBlueId",h.blueIds["Triggered Event Channel"])}supports(t){return this.baseSupports(t)?t.emissionType==="triggered":!1}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}const Xe=[new de,new se,new re,new me,new ce,new le,new oe,new ie,new fe,new ue,new U,new pe,new ae];class Qe{constructor(e,t=Xe){l(this,"taskCounter",0);l(this,"eventCounter",0);l(this,"registry");l(this,"queue");l(this,"router");l(this,"checkpointCache",new Ve);this.blue=e,this.registry=new qe(t),this.queue=new Me,this.router=new Ae(this.blue,this.registry,this.queue,()=>++this.taskCounter,()=>++this.eventCounter),this.register(new ne(this.checkpointCache),9999)}register(e,t){this.registry.register(e,t)}async initialize(e){let t=F(B(e),this.blue);const n={payload:Le(this.blue),source:"internal",emissionType:"lifecycle"},o=[n.payload];await this.router.route(t,[],n,0);const r=await this.drainQueue(t);return t=r.state,o.push(...r.emitted),t=xe(t,this.blue),{state:M(t),emitted:o}}async processEvents(e,t){let n=F(B(e),this.blue);const o=[];if(!te(n,this.blue))throw new Error("Document is not initialized");for(const r of t)try{const s={payload:r,source:"external"};await this.router.route(n,[],s,0);const i=await this.drainQueue(n);n=i.state,o.push(...i.emitted);const c=this.checkpointCache.flush(n);c.length&&(n=H(n,c))}finally{this.checkpointCache.clear()}return{state:M(n),emitted:o}}async drainQueue(e){var s;let t=e;const n=[],o=1e4;let r=0;for(;this.queue.length;){if(++r>o)throw new Error("Possible cycle – too many iterations");const i=this.queue.pop(),{nodePath:c,contractName:d,contractNode:u,event:p}=i,f=t.get(c);if(!N(f)||!((s=f.getContracts())!=null&&s[d])||!u.getType())continue;const g=this.registry.get(u.getType());if(!g){console.warn(`No processor registered for contract: ${d}`);continue}const T=new Y(()=>t,i,this.blue,async b=>{for(const E of b)if(E.kind==="patch"){const A=D(t,this.blue);for(const k of A){const ye=E.patch.op==="move"||E.patch.op==="copy"?[E.patch.from,E.patch.path]:[E.patch.path],L=T.getNodePath(),Ee=ye.some(we=>R(we,k.absPath)),ve=R(L,k.absPath);if(Ee&&!ve)throw new W(E.patch,k.absPath,L)}try{t=H(t,[E.patch])}catch(k){throw je(d,p,k),k}}else E.kind==="event"&&(n.push(E.event.payload),await this.router.route(t,[],E.event,i.key[5]))});await g.handle(p,u,T,d),await T.flush()}return{state:t,emitted:n}}}class ge{process(e,t){const n=t.getValue();if(P(n)){const o=t.clone();return o.setValue(n),o.setProperties(void 0),o.setItems(void 0),o.setType(void 0),o}return e}postProcess(e,t){const n=t.getValue();if(P(n)&&e.getValue()!==n&&n!==void 0){const o=e.clone();return o.setValue(n),o}return e}}const Ge=Object.freeze(Object.defineProperty({__proto__:null,ExpressionPreserver:ge},Symbol.toStringTag,{value:"Module"}));function Ke(){return new m.MergingProcessors.SequentialMergingProcessor([new m.MergingProcessors.ValuePropagator,new ge,new m.MergingProcessors.TypeAssigner,new m.MergingProcessors.ListProcessor,new m.MergingProcessors.DictionaryProcessor,new m.MergingProcessors.BasicTypesVerifier])}exports.BlueDocumentProcessor=Qe;exports.ChannelEventCheckpointProcessor=ne;exports.CodeBlockEvaluationError=ee;exports.CompositeTimelineChannelProcessor=oe;exports.DocumentUpdateChannelProcessor=re;exports.EmbeddedDocumentModificationError=W;exports.EmbeddedNodeChannelProcessor=se;exports.ExpressionEvaluationError=Z;exports.InitializedMarkerProcessor=ae;exports.LifecycleEventChannelProcessor=ie;exports.MergingProcessors=Ge;exports.MyOSAgentChannelProcessor=le;exports.MyOSTimelineChannelProcessor=ce;exports.OperationProcessor=ue;exports.PatchApplicationError=_;exports.ProcessEmbeddedProcessor=de;exports.SequentialWorkflowOperationProcessor=pe;exports.SequentialWorkflowProcessor=U;exports.TimelineChannelProcessor=me;exports.TriggeredEventChannelProcessor=fe;exports.collectEmbeddedPathSpecs=D;exports.createDefaultMergingProcessor=Ke;
package/dist/index.mjs CHANGED
@@ -1,17 +1,17 @@
1
- var we = Object.defineProperty;
2
- var ve = (a, e, t) => e in a ? we(a, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : a[e] = t;
3
- var l = (a, e, t) => ve(a, typeof e != "symbol" ? e + "" : e, t);
4
- import { ProcessEmbeddedSchema as W, ChannelEventCheckpointSchema as Te, blueIds as y, InitializedMarkerSchema as be, CompositeTimelineChannelSchema as Pe, DocumentUpdateChannelSchema as Se, EmbeddedNodeChannelSchema as H, LifecycleEventSchema as Ce, TimelineEntrySchema as O, OperationSchema as Ne, OperationRequestSchema as ke, UpdateDocumentSchema as j, TriggerEventSchema as x, JavaScriptCodeSchema as V, SequentialWorkflowSchema as Ie, SequentialWorkflowOperationSchema as Be, TimelineChannelSchema as Oe } from "@blue-repository/core-dev";
5
- import { applyBlueNodePatch as re, BlueNode as Me, isBigNumber as L, BlueNodeTypeSchema as P, ResolvedBlueNode as $e, MergingProcessors as k } from "@blue-labs/language";
6
- import { deepFreeze as qe, isNonNullable as M, deepContains as Ae, isNullable as _ } from "@blue-labs/shared-utils";
7
- import { blueIds as se, MyOSTimelineEntrySchema as ae, MyOSTimelineChannelSchema as De, MyOSAgentEventSchema as je, MyOSAgentChannelSchema as xe } from "@blue-repository/myos-dev";
1
+ var me = Object.defineProperty;
2
+ var ge = (a, e, t) => e in a ? me(a, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : a[e] = t;
3
+ var l = (a, e, t) => ge(a, typeof e != "symbol" ? e + "" : e, t);
4
+ import { ProcessEmbeddedSchema as W, ChannelEventCheckpointSchema as ye, blueIds as y, InitializedMarkerSchema as Ee, CompositeTimelineChannelSchema as we, DocumentUpdateChannelSchema as ve, EmbeddedNodeChannelSchema as F, LifecycleEventSchema as Te, TimelineEntrySchema as O, OperationSchema as be, OperationRequestSchema as Pe, UpdateDocumentSchema as j, TriggerEventSchema as x, JavaScriptCodeSchema as V, SequentialWorkflowSchema as Se, SequentialWorkflowOperationSchema as Ce, TimelineChannelSchema as Ne } from "@blue-repository/core-dev";
5
+ import { applyBlueNodePatch as te, BlueNode as ke, isBigNumber as J, BlueNodeTypeSchema as P, ResolvedBlueNode as Ie, MergingProcessors as k } from "@blue-labs/language";
6
+ import { deepFreeze as Be, isNonNullable as M, deepContains as Oe, isNullable as _ } from "@blue-labs/shared-utils";
7
+ import { blueIds as ne, MyOSTimelineEntrySchema as oe, MyOSTimelineChannelSchema as Me, MyOSAgentEventSchema as $e, MyOSAgentChannelSchema as qe } from "@blue-repository/myos-dev";
8
8
  const b = (...a) => a.map((e, t) => {
9
9
  if (typeof e != "string") return "";
10
10
  if (t === 0 && e === "/") return "/";
11
11
  const n = t > 0 ? e.replace(/^\/+/, "") : e;
12
12
  return t < a.length - 1 ? n.replace(/\/+$/, "") : n;
13
13
  }).filter(Boolean).join("/").replace(/\/{2,}/g, "/");
14
- class ie {
14
+ class re {
15
15
  constructor(e, t, n, o) {
16
16
  l(this, "actions", []);
17
17
  this.getDocument = e, this.taskInfo = t, this.blue = n, this.onFlush = o;
@@ -69,35 +69,35 @@ class ie {
69
69
  return Promise.resolve(JSON.stringify(this.blue.nodeToJson(t)));
70
70
  }
71
71
  }
72
- class ce extends Error {
72
+ class se extends Error {
73
73
  constructor(e, t) {
74
74
  super(`Cannot apply patch ${JSON.stringify(e)}`), this.patch = e, this.cause = t, this.name = "PatchApplicationError";
75
75
  }
76
76
  }
77
- class le extends Error {
77
+ class ae extends Error {
78
78
  constructor(e, t, n) {
79
79
  super(
80
80
  `Patch ${JSON.stringify(e)} touches "${e.op === "move" || e.op === "copy" ? `${e.from} → ${e.path}` : e.path}" which is inside embedded document "${t}" (Process Embedded @ "${n}")`
81
81
  ), this.patch = e, this.offendingPath = t, this.contractNodePath = n, this.name = "EmbeddedDocumentModificationError";
82
82
  }
83
83
  }
84
- class X extends Error {
84
+ class Ae extends Error {
85
85
  constructor(e, t) {
86
86
  super(`Failed to evaluate expression "${e}"`), this.code = e, this.cause = t, this.name = "ExpressionEvaluationError";
87
87
  }
88
88
  }
89
- class Q extends Error {
89
+ class De extends Error {
90
90
  constructor(e, t) {
91
91
  super(`Failed to evaluate code block "${e}"`), this.code = e, this.cause = t, this.name = "CodeBlockEvaluationError";
92
92
  }
93
93
  }
94
94
  function I(a) {
95
- return qe(a);
95
+ return Be(a);
96
96
  }
97
97
  function $(a) {
98
98
  return a.clone();
99
99
  }
100
- function U(a, e, t = "/", n = []) {
100
+ function z(a, e, t = "/", n = []) {
101
101
  const o = a.getContracts() ?? {};
102
102
  for (const [r, s] of Object.entries(o))
103
103
  if (e.isTypeOf(s, W)) {
@@ -112,7 +112,7 @@ function U(a, e, t = "/", n = []) {
112
112
  });
113
113
  }
114
114
  for (const [r, s] of Object.entries(a.getProperties() ?? {}))
115
- U(
115
+ z(
116
116
  s,
117
117
  e,
118
118
  b(t, r),
@@ -120,27 +120,27 @@ function U(a, e, t = "/", n = []) {
120
120
  );
121
121
  return n;
122
122
  }
123
- function K(a, e) {
123
+ function X(a, e) {
124
124
  return a === e || a.startsWith(e.endsWith("/") ? e : e + "/");
125
125
  }
126
- function G(a, e) {
126
+ function Q(a, e) {
127
127
  if (!e.length) return a;
128
128
  let t = $(a);
129
129
  for (const n of e)
130
130
  try {
131
- t = re(t, n, !0);
131
+ t = te(t, n, !0);
132
132
  } catch (o) {
133
- throw new ce(n, o);
133
+ throw new se(n, o);
134
134
  }
135
135
  return I(t);
136
136
  }
137
- function g(a) {
137
+ function E(a) {
138
138
  return a != null;
139
139
  }
140
140
  function S(a) {
141
- return a instanceof Me;
141
+ return a instanceof ke;
142
142
  }
143
- class Ve {
143
+ class je {
144
144
  constructor(e = [], t = (n, o) => n < o ? -1 : n > o ? 1 : 0) {
145
145
  l(this, "data");
146
146
  l(this, "length");
@@ -179,14 +179,14 @@ class Ve {
179
179
  t[e] = r;
180
180
  }
181
181
  }
182
- const _e = (a, e, t, n, o, r) => [
182
+ const xe = (a, e, t, n, o, r) => [
183
183
  -a,
184
184
  e,
185
185
  t,
186
186
  n,
187
187
  o,
188
188
  r
189
- ], We = (a, e) => {
189
+ ], Ve = (a, e) => {
190
190
  for (let t = 0; t < a.key.length; t++) {
191
191
  const n = a.key[t], o = e.key[t];
192
192
  if (n !== o)
@@ -194,13 +194,13 @@ const _e = (a, e, t, n, o, r) => [
194
194
  }
195
195
  return 0;
196
196
  };
197
- class Le {
197
+ class _e {
198
198
  /**
199
199
  * Creates a new task queue with the task key comparator
200
200
  */
201
201
  constructor() {
202
202
  l(this, "queue");
203
- this.queue = new Ve([], We);
203
+ this.queue = new je([], Ve);
204
204
  }
205
205
  /**
206
206
  * Adds a task to the queue
@@ -225,7 +225,7 @@ class Le {
225
225
  return this.queue.length;
226
226
  }
227
227
  }
228
- class Fe {
228
+ class We {
229
229
  /**
230
230
  * Creates a new contract registry
231
231
  *
@@ -345,12 +345,12 @@ const B = class B {
345
345
  }
346
346
  };
347
347
  l(B, "MAX_TRACE_LENGTH", 128);
348
- let F = B;
348
+ let L = B;
349
349
  function Je(a) {
350
350
  return Object.entries(a.getContracts() ?? {});
351
351
  }
352
- const Ue = 64;
353
- class ze {
352
+ const Le = 64;
353
+ class Ue {
354
354
  /**
355
355
  * Creates a new event router
356
356
  *
@@ -361,7 +361,7 @@ class ze {
361
361
  */
362
362
  constructor(e, t, n, o, r) {
363
363
  l(this, "traceManager");
364
- this.blue = e, this.registry = t, this.queue = n, this.getNextTaskId = o, this.getNextEventSeq = r, this.traceManager = new F();
364
+ this.blue = e, this.registry = t, this.queue = n, this.getNextTaskId = o, this.getNextEventSeq = r, this.traceManager = new L();
365
365
  }
366
366
  /**
367
367
  * Routes an event to matching contracts in the document
@@ -421,15 +421,15 @@ class ze {
421
421
  contractName: h,
422
422
  contractNode: u,
423
423
  event: r
424
- }, m = new ie(() => t, p, this.blue);
425
- if (d.supports(r, u, m, h))
424
+ }, f = new re(() => t, p, this.blue);
425
+ if (d.supports(r, u, f, h))
426
426
  switch (d.role) {
427
427
  case "adapter":
428
428
  await this.processAdapter({
429
429
  cp: d,
430
430
  event: r,
431
431
  contractNode: u,
432
- ctx: m,
432
+ ctx: f,
433
433
  contractName: h,
434
434
  doc: t,
435
435
  afterTaskId: s,
@@ -464,7 +464,7 @@ class ze {
464
464
  afterTaskId: c,
465
465
  inlineDepth: h
466
466
  } = e;
467
- if (h >= Ue)
467
+ if (h >= Le)
468
468
  throw new Error("Adapter recursion limit reached");
469
469
  const u = this.traceManager.addHop(
470
470
  n,
@@ -473,13 +473,13 @@ class ze {
473
473
  );
474
474
  await t.handle(u, o, r, s);
475
475
  const d = await r.flush();
476
- if (d.find((E) => E.kind === "patch"))
476
+ if (d.find((w) => w.kind === "patch"))
477
477
  throw new Error(
478
478
  `Contract "${s}" (adapter) attempted to patch the document`
479
479
  );
480
- const m = d.filter((E) => E.kind === "event");
481
- for (const E of m)
482
- await this.route(i, [], E.event, c, h + 1);
480
+ const f = d.filter((w) => w.kind === "event");
481
+ for (const w of f)
482
+ await this.route(i, [], w.event, c, h + 1);
483
483
  }
484
484
  /**
485
485
  * Schedules a handler contract for future execution
@@ -490,31 +490,31 @@ class ze {
490
490
  console.warn(`Contract node type is not defined for: ${n}`);
491
491
  return;
492
492
  }
493
- const h = this.registry.orderOf(c), u = t.get("/order"), d = L(u) ? u.toNumber() : 0, p = this.getNextTaskId() + i, m = r.seq;
494
- if (m === void 0)
493
+ const h = this.registry.orderOf(c), u = t.get("/order"), d = J(u) ? u.toNumber() : 0, p = this.getNextTaskId() + i, f = r.seq;
494
+ if (f === void 0)
495
495
  throw new Error("Event sequence missing");
496
- const v = _e(
496
+ const v = xe(
497
497
  s,
498
- m,
498
+ f,
499
499
  h,
500
500
  d,
501
501
  n,
502
502
  p
503
503
  );
504
504
  {
505
- const f = `${o}#${n}`, D = r.trace ?? [];
506
- if (r.source !== "external" && D.includes(f))
505
+ const g = `${o}#${n}`, D = r.trace ?? [];
506
+ if (r.source !== "external" && D.includes(g))
507
507
  throw new Error(
508
- `Loop detected: repeated hop ${f} within the same event chain`
508
+ `Loop detected: repeated hop ${g} within the same event chain`
509
509
  );
510
510
  }
511
- const E = this.traceManager.addHop(r, o, n);
511
+ const w = this.traceManager.addHop(r, o, n);
512
512
  this.queue.push({
513
513
  key: v,
514
514
  nodePath: o,
515
515
  contractName: n,
516
516
  contractNode: t,
517
- event: E
517
+ event: w
518
518
  });
519
519
  }
520
520
  /**
@@ -524,19 +524,19 @@ class ze {
524
524
  return e.source === "channel" && !!e.originNodePath && e.originNodePath !== t;
525
525
  }
526
526
  }
527
- const Re = (a, e, t) => {
528
- (t instanceof ce || t instanceof le) && console.error(
527
+ const ze = (a, e, t) => {
528
+ (t instanceof se || t instanceof ae) && console.error(
529
529
  `[Blue] Failed to apply patches for contract "${a}" on event ${JSON.stringify(e)}`,
530
530
  t
531
531
  );
532
532
  };
533
- function Y(a, e) {
533
+ function G(a, e) {
534
534
  const t = $(a), n = (o) => {
535
535
  if (!S(o)) return;
536
536
  const r = o.getContracts();
537
537
  (!(r != null && r.checkpoint) || !P.isTypeOf(
538
538
  r.checkpoint,
539
- Te
539
+ ye
540
540
  )) && o.addContract(
541
541
  "checkpoint",
542
542
  e.jsonValueToNode({
@@ -549,15 +549,15 @@ function Y(a, e) {
549
549
  );
550
550
  };
551
551
  n(t);
552
- for (const { absPath: o } of U(t, e)) {
552
+ for (const { absPath: o } of z(t, e)) {
553
553
  const r = t.get(o);
554
554
  S(r) && n(r);
555
555
  }
556
556
  return I(t);
557
557
  }
558
- function He(a, e) {
558
+ function Re(a, e) {
559
559
  const t = $(a);
560
- return S(t) && (ue(t, e) || t.addContract(
560
+ return S(t) && (ie(t, e) || t.addContract(
561
561
  "initialized",
562
562
  e.jsonValueToNode({
563
563
  type: {
@@ -567,15 +567,15 @@ function He(a, e) {
567
567
  })
568
568
  )), I(t);
569
569
  }
570
- function ue(a, e) {
570
+ function ie(a, e) {
571
571
  const t = a.getContracts();
572
572
  return Object.values(t ?? {}).some(
573
- (n) => e.isTypeOf(n, be, {
573
+ (n) => e.isTypeOf(n, Ee, {
574
574
  checkSchemaExtensions: !0
575
575
  })
576
576
  );
577
577
  }
578
- class Xe {
578
+ class He {
579
579
  constructor(e) {
580
580
  l(this, "contractType", "Channel Event Checkpoint");
581
581
  l(this, "contractBlueId", y["Channel Event Checkpoint"]);
@@ -593,7 +593,7 @@ class Xe {
593
593
  throw new Error(
594
594
  "Cannot calculate blueId for checkpoint: missing root event payload"
595
595
  );
596
- if (n instanceof $e) {
596
+ if (n instanceof Ie) {
597
597
  const r = n.getMinimalNode();
598
598
  return await t.getBlue().calculateBlueId(r);
599
599
  }
@@ -606,8 +606,8 @@ class Xe {
606
606
  this.cache.record(r, e, o);
607
607
  }
608
608
  }
609
- const Z = (a, e) => a.get(e) !== void 0;
610
- class Qe {
609
+ const K = (a, e) => a.get(e) !== void 0;
610
+ class Fe {
611
611
  constructor() {
612
612
  l(this, "firstSeen", /* @__PURE__ */ new Map());
613
613
  }
@@ -625,8 +625,8 @@ class Qe {
625
625
  "contracts/checkpoint/lastEvents",
626
626
  o.channelName
627
627
  ), i = `${s}/blueId`;
628
- Z(e, s) ? t.push({
629
- op: Z(e, i) ? "replace" : "add",
628
+ K(e, s) ? t.push({
629
+ op: K(e, i) ? "replace" : "add",
630
630
  path: i,
631
631
  val: r
632
632
  }) : t.push({
@@ -641,14 +641,14 @@ class Qe {
641
641
  this.firstSeen.clear();
642
642
  }
643
643
  }
644
- class Ke {
644
+ class Xe {
645
645
  constructor() {
646
646
  l(this, "contractType", "Composite Timeline Channel");
647
647
  l(this, "contractBlueId", y["Composite Timeline Channel"]);
648
648
  l(this, "role", "adapter");
649
649
  }
650
650
  supports(e, t, n) {
651
- const o = n.getBlue().nodeToSchemaOutput(t, Pe);
651
+ const o = n.getBlue().nodeToSchemaOutput(t, we);
652
652
  return !o.channels || !e.channelName ? !1 : o.channels.includes(e.channelName);
653
653
  }
654
654
  handle(e, t, n, o) {
@@ -671,7 +671,7 @@ class C {
671
671
  return e.source !== "channel";
672
672
  }
673
673
  }
674
- class Ge extends C {
674
+ class Qe extends C {
675
675
  constructor() {
676
676
  super(...arguments);
677
677
  l(this, "contractType", "Document Update Channel");
@@ -679,7 +679,7 @@ class Ge extends C {
679
679
  }
680
680
  supports(t, n, o) {
681
681
  if (!this.baseSupports(t) || t.emissionType !== "update") return !1;
682
- const r = o.getBlue().nodeToSchemaOutput(n, Se), s = t.payload.get("/path");
682
+ const r = o.getBlue().nodeToSchemaOutput(n, ve), s = t.payload.get("/path");
683
683
  if (!s) return !1;
684
684
  const i = r.path;
685
685
  return M(i) && s === o.resolvePath(i);
@@ -692,7 +692,7 @@ class Ge extends C {
692
692
  });
693
693
  }
694
694
  }
695
- class Ye extends C {
695
+ class Ge extends C {
696
696
  constructor() {
697
697
  super(...arguments);
698
698
  l(this, "contractType", "Embedded Node Channel");
@@ -700,19 +700,19 @@ class Ye extends C {
700
700
  }
701
701
  supports(t, n, o) {
702
702
  if (!this.baseSupports(t)) return !1;
703
- const r = o.getBlue().nodeToSchemaOutput(n, H);
704
- return g(t.originNodePath) && g(r.path) && t.originNodePath === o.resolvePath(r.path);
703
+ const r = o.getBlue().nodeToSchemaOutput(n, F);
704
+ return E(t.originNodePath) && E(r.path) && t.originNodePath === o.resolvePath(r.path);
705
705
  }
706
706
  handle(t, n, o, r) {
707
- const s = o.getBlue().nodeToSchemaOutput(n, H), { originNodePath: i, payload: c } = t;
708
- g(s.path) && i === o.resolvePath(s.path) && o.emitEvent({
707
+ const s = o.getBlue().nodeToSchemaOutput(n, F), { originNodePath: i, payload: c } = t;
708
+ E(s.path) && i === o.resolvePath(s.path) && o.emitEvent({
709
709
  payload: c,
710
710
  channelName: r,
711
711
  source: "channel"
712
712
  });
713
713
  }
714
714
  }
715
- class Ze {
715
+ class Ke {
716
716
  constructor() {
717
717
  l(this, "contractType", "Initialized Marker");
718
718
  l(this, "contractBlueId", y["Initialized Marker"]);
@@ -724,7 +724,7 @@ class Ze {
724
724
  handle() {
725
725
  }
726
726
  }
727
- class et extends C {
727
+ class Ye extends C {
728
728
  constructor() {
729
729
  super(...arguments);
730
730
  l(this, "contractType", "Lifecycle Event Channel");
@@ -746,7 +746,7 @@ class et extends C {
746
746
  */
747
747
  isLifecycleEvent(t, n) {
748
748
  const o = n.getBlue(), r = t.payload;
749
- return o.isTypeOf(r, Ce, {
749
+ return o.isTypeOf(r, Te, {
750
750
  checkSchemaExtensions: !0
751
751
  });
752
752
  }
@@ -766,38 +766,38 @@ class et extends C {
766
766
  }
767
767
  }
768
768
  }
769
- const ee = (a, e) => {
769
+ const Y = (a, e) => {
770
770
  const t = e.getBlue();
771
- return t.isTypeOf(a.payload, O) || t.isTypeOf(a.payload, ae);
771
+ return t.isTypeOf(a.payload, O) || t.isTypeOf(a.payload, oe);
772
772
  };
773
- class tt extends C {
773
+ class Ze extends C {
774
774
  constructor() {
775
775
  super(...arguments);
776
776
  l(this, "contractType", "MyOS Timeline Channel");
777
- l(this, "contractBlueId", se["MyOS Timeline Channel"]);
777
+ l(this, "contractBlueId", ne["MyOS Timeline Channel"]);
778
778
  }
779
779
  supports(t, n, o) {
780
780
  var u;
781
- if (!this.baseSupports(t) || !ee(t, o)) return !1;
781
+ if (!this.baseSupports(t) || !Y(t, o)) return !1;
782
782
  const s = o.getBlue().nodeToSchemaOutput(
783
783
  t.payload,
784
- ae
785
- ), i = o.getBlue().nodeToSchemaOutput(n, De), c = (u = s.timeline) == null ? void 0 : u.timelineId;
786
- return g(i.timelineId) && g(c) && c === i.timelineId;
784
+ oe
785
+ ), i = o.getBlue().nodeToSchemaOutput(n, Me), c = (u = s.timeline) == null ? void 0 : u.timelineId;
786
+ return E(i.timelineId) && E(c) && c === i.timelineId;
787
787
  }
788
788
  handle(t, n, o, r) {
789
- ee(t, o) && o.emitEvent({
789
+ Y(t, o) && o.emitEvent({
790
790
  payload: t.payload,
791
791
  channelName: r,
792
792
  source: "channel"
793
793
  });
794
794
  }
795
795
  }
796
- class nt extends C {
796
+ class et extends C {
797
797
  constructor() {
798
798
  super(...arguments);
799
799
  l(this, "contractType", "MyOS Agent Channel");
800
- l(this, "contractBlueId", se["MyOS Agent Channel"]);
800
+ l(this, "contractBlueId", ne["MyOS Agent Channel"]);
801
801
  }
802
802
  supports(t, n, o) {
803
803
  if (!this.baseSupports(t)) return !1;
@@ -826,10 +826,10 @@ class nt extends C {
826
826
  parseEventAndChannel(t, n, o) {
827
827
  const r = o.getBlue(), s = r.nodeToSchemaOutput(
828
828
  t.payload,
829
- je
829
+ $e
830
830
  ), i = r.nodeToSchemaOutput(
831
831
  n,
832
- xe
832
+ qe
833
833
  );
834
834
  return { myosAgentEvent: s, myosAgentChannel: i };
835
835
  }
@@ -842,7 +842,7 @@ class nt extends C {
842
842
  isAgentMatch(t, n) {
843
843
  var s;
844
844
  const o = t.agentId, r = (s = n.agent) == null ? void 0 : s.agentId;
845
- return g(o) && g(r) && o === r;
845
+ return E(o) && E(r) && o === r;
846
846
  }
847
847
  /**
848
848
  * Checks if the event pattern matches the channel's event filter
@@ -866,20 +866,20 @@ class nt extends C {
866
866
  return !1;
867
867
  try {
868
868
  const i = o.getBlue(), c = i.nodeToJson(s), h = i.nodeToJson(r);
869
- return Ae(c, h);
869
+ return Oe(c, h);
870
870
  } catch (i) {
871
871
  return console.warn("Error during event pattern matching:", i), !1;
872
872
  }
873
873
  }
874
874
  }
875
- class ot {
875
+ class tt {
876
876
  constructor() {
877
877
  l(this, "contractType", "Operation");
878
878
  l(this, "contractBlueId", y.Operation);
879
879
  l(this, "role", "adapter");
880
880
  }
881
881
  supports(e, t, n, o) {
882
- const s = n.getBlue().nodeToSchemaOutput(t, Ne), i = this.parseEventPayload(e, n), c = this.isOperationNameMatch(
882
+ const s = n.getBlue().nodeToSchemaOutput(t, be), i = this.parseEventPayload(e, n), c = this.isOperationNameMatch(
883
883
  i,
884
884
  o
885
885
  ), h = this.isOperationChannelMatch(
@@ -911,13 +911,13 @@ class ot {
911
911
  if (o.message)
912
912
  return n.nodeToSchemaOutput(
913
913
  o.message,
914
- ke
914
+ Pe
915
915
  );
916
916
  }
917
917
  return null;
918
918
  }
919
919
  isOperationNameMatch(e, t) {
920
- return g(e == null ? void 0 : e.operation) && (e == null ? void 0 : e.operation) === t;
920
+ return E(e == null ? void 0 : e.operation) && (e == null ? void 0 : e.operation) === t;
921
921
  }
922
922
  isOperationChannelMatch(e, t) {
923
923
  const n = t.channel;
@@ -934,7 +934,7 @@ class ot {
934
934
  return r.isTypeOfNode(i, o);
935
935
  }
936
936
  }
937
- class rt {
937
+ class nt {
938
938
  constructor() {
939
939
  l(this, "contractType", "Process Embedded");
940
940
  l(this, "role", "adapter");
@@ -952,15 +952,15 @@ class rt {
952
952
  });
953
953
  }
954
954
  }
955
- const he = !process.env.SKIP_ISOLATED_VM;
956
- let w = null;
957
- if (he)
955
+ const ot = !process.env.SKIP_ISOLATED_VM;
956
+ let m = null;
957
+ if (ot)
958
958
  try {
959
- w = require("isolated-vm");
959
+ m = require("isolated-vm");
960
960
  } catch {
961
961
  console.warn("isolated-vm not available, using fallback evaluation method");
962
962
  }
963
- function te(a) {
963
+ function rt(a) {
964
964
  return /\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(a) || /\bexport\s+/.test(a);
965
965
  }
966
966
  class A {
@@ -984,6 +984,16 @@ class A {
984
984
  ].join(`
985
985
  `);
986
986
  }
987
+ static async ensureIvm() {
988
+ if (m)
989
+ return m;
990
+ try {
991
+ typeof require == "function" ? m = require("isolated-vm") : m = (await import("isolated-vm")).default ?? await import("isolated-vm");
992
+ } catch (e) {
993
+ console.error(e), m = null;
994
+ }
995
+ return m;
996
+ }
987
997
  /**
988
998
  * Main evaluation method - chooses between secure and simple evaluation strategies
989
999
  */
@@ -993,43 +1003,16 @@ class A {
993
1003
  bindings: n = {},
994
1004
  options: o = {}
995
1005
  }) {
996
- return !w || !he ? this.evaluateSimple(e, n, o) : this.evaluateSecure(e, n, t, o);
997
- }
998
- /**
999
- * Fallback evaluation using Node's Function constructor
1000
- * Used when isolated-vm is not available
1001
- */
1002
- static async evaluateSimple(e, t, n = {}) {
1003
- if (te(e))
1004
- throw new Error(
1005
- "Static import/export syntax requires isolated-vm – start Node without SKIP_ISOLATED_VM."
1006
- );
1007
- try {
1008
- if (n.isCodeBlock) {
1009
- const o = Object.keys(t);
1010
- return await (await new Function(
1011
- ...o,
1012
- `return async function codeBlock(${o.join(
1013
- ", "
1014
- )}) { ${e} }`
1015
- )(
1016
- ...o.map((i) => t[i])
1017
- ))(...o.map((i) => t[i]));
1018
- } else
1019
- return new Function(
1020
- ...Object.keys(t),
1021
- `return ${e};`
1022
- )(...Object.values(t));
1023
- } catch (o) {
1024
- throw n.isCodeBlock ? new Q(e, o) : new X(e, o);
1025
- }
1006
+ if (await this.ensureIvm(), !m)
1007
+ throw new Error(this.getIvmUnavailableMessage());
1008
+ return this.evaluateSecure(e, n, t, o);
1026
1009
  }
1027
1010
  /**
1028
1011
  * Secure evaluation using isolated-vm with support for ES modules
1029
1012
  */
1030
1013
  static async evaluateSecure(e, t, n, o = {}) {
1031
- if (!w) throw new Error(this.getIvmUnavailableMessage());
1032
- const r = new w.Isolate({ memoryLimit: 32 }), s = await r.createContext(), i = s.global;
1014
+ if (!m) throw new Error(this.getIvmUnavailableMessage());
1015
+ const r = new m.Isolate({ memoryLimit: 32 }), s = await r.createContext(), i = s.global;
1033
1016
  try {
1034
1017
  await this.setupIsolateEnvironment(i, t);
1035
1018
  const c = /* @__PURE__ */ new Map(), h = this.createModuleResolver(
@@ -1039,7 +1022,7 @@ class A {
1039
1022
  n
1040
1023
  );
1041
1024
  let u;
1042
- return te(e) ? u = await this.evaluateESModule(
1025
+ return rt(e) ? u = await this.evaluateESModule(
1043
1026
  r,
1044
1027
  s,
1045
1028
  e,
@@ -1053,7 +1036,7 @@ class A {
1053
1036
  o
1054
1037
  ), this.deepClone(u);
1055
1038
  } catch (c) {
1056
- throw o.isCodeBlock ? new Q(e, c) : new X(e, c);
1039
+ throw o.isCodeBlock ? new De(e, c) : new Ae(e, c);
1057
1040
  } finally {
1058
1041
  s.release(), r.dispose();
1059
1042
  }
@@ -1062,18 +1045,18 @@ class A {
1062
1045
  * Setup the isolated VM environment with necessary host functions and data
1063
1046
  */
1064
1047
  static async setupIsolateEnvironment(e, t) {
1065
- if (!w) throw new Error("isolated-vm not available");
1066
- const n = new w.Callback(
1048
+ if (!m) throw new Error("isolated-vm not available");
1049
+ const n = new m.Callback(
1067
1050
  (...r) => console.log(...r)
1068
- ), o = new w.ExternalCopy({
1051
+ ), o = new m.ExternalCopy({
1069
1052
  log: n
1070
1053
  }).copyInto();
1071
1054
  await e.set("console", o);
1072
1055
  for (const [r, s] of Object.entries(t))
1073
1056
  typeof s == "function" ? await e.set(
1074
1057
  r,
1075
- new w.Callback(s)
1076
- ) : await e.set(r, new w.ExternalCopy(s).copyInto());
1058
+ new m.Callback(s)
1059
+ ) : await e.set(r, new m.ExternalCopy(s).copyInto());
1077
1060
  }
1078
1061
  /**
1079
1062
  * Create module resolver function for handling imports
@@ -1161,42 +1144,42 @@ class A {
1161
1144
  return typeof e > "u" ? e : JSON.parse(JSON.stringify(e));
1162
1145
  }
1163
1146
  }
1164
- class z {
1147
+ class R {
1165
1148
  /**
1166
1149
  * Creates standard bindings for workflow step execution
1167
1150
  */
1168
1151
  static createStandardBindings(e, t, n) {
1169
- const o = e.getBlue(), r = o.nodeToJson(t.payload, "simple"), s = L(r) ? r.toNumber() : r;
1152
+ const o = e.getBlue(), r = o.nodeToJson(t.payload, "simple"), s = J(r) ? r.toNumber() : r;
1170
1153
  return {
1171
1154
  document: (i) => {
1172
1155
  const c = e.get(i);
1173
- return L(c) ? c.toNumber() : S(c) ? o.nodeToJson(c, "original") : c;
1156
+ return J(c) ? c.toNumber() : S(c) ? o.nodeToJson(c, "original") : c;
1174
1157
  },
1175
1158
  event: s,
1176
1159
  steps: n
1177
1160
  };
1178
1161
  }
1179
1162
  }
1180
- const st = /^\$\{([\s\S]*)\}$/, at = /\$\{([\s\S]*?)\}/, T = (a) => typeof a != "string" ? !1 : st.test(a), J = (a) => typeof a != "string" ? !1 : at.test(a), de = (a) => {
1163
+ const st = /^\$\{([\s\S]*)\}$/, at = /\$\{([\s\S]*?)\}/, T = (a) => typeof a != "string" ? !1 : st.test(a), U = (a) => typeof a != "string" ? !1 : at.test(a), ce = (a) => {
1181
1164
  if (!T(a))
1182
1165
  throw new Error(`Invalid expression: ${a}`);
1183
1166
  return a.slice(2, -1);
1184
1167
  };
1185
1168
  class q {
1186
1169
  static createBindings(e, t, n) {
1187
- return z.createStandardBindings(e, t, n);
1170
+ return R.createStandardBindings(e, t, n);
1188
1171
  }
1189
1172
  static async evaluate(e, t, n, o) {
1190
1173
  const { coerceToString: r } = o;
1191
1174
  if (T(e)) {
1192
- const s = de(e), i = await A.evaluate({
1175
+ const s = ce(e), i = await A.evaluate({
1193
1176
  code: s,
1194
1177
  ctx: t,
1195
1178
  bindings: n
1196
1179
  });
1197
1180
  return r ? String(i ?? "") : i;
1198
1181
  }
1199
- if (J(e)) {
1182
+ if (U(e)) {
1200
1183
  const i = `\`${String(e).replace(/`/g, "\\`")}\``, c = await A.evaluate({
1201
1184
  code: i,
1202
1185
  ctx: t,
@@ -1207,7 +1190,7 @@ class q {
1207
1190
  return r ? String(e) : e;
1208
1191
  }
1209
1192
  }
1210
- function ne(a, e) {
1193
+ function Z(a, e) {
1211
1194
  const { op: t, path: n, val: o, from: r } = a;
1212
1195
  if ((t === "move" || t === "copy") && !r)
1213
1196
  throw new Error(`${t} operation requires 'from' path`);
@@ -1240,7 +1223,7 @@ class ct {
1240
1223
  n,
1241
1224
  t,
1242
1225
  r
1243
- ), c = re(e, {
1226
+ ), c = te(e, {
1244
1227
  op: "replace",
1245
1228
  path: "/changeset",
1246
1229
  val: i
@@ -1254,7 +1237,7 @@ class ct {
1254
1237
  r
1255
1238
  ), p = u.val;
1256
1239
  if ((u.op === "replace" || u.op === "add") && M(p)) {
1257
- const m = await this.evaluateChangeValue(
1240
+ const f = await this.evaluateChangeValue(
1258
1241
  p,
1259
1242
  n,
1260
1243
  t,
@@ -1263,13 +1246,13 @@ class ct {
1263
1246
  n.addPatch({
1264
1247
  op: u.op,
1265
1248
  path: d,
1266
- val: m
1249
+ val: f
1267
1250
  }), n.emitEvent({
1268
- payload: ne(
1251
+ payload: Z(
1269
1252
  {
1270
1253
  op: u.op,
1271
1254
  path: n.resolvePath(d),
1272
- val: s.nodeToJson(m, "original")
1255
+ val: s.nodeToJson(f, "original")
1273
1256
  },
1274
1257
  s
1275
1258
  ),
@@ -1277,7 +1260,7 @@ class ct {
1277
1260
  });
1278
1261
  }
1279
1262
  u.op === "remove" && (n.addPatch({ op: u.op, path: d }), n.emitEvent({
1280
- payload: ne(
1263
+ payload: Z(
1281
1264
  {
1282
1265
  op: u.op,
1283
1266
  path: n.resolvePath(d),
@@ -1292,10 +1275,10 @@ class ct {
1292
1275
  async evaluateChangeset(e, t, n, o) {
1293
1276
  const r = t.getBlue();
1294
1277
  if (T(e)) {
1295
- const s = de(e), i = await A.evaluate({
1278
+ const s = ce(e), i = await A.evaluate({
1296
1279
  code: s,
1297
1280
  ctx: t,
1298
- bindings: z.createStandardBindings(
1281
+ bindings: R.createStandardBindings(
1299
1282
  t,
1300
1283
  n,
1301
1284
  o
@@ -1309,7 +1292,7 @@ class ct {
1309
1292
  }
1310
1293
  async evaluateChangeValue(e, t, n, o) {
1311
1294
  const r = e.getValue(), s = t.getBlue();
1312
- if (T(r) || typeof r == "string" && J(r)) {
1295
+ if (T(r) || typeof r == "string" && U(r)) {
1313
1296
  const i = q.createBindings(
1314
1297
  t,
1315
1298
  n,
@@ -1326,7 +1309,7 @@ class ct {
1326
1309
  }
1327
1310
  async evaluateChangePath(e, t, n, o) {
1328
1311
  const r = q.createBindings(t, n, o);
1329
- if (T(e) || J(e)) {
1312
+ if (T(e) || U(e)) {
1330
1313
  const s = await q.evaluate(e, t, r, {
1331
1314
  coerceToString: !0
1332
1315
  });
@@ -1370,7 +1353,7 @@ class ut {
1370
1353
  const c = await A.evaluate({
1371
1354
  code: i.code,
1372
1355
  ctx: n,
1373
- bindings: z.createStandardBindings(n, t, r),
1356
+ bindings: R.createStandardBindings(n, t, r),
1374
1357
  options: {
1375
1358
  isCodeBlock: !0,
1376
1359
  timeout: 500
@@ -1393,7 +1376,7 @@ const ht = [
1393
1376
  new lt(),
1394
1377
  new ut()
1395
1378
  ];
1396
- class pe {
1379
+ class le {
1397
1380
  constructor(e = ht) {
1398
1381
  l(this, "contractType", "Sequential Workflow");
1399
1382
  l(this, "contractBlueId", y["Sequential Workflow"]);
@@ -1408,7 +1391,7 @@ class pe {
1408
1391
  supports(e, t, n) {
1409
1392
  const r = n.getBlue().nodeToSchemaOutput(
1410
1393
  t,
1411
- Ie
1394
+ Se
1412
1395
  ), s = this.isChannelNameMatch(e, r), i = this.isEventPatternMatch(e, t, n);
1413
1396
  return s && i;
1414
1397
  }
@@ -1427,8 +1410,8 @@ class pe {
1427
1410
  r
1428
1411
  );
1429
1412
  if (d !== void 0) {
1430
- const p = h.getName(), m = typeof p == "string" ? p : `Step${c + 1}`;
1431
- r[m] = d;
1413
+ const p = h.getName(), f = typeof p == "string" ? p : `Step${c + 1}`;
1414
+ r[f] = d;
1432
1415
  }
1433
1416
  await n.flush();
1434
1417
  }
@@ -1459,12 +1442,12 @@ class dt {
1459
1442
  l(this, "contractBlueId", y["Sequential Workflow Operation"]);
1460
1443
  l(this, "role", "handler");
1461
1444
  l(this, "sequentialWorkflowProcessor");
1462
- this.sequentialWorkflowProcessor = e || new pe();
1445
+ this.sequentialWorkflowProcessor = e || new le();
1463
1446
  }
1464
1447
  supports(e, t, n) {
1465
1448
  const s = n.getBlue().nodeToSchemaOutput(
1466
1449
  t,
1467
- Be
1450
+ Ce
1468
1451
  ).operation, i = e.channelName;
1469
1452
  return e.source === "channel" && M(i) && M(s) && i === s;
1470
1453
  }
@@ -1479,7 +1462,7 @@ class dt {
1479
1462
  }
1480
1463
  }
1481
1464
  }
1482
- const oe = (a) => P.isTypeOf(a.payload, O);
1465
+ const ee = (a) => P.isTypeOf(a.payload, O);
1483
1466
  class pt extends C {
1484
1467
  constructor() {
1485
1468
  super(...arguments);
@@ -1488,22 +1471,22 @@ class pt extends C {
1488
1471
  }
1489
1472
  supports(t, n, o) {
1490
1473
  var u;
1491
- if (!this.baseSupports(t) || !oe(t)) return !1;
1474
+ if (!this.baseSupports(t) || !ee(t)) return !1;
1492
1475
  const s = o.getBlue().nodeToSchemaOutput(
1493
1476
  t.payload,
1494
1477
  O
1495
- ), i = o.getBlue().nodeToSchemaOutput(n, Oe), c = (u = s.timeline) == null ? void 0 : u.timelineId;
1496
- return g(i.timelineId) && g(c) && c === i.timelineId;
1478
+ ), i = o.getBlue().nodeToSchemaOutput(n, Ne), c = (u = s.timeline) == null ? void 0 : u.timelineId;
1479
+ return E(i.timelineId) && E(c) && c === i.timelineId;
1497
1480
  }
1498
1481
  handle(t, n, o, r) {
1499
- oe(t) && o.emitEvent({
1482
+ ee(t) && o.emitEvent({
1500
1483
  payload: t.payload,
1501
1484
  channelName: r,
1502
1485
  source: "channel"
1503
1486
  });
1504
1487
  }
1505
1488
  }
1506
- class mt extends C {
1489
+ class ft extends C {
1507
1490
  constructor() {
1508
1491
  super(...arguments);
1509
1492
  l(this, "contractType", "Triggered Event Channel");
@@ -1520,23 +1503,23 @@ class mt extends C {
1520
1503
  });
1521
1504
  }
1522
1505
  }
1523
- const ft = [
1524
- new rt(),
1506
+ const mt = [
1507
+ new nt(),
1525
1508
  // channels
1526
- new Ye(),
1527
1509
  new Ge(),
1510
+ new Qe(),
1528
1511
  new pt(),
1529
- new tt(),
1530
- new nt(),
1531
- new Ke(),
1512
+ new Ze(),
1532
1513
  new et(),
1533
- new mt(),
1534
- new ot(),
1514
+ new Xe(),
1515
+ new Ye(),
1516
+ new ft(),
1517
+ new tt(),
1535
1518
  // sequential workflows
1536
- new pe(),
1519
+ new le(),
1537
1520
  new dt(),
1538
1521
  // markers
1539
- new Ze()
1522
+ new Ke()
1540
1523
  ];
1541
1524
  class bt {
1542
1525
  /**
@@ -1544,21 +1527,21 @@ class bt {
1544
1527
  *
1545
1528
  * @param processors - Initial list of processors to register
1546
1529
  */
1547
- constructor(e, t = ft) {
1530
+ constructor(e, t = mt) {
1548
1531
  l(this, "taskCounter", 0);
1549
1532
  l(this, "eventCounter", 0);
1550
1533
  l(this, "registry");
1551
1534
  l(this, "queue");
1552
1535
  l(this, "router");
1553
- l(this, "checkpointCache", new Qe());
1554
- this.blue = e, this.registry = new Fe(t), this.queue = new Le(), this.router = new ze(
1536
+ l(this, "checkpointCache", new Fe());
1537
+ this.blue = e, this.registry = new We(t), this.queue = new _e(), this.router = new Ue(
1555
1538
  this.blue,
1556
1539
  this.registry,
1557
1540
  this.queue,
1558
1541
  () => ++this.taskCounter,
1559
1542
  () => ++this.eventCounter
1560
1543
  ), this.register(
1561
- new Xe(this.checkpointCache),
1544
+ new He(this.checkpointCache),
1562
1545
  9999
1563
1546
  );
1564
1547
  }
@@ -1578,7 +1561,7 @@ class bt {
1578
1561
  * @returns Processing result with final state and emitted events
1579
1562
  */
1580
1563
  async initialize(e) {
1581
- let t = Y(I(e), this.blue);
1564
+ let t = G(I(e), this.blue);
1582
1565
  const n = {
1583
1566
  payload: it(this.blue),
1584
1567
  source: "internal",
@@ -1586,7 +1569,7 @@ class bt {
1586
1569
  }, o = [n.payload];
1587
1570
  await this.router.route(t, [], n, 0);
1588
1571
  const r = await this.drainQueue(t);
1589
- return t = r.state, o.push(...r.emitted), t = He(t, this.blue), { state: $(t), emitted: o };
1572
+ return t = r.state, o.push(...r.emitted), t = Re(t, this.blue), { state: $(t), emitted: o };
1590
1573
  }
1591
1574
  /**
1592
1575
  * Processes a batch of events against the document
@@ -1596,9 +1579,9 @@ class bt {
1596
1579
  * @returns Processing result with final state and emitted events
1597
1580
  */
1598
1581
  async processEvents(e, t) {
1599
- let n = Y(I(e), this.blue);
1582
+ let n = G(I(e), this.blue);
1600
1583
  const o = [];
1601
- if (!ue(n, this.blue))
1584
+ if (!ie(n, this.blue))
1602
1585
  throw new Error("Document is not initialized");
1603
1586
  for (const r of t)
1604
1587
  try {
@@ -1607,7 +1590,7 @@ class bt {
1607
1590
  const i = await this.drainQueue(n);
1608
1591
  n = i.state, o.push(...i.emitted);
1609
1592
  const c = this.checkpointCache.flush(n);
1610
- c.length && (n = G(n, c));
1593
+ c.length && (n = Q(n, c));
1611
1594
  } finally {
1612
1595
  this.checkpointCache.clear();
1613
1596
  }
@@ -1626,50 +1609,50 @@ class bt {
1626
1609
  throw new Error("Possible cycle – too many iterations");
1627
1610
  const i = this.queue.pop(), { nodePath: c, contractName: h, contractNode: u, event: d } = i, p = t.get(c);
1628
1611
  if (!S(p) || !((s = p.getContracts()) != null && s[h]) || !u.getType()) continue;
1629
- const m = this.registry.get(u.getType());
1630
- if (!m) {
1612
+ const f = this.registry.get(u.getType());
1613
+ if (!f) {
1631
1614
  console.warn(`No processor registered for contract: ${h}`);
1632
1615
  continue;
1633
1616
  }
1634
- const v = new ie(
1617
+ const v = new re(
1635
1618
  () => t,
1636
1619
  i,
1637
1620
  this.blue,
1638
- async (E) => {
1639
- for (const f of E)
1640
- if (f.kind === "patch") {
1641
- const D = U(
1621
+ async (w) => {
1622
+ for (const g of w)
1623
+ if (g.kind === "patch") {
1624
+ const D = z(
1642
1625
  t,
1643
1626
  this.blue
1644
1627
  );
1645
1628
  for (const N of D) {
1646
- const fe = f.patch.op === "move" || f.patch.op === "copy" ? [f.patch.from, f.patch.path] : [f.patch.path], R = v.getNodePath(), ye = fe.some(
1647
- (Ee) => K(Ee, N.absPath)
1648
- ), ge = K(
1649
- R,
1629
+ const he = g.patch.op === "move" || g.patch.op === "copy" ? [g.patch.from, g.patch.path] : [g.patch.path], H = v.getNodePath(), de = he.some(
1630
+ (fe) => X(fe, N.absPath)
1631
+ ), pe = X(
1632
+ H,
1650
1633
  N.absPath
1651
1634
  );
1652
- if (ye && !ge)
1653
- throw new le(
1654
- f.patch,
1635
+ if (de && !pe)
1636
+ throw new ae(
1637
+ g.patch,
1655
1638
  N.absPath,
1656
- R
1639
+ H
1657
1640
  );
1658
1641
  }
1659
1642
  try {
1660
- t = G(t, [f.patch]);
1643
+ t = Q(t, [g.patch]);
1661
1644
  } catch (N) {
1662
- throw Re(h, d, N), N;
1645
+ throw ze(h, d, N), N;
1663
1646
  }
1664
- } else f.kind === "event" && (n.push(f.event.payload), await this.router.route(t, [], f.event, i.key[5]));
1647
+ } else g.kind === "event" && (n.push(g.event.payload), await this.router.route(t, [], g.event, i.key[5]));
1665
1648
  }
1666
1649
  );
1667
- await m.handle(d, u, v, h), await v.flush();
1650
+ await f.handle(d, u, v, h), await v.flush();
1668
1651
  }
1669
1652
  return { state: t, emitted: n };
1670
1653
  }
1671
1654
  }
1672
- class me {
1655
+ class ue {
1673
1656
  process(e, t) {
1674
1657
  const n = t.getValue();
1675
1658
  if (T(n)) {
@@ -1692,12 +1675,12 @@ class me {
1692
1675
  }
1693
1676
  const Pt = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1694
1677
  __proto__: null,
1695
- ExpressionPreserver: me
1678
+ ExpressionPreserver: ue
1696
1679
  }, Symbol.toStringTag, { value: "Module" }));
1697
1680
  function St() {
1698
1681
  return new k.SequentialMergingProcessor([
1699
1682
  new k.ValuePropagator(),
1700
- new me(),
1683
+ new ue(),
1701
1684
  new k.TypeAssigner(),
1702
1685
  new k.ListProcessor(),
1703
1686
  new k.DictionaryProcessor(),
@@ -1706,25 +1689,25 @@ function St() {
1706
1689
  }
1707
1690
  export {
1708
1691
  bt as BlueDocumentProcessor,
1709
- Xe as ChannelEventCheckpointProcessor,
1710
- Q as CodeBlockEvaluationError,
1711
- Ke as CompositeTimelineChannelProcessor,
1712
- Ge as DocumentUpdateChannelProcessor,
1713
- le as EmbeddedDocumentModificationError,
1714
- Ye as EmbeddedNodeChannelProcessor,
1715
- X as ExpressionEvaluationError,
1716
- Ze as InitializedMarkerProcessor,
1717
- et as LifecycleEventChannelProcessor,
1692
+ He as ChannelEventCheckpointProcessor,
1693
+ De as CodeBlockEvaluationError,
1694
+ Xe as CompositeTimelineChannelProcessor,
1695
+ Qe as DocumentUpdateChannelProcessor,
1696
+ ae as EmbeddedDocumentModificationError,
1697
+ Ge as EmbeddedNodeChannelProcessor,
1698
+ Ae as ExpressionEvaluationError,
1699
+ Ke as InitializedMarkerProcessor,
1700
+ Ye as LifecycleEventChannelProcessor,
1718
1701
  Pt as MergingProcessors,
1719
- nt as MyOSAgentChannelProcessor,
1720
- tt as MyOSTimelineChannelProcessor,
1721
- ot as OperationProcessor,
1722
- ce as PatchApplicationError,
1723
- rt as ProcessEmbeddedProcessor,
1702
+ et as MyOSAgentChannelProcessor,
1703
+ Ze as MyOSTimelineChannelProcessor,
1704
+ tt as OperationProcessor,
1705
+ se as PatchApplicationError,
1706
+ nt as ProcessEmbeddedProcessor,
1724
1707
  dt as SequentialWorkflowOperationProcessor,
1725
- pe as SequentialWorkflowProcessor,
1708
+ le as SequentialWorkflowProcessor,
1726
1709
  pt as TimelineChannelProcessor,
1727
- mt as TriggeredEventChannelProcessor,
1728
- U as collectEmbeddedPathSpecs,
1710
+ ft as TriggeredEventChannelProcessor,
1711
+ z as collectEmbeddedPathSpecs,
1729
1712
  St as createDefaultMergingProcessor
1730
1713
  };
@@ -19,6 +19,7 @@ export interface VMBindings {
19
19
  */
20
20
  export declare class ExpressionEvaluator {
21
21
  private static getIvmUnavailableMessage;
22
+ private static ensureIvm;
22
23
  /**
23
24
  * Main evaluation method - chooses between secure and simple evaluation strategies
24
25
  */
@@ -31,11 +32,6 @@ export declare class ExpressionEvaluator {
31
32
  timeout?: number;
32
33
  };
33
34
  }): Promise<unknown>;
34
- /**
35
- * Fallback evaluation using Node's Function constructor
36
- * Used when isolated-vm is not available
37
- */
38
- private static evaluateSimple;
39
35
  /**
40
36
  * Secure evaluation using isolated-vm with support for ES modules
41
37
  */
@@ -1 +1 @@
1
- {"version":3,"file":"ExpressionEvaluator.d.ts","sourceRoot":"","sources":["../../../../src/processors/SequentialWorkflowProcessor/utils/ExpressionEvaluator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AASnD;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;IACrC,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC;AAuBD;;;;;;;;GAQG;AACH,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,MAAM,CAAC,wBAAwB;IA6BvC;;OAEG;WACU,QAAQ,CAAC,EACpB,IAAI,EACJ,GAAG,EACH,QAAa,EACb,OAAY,GACb,EAAE;QACD,IAAI,EAAE,MAAM,CAAC;QACb,GAAG,EAAE,iBAAiB,CAAC;QACvB,QAAQ,CAAC,EAAE,UAAU,CAAC;QACtB,OAAO,CAAC,EAAE;YAAE,WAAW,CAAC,EAAE,OAAO,CAAC;YAAC,OAAO,CAAC,EAAE,MAAM,CAAA;SAAE,CAAC;KACvD,GAAG,OAAO,CAAC,OAAO,CAAC;IAOpB;;;OAGG;mBACkB,cAAc;IAqCnC;;OAEG;mBACkB,cAAc;IAuDnC;;OAEG;mBACkB,uBAAuB;IA6B5C;;OAEG;IACH,OAAO,CAAC,MAAM,CAAC,oBAAoB;IAqDnC;;OAEG;mBACkB,oBAAoB;IAwBzC;;OAEG;mBACkB,gBAAgB;IA2CrC;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,SAAS;CAMzB"}
1
+ {"version":3,"file":"ExpressionEvaluator.d.ts","sourceRoot":"","sources":["../../../../src/processors/SequentialWorkflowProcessor/utils/ExpressionEvaluator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AASnD;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;IACrC,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC;AAuBD;;;;;;;;GAQG;AACH,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,MAAM,CAAC,wBAAwB;mBA6BlB,SAAS;IAqB9B;;OAEG;WACU,QAAQ,CAAC,EACpB,IAAI,EACJ,GAAG,EACH,QAAa,EACb,OAAY,GACb,EAAE;QACD,IAAI,EAAE,MAAM,CAAC;QACb,GAAG,EAAE,iBAAiB,CAAC;QACvB,QAAQ,CAAC,EAAE,UAAU,CAAC;QACtB,OAAO,CAAC,EAAE;YAAE,WAAW,CAAC,EAAE,OAAO,CAAC;YAAC,OAAO,CAAC,EAAE,MAAM,CAAA;SAAE,CAAC;KACvD,GAAG,OAAO,CAAC,OAAO,CAAC;IASpB;;OAEG;mBACkB,cAAc;IAuDnC;;OAEG;mBACkB,uBAAuB;IA6B5C;;OAEG;IACH,OAAO,CAAC,MAAM,CAAC,oBAAoB;IAqDnC;;OAEG;mBACkB,oBAAoB;IAwBzC;;OAEG;mBACkB,gBAAgB;IA2CrC;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,SAAS;CAMzB"}
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@blue-labs/document-processor",
3
- "version": "1.33.2",
3
+ "version": "1.33.3",
4
4
  "dependencies": {
5
- "@blue-labs/language": "1.33.2",
6
- "@blue-labs/shared-utils": "1.33.2",
5
+ "@blue-labs/language": "1.33.3",
6
+ "@blue-labs/shared-utils": "1.33.3",
7
7
  "isolated-vm": "^5.0.4"
8
8
  },
9
9
  "main": "./dist/index.js",