@blue-labs/document-processor 1.21.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 (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +11 -0
  3. package/dist/BlueDocumentProcessor.d.ts +54 -0
  4. package/dist/BlueDocumentProcessor.d.ts.map +1 -0
  5. package/dist/config.d.ts +3 -0
  6. package/dist/config.d.ts.map +1 -0
  7. package/dist/context.d.ts +21 -0
  8. package/dist/context.d.ts.map +1 -0
  9. package/dist/index.d.ts +4 -0
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/index.js +8 -0
  12. package/dist/index.mjs +1557 -0
  13. package/dist/processors/BaseChannelProcessor.d.ts +27 -0
  14. package/dist/processors/BaseChannelProcessor.d.ts.map +1 -0
  15. package/dist/processors/ChannelEventCheckpointProcessor.d.ts +13 -0
  16. package/dist/processors/ChannelEventCheckpointProcessor.d.ts.map +1 -0
  17. package/dist/processors/CompositeTimelineChannelProcessor.d.ts +9 -0
  18. package/dist/processors/CompositeTimelineChannelProcessor.d.ts.map +1 -0
  19. package/dist/processors/DocumentUpdateChannelProcessor.d.ts +9 -0
  20. package/dist/processors/DocumentUpdateChannelProcessor.d.ts.map +1 -0
  21. package/dist/processors/EmbeddedNodeChannelProcessor.d.ts +9 -0
  22. package/dist/processors/EmbeddedNodeChannelProcessor.d.ts.map +1 -0
  23. package/dist/processors/MyOSAgentChannelProcessor.d.ts +60 -0
  24. package/dist/processors/MyOSAgentChannelProcessor.d.ts.map +1 -0
  25. package/dist/processors/MyOSTimelineChannelProcessor.d.ts +9 -0
  26. package/dist/processors/MyOSTimelineChannelProcessor.d.ts.map +1 -0
  27. package/dist/processors/OperationProcessor.d.ts +11 -0
  28. package/dist/processors/OperationProcessor.d.ts.map +1 -0
  29. package/dist/processors/ProcessEmbeddedProcessor.d.ts +10 -0
  30. package/dist/processors/ProcessEmbeddedProcessor.d.ts.map +1 -0
  31. package/dist/processors/SequentialWorkflowOperationProcessor.d.ts +12 -0
  32. package/dist/processors/SequentialWorkflowOperationProcessor.d.ts.map +1 -0
  33. package/dist/processors/SequentialWorkflowProcessor/SequentialWorkflowProcessor.d.ts +15 -0
  34. package/dist/processors/SequentialWorkflowProcessor/SequentialWorkflowProcessor.d.ts.map +1 -0
  35. package/dist/processors/SequentialWorkflowProcessor/index.d.ts +2 -0
  36. package/dist/processors/SequentialWorkflowProcessor/index.d.ts.map +1 -0
  37. package/dist/processors/SequentialWorkflowProcessor/steps/JavaScriptCodeExecutor.d.ts +8 -0
  38. package/dist/processors/SequentialWorkflowProcessor/steps/JavaScriptCodeExecutor.d.ts.map +1 -0
  39. package/dist/processors/SequentialWorkflowProcessor/steps/TriggerEventExecutor.d.ts +8 -0
  40. package/dist/processors/SequentialWorkflowProcessor/steps/TriggerEventExecutor.d.ts.map +1 -0
  41. package/dist/processors/SequentialWorkflowProcessor/steps/UpdateDocumentExecutor.d.ts +12 -0
  42. package/dist/processors/SequentialWorkflowProcessor/steps/UpdateDocumentExecutor.d.ts.map +1 -0
  43. package/dist/processors/SequentialWorkflowProcessor/types.d.ts +7 -0
  44. package/dist/processors/SequentialWorkflowProcessor/types.d.ts.map +1 -0
  45. package/dist/processors/SequentialWorkflowProcessor/utils/BindingsFactory.d.ts +12 -0
  46. package/dist/processors/SequentialWorkflowProcessor/utils/BindingsFactory.d.ts.map +1 -0
  47. package/dist/processors/SequentialWorkflowProcessor/utils/ExpressionEvaluator.d.ts +59 -0
  48. package/dist/processors/SequentialWorkflowProcessor/utils/ExpressionEvaluator.d.ts.map +1 -0
  49. package/dist/processors/TimelineChannelProcessor.d.ts +9 -0
  50. package/dist/processors/TimelineChannelProcessor.d.ts.map +1 -0
  51. package/dist/processors/index.d.ts +12 -0
  52. package/dist/processors/index.d.ts.map +1 -0
  53. package/dist/queue/TaskKey.d.ts +22 -0
  54. package/dist/queue/TaskKey.d.ts.map +1 -0
  55. package/dist/queue/TaskQueue.d.ts +31 -0
  56. package/dist/queue/TaskQueue.d.ts.map +1 -0
  57. package/dist/registry/ContractRegistry.d.ts +47 -0
  58. package/dist/registry/ContractRegistry.d.ts.map +1 -0
  59. package/dist/repo/core/blue-ids/index.d.ts +21 -0
  60. package/dist/repo/core/blue-ids/index.d.ts.map +1 -0
  61. package/dist/repo/core/index.d.ts +199 -0
  62. package/dist/repo/core/index.d.ts.map +1 -0
  63. package/dist/repo/core/schema/Channel.d.ts +13 -0
  64. package/dist/repo/core/schema/Channel.d.ts.map +1 -0
  65. package/dist/repo/core/schema/CompositeTimelineChannel.d.ts +17 -0
  66. package/dist/repo/core/schema/CompositeTimelineChannel.d.ts.map +1 -0
  67. package/dist/repo/core/schema/DocumentUpdateChannel.d.ts +17 -0
  68. package/dist/repo/core/schema/DocumentUpdateChannel.d.ts.map +1 -0
  69. package/dist/repo/core/schema/EmbeddedNodeChannel.d.ts +17 -0
  70. package/dist/repo/core/schema/EmbeddedNodeChannel.d.ts.map +1 -0
  71. package/dist/repo/core/schema/JavaScriptCode.d.ts +10 -0
  72. package/dist/repo/core/schema/JavaScriptCode.d.ts.map +1 -0
  73. package/dist/repo/core/schema/JsonPatchEntry.d.ts +22 -0
  74. package/dist/repo/core/schema/JsonPatchEntry.d.ts.map +1 -0
  75. package/dist/repo/core/schema/Operation.d.ts +16 -0
  76. package/dist/repo/core/schema/Operation.d.ts.map +1 -0
  77. package/dist/repo/core/schema/OperationRequest.d.ts +29 -0
  78. package/dist/repo/core/schema/OperationRequest.d.ts.map +1 -0
  79. package/dist/repo/core/schema/ProcessEmbedded.d.ts +10 -0
  80. package/dist/repo/core/schema/ProcessEmbedded.d.ts.map +1 -0
  81. package/dist/repo/core/schema/SequentialWorkflow.d.ts +13 -0
  82. package/dist/repo/core/schema/SequentialWorkflow.d.ts.map +1 -0
  83. package/dist/repo/core/schema/SequentialWorkflowOperation.d.ts +15 -0
  84. package/dist/repo/core/schema/SequentialWorkflowOperation.d.ts.map +1 -0
  85. package/dist/repo/core/schema/SequentialWorkflowStep.d.ts +13 -0
  86. package/dist/repo/core/schema/SequentialWorkflowStep.d.ts.map +1 -0
  87. package/dist/repo/core/schema/TimelineChannel.d.ts +17 -0
  88. package/dist/repo/core/schema/TimelineChannel.d.ts.map +1 -0
  89. package/dist/repo/core/schema/TimelineEntry.d.ts +25 -0
  90. package/dist/repo/core/schema/TimelineEntry.d.ts.map +1 -0
  91. package/dist/repo/core/schema/TriggerEvent.d.ts +10 -0
  92. package/dist/repo/core/schema/TriggerEvent.d.ts.map +1 -0
  93. package/dist/repo/core/schema/UpdateDocument.d.ts +40 -0
  94. package/dist/repo/core/schema/UpdateDocument.d.ts.map +1 -0
  95. package/dist/repo/core/schema/index.d.ts +15 -0
  96. package/dist/repo/core/schema/index.d.ts.map +1 -0
  97. package/dist/repo/myos/blue-ids/index.d.ts +8 -0
  98. package/dist/repo/myos/blue-ids/index.d.ts.map +1 -0
  99. package/dist/repo/myos/index.d.ts +101 -0
  100. package/dist/repo/myos/index.d.ts.map +1 -0
  101. package/dist/repo/myos/schema/MyOSAgent.d.ts +10 -0
  102. package/dist/repo/myos/schema/MyOSAgent.d.ts.map +1 -0
  103. package/dist/repo/myos/schema/MyOSAgentChannel.d.ts +30 -0
  104. package/dist/repo/myos/schema/MyOSAgentChannel.d.ts.map +1 -0
  105. package/dist/repo/myos/schema/MyOSAgentEvent.d.ts +19 -0
  106. package/dist/repo/myos/schema/MyOSAgentEvent.d.ts.map +1 -0
  107. package/dist/repo/myos/schema/MyOSTimelineChannel.d.ts +24 -0
  108. package/dist/repo/myos/schema/MyOSTimelineChannel.d.ts.map +1 -0
  109. package/dist/repo/myos/schema/MyOSTimelineEntry.d.ts +32 -0
  110. package/dist/repo/myos/schema/MyOSTimelineEntry.d.ts.map +1 -0
  111. package/dist/repo/myos/schema/index.d.ts +6 -0
  112. package/dist/repo/myos/schema/index.d.ts.map +1 -0
  113. package/dist/routing/EventRouter.d.ts +51 -0
  114. package/dist/routing/EventRouter.d.ts.map +1 -0
  115. package/dist/types.d.ts +86 -0
  116. package/dist/types.d.ts.map +1 -0
  117. package/dist/utils/CheckpointCache.d.ts +10 -0
  118. package/dist/utils/CheckpointCache.d.ts.map +1 -0
  119. package/dist/utils/EventTraceManager.d.ts +46 -0
  120. package/dist/utils/EventTraceManager.d.ts.map +1 -0
  121. package/dist/utils/TinyQueue.d.ts +12 -0
  122. package/dist/utils/TinyQueue.d.ts.map +1 -0
  123. package/dist/utils/checkpoint.d.ts +4 -0
  124. package/dist/utils/checkpoint.d.ts.map +1 -0
  125. package/dist/utils/document.d.ts +19 -0
  126. package/dist/utils/document.d.ts.map +1 -0
  127. package/dist/utils/exceptions.d.ts +28 -0
  128. package/dist/utils/exceptions.d.ts.map +1 -0
  129. package/dist/utils/fetchText.d.ts +2 -0
  130. package/dist/utils/fetchText.d.ts.map +1 -0
  131. package/dist/utils/logPatchError.d.ts +3 -0
  132. package/dist/utils/logPatchError.d.ts.map +1 -0
  133. package/dist/utils/path.d.ts +2 -0
  134. package/dist/utils/path.d.ts.map +1 -0
  135. package/dist/utils/typeGuard.d.ts +5 -0
  136. package/dist/utils/typeGuard.d.ts.map +1 -0
  137. package/package.json +44 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,1557 @@
1
+ var he = Object.defineProperty;
2
+ var de = (i, e, t) => e in i ? he(i, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[e] = t;
3
+ var l = (i, e, t) => de(i, typeof e != "symbol" ? e + "" : e, t);
4
+ import { z as u } from "zod";
5
+ import { withTypeBlueId as m, blueNodeField as k, applyBlueNodePatch as pe, BlueNodeTypeSchema as P, BlueNode as me, isBigNumber as z } from "@blue-labs/language";
6
+ import { deepFreeze as X, isNonNullable as D, deepContains as fe } from "@blue-labs/shared-utils";
7
+ const ge = (i, e) => ({
8
+ on: (t, n) => ({ end: () => n(null) })
9
+ });
10
+ async function ye(i) {
11
+ return new Promise((e, t) => {
12
+ ge().on("error", t).end();
13
+ });
14
+ }
15
+ const S = (...i) => i.map((e, t) => {
16
+ if (typeof e != "string") return "";
17
+ if (t === 0 && e === "/") return "/";
18
+ const n = t > 0 ? e.replace(/^\/+/, "") : e;
19
+ return t < i.length - 1 ? n.replace(/\/+$/, "") : n;
20
+ }).filter(Boolean).join("/").replace(/\/{2,}/g, "/");
21
+ class Y {
22
+ constructor(e, t, n, o) {
23
+ l(this, "actions", []);
24
+ this.getDocument = e, this.taskInfo = t, this.blue = n, this.onFlush = o;
25
+ }
26
+ get(e) {
27
+ const t = this.getDocument(), n = S(this.taskInfo.nodePath, e);
28
+ return t.get(n);
29
+ }
30
+ addPatch(e) {
31
+ this.actions.push({
32
+ kind: "patch",
33
+ patch: {
34
+ ...e,
35
+ path: S(this.taskInfo.nodePath, e.path)
36
+ }
37
+ });
38
+ }
39
+ emitEvent(e) {
40
+ const t = this.taskInfo.event, n = t.trace ?? [], o = {
41
+ ...e,
42
+ originNodePath: e.originNodePath ?? this.taskInfo.nodePath,
43
+ rootEvent: e.rootEvent ?? t.rootEvent ?? t,
44
+ trace: [...n]
45
+ };
46
+ this.actions.push({ kind: "event", event: o });
47
+ }
48
+ async flush() {
49
+ var t;
50
+ if (!this.actions.length) return [];
51
+ const e = [...this.actions];
52
+ return this.actions.length = 0, await ((t = this.onFlush) == null ? void 0 : t.call(this, e)), e;
53
+ }
54
+ getNodePath() {
55
+ return this.taskInfo.nodePath;
56
+ }
57
+ resolvePath(e) {
58
+ return S(this.taskInfo.nodePath, e);
59
+ }
60
+ getTaskInfo() {
61
+ return this.taskInfo;
62
+ }
63
+ getBlue() {
64
+ return this.blue;
65
+ }
66
+ /* TODO: Move to a separate interface */
67
+ loadExternalModule(e) {
68
+ if (!/^https?:\/\//.test(e))
69
+ throw new Error("Only http/https URLs are allowed");
70
+ return ye();
71
+ }
72
+ loadBlueContent(e) {
73
+ throw new Error("Not implemented");
74
+ }
75
+ }
76
+ class G extends Error {
77
+ constructor(e, t) {
78
+ super(`Cannot apply patch ${JSON.stringify(e)}`), this.patch = e, this.cause = t, this.name = "PatchApplicationError";
79
+ }
80
+ }
81
+ class ee extends Error {
82
+ constructor(e, t, n) {
83
+ super(
84
+ `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}")`
85
+ ), this.patch = e, this.offendingPath = t, this.contractNodePath = n, this.name = "EmbeddedDocumentModificationError";
86
+ }
87
+ }
88
+ class W extends Error {
89
+ constructor(e, t) {
90
+ super(`Failed to evaluate expression "${e}"`), this.code = e, this.cause = t, this.name = "ExpressionEvaluationError";
91
+ }
92
+ }
93
+ class Q extends Error {
94
+ constructor(e, t) {
95
+ super(`Failed to evaluate code block "${e}"`), this.code = e, this.cause = t, this.name = "CodeBlockEvaluationError";
96
+ }
97
+ }
98
+ const p = {
99
+ Channel: "2RMkKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc",
100
+ "Timeline Channel": "RMkKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc2",
101
+ "Composite Timeline Channel": "qxkh3uMkKoutP5DxZ7dr6Eo27B7fuxQCS1VAptiCPc2R",
102
+ "Sequential Workflow": "h3uDxZ7dr6Eo27B7fuxMkKoutP5qxkQCS1VAptiCPc2R",
103
+ "Process Embedded": "DxZ7dr6EoMkKoutP5qxkh3u27B7fuxQCS1VAptiCPc2R",
104
+ "Embedded Node Channel": "MkKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc2",
105
+ "Document Update Channel": "MkKoutP5qxkh3uDQCS1VAptiCPc2xZ7dr6Eo27B7fux",
106
+ "Channel Event Checkpoint": "o27B7fuxMkKoutPh3uDxZ7dr6E5qxkQCS1VAptiCPc2R",
107
+ "Update Document": "7fuxMkKoutPh3uDxZ7dr6E5qxkQCS1VAptiCPc2R",
108
+ "Trigger Event": "kQCS1VAp7fuxMkKoutPh3uDxZ7dr6E5qxtiCPc2R",
109
+ "Json Patch Entry": "EnUQeMiMa2wHFW3JbeSPvdgfpL6qZYCR29m3SfeHsKSY",
110
+ "JavaScript Code": "MkKoutPDxZ7dr6Eo5qxkh3u27B7fuxQCS1VAptiCPc2R",
111
+ "Timeline Entry": "uDxZ7dr6Eo27B7fMkKoutP5qxkh3uxQCS1VAptiCPc2R",
112
+ Operation: "OpKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc2R",
113
+ "Sequential Workflow Operation": "SeqOpKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiC",
114
+ "Operation Request": "OpReqKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiC"
115
+ }, N = m(p.Channel)(
116
+ u.object({
117
+ name: u.string().optional(),
118
+ description: u.string().optional()
119
+ })
120
+ ), Ee = m(
121
+ p["Composite Timeline Channel"]
122
+ )(
123
+ N.extend({
124
+ channels: u.array(u.string()).optional()
125
+ })
126
+ ), Ce = m(
127
+ p["Document Update Channel"]
128
+ )(
129
+ N.extend({
130
+ path: u.string().optional()
131
+ })
132
+ ), K = m(
133
+ p["Embedded Node Channel"]
134
+ )(
135
+ N.extend({
136
+ path: u.string().optional()
137
+ })
138
+ ), M = m(p["JavaScript Code"])(
139
+ u.object({
140
+ code: u.string().optional()
141
+ })
142
+ ), we = m(p.Operation)(
143
+ u.object({
144
+ request: k().optional(),
145
+ description: u.string().optional(),
146
+ channel: u.string().optional()
147
+ })
148
+ ), ve = m(
149
+ p["Operation Request"]
150
+ )(
151
+ u.object({
152
+ operation: u.string().optional(),
153
+ request: k(),
154
+ document: u.object({
155
+ blueId: u.string().optional()
156
+ }).optional(),
157
+ allowNewerVersion: u.boolean().optional()
158
+ })
159
+ ), $ = m(
160
+ p["Process Embedded"]
161
+ )(
162
+ u.object({
163
+ paths: u.array(u.string()).optional()
164
+ })
165
+ ), j = m(
166
+ p["Sequential Workflow"]
167
+ )(
168
+ u.object({
169
+ steps: u.array(k()).optional(),
170
+ channel: u.string().optional()
171
+ })
172
+ ), Se = m(
173
+ p["Sequential Workflow Operation"]
174
+ )(
175
+ j.omit({
176
+ channel: !0
177
+ }).extend({
178
+ operation: u.string().optional()
179
+ })
180
+ ), te = m(
181
+ p["Timeline Channel"]
182
+ )(
183
+ N.extend({
184
+ timelineId: u.string().optional()
185
+ })
186
+ ), I = m(p["Timeline Entry"])(
187
+ u.object({
188
+ timelineId: u.string().optional(),
189
+ timelinePrev: u.string().optional(),
190
+ thread: u.string().optional(),
191
+ threadPrev: u.string().optional(),
192
+ message: k().optional(),
193
+ signature: u.string().optional()
194
+ })
195
+ ), q = m(p["Trigger Event"])(
196
+ u.object({
197
+ event: k()
198
+ })
199
+ ), Pe = m(p["Json Patch Entry"])(
200
+ u.object({
201
+ name: u.string().optional(),
202
+ description: u.string().optional(),
203
+ val: k().optional(),
204
+ op: u.string().optional(),
205
+ path: u.string().optional()
206
+ })
207
+ ), A = m(p["Update Document"])(
208
+ u.object({
209
+ changeset: u.array(Pe)
210
+ })
211
+ );
212
+ function V(i, e, t = "/", n = []) {
213
+ const o = i.getContracts() ?? {};
214
+ for (const [a, r] of Object.entries(o))
215
+ if (P.isTypeOf(
216
+ r,
217
+ $
218
+ )) {
219
+ const h = e.nodeToSchemaOutput(
220
+ r,
221
+ $
222
+ ).paths ?? [];
223
+ for (const d of h)
224
+ n.push({
225
+ absPath: S(t, d),
226
+ contractPath: S(t, `contracts/${a}`)
227
+ });
228
+ }
229
+ for (const [a, r] of Object.entries(i.getProperties() ?? {}))
230
+ V(r, e, S(t, a), n);
231
+ return n;
232
+ }
233
+ function F(i, e) {
234
+ return i === e || i.startsWith(e.endsWith("/") ? e : e + "/");
235
+ }
236
+ function U(i, e) {
237
+ if (!e.length) return i;
238
+ let t = i.clone();
239
+ for (const n of e)
240
+ try {
241
+ t = pe(t, n, !0);
242
+ } catch (o) {
243
+ throw new G(n, o);
244
+ }
245
+ return X(t);
246
+ }
247
+ function y(i) {
248
+ return i != null;
249
+ }
250
+ function x(i) {
251
+ return i instanceof me;
252
+ }
253
+ class ke {
254
+ constructor(e = [], t = (n, o) => n < o ? -1 : n > o ? 1 : 0) {
255
+ l(this, "data");
256
+ l(this, "length");
257
+ l(this, "compare");
258
+ if (this.data = e, this.length = this.data.length, this.compare = t, this.length > 0)
259
+ for (let n = (this.length >> 1) - 1; n >= 0; n--) this._down(n);
260
+ }
261
+ push(e) {
262
+ this.data.push(e), this._up(this.length++);
263
+ }
264
+ pop() {
265
+ if (this.length === 0) return;
266
+ const e = this.data[0], t = this.data.pop();
267
+ return --this.length > 0 && (this.data[0] = t, this._down(0)), e;
268
+ }
269
+ peek() {
270
+ return this.data[0];
271
+ }
272
+ _up(e) {
273
+ const { data: t, compare: n } = this, o = t[e];
274
+ for (; e > 0; ) {
275
+ const a = e - 1 >> 1, r = t[a];
276
+ if (n(o, r) >= 0) break;
277
+ t[e] = r, e = a;
278
+ }
279
+ t[e] = o;
280
+ }
281
+ _down(e) {
282
+ const { data: t, compare: n } = this, o = this.length >> 1, a = t[e];
283
+ for (; e < o; ) {
284
+ let r = (e << 1) + 1;
285
+ const s = r + 1;
286
+ if (s < this.length && n(t[s], t[r]) < 0 && (r = s), n(t[r], a) >= 0) break;
287
+ t[e] = t[r], e = r;
288
+ }
289
+ t[e] = a;
290
+ }
291
+ }
292
+ const be = (i, e, t, n, o, a) => [
293
+ -i,
294
+ e,
295
+ t,
296
+ n,
297
+ o,
298
+ a
299
+ ], Te = (i, e) => {
300
+ for (let t = 0; t < i.key.length; t++) {
301
+ const n = i.key[t], o = e.key[t];
302
+ if (n !== o)
303
+ return typeof n == "number" && typeof o == "number" ? n - o : typeof n == "string" && typeof o == "string" ? n.localeCompare(o) : 0;
304
+ }
305
+ return 0;
306
+ };
307
+ class Oe {
308
+ /**
309
+ * Creates a new task queue with the task key comparator
310
+ */
311
+ constructor() {
312
+ l(this, "queue");
313
+ this.queue = new ke([], Te);
314
+ }
315
+ /**
316
+ * Adds a task to the queue
317
+ *
318
+ * @param task - The task to add
319
+ */
320
+ push(e) {
321
+ this.queue.push(e);
322
+ }
323
+ /**
324
+ * Removes and returns the highest priority task
325
+ *
326
+ * @returns The highest priority task or undefined if queue is empty
327
+ */
328
+ pop() {
329
+ return this.queue.pop();
330
+ }
331
+ /**
332
+ * Gets the number of tasks in the queue
333
+ */
334
+ get length() {
335
+ return this.queue.length;
336
+ }
337
+ }
338
+ class Be {
339
+ /**
340
+ * Creates a new contract registry
341
+ *
342
+ * @param list - Initial list of processors to register
343
+ */
344
+ constructor(e = []) {
345
+ l(this, "processors", /* @__PURE__ */ new Map());
346
+ l(this, "typeOrder", /* @__PURE__ */ new Map());
347
+ e.forEach((t, n) => this.register(t, n));
348
+ }
349
+ /**
350
+ * Registers a new contract processor
351
+ *
352
+ * @param proc - The processor to register
353
+ * @param orderHint - Optional priority value for execution order
354
+ * @throws Error if a processor for the same contract type is already registered
355
+ */
356
+ register(e, t) {
357
+ if (this.processors.has(e.contractBlueId))
358
+ throw new Error(`Processor for ${e.contractType} already registered`);
359
+ this.processors.set(e.contractBlueId, e), this.typeOrder.has(e.contractBlueId) || this.typeOrder.set(e.contractBlueId, t ?? this.typeOrder.size);
360
+ }
361
+ /**
362
+ * Gets a processor by contract type node
363
+ *
364
+ * @param typeNode - The contract type node
365
+ * @returns The associated processor or undefined
366
+ */
367
+ get(e) {
368
+ if (!e) return;
369
+ const t = e.getBlueId();
370
+ if (t)
371
+ return this.processors.get(t);
372
+ }
373
+ /**
374
+ * Gets the order priority for a contract type node
375
+ *
376
+ * @param typeNode - The contract type node
377
+ * @returns The priority value (0 if not found)
378
+ */
379
+ orderOf(e) {
380
+ if (!e) return 0;
381
+ const t = e.getBlueId();
382
+ return t ? this.typeOrder.get(t) ?? 0 : 0;
383
+ }
384
+ /**
385
+ * Gets all registered processors
386
+ *
387
+ * @returns Iterator of all registered processors
388
+ */
389
+ values() {
390
+ return this.processors.values();
391
+ }
392
+ }
393
+ class xe {
394
+ constructor() {
395
+ l(this, "isEnabled");
396
+ this.isEnabled = process.env.TRACE_BLUE_ENABLED === "true";
397
+ }
398
+ /**
399
+ * Creates a hop entry for the trace
400
+ * @param nodePath - The path to the node
401
+ * @param contractName - The name of the contract
402
+ * @returns A formatted hop string
403
+ */
404
+ makeHop(e, t) {
405
+ return `${e}#${t}`;
406
+ }
407
+ /**
408
+ * Checks if tracing is enabled
409
+ * @returns Whether tracing is enabled
410
+ */
411
+ shouldTrace() {
412
+ return this.isEnabled;
413
+ }
414
+ /**
415
+ * Adds a hop to the event's trace if tracing is enabled
416
+ * @param event - The event to add the trace to
417
+ * @param nodePath - The path to the node
418
+ * @param contractName - The name of the contract
419
+ * @returns A new event with the updated trace
420
+ */
421
+ addHop(e, t, n) {
422
+ if (!this.shouldTrace())
423
+ return { ...e };
424
+ const o = [
425
+ ...e.trace ?? [],
426
+ this.makeHop(t, n)
427
+ ];
428
+ return {
429
+ ...e,
430
+ trace: o
431
+ };
432
+ }
433
+ /**
434
+ * Gets the current trace for an event
435
+ * @param event - The event to get the trace for
436
+ * @returns The current trace array or an empty array if none exists
437
+ */
438
+ getTrace(e) {
439
+ return e.trace ?? [];
440
+ }
441
+ /**
442
+ * Clears the trace for an event
443
+ * @param event - The event to clear the trace for
444
+ * @returns A new event with an empty trace
445
+ */
446
+ clearTrace(e) {
447
+ return {
448
+ ...e,
449
+ trace: []
450
+ };
451
+ }
452
+ /**
453
+ * Checks if tracing is enabled globally
454
+ * @returns Whether tracing is enabled
455
+ */
456
+ isTracingEnabled() {
457
+ return this.isEnabled;
458
+ }
459
+ }
460
+ const Ne = 64;
461
+ class Ie {
462
+ /**
463
+ * Creates a new event router
464
+ *
465
+ * @param registry - Contract registry for looking up processors
466
+ * @param queue - Task queue for scheduling handlers
467
+ * @param getNextTaskId - Function to get the next task ID
468
+ * @param getNextEventSeq - Function to get the next event sequence number
469
+ */
470
+ constructor(e, t, n, o, a) {
471
+ l(this, "traceManager");
472
+ this.blue = e, this.registry = t, this.queue = n, this.getNextTaskId = o, this.getNextEventSeq = a, this.traceManager = new xe();
473
+ }
474
+ /**
475
+ * Routes an event to matching contracts in the document
476
+ *
477
+ * @param doc - The document to route events in
478
+ * @param pathSegments - Path segments to the current node
479
+ * @param event - The event to route
480
+ * @param afterTaskId - Minimum task ID to use
481
+ * @param inlineDepth - Current adapter recursion depth
482
+ */
483
+ async route(e, t, n, o, a = 0) {
484
+ var c;
485
+ if (n.seq === void 0 && (n.seq = this.getNextEventSeq()), t.length === 0) {
486
+ if (n.dispatchPath) {
487
+ const h = n.dispatchPath.split("/").filter(Boolean), d = { ...n };
488
+ return delete d.dispatchPath, this.route(e, h, d, o, a);
489
+ }
490
+ if (n.source === "channel" && n.originNodePath && n.originNodePath !== "/") {
491
+ const h = ((c = n.originNodePath) == null ? void 0 : c.split("/").filter(Boolean)) ?? [];
492
+ return this.route(e, h, n, o, a);
493
+ }
494
+ }
495
+ const r = S("/", t.join("/")), s = e.get(r);
496
+ x(s) && await this.traverseContracts({
497
+ doc: e,
498
+ node: s,
499
+ nodePath: r,
500
+ event: n,
501
+ afterTaskId: o,
502
+ pathSegments: t,
503
+ inlineDepth: a
504
+ });
505
+ }
506
+ /**
507
+ * Traverses contracts at the current node and routes to matching ones
508
+ */
509
+ async traverseContracts(e) {
510
+ const {
511
+ doc: t,
512
+ node: n,
513
+ nodePath: o,
514
+ event: a,
515
+ afterTaskId: r,
516
+ pathSegments: s,
517
+ inlineDepth: c
518
+ } = e;
519
+ if (!this.shouldSkipForChannel(a, o))
520
+ for (const [h, d] of Object.entries(
521
+ n.getContracts() ?? {}
522
+ )) {
523
+ if (!d.getType()) continue;
524
+ const f = this.registry.get(d.getType());
525
+ if (!f) {
526
+ console.warn(`No processor registered for contract: ${h}`);
527
+ continue;
528
+ }
529
+ const C = {
530
+ nodePath: o,
531
+ contractName: h,
532
+ contractNode: d,
533
+ event: a
534
+ }, g = new Y(() => t, C, this.blue);
535
+ if (f.supports(a, d, g, h))
536
+ switch (f.role) {
537
+ case "adapter":
538
+ await this.processAdapter({
539
+ cp: f,
540
+ event: a,
541
+ contractNode: d,
542
+ ctx: g,
543
+ contractName: h,
544
+ doc: t,
545
+ afterTaskId: r,
546
+ inlineDepth: c
547
+ });
548
+ break;
549
+ case "handler":
550
+ this.scheduleHandler({
551
+ contractNode: d,
552
+ contractName: h,
553
+ nodePath: o,
554
+ event: a,
555
+ depth: s.length,
556
+ afterTaskId: r
557
+ });
558
+ break;
559
+ }
560
+ }
561
+ }
562
+ /**
563
+ * Processes an adapter contract and routes any emitted events
564
+ */
565
+ async processAdapter(e) {
566
+ var w;
567
+ const {
568
+ cp: t,
569
+ event: n,
570
+ contractNode: o,
571
+ ctx: a,
572
+ contractName: r,
573
+ doc: s,
574
+ afterTaskId: c,
575
+ inlineDepth: h
576
+ } = e;
577
+ if (h >= Ne)
578
+ throw new Error("Adapter recursion limit reached");
579
+ const d = this.traceManager.addHop(
580
+ n,
581
+ ((w = a.getTaskInfo()) == null ? void 0 : w.nodePath) ?? "",
582
+ r
583
+ );
584
+ await t.handle(d, o, a, r);
585
+ const f = await a.flush();
586
+ if (f.find((b) => b.kind === "patch"))
587
+ throw new Error(
588
+ `Contract "${r}" (adapter) attempted to patch the document`
589
+ );
590
+ const g = f.filter((b) => b.kind === "event");
591
+ for (const b of g)
592
+ await this.route(s, [], b.event, c, h + 1);
593
+ }
594
+ /**
595
+ * Schedules a handler contract for future execution
596
+ */
597
+ scheduleHandler(e) {
598
+ const { contractNode: t, contractName: n, nodePath: o, event: a, depth: r, afterTaskId: s } = e, c = t.getType();
599
+ if (!c) {
600
+ console.warn(`Contract node type is not defined for: ${n}`);
601
+ return;
602
+ }
603
+ const h = this.registry.orderOf(c), d = t.get("/order"), f = z(d) ? d.toNumber() : 0, C = this.getNextTaskId() + s, g = be(
604
+ r,
605
+ a.seq,
606
+ h,
607
+ f,
608
+ n,
609
+ C
610
+ ), w = this.traceManager.addHop(a, o, n);
611
+ this.queue.push({
612
+ key: g,
613
+ nodePath: o,
614
+ contractName: n,
615
+ contractNode: t,
616
+ event: w
617
+ });
618
+ }
619
+ /**
620
+ * Checks if an event should be skipped because it came from another channel node
621
+ */
622
+ shouldSkipForChannel(e, t) {
623
+ return e.source === "channel" && !!e.originNodePath && e.originNodePath !== t;
624
+ }
625
+ }
626
+ const Me = (i, e, t) => {
627
+ (t instanceof G || t instanceof ee) && console.error(
628
+ `[Blue] Failed to apply patches for contract "${i}" on event ${JSON.stringify(e)}`,
629
+ t
630
+ );
631
+ };
632
+ function J(i, e) {
633
+ const t = i.clone(), n = (o) => {
634
+ var r;
635
+ if (!x(o)) return;
636
+ const a = o.getContracts();
637
+ a && (!a.checkpoint || ((r = a.checkpoint.getType()) == null ? void 0 : r.getBlueId()) !== p["Channel Event Checkpoint"]) && o.addContract(
638
+ "checkpoint",
639
+ e.jsonValueToNode({
640
+ type: {
641
+ name: "Channel Event Checkpoint",
642
+ blueId: p["Channel Event Checkpoint"]
643
+ },
644
+ lastEvents: {}
645
+ })
646
+ );
647
+ };
648
+ n(t);
649
+ for (const { absPath: o } of V(t, e)) {
650
+ const a = t.get(o);
651
+ x(a) && n(a);
652
+ }
653
+ return X(t);
654
+ }
655
+ class qe {
656
+ constructor(e) {
657
+ l(this, "contractType", "Channel Event Checkpoint");
658
+ l(this, "contractBlueId", p["Channel Event Checkpoint"]);
659
+ l(this, "role", "handler");
660
+ this.cache = e;
661
+ }
662
+ supports(e) {
663
+ var t, n;
664
+ return e.source === "channel" && ((t = e.rootEvent) == null ? void 0 : t.payload) === e.payload && ((n = e.rootEvent) == null ? void 0 : n.source) === "external";
665
+ }
666
+ async handle(e, t, n) {
667
+ var r;
668
+ if (!e.channelName || !((r = e.rootEvent) != null && r.seq)) return;
669
+ const o = await n.getBlue().calculateBlueId(e.rootEvent.payload), a = n.getNodePath().replace(/\/contracts\/checkpoint$/, "");
670
+ this.cache.record(a, e, o);
671
+ }
672
+ init() {
673
+ return [];
674
+ }
675
+ }
676
+ const Z = (i, e) => i.get(e) !== void 0;
677
+ class Ae {
678
+ constructor() {
679
+ l(this, "firstSeen", /* @__PURE__ */ new Map());
680
+ }
681
+ record(e, t, n) {
682
+ const o = e;
683
+ this.firstSeen.has(o) || this.firstSeen.set(o, { docBase: e, event: t, eventBlueId: n });
684
+ }
685
+ /** Turn cached data into JSON-Patch ops */
686
+ flush(e) {
687
+ const t = [];
688
+ for (const { docBase: n, event: o, eventBlueId: a } of this.firstSeen.values()) {
689
+ if (!o.channelName) continue;
690
+ const r = S(
691
+ n,
692
+ "contracts/checkpoint/lastEvents",
693
+ o.channelName
694
+ ), s = `${r}/blueId`;
695
+ Z(e, r) ? t.push({
696
+ op: Z(e, s) ? "replace" : "add",
697
+ path: s,
698
+ val: a
699
+ }) : t.push({
700
+ op: "add",
701
+ path: r,
702
+ val: { blueId: a }
703
+ });
704
+ }
705
+ return t;
706
+ }
707
+ clear() {
708
+ this.firstSeen.clear();
709
+ }
710
+ }
711
+ class B {
712
+ constructor() {
713
+ l(this, "role", "adapter");
714
+ }
715
+ /**
716
+ * Base implementation of supports that checks if the event is not from a channel
717
+ * Derived classes should call this method first in their supports implementation
718
+ */
719
+ baseSupports(e) {
720
+ return e.source !== "channel";
721
+ }
722
+ /**
723
+ * Base implementation that returns empty array
724
+ * Can be overridden by derived classes if needed
725
+ */
726
+ init() {
727
+ return [];
728
+ }
729
+ }
730
+ class De extends B {
731
+ constructor() {
732
+ super(...arguments);
733
+ l(this, "contractType", "Composite Timeline Channel");
734
+ l(this, "contractBlueId", p["Composite Timeline Channel"]);
735
+ }
736
+ supports(t, n, o) {
737
+ const a = o.getBlue().nodeToSchemaOutput(n, Ee);
738
+ return !a.channels || !t.channelName ? !1 : a.channels.includes(t.channelName);
739
+ }
740
+ handle(t, n, o, a) {
741
+ o.emitEvent({
742
+ payload: t.payload,
743
+ channelName: a,
744
+ source: "channel"
745
+ });
746
+ }
747
+ }
748
+ class $e extends B {
749
+ constructor() {
750
+ super(...arguments);
751
+ l(this, "contractType", "Document Update Channel");
752
+ l(this, "contractBlueId", p["Document Update Channel"]);
753
+ }
754
+ supports(t, n, o, a) {
755
+ if (!this.baseSupports(t)) return !1;
756
+ const r = o.getBlue().nodeToSchemaOutput(n, Ce), s = t.payload.path;
757
+ if (!s || t.channelName === a) return !1;
758
+ const c = r.path;
759
+ return D(c) && s === o.resolvePath(c);
760
+ }
761
+ handle(t, n, o, a) {
762
+ const r = t.payload;
763
+ r && o.emitEvent({
764
+ payload: r,
765
+ channelName: a,
766
+ source: "channel"
767
+ });
768
+ }
769
+ }
770
+ class je extends B {
771
+ constructor() {
772
+ super(...arguments);
773
+ l(this, "contractType", "Embedded Node Channel");
774
+ l(this, "contractBlueId", p["Embedded Node Channel"]);
775
+ }
776
+ supports(t, n, o) {
777
+ if (!this.baseSupports(t)) return !1;
778
+ const a = o.getBlue().nodeToSchemaOutput(n, K);
779
+ return y(t.originNodePath) && y(a.path) && t.originNodePath === o.resolvePath(a.path);
780
+ }
781
+ handle(t, n, o, a) {
782
+ const r = o.getBlue().nodeToSchemaOutput(n, K), { originNodePath: s, payload: c } = t;
783
+ y(r.path) && s === o.resolvePath(r.path) && o.emitEvent({
784
+ payload: c,
785
+ channelName: a,
786
+ source: "channel"
787
+ });
788
+ }
789
+ }
790
+ const T = {
791
+ "MyOS Timeline Channel": "MkKoutP5qxkh3uDxZ7dr6Eo27B7fuxQCS1VAptiCPc2R",
792
+ "MyOS Timeline Entry": "uDxZ7dr6Eo2MkKoutP5qxkh3uxQCS1VAptiCPc2R7B7f",
793
+ "MyOS Agent": "AgentBlu3Id7dr6Eo2MkKoutP5qxkh3uxQCS1V",
794
+ "MyOS Agent Channel": "AgentCh4nn3lBlu3Id7dr6Eo2MkKoutP5qxkh3uxQCS1V",
795
+ "MyOS Agent Event": "AgentEv3ntBlu3Id7dr6Eo2MkKoutP5qxkh3uxQCS1V"
796
+ }, Ve = m(
797
+ T["MyOS Timeline Channel"]
798
+ )(
799
+ te.extend({
800
+ account: u.string().optional(),
801
+ email: u.string().optional()
802
+ })
803
+ ), Re = m(
804
+ T["MyOS Timeline Entry"]
805
+ )(
806
+ I.extend({
807
+ account: u.string().optional(),
808
+ email: u.string().optional()
809
+ })
810
+ ), We = m(T["MyOS Agent"])(
811
+ u.object({
812
+ agentId: u.string().optional()
813
+ })
814
+ ), Qe = m(
815
+ T["MyOS Agent Channel"]
816
+ )(
817
+ N.extend({
818
+ agent: We.optional(),
819
+ event: k().optional()
820
+ })
821
+ ), Ke = m(T["MyOS Agent Event"])(
822
+ u.object({
823
+ agentId: u.string().optional(),
824
+ id: u.number().optional(),
825
+ timestamp: u.number().optional(),
826
+ event: k().optional()
827
+ })
828
+ ), _ = (i) => i.payload.type === "Timeline Entry" || i.payload.type === "MyOS Timeline Entry";
829
+ class Fe extends B {
830
+ constructor() {
831
+ super(...arguments);
832
+ l(this, "contractType", "MyOS Timeline Channel");
833
+ l(this, "contractBlueId", T["MyOS Timeline Channel"]);
834
+ }
835
+ supports(t, n, o) {
836
+ if (!this.baseSupports(t) || !_(t)) return !1;
837
+ const a = o.getBlue(), r = a.jsonValueToNode(t.payload), s = a.nodeToSchemaOutput(
838
+ r,
839
+ Re
840
+ ), c = o.getBlue().nodeToSchemaOutput(n, Ve), h = y(c.timelineId) && y(s.timelineId), d = y(c.account) && y(s.account), f = y(c.email) && y(s.email);
841
+ return h && s.timelineId === c.timelineId || d && s.account === c.account || f && s.email === c.email;
842
+ }
843
+ handle(t, n, o, a) {
844
+ _(t) && o.emitEvent({
845
+ payload: t.payload,
846
+ channelName: a,
847
+ source: "channel"
848
+ });
849
+ }
850
+ }
851
+ class Ue extends B {
852
+ constructor() {
853
+ super(...arguments);
854
+ l(this, "contractType", "MyOS Agent Channel");
855
+ l(this, "contractBlueId", T["MyOS Agent Channel"]);
856
+ }
857
+ supports(t, n, o) {
858
+ if (!this.baseSupports(t)) return !1;
859
+ try {
860
+ const { myosAgentEvent: a, myosAgentChannel: r } = this.parseEventAndChannel(
861
+ t,
862
+ n,
863
+ o
864
+ );
865
+ return this.isAgentMatch(a, r) && this.isEventPatternMatch(a, r, o);
866
+ } catch (a) {
867
+ return console.warn("Error in MyOSAgentChannelProcessor.supports:", a), !1;
868
+ }
869
+ }
870
+ handle(t, n, o, a) {
871
+ o.emitEvent({
872
+ payload: t.payload,
873
+ channelName: a,
874
+ source: "channel"
875
+ });
876
+ }
877
+ /**
878
+ * Parses and validates the event payload and channel configuration
879
+ * @throws {Error} If schema validation fails
880
+ */
881
+ parseEventAndChannel(t, n, o) {
882
+ const a = o.getBlue(), r = a.jsonValueToNode(t.payload), s = a.nodeToSchemaOutput(
883
+ r,
884
+ Ke
885
+ ), c = a.nodeToSchemaOutput(
886
+ n,
887
+ Qe
888
+ );
889
+ return { myosAgentEvent: s, myosAgentChannel: c };
890
+ }
891
+ /**
892
+ * Checks if the agent IDs match between event and channel
893
+ * @param myosAgentEvent - The parsed agent event
894
+ * @param myosAgentChannel - The parsed agent channel configuration
895
+ * @returns true if both have valid agent IDs and they match
896
+ */
897
+ isAgentMatch(t, n) {
898
+ var r;
899
+ const o = t.agentId, a = (r = n.agent) == null ? void 0 : r.agentId;
900
+ return y(o) && y(a) && o === a;
901
+ }
902
+ /**
903
+ * Checks if the event pattern matches the channel's event filter
904
+ *
905
+ * @param myosAgentEvent - The parsed agent event
906
+ * @param myosAgentChannel - The parsed agent channel configuration
907
+ * @param ctx - Processing context for Blue instance access
908
+ * @returns true if the event matches the channel's filter criteria
909
+ *
910
+ * **Matching Logic:**
911
+ * - If no event pattern is specified in channel → matches all events
912
+ * - If channel has event pattern but incoming event has no event data → no match
913
+ * - Otherwise → uses deep containment matching (event must contain all channel pattern fields)
914
+ */
915
+ isEventPatternMatch(t, n, o) {
916
+ const a = n.event;
917
+ if (!a)
918
+ return !0;
919
+ const r = t.event;
920
+ if (!r)
921
+ return !1;
922
+ try {
923
+ const s = o.getBlue(), c = s.nodeToJson(r), h = s.nodeToJson(a);
924
+ return fe(c, h);
925
+ } catch (s) {
926
+ return console.warn("Error during event pattern matching:", s), !1;
927
+ }
928
+ }
929
+ }
930
+ class Je {
931
+ constructor() {
932
+ l(this, "contractType", "Operation");
933
+ l(this, "contractBlueId", p.Operation);
934
+ l(this, "role", "adapter");
935
+ }
936
+ supports(e, t, n, o) {
937
+ const r = n.getBlue().nodeToSchemaOutput(t, we), s = this.parseEventPayload(e, n);
938
+ return y(s == null ? void 0 : s.operation) && s.operation === o && e.source === "channel" && e.channelName === r.channel;
939
+ }
940
+ async handle(e, t, n, o) {
941
+ n.emitEvent({
942
+ payload: e.payload,
943
+ channelName: o,
944
+ source: "channel"
945
+ });
946
+ }
947
+ init() {
948
+ return [];
949
+ }
950
+ parseEventPayload(e, t) {
951
+ const n = t.getBlue(), o = n.jsonValueToNode(e.payload);
952
+ if (P.isTypeOf(o, I)) {
953
+ const a = n.nodeToSchemaOutput(
954
+ o,
955
+ I
956
+ );
957
+ if (a.message)
958
+ return n.nodeToSchemaOutput(
959
+ a.message,
960
+ ve
961
+ );
962
+ }
963
+ return null;
964
+ }
965
+ }
966
+ class Ze {
967
+ constructor() {
968
+ l(this, "contractType", "Process Embedded");
969
+ l(this, "role", "adapter");
970
+ l(this, "contractBlueId", p["Process Embedded"]);
971
+ }
972
+ supports(e) {
973
+ return e.source !== "channel";
974
+ }
975
+ handle(e, t, n) {
976
+ const o = n.getBlue().nodeToSchemaOutput(t, $);
977
+ for (const a of o.paths ?? [])
978
+ n.emitEvent({
979
+ ...e,
980
+ dispatchPath: n.resolvePath(a)
981
+ });
982
+ }
983
+ init() {
984
+ return [];
985
+ }
986
+ }
987
+ const ne = !process.env.SKIP_ISOLATED_VM;
988
+ let v = null;
989
+ if (ne)
990
+ try {
991
+ v = require("isolated-vm");
992
+ } catch {
993
+ console.warn("isolated-vm not available, using fallback evaluation method");
994
+ }
995
+ function L(i) {
996
+ return /\bimport\s.+\sfrom\s+['"][^'"]+['"]/.test(i) || /\bexport\s+/.test(i);
997
+ }
998
+ class oe {
999
+ /**
1000
+ * Main evaluation method - chooses between secure and simple evaluation strategies
1001
+ */
1002
+ static async evaluate({
1003
+ code: e,
1004
+ ctx: t,
1005
+ bindings: n = {},
1006
+ options: o = {}
1007
+ }) {
1008
+ return !v || !ne ? this.evaluateSimple(e, n, o) : this.evaluateSecure(e, n, t, o);
1009
+ }
1010
+ /**
1011
+ * Fallback evaluation using Node's Function constructor
1012
+ * Used when isolated-vm is not available
1013
+ */
1014
+ static async evaluateSimple(e, t, n = {}) {
1015
+ if (L(e))
1016
+ throw new Error(
1017
+ "Static import/export syntax requires isolated-vm – start Node without SKIP_ISOLATED_VM."
1018
+ );
1019
+ try {
1020
+ if (n.isCodeBlock) {
1021
+ const o = Object.keys(t);
1022
+ return await (await new Function(
1023
+ ...o,
1024
+ `return async function codeBlock(${o.join(
1025
+ ", "
1026
+ )}) { ${e} }`
1027
+ )(
1028
+ ...o.map((s) => t[s])
1029
+ ))(...o.map((s) => t[s]));
1030
+ } else
1031
+ return new Function(
1032
+ ...Object.keys(t),
1033
+ `return ${e};`
1034
+ )(...Object.values(t));
1035
+ } catch (o) {
1036
+ throw n.isCodeBlock ? new Q(e, o) : new W(e, o);
1037
+ }
1038
+ }
1039
+ /**
1040
+ * Secure evaluation using isolated-vm with support for ES modules
1041
+ */
1042
+ static async evaluateSecure(e, t, n, o = {}) {
1043
+ if (!v) throw new Error("isolated-vm not available");
1044
+ const a = new v.Isolate({ memoryLimit: 32 }), r = await a.createContext(), s = r.global;
1045
+ try {
1046
+ await this.setupIsolateEnvironment(s, t);
1047
+ const c = /* @__PURE__ */ new Map(), h = this.createModuleResolver(
1048
+ a,
1049
+ r,
1050
+ c,
1051
+ n
1052
+ );
1053
+ return L(e) ? await this.evaluateESModule(
1054
+ a,
1055
+ r,
1056
+ e,
1057
+ o,
1058
+ h
1059
+ ) : await this.evaluateSimpleScript(
1060
+ a,
1061
+ r,
1062
+ e,
1063
+ t,
1064
+ o
1065
+ );
1066
+ } catch (c) {
1067
+ throw o.isCodeBlock ? new Q(e, c) : new W(e, c);
1068
+ } finally {
1069
+ r.release(), a.dispose();
1070
+ }
1071
+ }
1072
+ /**
1073
+ * Setup the isolated VM environment with necessary host functions and data
1074
+ */
1075
+ static async setupIsolateEnvironment(e, t) {
1076
+ if (!v) throw new Error("isolated-vm not available");
1077
+ const n = new v.Callback(
1078
+ (...o) => console.log(...o)
1079
+ );
1080
+ await e.set("log", n);
1081
+ for (const [o, a] of Object.entries(t))
1082
+ typeof a == "function" ? await e.set(
1083
+ o,
1084
+ new v.Callback(a)
1085
+ ) : await e.set(o, new v.ExternalCopy(a).copyInto());
1086
+ }
1087
+ /**
1088
+ * Create module resolver function for handling imports
1089
+ */
1090
+ static createModuleResolver(e, t, n, o) {
1091
+ return async (a) => {
1092
+ if (n.has(a)) return n.get(a);
1093
+ if (a.startsWith("blue:")) {
1094
+ const r = a.slice(5), s = o.loadBlueContent;
1095
+ if (typeof s != "function")
1096
+ throw new Error(
1097
+ `ProcessingContext is missing a loadBlueContent(blueId) implementation (needed for ${a})`
1098
+ );
1099
+ const c = await s(r), h = await e.compileModule(c);
1100
+ return n.set(a, h), await h.instantiate(
1101
+ t,
1102
+ this.createModuleResolver(e, t, n, o)
1103
+ ), h;
1104
+ }
1105
+ if (/^https?:\/\//.test(a)) {
1106
+ let r;
1107
+ if (typeof o.loadExternalModule == "function")
1108
+ r = await o.loadExternalModule(a);
1109
+ else
1110
+ throw new Error(
1111
+ `ProcessingContext is missing a loadExternalModule(url) implementation (needed for ${a})`
1112
+ );
1113
+ const s = await e.compileModule(r);
1114
+ return n.set(a, s), await s.instantiate(
1115
+ t,
1116
+ this.createModuleResolver(e, t, n, o)
1117
+ ), s;
1118
+ }
1119
+ throw new Error(`Unsupported module specifier "${a}"`);
1120
+ };
1121
+ }
1122
+ /**
1123
+ * Evaluate code as a simple script (no imports/exports)
1124
+ */
1125
+ static async evaluateSimpleScript(e, t, n, o, a) {
1126
+ const r = Object.keys(o).join(", "), s = Object.keys(o).map((d) => d), c = `(async (${r}) => { ${a.isCodeBlock ? n : `return (${n});`} })(${s.join(", ")})`;
1127
+ return await (await e.compileScript(c)).run(t, {
1128
+ timeout: a.timeout ?? 500,
1129
+ promise: !0,
1130
+ copy: !0,
1131
+ release: !0
1132
+ });
1133
+ }
1134
+ /**
1135
+ * Evaluate code as an ES module with import/export support
1136
+ */
1137
+ static async evaluateESModule(e, t, n, o, a) {
1138
+ let r = n;
1139
+ if (o.isCodeBlock) {
1140
+ const h = /^\s*(import\s.+?;|export\s.+?;)/gm, d = (n.match(h) || []).join(
1141
+ `
1142
+ `
1143
+ ), f = n.replace(h, "").trim();
1144
+ r = `
1145
+ ${d}
1146
+ const run = function() {
1147
+ ${f}
1148
+ };
1149
+ export default run();
1150
+ `;
1151
+ }
1152
+ const s = await e.compileModule(r);
1153
+ return await s.instantiate(t, a), await s.evaluate({
1154
+ timeout: o.timeout ?? 500,
1155
+ promise: !0,
1156
+ reference: !0,
1157
+ release: !0
1158
+ }), await s.namespace.get("default", {
1159
+ timeout: o.timeout ?? 500,
1160
+ promise: !0,
1161
+ copy: !0,
1162
+ release: !0
1163
+ });
1164
+ }
1165
+ }
1166
+ class ae {
1167
+ /**
1168
+ * Creates standard bindings for workflow step execution
1169
+ */
1170
+ static createStandardBindings(e, t, n) {
1171
+ const o = e.getBlue();
1172
+ return {
1173
+ document: (a) => {
1174
+ const r = e.get(a);
1175
+ return z(r) ? r.toNumber() : x(r) ? o.nodeToJson(r, "original") : r;
1176
+ },
1177
+ event: t.payload,
1178
+ steps: n
1179
+ };
1180
+ }
1181
+ }
1182
+ class _e {
1183
+ constructor() {
1184
+ l(this, "stepType", "Update Document");
1185
+ }
1186
+ supports(e) {
1187
+ return P.isTypeOf(e, A);
1188
+ }
1189
+ async evaluateChangeValue(e, t, n, o) {
1190
+ const a = e == null ? void 0 : e.getValue();
1191
+ if (typeof a == "string" && a.startsWith("${") && a.endsWith("}")) {
1192
+ const r = a.slice(2, -1);
1193
+ return await oe.evaluate({
1194
+ code: r,
1195
+ ctx: t,
1196
+ bindings: ae.createStandardBindings(
1197
+ t,
1198
+ n,
1199
+ o
1200
+ )
1201
+ });
1202
+ }
1203
+ return e;
1204
+ }
1205
+ async execute(e, t, n, o, a) {
1206
+ if (!P.isTypeOf(e, A)) return;
1207
+ const r = n.getBlue().nodeToSchemaOutput(e, A);
1208
+ for (const s of r.changeset ?? [])
1209
+ if (s.path) {
1210
+ if (s.op === "replace" || s.op === "add") {
1211
+ const c = await this.evaluateChangeValue(
1212
+ s.val,
1213
+ n,
1214
+ t,
1215
+ a
1216
+ );
1217
+ n.addPatch({
1218
+ op: s.op,
1219
+ path: s.path,
1220
+ val: c
1221
+ }), n.emitEvent({
1222
+ payload: {
1223
+ type: "Document Update",
1224
+ op: s.op,
1225
+ path: n.resolvePath(s.path),
1226
+ val: c
1227
+ }
1228
+ });
1229
+ }
1230
+ s.op === "remove" && (n.addPatch({ op: s.op, path: s.path }), n.emitEvent({
1231
+ payload: {
1232
+ type: "Document Update",
1233
+ op: s.op,
1234
+ path: n.resolvePath(s.path),
1235
+ val: null
1236
+ }
1237
+ }));
1238
+ }
1239
+ }
1240
+ }
1241
+ class Le {
1242
+ constructor() {
1243
+ l(this, "stepType", "Trigger Event");
1244
+ }
1245
+ supports(e) {
1246
+ return P.isTypeOf(e, q);
1247
+ }
1248
+ async execute(e, t, n) {
1249
+ const o = n.getBlue();
1250
+ if (!P.isTypeOf(e, q)) return;
1251
+ const a = o.nodeToSchemaOutput(e, q), r = o.nodeToJson(
1252
+ a.event,
1253
+ "original"
1254
+ );
1255
+ n.emitEvent({
1256
+ payload: r
1257
+ });
1258
+ }
1259
+ }
1260
+ class He {
1261
+ constructor() {
1262
+ l(this, "stepType", "JavaScript Code");
1263
+ }
1264
+ supports(e) {
1265
+ return P.isTypeOf(e, M);
1266
+ }
1267
+ async execute(e, t, n, o, a) {
1268
+ if (!P.isTypeOf(e, M)) return;
1269
+ const s = n.getBlue().nodeToSchemaOutput(
1270
+ e,
1271
+ M
1272
+ );
1273
+ if (!s.code)
1274
+ throw new Error("JavaScript code is required");
1275
+ const c = await oe.evaluate({
1276
+ code: s.code,
1277
+ ctx: n,
1278
+ bindings: ae.createStandardBindings(n, t, a),
1279
+ options: {
1280
+ isCodeBlock: !0,
1281
+ timeout: 500
1282
+ }
1283
+ });
1284
+ if (c && typeof c == "object" && "events" in c) {
1285
+ const h = c;
1286
+ if (Array.isArray(h.events))
1287
+ for (const d of h.events)
1288
+ n.emitEvent({
1289
+ payload: d
1290
+ });
1291
+ }
1292
+ return c;
1293
+ }
1294
+ }
1295
+ const ze = [
1296
+ new _e(),
1297
+ new Le(),
1298
+ new He()
1299
+ ];
1300
+ class re {
1301
+ constructor(e = ze) {
1302
+ l(this, "contractType", "Sequential Workflow");
1303
+ l(this, "contractBlueId", p["Sequential Workflow"]);
1304
+ l(this, "role", "handler");
1305
+ l(this, "executors", []);
1306
+ this.executors = e;
1307
+ }
1308
+ /** allow registering custom step executors */
1309
+ registerExecutor(e) {
1310
+ this.executors.push(e);
1311
+ }
1312
+ supports(e, t, n) {
1313
+ const r = n.getBlue().nodeToSchemaOutput(
1314
+ t,
1315
+ j
1316
+ ).channel;
1317
+ return e.source === "channel" && e.channelName === r;
1318
+ }
1319
+ async handle(e, t, n, o) {
1320
+ const r = n.getBlue().nodeToSchemaOutput(
1321
+ t,
1322
+ j
1323
+ ), s = {}, c = r.steps;
1324
+ for (const [h, d] of (c ?? []).entries()) {
1325
+ const f = this.executors.find((g) => g.supports(d));
1326
+ if (!f)
1327
+ throw new Error(`Unsupported workflow step type "${d.getType()}"`);
1328
+ const C = await f.execute(
1329
+ d,
1330
+ e,
1331
+ n,
1332
+ o,
1333
+ s
1334
+ );
1335
+ if (C !== void 0) {
1336
+ const g = d.getName(), w = typeof g == "string" ? g : `Step${h + 1}`;
1337
+ s[w] = C;
1338
+ }
1339
+ await n.flush();
1340
+ }
1341
+ }
1342
+ init() {
1343
+ return [];
1344
+ }
1345
+ }
1346
+ class Xe {
1347
+ constructor(e) {
1348
+ l(this, "contractType", "Sequential Workflow Operation");
1349
+ l(this, "contractBlueId", p["Sequential Workflow Operation"]);
1350
+ l(this, "role", "handler");
1351
+ l(this, "sequentialWorkflowProcessor");
1352
+ this.sequentialWorkflowProcessor = e || new re();
1353
+ }
1354
+ supports(e, t, n) {
1355
+ const r = n.getBlue().nodeToSchemaOutput(
1356
+ t,
1357
+ Se
1358
+ ).operation, s = e.channelName;
1359
+ return e.source === "channel" && D(s) && D(r) && s === r;
1360
+ }
1361
+ async handle(e, t, n, o) {
1362
+ try {
1363
+ await this.sequentialWorkflowProcessor.handle(e, t, n, o);
1364
+ } catch (a) {
1365
+ throw console.error(
1366
+ "Error in SequentialWorkflowOperationProcessor.handle:",
1367
+ a
1368
+ ), a;
1369
+ }
1370
+ }
1371
+ }
1372
+ const H = (i) => i.payload.type === "Timeline Entry";
1373
+ class Ye extends B {
1374
+ constructor() {
1375
+ super(...arguments);
1376
+ l(this, "contractType", "Timeline Channel");
1377
+ l(this, "contractBlueId", p["Timeline Channel"]);
1378
+ }
1379
+ supports(t, n, o) {
1380
+ if (!this.baseSupports(t) || !H(t)) return !1;
1381
+ const a = o.getBlue(), r = a.jsonValueToNode(t.payload), s = a.nodeToSchemaOutput(
1382
+ r,
1383
+ I
1384
+ ), c = o.getBlue().nodeToSchemaOutput(n, te);
1385
+ return y(c.timelineId) && y(s.timelineId) && s.timelineId === c.timelineId;
1386
+ }
1387
+ handle(t, n, o, a) {
1388
+ H(t) && o.emitEvent({
1389
+ payload: t.payload,
1390
+ channelName: a,
1391
+ source: "channel"
1392
+ });
1393
+ }
1394
+ }
1395
+ const Ge = [
1396
+ new Ze(),
1397
+ // channels
1398
+ new je(),
1399
+ new $e(),
1400
+ new Ye(),
1401
+ new Fe(),
1402
+ new Ue(),
1403
+ new De(),
1404
+ new Je(),
1405
+ // sequential workflows
1406
+ new re(),
1407
+ new Xe()
1408
+ ];
1409
+ class rt {
1410
+ /**
1411
+ * Creates a new document processor
1412
+ *
1413
+ * @param processors - Initial list of processors to register
1414
+ */
1415
+ constructor(e, t = Ge) {
1416
+ l(this, "taskCounter", 0);
1417
+ l(this, "eventCounter", 0);
1418
+ l(this, "registry");
1419
+ l(this, "queue");
1420
+ l(this, "router");
1421
+ l(this, "checkpointCache", new Ae());
1422
+ this.blue = e, this.registry = new Be(t), this.queue = new Oe(), this.router = new Ie(
1423
+ this.blue,
1424
+ this.registry,
1425
+ this.queue,
1426
+ () => ++this.taskCounter,
1427
+ () => ++this.eventCounter
1428
+ ), this.register(
1429
+ new qe(this.checkpointCache),
1430
+ 9999
1431
+ );
1432
+ }
1433
+ /**
1434
+ * Registers a new contract processor
1435
+ *
1436
+ * @param cp - The processor to register
1437
+ * @param orderHint - Optional priority value for execution order
1438
+ */
1439
+ register(e, t) {
1440
+ this.registry.register(e, t);
1441
+ }
1442
+ /**
1443
+ * Initializes a document and runs all init events
1444
+ *
1445
+ * @param document - The document to initialize
1446
+ * @returns Processing result with final state and emitted events
1447
+ */
1448
+ async initialise(e) {
1449
+ e = J(e, this.blue);
1450
+ const t = await this.bootstrapContracts(e);
1451
+ for (const n of t)
1452
+ await this.router.route(e, [], n, 0);
1453
+ return this.drainQueue(e);
1454
+ }
1455
+ /**
1456
+ * Processes a batch of events against the document
1457
+ *
1458
+ * @param document - The document to process events against
1459
+ * @param incoming - List of event payloads to process
1460
+ * @returns Processing result with final state and emitted events
1461
+ */
1462
+ async processEvents(e, t) {
1463
+ let n = J(e, this.blue);
1464
+ const o = [];
1465
+ for (const a of t)
1466
+ try {
1467
+ const r = { payload: a, source: "external" };
1468
+ await this.router.route(n, [], r, 0);
1469
+ const s = await this.drainQueue(n);
1470
+ n = s.state, o.push(...s.emitted);
1471
+ const c = this.checkpointCache.flush(n);
1472
+ c.length && (n = U(n, c));
1473
+ } finally {
1474
+ this.checkpointCache.clear();
1475
+ }
1476
+ return { state: n, emitted: o };
1477
+ }
1478
+ /**
1479
+ * Collects initialization events from contract processors
1480
+ */
1481
+ async bootstrapContracts(e) {
1482
+ const t = [], n = e.getContracts();
1483
+ if (!n)
1484
+ return t;
1485
+ for (const [, o] of Object.entries(n)) {
1486
+ const a = this.registry.get(o.getType());
1487
+ a != null && a.init && t.push(...await a.init(o));
1488
+ }
1489
+ return t;
1490
+ }
1491
+ /**
1492
+ * Drains the task queue and applies all actions
1493
+ */
1494
+ async drainQueue(e) {
1495
+ var r;
1496
+ let t = e;
1497
+ const n = [], o = 1e4;
1498
+ let a = 0;
1499
+ for (; this.queue.length; ) {
1500
+ if (++a > o)
1501
+ throw new Error("Possible cycle – too many iterations");
1502
+ const s = this.queue.pop(), { nodePath: c, contractName: h, contractNode: d, event: f } = s, C = t.get(c);
1503
+ if (!x(C) || !((r = C.getContracts()) != null && r[h]) || !d.getType()) continue;
1504
+ const g = this.registry.get(d.getType());
1505
+ if (!g) {
1506
+ console.warn(`No processor registered for contract: ${h}`);
1507
+ continue;
1508
+ }
1509
+ const w = new Y(
1510
+ () => t,
1511
+ s,
1512
+ this.blue,
1513
+ async (b) => {
1514
+ for (const E of b)
1515
+ if (E.kind === "patch") {
1516
+ const se = V(t, this.blue);
1517
+ for (const O of se) {
1518
+ const ie = E.patch.op === "move" || E.patch.op === "copy" ? [E.patch.from, E.patch.path] : [E.patch.path], R = w.getNodePath(), ce = ie.some(
1519
+ (ue) => F(ue, O.absPath)
1520
+ ), le = F(
1521
+ R,
1522
+ O.absPath
1523
+ );
1524
+ if (ce && !le)
1525
+ throw new ee(
1526
+ E.patch,
1527
+ O.absPath,
1528
+ R
1529
+ );
1530
+ }
1531
+ try {
1532
+ t = U(t, [E.patch]);
1533
+ } catch (O) {
1534
+ throw Me(h, f, O), O;
1535
+ }
1536
+ } else E.kind === "event" && (n.push(E.event.payload), await this.router.route(t, [], E.event, s.key[5]));
1537
+ }
1538
+ );
1539
+ await g.handle(f, d, w, h), await w.flush();
1540
+ }
1541
+ return { state: t, emitted: n };
1542
+ }
1543
+ }
1544
+ export {
1545
+ rt as BlueDocumentProcessor,
1546
+ qe as ChannelEventCheckpointProcessor,
1547
+ De as CompositeTimelineChannelProcessor,
1548
+ $e as DocumentUpdateChannelProcessor,
1549
+ je as EmbeddedNodeChannelProcessor,
1550
+ Ue as MyOSAgentChannelProcessor,
1551
+ Fe as MyOSTimelineChannelProcessor,
1552
+ Je as OperationProcessor,
1553
+ Ze as ProcessEmbeddedProcessor,
1554
+ Xe as SequentialWorkflowOperationProcessor,
1555
+ re as SequentialWorkflowProcessor,
1556
+ Ye as TimelineChannelProcessor
1557
+ };