@cosmneo/onion-lasagna 0.1.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 (97) hide show
  1. package/dist/backend/core/global.cjs +283 -0
  2. package/dist/backend/core/global.cjs.map +1 -0
  3. package/dist/backend/core/global.d.cts +294 -0
  4. package/dist/backend/core/global.d.ts +294 -0
  5. package/dist/backend/core/global.js +39 -0
  6. package/dist/backend/core/global.js.map +1 -0
  7. package/dist/backend/core/onion-layers.cjs +2302 -0
  8. package/dist/backend/core/onion-layers.cjs.map +1 -0
  9. package/dist/backend/core/onion-layers.d.cts +1675 -0
  10. package/dist/backend/core/onion-layers.d.ts +1675 -0
  11. package/dist/backend/core/onion-layers.js +1158 -0
  12. package/dist/backend/core/onion-layers.js.map +1 -0
  13. package/dist/backend/core/presentation.cjs +573 -0
  14. package/dist/backend/core/presentation.cjs.map +1 -0
  15. package/dist/backend/core/presentation.d.cts +5 -0
  16. package/dist/backend/core/presentation.d.ts +5 -0
  17. package/dist/backend/core/presentation.js +28 -0
  18. package/dist/backend/core/presentation.js.map +1 -0
  19. package/dist/backend/core/validators/arktype.cjs +947 -0
  20. package/dist/backend/core/validators/arktype.cjs.map +1 -0
  21. package/dist/backend/core/validators/arktype.d.cts +188 -0
  22. package/dist/backend/core/validators/arktype.d.ts +188 -0
  23. package/dist/backend/core/validators/arktype.js +287 -0
  24. package/dist/backend/core/validators/arktype.js.map +1 -0
  25. package/dist/backend/core/validators/typebox.cjs +939 -0
  26. package/dist/backend/core/validators/typebox.cjs.map +1 -0
  27. package/dist/backend/core/validators/typebox.d.cts +189 -0
  28. package/dist/backend/core/validators/typebox.d.ts +189 -0
  29. package/dist/backend/core/validators/typebox.js +281 -0
  30. package/dist/backend/core/validators/typebox.js.map +1 -0
  31. package/dist/backend/core/validators/valibot.cjs +942 -0
  32. package/dist/backend/core/validators/valibot.cjs.map +1 -0
  33. package/dist/backend/core/validators/valibot.d.cts +160 -0
  34. package/dist/backend/core/validators/valibot.d.ts +160 -0
  35. package/dist/backend/core/validators/valibot.js +294 -0
  36. package/dist/backend/core/validators/valibot.js.map +1 -0
  37. package/dist/backend/core/validators/zod.cjs +934 -0
  38. package/dist/backend/core/validators/zod.cjs.map +1 -0
  39. package/dist/backend/core/validators/zod.d.cts +188 -0
  40. package/dist/backend/core/validators/zod.d.ts +188 -0
  41. package/dist/backend/core/validators/zod.js +278 -0
  42. package/dist/backend/core/validators/zod.js.map +1 -0
  43. package/dist/backend/frameworks/elysia.cjs +715 -0
  44. package/dist/backend/frameworks/elysia.cjs.map +1 -0
  45. package/dist/backend/frameworks/elysia.d.cts +208 -0
  46. package/dist/backend/frameworks/elysia.d.ts +208 -0
  47. package/dist/backend/frameworks/elysia.js +251 -0
  48. package/dist/backend/frameworks/elysia.js.map +1 -0
  49. package/dist/backend/frameworks/fastify.cjs +677 -0
  50. package/dist/backend/frameworks/fastify.cjs.map +1 -0
  51. package/dist/backend/frameworks/fastify.d.cts +201 -0
  52. package/dist/backend/frameworks/fastify.d.ts +201 -0
  53. package/dist/backend/frameworks/fastify.js +213 -0
  54. package/dist/backend/frameworks/fastify.js.map +1 -0
  55. package/dist/backend/frameworks/hono.cjs +715 -0
  56. package/dist/backend/frameworks/hono.cjs.map +1 -0
  57. package/dist/backend/frameworks/hono.d.cts +163 -0
  58. package/dist/backend/frameworks/hono.d.ts +163 -0
  59. package/dist/backend/frameworks/hono.js +249 -0
  60. package/dist/backend/frameworks/hono.js.map +1 -0
  61. package/dist/backend/frameworks/nestjs.cjs +260 -0
  62. package/dist/backend/frameworks/nestjs.cjs.map +1 -0
  63. package/dist/backend/frameworks/nestjs.d.cts +168 -0
  64. package/dist/backend/frameworks/nestjs.d.ts +168 -0
  65. package/dist/backend/frameworks/nestjs.js +193 -0
  66. package/dist/backend/frameworks/nestjs.js.map +1 -0
  67. package/dist/base-dto.class-D7W9iqoU.d.cts +146 -0
  68. package/dist/base-dto.class-D7W9iqoU.d.ts +146 -0
  69. package/dist/base-uuid-v7.vo-BPGEIWLM.d.ts +799 -0
  70. package/dist/base-uuid-v7.vo-BjqKX44G.d.cts +799 -0
  71. package/dist/chunk-74IKUOSE.js +116 -0
  72. package/dist/chunk-74IKUOSE.js.map +1 -0
  73. package/dist/chunk-BKZOLGQW.js +29 -0
  74. package/dist/chunk-BKZOLGQW.js.map +1 -0
  75. package/dist/chunk-CGZBV6BD.js +54 -0
  76. package/dist/chunk-CGZBV6BD.js.map +1 -0
  77. package/dist/chunk-DDAHJZVK.js +258 -0
  78. package/dist/chunk-DDAHJZVK.js.map +1 -0
  79. package/dist/chunk-MQD5GXMT.js +171 -0
  80. package/dist/chunk-MQD5GXMT.js.map +1 -0
  81. package/dist/chunk-OKFXZHBC.js +43 -0
  82. package/dist/chunk-OKFXZHBC.js.map +1 -0
  83. package/dist/chunk-RLLWYFPI.js +168 -0
  84. package/dist/chunk-RLLWYFPI.js.map +1 -0
  85. package/dist/chunk-VCHFXT5W.js +425 -0
  86. package/dist/chunk-VCHFXT5W.js.map +1 -0
  87. package/dist/chunk-ZWLYNGO3.js +40 -0
  88. package/dist/chunk-ZWLYNGO3.js.map +1 -0
  89. package/dist/http-response-BAhi8lF4.d.cts +124 -0
  90. package/dist/http-response-BAhi8lF4.d.ts +124 -0
  91. package/dist/index-DingXh7B.d.cts +1187 -0
  92. package/dist/index-tOH7XBa3.d.ts +1187 -0
  93. package/dist/routing.type-DB4pt-d9.d.ts +184 -0
  94. package/dist/routing.type-DF2BIL7x.d.cts +184 -0
  95. package/dist/validation-error.type-kD4_qNZ9.d.cts +199 -0
  96. package/dist/validation-error.type-kD4_qNZ9.d.ts +199 -0
  97. package/package.json +191 -0
@@ -0,0 +1,283 @@
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/backend/core/global/index.ts
21
+ var global_exports = {};
22
+ __export(global_exports, {
23
+ BaseDto: () => BaseDto,
24
+ CodedError: () => CodedError,
25
+ ErrorCodes: () => ErrorCodes,
26
+ ObjectValidationError: () => ObjectValidationError,
27
+ SKIP_DTO_VALIDATION: () => SKIP_DTO_VALIDATION,
28
+ fieldChanged: () => fieldChanged,
29
+ wrapError: () => wrapError,
30
+ wrapErrorAsync: () => wrapErrorAsync,
31
+ wrapErrorUnless: () => wrapErrorUnless,
32
+ wrapErrorUnlessAsync: () => wrapErrorUnlessAsync
33
+ });
34
+ module.exports = __toCommonJS(global_exports);
35
+
36
+ // src/backend/core/global/classes/base-dto.class.ts
37
+ var SKIP_DTO_VALIDATION = "skip dto validation";
38
+ var BaseDto = class {
39
+ _data;
40
+ /**
41
+ * Creates a new DTO instance.
42
+ *
43
+ * @param data - The raw data to validate and wrap
44
+ * @param validator - A bound validator or SKIP_DTO_VALIDATION to bypass
45
+ * @throws {ObjectValidationError} When validation fails
46
+ */
47
+ constructor(data, validator) {
48
+ this._data = validator === SKIP_DTO_VALIDATION ? data : validator.validate(data);
49
+ }
50
+ /**
51
+ * The validated data payload.
52
+ *
53
+ * @returns The validated data of type T
54
+ */
55
+ get data() {
56
+ return this._data;
57
+ }
58
+ };
59
+
60
+ // src/backend/core/global/exceptions/error-codes.const.ts
61
+ var ErrorCodes = {
62
+ /**
63
+ * Domain layer error codes.
64
+ * Used for business rule violations and invariant failures.
65
+ */
66
+ Domain: {
67
+ /** Generic domain error */
68
+ DOMAIN_ERROR: "DOMAIN_ERROR",
69
+ /** Business invariant was violated */
70
+ INVARIANT_VIOLATION: "INVARIANT_VIOLATION",
71
+ /** Aggregate was partially loaded (missing required relations) */
72
+ PARTIAL_LOAD: "PARTIAL_LOAD"
73
+ },
74
+ /**
75
+ * Application layer (use case) error codes.
76
+ * Used for orchestration failures and business operation errors.
77
+ */
78
+ App: {
79
+ /** Generic use case error */
80
+ USE_CASE_ERROR: "USE_CASE_ERROR",
81
+ /** Requested resource was not found */
82
+ NOT_FOUND: "NOT_FOUND",
83
+ /** Resource state conflict (e.g., duplicate, already exists) */
84
+ CONFLICT: "CONFLICT",
85
+ /** Request is valid but cannot be processed due to business rules */
86
+ UNPROCESSABLE: "UNPROCESSABLE"
87
+ },
88
+ /**
89
+ * Infrastructure layer error codes.
90
+ * Used for data access, external services, and I/O failures.
91
+ */
92
+ Infra: {
93
+ /** Generic infrastructure error */
94
+ INFRA_ERROR: "INFRA_ERROR",
95
+ /** Database operation failed */
96
+ DB_ERROR: "DB_ERROR",
97
+ /** Network connectivity or communication error */
98
+ NETWORK_ERROR: "NETWORK_ERROR",
99
+ /** Operation timed out */
100
+ TIMEOUT_ERROR: "TIMEOUT_ERROR",
101
+ /** External/third-party service error */
102
+ EXTERNAL_SERVICE_ERROR: "EXTERNAL_SERVICE_ERROR"
103
+ },
104
+ /**
105
+ * Presentation layer error codes.
106
+ * Used for controller, request handling, and authorization errors.
107
+ */
108
+ Presentation: {
109
+ /** Generic controller error */
110
+ CONTROLLER_ERROR: "CONTROLLER_ERROR",
111
+ /** Request denied due to authorization failure */
112
+ ACCESS_DENIED: "ACCESS_DENIED",
113
+ /** Request validation failed (malformed input) */
114
+ INVALID_REQUEST: "INVALID_REQUEST"
115
+ },
116
+ /**
117
+ * Global/cross-cutting error codes.
118
+ * Used for validation and other cross-layer concerns.
119
+ */
120
+ Global: {
121
+ /** Object/schema validation failed */
122
+ OBJECT_VALIDATION_ERROR: "OBJECT_VALIDATION_ERROR"
123
+ }
124
+ };
125
+
126
+ // src/backend/core/global/exceptions/coded-error.error.ts
127
+ var CodedError = class extends Error {
128
+ /** Machine-readable error code for programmatic handling. */
129
+ code;
130
+ /**
131
+ * Creates a new CodedError instance.
132
+ *
133
+ * @param options - Error configuration
134
+ * @param options.message - Human-readable error message
135
+ * @param options.code - Machine-readable error code from ErrorCodes registry or custom string
136
+ * @param options.cause - Optional underlying error that caused this error
137
+ */
138
+ constructor({
139
+ message,
140
+ code,
141
+ cause
142
+ }) {
143
+ super(message);
144
+ this.name = this.constructor.name;
145
+ this.code = code;
146
+ if (cause !== void 0) {
147
+ Object.defineProperty(this, "cause", {
148
+ value: cause,
149
+ writable: false,
150
+ enumerable: false,
151
+ configurable: true
152
+ });
153
+ }
154
+ }
155
+ /**
156
+ * Factory method to create a typed error from a caught error.
157
+ *
158
+ * Subclasses should override this to provide proper error transformation.
159
+ * Designed for use with {@link wrapErrorAsync} and {@link wrapError}.
160
+ *
161
+ * @param _cause - The original caught error
162
+ * @returns A new CodedError instance
163
+ * @throws {Error} If not overridden by subclass
164
+ *
165
+ * @example
166
+ * ```typescript
167
+ * class NotFoundError extends UseCaseError {
168
+ * static override fromError(cause: unknown): NotFoundError {
169
+ * return new NotFoundError({
170
+ * message: 'Resource not found',
171
+ * cause,
172
+ * });
173
+ * }
174
+ * }
175
+ * ```
176
+ */
177
+ static fromError(_cause) {
178
+ throw new Error(`${this.name}.fromError() must be implemented by subclass`);
179
+ }
180
+ };
181
+
182
+ // src/backend/core/global/exceptions/object-validation.error.ts
183
+ var ObjectValidationError = class _ObjectValidationError extends CodedError {
184
+ /**
185
+ * Array of field-level validation errors.
186
+ *
187
+ * Each entry contains:
188
+ * - `field`: Dot-notation path to the invalid field (e.g., 'user.email')
189
+ * - `message`: Human-readable validation failure message
190
+ */
191
+ validationErrors;
192
+ /**
193
+ * Creates a new ObjectValidationError instance.
194
+ *
195
+ * @param options - Error configuration
196
+ * @param options.message - Human-readable summary message
197
+ * @param options.code - Machine-readable error code (default: 'OBJECT_VALIDATION_ERROR')
198
+ * @param options.cause - Optional underlying error from validation library
199
+ * @param options.validationErrors - Array of field-level validation errors
200
+ */
201
+ constructor({
202
+ message,
203
+ code = ErrorCodes.Global.OBJECT_VALIDATION_ERROR,
204
+ cause,
205
+ validationErrors
206
+ }) {
207
+ super({ message, code, cause });
208
+ this.validationErrors = validationErrors;
209
+ }
210
+ /**
211
+ * Creates an ObjectValidationError from a caught error.
212
+ *
213
+ * @param cause - The original caught error
214
+ * @returns A new ObjectValidationError instance with the cause attached
215
+ */
216
+ static fromError(cause) {
217
+ return new _ObjectValidationError({
218
+ message: cause instanceof Error ? cause.message : "Validation failed",
219
+ cause,
220
+ validationErrors: []
221
+ });
222
+ }
223
+ };
224
+
225
+ // src/backend/core/global/utils/field-changed.util.ts
226
+ function fieldChanged({
227
+ value,
228
+ newValue,
229
+ partialUpdate = true
230
+ }) {
231
+ if (partialUpdate && newValue === void 0) return false;
232
+ return value !== newValue;
233
+ }
234
+
235
+ // src/backend/core/global/utils/wrap-error.util.ts
236
+ function wrapError(fn, errorFactory) {
237
+ try {
238
+ return fn();
239
+ } catch (error) {
240
+ throw errorFactory(error);
241
+ }
242
+ }
243
+ async function wrapErrorAsync(fn, errorFactory) {
244
+ try {
245
+ return await fn();
246
+ } catch (error) {
247
+ throw errorFactory(error);
248
+ }
249
+ }
250
+ function wrapErrorUnless(fn, errorFactory, passthroughTypes) {
251
+ try {
252
+ return fn();
253
+ } catch (error) {
254
+ if (passthroughTypes.some((Type) => error instanceof Type)) {
255
+ throw error;
256
+ }
257
+ throw errorFactory(error);
258
+ }
259
+ }
260
+ async function wrapErrorUnlessAsync(fn, errorFactory, passthroughTypes) {
261
+ try {
262
+ return await fn();
263
+ } catch (error) {
264
+ if (passthroughTypes.some((Type) => error instanceof Type)) {
265
+ throw error;
266
+ }
267
+ throw errorFactory(error);
268
+ }
269
+ }
270
+ // Annotate the CommonJS export names for ESM import in node:
271
+ 0 && (module.exports = {
272
+ BaseDto,
273
+ CodedError,
274
+ ErrorCodes,
275
+ ObjectValidationError,
276
+ SKIP_DTO_VALIDATION,
277
+ fieldChanged,
278
+ wrapError,
279
+ wrapErrorAsync,
280
+ wrapErrorUnless,
281
+ wrapErrorUnlessAsync
282
+ });
283
+ //# sourceMappingURL=global.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/backend/core/global/index.ts","../../../src/backend/core/global/classes/base-dto.class.ts","../../../src/backend/core/global/exceptions/error-codes.const.ts","../../../src/backend/core/global/exceptions/coded-error.error.ts","../../../src/backend/core/global/exceptions/object-validation.error.ts","../../../src/backend/core/global/utils/field-changed.util.ts","../../../src/backend/core/global/utils/wrap-error.util.ts"],"sourcesContent":["export * from './classes';\nexport * from './exceptions';\nexport * from './interfaces';\nexport * from './utils';\n","import type { BoundValidator } from '../interfaces/ports/object-validator.port';\n\n/**\n * Sentinel value to skip validation in DTO constructors.\n *\n * Use this when creating a DTO from already-validated data,\n * such as when mapping between layers or in tests.\n *\n * @example\n * ```typescript\n * // Skip validation for already-validated data\n * const dto = new CreateUserInputDto(validatedData, SKIP_DTO_VALIDATION);\n * ```\n */\nexport const SKIP_DTO_VALIDATION = 'skip dto validation' as const;\n\n/**\n * Base class for Data Transfer Objects (DTOs).\n *\n * DTOs are validated data containers used to transfer data between layers.\n * Unlike Value Objects, DTOs are not domain concepts - they are purely\n * for data transfer and validation at system boundaries.\n *\n * Key differences from Value Objects:\n * - **DTOs**: Transfer data between layers (e.g., request/response payloads)\n * - **Value Objects**: Represent domain concepts with behavior (e.g., Email, Money)\n *\n * @typeParam T - The shape of the data being transferred\n *\n * @example\n * ```typescript\n * // Define a DTO with validation\n * class CreateUserInputDto extends BaseDto<{ name: string; email: string }> {\n * private constructor(data: unknown, validator: BoundValidator<{ name: string; email: string }>) {\n * super(data, validator);\n * }\n *\n * static create(data: unknown): CreateUserInputDto {\n * return new CreateUserInputDto(data, createUserValidator);\n * }\n * }\n *\n * // Usage in a controller\n * const dto = CreateUserInputDto.create(request.body);\n * console.log(dto.data.name); // Typed and validated\n * ```\n */\nexport class BaseDto<T> {\n private readonly _data: T;\n\n /**\n * Creates a new DTO instance.\n *\n * @param data - The raw data to validate and wrap\n * @param validator - A bound validator or SKIP_DTO_VALIDATION to bypass\n * @throws {ObjectValidationError} When validation fails\n */\n constructor(data: T, validator: BoundValidator<T> | typeof SKIP_DTO_VALIDATION) {\n this._data = validator === SKIP_DTO_VALIDATION ? data : validator.validate(data);\n }\n\n /**\n * The validated data payload.\n *\n * @returns The validated data of type T\n */\n public get data(): T {\n return this._data;\n }\n}\n","/**\n * Centralized registry of all error codes used across the application.\n *\n * Error codes are grouped by architectural layer to maintain clear boundaries\n * and make it easy to identify where an error originated.\n *\n * @example Using error codes in custom errors\n * ```typescript\n * import { ErrorCodes } from '@cosmneo/onion-lasagna/backend/core/global';\n *\n * throw new NotFoundError({\n * message: 'User not found',\n * code: ErrorCodes.App.NOT_FOUND,\n * });\n * ```\n *\n * @example Checking error codes programmatically\n * ```typescript\n * if (error.code === ErrorCodes.App.NOT_FOUND) {\n * // Handle not found case\n * }\n * ```\n */\nexport const ErrorCodes = {\n /**\n * Domain layer error codes.\n * Used for business rule violations and invariant failures.\n */\n Domain: {\n /** Generic domain error */\n DOMAIN_ERROR: 'DOMAIN_ERROR',\n /** Business invariant was violated */\n INVARIANT_VIOLATION: 'INVARIANT_VIOLATION',\n /** Aggregate was partially loaded (missing required relations) */\n PARTIAL_LOAD: 'PARTIAL_LOAD',\n },\n\n /**\n * Application layer (use case) error codes.\n * Used for orchestration failures and business operation errors.\n */\n App: {\n /** Generic use case error */\n USE_CASE_ERROR: 'USE_CASE_ERROR',\n /** Requested resource was not found */\n NOT_FOUND: 'NOT_FOUND',\n /** Resource state conflict (e.g., duplicate, already exists) */\n CONFLICT: 'CONFLICT',\n /** Request is valid but cannot be processed due to business rules */\n UNPROCESSABLE: 'UNPROCESSABLE',\n },\n\n /**\n * Infrastructure layer error codes.\n * Used for data access, external services, and I/O failures.\n */\n Infra: {\n /** Generic infrastructure error */\n INFRA_ERROR: 'INFRA_ERROR',\n /** Database operation failed */\n DB_ERROR: 'DB_ERROR',\n /** Network connectivity or communication error */\n NETWORK_ERROR: 'NETWORK_ERROR',\n /** Operation timed out */\n TIMEOUT_ERROR: 'TIMEOUT_ERROR',\n /** External/third-party service error */\n EXTERNAL_SERVICE_ERROR: 'EXTERNAL_SERVICE_ERROR',\n },\n\n /**\n * Presentation layer error codes.\n * Used for controller, request handling, and authorization errors.\n */\n Presentation: {\n /** Generic controller error */\n CONTROLLER_ERROR: 'CONTROLLER_ERROR',\n /** Request denied due to authorization failure */\n ACCESS_DENIED: 'ACCESS_DENIED',\n /** Request validation failed (malformed input) */\n INVALID_REQUEST: 'INVALID_REQUEST',\n },\n\n /**\n * Global/cross-cutting error codes.\n * Used for validation and other cross-layer concerns.\n */\n Global: {\n /** Object/schema validation failed */\n OBJECT_VALIDATION_ERROR: 'OBJECT_VALIDATION_ERROR',\n },\n} as const;\n\n/**\n * Type representing all possible domain error codes.\n */\nexport type DomainErrorCode = (typeof ErrorCodes.Domain)[keyof typeof ErrorCodes.Domain];\n\n/**\n * Type representing all possible application error codes.\n */\nexport type AppErrorCode = (typeof ErrorCodes.App)[keyof typeof ErrorCodes.App];\n\n/**\n * Type representing all possible infrastructure error codes.\n */\nexport type InfraErrorCode = (typeof ErrorCodes.Infra)[keyof typeof ErrorCodes.Infra];\n\n/**\n * Type representing all possible presentation error codes.\n */\nexport type PresentationErrorCode =\n (typeof ErrorCodes.Presentation)[keyof typeof ErrorCodes.Presentation];\n\n/**\n * Type representing all possible global error codes.\n */\nexport type GlobalErrorCode = (typeof ErrorCodes.Global)[keyof typeof ErrorCodes.Global];\n\n/**\n * Union type of all error codes across all layers.\n *\n * Use this when you need to accept any valid error code.\n *\n * @example\n * ```typescript\n * function logError(code: ErrorCode, message: string) {\n * console.error(`[${code}] ${message}`);\n * }\n * ```\n */\nexport type ErrorCode =\n | DomainErrorCode\n | AppErrorCode\n | InfraErrorCode\n | PresentationErrorCode\n | GlobalErrorCode;\n","import type { ErrorCode } from './error-codes.const';\n\n/**\n * Base error class for all application errors with a machine-readable code.\n *\n * Abstract class that extends the native `Error` with:\n * - A `code` property for programmatic error handling\n * - Optional `cause` for error chaining (ES2022 compatible)\n * - A `fromError` static factory pattern for error transformation\n *\n * **Why abstract:** Prevents non-declarative error usage. All errors must\n * be explicitly defined as subclasses to ensure consistent error taxonomy.\n *\n * @example Subclass implementation\n * ```typescript\n * class DbError extends InfraError {\n * static override fromError(cause: unknown): DbError {\n * return new DbError({\n * message: cause instanceof Error ? cause.message : 'Database error',\n * cause,\n * });\n * }\n * }\n * ```\n *\n * @example Usage with wrapErrorAsync\n * ```typescript\n * await wrapErrorAsync(\n * () => this.db.query(...),\n * DbError.fromError,\n * );\n * ```\n */\nexport abstract class CodedError extends Error {\n /** Machine-readable error code for programmatic handling. */\n public readonly code: ErrorCode | string;\n\n /**\n * Creates a new CodedError instance.\n *\n * @param options - Error configuration\n * @param options.message - Human-readable error message\n * @param options.code - Machine-readable error code from ErrorCodes registry or custom string\n * @param options.cause - Optional underlying error that caused this error\n */\n constructor({\n message,\n code,\n cause,\n }: {\n message: string;\n code: ErrorCode | string;\n cause?: unknown;\n }) {\n super(message);\n this.name = this.constructor.name;\n this.code = code;\n if (cause !== undefined) {\n Object.defineProperty(this, 'cause', {\n value: cause,\n writable: false,\n enumerable: false,\n configurable: true,\n });\n }\n }\n\n /**\n * Factory method to create a typed error from a caught error.\n *\n * Subclasses should override this to provide proper error transformation.\n * Designed for use with {@link wrapErrorAsync} and {@link wrapError}.\n *\n * @param _cause - The original caught error\n * @returns A new CodedError instance\n * @throws {Error} If not overridden by subclass\n *\n * @example\n * ```typescript\n * class NotFoundError extends UseCaseError {\n * static override fromError(cause: unknown): NotFoundError {\n * return new NotFoundError({\n * message: 'Resource not found',\n * cause,\n * });\n * }\n * }\n * ```\n */\n static fromError(_cause: unknown): CodedError {\n throw new Error(`${this.name}.fromError() must be implemented by subclass`);\n }\n}\n","import { CodedError } from './coded-error.error';\nimport { ErrorCodes, type GlobalErrorCode } from './error-codes.const';\nimport type { ValidationError } from '../interfaces/types/validation-error.type';\n\n/**\n * Error thrown when object validation fails.\n *\n * Contains structured validation errors with field paths and messages,\n * making it easy to report specific validation failures to clients.\n * Thrown by all validator implementations (Zod, ArkType, TypeBox, Valibot).\n *\n * **Flow:**\n * 1. Validator throws `ObjectValidationError` with field-level errors\n * 2. Controller catches and converts to {@link InvalidRequestError}\n * 3. HTTP layer maps to 400 Bad Request with error details\n *\n * @example\n * ```typescript\n * try {\n * const dto = CreateUserDto.create(invalidData);\n * } catch (error) {\n * if (error instanceof ObjectValidationError) {\n * console.log(error.validationErrors);\n * // [\n * // { field: 'email', message: 'Invalid email format' },\n * // { field: 'age', message: 'Must be a positive number' }\n * // ]\n * }\n * }\n * ```\n */\nexport class ObjectValidationError extends CodedError {\n /**\n * Array of field-level validation errors.\n *\n * Each entry contains:\n * - `field`: Dot-notation path to the invalid field (e.g., 'user.email')\n * - `message`: Human-readable validation failure message\n */\n validationErrors: ValidationError[];\n\n /**\n * Creates a new ObjectValidationError instance.\n *\n * @param options - Error configuration\n * @param options.message - Human-readable summary message\n * @param options.code - Machine-readable error code (default: 'OBJECT_VALIDATION_ERROR')\n * @param options.cause - Optional underlying error from validation library\n * @param options.validationErrors - Array of field-level validation errors\n */\n constructor({\n message,\n code = ErrorCodes.Global.OBJECT_VALIDATION_ERROR,\n cause,\n validationErrors,\n }: {\n message: string;\n code?: GlobalErrorCode | string;\n cause?: unknown;\n validationErrors: ValidationError[];\n }) {\n super({ message, code, cause });\n this.validationErrors = validationErrors;\n }\n\n /**\n * Creates an ObjectValidationError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new ObjectValidationError instance with the cause attached\n */\n static override fromError(cause: unknown): ObjectValidationError {\n return new ObjectValidationError({\n message: cause instanceof Error ? cause.message : 'Validation failed',\n cause,\n validationErrors: [],\n });\n }\n}\n","/**\n * Checks if a field has changed by comparing the current value with a new value.\n *\n * Useful for detecting changes in update operations, supporting both partial\n * and full update semantics.\n *\n * **Modes:**\n * - **Partial update** (default): `undefined` means \"keep existing value\" (no change)\n * - **Full update**: `undefined` means \"set to undefined\" (is a change if value !== undefined)\n *\n * **Limitation:** Uses strict equality (`!==`) for comparison, which only works\n * correctly for primitives and reference equality. For objects or arrays, this\n * compares references, not content. Two objects with identical content but\n * different references will be considered \"changed\".\n *\n * For complex objects, either:\n * - Compare by a unique identifier (e.g., `value.id !== newValue?.id`)\n * - Use value objects with `.equals()` methods\n * - Implement deep equality checking in your update logic\n *\n * @typeParam T - The type of the field being compared\n * @param options - Comparison options\n * @param options.value - The current field value\n * @param options.newValue - The incoming value (may be undefined)\n * @param options.partialUpdate - Whether to use partial update semantics (default: true)\n * @returns `true` if the field has changed, `false` otherwise\n *\n * @example Partial update (PATCH semantics)\n * ```typescript\n * // undefined means \"don't change\"\n * fieldChanged({ value: 'John', newValue: undefined }); // false\n * fieldChanged({ value: 'John', newValue: 'Jane' }); // true\n * fieldChanged({ value: 'John', newValue: 'John' }); // false\n * ```\n *\n * @example Full update (PUT semantics)\n * ```typescript\n * // undefined means \"set to undefined\"\n * fieldChanged({ value: 'John', newValue: undefined, partialUpdate: false }); // true\n * ```\n *\n * @example Object comparison (reference-based)\n * ```typescript\n * const obj1 = { name: 'John' };\n * const obj2 = { name: 'John' };\n * fieldChanged({ value: obj1, newValue: obj2 }); // true (different references)\n * fieldChanged({ value: obj1, newValue: obj1 }); // false (same reference)\n * ```\n */\nexport function fieldChanged<T>({\n value,\n newValue,\n partialUpdate = true,\n}: {\n value: T;\n newValue: T | undefined;\n partialUpdate?: boolean;\n}): boolean {\n if (partialUpdate && newValue === undefined) return false;\n // For full updates, undefined means \"set to undefined\" which is a change if value !== undefined\n return value !== newValue;\n}\n","/**\n * Error wrapping utilities for boundary error handling.\n *\n * Provides functions to wrap code execution with error transformation,\n * converting caught errors into typed Error instances.\n * Useful at layer boundaries (infra, use case, controller) to normalize errors.\n *\n * @example Wrapping async database calls\n * ```typescript\n * const user = await wrapErrorAsync(\n * () => this.db.query('SELECT * FROM users WHERE id = ?', [id]),\n * (cause) => new DbError({ message: 'Failed to fetch user', cause }),\n * );\n * ```\n *\n * @example Wrapping sync operations\n * ```typescript\n * const parsed = wrapError(\n * () => JSON.parse(data),\n * (cause) => new InvariantViolationError({\n * message: 'Invalid JSON format',\n * cause,\n * }),\n * );\n * ```\n *\n * @module\n */\n\n/**\n * Factory function that creates an Error from a caught error.\n *\n * @typeParam E - The specific Error subclass to create\n * @param cause - The original caught error\n * @returns A new Error instance\n */\nexport type ErrorFactory<E extends Error> = (cause: unknown) => E;\n\n/**\n * Wraps a synchronous function with error transformation.\n *\n * Executes the provided function and catches any thrown errors,\n * transforming them using the error factory.\n *\n * @typeParam T - The return type of the wrapped function\n * @typeParam E - The Error subclass to throw on error\n * @param fn - The function to execute\n * @param errorFactory - Factory to create the typed error from the caught error\n * @returns The result of the function if successful\n * @throws {E} The transformed error if the function throws\n *\n * @example\n * ```typescript\n * const config = wrapError(\n * () => JSON.parse(configString),\n * (cause) => new InvariantViolationError({\n * message: 'Invalid configuration format',\n * code: 'CONFIG_PARSE_ERROR',\n * cause,\n * }),\n * );\n * ```\n */\nexport function wrapError<T, E extends Error>(fn: () => T, errorFactory: ErrorFactory<E>): T {\n try {\n return fn();\n } catch (error) {\n throw errorFactory(error);\n }\n}\n\n/**\n * Wraps an asynchronous function with error transformation.\n *\n * Executes the provided async function and catches any thrown errors,\n * transforming them using the error factory.\n *\n * @typeParam T - The return type of the wrapped function\n * @typeParam E - The Error subclass to throw on error\n * @param fn - The async function to execute\n * @param errorFactory - Factory to create the typed error from the caught error\n * @returns A promise resolving to the result if successful\n * @throws {E} The transformed error if the function throws\n *\n * @example Repository usage\n * ```typescript\n * async findById(id: string): Promise<User | null> {\n * return wrapErrorAsync(\n * () => this.db.users.findUnique({ where: { id } }),\n * (cause) => new DbError({\n * message: `Failed to find user by ID: ${id}`,\n * cause,\n * }),\n * );\n * }\n * ```\n *\n * @example External service usage\n * ```typescript\n * async sendEmail(to: string, body: string): Promise<void> {\n * await wrapErrorAsync(\n * () => this.emailClient.send({ to, body }),\n * (cause) => new ExternalServiceError({\n * message: 'Email delivery failed',\n * code: 'EMAIL_SEND_FAILED',\n * cause,\n * }),\n * );\n * }\n * ```\n */\nexport async function wrapErrorAsync<T, E extends Error>(\n fn: () => Promise<T>,\n errorFactory: ErrorFactory<E>,\n): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n throw errorFactory(error);\n }\n}\n\n/**\n * Constructor type for error classes (including abstract classes).\n *\n * Used to specify error types that should pass through without transformation.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ErrorConstructor = abstract new (...args: any[]) => Error;\n\n/**\n * Wraps a synchronous function with conditional error transformation.\n *\n * Executes the provided function and catches any thrown errors.\n * Errors matching any of the passthrough types are re-thrown as-is.\n * All other errors are transformed using the error factory.\n *\n * @typeParam T - The return type of the wrapped function\n * @typeParam E - The Error subclass to throw for unknown errors\n * @param fn - The function to execute\n * @param errorFactory - Factory to create the typed error from unknown errors\n * @param passthroughTypes - Array of error classes to re-throw without transformation\n * @returns The result of the function if successful\n * @throws The original error if it matches a passthrough type\n * @throws {E} The transformed error for unknown error types\n *\n * @example Controller boundary\n * ```typescript\n * const result = wrapErrorUnless(\n * () => this.requestMapper(input),\n * (cause) => new ControllerError({ message: 'Mapping failed', cause }),\n * [CodedError],\n * );\n * ```\n */\nexport function wrapErrorUnless<T, E extends Error>(\n fn: () => T,\n errorFactory: ErrorFactory<E>,\n passthroughTypes: ErrorConstructor[],\n): T {\n try {\n return fn();\n } catch (error) {\n if (passthroughTypes.some((Type) => error instanceof Type)) {\n throw error;\n }\n throw errorFactory(error);\n }\n}\n\n/**\n * Wraps an asynchronous function with conditional error transformation.\n *\n * Executes the provided async function and catches any thrown errors.\n * Errors matching any of the passthrough types are re-thrown as-is.\n * All other errors are transformed using the error factory.\n *\n * @typeParam T - The return type of the wrapped function\n * @typeParam E - The Error subclass to throw for unknown errors\n * @param fn - The async function to execute\n * @param errorFactory - Factory to create the typed error from unknown errors\n * @param passthroughTypes - Array of error classes to re-throw without transformation\n * @returns A promise resolving to the result if successful\n * @throws The original error if it matches a passthrough type\n * @throws {E} The transformed error for unknown error types\n *\n * @example Use case boundary\n * ```typescript\n * return wrapErrorUnlessAsync(\n * () => this.handle(input),\n * (cause) => new UseCaseError({ message: 'Unexpected error', cause }),\n * [ObjectValidationError, UseCaseError, DomainError, InfraError],\n * );\n * ```\n *\n * @example Controller boundary\n * ```typescript\n * return wrapErrorUnlessAsync(\n * async () => {\n * const result = await this.useCase.execute(input);\n * return this.responseMapper(result);\n * },\n * (cause) => new ControllerError({ message: 'Controller failed', cause }),\n * [CodedError],\n * );\n * ```\n */\nexport async function wrapErrorUnlessAsync<T, E extends Error>(\n fn: () => Promise<T>,\n errorFactory: ErrorFactory<E>,\n passthroughTypes: ErrorConstructor[],\n): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (passthroughTypes.some((Type) => error instanceof Type)) {\n throw error;\n }\n throw errorFactory(error);\n }\n}\n"],"mappings":"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","names":[]}
@@ -0,0 +1,294 @@
1
+ export { B as BaseDto, a as BoundValidator, O as ObjectValidatorPort, S as SKIP_DTO_VALIDATION, V as ValidateObject } from '../../base-dto.class-D7W9iqoU.cjs';
2
+ import { C as CodedError, V as ValidationError, G as GlobalErrorCode } from '../../validation-error.type-kD4_qNZ9.cjs';
3
+ export { A as AppErrorCode, D as DomainErrorCode, a as ErrorCode, E as ErrorCodes, I as InfraErrorCode, P as PresentationErrorCode } from '../../validation-error.type-kD4_qNZ9.cjs';
4
+
5
+ /**
6
+ * Error thrown when object validation fails.
7
+ *
8
+ * Contains structured validation errors with field paths and messages,
9
+ * making it easy to report specific validation failures to clients.
10
+ * Thrown by all validator implementations (Zod, ArkType, TypeBox, Valibot).
11
+ *
12
+ * **Flow:**
13
+ * 1. Validator throws `ObjectValidationError` with field-level errors
14
+ * 2. Controller catches and converts to {@link InvalidRequestError}
15
+ * 3. HTTP layer maps to 400 Bad Request with error details
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * try {
20
+ * const dto = CreateUserDto.create(invalidData);
21
+ * } catch (error) {
22
+ * if (error instanceof ObjectValidationError) {
23
+ * console.log(error.validationErrors);
24
+ * // [
25
+ * // { field: 'email', message: 'Invalid email format' },
26
+ * // { field: 'age', message: 'Must be a positive number' }
27
+ * // ]
28
+ * }
29
+ * }
30
+ * ```
31
+ */
32
+ declare class ObjectValidationError extends CodedError {
33
+ /**
34
+ * Array of field-level validation errors.
35
+ *
36
+ * Each entry contains:
37
+ * - `field`: Dot-notation path to the invalid field (e.g., 'user.email')
38
+ * - `message`: Human-readable validation failure message
39
+ */
40
+ validationErrors: ValidationError[];
41
+ /**
42
+ * Creates a new ObjectValidationError instance.
43
+ *
44
+ * @param options - Error configuration
45
+ * @param options.message - Human-readable summary message
46
+ * @param options.code - Machine-readable error code (default: 'OBJECT_VALIDATION_ERROR')
47
+ * @param options.cause - Optional underlying error from validation library
48
+ * @param options.validationErrors - Array of field-level validation errors
49
+ */
50
+ constructor({ message, code, cause, validationErrors, }: {
51
+ message: string;
52
+ code?: GlobalErrorCode | string;
53
+ cause?: unknown;
54
+ validationErrors: ValidationError[];
55
+ });
56
+ /**
57
+ * Creates an ObjectValidationError from a caught error.
58
+ *
59
+ * @param cause - The original caught error
60
+ * @returns A new ObjectValidationError instance with the cause attached
61
+ */
62
+ static fromError(cause: unknown): ObjectValidationError;
63
+ }
64
+
65
+ /**
66
+ * Checks if a field has changed by comparing the current value with a new value.
67
+ *
68
+ * Useful for detecting changes in update operations, supporting both partial
69
+ * and full update semantics.
70
+ *
71
+ * **Modes:**
72
+ * - **Partial update** (default): `undefined` means "keep existing value" (no change)
73
+ * - **Full update**: `undefined` means "set to undefined" (is a change if value !== undefined)
74
+ *
75
+ * **Limitation:** Uses strict equality (`!==`) for comparison, which only works
76
+ * correctly for primitives and reference equality. For objects or arrays, this
77
+ * compares references, not content. Two objects with identical content but
78
+ * different references will be considered "changed".
79
+ *
80
+ * For complex objects, either:
81
+ * - Compare by a unique identifier (e.g., `value.id !== newValue?.id`)
82
+ * - Use value objects with `.equals()` methods
83
+ * - Implement deep equality checking in your update logic
84
+ *
85
+ * @typeParam T - The type of the field being compared
86
+ * @param options - Comparison options
87
+ * @param options.value - The current field value
88
+ * @param options.newValue - The incoming value (may be undefined)
89
+ * @param options.partialUpdate - Whether to use partial update semantics (default: true)
90
+ * @returns `true` if the field has changed, `false` otherwise
91
+ *
92
+ * @example Partial update (PATCH semantics)
93
+ * ```typescript
94
+ * // undefined means "don't change"
95
+ * fieldChanged({ value: 'John', newValue: undefined }); // false
96
+ * fieldChanged({ value: 'John', newValue: 'Jane' }); // true
97
+ * fieldChanged({ value: 'John', newValue: 'John' }); // false
98
+ * ```
99
+ *
100
+ * @example Full update (PUT semantics)
101
+ * ```typescript
102
+ * // undefined means "set to undefined"
103
+ * fieldChanged({ value: 'John', newValue: undefined, partialUpdate: false }); // true
104
+ * ```
105
+ *
106
+ * @example Object comparison (reference-based)
107
+ * ```typescript
108
+ * const obj1 = { name: 'John' };
109
+ * const obj2 = { name: 'John' };
110
+ * fieldChanged({ value: obj1, newValue: obj2 }); // true (different references)
111
+ * fieldChanged({ value: obj1, newValue: obj1 }); // false (same reference)
112
+ * ```
113
+ */
114
+ declare function fieldChanged<T>({ value, newValue, partialUpdate, }: {
115
+ value: T;
116
+ newValue: T | undefined;
117
+ partialUpdate?: boolean;
118
+ }): boolean;
119
+
120
+ /**
121
+ * Error wrapping utilities for boundary error handling.
122
+ *
123
+ * Provides functions to wrap code execution with error transformation,
124
+ * converting caught errors into typed Error instances.
125
+ * Useful at layer boundaries (infra, use case, controller) to normalize errors.
126
+ *
127
+ * @example Wrapping async database calls
128
+ * ```typescript
129
+ * const user = await wrapErrorAsync(
130
+ * () => this.db.query('SELECT * FROM users WHERE id = ?', [id]),
131
+ * (cause) => new DbError({ message: 'Failed to fetch user', cause }),
132
+ * );
133
+ * ```
134
+ *
135
+ * @example Wrapping sync operations
136
+ * ```typescript
137
+ * const parsed = wrapError(
138
+ * () => JSON.parse(data),
139
+ * (cause) => new InvariantViolationError({
140
+ * message: 'Invalid JSON format',
141
+ * cause,
142
+ * }),
143
+ * );
144
+ * ```
145
+ *
146
+ * @module
147
+ */
148
+ /**
149
+ * Factory function that creates an Error from a caught error.
150
+ *
151
+ * @typeParam E - The specific Error subclass to create
152
+ * @param cause - The original caught error
153
+ * @returns A new Error instance
154
+ */
155
+ type ErrorFactory<E extends Error> = (cause: unknown) => E;
156
+ /**
157
+ * Wraps a synchronous function with error transformation.
158
+ *
159
+ * Executes the provided function and catches any thrown errors,
160
+ * transforming them using the error factory.
161
+ *
162
+ * @typeParam T - The return type of the wrapped function
163
+ * @typeParam E - The Error subclass to throw on error
164
+ * @param fn - The function to execute
165
+ * @param errorFactory - Factory to create the typed error from the caught error
166
+ * @returns The result of the function if successful
167
+ * @throws {E} The transformed error if the function throws
168
+ *
169
+ * @example
170
+ * ```typescript
171
+ * const config = wrapError(
172
+ * () => JSON.parse(configString),
173
+ * (cause) => new InvariantViolationError({
174
+ * message: 'Invalid configuration format',
175
+ * code: 'CONFIG_PARSE_ERROR',
176
+ * cause,
177
+ * }),
178
+ * );
179
+ * ```
180
+ */
181
+ declare function wrapError<T, E extends Error>(fn: () => T, errorFactory: ErrorFactory<E>): T;
182
+ /**
183
+ * Wraps an asynchronous function with error transformation.
184
+ *
185
+ * Executes the provided async function and catches any thrown errors,
186
+ * transforming them using the error factory.
187
+ *
188
+ * @typeParam T - The return type of the wrapped function
189
+ * @typeParam E - The Error subclass to throw on error
190
+ * @param fn - The async function to execute
191
+ * @param errorFactory - Factory to create the typed error from the caught error
192
+ * @returns A promise resolving to the result if successful
193
+ * @throws {E} The transformed error if the function throws
194
+ *
195
+ * @example Repository usage
196
+ * ```typescript
197
+ * async findById(id: string): Promise<User | null> {
198
+ * return wrapErrorAsync(
199
+ * () => this.db.users.findUnique({ where: { id } }),
200
+ * (cause) => new DbError({
201
+ * message: `Failed to find user by ID: ${id}`,
202
+ * cause,
203
+ * }),
204
+ * );
205
+ * }
206
+ * ```
207
+ *
208
+ * @example External service usage
209
+ * ```typescript
210
+ * async sendEmail(to: string, body: string): Promise<void> {
211
+ * await wrapErrorAsync(
212
+ * () => this.emailClient.send({ to, body }),
213
+ * (cause) => new ExternalServiceError({
214
+ * message: 'Email delivery failed',
215
+ * code: 'EMAIL_SEND_FAILED',
216
+ * cause,
217
+ * }),
218
+ * );
219
+ * }
220
+ * ```
221
+ */
222
+ declare function wrapErrorAsync<T, E extends Error>(fn: () => Promise<T>, errorFactory: ErrorFactory<E>): Promise<T>;
223
+ /**
224
+ * Constructor type for error classes (including abstract classes).
225
+ *
226
+ * Used to specify error types that should pass through without transformation.
227
+ */
228
+ type ErrorConstructor = abstract new (...args: any[]) => Error;
229
+ /**
230
+ * Wraps a synchronous function with conditional error transformation.
231
+ *
232
+ * Executes the provided function and catches any thrown errors.
233
+ * Errors matching any of the passthrough types are re-thrown as-is.
234
+ * All other errors are transformed using the error factory.
235
+ *
236
+ * @typeParam T - The return type of the wrapped function
237
+ * @typeParam E - The Error subclass to throw for unknown errors
238
+ * @param fn - The function to execute
239
+ * @param errorFactory - Factory to create the typed error from unknown errors
240
+ * @param passthroughTypes - Array of error classes to re-throw without transformation
241
+ * @returns The result of the function if successful
242
+ * @throws The original error if it matches a passthrough type
243
+ * @throws {E} The transformed error for unknown error types
244
+ *
245
+ * @example Controller boundary
246
+ * ```typescript
247
+ * const result = wrapErrorUnless(
248
+ * () => this.requestMapper(input),
249
+ * (cause) => new ControllerError({ message: 'Mapping failed', cause }),
250
+ * [CodedError],
251
+ * );
252
+ * ```
253
+ */
254
+ declare function wrapErrorUnless<T, E extends Error>(fn: () => T, errorFactory: ErrorFactory<E>, passthroughTypes: ErrorConstructor[]): T;
255
+ /**
256
+ * Wraps an asynchronous function with conditional error transformation.
257
+ *
258
+ * Executes the provided async function and catches any thrown errors.
259
+ * Errors matching any of the passthrough types are re-thrown as-is.
260
+ * All other errors are transformed using the error factory.
261
+ *
262
+ * @typeParam T - The return type of the wrapped function
263
+ * @typeParam E - The Error subclass to throw for unknown errors
264
+ * @param fn - The async function to execute
265
+ * @param errorFactory - Factory to create the typed error from unknown errors
266
+ * @param passthroughTypes - Array of error classes to re-throw without transformation
267
+ * @returns A promise resolving to the result if successful
268
+ * @throws The original error if it matches a passthrough type
269
+ * @throws {E} The transformed error for unknown error types
270
+ *
271
+ * @example Use case boundary
272
+ * ```typescript
273
+ * return wrapErrorUnlessAsync(
274
+ * () => this.handle(input),
275
+ * (cause) => new UseCaseError({ message: 'Unexpected error', cause }),
276
+ * [ObjectValidationError, UseCaseError, DomainError, InfraError],
277
+ * );
278
+ * ```
279
+ *
280
+ * @example Controller boundary
281
+ * ```typescript
282
+ * return wrapErrorUnlessAsync(
283
+ * async () => {
284
+ * const result = await this.useCase.execute(input);
285
+ * return this.responseMapper(result);
286
+ * },
287
+ * (cause) => new ControllerError({ message: 'Controller failed', cause }),
288
+ * [CodedError],
289
+ * );
290
+ * ```
291
+ */
292
+ declare function wrapErrorUnlessAsync<T, E extends Error>(fn: () => Promise<T>, errorFactory: ErrorFactory<E>, passthroughTypes: ErrorConstructor[]): Promise<T>;
293
+
294
+ export { CodedError, type ErrorConstructor, type ErrorFactory, GlobalErrorCode, ObjectValidationError, ValidationError, fieldChanged, wrapError, wrapErrorAsync, wrapErrorUnless, wrapErrorUnlessAsync };