@blue-labs/document-processor 1.37.0 → 2.0.0-rc.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.
Files changed (257) hide show
  1. package/dist/api/document-processor.d.ts +38 -0
  2. package/dist/api/document-processor.d.ts.map +1 -0
  3. package/dist/constants/processor-contract-constants.d.ts +24 -0
  4. package/dist/constants/processor-contract-constants.d.ts.map +1 -0
  5. package/dist/constants/processor-pointer-constants.d.ts +21 -0
  6. package/dist/constants/processor-pointer-constants.d.ts.map +1 -0
  7. package/dist/engine/boundary-violation-exception.d.ts +4 -0
  8. package/dist/engine/boundary-violation-exception.d.ts.map +1 -0
  9. package/dist/engine/channel-runner.d.ts +27 -0
  10. package/dist/engine/channel-runner.d.ts.map +1 -0
  11. package/dist/engine/checkpoint-manager.d.ts +23 -0
  12. package/dist/engine/checkpoint-manager.d.ts.map +1 -0
  13. package/dist/engine/contract-bundle.d.ts +70 -0
  14. package/dist/engine/contract-bundle.d.ts.map +1 -0
  15. package/dist/engine/contract-loader.d.ts +17 -0
  16. package/dist/engine/contract-loader.d.ts.map +1 -0
  17. package/dist/engine/handler-registration-service.d.ts +27 -0
  18. package/dist/engine/handler-registration-service.d.ts.map +1 -0
  19. package/dist/engine/illegal-state-exception.d.ts +5 -0
  20. package/dist/engine/illegal-state-exception.d.ts.map +1 -0
  21. package/dist/engine/index.d.ts +11 -0
  22. package/dist/engine/index.d.ts.map +1 -0
  23. package/dist/engine/must-understand-failure.d.ts +4 -0
  24. package/dist/engine/must-understand-failure.d.ts.map +1 -0
  25. package/dist/engine/processor-engine.d.ts +66 -0
  26. package/dist/engine/processor-engine.d.ts.map +1 -0
  27. package/dist/engine/processor-execution-context.d.ts +38 -0
  28. package/dist/engine/processor-execution-context.d.ts.map +1 -0
  29. package/dist/engine/processor-fatal-error.d.ts +6 -0
  30. package/dist/engine/processor-fatal-error.d.ts.map +1 -0
  31. package/dist/engine/run-termination-error.d.ts +5 -0
  32. package/dist/engine/run-termination-error.d.ts.map +1 -0
  33. package/dist/engine/scope-executor.d.ts +60 -0
  34. package/dist/engine/scope-executor.d.ts.map +1 -0
  35. package/dist/engine/termination-service.d.ts +17 -0
  36. package/dist/engine/termination-service.d.ts.map +1 -0
  37. package/dist/index.d.ts +14 -6
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +3176 -9
  40. package/dist/merge/index.d.ts +2 -2
  41. package/dist/merge/index.d.ts.map +1 -1
  42. package/dist/merge/processors/index.d.ts +1 -1
  43. package/dist/merge/processors/index.d.ts.map +1 -1
  44. package/dist/model/channels/document-update-channel.d.ts +41 -0
  45. package/dist/model/channels/document-update-channel.d.ts.map +1 -0
  46. package/dist/model/channels/embedded-node-channel.d.ts +43 -0
  47. package/dist/model/channels/embedded-node-channel.d.ts.map +1 -0
  48. package/dist/model/channels/index.d.ts +7 -0
  49. package/dist/model/channels/index.d.ts.map +1 -0
  50. package/dist/model/channels/lifecycle-channel.d.ts +40 -0
  51. package/dist/model/channels/lifecycle-channel.d.ts.map +1 -0
  52. package/dist/model/channels/myos-timeline-channel.d.ts +52 -0
  53. package/dist/model/channels/myos-timeline-channel.d.ts.map +1 -0
  54. package/dist/model/channels/timeline-channel.d.ts +43 -0
  55. package/dist/model/channels/timeline-channel.d.ts.map +1 -0
  56. package/dist/model/channels/triggered-event-channel.d.ts +40 -0
  57. package/dist/model/channels/triggered-event-channel.d.ts.map +1 -0
  58. package/dist/model/events/document-update.d.ts +15 -0
  59. package/dist/model/events/document-update.d.ts.map +1 -0
  60. package/dist/model/handlers/index.d.ts +3 -0
  61. package/dist/model/handlers/index.d.ts.map +1 -0
  62. package/dist/model/handlers/sequential-workflow-operation.d.ts +61 -0
  63. package/dist/model/handlers/sequential-workflow-operation.d.ts.map +1 -0
  64. package/dist/model/handlers/sequential-workflow.d.ts +57 -0
  65. package/dist/model/handlers/sequential-workflow.d.ts.map +1 -0
  66. package/dist/model/index.d.ts +6 -0
  67. package/dist/model/index.d.ts.map +1 -0
  68. package/dist/model/markers/channel-event-checkpoint.d.ts +40 -0
  69. package/dist/model/markers/channel-event-checkpoint.d.ts.map +1 -0
  70. package/dist/model/markers/index.d.ts +6 -0
  71. package/dist/model/markers/index.d.ts.map +1 -0
  72. package/dist/model/markers/initialization-marker.d.ts +36 -0
  73. package/dist/model/markers/initialization-marker.d.ts.map +1 -0
  74. package/dist/model/markers/operation.d.ts +39 -0
  75. package/dist/model/markers/operation.d.ts.map +1 -0
  76. package/dist/model/markers/process-embedded.d.ts +36 -0
  77. package/dist/model/markers/process-embedded.d.ts.map +1 -0
  78. package/dist/model/markers/processing-terminated-marker.d.ts +39 -0
  79. package/dist/model/markers/processing-terminated-marker.d.ts.map +1 -0
  80. package/dist/model/shared/channel-contract-base.d.ts +30 -0
  81. package/dist/model/shared/channel-contract-base.d.ts.map +1 -0
  82. package/dist/model/shared/contract-base.d.ts +16 -0
  83. package/dist/model/shared/contract-base.d.ts.map +1 -0
  84. package/dist/model/shared/handler-contract-base.d.ts +29 -0
  85. package/dist/model/shared/handler-contract-base.d.ts.map +1 -0
  86. package/dist/model/shared/index.d.ts +6 -0
  87. package/dist/model/shared/index.d.ts.map +1 -0
  88. package/dist/model/shared/json-patch.d.ts +24 -0
  89. package/dist/model/shared/json-patch.d.ts.map +1 -0
  90. package/dist/model/shared/marker-contract-base.d.ts +23 -0
  91. package/dist/model/shared/marker-contract-base.d.ts.map +1 -0
  92. package/dist/model/types.d.ts +13 -0
  93. package/dist/model/types.d.ts.map +1 -0
  94. package/dist/registry/contract-processor-registry-builder.d.ts +11 -0
  95. package/dist/registry/contract-processor-registry-builder.d.ts.map +1 -0
  96. package/dist/registry/contract-processor-registry.d.ts +17 -0
  97. package/dist/registry/contract-processor-registry.d.ts.map +1 -0
  98. package/dist/registry/index.d.ts +4 -0
  99. package/dist/registry/index.d.ts.map +1 -0
  100. package/dist/registry/processors/myos-timeline-channel-processor.d.ts +59 -0
  101. package/dist/registry/processors/myos-timeline-channel-processor.d.ts.map +1 -0
  102. package/dist/registry/processors/operation-marker-processor.d.ts +43 -0
  103. package/dist/registry/processors/operation-marker-processor.d.ts.map +1 -0
  104. package/dist/registry/processors/sequential-workflow-operation-processor.d.ts +76 -0
  105. package/dist/registry/processors/sequential-workflow-operation-processor.d.ts.map +1 -0
  106. package/dist/registry/processors/sequential-workflow-processor.d.ts +64 -0
  107. package/dist/registry/processors/sequential-workflow-processor.d.ts.map +1 -0
  108. package/dist/registry/processors/steps/javascript-code-step-executor.d.ts +8 -0
  109. package/dist/registry/processors/steps/javascript-code-step-executor.d.ts.map +1 -0
  110. package/dist/registry/processors/steps/quickjs-step-bindings.d.ts +4 -0
  111. package/dist/registry/processors/steps/quickjs-step-bindings.d.ts.map +1 -0
  112. package/dist/registry/processors/steps/trigger-event-step-executor.d.ts +7 -0
  113. package/dist/registry/processors/steps/trigger-event-step-executor.d.ts.map +1 -0
  114. package/dist/registry/processors/steps/update-document-step-executor.d.ts +11 -0
  115. package/dist/registry/processors/steps/update-document-step-executor.d.ts.map +1 -0
  116. package/dist/registry/processors/timeline-channel-processor.d.ts +50 -0
  117. package/dist/registry/processors/timeline-channel-processor.d.ts.map +1 -0
  118. package/dist/registry/processors/utils/operation-utils.d.ts +6 -0
  119. package/dist/registry/processors/utils/operation-utils.d.ts.map +1 -0
  120. package/dist/registry/processors/workflow/operation-matcher.d.ts +17 -0
  121. package/dist/registry/processors/workflow/operation-matcher.d.ts.map +1 -0
  122. package/dist/registry/processors/workflow/step-runner.d.ts +28 -0
  123. package/dist/registry/processors/workflow/step-runner.d.ts.map +1 -0
  124. package/dist/registry/types.d.ts +71 -0
  125. package/dist/registry/types.d.ts.map +1 -0
  126. package/dist/runtime/document-processing-runtime.d.ts +31 -0
  127. package/dist/runtime/document-processing-runtime.d.ts.map +1 -0
  128. package/dist/runtime/emission-registry.d.ts +14 -0
  129. package/dist/runtime/emission-registry.d.ts.map +1 -0
  130. package/dist/runtime/gas-helpers.d.ts +9 -0
  131. package/dist/runtime/gas-helpers.d.ts.map +1 -0
  132. package/dist/runtime/gas-meter.d.ts +32 -0
  133. package/dist/runtime/gas-meter.d.ts.map +1 -0
  134. package/dist/runtime/index.d.ts +6 -0
  135. package/dist/runtime/index.d.ts.map +1 -0
  136. package/dist/runtime/patch-engine.d.ts +28 -0
  137. package/dist/runtime/patch-engine.d.ts.map +1 -0
  138. package/dist/runtime/scope-runtime-context.d.ts +31 -0
  139. package/dist/runtime/scope-runtime-context.d.ts.map +1 -0
  140. package/dist/test-support/blue.d.ts +27 -0
  141. package/dist/test-support/blue.d.ts.map +1 -0
  142. package/dist/test-support/workflow.d.ts +18 -0
  143. package/dist/test-support/workflow.d.ts.map +1 -0
  144. package/dist/types/document-processing-result.d.ts +13 -0
  145. package/dist/types/document-processing-result.d.ts.map +1 -0
  146. package/dist/types/errors.d.ts +42 -0
  147. package/dist/types/errors.d.ts.map +1 -0
  148. package/dist/types/index.d.ts +4 -0
  149. package/dist/types/index.d.ts.map +1 -0
  150. package/dist/types/result.d.ts +23 -0
  151. package/dist/types/result.d.ts.map +1 -0
  152. package/dist/types/scope-contracts.d.ts +7 -0
  153. package/dist/types/scope-contracts.d.ts.map +1 -0
  154. package/dist/util/expression/exceptions.d.ts +6 -0
  155. package/dist/util/expression/exceptions.d.ts.map +1 -0
  156. package/dist/util/expression/quickjs-evaluator.d.ts +23 -0
  157. package/dist/util/expression/quickjs-evaluator.d.ts.map +1 -0
  158. package/dist/util/expression/quickjs-expression-utils.d.ts +29 -0
  159. package/dist/util/expression/quickjs-expression-utils.d.ts.map +1 -0
  160. package/dist/util/node-canonicalizer.d.ts +4 -0
  161. package/dist/util/node-canonicalizer.d.ts.map +1 -0
  162. package/dist/util/pointer-utils.d.ts +7 -0
  163. package/dist/util/pointer-utils.d.ts.map +1 -0
  164. package/package.json +21 -19
  165. package/dist/BlueDocumentProcessor.d.ts +0 -50
  166. package/dist/BlueDocumentProcessor.d.ts.map +0 -1
  167. package/dist/config.d.ts +0 -3
  168. package/dist/config.d.ts.map +0 -1
  169. package/dist/context.d.ts +0 -21
  170. package/dist/context.d.ts.map +0 -1
  171. package/dist/index.mjs +0 -1657
  172. package/dist/processors/BaseChannelProcessor.d.ts +0 -22
  173. package/dist/processors/BaseChannelProcessor.d.ts.map +0 -1
  174. package/dist/processors/ChannelEventCheckpointProcessor.d.ts +0 -13
  175. package/dist/processors/ChannelEventCheckpointProcessor.d.ts.map +0 -1
  176. package/dist/processors/CompositeTimelineChannelProcessor.d.ts +0 -9
  177. package/dist/processors/CompositeTimelineChannelProcessor.d.ts.map +0 -1
  178. package/dist/processors/DocumentUpdateChannelProcessor.d.ts +0 -9
  179. package/dist/processors/DocumentUpdateChannelProcessor.d.ts.map +0 -1
  180. package/dist/processors/EmbeddedNodeChannelProcessor.d.ts +0 -9
  181. package/dist/processors/EmbeddedNodeChannelProcessor.d.ts.map +0 -1
  182. package/dist/processors/InitializedMarkerProcessor.d.ts +0 -9
  183. package/dist/processors/InitializedMarkerProcessor.d.ts.map +0 -1
  184. package/dist/processors/LifecycleEventChannelProcessor.d.ts +0 -33
  185. package/dist/processors/LifecycleEventChannelProcessor.d.ts.map +0 -1
  186. package/dist/processors/MyOSAgentChannelProcessor.d.ts +0 -60
  187. package/dist/processors/MyOSAgentChannelProcessor.d.ts.map +0 -1
  188. package/dist/processors/MyOSTimelineChannelProcessor.d.ts +0 -9
  189. package/dist/processors/MyOSTimelineChannelProcessor.d.ts.map +0 -1
  190. package/dist/processors/OperationProcessor.d.ts +0 -13
  191. package/dist/processors/OperationProcessor.d.ts.map +0 -1
  192. package/dist/processors/ProcessEmbeddedProcessor.d.ts +0 -9
  193. package/dist/processors/ProcessEmbeddedProcessor.d.ts.map +0 -1
  194. package/dist/processors/SequentialWorkflowOperationProcessor.d.ts +0 -12
  195. package/dist/processors/SequentialWorkflowOperationProcessor.d.ts.map +0 -1
  196. package/dist/processors/SequentialWorkflowProcessor/SequentialWorkflowProcessor.d.ts +0 -19
  197. package/dist/processors/SequentialWorkflowProcessor/SequentialWorkflowProcessor.d.ts.map +0 -1
  198. package/dist/processors/SequentialWorkflowProcessor/index.d.ts +0 -2
  199. package/dist/processors/SequentialWorkflowProcessor/index.d.ts.map +0 -1
  200. package/dist/processors/SequentialWorkflowProcessor/steps/JavaScriptCodeExecutor.d.ts +0 -8
  201. package/dist/processors/SequentialWorkflowProcessor/steps/JavaScriptCodeExecutor.d.ts.map +0 -1
  202. package/dist/processors/SequentialWorkflowProcessor/steps/TriggerEventExecutor.d.ts +0 -8
  203. package/dist/processors/SequentialWorkflowProcessor/steps/TriggerEventExecutor.d.ts.map +0 -1
  204. package/dist/processors/SequentialWorkflowProcessor/steps/UpdateDocumentExecutor.d.ts +0 -14
  205. package/dist/processors/SequentialWorkflowProcessor/steps/UpdateDocumentExecutor.d.ts.map +0 -1
  206. package/dist/processors/SequentialWorkflowProcessor/types.d.ts +0 -7
  207. package/dist/processors/SequentialWorkflowProcessor/types.d.ts.map +0 -1
  208. package/dist/processors/SequentialWorkflowProcessor/utils/BindingsFactory.d.ts +0 -12
  209. package/dist/processors/SequentialWorkflowProcessor/utils/BindingsFactory.d.ts.map +0 -1
  210. package/dist/processors/SequentialWorkflowProcessor/utils/ExpressionEvaluator.d.ts +0 -61
  211. package/dist/processors/SequentialWorkflowProcessor/utils/ExpressionEvaluator.d.ts.map +0 -1
  212. package/dist/processors/SequentialWorkflowProcessor/utils/ExpressionResolver.d.ts +0 -8
  213. package/dist/processors/SequentialWorkflowProcessor/utils/ExpressionResolver.d.ts.map +0 -1
  214. package/dist/processors/TimelineChannelProcessor.d.ts +0 -9
  215. package/dist/processors/TimelineChannelProcessor.d.ts.map +0 -1
  216. package/dist/processors/TriggeredEventChannelProcessor.d.ts +0 -12
  217. package/dist/processors/TriggeredEventChannelProcessor.d.ts.map +0 -1
  218. package/dist/processors/index.d.ts +0 -15
  219. package/dist/processors/index.d.ts.map +0 -1
  220. package/dist/queue/TaskKey.d.ts +0 -22
  221. package/dist/queue/TaskKey.d.ts.map +0 -1
  222. package/dist/queue/TaskQueue.d.ts +0 -31
  223. package/dist/queue/TaskQueue.d.ts.map +0 -1
  224. package/dist/registry/ContractRegistry.d.ts +0 -47
  225. package/dist/registry/ContractRegistry.d.ts.map +0 -1
  226. package/dist/routing/EventRouter.d.ts +0 -51
  227. package/dist/routing/EventRouter.d.ts.map +0 -1
  228. package/dist/routing/buildContractEntries.d.ts +0 -3
  229. package/dist/routing/buildContractEntries.d.ts.map +0 -1
  230. package/dist/testUtils.d.ts +0 -15
  231. package/dist/testUtils.d.ts.map +0 -1
  232. package/dist/types.d.ts +0 -84
  233. package/dist/types.d.ts.map +0 -1
  234. package/dist/utils/CheckpointCache.d.ts +0 -10
  235. package/dist/utils/CheckpointCache.d.ts.map +0 -1
  236. package/dist/utils/EventTraceManager.d.ts +0 -47
  237. package/dist/utils/EventTraceManager.d.ts.map +0 -1
  238. package/dist/utils/TinyQueue.d.ts +0 -12
  239. package/dist/utils/TinyQueue.d.ts.map +0 -1
  240. package/dist/utils/checkpoint.d.ts +0 -4
  241. package/dist/utils/checkpoint.d.ts.map +0 -1
  242. package/dist/utils/document.d.ts +0 -29
  243. package/dist/utils/document.d.ts.map +0 -1
  244. package/dist/utils/eventFactories.d.ts +0 -37
  245. package/dist/utils/eventFactories.d.ts.map +0 -1
  246. package/dist/utils/exceptions.d.ts +0 -28
  247. package/dist/utils/exceptions.d.ts.map +0 -1
  248. package/dist/utils/expressionUtils.d.ts +0 -18
  249. package/dist/utils/expressionUtils.d.ts.map +0 -1
  250. package/dist/utils/initialized.d.ts +0 -5
  251. package/dist/utils/initialized.d.ts.map +0 -1
  252. package/dist/utils/logPatchError.d.ts +0 -3
  253. package/dist/utils/logPatchError.d.ts.map +0 -1
  254. package/dist/utils/path.d.ts +0 -2
  255. package/dist/utils/path.d.ts.map +0 -1
  256. package/dist/utils/typeGuard.d.ts +0 -5
  257. package/dist/utils/typeGuard.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,9 +1,3176 @@
1
- "use strict";var Ee=Object.create;var R=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var be=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty;var Pe=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of we(e))!Te.call(a,o)&&o!==t&&R(a,o,{get:()=>e[o],enumerable:!(n=ve(e,o))||n.enumerable});return a};var W=(a,e,t)=>(t=a!=null?Ee(be(a)):{},Pe(e||!a||!a.__esModule?R(t,"default",{value:a,enumerable:!0}):t,a));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("@blue-repository/core-dev"),p=require("@blue-labs/language"),E=require("@blue-labs/shared-utils"),S=require("@blue-repository/myos-dev"),P=(...a)=>a.map((e,t)=>{if(typeof e!="string")return"";if(t===0&&e==="/")return"/";const n=t>0?e.replace(/^\/+/,""):e;return t<a.length-1?n.replace(/\/+$/,""):n}).filter(Boolean).join("/").replace(/\/{2,}/g,"/");class Q{constructor(e,t,n,o){this.getDocument=e,this.taskInfo=t,this.blue=n,this.onFlush=o}actions=[];get(e){const t=this.getDocument(),n=P(this.taskInfo.nodePath,e);return t.get(n)}addPatch(e){this.actions.push({kind:"patch",patch:{...e,path:P(this.taskInfo.nodePath,e.path)}})}emitEvent(e){const t=this.taskInfo.event,n=t.trace??[],o={...e,source:e.source??"internal",originNodePath:e.originNodePath??this.taskInfo.nodePath,rootEvent:e.rootEvent??t.rootEvent??t,trace:[...n],emissionType:e.emissionType??t.emissionType};this.actions.push({kind:"event",event:o})}async flush(){if(!this.actions.length)return[];const e=[...this.actions];return this.actions.length=0,await this.onFlush?.(e),e}getNodePath(){return this.taskInfo.nodePath}resolvePath(e){return P(this.taskInfo.nodePath,e)}getTaskInfo(){return this.taskInfo}getBlue(){return this.blue}loadExternalModule(){throw new Error("Not implemented")}loadBlueContent(e){const t=this.blue.getNodeProvider().fetchFirstByBlueId(e);if(!t)throw new Error(`Blue node not found for blueId: ${e}`);return Promise.resolve(JSON.stringify(this.blue.nodeToJson(t)))}}class 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 G extends Error{constructor(e,t){super(`Failed to evaluate expression "${e}"`),this.code=e,this.cause=t,this.name="ExpressionEvaluationError"}}class K extends Error{constructor(e,t){super(`Failed to evaluate code block "${e}"`),this.code=e,this.cause=t,this.name="CodeBlockEvaluationError"}}function I(a){return E.deepFreeze(a)}function k(a){return a.clone()}function $(a,e,t="/",n=[]){const o=a.getContracts()??{};for(const[r,s]of Object.entries(o))if(e.isTypeOf(s,l.ProcessEmbeddedSchema)){const d=e.nodeToSchemaOutput(s,l.ProcessEmbeddedSchema).paths??[];for(const u of d)n.push({absPath:P(t,u),contractPath:P(t,`contracts/${r}`)})}for(const[r,s]of Object.entries(a.getProperties()??{}))$(s,e,P(t,r),n);return n}function J(a,e){return a===e||a.startsWith(e.endsWith("/")?e:e+"/")}function U(a,e){if(!e.length)return a;let t=k(a);for(const n of e)try{t=p.applyBlueNodePatch(t,n,!0)}catch(o){throw new A(n,o)}return I(t)}function v(a){return a!=null}function C(a){return a instanceof p.BlueNode}class Se{data;length;compare;constructor(e=[],t=(n,o)=>n<o?-1:n>o?1:0){if(this.data=e,this.length=this.data.length,this.compare=t,this.length>0)for(let n=(this.length>>1)-1;n>=0;n--)this._down(n)}push(e){this.data.push(e),this._up(this.length++)}pop(){if(this.length===0)return;const e=this.data[0],t=this.data.pop();return--this.length>0&&(this.data[0]=t,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:t,compare:n}=this,o=t[e];for(;e>0;){const r=e-1>>1,s=t[r];if(n(o,s)>=0)break;t[e]=s,e=r}t[e]=o}_down(e){const{data:t,compare:n}=this,o=this.length>>1,r=t[e];for(;e<o;){let s=(e<<1)+1;const i=s+1;if(i<this.length&&n(t[i],t[s])<0&&(s=i),n(t[s],r)>=0)break;t[e]=t[s],e=s}t[e]=r}}const Ce=(a,e,t,n,o,r)=>[-a,e,t,n,o,r],Ne=(a,e)=>{for(let t=0;t<a.key.length;t++){const n=a.key[t],o=e.key[t];if(n!==o)return typeof n=="number"&&typeof o=="number"?n-o:typeof n=="string"&&typeof o=="string"?n.localeCompare(o):0}return 0};class Ie{queue;constructor(){this.queue=new Se([],Ne)}push(e){this.queue.push(e)}pop(){return this.queue.pop()}get length(){return this.queue.length}}class ke{processors=new Map;typeOrder=new Map;constructor(e=[]){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 M{isEnabled;static MAX_TRACE_LENGTH=128;constructor(){this.isEnabled=process.env.TRACE_BLUE_ENABLED!=="false"}makeHop(e,t){return`${e}#${t}`}shouldTrace(){return this.isEnabled}addHop(e,t,n){if(!this.shouldTrace())return{...e};const o=e.trace??[],s=[...o.length>=M.MAX_TRACE_LENGTH?o.slice(o.length-(M.MAX_TRACE_LENGTH-1)):o,this.makeHop(t,n)];return{...e,trace:s}}getTrace(e){return e.trace??[]}clearTrace(e){return{...e,trace:[]}}isTracingEnabled(){return this.isEnabled}}function Be(a){return Object.entries(a.getContracts()??{})}const Oe=64;class Me{constructor(e,t,n,o,r){this.blue=e,this.registry=t,this.queue=n,this.getNextTaskId=o,this.getNextEventSeq=r,this.traceManager=new M}traceManager;async route(e,t,n,o,r=0){if(n.seq===void 0&&(n.seq=this.getNextEventSeq()),t.length===0){if(n.dispatchPath){const c=n.dispatchPath.split("/").filter(Boolean),d={...n};return delete d.dispatchPath,this.route(e,c,d,o,r)}if(n.source==="channel"&&n.originNodePath&&n.originNodePath!=="/"){const c=n.originNodePath?.split("/").filter(Boolean)??[];return this.route(e,c,n,o,r)}}const s=P("/",t.join("/")),i=e.get(s);C(i)&&await this.traverseContracts({doc:e,node:i,nodePath:s,event:n,afterTaskId:o,pathSegments:t,inlineDepth:r})}async traverseContracts(e){const{doc:t,node:n,nodePath:o,event:r,afterTaskId:s,pathSegments:i,inlineDepth:c}=e;if(!this.shouldSkipForChannel(r,o))for(const[d,u]of Be(n)){if(!u.getType())continue;const h=this.registry.get(u.getType());if(!h){console.warn(`No processor registered for contract: ${d}`);continue}const y={nodePath:o,contractName:d,contractNode:u,event:r},f=new Q(()=>t,y,this.blue);if(h.supports(r,u,f,d))switch(h.role){case"adapter":await this.processAdapter({cp:h,event:r,contractNode:u,ctx:f,contractName:d,doc:t,afterTaskId:s,inlineDepth:c});break;case"handler":this.scheduleHandler({contractNode:u,contractName:d,nodePath:o,event:r,depth:i.length,afterTaskId:s});break}}}async processAdapter(e){const{cp:t,event:n,contractNode:o,ctx:r,contractName:s,doc:i,afterTaskId:c,inlineDepth:d}=e;if(d>=Oe)throw new Error("Adapter recursion limit reached");const u=this.traceManager.addHop(n,r.getTaskInfo()?.nodePath??"",s);await t.handle(u,o,r,s);const h=await r.flush();if(h.find(w=>w.kind==="patch"))throw new Error(`Contract "${s}" (adapter) attempted to patch the document`);const f=h.filter(w=>w.kind==="event");for(const w of f)await this.route(i,[],w.event,c,d+1)}scheduleHandler(e){const{contractNode:t,contractName:n,nodePath:o,event:r,depth:s,afterTaskId:i}=e,c=t.getType();if(!c){console.warn(`Contract node type is not defined for: ${n}`);return}const d=this.registry.orderOf(c),u=t.get("/order"),h=p.isBigNumber(u)?u.toNumber():0,y=this.getNextTaskId()+i,f=r.seq;if(f===void 0)throw new Error("Event sequence missing");const w=Ce(s,f,d,h,n,y);{const B=`${o}#${n}`,b=r.trace??[];if(r.source!=="external"&&b.includes(B))throw new Error(`Loop detected: repeated hop ${B} within the same event chain`)}const g=this.traceManager.addHop(r,o,n);this.queue.push({key:w,nodePath:o,contractName:n,contractNode:t,event:g})}shouldSkipForChannel(e,t){return e.source==="channel"&&!!e.originNodePath&&e.originNodePath!==t}}const qe=(a,e,t)=>{(t instanceof A||t instanceof j)&&console.error(`[Blue] Failed to apply patches for contract "${a}" on event ${JSON.stringify(e)}`,t)};function L(a,e){const t=k(a),n=o=>{if(!C(o))return;const r=o.getContracts();(!r?.checkpoint||!p.BlueNodeTypeSchema.isTypeOf(r.checkpoint,l.ChannelEventCheckpointSchema))&&o.addContract("checkpoint",e.jsonValueToNode({type:{name:"Channel Event Checkpoint",blueId:l.blueIds["Channel Event Checkpoint"]},lastEvents:{}}))};n(t);for(const{absPath:o}of $(t,e)){const r=t.get(o);C(r)&&n(r)}return I(t)}function $e(a,e){const t=k(a);return C(t)&&(Y(t,e)||t.addContract("initialized",e.jsonValueToNode({type:{name:"Initialized Marker",blueId:l.blueIds["Initialized Marker"]}}))),I(t)}function Y(a,e){const t=a.getContracts();return Object.values(t??{}).some(n=>e.isTypeOf(n,l.InitializedMarkerSchema,{checkSchemaExtensions:!0}))}class Z{constructor(e){this.cache=e}contractType="Channel Event Checkpoint";contractBlueId=l.blueIds["Channel Event Checkpoint"];role="handler";supports(e){return e.source==="channel"&&e.rootEvent?.payload===e.payload&&e.rootEvent?.source==="external"}async getEventBlueId(e,t){const n=e.rootEvent?.payload;if(!n)throw new Error("Cannot calculate blueId for checkpoint: missing root event payload");if(n instanceof p.ResolvedBlueNode){const o=n.getMinimalNode();return await t.getBlue().calculateBlueId(o)}return await t.getBlue().calculateBlueId(n)}async handle(e,t,n){if(!e.channelName||!e.rootEvent?.seq)return;const o=await this.getEventBlueId(e,n),r=n.getNodePath().replace(/\/contracts\/checkpoint$/,"");this.cache.record(r,e,o)}}const z=(a,e)=>a.get(e)!==void 0;class De{firstSeen=new Map;record(e,t,n){const o=e;this.firstSeen.has(o)||this.firstSeen.set(o,{docBase:e,event:t,eventBlueId:n})}flush(e){const t=[];for(const{docBase:n,event:o,eventBlueId:r}of this.firstSeen.values()){if(!o.channelName)continue;const s=P(n,"contracts/checkpoint/lastEvents",o.channelName),i=`${s}/blueId`;z(e,s)?t.push({op:z(e,i)?"replace":"add",path:i,val:r}):t.push({op:"add",path:s,val:{blueId:r}})}return t}clear(){this.firstSeen.clear()}}class ee{contractType="Composite Timeline Channel";contractBlueId=l.blueIds["Composite Timeline Channel"];role="adapter";supports(e,t,n){const o=n.getBlue().nodeToSchemaOutput(t,l.CompositeTimelineChannelSchema);return!o.channels||!e.channelName?!1:o.channels.includes(e.channelName)}handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}}class N{role="adapter";baseSupports(e){return e.source!=="channel"}}class te extends N{contractType="Document Update Channel";contractBlueId=l.blueIds["Document Update Channel"];supports(e,t,n){if(!this.baseSupports(e)||e.emissionType!=="update")return!1;const o=n.getBlue().nodeToSchemaOutput(t,l.DocumentUpdateChannelSchema),r=e.payload.get("/path");if(!r)return!1;const s=o.path;return E.isNonNullable(s)&&r===n.resolvePath(s)}handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}}class ne extends N{contractType="Embedded Node Channel";contractBlueId=l.blueIds["Embedded Node Channel"];supports(e,t,n){if(!this.baseSupports(e))return!1;const o=n.getBlue().nodeToSchemaOutput(t,l.EmbeddedNodeChannelSchema);return v(e.originNodePath)&&v(o.path)&&e.originNodePath===n.resolvePath(o.path)}handle(e,t,n,o){const r=n.getBlue().nodeToSchemaOutput(t,l.EmbeddedNodeChannelSchema),{originNodePath:s,payload:i}=e;v(r.path)&&s===n.resolvePath(r.path)&&n.emitEvent({payload:i,channelName:o,source:"channel"})}}class oe{contractType="Initialized Marker";contractBlueId=l.blueIds["Initialized Marker"];role="marker";supports(){return!1}handle(){}}class re extends N{contractType="Lifecycle Event Channel";contractBlueId=l.blueIds["Lifecycle Event Channel"];supports(e,t,n){return!this.baseSupports(e)||e.emissionType!=="lifecycle"||!this.isLifecycleEvent(e,n)?!1:this.isEventPatternMatch(e,t,n)}handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel",emissionType:e.emissionType})}isLifecycleEvent(e,t){const n=t.getBlue(),o=e.payload;return n.isTypeOf(o,l.LifecycleEventSchema,{checkSchemaExtensions:!0})}isEventPatternMatch(e,t,n){const o=t.getProperties()?.event;if(!o)return!0;try{const r=n.getBlue(),s=r.resolve(e.payload);return r.isTypeOfNode(s,o)}catch(r){return console.warn("Error during lifecycle event pattern matching:",r),!1}}}const H=(a,e)=>{const t=e.getBlue();return t.isTypeOf(a.payload,l.TimelineEntrySchema)||t.isTypeOf(a.payload,S.MyOSTimelineEntrySchema)};class se extends N{contractType="MyOS Timeline Channel";contractBlueId=S.blueIds["MyOS Timeline Channel"];supports(e,t,n){if(!this.baseSupports(e)||!H(e,n))return!1;const r=n.getBlue().nodeToSchemaOutput(e.payload,S.MyOSTimelineEntrySchema),s=n.getBlue().nodeToSchemaOutput(t,S.MyOSTimelineChannelSchema),i=r.timeline?.timelineId;return v(s.timelineId)&&v(i)&&i===s.timelineId}handle(e,t,n,o){H(e,n)&&n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}}class ae extends N{contractType="MyOS Agent Channel";contractBlueId=S.blueIds["MyOS Agent Channel"];supports(e,t,n){if(!this.baseSupports(e))return!1;try{const{myosAgentEvent:o,myosAgentChannel:r}=this.parseEventAndChannel(e,t,n);return this.isAgentMatch(o,r)&&this.isEventPatternMatch(o,r,n)}catch(o){return console.warn("Error in MyOSAgentChannelProcessor.supports:",o),!1}}handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}parseEventAndChannel(e,t,n){const o=n.getBlue(),r=o.nodeToSchemaOutput(e.payload,S.MyOSAgentEventSchema),s=o.nodeToSchemaOutput(t,S.MyOSAgentChannelSchema);return{myosAgentEvent:r,myosAgentChannel:s}}isAgentMatch(e,t){const n=e.agentId,o=t.agent?.agentId;return v(n)&&v(o)&&n===o}isEventPatternMatch(e,t,n){const o=t.event;if(!o)return!0;const r=e.event;if(!r)return!1;try{const s=n.getBlue(),i=s.nodeToJson(r),c=s.nodeToJson(o);return E.deepContains(i,c)}catch(s){return console.warn("Error during event pattern matching:",s),!1}}}class ie{contractType="Operation";contractBlueId=l.blueIds.Operation;role="adapter";supports(e,t,n,o){const s=n.getBlue().nodeToSchemaOutput(t,l.OperationSchema),i=this.parseEventPayload(e,n),c=this.isOperationNameMatch(i,o),d=this.isOperationChannelMatch(e,s),u=this.isRequestPatternMatch(i,s,n);return c&&d&&u}async handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}parseEventPayload(e,t){const n=t.getBlue();if(n.isTypeOf(e.payload,l.TimelineEntrySchema,{checkSchemaExtensions:!0})){const o=n.nodeToSchemaOutput(e.payload,l.TimelineEntrySchema);if(o.message)return n.nodeToSchemaOutput(o.message,l.OperationRequestSchema)}return null}isOperationNameMatch(e,t){return v(e?.operation)&&e?.operation===t}isOperationChannelMatch(e,t){const n=t.channel;return E.isNullable(n)?!0:e.source==="channel"&&e.channelName===n}isRequestPatternMatch(e,t,n){const o=t.request;if(E.isNullable(o))return!0;const r=n.getBlue(),s=e?.request;if(E.isNullable(s))return!1;const i=r.resolve(s);return r.isTypeOfNode(i,o)}}class ce{contractType="Process Embedded";role="adapter";contractBlueId=l.blueIds["Process Embedded"];supports(e){return e.source!=="channel"}handle(e,t,n){const o=n.getBlue().nodeToSchemaOutput(t,l.ProcessEmbeddedSchema);for(const r of o.paths??[])n.emitEvent({...e,dispatchPath:n.resolvePath(r)})}}const Ae=!process.env.SKIP_ISOLATED_VM;let m=null;if(Ae)try{m=require("isolated-vm")}catch{console.warn("isolated-vm not available, using fallback evaluation method")}function je(a){return/\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(a)||/\bexport\s+/.test(a)}class q{static getIvmUnavailableMessage(){const e=typeof process<"u"&&process.version?process.version:"unknown",t=typeof process<"u"&&process.platform?process.platform:"unknown",n=typeof process<"u"&&process.arch?process.arch:"unknown";return["isolated-vm is required for expression evaluation but could not be loaded.","This feature only works in a Node.js environment with the native addon available.","",`Detected environment: Node ${e} on ${t}/${n}.`,"","Common causes:","- Running in a non-Node environment (browser, edge/runtime without Node).","- 'isolated-vm' is not installed, or failed to build its native addon.","- The module was bundled/stripped by a build tool.","","How to fix:","- Ensure 'isolated-vm' is listed in dependencies (not devDependencies) of the executing package.","- Reinstall or rebuild: npm ci && npm rebuild isolated-vm (or equivalent with your package manager).","- Run this code on a supported Node.js runtime (not browser/edge workers)."].join(`
2
- `)}static async ensureIvm(){if(m)return m;try{typeof require=="function"?m=require("isolated-vm"):m=(await import("isolated-vm")).default??await import("isolated-vm")}catch(e){console.error(e),m=null}return m}static async evaluate({code:e,ctx:t,bindings:n={},options:o={}}){if(await this.ensureIvm(),!m)throw new Error(this.getIvmUnavailableMessage());return this.evaluateSecure(e,n,t,o)}static async evaluateSecure(e,t,n,o={}){if(!m)throw new Error(this.getIvmUnavailableMessage());const r=new m.Isolate({memoryLimit:32}),s=await r.createContext(),i=s.global;try{await this.setupIsolateEnvironment(i,t);const c=new Map,d=this.createModuleResolver(r,s,c,n);let u;return je(e)?u=await this.evaluateESModule(r,s,e,o,d):u=await this.evaluateSimpleScript(r,s,e,t,o),this.deepClone(u)}catch(c){throw o.isCodeBlock?new K(e,c):new G(e,c)}finally{s.release(),r.dispose()}}static async setupIsolateEnvironment(e,t){if(!m)throw new Error("isolated-vm not available");const n=new m.Callback((...r)=>console.log(...r)),o=new m.ExternalCopy({log:n}).copyInto();await e.set("console",o);for(const[r,s]of Object.entries(t))typeof s=="function"?await e.set(r,new m.Callback(s)):await e.set(r,new m.ExternalCopy(s).copyInto())}static createModuleResolver(e,t,n,o){return async r=>{if(n.has(r))return n.get(r);if(r.startsWith("blue:")){const s=r.slice(5),i=o.loadBlueContent;if(typeof i!="function")throw new Error(`ProcessingContext is missing a loadBlueContent(blueId) implementation (needed for ${r})`);const c=await i(s),d=await e.compileModule(c);return n.set(r,d),await d.instantiate(t,this.createModuleResolver(e,t,n,o)),d}if(/^https?:\/\//.test(r)){let s;if(typeof o.loadExternalModule=="function")s=await o.loadExternalModule(r);else throw new Error(`ProcessingContext is missing a loadExternalModule(url) implementation (needed for ${r})`);const i=await e.compileModule(s);return n.set(r,i),await i.instantiate(t,this.createModuleResolver(e,t,n,o)),i}throw new Error(`Unsupported module specifier "${r}"`)}}static async evaluateSimpleScript(e,t,n,o,r){const s=Object.keys(o).join(", "),i=Object.keys(o).map(u=>u),c=`(async (${s}) => { ${r.isCodeBlock?n:`return (${n});`} })(${i.join(", ")})`;return await(await e.compileScript(c)).run(t,{timeout:r.timeout??500,promise:!0,copy:!0,release:!0})}static async evaluateESModule(e,t,n,o,r){let s=n;if(o.isCodeBlock){const d=/^\s*(import\s.+?;|export\s.+?;)/gm,u=(n.match(d)||[]).join(`
3
- `),h=n.replace(d,"").trim();s=`
4
- ${u}
5
- const run = function() {
6
- ${h}
7
- };
8
- export default run();
9
- `}const i=await e.compileModule(s);return await i.instantiate(t,r),await i.evaluate({timeout:o.timeout??500,promise:!0,reference:!0,release:!0}),await i.namespace.get("default",{timeout:o.timeout??500,promise:!0,copy:!0,release:!0})}static deepClone(e){return typeof e>"u"?e:JSON.parse(JSON.stringify(e))}}class x{static createStandardBindings(e,t,n){const o=e.getBlue(),r=o.nodeToJson(t.payload,"simple"),s=p.isBigNumber(r)?r.toNumber():r;return{document:i=>{const c=e.get(i);return p.isBigNumber(c)?c.toNumber():C(c)?o.nodeToJson(c,"original"):c},event:s,steps:n}}}const xe=/^\$\{([\s\S]*)\}$/,Ve=/\$\{([\s\S]*?)\}/,T=a=>typeof a!="string"?!1:xe.test(a),D=a=>typeof a!="string"?!1:Ve.test(a),le=a=>{if(!T(a))throw new Error(`Invalid expression: ${a}`);return a.slice(2,-1)};class O{static createBindings(e,t,n){return x.createStandardBindings(e,t,n)}static async evaluate(e,t,n,o){const{coerceToString:r}=o;if(T(e)){const s=le(e),i=await q.evaluate({code:s,ctx:t,bindings:n});return r?String(i??""):i}if(D(e)){const i=`\`${String(e).replace(/`/g,"\\`")}\``,c=await q.evaluate({code:i,ctx:t,bindings:n});return String(c??"")}return r?String(e):e}}function F(a,e){const{op:t,path:n,val:o,from:r}=a;if((t==="move"||t==="copy")&&!r)throw new Error(`${t} operation requires 'from' path`);if((t==="add"||t==="replace")&&o===void 0)throw new Error(`${t} operation requires 'val' property`);const s={type:"Document Update",op:t,path:n};return o!==void 0&&(s.val=o),r!==void 0&&(s.from=r),e.jsonValueToNode(s)}function _e(a){return a.jsonValueToNode({type:"Document Processing Initiated"})}class Re{stepType="Update Document";supports(e){return p.BlueNodeTypeSchema.isTypeOf(e,l.UpdateDocumentSchema)}async execute(e,t,n,o,r){const s=n.getBlue();if(!p.BlueNodeTypeSchema.isTypeOf(e,l.UpdateDocumentSchema))return;const i=await this.evaluateChangeset(e.get("/changeset"),n,t,r),c=p.applyBlueNodePatch(e,{op:"replace",path:"/changeset",val:i}),d=n.getBlue().nodeToSchemaOutput(c,l.UpdateDocumentSchema);for(const u of d.changeset??[]){if(!u.path)continue;const h=await this.evaluateChangePath(u.path,n,t,r),y=u.val;if((u.op==="replace"||u.op==="add")&&E.isNonNullable(y)){const f=await this.evaluateChangeValue(y,n,t,r);n.addPatch({op:u.op,path:h,val:f}),n.emitEvent({payload:F({op:u.op,path:n.resolvePath(h),val:s.nodeToJson(f,"original")},s),emissionType:"update"})}u.op==="remove"&&(n.addPatch({op:u.op,path:h}),n.emitEvent({payload:F({op:u.op,path:n.resolvePath(h),val:null},s),emissionType:"update"}))}}async evaluateChangeset(e,t,n,o){const r=t.getBlue();if(T(e)){const s=le(e),i=await q.evaluate({code:s,ctx:t,bindings:x.createStandardBindings(t,n,o)});return r.jsonValueToNode(i??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(),s=t.getBlue();if(T(r)||typeof r=="string"&&D(r)){const i=O.createBindings(t,n,o),c=await O.evaluate(String(r),t,i,{coerceToString:!T(r)});return s.jsonValueToNode(c??null)}return e}async evaluateChangePath(e,t,n,o){const r=O.createBindings(t,n,o);if(T(e)||D(e)){const s=await O.evaluate(e,t,r,{coerceToString:!0});return String(s??"")}return e}}class We{stepType="Trigger Event";supports(e){return p.BlueNodeTypeSchema.isTypeOf(e,l.TriggerEventSchema)}async execute(e,t,n){const o=n.getBlue();if(!p.BlueNodeTypeSchema.isTypeOf(e,l.TriggerEventSchema))return;const r=o.nodeToSchemaOutput(e,l.TriggerEventSchema);r.event&&n.emitEvent({payload:r.event,emissionType:"triggered"})}}class Je{stepType="JavaScript Code";supports(e){return p.BlueNodeTypeSchema.isTypeOf(e,l.JavaScriptCodeSchema)}async execute(e,t,n,o,r){if(!p.BlueNodeTypeSchema.isTypeOf(e,l.JavaScriptCodeSchema))return;const s=n.getBlue(),i=s.nodeToSchemaOutput(e,l.JavaScriptCodeSchema);if(!i.code)throw new Error("JavaScript code is required");const c=await q.evaluate({code:i.code,ctx:n,bindings:x.createStandardBindings(n,t,r),options:{isCodeBlock:!0,timeout:500}});if(c&&typeof c=="object"&&"events"in c){const d=c;if(Array.isArray(d.events))for(const u of d.events)n.emitEvent({payload:s.jsonValueToNode(u),emissionType:"triggered"})}return c}}const Ue=[new Re,new We,new Je];class V{contractType="Sequential Workflow";contractBlueId=l.blueIds["Sequential Workflow"];role="handler";executors=[];constructor(e=Ue){this.executors=e}registerExecutor(e){this.executors.push(e)}supports(e,t,n){const r=n.getBlue().nodeToSchemaOutput(t,l.SequentialWorkflowSchema),s=this.isChannelNameMatch(e,r),i=this.isEventPatternMatch(e,t,n);return s&&i}async handle(e,t,n,o){const r={},s=t.getProperties()?.steps.getItems();for(const[i,c]of(s??[]).entries()){const d=this.executors.find(h=>h.supports(c));if(!d)throw new Error(`Unsupported workflow step type "${c.getType()}"`);const u=await d.execute(c,e,n,o,r);if(u!==void 0){const h=c.getName(),y=typeof h=="string"?h:`Step${i+1}`;r[y]=u}await n.flush()}}isChannelNameMatch(e,t){const n=t.channel;return E.isNonNullable(n)&&e.source==="channel"&&e.channelName===n}isEventPatternMatch(e,t,n){const o=t.getProperties()?.event;if(!o)return!0;try{const r=n.getBlue(),s=r.resolve(e.payload);return r.isTypeOfNode(s,o)}catch(r){return console.warn("Error during event pattern matching:",r),!1}}}class ue{contractType="Sequential Workflow Operation";contractBlueId=l.blueIds["Sequential Workflow Operation"];role="handler";sequentialWorkflowProcessor;constructor(e){this.sequentialWorkflowProcessor=e||new V}supports(e,t,n){const s=n.getBlue().nodeToSchemaOutput(t,l.SequentialWorkflowOperationSchema).operation,i=e.channelName;return e.source==="channel"&&E.isNonNullable(i)&&E.isNonNullable(s)&&i===s}async handle(e,t,n,o){try{await this.sequentialWorkflowProcessor.handle(e,t,n,o)}catch(r){throw console.error("Error in SequentialWorkflowOperationProcessor.handle:",r),r}}}const X=a=>p.BlueNodeTypeSchema.isTypeOf(a.payload,l.TimelineEntrySchema);class de extends N{contractType="Timeline Channel";contractBlueId=l.blueIds["Timeline Channel"];supports(e,t,n){if(!this.baseSupports(e)||!X(e))return!1;const r=n.getBlue().nodeToSchemaOutput(e.payload,l.TimelineEntrySchema),s=n.getBlue().nodeToSchemaOutput(t,l.TimelineChannelSchema),i=r.timeline?.timelineId;return v(s.timelineId)&&v(i)&&i===s.timelineId}handle(e,t,n,o){X(e)&&n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}}class he extends N{contractType="Triggered Event Channel";contractBlueId=l.blueIds["Triggered Event Channel"];supports(e){return this.baseSupports(e)?e.emissionType==="triggered":!1}handle(e,t,n,o){n.emitEvent({payload:e.payload,channelName:o,source:"channel"})}}const Le=[new ce,new ne,new te,new de,new se,new ae,new ee,new re,new he,new ie,new V,new ue,new oe];class ze{constructor(e,t=Le){this.blue=e,this.registry=new ke(t),this.queue=new Ie,this.router=new Me(this.blue,this.registry,this.queue,()=>++this.taskCounter,()=>++this.eventCounter),this.register(new Z(this.checkpointCache),9999)}taskCounter=0;eventCounter=0;registry;queue;router;checkpointCache=new De;register(e,t){this.registry.register(e,t)}async initialize(e){let t=L(I(e),this.blue);const n={payload:_e(this.blue),source:"internal",emissionType:"lifecycle"},o=[n.payload];await this.router.route(t,[],n,0);const r=await this.drainQueue(t);return t=r.state,o.push(...r.emitted),t=$e(t,this.blue),{state:k(t),emitted:o}}async processEvents(e,t){let n=L(I(e),this.blue);const o=[];if(!Y(n,this.blue))throw new Error("Document is not initialized");for(const r of t)try{const s={payload:r,source:"external"};await this.router.route(n,[],s,0);const i=await this.drainQueue(n);n=i.state,o.push(...i.emitted);const c=this.checkpointCache.flush(n);c.length&&(n=U(n,c))}finally{this.checkpointCache.clear()}return{state:k(n),emitted:o}}async drainQueue(e){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 s=this.queue.pop(),{nodePath:i,contractName:c,contractNode:d,event:u}=s,h=t.get(i);if(!C(h)||!h.getContracts()?.[c]||!d.getType())continue;const y=this.registry.get(d.getType());if(!y){console.warn(`No processor registered for contract: ${c}`);continue}const f=new Q(()=>t,s,this.blue,async w=>{for(const g of w)if(g.kind==="patch"){const B=$(t,this.blue);for(const b of B){const me=g.patch.op==="move"||g.patch.op==="copy"?[g.patch.from,g.patch.path]:[g.patch.path],_=f.getNodePath(),fe=me.some(ye=>J(ye,b.absPath)),ge=J(_,b.absPath);if(fe&&!ge)throw new j(g.patch,b.absPath,_)}try{t=U(t,[g.patch])}catch(b){throw qe(c,u,b),b}}else g.kind==="event"&&(n.push(g.event.payload),await this.router.route(t,[],g.event,s.key[5]))});await y.handle(u,d,f,c),await f.flush()}return{state:t,emitted:n}}}class pe{process(e,t){const n=t.getValue();if(T(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(T(n)&&e.getValue()!==n&&n!==void 0){const o=e.clone();return o.setValue(n),o}return e}}const He=Object.freeze(Object.defineProperty({__proto__:null,ExpressionPreserver:pe},Symbol.toStringTag,{value:"Module"}));function Fe(){return new p.MergingProcessors.SequentialMergingProcessor([new p.MergingProcessors.ValuePropagator,new pe,new p.MergingProcessors.TypeAssigner,new p.MergingProcessors.ListProcessor,new p.MergingProcessors.DictionaryProcessor,new p.MergingProcessors.BasicTypesVerifier])}exports.BlueDocumentProcessor=ze;exports.ChannelEventCheckpointProcessor=Z;exports.CodeBlockEvaluationError=K;exports.CompositeTimelineChannelProcessor=ee;exports.DocumentUpdateChannelProcessor=te;exports.EmbeddedDocumentModificationError=j;exports.EmbeddedNodeChannelProcessor=ne;exports.ExpressionEvaluationError=G;exports.InitializedMarkerProcessor=oe;exports.LifecycleEventChannelProcessor=re;exports.MergingProcessors=He;exports.MyOSAgentChannelProcessor=ae;exports.MyOSTimelineChannelProcessor=se;exports.OperationProcessor=ie;exports.PatchApplicationError=A;exports.ProcessEmbeddedProcessor=ce;exports.SequentialWorkflowOperationProcessor=ue;exports.SequentialWorkflowProcessor=V;exports.TimelineChannelProcessor=de;exports.TriggeredEventChannelProcessor=he;exports.collectEmbeddedPathSpecs=$;exports.createDefaultMergingProcessor=Fe;
1
+ import { blueIds as p, ContractSchema as Ye, ChannelSchema as Ze, HandlerSchema as Xe, MarkerSchema as et, DocumentUpdateChannelSchema as tt, EmbeddedNodeChannelSchema as nt, LifecycleEventChannelSchema as rt, TriggeredEventChannelSchema as it, ChannelEventCheckpointSchema as st, ProcessingInitializedMarkerSchema as ot, ProcessEmbeddedSchema as at, ProcessingTerminatedMarkerSchema as ct, repository as lt } from "@blue-repository/core";
2
+ import { getQuickJS as ut } from "quickjs-emscripten";
3
+ import { BlueNode as d, blueNodeField as x, withTypeBlueId as dt, Blue as ht, MergingProcessors as v } from "@blue-labs/language";
4
+ import ue from "picomatch";
5
+ import { z as S, ZodError as Te } from "zod";
6
+ import { TimelineChannelSchema as ft, OperationSchema as $, SequentialWorkflowSchema as pt, SequentialWorkflowOperationSchema as mt, TimelineEntrySchema as P, blueIds as I, TriggerEventSchema as de, JavaScriptCodeSchema as he, UpdateDocumentSchema as fe, OperationRequestSchema as Z, repository as gt } from "@blue-repository/conversation";
7
+ import { MyOSTimelineChannelSchema as Et, blueIds as yt, MyOSTimelineEntrySchema as pe, repository as wt } from "@blue-repository/myos";
8
+ import { isNullable as X } from "@blue-labs/shared-utils";
9
+ function bt(s) {
10
+ return { ok: !0, value: s };
11
+ }
12
+ function St(s) {
13
+ return { ok: !1, error: s };
14
+ }
15
+ function Ur(s) {
16
+ return s.ok;
17
+ }
18
+ function Vr(s) {
19
+ return !s.ok;
20
+ }
21
+ function Hr(s, e) {
22
+ return s.ok ? bt(e(s.value)) : s;
23
+ }
24
+ function Kr(s, e) {
25
+ return s.ok ? s : St(e(s.error));
26
+ }
27
+ function Wr(s, e) {
28
+ return s.ok ? e(s.value) : s;
29
+ }
30
+ function Gr(s, e) {
31
+ return s.ok ? s.value : e;
32
+ }
33
+ function qr(s, e) {
34
+ return s.ok ? s.value : e(s.error);
35
+ }
36
+ function Jr(s, e) {
37
+ return s.ok ? e.ok(s.value) : e.err(s.error);
38
+ }
39
+ const g = {
40
+ capabilityFailure(s, e, t) {
41
+ return { kind: "CapabilityFailure", capability: s, reason: e, details: t };
42
+ },
43
+ boundaryViolation(s, e) {
44
+ return { kind: "BoundaryViolation", pointer: s, reason: e };
45
+ },
46
+ runtimeFatal(s, e) {
47
+ return { kind: "RuntimeFatal", reason: s, cause: e };
48
+ },
49
+ invalidContract(s, e, t, n) {
50
+ return { kind: "InvalidContract", contractId: s, reason: e, pointer: t, details: n };
51
+ },
52
+ illegalState(s) {
53
+ return { kind: "IllegalState", reason: s };
54
+ },
55
+ unsupported(s, e) {
56
+ return { kind: "UnsupportedOp", operation: s, reason: e };
57
+ }
58
+ };
59
+ function Ct(s) {
60
+ return Object.freeze([...s]);
61
+ }
62
+ const kt = {
63
+ of(s, e, t) {
64
+ return {
65
+ document: s,
66
+ triggeredEvents: Ct(e),
67
+ totalGas: t,
68
+ capabilityFailure: !1,
69
+ failureReason: null
70
+ };
71
+ },
72
+ capabilityFailure(s, e) {
73
+ return {
74
+ document: s,
75
+ triggeredEvents: Object.freeze([]),
76
+ totalGas: 0,
77
+ capabilityFailure: !0,
78
+ failureReason: e ?? null
79
+ };
80
+ }
81
+ }, Re = kt, It = [
82
+ "embedded",
83
+ "initialized",
84
+ "terminated",
85
+ "checkpoint"
86
+ ], vt = [
87
+ p["Document Update Channel"],
88
+ p["Triggered Event Channel"],
89
+ p["Lifecycle Event Channel"],
90
+ p["Embedded Node Channel"]
91
+ ], Pe = "embedded", Me = "initialized", Ne = "terminated", k = "checkpoint", re = new Set(
92
+ It
93
+ ), Ae = new Set(vt);
94
+ function Tt(s) {
95
+ return s != null && re.has(s);
96
+ }
97
+ function ie(s) {
98
+ return s != null && Ae.has(
99
+ s
100
+ );
101
+ }
102
+ const jr = {
103
+ KEY_EMBEDDED: Pe,
104
+ KEY_INITIALIZED: Me,
105
+ KEY_TERMINATED: Ne,
106
+ KEY_CHECKPOINT: k,
107
+ RESERVED_CONTRACT_KEYS: re,
108
+ PROCESSOR_MANAGED_CHANNEL_BLUE_IDS: Ae,
109
+ isReservedContractKey: Tt,
110
+ isProcessorManagedChannelBlueId: ie
111
+ }, A = "/contracts", ee = `${A}/${Me}`, De = `${A}/${Ne}`, Rt = `${A}/${Pe}`, Oe = `${A}/${k}`, Be = "/lastEvents", Le = "/lastSignatures";
112
+ function q(s) {
113
+ return `${A}/${s}`;
114
+ }
115
+ function _e(s, e) {
116
+ return `${q(s)}${Be}/${e}`;
117
+ }
118
+ function $e(s, e) {
119
+ return `${q(s)}${Le}/${e}`;
120
+ }
121
+ const Qr = {
122
+ RELATIVE_CONTRACTS: A,
123
+ RELATIVE_INITIALIZED: ee,
124
+ RELATIVE_TERMINATED: De,
125
+ RELATIVE_EMBEDDED: Rt,
126
+ RELATIVE_CHECKPOINT: Oe,
127
+ LAST_EVENTS_SUFFIX: Be,
128
+ LAST_SIGNATURES_SUFFIX: Le,
129
+ relativeContractsEntry: q,
130
+ relativeCheckpointLastEvent: _e,
131
+ relativeCheckpointLastSignature: $e
132
+ };
133
+ function xe(s) {
134
+ return s == null || s.length === 0;
135
+ }
136
+ function y(s) {
137
+ return xe(s) ? "/" : s.startsWith("/") ? s : `/${s}`;
138
+ }
139
+ function b(s) {
140
+ return xe(s) ? "/" : s.startsWith("/") ? s : `/${s}`;
141
+ }
142
+ function me(s) {
143
+ if (s == null)
144
+ return "";
145
+ let e = s.trim();
146
+ if (e.length === 0)
147
+ return "";
148
+ for (; e.startsWith("/"); )
149
+ e = e.substring(1);
150
+ for (; e.endsWith("/"); )
151
+ e = e.substring(0, e.length - 1);
152
+ return e;
153
+ }
154
+ function Yr(s, e) {
155
+ const t = me(s), n = me(e);
156
+ return t.length === 0 && n.length === 0 ? "/" : t.length === 0 ? `/${n}` : n.length === 0 ? `/${t}` : `/${t}/${n}`;
157
+ }
158
+ function w(s, e) {
159
+ const t = y(s), n = b(e);
160
+ return t === "/" ? n : n === "/" || n.length === 1 ? t : `${t}${n}`;
161
+ }
162
+ function Pt(s, e) {
163
+ const t = y(s), n = b(e);
164
+ if (t === "/" || !n.startsWith(t))
165
+ return n;
166
+ if (n.length === t.length)
167
+ return "/";
168
+ const r = n.substring(t.length);
169
+ return r.length === 0 ? "/" : r.startsWith("/") ? r : `/${r}`;
170
+ }
171
+ function Mt(s) {
172
+ return s && s.__esModule && Object.prototype.hasOwnProperty.call(s, "default") ? s.default : s;
173
+ }
174
+ var j, ge;
175
+ function Nt() {
176
+ return ge || (ge = 1, j = function s(e) {
177
+ if (typeof e == "number" && isNaN(e))
178
+ throw new Error("NaN is not allowed");
179
+ if (typeof e == "number" && !isFinite(e))
180
+ throw new Error("Infinity is not allowed");
181
+ return e === null || typeof e != "object" ? JSON.stringify(e) : e.toJSON instanceof Function ? s(e.toJSON()) : Array.isArray(e) ? `[${e.reduce((r, i, o) => `${r}${o === 0 ? "" : ","}${s(i === void 0 || typeof i == "symbol" ? null : i)}`, "")}]` : `{${Object.keys(e).sort().reduce((n, r) => {
182
+ if (e[r] === void 0 || typeof e[r] == "symbol")
183
+ return n;
184
+ const i = n.length === 0 ? "" : ",";
185
+ return `${n}${i}${s(r)}:${s(e[r])}`;
186
+ }, "")}}`;
187
+ }), j;
188
+ }
189
+ var At = Nt();
190
+ const Dt = /* @__PURE__ */ Mt(At);
191
+ function Ot(s, e) {
192
+ return s.nodeToJson(e, "official");
193
+ }
194
+ function Bt(s, e) {
195
+ const t = Ot(s, e);
196
+ return Dt(t);
197
+ }
198
+ function ze(s, e) {
199
+ return e ? Bt(s, e) : null;
200
+ }
201
+ function Ee(s, e) {
202
+ const t = ze(s, e);
203
+ return t == null ? 0 : new TextEncoder().encode(t).length;
204
+ }
205
+ const Lt = 500, _t = 32 * 1024 * 1024;
206
+ class se {
207
+ modulePromise;
208
+ moduleInstance;
209
+ async evaluate({
210
+ code: e,
211
+ bindings: t,
212
+ timeout: n = Lt,
213
+ memoryLimit: r = _t
214
+ }) {
215
+ const o = (await this.ensureModule()).newRuntime();
216
+ o.setMemoryLimit(r);
217
+ const a = Number.isFinite(n) ? Date.now() + Math.max(n, 0) : void 0;
218
+ a !== void 0 && o.setInterruptHandler(() => Date.now() > a);
219
+ const c = o.newContext();
220
+ try {
221
+ this.installConsole(c), this.installDeterministicGlobals(c), this.installBindings(c, t);
222
+ const l = this.wrapCode(e), u = c.evalCode(l), h = c.unwrapResult(u);
223
+ let f = null;
224
+ try {
225
+ return f = await this.resolveHandle(
226
+ c,
227
+ o,
228
+ h,
229
+ a
230
+ ), c.dump(f);
231
+ } finally {
232
+ f ? f.dispose() : h.dispose();
233
+ }
234
+ } finally {
235
+ c.dispose(), o.removeInterruptHandler?.(), o.dispose();
236
+ }
237
+ }
238
+ async ensureModule() {
239
+ return this.moduleInstance ? this.moduleInstance : (this.modulePromise || (this.modulePromise = ut().then((e) => (this.moduleInstance = e, e))), this.modulePromise);
240
+ }
241
+ wrapCode(e) {
242
+ return `(async () => {
243
+ ${e}
244
+ })()`;
245
+ }
246
+ installConsole(e) {
247
+ e.newObject().consume((t) => {
248
+ const n = ["log", "info", "warn", "error"];
249
+ for (const r of n) {
250
+ const i = console[r] ?? console.log;
251
+ e.newFunction(r, (...o) => {
252
+ const a = o.map((c) => e.dump(c));
253
+ return i.apply(console, a), e.undefined;
254
+ }).consume((o) => e.setProp(t, r, o));
255
+ }
256
+ e.setProp(e.global, "console", t);
257
+ });
258
+ }
259
+ installDeterministicGlobals(e) {
260
+ e.setProp(e.global, "Date", e.undefined.dup());
261
+ }
262
+ installBindings(e, t) {
263
+ if (t)
264
+ for (const [n, r] of Object.entries(t))
265
+ typeof r == "function" ? e.newFunction(
266
+ n,
267
+ (...o) => {
268
+ try {
269
+ const a = o.map((l) => e.dump(l)), c = r(...a);
270
+ if (c instanceof Promise)
271
+ throw new TypeError("Async bindings are not supported");
272
+ return this.createReturnHandle(e, c);
273
+ } catch (a) {
274
+ const c = a instanceof Error ? a.message : String(a);
275
+ return e.newError(c);
276
+ }
277
+ }
278
+ ).consume(
279
+ (o) => e.setProp(e.global, n, o)
280
+ ) : r !== void 0 && this.createOwnedHandle(e, r).consume(
281
+ (o) => e.setProp(e.global, n, o)
282
+ );
283
+ }
284
+ createOwnedHandle(e, t) {
285
+ if (t === void 0)
286
+ return e.undefined.dup();
287
+ if (t === null)
288
+ return e.null.dup();
289
+ if (typeof t == "boolean")
290
+ return (t ? e.true : e.false).dup();
291
+ if (typeof t == "number")
292
+ return e.newNumber(t);
293
+ if (typeof t == "string")
294
+ return e.newString(t);
295
+ if (typeof t == "bigint")
296
+ return e.newBigInt(t);
297
+ if (Array.isArray(t) || typeof t == "object") {
298
+ const n = JSON.stringify(t);
299
+ if (n === void 0)
300
+ return e.undefined.dup();
301
+ const r = e.evalCode(`(${n})`);
302
+ return e.unwrapResult(r);
303
+ }
304
+ throw new TypeError(
305
+ `Unsupported binding value type: ${typeof t}`
306
+ );
307
+ }
308
+ createReturnHandle(e, t) {
309
+ if (t === void 0)
310
+ return e.undefined;
311
+ if (t === null)
312
+ return e.null;
313
+ if (typeof t == "boolean")
314
+ return t ? e.true : e.false;
315
+ if (typeof t == "number")
316
+ return e.newNumber(t);
317
+ if (typeof t == "string")
318
+ return e.newString(t);
319
+ if (typeof t == "bigint")
320
+ return e.newBigInt(t);
321
+ if (Array.isArray(t) || typeof t == "object") {
322
+ const n = JSON.stringify(t);
323
+ if (n === void 0)
324
+ return e.undefined;
325
+ const r = e.evalCode(`(${n})`);
326
+ return e.unwrapResult(r);
327
+ }
328
+ throw new TypeError(
329
+ `Unsupported binding return type: ${typeof t}`
330
+ );
331
+ }
332
+ async resolveHandle(e, t, n, r) {
333
+ let i = n;
334
+ for (; ; ) {
335
+ const o = e.getPromiseState(i);
336
+ if (o.type === "pending") {
337
+ if (r !== void 0 && Date.now() > r)
338
+ throw i.dispose(), new Error("QuickJS execution timed out while awaiting Promise");
339
+ const a = t.executePendingJobs();
340
+ let c = 0;
341
+ try {
342
+ c = e.unwrapResult(a);
343
+ } finally {
344
+ a.dispose();
345
+ }
346
+ if (c === 0) {
347
+ if (r !== void 0 && Date.now() > r)
348
+ throw i.dispose(), new Error(
349
+ "QuickJS execution timed out while awaiting Promise"
350
+ );
351
+ await new Promise((l) => setTimeout(l, 0));
352
+ }
353
+ continue;
354
+ }
355
+ if (o.type === "fulfilled") {
356
+ if (o.notAPromise)
357
+ return i;
358
+ i.dispose(), i = o.value;
359
+ continue;
360
+ }
361
+ if (o.type === "rejected")
362
+ try {
363
+ const a = e.dump(o.error);
364
+ throw a instanceof Error ? a : a && typeof a == "object" && "message" in a ? new Error(
365
+ String(a.message)
366
+ ) : new Error(
367
+ typeof a == "string" ? a : JSON.stringify(a)
368
+ );
369
+ } finally {
370
+ o.error.dispose(), i.dispose();
371
+ }
372
+ }
373
+ }
374
+ }
375
+ const ye = 120;
376
+ function $t(s) {
377
+ return s.length <= ye ? s : `${s.slice(0, ye - 3)}...`;
378
+ }
379
+ class Fe extends Error {
380
+ constructor(e, t) {
381
+ super(`Failed to evaluate code block: ${$t(e)}`, { cause: t }), this.code = e, this.cause = t, this.name = "CodeBlockEvaluationError";
382
+ }
383
+ }
384
+ const Ue = /^\$\{([\s\S]*)\}$/, xt = /\$\{([\s\S]+?)\}/, Ve = /\$\{([\s\S]+?)\}/g;
385
+ function H(s) {
386
+ if (typeof s != "string" || !Ue.test(s))
387
+ return !1;
388
+ const e = s.indexOf("${"), t = s.lastIndexOf("${");
389
+ return e === t;
390
+ }
391
+ function zt(s) {
392
+ return typeof s != "string" ? !1 : Ue.test(s) ? !0 : xt.test(s);
393
+ }
394
+ function Ft(s) {
395
+ if (!H(s))
396
+ throw new Error(`Invalid expression: ${s}`);
397
+ return s.slice(2, -1);
398
+ }
399
+ async function He(s, e, t) {
400
+ const n = `return await (${e});`;
401
+ try {
402
+ return await s.evaluate({ code: n, bindings: t });
403
+ } catch (r) {
404
+ throw new Fe(e, r);
405
+ }
406
+ }
407
+ async function Ut(s, e, t) {
408
+ let n = "", r = 0;
409
+ for (const i of e.matchAll(Ve)) {
410
+ const o = i[0], a = i[1], c = i.index ?? 0;
411
+ n += e.slice(r, c);
412
+ const l = await He(
413
+ s,
414
+ a,
415
+ t
416
+ );
417
+ n += l == null ? "" : String(l), r = c + o.length;
418
+ }
419
+ return n += e.slice(r), n;
420
+ }
421
+ function Ke({
422
+ include: s,
423
+ exclude: e = [],
424
+ options: t
425
+ }) {
426
+ const n = { dot: !0, ...t ?? {} }, r = s.map(
427
+ (o) => ue(o, n)
428
+ ), i = e.map(
429
+ (o) => ue(o, n)
430
+ );
431
+ return (o) => r.some((a) => a(o)) && !i.some((a) => a(o));
432
+ }
433
+ async function K(s) {
434
+ const {
435
+ evaluator: e,
436
+ node: t,
437
+ bindings: n,
438
+ shouldResolve: r,
439
+ context: i,
440
+ pointer: o = "/"
441
+ } = s, a = t.clone(), c = a.getValue();
442
+ if (c !== void 0) {
443
+ if (typeof c == "string" && r(o)) {
444
+ if (H(c)) {
445
+ const h = Ft(c);
446
+ i.gasMeter().chargeExpression(h);
447
+ const f = await He(
448
+ e,
449
+ h,
450
+ n
451
+ );
452
+ return i.blue.jsonValueToNode(f ?? null);
453
+ } else if (zt(c)) {
454
+ const h = new RegExp(Ve);
455
+ let f = 0;
456
+ for (h.lastIndex = 0; h.exec(c); )
457
+ f += 1;
458
+ i.gasMeter().chargeTemplate(f, c);
459
+ const E = await Ut(
460
+ e,
461
+ c,
462
+ n
463
+ );
464
+ return new d().setValue(E);
465
+ }
466
+ }
467
+ return a;
468
+ }
469
+ const l = a.getItems?.();
470
+ if (Array.isArray(l)) {
471
+ const h = await Promise.all(
472
+ l.map(
473
+ (f, E) => K({
474
+ ...s,
475
+ node: f,
476
+ pointer: `${o}/${E}`
477
+ })
478
+ )
479
+ );
480
+ return a.setItems(h), a;
481
+ }
482
+ const u = a.getProperties?.();
483
+ if (u) {
484
+ const h = {};
485
+ for (const [f, E] of Object.entries(u)) {
486
+ const O = o === "/" ? `/${f}` : `${o}/${f}`;
487
+ h[f] = await K({
488
+ ...s,
489
+ node: E,
490
+ pointer: O
491
+ });
492
+ }
493
+ a.setProperties(h);
494
+ }
495
+ return a;
496
+ }
497
+ const oe = Ye, D = Ze.merge(
498
+ oe
499
+ ).extend({
500
+ path: S.string().optional(),
501
+ definition: x().optional()
502
+ }), We = Xe.merge(oe), z = et.merge(oe), Vt = S.object({
503
+ op: S.enum(["ADD", "REPLACE", "REMOVE"]),
504
+ path: S.string(),
505
+ val: x().optional()
506
+ }), Zr = dt("JsonPatch")(
507
+ Vt
508
+ ).superRefine((s, e) => {
509
+ s.op === "REMOVE" && s.val !== void 0 && e.addIssue({
510
+ code: S.ZodIssueCode.custom,
511
+ message: "REMOVE operations cannot include a value",
512
+ path: ["val"]
513
+ }), s.op !== "REMOVE" && s.val === void 0 && e.addIssue({
514
+ code: S.ZodIssueCode.custom,
515
+ message: `${s.op} operations must include a value`,
516
+ path: ["val"]
517
+ });
518
+ }), Ht = tt.merge(
519
+ D
520
+ ), Kt = nt.merge(
521
+ D
522
+ ), Wt = rt.merge(
523
+ D
524
+ ), Gt = it.merge(D), qt = ft.merge(
525
+ D
526
+ ), Jt = Et.merge(D), jt = st.merge(z).extend({
527
+ lastSignatures: S.record(S.string()).optional()
528
+ }), Qt = ot.merge(z), Yt = at.merge(
529
+ z
530
+ ), Zt = ct.merge(z), Xt = $.merge(
531
+ z
532
+ ), Xr = x(), en = pt.merge(We).extend({
533
+ steps: S.array(x()).optional()
534
+ }), tn = mt.merge(
535
+ We
536
+ ).extend({
537
+ steps: S.array(x()).optional()
538
+ });
539
+ function nn(s) {
540
+ if (!Array.isArray(s.blueIds) || s.blueIds.length === 0)
541
+ throw new Error("Contract processors must declare at least one BlueId");
542
+ for (const e of s.blueIds)
543
+ if (typeof e != "string" || e.trim().length === 0)
544
+ throw new Error("Contract processor BlueIds must be non-empty strings");
545
+ }
546
+ function U(s, e) {
547
+ nn(s);
548
+ for (const t of s.blueIds)
549
+ e.set(t, s);
550
+ }
551
+ class rn {
552
+ processorsByBlueId = /* @__PURE__ */ new Map();
553
+ handlerProcessors = /* @__PURE__ */ new Map();
554
+ channelProcessors = /* @__PURE__ */ new Map();
555
+ markerProcessors = /* @__PURE__ */ new Map();
556
+ registerHandler(e) {
557
+ U(e, this.handlerProcessors), this.registerProcessorMap(e);
558
+ }
559
+ registerChannel(e) {
560
+ U(e, this.channelProcessors), this.registerProcessorMap(e);
561
+ }
562
+ registerMarker(e) {
563
+ U(e, this.markerProcessors), this.registerProcessorMap(e);
564
+ }
565
+ register(e) {
566
+ switch (e.kind) {
567
+ case "handler":
568
+ this.registerHandler(e);
569
+ break;
570
+ case "channel":
571
+ this.registerChannel(e);
572
+ break;
573
+ case "marker":
574
+ this.registerMarker(e);
575
+ break;
576
+ default:
577
+ throw new Error(
578
+ `Unsupported processor kind: ${String(
579
+ e.kind
580
+ )}`
581
+ );
582
+ }
583
+ }
584
+ lookupHandler(e) {
585
+ return this.handlerProcessors.get(e);
586
+ }
587
+ lookupChannel(e) {
588
+ return this.channelProcessors.get(e);
589
+ }
590
+ lookupMarker(e) {
591
+ return this.markerProcessors.get(e);
592
+ }
593
+ processors() {
594
+ return new Map(this.processorsByBlueId);
595
+ }
596
+ registerProcessorMap(e) {
597
+ U(e, this.processorsByBlueId);
598
+ }
599
+ }
600
+ function we(s, e) {
601
+ return s.isTypeOf(e, pe) ? s.nodeToSchemaOutput(e, pe) : s.isTypeOf(e, P) ? s.nodeToSchemaOutput(e, P) : null;
602
+ }
603
+ class sn {
604
+ kind = "channel";
605
+ blueIds = [yt["MyOS Timeline Channel"]];
606
+ schema = Jt;
607
+ matches(e, t) {
608
+ const { event: n, blue: r } = t;
609
+ if (!n)
610
+ return !1;
611
+ const i = we(r, n);
612
+ if (!i)
613
+ return !1;
614
+ const o = i.timeline?.timelineId;
615
+ return !o || !e.timelineId ? !1 : o === e.timelineId;
616
+ }
617
+ channelize(e, t) {
618
+ const { event: n, blue: r } = t;
619
+ if (!n)
620
+ return null;
621
+ const i = we(r, n);
622
+ if (!i)
623
+ return null;
624
+ const o = i.message;
625
+ return o ? o.clone() : null;
626
+ }
627
+ }
628
+ class on {
629
+ kind = "channel";
630
+ blueIds = [I["Timeline Channel"]];
631
+ schema = qt;
632
+ matches(e, t) {
633
+ const { event: n, blue: r } = t;
634
+ if (!n || !r.isTypeOf(n, P))
635
+ return !1;
636
+ const o = r.nodeToSchemaOutput(n, P).timeline?.timelineId;
637
+ return !(!o || !e.timelineId || o !== e.timelineId);
638
+ }
639
+ channelize(e, t) {
640
+ const { event: n, blue: r } = t;
641
+ if (!n || !r.isTypeOf(n, P))
642
+ return null;
643
+ const o = r.nodeToSchemaOutput(n, P).message;
644
+ return o ? o.clone() : null;
645
+ }
646
+ }
647
+ function ae(s) {
648
+ const { context: e, eventNode: t, stepResults: n } = s;
649
+ return {
650
+ event: e.blue.nodeToJson(t, "original"),
651
+ steps: n,
652
+ document: (r) => {
653
+ const i = r == null ? "/" : typeof r == "string" ? r : (() => {
654
+ throw new TypeError("document() expects a string pointer");
655
+ })(), o = i.startsWith("/") ? i : e.resolvePointer(i), a = b(o), c = e.documentAt(a);
656
+ if (e.gasMeter().chargeDocumentSnapshot(a, c), !!c)
657
+ return e.blue.nodeToJson(c, "original");
658
+ }
659
+ };
660
+ }
661
+ class an {
662
+ supportedBlueIds = [I["Trigger Event"]];
663
+ evaluator = new se();
664
+ async execute(e) {
665
+ const { stepNode: t, context: n } = e;
666
+ if (!n.blue.isTypeOf(t, de))
667
+ return n.throwFatal("Trigger Event step payload is invalid");
668
+ n.gasMeter().chargeTriggerEventBase();
669
+ const r = await K({
670
+ evaluator: this.evaluator,
671
+ node: t,
672
+ bindings: ae(e),
673
+ shouldResolve: Ke({
674
+ include: ["/event", "/event/**"]
675
+ }),
676
+ context: n
677
+ }), o = n.blue.nodeToSchemaOutput(
678
+ r,
679
+ de
680
+ ).event;
681
+ if (X(o))
682
+ return n.throwFatal(
683
+ "Trigger Event step must declare event payload"
684
+ );
685
+ n.emitEvent(o.clone());
686
+ }
687
+ }
688
+ class cn {
689
+ supportedBlueIds = [I["JavaScript Code"]];
690
+ evaluator = new se();
691
+ async execute(e) {
692
+ const { context: t, stepNode: n } = e, { blue: r } = t;
693
+ if (!r.isTypeOf(n, he))
694
+ return t.throwFatal("JavaScript Code step payload is invalid");
695
+ const o = r.nodeToSchemaOutput(
696
+ n,
697
+ he
698
+ ).code;
699
+ if (!o)
700
+ return t.throwFatal(
701
+ "JavaScript Code step must include code to execute"
702
+ );
703
+ t.gasMeter().chargeJavaScriptCodeBase(o);
704
+ const a = ae(e);
705
+ try {
706
+ const c = await this.evaluator.evaluate({
707
+ code: o,
708
+ bindings: a
709
+ });
710
+ return this.handleEvents(c, t), c;
711
+ } catch (c) {
712
+ throw new Fe(o, c);
713
+ }
714
+ }
715
+ handleEvents(e, t) {
716
+ if (!e || typeof e != "object")
717
+ return;
718
+ const n = e;
719
+ if (Array.isArray(n.events))
720
+ for (const r of n.events) {
721
+ const i = t.blue.jsonValueToNode(r);
722
+ t.emitEvent(i);
723
+ }
724
+ }
725
+ }
726
+ class ln {
727
+ supportedBlueIds = [I["Update Document"]];
728
+ evaluator = new se();
729
+ async execute(e) {
730
+ const { context: t, stepNode: n } = e, { blue: r } = t;
731
+ if (!r.isTypeOf(n, fe))
732
+ return t.throwFatal("Update Document step payload is invalid");
733
+ const i = await K({
734
+ evaluator: this.evaluator,
735
+ node: n,
736
+ bindings: ae(e),
737
+ shouldResolve: Ke({
738
+ include: ["/changeset", "/changeset/**"]
739
+ }),
740
+ context: t
741
+ }), o = this.extractChanges(i, t);
742
+ t.gasMeter().chargeUpdateDocumentBase(o.length);
743
+ for (const a of o) {
744
+ const c = this.createPatch(a, t);
745
+ await t.applyPatch(c);
746
+ }
747
+ }
748
+ extractChanges(e, t) {
749
+ return t.blue.nodeToSchemaOutput(
750
+ e,
751
+ fe
752
+ ).changeset ?? [];
753
+ }
754
+ createPatch(e, t) {
755
+ const n = this.normalizeOperation(e.op, t), r = this.normalizePath(e.path, t), i = t.resolvePointer(r);
756
+ return n === "REMOVE" ? { op: n, path: i } : { op: n, path: i, val: e.val };
757
+ }
758
+ normalizeOperation(e, t) {
759
+ const n = typeof e == "string" ? e : void 0, r = (n ?? "REPLACE").toUpperCase();
760
+ return r === "ADD" || r === "REPLACE" || r === "REMOVE" ? r : t.throwFatal(
761
+ `Unsupported Update Document operation "${n}"`
762
+ );
763
+ }
764
+ normalizePath(e, t) {
765
+ if (typeof e != "string")
766
+ return t.throwFatal("Update Document changeset requires a path");
767
+ const n = e.trim();
768
+ return n.length === 0 ? t.throwFatal("Update Document path cannot be empty") : n;
769
+ }
770
+ }
771
+ const ce = [
772
+ new an(),
773
+ new cn(),
774
+ new ln()
775
+ ];
776
+ class Ge {
777
+ executorIndex;
778
+ constructor(e = ce) {
779
+ const t = /* @__PURE__ */ new Map();
780
+ for (const n of e)
781
+ for (const r of n.supportedBlueIds)
782
+ t.set(r, n);
783
+ this.executorIndex = t;
784
+ }
785
+ async run(e) {
786
+ const { workflow: t, eventNode: n, context: r } = e, i = t.steps ?? [];
787
+ if (i.length === 0)
788
+ return {};
789
+ const o = {};
790
+ for (const [a, c] of i.entries()) {
791
+ const l = c.getType?.()?.getBlueId();
792
+ if (X(l))
793
+ return r.throwFatal(
794
+ "Sequential workflow step is missing type metadata"
795
+ );
796
+ const u = this.executorIndex.get(l);
797
+ if (X(u)) {
798
+ const E = c.getType?.()?.getName?.() ?? l;
799
+ return r.throwFatal(
800
+ `Unsupported workflow step type "${E}"`
801
+ );
802
+ }
803
+ const h = {
804
+ workflow: t,
805
+ stepNode: c,
806
+ eventNode: n,
807
+ context: r,
808
+ stepResults: o,
809
+ stepIndex: a
810
+ }, f = await u.execute(h);
811
+ if (f !== void 0) {
812
+ const E = this.stepResultKey(c, a);
813
+ o[E] = f;
814
+ }
815
+ }
816
+ return o;
817
+ }
818
+ stepResultKey(e, t) {
819
+ const n = e.getName?.();
820
+ return n && typeof n == "string" && n.length > 0 ? n : `Step${t + 1}`;
821
+ }
822
+ }
823
+ class un {
824
+ kind = "handler";
825
+ blueIds = [I["Sequential Workflow"]];
826
+ schema = en;
827
+ runner;
828
+ constructor(e = ce) {
829
+ this.runner = new Ge(e);
830
+ }
831
+ async matches(e, t) {
832
+ const n = t.event();
833
+ return !(!n || e.event && !t.blue.isTypeOfNode(n, e.event));
834
+ }
835
+ async execute(e, t) {
836
+ const n = t.event();
837
+ n && await this.runner.run({ workflow: e, eventNode: n, context: t });
838
+ }
839
+ }
840
+ class dn {
841
+ kind = "marker";
842
+ blueIds = [I.Operation];
843
+ schema = Xt;
844
+ }
845
+ function qe(s) {
846
+ const e = s.channel;
847
+ if (typeof e == "string") {
848
+ const t = e.trim();
849
+ if (t.length > 0)
850
+ return t;
851
+ }
852
+ return null;
853
+ }
854
+ function hn(s, e) {
855
+ const t = s.getProperties()?.document;
856
+ return t instanceof d ? e.blue.calculateBlueIdSync(t) : null;
857
+ }
858
+ function fn(s, e, t) {
859
+ const { blue: n } = t;
860
+ if (!n.isTypeOf(e, Z, {
861
+ checkSchemaExtensions: !0
862
+ }))
863
+ return !1;
864
+ const r = n.nodeToSchemaOutput(e, Z), i = s.operation;
865
+ return !(!i || r.operation !== i || s.event && !n.isTypeOfNode(e, s.event));
866
+ }
867
+ function pn(s, e) {
868
+ const t = s.operation;
869
+ if (!t)
870
+ return null;
871
+ const n = e.resolvePointer(`/contracts/${t}`), r = e.documentAt(n);
872
+ if (!r || !e.blue.isTypeOf(r, $))
873
+ return null;
874
+ const i = e.blue.nodeToSchemaOutput(
875
+ r,
876
+ $
877
+ ), o = qe(i);
878
+ return { operationNode: r, operation: i, channelKey: o };
879
+ }
880
+ function mn(s, e) {
881
+ return !(s && e && s !== e);
882
+ }
883
+ function gn(s, e, t) {
884
+ const n = s.getProperties()?.request, r = e.getProperties()?.request;
885
+ if (!(n instanceof d) || !(r instanceof d))
886
+ return !1;
887
+ try {
888
+ if (!t.isTypeOfNode(n, r))
889
+ return !1;
890
+ } catch {
891
+ return !1;
892
+ }
893
+ return !0;
894
+ }
895
+ function En(s, e, t) {
896
+ if (!s || s.allowNewerVersion !== !1)
897
+ return !0;
898
+ const n = hn(e, t);
899
+ if (!n)
900
+ return !0;
901
+ const r = t.resolvePointer("/"), i = t.documentAt(r);
902
+ if (!i)
903
+ return !1;
904
+ const c = (i.getContracts()?.initialized ?? null)?.get("/documentId") ?? null, l = typeof c == "string" && c.length > 0 ? c : t.blue.calculateBlueIdSync(i);
905
+ return n === l;
906
+ }
907
+ class yn {
908
+ kind = "handler";
909
+ blueIds = [
910
+ I["Sequential Workflow Operation"]
911
+ ];
912
+ schema = tn;
913
+ runner;
914
+ constructor(e = ce) {
915
+ this.runner = new Ge(e);
916
+ }
917
+ deriveChannel(e, t) {
918
+ const n = e.operation;
919
+ if (!n)
920
+ return null;
921
+ const r = t.scopeContracts.get(n);
922
+ if (!r || !t.blue.isTypeOf(r.node, $, {
923
+ checkSchemaExtensions: !0
924
+ }))
925
+ return null;
926
+ const i = t.blue.nodeToSchemaOutput(r.node, $);
927
+ return i ? qe(i) : null;
928
+ }
929
+ async matches(e, t) {
930
+ const n = t.event();
931
+ if (!n || !fn(e, n, t))
932
+ return !1;
933
+ const r = pn(e, t);
934
+ if (!r)
935
+ return !1;
936
+ const i = typeof e.channel == "string" ? e.channel.trim() : "", o = i.length > 0 ? i : null;
937
+ if (!mn(r.channelKey, o) || !gn(
938
+ n,
939
+ r.operationNode,
940
+ t.blue
941
+ ))
942
+ return !1;
943
+ const a = t.blue.nodeToSchemaOutput(
944
+ n,
945
+ Z
946
+ );
947
+ return !(a?.allowNewerVersion === !1 && !En(a, n, t));
948
+ }
949
+ async execute(e, t) {
950
+ const n = t.event();
951
+ n && await this.runner.run({
952
+ workflow: e,
953
+ eventNode: n,
954
+ context: t
955
+ });
956
+ }
957
+ }
958
+ class J {
959
+ constructor(e) {
960
+ this.registry = e;
961
+ }
962
+ static create() {
963
+ return new J(
964
+ new rn()
965
+ );
966
+ }
967
+ registerDefaults() {
968
+ return this.registry.register(new sn()), this.registry.register(new on()), this.registry.register(new un()), this.registry.register(new dn()), this.registry.register(new yn()), this;
969
+ }
970
+ register(e) {
971
+ return this.registry.register(e), this;
972
+ }
973
+ build() {
974
+ return this.registry;
975
+ }
976
+ }
977
+ const te = p["Channel Event Checkpoint"];
978
+ function Je(s) {
979
+ return typeof s.order == "number" ? s.order : 0;
980
+ }
981
+ class wn {
982
+ constructor(e, t, n) {
983
+ this.bindingKey = e, this.bindingContract = t, this.bindingBlueId = n;
984
+ }
985
+ key() {
986
+ return this.bindingKey;
987
+ }
988
+ contract() {
989
+ return this.bindingContract;
990
+ }
991
+ blueId() {
992
+ return this.bindingBlueId;
993
+ }
994
+ order() {
995
+ return Je(this.bindingContract);
996
+ }
997
+ }
998
+ class bn {
999
+ constructor(e, t, n) {
1000
+ this.bindingKey = e, this.bindingContract = t, this.bindingBlueId = n;
1001
+ }
1002
+ key() {
1003
+ return this.bindingKey;
1004
+ }
1005
+ contract() {
1006
+ return this.bindingContract;
1007
+ }
1008
+ blueId() {
1009
+ return this.bindingBlueId;
1010
+ }
1011
+ order() {
1012
+ return Je(this.bindingContract);
1013
+ }
1014
+ }
1015
+ class N {
1016
+ constructor(e, t, n, r, i) {
1017
+ this.channels = e, this.handlersByChannel = t, this.markerStore = n, this.embeddedPathsInternal = r, this.checkpointDeclared = i;
1018
+ }
1019
+ checkpointDeclared;
1020
+ static fromComponents(e, t, n, r, i) {
1021
+ return new N(
1022
+ e,
1023
+ t,
1024
+ n,
1025
+ r,
1026
+ i
1027
+ );
1028
+ }
1029
+ static builder() {
1030
+ return new Sn();
1031
+ }
1032
+ static empty() {
1033
+ return N.builder().build();
1034
+ }
1035
+ markers() {
1036
+ return new Map(
1037
+ Array.from(this.markerStore.entries(), ([e, t]) => [
1038
+ e,
1039
+ t.contract
1040
+ ])
1041
+ );
1042
+ }
1043
+ marker(e) {
1044
+ return this.markerStore.get(e)?.contract;
1045
+ }
1046
+ markerEntries() {
1047
+ return Array.from(this.markerStore.entries(), ([e, t]) => [
1048
+ e,
1049
+ t.contract
1050
+ ]);
1051
+ }
1052
+ embeddedPaths() {
1053
+ return this.embeddedPathsInternal;
1054
+ }
1055
+ hasCheckpoint() {
1056
+ return this.checkpointDeclared;
1057
+ }
1058
+ registerCheckpointMarker(e) {
1059
+ if (this.checkpointDeclared)
1060
+ throw new Error(
1061
+ "Duplicate Channel Event Checkpoint markers detected in same contracts map"
1062
+ );
1063
+ this.markerStore.set(k, {
1064
+ key: k,
1065
+ contract: e,
1066
+ blueId: te
1067
+ }), this.checkpointDeclared = !0;
1068
+ }
1069
+ handlersFor(e) {
1070
+ const t = this.handlersByChannel.get(e);
1071
+ return !t || t.length === 0 ? [] : [...t].map(
1072
+ (n) => new bn(n.key, n.contract, n.blueId)
1073
+ ).sort((n, r) => {
1074
+ const i = n.order() - r.order();
1075
+ return i !== 0 ? i : n.key().localeCompare(r.key());
1076
+ });
1077
+ }
1078
+ channelsOfType(...e) {
1079
+ const t = e.length > 0 ? new Set(e) : null, n = Array.from(this.channels.values()).filter((r) => !t || t.has(r.blueId)).map(
1080
+ (r) => new wn(r.key, r.contract, r.blueId)
1081
+ );
1082
+ return n.sort((r, i) => {
1083
+ const o = r.order() - i.order();
1084
+ return o !== 0 ? o : r.key().localeCompare(i.key());
1085
+ }), n;
1086
+ }
1087
+ }
1088
+ class Sn {
1089
+ channels = /* @__PURE__ */ new Map();
1090
+ handlersByChannel = /* @__PURE__ */ new Map();
1091
+ markerStore = /* @__PURE__ */ new Map();
1092
+ embeddedPaths = [];
1093
+ embeddedDeclared = !1;
1094
+ checkpointDeclared = !1;
1095
+ addChannel(e, t, n) {
1096
+ return this.channels.set(e, { key: e, contract: t, blueId: n }), this;
1097
+ }
1098
+ addHandler(e, t, n) {
1099
+ const r = t.channel;
1100
+ if (!r)
1101
+ throw new Error(`Handler ${e} must declare channel`);
1102
+ const i = this.handlersByChannel.get(r) ?? [];
1103
+ return i.push({ key: e, contract: t, blueId: n }), this.handlersByChannel.set(r, i), this;
1104
+ }
1105
+ setEmbedded(e) {
1106
+ if (this.embeddedDeclared)
1107
+ throw new Error(
1108
+ "Multiple Process Embedded markers detected in same contracts map"
1109
+ );
1110
+ return this.embeddedDeclared = !0, this.embeddedPaths = e.paths ? [...e.paths] : [], this;
1111
+ }
1112
+ addMarker(e, t, n) {
1113
+ if (e === k && n !== te)
1114
+ throw new Error(
1115
+ "Reserved key 'checkpoint' must contain a Channel Event Checkpoint"
1116
+ );
1117
+ if (n === te) {
1118
+ if (e !== k)
1119
+ throw new Error(
1120
+ `Channel Event Checkpoint must use reserved key 'checkpoint' at key '${e}'`
1121
+ );
1122
+ if (this.checkpointDeclared)
1123
+ throw new Error(
1124
+ "Duplicate Channel Event Checkpoint markers detected in same contracts map"
1125
+ );
1126
+ this.checkpointDeclared = !0;
1127
+ }
1128
+ return this.markerStore.set(e, { key: e, contract: t, blueId: n }), this;
1129
+ }
1130
+ build() {
1131
+ return N.fromComponents(
1132
+ new Map(this.channels),
1133
+ new Map(
1134
+ Array.from(this.handlersByChannel.entries(), ([e, t]) => [
1135
+ e,
1136
+ [...t]
1137
+ ])
1138
+ ),
1139
+ new Map(this.markerStore),
1140
+ [...this.embeddedPaths],
1141
+ this.checkpointDeclared
1142
+ );
1143
+ }
1144
+ }
1145
+ class m extends Error {
1146
+ constructor(e, t) {
1147
+ super(e || "Processor fatal error"), this.processorError = t, this.name = "ProcessorFatalError";
1148
+ }
1149
+ }
1150
+ class Cn {
1151
+ constructor(e, t, n) {
1152
+ this.blue = e, this.registry = t, this.builtinChannelSchemas = n;
1153
+ }
1154
+ register({
1155
+ builder: e,
1156
+ key: t,
1157
+ node: n,
1158
+ processor: r,
1159
+ blueId: i,
1160
+ scopeContracts: o
1161
+ }) {
1162
+ try {
1163
+ const a = r.schema, c = this.blue.nodeToSchemaOutput(
1164
+ n,
1165
+ a
1166
+ ), l = this.resolveChannelKey({
1167
+ contract: c,
1168
+ processor: r,
1169
+ scopeContracts: o,
1170
+ handlerKey: t
1171
+ }), u = o.get(l);
1172
+ if (!u)
1173
+ throw new m(
1174
+ `Handler ${t} references unknown channel '${l}'`,
1175
+ g.invalidContract(
1176
+ i,
1177
+ `Channel '${l}' is not declared in this scope`,
1178
+ `/contracts/${l}`
1179
+ )
1180
+ );
1181
+ if (!this.isRegisteredChannel(u.nodeTypeBlueId))
1182
+ throw new m(
1183
+ `Contract '${l}' is not a channel`,
1184
+ g.invalidContract(
1185
+ u.nodeTypeBlueId,
1186
+ `Contract '${l}' is not a channel`,
1187
+ `/contracts/${l}`
1188
+ )
1189
+ );
1190
+ e.addHandler(t, { ...c, channel: l }, i);
1191
+ } catch (a) {
1192
+ if (this.isZodError(a))
1193
+ throw new m(
1194
+ "Failed to parse handler contract",
1195
+ g.invalidContract(
1196
+ i,
1197
+ "Failed to parse handler contract",
1198
+ t,
1199
+ a
1200
+ )
1201
+ );
1202
+ const c = a?.message ?? "Failed to register handler contract";
1203
+ throw new m(
1204
+ c,
1205
+ g.illegalState(c)
1206
+ );
1207
+ }
1208
+ }
1209
+ resolveChannelKey({
1210
+ contract: e,
1211
+ processor: t,
1212
+ scopeContracts: n,
1213
+ handlerKey: r
1214
+ }) {
1215
+ let i = typeof e.channel == "string" ? e.channel.trim() : null;
1216
+ if (i && i.length === 0 && (i = null), !i) {
1217
+ const o = t.deriveChannel?.call(t, e, {
1218
+ blue: this.blue,
1219
+ scopeContracts: n
1220
+ }) ?? null;
1221
+ if (typeof o == "string") {
1222
+ const a = o.trim();
1223
+ a.length > 0 && (i = a);
1224
+ }
1225
+ }
1226
+ if (!i)
1227
+ throw new m(
1228
+ `Handler ${r} must declare channel (missing explicit channel and derivation failed)`,
1229
+ g.illegalState(
1230
+ `Handler ${r} must declare channel (missing explicit channel and derivation failed)`
1231
+ )
1232
+ );
1233
+ return i;
1234
+ }
1235
+ isRegisteredChannel(e) {
1236
+ return this.builtinChannelSchemas.has(e) ? !0 : this.registry.lookupChannel(e) != null;
1237
+ }
1238
+ isZodError(e) {
1239
+ return e instanceof Te;
1240
+ }
1241
+ }
1242
+ class W extends Error {
1243
+ constructor(e) {
1244
+ super(e ?? "MustUnderstand failure"), this.name = "MustUnderstandFailure";
1245
+ }
1246
+ }
1247
+ const kn = p["Document Update Channel"], In = p["Embedded Node Channel"], vn = p["Lifecycle Event Channel"], Tn = p["Triggered Event Channel"], be = p["Process Embedded"], Rn = p["Processing Initialized Marker"], Pn = p["Processing Terminated Marker"], Mn = p["Channel Event Checkpoint"], Se = /* @__PURE__ */ new Map([
1248
+ [
1249
+ kn,
1250
+ Ht
1251
+ ],
1252
+ [
1253
+ In,
1254
+ Kt
1255
+ ],
1256
+ [
1257
+ vn,
1258
+ Wt
1259
+ ],
1260
+ [
1261
+ Tn,
1262
+ Gt
1263
+ ]
1264
+ ]), Nn = /* @__PURE__ */ new Map([
1265
+ [
1266
+ Rn,
1267
+ Qt
1268
+ ],
1269
+ [
1270
+ Pn,
1271
+ Zt
1272
+ ],
1273
+ [
1274
+ Mn,
1275
+ jt
1276
+ ]
1277
+ ]);
1278
+ class An {
1279
+ constructor(e, t) {
1280
+ this.registry = e, this.blue = t, this.handlerRegistration = new Cn(
1281
+ this.blue,
1282
+ this.registry,
1283
+ Se
1284
+ );
1285
+ }
1286
+ handlerRegistration;
1287
+ load(e, t) {
1288
+ try {
1289
+ const n = N.builder(), r = e.getContracts();
1290
+ if (!r)
1291
+ return n.build();
1292
+ const i = this.buildScopeContractsIndex(r);
1293
+ for (const [o, a] of Object.entries(r))
1294
+ a && this.processContract(n, o, a, i);
1295
+ return n.build();
1296
+ } catch (n) {
1297
+ if (n instanceof W || n instanceof m)
1298
+ throw n;
1299
+ const r = n?.message ?? "Failed to load contracts";
1300
+ throw new m(
1301
+ `Failed to load contracts for scope ${t}: ${r}`,
1302
+ g.runtimeFatal(
1303
+ `Failed to load contracts for scope ${t}`,
1304
+ n
1305
+ )
1306
+ );
1307
+ }
1308
+ }
1309
+ processContract(e, t, n, r) {
1310
+ const i = n.getType()?.getBlueId();
1311
+ if (!i)
1312
+ return;
1313
+ if (i === be) {
1314
+ this.handleProcessEmbedded(e, t, n);
1315
+ return;
1316
+ }
1317
+ const o = Nn.get(i);
1318
+ if (o) {
1319
+ this.handleMarker(e, t, n, o, i);
1320
+ return;
1321
+ }
1322
+ const a = Se.get(i);
1323
+ if (a) {
1324
+ this.handleChannel(e, t, n, a, i);
1325
+ return;
1326
+ }
1327
+ const c = this.registry.lookupChannel(i);
1328
+ if (c) {
1329
+ this.handleChannel(
1330
+ e,
1331
+ t,
1332
+ n,
1333
+ c.schema,
1334
+ i
1335
+ );
1336
+ return;
1337
+ }
1338
+ const l = this.registry.lookupHandler(i);
1339
+ if (l) {
1340
+ this.handlerRegistration.register({
1341
+ builder: e,
1342
+ key: t,
1343
+ node: n,
1344
+ processor: l,
1345
+ blueId: i,
1346
+ scopeContracts: r
1347
+ });
1348
+ return;
1349
+ }
1350
+ const u = this.registry.lookupMarker(i);
1351
+ if (u) {
1352
+ this.handleMarker(
1353
+ e,
1354
+ t,
1355
+ n,
1356
+ u.schema,
1357
+ i
1358
+ );
1359
+ return;
1360
+ }
1361
+ throw ie(i) ? new m(
1362
+ "Built-in processor-managed channel is missing schema registration",
1363
+ g.invalidContract(
1364
+ i,
1365
+ "Built-in processor-managed channel is missing schema registration",
1366
+ t
1367
+ )
1368
+ ) : new W(`Unsupported contract type: ${i}`);
1369
+ }
1370
+ handleProcessEmbedded(e, t, n) {
1371
+ try {
1372
+ const r = this.convert(
1373
+ n,
1374
+ Yt
1375
+ );
1376
+ e.setEmbedded(r);
1377
+ } catch (r) {
1378
+ throw Q(r) ? new m(
1379
+ "Failed to parse ProcessEmbedded marker",
1380
+ g.invalidContract(
1381
+ be,
1382
+ "Failed to parse ProcessEmbedded marker",
1383
+ t,
1384
+ r
1385
+ )
1386
+ ) : new m(
1387
+ r?.message ?? "Failed to register ProcessEmbedded marker",
1388
+ g.illegalState(
1389
+ r?.message ?? "Failed to register ProcessEmbedded marker"
1390
+ )
1391
+ );
1392
+ }
1393
+ }
1394
+ handleChannel(e, t, n, r, i) {
1395
+ try {
1396
+ const o = this.convert(n, r);
1397
+ e.addChannel(t, o, i);
1398
+ } catch (o) {
1399
+ if (Q(o))
1400
+ throw new m(
1401
+ "Failed to parse channel contract",
1402
+ g.invalidContract(
1403
+ i,
1404
+ "Failed to parse channel contract",
1405
+ t,
1406
+ o
1407
+ )
1408
+ );
1409
+ const a = o?.message ?? "Failed to register channel contract";
1410
+ throw new m(
1411
+ a,
1412
+ g.illegalState(a)
1413
+ );
1414
+ }
1415
+ }
1416
+ handleMarker(e, t, n, r, i) {
1417
+ try {
1418
+ const o = this.convert(n, r);
1419
+ e.addMarker(t, o, i);
1420
+ } catch (o) {
1421
+ if (Q(o))
1422
+ throw new m(
1423
+ "Failed to parse marker contract",
1424
+ g.invalidContract(
1425
+ i,
1426
+ "Failed to parse marker contract",
1427
+ t,
1428
+ o
1429
+ )
1430
+ );
1431
+ const a = o?.message ?? "Failed to register marker contract";
1432
+ throw new m(
1433
+ a,
1434
+ g.illegalState(a)
1435
+ );
1436
+ }
1437
+ }
1438
+ buildScopeContractsIndex(e) {
1439
+ const t = /* @__PURE__ */ new Map();
1440
+ for (const [n, r] of Object.entries(e)) {
1441
+ if (!r)
1442
+ continue;
1443
+ const i = r.getType()?.getBlueId();
1444
+ typeof i == "string" && i.trim().length > 0 && t.set(n, { node: r, nodeTypeBlueId: i });
1445
+ }
1446
+ return t;
1447
+ }
1448
+ convert(e, t) {
1449
+ return this.blue.nodeToSchemaOutput(e, t);
1450
+ }
1451
+ }
1452
+ function Q(s) {
1453
+ return s instanceof Te;
1454
+ }
1455
+ const Dn = p["Channel Event Checkpoint"];
1456
+ function On(s) {
1457
+ return s.jsonValueToNode({
1458
+ type: { blueId: Dn },
1459
+ lastEvents: {},
1460
+ lastSignatures: {}
1461
+ });
1462
+ }
1463
+ function Bn() {
1464
+ return {
1465
+ lastEvents: {},
1466
+ lastSignatures: {}
1467
+ };
1468
+ }
1469
+ function Ce(s) {
1470
+ return s != null && Object.prototype.hasOwnProperty.call(s, "lastEvents") && Object.prototype.hasOwnProperty.call(s, "lastSignatures");
1471
+ }
1472
+ class Ln {
1473
+ constructor(e, t, n, r, i) {
1474
+ this.markerKey = e, this.checkpoint = t, this.channelKey = n, this.lastEventNode = r, this.lastEventSignature = i;
1475
+ }
1476
+ lastEventNode;
1477
+ lastEventSignature;
1478
+ matches(e) {
1479
+ return e != null && e === this.lastEventSignature;
1480
+ }
1481
+ }
1482
+ class _n {
1483
+ constructor(e, t) {
1484
+ this.runtime = e, this.signatureFn = t;
1485
+ }
1486
+ ensureCheckpointMarker(e, t) {
1487
+ const n = t.marker(k), r = w(e, Oe);
1488
+ if (!n) {
1489
+ const i = On(this.runtime.blue());
1490
+ this.runtime.directWrite(r, i), t.registerCheckpointMarker(Bn());
1491
+ return;
1492
+ }
1493
+ if (!Ce(n))
1494
+ throw new Error(
1495
+ `Reserved key 'checkpoint' must contain a Channel Event Checkpoint at ${r}`
1496
+ );
1497
+ }
1498
+ findCheckpoint(e, t) {
1499
+ for (const [n, r] of e.markerEntries()) {
1500
+ if (!Ce(r))
1501
+ continue;
1502
+ const o = (r.lastEvents?.[t] ?? null)?.clone() ?? null, c = r.lastSignatures?.[t] ?? null ?? this.signatureFn(o);
1503
+ return new Ln(
1504
+ n,
1505
+ r,
1506
+ t,
1507
+ o,
1508
+ c
1509
+ );
1510
+ }
1511
+ return null;
1512
+ }
1513
+ isDuplicate(e, t) {
1514
+ return e != null && e.matches(t);
1515
+ }
1516
+ persist(e, t, n, r, i) {
1517
+ if (!n)
1518
+ return;
1519
+ const o = w(
1520
+ e,
1521
+ _e(n.markerKey, n.channelKey)
1522
+ ), a = i?.clone() ?? null;
1523
+ this.runtime.gasMeter().chargeCheckpointUpdate(), this.runtime.directWrite(o, a), n.checkpoint.lastEvents || (n.checkpoint.lastEvents = {}), a ? n.checkpoint.lastEvents[n.channelKey] = a.clone() ?? null : delete n.checkpoint.lastEvents[n.channelKey], n.lastEventNode = a?.clone() ?? null;
1524
+ const c = w(
1525
+ e,
1526
+ $e(n.markerKey, n.channelKey)
1527
+ ), l = r == null ? null : new d().setValue(r);
1528
+ this.runtime.directWrite(c, l), n.checkpoint.lastSignatures || (n.checkpoint.lastSignatures = {}), r == null ? delete n.checkpoint.lastSignatures[n.channelKey] : n.checkpoint.lastSignatures[n.channelKey] = r, n.lastEventSignature = r ?? null;
1529
+ }
1530
+ }
1531
+ class $n {
1532
+ constructor(e, t, n) {
1533
+ this.runtime = e, this.checkpointManager = t, this.deps = n;
1534
+ }
1535
+ async runExternalChannel(e, t, n, r) {
1536
+ if (this.deps.isScopeInactive(e))
1537
+ return;
1538
+ this.runtime.gasMeter().chargeChannelMatchAttempt();
1539
+ const i = await this.deps.evaluateChannel(
1540
+ n,
1541
+ t,
1542
+ e,
1543
+ r
1544
+ );
1545
+ if (!i.matches)
1546
+ return;
1547
+ const o = i.eventNode ?? r, a = r;
1548
+ this.checkpointManager.ensureCheckpointMarker(e, t);
1549
+ const c = this.checkpointManager.findCheckpoint(
1550
+ t,
1551
+ n.key()
1552
+ ), l = i.eventId ?? this.deps.canonicalSignature(a);
1553
+ this.checkpointManager.isDuplicate(c, l) || (await this.runHandlers(
1554
+ e,
1555
+ t,
1556
+ n.key(),
1557
+ o,
1558
+ !1
1559
+ ), !this.deps.isScopeInactive(e) && this.checkpointManager.persist(
1560
+ e,
1561
+ t,
1562
+ c,
1563
+ l ?? null,
1564
+ a
1565
+ ));
1566
+ }
1567
+ async runHandlers(e, t, n, r, i) {
1568
+ const o = t.handlersFor(n);
1569
+ if (o.length !== 0)
1570
+ for (const a of o) {
1571
+ if (!i && this.deps.isScopeInactive(e))
1572
+ break;
1573
+ const c = this.deps.createContext(
1574
+ e,
1575
+ t,
1576
+ r,
1577
+ i
1578
+ );
1579
+ if (await this.deps.shouldRunHandler(a, c) && (this.runtime.gasMeter().chargeHandlerOverhead(), await this.deps.executeHandler(a, c), !i && this.deps.isScopeInactive(e)))
1580
+ break;
1581
+ }
1582
+ }
1583
+ }
1584
+ class M extends m {
1585
+ constructor(e) {
1586
+ super(e, g.illegalState(e)), this.name = "IllegalStateException";
1587
+ }
1588
+ }
1589
+ class T extends Error {
1590
+ constructor(e) {
1591
+ super(e), this.name = "BoundaryViolationException";
1592
+ }
1593
+ }
1594
+ const xn = p["Document Update Channel"], zn = p["Embedded Node Channel"], Fn = p["Triggered Event Channel"], Un = p["Lifecycle Event Channel"], ke = p["Processing Initialized Marker"], Vn = p["Document Processing Initiated"];
1595
+ class Hn {
1596
+ runtime;
1597
+ contractLoader;
1598
+ channelRunner;
1599
+ bundles;
1600
+ hooks;
1601
+ blueId;
1602
+ nodeAt;
1603
+ createDocumentUpdateEvent;
1604
+ matchesDocumentUpdate;
1605
+ constructor(e) {
1606
+ this.runtime = e.runtime, this.contractLoader = e.contractLoader, this.channelRunner = e.channelRunner, this.bundles = e.bundles, this.hooks = e.hooks, this.blueId = e.blueId, this.nodeAt = e.nodeAt, this.createDocumentUpdateEvent = e.createDocumentUpdateEvent, this.matchesDocumentUpdate = e.matchesDocumentUpdate;
1607
+ }
1608
+ async initializeScope(e, t) {
1609
+ const n = y(e), r = /* @__PURE__ */ new Set();
1610
+ let i = null, o = null;
1611
+ for (t && this.runtime.gasMeter().chargeScopeEntry(n); ; ) {
1612
+ const h = this.nodeAt(n);
1613
+ if (!h)
1614
+ return;
1615
+ o || (o = h.clone()), i = this.loadBundle(h, n), this.bundles.set(n, i);
1616
+ const f = i.embeddedPaths().find((Qe) => !r.has(Qe)) ?? null;
1617
+ if (!f)
1618
+ break;
1619
+ r.add(f);
1620
+ const E = w(n, f);
1621
+ this.nodeAt(E) && await this.initializeScope(E, !0);
1622
+ }
1623
+ if (!i)
1624
+ return;
1625
+ const a = this.hasInitializationMarker(n);
1626
+ if (!a && i.hasCheckpoint())
1627
+ throw new M(
1628
+ `Reserved key 'checkpoint' must not appear before initialization at scope ${n}`
1629
+ );
1630
+ if (a)
1631
+ return;
1632
+ this.runtime.gasMeter().chargeInitialization();
1633
+ const c = this.blueId(o ?? new d()), l = this.createLifecycleEvent(c), u = this.hooks.createContext(
1634
+ n,
1635
+ i,
1636
+ l,
1637
+ !1,
1638
+ !0
1639
+ );
1640
+ await this.deliverLifecycle(n, i, l, !0), await this.addInitializationMarker(u, c);
1641
+ }
1642
+ loadBundles(e) {
1643
+ const t = y(e);
1644
+ if (this.bundles.has(t))
1645
+ return;
1646
+ const n = this.nodeAt(t), r = n ? this.loadBundle(n, t) : N.empty();
1647
+ this.bundles.set(t, r);
1648
+ for (const i of r.embeddedPaths()) {
1649
+ const o = w(t, i);
1650
+ this.loadBundles(o);
1651
+ }
1652
+ }
1653
+ async processExternalEvent(e, t) {
1654
+ const n = y(e);
1655
+ if (this.hooks.isScopeInactive(n))
1656
+ return;
1657
+ this.runtime.gasMeter().chargeScopeEntry(n);
1658
+ const r = await this.processEmbeddedChildren(n, t);
1659
+ if (!r)
1660
+ return;
1661
+ const i = r.channelsOfType();
1662
+ if (i.length === 0) {
1663
+ this.finalizeScope(n, r);
1664
+ return;
1665
+ }
1666
+ for (const o of i) {
1667
+ if (this.hooks.isScopeInactive(n))
1668
+ break;
1669
+ ie(o.blueId()) || await this.channelRunner.runExternalChannel(
1670
+ n,
1671
+ r,
1672
+ o,
1673
+ t
1674
+ );
1675
+ }
1676
+ await this.finalizeScope(n, r);
1677
+ }
1678
+ async handlePatch(e, t, n, r) {
1679
+ if (!this.hooks.isScopeInactive(e)) {
1680
+ this.runtime.gasMeter().chargeBoundaryCheck();
1681
+ try {
1682
+ this.validatePatchBoundary(e, t, n), this.enforceReservedKeyWriteProtection(
1683
+ e,
1684
+ n,
1685
+ r
1686
+ );
1687
+ } catch (i) {
1688
+ if (i instanceof T) {
1689
+ const o = this.hooks.fatalReason(i, "Boundary violation");
1690
+ await this.hooks.enterFatalTermination(e, t, o);
1691
+ return;
1692
+ }
1693
+ throw i;
1694
+ }
1695
+ try {
1696
+ switch (n.op) {
1697
+ case "ADD":
1698
+ case "REPLACE":
1699
+ this.runtime.gasMeter().chargePatchAddOrReplace(n.val ?? null);
1700
+ break;
1701
+ case "REMOVE":
1702
+ this.runtime.gasMeter().chargePatchRemove();
1703
+ break;
1704
+ default:
1705
+ break;
1706
+ }
1707
+ const i = this.runtime.applyPatch(e, n);
1708
+ if (!i)
1709
+ return;
1710
+ await this.markCutOffChildrenIfNeeded(e, t, i), this.runtime.gasMeter().chargeCascadeRouting(i.cascadeScopes.length);
1711
+ for (const o of i.cascadeScopes) {
1712
+ const a = this.bundles.get(o);
1713
+ if (!a || this.hooks.isScopeInactive(o))
1714
+ continue;
1715
+ const c = this.createDocumentUpdateEvent(i, o), l = a.channelsOfType(
1716
+ xn
1717
+ );
1718
+ for (const u of l) {
1719
+ const h = u.contract();
1720
+ if (this.matchesDocumentUpdate(
1721
+ o,
1722
+ h.path ?? null,
1723
+ i.path
1724
+ ) && (await this.channelRunner.runHandlers(
1725
+ o,
1726
+ a,
1727
+ u.key(),
1728
+ c,
1729
+ !1
1730
+ ), this.hooks.isScopeInactive(o)))
1731
+ break;
1732
+ }
1733
+ }
1734
+ } catch (i) {
1735
+ if (i instanceof T) {
1736
+ const o = this.hooks.fatalReason(i, "Boundary violation");
1737
+ await this.hooks.enterFatalTermination(e, t, o);
1738
+ return;
1739
+ }
1740
+ if (i instanceof M || i instanceof Error && !(i instanceof m)) {
1741
+ const o = this.hooks.fatalReason(i, "Runtime fatal");
1742
+ await this.hooks.enterFatalTermination(e, t, o);
1743
+ return;
1744
+ }
1745
+ throw i;
1746
+ }
1747
+ }
1748
+ }
1749
+ async deliverLifecycle(e, t, n, r) {
1750
+ if (this.runtime.gasMeter().chargeLifecycleDelivery(), await this.hooks.recordLifecycleForBridging(e, n), !t)
1751
+ return;
1752
+ const i = t.channelsOfType(
1753
+ Un
1754
+ );
1755
+ for (const o of i)
1756
+ if (await this.channelRunner.runHandlers(
1757
+ e,
1758
+ t,
1759
+ o.key(),
1760
+ n,
1761
+ !0
1762
+ ), this.hooks.isScopeInactive(e))
1763
+ break;
1764
+ r && await this.finalizeScope(e, t);
1765
+ }
1766
+ async processEmbeddedChildren(e, t) {
1767
+ const n = y(e), r = /* @__PURE__ */ new Set();
1768
+ let i = this.refreshBundle(n);
1769
+ for (; i; ) {
1770
+ const o = this.nextEmbeddedPath(i, r);
1771
+ if (!o)
1772
+ return i;
1773
+ r.add(o);
1774
+ const a = w(n, o);
1775
+ if (a === n || this.hooks.isScopeInactive(a)) {
1776
+ i = this.refreshBundle(n);
1777
+ continue;
1778
+ }
1779
+ this.nodeAt(a) && (await this.initializeScope(a, !1), await this.processExternalEvent(a, t)), i = this.refreshBundle(n);
1780
+ }
1781
+ return null;
1782
+ }
1783
+ refreshBundle(e) {
1784
+ const t = y(e), n = this.nodeAt(t);
1785
+ if (!n)
1786
+ return this.bundles.delete(t), null;
1787
+ const r = this.loadBundle(n, t);
1788
+ return this.bundles.set(t, r), r;
1789
+ }
1790
+ nextEmbeddedPath(e, t) {
1791
+ if (!e)
1792
+ return null;
1793
+ for (const n of e.embeddedPaths())
1794
+ if (!t.has(n))
1795
+ return n;
1796
+ return null;
1797
+ }
1798
+ loadBundle(e, t) {
1799
+ try {
1800
+ return this.contractLoader.load(e, t);
1801
+ } catch (n) {
1802
+ if (n instanceof m || n instanceof W)
1803
+ throw n;
1804
+ const r = n?.message ?? "Failed to load contracts";
1805
+ throw new m(
1806
+ r,
1807
+ g.runtimeFatal(
1808
+ `Failed to load contracts for scope ${t}`,
1809
+ n
1810
+ )
1811
+ );
1812
+ }
1813
+ }
1814
+ async addInitializationMarker(e, t) {
1815
+ const n = new d().setType(new d().setBlueId(ke)).addProperty("documentId", new d().setValue(t)), r = e.resolvePointer(ee);
1816
+ await e.applyPatch({
1817
+ op: "ADD",
1818
+ path: r,
1819
+ val: n
1820
+ });
1821
+ }
1822
+ async finalizeScope(e, t) {
1823
+ this.hooks.isScopeInactive(e) || (await this.bridgeEmbeddedEmissions(e, t), await this.drainTriggeredQueue(e, t));
1824
+ }
1825
+ async bridgeEmbeddedEmissions(e, t) {
1826
+ if (this.hooks.isScopeInactive(e) || t.embeddedPaths().length === 0)
1827
+ return;
1828
+ const n = t.channelsOfType(
1829
+ zn
1830
+ );
1831
+ if (n.length !== 0)
1832
+ for (const r of t.embeddedPaths()) {
1833
+ const i = w(e, r), a = this.runtime.scope(i).drainBridgeableEvents();
1834
+ if (a.length !== 0)
1835
+ for (const c of a) {
1836
+ let l = !1;
1837
+ for (const u of n) {
1838
+ const f = u.contract().childPath ?? "/";
1839
+ w(e, f) === i && (l || (this.runtime.gasMeter().chargeBridge(), l = !0), await this.channelRunner.runHandlers(
1840
+ e,
1841
+ t,
1842
+ u.key(),
1843
+ c.clone(),
1844
+ !1
1845
+ ));
1846
+ }
1847
+ }
1848
+ }
1849
+ }
1850
+ async drainTriggeredQueue(e, t) {
1851
+ if (this.hooks.isScopeInactive(e))
1852
+ return;
1853
+ const n = this.runtime.scope(e), r = t.channelsOfType(
1854
+ Fn
1855
+ );
1856
+ if (r.length === 0) {
1857
+ n.clearTriggered();
1858
+ return;
1859
+ }
1860
+ for (; !n.triggeredIsEmpty(); ) {
1861
+ const i = n.pollTriggered();
1862
+ if (!i)
1863
+ break;
1864
+ this.runtime.gasMeter().chargeDrainEvent();
1865
+ for (const o of r) {
1866
+ if (this.hooks.isScopeInactive(e)) {
1867
+ n.clearTriggered();
1868
+ return;
1869
+ }
1870
+ if (await this.channelRunner.runHandlers(
1871
+ e,
1872
+ t,
1873
+ o.key(),
1874
+ i.clone(),
1875
+ !1
1876
+ ), this.hooks.isScopeInactive(e)) {
1877
+ n.clearTriggered();
1878
+ return;
1879
+ }
1880
+ }
1881
+ }
1882
+ }
1883
+ validatePatchBoundary(e, t, n) {
1884
+ const r = y(e), i = b(n.path);
1885
+ if (i === r)
1886
+ throw new T(
1887
+ `Self-root mutation is forbidden at scope ${r}`
1888
+ );
1889
+ if (r !== "/" && !i.startsWith(`${r}/`))
1890
+ throw new T(
1891
+ `Patch path ${i} is outside scope ${r}`
1892
+ );
1893
+ for (const o of t.embeddedPaths()) {
1894
+ const a = w(r, o);
1895
+ if (i.startsWith(`${a}/`))
1896
+ throw new T(
1897
+ `Boundary violation: patch ${i} enters embedded scope ${a}`
1898
+ );
1899
+ }
1900
+ }
1901
+ enforceReservedKeyWriteProtection(e, t, n) {
1902
+ if (n)
1903
+ return;
1904
+ const r = y(e), i = b(t.path);
1905
+ for (const o of re) {
1906
+ const a = w(
1907
+ r,
1908
+ q(o)
1909
+ );
1910
+ if (i === a || i.startsWith(`${a}/`))
1911
+ throw new T(
1912
+ `Reserved key '${o}' is write-protected at ${a}`
1913
+ );
1914
+ }
1915
+ }
1916
+ async markCutOffChildrenIfNeeded(e, t, n) {
1917
+ if (t.embeddedPaths().length === 0)
1918
+ return;
1919
+ const r = b(n.path);
1920
+ for (const i of t.embeddedPaths()) {
1921
+ const o = w(e, i);
1922
+ r === o && (n.op === "remove" || n.op === "replace") && await this.hooks.markCutOff(o);
1923
+ }
1924
+ }
1925
+ hasInitializationMarker(e) {
1926
+ const t = w(e, ee), n = this.nodeAt(t);
1927
+ if (!n)
1928
+ return !1;
1929
+ if (!(n instanceof d)) {
1930
+ const i = `Reserved key 'initialized' must contain a Processing Initialized Marker at ${t}`;
1931
+ throw new M(i);
1932
+ }
1933
+ if (n.getType()?.getBlueId() !== ke) {
1934
+ const i = `Reserved key 'initialized' must contain a Processing Initialized Marker at ${t}`;
1935
+ throw new M(i);
1936
+ }
1937
+ return !0;
1938
+ }
1939
+ createLifecycleEvent(e) {
1940
+ return new d().setType(new d().setBlueId(Vn)).setProperties({
1941
+ type: new d().setValue("Document Processing Initiated"),
1942
+ documentId: new d().setValue(e)
1943
+ });
1944
+ }
1945
+ }
1946
+ class ne extends Error {
1947
+ constructor(e) {
1948
+ super(
1949
+ e ? "Processing terminated due to fatal error" : "Processing terminated"
1950
+ ), this.fatal = e, this.name = "RunTerminationError";
1951
+ }
1952
+ }
1953
+ const Kn = p["Processing Terminated Marker"], Wn = p["Document Processing Terminated"];
1954
+ class Gn {
1955
+ constructor(e) {
1956
+ this.runtime = e;
1957
+ }
1958
+ async terminateScope(e, t, n, r, i) {
1959
+ e.recordPendingTermination(t, r, i ?? null);
1960
+ const o = e.normalizeScope(t), a = w(o, De);
1961
+ this.runtime.directWrite(
1962
+ a,
1963
+ qn(this.runtime.blue(), r, i)
1964
+ ), this.runtime.gasMeter().chargeTerminationMarker();
1965
+ const c = n ?? e.bundleForScope(o) ?? null, l = Jn(r, i);
1966
+ if (await e.deliverLifecycle(
1967
+ o,
1968
+ c,
1969
+ l,
1970
+ !1
1971
+ ), this.runtime.scope(o).finalizeTermination(r, i ?? null), e.clearPendingTermination(t), r === "FATAL" && this.runtime.gasMeter().chargeFatalTerminationOverhead(), r === "FATAL" && o === "/")
1972
+ throw this.runtime.markRunTerminated(), new ne(!0);
1973
+ if (r === "GRACEFUL" && o === "/")
1974
+ throw this.runtime.markRunTerminated(), new ne(!1);
1975
+ }
1976
+ }
1977
+ function qn(s, e, t) {
1978
+ return jn(s, {
1979
+ type: { blueId: Kn },
1980
+ cause: e === "GRACEFUL" ? "graceful" : "fatal",
1981
+ ...t ? { reason: t } : {}
1982
+ });
1983
+ }
1984
+ function Jn(s, e) {
1985
+ const t = new d().setType(
1986
+ new d().setBlueId(Wn)
1987
+ );
1988
+ return t.addProperty(
1989
+ "cause",
1990
+ new d().setValue(s === "GRACEFUL" ? "graceful" : "fatal")
1991
+ ), e && t.addProperty("reason", new d().setValue(e)), t;
1992
+ }
1993
+ function jn(s, e) {
1994
+ return s.jsonValueToNode(e);
1995
+ }
1996
+ const _ = "-";
1997
+ class Qn {
1998
+ constructor(e) {
1999
+ this.document = e;
2000
+ }
2001
+ applyPatch(e, t) {
2002
+ const n = y(e), r = b(t.path), i = ve(r), o = Ie(this.document, i, "before", r);
2003
+ switch (t.op) {
2004
+ case "ADD":
2005
+ this.applyAdd(i, r, t.val ?? null);
2006
+ break;
2007
+ case "REPLACE":
2008
+ this.applyReplace(i, r, t.val ?? null);
2009
+ break;
2010
+ case "REMOVE":
2011
+ this.applyRemove(i, r);
2012
+ break;
2013
+ }
2014
+ const a = t.op === "REMOVE" ? null : Ie(this.document, i, "after", r);
2015
+ return {
2016
+ path: r,
2017
+ before: o,
2018
+ after: a,
2019
+ op: t.op.toLowerCase(),
2020
+ originScope: n,
2021
+ cascadeScopes: Yn(n)
2022
+ };
2023
+ }
2024
+ directWrite(e, t) {
2025
+ const n = b(e);
2026
+ if (n === "/")
2027
+ throw new Error("Direct write cannot target root document");
2028
+ const r = ve(n), { parent: i, leaf: o } = this.resolveParent(r);
2029
+ if (o === _)
2030
+ throw new Error(
2031
+ `Direct write does not support append token '-' for path ${n}`
2032
+ );
2033
+ const a = i.getItems();
2034
+ if (a && R(o)) {
2035
+ this.directWriteArray(i, a, o, t, n);
2036
+ return;
2037
+ }
2038
+ this.directWriteObject(i, o, t);
2039
+ }
2040
+ directWriteArray(e, t, n, r, i) {
2041
+ const o = Y(e, t), a = C(n, i);
2042
+ if (r == null) {
2043
+ if (a < 0 || a >= o.length)
2044
+ return;
2045
+ o.splice(a, 1), e.setItems(o);
2046
+ return;
2047
+ }
2048
+ const c = r.clone();
2049
+ if (a === o.length) {
2050
+ o.push(c), e.setItems(o);
2051
+ return;
2052
+ }
2053
+ if (a >= 0 && a < o.length) {
2054
+ o[a] = c, e.setItems(o);
2055
+ return;
2056
+ }
2057
+ throw new Error(
2058
+ `Array index out of bounds for direct write: ${i}`
2059
+ );
2060
+ }
2061
+ directWriteObject(e, t, n) {
2062
+ const r = V(e);
2063
+ if (n == null) {
2064
+ delete r[t], e.setProperties(
2065
+ Object.keys(r).length > 0 ? r : void 0
2066
+ );
2067
+ return;
2068
+ }
2069
+ r[t] = n.clone(), e.setProperties(r);
2070
+ }
2071
+ resolveParent(e) {
2072
+ if (e.length === 0)
2073
+ throw new Error("Cannot apply direct write to root");
2074
+ let t = this.document;
2075
+ for (let n = 0; n < e.length - 1; n += 1) {
2076
+ const r = e[n];
2077
+ t = this.getOrCreateChild(t, r, e, n + 1);
2078
+ }
2079
+ return { parent: t, leaf: e[e.length - 1] };
2080
+ }
2081
+ getOrCreateChild(e, t, n, r) {
2082
+ if (t === _)
2083
+ throw new Error(
2084
+ `Append token '-' must be final segment: ${B(n, r)}`
2085
+ );
2086
+ const i = e.getItems();
2087
+ if (i && R(t)) {
2088
+ const c = C(t, B(n, r));
2089
+ if (c < 0 || c >= i.length)
2090
+ throw new Error(
2091
+ `Array index out of bounds: ${B(n, r)}`
2092
+ );
2093
+ const l = i[c];
2094
+ if (!l)
2095
+ throw new Error(
2096
+ `Path does not exist: ${B(n, r)}`
2097
+ );
2098
+ return l;
2099
+ }
2100
+ const o = V(e);
2101
+ let a = o[t];
2102
+ return a || (a = new d(), o[t] = a, e.setProperties(o)), a;
2103
+ }
2104
+ applyAdd(e, t, n) {
2105
+ if (t === "/" || t.length === 0)
2106
+ throw new Error("ADD operation cannot target document root");
2107
+ const { parent: r, key: i, pointer: o, created: a } = this.resolveParentForPatch(
2108
+ e,
2109
+ t,
2110
+ "ADD"
2111
+ );
2112
+ try {
2113
+ if (R(i)) {
2114
+ const l = r.getItems(), u = i === _;
2115
+ if (!l)
2116
+ throw new Error(
2117
+ u ? `Append token '-' requires array at ${o}` : `Array index segment requires array at ${o}`
2118
+ );
2119
+ if (u) {
2120
+ Y(r, l).push(L(n));
2121
+ return;
2122
+ }
2123
+ const h = C(i, t);
2124
+ if (h < 0 || h > l.length)
2125
+ throw new Error(`Array index out of bounds in path: ${t}`);
2126
+ Y(r, l).splice(h, 0, L(n));
2127
+ return;
2128
+ }
2129
+ const c = V(r);
2130
+ c[i] = L(n), r.setProperties(c);
2131
+ } catch (c) {
2132
+ throw this.rollbackCreated(a), c;
2133
+ }
2134
+ }
2135
+ applyReplace(e, t, n) {
2136
+ if (t === "/" || t.length === 0)
2137
+ throw new Error("REPLACE operation cannot target document root");
2138
+ const { parent: r, key: i, created: o } = this.resolveParentForPatch(
2139
+ e,
2140
+ t,
2141
+ "REPLACE"
2142
+ );
2143
+ try {
2144
+ if (R(i)) {
2145
+ const c = r.getItems();
2146
+ if (!c)
2147
+ throw new Error(`Array index segment requires array at ${t}`);
2148
+ const l = C(i, t);
2149
+ if (l < 0 || l >= c.length)
2150
+ throw new Error(`Array index out of bounds in path: ${t}`);
2151
+ c[l] = L(n), r.setItems(c);
2152
+ return;
2153
+ }
2154
+ const a = V(r);
2155
+ a[i] = L(n), r.setProperties(a);
2156
+ } catch (a) {
2157
+ throw this.rollbackCreated(o), a;
2158
+ }
2159
+ }
2160
+ applyRemove(e, t) {
2161
+ if (t === "/" || t.length === 0)
2162
+ throw new Error("REMOVE operation cannot target document root");
2163
+ const { parent: n, key: r } = this.resolveParentForPatch(
2164
+ e,
2165
+ t,
2166
+ "REMOVE"
2167
+ );
2168
+ if (R(r)) {
2169
+ const a = n.getItems();
2170
+ if (!a)
2171
+ throw new Error(`Array index segment requires array at ${t}`);
2172
+ const c = C(r, t);
2173
+ if (c < 0 || c >= a.length)
2174
+ throw new Error(`Array index out of bounds in path: ${t}`);
2175
+ a.splice(c, 1), n.setItems(a);
2176
+ return;
2177
+ }
2178
+ const i = n.getProperties();
2179
+ if (!i || !Object.prototype.hasOwnProperty.call(i, r))
2180
+ throw new Error(`Path does not exist: ${t}`);
2181
+ const o = { ...i };
2182
+ delete o[r], n.setProperties(o);
2183
+ }
2184
+ resolveParentForPatch(e, t, n) {
2185
+ if (e.length === 0)
2186
+ throw new Error(`${n} operation cannot target document root`);
2187
+ let r = this.document;
2188
+ const i = [];
2189
+ for (let a = 0; a < e.length - 1; a += 1) {
2190
+ const c = e[a], l = B(e, a + 1);
2191
+ if (R(c)) {
2192
+ const f = r.getItems();
2193
+ if (!f)
2194
+ throw new Error(`Array index segment requires array at ${l}`);
2195
+ const E = C(c, l);
2196
+ if (E < 0 || E >= f.length)
2197
+ throw new Error(`Array index out of bounds in path: ${l}`);
2198
+ const O = f[E];
2199
+ if (!(O instanceof d))
2200
+ throw new Error(`Array index out of bounds in path: ${l}`);
2201
+ r = O;
2202
+ continue;
2203
+ }
2204
+ let u = r.getProperties(), h = u?.[c] ?? null;
2205
+ if (!(h instanceof d)) {
2206
+ if (n === "REMOVE")
2207
+ throw new Error(`Path does not exist: ${l}`);
2208
+ h = new d(), u || (u = {}), u[c] = h, r.setProperties(u), i.push({ owner: r, key: c });
2209
+ }
2210
+ r = h;
2211
+ }
2212
+ const o = e[e.length - 1];
2213
+ return { parent: r, key: o, pointer: t, created: i };
2214
+ }
2215
+ rollbackCreated(e) {
2216
+ for (let t = e.length - 1; t >= 0; t -= 1) {
2217
+ const { owner: n, key: r } = e[t], i = n.getProperties();
2218
+ i && (delete i[r], Object.keys(i).length === 0 ? n.setProperties(void 0) : n.setProperties(i));
2219
+ }
2220
+ }
2221
+ }
2222
+ function Yn(s) {
2223
+ const e = [];
2224
+ let t = s;
2225
+ for (; e.push(t), t !== "/"; ) {
2226
+ const n = t.lastIndexOf("/");
2227
+ t = n <= 0 ? "/" : t.substring(0, n);
2228
+ }
2229
+ return e;
2230
+ }
2231
+ function Ie(s, e, t, n) {
2232
+ try {
2233
+ if (e.length === 0)
2234
+ return s.clone();
2235
+ const r = Zn(s, e, t, n);
2236
+ return r ? r.clone() : null;
2237
+ } catch {
2238
+ return null;
2239
+ }
2240
+ }
2241
+ function Zn(s, e, t, n) {
2242
+ let r = s;
2243
+ for (let i = 0; i < e.length; i += 1) {
2244
+ const o = e[i] ?? "", a = i === e.length - 1;
2245
+ if (r = Xn(r, o, a, t, n), !r)
2246
+ return null;
2247
+ }
2248
+ return r;
2249
+ }
2250
+ function Xn(s, e, t, n, r) {
2251
+ if (!s)
2252
+ return null;
2253
+ const i = s.getItems();
2254
+ if (i) {
2255
+ if (e === _) {
2256
+ if (!t)
2257
+ throw new Error(`Append token '-' must be final segment: ${r}`);
2258
+ return n === "before" || i.length === 0 ? null : i[i.length - 1] ?? null;
2259
+ }
2260
+ const c = C(e, r);
2261
+ return c < 0 || c >= i.length ? null : i[c] ?? null;
2262
+ }
2263
+ const o = s.getProperties();
2264
+ if (!o)
2265
+ return null;
2266
+ const a = o[e];
2267
+ return a instanceof d ? a : null;
2268
+ }
2269
+ function ve(s) {
2270
+ if (s === "/" || s === "")
2271
+ return [];
2272
+ const e = s.startsWith("/") ? s.slice(1) : s;
2273
+ return e.length === 0 ? [] : e.split("/");
2274
+ }
2275
+ function C(s, e) {
2276
+ const t = Number.parseInt(s, 10);
2277
+ if (Number.isNaN(t))
2278
+ throw new Error(`Expected numeric array index in path: ${e}`);
2279
+ if (t < 0)
2280
+ throw new Error(`Negative array index in path: ${e}`);
2281
+ return t;
2282
+ }
2283
+ function B(s, e) {
2284
+ if (e <= 0)
2285
+ return "/";
2286
+ const t = Math.min(e, s.length);
2287
+ let n = "";
2288
+ for (let r = 0; r < t; r += 1)
2289
+ n += `/${s[r] ?? ""}`;
2290
+ return n === "" ? "/" : n;
2291
+ }
2292
+ function Y(s, e) {
2293
+ const t = [...e];
2294
+ return s.setItems(t), t;
2295
+ }
2296
+ function V(s) {
2297
+ const e = s.getProperties();
2298
+ if (!e) {
2299
+ const n = {};
2300
+ return s.setProperties(n), n;
2301
+ }
2302
+ const t = { ...e };
2303
+ return s.setProperties(t), t;
2304
+ }
2305
+ function R(s) {
2306
+ return s === _ || /^\d+$/.test(s);
2307
+ }
2308
+ function L(s) {
2309
+ return s == null ? new d().setValue(null) : s.clone();
2310
+ }
2311
+ class er {
2312
+ constructor(e) {
2313
+ this.path = e;
2314
+ }
2315
+ triggeredQueue = [];
2316
+ bridgeableEvents = [];
2317
+ terminated = !1;
2318
+ terminationKindValue = null;
2319
+ terminationReasonValue = null;
2320
+ cutOff = !1;
2321
+ triggeredLimit = -1;
2322
+ bridgeableLimit = -1;
2323
+ scopePath() {
2324
+ return this.path;
2325
+ }
2326
+ enqueueTriggered(e) {
2327
+ this.cutOff && this.triggeredLimit >= 0 && this.triggeredQueue.length >= this.triggeredLimit || this.triggeredQueue.push(e);
2328
+ }
2329
+ pollTriggered() {
2330
+ return this.triggeredQueue.shift();
2331
+ }
2332
+ peekTriggered() {
2333
+ return this.triggeredQueue[0];
2334
+ }
2335
+ clearTriggered() {
2336
+ this.triggeredQueue.length = 0;
2337
+ }
2338
+ triggeredSize() {
2339
+ return this.triggeredQueue.length;
2340
+ }
2341
+ triggeredIsEmpty() {
2342
+ return this.triggeredQueue.length === 0;
2343
+ }
2344
+ triggeredSnapshot() {
2345
+ return [...this.triggeredQueue];
2346
+ }
2347
+ recordBridgeable(e) {
2348
+ this.cutOff && this.bridgeableLimit >= 0 && this.bridgeableEvents.length >= this.bridgeableLimit || this.bridgeableEvents.push(e);
2349
+ }
2350
+ drainBridgeableEvents() {
2351
+ let e;
2352
+ return this.cutOff && this.bridgeableLimit >= 0 && this.bridgeableLimit < this.bridgeableEvents.length ? e = this.bridgeableEvents.slice(0, this.bridgeableLimit) : e = [...this.bridgeableEvents], this.bridgeableEvents.length = 0, e;
2353
+ }
2354
+ isTerminated() {
2355
+ return this.terminated;
2356
+ }
2357
+ terminationKind() {
2358
+ return this.terminationKindValue;
2359
+ }
2360
+ terminationReason() {
2361
+ return this.terminationReasonValue;
2362
+ }
2363
+ finalizeTermination(e, t = null) {
2364
+ this.terminated || (this.terminated = !0, this.terminationKindValue = e, this.terminationReasonValue = t ?? null, this.clearTriggered());
2365
+ }
2366
+ markCutOff() {
2367
+ this.cutOff || (this.cutOff = !0, this.triggeredLimit = this.triggeredQueue.length, this.bridgeableLimit = this.bridgeableEvents.length);
2368
+ }
2369
+ isCutOff() {
2370
+ return this.cutOff;
2371
+ }
2372
+ }
2373
+ class tr {
2374
+ scopesMap = /* @__PURE__ */ new Map();
2375
+ rootEmissionList = [];
2376
+ scopes() {
2377
+ return this.scopesMap;
2378
+ }
2379
+ scope(e) {
2380
+ let t = this.scopesMap.get(e);
2381
+ return t || (t = new er(e), this.scopesMap.set(e, t)), t;
2382
+ }
2383
+ existingScope(e) {
2384
+ return this.scopesMap.get(e);
2385
+ }
2386
+ rootEmissions() {
2387
+ return [...this.rootEmissionList];
2388
+ }
2389
+ recordRootEmission(e) {
2390
+ this.rootEmissionList.push(e);
2391
+ }
2392
+ isScopeTerminated(e) {
2393
+ return this.scopesMap.get(e)?.isTerminated() ?? !1;
2394
+ }
2395
+ clearScope(e) {
2396
+ this.scopesMap.delete(e);
2397
+ }
2398
+ }
2399
+ function F(s) {
2400
+ return Math.floor((s + 99) / 100);
2401
+ }
2402
+ function le(s) {
2403
+ return new TextEncoder().encode(s).length;
2404
+ }
2405
+ function nr(s) {
2406
+ const e = b(s);
2407
+ return e === "/" ? 0 : e.split("/").length - 1;
2408
+ }
2409
+ function rr(s) {
2410
+ return 100 + F(le(s));
2411
+ }
2412
+ function ir(s) {
2413
+ return 40 + 5 * Math.max(0, s);
2414
+ }
2415
+ function sr(s) {
2416
+ return 5 + F(le(s));
2417
+ }
2418
+ function or(s, e) {
2419
+ return 3 * Math.max(0, s) + F(le(e));
2420
+ }
2421
+ function ar(s, e) {
2422
+ return 8 + nr(s) + F(e);
2423
+ }
2424
+ const cr = 1e3, lr = 5, ur = 50, dr = 2, hr = 10, fr = 10, pr = 10, mr = 20, gr = 20, Er = 30, yr = 30, wr = 100;
2425
+ function br(s) {
2426
+ return 50 + 10 * s;
2427
+ }
2428
+ function Sr(s) {
2429
+ return 20 + s;
2430
+ }
2431
+ function Cr(s) {
2432
+ return 10 * s;
2433
+ }
2434
+ function kr(s) {
2435
+ return 20 + s;
2436
+ }
2437
+ class Ir {
2438
+ constructor(e) {
2439
+ this.blue = e;
2440
+ }
2441
+ total = 0;
2442
+ totalGas() {
2443
+ return this.total;
2444
+ }
2445
+ add(e) {
2446
+ this.total += e;
2447
+ }
2448
+ chargeScopeEntry(e) {
2449
+ this.add(br(this.scopeDepth(e)));
2450
+ }
2451
+ chargeInitialization() {
2452
+ this.add(cr);
2453
+ }
2454
+ chargeChannelMatchAttempt() {
2455
+ this.add(lr);
2456
+ }
2457
+ chargeHandlerOverhead() {
2458
+ this.add(ur);
2459
+ }
2460
+ chargeBoundaryCheck() {
2461
+ this.add(dr);
2462
+ }
2463
+ chargePatchAddOrReplace(e) {
2464
+ this.add(Sr(this.payloadSizeCharge(e)));
2465
+ }
2466
+ chargePatchRemove() {
2467
+ this.add(hr);
2468
+ }
2469
+ chargeCascadeRouting(e) {
2470
+ e > 0 && this.add(Cr(e));
2471
+ }
2472
+ chargeEmitEvent(e) {
2473
+ this.add(kr(this.payloadSizeCharge(e)));
2474
+ }
2475
+ chargeBridge() {
2476
+ this.add(fr);
2477
+ }
2478
+ chargeDrainEvent() {
2479
+ this.add(pr);
2480
+ }
2481
+ chargeCheckpointUpdate() {
2482
+ this.add(mr);
2483
+ }
2484
+ chargeTerminationMarker() {
2485
+ this.add(gr);
2486
+ }
2487
+ chargeLifecycleDelivery() {
2488
+ this.add(Er);
2489
+ }
2490
+ chargeFatalTerminationOverhead() {
2491
+ this.add(wr);
2492
+ }
2493
+ chargeJavaScriptCodeBase(e) {
2494
+ this.add(rr(e));
2495
+ }
2496
+ chargeTriggerEventBase() {
2497
+ this.add(yr);
2498
+ }
2499
+ chargeUpdateDocumentBase(e) {
2500
+ this.add(ir(e));
2501
+ }
2502
+ chargeExpression(e) {
2503
+ this.add(sr(e));
2504
+ }
2505
+ chargeTemplate(e, t) {
2506
+ this.add(or(e, t));
2507
+ }
2508
+ chargeDocumentSnapshot(e, t) {
2509
+ const n = t ? Ee(this.blue, t) : 0;
2510
+ this.add(ar(e, n));
2511
+ }
2512
+ payloadSizeCharge(e) {
2513
+ if (!e)
2514
+ return 0;
2515
+ const t = Ee(this.blue, e);
2516
+ return F(t);
2517
+ }
2518
+ scopeDepth(e) {
2519
+ const t = y(e);
2520
+ if (t === "/" || t.length <= 1)
2521
+ return 0;
2522
+ let n = 1;
2523
+ for (let r = 1; r < t.length; r += 1)
2524
+ t.charAt(r) === "/" && (n += 1);
2525
+ return n;
2526
+ }
2527
+ }
2528
+ class vr {
2529
+ constructor(e, t) {
2530
+ this.documentRef = e, this.blueRef = t, this.patchEngine = new Qn(this.documentRef), this.meter = new Ir(this.blueRef);
2531
+ }
2532
+ patchEngine;
2533
+ emissionRegistry = new tr();
2534
+ meter;
2535
+ runTerminated = !1;
2536
+ document() {
2537
+ return this.documentRef;
2538
+ }
2539
+ scopes() {
2540
+ return this.emissionRegistry.scopes();
2541
+ }
2542
+ scope(e) {
2543
+ return this.emissionRegistry.scope(e);
2544
+ }
2545
+ existingScope(e) {
2546
+ return this.emissionRegistry.existingScope(e);
2547
+ }
2548
+ rootEmissions() {
2549
+ return this.emissionRegistry.rootEmissions();
2550
+ }
2551
+ recordRootEmission(e) {
2552
+ this.emissionRegistry.recordRootEmission(e);
2553
+ }
2554
+ addGas(e) {
2555
+ this.meter.add(e);
2556
+ }
2557
+ blue() {
2558
+ return this.blueRef;
2559
+ }
2560
+ gasMeter() {
2561
+ return this.meter;
2562
+ }
2563
+ totalGas() {
2564
+ return this.meter.totalGas();
2565
+ }
2566
+ isRunTerminated() {
2567
+ return this.runTerminated;
2568
+ }
2569
+ markRunTerminated() {
2570
+ this.runTerminated = !0;
2571
+ }
2572
+ isScopeTerminated(e) {
2573
+ return this.emissionRegistry.isScopeTerminated(e);
2574
+ }
2575
+ directWrite(e, t) {
2576
+ this.patchEngine.directWrite(e, t);
2577
+ }
2578
+ applyPatch(e, t) {
2579
+ return this.patchEngine.applyPatch(e, t);
2580
+ }
2581
+ }
2582
+ const Tr = p["Processing Initialized Marker"], Rr = p["Document Update"];
2583
+ class Pr {
2584
+ constructor(e, t, n, r) {
2585
+ this.contractLoader = e, this.registry = t, this.runtimeRef = new vr(r, n);
2586
+ const i = (o) => ze(this.runtimeRef.blue(), o);
2587
+ this.checkpointManager = new _n(
2588
+ this.runtimeRef,
2589
+ i
2590
+ ), this.terminationService = new Gn(this.runtimeRef), this.channelRunner = new $n(
2591
+ this.runtimeRef,
2592
+ this.checkpointManager,
2593
+ {
2594
+ evaluateChannel: async (o, a, c, l) => this.evaluateChannel(o, a, c, l),
2595
+ isScopeInactive: (o) => this.isScopeInactive(o),
2596
+ createContext: (o, a, c, l) => this.createContext(
2597
+ o,
2598
+ a,
2599
+ c,
2600
+ l,
2601
+ !1
2602
+ ),
2603
+ shouldRunHandler: async (o, a) => {
2604
+ const c = this.registry.lookupHandler(o.blueId());
2605
+ if (!c) {
2606
+ const u = `No processor registered for handler contract ${o.blueId()}`;
2607
+ throw new m(
2608
+ u,
2609
+ g.illegalState(u)
2610
+ );
2611
+ }
2612
+ const l = c.matches;
2613
+ return typeof l != "function" ? !0 : await l.call(c, o.contract(), a);
2614
+ },
2615
+ executeHandler: async (o, a) => this.executeHandler(o, a),
2616
+ canonicalSignature: i
2617
+ }
2618
+ ), this.scopeExecutor = new Hn({
2619
+ runtime: this.runtimeRef,
2620
+ contractLoader: this.contractLoader,
2621
+ channelRunner: this.channelRunner,
2622
+ bundles: this.bundles,
2623
+ hooks: {
2624
+ isScopeInactive: (o) => this.isScopeInactive(o),
2625
+ createContext: (o, a, c, l, u) => this.createContext(
2626
+ o,
2627
+ a,
2628
+ c,
2629
+ l,
2630
+ u ?? !1
2631
+ ),
2632
+ recordLifecycleForBridging: (o, a) => this.recordLifecycleForBridging(o, a),
2633
+ enterFatalTermination: (o, a, c) => this.enterFatalTermination(o, a, c ?? null),
2634
+ fatalReason: (o, a) => o instanceof Error && o.message || a,
2635
+ markCutOff: (o) => this.markCutOff(o)
2636
+ },
2637
+ blueId: (o) => this.runtimeRef.blue().calculateBlueIdSync(o),
2638
+ nodeAt: (o) => this.nodeAt(o),
2639
+ createDocumentUpdateEvent: (o, a) => this.createDocumentUpdateEvent(o, a),
2640
+ matchesDocumentUpdate: (o, a, c) => this.matchesDocumentUpdate(o, a, c)
2641
+ });
2642
+ }
2643
+ runtimeRef;
2644
+ bundles = /* @__PURE__ */ new Map();
2645
+ pendingTerminations = /* @__PURE__ */ new Map();
2646
+ cutOffScopes = /* @__PURE__ */ new Set();
2647
+ checkpointManager;
2648
+ terminationService;
2649
+ channelRunner;
2650
+ scopeExecutor;
2651
+ async initializeScope(e, t) {
2652
+ await this.scopeExecutor.initializeScope(e, t);
2653
+ }
2654
+ loadBundles(e) {
2655
+ this.scopeExecutor.loadBundles(e);
2656
+ }
2657
+ async processExternalEvent(e, t) {
2658
+ await this.scopeExecutor.processExternalEvent(e, t);
2659
+ }
2660
+ async handlePatch(e, t, n, r) {
2661
+ await this.scopeExecutor.handlePatch(
2662
+ e,
2663
+ t,
2664
+ n,
2665
+ r
2666
+ );
2667
+ }
2668
+ createContext(e, t, n, r = !1, i = !1) {
2669
+ return new Mr(
2670
+ this,
2671
+ t,
2672
+ e,
2673
+ n.clone(),
2674
+ r,
2675
+ i
2676
+ );
2677
+ }
2678
+ result() {
2679
+ const e = this.runtimeRef.document().clone(), t = this.runtimeRef.rootEmissions().map((n) => n.clone());
2680
+ return Re.of(
2681
+ e,
2682
+ t,
2683
+ this.runtimeRef.totalGas()
2684
+ );
2685
+ }
2686
+ runtime() {
2687
+ return this.runtimeRef;
2688
+ }
2689
+ bundleForScope(e) {
2690
+ return this.bundles.get(y(e));
2691
+ }
2692
+ isScopeInactive(e) {
2693
+ const t = y(e);
2694
+ return this.cutOffScopes.has(t) || this.pendingTerminations.has(t) || this.runtimeRef.isScopeTerminated(t);
2695
+ }
2696
+ async enterGracefulTermination(e, t, n) {
2697
+ await this.terminate(e, t, "GRACEFUL", n);
2698
+ }
2699
+ async enterFatalTermination(e, t, n) {
2700
+ await this.terminate(e, t, "FATAL", n);
2701
+ }
2702
+ recordPendingTermination(e, t, n) {
2703
+ this.pendingTerminations.set(y(e), { kind: t, reason: n });
2704
+ }
2705
+ clearPendingTermination(e) {
2706
+ this.pendingTerminations.delete(y(e));
2707
+ }
2708
+ async markCutOff(e) {
2709
+ const t = y(e);
2710
+ this.cutOffScopes.add(t) && this.runtimeRef.existingScope(t)?.markCutOff();
2711
+ }
2712
+ async deliverLifecycle(e, t, n, r) {
2713
+ await this.scopeExecutor.deliverLifecycle(
2714
+ e,
2715
+ t,
2716
+ n,
2717
+ r
2718
+ );
2719
+ }
2720
+ async recordLifecycleForBridging(e, t) {
2721
+ this.runtimeRef.scope(e).recordBridgeable(t.clone()), e === "/" && this.runtimeRef.recordRootEmission(t.clone());
2722
+ }
2723
+ normalizeScope(e) {
2724
+ return y(e);
2725
+ }
2726
+ resolvePointer(e, t) {
2727
+ return w(e, t);
2728
+ }
2729
+ async terminate(e, t, n, r) {
2730
+ const i = y(e);
2731
+ this.pendingTerminations.has(i) || this.runtimeRef.isScopeTerminated(i) || (this.pendingTerminations.set(i, { kind: n, reason: r }), await this.terminationService.terminateScope(
2732
+ this,
2733
+ e,
2734
+ t,
2735
+ n,
2736
+ r
2737
+ ));
2738
+ }
2739
+ nodeAt(e) {
2740
+ const t = y(e);
2741
+ return G.nodeAt(this.runtimeRef.document(), t);
2742
+ }
2743
+ async evaluateChannel(e, t, n, r) {
2744
+ const i = this.registry.lookupChannel(e.blueId());
2745
+ if (!i)
2746
+ return { matches: !1 };
2747
+ const o = this.runtimeRef.blue().calculateBlueIdSync(r), a = r.clone(), c = {
2748
+ scopePath: n,
2749
+ blue: this.runtimeRef.blue(),
2750
+ event: a,
2751
+ markers: t.markers(),
2752
+ bindingKey: e.key()
2753
+ };
2754
+ if (!await i.matches(
2755
+ e.contract(),
2756
+ c
2757
+ ))
2758
+ return { matches: !1 };
2759
+ const u = i.channelize, h = u ? u.call(i, e.contract(), c) : void 0;
2760
+ return {
2761
+ matches: !0,
2762
+ eventId: o,
2763
+ eventNode: h ?? a.clone()
2764
+ };
2765
+ }
2766
+ async executeHandler(e, t) {
2767
+ const n = this.registry.lookupHandler(e.blueId());
2768
+ if (!n) {
2769
+ const r = `No processor registered for handler contract ${e.blueId()}`;
2770
+ throw new m(
2771
+ r,
2772
+ g.illegalState(r)
2773
+ );
2774
+ }
2775
+ await n.execute(e.contract(), t);
2776
+ }
2777
+ createDocumentUpdateEvent(e, t) {
2778
+ const n = Pt(t, e.path), r = e.before != null ? e.before.clone() : new d().setValue(null), i = e.after != null ? e.after.clone() : new d().setValue(null), o = new d().setType(
2779
+ new d().setBlueId(Rr)
2780
+ );
2781
+ return o.setProperties({
2782
+ op: new d().setValue(e.op),
2783
+ path: new d().setValue(n),
2784
+ before: r,
2785
+ after: i
2786
+ }), o;
2787
+ }
2788
+ matchesDocumentUpdate(e, t, n) {
2789
+ if (!t || t.length === 0)
2790
+ return !1;
2791
+ const r = b(w(e, t)), i = b(n);
2792
+ return r === "/" || i === r ? !0 : i.startsWith(`${r}/`);
2793
+ }
2794
+ }
2795
+ class G {
2796
+ constructor(e, t, n) {
2797
+ this.contractLoader = e, this.registry = t, this.blue = n;
2798
+ }
2799
+ async initializeDocument(e) {
2800
+ if (this.isInitialized(e))
2801
+ throw new M("Document already initialized");
2802
+ const t = this.createExecution(e.clone());
2803
+ return this.run(e, t, async () => {
2804
+ await t.initializeScope("/", !0);
2805
+ });
2806
+ }
2807
+ async processDocument(e, t) {
2808
+ if (!this.isInitialized(e))
2809
+ throw new M("Document not initialized");
2810
+ const n = this.createExecution(e.clone()), r = t.clone();
2811
+ return this.run(e, n, async () => {
2812
+ n.loadBundles("/"), await n.processExternalEvent("/", r);
2813
+ });
2814
+ }
2815
+ isInitialized(e) {
2816
+ return this.initializationMarker(e) != null;
2817
+ }
2818
+ createExecution(e) {
2819
+ return new Pr(
2820
+ this.contractLoader,
2821
+ this.registry,
2822
+ this.blue,
2823
+ e
2824
+ );
2825
+ }
2826
+ async run(e, t, n) {
2827
+ try {
2828
+ await n();
2829
+ } catch (r) {
2830
+ if (r instanceof ne)
2831
+ return t.result();
2832
+ if (r instanceof W) {
2833
+ const i = e.clone();
2834
+ return Re.capabilityFailure(
2835
+ i,
2836
+ r.message ?? null
2837
+ );
2838
+ }
2839
+ throw r;
2840
+ }
2841
+ return t.result();
2842
+ }
2843
+ initializationMarker(e) {
2844
+ const n = e.getProperties()?.contracts?.getProperties()?.initialized ?? null;
2845
+ if (!n)
2846
+ return null;
2847
+ if (!(n instanceof d))
2848
+ throw new m(
2849
+ "Initialization Marker must be a BlueNode",
2850
+ g.illegalState(
2851
+ "Initialization Marker must be a BlueNode"
2852
+ )
2853
+ );
2854
+ if (n.getType()?.getBlueId() !== Tr)
2855
+ throw new m(
2856
+ "Initialization Marker must declare type 'Processing Initialized Marker'",
2857
+ g.illegalState(
2858
+ "Initialization Marker must declare type 'Processing Initialized Marker'"
2859
+ )
2860
+ );
2861
+ return n;
2862
+ }
2863
+ static nodeAt(e, t) {
2864
+ if (!(e instanceof d))
2865
+ return null;
2866
+ const n = b(t);
2867
+ if (n === "/")
2868
+ return e;
2869
+ const r = n.slice(1).split("/");
2870
+ let i = e;
2871
+ for (const o of r) {
2872
+ if (!i)
2873
+ return null;
2874
+ if (!o)
2875
+ continue;
2876
+ const a = i.getItems();
2877
+ if (a && /^\d+$/.test(o)) {
2878
+ const u = Number.parseInt(o, 10);
2879
+ i = a[u] ?? null;
2880
+ continue;
2881
+ }
2882
+ const c = i.getProperties();
2883
+ if (!c)
2884
+ return null;
2885
+ const l = c[o];
2886
+ if (!(l instanceof d))
2887
+ return null;
2888
+ i = l;
2889
+ }
2890
+ return i;
2891
+ }
2892
+ }
2893
+ class Mr {
2894
+ constructor(e, t, n, r, i, o) {
2895
+ this.execution = e, this.bundle = t, this.scopePathValue = n, this.eventNode = r, this.allowTerminatedWork = i, this.allowReservedMutation = o;
2896
+ }
2897
+ get scopePath() {
2898
+ return this.scopePathValue;
2899
+ }
2900
+ get blue() {
2901
+ return this.execution.runtime().blue();
2902
+ }
2903
+ gasMeter() {
2904
+ return this.execution.runtime().gasMeter();
2905
+ }
2906
+ event() {
2907
+ return this.eventNode;
2908
+ }
2909
+ async applyPatch(e) {
2910
+ this.shouldSkipTerminatedWork() || await this.execution.handlePatch(
2911
+ this.scopePathValue,
2912
+ this.bundle,
2913
+ e,
2914
+ this.allowReservedMutation
2915
+ );
2916
+ }
2917
+ emitEvent(e) {
2918
+ if (this.shouldSkipTerminatedWork())
2919
+ return;
2920
+ const t = this.execution.runtime(), n = t.scope(this.scopePathValue);
2921
+ t.gasMeter().chargeEmitEvent(e);
2922
+ const r = e.clone();
2923
+ n.enqueueTriggered(r), n.recordBridgeable(r.clone()), this.scopePathValue === "/" && t.recordRootEmission(r.clone());
2924
+ }
2925
+ consumeGas(e) {
2926
+ this.shouldSkipTerminatedWork() || this.execution.runtime().addGas(e);
2927
+ }
2928
+ throwFatal(e) {
2929
+ throw new m(e, g.runtimeFatal(e));
2930
+ }
2931
+ resolvePointer(e) {
2932
+ return this.execution.resolvePointer(this.scopePathValue, e);
2933
+ }
2934
+ documentAt(e) {
2935
+ if (!e)
2936
+ return null;
2937
+ try {
2938
+ const t = this.documentNodeAt(e);
2939
+ return t ? t.clone() : null;
2940
+ } catch {
2941
+ return null;
2942
+ }
2943
+ }
2944
+ documentContains(e) {
2945
+ if (!e)
2946
+ return !1;
2947
+ try {
2948
+ return G.nodeAt(
2949
+ this.execution.runtime().document(),
2950
+ e
2951
+ ) != null;
2952
+ } catch {
2953
+ return !1;
2954
+ }
2955
+ }
2956
+ documentNodeAt(e) {
2957
+ const t = G.nodeAt(
2958
+ this.execution.runtime().document(),
2959
+ e
2960
+ );
2961
+ return t instanceof d ? t : null;
2962
+ }
2963
+ async terminateGracefully(e) {
2964
+ await this.execution.enterGracefulTermination(
2965
+ this.scopePathValue,
2966
+ this.bundle,
2967
+ e ?? null
2968
+ );
2969
+ }
2970
+ async terminateFatally(e) {
2971
+ await this.execution.enterFatalTermination(
2972
+ this.scopePathValue,
2973
+ this.bundle,
2974
+ e ?? null
2975
+ );
2976
+ }
2977
+ shouldSkipTerminatedWork() {
2978
+ return !this.allowTerminatedWork && this.execution.isScopeInactive(this.scopePathValue);
2979
+ }
2980
+ }
2981
+ const Nr = new ht({
2982
+ repositories: [lt, gt, wt]
2983
+ });
2984
+ class Ar {
2985
+ blue;
2986
+ registryRef;
2987
+ contractLoaderRef;
2988
+ engine;
2989
+ constructor(e) {
2990
+ this.registryRef = e?.registry ?? J.create().registerDefaults().build(), this.blue = e?.blue ?? Nr, this.contractLoaderRef = new An(this.registryRef, this.blue), this.engine = new G(
2991
+ this.contractLoaderRef,
2992
+ this.registryRef,
2993
+ this.blue
2994
+ );
2995
+ }
2996
+ registerContractProcessor(e) {
2997
+ return this.registryRef.register(e), this;
2998
+ }
2999
+ async initializeDocument(e) {
3000
+ return this.engine.initializeDocument(e);
3001
+ }
3002
+ async processDocument(e, t) {
3003
+ return this.engine.processDocument(e, t);
3004
+ }
3005
+ markersFor(e, t) {
3006
+ return this.contractLoaderRef.load(e, t).markers();
3007
+ }
3008
+ isInitialized(e) {
3009
+ return this.engine.isInitialized(e);
3010
+ }
3011
+ getContractRegistry() {
3012
+ return this.registryRef;
3013
+ }
3014
+ /** @internal */
3015
+ registry() {
3016
+ return this.registryRef;
3017
+ }
3018
+ /** @internal */
3019
+ contractLoader() {
3020
+ return this.contractLoaderRef;
3021
+ }
3022
+ static builder() {
3023
+ return new Dr();
3024
+ }
3025
+ }
3026
+ class Dr {
3027
+ contractRegistry;
3028
+ blueInstance;
3029
+ constructor() {
3030
+ this.contractRegistry = J.create().registerDefaults().build();
3031
+ }
3032
+ withRegistry(e) {
3033
+ return this.contractRegistry = e, this;
3034
+ }
3035
+ registerDefaults() {
3036
+ return this;
3037
+ }
3038
+ withBlue(e) {
3039
+ return this.blueInstance = e, this;
3040
+ }
3041
+ build() {
3042
+ return new Ar({
3043
+ registry: this.contractRegistry,
3044
+ blue: this.blueInstance
3045
+ });
3046
+ }
3047
+ }
3048
+ class je {
3049
+ process(e, t) {
3050
+ const n = t.getValue();
3051
+ if (H(n)) {
3052
+ const r = t.clone();
3053
+ return r.setValue(n), r.setProperties(void 0), r.setItems(void 0), r.setType(void 0), r;
3054
+ }
3055
+ return e;
3056
+ }
3057
+ /**
3058
+ * Post-process to ensure expressions aren't overridden by subsequent processors
3059
+ */
3060
+ postProcess(e, t) {
3061
+ const n = t.getValue();
3062
+ if (H(n) && e.getValue() !== n && n !== void 0) {
3063
+ const r = e.clone();
3064
+ return r.setValue(n), r;
3065
+ }
3066
+ return e;
3067
+ }
3068
+ }
3069
+ const ei = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
3070
+ __proto__: null,
3071
+ ExpressionPreserver: je
3072
+ }, Symbol.toStringTag, { value: "Module" }));
3073
+ function ti() {
3074
+ return new v.SequentialMergingProcessor([
3075
+ new v.ValuePropagator(),
3076
+ new je(),
3077
+ new v.TypeAssigner(),
3078
+ new v.ListProcessor(),
3079
+ new v.DictionaryProcessor(),
3080
+ new v.BasicTypesVerifier()
3081
+ ]);
3082
+ }
3083
+ export {
3084
+ wn as ChannelBinding,
3085
+ $n as ChannelRunner,
3086
+ _n as CheckpointManager,
3087
+ Ln as CheckpointRecord,
3088
+ Fe as CodeBlockEvaluationError,
3089
+ N as ContractBundle,
3090
+ Sn as ContractBundleBuilder,
3091
+ An as ContractLoader,
3092
+ rn as ContractProcessorRegistry,
3093
+ J as ContractProcessorRegistryBuilder,
3094
+ Re as DocumentProcessingResult,
3095
+ vr as DocumentProcessingRuntime,
3096
+ Ar as DocumentProcessor,
3097
+ Dr as DocumentProcessorBuilder,
3098
+ tr as EmissionRegistry,
3099
+ Ir as GasMeter,
3100
+ bn as HandlerBinding,
3101
+ k as KEY_CHECKPOINT,
3102
+ Pe as KEY_EMBEDDED,
3103
+ Me as KEY_INITIALIZED,
3104
+ Ne as KEY_TERMINATED,
3105
+ ei as MergingProcessors,
3106
+ Ae as PROCESSOR_MANAGED_CHANNEL_BLUE_IDS,
3107
+ Qn as PatchEngine,
3108
+ jr as ProcessorContractConstants,
3109
+ G as ProcessorEngine,
3110
+ g as ProcessorErrors,
3111
+ Pr as ProcessorExecution,
3112
+ Mr as ProcessorExecutionContext,
3113
+ m as ProcessorFatalError,
3114
+ Qr as ProcessorPointerConstants,
3115
+ se as QuickJSEvaluator,
3116
+ Oe as RELATIVE_CHECKPOINT,
3117
+ A as RELATIVE_CONTRACTS,
3118
+ Rt as RELATIVE_EMBEDDED,
3119
+ ee as RELATIVE_INITIALIZED,
3120
+ De as RELATIVE_TERMINATED,
3121
+ re as RESERVED_CONTRACT_KEYS,
3122
+ ne as RunTerminationError,
3123
+ Hn as ScopeExecutor,
3124
+ er as ScopeRuntimeContext,
3125
+ Gn as TerminationService,
3126
+ Wr as andThen,
3127
+ ze as canonicalSignature,
3128
+ Ee as canonicalSize,
3129
+ D as channelContractBaseSchema,
3130
+ jt as channelEventCheckpointSchema,
3131
+ zt as containsExpression,
3132
+ oe as contractBaseSchema,
3133
+ ti as createDefaultMergingProcessor,
3134
+ Ke as createPicomatchShouldResolve,
3135
+ Ht as documentUpdateChannelSchema,
3136
+ Kt as embeddedNodeChannelSchema,
3137
+ St as err,
3138
+ He as evaluateQuickJSExpression,
3139
+ Ft as extractExpressionContent,
3140
+ We as handlerContractBaseSchema,
3141
+ Qt as initializationMarkerSchema,
3142
+ Vr as isErr,
3143
+ H as isExpression,
3144
+ Ur as isOk,
3145
+ ie as isProcessorManagedChannelBlueId,
3146
+ Tt as isReservedContractKey,
3147
+ Yr as joinRelativePointers,
3148
+ Zr as jsonPatchSchema,
3149
+ Wt as lifecycleChannelSchema,
3150
+ Hr as map,
3151
+ Kr as mapErr,
3152
+ z as markerContractBaseSchema,
3153
+ Jr as match,
3154
+ Jt as myosTimelineChannelSchema,
3155
+ b as normalizePointer,
3156
+ y as normalizeScope,
3157
+ bt as ok,
3158
+ Xt as operationMarkerSchema,
3159
+ Yt as processEmbeddedMarkerSchema,
3160
+ Zt as processingTerminatedMarkerSchema,
3161
+ _e as relativeCheckpointLastEvent,
3162
+ $e as relativeCheckpointLastSignature,
3163
+ q as relativeContractsEntry,
3164
+ Pt as relativizePointer,
3165
+ K as resolveNodeExpressions,
3166
+ w as resolvePointer,
3167
+ Ut as resolveTemplateString,
3168
+ tn as sequentialWorkflowOperationSchema,
3169
+ en as sequentialWorkflowSchema,
3170
+ Xr as sequentialWorkflowStepSchema,
3171
+ me as stripSlashes,
3172
+ qt as timelineChannelSchema,
3173
+ Gt as triggeredEventChannelSchema,
3174
+ Gr as unwrapOr,
3175
+ qr as unwrapOrElse
3176
+ };