@blue-labs/document-processor 1.21.1 → 1.23.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/BlueDocumentProcessor.d.ts +2 -6
- package/dist/BlueDocumentProcessor.d.ts.map +1 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/index.js +5 -5
- package/dist/index.mjs +483 -533
- package/dist/mocks/blueIds.d.ts +5 -0
- package/dist/mocks/blueIds.d.ts.map +1 -0
- package/dist/processors/BaseChannelProcessor.d.ts +0 -5
- package/dist/processors/BaseChannelProcessor.d.ts.map +1 -1
- package/dist/processors/ChannelEventCheckpointProcessor.d.ts +1 -2
- package/dist/processors/ChannelEventCheckpointProcessor.d.ts.map +1 -1
- package/dist/processors/CompositeTimelineChannelProcessor.d.ts +1 -1
- package/dist/processors/CompositeTimelineChannelProcessor.d.ts.map +1 -1
- package/dist/processors/DocumentUpdateChannelProcessor.d.ts +1 -1
- package/dist/processors/DocumentUpdateChannelProcessor.d.ts.map +1 -1
- package/dist/processors/EmbeddedNodeChannelProcessor.d.ts +1 -1
- package/dist/processors/EmbeddedNodeChannelProcessor.d.ts.map +1 -1
- package/dist/processors/InitializedMarkerProcessor.d.ts +9 -0
- package/dist/processors/InitializedMarkerProcessor.d.ts.map +1 -0
- package/dist/processors/LifecycleEventChannelProcessor.d.ts +33 -0
- package/dist/processors/LifecycleEventChannelProcessor.d.ts.map +1 -0
- package/dist/processors/MyOSAgentChannelProcessor.d.ts +1 -1
- package/dist/processors/MyOSAgentChannelProcessor.d.ts.map +1 -1
- package/dist/processors/MyOSTimelineChannelProcessor.d.ts +1 -1
- package/dist/processors/MyOSTimelineChannelProcessor.d.ts.map +1 -1
- package/dist/processors/OperationProcessor.d.ts +1 -2
- package/dist/processors/OperationProcessor.d.ts.map +1 -1
- package/dist/processors/ProcessEmbeddedProcessor.d.ts +1 -2
- package/dist/processors/ProcessEmbeddedProcessor.d.ts.map +1 -1
- package/dist/processors/SequentialWorkflowOperationProcessor.d.ts +1 -1
- package/dist/processors/SequentialWorkflowOperationProcessor.d.ts.map +1 -1
- package/dist/processors/SequentialWorkflowProcessor/SequentialWorkflowProcessor.d.ts +1 -2
- package/dist/processors/SequentialWorkflowProcessor/SequentialWorkflowProcessor.d.ts.map +1 -1
- package/dist/processors/SequentialWorkflowProcessor/steps/TriggerEventExecutor.d.ts.map +1 -1
- package/dist/processors/SequentialWorkflowProcessor/steps/UpdateDocumentExecutor.d.ts +2 -1
- package/dist/processors/SequentialWorkflowProcessor/steps/UpdateDocumentExecutor.d.ts.map +1 -1
- package/dist/processors/TimelineChannelProcessor.d.ts +1 -1
- package/dist/processors/TimelineChannelProcessor.d.ts.map +1 -1
- package/dist/processors/index.d.ts +2 -0
- package/dist/processors/index.d.ts.map +1 -1
- package/dist/routing/EventRouter.d.ts.map +1 -1
- package/dist/types.d.ts +1 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/checkpoint.d.ts.map +1 -1
- package/dist/utils/eventFactories.d.ts +37 -0
- package/dist/utils/eventFactories.d.ts.map +1 -0
- package/dist/utils/initialized.d.ts +4 -0
- package/dist/utils/initialized.d.ts.map +1 -0
- package/package.json +5 -6
- package/dist/repo/core/blue-ids/index.d.ts +0 -21
- package/dist/repo/core/blue-ids/index.d.ts.map +0 -1
- package/dist/repo/core/index.d.ts +0 -199
- package/dist/repo/core/index.d.ts.map +0 -1
- package/dist/repo/core/schema/Channel.d.ts +0 -13
- package/dist/repo/core/schema/Channel.d.ts.map +0 -1
- package/dist/repo/core/schema/CompositeTimelineChannel.d.ts +0 -17
- package/dist/repo/core/schema/CompositeTimelineChannel.d.ts.map +0 -1
- package/dist/repo/core/schema/DocumentUpdateChannel.d.ts +0 -17
- package/dist/repo/core/schema/DocumentUpdateChannel.d.ts.map +0 -1
- package/dist/repo/core/schema/EmbeddedNodeChannel.d.ts +0 -17
- package/dist/repo/core/schema/EmbeddedNodeChannel.d.ts.map +0 -1
- package/dist/repo/core/schema/JavaScriptCode.d.ts +0 -10
- package/dist/repo/core/schema/JavaScriptCode.d.ts.map +0 -1
- package/dist/repo/core/schema/JsonPatchEntry.d.ts +0 -22
- package/dist/repo/core/schema/JsonPatchEntry.d.ts.map +0 -1
- package/dist/repo/core/schema/Operation.d.ts +0 -16
- package/dist/repo/core/schema/Operation.d.ts.map +0 -1
- package/dist/repo/core/schema/OperationRequest.d.ts +0 -29
- package/dist/repo/core/schema/OperationRequest.d.ts.map +0 -1
- package/dist/repo/core/schema/ProcessEmbedded.d.ts +0 -10
- package/dist/repo/core/schema/ProcessEmbedded.d.ts.map +0 -1
- package/dist/repo/core/schema/SequentialWorkflow.d.ts +0 -13
- package/dist/repo/core/schema/SequentialWorkflow.d.ts.map +0 -1
- package/dist/repo/core/schema/SequentialWorkflowOperation.d.ts +0 -15
- package/dist/repo/core/schema/SequentialWorkflowOperation.d.ts.map +0 -1
- package/dist/repo/core/schema/SequentialWorkflowStep.d.ts +0 -13
- package/dist/repo/core/schema/SequentialWorkflowStep.d.ts.map +0 -1
- package/dist/repo/core/schema/TimelineChannel.d.ts +0 -17
- package/dist/repo/core/schema/TimelineChannel.d.ts.map +0 -1
- package/dist/repo/core/schema/TimelineEntry.d.ts +0 -25
- package/dist/repo/core/schema/TimelineEntry.d.ts.map +0 -1
- package/dist/repo/core/schema/TriggerEvent.d.ts +0 -10
- package/dist/repo/core/schema/TriggerEvent.d.ts.map +0 -1
- package/dist/repo/core/schema/UpdateDocument.d.ts +0 -40
- package/dist/repo/core/schema/UpdateDocument.d.ts.map +0 -1
- package/dist/repo/core/schema/index.d.ts +0 -15
- package/dist/repo/core/schema/index.d.ts.map +0 -1
- package/dist/repo/myos/blue-ids/index.d.ts +0 -8
- package/dist/repo/myos/blue-ids/index.d.ts.map +0 -1
- package/dist/repo/myos/index.d.ts +0 -101
- package/dist/repo/myos/index.d.ts.map +0 -1
- package/dist/repo/myos/schema/MyOSAgent.d.ts +0 -10
- package/dist/repo/myos/schema/MyOSAgent.d.ts.map +0 -1
- package/dist/repo/myos/schema/MyOSAgentChannel.d.ts +0 -30
- package/dist/repo/myos/schema/MyOSAgentChannel.d.ts.map +0 -1
- package/dist/repo/myos/schema/MyOSAgentEvent.d.ts +0 -19
- package/dist/repo/myos/schema/MyOSAgentEvent.d.ts.map +0 -1
- package/dist/repo/myos/schema/MyOSTimelineChannel.d.ts +0 -24
- package/dist/repo/myos/schema/MyOSTimelineChannel.d.ts.map +0 -1
- package/dist/repo/myos/schema/MyOSTimelineEntry.d.ts +0 -32
- package/dist/repo/myos/schema/MyOSTimelineEntry.d.ts.map +0 -1
- package/dist/repo/myos/schema/index.d.ts +0 -6
- package/dist/repo/myos/schema/index.d.ts.map +0 -1
|
@@ -28,12 +28,12 @@ export declare class BlueDocumentProcessor {
|
|
|
28
28
|
*/
|
|
29
29
|
register(cp: ContractProcessor, orderHint?: number): void;
|
|
30
30
|
/**
|
|
31
|
-
* Initializes a document
|
|
31
|
+
* Initializes a document by emitting a Document Processing Initiated event
|
|
32
32
|
*
|
|
33
33
|
* @param document - The document to initialize
|
|
34
34
|
* @returns Processing result with final state and emitted events
|
|
35
35
|
*/
|
|
36
|
-
|
|
36
|
+
initialize(document: DocumentNode): Promise<ProcessingResult>;
|
|
37
37
|
/**
|
|
38
38
|
* Processes a batch of events against the document
|
|
39
39
|
*
|
|
@@ -42,10 +42,6 @@ export declare class BlueDocumentProcessor {
|
|
|
42
42
|
* @returns Processing result with final state and emitted events
|
|
43
43
|
*/
|
|
44
44
|
processEvents(document: DocumentNode, incoming: EventNodePayload[]): Promise<ProcessingResult>;
|
|
45
|
-
/**
|
|
46
|
-
* Collects initialization events from contract processors
|
|
47
|
-
*/
|
|
48
|
-
private bootstrapContracts;
|
|
49
45
|
/**
|
|
50
46
|
* Drains the task queue and applies all actions
|
|
51
47
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BlueDocumentProcessor.d.ts","sourceRoot":"","sources":["../src/BlueDocumentProcessor.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,YAAY,EAEZ,gBAAgB,EAChB,gBAAgB,EACjB,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"BlueDocumentProcessor.d.ts","sourceRoot":"","sources":["../src/BlueDocumentProcessor.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,YAAY,EAEZ,gBAAgB,EAChB,gBAAgB,EACjB,MAAM,SAAS,CAAC;AAajB,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAK3C;;;;;GAKG;AACH,qBAAa,qBAAqB;IAc9B,OAAO,CAAC,QAAQ,CAAC,IAAI;IAbvB,OAAO,CAAC,WAAW,CAAK;IACxB,OAAO,CAAC,YAAY,CAAK;IACzB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAmB;IAC5C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAY;IAClC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAc;IACrC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAyB;IAEzD;;;;OAIG;gBAEgB,IAAI,EAAE,IAAI,EAC3B,UAAU,GAAE,iBAAiB,EAAsB;IAwBrD;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,EAAE,iBAAiB,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI;IAIzD;;;;;OAKG;IACG,UAAU,CAAC,QAAQ,EAAE,YAAY,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAqBnE;;;;;;OAMG;IACG,aAAa,CACjB,QAAQ,EAAE,YAAY,EACtB,QAAQ,EAAE,gBAAgB,EAAE,GAC3B,OAAO,CAAC,gBAAgB,CAAC;IAyB5B;;OAEG;YACW,UAAU;CAmFzB"}
|
package/dist/config.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAE5C,eAAO,MAAM,iBAAiB,EAAE,iBAAiB,EAmBhD,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var ge=Object.defineProperty;var Ee=(i,e,t)=>e in i?ge(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var l=(i,e,t)=>Ee(i,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("zod"),d=require("@blue-labs/language"),k=require("@blue-labs/shared-utils"),we=(i,e)=>({on:(t,n)=>({end:()=>n(null)})});async function Ce(i){return new Promise((e,t)=>{we().on("error",t).end()})}const P=(...i)=>i.map((e,t)=>{if(typeof e!="string")return"";if(t===0&&e==="/")return"/";const n=t>0?e.replace(/^\/+/,""):e;return t<i.length-1?n.replace(/\/+$/,""):n}).filter(Boolean).join("/").replace(/\/{2,}/g,"/");class L{constructor(e,t,n,o){l(this,"actions",[]);this.getDocument=e,this.taskInfo=t,this.blue=n,this.onFlush=o}get(e){const t=this.getDocument(),n=P(this.taskInfo.nodePath,e);return t.get(n)}addPatch(e){this.actions.push({kind:"patch",patch:{...e,path:P(this.taskInfo.nodePath,e.path)}})}emitEvent(e){const t=this.taskInfo.event,n=t.trace??[],o={...e,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 P(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 Ce()}loadBlueContent(e){throw new Error("Not implemented")}}class H 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 V extends Error{constructor(e,t){super(`Failed to evaluate expression "${e}"`),this.code=e,this.cause=t,this.name="ExpressionEvaluationError"}}class W extends Error{constructor(e,t){super(`Failed to evaluate code block "${e}"`),this.code=e,this.cause=t,this.name="CodeBlockEvaluationError"}}const m={Channel:"2RMkKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc","Timeline Channel":"RMkKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc2","Composite Timeline Channel":"qxkh3uMkKoutP5DxZ7dr6Eo27B7fuxQCS1VAptiCPc2R","Sequential Workflow":"h3uDxZ7dr6Eo27B7fuxMkKoutP5qxkQCS1VAptiCPc2R","Process Embedded":"DxZ7dr6EoMkKoutP5qxkh3u27B7fuxQCS1VAptiCPc2R","Embedded Node Channel":"MkKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc2","Document Update Channel":"MkKoutP5qxkh3uDQCS1VAptiCPc2xZ7dr6Eo27B7fux","Channel Event Checkpoint":"o27B7fuxMkKoutPh3uDxZ7dr6E5qxkQCS1VAptiCPc2R","Update Document":"7fuxMkKoutPh3uDxZ7dr6E5qxkQCS1VAptiCPc2R","Trigger Event":"kQCS1VAp7fuxMkKoutPh3uDxZ7dr6E5qxtiCPc2R","Json Patch Entry":"EnUQeMiMa2wHFW3JbeSPvdgfpL6qZYCR29m3SfeHsKSY","JavaScript Code":"MkKoutPDxZ7dr6Eo5qxkh3u27B7fuxQCS1VAptiCPc2R","Timeline Entry":"uDxZ7dr6Eo27B7fMkKoutP5qxkh3uxQCS1VAptiCPc2R",Operation:"OpKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc2R","Sequential Workflow Operation":"SeqOpKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiC","Operation Request":"OpReqKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiC"},I=d.withTypeBlueId(m.Channel)(u.z.object({name:u.z.string().optional(),description:u.z.string().optional()})),Se=d.withTypeBlueId(m["Composite Timeline Channel"])(I.extend({channels:u.z.array(u.z.string()).optional()})),Pe=d.withTypeBlueId(m["Document Update Channel"])(I.extend({path:u.z.string().optional()})),R=d.withTypeBlueId(m["Embedded Node Channel"])(I.extend({path:u.z.string().optional()})),x=d.withTypeBlueId(m["JavaScript Code"])(u.z.object({code:u.z.string().optional()})),Te=d.withTypeBlueId(m.Operation)(u.z.object({request:d.blueNodeField().optional(),description:u.z.string().optional(),channel:u.z.string().optional()})),ve=d.withTypeBlueId(m["Operation Request"])(u.z.object({operation:u.z.string().optional(),request:d.blueNodeField(),document:u.z.object({blueId:u.z.string().optional()}).optional(),allowNewerVersion:u.z.boolean().optional()})),A=d.withTypeBlueId(m["Process Embedded"])(u.z.object({paths:u.z.array(u.z.string()).optional()})),z=d.withTypeBlueId(m["Sequential Workflow"])(u.z.object({steps:u.z.array(d.blueNodeField()).optional(),channel:u.z.string().optional()})),be=d.withTypeBlueId(m["Sequential Workflow Operation"])(z.omit({channel:!0}).extend({operation:u.z.string().optional()})),Y=d.withTypeBlueId(m["Timeline Channel"])(I.extend({timelineId:u.z.string().optional()})),O=d.withTypeBlueId(m["Timeline Entry"])(u.z.object({timelineId:u.z.string().optional(),timelinePrev:u.z.string().optional(),thread:u.z.string().optional(),threadPrev:u.z.string().optional(),message:d.blueNodeField().optional(),signature:u.z.string().optional()})),M=d.withTypeBlueId(m["Trigger Event"])(u.z.object({event:d.blueNodeField()})),ke=d.withTypeBlueId(m["Json Patch Entry"])(u.z.object({name:u.z.string().optional(),description:u.z.string().optional(),val:d.blueNodeField().optional(),op:u.z.string().optional(),path:u.z.string().optional()})),q=d.withTypeBlueId(m["Update Document"])(u.z.object({changeset:u.z.array(ke)}));function D(i,e,t="/",n=[]){const o=i.getContracts()??{};for(const[a,r]of Object.entries(o))if(d.BlueNodeTypeSchema.isTypeOf(r,A)){const h=e.nodeToSchemaOutput(r,A).paths??[];for(const p of h)n.push({absPath:P(t,p),contractPath:P(t,`contracts/${a}`)})}for(const[a,r]of Object.entries(i.getProperties()??{}))D(r,e,P(t,a),n);return n}function F(i,e){return i===e||i.startsWith(e.endsWith("/")?e:e+"/")}function Q(i,e){if(!e.length)return i;let t=i.clone();for(const n of e)try{t=d.applyBlueNodePatch(t,n,!0)}catch(o){throw new H(n,o)}return k.deepFreeze(t)}function g(i){return i!=null}function N(i){return i instanceof d.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 a=e-1>>1,r=t[a];if(n(o,r)>=0)break;t[e]=r,e=a}t[e]=o}_down(e){const{data:t,compare:n}=this,o=this.length>>1,a=t[e];for(;e<o;){let r=(e<<1)+1;const s=r+1;if(s<this.length&&n(t[s],t[r])<0&&(r=s),n(t[r],a)>=0)break;t[e]=t[r],e=r}t[e]=a}}const Ne=(i,e,t,n,o,a)=>[-i,e,t,n,o,a],Ie=(i,e)=>{for(let t=0;t<i.key.length;t++){const n=i.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 Oe{constructor(){l(this,"queue");this.queue=new Be([],Ie)}push(e){this.queue.push(e)}pop(){return this.queue.pop()}get length(){return this.queue.length}}class xe{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 Me{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 qe=64;class Ae{constructor(e,t,n,o,a){l(this,"traceManager");this.blue=e,this.registry=t,this.queue=n,this.getNextTaskId=o,this.getNextEventSeq=a,this.traceManager=new Me}async route(e,t,n,o,a=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),p={...n};return delete p.dispatchPath,this.route(e,h,p,o,a)}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,a)}}const r=P("/",t.join("/")),s=e.get(r);N(s)&&await this.traverseContracts({doc:e,node:s,nodePath:r,event:n,afterTaskId:o,pathSegments:t,inlineDepth:a})}async traverseContracts(e){const{doc:t,node:n,nodePath:o,event:a,afterTaskId:r,pathSegments:s,inlineDepth:c}=e;if(!this.shouldSkipForChannel(a,o))for(const[h,p]of Object.entries(n.getContracts()??{})){if(!p.getType())continue;const f=this.registry.get(p.getType());if(!f){console.warn(`No processor registered for contract: ${h}`);continue}const w={nodePath:o,contractName:h,contractNode:p,event:a},y=new L(()=>t,w,this.blue);if(f.supports(a,p,y,h))switch(f.role){case"adapter":await this.processAdapter({cp:f,event:a,contractNode:p,ctx:y,contractName:h,doc:t,afterTaskId:r,inlineDepth:c});break;case"handler":this.scheduleHandler({contractNode:p,contractName:h,nodePath:o,event:a,depth:s.length,afterTaskId:r});break}}}async processAdapter(e){var C;const{cp:t,event:n,contractNode:o,ctx:a,contractName:r,doc:s,afterTaskId:c,inlineDepth:h}=e;if(h>=qe)throw new Error("Adapter recursion limit reached");const p=this.traceManager.addHop(n,((C=a.getTaskInfo())==null?void 0:C.nodePath)??"",r);await t.handle(p,o,a,r);const f=await a.flush();if(f.find(T=>T.kind==="patch"))throw new Error(`Contract "${r}" (adapter) attempted to patch the document`);const y=f.filter(T=>T.kind==="event");for(const T of y)await this.route(s,[],T.event,c,h+1)}scheduleHandler(e){const{contractNode:t,contractName:n,nodePath:o,event:a,depth:r,afterTaskId:s}=e,c=t.getType();if(!c){console.warn(`Contract node type is not defined for: ${n}`);return}const h=this.registry.orderOf(c),p=t.get("/order"),f=d.isBigNumber(p)?p.toNumber():0,w=this.getNextTaskId()+s,y=Ne(r,a.seq,h,f,n,w),C=this.traceManager.addHop(a,o,n);this.queue.push({key:y,nodePath:o,contractName:n,contractNode:t,event:C})}shouldSkipForChannel(e,t){return e.source==="channel"&&!!e.originNodePath&&e.originNodePath!==t}}const ze=(i,e,t)=>{(t instanceof H||t instanceof X)&&console.error(`[Blue] Failed to apply patches for contract "${i}" on event ${JSON.stringify(e)}`,t)};function K(i,e){const t=i.clone(),n=o=>{var r;if(!N(o))return;const a=o.getContracts();a&&(!a.checkpoint||((r=a.checkpoint.getType())==null?void 0:r.getBlueId())!==m["Channel Event Checkpoint"])&&o.addContract("checkpoint",e.jsonValueToNode({type:{name:"Channel Event Checkpoint",blueId:m["Channel Event Checkpoint"]},lastEvents:{}}))};n(t);for(const{absPath:o}of D(t,e)){const a=t.get(o);N(a)&&n(a)}return k.deepFreeze(t)}class G{constructor(e){l(this,"contractType","Channel Event Checkpoint");l(this,"contractBlueId",m["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 r;if(!e.channelName||!((r=e.rootEvent)!=null&&r.seq))return;const o=await n.getBlue().calculateBlueId(e.rootEvent.payload),a=n.getNodePath().replace(/\/contracts\/checkpoint$/,"");this.cache.record(a,e,o)}init(){return[]}}const U=(i,e)=>i.get(e)!==void 0;class De{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:a}of this.firstSeen.values()){if(!o.channelName)continue;const r=P(n,"contracts/checkpoint/lastEvents",o.channelName),s=`${r}/blueId`;U(e,r)?t.push({op:U(e,s)?"replace":"add",path:s,val:a}):t.push({op:"add",path:r,val:{blueId:a}})}return t}clear(){this.firstSeen.clear()}}class B{constructor(){l(this,"role","adapter")}baseSupports(e){return e.source!=="channel"}init(){return[]}}class ee extends B{constructor(){super(...arguments);l(this,"contractType","Composite Timeline Channel");l(this,"contractBlueId",m["Composite Timeline Channel"])}supports(t,n,o){const a=o.getBlue().nodeToSchemaOutput(n,Se);return!a.channels||!t.channelName?!1:a.channels.includes(t.channelName)}handle(t,n,o,a){o.emitEvent({payload:t.payload,channelName:a,source:"channel"})}}class te extends B{constructor(){super(...arguments);l(this,"contractType","Document Update Channel");l(this,"contractBlueId",m["Document Update Channel"])}supports(t,n,o,a){if(!this.baseSupports(t))return!1;const r=o.getBlue().nodeToSchemaOutput(n,Pe),s=t.payload.path;if(!s||t.channelName===a)return!1;const c=r.path;return k.isNonNullable(c)&&s===o.resolvePath(c)}handle(t,n,o,a){const r=t.payload;r&&o.emitEvent({payload:r,channelName:a,source:"channel"})}}class ne extends B{constructor(){super(...arguments);l(this,"contractType","Embedded Node Channel");l(this,"contractBlueId",m["Embedded Node Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;const a=o.getBlue().nodeToSchemaOutput(n,R);return g(t.originNodePath)&&g(a.path)&&t.originNodePath===o.resolvePath(a.path)}handle(t,n,o,a){const r=o.getBlue().nodeToSchemaOutput(n,R),{originNodePath:s,payload:c}=t;g(r.path)&&s===o.resolvePath(r.path)&&o.emitEvent({payload:c,channelName:a,source:"channel"})}}const v={"MyOS Timeline Channel":"MkKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc2R","MyOS Timeline Entry":"uDxZ7dr6Eo2MkKoutP5qxkh3uxQCS1VAptiCPc2R7B7f","MyOS Agent":"AgentBlu3Id7dr6Eo2MkKoutP5qxkh3uxQCS1V","MyOS Agent Channel":"AgentCh4nn3lBlu3Id7dr6Eo2MkKoutP5qxkh3uxQCS1V","MyOS Agent Event":"AgentEv3ntBlu3Id7dr6Eo2MkKoutP5qxkh3uxQCS1V"},$e=d.withTypeBlueId(v["MyOS Timeline Channel"])(Y.extend({account:u.z.string().optional(),email:u.z.string().optional()})),je=d.withTypeBlueId(v["MyOS Timeline Entry"])(O.extend({account:u.z.string().optional(),email:u.z.string().optional()})),Ve=d.withTypeBlueId(v["MyOS Agent"])(u.z.object({agentId:u.z.string().optional()})),We=d.withTypeBlueId(v["MyOS Agent Channel"])(I.extend({agent:Ve.optional(),event:d.blueNodeField().optional()})),Re=d.withTypeBlueId(v["MyOS Agent Event"])(u.z.object({agentId:u.z.string().optional(),id:u.z.number().optional(),timestamp:u.z.number().optional(),event:d.blueNodeField().optional()})),J=i=>i.payload.type==="Timeline Entry"||i.payload.type==="MyOS Timeline Entry";class oe extends B{constructor(){super(...arguments);l(this,"contractType","MyOS Timeline Channel");l(this,"contractBlueId",v["MyOS Timeline Channel"])}supports(t,n,o){if(!this.baseSupports(t)||!J(t))return!1;const a=o.getBlue(),r=a.jsonValueToNode(t.payload),s=a.nodeToSchemaOutput(r,je),c=o.getBlue().nodeToSchemaOutput(n,$e),h=g(c.timelineId)&&g(s.timelineId),p=g(c.account)&&g(s.account),f=g(c.email)&&g(s.email);return h&&s.timelineId===c.timelineId||p&&s.account===c.account||f&&s.email===c.email}handle(t,n,o,a){J(t)&&o.emitEvent({payload:t.payload,channelName:a,source:"channel"})}}class ae extends B{constructor(){super(...arguments);l(this,"contractType","MyOS Agent Channel");l(this,"contractBlueId",v["MyOS Agent Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;try{const{myosAgentEvent:a,myosAgentChannel:r}=this.parseEventAndChannel(t,n,o);return this.isAgentMatch(a,r)&&this.isEventPatternMatch(a,r,o)}catch(a){return console.warn("Error in MyOSAgentChannelProcessor.supports:",a),!1}}handle(t,n,o,a){o.emitEvent({payload:t.payload,channelName:a,source:"channel"})}parseEventAndChannel(t,n,o){const a=o.getBlue(),r=a.jsonValueToNode(t.payload),s=a.nodeToSchemaOutput(r,Re),c=a.nodeToSchemaOutput(n,We);return{myosAgentEvent:s,myosAgentChannel:c}}isAgentMatch(t,n){var r;const o=t.agentId,a=(r=n.agent)==null?void 0:r.agentId;return g(o)&&g(a)&&o===a}isEventPatternMatch(t,n,o){const a=n.event;if(!a)return!0;const r=t.event;if(!r)return!1;try{const s=o.getBlue(),c=s.nodeToJson(r),h=s.nodeToJson(a);return k.deepContains(c,h)}catch(s){return console.warn("Error during event pattern matching:",s),!1}}}class re{constructor(){l(this,"contractType","Operation");l(this,"contractBlueId",m.Operation);l(this,"role","adapter")}supports(e,t,n,o){const r=n.getBlue().nodeToSchemaOutput(t,Te),s=this.parseEventPayload(e,n);return g(s==null?void 0:s.operation)&&s.operation===o&&e.source==="channel"&&e.channelName===r.channel}async handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}init(){return[]}parseEventPayload(e,t){const n=t.getBlue(),o=n.jsonValueToNode(e.payload);if(d.BlueNodeTypeSchema.isTypeOf(o,O)){const a=n.nodeToSchemaOutput(o,O);if(a.message)return n.nodeToSchemaOutput(a.message,ve)}return null}}class se{constructor(){l(this,"contractType","Process Embedded");l(this,"role","adapter");l(this,"contractBlueId",m["Process Embedded"])}supports(e){return e.source!=="channel"}handle(e,t,n){const o=n.getBlue().nodeToSchemaOutput(t,A);for(const a of o.paths??[])n.emitEvent({...e,dispatchPath:n.resolvePath(a)})}init(){return[]}}const ie=!process.env.SKIP_ISOLATED_VM;let S=null;if(ie)try{S=require("isolated-vm")}catch{console.warn("isolated-vm not available, using fallback evaluation method")}function Z(i){return/\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(i)||/\bexport\s+/.test(i)}class ce{static async evaluate({code:e,ctx:t,bindings:n={},options:o={}}){return!S||!ie?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(s=>t[s])))(...o.map(s=>t[s]))}else return new Function(...Object.keys(t),`return ${e};`)(...Object.values(t))}catch(o){throw n.isCodeBlock?new W(e,o):new V(e,o)}}static async evaluateSecure(e,t,n,o={}){if(!S)throw new Error("isolated-vm not available");const a=new S.Isolate({memoryLimit:32}),r=await a.createContext(),s=r.global;try{await this.setupIsolateEnvironment(s,t);const c=new Map,h=this.createModuleResolver(a,r,c,n);return Z(e)?await this.evaluateESModule(a,r,e,o,h):await this.evaluateSimpleScript(a,r,e,t,o)}catch(c){throw o.isCodeBlock?new W(e,c):new V(e,c)}finally{r.release(),a.dispose()}}static async setupIsolateEnvironment(e,t){if(!S)throw new Error("isolated-vm not available");const n=new S.Callback((...o)=>console.log(...o));await e.set("log",n);for(const[o,a]of Object.entries(t))typeof a=="function"?await e.set(o,new S.Callback(a)):await e.set(o,new S.ExternalCopy(a).copyInto())}static createModuleResolver(e,t,n,o){return async a=>{if(n.has(a))return n.get(a);if(a.startsWith("blue:")){const r=a.slice(5),s=o.loadBlueContent;if(typeof s!="function")throw new Error(`ProcessingContext is missing a loadBlueContent(blueId) implementation (needed for ${a})`);const c=await s(r),h=await e.compileModule(c);return n.set(a,h),await h.instantiate(t,this.createModuleResolver(e,t,n,o)),h}if(/^https?:\/\//.test(a)){let r;if(typeof o.loadExternalModule=="function")r=await o.loadExternalModule(a);else throw new Error(`ProcessingContext is missing a loadExternalModule(url) implementation (needed for ${a})`);const s=await e.compileModule(r);return n.set(a,s),await s.instantiate(t,this.createModuleResolver(e,t,n,o)),s}throw new Error(`Unsupported module specifier "${a}"`)}}static async evaluateSimpleScript(e,t,n,o,a){const r=Object.keys(o).join(", "),s=Object.keys(o).map(p=>p),c=`(async (${r}) => { ${a.isCodeBlock?n:`return (${n});`} })(${s.join(", ")})`;return await(await e.compileScript(c)).run(t,{timeout:a.timeout??500,promise:!0,copy:!0,release:!0})}static async evaluateESModule(e,t,n,o,a){let r=n;if(o.isCodeBlock){const h=/^\s*(import\s.+?;|export\s.+?;)/gm,p=(n.match(h)||[]).join(`
|
|
2
|
-
`),
|
|
3
|
-
${
|
|
1
|
+
"use strict";var he=Object.defineProperty;var de=(c,e,t)=>e in c?he(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var l=(c,e,t)=>de(c,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("@blue-repository/core-dev"),g=require("@blue-labs/language"),v=require("@blue-labs/shared-utils"),I=require("@blue-repository/myos-dev"),pe=(c,e)=>({on:(t,n)=>({end:()=>n(null)})});async function me(c){return new Promise((e,t)=>{pe().on("error",t).end()})}const S=(...c)=>c.map((e,t)=>{if(typeof e!="string")return"";if(t===0&&e==="/")return"/";const n=t>0?e.replace(/^\/+/,""):e;return t<c.length-1?n.replace(/\/+$/,""):n}).filter(Boolean).join("/").replace(/\/{2,}/g,"/");class U{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 me()}loadBlueContent(e){throw new Error("Not implemented")}}class _ extends Error{constructor(e,t){super(`Cannot apply patch ${JSON.stringify(e)}`),this.patch=e,this.cause=t,this.name="PatchApplicationError"}}class H 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 A extends Error{constructor(e,t){super(`Failed to evaluate expression "${e}"`),this.code=e,this.cause=t,this.name="ExpressionEvaluationError"}}class D extends Error{constructor(e,t){super(`Failed to evaluate code block "${e}"`),this.code=e,this.cause=t,this.name="CodeBlockEvaluationError"}}function M(c,e,t="/",n=[]){const o=c.getContracts()??{};for(const[a,r]of Object.entries(o))if(g.BlueNodeTypeSchema.isTypeOf(r,d.ProcessEmbeddedSchema)){const u=e.nodeToSchemaOutput(r,d.ProcessEmbeddedSchema).paths??[];for(const h of u)n.push({absPath:S(t,h),contractPath:S(t,`contracts/${a}`)})}for(const[a,r]of Object.entries(c.getProperties()??{}))M(r,e,S(t,a),n);return n}function W(c,e){return c===e||c.startsWith(e.endsWith("/")?e:e+"/")}function j(c,e){if(!e.length)return c;let t=c.clone();for(const n of e)try{t=g.applyBlueNodePatch(t,n,!0)}catch(o){throw new _(n,o)}return v.deepFreeze(t)}function y(c){return c!=null}function b(c){return c instanceof g.BlueNode}class fe{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 a=e-1>>1,r=t[a];if(n(o,r)>=0)break;t[e]=r,e=a}t[e]=o}_down(e){const{data:t,compare:n}=this,o=this.length>>1,a=t[e];for(;e<o;){let r=(e<<1)+1;const s=r+1;if(s<this.length&&n(t[s],t[r])<0&&(r=s),n(t[r],a)>=0)break;t[e]=t[r],e=r}t[e]=a}}const ye=(c,e,t,n,o,a)=>[-c,e,t,n,o,a],ge=(c,e)=>{for(let t=0;t<c.key.length;t++){const n=c.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 Ee{constructor(){l(this,"queue");this.queue=new fe([],ge)}push(e){this.queue.push(e)}pop(){return this.queue.pop()}get length(){return this.queue.length}}class ve{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 we{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 Te=64;class Se{constructor(e,t,n,o,a){l(this,"traceManager");this.blue=e,this.registry=t,this.queue=n,this.getNextTaskId=o,this.getNextEventSeq=a,this.traceManager=new we}async route(e,t,n,o,a=0){var i;if(n.seq===void 0&&(n.seq=this.getNextEventSeq()),t.length===0){if(n.dispatchPath){const u=n.dispatchPath.split("/").filter(Boolean),h={...n};return delete h.dispatchPath,this.route(e,u,h,o,a)}if(n.source==="channel"&&n.originNodePath&&n.originNodePath!=="/"){const u=((i=n.originNodePath)==null?void 0:i.split("/").filter(Boolean))??[];return this.route(e,u,n,o,a)}}const r=S("/",t.join("/")),s=e.get(r);b(s)&&await this.traverseContracts({doc:e,node:s,nodePath:r,event:n,afterTaskId:o,pathSegments:t,inlineDepth:a})}async traverseContracts(e){const{doc:t,node:n,nodePath:o,event:a,afterTaskId:r,pathSegments:s,inlineDepth:i}=e;if(!this.shouldSkipForChannel(a,o))for(const[u,h]of Object.entries(n.getContracts()??{})){if(!h.getType())continue;const p=this.registry.get(h.getType());if(!p){console.warn(`No processor registered for contract: ${u}`);continue}const m={nodePath:o,contractName:u,contractNode:h,event:a},f=new U(()=>t,m,this.blue);if(p.supports(a,h,f,u))switch(p.role){case"adapter":await this.processAdapter({cp:p,event:a,contractNode:h,ctx:f,contractName:u,doc:t,afterTaskId:r,inlineDepth:i});break;case"handler":this.scheduleHandler({contractNode:h,contractName:u,nodePath:o,event:a,depth:s.length,afterTaskId:r});break}}}async processAdapter(e){var w;const{cp:t,event:n,contractNode:o,ctx:a,contractName:r,doc:s,afterTaskId:i,inlineDepth:u}=e;if(u>=Te)throw new Error("Adapter recursion limit reached");const h=this.traceManager.addHop(n,((w=a.getTaskInfo())==null?void 0:w.nodePath)??"",r);await t.handle(h,o,a,r);const p=await a.flush();if(p.find(P=>P.kind==="patch"))throw new Error(`Contract "${r}" (adapter) attempted to patch the document`);const f=p.filter(P=>P.kind==="event");for(const P of f)await this.route(s,[],P.event,i,u+1)}scheduleHandler(e){const{contractNode:t,contractName:n,nodePath:o,event:a,depth:r,afterTaskId:s}=e,i=t.getType();if(!i){console.warn(`Contract node type is not defined for: ${n}`);return}const u=this.registry.orderOf(i),h=t.get("/order"),p=g.isBigNumber(h)?h.toNumber():0,m=this.getNextTaskId()+s,f=ye(r,a.seq,u,p,n,m),w=this.traceManager.addHop(a,o,n);this.queue.push({key:f,nodePath:o,contractName:n,contractNode:t,event:w})}shouldSkipForChannel(e,t){return e.source==="channel"&&!!e.originNodePath&&e.originNodePath!==t}}const Pe=(c,e,t)=>{(t instanceof _||t instanceof H)&&console.error(`[Blue] Failed to apply patches for contract "${c}" on event ${JSON.stringify(e)}`,t)};function x(c,e){const t=c.clone(),n=o=>{if(!b(o))return;const a=o.getContracts();(!(a!=null&&a.checkpoint)||!g.BlueNodeTypeSchema.isTypeOf(a.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 M(t,e)){const a=t.get(o);b(a)&&n(a)}return v.deepFreeze(t)}const N={"Lifecycle Event Channel":"LifecycleEventChannelPlaceholderId1234567890ABC","Initialized Marker":"InitializedMarkerPlaceholderId1234567890ABC"};function be(c,e){const t=c.clone();if(!b(t))return v.deepFreeze(t);const n=t.getContracts();return n!=null&&n.initialized||t.addContract("initialized",e.jsonValueToNode({type:{name:"Initialized Marker",blueId:N["Initialized Marker"]}})),v.deepFreeze(t)}class R{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 r;if(!e.channelName||!((r=e.rootEvent)!=null&&r.seq))return;const o=await n.getBlue().calculateBlueId(e.rootEvent.payload),a=n.getNodePath().replace(/\/contracts\/checkpoint$/,"");this.cache.record(a,e,o)}}const F=(c,e)=>c.get(e)!==void 0;class Ce{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:a}of this.firstSeen.values()){if(!o.channelName)continue;const r=S(n,"contracts/checkpoint/lastEvents",o.channelName),s=`${r}/blueId`;F(e,r)?t.push({op:F(e,s)?"replace":"add",path:s,val:a}):t.push({op:"add",path:r,val:{blueId:a}})}return t}clear(){this.firstSeen.clear()}}class C{constructor(){l(this,"role","adapter")}baseSupports(e){return e.source!=="channel"}}class Q extends C{constructor(){super(...arguments);l(this,"contractType","Composite Timeline Channel");l(this,"contractBlueId",d.blueIds["Composite Timeline Channel"])}supports(t,n,o){const a=o.getBlue().nodeToSchemaOutput(n,d.CompositeTimelineChannelSchema);return!a.channels||!t.channelName?!1:a.channels.includes(t.channelName)}handle(t,n,o,a){o.emitEvent({payload:t.payload,channelName:a,source:"channel"})}}class K extends C{constructor(){super(...arguments);l(this,"contractType","Document Update Channel");l(this,"contractBlueId",d.blueIds["Document Update Channel"])}supports(t,n,o,a){if(!this.baseSupports(t))return!1;const r=o.getBlue().nodeToSchemaOutput(n,d.DocumentUpdateChannelSchema),s=t.payload.path;if(!s||t.channelName===a)return!1;const i=r.path;return v.isNonNullable(i)&&s===o.resolvePath(i)}handle(t,n,o,a){const r=t.payload;r&&o.emitEvent({payload:r,channelName:a,source:"channel"})}}class X extends C{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 a=o.getBlue().nodeToSchemaOutput(n,d.EmbeddedNodeChannelSchema);return y(t.originNodePath)&&y(a.path)&&t.originNodePath===o.resolvePath(a.path)}handle(t,n,o,a){const r=o.getBlue().nodeToSchemaOutput(n,d.EmbeddedNodeChannelSchema),{originNodePath:s,payload:i}=t;y(r.path)&&s===o.resolvePath(r.path)&&o.emitEvent({payload:i,channelName:a,source:"channel"})}}class Y{constructor(){l(this,"contractType","Initialized Marker");l(this,"contractBlueId",N["Initialized Marker"]);l(this,"role","marker")}supports(){return!1}handle(){}}const ke=new Set(["Document Processing Initiated"]);class Z extends C{constructor(){super(...arguments);l(this,"contractType","Lifecycle Event Channel");l(this,"contractBlueId",N["Lifecycle Event Channel"])}supports(t,n,o){return!this.baseSupports(t)||!this.isLifecycleEvent(t)?!1:this.isEventPatternMatch(t,n,o)}handle(t,n,o,a){o.emitEvent({payload:t.payload,channelName:a,source:"channel"})}isLifecycleEvent(t){return ke.has(t.payload.type)}isEventPatternMatch(t,n,o){var r;const a=(r=n.getProperties())==null?void 0:r.event;if(!a)return!0;try{const s=o.getBlue(),i=s.nodeToJson(s.jsonValueToNode(t.payload)),u=s.nodeToJson(a);return v.deepContains(i,u)}catch(s){return console.warn("Error during lifecycle event pattern matching:",s),!1}}}const L=c=>c.payload.type==="Timeline Entry"||c.payload.type==="MyOS Timeline Entry";class G extends C{constructor(){super(...arguments);l(this,"contractType","MyOS Timeline Channel");l(this,"contractBlueId",I.blueIds["MyOS Timeline Channel"])}supports(t,n,o){var f;if(!this.baseSupports(t)||!L(t))return!1;const a=o.getBlue(),r=a.jsonValueToNode(t.payload),s=a.nodeToSchemaOutput(r,I.MyOSTimelineEntrySchema),i=o.getBlue().nodeToSchemaOutput(n,I.MyOSTimelineChannelSchema),u=(f=s.timeline)==null?void 0:f.timelineId,h=y(i.timelineId)&&y(u),p=y(i.account)&&y(s.account),m=y(i.email)&&y(s.email);return h&&u===i.timelineId||p&&s.account===i.account||m&&s.email===i.email}handle(t,n,o,a){L(t)&&o.emitEvent({payload:t.payload,channelName:a,source:"channel"})}}class ee extends C{constructor(){super(...arguments);l(this,"contractType","MyOS Agent Channel");l(this,"contractBlueId",I.blueIds["MyOS Agent Channel"])}supports(t,n,o){if(!this.baseSupports(t))return!1;try{const{myosAgentEvent:a,myosAgentChannel:r}=this.parseEventAndChannel(t,n,o);return this.isAgentMatch(a,r)&&this.isEventPatternMatch(a,r,o)}catch(a){return console.warn("Error in MyOSAgentChannelProcessor.supports:",a),!1}}handle(t,n,o,a){o.emitEvent({payload:t.payload,channelName:a,source:"channel"})}parseEventAndChannel(t,n,o){const a=o.getBlue(),r=a.jsonValueToNode(t.payload),s=a.nodeToSchemaOutput(r,I.MyOSAgentEventSchema),i=a.nodeToSchemaOutput(n,I.MyOSAgentChannelSchema);return{myosAgentEvent:s,myosAgentChannel:i}}isAgentMatch(t,n){var r;const o=t.agentId,a=(r=n.agent)==null?void 0:r.agentId;return y(o)&&y(a)&&o===a}isEventPatternMatch(t,n,o){const a=n.event;if(!a)return!0;const r=t.event;if(!r)return!1;try{const s=o.getBlue(),i=s.nodeToJson(r),u=s.nodeToJson(a);return v.deepContains(i,u)}catch(s){return console.warn("Error during event pattern matching:",s),!1}}}class te{constructor(){l(this,"contractType","Operation");l(this,"contractBlueId",d.blueIds.Operation);l(this,"role","adapter")}supports(e,t,n,o){const r=n.getBlue().nodeToSchemaOutput(t,d.OperationSchema),s=this.parseEventPayload(e,n);return y(s==null?void 0:s.operation)&&s.operation===o&&e.source==="channel"&&e.channelName===r.channel}async handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}parseEventPayload(e,t){const n=t.getBlue(),o=n.jsonValueToNode(e.payload);if(g.BlueNodeTypeSchema.isTypeOf(o,d.TimelineEntrySchema)){const a=n.nodeToSchemaOutput(o,d.TimelineEntrySchema);if(a.message)return n.nodeToSchemaOutput(a.message,d.OperationRequestSchema)}return null}}class ne{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 a of o.paths??[])n.emitEvent({...e,dispatchPath:n.resolvePath(a)})}}const oe=!process.env.SKIP_ISOLATED_VM;let T=null;if(oe)try{T=require("isolated-vm")}catch{console.warn("isolated-vm not available, using fallback evaluation method")}function V(c){return/\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(c)||/\bexport\s+/.test(c)}class B{static async evaluate({code:e,ctx:t,bindings:n={},options:o={}}){return!T||!oe?this.evaluateSimple(e,n,o):this.evaluateSecure(e,n,t,o)}static async evaluateSimple(e,t,n={}){if(V(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(s=>t[s])))(...o.map(s=>t[s]))}else return new Function(...Object.keys(t),`return ${e};`)(...Object.values(t))}catch(o){throw n.isCodeBlock?new D(e,o):new A(e,o)}}static async evaluateSecure(e,t,n,o={}){if(!T)throw new Error("isolated-vm not available");const a=new T.Isolate({memoryLimit:32}),r=await a.createContext(),s=r.global;try{await this.setupIsolateEnvironment(s,t);const i=new Map,u=this.createModuleResolver(a,r,i,n);return V(e)?await this.evaluateESModule(a,r,e,o,u):await this.evaluateSimpleScript(a,r,e,t,o)}catch(i){throw o.isCodeBlock?new D(e,i):new A(e,i)}finally{r.release(),a.dispose()}}static async setupIsolateEnvironment(e,t){if(!T)throw new Error("isolated-vm not available");const n=new T.Callback((...o)=>console.log(...o));await e.set("log",n);for(const[o,a]of Object.entries(t))typeof a=="function"?await e.set(o,new T.Callback(a)):await e.set(o,new T.ExternalCopy(a).copyInto())}static createModuleResolver(e,t,n,o){return async a=>{if(n.has(a))return n.get(a);if(a.startsWith("blue:")){const r=a.slice(5),s=o.loadBlueContent;if(typeof s!="function")throw new Error(`ProcessingContext is missing a loadBlueContent(blueId) implementation (needed for ${a})`);const i=await s(r),u=await e.compileModule(i);return n.set(a,u),await u.instantiate(t,this.createModuleResolver(e,t,n,o)),u}if(/^https?:\/\//.test(a)){let r;if(typeof o.loadExternalModule=="function")r=await o.loadExternalModule(a);else throw new Error(`ProcessingContext is missing a loadExternalModule(url) implementation (needed for ${a})`);const s=await e.compileModule(r);return n.set(a,s),await s.instantiate(t,this.createModuleResolver(e,t,n,o)),s}throw new Error(`Unsupported module specifier "${a}"`)}}static async evaluateSimpleScript(e,t,n,o,a){const r=Object.keys(o).join(", "),s=Object.keys(o).map(h=>h),i=`(async (${r}) => { ${a.isCodeBlock?n:`return (${n});`} })(${s.join(", ")})`;return await(await e.compileScript(i)).run(t,{timeout:a.timeout??500,promise:!0,copy:!0,release:!0})}static async evaluateESModule(e,t,n,o,a){let r=n;if(o.isCodeBlock){const u=/^\s*(import\s.+?;|export\s.+?;)/gm,h=(n.match(u)||[]).join(`
|
|
2
|
+
`),p=n.replace(u,"").trim();r=`
|
|
3
|
+
${h}
|
|
4
4
|
const run = function() {
|
|
5
|
-
${
|
|
5
|
+
${p}
|
|
6
6
|
};
|
|
7
7
|
export default run();
|
|
8
|
-
`}const s=await e.compileModule(r);return await s.instantiate(t,a),await s.evaluate({timeout:o.timeout??500,promise:!0,reference:!0,release:!0}),await s.namespace.get("default",{timeout:o.timeout??500,promise:!0,copy:!0,release:!0})}}class
|
|
8
|
+
`}const s=await e.compileModule(r);return await s.instantiate(t,a),await s.evaluate({timeout:o.timeout??500,promise:!0,reference:!0,release:!0}),await s.namespace.get("default",{timeout:o.timeout??500,promise:!0,copy:!0,release:!0})}}class O{static createStandardBindings(e,t,n){const o=e.getBlue();return{document:a=>{const r=e.get(a);return g.isBigNumber(r)?r.toNumber():b(r)?o.nodeToJson(r,"original"):r},event:t.payload,steps:n}}}function J(c){const{op:e,path:t,val:n,from:o}=c;if((e==="move"||e==="copy")&&!o)throw new Error(`${e} operation requires 'from' path`);if((e==="add"||e==="replace")&&n===void 0)throw new Error(`${e} operation requires 'val' property`);const a={type:"Document Update",op:e,path:t};return n!==void 0&&(a.val=n),o!==void 0&&(a.from=o),a}function Ie(){return{type:"Document Processing Initiated"}}class Ne{constructor(){l(this,"stepType","Update Document")}supports(e){return g.BlueNodeTypeSchema.isTypeOf(e,d.UpdateDocumentSchema)}async execute(e,t,n,o,a){const r=n.getBlue();if(!g.BlueNodeTypeSchema.isTypeOf(e,d.UpdateDocumentSchema))return;const s=await this.evaluateChangeset(e.get("/changeset"),n,t,a),i=g.applyBlueNodePatch(e,{op:"replace",path:"/changeset",val:s}),u=n.getBlue().nodeToSchemaOutput(i,d.UpdateDocumentSchema);for(const h of u.changeset??[]){if(!h.path)continue;const p=h.val;if((h.op==="replace"||h.op==="add")&&v.isNonNullable(p)){const m=await this.evaluateChangeValue(p,n,t,a);n.addPatch({op:h.op,path:h.path,val:m}),n.emitEvent({payload:J({op:h.op,path:n.resolvePath(h.path),val:r.nodeToJson(m,"original")})})}h.op==="remove"&&(n.addPatch({op:h.op,path:h.path}),n.emitEvent({payload:J({op:h.op,path:n.resolvePath(h.path),val:null})}))}}async evaluateChangeset(e,t,n,o){const a=t.getBlue();if(typeof e=="string"&&e.startsWith("${")&&e.endsWith("}")){const r=e.slice(2,-1),s=await B.evaluate({code:r,ctx:t,bindings:O.createStandardBindings(t,n,o)});return a.jsonValueToNode(s??null)}if(b(e))return e;throw new Error("Invalid changeset: expected a string or document node")}async evaluateChangeValue(e,t,n,o){const a=e.getValue(),r=t.getBlue();if(typeof a=="string"&&a.startsWith("${")&&a.endsWith("}")){const s=a.slice(2,-1),i=await B.evaluate({code:s,ctx:t,bindings:O.createStandardBindings(t,n,o)});return r.jsonValueToNode(i??null)}return e}}class Be{constructor(){l(this,"stepType","Trigger Event")}supports(e){return g.BlueNodeTypeSchema.isTypeOf(e,d.TriggerEventSchema)}async execute(e,t,n){const o=n.getBlue();if(!g.BlueNodeTypeSchema.isTypeOf(e,d.TriggerEventSchema))return;const a=o.nodeToSchemaOutput(e,d.TriggerEventSchema);if(!a.event)return;const r=o.nodeToJson(a.event,"original");n.emitEvent({payload:r})}}class Oe{constructor(){l(this,"stepType","JavaScript Code")}supports(e){return g.BlueNodeTypeSchema.isTypeOf(e,d.JavaScriptCodeSchema)}async execute(e,t,n,o,a){if(!g.BlueNodeTypeSchema.isTypeOf(e,d.JavaScriptCodeSchema))return;const s=n.getBlue().nodeToSchemaOutput(e,d.JavaScriptCodeSchema);if(!s.code)throw new Error("JavaScript code is required");const i=await B.evaluate({code:s.code,ctx:n,bindings:O.createStandardBindings(n,t,a),options:{isCodeBlock:!0,timeout:500}});if(i&&typeof i=="object"&&"events"in i){const u=i;if(Array.isArray(u.events))for(const h of u.events)n.emitEvent({payload:h})}return i}}const Me=[new Ne,new Be,new Oe];class q{constructor(e=Me){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).channel;return e.source==="channel"&&e.channelName===r}async handle(e,t,n,o){var s;const a={},r=(s=t.getProperties())==null?void 0:s.steps.getItems();for(const[i,u]of(r??[]).entries()){const h=this.executors.find(m=>m.supports(u));if(!h)throw new Error(`Unsupported workflow step type "${u.getType()}"`);const p=await h.execute(u,e,n,o,a);if(p!==void 0){const m=u.getName(),f=typeof m=="string"?m:`Step${i+1}`;a[f]=p}await n.flush()}}}class ae{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 q}supports(e,t,n){const r=n.getBlue().nodeToSchemaOutput(t,d.SequentialWorkflowOperationSchema).operation,s=e.channelName;return e.source==="channel"&&v.isNonNullable(s)&&v.isNonNullable(r)&&s===r}async handle(e,t,n,o){try{await this.sequentialWorkflowProcessor.handle(e,t,n,o)}catch(a){throw console.error("Error in SequentialWorkflowOperationProcessor.handle:",a),a}}}const z=c=>c.payload.type==="Timeline Entry";class re extends C{constructor(){super(...arguments);l(this,"contractType","Timeline Channel");l(this,"contractBlueId",d.blueIds["Timeline Channel"])}supports(t,n,o){var h;if(!this.baseSupports(t)||!z(t))return!1;const a=o.getBlue(),r=a.nodeToSchemaOutput(a.jsonValueToNode(t.payload),d.TimelineEntrySchema),s=o.getBlue().nodeToSchemaOutput(n,d.TimelineChannelSchema),i=(h=r.timeline)==null?void 0:h.timelineId;return y(s.timelineId)&&y(i)&&i===s.timelineId}handle(t,n,o,a){z(t)&&o.emitEvent({payload:t.payload,channelName:a,source:"channel"})}}const qe=[new ne,new X,new K,new re,new G,new ee,new Q,new Z,new te,new q,new ae,new Y];class $e{constructor(e,t=qe){l(this,"taskCounter",0);l(this,"eventCounter",0);l(this,"registry");l(this,"queue");l(this,"router");l(this,"checkpointCache",new Ce);this.blue=e,this.registry=new ve(t),this.queue=new Ee,this.router=new Se(this.blue,this.registry,this.queue,()=>++this.taskCounter,()=>++this.eventCounter),this.register(new R(this.checkpointCache),9999),this.blue.registerBlueIds({"Lifecycle Event Channel":N["Lifecycle Event Channel"],"Initialized Marker":N["Initialized Marker"]})}register(e,t){this.registry.register(e,t)}async initialize(e){let t=x(e,this.blue);const n={payload:Ie()},o=[n.payload];await this.router.route(t,[],n,0);const a=await this.drainQueue(t);return t=a.state,o.push(...a.emitted),t=be(t,this.blue),{state:t,emitted:o}}async processEvents(e,t){let n=x(e,this.blue);const o=[];for(const a of t)try{const r={payload:a,source:"external"};await this.router.route(n,[],r,0);const s=await this.drainQueue(n);n=s.state,o.push(...s.emitted);const i=this.checkpointCache.flush(n);i.length&&(n=j(n,i))}finally{this.checkpointCache.clear()}return{state:n,emitted:o}}async drainQueue(e){var r;let t=e;const n=[],o=1e4;let a=0;for(;this.queue.length;){if(++a>o)throw new Error("Possible cycle – too many iterations");const s=this.queue.pop(),{nodePath:i,contractName:u,contractNode:h,event:p}=s,m=t.get(i);if(!b(m)||!((r=m.getContracts())!=null&&r[u])||!h.getType())continue;const f=this.registry.get(h.getType());if(!f){console.warn(`No processor registered for contract: ${u}`);continue}const w=new U(()=>t,s,this.blue,async P=>{for(const E of P)if(E.kind==="patch"){const se=M(t,this.blue);for(const k of se){const ce=E.patch.op==="move"||E.patch.op==="copy"?[E.patch.from,E.patch.path]:[E.patch.path],$=w.getNodePath(),ie=ce.some(ue=>W(ue,k.absPath)),le=W($,k.absPath);if(ie&&!le)throw new H(E.patch,k.absPath,$)}try{t=j(t,[E.patch])}catch(k){throw Pe(u,p,k),k}}else E.kind==="event"&&(n.push(E.event.payload),await this.router.route(t,[],E.event,s.key[5]))});await f.handle(p,h,w,u),await w.flush()}return{state:t,emitted:n}}}exports.BlueDocumentProcessor=$e;exports.ChannelEventCheckpointProcessor=R;exports.CompositeTimelineChannelProcessor=Q;exports.DocumentUpdateChannelProcessor=K;exports.EmbeddedNodeChannelProcessor=X;exports.InitializedMarkerProcessor=Y;exports.LifecycleEventChannelProcessor=Z;exports.MyOSAgentChannelProcessor=ee;exports.MyOSTimelineChannelProcessor=G;exports.OperationProcessor=te;exports.ProcessEmbeddedProcessor=ne;exports.SequentialWorkflowOperationProcessor=ae;exports.SequentialWorkflowProcessor=q;exports.TimelineChannelProcessor=re;
|