@cosmneo/onion-lasagna 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/dist/chunk-36IO4BM7.js +113 -0
  2. package/dist/chunk-36IO4BM7.js.map +1 -0
  3. package/dist/chunk-4BVOLXDJ.js +54 -0
  4. package/dist/chunk-4BVOLXDJ.js.map +1 -0
  5. package/dist/{chunk-GGSAAZPM.js → chunk-AUMHMWDD.js} +19 -20
  6. package/dist/chunk-AUMHMWDD.js.map +1 -0
  7. package/dist/chunk-CBTICRSM.js +34 -0
  8. package/dist/chunk-CBTICRSM.js.map +1 -0
  9. package/dist/chunk-H5TNDC5U.js +138 -0
  10. package/dist/chunk-H5TNDC5U.js.map +1 -0
  11. package/dist/chunk-KJ4JGZOE.js +96 -0
  12. package/dist/chunk-KJ4JGZOE.js.map +1 -0
  13. package/dist/chunk-MF2JDREK.js +168 -0
  14. package/dist/chunk-MF2JDREK.js.map +1 -0
  15. package/dist/chunk-RVSBIYY4.js +1 -0
  16. package/dist/chunk-RVSBIYY4.js.map +1 -0
  17. package/dist/{chunk-PUVAB3JX.js → chunk-XIRJ73IO.js} +38 -36
  18. package/dist/chunk-XIRJ73IO.js.map +1 -0
  19. package/dist/{chunk-DS7TE6KZ.js → chunk-XP6PLTV2.js} +11 -3
  20. package/dist/chunk-XP6PLTV2.js.map +1 -0
  21. package/dist/chunk-XWKHOLIP.js +191 -0
  22. package/dist/chunk-XWKHOLIP.js.map +1 -0
  23. package/dist/event-router-definition.type-CP9uTlux.d.cts +150 -0
  24. package/dist/event-router-definition.type-D8CG-kjZ.d.ts +150 -0
  25. package/dist/events/asyncapi/index.cjs +143 -0
  26. package/dist/events/asyncapi/index.cjs.map +1 -0
  27. package/dist/events/asyncapi/index.d.cts +184 -0
  28. package/dist/events/asyncapi/index.d.ts +184 -0
  29. package/dist/events/asyncapi/index.js +8 -0
  30. package/dist/events/asyncapi/index.js.map +1 -0
  31. package/dist/events/handler/index.cjs +171 -0
  32. package/dist/events/handler/index.cjs.map +1 -0
  33. package/dist/events/handler/index.d.cts +153 -0
  34. package/dist/events/handler/index.d.ts +153 -0
  35. package/dist/events/handler/index.js +21 -0
  36. package/dist/events/handler/index.js.map +1 -0
  37. package/dist/events/index.cjs +497 -0
  38. package/dist/events/index.cjs.map +1 -0
  39. package/dist/events/index.d.cts +9 -0
  40. package/dist/events/index.d.ts +9 -0
  41. package/dist/events/index.js +41 -0
  42. package/dist/events/index.js.map +1 -0
  43. package/dist/events/server/index.cjs +291 -0
  44. package/dist/events/server/index.cjs.map +1 -0
  45. package/dist/events/server/index.d.cts +281 -0
  46. package/dist/events/server/index.d.ts +281 -0
  47. package/dist/events/server/index.js +16 -0
  48. package/dist/events/server/index.js.map +1 -0
  49. package/dist/events/shared/index.cjs +85 -0
  50. package/dist/events/shared/index.cjs.map +1 -0
  51. package/dist/events/shared/index.d.cts +35 -0
  52. package/dist/events/shared/index.d.ts +35 -0
  53. package/dist/events/shared/index.js +13 -0
  54. package/dist/events/shared/index.js.map +1 -0
  55. package/dist/global.js +3 -3
  56. package/dist/http/index.cjs +563 -93
  57. package/dist/http/index.cjs.map +1 -1
  58. package/dist/http/index.d.cts +5 -3
  59. package/dist/http/index.d.ts +5 -3
  60. package/dist/http/index.js +30 -12
  61. package/dist/http/openapi/index.cjs +43 -35
  62. package/dist/http/openapi/index.cjs.map +1 -1
  63. package/dist/http/openapi/index.d.cts +8 -34
  64. package/dist/http/openapi/index.d.ts +8 -34
  65. package/dist/http/openapi/index.js +2 -2
  66. package/dist/http/route/index.cjs +106 -9
  67. package/dist/http/route/index.cjs.map +1 -1
  68. package/dist/http/route/index.d.cts +133 -227
  69. package/dist/http/route/index.d.ts +133 -227
  70. package/dist/http/route/index.js +5 -2
  71. package/dist/http/server/index.cjs +24 -19
  72. package/dist/http/server/index.cjs.map +1 -1
  73. package/dist/http/server/index.d.cts +4 -261
  74. package/dist/http/server/index.d.ts +4 -261
  75. package/dist/http/server/index.js +2 -2
  76. package/dist/http/shared/index.cjs.map +1 -1
  77. package/dist/http/shared/index.d.cts +10 -14
  78. package/dist/http/shared/index.d.ts +10 -14
  79. package/dist/http/shared/index.js +11 -127
  80. package/dist/http/shared/index.js.map +1 -1
  81. package/dist/index.js +6 -6
  82. package/dist/{router-definition.type-ynBhT16T.d.cts → router-definition.type-BElX-Pl4.d.cts} +169 -256
  83. package/dist/{router-definition.type-DORVlLNk.d.ts → router-definition.type-DxG8ncJZ.d.ts} +169 -256
  84. package/dist/types-B6Q1iCgf.d.ts +262 -0
  85. package/dist/types-afYpL7Ap.d.cts +262 -0
  86. package/dist/types-cke61juH.d.cts +42 -0
  87. package/dist/types-cke61juH.d.ts +42 -0
  88. package/package.json +35 -2
  89. package/dist/chunk-BZULBF4N.js +0 -82
  90. package/dist/chunk-BZULBF4N.js.map +0 -1
  91. package/dist/chunk-DS7TE6KZ.js.map +0 -1
  92. package/dist/chunk-GGSAAZPM.js.map +0 -1
  93. package/dist/chunk-PUVAB3JX.js.map +0 -1
@@ -0,0 +1,153 @@
1
+ import { SchemaAdapter, InferOutput } from '../../http/schema/types.js';
2
+ import { E as EventHandlerDefinition, c as EventRouterConfig, d as EventRouterDefaults, e as EventRouterDefinition, D as DeepMergeTwo, l as DeepMergeAll } from '../../event-router-definition.type-D8CG-kjZ.js';
3
+ export { a as EventHandlerDocumentation, b as EventRouterEntry, f as EventRouterKeys, F as FlattenEventRouter, G as GetEventHandler, h as InferEventContext, g as InferEventPayload, I as InferEventType, k as collectEventHandlers, i as isEventHandlerDefinition, j as isEventRouterDefinition } from '../../event-router-definition.type-D8CG-kjZ.js';
4
+
5
+ /**
6
+ * @fileoverview Factory function for creating event handler definitions.
7
+ *
8
+ * The `defineEventHandler` function is the main entry point for defining
9
+ * event handlers. It mirrors `defineRoute` from the HTTP layer but is
10
+ * tailored for asynchronous event processing.
11
+ *
12
+ * @module events/handler/define-event-handler
13
+ */
14
+
15
+ /**
16
+ * Input for defineEventHandler.
17
+ *
18
+ * @example Basic handler with payload schema
19
+ * ```typescript
20
+ * defineEventHandler({
21
+ * eventType: 'ticket.created',
22
+ * payload: zodSchema(z.object({ ticketId: z.string() })),
23
+ * docs: { summary: 'Handle ticket creation', tags: ['ticket'] },
24
+ * })
25
+ * ```
26
+ *
27
+ * @example With context schema
28
+ * ```typescript
29
+ * defineEventHandler({
30
+ * eventType: 'order.shipped',
31
+ * payload: zodSchema(orderShippedSchema),
32
+ * context: zodSchema(eventMetadataSchema),
33
+ * })
34
+ * ```
35
+ */
36
+ interface DefineEventHandlerInput<TEventType extends string, TPayload extends SchemaAdapter | undefined = undefined, TContext extends SchemaAdapter | undefined = undefined> {
37
+ /** Event type string used for routing (e.g., 'ticket.created'). */
38
+ readonly eventType: TEventType;
39
+ /** Payload validation schema. */
40
+ readonly payload?: TPayload;
41
+ /** Context validation schema (validates event metadata). */
42
+ readonly context?: TContext;
43
+ /** Handler documentation. */
44
+ readonly docs?: {
45
+ readonly summary?: string;
46
+ readonly description?: string;
47
+ readonly tags?: readonly string[];
48
+ readonly deprecated?: boolean;
49
+ };
50
+ }
51
+ type ResolvePayload<T> = T extends SchemaAdapter ? InferOutput<T> : undefined;
52
+ type ResolveContext<T> = T extends SchemaAdapter ? InferOutput<T> : undefined;
53
+ /**
54
+ * Creates an event handler definition from the provided configuration.
55
+ *
56
+ * This is the main entry point for defining event handlers. The resulting
57
+ * definition can be used for type-safe handler registration, payload
58
+ * validation, and documentation generation.
59
+ *
60
+ * @param input - Event handler configuration with optional schemas
61
+ * @returns A frozen EventHandlerDefinition object with full type information
62
+ */
63
+ declare function defineEventHandler<TEventType extends string, TPayload extends SchemaAdapter | undefined = undefined, TContext extends SchemaAdapter | undefined = undefined>(input: DefineEventHandlerInput<TEventType, TPayload, TContext>): EventHandlerDefinition<TEventType, ResolvePayload<TPayload>, ResolveContext<TContext>>;
64
+
65
+ /**
66
+ * @fileoverview Factory function for creating event router definitions.
67
+ *
68
+ * The `defineEventRouter` function groups event handlers into a hierarchical
69
+ * structure with optional router-level defaults for context and tags.
70
+ *
71
+ * @module events/handler/define-event-router
72
+ */
73
+
74
+ /**
75
+ * Options for event router definition.
76
+ */
77
+ interface DefineEventRouterOptions {
78
+ /**
79
+ * Default values applied to all child handlers.
80
+ *
81
+ * @example
82
+ * ```typescript
83
+ * defineEventRouter({
84
+ * created: onTicketCreated,
85
+ * assigned: onTicketAssigned,
86
+ * }, {
87
+ * defaults: {
88
+ * context: zodSchema(eventMetadataSchema),
89
+ * tags: ['ticket'],
90
+ * },
91
+ * })
92
+ * ```
93
+ */
94
+ readonly defaults?: EventRouterDefaults;
95
+ }
96
+ /**
97
+ * Creates an event router definition from a configuration object.
98
+ *
99
+ * @param handlers - Object containing event handlers and nested routers
100
+ * @param options - Optional router configuration
101
+ * @returns A frozen EventRouterDefinition object
102
+ *
103
+ * @example Basic router
104
+ * ```typescript
105
+ * const ticketEvents = defineEventRouter({
106
+ * created: onTicketCreated,
107
+ * assigned: onTicketAssigned,
108
+ * transferred: onTicketTransferred,
109
+ * });
110
+ * ```
111
+ *
112
+ * @example Nested router
113
+ * ```typescript
114
+ * const events = defineEventRouter({
115
+ * ticket: {
116
+ * created: onTicketCreated,
117
+ * assigned: onTicketAssigned,
118
+ * },
119
+ * ecosystem: {
120
+ * memberAdded: onMemberAdded,
121
+ * },
122
+ * });
123
+ * ```
124
+ */
125
+ declare function defineEventRouter<T extends EventRouterConfig>(handlers: T, options?: DefineEventRouterOptions): EventRouterDefinition<T>;
126
+ type EventRouterInput<T extends EventRouterConfig> = T | EventRouterDefinition<T>;
127
+ declare function mergeEventRouters<T1 extends EventRouterConfig, T2 extends EventRouterConfig>(r1: EventRouterInput<T1>, r2: EventRouterInput<T2>): EventRouterDefinition<DeepMergeTwo<T1, T2>>;
128
+ declare function mergeEventRouters<T1 extends EventRouterConfig, T2 extends EventRouterConfig, T3 extends EventRouterConfig>(r1: EventRouterInput<T1>, r2: EventRouterInput<T2>, r3: EventRouterInput<T3>): EventRouterDefinition<DeepMergeAll<[T1, T2, T3]>>;
129
+ declare function mergeEventRouters<T1 extends EventRouterConfig, T2 extends EventRouterConfig, T3 extends EventRouterConfig, T4 extends EventRouterConfig>(r1: EventRouterInput<T1>, r2: EventRouterInput<T2>, r3: EventRouterInput<T3>, r4: EventRouterInput<T4>): EventRouterDefinition<DeepMergeAll<[T1, T2, T3, T4]>>;
130
+ declare function mergeEventRouters<T1 extends EventRouterConfig, T2 extends EventRouterConfig, T3 extends EventRouterConfig, T4 extends EventRouterConfig, T5 extends EventRouterConfig>(r1: EventRouterInput<T1>, r2: EventRouterInput<T2>, r3: EventRouterInput<T3>, r4: EventRouterInput<T4>, r5: EventRouterInput<T5>): EventRouterDefinition<DeepMergeAll<[T1, T2, T3, T4, T5]>>;
131
+ declare function mergeEventRouters<T1 extends EventRouterConfig, T2 extends EventRouterConfig, T3 extends EventRouterConfig, T4 extends EventRouterConfig, T5 extends EventRouterConfig, T6 extends EventRouterConfig>(r1: EventRouterInput<T1>, r2: EventRouterInput<T2>, r3: EventRouterInput<T3>, r4: EventRouterInput<T4>, r5: EventRouterInput<T5>, r6: EventRouterInput<T6>): EventRouterDefinition<DeepMergeAll<[T1, T2, T3, T4, T5, T6]>>;
132
+ declare function mergeEventRouters<T1 extends EventRouterConfig, T2 extends EventRouterConfig, T3 extends EventRouterConfig, T4 extends EventRouterConfig, T5 extends EventRouterConfig, T6 extends EventRouterConfig, T7 extends EventRouterConfig>(r1: EventRouterInput<T1>, r2: EventRouterInput<T2>, r3: EventRouterInput<T3>, r4: EventRouterInput<T4>, r5: EventRouterInput<T5>, r6: EventRouterInput<T6>, r7: EventRouterInput<T7>): EventRouterDefinition<DeepMergeAll<[T1, T2, T3, T4, T5, T6, T7]>>;
133
+ declare function mergeEventRouters<T1 extends EventRouterConfig, T2 extends EventRouterConfig, T3 extends EventRouterConfig, T4 extends EventRouterConfig, T5 extends EventRouterConfig, T6 extends EventRouterConfig, T7 extends EventRouterConfig, T8 extends EventRouterConfig>(r1: EventRouterInput<T1>, r2: EventRouterInput<T2>, r3: EventRouterInput<T3>, r4: EventRouterInput<T4>, r5: EventRouterInput<T5>, r6: EventRouterInput<T6>, r7: EventRouterInput<T7>, r8: EventRouterInput<T8>): EventRouterDefinition<DeepMergeAll<[T1, T2, T3, T4, T5, T6, T7, T8]>>;
134
+ declare function mergeEventRouters(...routers: EventRouterInput<EventRouterConfig>[]): EventRouterDefinition<EventRouterConfig>;
135
+
136
+ /**
137
+ * @fileoverview Utility functions for event handler routing.
138
+ *
139
+ * @module events/handler/utils
140
+ */
141
+ /**
142
+ * Generates a handler ID from a dotted key path.
143
+ *
144
+ * Converts dot-separated keys to camelCase:
145
+ * - `"ticket.created"` → `"ticketCreated"`
146
+ * - `"ecosystem.member.added"` → `"ecosystemMemberAdded"`
147
+ *
148
+ * @param key - The dotted key path
149
+ * @returns A camelCase handler ID
150
+ */
151
+ declare function generateHandlerId(key: string): string;
152
+
153
+ export { DeepMergeAll, DeepMergeTwo, type DefineEventRouterOptions, EventHandlerDefinition, EventRouterConfig, EventRouterDefaults, EventRouterDefinition, defineEventHandler, defineEventRouter, generateHandlerId, mergeEventRouters };
@@ -0,0 +1,21 @@
1
+ import {
2
+ defineEventHandler,
3
+ defineEventRouter,
4
+ mergeEventRouters
5
+ } from "../../chunk-36IO4BM7.js";
6
+ import {
7
+ collectEventHandlers,
8
+ generateHandlerId,
9
+ isEventHandlerDefinition,
10
+ isEventRouterDefinition
11
+ } from "../../chunk-CBTICRSM.js";
12
+ export {
13
+ collectEventHandlers,
14
+ defineEventHandler,
15
+ defineEventRouter,
16
+ generateHandlerId,
17
+ isEventHandlerDefinition,
18
+ isEventRouterDefinition,
19
+ mergeEventRouters
20
+ };
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,497 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/presentation/events/index.ts
21
+ var events_exports = {};
22
+ __export(events_exports, {
23
+ collectEventHandlers: () => collectEventHandlers,
24
+ defineEventHandler: () => defineEventHandler,
25
+ defineEventRouter: () => defineEventRouter,
26
+ eventRoutes: () => eventRoutes,
27
+ generateAsyncAPI: () => generateAsyncAPI,
28
+ generateHandlerId: () => generateHandlerId,
29
+ isEventHandlerDefinition: () => isEventHandlerDefinition,
30
+ isEventRouterDefinition: () => isEventRouterDefinition,
31
+ isSimpleEventHandlerConfig: () => isSimpleEventHandlerConfig,
32
+ mapErrorToEventResult: () => mapErrorToEventResult,
33
+ mergeEventRouters: () => mergeEventRouters
34
+ });
35
+ module.exports = __toCommonJS(events_exports);
36
+
37
+ // src/presentation/events/handler/define-event-handler.ts
38
+ function defineEventHandler(input) {
39
+ const definition = {
40
+ eventType: input.eventType,
41
+ payload: input.payload ?? void 0,
42
+ context: input.context ?? void 0,
43
+ docs: {
44
+ summary: input.docs?.summary,
45
+ description: input.docs?.description,
46
+ tags: input.docs?.tags,
47
+ deprecated: input.docs?.deprecated ?? false
48
+ },
49
+ _types: void 0
50
+ };
51
+ return Object.freeze(definition);
52
+ }
53
+
54
+ // src/presentation/events/handler/types/event-router-definition.type.ts
55
+ function isEventHandlerDefinition(value) {
56
+ return typeof value === "object" && value !== null && "eventType" in value && "_types" in value;
57
+ }
58
+ function isEventRouterDefinition(value) {
59
+ return typeof value === "object" && value !== null && "_isEventRouter" in value && value._isEventRouter === true;
60
+ }
61
+ function collectEventHandlers(config, basePath = "") {
62
+ const handlers = [];
63
+ for (const [key, value] of Object.entries(config)) {
64
+ const fullKey = basePath ? `${basePath}.${key}` : key;
65
+ if (isEventHandlerDefinition(value)) {
66
+ handlers.push({ key: fullKey, handler: value });
67
+ } else if (isEventRouterDefinition(value)) {
68
+ handlers.push(...collectEventHandlers(value.handlers, fullKey));
69
+ } else if (typeof value === "object" && value !== null) {
70
+ handlers.push(...collectEventHandlers(value, fullKey));
71
+ }
72
+ }
73
+ return handlers;
74
+ }
75
+
76
+ // src/presentation/events/handler/define-event-router.ts
77
+ function defineEventRouter(handlers, options) {
78
+ const defaults = options?.defaults;
79
+ const processedHandlers = defaults?.context || defaults?.tags ? applyEventRouterDefaults(handlers, defaults) : handlers;
80
+ const definition = {
81
+ handlers: processedHandlers,
82
+ defaults,
83
+ _isEventRouter: true
84
+ };
85
+ return deepFreeze(definition);
86
+ }
87
+ function applyEventRouterDefaults(handlers, defaults) {
88
+ const result = {};
89
+ for (const [key, value] of Object.entries(handlers)) {
90
+ if (isEventHandlerDefinition(value)) {
91
+ result[key] = applyDefaultsToEventHandler(value, defaults);
92
+ } else if (isEventRouterDefinition(value)) {
93
+ result[key] = {
94
+ ...value,
95
+ handlers: applyEventRouterDefaults(value.handlers, defaults)
96
+ };
97
+ } else if (typeof value === "object" && value !== null) {
98
+ result[key] = applyEventRouterDefaults(value, defaults);
99
+ }
100
+ }
101
+ return result;
102
+ }
103
+ function applyDefaultsToEventHandler(handler, defaults) {
104
+ const needsContext = defaults.context && !handler.context;
105
+ const needsTags = defaults.tags && defaults.tags.length > 0;
106
+ if (!needsContext && !needsTags) return handler;
107
+ return Object.freeze({
108
+ ...handler,
109
+ context: handler.context ?? defaults.context ?? void 0,
110
+ docs: {
111
+ ...handler.docs,
112
+ tags: mergeTags(defaults.tags, handler.docs.tags)
113
+ }
114
+ });
115
+ }
116
+ function mergeTags(routerTags, handlerTags) {
117
+ if (!routerTags || routerTags.length === 0) return handlerTags;
118
+ if (!handlerTags || handlerTags.length === 0) return routerTags;
119
+ const merged = [...routerTags];
120
+ for (const tag of handlerTags) {
121
+ if (!merged.includes(tag)) {
122
+ merged.push(tag);
123
+ }
124
+ }
125
+ return merged;
126
+ }
127
+ function deepFreeze(obj) {
128
+ const propNames = Object.getOwnPropertyNames(obj);
129
+ for (const name of propNames) {
130
+ const value = obj[name];
131
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
132
+ deepFreeze(value);
133
+ }
134
+ }
135
+ return Object.freeze(obj);
136
+ }
137
+ function extractHandlers(input) {
138
+ return isEventRouterDefinition(input) ? input.handlers : input;
139
+ }
140
+ function isSubRouter(value) {
141
+ return typeof value === "object" && value !== null && !isEventHandlerDefinition(value) && !isEventRouterDefinition(value);
142
+ }
143
+ function deepMergeConfigs(a, b) {
144
+ const result = { ...a };
145
+ for (const key of Object.keys(b)) {
146
+ const aVal = result[key];
147
+ const bVal = b[key];
148
+ if (isSubRouter(aVal) && isSubRouter(bVal)) {
149
+ result[key] = deepMergeConfigs(aVal, bVal);
150
+ } else {
151
+ result[key] = bVal;
152
+ }
153
+ }
154
+ return result;
155
+ }
156
+ function mergeEventRouters(...routers) {
157
+ const merged = routers.map(extractHandlers).reduce(deepMergeConfigs);
158
+ return defineEventRouter(merged);
159
+ }
160
+
161
+ // src/presentation/events/handler/utils.ts
162
+ function generateHandlerId(key) {
163
+ return key.replace(/\.(\w)/g, (_, char) => char.toUpperCase());
164
+ }
165
+
166
+ // src/presentation/http/shared/error-mapping.ts
167
+ function isErrorType(error, typeName) {
168
+ if (!error || typeof error !== "object") return false;
169
+ const constructor = Object.prototype.hasOwnProperty.call(error, "constructor") ? error.constructor : Object.getPrototypeOf(error)?.constructor;
170
+ if (!constructor) return false;
171
+ const name = constructor.name;
172
+ return name === typeName || name === `_${typeName}`;
173
+ }
174
+
175
+ // src/presentation/events/shared/error-mapping.ts
176
+ var DLQ_ERROR_TYPES = [
177
+ "ObjectValidationError",
178
+ "InvalidRequestError",
179
+ "UseCaseError",
180
+ "DomainError",
181
+ "UnprocessableError",
182
+ "AccessDeniedError",
183
+ "ForbiddenError",
184
+ "UnauthorizedError",
185
+ "InvariantViolationError"
186
+ ];
187
+ var RETRY_ERROR_TYPES = [
188
+ "NotFoundError",
189
+ "ConflictError",
190
+ "InfraError",
191
+ "DbError",
192
+ "NetworkError",
193
+ "TimeoutError",
194
+ "ExternalServiceError",
195
+ "PersistenceError"
196
+ ];
197
+ function mapErrorToEventResult(error) {
198
+ for (const typeName of DLQ_ERROR_TYPES) {
199
+ if (isErrorType(error, typeName)) {
200
+ return {
201
+ outcome: "dlq",
202
+ reason: error.message
203
+ };
204
+ }
205
+ }
206
+ for (const typeName of RETRY_ERROR_TYPES) {
207
+ if (isErrorType(error, typeName)) {
208
+ return {
209
+ outcome: "retry",
210
+ reason: error.message
211
+ };
212
+ }
213
+ }
214
+ const message = error instanceof Error ? error.message : "Unknown error occurred during event processing";
215
+ return {
216
+ outcome: "retry",
217
+ reason: message
218
+ };
219
+ }
220
+
221
+ // src/presentation/events/server/types.ts
222
+ function isSimpleEventHandlerConfig(config) {
223
+ return "handler" in config && typeof config.handler === "function";
224
+ }
225
+
226
+ // src/presentation/events/server/create-event-routes.ts
227
+ function createEventRoutesInternal(router, handlers, options) {
228
+ const config = isEventRouterDefinition(router) ? router.handlers : router;
229
+ const collectedHandlers = collectEventHandlers(config);
230
+ const result = [];
231
+ const resolvedOptions = {
232
+ ...options,
233
+ validatePayload: options?.validatePayload ?? true,
234
+ allowPartial: options?.allowPartial ?? false
235
+ };
236
+ for (const { key, handler: handlerDef } of collectedHandlers) {
237
+ const handlerConfig = handlers[key];
238
+ if (!handlerConfig) {
239
+ if (resolvedOptions.allowPartial) {
240
+ continue;
241
+ }
242
+ throw new Error(
243
+ `Missing handler for event "${key}". All event handlers must have a handler configuration.`
244
+ );
245
+ }
246
+ result.push(createEventHandler(key, handlerDef, handlerConfig, resolvedOptions));
247
+ }
248
+ return result;
249
+ }
250
+ function createEventHandler(key, handlerDef, config, options) {
251
+ const middleware = config.middleware ?? [];
252
+ const globalMiddleware = options?.middleware ?? [];
253
+ const allMiddleware = [...globalMiddleware, ...middleware];
254
+ const shouldValidatePayload = options.validatePayload ?? true;
255
+ const errorMapper = options.errorMapper ?? mapErrorToEventResult;
256
+ return {
257
+ eventType: handlerDef.eventType,
258
+ metadata: {
259
+ handlerId: generateHandlerId(key),
260
+ summary: handlerDef.docs.summary,
261
+ description: handlerDef.docs.description,
262
+ tags: handlerDef.docs.tags,
263
+ deprecated: handlerDef.docs.deprecated
264
+ },
265
+ handler: async (rawEvent) => {
266
+ try {
267
+ let validatedContext = rawEvent.metadata;
268
+ if (handlerDef.context) {
269
+ const contextResult = validateContextData(handlerDef, rawEvent.metadata);
270
+ if (!contextResult.success) {
271
+ const errors = contextResult.errors ?? [];
272
+ return {
273
+ outcome: "dlq",
274
+ reason: `Context validation failed: ${errors.map((e) => `${e.path.join(".")}: ${e.message}`).join("; ")}`
275
+ };
276
+ }
277
+ validatedContext = contextResult.data;
278
+ }
279
+ let validatedPayload = rawEvent.payload;
280
+ if (shouldValidatePayload && handlerDef.payload) {
281
+ const payloadResult = validatePayloadData(handlerDef, rawEvent.payload);
282
+ if (!payloadResult.success) {
283
+ const errors = payloadResult.errors ?? [];
284
+ return {
285
+ outcome: "dlq",
286
+ reason: `Payload validation failed: ${errors.map((e) => `${e.path.join(".")}: ${e.message}`).join("; ")}`
287
+ };
288
+ }
289
+ validatedPayload = payloadResult.data;
290
+ }
291
+ const validatedEvent = {
292
+ payload: validatedPayload,
293
+ raw: rawEvent
294
+ };
295
+ const executePipeline = async () => {
296
+ if (isSimpleEventHandlerConfig(config)) {
297
+ return config.handler(
298
+ validatedEvent,
299
+ validatedContext
300
+ );
301
+ } else {
302
+ const { payloadMapper, useCase, resultMapper } = config;
303
+ const input = payloadMapper(
304
+ validatedEvent,
305
+ validatedContext
306
+ );
307
+ const output = await useCase.execute(input);
308
+ return resultMapper ? resultMapper(output) : { outcome: "ack" };
309
+ }
310
+ };
311
+ if (allMiddleware.length === 0) {
312
+ return await executePipeline();
313
+ }
314
+ let index = 0;
315
+ const next = async () => {
316
+ if (index >= allMiddleware.length) {
317
+ return executePipeline();
318
+ }
319
+ const mw = allMiddleware[index++];
320
+ return mw(rawEvent, next);
321
+ };
322
+ return await next();
323
+ } catch (error) {
324
+ return errorMapper(error);
325
+ }
326
+ }
327
+ };
328
+ }
329
+ function validatePayloadData(handler, payload) {
330
+ const schema = handler.payload;
331
+ if (!schema) return { success: true, data: payload };
332
+ const result = schema.validate(payload);
333
+ if (result.success) {
334
+ return { success: true, data: result.data };
335
+ }
336
+ const errors = result.issues.map((issue) => ({
337
+ ...issue,
338
+ path: ["payload", ...issue.path]
339
+ }));
340
+ return { success: false, errors };
341
+ }
342
+ function validateContextData(handler, metadata) {
343
+ const schema = handler.context;
344
+ if (!schema) return { success: true, data: metadata };
345
+ const result = schema.validate(metadata);
346
+ if (result.success) {
347
+ return { success: true, data: result.data };
348
+ }
349
+ const errors = result.issues.map((issue) => ({
350
+ ...issue,
351
+ path: ["context", ...issue.path]
352
+ }));
353
+ return { success: false, errors };
354
+ }
355
+
356
+ // src/presentation/events/server/event-routes-builder.ts
357
+ var EventRoutesBuilderImpl = class _EventRoutesBuilderImpl {
358
+ router;
359
+ handlers;
360
+ constructor(router, handlers) {
361
+ this.router = router;
362
+ this.handlers = handlers ?? /* @__PURE__ */ new Map();
363
+ }
364
+ handle(key, handlerOrConfig) {
365
+ const config = typeof handlerOrConfig === "function" ? { handler: handlerOrConfig } : handlerOrConfig;
366
+ const newHandlers = new Map(this.handlers);
367
+ newHandlers.set(key, config);
368
+ return new _EventRoutesBuilderImpl(
369
+ this.router,
370
+ newHandlers
371
+ );
372
+ }
373
+ handleWithUseCase(key, config) {
374
+ const newHandlers = new Map(this.handlers);
375
+ newHandlers.set(
376
+ key,
377
+ config
378
+ );
379
+ return new _EventRoutesBuilderImpl(
380
+ this.router,
381
+ newHandlers
382
+ );
383
+ }
384
+ build(options) {
385
+ return createEventRoutesInternal(this.router, Object.fromEntries(this.handlers), options);
386
+ }
387
+ buildPartial(options) {
388
+ return createEventRoutesInternal(this.router, Object.fromEntries(this.handlers), {
389
+ ...options,
390
+ allowPartial: true
391
+ });
392
+ }
393
+ };
394
+ function eventRoutes(router) {
395
+ return new EventRoutesBuilderImpl(router);
396
+ }
397
+
398
+ // src/presentation/events/asyncapi/generate.ts
399
+ function generateAsyncAPI(router, config) {
400
+ const routerConfig = isEventRouterDefinition(router) ? router.handlers : router;
401
+ const handlers = collectEventHandlers(routerConfig);
402
+ const channels = {};
403
+ const operations = {};
404
+ const allTags = /* @__PURE__ */ new Set();
405
+ for (const { key, handler } of handlers) {
406
+ const handlerId = generateHandlerId(key);
407
+ const channelId = handler.eventType;
408
+ const message = buildMessage(handler.eventType, handler.payload, handler.docs);
409
+ if (!channels[channelId]) {
410
+ channels[channelId] = {
411
+ address: handler.eventType,
412
+ messages: {}
413
+ };
414
+ }
415
+ const channelMessages = { ...channels[channelId].messages ?? {} };
416
+ channelMessages[handlerId] = message;
417
+ channels[channelId] = { ...channels[channelId], messages: channelMessages };
418
+ const operation = {
419
+ action: "receive",
420
+ channel: { $ref: `#/channels/${channelId}` },
421
+ messages: [{ $ref: `#/channels/${channelId}/messages/${handlerId}` }]
422
+ };
423
+ if (handler.docs.summary) {
424
+ operation.summary = handler.docs.summary;
425
+ }
426
+ if (handler.docs.description) {
427
+ operation.description = handler.docs.description;
428
+ }
429
+ if (handler.docs.deprecated) {
430
+ operation.deprecated = true;
431
+ }
432
+ if (handler.docs.tags && handler.docs.tags.length > 0) {
433
+ operation.tags = handler.docs.tags.map((t) => ({
434
+ name: t
435
+ }));
436
+ for (const tag of handler.docs.tags) {
437
+ allTags.add(tag);
438
+ }
439
+ }
440
+ operations[handlerId] = operation;
441
+ }
442
+ const tags = config.tags ? [...config.tags] : [];
443
+ for (const tagName of allTags) {
444
+ if (!tags.some((t) => t.name === tagName)) {
445
+ tags.push({ name: tagName });
446
+ }
447
+ }
448
+ const info = tags.length > 0 ? { ...config.info, tags } : config.info;
449
+ const spec = {
450
+ asyncapi: config.asyncapi ?? "3.0.0",
451
+ info,
452
+ defaultContentType: config.defaultContentType ?? "application/json",
453
+ channels,
454
+ operations
455
+ };
456
+ if (config.servers && Object.keys(config.servers).length > 0) {
457
+ spec.servers = config.servers;
458
+ }
459
+ if (config.externalDocs) {
460
+ spec.externalDocs = config.externalDocs;
461
+ }
462
+ return spec;
463
+ }
464
+ function buildMessage(eventType, payload, docs) {
465
+ const message = {
466
+ name: eventType
467
+ };
468
+ if (docs.summary) {
469
+ message.summary = docs.summary;
470
+ }
471
+ if (docs.description) {
472
+ message.description = docs.description;
473
+ }
474
+ if (docs.deprecated) {
475
+ message.deprecated = true;
476
+ }
477
+ if (payload) {
478
+ const schema = payload.toJsonSchema();
479
+ message.payload = schema;
480
+ }
481
+ return message;
482
+ }
483
+ // Annotate the CommonJS export names for ESM import in node:
484
+ 0 && (module.exports = {
485
+ collectEventHandlers,
486
+ defineEventHandler,
487
+ defineEventRouter,
488
+ eventRoutes,
489
+ generateAsyncAPI,
490
+ generateHandlerId,
491
+ isEventHandlerDefinition,
492
+ isEventRouterDefinition,
493
+ isSimpleEventHandlerConfig,
494
+ mapErrorToEventResult,
495
+ mergeEventRouters
496
+ });
497
+ //# sourceMappingURL=index.cjs.map