-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path.cursorrules
More file actions
247 lines (196 loc) · 6.32 KB
/
.cursorrules
File metadata and controls
247 lines (196 loc) · 6.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# CleanStack - TDD/BDD/DDD/Clean Architecture Rules
## Quick Reference
```bash
pnpm dev # Dev server
pnpm test # Run tests
pnpm check:all # Full validation (lint, types, tests, duplication)
pnpm type-check # TypeScript only
```
## Core Principles
### TDD Workflow (Mandatory)
```
1. Write Tests FIRST (Red)
- Domain tests: src/domain/{name}/__tests__/
- UseCase tests: src/application/use-cases/{domain}/__tests__/
2. Run tests → FAIL (expected)
3. Write Implementation (Green)
- Minimal code to pass tests
4. Run tests → PASS
5. Refactor if needed
```
### BDD Test Format (Given/When/Then)
```typescript
describe("Context", () => {
describe("Given [precondition]", () => {
it("When [action], Then [expected outcome]", () => {
// Given - Setup
const input = { ... };
// When - Action
const result = await sut.execute(input);
// Then - Assertions
expect(result.isSuccess).toBe(true);
});
});
});
```
### Clean Architecture Layers
```
Domain (Core) → Entities, VOs, Aggregates, Events (NO external deps)
↑
Application → Use Cases, Ports (interfaces)
↑
Adapters → Controllers, Repositories, Guards
↑
Infrastructure → DB, DI config, External Services
```
**Rule:** Dependencies flow INWARD only. Never import outer layer in inner.
### DDD Patterns
| Pattern | Use For | Return Type |
|---------|---------|-------------|
| `Result<T>` | Operations that can fail | `Result.ok(value)` / `Result.fail(error)` |
| `Option<T>` | Nullable values | `Option.some(v)` / `Option.none()` |
| `ValueObject<T>` | Validated business values | Via `create()` → `Result<VO>` |
| `Aggregate<T>` | Entity with events | Via `create()` / `reconstitute()` |
## Code Templates
### Value Object
```typescript
import { Result, ValueObject } from "@packages/ddd-kit";
import { z } from "zod";
const schema = z.string().min(1).max(100);
export class {Name} extends ValueObject<string> {
protected validate(value: string): Result<string> {
const result = schema.safeParse(value);
if (!result.success) {
return Result.fail(result.error.errors[0].message);
}
return Result.ok(result.data);
}
}
```
### Aggregate
```typescript
import { Aggregate, UUID } from "@packages/ddd-kit";
import { {Name}CreatedEvent } from "./events/{name}-created.event";
interface I{Name}Props {
// properties
createdAt: Date;
updatedAt?: Date;
}
export class {Name} extends Aggregate<I{Name}Props> {
get id(): {Name}Id {
return {Name}Id.create(this._id);
}
static create(props: Omit<I{Name}Props, "createdAt">, id?: UUID): {Name} {
const entity = new {Name}({ ...props, createdAt: new Date() }, id ?? new UUID());
if (!id) entity.addEvent(new {Name}CreatedEvent(entity));
return entity;
}
static reconstitute(props: I{Name}Props, id: UUID): {Name} {
return new {Name}(props, id);
}
}
```
### Use Case
```typescript
import { match, Result, type UseCase } from "@packages/ddd-kit";
import type { IEventDispatcher } from "@/application/ports/event-dispatcher.port";
export class {Name}UseCase implements UseCase<Input, Output> {
constructor(
private readonly repo: IRepository,
private readonly eventDispatcher: IEventDispatcher,
) {}
async execute(input: Input): Promise<Result<Output>> {
// 1. Validate input - create VOs
// 2. Check business rules
// 3. Create/update domain entity
// 4. Persist FIRST
// 5. Dispatch events AFTER save
// 6. Return DTO
}
}
```
### Domain Event
```typescript
import { BaseDomainEvent } from "@packages/ddd-kit";
interface Payload {
aggregateId: string;
}
export class {Name}Event extends BaseDomainEvent<Payload> {
readonly eventType = "{aggregate}.{action}";
constructor(aggregate: Aggregate) {
super();
this.aggregateId = aggregate.id.value;
this.payload = { aggregateId: aggregate.id.value };
}
}
```
## Testing Rules
### Test Location
- Domain: `src/domain/{name}/__tests__/`
- UseCases: `src/application/use-cases/{domain}/__tests__/`
- Adapters: `src/__TESTS__/adapters/`
### Test Categories
1. **Happy Path** - Valid input produces expected output
2. **Validation Errors** - Invalid input fails gracefully
3. **Business Rules** - Domain rules enforced
4. **Error Handling** - Repository/service failures handled
5. **Event Emission** - Events dispatched AFTER save
### Mocking Rules
- Mock at PORT/INTERFACE level only (Clean Architecture)
- Use `vi.fn()` for all mock functions
- Return `Result.ok/fail` for Result-returning methods
- Return `Option.some/none` for Option-returning methods
```typescript
const mockRepo: IRepository = {
create: vi.fn(),
findById: vi.fn(),
// ...all BaseRepository methods
};
```
## Anti-Patterns (NEVER DO)
| Don't | Do Instead |
|-------|------------|
| `throw new Error()` in domain | `return Result.fail("message")` |
| `return null` | `return Option.none()` |
| Import React in domain | Keep domain pure |
| Logic in controllers | Logic in use cases |
| Tests AFTER code | Tests FIRST (TDD) |
| `any` types | `unknown` or proper types |
| Index barrels | Direct imports |
## Key Rules
1. **Domain = zero external imports** (only ddd-kit + Zod)
2. **Never throw** in Domain/Application → use `Result<T>`
3. **Never null** → use `Option<T>`
4. **VOs use Zod** for validation
5. **Events dispatch AFTER save** succeeds
6. **All deps injected** via DI
7. **No index.ts barrels** → import directly
8. **Only `get id()` getter** → use `entity.get('propName')` for others
## File Structure
```
apps/nextjs/src/
├── domain/{aggregate}/
│ ├── {aggregate}.aggregate.ts
│ ├── {aggregate}-id.ts
│ ├── __tests__/ # Domain tests
│ ├── value-objects/
│ └── events/
├── application/
│ ├── use-cases/{domain}/
│ │ ├── {name}.use-case.ts
│ │ └── __tests__/ # UseCase tests
│ ├── ports/ # Interfaces
│ └── dto/
└── adapters/
├── repositories/
├── mappers/
├── guards/
└── services/
```
## Before Coding Checklist
- [ ] Read CLAUDE.md for full patterns
- [ ] Write failing tests FIRST
- [ ] Use Result<T> for fallible operations
- [ ] Use Option<T> for nullable values
- [ ] Keep domain layer pure
- [ ] Dispatch events AFTER successful save