@signaltree/events 7.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.esm.js ADDED
@@ -0,0 +1,167 @@
1
+ export { D as DEFAULT_EVENT_VERSION, E as EVENT_PRIORITIES, c as createEvent, a as createEventFactory, b as generateCorrelationId, g as generateEventId } from './factory.esm.js';
2
+ import { z } from 'zod';
3
+ export { z } from 'zod';
4
+ export { D as DEFAULT_RETRY_CONFIGS, E as EventRegistry, I as InMemoryIdempotencyStore, a as classifyError, b as createErrorClassifier, c as createEventRegistry, e as createInMemoryIdempotencyStore, d as defaultErrorClassifier, f as generateCorrelationKey, g as generateIdempotencyKey, i as isRetryableError } from './idempotency.esm.js';
5
+
6
+ /**
7
+ * Event validation using Zod schemas
8
+ *
9
+ * Provides:
10
+ * - Base schemas for common event fields
11
+ * - Factory function to create event schemas
12
+ * - Runtime validation with detailed errors
13
+ */
14
+ // ============================================================================
15
+ // Base Schemas
16
+ // ============================================================================
17
+ /**
18
+ * Schema for event actor
19
+ */
20
+ const EventActorSchema = z.object({
21
+ id: z.string().min(1),
22
+ type: z.enum(['user', 'system', 'admin', 'webhook']),
23
+ name: z.string().optional()
24
+ });
25
+ /**
26
+ * Schema for event version
27
+ */
28
+ const EventVersionSchema = z.object({
29
+ major: z.number().int().min(1),
30
+ minor: z.number().int().min(0)
31
+ });
32
+ /**
33
+ * Schema for event metadata
34
+ */
35
+ const EventMetadataSchema = z.object({
36
+ source: z.string().min(1),
37
+ environment: z.string().min(1),
38
+ ip: z.string().optional(),
39
+ userAgent: z.string().optional()
40
+ }).passthrough(); // Allow additional properties
41
+ /**
42
+ * Schema for aggregate info
43
+ */
44
+ const AggregateSchema = z.object({
45
+ type: z.string().min(1),
46
+ id: z.string().min(1)
47
+ }).optional();
48
+ /**
49
+ * Base event schema without data field
50
+ */
51
+ const BaseEventSchema = z.object({
52
+ id: z.string().uuid(),
53
+ type: z.string().min(1),
54
+ version: EventVersionSchema,
55
+ timestamp: z.string().datetime(),
56
+ correlationId: z.string().uuid(),
57
+ causationId: z.string().uuid().optional(),
58
+ actor: EventActorSchema,
59
+ metadata: EventMetadataSchema,
60
+ priority: z.enum(['critical', 'high', 'normal', 'low', 'bulk']).optional(),
61
+ aggregate: AggregateSchema
62
+ });
63
+ // ============================================================================
64
+ // Schema Factory
65
+ // ============================================================================
66
+ /**
67
+ * Create a typed event schema with Zod validation
68
+ *
69
+ * @param eventType - The event type string (e.g., 'TradeProposalCreated')
70
+ * @param dataSchema - Zod schema for the event's data field
71
+ * @returns Complete event schema
72
+ *
73
+ * @example
74
+ * ```typescript
75
+ * const TradeProposalCreatedSchema = createEventSchema('TradeProposalCreated', {
76
+ * tradeId: z.string().uuid(),
77
+ * initiatorId: z.string().uuid(),
78
+ * recipientId: z.string().uuid(),
79
+ * vehicleOfferedId: z.string().uuid(),
80
+ * terms: z.object({
81
+ * cashDifference: z.number().optional(),
82
+ * }),
83
+ * });
84
+ *
85
+ * type TradeProposalCreated = z.infer<typeof TradeProposalCreatedSchema>;
86
+ * ```
87
+ */
88
+ function createEventSchema(eventType, dataSchema) {
89
+ return BaseEventSchema.extend({
90
+ type: z.literal(eventType),
91
+ data: z.object(dataSchema)
92
+ });
93
+ }
94
+ // ============================================================================
95
+ // Validation Functions
96
+ // ============================================================================
97
+ /**
98
+ * Custom error class for event validation failures
99
+ */
100
+ class EventValidationError extends Error {
101
+ zodError;
102
+ event;
103
+ constructor(message, zodError, event) {
104
+ super(message);
105
+ this.zodError = zodError;
106
+ this.event = event;
107
+ this.name = 'EventValidationError';
108
+ }
109
+ /**
110
+ * Get formatted error messages
111
+ */
112
+ get issues() {
113
+ return this.zodError.issues.map(issue => {
114
+ const path = issue.path.join('.');
115
+ return path ? `${path}: ${issue.message}` : issue.message;
116
+ });
117
+ }
118
+ }
119
+ /**
120
+ * Validate an event against a schema, throwing on failure
121
+ *
122
+ * @param schema - Zod schema to validate against
123
+ * @param event - Event to validate
124
+ * @returns Validated and typed event
125
+ * @throws EventValidationError if validation fails
126
+ *
127
+ * @example
128
+ * ```typescript
129
+ * try {
130
+ * const validEvent = validateEvent(TradeProposalCreatedSchema, rawEvent);
131
+ * // validEvent is typed as TradeProposalCreated
132
+ * } catch (error) {
133
+ * if (error instanceof EventValidationError) {
134
+ * console.error('Validation failed:', error.issues);
135
+ * }
136
+ * }
137
+ * ```
138
+ */
139
+ function validateEvent(schema, event) {
140
+ const result = schema.safeParse(event);
141
+ if (!result.success) {
142
+ throw new EventValidationError(`Event validation failed: ${result.error.issues.map(i => i.message).join(', ')}`, result.error, event);
143
+ }
144
+ return result.data;
145
+ }
146
+ /**
147
+ * Check if an event is valid without throwing
148
+ *
149
+ * @param schema - Zod schema to validate against
150
+ * @param event - Event to check
151
+ * @returns true if valid, false otherwise
152
+ */
153
+ function isValidEvent(schema, event) {
154
+ return schema.safeParse(event).success;
155
+ }
156
+ /**
157
+ * Parse an event, returning result with success/error
158
+ *
159
+ * @param schema - Zod schema to parse with
160
+ * @param event - Event to parse
161
+ * @returns SafeParseResult with data or error
162
+ */
163
+ function parseEvent(schema, event) {
164
+ return schema.safeParse(event);
165
+ }
166
+
167
+ export { BaseEventSchema, EventActorSchema, EventMetadataSchema, EventValidationError, EventVersionSchema, createEventSchema, isValidEvent, parseEvent, validateEvent };
package/nestjs.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./src/nestjs";