@blue-labs/document-processor 1.33.0 → 1.33.1

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,8 +1,9 @@
1
- "use strict";var ve=Object.defineProperty;var we=(a,e,t)=>e in a?ve(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var l=(a,e,t)=>we(a,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=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 G{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 V extends Error{constructor(e,t){super(`Cannot apply patch ${JSON.stringify(e)}`),this.patch=e,this.cause=t,this.name="PatchApplicationError"}}class _ 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 K extends Error{constructor(e,t){super(`Failed to evaluate expression "${e}"`),this.code=e,this.cause=t,this.name="ExpressionEvaluationError"}}class Y 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,d.ProcessEmbeddedSchema)){const h=e.nodeToSchemaOutput(s,d.ProcessEmbeddedSchema).paths??[];for(const u of h)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 U(a,e){return a===e||a.startsWith(e.endsWith("/")?e:e+"/")}function z(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 V(n,o)}return B(t)}function w(a){return a!=null}function N(a){return a instanceof m.BlueNode}class Te{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],be=(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 Se{constructor(){l(this,"queue");this.queue=new Te([],be)}push(e){this.queue.push(e)}pop(){return this.queue.pop()}get length(){return this.queue.length}}class Ce{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 j=O;function Ne(a){return Object.entries(a.getContracts()??{})}const Ie=64;class ke{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 j}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 h=n.dispatchPath.split("/").filter(Boolean),u={...n};return delete u.dispatchPath,this.route(e,h,u,o,r)}if(n.source==="channel"&&n.originNodePath&&n.originNodePath!=="/"){const h=((c=n.originNodePath)==null?void 0:c.split("/").filter(Boolean))??[];return this.route(e,h,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[h,u]of Ne(n)){if(!u.getType())continue;const p=this.registry.get(u.getType());if(!p){console.warn(`No processor registered for contract: ${h}`);continue}const f={nodePath:o,contractName:h,contractNode:u,event:r},g=new G(()=>t,f,this.blue);if(p.supports(r,u,g,h))switch(p.role){case"adapter":await this.processAdapter({cp:p,event:r,contractNode:u,ctx:g,contractName:h,doc:t,afterTaskId:s,inlineDepth:c});break;case"handler":this.scheduleHandler({contractNode:u,contractName:h,nodePath:o,event:r,depth:i.length,afterTaskId:s});break}}}async processAdapter(e){var P;const{cp:t,event:n,contractNode:o,ctx:r,contractName:s,doc:i,afterTaskId:c,inlineDepth:h}=e;if(h>=Ie)throw new Error("Adapter recursion limit reached");const u=this.traceManager.addHop(n,((P=r.getTaskInfo())==null?void 0:P.nodePath)??"",s);await t.handle(u,o,r,s);const p=await r.flush();if(p.find(T=>T.kind==="patch"))throw new Error(`Contract "${s}" (adapter) attempted to patch the document`);const g=p.filter(T=>T.kind==="event");for(const T of g)await this.route(i,[],T.event,c,h+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 h=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 P=Pe(s,g,h,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 T=this.traceManager.addHop(r,o,n);this.queue.push({key:P,nodePath:o,contractName:n,contractNode:t,event:T})}shouldSkipForChannel(e,t){return e.source==="channel"&&!!e.originNodePath&&e.originNodePath!==t}}const Be=(a,e,t)=>{(t instanceof V||t instanceof _)&&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,d.ChannelEventCheckpointSchema))&&o.addContract("checkpoint",e.jsonValueToNode({type:{name:"Channel Event Checkpoint",blueId:d.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 Oe(a,e){const t=M(a);return N(t)&&(Z(t,e)||t.addContract("initialized",e.jsonValueToNode({type:{name:"Initialized Marker",blueId:d.blueIds["Initialized Marker"]}}))),B(t)}function Z(a,e){const t=a.getContracts();return Object.values(t??{}).some(n=>e.isTypeOf(n,d.InitializedMarkerSchema,{checkSchemaExtensions:!0}))}class ee{constructor(e){l(this,"contractType","Channel Event Checkpoint");l(this,"contractBlueId",d.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 F=(a,e)=>a.get(e)!==void 0;class Me{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`;F(e,s)?t.push({op:F(e,i)?"replace":"add",path:i,val:r}):t.push({op:"add",path:s,val:{blueId:r}})}return t}clear(){this.firstSeen.clear()}}class te{constructor(){l(this,"contractType","Composite Timeline Channel");l(this,"contractBlueId",d.blueIds["Composite Timeline Channel"]);l(this,"role","adapter")}supports(e,t,n){const o=n.getBlue().nodeToSchemaOutput(t,d.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 ne extends I{constructor(){super(...arguments);l(this,"contractType","Document Update Channel");l(this,"contractBlueId",d.blueIds["Document Update Channel"])}supports(t,n,o){if(!this.baseSupports(t)||t.emissionType!=="update")return!1;const r=o.getBlue().nodeToSchemaOutput(n,d.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 oe extends I{constructor(){super(...arguments);l(this,"contractType","Embedded Node Channel");l(this,"contractBlueId",d.blueIds["Embedded Node Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;const r=o.getBlue().nodeToSchemaOutput(n,d.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,d.EmbeddedNodeChannelSchema),{originNodePath:i,payload:c}=t;w(s.path)&&i===o.resolvePath(s.path)&&o.emitEvent({payload:c,channelName:r,source:"channel"})}}class re{constructor(){l(this,"contractType","Initialized Marker");l(this,"contractBlueId",d.blueIds["Initialized Marker"]);l(this,"role","marker")}supports(){return!1}handle(){}}class se extends I{constructor(){super(...arguments);l(this,"contractType","Lifecycle Event Channel");l(this,"contractBlueId",d.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,d.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 R=(a,e)=>{const t=e.getBlue();return t.isTypeOf(a.payload,d.TimelineEntrySchema)||t.isTypeOf(a.payload,C.MyOSTimelineEntrySchema)};class ae 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)||!R(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){R(t,o)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class ie 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),h=i.nodeToJson(r);return v.deepContains(c,h)}catch(i){return console.warn("Error during event pattern matching:",i),!1}}}class ce{constructor(){l(this,"contractType","Operation");l(this,"contractBlueId",d.blueIds.Operation);l(this,"role","adapter")}supports(e,t,n,o){const s=n.getBlue().nodeToSchemaOutput(t,d.OperationSchema),i=this.parseEventPayload(e,n),c=this.isOperationNameMatch(i,o),h=this.isOperationChannelMatch(e,s),u=this.isRequestPatternMatch(i,s,n);return c&&h&&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,d.TimelineEntrySchema,{checkSchemaExtensions:!0})){const o=n.nodeToSchemaOutput(e.payload,d.TimelineEntrySchema);if(o.message)return n.nodeToSchemaOutput(o.message,d.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 le{constructor(){l(this,"contractType","Process Embedded");l(this,"role","adapter");l(this,"contractBlueId",d.blueIds["Process Embedded"])}supports(e){return e.source!=="channel"}handle(e,t,n){const o=n.getBlue().nodeToSchemaOutput(t,d.ProcessEmbeddedSchema);for(const r of o.paths??[])n.emitEvent({...e,dispatchPath:n.resolvePath(r)})}}let E=null;try{E=require("isolated-vm")}catch{E=null}function qe(a){return/\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(a)||/\bexport\s+/.test(a)}class ${static async evaluate({code:e,ctx:t,bindings:n={},options:o={}}){if(!E)throw new Error("isolated-vm is required for expression evaluation");return this.evaluateSecure(e,n,t,o)}static async evaluateSecure(e,t,n,o={}){if(!E)throw new Error("isolated-vm not available");const r=new E.Isolate({memoryLimit:32}),s=await r.createContext(),i=s.global;try{await this.setupIsolateEnvironment(i,t);const c=new Map,h=this.createModuleResolver(r,s,c,n);let u;return qe(e)?u=await this.evaluateESModule(r,s,e,o,h):u=await this.evaluateSimpleScript(r,s,e,t,o),this.deepClone(u)}catch(c){throw o.isCodeBlock?new Y(e,c):new K(e,c)}finally{s.release(),r.dispose()}}static async setupIsolateEnvironment(e,t){if(!E)throw new Error("isolated-vm not available");const n=new E.Callback((...r)=>console.log(...r)),o=new E.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 E.Callback(s)):await e.set(r,new E.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),h=await e.compileModule(c);return n.set(r,h),await h.instantiate(t,this.createModuleResolver(e,t,n,o)),h}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 h=/^\s*(import\s.+?;|export\s.+?;)/gm,u=(n.match(h)||[]).join(`
2
- `),p=n.replace(h,"").trim();s=`
1
+ "use strict";var ve=Object.defineProperty;var we=(a,e,t)=>e in a?ve(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var l=(a,e,t)=>we(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 G{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 V extends Error{constructor(e,t){super(`Cannot apply patch ${JSON.stringify(e)}`),this.patch=e,this.cause=t,this.name="PatchApplicationError"}}class _ 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 K extends Error{constructor(e,t){super(`Failed to evaluate expression "${e}"`),this.code=e,this.cause=t,this.name="ExpressionEvaluationError"}}class Y 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 U(a,e){return a===e||a.startsWith(e.endsWith("/")?e:e+"/")}function z(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 V(n,o)}return B(t)}function w(a){return a!=null}function N(a){return a instanceof m.BlueNode}class be{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 Te=(a,e,t,n,o,r)=>[-a,e,t,n,o,r],Pe=(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 Se{constructor(){l(this,"queue");this.queue=new be([],Pe)}push(e){this.queue.push(e)}pop(){return this.queue.pop()}get length(){return this.queue.length}}class Ce{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 j=O;function Ne(a){return Object.entries(a.getContracts()??{})}const Ie=64;class ke{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 j}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 Ne(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 G(()=>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>=Ie)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=Te(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 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 Be=(a,e,t)=>{(t instanceof V||t instanceof _)&&console.error(`[Blue] Failed to apply patches for contract "${a}" on event ${JSON.stringify(e)}`,t)};function R(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 Oe(a,e){const t=M(a);return N(t)&&(Z(t,e)||t.addContract("initialized",e.jsonValueToNode({type:{name:"Initialized Marker",blueId:h.blueIds["Initialized Marker"]}}))),B(t)}function Z(a,e){const t=a.getContracts();return Object.values(t??{}).some(n=>e.isTypeOf(n,h.InitializedMarkerSchema,{checkSchemaExtensions:!0}))}class ee{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 H=(a,e)=>a.get(e)!==void 0;class Me{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`;H(e,s)?t.push({op:H(e,i)?"replace":"add",path:i,val:r}):t.push({op:"add",path:s,val:{blueId:r}})}return t}clear(){this.firstSeen.clear()}}class te{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 ne 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 oe 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 re{constructor(){l(this,"contractType","Initialized Marker");l(this,"contractBlueId",h.blueIds["Initialized Marker"]);l(this,"role","marker")}supports(){return!1}handle(){}}class se 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 F=(a,e)=>{const t=e.getBlue();return t.isTypeOf(a.payload,h.TimelineEntrySchema)||t.isTypeOf(a.payload,C.MyOSTimelineEntrySchema)};class ae 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)||!F(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){F(t,o)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class ie 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 ce{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 le{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)})}}let E=null;function qe(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 ensureIvmLoaded(){var t;if(!(E||!(typeof process<"u"&&((t=process.versions)!=null&&t.node)))){try{if(typeof require=="function"){E=require("isolated-vm");return}}catch{}try{const r=await import("isolated-vm").catch(()=>null);E=(r==null?void 0:r.default)??r}catch{}}}static async evaluate({code:e,ctx:t,bindings:n={},options:o={}}){if(await this.ensureIvmLoaded(),!E)throw new Error(this.getIvmUnavailableMessage());return this.evaluateSecure(e,n,t,o)}static async evaluateSecure(e,t,n,o={}){if(!E)throw new Error(this.getIvmUnavailableMessage());const r=new E.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 qe(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 Y(e,c):new K(e,c)}finally{s.release(),r.dispose()}}static async setupIsolateEnvironment(e,t){if(!E)throw new Error("isolated-vm not available");const n=new E.Callback((...r)=>console.log(...r)),o=new E.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 E.Callback(s)):await e.set(r,new E.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
+ `),p=n.replace(d,"").trim();s=`
3
4
  ${u}
4
5
  const run = function() {
5
6
  ${p}
6
7
  };
7
8
  export default run();
8
- `}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 W{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 $e=/^\$\{([\s\S]*)\}$/,De=/\$\{([\s\S]*?)\}/,b=a=>typeof a!="string"?!1:$e.test(a),x=a=>typeof a!="string"?!1:De.test(a),ue=a=>{if(!b(a))throw new Error(`Invalid expression: ${a}`);return a.slice(2,-1)};class q{static createBindings(e,t,n){return W.createStandardBindings(e,t,n)}static async evaluate(e,t,n,o){const{coerceToString:r}=o;if(b(e)){const s=ue(e),i=await $.evaluate({code:s,ctx:t,bindings:n});return r?String(i??""):i}if(x(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 X(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 Ae(a){return a.jsonValueToNode({type:"Document Processing Initiated"})}class je{constructor(){l(this,"stepType","Update Document")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,d.UpdateDocumentSchema)}async execute(e,t,n,o,r){const s=n.getBlue();if(!m.BlueNodeTypeSchema.isTypeOf(e,d.UpdateDocumentSchema))return;const i=await this.evaluateChangeset(e.get("/changeset"),n,t,r),c=m.applyBlueNodePatch(e,{op:"replace",path:"/changeset",val:i}),h=n.getBlue().nodeToSchemaOutput(c,d.UpdateDocumentSchema);for(const u of h.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:X({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:X({op:u.op,path:n.resolvePath(p),val:null},s),emissionType:"update"}))}}async evaluateChangeset(e,t,n,o){const r=t.getBlue();if(b(e)){const s=ue(e),i=await $.evaluate({code:s,ctx:t,bindings:W.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(b(r)||typeof r=="string"&&x(r)){const i=q.createBindings(t,n,o),c=await q.evaluate(String(r),t,i,{coerceToString:!b(r)});return s.jsonValueToNode(c??null)}return e}async evaluateChangePath(e,t,n,o){const r=q.createBindings(t,n,o);if(b(e)||x(e)){const s=await q.evaluate(e,t,r,{coerceToString:!0});return String(s??"")}return e}}class xe{constructor(){l(this,"stepType","Trigger Event")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,d.TriggerEventSchema)}async execute(e,t,n){const o=n.getBlue();if(!m.BlueNodeTypeSchema.isTypeOf(e,d.TriggerEventSchema))return;const r=o.nodeToSchemaOutput(e,d.TriggerEventSchema);r.event&&n.emitEvent({payload:r.event,emissionType:"triggered"})}}class Ve{constructor(){l(this,"stepType","JavaScript Code")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,d.JavaScriptCodeSchema)}async execute(e,t,n,o,r){if(!m.BlueNodeTypeSchema.isTypeOf(e,d.JavaScriptCodeSchema))return;const s=n.getBlue(),i=s.nodeToSchemaOutput(e,d.JavaScriptCodeSchema);if(!i.code)throw new Error("JavaScript code is required");const c=await $.evaluate({code:i.code,ctx:n,bindings:W.createStandardBindings(n,t,r),options:{isCodeBlock:!0,timeout:500}});if(c&&typeof c=="object"&&"events"in c){const h=c;if(Array.isArray(h.events))for(const u of h.events)n.emitEvent({payload:s.jsonValueToNode(u),emissionType:"triggered"})}return c}}const _e=[new je,new xe,new Ve];class J{constructor(e=_e){l(this,"contractType","Sequential Workflow");l(this,"contractBlueId",d.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,d.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,h]of(s??[]).entries()){const u=this.executors.find(f=>f.supports(h));if(!u)throw new Error(`Unsupported workflow step type "${h.getType()}"`);const p=await u.execute(h,e,n,o,r);if(p!==void 0){const f=h.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 he{constructor(e){l(this,"contractType","Sequential Workflow Operation");l(this,"contractBlueId",d.blueIds["Sequential Workflow Operation"]);l(this,"role","handler");l(this,"sequentialWorkflowProcessor");this.sequentialWorkflowProcessor=e||new J}supports(e,t,n){const s=n.getBlue().nodeToSchemaOutput(t,d.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 Q=a=>m.BlueNodeTypeSchema.isTypeOf(a.payload,d.TimelineEntrySchema);class de extends I{constructor(){super(...arguments);l(this,"contractType","Timeline Channel");l(this,"contractBlueId",d.blueIds["Timeline Channel"])}supports(t,n,o){var u;if(!this.baseSupports(t)||!Q(t))return!1;const s=o.getBlue().nodeToSchemaOutput(t.payload,d.TimelineEntrySchema),i=o.getBlue().nodeToSchemaOutput(n,d.TimelineChannelSchema),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.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class pe extends I{constructor(){super(...arguments);l(this,"contractType","Triggered Event Channel");l(this,"contractBlueId",d.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 We=[new le,new oe,new ne,new de,new ae,new ie,new te,new se,new pe,new ce,new J,new he,new re];class Je{constructor(e,t=We){l(this,"taskCounter",0);l(this,"eventCounter",0);l(this,"registry");l(this,"queue");l(this,"router");l(this,"checkpointCache",new Me);this.blue=e,this.registry=new Ce(t),this.queue=new Se,this.router=new ke(this.blue,this.registry,this.queue,()=>++this.taskCounter,()=>++this.eventCounter),this.register(new ee(this.checkpointCache),9999)}register(e,t){this.registry.register(e,t)}async initialize(e){let t=H(B(e),this.blue);const n={payload:Ae(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=Oe(t,this.blue),{state:M(t),emitted:o}}async processEvents(e,t){let n=H(B(e),this.blue);const o=[];if(!Z(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=z(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:h,contractNode:u,event:p}=i,f=t.get(c);if(!N(f)||!((s=f.getContracts())!=null&&s[h])||!u.getType())continue;const g=this.registry.get(u.getType());if(!g){console.warn(`No processor registered for contract: ${h}`);continue}const P=new G(()=>t,i,this.blue,async T=>{for(const y of T)if(y.kind==="patch"){const A=D(t,this.blue);for(const k of A){const fe=y.patch.op==="move"||y.patch.op==="copy"?[y.patch.from,y.patch.path]:[y.patch.path],L=P.getNodePath(),ge=fe.some(Ee=>U(Ee,k.absPath)),ye=U(L,k.absPath);if(ge&&!ye)throw new _(y.patch,k.absPath,L)}try{t=z(t,[y.patch])}catch(k){throw Be(h,p,k),k}}else y.kind==="event"&&(n.push(y.event.payload),await this.router.route(t,[],y.event,i.key[5]))});await g.handle(p,u,P,h),await P.flush()}return{state:t,emitted:n}}}class me{process(e,t){const n=t.getValue();if(b(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(b(n)&&e.getValue()!==n&&n!==void 0){const o=e.clone();return o.setValue(n),o}return e}}const Le=Object.freeze(Object.defineProperty({__proto__:null,ExpressionPreserver:me},Symbol.toStringTag,{value:"Module"}));function Ue(){return new m.MergingProcessors.SequentialMergingProcessor([new m.MergingProcessors.ValuePropagator,new me,new m.MergingProcessors.TypeAssigner,new m.MergingProcessors.ListProcessor,new m.MergingProcessors.DictionaryProcessor,new m.MergingProcessors.BasicTypesVerifier])}exports.BlueDocumentProcessor=Je;exports.ChannelEventCheckpointProcessor=ee;exports.CodeBlockEvaluationError=Y;exports.CompositeTimelineChannelProcessor=te;exports.DocumentUpdateChannelProcessor=ne;exports.EmbeddedDocumentModificationError=_;exports.EmbeddedNodeChannelProcessor=oe;exports.ExpressionEvaluationError=K;exports.InitializedMarkerProcessor=re;exports.LifecycleEventChannelProcessor=se;exports.MergingProcessors=Le;exports.MyOSAgentChannelProcessor=ie;exports.MyOSTimelineChannelProcessor=ae;exports.OperationProcessor=ce;exports.PatchApplicationError=V;exports.ProcessEmbeddedProcessor=le;exports.SequentialWorkflowOperationProcessor=he;exports.SequentialWorkflowProcessor=J;exports.TimelineChannelProcessor=de;exports.TriggeredEventChannelProcessor=pe;exports.collectEmbeddedPathSpecs=D;exports.createDefaultMergingProcessor=Ue;
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 W{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 $e=/^\$\{([\s\S]*)\}$/,De=/\$\{([\s\S]*?)\}/,P=a=>typeof a!="string"?!1:$e.test(a),x=a=>typeof a!="string"?!1:De.test(a),ue=a=>{if(!P(a))throw new Error(`Invalid expression: ${a}`);return a.slice(2,-1)};class q{static createBindings(e,t,n){return W.createStandardBindings(e,t,n)}static async evaluate(e,t,n,o){const{coerceToString:r}=o;if(P(e)){const s=ue(e),i=await $.evaluate({code:s,ctx:t,bindings:n});return r?String(i??""):i}if(x(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 X(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 Ae(a){return a.jsonValueToNode({type:"Document Processing Initiated"})}class je{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:X({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:X({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=ue(e),i=await $.evaluate({code:s,ctx:t,bindings:W.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"&&x(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)||x(e)){const s=await q.evaluate(e,t,r,{coerceToString:!0});return String(s??"")}return e}}class xe{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 Ve{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:W.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 _e=[new je,new xe,new Ve];class J{constructor(e=_e){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 de{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 J}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 Q=a=>m.BlueNodeTypeSchema.isTypeOf(a.payload,h.TimelineEntrySchema);class he 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)||!Q(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){Q(t)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class pe 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 We=[new le,new oe,new ne,new he,new ae,new ie,new te,new se,new pe,new ce,new J,new de,new re];class Je{constructor(e,t=We){l(this,"taskCounter",0);l(this,"eventCounter",0);l(this,"registry");l(this,"queue");l(this,"router");l(this,"checkpointCache",new Me);this.blue=e,this.registry=new Ce(t),this.queue=new Se,this.router=new ke(this.blue,this.registry,this.queue,()=>++this.taskCounter,()=>++this.eventCounter),this.register(new ee(this.checkpointCache),9999)}register(e,t){this.registry.register(e,t)}async initialize(e){let t=R(B(e),this.blue);const n={payload:Ae(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=Oe(t,this.blue),{state:M(t),emitted:o}}async processEvents(e,t){let n=R(B(e),this.blue);const o=[];if(!Z(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=z(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 G(()=>t,i,this.blue,async b=>{for(const y of b)if(y.kind==="patch"){const A=D(t,this.blue);for(const k of A){const fe=y.patch.op==="move"||y.patch.op==="copy"?[y.patch.from,y.patch.path]:[y.patch.path],L=T.getNodePath(),ge=fe.some(Ee=>U(Ee,k.absPath)),ye=U(L,k.absPath);if(ge&&!ye)throw new _(y.patch,k.absPath,L)}try{t=z(t,[y.patch])}catch(k){throw Be(d,p,k),k}}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 me{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 Le=Object.freeze(Object.defineProperty({__proto__:null,ExpressionPreserver:me},Symbol.toStringTag,{value:"Module"}));function Ue(){return new m.MergingProcessors.SequentialMergingProcessor([new m.MergingProcessors.ValuePropagator,new me,new m.MergingProcessors.TypeAssigner,new m.MergingProcessors.ListProcessor,new m.MergingProcessors.DictionaryProcessor,new m.MergingProcessors.BasicTypesVerifier])}exports.BlueDocumentProcessor=Je;exports.ChannelEventCheckpointProcessor=ee;exports.CodeBlockEvaluationError=Y;exports.CompositeTimelineChannelProcessor=te;exports.DocumentUpdateChannelProcessor=ne;exports.EmbeddedDocumentModificationError=_;exports.EmbeddedNodeChannelProcessor=oe;exports.ExpressionEvaluationError=K;exports.InitializedMarkerProcessor=re;exports.LifecycleEventChannelProcessor=se;exports.MergingProcessors=Le;exports.MyOSAgentChannelProcessor=ie;exports.MyOSTimelineChannelProcessor=ae;exports.OperationProcessor=ce;exports.PatchApplicationError=V;exports.ProcessEmbeddedProcessor=le;exports.SequentialWorkflowOperationProcessor=de;exports.SequentialWorkflowProcessor=J;exports.TimelineChannelProcessor=he;exports.TriggeredEventChannelProcessor=pe;exports.collectEmbeddedPathSpecs=D;exports.createDefaultMergingProcessor=Ue;
package/dist/index.mjs CHANGED
@@ -1,11 +1,11 @@
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;
1
+ var fe = Object.defineProperty;
2
+ var ge = (a, e, t) => e in a ? fe(a, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : a[e] = t;
3
3
  var l = (a, e, t) => ge(a, typeof e != "symbol" ? e + "" : e, t);
4
- import { ProcessEmbeddedSchema as W, ChannelEventCheckpointSchema as ye, blueIds as g, InitializedMarkerSchema as Ee, CompositeTimelineChannelSchema as we, DocumentUpdateChannelSchema as ve, EmbeddedNodeChannelSchema as R, LifecycleEventSchema as Te, TimelineEntrySchema as O, OperationSchema as Pe, OperationRequestSchema as be, UpdateDocumentSchema as x, TriggerEventSchema as j, 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 b, ResolvedBlueNode as Ie, MergingProcessors as k } from "@blue-labs/language";
4
+ import { ProcessEmbeddedSchema as W, ChannelEventCheckpointSchema as ye, blueIds as g, InitializedMarkerSchema as Ee, CompositeTimelineChannelSchema as ve, DocumentUpdateChannelSchema as we, 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 L, BlueNodeTypeSchema as P, ResolvedBlueNode as Ie, MergingProcessors as k } from "@blue-labs/language";
6
6
  import { deepFreeze as Be, isNonNullable as M, deepContains as Oe, isNullable as _ } from "@blue-labs/shared-utils";
7
7
  import { blueIds as ne, MyOSTimelineEntrySchema as oe, MyOSTimelineChannelSchema as Me, MyOSAgentEventSchema as $e, MyOSAgentChannelSchema as qe } from "@blue-repository/myos-dev";
8
- const P = (...a) => a.map((e, t) => {
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;
@@ -17,7 +17,7 @@ class re {
17
17
  this.getDocument = e, this.taskInfo = t, this.blue = n, this.onFlush = o;
18
18
  }
19
19
  get(e) {
20
- const t = this.getDocument(), n = P(this.taskInfo.nodePath, e);
20
+ const t = this.getDocument(), n = b(this.taskInfo.nodePath, e);
21
21
  return t.get(n);
22
22
  }
23
23
  addPatch(e) {
@@ -25,7 +25,7 @@ class re {
25
25
  kind: "patch",
26
26
  patch: {
27
27
  ...e,
28
- path: P(this.taskInfo.nodePath, e.path)
28
+ path: b(this.taskInfo.nodePath, e.path)
29
29
  }
30
30
  });
31
31
  }
@@ -50,7 +50,7 @@ class re {
50
50
  return this.taskInfo.nodePath;
51
51
  }
52
52
  resolvePath(e) {
53
- return P(this.taskInfo.nodePath, e);
53
+ return b(this.taskInfo.nodePath, e);
54
54
  }
55
55
  getTaskInfo() {
56
56
  return this.taskInfo;
@@ -97,25 +97,25 @@ function I(a) {
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)) {
104
- const h = e.nodeToSchemaOutput(
104
+ const d = e.nodeToSchemaOutput(
105
105
  s,
106
106
  W
107
107
  ).paths ?? [];
108
- for (const u of h)
108
+ for (const u of d)
109
109
  n.push({
110
- absPath: P(t, u),
111
- contractPath: P(t, `contracts/${r}`)
110
+ absPath: b(t, u),
111
+ contractPath: b(t, `contracts/${r}`)
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
- P(t, r),
118
+ b(t, r),
119
119
  n
120
120
  );
121
121
  return n;
@@ -140,7 +140,7 @@ function E(a) {
140
140
  function S(a) {
141
141
  return a instanceof ke;
142
142
  }
143
- class xe {
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,7 +179,7 @@ class xe {
179
179
  t[e] = r;
180
180
  }
181
181
  }
182
- const je = (a, e, t, n, o, r) => [
182
+ const xe = (a, e, t, n, o, r) => [
183
183
  -a,
184
184
  e,
185
185
  t,
@@ -200,7 +200,7 @@ class _e {
200
200
  */
201
201
  constructor() {
202
202
  l(this, "queue");
203
- this.queue = new xe([], Ve);
203
+ this.queue = new je([], Ve);
204
204
  }
205
205
  /**
206
206
  * Adds a task to the queue
@@ -345,12 +345,12 @@ const B = class B {
345
345
  }
346
346
  };
347
347
  l(B, "MAX_TRACE_LENGTH", 128);
348
- let L = B;
349
- function Je(a) {
348
+ let J = B;
349
+ function Le(a) {
350
350
  return Object.entries(a.getContracts() ?? {});
351
351
  }
352
- const Le = 64;
353
- class ze {
352
+ const Je = 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 L();
364
+ this.blue = e, this.registry = t, this.queue = n, this.getNextTaskId = o, this.getNextEventSeq = r, this.traceManager = new J();
365
365
  }
366
366
  /**
367
367
  * Routes an event to matching contracts in the document
@@ -376,15 +376,15 @@ class ze {
376
376
  var c;
377
377
  if (n.seq === void 0 && (n.seq = this.getNextEventSeq()), t.length === 0) {
378
378
  if (n.dispatchPath) {
379
- const h = n.dispatchPath.split("/").filter(Boolean), u = { ...n };
380
- return delete u.dispatchPath, this.route(e, h, u, o, r);
379
+ const d = n.dispatchPath.split("/").filter(Boolean), u = { ...n };
380
+ return delete u.dispatchPath, this.route(e, d, u, o, r);
381
381
  }
382
382
  if (n.source === "channel" && n.originNodePath && n.originNodePath !== "/") {
383
- const h = ((c = n.originNodePath) == null ? void 0 : c.split("/").filter(Boolean)) ?? [];
384
- return this.route(e, h, n, o, r);
383
+ const d = ((c = n.originNodePath) == null ? void 0 : c.split("/").filter(Boolean)) ?? [];
384
+ return this.route(e, d, n, o, r);
385
385
  }
386
386
  }
387
- const s = P("/", t.join("/")), i = e.get(s);
387
+ const s = b("/", t.join("/")), i = e.get(s);
388
388
  S(i) && await this.traverseContracts({
389
389
  doc: e,
390
390
  node: i,
@@ -409,28 +409,28 @@ class ze {
409
409
  inlineDepth: c
410
410
  } = e;
411
411
  if (!this.shouldSkipForChannel(r, o))
412
- for (const [h, u] of Je(n)) {
412
+ for (const [d, u] of Le(n)) {
413
413
  if (!u.getType()) continue;
414
- const d = this.registry.get(u.getType());
415
- if (!d) {
416
- console.warn(`No processor registered for contract: ${h}`);
414
+ const h = this.registry.get(u.getType());
415
+ if (!h) {
416
+ console.warn(`No processor registered for contract: ${d}`);
417
417
  continue;
418
418
  }
419
419
  const p = {
420
420
  nodePath: o,
421
- contractName: h,
421
+ contractName: d,
422
422
  contractNode: u,
423
423
  event: r
424
- }, f = new re(() => t, p, this.blue);
425
- if (d.supports(r, u, f, h))
426
- switch (d.role) {
424
+ }, m = new re(() => t, p, this.blue);
425
+ if (h.supports(r, u, m, d))
426
+ switch (h.role) {
427
427
  case "adapter":
428
428
  await this.processAdapter({
429
- cp: d,
429
+ cp: h,
430
430
  event: r,
431
431
  contractNode: u,
432
- ctx: f,
433
- contractName: h,
432
+ ctx: m,
433
+ contractName: d,
434
434
  doc: t,
435
435
  afterTaskId: s,
436
436
  inlineDepth: c
@@ -439,7 +439,7 @@ class ze {
439
439
  case "handler":
440
440
  this.scheduleHandler({
441
441
  contractNode: u,
442
- contractName: h,
442
+ contractName: d,
443
443
  nodePath: o,
444
444
  event: r,
445
445
  depth: i.length,
@@ -453,7 +453,7 @@ class ze {
453
453
  * Processes an adapter contract and routes any emitted events
454
454
  */
455
455
  async processAdapter(e) {
456
- var v;
456
+ var w;
457
457
  const {
458
458
  cp: t,
459
459
  event: n,
@@ -462,24 +462,24 @@ class ze {
462
462
  contractName: s,
463
463
  doc: i,
464
464
  afterTaskId: c,
465
- inlineDepth: h
465
+ inlineDepth: d
466
466
  } = e;
467
- if (h >= Le)
467
+ if (d >= Je)
468
468
  throw new Error("Adapter recursion limit reached");
469
469
  const u = this.traceManager.addHop(
470
470
  n,
471
- ((v = r.getTaskInfo()) == null ? void 0 : v.nodePath) ?? "",
471
+ ((w = r.getTaskInfo()) == null ? void 0 : w.nodePath) ?? "",
472
472
  s
473
473
  );
474
474
  await t.handle(u, o, r, s);
475
- const d = await r.flush();
476
- if (d.find((w) => w.kind === "patch"))
475
+ const h = await r.flush();
476
+ if (h.find((v) => v.kind === "patch"))
477
477
  throw new Error(
478
478
  `Contract "${s}" (adapter) attempted to patch the document`
479
479
  );
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);
480
+ const m = h.filter((v) => v.kind === "event");
481
+ for (const v of m)
482
+ await this.route(i, [], v.event, c, d + 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 = J(u) ? u.toNumber() : 0, p = this.getNextTaskId() + i, f = r.seq;
494
- if (f === void 0)
493
+ const d = this.registry.orderOf(c), u = t.get("/order"), h = L(u) ? u.toNumber() : 0, p = this.getNextTaskId() + i, m = r.seq;
494
+ if (m === void 0)
495
495
  throw new Error("Event sequence missing");
496
- const v = je(
496
+ const w = xe(
497
497
  s,
498
- f,
499
- h,
498
+ m,
500
499
  d,
500
+ h,
501
501
  n,
502
502
  p
503
503
  );
504
504
  {
505
- const m = `${o}#${n}`, D = r.trace ?? [];
506
- if (r.source !== "external" && D.includes(m))
505
+ const f = `${o}#${n}`, D = r.trace ?? [];
506
+ if (r.source !== "external" && D.includes(f))
507
507
  throw new Error(
508
- `Loop detected: repeated hop ${m} within the same event chain`
508
+ `Loop detected: repeated hop ${f} within the same event chain`
509
509
  );
510
510
  }
511
- const w = this.traceManager.addHop(r, o, n);
511
+ const v = this.traceManager.addHop(r, o, n);
512
512
  this.queue.push({
513
- key: v,
513
+ key: w,
514
514
  nodePath: o,
515
515
  contractName: n,
516
516
  contractNode: t,
517
- event: w
517
+ event: v
518
518
  });
519
519
  }
520
520
  /**
@@ -524,7 +524,7 @@ class ze {
524
524
  return e.source === "channel" && !!e.originNodePath && e.originNodePath !== t;
525
525
  }
526
526
  }
527
- const Ue = (a, e, t) => {
527
+ const ze = (a, e, t) => {
528
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
@@ -534,7 +534,7 @@ function G(a, e) {
534
534
  const t = $(a), n = (o) => {
535
535
  if (!S(o)) return;
536
536
  const r = o.getContracts();
537
- (!(r != null && r.checkpoint) || !b.isTypeOf(
537
+ (!(r != null && r.checkpoint) || !P.isTypeOf(
538
538
  r.checkpoint,
539
539
  ye
540
540
  )) && o.addContract(
@@ -549,13 +549,13 @@ function G(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
560
  return S(t) && (ie(t, e) || t.addContract(
561
561
  "initialized",
@@ -575,7 +575,7 @@ function ie(a, e) {
575
575
  })
576
576
  );
577
577
  }
578
- class Fe {
578
+ class He {
579
579
  constructor(e) {
580
580
  l(this, "contractType", "Channel Event Checkpoint");
581
581
  l(this, "contractBlueId", g["Channel Event Checkpoint"]);
@@ -607,7 +607,7 @@ class Fe {
607
607
  }
608
608
  }
609
609
  const K = (a, e) => a.get(e) !== void 0;
610
- class Re {
610
+ class Fe {
611
611
  constructor() {
612
612
  l(this, "firstSeen", /* @__PURE__ */ new Map());
613
613
  }
@@ -620,7 +620,7 @@ class Re {
620
620
  const t = [];
621
621
  for (const { docBase: n, event: o, eventBlueId: r } of this.firstSeen.values()) {
622
622
  if (!o.channelName) continue;
623
- const s = P(
623
+ const s = b(
624
624
  n,
625
625
  "contracts/checkpoint/lastEvents",
626
626
  o.channelName
@@ -648,7 +648,7 @@ class Xe {
648
648
  l(this, "role", "adapter");
649
649
  }
650
650
  supports(e, t, n) {
651
- const o = n.getBlue().nodeToSchemaOutput(t, we);
651
+ const o = n.getBlue().nodeToSchemaOutput(t, ve);
652
652
  return !o.channels || !e.channelName ? !1 : o.channels.includes(e.channelName);
653
653
  }
654
654
  handle(e, t, n, o) {
@@ -679,7 +679,7 @@ class Qe 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, ve), s = t.payload.get("/path");
682
+ const r = o.getBlue().nodeToSchemaOutput(n, we), 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);
@@ -700,11 +700,11 @@ class Ge 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, R);
703
+ const r = o.getBlue().nodeToSchemaOutput(n, F);
704
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, R), { originNodePath: i, payload: c } = t;
707
+ const s = o.getBlue().nodeToSchemaOutput(n, F), { originNodePath: i, payload: c } = t;
708
708
  E(s.path) && i === o.resolvePath(s.path) && o.emitEvent({
709
709
  payload: c,
710
710
  channelName: r,
@@ -865,8 +865,8 @@ class et extends C {
865
865
  if (!s)
866
866
  return !1;
867
867
  try {
868
- const i = o.getBlue(), c = i.nodeToJson(s), h = i.nodeToJson(r);
869
- return Oe(c, h);
868
+ const i = o.getBlue(), c = i.nodeToJson(s), d = i.nodeToJson(r);
869
+ return Oe(c, d);
870
870
  } catch (i) {
871
871
  return console.warn("Error during event pattern matching:", i), !1;
872
872
  }
@@ -879,10 +879,10 @@ class tt {
879
879
  l(this, "role", "adapter");
880
880
  }
881
881
  supports(e, t, n, o) {
882
- const s = n.getBlue().nodeToSchemaOutput(t, Pe), 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
- ), h = this.isOperationChannelMatch(
885
+ ), d = this.isOperationChannelMatch(
886
886
  e,
887
887
  s
888
888
  ), u = this.isRequestPatternMatch(
@@ -890,7 +890,7 @@ class tt {
890
890
  s,
891
891
  n
892
892
  );
893
- return c && h && u;
893
+ return c && d && u;
894
894
  }
895
895
  async handle(e, t, n, o) {
896
896
  n.emitEvent({
@@ -911,7 +911,7 @@ class tt {
911
911
  if (o.message)
912
912
  return n.nodeToSchemaOutput(
913
913
  o.message,
914
- be
914
+ Pe
915
915
  );
916
916
  }
917
917
  return null;
@@ -953,15 +953,47 @@ class nt {
953
953
  }
954
954
  }
955
955
  let y = null;
956
- try {
957
- y = require("isolated-vm");
958
- } catch {
959
- y = null;
960
- }
961
956
  function ot(a) {
962
957
  return /\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(a) || /\bexport\s+/.test(a);
963
958
  }
964
959
  class A {
960
+ static getIvmUnavailableMessage() {
961
+ 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";
962
+ return [
963
+ "isolated-vm is required for expression evaluation but could not be loaded.",
964
+ "This feature only works in a Node.js environment with the native addon available.",
965
+ "",
966
+ `Detected environment: Node ${e} on ${t}/${n}.`,
967
+ "",
968
+ "Common causes:",
969
+ "- Running in a non-Node environment (browser, edge/runtime without Node).",
970
+ "- 'isolated-vm' is not installed, or failed to build its native addon.",
971
+ "- The module was bundled/stripped by a build tool.",
972
+ "",
973
+ "How to fix:",
974
+ "- Ensure 'isolated-vm' is listed in dependencies (not devDependencies) of the executing package.",
975
+ "- Reinstall or rebuild: npm ci && npm rebuild isolated-vm (or equivalent with your package manager).",
976
+ "- Run this code on a supported Node.js runtime (not browser/edge workers)."
977
+ ].join(`
978
+ `);
979
+ }
980
+ static async ensureIvmLoaded() {
981
+ var t;
982
+ if (!(y || !(typeof process < "u" && ((t = process.versions) != null && t.node)))) {
983
+ try {
984
+ if (typeof require == "function") {
985
+ y = require("isolated-vm");
986
+ return;
987
+ }
988
+ } catch {
989
+ }
990
+ try {
991
+ const r = await import("isolated-vm").catch(() => null);
992
+ y = (r == null ? void 0 : r.default) ?? r;
993
+ } catch {
994
+ }
995
+ }
996
+ }
965
997
  /**
966
998
  * Main evaluation method - evaluates code securely in an isolated VM
967
999
  */
@@ -971,19 +1003,19 @@ class A {
971
1003
  bindings: n = {},
972
1004
  options: o = {}
973
1005
  }) {
974
- if (!y)
975
- throw new Error("isolated-vm is required for expression evaluation");
1006
+ if (await this.ensureIvmLoaded(), !y)
1007
+ throw new Error(this.getIvmUnavailableMessage());
976
1008
  return this.evaluateSecure(e, n, t, o);
977
1009
  }
978
1010
  /**
979
1011
  * Secure evaluation using isolated-vm with support for ES modules
980
1012
  */
981
1013
  static async evaluateSecure(e, t, n, o = {}) {
982
- if (!y) throw new Error("isolated-vm not available");
1014
+ if (!y) throw new Error(this.getIvmUnavailableMessage());
983
1015
  const r = new y.Isolate({ memoryLimit: 32 }), s = await r.createContext(), i = s.global;
984
1016
  try {
985
1017
  await this.setupIsolateEnvironment(i, t);
986
- const c = /* @__PURE__ */ new Map(), h = this.createModuleResolver(
1018
+ const c = /* @__PURE__ */ new Map(), d = this.createModuleResolver(
987
1019
  r,
988
1020
  s,
989
1021
  c,
@@ -995,7 +1027,7 @@ class A {
995
1027
  s,
996
1028
  e,
997
1029
  o,
998
- h
1030
+ d
999
1031
  ) : u = await this.evaluateSimpleScript(
1000
1032
  r,
1001
1033
  s,
@@ -1038,11 +1070,11 @@ class A {
1038
1070
  throw new Error(
1039
1071
  `ProcessingContext is missing a loadBlueContent(blueId) implementation (needed for ${r})`
1040
1072
  );
1041
- const c = await i(s), h = await e.compileModule(c);
1042
- return n.set(r, h), await h.instantiate(
1073
+ const c = await i(s), d = await e.compileModule(c);
1074
+ return n.set(r, d), await d.instantiate(
1043
1075
  t,
1044
1076
  this.createModuleResolver(e, t, n, o)
1045
- ), h;
1077
+ ), d;
1046
1078
  }
1047
1079
  if (/^https?:\/\//.test(r)) {
1048
1080
  let s;
@@ -1079,14 +1111,14 @@ class A {
1079
1111
  static async evaluateESModule(e, t, n, o, r) {
1080
1112
  let s = n;
1081
1113
  if (o.isCodeBlock) {
1082
- const h = /^\s*(import\s.+?;|export\s.+?;)/gm, u = (n.match(h) || []).join(
1114
+ const d = /^\s*(import\s.+?;|export\s.+?;)/gm, u = (n.match(d) || []).join(
1083
1115
  `
1084
1116
  `
1085
- ), d = n.replace(h, "").trim();
1117
+ ), h = n.replace(d, "").trim();
1086
1118
  s = `
1087
1119
  ${u}
1088
1120
  const run = function() {
1089
- ${d}
1121
+ ${h}
1090
1122
  };
1091
1123
  export default run();
1092
1124
  `;
@@ -1112,30 +1144,30 @@ class A {
1112
1144
  return typeof e > "u" ? e : JSON.parse(JSON.stringify(e));
1113
1145
  }
1114
1146
  }
1115
- class H {
1147
+ class R {
1116
1148
  /**
1117
1149
  * Creates standard bindings for workflow step execution
1118
1150
  */
1119
1151
  static createStandardBindings(e, t, n) {
1120
- const o = e.getBlue(), r = o.nodeToJson(t.payload, "simple"), s = J(r) ? r.toNumber() : r;
1152
+ const o = e.getBlue(), r = o.nodeToJson(t.payload, "simple"), s = L(r) ? r.toNumber() : r;
1121
1153
  return {
1122
1154
  document: (i) => {
1123
1155
  const c = e.get(i);
1124
- return J(c) ? c.toNumber() : S(c) ? o.nodeToJson(c, "original") : c;
1156
+ return L(c) ? c.toNumber() : S(c) ? o.nodeToJson(c, "original") : c;
1125
1157
  },
1126
1158
  event: s,
1127
1159
  steps: n
1128
1160
  };
1129
1161
  }
1130
1162
  }
1131
- const rt = /^\$\{([\s\S]*)\}$/, st = /\$\{([\s\S]*?)\}/, T = (a) => typeof a != "string" ? !1 : rt.test(a), z = (a) => typeof a != "string" ? !1 : st.test(a), ce = (a) => {
1163
+ const rt = /^\$\{([\s\S]*)\}$/, st = /\$\{([\s\S]*?)\}/, T = (a) => typeof a != "string" ? !1 : rt.test(a), U = (a) => typeof a != "string" ? !1 : st.test(a), ce = (a) => {
1132
1164
  if (!T(a))
1133
1165
  throw new Error(`Invalid expression: ${a}`);
1134
1166
  return a.slice(2, -1);
1135
1167
  };
1136
1168
  class q {
1137
1169
  static createBindings(e, t, n) {
1138
- return H.createStandardBindings(e, t, n);
1170
+ return R.createStandardBindings(e, t, n);
1139
1171
  }
1140
1172
  static async evaluate(e, t, n, o) {
1141
1173
  const { coerceToString: r } = o;
@@ -1147,7 +1179,7 @@ class q {
1147
1179
  });
1148
1180
  return r ? String(i ?? "") : i;
1149
1181
  }
1150
- if (z(e)) {
1182
+ if (U(e)) {
1151
1183
  const i = `\`${String(e).replace(/`/g, "\\`")}\``, c = await A.evaluate({
1152
1184
  code: i,
1153
1185
  ctx: t,
@@ -1181,11 +1213,11 @@ class it {
1181
1213
  l(this, "stepType", "Update Document");
1182
1214
  }
1183
1215
  supports(e) {
1184
- return b.isTypeOf(e, x);
1216
+ return P.isTypeOf(e, j);
1185
1217
  }
1186
1218
  async execute(e, t, n, o, r) {
1187
1219
  const s = n.getBlue();
1188
- if (!b.isTypeOf(e, x)) return;
1220
+ if (!P.isTypeOf(e, j)) return;
1189
1221
  const i = await this.evaluateChangeset(
1190
1222
  e.get("/changeset"),
1191
1223
  n,
@@ -1195,17 +1227,17 @@ class it {
1195
1227
  op: "replace",
1196
1228
  path: "/changeset",
1197
1229
  val: i
1198
- }), h = n.getBlue().nodeToSchemaOutput(c, x);
1199
- for (const u of h.changeset ?? []) {
1230
+ }), d = n.getBlue().nodeToSchemaOutput(c, j);
1231
+ for (const u of d.changeset ?? []) {
1200
1232
  if (!u.path) continue;
1201
- const d = await this.evaluateChangePath(
1233
+ const h = await this.evaluateChangePath(
1202
1234
  u.path,
1203
1235
  n,
1204
1236
  t,
1205
1237
  r
1206
1238
  ), p = u.val;
1207
1239
  if ((u.op === "replace" || u.op === "add") && M(p)) {
1208
- const f = await this.evaluateChangeValue(
1240
+ const m = await this.evaluateChangeValue(
1209
1241
  p,
1210
1242
  n,
1211
1243
  t,
@@ -1213,25 +1245,25 @@ class it {
1213
1245
  );
1214
1246
  n.addPatch({
1215
1247
  op: u.op,
1216
- path: d,
1217
- val: f
1248
+ path: h,
1249
+ val: m
1218
1250
  }), n.emitEvent({
1219
1251
  payload: Z(
1220
1252
  {
1221
1253
  op: u.op,
1222
- path: n.resolvePath(d),
1223
- val: s.nodeToJson(f, "original")
1254
+ path: n.resolvePath(h),
1255
+ val: s.nodeToJson(m, "original")
1224
1256
  },
1225
1257
  s
1226
1258
  ),
1227
1259
  emissionType: "update"
1228
1260
  });
1229
1261
  }
1230
- u.op === "remove" && (n.addPatch({ op: u.op, path: d }), n.emitEvent({
1262
+ u.op === "remove" && (n.addPatch({ op: u.op, path: h }), n.emitEvent({
1231
1263
  payload: Z(
1232
1264
  {
1233
1265
  op: u.op,
1234
- path: n.resolvePath(d),
1266
+ path: n.resolvePath(h),
1235
1267
  val: null
1236
1268
  },
1237
1269
  s
@@ -1246,7 +1278,7 @@ class it {
1246
1278
  const s = ce(e), i = await A.evaluate({
1247
1279
  code: s,
1248
1280
  ctx: t,
1249
- bindings: H.createStandardBindings(
1281
+ bindings: R.createStandardBindings(
1250
1282
  t,
1251
1283
  n,
1252
1284
  o
@@ -1260,7 +1292,7 @@ class it {
1260
1292
  }
1261
1293
  async evaluateChangeValue(e, t, n, o) {
1262
1294
  const r = e.getValue(), s = t.getBlue();
1263
- if (T(r) || typeof r == "string" && z(r)) {
1295
+ if (T(r) || typeof r == "string" && U(r)) {
1264
1296
  const i = q.createBindings(
1265
1297
  t,
1266
1298
  n,
@@ -1277,7 +1309,7 @@ class it {
1277
1309
  }
1278
1310
  async evaluateChangePath(e, t, n, o) {
1279
1311
  const r = q.createBindings(t, n, o);
1280
- if (T(e) || z(e)) {
1312
+ if (T(e) || U(e)) {
1281
1313
  const s = await q.evaluate(e, t, r, {
1282
1314
  coerceToString: !0
1283
1315
  });
@@ -1291,12 +1323,12 @@ class ct {
1291
1323
  l(this, "stepType", "Trigger Event");
1292
1324
  }
1293
1325
  supports(e) {
1294
- return b.isTypeOf(e, j);
1326
+ return P.isTypeOf(e, x);
1295
1327
  }
1296
1328
  async execute(e, t, n) {
1297
1329
  const o = n.getBlue();
1298
- if (!b.isTypeOf(e, j)) return;
1299
- const r = o.nodeToSchemaOutput(e, j);
1330
+ if (!P.isTypeOf(e, x)) return;
1331
+ const r = o.nodeToSchemaOutput(e, x);
1300
1332
  r.event && n.emitEvent({
1301
1333
  payload: r.event,
1302
1334
  emissionType: "triggered"
@@ -1308,10 +1340,10 @@ class lt {
1308
1340
  l(this, "stepType", "JavaScript Code");
1309
1341
  }
1310
1342
  supports(e) {
1311
- return b.isTypeOf(e, V);
1343
+ return P.isTypeOf(e, V);
1312
1344
  }
1313
1345
  async execute(e, t, n, o, r) {
1314
- if (!b.isTypeOf(e, V)) return;
1346
+ if (!P.isTypeOf(e, V)) return;
1315
1347
  const s = n.getBlue(), i = s.nodeToSchemaOutput(
1316
1348
  e,
1317
1349
  V
@@ -1321,16 +1353,16 @@ class lt {
1321
1353
  const c = await A.evaluate({
1322
1354
  code: i.code,
1323
1355
  ctx: n,
1324
- bindings: H.createStandardBindings(n, t, r),
1356
+ bindings: R.createStandardBindings(n, t, r),
1325
1357
  options: {
1326
1358
  isCodeBlock: !0,
1327
1359
  timeout: 500
1328
1360
  }
1329
1361
  });
1330
1362
  if (c && typeof c == "object" && "events" in c) {
1331
- const h = c;
1332
- if (Array.isArray(h.events))
1333
- for (const u of h.events)
1363
+ const d = c;
1364
+ if (Array.isArray(d.events))
1365
+ for (const u of d.events)
1334
1366
  n.emitEvent({
1335
1367
  payload: s.jsonValueToNode(u),
1336
1368
  emissionType: "triggered"
@@ -1366,20 +1398,20 @@ class le {
1366
1398
  async handle(e, t, n, o) {
1367
1399
  var i;
1368
1400
  const r = {}, s = (i = t.getProperties()) == null ? void 0 : i.steps.getItems();
1369
- for (const [c, h] of (s ?? []).entries()) {
1370
- const u = this.executors.find((p) => p.supports(h));
1401
+ for (const [c, d] of (s ?? []).entries()) {
1402
+ const u = this.executors.find((p) => p.supports(d));
1371
1403
  if (!u)
1372
- throw new Error(`Unsupported workflow step type "${h.getType()}"`);
1373
- const d = await u.execute(
1374
- h,
1404
+ throw new Error(`Unsupported workflow step type "${d.getType()}"`);
1405
+ const h = await u.execute(
1406
+ d,
1375
1407
  e,
1376
1408
  n,
1377
1409
  o,
1378
1410
  r
1379
1411
  );
1380
- if (d !== void 0) {
1381
- const p = h.getName(), f = typeof p == "string" ? p : `Step${c + 1}`;
1382
- r[f] = d;
1412
+ if (h !== void 0) {
1413
+ const p = d.getName(), m = typeof p == "string" ? p : `Step${c + 1}`;
1414
+ r[m] = h;
1383
1415
  }
1384
1416
  await n.flush();
1385
1417
  }
@@ -1404,7 +1436,7 @@ class le {
1404
1436
  }
1405
1437
  }
1406
1438
  }
1407
- class ht {
1439
+ class dt {
1408
1440
  constructor(e) {
1409
1441
  l(this, "contractType", "Sequential Workflow Operation");
1410
1442
  l(this, "contractBlueId", g["Sequential Workflow Operation"]);
@@ -1430,8 +1462,8 @@ class ht {
1430
1462
  }
1431
1463
  }
1432
1464
  }
1433
- const ee = (a) => b.isTypeOf(a.payload, O);
1434
- class dt extends C {
1465
+ const ee = (a) => P.isTypeOf(a.payload, O);
1466
+ class ht extends C {
1435
1467
  constructor() {
1436
1468
  super(...arguments);
1437
1469
  l(this, "contractType", "Timeline Channel");
@@ -1471,12 +1503,12 @@ class pt extends C {
1471
1503
  });
1472
1504
  }
1473
1505
  }
1474
- const ft = [
1506
+ const mt = [
1475
1507
  new nt(),
1476
1508
  // channels
1477
1509
  new Ge(),
1478
1510
  new Qe(),
1479
- new dt(),
1511
+ new ht(),
1480
1512
  new Ze(),
1481
1513
  new et(),
1482
1514
  new Xe(),
@@ -1485,7 +1517,7 @@ const ft = [
1485
1517
  new tt(),
1486
1518
  // sequential workflows
1487
1519
  new le(),
1488
- new ht(),
1520
+ new dt(),
1489
1521
  // markers
1490
1522
  new Ke()
1491
1523
  ];
@@ -1495,21 +1527,21 @@ class Tt {
1495
1527
  *
1496
1528
  * @param processors - Initial list of processors to register
1497
1529
  */
1498
- constructor(e, t = ft) {
1530
+ constructor(e, t = mt) {
1499
1531
  l(this, "taskCounter", 0);
1500
1532
  l(this, "eventCounter", 0);
1501
1533
  l(this, "registry");
1502
1534
  l(this, "queue");
1503
1535
  l(this, "router");
1504
- l(this, "checkpointCache", new Re());
1505
- this.blue = e, this.registry = new We(t), this.queue = new _e(), 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(
1506
1538
  this.blue,
1507
1539
  this.registry,
1508
1540
  this.queue,
1509
1541
  () => ++this.taskCounter,
1510
1542
  () => ++this.eventCounter
1511
1543
  ), this.register(
1512
- new Fe(this.checkpointCache),
1544
+ new He(this.checkpointCache),
1513
1545
  9999
1514
1546
  );
1515
1547
  }
@@ -1537,7 +1569,7 @@ class Tt {
1537
1569
  }, o = [n.payload];
1538
1570
  await this.router.route(t, [], n, 0);
1539
1571
  const r = await this.drainQueue(t);
1540
- 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 };
1541
1573
  }
1542
1574
  /**
1543
1575
  * Processes a batch of events against the document
@@ -1575,47 +1607,47 @@ class Tt {
1575
1607
  for (; this.queue.length; ) {
1576
1608
  if (++r > o)
1577
1609
  throw new Error("Possible cycle – too many iterations");
1578
- const i = this.queue.pop(), { nodePath: c, contractName: h, contractNode: u, event: d } = i, p = t.get(c);
1579
- if (!S(p) || !((s = p.getContracts()) != null && s[h]) || !u.getType()) continue;
1580
- const f = this.registry.get(u.getType());
1581
- if (!f) {
1582
- console.warn(`No processor registered for contract: ${h}`);
1610
+ const i = this.queue.pop(), { nodePath: c, contractName: d, contractNode: u, event: h } = i, p = t.get(c);
1611
+ if (!S(p) || !((s = p.getContracts()) != null && s[d]) || !u.getType()) continue;
1612
+ const m = this.registry.get(u.getType());
1613
+ if (!m) {
1614
+ console.warn(`No processor registered for contract: ${d}`);
1583
1615
  continue;
1584
1616
  }
1585
- const v = new re(
1617
+ const w = new re(
1586
1618
  () => t,
1587
1619
  i,
1588
1620
  this.blue,
1589
- async (w) => {
1590
- for (const m of w)
1591
- if (m.kind === "patch") {
1592
- const D = U(
1621
+ async (v) => {
1622
+ for (const f of v)
1623
+ if (f.kind === "patch") {
1624
+ const D = z(
1593
1625
  t,
1594
1626
  this.blue
1595
1627
  );
1596
1628
  for (const N of D) {
1597
- const he = m.patch.op === "move" || m.patch.op === "copy" ? [m.patch.from, m.patch.path] : [m.patch.path], F = v.getNodePath(), de = he.some(
1598
- (fe) => X(fe, N.absPath)
1629
+ const de = f.patch.op === "move" || f.patch.op === "copy" ? [f.patch.from, f.patch.path] : [f.patch.path], H = w.getNodePath(), he = de.some(
1630
+ (me) => X(me, N.absPath)
1599
1631
  ), pe = X(
1600
- F,
1632
+ H,
1601
1633
  N.absPath
1602
1634
  );
1603
- if (de && !pe)
1635
+ if (he && !pe)
1604
1636
  throw new ae(
1605
- m.patch,
1637
+ f.patch,
1606
1638
  N.absPath,
1607
- F
1639
+ H
1608
1640
  );
1609
1641
  }
1610
1642
  try {
1611
- t = Q(t, [m.patch]);
1643
+ t = Q(t, [f.patch]);
1612
1644
  } catch (N) {
1613
- throw Ue(h, d, N), N;
1645
+ throw ze(d, h, N), N;
1614
1646
  }
1615
- } else m.kind === "event" && (n.push(m.event.payload), await this.router.route(t, [], m.event, i.key[5]));
1647
+ } else f.kind === "event" && (n.push(f.event.payload), await this.router.route(t, [], f.event, i.key[5]));
1616
1648
  }
1617
1649
  );
1618
- await f.handle(d, u, v, h), await v.flush();
1650
+ await m.handle(h, u, w, d), await w.flush();
1619
1651
  }
1620
1652
  return { state: t, emitted: n };
1621
1653
  }
@@ -1641,11 +1673,11 @@ class ue {
1641
1673
  return e;
1642
1674
  }
1643
1675
  }
1644
- const Pt = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1676
+ const bt = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1645
1677
  __proto__: null,
1646
1678
  ExpressionPreserver: ue
1647
1679
  }, Symbol.toStringTag, { value: "Module" }));
1648
- function bt() {
1680
+ function Pt() {
1649
1681
  return new k.SequentialMergingProcessor([
1650
1682
  new k.ValuePropagator(),
1651
1683
  new ue(),
@@ -1657,7 +1689,7 @@ function bt() {
1657
1689
  }
1658
1690
  export {
1659
1691
  Tt as BlueDocumentProcessor,
1660
- Fe as ChannelEventCheckpointProcessor,
1692
+ He as ChannelEventCheckpointProcessor,
1661
1693
  De as CodeBlockEvaluationError,
1662
1694
  Xe as CompositeTimelineChannelProcessor,
1663
1695
  Qe as DocumentUpdateChannelProcessor,
@@ -1666,16 +1698,16 @@ export {
1666
1698
  Ae as ExpressionEvaluationError,
1667
1699
  Ke as InitializedMarkerProcessor,
1668
1700
  Ye as LifecycleEventChannelProcessor,
1669
- Pt as MergingProcessors,
1701
+ bt as MergingProcessors,
1670
1702
  et as MyOSAgentChannelProcessor,
1671
1703
  Ze as MyOSTimelineChannelProcessor,
1672
1704
  tt as OperationProcessor,
1673
1705
  se as PatchApplicationError,
1674
1706
  nt as ProcessEmbeddedProcessor,
1675
- ht as SequentialWorkflowOperationProcessor,
1707
+ dt as SequentialWorkflowOperationProcessor,
1676
1708
  le as SequentialWorkflowProcessor,
1677
- dt as TimelineChannelProcessor,
1709
+ ht as TimelineChannelProcessor,
1678
1710
  pt as TriggeredEventChannelProcessor,
1679
- U as collectEmbeddedPathSpecs,
1680
- bt as createDefaultMergingProcessor
1711
+ z as collectEmbeddedPathSpecs,
1712
+ Pt as createDefaultMergingProcessor
1681
1713
  };
@@ -18,6 +18,8 @@ export interface VMBindings {
18
18
  * - Support for HTTP/HTTPS URLs for external modules
19
19
  */
20
20
  export declare class ExpressionEvaluator {
21
+ private static getIvmUnavailableMessage;
22
+ private static ensureIvmLoaded;
21
23
  /**
22
24
  * Main evaluation method - evaluates code securely in an isolated VM
23
25
  */
@@ -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;AAkBD;;;;;;;;GAQG;AACH,qBAAa,mBAAmB;IAC9B;;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;;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;AAWnD;;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;AAaD;;;;;;;;GAQG;AACH,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,MAAM,CAAC,wBAAwB;mBA6BlB,eAAe;IA4BpC;;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;IAQpB;;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.0",
3
+ "version": "1.33.1",
4
4
  "dependencies": {
5
- "@blue-labs/language": "1.33.0",
6
- "@blue-labs/shared-utils": "1.33.0",
5
+ "@blue-labs/language": "1.33.1",
6
+ "@blue-labs/shared-utils": "1.33.1",
7
7
  "isolated-vm": "^5.0.4"
8
8
  },
9
9
  "main": "./dist/index.js",