@hexafy/core 1.0.0-rc.5 → 1.0.0-rc.6

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 (2) hide show
  1. package/README.md +318 -109
  2. package/package.json +3 -3
package/README.md CHANGED
@@ -6,145 +6,359 @@ Core hexagonal architecture primitives for TypeScript: use cases, domain buildin
6
6
 
7
7
  `@hexafy/core` is the foundation of the Hexafy package family. It keeps business logic framework-agnostic and provides:
8
8
 
9
- - Application orchestration (`Usecase`, `ServiceBase`)
10
- - Use-case outcome contract (`UsecaseResult`)
11
- - Domain errors and primitives (`ApplicationError`, `Entity`, `AggregateRoot`, `ValueObject`)
9
+ - Application orchestration (`UseCase`, `ServiceBase`)
10
+ - Use-case outcome contract (`UseCaseResult`)
11
+ - Domain errors and primitives (`ApplicationError`, `Entity`, `AggregateRoot`, `ValueObject`, `RepositoryBase`, `Brand`, `ErrorCodes`)
12
+ - Domain error helpers (`isDomainError`, `getDomainErrorCode`)
13
+ - Transaction boundaries (`UnitOfWorkBase`)
12
14
  - Cross-cutting ports and default adapters (logging, metrics, clock, identifier)
13
15
 
14
- ## Architecture overview
15
-
16
- This package implements [hexagonal (ports-and-adapters) architecture](https://alistair.cockburn.us/hexagonal-architecture/) to keep your business logic independent of frameworks, databases, and external services.
17
-
18
- ### Benefits
19
-
20
- ```
21
- ┌─────────────────────────────────────────────────────────────────────┐
22
- │ Frameworks / Databases / External │
23
- │ (can change freely) │
24
- └─────────────────────────────────────────────────────────────────────┘
25
- │
26
- │ implements
27
- ▼
28
- ┌─────────────────────────────────────────────────────────────────────┐
29
- │ Application Layer │
30
- │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
31
- │ │ Usecase │ │ Service │ │ Ports │ │
32
- │ │ Base │ │ Base │ │ (interfaces)│ │
33
- │ └──────────────┘ └──────────────┘ └──────────────┘ │
34
- └─────────────────────┬───────────────────────────────────────────────┘
35
- │ depends on
36
- │
37
- ┌─────────────────────▼───────────────────────────────────────────────┐
38
- │ Domain Layer │
39
- │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
40
- │ │ Entity │ │ Repository │ │ Errors │ │
41
- │ │ primitives │ │ Ports │ │ (typed) │ │
42
- │ └──────────────┘ └──────────────┘ └──────────────┘ │
43
- │ ◄───── CORE ─────► │
44
- └─────────────────────────────────────────────────────────────────────┘
45
-
46
- Key benefits:
47
- • Domain logic is framework-agnostic and easily testable
48
- • Swap infrastructure (database, email provider, etc.) without touching business rules
49
- • Clear boundaries: ports define contracts, adapters implement them
50
- ```
51
-
52
- **Rule:** Dependencies flow inward. Infrastructure depends on Application (implements ports), Application depends on Domain (uses primitives). Domain has no dependencies.
53
-
54
16
  ## Installation
55
17
 
56
18
  ```bash
57
19
  npm install @hexafy/core
58
- # or
59
- bun add @hexafy/core
60
- # or
61
- yarn add @hexafy/core
62
20
  ```
63
21
 
64
- ## Quick start
22
+ ## Core Concepts
23
+
24
+ ### UseCase - Lifecycle & Execution
25
+
26
+ Use cases define single-responsibility business operations with built-in lifecycle management, timeouts, and cancellation.
65
27
 
66
28
  ```ts
67
29
  import {
68
30
  type LoggingPort,
69
- Usecase,
70
- type UsecaseConfiguration
31
+ UseCase,
32
+ type UseCaseConfiguration
71
33
  } from '@hexafy/core/application';
72
- import { ValidationError } from '@hexafy/core/domain';
34
+ import {
35
+ RepositoryBase,
36
+ type RepositoryPort,
37
+ type UniqueIdentifier,
38
+ ValidationError
39
+ } from '@hexafy/core/domain';
40
+ import { ConsoleLoggingAdapter } from '@hexafy/core/infrastructure';
73
41
 
74
- interface CreateUserInput {
42
+ interface User {
43
+ id: UniqueIdentifier;
75
44
  email: string;
76
45
  name: string;
77
46
  }
78
- interface User {
79
- id: string;
47
+
48
+ interface CreateUserInput {
80
49
  email: string;
81
50
  name: string;
82
51
  }
83
52
 
84
- class CreateUserUseCase extends Usecase<CreateUserInput, User> {
85
- constructor(config?: UsecaseConfiguration) {
53
+ interface CreateUserOutput {
54
+ id: UniqueIdentifier;
55
+ }
56
+
57
+ class UserRepository extends RepositoryBase<User, UniqueIdentifier> {
58
+ // Override methods (save, findById, etc.) only if you need custom logic
59
+ }
60
+
61
+ class CreateUserUseCase extends UseCase<CreateUserInput, CreateUserOutput> {
62
+ constructor(
63
+ private readonly userRepository: RepositoryPort<User, UniqueIdentifier>,
64
+ config?: UseCaseConfiguration
65
+ ) {
86
66
  super(config);
87
67
  }
88
68
 
69
+ // Implement business logic here
89
70
  protected async executeInternal(
90
71
  input: CreateUserInput,
91
- logger: LoggingPort,
92
- signal?: AbortSignal
93
- ): Promise<User> {
72
+ logger: LoggingPort
73
+ ): Promise<CreateUserOutput> {
94
74
  if (!input.email.includes('@')) {
95
75
  throw new ValidationError('Invalid email');
96
76
  }
77
+
78
+ const user = {
79
+ id: crypto.randomUUID() as UniqueIdentifier,
80
+ email: input.email,
81
+ name: input.name
82
+ } satisfies User;
83
+
84
+ await this.userRepository.save(user);
97
85
  logger.info('User created', { email: input.email });
98
- return { id: 'user_123', email: input.email, name: input.name };
86
+
87
+ return { id: user.id };
99
88
  }
100
89
  }
101
90
 
102
- const useCase = new CreateUserUseCase();
91
+ // Wire everything together at the boundary
92
+ const userRepository = new UserRepository();
93
+ const useCase = new CreateUserUseCase(userRepository, {
94
+ // Logging is provided by base class and injected into executeInternal
95
+ logging: ConsoleLoggingAdapter,
96
+ // Safety net: 5 second timeout with automatic cancellation
97
+ timeoutMs: 5000
98
+ });
99
+
103
100
  const result = await useCase.execute({
104
101
  email: 'user@example.com',
105
102
  name: 'John'
106
103
  });
107
104
 
108
105
  if (result.success) {
109
- console.log('User:', result.value);
110
- } else {
111
- console.error('Failed:', result.error);
106
+ console.log('Created:', result.value);
112
107
  }
108
+ // else handle error
113
109
  ```
114
110
 
115
- ## Best practices
111
+ ### Cancellation & Timeouts
116
112
 
117
- - Keep business rules in domain/application layers; framework details in infrastructure adapters
118
- - Use `Usecase` for operation boundaries and `ServiceBase` for reusable services
119
- - In `executeInternal`, return plain output for success; throw typed domain errors for business failures
120
- - Treat `AbortSignal` as the cancellation boundary for long-running operations
121
- - Handle outcomes via `result.success` at `execute()` call sites
122
- - Import from explicit subpaths (`@hexafy/core/application`, `/domain`, `/infrastructure`)
113
+ Cancellation via `AbortSignal` and automatic timeouts:
123
114
 
124
- ## Error handling model
115
+ ```ts
116
+ // Cancellation
117
+ const controller = new AbortController();
118
+ const result = await useCase.execute(input, { signal: controller.signal });
119
+ controller.abort();
125
120
 
126
- `Usecase.execute(...)` returns a `UsecaseResult` and never relies on raw thrown exceptions. It separates two failure types:
121
+ // Timeout in constructor
122
+ const useCase = new MyUseCase({ timeoutMs: 10000 });
123
+ ```
127
124
 
128
- 1. **Domain/business failures** – validation, conflict, not found, authorization violations thrown in `executeInternal`; returned unchanged in `result.error`
129
- 2. **Execution-boundary failures** – cancellation and timeout represented by `UsecaseCancelledError` and `UsecaseTimeoutError`
125
+ ### ServiceBase
130
126
 
131
- Domain errors preserve their type identity. Wrapper failures are explicit for easy narrowing:
127
+ For reusable services without full use case lifecycle. Services can be injected into use cases.
132
128
 
133
129
  ```ts
134
130
  import {
135
- UsecaseCancelledError,
136
- UsecaseTimeoutError
131
+ type ClockPort,
132
+ type MetricsPort,
133
+ ServiceBase
137
134
  } from '@hexafy/core/application';
138
135
 
139
- const result = await usecase.execute(input, { signal });
136
+ interface Product {
137
+ id: string;
138
+ name: string;
139
+ price: number;
140
+ }
141
+
142
+ class PricingService extends ServiceBase {
143
+ constructor(
144
+ clock: ClockPort,
145
+ metrics: MetricsPort,
146
+ config?: { logging?: any; clock?: ClockPort; metrics?: MetricsPort }
147
+ ) {
148
+ super(config);
149
+ }
150
+
151
+ // Calculate total price for products
152
+ async calculateTotal(items: Product[]): Promise<number> {
153
+ const startTime = this.clock.now();
154
+
155
+ const total = items.reduce((sum, p) => sum + p.price, 0);
156
+
157
+ this.metrics.increment('orders_calculated_total');
158
+ this.metrics.histogram(
159
+ 'calculation_duration',
160
+ this.clock.now() - startTime
161
+ );
162
+
163
+ return total;
164
+ }
165
+ }
166
+
167
+ // Use the service in a use case
168
+ class CheckoutUseCase {
169
+ constructor(
170
+ private readonly pricingService: PricingService,
171
+ private readonly paymentPort: PaymentPort
172
+ ) {}
173
+
174
+ async execute(items: Product[], userId: string): Promise<OrderId> {
175
+ const total = await this.pricingService.calculateTotal(items);
176
+
177
+ const orderId = await this.paymentPort.charge(userId, total);
178
+ return orderId;
179
+ }
180
+ }
181
+ ```
182
+
183
+ ### Ports & Adapters
184
+
185
+ Define ports for external concerns and implement them in infrastructure:
186
+
187
+ ```ts
188
+ // Define your port interface
189
+ interface NotificationPort {
190
+ sendEmail(recipient: string, subject: string, body: string): Promise<void>;
191
+ sendSms(phone: string, message: string): Promise<void>;
192
+ }
193
+
194
+ // Implement in your infrastructure layer
195
+ class SendGridNotificationAdapter implements NotificationPort {
196
+ async sendEmail(recipient: string, subject: string, body: string) {
197
+ await sendGrid.send({ to: recipient, subject, body });
198
+ }
199
+
200
+ async sendSms(phone: string, message: string) {
201
+ await twilio.send({ to: phone, message });
202
+ }
203
+ }
204
+
205
+ // Inject the port into your use case
206
+ class UserRegistrationUseCase extends UseCase<RegisterInput, UserId> {
207
+ constructor(
208
+ private readonly notificationPort: NotificationPort, // <-- Injected
209
+ config?: UseCaseConfiguration
210
+ ) {
211
+ super(config);
212
+ }
213
+
214
+ protected async executeInternal(input: RegisterInput): Promise<UserId> {
215
+ const userId = await this.userRepository.save(/* ... */);
216
+
217
+ // Use the port in your business logic
218
+ await this.notificationPort.sendEmail(
219
+ input.email,
220
+ 'Welcome!',
221
+ 'Thanks for signing up!'
222
+ );
223
+
224
+ return userId;
225
+ }
226
+ }
227
+
228
+ // Wire at the application boundary
229
+ const notificationAdapter = new SendGridNotificationAdapter();
230
+ const useCase = new UserRegistrationUseCase(notificationAdapter);
231
+ ```
232
+
233
+ ### Domain Errors
234
+
235
+ Typed error classes for expected failures:
236
+
237
+ ```ts
238
+ import {
239
+ ConflictError,
240
+ NotFoundError,
241
+ ValidationError
242
+ } from '@hexafy/core/domain';
243
+
244
+ throw new ValidationError('Invalid input', { context: { field: 'email' } });
245
+ throw new NotFoundError('User', { cause: dbError });
246
+ ```
247
+
248
+ ## Error Handling
249
+
250
+ `execute()` returns `UseCaseResult<TSuccess, TFailure>` - never throws exceptions:
251
+
252
+ ```ts
253
+ import {
254
+ UseCaseCancelledError,
255
+ UseCaseTimeoutError
256
+ } from '@hexafy/core/application';
257
+
258
+ const result = await useCase.execute(input, { signal });
140
259
 
141
260
  if (!result.success) {
142
- if (result.error instanceof UsecaseCancelledError) {
143
- // map to transport/client-cancel semantics
144
- } else if (result.error instanceof UsecaseTimeoutError) {
145
- // map to timeout semantics
261
+ if (result.error instanceof UseCaseTimeoutError) {
262
+ // Operation exceeded timeoutMs
263
+ } else if (result.error instanceof UseCaseCancelledError) {
264
+ // Request was cancelled
146
265
  } else {
147
- // domain/application error from executeInternal
266
+ // Domain/application error from executeInternal (ValidationError, NotFoundError, etc.)
267
+ }
268
+ }
269
+ ```
270
+
271
+ ### Error Classes
272
+
273
+ Typed error classes for expected failures:
274
+
275
+ ```ts
276
+ import {
277
+ ConflictError,
278
+ NotFoundError,
279
+ ValidationError
280
+ } from '@hexafy/core/domain';
281
+
282
+ throw new ValidationError('Invalid input', { context: { field: 'email' } });
283
+ throw new NotFoundError('User', { cause: dbError });
284
+ ```
285
+
286
+ ### Error Flow
287
+
288
+ 1. **In `executeInternal`**: Throw typed domain errors (`ValidationError`, `NotFoundError`, etc.)
289
+ 2. **Wrapped automatically**: Errors flow through `result.error` intact
290
+ 3. **At boundaries**: Map error codes to HTTP status, format responses
291
+
292
+ ### Custom Error Hierarchies
293
+
294
+ Extend `ApplicationError` for your business domain:
295
+
296
+ ```ts
297
+ import { ApplicationError, ErrorCodes } from '@hexafy/core/domain';
298
+
299
+ export class InsufficientBalanceError extends ApplicationError {
300
+ constructor(
301
+ message = 'Insufficient balance',
302
+ options?: { balance: number; required: number }
303
+ ) {
304
+ super(message, {
305
+ ...options,
306
+ code: options?.code ?? ErrorCodes.CONFLICT_ERROR
307
+ });
308
+ }
309
+ }
310
+
311
+ // Usage
312
+ const balance = await accountRepository.getBalance(accountId);
313
+ if (balance < required) {
314
+ throw new InsufficientBalanceError('Insufficient funds', {
315
+ balance,
316
+ required
317
+ });
318
+ }
319
+ ```
320
+
321
+ ### HTTP Mapping
322
+
323
+ Map error codes to HTTP status at your adapter:
324
+
325
+ ```ts
326
+ import { ArgumentsHost, Catch, ExceptionFilter } from '@nestjs/common';
327
+
328
+ function mapErrorToStatus(error: Error): number {
329
+ switch (error.code) {
330
+ case ErrorCodes.VALIDATION_ERROR:
331
+ return 400;
332
+ case ErrorCodes.UNAUTHORIZED_ERROR:
333
+ return 401;
334
+ case ErrorCodes.FORBIDDEN_ERROR:
335
+ return 403;
336
+ case ErrorCodes.NOT_FOUND_ERROR:
337
+ return 404;
338
+ case ErrorCodes.CONFLICT_ERROR:
339
+ return 409;
340
+ case ErrorCodes.INFRASTRUCTURE_ERROR:
341
+ return 500;
342
+ default:
343
+ return 500;
344
+ }
345
+ }
346
+
347
+ // NestJS exception filter
348
+ @Catch()
349
+ export class DomainExceptionFilter implements ExceptionFilter {
350
+ catch(exception: unknown, host: ArgumentsHost) {
351
+ const ctx = host.switchToHttp();
352
+ const response = ctx.getResponse<Response>();
353
+
354
+ const statusCode = mapErrorToStatus(exception as Error);
355
+ const error = exception as Error & { code?: string };
356
+
357
+ response.status(statusCode).json({
358
+ success: false,
359
+ error: error.message,
360
+ code: error.code
361
+ });
148
362
  }
149
363
  }
150
364
  ```
@@ -153,34 +367,29 @@ if (!result.success) {
153
367
 
154
368
  Three subpath entry points:
155
369
 
156
- - `@hexafy/core/application` – `Usecase`, `ServiceBase`, `UsecaseResult`, ports, configuration
370
+ - `@hexafy/core/application` – UseCase, ServiceBase, ports, configuration
157
371
  - `@hexafy/core/domain` – Domain primitives, errors, repository ports
158
372
  - `@hexafy/core/infrastructure` – Default adapters (logging, clock, metrics, identifier)
159
373
 
160
- See the [Exported artifacts and usage](#exported-artifacts-and-usage) table below for complete details.
161
-
162
- ## Exported artifacts and usage
163
-
164
- | Export | Entry point | What it is for | When to use | Minimal usage |
165
- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
166
- | `Usecase`, `UsecaseConfiguration` | `/application` | Execution lifecycle, timeouts, cancellation | One business operation with result contract | `class X extends Usecase<I, O> { ... }` |
167
- | `UsecaseExecutionOptions` | `/application` | Per-execution context and cancellation options | Passing execution metadata and `AbortSignal` | `usecase.execute(input, { executionContext, signal })` |
168
- | `ServiceBase`, `ServiceConfiguration` | `/application` | Shared app logic without full use-case lifecycle | Reusable services used by multiple use cases | `class PricingService extends ServiceBase { ... }` |
169
- | `UsecaseResult` | `/application` | Typed success/failure result contract returned by `Usecase.execute(...)` | Handling use-case outcomes at call sites | `const result = await usecase.execute(input)` |
170
- | `UsecaseCancelledError`, `UsecaseTimeoutError` | `/application` | Wrapper-owned execution failures and failure narrowing | Handling cancellation and timeout failures | `if (!result.success && result.error instanceof UsecaseTimeoutError) { ... }` |
171
- | `ClockPort`, `IdentifierPort`, `LoggingPort`, `MetricsPort` | `/application` | Boundary contracts for cross-cutting concerns | Invert infrastructure dependencies in app layer | Depend on interfaces, inject adapters |
172
- | `ApplicationError` | `/domain` | Base application error class | Custom error hierarchies and error handling | `class MyError extends ApplicationError { ... }` |
173
- | Domain error classes (`ValidationError`, `NotFoundError`, `ConflictError`, `UnauthorizedError`, `ForbiddenError`, `InvariantError`, `InfrastructureError`) | `/domain` | Standardized, typed error model | Expected business and boundary failures | `throw new ValidationError('...')` |
174
- | `isDomainError`, `getDomainErrorCode`, `DomainErrorLike` | `/domain` | Domain-error narrowing and metadata extraction | Boundary code (exception filters, handlers) for distinguishing domain vs. infrastructure errors | `if (isDomainError(err)) { return { status: 400, code: getDomainErrorCode(err) } }` |
175
- | `ApplicationErrorOptions`, `ApplicationErrorDetails` | `/domain` | Error construction metadata typing | Custom error subclasses and factories | Pass options to `ApplicationError` subclass |
176
- | `Entity`, `AggregateRoot`, `ValueObject`, `UniqueIdentifier`, `Brand` | `/domain` | DDD-oriented domain primitives and type branding | Rich domain model boundaries | Extend primitives in domain models |
177
- | `RepositoryBase`, `RepositoryPort` | `/domain` | Persistence abstraction contracts/bases | Domain persistence ports and adapters | Implement `RepositoryPort` in infrastructure |
178
- | `UnitOfWorkBase` | `/domain` | Transaction boundary abstraction | Multi-step persistence transactions | Extend in persistence adapters |
179
- | `SystemClockAdapter`, `SystemIdentifierAdapter` | `/infrastructure` | Default clock and id providers | Production defaults without custom implementations | Inject adapter constants in config |
180
- | `ConsoleLoggingAdapter`, `JSONConsoleLoggingAdapter`, `NoOpLoggingAdapter` | `/infrastructure` | Built-in logging adapters | Console logging, JSON logging, or silent logging | Use in `UsecaseConfiguration.logging` |
181
- | `NoOpMetricsAdapter` | `/infrastructure` | No-op metrics implementation | Disable metrics while keeping port contract | Inject as default metrics adapter |
182
-
183
- `AbortSignal` is a platform type (not a package export) used by `UsecaseExecutionOptions.signal` for cancellation-aware executions.
374
+ ## Export Reference
375
+
376
+ | Export | Entry Point | When to Use |
377
+ | -------------------------------------------------------------------------- | ----------------- | ----------------------------------------------- |
378
+ | `UseCase`, `UseCaseConfiguration` | `/application` | Business operations with result contract |
379
+ | `ServiceBase`, `ServiceConfiguration` | `/application` | Reusable services |
380
+ | `UseCaseResult`, `UseCaseExecutionOptions` | `/application` | Handling outcomes, passing context/signal |
381
+ | `UseCaseCancelledError`, `UseCaseTimeoutError` | `/application` | Handling execution boundary failures |
382
+ | `ClockPort`, `IdentifierPort`, `LoggingPort`, `MetricsPort` | `/application` | Dependency inversion for cross-cutting concerns |
383
+ | `ApplicationError`, `ErrorCodes` | `/domain` | Error handling, custom error hierarchies |
384
+ | Domain errors (`ValidationError`, `NotFoundError`, etc.) | `/domain` | Expected business failures |
385
+ | `isDomainError`, `getDomainErrorCode` | `/domain` | Type guards and error metadata extraction |
386
+ | `Entity`, `AggregateRoot`, `ValueObject`, `UniqueIdentifier`, `Brand` | `/domain` | Rich domain models |
387
+ | `ApplicationErrorOptions` | `/domain` | Error configuration typing |
388
+ | `RepositoryBase`, `RepositoryPort` | `/domain` | Persistence abstractions |
389
+ | `UnitOfWorkBase` | `/domain` | Transaction boundaries |
390
+ | `SystemClockAdapter`, `SystemIdentifierAdapter` | `/infrastructure` | Production defaults |
391
+ | `ConsoleLoggingAdapter`, `JSONConsoleLoggingAdapter`, `NoOpLoggingAdapter` | `/infrastructure` | Built-in logging implementations |
392
+ | `NoOpMetricsAdapter` | `/infrastructure` | Disable metrics while keeping port contract |
184
393
 
185
394
  ## License
186
395
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hexafy/core",
3
- "version": "1.0.0-rc.5",
3
+ "version": "1.0.0-rc.6",
4
4
  "description": "Hexagonal (ports and adapters) architecture primitives for TypeScript: use cases, domain entities, and infrastructure adapters.",
5
5
  "keywords": [
6
6
  "clean-architecture",
@@ -9,8 +9,8 @@
9
9
  "ports-adapter",
10
10
  "ports-and-adapters",
11
11
  "typescript",
12
- "use-case",
13
- "use-case-pattern"
12
+ "use case",
13
+ "use case pattern"
14
14
  ],
15
15
  "license": "MIT",
16
16
  "author": "Philipp Teßner-Müller",