arvo-event-handler 3.0.14 → 3.0.15

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 (39) hide show
  1. package/dist/ArvoEventHandler/index.d.ts +20 -123
  2. package/dist/ArvoEventHandler/index.js +5 -112
  3. package/dist/ArvoMachine/createMachine.d.ts +103 -158
  4. package/dist/ArvoMachine/createMachine.js +59 -181
  5. package/dist/ArvoMachine/index.d.ts +5 -57
  6. package/dist/ArvoMachine/index.js +8 -117
  7. package/dist/ArvoMachine/types.d.ts +0 -82
  8. package/dist/ArvoMachine/utils.d.ts +0 -15
  9. package/dist/ArvoMachine/utils.js +0 -15
  10. package/dist/ArvoOrchestrationUtils/createEmitableEvent.d.ts +31 -0
  11. package/dist/ArvoOrchestrationUtils/createEmitableEvent.js +18 -0
  12. package/dist/ArvoOrchestrationUtils/error.d.ts +22 -0
  13. package/dist/ArvoOrchestrationUtils/error.js +21 -0
  14. package/dist/ArvoOrchestrationUtils/handlerErrors.d.ts +30 -2
  15. package/dist/ArvoOrchestrationUtils/handlerErrors.js +19 -2
  16. package/dist/ArvoOrchestrationUtils/inputValidation.d.ts +47 -0
  17. package/dist/ArvoOrchestrationUtils/inputValidation.js +120 -0
  18. package/dist/ArvoOrchestrationUtils/orchestrationExecutionState.d.ts +24 -1
  19. package/dist/ArvoOrchestrationUtils/orchestrationExecutionState.js +9 -1
  20. package/dist/ArvoOrchestrationUtils/orchestrationExecutionWrapper/acquireLockWithValidation.d.ts +5 -1
  21. package/dist/ArvoOrchestrationUtils/orchestrationExecutionWrapper/acquireLockWithValidation.js +5 -1
  22. package/dist/ArvoOrchestrationUtils/orchestrationExecutionWrapper/index.d.ts +44 -5
  23. package/dist/ArvoOrchestrationUtils/orchestrationExecutionWrapper/index.js +17 -5
  24. package/dist/ArvoOrchestrationUtils/orchestrationExecutionWrapper/validateAndParseSubject.d.ts +6 -1
  25. package/dist/ArvoOrchestrationUtils/orchestrationExecutionWrapper/validateAndParseSubject.js +6 -1
  26. package/dist/ArvoOrchestrationUtils/servicesValidation.d.ts +14 -6
  27. package/dist/ArvoOrchestrationUtils/servicesValidation.js +14 -6
  28. package/dist/ArvoOrchestrator/factory.d.ts +18 -15
  29. package/dist/ArvoOrchestrator/factory.js +19 -16
  30. package/dist/ArvoOrchestrator/index.d.ts +51 -19
  31. package/dist/ArvoOrchestrator/index.js +29 -17
  32. package/dist/ArvoOrchestrator/types.d.ts +74 -49
  33. package/dist/ArvoResumable/factory.d.ts +31 -36
  34. package/dist/ArvoResumable/factory.js +29 -18
  35. package/dist/ArvoResumable/index.d.ts +69 -65
  36. package/dist/ArvoResumable/index.js +49 -92
  37. package/dist/ArvoResumable/types.d.ts +177 -72
  38. package/dist/IArvoEventHandler/index.d.ts +29 -15
  39. package/package.json +2 -2
@@ -5,13 +5,11 @@ import type { z } from 'zod';
5
5
  * Represents an extended context for Arvo XState machines, including additional properties
6
6
  * for volatile and internal data.
7
7
  *
8
- * @remarks
9
8
  * This type extends the base XState MachineContext with additional properties
10
9
  * to provide more flexibility and organization in storing machine-related data.
11
10
  *
12
11
  * The `$$` suffix in property names is used to indicate special storage objects within the context.
13
12
  *
14
- * @note
15
13
  * To avoid runtime errors, it is recommended not to use `arvo$$` object at all in the
16
14
  * machine context
17
15
  */
@@ -27,12 +25,6 @@ export type ArvoMachineContext = {
27
25
  * Represents the parameters for the emitArvoEvent action in ArvoXState.
28
26
  * This type defines a subset of properties from the CreateArvoEvent type,
29
27
  * specifically tailored for emitting an ArvoEvent within the state machine context.
30
- *
31
- * @remarks
32
- * The EmitArvoEventActionParam type is crucial for maintaining consistency and
33
- * type safety when emitting events in an ArvoXState machine. It ensures that
34
- * only relevant properties are included and properly typed.
35
- * ```
36
28
  */
37
29
  export type EnqueueArvoEventActionParam<TData extends ArvoEventData = ArvoEventData, TType extends string = string, TExtension extends CloudEventExtension = CloudEventExtension> = {
38
30
  /**
@@ -41,107 +33,46 @@ export type EnqueueArvoEventActionParam<TData extends ArvoEventData = ArvoEventD
41
33
  id?: CreateArvoEvent<TData, TType>['id'];
42
34
  /**
43
35
  * The domain configuration for multi-domain event broadcasting.
44
- *
45
- * When an event is emitted with a `domain` array, Arvo generates a separate ArvoEvent
46
- * for each resolved domain value. This enables parallel routing to multiple contexts
47
- * such as analytics, auditing, human-in-the-loop systems, or external integrations.
48
- *
49
- * **Accepted Values:**
50
- * - A concrete domain string (e.g. `'audit.orders'`)
51
- * - `null` for standard internal routing (no domain)
52
- * - A symbolic value from {@link ArvoDomain}.
53
- *
54
- * **Broadcasting Rules:**
55
- * - Each resolved domain in the array creates a separate ArvoEvent instance
56
- * - Duplicate resolved domains are automatically removed
57
- * - If the field is omitted, Arvo defaults to `[null]`
58
- *
59
- * **Examples:**
60
- * - `['analytics.orders', 'audit.orders']` → Creates two routed events
61
- * - `[ArvoDomain.FROM_TRIGGERING_EVENT, 'human.review', null]` → Mirrors source domain, routes to review, and standard consumer
62
- * - `[null]` → Emits a single event with no domain routing
63
- * - _Omitted_ → Same as `[null]`
64
36
  */
65
37
  domain?: (string | null)[];
66
38
  /**
67
39
  * Custom extensions for the CloudEvent.
68
40
  * Allows for additional metadata to be attached to the event.
69
- *
70
- * @remarks
71
- * Use this field to include any non-standard attributes that are not
72
- * covered by the core CloudEvent specification or Arvo extensions.
73
41
  */
74
42
  __extensions?: TExtension;
75
43
  /**
76
44
  * Defines access controls for the event.
77
45
  * Can be a UserID, encrypted string, or key-value pairs.
78
- *
79
- * @remarks
80
- * This field is used to implement fine-grained access control on event
81
- * consumption. The exact format and interpretation may depend on your
82
- * system's access control mechanisms.
83
46
  */
84
47
  accesscontrol?: string;
85
48
  /**
86
49
  * The event payload. This payload must be JSON serializable.
87
- *
88
- * @remarks
89
- * The data field contains the event-specific information. Ensure that
90
- * the structure of this data conforms to the schema specified in the
91
- * `dataschema` field, if provided.
92
50
  */
93
51
  data: TData;
94
52
  /**
95
53
  * Identifies the schema that the `data` adheres to.
96
- * Must be a valid URI if present.
97
- *
98
- * @remarks
99
- * Use this field to provide a link to the schema definition for the
100
- * event data. This helps consumers understand and validate the event structure.
101
54
  */
102
55
  dataschema?: string;
103
56
  /**
104
57
  * Indicates alternative recipients or destinations for events.
105
- * Must be a valid URI if present.
106
- *
107
- * @remarks
108
- * Use this field to implement event forwarding or to specify secondary
109
- * event consumers in addition to the primary one specified in the `to` field.
110
58
  */
111
59
  redirectto?: string;
112
60
  /**
113
61
  * Defines the consumer machine of the event. Used for event routing.
114
62
  * Must be a valid URI if present. If not available, the `type` field
115
63
  * is used as a default.
116
- *
117
- * @remarks
118
- * This field is crucial for directing events to specific services or
119
- * components in your system. Ensure the URI is correctly formatted and
120
- * recognized by your event routing infrastructure.
121
64
  */
122
65
  to?: string;
123
66
  /**
124
67
  * Describes the type of event.
125
- * Should be prefixed with a reverse-DNS name.
126
- *
127
- * @remarks
128
- * The event type is a key field for consumers to understand the nature
129
- * of the event without inspecting its data. Use a consistent naming convention
130
- * to enhance system-wide event comprehension.
131
68
  */
132
69
  type: TType;
133
70
  /**
134
71
  * Represents the cost associated with generating the cloudevent.
135
- *
136
- * @remarks
137
- * By default, it uses the actor's executionunits. This field can be used for
138
- * resource accounting or billing purposes. Only override this if you have a specific
139
- * reason to assign a different cost to this particular event emission.
140
72
  */
141
73
  executionunits?: number;
142
74
  };
143
75
  /**
144
- * @remarks
145
76
  * This is an internal type. Copied as it is from the
146
77
  * xstate core [here](https://github.com/statelyai/xstate/blob/main/packages/core/src/setup.ts#L26)
147
78
  */
@@ -152,7 +83,6 @@ export type ToParameterizedObject<TParameterizedMap extends Record<string, Param
152
83
  };
153
84
  }>;
154
85
  /**
155
- * @remarks
156
86
  * This is an internal type. Copied as it is from the
157
87
  * xstate core [here](https://github.com/statelyai/xstate/blob/main/packages/core/src/setup.ts#L43)
158
88
  */
@@ -165,10 +95,6 @@ export type ToProvidedActor<TChildrenMap extends Record<string, string>, TActors
165
95
  }>;
166
96
  /**
167
97
  * Infers emittable events from a versioned Arvo contract.
168
- *
169
- * @template T - Versioned Arvo contract type
170
- *
171
- * @remarks
172
98
  * Extracts all possible events that can be emitted by a contract,
173
99
  * including system error events.
174
100
  */
@@ -177,19 +103,11 @@ export type InferEmittableEventsFromVersionedArvoContract<T extends VersionedArv
177
103
  }[keyof InferVersionedArvoContract<T>['emits']] | InferVersionedArvoContract<T>['systemError'];
178
104
  /**
179
105
  * Extracts the orchestrator type from an event type string.
180
- *
181
- * @template T - Event type string
182
- *
183
- * @remarks
184
106
  * Parses the specific orchestrator type from a fully qualified event type string.
185
107
  */
186
108
  export type ExtractOrchestratorType<T extends string> = T extends `${typeof ArvoOrchestratorEventTypeGen.prefix}.${infer Type}` ? Type : never;
187
109
  /**
188
110
  * Infers the complete service contract from a record of versioned Arvo contracts.
189
- *
190
- * @template T - Record of versioned Arvo contracts
191
- *
192
- * @remarks
193
111
  * Generates a comprehensive type definition including both emitted and received events
194
112
  * for all services in the contract.
195
113
  *
@@ -2,22 +2,7 @@ import type { MachineConfig } from 'xstate';
2
2
  /**
3
3
  * Detects if an XState machine configuration contains any parallel states.
4
4
  * Uses a stack-based approach for efficient traversal of the state hierarchy.
5
- *
6
5
  * @param config - XState machine configuration
7
6
  * @returns True if the machine contains at least one parallel state, false otherwise
8
- *
9
- * @example
10
- * const machine = {
11
- * states: {
12
- * processing: {
13
- * type: 'parallel',
14
- * states: {
15
- * upload: { ... },
16
- * scan: { ... }
17
- * }
18
- * }
19
- * }
20
- * }
21
- * const hasParallel = detectParallelStates(machine) // Returns true
22
7
  */
23
8
  export declare const detectParallelStates: (config?: MachineConfig<any, any, any, any, any, any, any, any, any, any, any>) => boolean;
@@ -4,23 +4,8 @@ exports.detectParallelStates = void 0;
4
4
  /**
5
5
  * Detects if an XState machine configuration contains any parallel states.
6
6
  * Uses a stack-based approach for efficient traversal of the state hierarchy.
7
- *
8
7
  * @param config - XState machine configuration
9
8
  * @returns True if the machine contains at least one parallel state, false otherwise
10
- *
11
- * @example
12
- * const machine = {
13
- * states: {
14
- * processing: {
15
- * type: 'parallel',
16
- * states: {
17
- * upload: { ... },
18
- * scan: { ... }
19
- * }
20
- * }
21
- * }
22
- * }
23
- * const hasParallel = detectParallelStates(machine) // Returns true
24
9
  */
25
10
  var detectParallelStates = function (config) {
26
11
  if (!(config === null || config === void 0 ? void 0 : config.states)) {
@@ -1,18 +1,49 @@
1
1
  import type { Span } from '@opentelemetry/api';
2
2
  import { type ArvoEvent, type ArvoOrchestratorContract, type ArvoSemanticVersion, type OpenTelemetryHeaders, type VersionedArvoContract } from 'arvo-core';
3
3
  import type { EnqueueArvoEventActionParam } from '../ArvoMachine/types';
4
+ /**
5
+ * Parameters for creating an emittable event from raw event data.
6
+ */
4
7
  export type CreateEmittableEventParams = {
8
+ /** Raw event parameters from machine execution */
5
9
  event: EnqueueArvoEventActionParam;
10
+ /** OpenTelemetry headers for distributed tracing */
6
11
  otelHeaders: OpenTelemetryHeaders;
12
+ /** Parent orchestration subject for nested workflows */
7
13
  orchestrationParentSubject: string | null;
14
+ /** Event that triggered this emission */
8
15
  sourceEvent: ArvoEvent;
16
+ /** Self contract for orchestrator validation */
9
17
  selfContract: VersionedArvoContract<ArvoOrchestratorContract, ArvoSemanticVersion>;
18
+ /** Service contracts for external event validation */
10
19
  serviceContracts: Record<string, VersionedArvoContract<any, any>>;
20
+ /** ID of the workflow initialization event */
11
21
  initEventId: string;
22
+ /** Domain for event routing */
12
23
  domain: string | null;
24
+ /** Execution units to assign to event */
13
25
  executionunits: number;
26
+ /** Source identifier for the orchestrator */
14
27
  source: string;
15
28
  };
29
+ /**
30
+ * Creates a fully-formed emittable event from raw event parameters.
31
+ *
32
+ * Transforms machine-emitted event data into valid Arvo events by:
33
+ * - Validating against appropriate contracts (self or service)
34
+ * - Resolving domains for routing
35
+ * - Generating proper subjects for orchestration events
36
+ * - Adding tracing context and metadata
37
+ *
38
+ * Handles three event types differently:
39
+ * 1. Completion events - routed to workflow initiator with parent subject
40
+ * 2. Service orchestrator events - creates/extends orchestration subjects
41
+ * 3. Regular service events - standard external service calls
42
+ *
43
+ * @returns Fully-formed Arvo event ready for emission
44
+ * @throws {ContractViolation} When event data fails schema validation
45
+ * @throws {ExecutionViolation} When orchestration subject creation fails
46
+ */
16
47
  export declare const createEmittableEvent: ({ event, otelHeaders, orchestrationParentSubject, sourceEvent, selfContract, serviceContracts, initEventId, domain: _domain, executionunits, source, }: CreateEmittableEventParams, span: Span) => ArvoEvent;
17
48
  /**
18
49
  * Processes raw events into emittable events with domain resolution
@@ -4,6 +4,24 @@ exports.processRawEventsIntoEmittables = exports.createEmittableEvent = void 0;
4
4
  var arvo_core_1 = require("arvo-core");
5
5
  var ArvoDomain_1 = require("../ArvoDomain");
6
6
  var errors_1 = require("../errors");
7
+ /**
8
+ * Creates a fully-formed emittable event from raw event parameters.
9
+ *
10
+ * Transforms machine-emitted event data into valid Arvo events by:
11
+ * - Validating against appropriate contracts (self or service)
12
+ * - Resolving domains for routing
13
+ * - Generating proper subjects for orchestration events
14
+ * - Adding tracing context and metadata
15
+ *
16
+ * Handles three event types differently:
17
+ * 1. Completion events - routed to workflow initiator with parent subject
18
+ * 2. Service orchestrator events - creates/extends orchestration subjects
19
+ * 3. Regular service events - standard external service calls
20
+ *
21
+ * @returns Fully-formed Arvo event ready for emission
22
+ * @throws {ContractViolation} When event data fails schema validation
23
+ * @throws {ExecutionViolation} When orchestration subject creation fails
24
+ */
7
25
  var createEmittableEvent = function (_a, span) {
8
26
  var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
9
27
  var event = _a.event, otelHeaders = _a.otelHeaders, orchestrationParentSubject = _a.orchestrationParentSubject, sourceEvent = _a.sourceEvent, selfContract = _a.selfContract, serviceContracts = _a.serviceContracts, initEventId = _a.initEventId, _domain = _a.domain, executionunits = _a.executionunits, source = _a.source;
@@ -1,13 +1,28 @@
1
1
  import { type ArvoEvent, ViolationError } from 'arvo-core';
2
+ /**
3
+ * Enumeration of transaction violation causes for state management operations.
4
+ */
2
5
  export declare const TransactionViolationCause: {
6
+ /** Failed to read from machine memory */
3
7
  readonly READ_FAILURE: "READ_MACHINE_MEMORY_FAILURE";
8
+ /** Failed to acquire lock on machine memory */
4
9
  readonly LOCK_FAILURE: "LOCK_MACHINE_MEMORY_FAILURE";
10
+ /** Failed to write to machine memory */
5
11
  readonly WRITE_FAILURE: "WRITE_MACHINE_MEMORY_FAILURE";
12
+ /** Lock acquisition was denied */
6
13
  readonly LOCK_UNACQUIRED: "LOCK_UNACQUIRED";
14
+ /** Event subject format is invalid */
7
15
  readonly INVALID_SUBJECT: "INVALID_SUBJECT";
8
16
  };
9
17
  export type TransactionViolationCauseType = (typeof TransactionViolationCause)[keyof typeof TransactionViolationCause];
18
+ /**
19
+ * Error representing failures in orchestrator state transaction operations.
20
+ *
21
+ * Indicates issues with lock acquisition, state persistence, or memory access
22
+ * during orchestration execution. These errors typically trigger retries.
23
+ */
10
24
  export declare class TransactionViolation extends ViolationError<'OrchestratorTransaction'> {
25
+ /** Specific cause of the transaction failure */
11
26
  readonly cause: TransactionViolationCauseType;
12
27
  constructor(param: {
13
28
  cause: TransactionViolationCauseType;
@@ -15,4 +30,11 @@ export declare class TransactionViolation extends ViolationError<'OrchestratorTr
15
30
  initiatingEvent: ArvoEvent;
16
31
  });
17
32
  }
33
+ /**
34
+ * Type guard checking if an error is a TransactionViolation.
35
+ *
36
+ * @param error - Error to check
37
+ * @param cause - Optional specific cause to match
38
+ * @returns True if error is TransactionViolation with optional matching cause
39
+ */
18
40
  export declare const isTransactionViolationError: (error: unknown, cause?: TransactionViolationCauseType) => boolean;
@@ -17,13 +17,27 @@ var __extends = (this && this.__extends) || (function () {
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.isTransactionViolationError = exports.TransactionViolation = exports.TransactionViolationCause = void 0;
19
19
  var arvo_core_1 = require("arvo-core");
20
+ /**
21
+ * Enumeration of transaction violation causes for state management operations.
22
+ */
20
23
  exports.TransactionViolationCause = {
24
+ /** Failed to read from machine memory */
21
25
  READ_FAILURE: 'READ_MACHINE_MEMORY_FAILURE',
26
+ /** Failed to acquire lock on machine memory */
22
27
  LOCK_FAILURE: 'LOCK_MACHINE_MEMORY_FAILURE',
28
+ /** Failed to write to machine memory */
23
29
  WRITE_FAILURE: 'WRITE_MACHINE_MEMORY_FAILURE',
30
+ /** Lock acquisition was denied */
24
31
  LOCK_UNACQUIRED: 'LOCK_UNACQUIRED',
32
+ /** Event subject format is invalid */
25
33
  INVALID_SUBJECT: 'INVALID_SUBJECT',
26
34
  };
35
+ /**
36
+ * Error representing failures in orchestrator state transaction operations.
37
+ *
38
+ * Indicates issues with lock acquisition, state persistence, or memory access
39
+ * during orchestration execution. These errors typically trigger retries.
40
+ */
27
41
  var TransactionViolation = /** @class */ (function (_super) {
28
42
  __extends(TransactionViolation, _super);
29
43
  function TransactionViolation(param) {
@@ -40,6 +54,13 @@ var TransactionViolation = /** @class */ (function (_super) {
40
54
  return TransactionViolation;
41
55
  }(arvo_core_1.ViolationError));
42
56
  exports.TransactionViolation = TransactionViolation;
57
+ /**
58
+ * Type guard checking if an error is a TransactionViolation.
59
+ *
60
+ * @param error - Error to check
61
+ * @param cause - Optional specific cause to match
62
+ * @returns True if error is TransactionViolation with optional matching cause
63
+ */
43
64
  var isTransactionViolationError = function (error, cause) {
44
65
  return ((0, arvo_core_1.isViolationError)(error) &&
45
66
  error.type === 'OrchestratorTransaction' &&
@@ -4,27 +4,55 @@ import type { SyncEventResource } from '../SyncEventResource';
4
4
  import type { OrchestrationExecutionMemoryRecord } from './orchestrationExecutionState';
5
5
  import { type ArvoOrchestrationHandlerType } from './types';
6
6
  /**
7
- * Parameters for system error event creation
7
+ * Parameters for creating system error events during orchestration failures.
8
8
  */
9
9
  export type CreateSystemErrorEventsParams = {
10
+ /** The error that occurred */
10
11
  error: unknown;
12
+ /** Event that triggered the error */
11
13
  event: ArvoEvent;
14
+ /** OpenTelemetry headers for tracing */
12
15
  otelHeaders: OpenTelemetryHeaders;
16
+ /** Parent orchestration subject if nested */
13
17
  orchestrationParentSubject: string | null;
18
+ /** ID of the initiating event */
14
19
  initEventId: string | null;
20
+ /** Self contract defining error schema */
15
21
  selfContract: VersionedArvoContract<ArvoContract, ArvoSemanticVersion>;
22
+ /** Optional domains for error event routing */
16
23
  systemErrorDomain?: (string | null)[];
24
+ /** Execution units for error events */
17
25
  executionunits: number;
26
+ /** Source identifier */
18
27
  source: string;
28
+ /** Domain for error events */
19
29
  domain: string | null;
30
+ /** Type of handler reporting the error */
20
31
  handlerType: ArvoOrchestrationHandlerType;
21
32
  };
22
33
  /**
23
- * Creates system error events
34
+ * Creates standardized system error events for orchestration failures.
35
+ *
36
+ * Generates error events that route back to the workflow initiator, preserving
37
+ * tracing context and orchestration hierarchy. Supports multiple domains for
38
+ * error distribution.
39
+ *
40
+ * @param params - Error event creation parameters
41
+ * @returns Array of system error events for each configured domain
24
42
  */
25
43
  export declare const createSystemErrorEvents: ({ error, event, otelHeaders, orchestrationParentSubject: _orchestrationParentSubject, initEventId, selfContract, systemErrorDomain, executionunits, source, domain, handlerType, }: CreateSystemErrorEventsParams & {
26
44
  error: Error;
27
45
  }) => ArvoEvent[];
46
+ /**
47
+ * Handles errors during orchestration execution with proper state management.
48
+ *
49
+ * Processes errors by determining if they are violations (retriable) or execution
50
+ * errors (terminal). For execution errors, persists failure state and generates
51
+ * system error events. For violations, returns the error to be thrown without
52
+ * state persistence.
53
+ *
54
+ * @returns Either the violation error to throw or system error events to emit
55
+ */
28
56
  export declare const handleOrchestrationErrors: (_handlerType: ArvoOrchestrationHandlerType, param: CreateSystemErrorEventsParams & {
29
57
  syncEventResource: SyncEventResource<OrchestrationExecutionMemoryRecord<Record<string, any>>>;
30
58
  }, span: Span) => Promise<{
@@ -55,7 +55,14 @@ var errors_1 = require("../errors");
55
55
  var utils_1 = require("../utils");
56
56
  var types_1 = require("./types");
57
57
  /**
58
- * Creates system error events
58
+ * Creates standardized system error events for orchestration failures.
59
+ *
60
+ * Generates error events that route back to the workflow initiator, preserving
61
+ * tracing context and orchestration hierarchy. Supports multiple domains for
62
+ * error distribution.
63
+ *
64
+ * @param params - Error event creation parameters
65
+ * @returns Array of system error events for each configured domain
59
66
  */
60
67
  var createSystemErrorEvents = function (_a) {
61
68
  var _b, _c, _d, _e, _f;
@@ -79,7 +86,7 @@ var createSystemErrorEvents = function (_a) {
79
86
  });
80
87
  }
81
88
  }
82
- var domainSets = new Set(systemErrorDomain
89
+ var domainSets = new Set((systemErrorDomain === null || systemErrorDomain === void 0 ? void 0 : systemErrorDomain.length)
83
90
  ? systemErrorDomain.map(function (item) {
84
91
  return (0, ArvoDomain_1.resolveEventDomain)({
85
92
  domainToResolve: item,
@@ -119,6 +126,16 @@ var createSystemErrorEvents = function (_a) {
119
126
  return result;
120
127
  };
121
128
  exports.createSystemErrorEvents = createSystemErrorEvents;
129
+ /**
130
+ * Handles errors during orchestration execution with proper state management.
131
+ *
132
+ * Processes errors by determining if they are violations (retriable) or execution
133
+ * errors (terminal). For execution errors, persists failure state and generates
134
+ * system error events. For violations, returns the error to be thrown without
135
+ * state persistence.
136
+ *
137
+ * @returns Either the violation error to throw or system error events to emit
138
+ */
122
139
  var handleOrchestrationErrors = function (_handlerType, param, span) { return __awaiter(void 0, void 0, void 0, function () {
123
140
  var handlerType, error, errorEvents, _i, _a, _b, errEvtIdx, errEvt, _c, _d, _e, key, value;
124
141
  return __generator(this, function (_f) {
@@ -0,0 +1,47 @@
1
+ import type { Span } from '@opentelemetry/api';
2
+ import { type ArvoContract, type ArvoEvent, VersionedArvoContract } from 'arvo-core';
3
+ import type { z } from 'zod';
4
+ /**
5
+ * Result type for event validation operations.
6
+ *
7
+ * Discriminated union representing all possible validation outcomes:
8
+ * - VALID: Event passed all validation checks
9
+ * - CONTRACT_UNRESOLVED: No matching contract found for the event
10
+ * - INVALID: Event dataschema conflicts with contract (URI or version mismatch)
11
+ * - INVALID_DATA: Event data doesn't match contract schema (Zod validation failure)
12
+ */
13
+ export type EventValidationResult = {
14
+ type: 'VALID';
15
+ contractType: 'self' | 'service';
16
+ } | {
17
+ type: 'CONTRACT_UNRESOLVED';
18
+ } | {
19
+ type: 'INVALID';
20
+ error: Error;
21
+ } | {
22
+ type: 'INVALID_DATA';
23
+ error: z.ZodError;
24
+ };
25
+ /**
26
+ * Configuration for event validation.
27
+ */
28
+ export type EventValidationConfig = {
29
+ /** The event to validate */
30
+ event: ArvoEvent;
31
+ /** Self contract for initialization event validation */
32
+ selfContract: VersionedArvoContract<any, any> | ArvoContract;
33
+ /** Service contracts for response event validation */
34
+ serviceContracts: Record<string, VersionedArvoContract<any, any>>;
35
+ /** Optional OpenTelemetry span for logging */
36
+ span?: Span;
37
+ };
38
+ /**
39
+ * Validates an event against provided contracts.
40
+ *
41
+ * Performs comprehensive validation including:
42
+ * - Dataschema parsing and resolution
43
+ * - Contract resolution (self vs service)
44
+ * - URI and version compatibility checks
45
+ * - Schema-based data validation
46
+ */
47
+ export declare function validateInputEvent({ event, selfContract: _selfContract, serviceContracts, span, }: EventValidationConfig): EventValidationResult;
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
3
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
4
+ if (ar || !(i in from)) {
5
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
6
+ ar[i] = from[i];
7
+ }
8
+ }
9
+ return to.concat(ar || Array.prototype.slice.call(from));
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.validateInputEvent = validateInputEvent;
13
+ var arvo_core_1 = require("arvo-core");
14
+ /**
15
+ * Validates an event against provided contracts.
16
+ *
17
+ * Performs comprehensive validation including:
18
+ * - Dataschema parsing and resolution
19
+ * - Contract resolution (self vs service)
20
+ * - URI and version compatibility checks
21
+ * - Schema-based data validation
22
+ */
23
+ function validateInputEvent(_a) {
24
+ var _b;
25
+ var event = _a.event, _selfContract = _a.selfContract, serviceContracts = _a.serviceContracts, span = _a.span;
26
+ var resolvedContract = null;
27
+ var contractType;
28
+ var parsedEventDataSchema = arvo_core_1.EventDataschemaUtil.parse(event);
29
+ if (!parsedEventDataSchema) {
30
+ var errorMessage = "Event dataschema resolution failed: Unable to parse dataschema='".concat(event.dataschema, "' for event(id='").concat(event.id, "', type='").concat(event.type, "'). This makes the event opaque and does not allow contract resolution");
31
+ (0, arvo_core_1.logToSpan)({
32
+ level: 'WARNING',
33
+ message: errorMessage,
34
+ }, span);
35
+ return {
36
+ type: 'INVALID',
37
+ error: new Error(errorMessage),
38
+ };
39
+ }
40
+ var selfContract;
41
+ if (_selfContract instanceof arvo_core_1.VersionedArvoContract) {
42
+ selfContract = _selfContract;
43
+ }
44
+ else {
45
+ if (!_selfContract.versions[parsedEventDataSchema.version]) {
46
+ var errorMessage = "Contract resolution failed: No matching contract found for event (id='".concat(event.id, "', type='").concat(event.type, "', dataschema='").concat(event.dataschema, "')");
47
+ (0, arvo_core_1.logToSpan)({
48
+ level: 'WARNING',
49
+ message: errorMessage,
50
+ }, span);
51
+ return {
52
+ type: 'CONTRACT_UNRESOLVED',
53
+ };
54
+ }
55
+ selfContract = _selfContract.version(parsedEventDataSchema.version);
56
+ }
57
+ if (event.type === selfContract.accepts.type) {
58
+ contractType = 'self';
59
+ resolvedContract = selfContract;
60
+ }
61
+ else {
62
+ contractType = 'service';
63
+ // Search through service contracts for matching event type
64
+ for (var _i = 0, _c = Object.values(serviceContracts); _i < _c.length; _i++) {
65
+ var contract = _c[_i];
66
+ if (resolvedContract)
67
+ break;
68
+ // Check both emitted events and system error
69
+ for (var _d = 0, _e = __spreadArray(__spreadArray([], contract.emitList, true), [contract.systemError], false); _d < _e.length; _d++) {
70
+ var emitType = _e[_d];
71
+ if (resolvedContract)
72
+ break;
73
+ if (event.type === emitType.type) {
74
+ resolvedContract = contract;
75
+ }
76
+ }
77
+ }
78
+ }
79
+ if (!resolvedContract) {
80
+ var errorMessage = "Contract resolution failed: No matching contract found for event (id='".concat(event.id, "', type='").concat(event.type, "')");
81
+ (0, arvo_core_1.logToSpan)({
82
+ level: 'WARNING',
83
+ message: errorMessage,
84
+ }, span);
85
+ return {
86
+ type: 'CONTRACT_UNRESOLVED',
87
+ };
88
+ }
89
+ (0, arvo_core_1.logToSpan)({
90
+ level: 'INFO',
91
+ message: "Dataschema resolved: ".concat(event.dataschema, " matches contract(uri='").concat(resolvedContract.uri, "', version='").concat(resolvedContract.version, "')"),
92
+ }, span);
93
+ if (parsedEventDataSchema.uri !== resolvedContract.uri) {
94
+ return {
95
+ type: 'INVALID',
96
+ error: new Error("Contract URI mismatch: ".concat(contractType, " Contract(uri='").concat(resolvedContract.uri, "', type='").concat(resolvedContract.accepts.type, "') does not match Event(dataschema='").concat(event.dataschema, "', type='").concat(event.type, "')")),
97
+ };
98
+ }
99
+ if (!(0, arvo_core_1.isWildCardArvoSematicVersion)(parsedEventDataSchema.version) &&
100
+ parsedEventDataSchema.version !== resolvedContract.version) {
101
+ return {
102
+ type: 'INVALID',
103
+ error: new Error("Contract version mismatch: ".concat(contractType, " Contract(version='").concat(resolvedContract.version, "', type='").concat(resolvedContract.accepts.type, "', uri=").concat(resolvedContract.uri, ") does not match Event(dataschema='").concat(event.dataschema, "', type='").concat(event.type, "')")),
104
+ };
105
+ }
106
+ var validationSchema = contractType === 'self'
107
+ ? resolvedContract.accepts.schema
108
+ : ((_b = resolvedContract.emits[event.type]) !== null && _b !== void 0 ? _b : resolvedContract.systemError.schema);
109
+ var validationResult = validationSchema.safeParse(event.data);
110
+ if (!validationResult.success) {
111
+ return {
112
+ type: 'INVALID_DATA',
113
+ error: validationResult.error,
114
+ };
115
+ }
116
+ return {
117
+ type: 'VALID',
118
+ contractType: contractType,
119
+ };
120
+ }