@blue-labs/document-processor 1.28.0 → 1.29.0

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,8 @@
1
- "use strict";var ye=Object.defineProperty;var ge=(s,e,t)=>e in s?ye(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var l=(s,e,t)=>ge(s,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"),T=require("@blue-labs/shared-utils"),P=require("@blue-repository/myos-dev"),Ee=(s,e)=>({on:(t,n)=>({end:()=>n(null)})});async function we(s){return new Promise((e,t)=>{Ee().on("error",t).end()})}const S=(...s)=>s.map((e,t)=>{if(typeof e!="string")return"";if(t===0&&e==="/")return"/";const n=t>0?e.replace(/^\/+/,""):e;return t<s.length-1?n.replace(/\/+$/,""):n}).filter(Boolean).join("/").replace(/\/{2,}/g,"/");class K{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,originNodePath:e.originNodePath??this.taskInfo.nodePath,rootEvent:e.rootEvent??t.rootEvent??t,trace:[...n]};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(e){if(!/^https?:\/\//.test(e))throw new Error("Only http/https URLs are allowed");return we()}loadBlueContent(e){throw new Error("Not implemented")}}class A extends Error{constructor(e,t){super(`Cannot apply patch ${JSON.stringify(e)}`),this.patch=e,this.cause=t,this.name="PatchApplicationError"}}class x 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 M extends Error{constructor(e,t){super(`Failed to evaluate expression "${e}"`),this.code=e,this.cause=t,this.name="ExpressionEvaluationError"}}class q extends Error{constructor(e,t){super(`Failed to evaluate code block "${e}"`),this.code=e,this.cause=t,this.name="CodeBlockEvaluationError"}}function N(s){return T.deepFreeze(s)}function B(s){return s.clone()}function j(s,e,t="/",n=[]){const o=s.getContracts()??{};for(const[r,a]of Object.entries(o))if(m.BlueNodeTypeSchema.isTypeOf(a,d.ProcessEmbeddedSchema)){const h=e.nodeToSchemaOutput(a,d.ProcessEmbeddedSchema).paths??[];for(const u of h)n.push({absPath:S(t,u),contractPath:S(t,`contracts/${r}`)})}for(const[r,a]of Object.entries(s.getProperties()??{}))j(a,e,S(t,r),n);return n}function J(s,e){return s===e||s.startsWith(e.endsWith("/")?e:e+"/")}function _(s,e){if(!e.length)return s;let t=B(s);for(const n of e)try{t=m.applyBlueNodePatch(t,n,!0)}catch(o){throw new A(n,o)}return N(t)}function y(s){return s!=null}function C(s){return s instanceof m.BlueNode}class ve{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,a=t[r];if(n(o,a)>=0)break;t[e]=a,e=r}t[e]=o}_down(e){const{data:t,compare:n}=this,o=this.length>>1,r=t[e];for(;e<o;){let a=(e<<1)+1;const c=a+1;if(c<this.length&&n(t[c],t[a])<0&&(a=c),n(t[a],r)>=0)break;t[e]=t[a],e=a}t[e]=r}}const Se=(s,e,t,n,o,r)=>[-s,e,t,n,o,r],be=(s,e)=>{for(let t=0;t<s.key.length;t++){const n=s.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 Pe{constructor(){l(this,"queue");this.queue=new ve([],be)}push(e){this.queue.push(e)}pop(){return this.queue.pop()}get length(){return this.queue.length}}class Te{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()}}class Ce{constructor(){l(this,"isEnabled");this.isEnabled=process.env.TRACE_BLUE_ENABLED==="true"}makeHop(e,t){return`${e}#${t}`}shouldTrace(){return this.isEnabled}addHop(e,t,n){if(!this.shouldTrace())return{...e};const o=[...e.trace??[],this.makeHop(t,n)];return{...e,trace:o}}getTrace(e){return e.trace??[]}clearTrace(e){return{...e,trace:[]}}isTracingEnabled(){return this.isEnabled}}const ke=64;class Ie{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 Ce}async route(e,t,n,o,r=0){var i;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=((i=n.originNodePath)==null?void 0:i.split("/").filter(Boolean))??[];return this.route(e,h,n,o,r)}}const a=S("/",t.join("/")),c=e.get(a);C(c)&&await this.traverseContracts({doc:e,node:c,nodePath:a,event:n,afterTaskId:o,pathSegments:t,inlineDepth:r})}async traverseContracts(e){const{doc:t,node:n,nodePath:o,event:r,afterTaskId:a,pathSegments:c,inlineDepth:i}=e;if(!this.shouldSkipForChannel(r,o))for(const[h,u]of Object.entries(n.getContracts()??{})){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 K(()=>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:a,inlineDepth:i});break;case"handler":this.scheduleHandler({contractNode:u,contractName:h,nodePath:o,event:r,depth:c.length,afterTaskId:a});break}}}async processAdapter(e){var v;const{cp:t,event:n,contractNode:o,ctx:r,contractName:a,doc:c,afterTaskId:i,inlineDepth:h}=e;if(h>=ke)throw new Error("Adapter recursion limit reached");const u=this.traceManager.addHop(n,((v=r.getTaskInfo())==null?void 0:v.nodePath)??"",a);await t.handle(u,o,r,a);const p=await r.flush();if(p.find(b=>b.kind==="patch"))throw new Error(`Contract "${a}" (adapter) attempted to patch the document`);const g=p.filter(b=>b.kind==="event");for(const b of g)await this.route(c,[],b.event,i,h+1)}scheduleHandler(e){const{contractNode:t,contractName:n,nodePath:o,event:r,depth:a,afterTaskId:c}=e,i=t.getType();if(!i){console.warn(`Contract node type is not defined for: ${n}`);return}const h=this.registry.orderOf(i),u=t.get("/order"),p=m.isBigNumber(u)?u.toNumber():0,f=this.getNextTaskId()+c,g=Se(a,r.seq,h,p,n,f),v=this.traceManager.addHop(r,o,n);this.queue.push({key:g,nodePath:o,contractName:n,contractNode:t,event:v})}shouldSkipForChannel(e,t){return e.source==="channel"&&!!e.originNodePath&&e.originNodePath!==t}}const Ne=(s,e,t)=>{(t instanceof A||t instanceof x)&&console.error(`[Blue] Failed to apply patches for contract "${s}" on event ${JSON.stringify(e)}`,t)};function U(s,e){const t=B(s),n=o=>{if(!C(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 j(t,e)){const r=t.get(o);C(r)&&n(r)}return N(t)}function Be(s,e){const t=B(s);return C(t)&&(X(t,e)||t.addContract("initialized",e.jsonValueToNode({type:{name:"Initialized Marker",blueId:d.blueIds["Initialized Marker"]}}))),N(t)}function X(s,e){const t=s.getContracts();return Object.values(t??{}).some(n=>e.isTypeOf(n,d.InitializedMarkerSchema,{checkSchemaExtensions:!0}))}class Y{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 handle(e,t,n){var a;if(!e.channelName||!((a=e.rootEvent)!=null&&a.seq))return;const o=await n.getBlue().calculateBlueId(e.rootEvent.payload),r=n.getNodePath().replace(/\/contracts\/checkpoint$/,"");this.cache.record(r,e,o)}}const F=(s,e)=>s.get(e)!==void 0;class Oe{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 a=S(n,"contracts/checkpoint/lastEvents",o.channelName),c=`${a}/blueId`;F(e,a)?t.push({op:F(e,c)?"replace":"add",path:c,val:r}):t.push({op:"add",path:a,val:{blueId:r}})}return t}clear(){this.firstSeen.clear()}}class k{constructor(){l(this,"role","adapter")}baseSupports(e){return e.source!=="channel"}}class Z extends k{constructor(){super(...arguments);l(this,"contractType","Composite Timeline Channel");l(this,"contractBlueId",d.blueIds["Composite Timeline Channel"])}supports(t,n,o){const r=o.getBlue().nodeToSchemaOutput(n,d.CompositeTimelineChannelSchema);return!r.channels||!t.channelName?!1:r.channels.includes(t.channelName)}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class G extends k{constructor(){super(...arguments);l(this,"contractType","Document Update Channel");l(this,"contractBlueId",d.blueIds["Document Update Channel"])}supports(t,n,o,r){if(!this.baseSupports(t))return!1;const a=o.getBlue().nodeToSchemaOutput(n,d.DocumentUpdateChannelSchema),c=t.payload.get("/path");if(!c||t.channelName===r)return!1;const i=a.path;return T.isNonNullable(i)&&c===o.resolvePath(i)}handle(t,n,o,r){const a=t.payload;a&&o.emitEvent({payload:a,channelName:r,source:"channel"})}}class ee extends k{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 y(t.originNodePath)&&y(r.path)&&t.originNodePath===o.resolvePath(r.path)}handle(t,n,o,r){const a=o.getBlue().nodeToSchemaOutput(n,d.EmbeddedNodeChannelSchema),{originNodePath:c,payload:i}=t;y(a.path)&&c===o.resolvePath(a.path)&&o.emitEvent({payload:i,channelName:r,source:"channel"})}}class te{constructor(){l(this,"contractType","Initialized Marker");l(this,"contractBlueId",d.blueIds["Initialized Marker"]);l(this,"role","marker")}supports(){return!1}handle(){}}class ne extends k{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)||!this.isLifecycleEvent(t,o)?!1:this.isEventPatternMatch(t,n,o)}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}isLifecycleEvent(t,n){const o=n.getBlue(),r=t.payload;return o.isTypeOf(r,d.LifecycleEventSchema,{checkSchemaExtensions:!0})}isEventPatternMatch(t,n,o){var a;const r=(a=n.getProperties())==null?void 0:a.event;if(!r)return!0;try{const c=o.getBlue(),i=c.nodeToJson(t.payload),h=c.nodeToJson(r);return T.deepContains(i,h)}catch(c){return console.warn("Error during lifecycle event pattern matching:",c),!1}}}const L=(s,e)=>{const t=e.getBlue();return t.isTypeOf(s.payload,d.TimelineEntrySchema)||t.isTypeOf(s.payload,P.MyOSTimelineEntrySchema)};class oe extends k{constructor(){super(...arguments);l(this,"contractType","MyOS Timeline Channel");l(this,"contractBlueId",P.blueIds["MyOS Timeline Channel"])}supports(t,n,o){var f;if(!this.baseSupports(t)||!L(t,o))return!1;const a=o.getBlue().nodeToSchemaOutput(t.payload,P.MyOSTimelineEntrySchema),c=o.getBlue().nodeToSchemaOutput(n,P.MyOSTimelineChannelSchema),i=(f=a.timeline)==null?void 0:f.timelineId,h=y(c.timelineId)&&y(i),u=y(c.account)&&y(a.account),p=y(c.email)&&y(a.email);return h&&i===c.timelineId||u&&a.account===c.account||p&&a.email===c.email}handle(t,n,o,r){L(t,o)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class re extends k{constructor(){super(...arguments);l(this,"contractType","MyOS Agent Channel");l(this,"contractBlueId",P.blueIds["MyOS Agent Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;try{const{myosAgentEvent:r,myosAgentChannel:a}=this.parseEventAndChannel(t,n,o);return this.isAgentMatch(r,a)&&this.isEventPatternMatch(r,a,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(),a=r.nodeToSchemaOutput(t.payload,P.MyOSAgentEventSchema),c=r.nodeToSchemaOutput(n,P.MyOSAgentChannelSchema);return{myosAgentEvent:a,myosAgentChannel:c}}isAgentMatch(t,n){var a;const o=t.agentId,r=(a=n.agent)==null?void 0:a.agentId;return y(o)&&y(r)&&o===r}isEventPatternMatch(t,n,o){const r=n.event;if(!r)return!0;const a=t.event;if(!a)return!1;try{const c=o.getBlue(),i=c.nodeToJson(a),h=c.nodeToJson(r);return T.deepContains(i,h)}catch(c){return console.warn("Error during event pattern matching:",c),!1}}}class ae{constructor(){l(this,"contractType","Operation");l(this,"contractBlueId",d.blueIds.Operation);l(this,"role","adapter")}supports(e,t,n,o){const a=n.getBlue().nodeToSchemaOutput(t,d.OperationSchema),c=this.parseEventPayload(e,n);return y(c==null?void 0:c.operation)&&c.operation===o&&e.source==="channel"&&e.channelName===a.channel}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}}class se{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)})}}const ce=!process.env.SKIP_ISOLATED_VM;let w=null;if(ce)try{w=require("isolated-vm")}catch{console.warn("isolated-vm not available, using fallback evaluation method")}function z(s){return/\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(s)||/\bexport\s+/.test(s)}class ${static async evaluate({code:e,ctx:t,bindings:n={},options:o={}}){return!w||!ce?this.evaluateSimple(e,n,o):this.evaluateSecure(e,n,t,o)}static async evaluateSimple(e,t,n={}){if(z(e))throw new Error("Static import/export syntax requires isolated-vm – start Node without SKIP_ISOLATED_VM.");try{if(n.isCodeBlock){const o=Object.keys(t);return await(await new Function(...o,`return async function codeBlock(${o.join(", ")}) { ${e} }`)(...o.map(c=>t[c])))(...o.map(c=>t[c]))}else return new Function(...Object.keys(t),`return ${e};`)(...Object.values(t))}catch(o){throw n.isCodeBlock?new q(e,o):new M(e,o)}}static async evaluateSecure(e,t,n,o={}){if(!w)throw new Error("isolated-vm not available");const r=new w.Isolate({memoryLimit:32}),a=await r.createContext(),c=a.global;try{await this.setupIsolateEnvironment(c,t);const i=new Map,h=this.createModuleResolver(r,a,i,n);let u;return z(e)?u=await this.evaluateESModule(r,a,e,o,h):u=await this.evaluateSimpleScript(r,a,e,t,o),this.deepClone(u)}catch(i){throw o.isCodeBlock?new q(e,i):new M(e,i)}finally{a.release(),r.dispose()}}static async setupIsolateEnvironment(e,t){if(!w)throw new Error("isolated-vm not available");const n=new w.Callback((...r)=>console.log(...r)),o=new w.ExternalCopy({log:n}).copyInto();await e.set("console",o);for(const[r,a]of Object.entries(t))typeof a=="function"?await e.set(r,new w.Callback(a)):await e.set(r,new w.ExternalCopy(a).copyInto())}static createModuleResolver(e,t,n,o){return async r=>{if(n.has(r))return n.get(r);if(r.startsWith("blue:")){const a=r.slice(5),c=o.loadBlueContent;if(typeof c!="function")throw new Error(`ProcessingContext is missing a loadBlueContent(blueId) implementation (needed for ${r})`);const i=await c(a),h=await e.compileModule(i);return n.set(r,h),await h.instantiate(t,this.createModuleResolver(e,t,n,o)),h}if(/^https?:\/\//.test(r)){let a;if(typeof o.loadExternalModule=="function")a=await o.loadExternalModule(r);else throw new Error(`ProcessingContext is missing a loadExternalModule(url) implementation (needed for ${r})`);const c=await e.compileModule(a);return n.set(r,c),await c.instantiate(t,this.createModuleResolver(e,t,n,o)),c}throw new Error(`Unsupported module specifier "${r}"`)}}static async evaluateSimpleScript(e,t,n,o,r){const a=Object.keys(o).join(", "),c=Object.keys(o).map(u=>u),i=`(async (${a}) => { ${r.isCodeBlock?n:`return (${n});`} })(${c.join(", ")})`;return await(await e.compileScript(i)).run(t,{timeout:r.timeout??500,promise:!0,copy:!0,release:!0})}static async evaluateESModule(e,t,n,o,r){let a=n;if(o.isCodeBlock){const h=/^\s*(import\s.+?;|export\s.+?;)/gm,u=(n.match(h)||[]).join(`
1
+ "use strict";var ye=Object.defineProperty;var ge=(s,e,t)=>e in s?ye(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var l=(s,e,t)=>ge(s,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"),T=require("@blue-labs/shared-utils"),P=require("@blue-repository/myos-dev"),Ee=(s,e)=>({on:(t,n)=>({end:()=>n(null)})});async function we(s){return new Promise((e,t)=>{Ee().on("error",t).end()})}const b=(...s)=>s.map((e,t)=>{if(typeof e!="string")return"";if(t===0&&e==="/")return"/";const n=t>0?e.replace(/^\/+/,""):e;return t<s.length-1?n.replace(/\/+$/,""):n}).filter(Boolean).join("/").replace(/\/{2,}/g,"/");class K{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=b(this.taskInfo.nodePath,e);return t.get(n)}addPatch(e){this.actions.push({kind:"patch",patch:{...e,path:b(this.taskInfo.nodePath,e.path)}})}emitEvent(e){const t=this.taskInfo.event,n=t.trace??[],o={...e,originNodePath:e.originNodePath??this.taskInfo.nodePath,rootEvent:e.rootEvent??t.rootEvent??t,trace:[...n]};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 b(this.taskInfo.nodePath,e)}getTaskInfo(){return this.taskInfo}getBlue(){return this.blue}loadExternalModule(e){if(!/^https?:\/\//.test(e))throw new Error("Only http/https URLs are allowed");return we()}loadBlueContent(e){throw new Error("Not implemented")}}class A extends Error{constructor(e,t){super(`Cannot apply patch ${JSON.stringify(e)}`),this.patch=e,this.cause=t,this.name="PatchApplicationError"}}class j extends Error{constructor(e,t,n){super(`Patch ${JSON.stringify(e)} touches "${e.op==="move"||e.op==="copy"?`${e.from} → ${e.path}`:e.path}" which is inside embedded document "${t}" (Process Embedded @ "${n}")`),this.patch=e,this.offendingPath=t,this.contractNodePath=n,this.name="EmbeddedDocumentModificationError"}}class M extends Error{constructor(e,t){super(`Failed to evaluate expression "${e}"`),this.code=e,this.cause=t,this.name="ExpressionEvaluationError"}}class q extends Error{constructor(e,t){super(`Failed to evaluate code block "${e}"`),this.code=e,this.cause=t,this.name="CodeBlockEvaluationError"}}function N(s){return T.deepFreeze(s)}function B(s){return s.clone()}function x(s,e,t="/",n=[]){const o=s.getContracts()??{};for(const[r,a]of Object.entries(o))if(m.BlueNodeTypeSchema.isTypeOf(a,d.ProcessEmbeddedSchema)){const h=e.nodeToSchemaOutput(a,d.ProcessEmbeddedSchema).paths??[];for(const u of h)n.push({absPath:b(t,u),contractPath:b(t,`contracts/${r}`)})}for(const[r,a]of Object.entries(s.getProperties()??{}))x(a,e,b(t,r),n);return n}function J(s,e){return s===e||s.startsWith(e.endsWith("/")?e:e+"/")}function _(s,e){if(!e.length)return s;let t=B(s);for(const n of e)try{t=m.applyBlueNodePatch(t,n,!0)}catch(o){throw new A(n,o)}return N(t)}function y(s){return s!=null}function C(s){return s instanceof m.BlueNode}class ve{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,a=t[r];if(n(o,a)>=0)break;t[e]=a,e=r}t[e]=o}_down(e){const{data:t,compare:n}=this,o=this.length>>1,r=t[e];for(;e<o;){let a=(e<<1)+1;const c=a+1;if(c<this.length&&n(t[c],t[a])<0&&(a=c),n(t[a],r)>=0)break;t[e]=t[a],e=a}t[e]=r}}const be=(s,e,t,n,o,r)=>[-s,e,t,n,o,r],Se=(s,e)=>{for(let t=0;t<s.key.length;t++){const n=s.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 Pe{constructor(){l(this,"queue");this.queue=new ve([],Se)}push(e){this.queue.push(e)}pop(){return this.queue.pop()}get length(){return this.queue.length}}class Te{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()}}class Ce{constructor(){l(this,"isEnabled");this.isEnabled=process.env.TRACE_BLUE_ENABLED==="true"}makeHop(e,t){return`${e}#${t}`}shouldTrace(){return this.isEnabled}addHop(e,t,n){if(!this.shouldTrace())return{...e};const o=[...e.trace??[],this.makeHop(t,n)];return{...e,trace:o}}getTrace(e){return e.trace??[]}clearTrace(e){return{...e,trace:[]}}isTracingEnabled(){return this.isEnabled}}const ke=64;class Ie{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 Ce}async route(e,t,n,o,r=0){var i;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=((i=n.originNodePath)==null?void 0:i.split("/").filter(Boolean))??[];return this.route(e,h,n,o,r)}}const a=b("/",t.join("/")),c=e.get(a);C(c)&&await this.traverseContracts({doc:e,node:c,nodePath:a,event:n,afterTaskId:o,pathSegments:t,inlineDepth:r})}async traverseContracts(e){const{doc:t,node:n,nodePath:o,event:r,afterTaskId:a,pathSegments:c,inlineDepth:i}=e;if(!this.shouldSkipForChannel(r,o))for(const[h,u]of Object.entries(n.getContracts()??{})){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 K(()=>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:a,inlineDepth:i});break;case"handler":this.scheduleHandler({contractNode:u,contractName:h,nodePath:o,event:r,depth:c.length,afterTaskId:a});break}}}async processAdapter(e){var v;const{cp:t,event:n,contractNode:o,ctx:r,contractName:a,doc:c,afterTaskId:i,inlineDepth:h}=e;if(h>=ke)throw new Error("Adapter recursion limit reached");const u=this.traceManager.addHop(n,((v=r.getTaskInfo())==null?void 0:v.nodePath)??"",a);await t.handle(u,o,r,a);const p=await r.flush();if(p.find(S=>S.kind==="patch"))throw new Error(`Contract "${a}" (adapter) attempted to patch the document`);const g=p.filter(S=>S.kind==="event");for(const S of g)await this.route(c,[],S.event,i,h+1)}scheduleHandler(e){const{contractNode:t,contractName:n,nodePath:o,event:r,depth:a,afterTaskId:c}=e,i=t.getType();if(!i){console.warn(`Contract node type is not defined for: ${n}`);return}const h=this.registry.orderOf(i),u=t.get("/order"),p=m.isBigNumber(u)?u.toNumber():0,f=this.getNextTaskId()+c,g=be(a,r.seq,h,p,n,f),v=this.traceManager.addHop(r,o,n);this.queue.push({key:g,nodePath:o,contractName:n,contractNode:t,event:v})}shouldSkipForChannel(e,t){return e.source==="channel"&&!!e.originNodePath&&e.originNodePath!==t}}const Ne=(s,e,t)=>{(t instanceof A||t instanceof j)&&console.error(`[Blue] Failed to apply patches for contract "${s}" on event ${JSON.stringify(e)}`,t)};function U(s,e){const t=B(s),n=o=>{if(!C(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 x(t,e)){const r=t.get(o);C(r)&&n(r)}return N(t)}function Be(s,e){const t=B(s);return C(t)&&(X(t,e)||t.addContract("initialized",e.jsonValueToNode({type:{name:"Initialized Marker",blueId:d.blueIds["Initialized Marker"]}}))),N(t)}function X(s,e){const t=s.getContracts();return Object.values(t??{}).some(n=>e.isTypeOf(n,d.InitializedMarkerSchema,{checkSchemaExtensions:!0}))}class Y{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 a;if(!e.channelName||!((a=e.rootEvent)!=null&&a.seq))return;const o=await this.getEventBlueId(e,n),r=n.getNodePath().replace(/\/contracts\/checkpoint$/,"");this.cache.record(r,e,o)}}const F=(s,e)=>s.get(e)!==void 0;class Oe{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 a=b(n,"contracts/checkpoint/lastEvents",o.channelName),c=`${a}/blueId`;F(e,a)?t.push({op:F(e,c)?"replace":"add",path:c,val:r}):t.push({op:"add",path:a,val:{blueId:r}})}return t}clear(){this.firstSeen.clear()}}class k{constructor(){l(this,"role","adapter")}baseSupports(e){return e.source!=="channel"}}class Z extends k{constructor(){super(...arguments);l(this,"contractType","Composite Timeline Channel");l(this,"contractBlueId",d.blueIds["Composite Timeline Channel"])}supports(t,n,o){const r=o.getBlue().nodeToSchemaOutput(n,d.CompositeTimelineChannelSchema);return!r.channels||!t.channelName?!1:r.channels.includes(t.channelName)}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class G extends k{constructor(){super(...arguments);l(this,"contractType","Document Update Channel");l(this,"contractBlueId",d.blueIds["Document Update Channel"])}supports(t,n,o,r){if(!this.baseSupports(t))return!1;const a=o.getBlue().nodeToSchemaOutput(n,d.DocumentUpdateChannelSchema),c=t.payload.get("/path");if(!c||t.channelName===r)return!1;const i=a.path;return T.isNonNullable(i)&&c===o.resolvePath(i)}handle(t,n,o,r){const a=t.payload;a&&o.emitEvent({payload:a,channelName:r,source:"channel"})}}class ee extends k{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 y(t.originNodePath)&&y(r.path)&&t.originNodePath===o.resolvePath(r.path)}handle(t,n,o,r){const a=o.getBlue().nodeToSchemaOutput(n,d.EmbeddedNodeChannelSchema),{originNodePath:c,payload:i}=t;y(a.path)&&c===o.resolvePath(a.path)&&o.emitEvent({payload:i,channelName:r,source:"channel"})}}class te{constructor(){l(this,"contractType","Initialized Marker");l(this,"contractBlueId",d.blueIds["Initialized Marker"]);l(this,"role","marker")}supports(){return!1}handle(){}}class ne extends k{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)||!this.isLifecycleEvent(t,o)?!1:this.isEventPatternMatch(t,n,o)}handle(t,n,o,r){o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}isLifecycleEvent(t,n){const o=n.getBlue(),r=t.payload;return o.isTypeOf(r,d.LifecycleEventSchema,{checkSchemaExtensions:!0})}isEventPatternMatch(t,n,o){var a;const r=(a=n.getProperties())==null?void 0:a.event;if(!r)return!0;try{const c=o.getBlue(),i=c.nodeToJson(t.payload),h=c.nodeToJson(r);return T.deepContains(i,h)}catch(c){return console.warn("Error during lifecycle event pattern matching:",c),!1}}}const L=(s,e)=>{const t=e.getBlue();return t.isTypeOf(s.payload,d.TimelineEntrySchema)||t.isTypeOf(s.payload,P.MyOSTimelineEntrySchema)};class oe extends k{constructor(){super(...arguments);l(this,"contractType","MyOS Timeline Channel");l(this,"contractBlueId",P.blueIds["MyOS Timeline Channel"])}supports(t,n,o){var f;if(!this.baseSupports(t)||!L(t,o))return!1;const a=o.getBlue().nodeToSchemaOutput(t.payload,P.MyOSTimelineEntrySchema),c=o.getBlue().nodeToSchemaOutput(n,P.MyOSTimelineChannelSchema),i=(f=a.timeline)==null?void 0:f.timelineId,h=y(c.timelineId)&&y(i),u=y(c.account)&&y(a.account),p=y(c.email)&&y(a.email);return h&&i===c.timelineId||u&&a.account===c.account||p&&a.email===c.email}handle(t,n,o,r){L(t,o)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}class re extends k{constructor(){super(...arguments);l(this,"contractType","MyOS Agent Channel");l(this,"contractBlueId",P.blueIds["MyOS Agent Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;try{const{myosAgentEvent:r,myosAgentChannel:a}=this.parseEventAndChannel(t,n,o);return this.isAgentMatch(r,a)&&this.isEventPatternMatch(r,a,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(),a=r.nodeToSchemaOutput(t.payload,P.MyOSAgentEventSchema),c=r.nodeToSchemaOutput(n,P.MyOSAgentChannelSchema);return{myosAgentEvent:a,myosAgentChannel:c}}isAgentMatch(t,n){var a;const o=t.agentId,r=(a=n.agent)==null?void 0:a.agentId;return y(o)&&y(r)&&o===r}isEventPatternMatch(t,n,o){const r=n.event;if(!r)return!0;const a=t.event;if(!a)return!1;try{const c=o.getBlue(),i=c.nodeToJson(a),h=c.nodeToJson(r);return T.deepContains(i,h)}catch(c){return console.warn("Error during event pattern matching:",c),!1}}}class ae{constructor(){l(this,"contractType","Operation");l(this,"contractBlueId",d.blueIds.Operation);l(this,"role","adapter")}supports(e,t,n,o){const a=n.getBlue().nodeToSchemaOutput(t,d.OperationSchema),c=this.parseEventPayload(e,n);return y(c==null?void 0:c.operation)&&c.operation===o&&e.source==="channel"&&e.channelName===a.channel}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}}class se{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)})}}const ce=!process.env.SKIP_ISOLATED_VM;let w=null;if(ce)try{w=require("isolated-vm")}catch{console.warn("isolated-vm not available, using fallback evaluation method")}function z(s){return/\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(s)||/\bexport\s+/.test(s)}class ${static async evaluate({code:e,ctx:t,bindings:n={},options:o={}}){return!w||!ce?this.evaluateSimple(e,n,o):this.evaluateSecure(e,n,t,o)}static async evaluateSimple(e,t,n={}){if(z(e))throw new Error("Static import/export syntax requires isolated-vm – start Node without SKIP_ISOLATED_VM.");try{if(n.isCodeBlock){const o=Object.keys(t);return await(await new Function(...o,`return async function codeBlock(${o.join(", ")}) { ${e} }`)(...o.map(c=>t[c])))(...o.map(c=>t[c]))}else return new Function(...Object.keys(t),`return ${e};`)(...Object.values(t))}catch(o){throw n.isCodeBlock?new q(e,o):new M(e,o)}}static async evaluateSecure(e,t,n,o={}){if(!w)throw new Error("isolated-vm not available");const r=new w.Isolate({memoryLimit:32}),a=await r.createContext(),c=a.global;try{await this.setupIsolateEnvironment(c,t);const i=new Map,h=this.createModuleResolver(r,a,i,n);let u;return z(e)?u=await this.evaluateESModule(r,a,e,o,h):u=await this.evaluateSimpleScript(r,a,e,t,o),this.deepClone(u)}catch(i){throw o.isCodeBlock?new q(e,i):new M(e,i)}finally{a.release(),r.dispose()}}static async setupIsolateEnvironment(e,t){if(!w)throw new Error("isolated-vm not available");const n=new w.Callback((...r)=>console.log(...r)),o=new w.ExternalCopy({log:n}).copyInto();await e.set("console",o);for(const[r,a]of Object.entries(t))typeof a=="function"?await e.set(r,new w.Callback(a)):await e.set(r,new w.ExternalCopy(a).copyInto())}static createModuleResolver(e,t,n,o){return async r=>{if(n.has(r))return n.get(r);if(r.startsWith("blue:")){const a=r.slice(5),c=o.loadBlueContent;if(typeof c!="function")throw new Error(`ProcessingContext is missing a loadBlueContent(blueId) implementation (needed for ${r})`);const i=await c(a),h=await e.compileModule(i);return n.set(r,h),await h.instantiate(t,this.createModuleResolver(e,t,n,o)),h}if(/^https?:\/\//.test(r)){let a;if(typeof o.loadExternalModule=="function")a=await o.loadExternalModule(r);else throw new Error(`ProcessingContext is missing a loadExternalModule(url) implementation (needed for ${r})`);const c=await e.compileModule(a);return n.set(r,c),await c.instantiate(t,this.createModuleResolver(e,t,n,o)),c}throw new Error(`Unsupported module specifier "${r}"`)}}static async evaluateSimpleScript(e,t,n,o,r){const a=Object.keys(o).join(", "),c=Object.keys(o).map(u=>u),i=`(async (${a}) => { ${r.isCodeBlock?n:`return (${n});`} })(${c.join(", ")})`;return await(await e.compileScript(i)).run(t,{timeout:r.timeout??500,promise:!0,copy:!0,release:!0})}static async evaluateESModule(e,t,n,o,r){let a=n;if(o.isCodeBlock){const h=/^\s*(import\s.+?;|export\s.+?;)/gm,u=(n.match(h)||[]).join(`
2
2
  `),p=n.replace(h,"").trim();a=`
3
3
  ${u}
4
4
  const run = function() {
5
5
  ${p}
6
6
  };
7
7
  export default run();
8
- `}const c=await e.compileModule(a);return await c.instantiate(t,r),await c.evaluate({timeout:o.timeout??500,promise:!0,reference:!0,release:!0}),await c.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 D{static createStandardBindings(e,t,n){const o=e.getBlue(),r=o.nodeToJson(t.payload,"simple"),a=m.isBigNumber(r)?r.toNumber():r;return{document:c=>{const i=e.get(c);return m.isBigNumber(i)?i.toNumber():C(i)?o.nodeToJson(i,"original"):i},event:a,steps:n}}}function R(s,e){const{op:t,path:n,val:o,from:r}=s;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 a={type:"Document Update",op:t,path:n};return o!==void 0&&(a.val=o),r!==void 0&&(a.from=r),e.jsonValueToNode(a)}function Me(s){return s.jsonValueToNode({type:"Document Processing Initiated"})}const qe=/^\$\{(.*)\}$/,O=s=>typeof s!="string"?!1:qe.test(s),H=s=>{if(!O(s))throw new Error(`Invalid expression: ${s}`);return s.slice(2,-1)};class $e{constructor(){l(this,"stepType","Update Document")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,d.UpdateDocumentSchema)}async execute(e,t,n,o,r){const a=n.getBlue();if(!m.BlueNodeTypeSchema.isTypeOf(e,d.UpdateDocumentSchema))return;const c=await this.evaluateChangeset(e.get("/changeset"),n,t,r),i=m.applyBlueNodePatch(e,{op:"replace",path:"/changeset",val:c}),h=n.getBlue().nodeToSchemaOutput(i,d.UpdateDocumentSchema);for(const u of h.changeset??[]){if(!u.path)continue;const p=u.val;if((u.op==="replace"||u.op==="add")&&T.isNonNullable(p)){const f=await this.evaluateChangeValue(p,n,t,r);n.addPatch({op:u.op,path:u.path,val:f}),n.emitEvent({payload:R({op:u.op,path:n.resolvePath(u.path),val:a.nodeToJson(f,"original")},a)})}u.op==="remove"&&(n.addPatch({op:u.op,path:u.path}),n.emitEvent({payload:R({op:u.op,path:n.resolvePath(u.path),val:null},a)}))}}async evaluateChangeset(e,t,n,o){const r=t.getBlue();if(O(e)){const a=H(e),c=await $.evaluate({code:a,ctx:t,bindings:D.createStandardBindings(t,n,o)});return r.jsonValueToNode(c??null)}if(C(e))return e;throw new Error("Invalid changeset: expected a string or document node")}async evaluateChangeValue(e,t,n,o){const r=e.getValue(),a=t.getBlue();if(O(r)){const c=H(r),i=await $.evaluate({code:c,ctx:t,bindings:D.createStandardBindings(t,n,o)});return a.jsonValueToNode(i??null)}return e}}class De{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})}}class Ae{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 a=n.getBlue(),c=a.nodeToSchemaOutput(e,d.JavaScriptCodeSchema);if(!c.code)throw new Error("JavaScript code is required");const i=await $.evaluate({code:c.code,ctx:n,bindings:D.createStandardBindings(n,t,r),options:{isCodeBlock:!0,timeout:500}});if(i&&typeof i=="object"&&"events"in i){const h=i;if(Array.isArray(h.events))for(const u of h.events)n.emitEvent({payload:a.jsonValueToNode(u)})}return i}}const xe=[new $e,new De,new Ae];class V{constructor(e=xe){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 a=n.getBlue().nodeToSchemaOutput(t,d.SequentialWorkflowSchema).channel;return e.source==="channel"&&e.channelName===a}async handle(e,t,n,o){var c;const r={},a=(c=t.getProperties())==null?void 0:c.steps.getItems();for(const[i,h]of(a??[]).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${i+1}`;r[g]=p}await n.flush()}}}class ie{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 V}supports(e,t,n){const a=n.getBlue().nodeToSchemaOutput(t,d.SequentialWorkflowOperationSchema).operation,c=e.channelName;return e.source==="channel"&&T.isNonNullable(c)&&T.isNonNullable(a)&&c===a}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=s=>m.BlueNodeTypeSchema.isTypeOf(s.payload,d.TimelineEntrySchema);class le extends k{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 a=o.getBlue().nodeToSchemaOutput(t.payload,d.TimelineEntrySchema),c=o.getBlue().nodeToSchemaOutput(n,d.TimelineChannelSchema),i=(u=a.timeline)==null?void 0:u.timelineId;return y(c.timelineId)&&y(i)&&i===c.timelineId}handle(t,n,o,r){Q(t)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}const je=[new se,new ee,new G,new le,new oe,new re,new Z,new ne,new ae,new V,new ie,new te];class Ve{constructor(e,t=je){l(this,"taskCounter",0);l(this,"eventCounter",0);l(this,"registry");l(this,"queue");l(this,"router");l(this,"checkpointCache",new Oe);this.blue=e,this.registry=new Te(t),this.queue=new Pe,this.router=new Ie(this.blue,this.registry,this.queue,()=>++this.taskCounter,()=>++this.eventCounter),this.register(new Y(this.checkpointCache),9999)}register(e,t){this.registry.register(e,t)}async initialize(e){let t=U(N(e),this.blue);const n={payload:Me(this.blue)},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=Be(t,this.blue),{state:B(t),emitted:o}}async processEvents(e,t){let n=U(N(e),this.blue);const o=[];if(!X(n,this.blue))throw new Error("Document is not initialized");for(const r of t)try{const a={payload:r,source:"external"};await this.router.route(n,[],a,0);const c=await this.drainQueue(n);n=c.state,o.push(...c.emitted);const i=this.checkpointCache.flush(n);i.length&&(n=_(n,i))}finally{this.checkpointCache.clear()}return{state:B(n),emitted:o}}async drainQueue(e){var a;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 c=this.queue.pop(),{nodePath:i,contractName:h,contractNode:u,event:p}=c,f=t.get(i);if(!C(f)||!((a=f.getContracts())!=null&&a[h])||!u.getType())continue;const g=this.registry.get(u.getType());if(!g){console.warn(`No processor registered for contract: ${h}`);continue}const v=new K(()=>t,c,this.blue,async b=>{for(const E of b)if(E.kind==="patch"){const he=j(t,this.blue);for(const I of he){const de=E.patch.op==="move"||E.patch.op==="copy"?[E.patch.from,E.patch.path]:[E.patch.path],W=v.getNodePath(),pe=de.some(fe=>J(fe,I.absPath)),me=J(W,I.absPath);if(pe&&!me)throw new x(E.patch,I.absPath,W)}try{t=_(t,[E.patch])}catch(I){throw Ne(h,p,I),I}}else E.kind==="event"&&(n.push(E.event.payload),await this.router.route(t,[],E.event,c.key[5]))});await g.handle(p,u,v,h),await v.flush()}return{state:t,emitted:n}}}class ue{process(e,t){const n=t.getValue();if(O(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(O(n)&&e.getValue()!==n&&n!==void 0){const o=e.clone();return o.setValue(n),o}return e}}const We=Object.freeze(Object.defineProperty({__proto__:null,ExpressionPreserver:ue},Symbol.toStringTag,{value:"Module"}));function Je(){return new m.MergingProcessors.SequentialMergingProcessor([new m.MergingProcessors.ValuePropagator,new ue,new m.MergingProcessors.TypeAssigner,new m.MergingProcessors.ListProcessor,new m.MergingProcessors.DictionaryProcessor,new m.MergingProcessors.BasicTypesVerifier])}exports.BlueDocumentProcessor=Ve;exports.ChannelEventCheckpointProcessor=Y;exports.CodeBlockEvaluationError=q;exports.CompositeTimelineChannelProcessor=Z;exports.DocumentUpdateChannelProcessor=G;exports.EmbeddedDocumentModificationError=x;exports.EmbeddedNodeChannelProcessor=ee;exports.ExpressionEvaluationError=M;exports.InitializedMarkerProcessor=te;exports.LifecycleEventChannelProcessor=ne;exports.MergingProcessors=We;exports.MyOSAgentChannelProcessor=re;exports.MyOSTimelineChannelProcessor=oe;exports.OperationProcessor=ae;exports.PatchApplicationError=A;exports.ProcessEmbeddedProcessor=se;exports.SequentialWorkflowOperationProcessor=ie;exports.SequentialWorkflowProcessor=V;exports.TimelineChannelProcessor=le;exports.createDefaultMergingProcessor=Je;
8
+ `}const c=await e.compileModule(a);return await c.instantiate(t,r),await c.evaluate({timeout:o.timeout??500,promise:!0,reference:!0,release:!0}),await c.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 D{static createStandardBindings(e,t,n){const o=e.getBlue(),r=o.nodeToJson(t.payload,"simple"),a=m.isBigNumber(r)?r.toNumber():r;return{document:c=>{const i=e.get(c);return m.isBigNumber(i)?i.toNumber():C(i)?o.nodeToJson(i,"original"):i},event:a,steps:n}}}function R(s,e){const{op:t,path:n,val:o,from:r}=s;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 a={type:"Document Update",op:t,path:n};return o!==void 0&&(a.val=o),r!==void 0&&(a.from=r),e.jsonValueToNode(a)}function Me(s){return s.jsonValueToNode({type:"Document Processing Initiated"})}const qe=/^\$\{(.*)\}$/,O=s=>typeof s!="string"?!1:qe.test(s),H=s=>{if(!O(s))throw new Error(`Invalid expression: ${s}`);return s.slice(2,-1)};class $e{constructor(){l(this,"stepType","Update Document")}supports(e){return m.BlueNodeTypeSchema.isTypeOf(e,d.UpdateDocumentSchema)}async execute(e,t,n,o,r){const a=n.getBlue();if(!m.BlueNodeTypeSchema.isTypeOf(e,d.UpdateDocumentSchema))return;const c=await this.evaluateChangeset(e.get("/changeset"),n,t,r),i=m.applyBlueNodePatch(e,{op:"replace",path:"/changeset",val:c}),h=n.getBlue().nodeToSchemaOutput(i,d.UpdateDocumentSchema);for(const u of h.changeset??[]){if(!u.path)continue;const p=u.val;if((u.op==="replace"||u.op==="add")&&T.isNonNullable(p)){const f=await this.evaluateChangeValue(p,n,t,r);n.addPatch({op:u.op,path:u.path,val:f}),n.emitEvent({payload:R({op:u.op,path:n.resolvePath(u.path),val:a.nodeToJson(f,"original")},a)})}u.op==="remove"&&(n.addPatch({op:u.op,path:u.path}),n.emitEvent({payload:R({op:u.op,path:n.resolvePath(u.path),val:null},a)}))}}async evaluateChangeset(e,t,n,o){const r=t.getBlue();if(O(e)){const a=H(e),c=await $.evaluate({code:a,ctx:t,bindings:D.createStandardBindings(t,n,o)});return r.jsonValueToNode(c??null)}if(C(e))return e;throw new Error("Invalid changeset: expected a string or document node")}async evaluateChangeValue(e,t,n,o){const r=e.getValue(),a=t.getBlue();if(O(r)){const c=H(r),i=await $.evaluate({code:c,ctx:t,bindings:D.createStandardBindings(t,n,o)});return a.jsonValueToNode(i??null)}return e}}class De{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})}}class Ae{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 a=n.getBlue(),c=a.nodeToSchemaOutput(e,d.JavaScriptCodeSchema);if(!c.code)throw new Error("JavaScript code is required");const i=await $.evaluate({code:c.code,ctx:n,bindings:D.createStandardBindings(n,t,r),options:{isCodeBlock:!0,timeout:500}});if(i&&typeof i=="object"&&"events"in i){const h=i;if(Array.isArray(h.events))for(const u of h.events)n.emitEvent({payload:a.jsonValueToNode(u)})}return i}}const je=[new $e,new De,new Ae];class V{constructor(e=je){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 a=n.getBlue().nodeToSchemaOutput(t,d.SequentialWorkflowSchema).channel;return e.source==="channel"&&e.channelName===a}async handle(e,t,n,o){var c;const r={},a=(c=t.getProperties())==null?void 0:c.steps.getItems();for(const[i,h]of(a??[]).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${i+1}`;r[g]=p}await n.flush()}}}class ie{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 V}supports(e,t,n){const a=n.getBlue().nodeToSchemaOutput(t,d.SequentialWorkflowOperationSchema).operation,c=e.channelName;return e.source==="channel"&&T.isNonNullable(c)&&T.isNonNullable(a)&&c===a}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=s=>m.BlueNodeTypeSchema.isTypeOf(s.payload,d.TimelineEntrySchema);class le extends k{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 a=o.getBlue().nodeToSchemaOutput(t.payload,d.TimelineEntrySchema),c=o.getBlue().nodeToSchemaOutput(n,d.TimelineChannelSchema),i=(u=a.timeline)==null?void 0:u.timelineId;return y(c.timelineId)&&y(i)&&i===c.timelineId}handle(t,n,o,r){Q(t)&&o.emitEvent({payload:t.payload,channelName:r,source:"channel"})}}const xe=[new se,new ee,new G,new le,new oe,new re,new Z,new ne,new ae,new V,new ie,new te];class Ve{constructor(e,t=xe){l(this,"taskCounter",0);l(this,"eventCounter",0);l(this,"registry");l(this,"queue");l(this,"router");l(this,"checkpointCache",new Oe);this.blue=e,this.registry=new Te(t),this.queue=new Pe,this.router=new Ie(this.blue,this.registry,this.queue,()=>++this.taskCounter,()=>++this.eventCounter),this.register(new Y(this.checkpointCache),9999)}register(e,t){this.registry.register(e,t)}async initialize(e){let t=U(N(e),this.blue);const n={payload:Me(this.blue)},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=Be(t,this.blue),{state:B(t),emitted:o}}async processEvents(e,t){let n=U(N(e),this.blue);const o=[];if(!X(n,this.blue))throw new Error("Document is not initialized");for(const r of t)try{const a={payload:r,source:"external"};await this.router.route(n,[],a,0);const c=await this.drainQueue(n);n=c.state,o.push(...c.emitted);const i=this.checkpointCache.flush(n);i.length&&(n=_(n,i))}finally{this.checkpointCache.clear()}return{state:B(n),emitted:o}}async drainQueue(e){var a;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 c=this.queue.pop(),{nodePath:i,contractName:h,contractNode:u,event:p}=c,f=t.get(i);if(!C(f)||!((a=f.getContracts())!=null&&a[h])||!u.getType())continue;const g=this.registry.get(u.getType());if(!g){console.warn(`No processor registered for contract: ${h}`);continue}const v=new K(()=>t,c,this.blue,async S=>{for(const E of S)if(E.kind==="patch"){const he=x(t,this.blue);for(const I of he){const de=E.patch.op==="move"||E.patch.op==="copy"?[E.patch.from,E.patch.path]:[E.patch.path],W=v.getNodePath(),pe=de.some(fe=>J(fe,I.absPath)),me=J(W,I.absPath);if(pe&&!me)throw new j(E.patch,I.absPath,W)}try{t=_(t,[E.patch])}catch(I){throw Ne(h,p,I),I}}else E.kind==="event"&&(n.push(E.event.payload),await this.router.route(t,[],E.event,c.key[5]))});await g.handle(p,u,v,h),await v.flush()}return{state:t,emitted:n}}}class ue{process(e,t){const n=t.getValue();if(O(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(O(n)&&e.getValue()!==n&&n!==void 0){const o=e.clone();return o.setValue(n),o}return e}}const We=Object.freeze(Object.defineProperty({__proto__:null,ExpressionPreserver:ue},Symbol.toStringTag,{value:"Module"}));function Je(){return new m.MergingProcessors.SequentialMergingProcessor([new m.MergingProcessors.ValuePropagator,new ue,new m.MergingProcessors.TypeAssigner,new m.MergingProcessors.ListProcessor,new m.MergingProcessors.DictionaryProcessor,new m.MergingProcessors.BasicTypesVerifier])}exports.BlueDocumentProcessor=Ve;exports.ChannelEventCheckpointProcessor=Y;exports.CodeBlockEvaluationError=q;exports.CompositeTimelineChannelProcessor=Z;exports.DocumentUpdateChannelProcessor=G;exports.EmbeddedDocumentModificationError=j;exports.EmbeddedNodeChannelProcessor=ee;exports.ExpressionEvaluationError=M;exports.InitializedMarkerProcessor=te;exports.LifecycleEventChannelProcessor=ne;exports.MergingProcessors=We;exports.MyOSAgentChannelProcessor=re;exports.MyOSTimelineChannelProcessor=oe;exports.OperationProcessor=ae;exports.PatchApplicationError=A;exports.ProcessEmbeddedProcessor=se;exports.SequentialWorkflowOperationProcessor=ie;exports.SequentialWorkflowProcessor=V;exports.TimelineChannelProcessor=le;exports.createDefaultMergingProcessor=Je;
package/dist/index.mjs CHANGED
@@ -1,16 +1,16 @@
1
1
  var me = Object.defineProperty;
2
2
  var ye = (s, e, t) => e in s ? me(s, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : s[e] = t;
3
3
  var l = (s, e, t) => ye(s, typeof e != "symbol" ? e + "" : e, t);
4
- import { ProcessEmbeddedSchema as D, ChannelEventCheckpointSchema as ge, blueIds as m, InitializedMarkerSchema as Ee, CompositeTimelineChannelSchema as we, DocumentUpdateChannelSchema as ve, EmbeddedNodeChannelSchema as _, LifecycleEventSchema as be, TimelineEntrySchema as N, OperationSchema as Te, OperationRequestSchema as Pe, UpdateDocumentSchema as $, TriggerEventSchema as q, JavaScriptCodeSchema as A, SequentialWorkflowSchema as Se, SequentialWorkflowOperationSchema as Ce, TimelineChannelSchema as ke } from "@blue-repository/core-dev";
5
- import { applyBlueNodePatch as G, BlueNodeTypeSchema as w, BlueNode as Ie, isBigNumber as x, MergingProcessors as k } from "@blue-labs/language";
6
- import { deepFreeze as Ne, isNonNullable as M, deepContains as ee } from "@blue-labs/shared-utils";
7
- import { blueIds as te, MyOSTimelineEntrySchema as ne, MyOSTimelineChannelSchema as Oe, MyOSAgentEventSchema as Be, MyOSAgentChannelSchema as Me } from "@blue-repository/myos-dev";
8
- const $e = (s, e) => ({
4
+ import { ProcessEmbeddedSchema as D, ChannelEventCheckpointSchema as ge, blueIds as m, InitializedMarkerSchema as Ee, CompositeTimelineChannelSchema as we, DocumentUpdateChannelSchema as ve, EmbeddedNodeChannelSchema as _, LifecycleEventSchema as be, TimelineEntrySchema as N, OperationSchema as Pe, OperationRequestSchema as Te, UpdateDocumentSchema as $, TriggerEventSchema as q, JavaScriptCodeSchema as A, SequentialWorkflowSchema as Se, SequentialWorkflowOperationSchema as Ce, TimelineChannelSchema as ke } from "@blue-repository/core-dev";
5
+ import { applyBlueNodePatch as G, BlueNodeTypeSchema as w, BlueNode as Ie, isBigNumber as x, ResolvedBlueNode as Ne, MergingProcessors as k } from "@blue-labs/language";
6
+ import { deepFreeze as Be, isNonNullable as M, deepContains as ee } from "@blue-labs/shared-utils";
7
+ import { blueIds as te, MyOSTimelineEntrySchema as ne, MyOSTimelineChannelSchema as Oe, MyOSAgentEventSchema as Me, MyOSAgentChannelSchema as $e } from "@blue-repository/myos-dev";
8
+ const qe = (s, e) => ({
9
9
  on: (t, n) => ({ end: () => n(null) })
10
10
  });
11
- async function qe(s) {
11
+ async function Ae(s) {
12
12
  return new Promise((e, t) => {
13
- $e().on("error", t).end();
13
+ qe().on("error", t).end();
14
14
  });
15
15
  }
16
16
  const b = (...s) => s.map((e, t) => {
@@ -68,7 +68,7 @@ class oe {
68
68
  loadExternalModule(e) {
69
69
  if (!/^https?:\/\//.test(e))
70
70
  throw new Error("Only http/https URLs are allowed");
71
- return qe();
71
+ return Ae();
72
72
  }
73
73
  loadBlueContent(e) {
74
74
  throw new Error("Not implemented");
@@ -97,9 +97,9 @@ class L extends Error {
97
97
  }
98
98
  }
99
99
  function I(s) {
100
- return Ne(s);
100
+ return Be(s);
101
101
  }
102
- function O(s) {
102
+ function B(s) {
103
103
  return s.clone();
104
104
  }
105
105
  function W(s, e, t = "/", n = []) {
@@ -128,7 +128,7 @@ function z(s, e) {
128
128
  }
129
129
  function U(s, e) {
130
130
  if (!e.length) return s;
131
- let t = O(s);
131
+ let t = B(s);
132
132
  for (const n of e)
133
133
  try {
134
134
  t = G(t, n, !0);
@@ -140,10 +140,10 @@ function U(s, e) {
140
140
  function f(s) {
141
141
  return s != null;
142
142
  }
143
- function P(s) {
143
+ function T(s) {
144
144
  return s instanceof Ie;
145
145
  }
146
- class Ae {
146
+ class De {
147
147
  constructor(e = [], t = (n, o) => n < o ? -1 : n > o ? 1 : 0) {
148
148
  l(this, "data");
149
149
  l(this, "length");
@@ -182,14 +182,14 @@ class Ae {
182
182
  t[e] = r;
183
183
  }
184
184
  }
185
- const De = (s, e, t, n, o, r) => [
185
+ const xe = (s, e, t, n, o, r) => [
186
186
  -s,
187
187
  e,
188
188
  t,
189
189
  n,
190
190
  o,
191
191
  r
192
- ], xe = (s, e) => {
192
+ ], je = (s, e) => {
193
193
  for (let t = 0; t < s.key.length; t++) {
194
194
  const n = s.key[t], o = e.key[t];
195
195
  if (n !== o)
@@ -197,13 +197,13 @@ const De = (s, e, t, n, o, r) => [
197
197
  }
198
198
  return 0;
199
199
  };
200
- class je {
200
+ class Ve {
201
201
  /**
202
202
  * Creates a new task queue with the task key comparator
203
203
  */
204
204
  constructor() {
205
205
  l(this, "queue");
206
- this.queue = new Ae([], xe);
206
+ this.queue = new De([], je);
207
207
  }
208
208
  /**
209
209
  * Adds a task to the queue
@@ -228,7 +228,7 @@ class je {
228
228
  return this.queue.length;
229
229
  }
230
230
  }
231
- class Ve {
231
+ class We {
232
232
  /**
233
233
  * Creates a new contract registry
234
234
  *
@@ -283,7 +283,7 @@ class Ve {
283
283
  return this.processors.values();
284
284
  }
285
285
  }
286
- class We {
286
+ class Je {
287
287
  constructor() {
288
288
  l(this, "isEnabled");
289
289
  this.isEnabled = process.env.TRACE_BLUE_ENABLED === "true";
@@ -350,8 +350,8 @@ class We {
350
350
  return this.isEnabled;
351
351
  }
352
352
  }
353
- const Je = 64;
354
- class _e {
353
+ const _e = 64;
354
+ class Fe {
355
355
  /**
356
356
  * Creates a new event router
357
357
  *
@@ -362,7 +362,7 @@ class _e {
362
362
  */
363
363
  constructor(e, t, n, o, r) {
364
364
  l(this, "traceManager");
365
- this.blue = e, this.registry = t, this.queue = n, this.getNextTaskId = o, this.getNextEventSeq = r, this.traceManager = new We();
365
+ this.blue = e, this.registry = t, this.queue = n, this.getNextTaskId = o, this.getNextEventSeq = r, this.traceManager = new Je();
366
366
  }
367
367
  /**
368
368
  * Routes an event to matching contracts in the document
@@ -386,7 +386,7 @@ class _e {
386
386
  }
387
387
  }
388
388
  const a = b("/", t.join("/")), c = e.get(a);
389
- P(c) && await this.traverseContracts({
389
+ T(c) && await this.traverseContracts({
390
390
  doc: e,
391
391
  node: c,
392
392
  nodePath: a,
@@ -467,7 +467,7 @@ class _e {
467
467
  afterTaskId: i,
468
468
  inlineDepth: h
469
469
  } = e;
470
- if (h >= Je)
470
+ if (h >= _e)
471
471
  throw new Error("Adapter recursion limit reached");
472
472
  const u = this.traceManager.addHop(
473
473
  n,
@@ -476,13 +476,13 @@ class _e {
476
476
  );
477
477
  await t.handle(u, o, r, a);
478
478
  const d = await r.flush();
479
- if (d.find((T) => T.kind === "patch"))
479
+ if (d.find((P) => P.kind === "patch"))
480
480
  throw new Error(
481
481
  `Contract "${a}" (adapter) attempted to patch the document`
482
482
  );
483
- const y = d.filter((T) => T.kind === "event");
484
- for (const T of y)
485
- await this.route(c, [], T.event, i, h + 1);
483
+ const y = d.filter((P) => P.kind === "event");
484
+ for (const P of y)
485
+ await this.route(c, [], P.event, i, h + 1);
486
486
  }
487
487
  /**
488
488
  * Schedules a handler contract for future execution
@@ -493,7 +493,7 @@ class _e {
493
493
  console.warn(`Contract node type is not defined for: ${n}`);
494
494
  return;
495
495
  }
496
- const h = this.registry.orderOf(i), u = t.get("/order"), d = x(u) ? u.toNumber() : 0, p = this.getNextTaskId() + c, y = De(
496
+ const h = this.registry.orderOf(i), u = t.get("/order"), d = x(u) ? u.toNumber() : 0, p = this.getNextTaskId() + c, y = xe(
497
497
  a,
498
498
  r.seq,
499
499
  h,
@@ -516,15 +516,15 @@ class _e {
516
516
  return e.source === "channel" && !!e.originNodePath && e.originNodePath !== t;
517
517
  }
518
518
  }
519
- const Fe = (s, e, t) => {
519
+ const Le = (s, e, t) => {
520
520
  (t instanceof re || t instanceof ae) && console.error(
521
521
  `[Blue] Failed to apply patches for contract "${s}" on event ${JSON.stringify(e)}`,
522
522
  t
523
523
  );
524
524
  };
525
525
  function R(s, e) {
526
- const t = O(s), n = (o) => {
527
- if (!P(o)) return;
526
+ const t = B(s), n = (o) => {
527
+ if (!T(o)) return;
528
528
  const r = o.getContracts();
529
529
  (!(r != null && r.checkpoint) || !w.isTypeOf(
530
530
  r.checkpoint,
@@ -543,13 +543,13 @@ function R(s, e) {
543
543
  n(t);
544
544
  for (const { absPath: o } of W(t, e)) {
545
545
  const r = t.get(o);
546
- P(r) && n(r);
546
+ T(r) && n(r);
547
547
  }
548
548
  return I(t);
549
549
  }
550
- function Le(s, e) {
551
- const t = O(s);
552
- return P(t) && (se(t, e) || t.addContract(
550
+ function ze(s, e) {
551
+ const t = B(s);
552
+ return T(t) && (se(t, e) || t.addContract(
553
553
  "initialized",
554
554
  e.jsonValueToNode({
555
555
  type: {
@@ -567,7 +567,7 @@ function se(s, e) {
567
567
  })
568
568
  );
569
569
  }
570
- class ze {
570
+ class Ue {
571
571
  constructor(e) {
572
572
  l(this, "contractType", "Channel Event Checkpoint");
573
573
  l(this, "contractBlueId", m["Channel Event Checkpoint"]);
@@ -578,15 +578,28 @@ class ze {
578
578
  var t, n;
579
579
  return e.source === "channel" && ((t = e.rootEvent) == null ? void 0 : t.payload) === e.payload && ((n = e.rootEvent) == null ? void 0 : n.source) === "external";
580
580
  }
581
+ async getEventBlueId(e, t) {
582
+ var o;
583
+ const n = (o = e.rootEvent) == null ? void 0 : o.payload;
584
+ if (!n)
585
+ throw new Error(
586
+ "Cannot calculate blueId for checkpoint: missing root event payload"
587
+ );
588
+ if (n instanceof Ne) {
589
+ const r = n.getMinimalNode();
590
+ return await t.getBlue().calculateBlueId(r);
591
+ }
592
+ return await t.getBlue().calculateBlueId(n);
593
+ }
581
594
  async handle(e, t, n) {
582
595
  var a;
583
596
  if (!e.channelName || !((a = e.rootEvent) != null && a.seq)) return;
584
- const o = await n.getBlue().calculateBlueId(e.rootEvent.payload), r = n.getNodePath().replace(/\/contracts\/checkpoint$/, "");
597
+ const o = await this.getEventBlueId(e, n), r = n.getNodePath().replace(/\/contracts\/checkpoint$/, "");
585
598
  this.cache.record(r, e, o);
586
599
  }
587
600
  }
588
601
  const H = (s, e) => s.get(e) !== void 0;
589
- class Ue {
602
+ class Re {
590
603
  constructor() {
591
604
  l(this, "firstSeen", /* @__PURE__ */ new Map());
592
605
  }
@@ -632,7 +645,7 @@ class S {
632
645
  return e.source !== "channel";
633
646
  }
634
647
  }
635
- class Re extends S {
648
+ class He extends S {
636
649
  constructor() {
637
650
  super(...arguments);
638
651
  l(this, "contractType", "Composite Timeline Channel");
@@ -650,7 +663,7 @@ class Re extends S {
650
663
  });
651
664
  }
652
665
  }
653
- class He extends S {
666
+ class Qe extends S {
654
667
  constructor() {
655
668
  super(...arguments);
656
669
  l(this, "contractType", "Document Update Channel");
@@ -672,7 +685,7 @@ class He extends S {
672
685
  });
673
686
  }
674
687
  }
675
- class Qe extends S {
688
+ class Ke extends S {
676
689
  constructor() {
677
690
  super(...arguments);
678
691
  l(this, "contractType", "Embedded Node Channel");
@@ -692,7 +705,7 @@ class Qe extends S {
692
705
  });
693
706
  }
694
707
  }
695
- class Ke {
708
+ class Xe {
696
709
  constructor() {
697
710
  l(this, "contractType", "Initialized Marker");
698
711
  l(this, "contractBlueId", m["Initialized Marker"]);
@@ -704,7 +717,7 @@ class Ke {
704
717
  handle() {
705
718
  }
706
719
  }
707
- class Xe extends S {
720
+ class Ye extends S {
708
721
  constructor() {
709
722
  super(...arguments);
710
723
  l(this, "contractType", "Lifecycle Event Channel");
@@ -749,7 +762,7 @@ const Q = (s, e) => {
749
762
  const t = e.getBlue();
750
763
  return t.isTypeOf(s.payload, N) || t.isTypeOf(s.payload, ne);
751
764
  };
752
- class Ye extends S {
765
+ class Ze extends S {
753
766
  constructor() {
754
767
  super(...arguments);
755
768
  l(this, "contractType", "MyOS Timeline Channel");
@@ -772,7 +785,7 @@ class Ye extends S {
772
785
  });
773
786
  }
774
787
  }
775
- class Ze extends S {
788
+ class Ge extends S {
776
789
  constructor() {
777
790
  super(...arguments);
778
791
  l(this, "contractType", "MyOS Agent Channel");
@@ -805,10 +818,10 @@ class Ze extends S {
805
818
  parseEventAndChannel(t, n, o) {
806
819
  const r = o.getBlue(), a = r.nodeToSchemaOutput(
807
820
  t.payload,
808
- Be
821
+ Me
809
822
  ), c = r.nodeToSchemaOutput(
810
823
  n,
811
- Me
824
+ $e
812
825
  );
813
826
  return { myosAgentEvent: a, myosAgentChannel: c };
814
827
  }
@@ -851,14 +864,14 @@ class Ze extends S {
851
864
  }
852
865
  }
853
866
  }
854
- class Ge {
867
+ class et {
855
868
  constructor() {
856
869
  l(this, "contractType", "Operation");
857
870
  l(this, "contractBlueId", m.Operation);
858
871
  l(this, "role", "adapter");
859
872
  }
860
873
  supports(e, t, n, o) {
861
- const a = n.getBlue().nodeToSchemaOutput(t, Te), c = this.parseEventPayload(e, n);
874
+ const a = n.getBlue().nodeToSchemaOutput(t, Pe), c = this.parseEventPayload(e, n);
862
875
  return f(c == null ? void 0 : c.operation) && c.operation === o && e.source === "channel" && e.channelName === a.channel;
863
876
  }
864
877
  async handle(e, t, n, o) {
@@ -880,13 +893,13 @@ class Ge {
880
893
  if (o.message)
881
894
  return n.nodeToSchemaOutput(
882
895
  o.message,
883
- Pe
896
+ Te
884
897
  );
885
898
  }
886
899
  return null;
887
900
  }
888
901
  }
889
- class et {
902
+ class tt {
890
903
  constructor() {
891
904
  l(this, "contractType", "Process Embedded");
892
905
  l(this, "role", "adapter");
@@ -1102,7 +1115,7 @@ class V {
1102
1115
  return {
1103
1116
  document: (c) => {
1104
1117
  const i = e.get(c);
1105
- return x(i) ? i.toNumber() : P(i) ? o.nodeToJson(i, "original") : i;
1118
+ return x(i) ? i.toNumber() : T(i) ? o.nodeToJson(i, "original") : i;
1106
1119
  },
1107
1120
  event: a,
1108
1121
  steps: n
@@ -1122,17 +1135,17 @@ function X(s, e) {
1122
1135
  };
1123
1136
  return o !== void 0 && (a.val = o), r !== void 0 && (a.from = r), e.jsonValueToNode(a);
1124
1137
  }
1125
- function tt(s) {
1138
+ function nt(s) {
1126
1139
  return s.jsonValueToNode({
1127
1140
  type: "Document Processing Initiated"
1128
1141
  });
1129
1142
  }
1130
- const nt = /^\$\{(.*)\}$/, B = (s) => typeof s != "string" ? !1 : nt.test(s), Y = (s) => {
1131
- if (!B(s))
1143
+ const ot = /^\$\{(.*)\}$/, O = (s) => typeof s != "string" ? !1 : ot.test(s), Y = (s) => {
1144
+ if (!O(s))
1132
1145
  throw new Error(`Invalid expression: ${s}`);
1133
1146
  return s.slice(2, -1);
1134
1147
  };
1135
- class ot {
1148
+ class rt {
1136
1149
  constructor() {
1137
1150
  l(this, "stepType", "Update Document");
1138
1151
  }
@@ -1191,7 +1204,7 @@ class ot {
1191
1204
  }
1192
1205
  async evaluateChangeset(e, t, n, o) {
1193
1206
  const r = t.getBlue();
1194
- if (B(e)) {
1207
+ if (O(e)) {
1195
1208
  const a = Y(e), c = await j.evaluate({
1196
1209
  code: a,
1197
1210
  ctx: t,
@@ -1203,13 +1216,13 @@ class ot {
1203
1216
  });
1204
1217
  return r.jsonValueToNode(c ?? null);
1205
1218
  }
1206
- if (P(e))
1219
+ if (T(e))
1207
1220
  return e;
1208
1221
  throw new Error("Invalid changeset: expected a string or document node");
1209
1222
  }
1210
1223
  async evaluateChangeValue(e, t, n, o) {
1211
1224
  const r = e.getValue(), a = t.getBlue();
1212
- if (B(r)) {
1225
+ if (O(r)) {
1213
1226
  const c = Y(r), i = await j.evaluate({
1214
1227
  code: c,
1215
1228
  ctx: t,
@@ -1224,7 +1237,7 @@ class ot {
1224
1237
  return e;
1225
1238
  }
1226
1239
  }
1227
- class rt {
1240
+ class at {
1228
1241
  constructor() {
1229
1242
  l(this, "stepType", "Trigger Event");
1230
1243
  }
@@ -1240,7 +1253,7 @@ class rt {
1240
1253
  });
1241
1254
  }
1242
1255
  }
1243
- class at {
1256
+ class st {
1244
1257
  constructor() {
1245
1258
  l(this, "stepType", "JavaScript Code");
1246
1259
  }
@@ -1275,13 +1288,13 @@ class at {
1275
1288
  return i;
1276
1289
  }
1277
1290
  }
1278
- const st = [
1279
- new ot(),
1291
+ const ct = [
1280
1292
  new rt(),
1281
- new at()
1293
+ new at(),
1294
+ new st()
1282
1295
  ];
1283
1296
  class ie {
1284
- constructor(e = st) {
1297
+ constructor(e = ct) {
1285
1298
  l(this, "contractType", "Sequential Workflow");
1286
1299
  l(this, "contractBlueId", m["Sequential Workflow"]);
1287
1300
  l(this, "role", "handler");
@@ -1321,7 +1334,7 @@ class ie {
1321
1334
  }
1322
1335
  }
1323
1336
  }
1324
- class ct {
1337
+ class it {
1325
1338
  constructor(e) {
1326
1339
  l(this, "contractType", "Sequential Workflow Operation");
1327
1340
  l(this, "contractBlueId", m["Sequential Workflow Operation"]);
@@ -1348,7 +1361,7 @@ class ct {
1348
1361
  }
1349
1362
  }
1350
1363
  const Z = (s) => w.isTypeOf(s.payload, N);
1351
- class it extends S {
1364
+ class lt extends S {
1352
1365
  constructor() {
1353
1366
  super(...arguments);
1354
1367
  l(this, "contractType", "Timeline Channel");
@@ -1371,44 +1384,44 @@ class it extends S {
1371
1384
  });
1372
1385
  }
1373
1386
  }
1374
- const lt = [
1375
- new et(),
1387
+ const ut = [
1388
+ new tt(),
1376
1389
  // channels
1390
+ new Ke(),
1377
1391
  new Qe(),
1378
- new He(),
1379
- new it(),
1380
- new Ye(),
1392
+ new lt(),
1381
1393
  new Ze(),
1382
- new Re(),
1383
- new Xe(),
1384
1394
  new Ge(),
1395
+ new He(),
1396
+ new Ye(),
1397
+ new et(),
1385
1398
  // sequential workflows
1386
1399
  new ie(),
1387
- new ct(),
1400
+ new it(),
1388
1401
  // markers
1389
- new Ke()
1402
+ new Xe()
1390
1403
  ];
1391
- class yt {
1404
+ class gt {
1392
1405
  /**
1393
1406
  * Creates a new document processor
1394
1407
  *
1395
1408
  * @param processors - Initial list of processors to register
1396
1409
  */
1397
- constructor(e, t = lt) {
1410
+ constructor(e, t = ut) {
1398
1411
  l(this, "taskCounter", 0);
1399
1412
  l(this, "eventCounter", 0);
1400
1413
  l(this, "registry");
1401
1414
  l(this, "queue");
1402
1415
  l(this, "router");
1403
- l(this, "checkpointCache", new Ue());
1404
- this.blue = e, this.registry = new Ve(t), this.queue = new je(), this.router = new _e(
1416
+ l(this, "checkpointCache", new Re());
1417
+ this.blue = e, this.registry = new We(t), this.queue = new Ve(), this.router = new Fe(
1405
1418
  this.blue,
1406
1419
  this.registry,
1407
1420
  this.queue,
1408
1421
  () => ++this.taskCounter,
1409
1422
  () => ++this.eventCounter
1410
1423
  ), this.register(
1411
- new ze(this.checkpointCache),
1424
+ new Ue(this.checkpointCache),
1412
1425
  9999
1413
1426
  );
1414
1427
  }
@@ -1430,11 +1443,11 @@ class yt {
1430
1443
  async initialize(e) {
1431
1444
  let t = R(I(e), this.blue);
1432
1445
  const n = {
1433
- payload: tt(this.blue)
1446
+ payload: nt(this.blue)
1434
1447
  }, o = [n.payload];
1435
1448
  await this.router.route(t, [], n, 0);
1436
1449
  const r = await this.drainQueue(t);
1437
- return t = r.state, o.push(...r.emitted), t = Le(t, this.blue), { state: O(t), emitted: o };
1450
+ return t = r.state, o.push(...r.emitted), t = ze(t, this.blue), { state: B(t), emitted: o };
1438
1451
  }
1439
1452
  /**
1440
1453
  * Processes a batch of events against the document
@@ -1459,7 +1472,7 @@ class yt {
1459
1472
  } finally {
1460
1473
  this.checkpointCache.clear();
1461
1474
  }
1462
- return { state: O(n), emitted: o };
1475
+ return { state: B(n), emitted: o };
1463
1476
  }
1464
1477
  /**
1465
1478
  * Drains the task queue and applies all actions
@@ -1473,7 +1486,7 @@ class yt {
1473
1486
  if (++r > o)
1474
1487
  throw new Error("Possible cycle – too many iterations");
1475
1488
  const c = this.queue.pop(), { nodePath: i, contractName: h, contractNode: u, event: d } = c, p = t.get(i);
1476
- if (!P(p) || !((a = p.getContracts()) != null && a[h]) || !u.getType()) continue;
1489
+ if (!T(p) || !((a = p.getContracts()) != null && a[h]) || !u.getType()) continue;
1477
1490
  const y = this.registry.get(u.getType());
1478
1491
  if (!y) {
1479
1492
  console.warn(`No processor registered for contract: ${h}`);
@@ -1483,8 +1496,8 @@ class yt {
1483
1496
  () => t,
1484
1497
  c,
1485
1498
  this.blue,
1486
- async (T) => {
1487
- for (const g of T)
1499
+ async (P) => {
1500
+ for (const g of P)
1488
1501
  if (g.kind === "patch") {
1489
1502
  const ue = W(t, this.blue);
1490
1503
  for (const C of ue) {
@@ -1504,7 +1517,7 @@ class yt {
1504
1517
  try {
1505
1518
  t = U(t, [g.patch]);
1506
1519
  } catch (C) {
1507
- throw Fe(h, d, C), C;
1520
+ throw Le(h, d, C), C;
1508
1521
  }
1509
1522
  } else g.kind === "event" && (n.push(g.event.payload), await this.router.route(t, [], g.event, c.key[5]));
1510
1523
  }
@@ -1517,7 +1530,7 @@ class yt {
1517
1530
  class le {
1518
1531
  process(e, t) {
1519
1532
  const n = t.getValue();
1520
- if (B(n)) {
1533
+ if (O(n)) {
1521
1534
  const o = t.clone();
1522
1535
  return o.setValue(n), o.setProperties(void 0), o.setItems(void 0), o.setType(void 0), o;
1523
1536
  }
@@ -1528,18 +1541,18 @@ class le {
1528
1541
  */
1529
1542
  postProcess(e, t) {
1530
1543
  const n = t.getValue();
1531
- if (B(n) && e.getValue() !== n && n !== void 0) {
1544
+ if (O(n) && e.getValue() !== n && n !== void 0) {
1532
1545
  const o = e.clone();
1533
1546
  return o.setValue(n), o;
1534
1547
  }
1535
1548
  return e;
1536
1549
  }
1537
1550
  }
1538
- const gt = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1551
+ const Et = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1539
1552
  __proto__: null,
1540
1553
  ExpressionPreserver: le
1541
1554
  }, Symbol.toStringTag, { value: "Module" }));
1542
- function Et() {
1555
+ function wt() {
1543
1556
  return new k.SequentialMergingProcessor([
1544
1557
  new k.ValuePropagator(),
1545
1558
  new le(),
@@ -1550,24 +1563,24 @@ function Et() {
1550
1563
  ]);
1551
1564
  }
1552
1565
  export {
1553
- yt as BlueDocumentProcessor,
1554
- ze as ChannelEventCheckpointProcessor,
1566
+ gt as BlueDocumentProcessor,
1567
+ Ue as ChannelEventCheckpointProcessor,
1555
1568
  L as CodeBlockEvaluationError,
1556
- Re as CompositeTimelineChannelProcessor,
1557
- He as DocumentUpdateChannelProcessor,
1569
+ He as CompositeTimelineChannelProcessor,
1570
+ Qe as DocumentUpdateChannelProcessor,
1558
1571
  ae as EmbeddedDocumentModificationError,
1559
- Qe as EmbeddedNodeChannelProcessor,
1572
+ Ke as EmbeddedNodeChannelProcessor,
1560
1573
  F as ExpressionEvaluationError,
1561
- Ke as InitializedMarkerProcessor,
1562
- Xe as LifecycleEventChannelProcessor,
1563
- gt as MergingProcessors,
1564
- Ze as MyOSAgentChannelProcessor,
1565
- Ye as MyOSTimelineChannelProcessor,
1566
- Ge as OperationProcessor,
1574
+ Xe as InitializedMarkerProcessor,
1575
+ Ye as LifecycleEventChannelProcessor,
1576
+ Et as MergingProcessors,
1577
+ Ge as MyOSAgentChannelProcessor,
1578
+ Ze as MyOSTimelineChannelProcessor,
1579
+ et as OperationProcessor,
1567
1580
  re as PatchApplicationError,
1568
- et as ProcessEmbeddedProcessor,
1569
- ct as SequentialWorkflowOperationProcessor,
1581
+ tt as ProcessEmbeddedProcessor,
1582
+ it as SequentialWorkflowOperationProcessor,
1570
1583
  ie as SequentialWorkflowProcessor,
1571
- it as TimelineChannelProcessor,
1572
- Et as createDefaultMergingProcessor
1584
+ lt as TimelineChannelProcessor,
1585
+ wt as createDefaultMergingProcessor
1573
1586
  };
@@ -7,6 +7,7 @@ export declare class ChannelEventCheckpointProcessor implements ContractProcesso
7
7
  readonly role = "handler";
8
8
  constructor(cache: CheckpointCache);
9
9
  supports(evt: EventNode): boolean;
10
+ private getEventBlueId;
10
11
  handle(event: EventNode, node: DocumentNode, ctx: ProcessingContext): Promise<void>;
11
12
  }
12
13
  //# sourceMappingURL=ChannelEventCheckpointProcessor.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ChannelEventCheckpointProcessor.d.ts","sourceRoot":"","sources":["../../src/processors/ChannelEventCheckpointProcessor.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,SAAS,EACT,iBAAiB,EAClB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAM3D,qBAAa,+BAAgC,YAAW,iBAAiB;IAK3D,OAAO,CAAC,QAAQ,CAAC,KAAK;IAJlC,QAAQ,CAAC,YAAY,8BAA8B;IACnD,QAAQ,CAAC,cAAc,iDAAuC;IAC9D,QAAQ,CAAC,IAAI,aAAa;gBAEG,KAAK,EAAE,eAAe;IAEnD,QAAQ,CAAC,GAAG,EAAE,SAAS,GAAG,OAAO;IAQ3B,MAAM,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,YAAY,EAAE,GAAG,EAAE,iBAAiB;CAS1E"}
1
+ {"version":3,"file":"ChannelEventCheckpointProcessor.d.ts","sourceRoot":"","sources":["../../src/processors/ChannelEventCheckpointProcessor.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,SAAS,EACT,iBAAiB,EAClB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAM3D,qBAAa,+BAAgC,YAAW,iBAAiB;IAK3D,OAAO,CAAC,QAAQ,CAAC,KAAK;IAJlC,QAAQ,CAAC,YAAY,8BAA8B;IACnD,QAAQ,CAAC,cAAc,iDAAuC;IAC9D,QAAQ,CAAC,IAAI,aAAa;gBAEG,KAAK,EAAE,eAAe;IAEnD,QAAQ,CAAC,GAAG,EAAE,SAAS,GAAG,OAAO;YAQnB,cAAc;IAgBtB,MAAM,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,YAAY,EAAE,GAAG,EAAE,iBAAiB;CAQ1E"}
package/dist/types.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { Blue, BlueNode, BlueNodePatch } from '@blue-labs/language';
1
+ import { Blue, BlueNode, BlueNodePatch, ResolvedBlueNode } from '@blue-labs/language';
2
2
  export type BlueId = string;
3
3
  export type DocumentNode = BlueNode;
4
- export type EventNodePayload = BlueNode;
4
+ export type EventNodePayload = BlueNode | ResolvedBlueNode;
5
5
  export interface EventNode<Payload = EventNodePayload> {
6
6
  payload: Payload;
7
7
  source?: 'channel' | 'external';
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"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"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"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"}
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@blue-labs/document-processor",
3
- "version": "1.28.0",
3
+ "version": "1.29.0",
4
4
  "dependencies": {
5
- "@blue-labs/language": "1.28.0",
6
- "@blue-labs/shared-utils": "1.28.0",
5
+ "@blue-labs/language": "1.29.0",
6
+ "@blue-labs/shared-utils": "1.29.0",
7
7
  "isolated-vm": "^5.0.4"
8
8
  },
9
9
  "main": "./dist/index.js",