@cosmneo/onion-lasagna 0.2.1 → 0.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.
Files changed (61) 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-CBTICRSM.js +34 -0
  6. package/dist/chunk-CBTICRSM.js.map +1 -0
  7. package/dist/chunk-KJ4JGZOE.js +96 -0
  8. package/dist/chunk-KJ4JGZOE.js.map +1 -0
  9. package/dist/chunk-RVSBIYY4.js +1 -0
  10. package/dist/chunk-RVSBIYY4.js.map +1 -0
  11. package/dist/{chunk-MF2JDREK.js → chunk-UNVB4INM.js} +1 -1
  12. package/dist/{chunk-MF2JDREK.js.map → chunk-UNVB4INM.js.map} +1 -1
  13. package/dist/chunk-XWKHOLIP.js +191 -0
  14. package/dist/chunk-XWKHOLIP.js.map +1 -0
  15. package/dist/event-router-definition.type-CP9uTlux.d.cts +150 -0
  16. package/dist/event-router-definition.type-D8CG-kjZ.d.ts +150 -0
  17. package/dist/events/asyncapi/index.cjs +143 -0
  18. package/dist/events/asyncapi/index.cjs.map +1 -0
  19. package/dist/events/asyncapi/index.d.cts +184 -0
  20. package/dist/events/asyncapi/index.d.ts +184 -0
  21. package/dist/events/asyncapi/index.js +8 -0
  22. package/dist/events/asyncapi/index.js.map +1 -0
  23. package/dist/events/handler/index.cjs +171 -0
  24. package/dist/events/handler/index.cjs.map +1 -0
  25. package/dist/events/handler/index.d.cts +153 -0
  26. package/dist/events/handler/index.d.ts +153 -0
  27. package/dist/events/handler/index.js +21 -0
  28. package/dist/events/handler/index.js.map +1 -0
  29. package/dist/events/index.cjs +497 -0
  30. package/dist/events/index.cjs.map +1 -0
  31. package/dist/events/index.d.cts +9 -0
  32. package/dist/events/index.d.ts +9 -0
  33. package/dist/events/index.js +41 -0
  34. package/dist/events/index.js.map +1 -0
  35. package/dist/events/server/index.cjs +291 -0
  36. package/dist/events/server/index.cjs.map +1 -0
  37. package/dist/events/server/index.d.cts +281 -0
  38. package/dist/events/server/index.d.ts +281 -0
  39. package/dist/events/server/index.js +16 -0
  40. package/dist/events/server/index.js.map +1 -0
  41. package/dist/events/shared/index.cjs +85 -0
  42. package/dist/events/shared/index.cjs.map +1 -0
  43. package/dist/events/shared/index.d.cts +35 -0
  44. package/dist/events/shared/index.d.ts +35 -0
  45. package/dist/events/shared/index.js +13 -0
  46. package/dist/events/shared/index.js.map +1 -0
  47. package/dist/http/index.cjs.map +1 -1
  48. package/dist/http/index.d.cts +2 -1
  49. package/dist/http/index.d.ts +2 -1
  50. package/dist/http/index.js +4 -4
  51. package/dist/http/route/index.cjs.map +1 -1
  52. package/dist/http/route/index.d.cts +4 -0
  53. package/dist/http/route/index.d.ts +4 -0
  54. package/dist/http/route/index.js +1 -1
  55. package/dist/http/server/index.d.cts +4 -261
  56. package/dist/http/server/index.d.ts +4 -261
  57. package/dist/types-B6Q1iCgf.d.ts +262 -0
  58. package/dist/types-afYpL7Ap.d.cts +262 -0
  59. package/dist/types-cke61juH.d.cts +42 -0
  60. package/dist/types-cke61juH.d.ts +42 -0
  61. package/package.json +35 -2
@@ -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