@girverket/xenocline 0.0.9

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 (112) hide show
  1. package/LICENSE.md +66 -0
  2. package/README.md +739 -0
  3. package/dist/aggregator.d.ts +53 -0
  4. package/dist/aggregator.js +31 -0
  5. package/dist/aggregator.js.map +1 -0
  6. package/dist/constants.d.ts +2 -0
  7. package/dist/context.d.ts +3 -0
  8. package/dist/event/aggregator.d.ts +16 -0
  9. package/dist/event/aggregator.js +29 -0
  10. package/dist/event/aggregator.js.map +1 -0
  11. package/dist/event/event.d.ts +14 -0
  12. package/dist/event/event.js +12 -0
  13. package/dist/event/event.js.map +1 -0
  14. package/dist/event/handler.d.ts +7 -0
  15. package/dist/event/handler.js +8 -0
  16. package/dist/event/handler.js.map +1 -0
  17. package/dist/event/node.d.ts +40 -0
  18. package/dist/event/node.js +24 -0
  19. package/dist/event/node.js.map +1 -0
  20. package/dist/event/phase.d.ts +15 -0
  21. package/dist/event/phase.js +12 -0
  22. package/dist/event/phase.js.map +1 -0
  23. package/dist/event/process.d.ts +14 -0
  24. package/dist/event/process.js +15 -0
  25. package/dist/event/process.js.map +1 -0
  26. package/dist/event/transition.d.ts +45 -0
  27. package/dist/event/transition.js +35 -0
  28. package/dist/event/transition.js.map +1 -0
  29. package/dist/event.d.ts +30 -0
  30. package/dist/execution/aggregator.d.ts +23 -0
  31. package/dist/execution/aggregator.js +81 -0
  32. package/dist/execution/aggregator.js.map +1 -0
  33. package/dist/execution/event.d.ts +26 -0
  34. package/dist/execution/event.js +29 -0
  35. package/dist/execution/event.js.map +1 -0
  36. package/dist/execution/next.d.ts +7 -0
  37. package/dist/execution/next.js +137 -0
  38. package/dist/execution/next.js.map +1 -0
  39. package/dist/execution/node.d.ts +4 -0
  40. package/dist/execution/node.js +194 -0
  41. package/dist/execution/node.js.map +1 -0
  42. package/dist/execution/phase.d.ts +5 -0
  43. package/dist/execution/phase.js +23 -0
  44. package/dist/execution/phase.js.map +1 -0
  45. package/dist/execution/process.d.ts +35 -0
  46. package/dist/execution/process.js +115 -0
  47. package/dist/execution/process.js.map +1 -0
  48. package/dist/input.d.ts +6 -0
  49. package/dist/input.js +4 -0
  50. package/dist/input.js.map +1 -0
  51. package/dist/logger.d.ts +12 -0
  52. package/dist/node/aggregatornode.d.ts +40 -0
  53. package/dist/node/aggregatornode.js +41 -0
  54. package/dist/node/aggregatornode.js.map +1 -0
  55. package/dist/node/node.d.ts +18 -0
  56. package/dist/node/node.js +80 -0
  57. package/dist/node/node.js.map +1 -0
  58. package/dist/node/phasenode.d.ts +49 -0
  59. package/dist/node/phasenode.js +37 -0
  60. package/dist/node/phasenode.js.map +1 -0
  61. package/dist/output.d.ts +6 -0
  62. package/dist/phase.d.ts +23 -0
  63. package/dist/phase.js +24 -0
  64. package/dist/phase.js.map +1 -0
  65. package/dist/process.d.ts +15 -0
  66. package/dist/process.js +106 -0
  67. package/dist/process.js.map +1 -0
  68. package/dist/transition/beginning.d.ts +19 -0
  69. package/dist/transition/beginning.js +31 -0
  70. package/dist/transition/beginning.js.map +1 -0
  71. package/dist/transition/connection.d.ts +55 -0
  72. package/dist/transition/connection.js +90 -0
  73. package/dist/transition/connection.js.map +1 -0
  74. package/dist/transition/decision.d.ts +20 -0
  75. package/dist/transition/decision.js +47 -0
  76. package/dist/transition/decision.js.map +1 -0
  77. package/dist/transition/next.d.ts +13 -0
  78. package/dist/transition/next.js +81 -0
  79. package/dist/transition/next.js.map +1 -0
  80. package/dist/transition/termination.d.ts +17 -0
  81. package/dist/transition/termination.js +50 -0
  82. package/dist/transition/termination.js.map +1 -0
  83. package/dist/transition/transition.d.ts +16 -0
  84. package/dist/transition/transition.js +72 -0
  85. package/dist/transition/transition.js.map +1 -0
  86. package/dist/util/general.d.ts +4 -0
  87. package/dist/util/general.js +6 -0
  88. package/dist/util/general.js.map +1 -0
  89. package/dist/utility/event/eventfilter.d.ts +7 -0
  90. package/dist/utility/event/eventfilter.js +15 -0
  91. package/dist/utility/event/eventfilter.js.map +1 -0
  92. package/dist/utility/event/filteredhandler.d.ts +13 -0
  93. package/dist/utility/event/filteredhandler.js +18 -0
  94. package/dist/utility/event/filteredhandler.js.map +1 -0
  95. package/dist/utility/event/logginghandler.d.ts +12 -0
  96. package/dist/xenocline.cjs +1362 -0
  97. package/dist/xenocline.cjs.map +1 -0
  98. package/dist/xenocline.d.ts +72 -0
  99. package/dist/xenocline.js +21 -0
  100. package/dist/xenocline.js.map +1 -0
  101. package/output/kodrdriv/260109-2305-commit-message.md +3 -0
  102. package/output/kodrdriv/260109-2307-release-notes.md +28 -0
  103. package/output/kodrdriv/260109-2318-commit-message.md +6 -0
  104. package/output/kodrdriv/260109-2321-release-notes.md +39 -0
  105. package/output/kodrdriv/RELEASE_NOTES.md +37 -0
  106. package/output/kodrdriv/RELEASE_TITLE.md +1 -0
  107. package/output/kodrdriv/agentic-reflection-commit-2026-01-10T07-05-39-771Z.md +52 -0
  108. package/output/kodrdriv/agentic-reflection-commit-2026-01-10T07-18-31-315Z.md +55 -0
  109. package/output/kodrdriv/agentic-reflection-release-2026-01-10T07-07-33-739Z.md +257 -0
  110. package/output/kodrdriv/agentic-reflection-release-2026-01-10T07-21-54-717Z.md +394 -0
  111. package/package.json +69 -0
  112. package/scripts/pre-commit-hook.sh +53 -0
@@ -0,0 +1,1362 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4
+
5
+ const clean = (obj)=>{
6
+ return Object.fromEntries(Object.entries(obj).filter(([_, v])=>v !== undefined));
7
+ };
8
+
9
+ const DEFAULT_AGGREGATOR_OPTIONS = {
10
+ aggregate: async (input)=>{
11
+ return {
12
+ status: 'Ready',
13
+ output: input
14
+ };
15
+ }
16
+ };
17
+ const createAggregator = (name, options)=>{
18
+ let aggregatorOptions = {
19
+ ...DEFAULT_AGGREGATOR_OPTIONS
20
+ };
21
+ if (options) {
22
+ aggregatorOptions = {
23
+ ...aggregatorOptions,
24
+ ...clean(options)
25
+ };
26
+ }
27
+ return {
28
+ name,
29
+ aggregate: aggregatorOptions.aggregate
30
+ };
31
+ };
32
+ const isAggregator = (obj)=>{
33
+ return obj !== undefined && obj !== null && typeof obj === 'object' && typeof obj.name === 'string' && typeof obj.aggregate === 'function';
34
+ };
35
+
36
+ const createEvent = (type, sourceId, stage, data)=>{
37
+ return {
38
+ date: new Date(),
39
+ type,
40
+ stage,
41
+ sourceId,
42
+ data
43
+ };
44
+ };
45
+
46
+ function createAggregatorEvent(sourceId, stage, aggregator, data) {
47
+ const event = createEvent('aggregator', sourceId, stage, data);
48
+ return {
49
+ ...event,
50
+ aggregator
51
+ };
52
+ }
53
+ function isAggregatorEvent(event) {
54
+ if (event === null || event === undefined || typeof event !== 'object') {
55
+ return false;
56
+ }
57
+ const hasRequiredProperties = event.type === 'aggregator' && 'stage' in event && 'aggregator' in event && typeof event.aggregator === 'object' && event.aggregator !== null && 'name' in event.aggregator;
58
+ if (!hasRequiredProperties) {
59
+ return false;
60
+ }
61
+ const aggregatorEvent = event;
62
+ const isValidStage = [
63
+ 'start',
64
+ 'aggregate',
65
+ 'ready',
66
+ 'defer'
67
+ ].includes(aggregatorEvent.stage);
68
+ return isValidStage;
69
+ }
70
+
71
+ const createTransition = (type, id)=>{
72
+ return {
73
+ id,
74
+ type
75
+ };
76
+ };
77
+ const isTransition = (item)=>{
78
+ return item !== null && typeof item === 'object' && typeof item.id === 'string' && (item.type === 'connection' || item.type === 'decision' || item.type === 'termination' || item.type === 'beginning');
79
+ };
80
+ const validateTransition = (item, coordinates)=>{
81
+ const errors = [];
82
+ const currentCoordinates = [
83
+ ...coordinates || [],
84
+ 'Transition'
85
+ ];
86
+ if (item === undefined || item === null) {
87
+ errors.push({
88
+ coordinates: [
89
+ ...currentCoordinates
90
+ ],
91
+ error: 'Transition is undefined or null.'
92
+ });
93
+ return errors;
94
+ }
95
+ if (typeof item !== 'object') {
96
+ errors.push({
97
+ coordinates: [
98
+ ...currentCoordinates
99
+ ],
100
+ error: 'Transition is not an object.'
101
+ });
102
+ return errors;
103
+ }
104
+ if (item.id === undefined || typeof item.id !== 'string') {
105
+ errors.push({
106
+ coordinates: [
107
+ ...currentCoordinates
108
+ ],
109
+ error: 'Transition id is undefined or not a string.'
110
+ });
111
+ }
112
+ if (item.type === undefined || typeof item.type !== 'string') {
113
+ errors.push({
114
+ coordinates: [
115
+ ...currentCoordinates
116
+ ],
117
+ error: 'Transition type is undefined or not a string.'
118
+ });
119
+ }
120
+ if (item.type !== 'connection' && item.type !== 'decision' && item.type !== 'termination' && item.type !== 'beginning') {
121
+ errors.push({
122
+ coordinates: [
123
+ ...currentCoordinates
124
+ ],
125
+ error: 'Transition type is not a valid type.'
126
+ });
127
+ }
128
+ // We have an id, push to current coordinates
129
+ currentCoordinates.push(`Transition: ${item.id}`);
130
+ if (item.type === undefined || typeof item.type !== 'string') {
131
+ errors.push({
132
+ coordinates: [
133
+ ...currentCoordinates
134
+ ],
135
+ error: 'Transition type is undefined or not a string.'
136
+ });
137
+ }
138
+ return errors;
139
+ };
140
+
141
+ // NEW: Termination type extending Transition
142
+ const createTermination = (id, options)=>{
143
+ const defaultOptions = {
144
+ terminate: async (output)=>{
145
+ return output;
146
+ }
147
+ };
148
+ let terminationOptions = {
149
+ ...defaultOptions
150
+ };
151
+ if (options) {
152
+ terminationOptions = {
153
+ ...terminationOptions,
154
+ ...clean(options)
155
+ };
156
+ }
157
+ return {
158
+ ...createTransition('termination', id),
159
+ terminate: terminationOptions.terminate
160
+ };
161
+ };
162
+ const isTermination = (item)=>{
163
+ return isTransition(item) && item.type === 'termination' && (item.terminate === undefined || typeof item.terminate === 'function');
164
+ };
165
+ const validateTermination = (item, coordinates)=>{
166
+ const errors = [];
167
+ const currentCoordinates = [
168
+ ...coordinates || [],
169
+ 'Termination'
170
+ ];
171
+ errors.push(...validateTransition(item, currentCoordinates));
172
+ if (errors.length === 0) {
173
+ currentCoordinates.push(`Termination: ${item.id}`);
174
+ if (item.terminate !== undefined && typeof item.terminate !== 'function') {
175
+ errors.push({
176
+ coordinates: [
177
+ ...currentCoordinates
178
+ ],
179
+ error: 'terminate is not a function.'
180
+ });
181
+ }
182
+ }
183
+ return errors;
184
+ };
185
+
186
+ /**
187
+ * Default connection options with a pass-through transform.
188
+ * WARNING: The default transform uses a type assertion (output as Input) which provides
189
+ * no runtime validation. Users should provide their own transform function if the output
190
+ * type does not structurally match the expected input type of the target node.
191
+ * The type assertion is used here to maintain backward compatibility and allow simple
192
+ * pass-through scenarios where Output and Input have compatible shapes.
193
+ */ const DEFAULT_CONNECTION_OPTIONS = {
194
+ transform: async (output, context)=>{
195
+ // Type assertion used here - Output and Input are both extensible objects
196
+ // so this is safe for pass-through scenarios, but users should validate
197
+ // or transform data if types don't align
198
+ return [
199
+ output,
200
+ context
201
+ ];
202
+ }
203
+ };
204
+ const createConnection = (id, targetNodeId, options)=>{
205
+ let connectionOptions = {
206
+ ...DEFAULT_CONNECTION_OPTIONS
207
+ };
208
+ if (options) {
209
+ connectionOptions = {
210
+ ...connectionOptions,
211
+ ...clean(options)
212
+ };
213
+ }
214
+ return {
215
+ ...createTransition('connection', id),
216
+ targetNodeId,
217
+ transform: connectionOptions.transform
218
+ };
219
+ };
220
+ const isConnection = (item)=>{
221
+ return isTransition(item) && item.type === 'connection' && item.targetNodeId !== undefined;
222
+ };
223
+ const validateConnection = (item, coordinates)=>{
224
+ const errors = [];
225
+ const connectionBaseCoordinates = [
226
+ ...coordinates || [],
227
+ 'Connection'
228
+ ];
229
+ errors.push(...validateTransition(item, coordinates));
230
+ if (errors.length === 0) {
231
+ if (item && typeof item === 'object') {
232
+ const connectionSpecificErrorPath = [
233
+ ...connectionBaseCoordinates,
234
+ `Connection: ${item.id}`
235
+ ];
236
+ if (item.type === 'connection') {
237
+ if (typeof item.targetNodeId !== 'string') {
238
+ errors.push({
239
+ coordinates: connectionSpecificErrorPath,
240
+ error: 'Property "targetNodeId" must be a string when type is "connection".'
241
+ });
242
+ }
243
+ // transform is optional, but if present, must be a function.
244
+ if (item.transform !== undefined && typeof item.transform !== 'function') {
245
+ errors.push({
246
+ coordinates: connectionSpecificErrorPath,
247
+ error: 'Optional property "transform" must be a function if present.'
248
+ });
249
+ }
250
+ } else {
251
+ // If type is not 'connection', but these properties exist and are malformed.
252
+ // This primarily helps catch if a non-connection object has these fields incorrectly defined.
253
+ if (item.targetNodeId !== undefined && typeof item.targetNodeId !== 'string') {
254
+ errors.push({
255
+ coordinates: connectionSpecificErrorPath,
256
+ error: 'Property "targetNodeId" is present but is not a string.'
257
+ });
258
+ }
259
+ if (item.transform !== undefined && typeof item.transform !== 'function') {
260
+ errors.push({
261
+ coordinates: connectionSpecificErrorPath,
262
+ error: 'Property "transform" is present but is not a function.'
263
+ });
264
+ }
265
+ }
266
+ }
267
+ }
268
+ return errors;
269
+ };
270
+
271
+ const createDecision = (id, decide)=>{
272
+ return {
273
+ ...createTransition('decision', id),
274
+ decide
275
+ };
276
+ };
277
+ const isDecision = (item)=>{
278
+ return isTransition(item) && item.type === 'decision' && typeof item.decide === 'function';
279
+ };
280
+ const validateDecision = (item, coordinates)=>{
281
+ const errors = [];
282
+ const decisionBaseCoordinates = [
283
+ ...coordinates || [],
284
+ 'Decision'
285
+ ];
286
+ errors.push(...validateTransition(item, coordinates));
287
+ if (errors.length === 0) {
288
+ if (item && typeof item === 'object') {
289
+ const decisionSpecificErrorPath = [
290
+ ...decisionBaseCoordinates,
291
+ `Decision: ${item.id}`
292
+ ];
293
+ if (item.type === 'decision') {
294
+ if (typeof item.decide !== 'function') {
295
+ errors.push({
296
+ coordinates: decisionSpecificErrorPath,
297
+ error: 'Property "decide" must be a function when type is "decision".'
298
+ });
299
+ }
300
+ } else {
301
+ // If type is not 'decision', but 'decide' property exists and is malformed.
302
+ if (item.decide !== undefined && typeof item.decide !== 'function') {
303
+ errors.push({
304
+ coordinates: decisionSpecificErrorPath,
305
+ error: 'Property "decide" is present but is not a function.'
306
+ });
307
+ }
308
+ }
309
+ }
310
+ }
311
+ return errors;
312
+ };
313
+
314
+ const isNext = (item)=>{
315
+ if (isTermination(item)) {
316
+ return true;
317
+ }
318
+ if (!Array.isArray(item)) {
319
+ return false;
320
+ }
321
+ if (item.length === 0) {
322
+ return true;
323
+ }
324
+ const firstElement = item[0];
325
+ if (isConnection(firstElement)) {
326
+ return item.every((el)=>isConnection(el));
327
+ }
328
+ if (isDecision(firstElement)) {
329
+ return item.every((el)=>isDecision(el));
330
+ }
331
+ return false;
332
+ };
333
+ const validateDecisionOrConnectionArray = (item, coordinates)=>{
334
+ const errors = [];
335
+ const currentCoordinates = [
336
+ ...coordinates || []
337
+ ];
338
+ if (item.length === 0) {
339
+ errors.push({
340
+ coordinates: [
341
+ ...currentCoordinates
342
+ ],
343
+ error: 'Next Array is empty.'
344
+ });
345
+ return errors;
346
+ }
347
+ const firstElement = item[0];
348
+ if (isConnection(firstElement)) {
349
+ for (const element of item){
350
+ errors.push(...validateConnection(element, currentCoordinates));
351
+ }
352
+ } else if (isDecision(firstElement)) {
353
+ for (const element of item){
354
+ errors.push(...validateDecision(element, currentCoordinates));
355
+ }
356
+ } else {
357
+ errors.push({
358
+ coordinates: [
359
+ ...currentCoordinates
360
+ ],
361
+ error: 'Next Array contains invalid element types. Expected all Connections or all Decisions.'
362
+ });
363
+ }
364
+ return errors;
365
+ };
366
+ const validateNext = (item, coordinates)=>{
367
+ const errors = [];
368
+ const currentCoordinates = [
369
+ ...coordinates || [],
370
+ 'Next'
371
+ ];
372
+ if (item === undefined || item === null) {
373
+ errors.push({
374
+ coordinates: [
375
+ ...currentCoordinates
376
+ ],
377
+ error: 'Next is undefined or null.'
378
+ });
379
+ return errors;
380
+ }
381
+ if (Array.isArray(item)) {
382
+ errors.push(...validateDecisionOrConnectionArray(item, currentCoordinates));
383
+ } else {
384
+ errors.push(...validateTermination(item, currentCoordinates));
385
+ }
386
+ return errors;
387
+ };
388
+
389
+ const DEFAULT_NODE_OPTIONS = {};
390
+ const createNode = (type, id, options)=>{
391
+ let nodeOptions = {
392
+ ...DEFAULT_NODE_OPTIONS
393
+ };
394
+ if (options) {
395
+ nodeOptions = {
396
+ ...nodeOptions,
397
+ ...clean(options)
398
+ };
399
+ }
400
+ return {
401
+ id,
402
+ type,
403
+ next: nodeOptions.next
404
+ };
405
+ };
406
+ const isNode = (item)=>{
407
+ return item !== null && typeof item === 'object' && typeof item.id === 'string' && (item.type === 'aggregator' || item.type === 'phase') && (item.next === undefined || isNext(item.next));
408
+ };
409
+ const validateNode = (item, coordinates)=>{
410
+ const errors = [];
411
+ const currentCoordinates = [
412
+ ...coordinates || [],
413
+ 'Node'
414
+ ];
415
+ if (item === undefined || item === null) {
416
+ errors.push({
417
+ coordinates: [
418
+ ...currentCoordinates
419
+ ],
420
+ error: 'Node is undefined or null.'
421
+ });
422
+ return errors;
423
+ }
424
+ if (typeof item !== 'object') {
425
+ errors.push({
426
+ coordinates: [
427
+ ...currentCoordinates
428
+ ],
429
+ error: 'Node is not an object.'
430
+ });
431
+ return errors;
432
+ }
433
+ if (item.id === undefined || typeof item.id !== 'string') {
434
+ errors.push({
435
+ coordinates: [
436
+ ...currentCoordinates
437
+ ],
438
+ error: 'Node id is undefined or not a string.'
439
+ });
440
+ }
441
+ if (item.type === undefined || typeof item.type !== 'string') {
442
+ errors.push({
443
+ coordinates: [
444
+ ...currentCoordinates
445
+ ],
446
+ error: 'Node type is undefined or not a string.'
447
+ });
448
+ }
449
+ if (item.type !== 'aggregator' && item.type !== 'phase') {
450
+ errors.push({
451
+ coordinates: [
452
+ ...currentCoordinates
453
+ ],
454
+ error: 'Node type is not a valid type.'
455
+ });
456
+ }
457
+ currentCoordinates.push(`Node: ${item.id}`);
458
+ if (item.next !== undefined) {
459
+ errors.push(...validateNext(item.next, currentCoordinates));
460
+ }
461
+ return errors;
462
+ };
463
+
464
+ const DEFAULT_AGGREGATOR_NODE_OPTIONS = {};
465
+ const createAggregatorNode = (id, aggregator, options)=>{
466
+ let aggregatorNodeOptions = {
467
+ ...DEFAULT_AGGREGATOR_NODE_OPTIONS
468
+ };
469
+ if (options) {
470
+ aggregatorNodeOptions = {
471
+ ...aggregatorNodeOptions,
472
+ ...clean(options)
473
+ };
474
+ }
475
+ return {
476
+ ...createNode('aggregator', id, {
477
+ next: aggregatorNodeOptions.next
478
+ }),
479
+ aggregator
480
+ };
481
+ };
482
+ /**
483
+ * Type guard to check if an object is an AggregatorNode.
484
+ *
485
+ * @param obj - The object to check.
486
+ * @returns True if the object is an AggregatorNode, false otherwise.
487
+ */ const isAggregatorNode = (obj)=>{
488
+ if (!isNode(obj) || obj.type !== 'aggregator') {
489
+ return false;
490
+ }
491
+ // At this point, obj is a Node with type 'aggregator'.
492
+ // Now check for AggregatorNode specific properties.
493
+ const potentialAggNode = obj; // Cast to access specific props
494
+ if (!(typeof potentialAggNode.aggregator === 'object' && potentialAggNode.aggregator !== null && typeof potentialAggNode.aggregator.aggregate === 'function')) {
495
+ return false;
496
+ }
497
+ return true; // Not Termination and not a recognized array type for 'next'
498
+ };
499
+
500
+ // NEW: Termination type extending Transition
501
+ const DEFAULT_BEGINNING_OPTIONS = {
502
+ begin: async (input)=>{
503
+ return input;
504
+ }
505
+ };
506
+ const createBeginning = (id, targetNodeId, options)=>{
507
+ let beginningOptions = {
508
+ ...DEFAULT_BEGINNING_OPTIONS
509
+ };
510
+ if (options) {
511
+ beginningOptions = {
512
+ ...beginningOptions,
513
+ ...clean(options)
514
+ };
515
+ }
516
+ return {
517
+ ...createTransition('beginning', id),
518
+ targetNodeId,
519
+ begin: beginningOptions.begin
520
+ };
521
+ };
522
+ const isBeginning = (item)=>{
523
+ return isTransition(item) && item.type === 'beginning' && (item.begin === undefined || typeof item.begin === 'function');
524
+ };
525
+
526
+ const createTransitionEvent = (sourceId, transitionType, stage, transition, data)=>{
527
+ const event = createEvent('transition', sourceId, stage, data);
528
+ return {
529
+ ...event,
530
+ transitionType,
531
+ transition
532
+ };
533
+ };
534
+ const createConnectionEvent = (sourceId, stage, transition, data)=>{
535
+ return createTransitionEvent(sourceId, 'connection', stage, transition, data);
536
+ };
537
+ const isConnectionEvent = (item)=>{
538
+ return typeof item === 'object' && item !== null && item.type === 'transition' && item.transitionType === 'connection' && typeof item.transitionType === 'string';
539
+ };
540
+ const createDecisionEvent = (sourceId, stage, transition, data)=>createTransitionEvent(sourceId, 'decision', stage, transition, data);
541
+ const isDecisionEvent = (item)=>{
542
+ return typeof item === 'object' && item !== null && item.type === 'transition' && item.transitionType === 'decision' && typeof item.transitionType === 'string';
543
+ };
544
+ const createTerminationEvent = (sourceId, stage, transition, data)=>{
545
+ return createTransitionEvent(sourceId, 'termination', stage, transition, data);
546
+ };
547
+ const isTerminationEvent = (item)=>{
548
+ return typeof item === 'object' && item !== null && item.type === 'transition' && item.transitionType === 'termination' && typeof item.transitionType === 'string';
549
+ };
550
+ const createBeginningEvent = (sourceId, stage, transition, data)=>{
551
+ return createTransitionEvent(sourceId, 'beginning', stage, transition, data);
552
+ };
553
+ const isBeginningEvent = (item)=>{
554
+ return typeof item === 'object' && item !== null && item.type === 'transition' && item.transitionType === 'beginning' && typeof item.transitionType === 'string';
555
+ };
556
+
557
+ const createEventHandler = (handle)=>{
558
+ return {
559
+ handle
560
+ };
561
+ };
562
+
563
+ const createEventFilter = (type, stage)=>{
564
+ const filterFn = (event)=>{
565
+ const typeMatch = !type || type.includes(event.type);
566
+ const stageMatch = !stage || stage.includes(event.stage);
567
+ return typeMatch && stageMatch;
568
+ };
569
+ return {
570
+ type,
571
+ stage,
572
+ filter: filterFn
573
+ };
574
+ };
575
+
576
+ const createFilteredHandler = (filter, options)=>{
577
+ const handler = 'handler' in options ? options.handler : createEventHandler(options.handle);
578
+ const handle = async (event, context)=>{
579
+ if (filter.filter(event)) {
580
+ await handler.handle(event, context);
581
+ }
582
+ };
583
+ return {
584
+ filter,
585
+ handler,
586
+ handle
587
+ };
588
+ };
589
+
590
+ /**
591
+ * Creates an instance of EventState.
592
+ * @param handlers An optional array of event handlers to initialize the state with.
593
+ * These handlers should be of type `EventHandler<Event, C>`, meaning they
594
+ * are prepared to receive any event and filter internally if necessary.
595
+ * @returns A new, readonly EventState object.
596
+ */ const createEventState = (handlers)=>{
597
+ // Store a copy of the handlers array to ensure immutability of the provided array.
598
+ return {
599
+ handlers: handlers ? [
600
+ ...handlers
601
+ ] : []
602
+ };
603
+ };
604
+ /**
605
+ * Dispatches an event to all registered handlers.
606
+ * @param eventState The current event state containing the handlers.
607
+ * @param event The event to dispatch. This can be any specific event type that extends `Event`.
608
+ * @param context The current context to pass to the handlers.
609
+ */ const dispatchEvent = async (eventState, event, context)=>{
610
+ for (const handler of eventState.handlers){
611
+ // Each handler is EventHandler<Event, C>, so its `handle` method expects an `Event`.
612
+ // Since `E` extends `Event`, passing `event` (of type `E`) is type-safe.
613
+ await handler.handle(event, context);
614
+ }
615
+ };
616
+
617
+ const createNodeEvent = (sourceId, nodeType, stage, node, data)=>{
618
+ const event = createEvent('node', sourceId, stage, data);
619
+ return {
620
+ ...event,
621
+ nodeType,
622
+ node
623
+ };
624
+ };
625
+ const isNodeEvent = (item)=>{
626
+ return item !== null && item !== undefined && typeof item === 'object' && item.type === 'node' && item.node !== null && item.node !== undefined && item.stage !== null && item.stage !== undefined;
627
+ };
628
+ const createAggregatorNodeEvent = (sourceId, stage, aggregatorNode, data)=>createNodeEvent(sourceId, 'aggregator', stage, aggregatorNode, data);
629
+ const isAggregatorNodeEvent = (item)=>{
630
+ return isNodeEvent(item) && item.nodeType === 'aggregator';
631
+ };
632
+ const createPhaseNodeEvent = (sourceId, stage, phaseNode, data)=>createNodeEvent(sourceId, 'phase', stage, phaseNode, data);
633
+ const isPhaseNodeEvent = (item)=>{
634
+ return isNodeEvent(item) && item.nodeType === 'phase';
635
+ };
636
+
637
+ const createPhase = (name, options)=>{
638
+ const defaultOptions = {
639
+ execute: async (input)=>{
640
+ return input;
641
+ }
642
+ };
643
+ const phaseOptions = {
644
+ ...defaultOptions,
645
+ ...clean(options)
646
+ };
647
+ return {
648
+ name,
649
+ execute: phaseOptions.execute,
650
+ verify: phaseOptions.verify
651
+ };
652
+ };
653
+ const isPhase = (obj)=>{
654
+ return obj !== undefined && obj !== null && typeof obj === 'object' && typeof obj.name === 'string' && typeof obj.execute === 'function';
655
+ };
656
+
657
+ const DEFAULT_PHASE_NODE_OPTIONS = {};
658
+ const createPhaseNode = (id, phase, options)=>{
659
+ let phaseNodeOptions = {
660
+ ...DEFAULT_PHASE_NODE_OPTIONS
661
+ };
662
+ if (options) {
663
+ phaseNodeOptions = {
664
+ ...phaseNodeOptions,
665
+ ...clean(options)
666
+ };
667
+ }
668
+ return {
669
+ ...createNode('phase', id, {
670
+ next: phaseNodeOptions.next
671
+ }),
672
+ phase,
673
+ prepare: phaseNodeOptions.prepare,
674
+ process: phaseNodeOptions.process
675
+ };
676
+ };
677
+ const isPhaseNode = (obj)=>{
678
+ if (!isNode(obj) || obj.type !== 'phase') {
679
+ return false;
680
+ }
681
+ const potentialPhaseNode = obj;
682
+ if (!(potentialPhaseNode.phase && typeof potentialPhaseNode.phase === 'object' && isPhase(potentialPhaseNode.phase))) {
683
+ return false;
684
+ }
685
+ return true;
686
+ };
687
+
688
+ //import * as ClassifyPhase from './phases/classify';
689
+ // import * as TranscribePhase from './phases/transcribe';
690
+ // import * as ComposePhase from './phases/compose';
691
+ // import * as CompletePhase from './phases/complete';
692
+ const createProcess = (name, options)=>{
693
+ const defaultOptions = {
694
+ phases: {}
695
+ };
696
+ const processOptions = {
697
+ ...defaultOptions,
698
+ ...clean(options)
699
+ };
700
+ // Removed: const eventState = createEventState<C>(processOptions.eventHandlers);
701
+ return {
702
+ name,
703
+ phases: processOptions.phases
704
+ };
705
+ };
706
+ const isProcess = (obj)=>{
707
+ return obj !== undefined && obj !== null && typeof obj === 'object' && typeof obj.name === 'string' && typeof obj.phases === 'object';
708
+ };
709
+ const validateProcess = (item, coordinates)=>{
710
+ const errors = [];
711
+ const currentCoordinates = [
712
+ ...[],
713
+ 'Process'
714
+ ];
715
+ if (item === undefined || item === null) {
716
+ errors.push({
717
+ coordinates: [
718
+ ...currentCoordinates
719
+ ],
720
+ error: 'Process is undefined or null.'
721
+ });
722
+ return errors;
723
+ }
724
+ if (item.name === undefined || typeof item.name !== 'string') {
725
+ errors.push({
726
+ coordinates: [
727
+ ...currentCoordinates
728
+ ],
729
+ error: 'Process name is undefined or not a string.'
730
+ });
731
+ }
732
+ const processNameForPath = typeof item.name === 'string' ? item.name : 'UnnamedProcess';
733
+ const basePath = [
734
+ ...currentCoordinates,
735
+ `name:${processNameForPath}`
736
+ ];
737
+ if (item.phases === undefined || typeof item.phases !== 'object') {
738
+ errors.push({
739
+ coordinates: [
740
+ ...basePath,
741
+ 'phases'
742
+ ],
743
+ error: 'Process phases is undefined or not an object.'
744
+ });
745
+ } else {
746
+ for(const phaseId in item.phases){
747
+ const node = item.phases[phaseId];
748
+ if (Object.prototype.hasOwnProperty.call(item.phases, phaseId)) {
749
+ errors.push(...validateNode(node, [
750
+ ...basePath,
751
+ 'phases',
752
+ phaseId
753
+ ]));
754
+ }
755
+ }
756
+ for(const phaseId in item.phases){
757
+ if (Object.prototype.hasOwnProperty.call(item.phases, phaseId)) {
758
+ const node = item.phases[phaseId];
759
+ if (node && typeof node === 'object' && node.next) {
760
+ if (Array.isArray(node.next)) {
761
+ const transitions = node.next;
762
+ if (transitions.length > 0 && transitions.every((t)=>isConnection(t))) {
763
+ transitions.forEach((connection, index)=>{
764
+ if (connection && typeof connection.targetNodeId === 'string') {
765
+ if (!(connection.targetNodeId in item.phases)) {
766
+ errors.push({
767
+ coordinates: [
768
+ ...basePath,
769
+ 'phases',
770
+ phaseId,
771
+ 'next',
772
+ connection.id || `connection-at-index-${index}`
773
+ ],
774
+ error: `Node "${phaseId}" has a connection to non-existent targetNodeId "${connection.targetNodeId}".`
775
+ });
776
+ }
777
+ } else if (!connection || connection.targetNodeId === undefined) ;
778
+ });
779
+ }
780
+ }
781
+ }
782
+ }
783
+ }
784
+ }
785
+ return errors;
786
+ };
787
+
788
+ const createProcessEvent = (sourceId, stage, process, data)=>{
789
+ const event = createEvent('process', sourceId, stage, data);
790
+ return {
791
+ ...event,
792
+ process
793
+ };
794
+ };
795
+ const isProcessEvent = (item)=>{
796
+ return item !== null && item !== undefined && typeof item === 'object' && item.type === 'process' && item.process !== null && item.process !== undefined && item.stage !== null && item.stage !== undefined;
797
+ };
798
+
799
+ function _define_property(obj, key, value) {
800
+ if (key in obj) {
801
+ Object.defineProperty(obj, key, {
802
+ value: value,
803
+ enumerable: true,
804
+ configurable: true,
805
+ writable: true
806
+ });
807
+ } else {
808
+ obj[key] = value;
809
+ }
810
+ return obj;
811
+ }
812
+ class Deferred {
813
+ constructor(){
814
+ _define_property(this, "promise", void 0);
815
+ _define_property(this, "resolve", void 0);
816
+ _define_property(this, "reject", void 0);
817
+ this.promise = new Promise((resolve, reject)=>{
818
+ this.resolve = resolve;
819
+ this.reject = reject;
820
+ });
821
+ }
822
+ }
823
+ function createAggregatorState() {
824
+ return {
825
+ aggregatorDeferreds: new Map(),
826
+ registerPendingAggregator (nodeId) {
827
+ let deferred = this.aggregatorDeferreds.get(nodeId);
828
+ if (!deferred) {
829
+ deferred = new Deferred();
830
+ this.aggregatorDeferreds.set(nodeId, deferred);
831
+ }
832
+ return deferred;
833
+ },
834
+ resolvePendingAggregator (nodeId, output) {
835
+ const deferred = this.aggregatorDeferreds.get(nodeId);
836
+ if (deferred) {
837
+ deferred.resolve(output);
838
+ this.aggregatorDeferreds.delete(nodeId);
839
+ }
840
+ },
841
+ getPendingAggregator (nodeId) {
842
+ return this.aggregatorDeferreds.get(nodeId);
843
+ },
844
+ pendingAggregatorIds () {
845
+ return Array.from(this.aggregatorDeferreds.keys());
846
+ }
847
+ };
848
+ }
849
+ async function executeAggregatorNode(nodeId, node, input, state) {
850
+ dispatchEvent(state.eventState, createAggregatorEvent(nodeId, 'start', node.aggregator, {
851
+ input
852
+ }), state.context);
853
+ let deferred = state.getPendingAggregator(nodeId);
854
+ const aggregationResult = await node.aggregator.aggregate(input, state.context);
855
+ dispatchEvent(state.eventState, createAggregatorEvent(nodeId, 'aggregate', node.aggregator, {
856
+ input,
857
+ result: aggregationResult
858
+ }), state.context);
859
+ if (aggregationResult.status === 'Ready') {
860
+ const output = aggregationResult.output;
861
+ dispatchEvent(state.eventState, createAggregatorEvent(nodeId, 'ready', node.aggregator, {
862
+ output
863
+ }), state.context);
864
+ state.resolvePendingAggregator(nodeId, output);
865
+ return output;
866
+ }
867
+ dispatchEvent(state.eventState, createAggregatorEvent(nodeId, 'defer', node.aggregator, {
868
+ input,
869
+ result: aggregationResult
870
+ }), state.context);
871
+ deferred = deferred !== null && deferred !== void 0 ? deferred : state.registerPendingAggregator(nodeId);
872
+ return deferred.promise;
873
+ }
874
+
875
+ // Helper function to handle the next step in the process
876
+ async function handleNextStep(nodeOutput, nodeId, next, state) {
877
+ //console.log('[_HANDLE_NEXT_STEP_START]', { nodeId, nodeOutput, nextType: next && next.constructor ? next.constructor.name : typeof next, next });
878
+ if (Array.isArray(next) && next.length > 0 && next.every(isDecision)) {
879
+ const decisions = next;
880
+ // console.log('[_HANDLE_NEXT_STEP_DECISIONS]', { nodeId, count: decisions.length, decisions });
881
+ for (const decision of decisions){
882
+ // console.log('[_HANDLE_NEXT_STEP_DECISION_PROCESSING]', { nodeId, decisionId: decision.id, decision });
883
+ await dispatchEvent(state.eventState, createDecisionEvent(nodeId, 'start', decision, {
884
+ output: nodeOutput
885
+ }), state.context);
886
+ try {
887
+ const decisionOutcome = await decision.decide(nodeOutput, state.context);
888
+ await dispatchEvent(state.eventState, createDecisionEvent(nodeId, 'decide', decision, {
889
+ output: nodeOutput,
890
+ result: decisionOutcome
891
+ }), state.context);
892
+ // console.log('[_HANDLE_NEXT_STEP_DECISION_OUTCOME]', { nodeId, decisionId: decision.id, decisionOutcome });
893
+ await handleNextStep(nodeOutput, decision.id, decisionOutcome, state); // outcome processed, decision.id is context for next step if it's an error source. The original nodeId is implicitly the source of this decision.
894
+ await dispatchEvent(state.eventState, createDecisionEvent(nodeId, 'end', decision), state.context);
895
+ } catch (decisionError) {
896
+ const errorMessage = `Decision error on '${decision.id}' from node '${nodeId}': ${decisionError.message}`;
897
+ // eslint-disable-next-line no-console
898
+ console.error(`[_HANDLE_NEXT_STEP_DECISION_ERROR]`, {
899
+ error: errorMessage,
900
+ decisionError,
901
+ decisionId: decision.id,
902
+ sourceNodeId: nodeId
903
+ });
904
+ state.errors.push({
905
+ nodeId: decision.id,
906
+ message: errorMessage,
907
+ details: {
908
+ sourceNodeId: nodeId,
909
+ originalError: decisionError.message
910
+ }
911
+ });
912
+ // Note: Decision errors are logged but do not halt the process.
913
+ // This allows other parallel decisions to continue executing.
914
+ // If you need decision errors to halt execution, consider throwing here
915
+ // or checking state.errors after process completion.
916
+ }
917
+ }
918
+ } else if (Array.isArray(next) && next.length > 0 && next.every(isConnection)) {
919
+ //console.log('[_HANDLE_NEXT_STEP_CONNECTIONS]', { nodeId, count: next.length, connections: next });
920
+ const connections = next;
921
+ const nextPhasePromises = [];
922
+ for (const connection of connections){
923
+ let nextInput = nodeOutput;
924
+ let nextContext = state.context;
925
+ await dispatchEvent(state.eventState, createConnectionEvent(nodeId, 'start', connection, {
926
+ input: nextInput
927
+ }), state.context);
928
+ if (connection.transform) {
929
+ //console.log('[_HANDLE_NEXT_STEP_CONNECTION_TRANSFORM_START]', { nodeId, targetNodeId: connection.targetNodeId });
930
+ try {
931
+ const context = state.context;
932
+ [nextInput, nextContext] = await connection.transform(nodeOutput, context);
933
+ await dispatchEvent(state.eventState, createConnectionEvent(nodeId, 'transform', connection, {
934
+ input: nextInput,
935
+ output: nodeOutput,
936
+ context: nextContext
937
+ }), state.context);
938
+ state.context = nextContext;
939
+ //console.log('[_HANDLE_NEXT_STEP_CONNECTION_TRANSFORM_SUCCESS]', { nodeId, targetNodeId: connection.targetNodeId, nextInput, nextContext });
940
+ } catch (transformError) {
941
+ const errorMessage = `Transform error on connection '${connection.id}' from node '${nodeId}' to '${connection.targetNodeId}': ${transformError.message}`;
942
+ // eslint-disable-next-line no-console
943
+ console.error(`[_HANDLE_NEXT_STEP_CONNECTION_TRANSFORM_ERROR]`, {
944
+ error: errorMessage,
945
+ transformError,
946
+ connectionId: connection.id,
947
+ sourceNodeId: nodeId,
948
+ targetNodeId: connection.targetNodeId
949
+ });
950
+ // Store error with connection ID for better traceability
951
+ state.errors.push({
952
+ nodeId: connection.id,
953
+ message: errorMessage,
954
+ details: {
955
+ sourceNodeId: nodeId,
956
+ targetNodeId: connection.targetNodeId,
957
+ originalError: transformError.message
958
+ }
959
+ });
960
+ continue;
961
+ }
962
+ }
963
+ //console.log('[_HANDLE_NEXT_STEP_CONNECTION_EXECUTE_TARGET]', { nodeId, targetNodeId: connection.targetNodeId, nextInput });
964
+ nextPhasePromises.push(executeNode(connection.targetNodeId, nextInput, state));
965
+ await dispatchEvent(state.eventState, createConnectionEvent(nodeId, 'end', connection), state.context);
966
+ }
967
+ // Optional: await Promise.all(nextPhasePromises); // Current design relies on executeProcess waiting on activeExecutions
968
+ //console.log('[_HANDLE_NEXT_STEP_CONNECTIONS_PROMISES_PUSHED]', { nodeId, count: nextPhasePromises.length });
969
+ } else if (isTermination(next)) {
970
+ //console.log('[_HANDLE_NEXT_STEP_TERMINATION]', { nodeId, termination: next });
971
+ const termination = next;
972
+ await dispatchEvent(state.eventState, createTerminationEvent(nodeId, 'start', termination, {
973
+ output: nodeOutput
974
+ }), state.context);
975
+ const result = nodeOutput;
976
+ if (termination.terminate) {
977
+ //console.log('[_HANDLE_NEXT_STEP_TERMINATION_CALLING_TERMINATE_FN]', { nodeId, terminationId: termination.id });
978
+ await termination.terminate(nodeOutput, state.context);
979
+ await dispatchEvent(state.eventState, createTerminationEvent(nodeId, 'terminate', termination, {
980
+ output: nodeOutput
981
+ }), state.context);
982
+ }
983
+ state.results[termination.id] = result;
984
+ } else if (Array.isArray(next) && next.length === 0) {
985
+ // Empty array from a Decision means no path should be taken from this node.
986
+ // This is treated as an implicit termination, storing the result with a generated key.
987
+ // Note: This behavior means a Decision can dynamically terminate a process path.
988
+ const result = nodeOutput;
989
+ const implicitTerminationId = `${nodeId}_implicit_end`;
990
+ state.results[implicitTerminationId] = result;
991
+ // eslint-disable-next-line no-console
992
+ console.warn(`[_HANDLE_NEXT_STEP_IMPLICIT_TERMINATION] Node ${nodeId} received empty next array, treating as implicit termination with id: ${implicitTerminationId}`);
993
+ } else {
994
+ // If there is no next (e.g. next is undefined or null after a decision), or it's an unhandled type.
995
+ // Consider this an end state and store the result with the nodeId
996
+ //console.log('[_HANDLE_NEXT_STEP_NO_NEXT_OR_UNHANDLED]', { nodeId, next, nodeOutput });
997
+ const result = nodeOutput;
998
+ state.results[nodeId] = result;
999
+ }
1000
+ //console.log('[_HANDLE_NEXT_STEP_END]', { nodeId });
1001
+ }
1002
+
1003
+ function createPhaseEvent(sourceId, stage, phase, data) {
1004
+ const event = createEvent('phase', sourceId, stage, data);
1005
+ return {
1006
+ ...event,
1007
+ phase
1008
+ };
1009
+ }
1010
+
1011
+ async function executePhase(nodeId, node, input, state) {
1012
+ dispatchEvent(state.eventState, createPhaseEvent(nodeId, 'start', node.phase, {
1013
+ input
1014
+ }), state.context);
1015
+ if (node.phase.verify) {
1016
+ const verifyResponse = await node.phase.verify(input);
1017
+ if (!verifyResponse.verified) {
1018
+ throw new Error(verifyResponse.messages.join('\n'));
1019
+ }
1020
+ }
1021
+ const output = await node.phase.execute(input);
1022
+ dispatchEvent(state.eventState, createPhaseEvent(nodeId, 'execute', node.phase, {
1023
+ input,
1024
+ output
1025
+ }), state.context);
1026
+ return output;
1027
+ }
1028
+
1029
+ async function executeNode(nodeId, input, state) {
1030
+ //console.log('[EXECUTE_NODE_RECURSIVE_START]', { nodeId, input, phaseResultsKeys: Object.keys(state.phaseResults), activeExecutionsKeys: Array.from(state.activeExecutions.keys()), aggregatorDeferredsKeys: Array.from(state.aggregatorDeferreds.keys()) });
1031
+ // 1. Check if result is already cached in phaseResults (final output, node fully completed)
1032
+ if (state.phaseResults[nodeId]) {
1033
+ //console.log('[EXECUTE_NODE_RECURSIVE_CACHE_HIT_PHASERESULTS]', { nodeId, result: state.phaseResults[nodeId] });
1034
+ return state.phaseResults[nodeId];
1035
+ }
1036
+ const node = state.process.phases[nodeId];
1037
+ if (!node) {
1038
+ const error = new Error(`Node with ID "${nodeId}" not found.`);
1039
+ //console.error('[EXECUTE_NODE_RECURSIVE_NODE_NOT_FOUND]', { nodeId, error });
1040
+ state.errors.push({
1041
+ nodeId,
1042
+ message: error.message
1043
+ });
1044
+ throw error;
1045
+ }
1046
+ //console.log('[EXECUTE_NODE_RECURSIVE_NODE_FOUND]', { nodeId, nodeType: node.constructor.name, node });
1047
+ // 2. Handle active/pending executions
1048
+ // If it's an aggregator that has a deferred promise, it means it's pending.
1049
+ // We need to re-evaluate it with the current input. The IIFE below will handle this.
1050
+ if (state.activeExecutions.has(nodeId) && !isAggregatorNode(node)) {
1051
+ // For non-aggregators, if already active, return the promise.
1052
+ // Aggregators will fall through to the IIFE to allow input processing.
1053
+ // The IIFE itself handles returning a shared deferred promise if needed.
1054
+ //console.log('[EXECUTE_NODE_RECURSIVE_ACTIVE_EXECUTION_HIT_NON_AGGREGATOR]', { nodeId });
1055
+ return state.activeExecutions.get(nodeId);
1056
+ }
1057
+ // If it IS an aggregator and state.activeExecutions.has(nodeId),
1058
+ // it means its deferred.promise might be in activeExecutions from a previous input that made it pending.
1059
+ // The IIFE logic below will correctly retrieve this deferred (if it exists and is still relevant)
1060
+ // from state.aggregatorDeferreds.get(nodeId) and use its promise, or process the input.
1061
+ //console.log('[EXECUTE_NODE_RECURSIVE_CONTINUING_TO_EXECUTION_LOGIC]', { nodeId, isActive: state.activeExecutions.has(nodeId), isAggregator: isAggregatorNode(node), hasDeferred: state.aggregatorDeferreds.has(nodeId) });
1062
+ // If it's an aggregator and it's pending (has a deferred), we fall through to re-execute its logic within the IIFE.
1063
+ // If it's the first call to any node, we fall through.
1064
+ // 3. Mark as active and execute (or re-evaluate pending aggregator)
1065
+ const executionPromise = (async ()=>{
1066
+ //console.log('[EXECUTE_NODE_RECURSIVE_IIFE_START]', { nodeId, input });
1067
+ try {
1068
+ let output;
1069
+ if (isAggregatorNode(node)) {
1070
+ dispatchEvent(state.eventState, createAggregatorNodeEvent(nodeId, 'start', node, {
1071
+ input
1072
+ }), state.context);
1073
+ output = await executeAggregatorNode(nodeId, node, input, state);
1074
+ } else if (isPhaseNode(node)) {
1075
+ dispatchEvent(state.eventState, createPhaseNodeEvent(nodeId, 'start', node, {
1076
+ input
1077
+ }), state.context);
1078
+ if (node.prepare) {
1079
+ const [preparedInput, preparedContext] = await node.prepare(input, state.context);
1080
+ input = preparedInput;
1081
+ state.context = preparedContext;
1082
+ }
1083
+ dispatchEvent(state.eventState, createPhaseNodeEvent(nodeId, 'prepared', node, {
1084
+ input
1085
+ }), state.context);
1086
+ output = await executePhase(nodeId, node, input, state);
1087
+ if (node.process) {
1088
+ const [processedOutput, processedContext] = await node.process(output, state.context);
1089
+ output = processedOutput;
1090
+ state.context = processedContext;
1091
+ }
1092
+ dispatchEvent(state.eventState, createPhaseNodeEvent(nodeId, 'processed', node, {
1093
+ input,
1094
+ output
1095
+ }), state.context);
1096
+ //console.log('[EXECUTE_NODE_RECURSIVE_PHASE_NODE_EXECUTE_END]', { nodeId, output });
1097
+ } else {
1098
+ const error = new Error(`Unknown or invalid node type for ID "${nodeId}". Expected PhaseNode or AggregatorNode.`);
1099
+ //console.error('[EXECUTE_NODE_RECURSIVE_UNKNOWN_NODE_TYPE]', { nodeId, node, error });
1100
+ throw error;
1101
+ }
1102
+ state.phaseResults[nodeId] = output; // Set final output once ready/executed
1103
+ //console.log('[EXECUTE_NODE_RECURSIVE_PHASE_RESULT_CACHED]', { nodeId, output });
1104
+ // 4. Handle next step
1105
+ if (node.next) {
1106
+ //console.log('[EXECUTE_NODE_RECURSIVE_HANDLING_NEXT_STEP]', { nodeId, nextType: node.next.constructor.name, next: node.next });
1107
+ if (Array.isArray(node.next) && node.next.length > 0 && node.next.every(isDecision)) {
1108
+ //console.log('[EXECUTE_NODE_RECURSIVE_DECISIONS_FOUND]', { nodeId, count: node.next.length, decisions: node.next });
1109
+ const decisions = node.next;
1110
+ const decisionExecutionPromises = [];
1111
+ for (const decision of decisions){
1112
+ dispatchEvent(state.eventState, createDecisionEvent(nodeId, 'start', decision, {
1113
+ output
1114
+ }), state.context);
1115
+ const decisionPromise = (async ()=>{
1116
+ //console.log('[EXECUTE_NODE_RECURSIVE_DECISION_EXECUTE_START]', { nodeId, decisionId: decision.id, output });
1117
+ try {
1118
+ const decisionOutcome = await decision.decide(output, state.context);
1119
+ dispatchEvent(state.eventState, createDecisionEvent(nodeId, 'decide', decision, {
1120
+ output,
1121
+ result: decisionOutcome
1122
+ }), state.context);
1123
+ //console.log('[EXECUTE_NODE_RECURSIVE_DECISION_OUTCOME]', { nodeId, decisionId: decision.id, decisionOutcome });
1124
+ await handleNextStep(output, decision.id, decisionOutcome, state);
1125
+ dispatchEvent(state.eventState, createDecisionEvent(nodeId, 'end', decision), state.context);
1126
+ } catch (decisionError) {
1127
+ const errorMessage = `Decision error on '${decision.id}' for node '${nodeId}': ${decisionError.message}`;
1128
+ // eslint-disable-next-line no-console
1129
+ console.error(`[_HANDLE_NEXT_STEP_DECISION_ERROR]`, {
1130
+ error: errorMessage,
1131
+ decisionError,
1132
+ decisionId: decision.id,
1133
+ sourceNodeId: nodeId
1134
+ });
1135
+ state.errors.push({
1136
+ nodeId: decision.id,
1137
+ message: errorMessage,
1138
+ details: {
1139
+ sourceNodeId: nodeId,
1140
+ originalError: decisionError.message
1141
+ }
1142
+ });
1143
+ }
1144
+ })();
1145
+ decisionExecutionPromises.push(decisionPromise);
1146
+ }
1147
+ //console.log('[EXECUTE_NODE_RECURSIVE_WAITING_FOR_DECISIONS]', { nodeId, count: decisionExecutionPromises.length });
1148
+ await Promise.all(decisionExecutionPromises);
1149
+ //console.log('[EXECUTE_NODE_RECURSIVE_DECISIONS_COMPLETE]', { nodeId });
1150
+ } else {
1151
+ //console.log('[EXECUTE_NODE_RECURSIVE_CALLING_HANDLE_NEXT_STEP_FOR_NON_DECISION]', { nodeId, next: node.next });
1152
+ await handleNextStep(output, nodeId, node.next, state);
1153
+ }
1154
+ } else {
1155
+ //console.log('[EXECUTE_NODE_RECURSIVE_NO_NEXT_NODE_IMPLICIT_TERMINATION]', { nodeId, output });
1156
+ const result = output;
1157
+ state.results[nodeId] = result;
1158
+ }
1159
+ if (isPhaseNode(node)) {
1160
+ dispatchEvent(state.eventState, createPhaseNodeEvent(nodeId, 'end', node, {
1161
+ input,
1162
+ output
1163
+ }), state.context);
1164
+ } else {
1165
+ dispatchEvent(state.eventState, createAggregatorNodeEvent(nodeId, 'end', node, {
1166
+ input,
1167
+ output
1168
+ }), state.context);
1169
+ }
1170
+ //console.log('[EXECUTE_NODE_RECURSIVE_IIFE_RETURNING_OUTPUT]', { nodeId, output });
1171
+ return output;
1172
+ } catch (error) {
1173
+ // eslint-disable-next-line no-console
1174
+ console.error(`[EXECUTE_NODE_RECURSIVE_IIFE_ERROR] Error executing node ${nodeId}:`, {
1175
+ error,
1176
+ nodeId
1177
+ });
1178
+ state.errors.push({
1179
+ nodeId,
1180
+ message: error.message
1181
+ });
1182
+ // Clean up any pending aggregator deferred on error
1183
+ if (state.aggregatorDeferreds.has(nodeId)) {
1184
+ const deferred = state.aggregatorDeferreds.get(nodeId);
1185
+ if (deferred) {
1186
+ deferred.reject(error);
1187
+ }
1188
+ state.aggregatorDeferreds.delete(nodeId);
1189
+ }
1190
+ throw error;
1191
+ } finally{
1192
+ //console.log('[EXECUTE_NODE_RECURSIVE_IIFE_FINALLY]', { nodeId, hasAggregatorDeferred: state.aggregatorDeferreds.has(nodeId) });
1193
+ // If a node completed (not pending via deferred mechanism) or an error occurred.
1194
+ // An aggregator that is still pending (has a deferred) should keep its promise in activeExecutions.
1195
+ if (!state.aggregatorDeferreds.has(nodeId)) {
1196
+ //console.log('[EXECUTE_NODE_RECURSIVE_IIFE_FINALLY_DELETING_ACTIVE_EXECUTION]', { nodeId });
1197
+ state.activeExecutions.delete(nodeId);
1198
+ }
1199
+ }
1200
+ })();
1201
+ // Store the promise from the IIFE.
1202
+ // If it's an aggregator that went pending, executionPromise IS deferred.promise.
1203
+ // If it's an aggregator that became ready, executionPromise is a promise resolving to its output.
1204
+ // If it's a phase node, executionPromise is a promise resolving to its output.
1205
+ //console.log('[EXECUTE_NODE_RECURSIVE_SETTING_ACTIVE_EXECUTION]', { nodeId });
1206
+ state.activeExecutions.set(nodeId, executionPromise);
1207
+ //console.log('[EXECUTE_NODE_RECURSIVE_END_RETURNING_PROMISE]', { nodeId });
1208
+ return executionPromise;
1209
+ }
1210
+
1211
+ const EMPTY_INPUT = {};
1212
+
1213
+ const DEFAULT_PROCESS_EXECUTION_OPTIONS = {
1214
+ input: EMPTY_INPUT,
1215
+ context: {},
1216
+ eventHandlers: []
1217
+ };
1218
+ async function executeProcess(processInstance, beginning, options) {
1219
+ const processExecutionOptions = {
1220
+ ...DEFAULT_PROCESS_EXECUTION_OPTIONS,
1221
+ ...clean(options || {})
1222
+ };
1223
+ if (options && options.input) {
1224
+ processExecutionOptions.input = options.input;
1225
+ }
1226
+ if (options && options.eventHandlers) {
1227
+ processExecutionOptions.eventHandlers = options.eventHandlers;
1228
+ }
1229
+ const validationErrors = validateProcess(processInstance);
1230
+ if (validationErrors.length > 0) {
1231
+ const errorMessages = validationErrors.map((err)=>err.error).join('\n');
1232
+ throw new Error(`Invalid process definition:\n${errorMessages}`);
1233
+ }
1234
+ const eventState = createEventState(processExecutionOptions.eventHandlers);
1235
+ const state = {
1236
+ process: processInstance,
1237
+ context: processExecutionOptions.context,
1238
+ results: {},
1239
+ phaseResults: {},
1240
+ activeExecutions: new Map(),
1241
+ errors: [],
1242
+ ...createAggregatorState(),
1243
+ eventState: eventState
1244
+ };
1245
+ dispatchEvent(state.eventState, createProcessEvent(processInstance.name, 'start', processInstance, {
1246
+ input: processExecutionOptions.input,
1247
+ context: state.context
1248
+ }), state.context);
1249
+ dispatchEvent(state.eventState, createBeginningEvent(beginning.id, 'start', beginning, {
1250
+ input: processExecutionOptions.input
1251
+ }), state.context);
1252
+ const initialInput = await beginning.begin(processExecutionOptions.input, state.context);
1253
+ dispatchEvent(state.eventState, createBeginningEvent(beginning.id, 'begin', beginning, {
1254
+ input: initialInput
1255
+ }), state.context);
1256
+ const initialNodeId = beginning.targetNodeId;
1257
+ if (!state.process.phases[initialNodeId]) {
1258
+ throw new Error(`Start phase ID "${initialNodeId}" not found in process phases.`);
1259
+ }
1260
+ try {
1261
+ await executeNode(initialNodeId, initialInput, state);
1262
+ const allPromises = Array.from(state.activeExecutions.values());
1263
+ if (allPromises.length > 0) {
1264
+ await Promise.all(allPromises);
1265
+ }
1266
+ } catch (error) {
1267
+ const errorMessage = error instanceof Error ? error.message : String(error);
1268
+ state.errors.push({
1269
+ message: "Critical error during process execution",
1270
+ details: errorMessage,
1271
+ nodeId: initialNodeId
1272
+ });
1273
+ // eslint-disable-next-line no-console
1274
+ console.error("[EXECUTE_PROCESS_CRITICAL_ERROR]", {
1275
+ processName: processInstance.name,
1276
+ error: errorMessage,
1277
+ collectedErrors: state.errors
1278
+ });
1279
+ }
1280
+ // Check for and reject any pending aggregators that never completed
1281
+ if (state.aggregatorDeferreds && state.aggregatorDeferreds.size > 0) {
1282
+ const pendingNodeIds = state.pendingAggregatorIds ? state.pendingAggregatorIds().join(', ') : 'unknown';
1283
+ // eslint-disable-next-line no-console
1284
+ console.warn(`[EXECUTE_PROCESS_PENDING_AGGREGATORS] Process execution completed with pending aggregators: ${pendingNodeIds}. These will be rejected.`, {
1285
+ processName: processInstance.name,
1286
+ pendingNodeIds
1287
+ });
1288
+ // Reject all pending aggregators to prevent hanging promises
1289
+ for (const nodeId of state.aggregatorDeferreds.keys()){
1290
+ const deferred = state.aggregatorDeferreds.get(nodeId);
1291
+ if (deferred) {
1292
+ const error = new Error(`Aggregator node '${nodeId}' did not receive all expected inputs before process completion. This may indicate a process design issue where not all paths leading to the aggregator were executed.`);
1293
+ deferred.reject(error);
1294
+ state.errors.push({
1295
+ nodeId,
1296
+ message: error.message,
1297
+ details: {
1298
+ reason: 'incomplete_aggregation'
1299
+ }
1300
+ });
1301
+ }
1302
+ }
1303
+ // Clear the map after rejecting all
1304
+ state.aggregatorDeferreds.clear();
1305
+ }
1306
+ dispatchEvent(state.eventState, createProcessEvent(processInstance.name, 'end', processInstance, {
1307
+ input: processExecutionOptions.input,
1308
+ context: state.context
1309
+ }), state.context);
1310
+ return [
1311
+ state.results,
1312
+ state.phaseResults,
1313
+ state.context
1314
+ ];
1315
+ }
1316
+
1317
+ exports.createAggregator = createAggregator;
1318
+ exports.createAggregatorEvent = createAggregatorEvent;
1319
+ exports.createAggregatorNode = createAggregatorNode;
1320
+ exports.createBeginning = createBeginning;
1321
+ exports.createBeginningEvent = createBeginningEvent;
1322
+ exports.createConnection = createConnection;
1323
+ exports.createConnectionEvent = createConnectionEvent;
1324
+ exports.createDecision = createDecision;
1325
+ exports.createDecisionEvent = createDecisionEvent;
1326
+ exports.createEventFilter = createEventFilter;
1327
+ exports.createEventHandler = createEventHandler;
1328
+ exports.createEventState = createEventState;
1329
+ exports.createFilteredHandler = createFilteredHandler;
1330
+ exports.createNode = createNode;
1331
+ exports.createNodeEvent = createNodeEvent;
1332
+ exports.createPhase = createPhase;
1333
+ exports.createPhaseNode = createPhaseNode;
1334
+ exports.createProcess = createProcess;
1335
+ exports.createProcessEvent = createProcessEvent;
1336
+ exports.createTermination = createTermination;
1337
+ exports.createTerminationEvent = createTerminationEvent;
1338
+ exports.createTransitionEvent = createTransitionEvent;
1339
+ exports.dispatchEvent = dispatchEvent;
1340
+ exports.executeProcess = executeProcess;
1341
+ exports.isAggregator = isAggregator;
1342
+ exports.isAggregatorEvent = isAggregatorEvent;
1343
+ exports.isAggregatorNode = isAggregatorNode;
1344
+ exports.isAggregatorNodeEvent = isAggregatorNodeEvent;
1345
+ exports.isBeginning = isBeginning;
1346
+ exports.isBeginningEvent = isBeginningEvent;
1347
+ exports.isConnection = isConnection;
1348
+ exports.isConnectionEvent = isConnectionEvent;
1349
+ exports.isDecision = isDecision;
1350
+ exports.isDecisionEvent = isDecisionEvent;
1351
+ exports.isNode = isNode;
1352
+ exports.isNodeEvent = isNodeEvent;
1353
+ exports.isPhase = isPhase;
1354
+ exports.isPhaseNode = isPhaseNode;
1355
+ exports.isPhaseNodeEvent = isPhaseNodeEvent;
1356
+ exports.isProcess = isProcess;
1357
+ exports.isProcessEvent = isProcessEvent;
1358
+ exports.isTermination = isTermination;
1359
+ exports.isTerminationEvent = isTerminationEvent;
1360
+ exports.isTransition = isTransition;
1361
+ exports.validateNode = validateNode;
1362
+ //# sourceMappingURL=xenocline.cjs.map