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

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 +116 -58
  2. package/package.json +8 -5
package/README.md CHANGED
@@ -1,16 +1,55 @@
1
1
  # @hexafy/core
2
2
 
3
- A small, opinionated toolkit for building hexagonal architecture applications in TypeScript.
3
+ Core hexagonal architecture primitives for TypeScript: use cases, domain building blocks, and infrastructure ports/adapters.
4
4
 
5
- This package gives you the core building blocks for domain logic, application use cases, repositories, and error handling without bringing in a framework.
5
+ ## Why this package exists
6
6
 
7
- ## What it includes
7
+ `@hexafy/core` is the foundation of the Hexafy package family. It keeps business logic framework-agnostic and provides:
8
8
 
9
- - `Usecase` base class for application logic
10
- - `UsecaseResult` helpers: `success`, `failure`, `unwrap`, `isSuccess`, `isFailure`
11
- - domain error types such as `ValidationError`, `NotFoundError`, `ConflictError`, and `ApplicationError`
12
- - repository and unit-of-work base abstractions
13
- - logging, clock, identifier, and metrics ports with adapters
9
+ - Application orchestration (`Usecase`, `ServiceBase`)
10
+ - Use-case outcome contract (`UsecaseResult`)
11
+ - Domain errors and primitives (`ApplicationError`, `Entity`, `AggregateRoot`, `ValueObject`)
12
+ - Cross-cutting ports and default adapters (logging, metrics, clock, identifier)
13
+
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.
14
53
 
15
54
  ## Installation
16
55
 
@@ -26,16 +65,16 @@ yarn add @hexafy/core
26
65
 
27
66
  ```ts
28
67
  import {
68
+ type LoggingPort,
29
69
  Usecase,
30
- type UsecaseExecutionConfiguration
70
+ type UsecaseConfiguration
31
71
  } from '@hexafy/core/application';
32
- import { type LoggerPort, ValidationError } from '@hexafy/core/domain';
72
+ import { ValidationError } from '@hexafy/core/domain';
33
73
 
34
74
  interface CreateUserInput {
35
75
  email: string;
36
76
  name: string;
37
77
  }
38
-
39
78
  interface User {
40
79
  id: string;
41
80
  email: string;
@@ -43,86 +82,105 @@ interface User {
43
82
  }
44
83
 
45
84
  class CreateUserUseCase extends Usecase<CreateUserInput, User> {
46
- constructor(config?: UsecaseExecutionConfiguration) {
85
+ constructor(config?: UsecaseConfiguration) {
47
86
  super(config);
48
87
  }
49
88
 
50
89
  protected async executeInternal(
51
90
  input: CreateUserInput,
52
- logger: LoggerPort
91
+ logger: LoggingPort,
92
+ signal?: AbortSignal
53
93
  ): Promise<User> {
54
94
  if (!input.email.includes('@')) {
55
95
  throw new ValidationError('Invalid email');
56
96
  }
57
-
58
97
  logger.info('User created', { email: input.email });
59
-
60
- return {
61
- id: 'user_123',
62
- email: input.email,
63
- name: input.name
64
- };
98
+ return { id: 'user_123', email: input.email, name: input.name };
65
99
  }
66
100
  }
67
101
 
68
102
  const useCase = new CreateUserUseCase();
69
103
  const result = await useCase.execute({
70
- email: 'john@example.com',
104
+ email: 'user@example.com',
71
105
  name: 'John'
72
106
  });
73
107
 
74
108
  if (result.success) {
75
- console.log(result.value);
109
+ console.log('User:', result.value);
76
110
  } else {
77
- console.error(result.error.message);
111
+ console.error('Failed:', result.error);
78
112
  }
79
113
  ```
80
114
 
81
- ## Core pattern
82
-
83
- The package is built around a simple application flow:
115
+ ## Best practices
84
116
 
85
- - business logic lives in a `Usecase`
86
- - the use case returns a value on success
87
- - thrown errors are converted into a failed `UsecaseResult`
88
- - infrastructure concerns stay outside the domain layer
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`)
89
123
 
90
- Example:
124
+ ## Error handling model
91
125
 
92
- ```ts
93
- import { failure, success } from '@hexafy/core/application';
94
-
95
- const ok = success({ id: '1' });
96
- const bad = failure(new Error('Something went wrong'));
97
-
98
- if (ok.success) {
99
- console.log(ok.value.id);
100
- }
101
- ```
126
+ `Usecase.execute(...)` returns a `UsecaseResult` and never relies on raw thrown exceptions. It separates two failure types:
102
127
 
103
- ## Package layout
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`
104
130
 
105
- This package exposes focused subpaths:
131
+ Domain errors preserve their type identity. Wrapper failures are explicit for easy narrowing:
106
132
 
107
133
  ```ts
108
- import { failure, success, Usecase } from '@hexafy/core/application';
109
134
  import {
110
- ApplicationError,
111
- type LoggerPort,
112
- RepositoryBase,
113
- type RepositoryPort,
114
- ValidationError
115
- } from '@hexafy/core/domain';
116
- import { ConsoleLoggingAdapter } from '@hexafy/core/infrastructure';
117
- ```
135
+ UsecaseCancelledError,
136
+ UsecaseTimeoutError
137
+ } from '@hexafy/core/application';
138
+
139
+ const result = await usecase.execute(input, { signal });
118
140
 
119
- ## Recommended usage
141
+ 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
146
+ } else {
147
+ // domain/application error from executeInternal
148
+ }
149
+ }
150
+ ```
120
151
 
121
- - keep domain rules and validation in `Usecase` or domain types
122
- - let infrastructure code throw unexpected exceptions
123
- - use domain errors for expected business failures
124
- - keep adapters on the edges of the system
125
- - prefer small, explicit ports over framework-specific abstractions
152
+ ## Public API
153
+
154
+ Three subpath entry points:
155
+
156
+ - `@hexafy/core/application` – `Usecase`, `ServiceBase`, `UsecaseResult`, ports, configuration
157
+ - `@hexafy/core/domain` – Domain primitives, errors, repository ports
158
+ - `@hexafy/core/infrastructure` – Default adapters (logging, clock, metrics, identifier)
159
+
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.
126
184
 
127
185
  ## License
128
186
 
package/package.json CHANGED
@@ -1,13 +1,16 @@
1
1
  {
2
2
  "name": "@hexafy/core",
3
- "version": "1.0.0-rc.3",
4
- "description": "Core hexagonal architecture constructs for TypeScript",
3
+ "version": "1.0.0-rc.5",
4
+ "description": "Hexagonal (ports and adapters) architecture primitives for TypeScript: use cases, domain entities, and infrastructure adapters.",
5
5
  "keywords": [
6
6
  "clean-architecture",
7
- "ddd",
7
+ "domain-driven-design",
8
8
  "hexagonal-architecture",
9
+ "ports-adapter",
10
+ "ports-and-adapters",
9
11
  "typescript",
10
- "use-case"
12
+ "use-case",
13
+ "use-case-pattern"
11
14
  ],
12
15
  "license": "MIT",
13
16
  "author": "Philipp Teßner-Müller",
@@ -43,7 +46,7 @@
43
46
  "devDependencies": {
44
47
  "@hexafy/tsdown-config": "0.0.0",
45
48
  "@hexafy/typescript-config": "0.0.0",
46
- "typescript": "^7.0.2"
49
+ "typescript": "7.0.2"
47
50
  },
48
51
  "engines": {
49
52
  "bun": ">=1.3",