@cosmneo/onion-lasagna 0.3.0 → 0.4.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 (74) hide show
  1. package/dist/{chunk-XWKHOLIP.js → chunk-4HMXTGHK.js} +2 -2
  2. package/dist/chunk-4RFWJ5XZ.js +192 -0
  3. package/dist/chunk-4RFWJ5XZ.js.map +1 -0
  4. package/dist/{chunk-4BVOLXDJ.js → chunk-4YBAV6LZ.js} +2 -2
  5. package/dist/chunk-ANLXZHUS.js +230 -0
  6. package/dist/chunk-ANLXZHUS.js.map +1 -0
  7. package/dist/chunk-BG2FY27M.js +36 -0
  8. package/dist/chunk-BG2FY27M.js.map +1 -0
  9. package/dist/chunk-FEY2GSVT.js +1 -0
  10. package/dist/chunk-FEY2GSVT.js.map +1 -0
  11. package/dist/{chunk-2BVCU32G.js → chunk-HNEAH6OZ.js} +121 -2
  12. package/dist/chunk-HNEAH6OZ.js.map +1 -0
  13. package/dist/chunk-NQMFWI6Q.js +1 -0
  14. package/dist/chunk-NQMFWI6Q.js.map +1 -0
  15. package/dist/chunk-TZRBETT3.js +127 -0
  16. package/dist/chunk-TZRBETT3.js.map +1 -0
  17. package/dist/{chunk-MF2JDREK.js → chunk-UNVB4INM.js} +1 -1
  18. package/dist/{chunk-MF2JDREK.js.map → chunk-UNVB4INM.js.map} +1 -1
  19. package/dist/chunk-VBG3UYQR.js +119 -0
  20. package/dist/chunk-VBG3UYQR.js.map +1 -0
  21. package/dist/events/index.js +3 -4
  22. package/dist/events/server/index.js +3 -4
  23. package/dist/events/shared/index.js +2 -3
  24. package/dist/graphql/field/index.cjs +189 -0
  25. package/dist/graphql/field/index.cjs.map +1 -0
  26. package/dist/graphql/field/index.d.cts +214 -0
  27. package/dist/graphql/field/index.d.ts +214 -0
  28. package/dist/graphql/field/index.js +25 -0
  29. package/dist/graphql/field/index.js.map +1 -0
  30. package/dist/graphql/index.cjs +1148 -0
  31. package/dist/graphql/index.cjs.map +1 -0
  32. package/dist/graphql/index.d.cts +8 -0
  33. package/dist/graphql/index.d.ts +8 -0
  34. package/dist/graphql/index.js +49 -0
  35. package/dist/graphql/index.js.map +1 -0
  36. package/dist/graphql/sdl/index.cjs +241 -0
  37. package/dist/graphql/sdl/index.cjs.map +1 -0
  38. package/dist/graphql/sdl/index.d.cts +77 -0
  39. package/dist/graphql/sdl/index.d.ts +77 -0
  40. package/dist/graphql/sdl/index.js +8 -0
  41. package/dist/graphql/sdl/index.js.map +1 -0
  42. package/dist/graphql/server/index.cjs +505 -0
  43. package/dist/graphql/server/index.cjs.map +1 -0
  44. package/dist/graphql/server/index.d.cts +268 -0
  45. package/dist/graphql/server/index.d.ts +268 -0
  46. package/dist/graphql/server/index.js +15 -0
  47. package/dist/graphql/server/index.js.map +1 -0
  48. package/dist/graphql/shared/index.cjs +586 -0
  49. package/dist/graphql/shared/index.cjs.map +1 -0
  50. package/dist/graphql/shared/index.d.cts +82 -0
  51. package/dist/graphql/shared/index.d.ts +82 -0
  52. package/dist/graphql/shared/index.js +16 -0
  53. package/dist/graphql/shared/index.js.map +1 -0
  54. package/dist/http/index.cjs.map +1 -1
  55. package/dist/http/index.js +2 -3
  56. package/dist/http/route/index.cjs.map +1 -1
  57. package/dist/http/route/index.d.cts +4 -0
  58. package/dist/http/route/index.d.ts +4 -0
  59. package/dist/http/route/index.js +1 -1
  60. package/dist/http/shared/index.js +1 -2
  61. package/dist/index.cjs +672 -0
  62. package/dist/index.cjs.map +1 -1
  63. package/dist/index.d.cts +8 -0
  64. package/dist/index.d.ts +8 -0
  65. package/dist/index.js +43 -1
  66. package/dist/index.js.map +1 -1
  67. package/dist/schema-definition.type-C9PntBVc.d.cts +166 -0
  68. package/dist/schema-definition.type-CuhQLDr0.d.ts +166 -0
  69. package/package.json +31 -1
  70. package/dist/chunk-2BVCU32G.js.map +0 -1
  71. package/dist/chunk-H5TNDC5U.js +0 -138
  72. package/dist/chunk-H5TNDC5U.js.map +0 -1
  73. /package/dist/{chunk-XWKHOLIP.js.map → chunk-4HMXTGHK.js.map} +0 -0
  74. /package/dist/{chunk-4BVOLXDJ.js.map → chunk-4YBAV6LZ.js.map} +0 -0
@@ -0,0 +1,166 @@
1
+ import { SchemaAdapter } from './http/schema/types.cjs';
2
+
3
+ /**
4
+ * @fileoverview Core GraphQL field definition types.
5
+ *
6
+ * A field definition captures all information needed for:
7
+ * - Type-safe resolver generation
8
+ * - Server-side schema registration with automatic validation
9
+ * - SDL generation (deferred)
10
+ *
11
+ * @module graphql/field/types/field-definition
12
+ */
13
+
14
+ /**
15
+ * GraphQL operation type.
16
+ */
17
+ type GraphQLOperationType = 'query' | 'mutation' | 'subscription';
18
+ /**
19
+ * GraphQL field documentation for SDL generation.
20
+ */
21
+ interface GraphQLFieldDocumentation {
22
+ /** Short summary of the field. */
23
+ readonly summary?: string;
24
+ /** Detailed description. Supports Markdown. */
25
+ readonly description?: string;
26
+ /** Tags for grouping fields. */
27
+ readonly tags?: readonly string[];
28
+ /** Whether this field is deprecated. @default false */
29
+ readonly deprecated?: boolean;
30
+ /** Deprecation reason (shown in SDL). */
31
+ readonly deprecationReason?: string;
32
+ }
33
+ /**
34
+ * A fully defined GraphQL field with computed types.
35
+ * This is the output of `defineQuery()` / `defineMutation()`.
36
+ */
37
+ interface GraphQLFieldDefinition<TOperation extends GraphQLOperationType = GraphQLOperationType, TInput = undefined, TOutput = undefined, TContext = undefined> {
38
+ /** GraphQL operation type ('query' or 'mutation'). */
39
+ readonly operation: TOperation;
40
+ /** Input arguments validation schema. */
41
+ readonly input: SchemaAdapter | undefined;
42
+ /** Output type validation schema. */
43
+ readonly output: SchemaAdapter | undefined;
44
+ /** Context validation schema. */
45
+ readonly context: SchemaAdapter | undefined;
46
+ /** Field documentation. */
47
+ readonly docs: GraphQLFieldDocumentation;
48
+ /**
49
+ * Marker to identify this as a GraphQL field definition.
50
+ * @internal
51
+ */
52
+ readonly _isGraphQLField: true;
53
+ /**
54
+ * Phantom types for TypeScript inference.
55
+ * Never accessed at runtime.
56
+ * @internal
57
+ */
58
+ readonly _types: {
59
+ readonly operation: TOperation;
60
+ readonly input: TInput;
61
+ readonly output: TOutput;
62
+ readonly context: TContext;
63
+ };
64
+ }
65
+ /** Infers the operation type from a field definition. */
66
+ type InferFieldOperation<T> = T extends GraphQLFieldDefinition<infer TOperation, unknown, unknown, unknown> ? TOperation : never;
67
+ /** Infers the input type from a field definition. */
68
+ type InferFieldInput<T> = T extends GraphQLFieldDefinition<GraphQLOperationType, infer TInput, unknown, unknown> ? TInput : never;
69
+ /** Infers the output type from a field definition. */
70
+ type InferFieldOutput<T> = T extends GraphQLFieldDefinition<GraphQLOperationType, unknown, infer TOutput, unknown> ? TOutput : never;
71
+ /** Infers the context type from a field definition. */
72
+ type InferFieldContext<T> = T extends GraphQLFieldDefinition<GraphQLOperationType, unknown, unknown, infer TContext> ? TContext : never;
73
+
74
+ /**
75
+ * @fileoverview GraphQL schema definition types for grouping fields.
76
+ *
77
+ * Mirrors the HTTP router definition pattern with hierarchical grouping,
78
+ * dotted-key access, and deep merge support.
79
+ *
80
+ * @module graphql/field/types/schema-definition
81
+ */
82
+
83
+ /**
84
+ * A schema entry can be a field definition, a nested config, or a schema definition.
85
+ */
86
+ type GraphQLSchemaEntry = GraphQLFieldDefinition<GraphQLOperationType, any, any, any> | GraphQLSchemaConfig | GraphQLSchemaDefinition;
87
+ /**
88
+ * Configuration for a GraphQL schema (group of fields).
89
+ */
90
+ interface GraphQLSchemaConfig {
91
+ readonly [key: string]: GraphQLSchemaEntry;
92
+ }
93
+ /**
94
+ * Schema-level defaults applied to all child fields.
95
+ */
96
+ interface GraphQLSchemaDefaults {
97
+ /** Default tags for all fields. Merged with field-specific tags. */
98
+ readonly tags?: readonly string[];
99
+ /** Default context schema. Applied to fields that don't define their own. */
100
+ readonly context?: SchemaAdapter;
101
+ }
102
+ /**
103
+ * A fully defined GraphQL schema.
104
+ */
105
+ interface GraphQLSchemaDefinition<T extends GraphQLSchemaConfig = GraphQLSchemaConfig> {
106
+ /** The fields and nested groups in this schema. */
107
+ readonly fields: T;
108
+ /** Default values applied to all child fields. */
109
+ readonly defaults?: GraphQLSchemaDefaults;
110
+ /**
111
+ * Marker to identify this as a GraphQL schema definition.
112
+ * @internal
113
+ */
114
+ readonly _isGraphQLSchema: true;
115
+ }
116
+ /**
117
+ * Checks if a value is a GraphQLFieldDefinition.
118
+ */
119
+ declare function isFieldDefinition(value: unknown): value is GraphQLFieldDefinition;
120
+ /**
121
+ * Checks if a value is a GraphQLSchemaDefinition.
122
+ */
123
+ declare function isSchemaDefinition(value: unknown): value is GraphQLSchemaDefinition;
124
+ /**
125
+ * Flattens a schema into a map of dotted keys to field definitions.
126
+ */
127
+ type FlattenSchema<T extends GraphQLSchemaConfig, Prefix extends string = ''> = T extends GraphQLSchemaConfig ? {
128
+ [K in keyof T]: T[K] extends GraphQLFieldDefinition<any, any, any, any> ? {
129
+ [P in `${Prefix}${K & string}`]: T[K];
130
+ } : T[K] extends GraphQLSchemaConfig ? FlattenSchema<T[K], `${Prefix}${K & string}.`> : never;
131
+ }[keyof T] extends infer U ? U extends Record<string, GraphQLFieldDefinition<any, any, any, any>> ? U : never : never : never;
132
+ /**
133
+ * Gets all field keys from a schema.
134
+ */
135
+ type SchemaKeys<T extends GraphQLSchemaConfig, Prefix extends string = ''> = T extends GraphQLSchemaConfig ? {
136
+ [K in keyof T]: T[K] extends GraphQLFieldDefinition<any, any, any, any> ? `${Prefix}${K & string}` : T[K] extends GraphQLSchemaConfig ? SchemaKeys<T[K], `${Prefix}${K & string}.`> : never;
137
+ }[keyof T] : never;
138
+ /**
139
+ * Gets a field by its dotted key path.
140
+ */
141
+ type GetField<T extends GraphQLSchemaConfig, K extends string> = K extends `${infer Head}.${infer Tail}` ? Head extends keyof T ? T[Head] extends GraphQLSchemaConfig ? GetField<T[Head], Tail> : never : never : K extends keyof T ? T[K] extends GraphQLFieldDefinition<any, any, any, any> ? T[K] : never : never;
142
+ /**
143
+ * Deep-merges two schema configs at the type level.
144
+ */
145
+ type DeepMergeSchemas<A extends GraphQLSchemaConfig, B extends GraphQLSchemaConfig> = {
146
+ readonly [K in keyof A | keyof B]: K extends keyof A ? K extends keyof B ? A[K] extends GraphQLSchemaConfig ? B[K] extends GraphQLSchemaConfig ? DeepMergeSchemas<A[K], B[K]> : B[K] : B[K] : A[K] : K extends keyof B ? B[K] : never;
147
+ };
148
+ /**
149
+ * Recursively deep-merges N schema configs left-to-right.
150
+ */
151
+ type DeepMergeSchemasAll<T extends readonly GraphQLSchemaConfig[]> = T extends readonly [
152
+ infer Only extends GraphQLSchemaConfig
153
+ ] ? Only : T extends readonly [
154
+ infer First extends GraphQLSchemaConfig,
155
+ infer Second extends GraphQLSchemaConfig,
156
+ ...infer Rest extends readonly GraphQLSchemaConfig[]
157
+ ] ? DeepMergeSchemasAll<[DeepMergeSchemas<First, Second>, ...Rest]> : GraphQLSchemaConfig;
158
+ /**
159
+ * Collects all fields from a schema into a flat array.
160
+ */
161
+ declare function collectFields(config: GraphQLSchemaConfig, basePath?: string): {
162
+ key: string;
163
+ field: GraphQLFieldDefinition;
164
+ }[];
165
+
166
+ export { type DeepMergeSchemas as D, type FlattenSchema as F, type GraphQLOperationType as G, type InferFieldOperation as I, type SchemaKeys as S, type GraphQLFieldDocumentation as a, type GraphQLFieldDefinition as b, type GraphQLSchemaEntry as c, type GraphQLSchemaConfig as d, type GraphQLSchemaDefaults as e, type GraphQLSchemaDefinition as f, type GetField as g, type DeepMergeSchemasAll as h, type InferFieldInput as i, type InferFieldOutput as j, type InferFieldContext as k, isFieldDefinition as l, isSchemaDefinition as m, collectFields as n };
@@ -0,0 +1,166 @@
1
+ import { SchemaAdapter } from './http/schema/types.js';
2
+
3
+ /**
4
+ * @fileoverview Core GraphQL field definition types.
5
+ *
6
+ * A field definition captures all information needed for:
7
+ * - Type-safe resolver generation
8
+ * - Server-side schema registration with automatic validation
9
+ * - SDL generation (deferred)
10
+ *
11
+ * @module graphql/field/types/field-definition
12
+ */
13
+
14
+ /**
15
+ * GraphQL operation type.
16
+ */
17
+ type GraphQLOperationType = 'query' | 'mutation' | 'subscription';
18
+ /**
19
+ * GraphQL field documentation for SDL generation.
20
+ */
21
+ interface GraphQLFieldDocumentation {
22
+ /** Short summary of the field. */
23
+ readonly summary?: string;
24
+ /** Detailed description. Supports Markdown. */
25
+ readonly description?: string;
26
+ /** Tags for grouping fields. */
27
+ readonly tags?: readonly string[];
28
+ /** Whether this field is deprecated. @default false */
29
+ readonly deprecated?: boolean;
30
+ /** Deprecation reason (shown in SDL). */
31
+ readonly deprecationReason?: string;
32
+ }
33
+ /**
34
+ * A fully defined GraphQL field with computed types.
35
+ * This is the output of `defineQuery()` / `defineMutation()`.
36
+ */
37
+ interface GraphQLFieldDefinition<TOperation extends GraphQLOperationType = GraphQLOperationType, TInput = undefined, TOutput = undefined, TContext = undefined> {
38
+ /** GraphQL operation type ('query' or 'mutation'). */
39
+ readonly operation: TOperation;
40
+ /** Input arguments validation schema. */
41
+ readonly input: SchemaAdapter | undefined;
42
+ /** Output type validation schema. */
43
+ readonly output: SchemaAdapter | undefined;
44
+ /** Context validation schema. */
45
+ readonly context: SchemaAdapter | undefined;
46
+ /** Field documentation. */
47
+ readonly docs: GraphQLFieldDocumentation;
48
+ /**
49
+ * Marker to identify this as a GraphQL field definition.
50
+ * @internal
51
+ */
52
+ readonly _isGraphQLField: true;
53
+ /**
54
+ * Phantom types for TypeScript inference.
55
+ * Never accessed at runtime.
56
+ * @internal
57
+ */
58
+ readonly _types: {
59
+ readonly operation: TOperation;
60
+ readonly input: TInput;
61
+ readonly output: TOutput;
62
+ readonly context: TContext;
63
+ };
64
+ }
65
+ /** Infers the operation type from a field definition. */
66
+ type InferFieldOperation<T> = T extends GraphQLFieldDefinition<infer TOperation, unknown, unknown, unknown> ? TOperation : never;
67
+ /** Infers the input type from a field definition. */
68
+ type InferFieldInput<T> = T extends GraphQLFieldDefinition<GraphQLOperationType, infer TInput, unknown, unknown> ? TInput : never;
69
+ /** Infers the output type from a field definition. */
70
+ type InferFieldOutput<T> = T extends GraphQLFieldDefinition<GraphQLOperationType, unknown, infer TOutput, unknown> ? TOutput : never;
71
+ /** Infers the context type from a field definition. */
72
+ type InferFieldContext<T> = T extends GraphQLFieldDefinition<GraphQLOperationType, unknown, unknown, infer TContext> ? TContext : never;
73
+
74
+ /**
75
+ * @fileoverview GraphQL schema definition types for grouping fields.
76
+ *
77
+ * Mirrors the HTTP router definition pattern with hierarchical grouping,
78
+ * dotted-key access, and deep merge support.
79
+ *
80
+ * @module graphql/field/types/schema-definition
81
+ */
82
+
83
+ /**
84
+ * A schema entry can be a field definition, a nested config, or a schema definition.
85
+ */
86
+ type GraphQLSchemaEntry = GraphQLFieldDefinition<GraphQLOperationType, any, any, any> | GraphQLSchemaConfig | GraphQLSchemaDefinition;
87
+ /**
88
+ * Configuration for a GraphQL schema (group of fields).
89
+ */
90
+ interface GraphQLSchemaConfig {
91
+ readonly [key: string]: GraphQLSchemaEntry;
92
+ }
93
+ /**
94
+ * Schema-level defaults applied to all child fields.
95
+ */
96
+ interface GraphQLSchemaDefaults {
97
+ /** Default tags for all fields. Merged with field-specific tags. */
98
+ readonly tags?: readonly string[];
99
+ /** Default context schema. Applied to fields that don't define their own. */
100
+ readonly context?: SchemaAdapter;
101
+ }
102
+ /**
103
+ * A fully defined GraphQL schema.
104
+ */
105
+ interface GraphQLSchemaDefinition<T extends GraphQLSchemaConfig = GraphQLSchemaConfig> {
106
+ /** The fields and nested groups in this schema. */
107
+ readonly fields: T;
108
+ /** Default values applied to all child fields. */
109
+ readonly defaults?: GraphQLSchemaDefaults;
110
+ /**
111
+ * Marker to identify this as a GraphQL schema definition.
112
+ * @internal
113
+ */
114
+ readonly _isGraphQLSchema: true;
115
+ }
116
+ /**
117
+ * Checks if a value is a GraphQLFieldDefinition.
118
+ */
119
+ declare function isFieldDefinition(value: unknown): value is GraphQLFieldDefinition;
120
+ /**
121
+ * Checks if a value is a GraphQLSchemaDefinition.
122
+ */
123
+ declare function isSchemaDefinition(value: unknown): value is GraphQLSchemaDefinition;
124
+ /**
125
+ * Flattens a schema into a map of dotted keys to field definitions.
126
+ */
127
+ type FlattenSchema<T extends GraphQLSchemaConfig, Prefix extends string = ''> = T extends GraphQLSchemaConfig ? {
128
+ [K in keyof T]: T[K] extends GraphQLFieldDefinition<any, any, any, any> ? {
129
+ [P in `${Prefix}${K & string}`]: T[K];
130
+ } : T[K] extends GraphQLSchemaConfig ? FlattenSchema<T[K], `${Prefix}${K & string}.`> : never;
131
+ }[keyof T] extends infer U ? U extends Record<string, GraphQLFieldDefinition<any, any, any, any>> ? U : never : never : never;
132
+ /**
133
+ * Gets all field keys from a schema.
134
+ */
135
+ type SchemaKeys<T extends GraphQLSchemaConfig, Prefix extends string = ''> = T extends GraphQLSchemaConfig ? {
136
+ [K in keyof T]: T[K] extends GraphQLFieldDefinition<any, any, any, any> ? `${Prefix}${K & string}` : T[K] extends GraphQLSchemaConfig ? SchemaKeys<T[K], `${Prefix}${K & string}.`> : never;
137
+ }[keyof T] : never;
138
+ /**
139
+ * Gets a field by its dotted key path.
140
+ */
141
+ type GetField<T extends GraphQLSchemaConfig, K extends string> = K extends `${infer Head}.${infer Tail}` ? Head extends keyof T ? T[Head] extends GraphQLSchemaConfig ? GetField<T[Head], Tail> : never : never : K extends keyof T ? T[K] extends GraphQLFieldDefinition<any, any, any, any> ? T[K] : never : never;
142
+ /**
143
+ * Deep-merges two schema configs at the type level.
144
+ */
145
+ type DeepMergeSchemas<A extends GraphQLSchemaConfig, B extends GraphQLSchemaConfig> = {
146
+ readonly [K in keyof A | keyof B]: K extends keyof A ? K extends keyof B ? A[K] extends GraphQLSchemaConfig ? B[K] extends GraphQLSchemaConfig ? DeepMergeSchemas<A[K], B[K]> : B[K] : B[K] : A[K] : K extends keyof B ? B[K] : never;
147
+ };
148
+ /**
149
+ * Recursively deep-merges N schema configs left-to-right.
150
+ */
151
+ type DeepMergeSchemasAll<T extends readonly GraphQLSchemaConfig[]> = T extends readonly [
152
+ infer Only extends GraphQLSchemaConfig
153
+ ] ? Only : T extends readonly [
154
+ infer First extends GraphQLSchemaConfig,
155
+ infer Second extends GraphQLSchemaConfig,
156
+ ...infer Rest extends readonly GraphQLSchemaConfig[]
157
+ ] ? DeepMergeSchemasAll<[DeepMergeSchemas<First, Second>, ...Rest]> : GraphQLSchemaConfig;
158
+ /**
159
+ * Collects all fields from a schema into a flat array.
160
+ */
161
+ declare function collectFields(config: GraphQLSchemaConfig, basePath?: string): {
162
+ key: string;
163
+ field: GraphQLFieldDefinition;
164
+ }[];
165
+
166
+ export { type DeepMergeSchemas as D, type FlattenSchema as F, type GraphQLOperationType as G, type InferFieldOperation as I, type SchemaKeys as S, type GraphQLFieldDocumentation as a, type GraphQLFieldDefinition as b, type GraphQLSchemaEntry as c, type GraphQLSchemaConfig as d, type GraphQLSchemaDefaults as e, type GraphQLSchemaDefinition as f, type GetField as g, type DeepMergeSchemasAll as h, type InferFieldInput as i, type InferFieldOutput as j, type InferFieldContext as k, isFieldDefinition as l, isSchemaDefinition as m, collectFields as n };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmneo/onion-lasagna",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Enterprise-grade TypeScript library for building backend applications with hexagonal/onion architecture",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -159,6 +159,36 @@
159
159
  "import": "./dist/events/asyncapi/index.js",
160
160
  "require": "./dist/events/asyncapi/index.cjs",
161
161
  "default": "./dist/events/asyncapi/index.js"
162
+ },
163
+ "./graphql": {
164
+ "types": "./dist/graphql/index.d.ts",
165
+ "import": "./dist/graphql/index.js",
166
+ "require": "./dist/graphql/index.cjs",
167
+ "default": "./dist/graphql/index.js"
168
+ },
169
+ "./graphql/field": {
170
+ "types": "./dist/graphql/field/index.d.ts",
171
+ "import": "./dist/graphql/field/index.js",
172
+ "require": "./dist/graphql/field/index.cjs",
173
+ "default": "./dist/graphql/field/index.js"
174
+ },
175
+ "./graphql/server": {
176
+ "types": "./dist/graphql/server/index.d.ts",
177
+ "import": "./dist/graphql/server/index.js",
178
+ "require": "./dist/graphql/server/index.cjs",
179
+ "default": "./dist/graphql/server/index.js"
180
+ },
181
+ "./graphql/shared": {
182
+ "types": "./dist/graphql/shared/index.d.ts",
183
+ "import": "./dist/graphql/shared/index.js",
184
+ "require": "./dist/graphql/shared/index.cjs",
185
+ "default": "./dist/graphql/shared/index.js"
186
+ },
187
+ "./graphql/sdl": {
188
+ "types": "./dist/graphql/sdl/index.d.ts",
189
+ "import": "./dist/graphql/sdl/index.js",
190
+ "require": "./dist/graphql/sdl/index.cjs",
191
+ "default": "./dist/graphql/sdl/index.js"
162
192
  }
163
193
  },
164
194
  "publishConfig": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/domain/exceptions/domain.error.ts","../src/infra/exceptions/infra.error.ts","../src/app/exceptions/not-found.error.ts","../src/app/exceptions/conflict.error.ts","../src/app/exceptions/unprocessable.error.ts","../src/app/exceptions/forbidden.error.ts","../src/presentation/exceptions/access-denied.error.ts"],"sourcesContent":["import { CodedError } from '../../global/exceptions/coded-error.error';\nimport { ErrorCodes, type DomainErrorCode } from '../../global/exceptions/error-codes.const';\n\n/**\n * Base error class for domain layer failures.\n *\n * Domain errors represent violations of business rules, invariants,\n * or aggregate consistency. They originate from the core domain logic\n * and should be caught and handled by the application layer.\n *\n * **When to throw:**\n * - Business rule violations (e.g., \"Cannot withdraw more than balance\")\n * - Invariant violations (e.g., \"Email format invalid\")\n * - Aggregate consistency failures\n *\n * **Child classes:**\n * - {@link InvariantViolationError} - Value object or entity invariant failures\n * - {@link PartialLoadError} - Incomplete aggregate reconstitution\n *\n * @example\n * ```typescript\n * if (account.balance < amount) {\n * throw new DomainError({\n * message: 'Insufficient funds for withdrawal',\n * code: 'INSUFFICIENT_FUNDS',\n * });\n * }\n * ```\n */\nexport class DomainError extends CodedError {\n /**\n * Creates a new DomainError instance.\n *\n * @param options - Error configuration\n * @param options.message - Human-readable error description\n * @param options.code - Machine-readable error code (default: 'DOMAIN_ERROR')\n * @param options.cause - Optional underlying error\n */\n constructor({\n message,\n code = ErrorCodes.Domain.DOMAIN_ERROR,\n cause,\n }: {\n message: string;\n code?: DomainErrorCode | string;\n cause?: unknown;\n }) {\n super({ message, code, cause });\n }\n\n /**\n * Creates a DomainError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new DomainError instance with the cause attached\n */\n static override fromError(cause: unknown): DomainError {\n return new DomainError({\n message: cause instanceof Error ? cause.message : 'Domain error',\n cause,\n });\n }\n}\n","import { CodedError } from '../../global/exceptions/coded-error.error';\nimport { ErrorCodes, type InfraErrorCode } from '../../global/exceptions/error-codes.const';\n\n/**\n * Base error class for infrastructure layer failures.\n *\n * Infrastructure errors represent failures in external dependencies\n * such as databases, network services, file systems, or third-party APIs.\n * They are automatically created by {@link BaseOutboundAdapter} when\n * repository or gateway methods fail.\n *\n * **When to throw:**\n * - Database connection or query failures\n * - Network timeouts or connection errors\n * - External API failures\n * - File system errors\n *\n * **Child classes:**\n * - {@link DbError} - Database operation failures\n * - {@link NetworkError} - Network connectivity issues\n * - {@link TimeoutError} - Operation timeout\n * - {@link ExternalServiceError} - Third-party service failures\n *\n * @example\n * ```typescript\n * // In a repository extending BaseOutboundAdapter\n * protected override createInfraError(error: unknown, methodName: string): InfraError {\n * return new DbError({\n * message: `Database error in ${methodName}`,\n * cause: error,\n * });\n * }\n * ```\n */\nexport class InfraError extends CodedError {\n /**\n * Creates a new InfraError instance.\n *\n * @param options - Error configuration\n * @param options.message - Human-readable error description\n * @param options.code - Machine-readable error code (default: 'INFRA_ERROR')\n * @param options.cause - Optional underlying error\n */\n constructor({\n message,\n code = ErrorCodes.Infra.INFRA_ERROR,\n cause,\n }: {\n message: string;\n code?: InfraErrorCode | string;\n cause?: unknown;\n }) {\n super({ message, code, cause });\n }\n\n /**\n * Creates an InfraError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new InfraError instance with the cause attached\n */\n static override fromError(cause: unknown): InfraError {\n return new InfraError({\n message: cause instanceof Error ? cause.message : 'Infrastructure error',\n cause,\n });\n }\n}\n","import { ErrorCodes, type AppErrorCode } from '../../global/exceptions/error-codes.const';\nimport { UseCaseError } from './use-case.error';\n\n/**\n * Error thrown when a requested resource does not exist.\n *\n * Indicates that the entity or resource referenced by the request\n * could not be found in the system.\n *\n * **When to throw:**\n * - Entity lookup by ID returns null\n * - Referenced resource doesn't exist\n * - Parent entity for a child operation not found\n *\n * @example\n * ```typescript\n * const user = await this.userRepo.findById(userId);\n * if (!user) {\n * throw new NotFoundError({\n * message: `User with ID ${userId} not found`,\n * code: 'USER_NOT_FOUND',\n * });\n * }\n * ```\n *\n * @extends UseCaseError\n */\nexport class NotFoundError extends UseCaseError {\n /**\n * Creates a new NotFoundError instance.\n *\n * @param options - Error configuration\n * @param options.message - Description of what was not found\n * @param options.code - Machine-readable error code (default: 'NOT_FOUND')\n * @param options.cause - Optional underlying error\n */\n constructor({\n message,\n code = ErrorCodes.App.NOT_FOUND,\n cause,\n }: {\n message: string;\n code?: AppErrorCode | string;\n cause?: unknown;\n }) {\n super({ message, code, cause });\n }\n\n /**\n * Creates a NotFoundError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new NotFoundError instance with the cause attached\n */\n static override fromError(cause: unknown): NotFoundError {\n return new NotFoundError({\n message: cause instanceof Error ? cause.message : 'Resource not found',\n cause,\n });\n }\n}\n","import { ErrorCodes, type AppErrorCode } from '../../global/exceptions/error-codes.const';\nimport { UseCaseError } from './use-case.error';\n\n/**\n * Error thrown when an operation conflicts with existing state.\n *\n * Indicates that the requested operation cannot be completed because\n * it would violate uniqueness constraints or cause state conflicts.\n *\n * **When to throw:**\n * - Duplicate unique field (e.g., email already registered)\n * - Optimistic locking conflict (stale version)\n * - Concurrent modification detected\n *\n * @example\n * ```typescript\n * const existing = await this.userRepo.findByEmail(email);\n * if (existing) {\n * throw new ConflictError({\n * message: 'Email already registered',\n * code: 'EMAIL_ALREADY_EXISTS',\n * });\n * }\n * ```\n *\n * @extends UseCaseError\n */\nexport class ConflictError extends UseCaseError {\n /**\n * Creates a new ConflictError instance.\n *\n * @param options - Error configuration\n * @param options.message - Description of the conflict\n * @param options.code - Machine-readable error code (default: 'CONFLICT')\n * @param options.cause - Optional underlying error\n */\n constructor({\n message,\n code = ErrorCodes.App.CONFLICT,\n cause,\n }: {\n message: string;\n code?: AppErrorCode | string;\n cause?: unknown;\n }) {\n super({ message, code, cause });\n }\n\n /**\n * Creates a ConflictError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new ConflictError instance with the cause attached\n */\n static override fromError(cause: unknown): ConflictError {\n return new ConflictError({\n message: cause instanceof Error ? cause.message : 'Conflict error',\n cause,\n });\n }\n}\n","import { ErrorCodes, type AppErrorCode } from '../../global/exceptions/error-codes.const';\nimport { UseCaseError } from './use-case.error';\n\n/**\n * Error thrown when a request is valid but cannot be processed.\n *\n * The request is syntactically correct and passes validation, but\n * business logic prevents the operation from being completed.\n *\n * **When to throw:**\n * - Business rule prevents operation (e.g., insufficient balance)\n * - Invalid state transition (e.g., canceling a completed order)\n * - Preconditions not met for the operation\n *\n * @example\n * ```typescript\n * if (account.balance < amount) {\n * throw new UnprocessableError({\n * message: 'Insufficient balance for withdrawal',\n * code: 'INSUFFICIENT_BALANCE',\n * });\n * }\n * ```\n *\n * @extends UseCaseError\n */\nexport class UnprocessableError extends UseCaseError {\n /**\n * Creates a new UnprocessableError instance.\n *\n * @param options - Error configuration\n * @param options.message - Description of why the request cannot be processed\n * @param options.code - Machine-readable error code (default: 'UNPROCESSABLE')\n * @param options.cause - Optional underlying error\n */\n constructor({\n message,\n code = ErrorCodes.App.UNPROCESSABLE,\n cause,\n }: {\n message: string;\n code?: AppErrorCode | string;\n cause?: unknown;\n }) {\n super({ message, code, cause });\n }\n\n /**\n * Creates an UnprocessableError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new UnprocessableError instance with the cause attached\n */\n static override fromError(cause: unknown): UnprocessableError {\n return new UnprocessableError({\n message: cause instanceof Error ? cause.message : 'Unprocessable request',\n cause,\n });\n }\n}\n","import { ErrorCodes, type AppErrorCode } from '../../global/exceptions/error-codes.const';\nimport { UseCaseError } from './use-case.error';\n\n/**\n * Error thrown when authorization for an operation is denied.\n *\n * Indicates that the user is authenticated but lacks permission to perform\n * the requested operation. Commonly thrown from the `authorize()` method\n * of use cases when access checks fail.\n *\n * **When to throw:**\n * - User doesn't own the resource they're trying to modify\n * - User lacks required role or permission\n * - Organization/tenant isolation violation\n * - Business rule restricts the operation for this user\n *\n * **Difference from AccessDeniedError:**\n * - `ForbiddenError` is an application layer error (use case authorization)\n * - `AccessDeniedError` is a presentation layer error (controller/guard level)\n *\n * @example Use case authorization\n * ```typescript\n * class UpdateActivityUseCase extends BaseInboundAdapter<Input, Output, AuthContext> {\n * protected async authorize(input: Input): Promise<AuthContext> {\n * const activity = await this.activityRepo.findById(input.activityId);\n * if (!activity) {\n * throw new NotFoundError({ message: 'Activity not found' });\n * }\n * if (activity.organizationId !== input.organizationId) {\n * throw new ForbiddenError({\n * message: 'Not authorized to modify this activity',\n * code: 'ACTIVITY_ACCESS_DENIED',\n * });\n * }\n * return { activity };\n * }\n * }\n * ```\n *\n * @example Role-based authorization\n * ```typescript\n * if (!user.roles.includes('admin')) {\n * throw new ForbiddenError({\n * message: 'Admin role required for this operation',\n * });\n * }\n * ```\n *\n * @extends UseCaseError\n */\nexport class ForbiddenError extends UseCaseError {\n /**\n * Creates a new ForbiddenError instance.\n *\n * @param options - Error configuration\n * @param options.message - Description of why authorization was denied\n * @param options.code - Machine-readable error code (default: 'FORBIDDEN')\n * @param options.cause - Optional underlying error\n */\n constructor({\n message,\n code = ErrorCodes.App.FORBIDDEN,\n cause,\n }: {\n message: string;\n code?: AppErrorCode | string;\n cause?: unknown;\n }) {\n super({ message, code, cause });\n }\n\n /**\n * Creates a ForbiddenError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new ForbiddenError instance with the cause attached\n */\n static override fromError(cause: unknown): ForbiddenError {\n return new ForbiddenError({\n message: cause instanceof Error ? cause.message : 'Operation forbidden',\n cause,\n });\n }\n}\n","import { CodedError } from '../../global/exceptions/coded-error.error';\nimport { ErrorCodes, type PresentationErrorCode } from '../../global/exceptions/error-codes.const';\n\n/**\n * Error thrown when access to a resource is denied.\n *\n * Indicates that the requester does not have permission to perform\n * the requested operation. Thrown by {@link GuardedController} when\n * an access guard returns `isAllowed: false`.\n *\n * **When thrown:**\n * - Access guard denies the request\n * - User lacks required permissions\n * - Resource ownership check fails\n *\n * @example GuardedController usage\n * ```typescript\n * const controller = GuardedController.create({\n * accessGuard: (req) => ({\n * isAllowed: req.user?.role === 'admin',\n * reason: 'Admin access required',\n * }),\n * // ... other config\n * });\n * ```\n *\n * @example Manual usage\n * ```typescript\n * if (!user.canAccess(resource)) {\n * throw new AccessDeniedError({\n * message: 'You do not have access to this resource',\n * code: 'RESOURCE_ACCESS_DENIED',\n * });\n * }\n * ```\n *\n * @extends CodedError\n */\nexport class AccessDeniedError extends CodedError {\n /**\n * Creates a new AccessDeniedError instance.\n *\n * @param options - Error configuration\n * @param options.message - Description of why access was denied\n * @param options.code - Machine-readable error code (default: 'ACCESS_DENIED')\n * @param options.cause - Optional underlying error\n */\n constructor({\n message,\n code = ErrorCodes.Presentation.ACCESS_DENIED,\n cause,\n }: {\n message: string;\n code?: PresentationErrorCode | string;\n cause?: unknown;\n }) {\n super({ message, code, cause });\n }\n\n /**\n * Creates an AccessDeniedError from a caught error.\n *\n * @param cause - The original caught error\n * @returns A new AccessDeniedError instance with the cause attached\n */\n static override fromError(cause: unknown): AccessDeniedError {\n return new AccessDeniedError({\n message: cause instanceof Error ? cause.message : 'Access denied',\n cause,\n });\n }\n}\n"],"mappings":";;;;;;;;;AA6BO,IAAM,cAAN,MAAM,qBAAoB,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAShD,YAAY;AAAA,IACV;AAAA,IACA,OAAO,WAAW,aAAa;AAAA,IAC/B;AAAA,EACF,GAIG;AACD,UAAM,EAAE,SAAS,MAAM,MAAM,CAAC;AAAA,EAChC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAgB,UAAU,OAAmC;AAC3D,WAAO,IAAI,mBAAkB;AAAA,MAC3B,SAAS,iBAAiB,QAAQ,MAAM,UAAU;AAAA,MAClD;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":[]}
@@ -1,138 +0,0 @@
1
- import {
2
- AccessDeniedError,
3
- ConflictError,
4
- DomainError,
5
- ForbiddenError,
6
- InfraError,
7
- NotFoundError,
8
- UnprocessableError
9
- } from "./chunk-2BVCU32G.js";
10
- import {
11
- ControllerError,
12
- InvalidRequestError,
13
- UnauthorizedError,
14
- UseCaseError
15
- } from "./chunk-T7S574XQ.js";
16
- import {
17
- ObjectValidationError
18
- } from "./chunk-3BY5RBF2.js";
19
- import {
20
- CodedError
21
- } from "./chunk-A4JUAZK4.js";
22
-
23
- // src/presentation/http/shared/error-mapping.ts
24
- var MASKED_ERROR_BODY = {
25
- message: "An unexpected error occurred",
26
- errorCode: "INTERNAL_ERROR"
27
- };
28
- var INTERNAL_ERROR_TYPES = [
29
- "DomainError",
30
- "InfraError",
31
- "ControllerError",
32
- "NetworkError",
33
- "PersistenceError",
34
- "ExternalServiceError",
35
- "InvariantViolationError"
36
- ];
37
- function isErrorType(error, typeName) {
38
- if (!error || typeof error !== "object") return false;
39
- const constructor = Object.prototype.hasOwnProperty.call(error, "constructor") ? error.constructor : Object.getPrototypeOf(error)?.constructor;
40
- if (!constructor) return false;
41
- const name = constructor.name;
42
- return name === typeName || name === `_${typeName}`;
43
- }
44
- function hasValidationErrors(error) {
45
- if (!error || typeof error !== "object") return false;
46
- return "validationErrors" in error && Array.isArray(error.validationErrors);
47
- }
48
- function buildValidationErrorBody(message, code, validationErrors) {
49
- return {
50
- message,
51
- errorCode: code,
52
- errorItems: validationErrors.map((e) => ({
53
- item: e.field,
54
- message: e.message
55
- }))
56
- };
57
- }
58
- function buildSimpleErrorBody(message, code) {
59
- return {
60
- message,
61
- errorCode: code
62
- };
63
- }
64
- function getHttpStatusCode(error) {
65
- if (error instanceof ObjectValidationError) return 400;
66
- if (error instanceof InvalidRequestError) return 400;
67
- if (error instanceof UnauthorizedError) return 401;
68
- if (error instanceof ForbiddenError) return 403;
69
- if (error instanceof AccessDeniedError) return 403;
70
- if (error instanceof NotFoundError) return 404;
71
- if (error instanceof ConflictError) return 409;
72
- if (error instanceof UnprocessableError) return 422;
73
- if (error instanceof UseCaseError) return 400;
74
- if (isErrorType(error, "ObjectValidationError")) return 400;
75
- if (isErrorType(error, "InvalidRequestError")) return 400;
76
- if (isErrorType(error, "UnauthorizedError")) return 401;
77
- if (isErrorType(error, "ForbiddenError")) return 403;
78
- if (isErrorType(error, "AccessDeniedError")) return 403;
79
- if (isErrorType(error, "NotFoundError")) return 404;
80
- if (isErrorType(error, "ConflictError")) return 409;
81
- if (isErrorType(error, "UnprocessableError")) return 422;
82
- if (isErrorType(error, "UseCaseError")) return 400;
83
- return 500;
84
- }
85
- function shouldMaskError(error) {
86
- if (error instanceof DomainError || error instanceof InfraError || error instanceof ControllerError) {
87
- return true;
88
- }
89
- for (const errorType of INTERNAL_ERROR_TYPES) {
90
- if (isErrorType(error, errorType)) {
91
- return true;
92
- }
93
- }
94
- return false;
95
- }
96
- function createErrorResponseBody(error) {
97
- if (shouldMaskError(error)) {
98
- return MASKED_ERROR_BODY;
99
- }
100
- if (error instanceof ObjectValidationError) {
101
- return buildValidationErrorBody(error.message, error.code, error.validationErrors);
102
- }
103
- if (error instanceof InvalidRequestError) {
104
- return buildValidationErrorBody(error.message, error.code, error.validationErrors);
105
- }
106
- if (isErrorType(error, "ObjectValidationError") && hasValidationErrors(error)) {
107
- return buildValidationErrorBody(error.message, error.code, error.validationErrors);
108
- }
109
- if (isErrorType(error, "InvalidRequestError") && hasValidationErrors(error)) {
110
- return buildValidationErrorBody(error.message, error.code, error.validationErrors);
111
- }
112
- if (error instanceof CodedError) {
113
- return buildSimpleErrorBody(error.message, error.code);
114
- }
115
- if (isErrorType(error, "CodedError")) {
116
- return buildSimpleErrorBody(error.message, error.code);
117
- }
118
- if (error && typeof error === "object" && "message" in error && "code" in error && typeof error.message === "string" && typeof error.code === "string") {
119
- return buildSimpleErrorBody(error.message, error.code);
120
- }
121
- return MASKED_ERROR_BODY;
122
- }
123
- function mapErrorToHttpResponse(error) {
124
- return {
125
- status: getHttpStatusCode(error),
126
- body: createErrorResponseBody(error)
127
- };
128
- }
129
-
130
- export {
131
- isErrorType,
132
- hasValidationErrors,
133
- getHttpStatusCode,
134
- shouldMaskError,
135
- createErrorResponseBody,
136
- mapErrorToHttpResponse
137
- };
138
- //# sourceMappingURL=chunk-H5TNDC5U.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/presentation/http/shared/error-mapping.ts"],"sourcesContent":["/**\n * @fileoverview Centralized error mapping for HTTP frameworks.\n *\n * Provides a single source of truth for mapping onion-lasagna errors\n * to HTTP status codes and response bodies.\n *\n * @module http/shared/error-mapping\n */\n\nimport { CodedError } from '../../../global/exceptions/coded-error.error';\nimport { ObjectValidationError } from '../../../global/exceptions/object-validation.error';\nimport { DomainError } from '../../../domain/exceptions/domain.error';\nimport { UseCaseError } from '../../../app/exceptions/use-case.error';\nimport { NotFoundError } from '../../../app/exceptions/not-found.error';\nimport { ConflictError } from '../../../app/exceptions/conflict.error';\nimport { UnprocessableError } from '../../../app/exceptions/unprocessable.error';\nimport { ForbiddenError } from '../../../app/exceptions/forbidden.error';\nimport { UnauthorizedError } from '../../../app/exceptions/unauthorized.error';\nimport { InfraError } from '../../../infra/exceptions/infra.error';\nimport { ControllerError } from '../../exceptions/controller.error';\nimport { AccessDeniedError } from '../../exceptions/access-denied.error';\nimport { InvalidRequestError } from '../../exceptions/invalid-request.error';\nimport type { ErrorResponseBody, MappedErrorResponse } from './types';\n\n// ============================================================================\n// Constants and Interfaces\n// ============================================================================\n\n/**\n * Default masked error response for internal errors.\n */\nconst MASKED_ERROR_BODY: ErrorResponseBody = {\n message: 'An unexpected error occurred',\n errorCode: 'INTERNAL_ERROR',\n};\n\n/**\n * Known internal error type names that should be masked.\n */\nconst INTERNAL_ERROR_TYPES = [\n 'DomainError',\n 'InfraError',\n 'ControllerError',\n 'NetworkError',\n 'PersistenceError',\n 'ExternalServiceError',\n 'InvariantViolationError',\n];\n\n/**\n * Validation error item structure.\n */\ninterface ValidationErrorInput {\n field: string;\n message: string;\n}\n\n/**\n * Validation error structure for string-based checking.\n */\ninterface ValidationErrorItem {\n field: string;\n message: string;\n}\n\n/**\n * Interface for errors with validation items.\n */\ninterface ErrorWithValidation {\n message: string;\n code: string;\n validationErrors: ValidationErrorItem[];\n}\n\n/**\n * Interface for coded errors.\n */\ninterface CodedErrorLike {\n message: string;\n code: string;\n}\n\n// ============================================================================\n// String-based type checking helpers (for bundled code compatibility)\n// ============================================================================\n\n/**\n * Checks if error matches a specific error type by checking its constructor name.\n * This approach avoids issues with multiple class instances in bundled code.\n * Handles both original names and tsup's mangled names (prefixed with _).\n *\n * @param error - The error to check\n * @param typeName - The error type name to match\n * @returns True if error matches the type name\n */\nexport function isErrorType(error: unknown, typeName: string): error is CodedErrorLike {\n if (!error || typeof error !== 'object') return false;\n // Guard against objects without constructor (e.g., Object.create(null))\n const constructor = Object.prototype.hasOwnProperty.call(error, 'constructor')\n ? (error as { constructor?: { name?: string } }).constructor\n : Object.getPrototypeOf(error)?.constructor;\n if (!constructor) return false;\n const name = constructor.name;\n // Check both the original name and the mangled name (tsup prefixes with _)\n return name === typeName || name === `_${typeName}`;\n}\n\n/**\n * Checks if error has validation errors array.\n *\n * @param error - The error to check\n * @returns True if error has validationErrors property\n */\nexport function hasValidationErrors(error: unknown): error is ErrorWithValidation {\n if (!error || typeof error !== 'object') return false;\n return (\n 'validationErrors' in error && Array.isArray((error as ErrorWithValidation).validationErrors)\n );\n}\n\n// ============================================================================\n// Response body builders\n// ============================================================================\n\n/**\n * Builds a validation error response body from error details.\n *\n * @param message - The error message\n * @param code - The error code\n * @param validationErrors - Array of field validation errors\n * @returns Error response body with errorItems\n */\nfunction buildValidationErrorBody(\n message: string,\n code: string,\n validationErrors: readonly ValidationErrorInput[],\n): ErrorResponseBody {\n return {\n message,\n errorCode: code,\n errorItems: validationErrors.map((e) => ({\n item: e.field,\n message: e.message,\n })),\n };\n}\n\n/**\n * Builds a simple error response body from error details.\n *\n * @param message - The error message\n * @param code - The error code\n * @returns Error response body\n */\nfunction buildSimpleErrorBody(message: string, code: string): ErrorResponseBody {\n return {\n message,\n errorCode: code,\n };\n}\n\n// ============================================================================\n// Primary error mapping functions (with bundled code fallback)\n// ============================================================================\n\n/**\n * Maps an error to the appropriate HTTP status code.\n * Uses instanceof first, then falls back to name-based checking for bundled code.\n *\n * @param error - The error to map\n * @returns HTTP status code\n */\nexport function getHttpStatusCode(error: unknown): number {\n // Try instanceof first (faster)\n if (error instanceof ObjectValidationError) return 400;\n if (error instanceof InvalidRequestError) return 400;\n if (error instanceof UnauthorizedError) return 401;\n if (error instanceof ForbiddenError) return 403;\n if (error instanceof AccessDeniedError) return 403;\n if (error instanceof NotFoundError) return 404;\n if (error instanceof ConflictError) return 409;\n if (error instanceof UnprocessableError) return 422;\n if (error instanceof UseCaseError) return 400;\n\n // Fall back to name-based checking for bundled code (e.g., _NotFoundError)\n if (isErrorType(error, 'ObjectValidationError')) return 400;\n if (isErrorType(error, 'InvalidRequestError')) return 400;\n if (isErrorType(error, 'UnauthorizedError')) return 401;\n if (isErrorType(error, 'ForbiddenError')) return 403;\n if (isErrorType(error, 'AccessDeniedError')) return 403;\n if (isErrorType(error, 'NotFoundError')) return 404;\n if (isErrorType(error, 'ConflictError')) return 409;\n if (isErrorType(error, 'UnprocessableError')) return 422;\n if (isErrorType(error, 'UseCaseError')) return 400;\n\n return 500;\n}\n\n/**\n * Checks if an error should have its details masked in the response.\n *\n * Security-sensitive errors (domain, infrastructure, controller) are masked\n * to prevent leaking implementation details.\n * Uses instanceof first, then falls back to name-based checking for bundled code.\n *\n * @param error - The error to check\n * @returns True if error details should be hidden\n */\nexport function shouldMaskError(error: unknown): boolean {\n // Try instanceof first (faster)\n if (\n error instanceof DomainError ||\n error instanceof InfraError ||\n error instanceof ControllerError\n ) {\n return true;\n }\n\n // Fall back to name-based checking for bundled code\n for (const errorType of INTERNAL_ERROR_TYPES) {\n if (isErrorType(error, errorType)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Creates the response body for an error.\n * Uses instanceof first, then falls back to name-based checking for bundled code.\n *\n * @param error - The error to create body for\n * @returns Error response body\n */\nexport function createErrorResponseBody(error: unknown): ErrorResponseBody {\n // Masked errors - hide internal details\n if (shouldMaskError(error)) {\n return MASKED_ERROR_BODY;\n }\n\n // Validation errors - include field details (try instanceof first)\n if (error instanceof ObjectValidationError) {\n return buildValidationErrorBody(error.message, error.code, error.validationErrors);\n }\n if (error instanceof InvalidRequestError) {\n return buildValidationErrorBody(error.message, error.code, error.validationErrors);\n }\n\n // Validation errors - fall back to name-based checking for bundled code\n if (isErrorType(error, 'ObjectValidationError') && hasValidationErrors(error)) {\n return buildValidationErrorBody(error.message, error.code, error.validationErrors);\n }\n if (isErrorType(error, 'InvalidRequestError') && hasValidationErrors(error)) {\n return buildValidationErrorBody(error.message, error.code, error.validationErrors);\n }\n\n // Other coded errors - expose message and code (try instanceof first)\n if (error instanceof CodedError) {\n return buildSimpleErrorBody(error.message, error.code);\n }\n\n // Other coded errors - fall back to name-based checking\n if (isErrorType(error, 'CodedError')) {\n return buildSimpleErrorBody(error.message, error.code);\n }\n\n // Check for any error with message and code properties\n if (\n error &&\n typeof error === 'object' &&\n 'message' in error &&\n 'code' in error &&\n typeof (error as CodedErrorLike).message === 'string' &&\n typeof (error as CodedErrorLike).code === 'string'\n ) {\n return buildSimpleErrorBody((error as CodedErrorLike).message, (error as CodedErrorLike).code);\n }\n\n // Unknown errors - mask\n return MASKED_ERROR_BODY;\n}\n\n/**\n * Maps an error to a complete HTTP response structure.\n *\n * Mapping strategy (checked in order):\n * 1. `ObjectValidationError` / `InvalidRequestError` → 400 Bad Request (with field errors)\n * 2. `UseCaseError` → 400 Bad Request\n * 3. `UnauthorizedError` → 401 Unauthorized\n * 4. `ForbiddenError` / `AccessDeniedError` → 403 Forbidden\n * 5. `NotFoundError` → 404 Not Found\n * 6. `ConflictError` → 409 Conflict\n * 7. `UnprocessableError` → 422 Unprocessable Entity\n * 8. `DomainError` / `InfraError` / `ControllerError` → 500 Internal Server Error (masked)\n * 9. Unknown → 500 Internal Server Error (masked)\n *\n * @param error - The error to map\n * @returns Mapped error response with status and body\n */\nexport function mapErrorToHttpResponse(error: unknown): MappedErrorResponse {\n return {\n status: getHttpStatusCode(error),\n body: createErrorResponseBody(error),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAM,oBAAuC;AAAA,EAC3C,SAAS;AAAA,EACT,WAAW;AACb;AAKA,IAAM,uBAAuB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAgDO,SAAS,YAAY,OAAgB,UAA2C;AACrF,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAEhD,QAAM,cAAc,OAAO,UAAU,eAAe,KAAK,OAAO,aAAa,IACxE,MAA8C,cAC/C,OAAO,eAAe,KAAK,GAAG;AAClC,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,OAAO,YAAY;AAEzB,SAAO,SAAS,YAAY,SAAS,IAAI,QAAQ;AACnD;AAQO,SAAS,oBAAoB,OAA8C;AAChF,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,SACE,sBAAsB,SAAS,MAAM,QAAS,MAA8B,gBAAgB;AAEhG;AAcA,SAAS,yBACP,SACA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