@beebear-plugins/mcp 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +85 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2095 -0
- package/package.json +56 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,2095 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
#!/usr/bin/env node
|
|
3
|
+
|
|
4
|
+
// src/index.ts
|
|
5
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
6
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
7
|
+
|
|
8
|
+
// src/resources/overview.ts
|
|
9
|
+
var OVERVIEW = `# beebear \u2014 Hexagonal Architecture Framework
|
|
10
|
+
|
|
11
|
+
## What is beebear?
|
|
12
|
+
|
|
13
|
+
beebear is a lightweight, **decorator-free** framework that provides the plumbing for
|
|
14
|
+
hexagonal architecture (ports and adapters) in Node.js/TypeScript. It has **zero runtime
|
|
15
|
+
dependencies**. Developers focus on domain logic and adapter implementations; beebear
|
|
16
|
+
handles dependency injection, error mapping, use case execution, and transport abstraction.
|
|
17
|
+
|
|
18
|
+
## Core Concepts
|
|
19
|
+
|
|
20
|
+
### Hexagonal Architecture
|
|
21
|
+
The application is split into an inner hexagon (domain logic) and outer adapters
|
|
22
|
+
(infrastructure). The domain defines **ports** (interfaces) that adapters implement.
|
|
23
|
+
Dependencies always point inward \u2014 the domain never imports infrastructure code.
|
|
24
|
+
|
|
25
|
+
### Ports
|
|
26
|
+
Ports are standard TypeScript interfaces with co-located runtime tokens created via
|
|
27
|
+
\`Port<T>(name)\`. Ports live inside the domain. There are two kinds:
|
|
28
|
+
- **Inbound (driving) ports** \u2014 use case interfaces that the outside world calls in
|
|
29
|
+
- **Outbound (driven) ports** \u2014 repository/service interfaces the domain depends on
|
|
30
|
+
|
|
31
|
+
### Adapters
|
|
32
|
+
Adapters live in infrastructure and implement port interfaces:
|
|
33
|
+
- **Driving adapters** \u2014 HTTP controllers, CLI handlers, message consumers
|
|
34
|
+
- **Driven adapters** \u2014 database repositories, email services, payment gateways
|
|
35
|
+
|
|
36
|
+
### Use Cases
|
|
37
|
+
Class-based by default. A use case implements a driving port and depends on driven ports.
|
|
38
|
+
Use cases live inside the hexagon and have zero framework imports.
|
|
39
|
+
|
|
40
|
+
### DI Container
|
|
41
|
+
Token-based, no decorators, no \`reflect-metadata\`. Explicit factory functions.
|
|
42
|
+
Singleton by default with transient and scoped opt-in. Startup validation catches
|
|
43
|
+
missing bindings before the app starts.
|
|
44
|
+
|
|
45
|
+
## What beebear Handles vs What You Handle
|
|
46
|
+
|
|
47
|
+
**beebear provides:**
|
|
48
|
+
- \`Port<T>()\` / \`Token<T>()\` \u2014 typed DI tokens
|
|
49
|
+
- \`createContainer()\` \u2014 DI container with bind/resolve/validate
|
|
50
|
+
- \`createHexApp()\` \u2014 ties container, error mapping, HTTP adapters, and hooks together
|
|
51
|
+
- Error base classes with automatic HTTP status mapping
|
|
52
|
+
- Transport abstraction via \`httpAdapter()\` (Express, Fastify, Hono)
|
|
53
|
+
- Lifecycle hooks: \`beforeExecute\`, \`afterExecute\`, \`onError\`
|
|
54
|
+
|
|
55
|
+
**You provide:**
|
|
56
|
+
- HTTP server (Express, Fastify, Hono)
|
|
57
|
+
- Database client (Prisma, Drizzle, Mongoose)
|
|
58
|
+
- Validation library (Zod, Joi, etc.) \u2014 used in middleware before routes
|
|
59
|
+
- Authentication / authorization
|
|
60
|
+
- Logging, tracing, metrics (plug into lifecycle hooks)
|
|
61
|
+
|
|
62
|
+
## Plugin Ecosystem
|
|
63
|
+
|
|
64
|
+
- **@beebear-plugins/di-decorators** \u2014 Opt-in decorator-based DI (\`@Injectable\`, \`@Inject\`).
|
|
65
|
+
Requires only \`experimentalDecorators: true\` in tsconfig (no \`reflect-metadata\`).
|
|
66
|
+
- **@beebear-plugins/ddd** \u2014 Domain-Driven Design building blocks: \`ValueObject\`,
|
|
67
|
+
\`Entity\`, \`AggregateRoot\`, \`DomainEvent\`. Zero dependencies, standalone.
|
|
68
|
+
`;
|
|
69
|
+
|
|
70
|
+
// src/resources/api.ts
|
|
71
|
+
var API = `# beebear API Reference
|
|
72
|
+
|
|
73
|
+
## Token & Port
|
|
74
|
+
|
|
75
|
+
\`\`\`ts
|
|
76
|
+
type InjectionToken<T> = symbol & { readonly __type?: T };
|
|
77
|
+
|
|
78
|
+
function Token<T>(name: string): InjectionToken<T>;
|
|
79
|
+
function Port<T>(name: string): InjectionToken<T>;
|
|
80
|
+
\`\`\`
|
|
81
|
+
|
|
82
|
+
- \`Token<T>(name)\` creates a unique branded symbol for DI. Throws if \`name\` is already used.
|
|
83
|
+
- \`Port<T>(name)\` is a semantic alias for \`Token\`. Use \`Port\` for hexagonal ports, \`Token\` for general dependencies.
|
|
84
|
+
- The phantom type \`T\` enables type-safe resolution \u2014 \`container.resolve(token)\` returns \`T\`.
|
|
85
|
+
|
|
86
|
+
## Container
|
|
87
|
+
|
|
88
|
+
\`\`\`ts
|
|
89
|
+
function createContainer(): Container;
|
|
90
|
+
|
|
91
|
+
interface Container {
|
|
92
|
+
bind<T>(token: InjectionToken<T>, factory: (c: Container) => T, options?: BindOptions): void;
|
|
93
|
+
bind<T>(token: InjectionToken<T>, constructor: new (...args: any[]) => T, deps: InjectionToken[], options?: BindOptions): void;
|
|
94
|
+
resolve<T>(token: InjectionToken<T>): T;
|
|
95
|
+
has<T>(token: InjectionToken<T>): boolean;
|
|
96
|
+
validate(): void;
|
|
97
|
+
createScope(): Container;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
interface BindOptions {
|
|
101
|
+
lifecycle?: 'singleton' | 'transient' | 'scoped';
|
|
102
|
+
}
|
|
103
|
+
\`\`\`
|
|
104
|
+
|
|
105
|
+
- \`bind(token, factory)\` \u2014 factory receives the container for resolving dependencies.
|
|
106
|
+
- \`bind(token, Constructor, [depTokens])\` \u2014 shorthand, container resolves deps and passes to constructor.
|
|
107
|
+
- \`resolve(token)\` \u2014 returns the instance. Singleton by default (cached after first resolve).
|
|
108
|
+
- \`has(token)\` \u2014 check if a binding exists.
|
|
109
|
+
- \`validate()\` \u2014 throws if any binding has unresolvable dependencies. Call at startup.
|
|
110
|
+
- \`createScope()\` \u2014 child container for scoped lifecycles.
|
|
111
|
+
|
|
112
|
+
## Errors
|
|
113
|
+
|
|
114
|
+
\`\`\`ts
|
|
115
|
+
class BusinessError extends Error {
|
|
116
|
+
code: string;
|
|
117
|
+
name: string;
|
|
118
|
+
constructor(message: string, code?: string);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
class ValidationError extends BusinessError {} // 400
|
|
122
|
+
class NotFoundError extends BusinessError {} // 404
|
|
123
|
+
class ConflictError extends BusinessError {} // 409
|
|
124
|
+
class UnauthorizedError extends BusinessError {} // 401
|
|
125
|
+
class ForbiddenError extends BusinessError {} // 403
|
|
126
|
+
\`\`\`
|
|
127
|
+
|
|
128
|
+
All error classes accept \`(message: string, code?: string)\`. The \`code\` defaults to a
|
|
129
|
+
snake_case derivation of the class name (e.g. \`VALIDATION_ERROR\`).
|
|
130
|
+
|
|
131
|
+
## UseCase
|
|
132
|
+
|
|
133
|
+
\`\`\`ts
|
|
134
|
+
interface UseCase<TInput, TOutput> {
|
|
135
|
+
execute(input: TInput): Promise<TOutput>;
|
|
136
|
+
}
|
|
137
|
+
\`\`\`
|
|
138
|
+
|
|
139
|
+
## createHexApp
|
|
140
|
+
|
|
141
|
+
\`\`\`ts
|
|
142
|
+
function createHexApp(options: HexAppOptions): HexApp;
|
|
143
|
+
|
|
144
|
+
interface HexAppOptions {
|
|
145
|
+
container: Container;
|
|
146
|
+
errorMap?: Record<string, number>;
|
|
147
|
+
framework?: BuiltInFramework | FrameworkStrategy;
|
|
148
|
+
hooks?: HexAppHooks;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
type BuiltInFramework = 'express' | 'fastify' | 'hono';
|
|
152
|
+
|
|
153
|
+
interface HexApp {
|
|
154
|
+
execute<TInput, TOutput>(token: InjectionToken<UseCase<TInput, TOutput>>, input: TInput): Promise<ExecuteResult<TOutput>>;
|
|
155
|
+
httpAdapter<TInput, TOutput>(token: InjectionToken<UseCase<TInput, TOutput>>, options: HttpAdapterOptions<TInput>): any;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
interface HttpAdapterOptions<TInput> {
|
|
159
|
+
toInput: (req: any) => TInput;
|
|
160
|
+
status?: number;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
type ExecuteResult<T> =
|
|
164
|
+
| { success: true; data: T }
|
|
165
|
+
| { success: false; error: { message: string; code: string }; statusCode: number };
|
|
166
|
+
\`\`\`
|
|
167
|
+
|
|
168
|
+
Default status by HTTP method: POST returns 201, DELETE returns 204, all others return 200.
|
|
169
|
+
|
|
170
|
+
Default error-to-status map: BusinessError 400, ValidationError 400, NotFoundError 404,
|
|
171
|
+
ConflictError 409, UnauthorizedError 401, ForbiddenError 403.
|
|
172
|
+
|
|
173
|
+
## Lifecycle Hooks
|
|
174
|
+
|
|
175
|
+
\`\`\`ts
|
|
176
|
+
interface HookContext {
|
|
177
|
+
token: symbol;
|
|
178
|
+
tokenName: string;
|
|
179
|
+
input: unknown;
|
|
180
|
+
result?: ExecuteResult<unknown>;
|
|
181
|
+
error?: unknown;
|
|
182
|
+
duration: number;
|
|
183
|
+
state: Record<string, unknown>;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
interface HexAppHooks {
|
|
187
|
+
beforeExecute?: (context: HookContext) => void;
|
|
188
|
+
afterExecute?: (context: HookContext) => void;
|
|
189
|
+
onError?: (context: HookContext) => void;
|
|
190
|
+
}
|
|
191
|
+
\`\`\`
|
|
192
|
+
|
|
193
|
+
- \`state\` is a mutable bag shared across all three hooks for a single execution.
|
|
194
|
+
- \`duration\` is 0 in \`beforeExecute\`, measured in ms in \`afterExecute\` and \`onError\`.
|
|
195
|
+
`;
|
|
196
|
+
|
|
197
|
+
// src/resources/patterns.ts
|
|
198
|
+
var PATTERNS = `# beebear Patterns
|
|
199
|
+
|
|
200
|
+
## 1. Port Definition
|
|
201
|
+
|
|
202
|
+
Ports are TypeScript interfaces with co-located runtime tokens. Inbound ports define
|
|
203
|
+
what the outside world can ask the domain to do. Outbound ports define what the domain
|
|
204
|
+
needs from infrastructure.
|
|
205
|
+
|
|
206
|
+
\`\`\`ts
|
|
207
|
+
// src/domain/ports/inbound/create-order.port.ts
|
|
208
|
+
import { Port } from 'beebear';
|
|
209
|
+
import type { UseCase } from 'beebear';
|
|
210
|
+
|
|
211
|
+
export interface CreateOrderInput {
|
|
212
|
+
customerId: string;
|
|
213
|
+
items: { productId: string; quantity: number }[];
|
|
214
|
+
}
|
|
215
|
+
export interface CreateOrderOutput {
|
|
216
|
+
orderId: string;
|
|
217
|
+
}
|
|
218
|
+
export type CreateOrderPort = UseCase<CreateOrderInput, CreateOrderOutput>;
|
|
219
|
+
export const CreateOrderPort = Port<CreateOrderPort>('CreateOrder');
|
|
220
|
+
|
|
221
|
+
// src/domain/ports/outbound/order-repository.port.ts
|
|
222
|
+
import { Port } from 'beebear';
|
|
223
|
+
|
|
224
|
+
export interface OrderRepository {
|
|
225
|
+
save(order: Order): Promise<void>;
|
|
226
|
+
findById(id: string): Promise<Order | null>;
|
|
227
|
+
}
|
|
228
|
+
export const OrderRepository = Port<OrderRepository>('OrderRepository');
|
|
229
|
+
\`\`\`
|
|
230
|
+
|
|
231
|
+
## 2. Use Case Implementation
|
|
232
|
+
|
|
233
|
+
Use cases implement inbound ports and depend on outbound ports. They contain
|
|
234
|
+
only domain logic \u2014 no framework imports.
|
|
235
|
+
|
|
236
|
+
\`\`\`ts
|
|
237
|
+
// src/domain/use-cases/create-order.use-case.ts
|
|
238
|
+
import type { CreateOrderPort, CreateOrderInput, CreateOrderOutput } from '../ports/inbound/create-order.port';
|
|
239
|
+
import type { OrderRepository } from '../ports/outbound/order-repository.port';
|
|
240
|
+
import { NotFoundError } from 'beebear';
|
|
241
|
+
|
|
242
|
+
export class CreateOrderUseCase implements CreateOrderPort {
|
|
243
|
+
constructor(private readonly orderRepo: OrderRepository) {}
|
|
244
|
+
|
|
245
|
+
async execute(input: CreateOrderInput): Promise<CreateOrderOutput> {
|
|
246
|
+
if (input.items.length === 0) {
|
|
247
|
+
throw new NotFoundError('Order must have at least one item');
|
|
248
|
+
}
|
|
249
|
+
const order = Order.create(input.customerId, input.items);
|
|
250
|
+
await this.orderRepo.save(order);
|
|
251
|
+
return { orderId: order.id };
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
\`\`\`
|
|
255
|
+
|
|
256
|
+
## 3. Adapter Implementation
|
|
257
|
+
|
|
258
|
+
Driven adapters implement outbound port interfaces and live in infrastructure.
|
|
259
|
+
|
|
260
|
+
\`\`\`ts
|
|
261
|
+
// src/infrastructure/persistence/prisma-order-repository.ts
|
|
262
|
+
import type { OrderRepository } from '../../domain/ports/outbound/order-repository.port';
|
|
263
|
+
import { PrismaClient } from '@prisma/client';
|
|
264
|
+
|
|
265
|
+
export class PrismaOrderRepository implements OrderRepository {
|
|
266
|
+
constructor(private readonly prisma: PrismaClient) {}
|
|
267
|
+
|
|
268
|
+
async save(order: Order): Promise<void> {
|
|
269
|
+
await this.prisma.order.create({ data: order.toPersistence() });
|
|
270
|
+
}
|
|
271
|
+
async findById(id: string): Promise<Order | null> {
|
|
272
|
+
const row = await this.prisma.order.findUnique({ where: { id } });
|
|
273
|
+
return row ? Order.fromPersistence(row) : null;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
\`\`\`
|
|
277
|
+
|
|
278
|
+
## 4. Container Binding
|
|
279
|
+
|
|
280
|
+
\`\`\`ts
|
|
281
|
+
import { createContainer, Token } from 'beebear';
|
|
282
|
+
import { OrderRepository } from './domain/ports/outbound/order-repository.port';
|
|
283
|
+
import { CreateOrderPort } from './domain/ports/inbound/create-order.port';
|
|
284
|
+
import { PrismaOrderRepository } from './infrastructure/persistence/prisma-order-repository';
|
|
285
|
+
import { CreateOrderUseCase } from './domain/use-cases/create-order.use-case';
|
|
286
|
+
import { PrismaClient } from '@prisma/client';
|
|
287
|
+
|
|
288
|
+
const PrismaToken = Token<PrismaClient>('PrismaClient');
|
|
289
|
+
const container = createContainer();
|
|
290
|
+
|
|
291
|
+
// Factory form \u2014 full control
|
|
292
|
+
container.bind(PrismaToken, () => new PrismaClient());
|
|
293
|
+
|
|
294
|
+
// Factory form \u2014 resolve dependencies from container
|
|
295
|
+
container.bind(OrderRepository, (c) => new PrismaOrderRepository(c.resolve(PrismaToken)));
|
|
296
|
+
|
|
297
|
+
// Constructor shorthand \u2014 deps array maps to constructor params
|
|
298
|
+
container.bind(CreateOrderPort, CreateOrderUseCase, [OrderRepository]);
|
|
299
|
+
|
|
300
|
+
// Transient lifecycle
|
|
301
|
+
container.bind(SomeToken, SomeClass, [], { lifecycle: 'transient' });
|
|
302
|
+
|
|
303
|
+
// Validate all bindings at startup (catches missing deps early)
|
|
304
|
+
container.validate();
|
|
305
|
+
\`\`\`
|
|
306
|
+
|
|
307
|
+
## 5. HTTP Routes with httpAdapter
|
|
308
|
+
|
|
309
|
+
\`\`\`ts
|
|
310
|
+
import express from 'express';
|
|
311
|
+
import { createHexApp } from 'beebear';
|
|
312
|
+
import { CreateOrderPort } from './domain/ports/inbound/create-order.port';
|
|
313
|
+
|
|
314
|
+
const app = express();
|
|
315
|
+
const hex = createHexApp({ container, framework: 'express' });
|
|
316
|
+
|
|
317
|
+
// toInput extracts use case input from the request
|
|
318
|
+
app.post('/orders', hex.httpAdapter(CreateOrderPort, {
|
|
319
|
+
toInput: (req) => ({
|
|
320
|
+
customerId: req.body.customerId,
|
|
321
|
+
items: req.body.items,
|
|
322
|
+
}),
|
|
323
|
+
}));
|
|
324
|
+
|
|
325
|
+
// Method defaults: POST -> 201, DELETE -> 204, else -> 200
|
|
326
|
+
// Override with status option:
|
|
327
|
+
app.get('/orders/:id', hex.httpAdapter(GetOrderPort, {
|
|
328
|
+
toInput: (req) => ({ orderId: req.params.id }),
|
|
329
|
+
status: 200,
|
|
330
|
+
}));
|
|
331
|
+
\`\`\`
|
|
332
|
+
|
|
333
|
+
## 6. Lifecycle Hooks
|
|
334
|
+
|
|
335
|
+
\`\`\`ts
|
|
336
|
+
const hex = createHexApp({
|
|
337
|
+
container,
|
|
338
|
+
hooks: {
|
|
339
|
+
beforeExecute(ctx) {
|
|
340
|
+
ctx.state.startTime = Date.now();
|
|
341
|
+
console.log(\\\`Executing \\\${ctx.tokenName} with input:\\\`, ctx.input);
|
|
342
|
+
},
|
|
343
|
+
afterExecute(ctx) {
|
|
344
|
+
console.log(\\\`\\\${ctx.tokenName} completed in \\\${ctx.duration}ms\\\`);
|
|
345
|
+
},
|
|
346
|
+
onError(ctx) {
|
|
347
|
+
console.error(\\\`\\\${ctx.tokenName} failed after \\\${ctx.duration}ms:\\\`, ctx.error);
|
|
348
|
+
},
|
|
349
|
+
},
|
|
350
|
+
});
|
|
351
|
+
\`\`\`
|
|
352
|
+
|
|
353
|
+
The \`state\` object is shared across all three hooks for a single execution, allowing
|
|
354
|
+
\`beforeExecute\` to store data that \`afterExecute\` or \`onError\` reads.
|
|
355
|
+
|
|
356
|
+
## 7. Third-Party DI (Escape Hatch)
|
|
357
|
+
|
|
358
|
+
If you already use another DI container, wrap it to match beebear's Container interface:
|
|
359
|
+
|
|
360
|
+
\`\`\`ts
|
|
361
|
+
import { createHexApp } from 'beebear';
|
|
362
|
+
import type { Container } from 'beebear';
|
|
363
|
+
|
|
364
|
+
function wrapExternalContainer(external: ExternalDI): Container {
|
|
365
|
+
return {
|
|
366
|
+
bind: (token, factory) => external.register(token, factory),
|
|
367
|
+
resolve: (token) => external.get(token),
|
|
368
|
+
has: (token) => external.has(token),
|
|
369
|
+
validate: () => { /* no-op or custom logic */ },
|
|
370
|
+
createScope: () => wrapExternalContainer(external.createChild()),
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const hex = createHexApp({ container: wrapExternalContainer(myExternalDI) });
|
|
375
|
+
\`\`\`
|
|
376
|
+
`;
|
|
377
|
+
|
|
378
|
+
// src/resources/project-structure.ts
|
|
379
|
+
var PROJECT_STRUCTURE = `# beebear Project Structure
|
|
380
|
+
|
|
381
|
+
## Standard Layout
|
|
382
|
+
|
|
383
|
+
\`\`\`
|
|
384
|
+
src/
|
|
385
|
+
\u251C\u2500\u2500 domain/
|
|
386
|
+
\u2502 \u251C\u2500\u2500 models/ # Domain objects (plain TS, no framework imports)
|
|
387
|
+
\u2502 \u251C\u2500\u2500 ports/
|
|
388
|
+
\u2502 \u2502 \u251C\u2500\u2500 inbound/ # Driving ports (use case interfaces + tokens)
|
|
389
|
+
\u2502 \u2502 \u2514\u2500\u2500 outbound/ # Driven ports (repo/service interfaces + tokens)
|
|
390
|
+
\u2502 \u251C\u2500\u2500 use-cases/ # Use case implementations
|
|
391
|
+
\u2502 \u2514\u2500\u2500 errors/ # Domain error subclasses
|
|
392
|
+
\u2514\u2500\u2500 infrastructure/
|
|
393
|
+
\u251C\u2500\u2500 persistence/ # Driven adapters (Prisma, Mongo, in-memory)
|
|
394
|
+
\u251C\u2500\u2500 http/ # Driving adapters (controllers/routes)
|
|
395
|
+
\u2514\u2500\u2500 services/ # Driven adapters (email, payment, etc.)
|
|
396
|
+
\`\`\`
|
|
397
|
+
|
|
398
|
+
## What Goes Where
|
|
399
|
+
|
|
400
|
+
### domain/models/
|
|
401
|
+
Plain TypeScript classes and types representing domain concepts. No framework imports,
|
|
402
|
+
no database annotations. These are the core business objects.
|
|
403
|
+
|
|
404
|
+
\`\`\`ts
|
|
405
|
+
// domain/models/order.ts
|
|
406
|
+
export class Order {
|
|
407
|
+
constructor(
|
|
408
|
+
public readonly id: string,
|
|
409
|
+
public readonly customerId: string,
|
|
410
|
+
public readonly items: OrderItem[],
|
|
411
|
+
public readonly status: OrderStatus,
|
|
412
|
+
) {}
|
|
413
|
+
}
|
|
414
|
+
\`\`\`
|
|
415
|
+
|
|
416
|
+
### domain/ports/inbound/
|
|
417
|
+
Driving port interfaces that define what the outside world can ask the domain to do.
|
|
418
|
+
Each file exports a TypeScript interface (extending \`UseCase<TInput, TOutput>\`) and
|
|
419
|
+
a co-located \`Port<T>()\` token.
|
|
420
|
+
|
|
421
|
+
\`\`\`ts
|
|
422
|
+
// domain/ports/inbound/create-order.port.ts
|
|
423
|
+
import { Port } from 'beebear';
|
|
424
|
+
import type { UseCase } from 'beebear';
|
|
425
|
+
|
|
426
|
+
export interface CreateOrderInput { customerId: string; items: Item[] }
|
|
427
|
+
export interface CreateOrderOutput { orderId: string }
|
|
428
|
+
export type CreateOrderPort = UseCase<CreateOrderInput, CreateOrderOutput>;
|
|
429
|
+
export const CreateOrderPort = Port<CreateOrderPort>('CreateOrder');
|
|
430
|
+
\`\`\`
|
|
431
|
+
|
|
432
|
+
### domain/ports/outbound/
|
|
433
|
+
Driven port interfaces that define what the domain needs from infrastructure (repos,
|
|
434
|
+
services). The domain calls these; infrastructure implements them.
|
|
435
|
+
|
|
436
|
+
\`\`\`ts
|
|
437
|
+
// domain/ports/outbound/order-repository.port.ts
|
|
438
|
+
import { Port } from 'beebear';
|
|
439
|
+
|
|
440
|
+
export interface OrderRepository {
|
|
441
|
+
save(order: Order): Promise<void>;
|
|
442
|
+
findById(id: string): Promise<Order | null>;
|
|
443
|
+
}
|
|
444
|
+
export const OrderRepository = Port<OrderRepository>('OrderRepository');
|
|
445
|
+
\`\`\`
|
|
446
|
+
|
|
447
|
+
### domain/use-cases/
|
|
448
|
+
Use case classes that implement inbound ports. They receive outbound ports via
|
|
449
|
+
constructor injection and contain only business logic.
|
|
450
|
+
|
|
451
|
+
### domain/errors/
|
|
452
|
+
Custom domain error subclasses extending beebear's error hierarchy. Example:
|
|
453
|
+
\`OrderAlreadyShippedError extends ConflictError\`.
|
|
454
|
+
|
|
455
|
+
### infrastructure/persistence/
|
|
456
|
+
Driven adapter implementations for data persistence. Implements outbound repository
|
|
457
|
+
ports using Prisma, Drizzle, Mongoose, or plain SQL.
|
|
458
|
+
|
|
459
|
+
### infrastructure/http/
|
|
460
|
+
Driving adapters \u2014 Express/Fastify/Hono route files that use \`hex.httpAdapter()\` to
|
|
461
|
+
connect HTTP endpoints to use case tokens.
|
|
462
|
+
|
|
463
|
+
\`\`\`ts
|
|
464
|
+
// infrastructure/http/order.routes.ts
|
|
465
|
+
import { Router } from 'express';
|
|
466
|
+
import { CreateOrderPort } from '../../domain/ports/inbound/create-order.port';
|
|
467
|
+
|
|
468
|
+
export function orderRoutes(hex: HexApp): Router {
|
|
469
|
+
const router = Router();
|
|
470
|
+
router.post('/', hex.httpAdapter(CreateOrderPort, {
|
|
471
|
+
toInput: (req) => ({ customerId: req.body.customerId, items: req.body.items }),
|
|
472
|
+
}));
|
|
473
|
+
return router;
|
|
474
|
+
}
|
|
475
|
+
\`\`\`
|
|
476
|
+
|
|
477
|
+
### infrastructure/services/
|
|
478
|
+
Driven adapters for external services (email providers, payment gateways, etc.).
|
|
479
|
+
Implements outbound service ports.
|
|
480
|
+
|
|
481
|
+
## Key Rules
|
|
482
|
+
|
|
483
|
+
1. **domain/ never imports from infrastructure/** \u2014 dependencies point inward.
|
|
484
|
+
2. **Ports are owned by the domain** \u2014 defined in domain/ports, implemented in infrastructure.
|
|
485
|
+
3. **Use cases depend on port interfaces**, not concrete implementations.
|
|
486
|
+
4. **Container wiring** happens at the app entry point (e.g., \`main.ts\` or \`app.ts\`),
|
|
487
|
+
where you bind concrete adapters to port tokens.
|
|
488
|
+
5. **Validation middleware** (Zod, Joi) runs in infrastructure/http before \`httpAdapter\`.
|
|
489
|
+
`;
|
|
490
|
+
|
|
491
|
+
// src/resources/errors.ts
|
|
492
|
+
var ERRORS = `# beebear Error Handling
|
|
493
|
+
|
|
494
|
+
## Error Hierarchy
|
|
495
|
+
|
|
496
|
+
\`\`\`
|
|
497
|
+
Error
|
|
498
|
+
\u2514\u2500\u2500 BusinessError (base, default 400)
|
|
499
|
+
\u251C\u2500\u2500 ValidationError (400 \u2014 invalid input)
|
|
500
|
+
\u251C\u2500\u2500 NotFoundError (404 \u2014 resource not found)
|
|
501
|
+
\u251C\u2500\u2500 ConflictError (409 \u2014 state conflict)
|
|
502
|
+
\u251C\u2500\u2500 UnauthorizedError (401 \u2014 not authenticated)
|
|
503
|
+
\u2514\u2500\u2500 ForbiddenError (403 \u2014 not authorized)
|
|
504
|
+
\`\`\`
|
|
505
|
+
|
|
506
|
+
All error classes share the same constructor signature:
|
|
507
|
+
|
|
508
|
+
\`\`\`ts
|
|
509
|
+
constructor(message: string, code?: string)
|
|
510
|
+
\`\`\`
|
|
511
|
+
|
|
512
|
+
The \`code\` property defaults to a snake_case derivation of the class name (e.g.
|
|
513
|
+
\`VALIDATION_ERROR\`). The \`name\` property is set to the class name automatically.
|
|
514
|
+
|
|
515
|
+
## When to Use Each Error
|
|
516
|
+
|
|
517
|
+
| Error Class | HTTP Status | When to Throw |
|
|
518
|
+
|--------------------|-------------|------------------------------------------------------|
|
|
519
|
+
| BusinessError | 400 | General domain rule violation |
|
|
520
|
+
| ValidationError | 400 | Input fails business validation inside the use case |
|
|
521
|
+
| NotFoundError | 404 | Requested entity does not exist |
|
|
522
|
+
| ConflictError | 409 | Operation conflicts with current state (duplicates) |
|
|
523
|
+
| UnauthorizedError | 401 | Caller identity is unknown or token is invalid |
|
|
524
|
+
| ForbiddenError | 403 | Caller is authenticated but lacks permission |
|
|
525
|
+
|
|
526
|
+
## Default Error-to-Status Map
|
|
527
|
+
|
|
528
|
+
\`createHexApp\` ships with a built-in map:
|
|
529
|
+
|
|
530
|
+
\`\`\`ts
|
|
531
|
+
{
|
|
532
|
+
BusinessError: 400,
|
|
533
|
+
ValidationError: 400,
|
|
534
|
+
NotFoundError: 404,
|
|
535
|
+
ConflictError: 409,
|
|
536
|
+
UnauthorizedError: 401,
|
|
537
|
+
ForbiddenError: 403,
|
|
538
|
+
}
|
|
539
|
+
\`\`\`
|
|
540
|
+
|
|
541
|
+
Unknown errors (not in the map) result in HTTP 500.
|
|
542
|
+
|
|
543
|
+
## Custom Error Subclasses
|
|
544
|
+
|
|
545
|
+
Extend any built-in error to create domain-specific errors:
|
|
546
|
+
|
|
547
|
+
\`\`\`ts
|
|
548
|
+
import { ConflictError } from 'beebear';
|
|
549
|
+
|
|
550
|
+
export class OrderAlreadyShippedError extends ConflictError {
|
|
551
|
+
constructor(orderId: string) {
|
|
552
|
+
super(\\\`Order \\\${orderId} has already been shipped\\\`, 'ORDER_ALREADY_SHIPPED');
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
\`\`\`
|
|
556
|
+
|
|
557
|
+
Custom subclasses automatically inherit the parent's HTTP status mapping. An
|
|
558
|
+
\`OrderAlreadyShippedError\` maps to 409 because it extends \`ConflictError\`.
|
|
559
|
+
|
|
560
|
+
## Overriding the Error Map
|
|
561
|
+
|
|
562
|
+
Use the \`errorMap\` option in \`createHexApp\` to add or override mappings:
|
|
563
|
+
|
|
564
|
+
\`\`\`ts
|
|
565
|
+
import { createHexApp } from 'beebear';
|
|
566
|
+
|
|
567
|
+
const hex = createHexApp({
|
|
568
|
+
container,
|
|
569
|
+
errorMap: {
|
|
570
|
+
RateLimitError: 429,
|
|
571
|
+
PaymentRequiredError: 402,
|
|
572
|
+
// Override a built-in:
|
|
573
|
+
BusinessError: 422,
|
|
574
|
+
},
|
|
575
|
+
});
|
|
576
|
+
\`\`\`
|
|
577
|
+
|
|
578
|
+
The map key is the error class \`name\` property (the class name string). beebear checks
|
|
579
|
+
the error's prototype chain, so subclass mappings take priority over parent mappings.
|
|
580
|
+
|
|
581
|
+
## Usage in Use Cases
|
|
582
|
+
|
|
583
|
+
\`\`\`ts
|
|
584
|
+
import { NotFoundError, ValidationError } from 'beebear';
|
|
585
|
+
|
|
586
|
+
export class GetOrderUseCase implements GetOrderPort {
|
|
587
|
+
constructor(private readonly orderRepo: OrderRepository) {}
|
|
588
|
+
|
|
589
|
+
async execute(input: { orderId: string }): Promise<Order> {
|
|
590
|
+
if (!input.orderId) {
|
|
591
|
+
throw new ValidationError('orderId is required');
|
|
592
|
+
}
|
|
593
|
+
const order = await this.orderRepo.findById(input.orderId);
|
|
594
|
+
if (!order) {
|
|
595
|
+
throw new NotFoundError(\\\`Order \\\${input.orderId} not found\\\`);
|
|
596
|
+
}
|
|
597
|
+
return order;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
\`\`\`
|
|
601
|
+
|
|
602
|
+
## ExecuteResult Shape
|
|
603
|
+
|
|
604
|
+
When errors are thrown inside \`hex.execute()\` or \`hex.httpAdapter()\`, they are caught
|
|
605
|
+
and mapped:
|
|
606
|
+
|
|
607
|
+
\`\`\`ts
|
|
608
|
+
// Success
|
|
609
|
+
{ success: true, data: { orderId: '123' } }
|
|
610
|
+
|
|
611
|
+
// Error
|
|
612
|
+
{ success: false, error: { message: 'Order not found', code: 'NOT_FOUND_ERROR' }, statusCode: 404 }
|
|
613
|
+
\`\`\`
|
|
614
|
+
|
|
615
|
+
The \`httpAdapter\` sends the JSON error response with the mapped status code automatically.
|
|
616
|
+
\`hex.execute()\` returns the \`ExecuteResult\` object for you to handle programmatically.
|
|
617
|
+
`;
|
|
618
|
+
|
|
619
|
+
// src/resources/http-adapters.ts
|
|
620
|
+
var HTTP_ADAPTERS = `# beebear HTTP Adapters
|
|
621
|
+
|
|
622
|
+
## Overview
|
|
623
|
+
|
|
624
|
+
beebear uses a **strategy pattern** for HTTP framework support. The framework strategy
|
|
625
|
+
is resolved once at startup \u2014 no branching at request time. Supported built-in frameworks:
|
|
626
|
+
Express, Fastify, and Hono.
|
|
627
|
+
|
|
628
|
+
## Framework Selection
|
|
629
|
+
|
|
630
|
+
\`\`\`ts
|
|
631
|
+
import { createHexApp } from 'beebear';
|
|
632
|
+
|
|
633
|
+
// Explicit selection (recommended)
|
|
634
|
+
const hex = createHexApp({ container, framework: 'express' });
|
|
635
|
+
const hex = createHexApp({ container, framework: 'fastify' });
|
|
636
|
+
const hex = createHexApp({ container, framework: 'hono' });
|
|
637
|
+
|
|
638
|
+
// Auto-detection: beebear calls require.resolve() at startup
|
|
639
|
+
// to find which HTTP framework is installed
|
|
640
|
+
const hex = createHexApp({ container });
|
|
641
|
+
\`\`\`
|
|
642
|
+
|
|
643
|
+
## httpAdapter Usage
|
|
644
|
+
|
|
645
|
+
\`httpAdapter\` creates a framework-native request handler that extracts input, runs
|
|
646
|
+
the use case, and sends the response.
|
|
647
|
+
|
|
648
|
+
\`\`\`ts
|
|
649
|
+
interface HttpAdapterOptions<TInput> {
|
|
650
|
+
toInput: (req: any) => TInput; // always required
|
|
651
|
+
status?: number; // override default status code
|
|
652
|
+
}
|
|
653
|
+
\`\`\`
|
|
654
|
+
|
|
655
|
+
### Express Example
|
|
656
|
+
|
|
657
|
+
\`\`\`ts
|
|
658
|
+
import express from 'express';
|
|
659
|
+
import { createHexApp } from 'beebear';
|
|
660
|
+
import { CreateOrderPort } from './domain/ports/inbound/create-order.port';
|
|
661
|
+
import { GetOrderPort } from './domain/ports/inbound/get-order.port';
|
|
662
|
+
import { DeleteOrderPort } from './domain/ports/inbound/delete-order.port';
|
|
663
|
+
|
|
664
|
+
const app = express();
|
|
665
|
+
app.use(express.json());
|
|
666
|
+
|
|
667
|
+
const hex = createHexApp({ container, framework: 'express' });
|
|
668
|
+
|
|
669
|
+
app.post('/orders', hex.httpAdapter(CreateOrderPort, {
|
|
670
|
+
toInput: (req) => ({ customerId: req.body.customerId, items: req.body.items }),
|
|
671
|
+
}));
|
|
672
|
+
|
|
673
|
+
app.get('/orders/:id', hex.httpAdapter(GetOrderPort, {
|
|
674
|
+
toInput: (req) => ({ orderId: req.params.id }),
|
|
675
|
+
}));
|
|
676
|
+
|
|
677
|
+
app.delete('/orders/:id', hex.httpAdapter(DeleteOrderPort, {
|
|
678
|
+
toInput: (req) => ({ orderId: req.params.id }),
|
|
679
|
+
}));
|
|
680
|
+
\`\`\`
|
|
681
|
+
|
|
682
|
+
### Fastify Example
|
|
683
|
+
|
|
684
|
+
\`\`\`ts
|
|
685
|
+
import Fastify from 'fastify';
|
|
686
|
+
import { createHexApp } from 'beebear';
|
|
687
|
+
|
|
688
|
+
const fastify = Fastify();
|
|
689
|
+
const hex = createHexApp({ container, framework: 'fastify' });
|
|
690
|
+
|
|
691
|
+
fastify.post('/orders', hex.httpAdapter(CreateOrderPort, {
|
|
692
|
+
toInput: (req) => ({ customerId: req.body.customerId, items: req.body.items }),
|
|
693
|
+
}));
|
|
694
|
+
\`\`\`
|
|
695
|
+
|
|
696
|
+
### Hono Example
|
|
697
|
+
|
|
698
|
+
\`\`\`ts
|
|
699
|
+
import { Hono } from 'hono';
|
|
700
|
+
import { createHexApp } from 'beebear';
|
|
701
|
+
|
|
702
|
+
const app = new Hono();
|
|
703
|
+
const hex = createHexApp({ container, framework: 'hono' });
|
|
704
|
+
|
|
705
|
+
app.post('/orders', hex.httpAdapter(CreateOrderPort, {
|
|
706
|
+
toInput: (c) => ({ customerId: c.req.json().customerId }),
|
|
707
|
+
}));
|
|
708
|
+
\`\`\`
|
|
709
|
+
|
|
710
|
+
## Default Status Codes by Method
|
|
711
|
+
|
|
712
|
+
| HTTP Method | Default Status |
|
|
713
|
+
|-------------|---------------|
|
|
714
|
+
| POST | 201 |
|
|
715
|
+
| DELETE | 204 |
|
|
716
|
+
| GET | 200 |
|
|
717
|
+
| PUT | 200 |
|
|
718
|
+
| PATCH | 200 |
|
|
719
|
+
|
|
720
|
+
Override with the \`status\` option:
|
|
721
|
+
|
|
722
|
+
\`\`\`ts
|
|
723
|
+
app.post('/orders', hex.httpAdapter(CreateOrderPort, {
|
|
724
|
+
toInput: (req) => req.body,
|
|
725
|
+
status: 200, // override POST's default 201
|
|
726
|
+
}));
|
|
727
|
+
\`\`\`
|
|
728
|
+
|
|
729
|
+
## Framework-Agnostic Fallback (hex.execute)
|
|
730
|
+
|
|
731
|
+
Use \`hex.execute()\` when you need to run a use case outside of HTTP \u2014 in tests,
|
|
732
|
+
CLI scripts, message consumers, or WebSocket handlers:
|
|
733
|
+
|
|
734
|
+
\`\`\`ts
|
|
735
|
+
const result = await hex.execute(CreateOrderPort, {
|
|
736
|
+
customerId: '123',
|
|
737
|
+
items: [{ productId: 'abc', quantity: 2 }],
|
|
738
|
+
});
|
|
739
|
+
|
|
740
|
+
if (result.success) {
|
|
741
|
+
console.log('Order created:', result.data.orderId);
|
|
742
|
+
} else {
|
|
743
|
+
console.error(result.error.message, result.statusCode);
|
|
744
|
+
}
|
|
745
|
+
\`\`\`
|
|
746
|
+
|
|
747
|
+
## Custom FrameworkStrategy
|
|
748
|
+
|
|
749
|
+
Implement a custom strategy for unsupported frameworks or non-HTTP transports:
|
|
750
|
+
|
|
751
|
+
\`\`\`ts
|
|
752
|
+
import { createHexApp } from 'beebear';
|
|
753
|
+
|
|
754
|
+
const customStrategy = {
|
|
755
|
+
createHandler(core, options) {
|
|
756
|
+
// core.execute(input) runs the use case and returns ExecuteResult
|
|
757
|
+
// options.toInput extracts input from the framework's request object
|
|
758
|
+
// options.status is the desired HTTP status code
|
|
759
|
+
return async (frameworkReq, frameworkRes) => {
|
|
760
|
+
const input = options.toInput(frameworkReq);
|
|
761
|
+
const result = await core.execute(input);
|
|
762
|
+
if (result.success) {
|
|
763
|
+
frameworkRes.status(options.status).json(result.data);
|
|
764
|
+
} else {
|
|
765
|
+
frameworkRes.status(result.statusCode).json(result.error);
|
|
766
|
+
}
|
|
767
|
+
};
|
|
768
|
+
},
|
|
769
|
+
};
|
|
770
|
+
|
|
771
|
+
const hex = createHexApp({ container, framework: customStrategy });
|
|
772
|
+
\`\`\`
|
|
773
|
+
|
|
774
|
+
## Payload Validation
|
|
775
|
+
|
|
776
|
+
Structural/payload validation (Zod, Joi, etc.) happens in middleware **before**
|
|
777
|
+
\`httpAdapter\`. It is a boundary concern, not the framework's job:
|
|
778
|
+
|
|
779
|
+
\`\`\`ts
|
|
780
|
+
import { z } from 'zod';
|
|
781
|
+
|
|
782
|
+
const CreateOrderSchema = z.object({
|
|
783
|
+
customerId: z.string().uuid(),
|
|
784
|
+
items: z.array(z.object({ productId: z.string(), quantity: z.number().positive() })),
|
|
785
|
+
});
|
|
786
|
+
|
|
787
|
+
app.post('/orders',
|
|
788
|
+
(req, res, next) => {
|
|
789
|
+
const parsed = CreateOrderSchema.safeParse(req.body);
|
|
790
|
+
if (!parsed.success) return res.status(400).json(parsed.error);
|
|
791
|
+
req.body = parsed.data;
|
|
792
|
+
next();
|
|
793
|
+
},
|
|
794
|
+
hex.httpAdapter(CreateOrderPort, { toInput: (req) => req.body }),
|
|
795
|
+
);
|
|
796
|
+
\`\`\`
|
|
797
|
+
`;
|
|
798
|
+
|
|
799
|
+
// src/resources/decorators.ts
|
|
800
|
+
var DECORATORS = `# @beebear-plugins/di-decorators
|
|
801
|
+
|
|
802
|
+
## Overview
|
|
803
|
+
|
|
804
|
+
Optional decorator-based DI plugin for beebear. Provides \`@Injectable\` and \`@Inject\`
|
|
805
|
+
decorators for developers who prefer annotation-style dependency injection. Requires
|
|
806
|
+
only \`experimentalDecorators: true\` in tsconfig \u2014 no \`reflect-metadata\` needed.
|
|
807
|
+
|
|
808
|
+
## Installation
|
|
809
|
+
|
|
810
|
+
\`\`\`bash
|
|
811
|
+
npm install @beebear-plugins/di-decorators
|
|
812
|
+
\`\`\`
|
|
813
|
+
|
|
814
|
+
**tsconfig.json** \u2014 only one flag needed:
|
|
815
|
+
\`\`\`json
|
|
816
|
+
{
|
|
817
|
+
"compilerOptions": {
|
|
818
|
+
"experimentalDecorators": true
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
\`\`\`
|
|
822
|
+
|
|
823
|
+
## API
|
|
824
|
+
|
|
825
|
+
### @Injectable(token, options?)
|
|
826
|
+
|
|
827
|
+
Class decorator. Registers the class in a global registry for auto-binding.
|
|
828
|
+
|
|
829
|
+
\`\`\`ts
|
|
830
|
+
import { Injectable, Inject } from '@beebear-plugins/di-decorators';
|
|
831
|
+
import { CreateOrderPort } from '../ports/inbound/create-order.port';
|
|
832
|
+
import { OrderRepository } from '../ports/outbound/order-repository.port';
|
|
833
|
+
|
|
834
|
+
@Injectable(CreateOrderPort)
|
|
835
|
+
export class CreateOrderUseCase {
|
|
836
|
+
constructor(
|
|
837
|
+
@Inject(OrderRepository) private readonly orderRepo: OrderRepository,
|
|
838
|
+
) {}
|
|
839
|
+
|
|
840
|
+
async execute(input: CreateOrderInput): Promise<CreateOrderOutput> {
|
|
841
|
+
// domain logic
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
\`\`\`
|
|
845
|
+
|
|
846
|
+
### @Inject(token)
|
|
847
|
+
|
|
848
|
+
Parameter decorator. Marks a constructor parameter as a dependency to be resolved
|
|
849
|
+
from the container.
|
|
850
|
+
|
|
851
|
+
### withDecorators(container)
|
|
852
|
+
|
|
853
|
+
Reads the global registry populated by \`@Injectable\`, binds all registered classes
|
|
854
|
+
to the container, and returns a \`DecoratorContainer\`.
|
|
855
|
+
|
|
856
|
+
\`\`\`ts
|
|
857
|
+
import { createContainer } from 'beebear';
|
|
858
|
+
import { withDecorators } from '@beebear-plugins/di-decorators';
|
|
859
|
+
|
|
860
|
+
// Import decorated classes to trigger registration
|
|
861
|
+
import './domain/use-cases/create-order.use-case';
|
|
862
|
+
import './infrastructure/persistence/prisma-order-repository';
|
|
863
|
+
|
|
864
|
+
const baseContainer = createContainer();
|
|
865
|
+
// Bind non-decorated dependencies manually
|
|
866
|
+
baseContainer.bind(PrismaToken, () => new PrismaClient());
|
|
867
|
+
|
|
868
|
+
const container = withDecorators(baseContainer);
|
|
869
|
+
// container now has all @Injectable bindings applied
|
|
870
|
+
\`\`\`
|
|
871
|
+
|
|
872
|
+
### DecoratorContainer
|
|
873
|
+
|
|
874
|
+
Returned by \`withDecorators()\`. Provides \`resolve\`, \`has\`, \`validate\`, and
|
|
875
|
+
\`createScope\` \u2014 but **not** \`bind\`. All manual bindings must be done on the base
|
|
876
|
+
container before calling \`withDecorators\`.
|
|
877
|
+
|
|
878
|
+
\`\`\`ts
|
|
879
|
+
interface DecoratorContainer {
|
|
880
|
+
resolve<T>(token: InjectionToken<T>): T;
|
|
881
|
+
has<T>(token: InjectionToken<T>): boolean;
|
|
882
|
+
validate(): void;
|
|
883
|
+
createScope(): Container;
|
|
884
|
+
}
|
|
885
|
+
\`\`\`
|
|
886
|
+
|
|
887
|
+
### clearRegistry()
|
|
888
|
+
|
|
889
|
+
Clears the global decorator registry. Use in tests to ensure a clean state:
|
|
890
|
+
|
|
891
|
+
\`\`\`ts
|
|
892
|
+
import { clearRegistry } from '@beebear-plugins/di-decorators';
|
|
893
|
+
|
|
894
|
+
beforeEach(() => {
|
|
895
|
+
clearRegistry();
|
|
896
|
+
});
|
|
897
|
+
\`\`\`
|
|
898
|
+
|
|
899
|
+
## Lifecycle Options
|
|
900
|
+
|
|
901
|
+
Pass lifecycle as the second argument to \`@Injectable\`:
|
|
902
|
+
|
|
903
|
+
\`\`\`ts
|
|
904
|
+
@Injectable(MyToken, { lifecycle: 'transient' })
|
|
905
|
+
export class MyService { ... }
|
|
906
|
+
|
|
907
|
+
@Injectable(MyToken, { lifecycle: 'scoped' })
|
|
908
|
+
export class MyScopedService { ... }
|
|
909
|
+
|
|
910
|
+
// Default is 'singleton'
|
|
911
|
+
@Injectable(MyToken)
|
|
912
|
+
export class MySingleton { ... }
|
|
913
|
+
\`\`\`
|
|
914
|
+
|
|
915
|
+
## Complete Example
|
|
916
|
+
|
|
917
|
+
\`\`\`ts
|
|
918
|
+
// domain/ports/outbound/email-service.port.ts
|
|
919
|
+
import { Port } from 'beebear';
|
|
920
|
+
|
|
921
|
+
export interface EmailService {
|
|
922
|
+
send(to: string, subject: string, body: string): Promise<void>;
|
|
923
|
+
}
|
|
924
|
+
export const EmailService = Port<EmailService>('EmailService');
|
|
925
|
+
|
|
926
|
+
// infrastructure/services/sendgrid-email.service.ts
|
|
927
|
+
import { Injectable } from '@beebear-plugins/di-decorators';
|
|
928
|
+
import { EmailService } from '../../domain/ports/outbound/email-service.port';
|
|
929
|
+
|
|
930
|
+
@Injectable(EmailService)
|
|
931
|
+
export class SendGridEmailService implements EmailService {
|
|
932
|
+
async send(to: string, subject: string, body: string): Promise<void> {
|
|
933
|
+
// SendGrid API call
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
// main.ts
|
|
938
|
+
import { createContainer, createHexApp } from 'beebear';
|
|
939
|
+
import { withDecorators } from '@beebear-plugins/di-decorators';
|
|
940
|
+
import './infrastructure/services/sendgrid-email.service';
|
|
941
|
+
|
|
942
|
+
const container = withDecorators(createContainer());
|
|
943
|
+
container.validate();
|
|
944
|
+
|
|
945
|
+
const hex = createHexApp({ container });
|
|
946
|
+
\`\`\`
|
|
947
|
+
|
|
948
|
+
## When to Use Decorators vs Manual Binding
|
|
949
|
+
|
|
950
|
+
- **Use decorators** when you prefer annotation-style DI and want less boilerplate
|
|
951
|
+
in the wiring file.
|
|
952
|
+
- **Use manual binding** when you want full explicit control, need to avoid
|
|
953
|
+
\`experimentalDecorators\`, or are writing library code where implicit globals are
|
|
954
|
+
undesirable.
|
|
955
|
+
- You can mix both: manually bind some tokens, decorate others, then call
|
|
956
|
+
\`withDecorators()\` to merge them.
|
|
957
|
+
`;
|
|
958
|
+
|
|
959
|
+
// src/resources/ddd.ts
|
|
960
|
+
var DDD = `# @beebear-plugins/ddd
|
|
961
|
+
|
|
962
|
+
## Overview
|
|
963
|
+
|
|
964
|
+
Domain-Driven Design building blocks for beebear. Provides \`ValueObject\`, \`Entity\`,
|
|
965
|
+
\`AggregateRoot\`, and \`DomainEvent\` base classes. Zero dependencies \u2014 works standalone
|
|
966
|
+
or with beebear.
|
|
967
|
+
|
|
968
|
+
## Installation
|
|
969
|
+
|
|
970
|
+
\`\`\`bash
|
|
971
|
+
npm install @beebear-plugins/ddd
|
|
972
|
+
\`\`\`
|
|
973
|
+
|
|
974
|
+
## ValueObject<TProps>
|
|
975
|
+
|
|
976
|
+
Abstract base class for immutable objects defined by their structural properties
|
|
977
|
+
(no identity). Uses structural equality and freezes props at construction.
|
|
978
|
+
|
|
979
|
+
\`\`\`ts
|
|
980
|
+
import { ValueObject } from '@beebear-plugins/ddd';
|
|
981
|
+
|
|
982
|
+
interface MoneyProps {
|
|
983
|
+
amount: number;
|
|
984
|
+
currency: string;
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
export class Money extends ValueObject<MoneyProps> {
|
|
988
|
+
protected validate(props: MoneyProps): void {
|
|
989
|
+
if (props.amount < 0) throw new Error('Amount cannot be negative');
|
|
990
|
+
if (!props.currency) throw new Error('Currency is required');
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
get amount(): number { return this.props.amount; }
|
|
994
|
+
get currency(): string { return this.props.currency; }
|
|
995
|
+
|
|
996
|
+
add(other: Money): Money {
|
|
997
|
+
if (this.currency !== other.currency) {
|
|
998
|
+
throw new Error('Cannot add different currencies');
|
|
999
|
+
}
|
|
1000
|
+
return new Money({ amount: this.amount + other.amount, currency: this.currency });
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
const a = new Money({ amount: 100, currency: 'USD' });
|
|
1005
|
+
const b = new Money({ amount: 100, currency: 'USD' });
|
|
1006
|
+
a.equals(b); // true \u2014 structural equality
|
|
1007
|
+
\`\`\`
|
|
1008
|
+
|
|
1009
|
+
Key behaviors:
|
|
1010
|
+
- \`props\` are frozen (Object.freeze) after construction \u2014 immutable at runtime.
|
|
1011
|
+
- \`validate(props)\` hook is called during construction. Override to add rules.
|
|
1012
|
+
- \`equals(other)\` compares all props by value (deep structural equality).
|
|
1013
|
+
|
|
1014
|
+
## Entity<TId>
|
|
1015
|
+
|
|
1016
|
+
Abstract base class for objects with a unique identity. Identity-based equality.
|
|
1017
|
+
\`TId\` must be \`string\` or \`number\`.
|
|
1018
|
+
|
|
1019
|
+
\`\`\`ts
|
|
1020
|
+
import { Entity } from '@beebear-plugins/ddd';
|
|
1021
|
+
|
|
1022
|
+
export class User extends Entity<string> {
|
|
1023
|
+
constructor(
|
|
1024
|
+
id: string,
|
|
1025
|
+
private _name: string,
|
|
1026
|
+
private _email: string,
|
|
1027
|
+
) {
|
|
1028
|
+
super(id);
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
get name(): string { return this._name; }
|
|
1032
|
+
get email(): string { return this._email; }
|
|
1033
|
+
|
|
1034
|
+
changeName(name: string): void {
|
|
1035
|
+
if (!name.trim()) throw new Error('Name cannot be empty');
|
|
1036
|
+
this._name = name;
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
const user1 = new User('abc', 'Alice', 'alice@example.com');
|
|
1041
|
+
const user2 = new User('abc', 'Alice Updated', 'alice@example.com');
|
|
1042
|
+
user1.equals(user2); // true \u2014 same id
|
|
1043
|
+
\`\`\`
|
|
1044
|
+
|
|
1045
|
+
Key behaviors:
|
|
1046
|
+
- \`id\` is set via \`super(id)\` and made runtime-immutable using \`Object.defineProperty\`.
|
|
1047
|
+
- \`equals(other)\` compares by \`id\` only, ignoring other properties.
|
|
1048
|
+
|
|
1049
|
+
## AggregateRoot<TId>
|
|
1050
|
+
|
|
1051
|
+
Extends \`Entity\` with domain event support. An aggregate root is the entry point
|
|
1052
|
+
for a cluster of related entities and value objects.
|
|
1053
|
+
|
|
1054
|
+
\`\`\`ts
|
|
1055
|
+
import { AggregateRoot } from '@beebear-plugins/ddd';
|
|
1056
|
+
|
|
1057
|
+
export class Order extends AggregateRoot<string> {
|
|
1058
|
+
private items: OrderItem[] = [];
|
|
1059
|
+
private _status: OrderStatus = 'draft';
|
|
1060
|
+
|
|
1061
|
+
get status(): OrderStatus { return this._status; }
|
|
1062
|
+
|
|
1063
|
+
addItem(productId: string, quantity: number): void {
|
|
1064
|
+
this.items.push(new OrderItem(productId, quantity));
|
|
1065
|
+
this.addEvent(new OrderItemAdded(this.id, productId, quantity));
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
submit(): void {
|
|
1069
|
+
if (this.items.length === 0) throw new Error('Cannot submit empty order');
|
|
1070
|
+
this._status = 'submitted';
|
|
1071
|
+
this.addEvent(new OrderSubmitted(this.id));
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
const order = new Order('order-1');
|
|
1076
|
+
order.addItem('prod-1', 2);
|
|
1077
|
+
order.submit();
|
|
1078
|
+
|
|
1079
|
+
const events = order.getEvents(); // [OrderItemAdded, OrderSubmitted]
|
|
1080
|
+
order.clearEvents(); // clears the internal event list
|
|
1081
|
+
\`\`\`
|
|
1082
|
+
|
|
1083
|
+
Key behaviors:
|
|
1084
|
+
- \`addEvent(event)\` is protected \u2014 only the aggregate itself can record events.
|
|
1085
|
+
- \`getEvents()\` returns all uncommitted domain events.
|
|
1086
|
+
- \`clearEvents()\` is called after events have been dispatched/persisted.
|
|
1087
|
+
|
|
1088
|
+
## DomainEvent
|
|
1089
|
+
|
|
1090
|
+
Abstract base class for domain events. All fields are runtime-immutable.
|
|
1091
|
+
|
|
1092
|
+
\`\`\`ts
|
|
1093
|
+
import { DomainEvent } from '@beebear-plugins/ddd';
|
|
1094
|
+
|
|
1095
|
+
export class OrderSubmitted extends DomainEvent {
|
|
1096
|
+
readonly eventName = 'OrderSubmitted';
|
|
1097
|
+
|
|
1098
|
+
constructor(aggregateId: string) {
|
|
1099
|
+
super(aggregateId);
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
const event = new OrderSubmitted('order-1');
|
|
1104
|
+
event.eventName; // 'OrderSubmitted'
|
|
1105
|
+
event.aggregateId; // 'order-1'
|
|
1106
|
+
event.occurredAt; // Date (auto-set at construction)
|
|
1107
|
+
\`\`\`
|
|
1108
|
+
|
|
1109
|
+
Key behaviors:
|
|
1110
|
+
- \`eventName\` \u2014 abstract, must be defined by subclass.
|
|
1111
|
+
- \`aggregateId\` \u2014 the id of the aggregate that raised the event.
|
|
1112
|
+
- \`occurredAt\` \u2014 timestamp, defaults to \`new Date()\`. Accepts \`Date\`, \`string\`, or \`number\`.
|
|
1113
|
+
- Optional \`timestampFactory\` parameter in constructor for deterministic testing.
|
|
1114
|
+
- All fields are made runtime-immutable after construction.
|
|
1115
|
+
|
|
1116
|
+
## Using with beebear
|
|
1117
|
+
|
|
1118
|
+
The DDD plugin is standalone but integrates naturally with beebear's architecture:
|
|
1119
|
+
|
|
1120
|
+
\`\`\`ts
|
|
1121
|
+
// domain/models/order.ts \u2014 uses @beebear-plugins/ddd
|
|
1122
|
+
import { AggregateRoot } from '@beebear-plugins/ddd';
|
|
1123
|
+
|
|
1124
|
+
export class Order extends AggregateRoot<string> { /* ... */ }
|
|
1125
|
+
|
|
1126
|
+
// domain/use-cases/submit-order.use-case.ts \u2014 uses beebear
|
|
1127
|
+
import type { UseCase } from 'beebear';
|
|
1128
|
+
import { NotFoundError } from 'beebear';
|
|
1129
|
+
import type { OrderRepository } from '../ports/outbound/order-repository.port';
|
|
1130
|
+
|
|
1131
|
+
export class SubmitOrderUseCase implements UseCase<{ orderId: string }, void> {
|
|
1132
|
+
constructor(private readonly orderRepo: OrderRepository) {}
|
|
1133
|
+
|
|
1134
|
+
async execute(input: { orderId: string }): Promise<void> {
|
|
1135
|
+
const order = await this.orderRepo.findById(input.orderId);
|
|
1136
|
+
if (!order) throw new NotFoundError('Order not found');
|
|
1137
|
+
order.submit();
|
|
1138
|
+
await this.orderRepo.save(order);
|
|
1139
|
+
// Dispatch order.getEvents() via event bus, then order.clearEvents()
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
\`\`\`
|
|
1143
|
+
`;
|
|
1144
|
+
|
|
1145
|
+
// src/resources/index.ts
|
|
1146
|
+
var resources = [
|
|
1147
|
+
{ name: "overview", uri: "beebear://docs/overview", content: OVERVIEW },
|
|
1148
|
+
{ name: "api", uri: "beebear://docs/api", content: API },
|
|
1149
|
+
{ name: "patterns", uri: "beebear://docs/patterns", content: PATTERNS },
|
|
1150
|
+
{ name: "project-structure", uri: "beebear://docs/project-structure", content: PROJECT_STRUCTURE },
|
|
1151
|
+
{ name: "errors", uri: "beebear://docs/errors", content: ERRORS },
|
|
1152
|
+
{ name: "http-adapters", uri: "beebear://docs/http-adapters", content: HTTP_ADAPTERS },
|
|
1153
|
+
{ name: "decorators", uri: "beebear://docs/decorators", content: DECORATORS },
|
|
1154
|
+
{ name: "ddd", uri: "beebear://docs/ddd", content: DDD }
|
|
1155
|
+
];
|
|
1156
|
+
function registerResources(server2) {
|
|
1157
|
+
for (const res of resources) {
|
|
1158
|
+
server2.registerResource(res.name, res.uri, { mimeType: "text/markdown" }, async () => ({
|
|
1159
|
+
contents: [{ uri: res.uri, mimeType: "text/markdown", text: res.content }]
|
|
1160
|
+
}));
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
// src/tools/scaffold-port.ts
|
|
1165
|
+
import { z } from "zod";
|
|
1166
|
+
|
|
1167
|
+
// src/tools/helpers.ts
|
|
1168
|
+
function isPascalCase(name) {
|
|
1169
|
+
return /^[A-Z][a-zA-Z0-9]*$/.test(name);
|
|
1170
|
+
}
|
|
1171
|
+
function makeErrorResult(message) {
|
|
1172
|
+
return {
|
|
1173
|
+
content: [{ type: "text", text: message }],
|
|
1174
|
+
isError: true
|
|
1175
|
+
};
|
|
1176
|
+
}
|
|
1177
|
+
function makeSuccessResult(code) {
|
|
1178
|
+
return {
|
|
1179
|
+
content: [{ type: "text", text: code }]
|
|
1180
|
+
};
|
|
1181
|
+
}
|
|
1182
|
+
function buildImportLines(imports) {
|
|
1183
|
+
return imports.map(({ names, from, typeOnly }) => {
|
|
1184
|
+
const keyword = typeOnly ? "import type" : "import";
|
|
1185
|
+
return `${keyword} { ${names.join(", ")} } from '${from}';`;
|
|
1186
|
+
}).join("\n");
|
|
1187
|
+
}
|
|
1188
|
+
function generateMethodStubs(methods) {
|
|
1189
|
+
return methods.map((m) => {
|
|
1190
|
+
const isAsync = m.returnType.startsWith("Promise");
|
|
1191
|
+
const prefix = isAsync ? "async " : "";
|
|
1192
|
+
return [
|
|
1193
|
+
` ${prefix}${m.name}(${m.params}): ${m.returnType} {`,
|
|
1194
|
+
` // TODO: implement`,
|
|
1195
|
+
` throw new Error('Not implemented');`,
|
|
1196
|
+
` }`
|
|
1197
|
+
].join("\n");
|
|
1198
|
+
}).join("\n\n");
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
// src/tools/scaffold-port.ts
|
|
1202
|
+
var scaffoldPortSchema = {
|
|
1203
|
+
name: z.string().describe('PascalCase port name, e.g. "UserRepository"'),
|
|
1204
|
+
direction: z.enum(["inbound", "outbound"]).describe("inbound = use case port, outbound = dependency port"),
|
|
1205
|
+
inputType: z.string().optional().describe('For inbound: use case input type, e.g. "{ email: string }"'),
|
|
1206
|
+
outputType: z.string().optional().describe('For inbound: use case output type, e.g. "{ id: string }"'),
|
|
1207
|
+
methods: z.array(z.object({
|
|
1208
|
+
name: z.string(),
|
|
1209
|
+
params: z.string(),
|
|
1210
|
+
returnType: z.string()
|
|
1211
|
+
})).optional().describe("For outbound: port methods")
|
|
1212
|
+
};
|
|
1213
|
+
function scaffoldPort(input) {
|
|
1214
|
+
if (input.direction === "inbound") {
|
|
1215
|
+
const inputType = input.inputType ?? "void";
|
|
1216
|
+
const outputType = input.outputType ?? "void";
|
|
1217
|
+
const imports2 = buildImportLines([
|
|
1218
|
+
{ names: ["Port"], from: "beebear" },
|
|
1219
|
+
{ names: ["UseCase"], from: "beebear", typeOnly: true }
|
|
1220
|
+
]);
|
|
1221
|
+
return `${imports2}
|
|
1222
|
+
|
|
1223
|
+
export interface ${input.name} extends UseCase<${inputType}, ${outputType}> {}
|
|
1224
|
+
|
|
1225
|
+
export const ${input.name} = Port<${input.name}>('${input.name}');
|
|
1226
|
+
`;
|
|
1227
|
+
}
|
|
1228
|
+
const imports = buildImportLines([
|
|
1229
|
+
{ names: ["Port"], from: "beebear" }
|
|
1230
|
+
]);
|
|
1231
|
+
const methods = (input.methods ?? []).map((m) => ` ${m.name}(${m.params}): ${m.returnType};`).join("\n");
|
|
1232
|
+
return `${imports}
|
|
1233
|
+
|
|
1234
|
+
export interface ${input.name} {
|
|
1235
|
+
${methods}
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
export const ${input.name} = Port<${input.name}>('${input.name}');
|
|
1239
|
+
`;
|
|
1240
|
+
}
|
|
1241
|
+
function handleScaffoldPort(input) {
|
|
1242
|
+
if (!isPascalCase(input.name)) {
|
|
1243
|
+
return makeErrorResult(`Port name "${input.name}" must be PascalCase (e.g. "UserRepository")`);
|
|
1244
|
+
}
|
|
1245
|
+
if (input.direction === "outbound" && (!input.methods || input.methods.length === 0)) {
|
|
1246
|
+
return makeErrorResult("Outbound ports require at least one method");
|
|
1247
|
+
}
|
|
1248
|
+
return makeSuccessResult(scaffoldPort(input));
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
// src/tools/scaffold-use-case.ts
|
|
1252
|
+
import { z as z2 } from "zod";
|
|
1253
|
+
var scaffoldUseCaseSchema = {
|
|
1254
|
+
name: z2.string().describe('PascalCase class name, e.g. "RegisterUserService"'),
|
|
1255
|
+
port: z2.string().describe('The inbound port it implements, e.g. "RegisterUser"'),
|
|
1256
|
+
inputType: z2.string().describe('Use case input type, e.g. "{ email: string; name: string }"'),
|
|
1257
|
+
outputType: z2.string().describe('Use case output type, e.g. "{ id: string }"'),
|
|
1258
|
+
dependencies: z2.array(z2.object({
|
|
1259
|
+
name: z2.string().describe('Parameter name, e.g. "userRepository"'),
|
|
1260
|
+
type: z2.string().describe('Port type name, e.g. "UserRepository"')
|
|
1261
|
+
})).optional().describe("Constructor dependencies (driven ports)")
|
|
1262
|
+
};
|
|
1263
|
+
function scaffoldUseCase(input) {
|
|
1264
|
+
const deps = input.dependencies ?? [];
|
|
1265
|
+
const typeImports = [input.port];
|
|
1266
|
+
for (const dep of deps) {
|
|
1267
|
+
if (!typeImports.includes(dep.type)) {
|
|
1268
|
+
typeImports.push(dep.type);
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
const imports = buildImportLines([
|
|
1272
|
+
{ names: typeImports, from: "beebear", typeOnly: true }
|
|
1273
|
+
]);
|
|
1274
|
+
const ctorParams = deps.map((d) => ` private readonly ${d.name}: ${d.type},`).join("\n");
|
|
1275
|
+
const ctor = deps.length > 0 ? `
|
|
1276
|
+
constructor(
|
|
1277
|
+
${ctorParams}
|
|
1278
|
+
) {}
|
|
1279
|
+
` : "";
|
|
1280
|
+
return `${imports}
|
|
1281
|
+
|
|
1282
|
+
export class ${input.name} implements ${input.port} {${ctor}
|
|
1283
|
+
async execute(input: ${input.inputType}): Promise<${input.outputType}> {
|
|
1284
|
+
// TODO: implement business logic
|
|
1285
|
+
throw new Error('Not implemented');
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
`;
|
|
1289
|
+
}
|
|
1290
|
+
function handleScaffoldUseCase(input) {
|
|
1291
|
+
if (!isPascalCase(input.name)) {
|
|
1292
|
+
return makeErrorResult(`Class name "${input.name}" must be PascalCase`);
|
|
1293
|
+
}
|
|
1294
|
+
if (!isPascalCase(input.port)) {
|
|
1295
|
+
return makeErrorResult(`Port name "${input.port}" must be PascalCase`);
|
|
1296
|
+
}
|
|
1297
|
+
return makeSuccessResult(scaffoldUseCase(input));
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
// src/tools/scaffold-adapter.ts
|
|
1301
|
+
import { z as z3 } from "zod";
|
|
1302
|
+
var scaffoldAdapterSchema = {
|
|
1303
|
+
name: z3.string().describe('PascalCase class name, e.g. "PrismaUserRepository"'),
|
|
1304
|
+
port: z3.string().describe('The outbound port it implements, e.g. "UserRepository"'),
|
|
1305
|
+
methods: z3.array(z3.object({
|
|
1306
|
+
name: z3.string(),
|
|
1307
|
+
params: z3.string(),
|
|
1308
|
+
returnType: z3.string()
|
|
1309
|
+
})).describe("Methods to implement")
|
|
1310
|
+
};
|
|
1311
|
+
function scaffoldAdapter(input) {
|
|
1312
|
+
const imports = buildImportLines([
|
|
1313
|
+
{ names: [input.port], from: "beebear", typeOnly: true }
|
|
1314
|
+
]);
|
|
1315
|
+
const methods = generateMethodStubs(input.methods);
|
|
1316
|
+
return `${imports}
|
|
1317
|
+
|
|
1318
|
+
export class ${input.name} implements ${input.port} {
|
|
1319
|
+
${methods}
|
|
1320
|
+
}
|
|
1321
|
+
`;
|
|
1322
|
+
}
|
|
1323
|
+
function handleScaffoldAdapter(input) {
|
|
1324
|
+
if (!isPascalCase(input.name)) {
|
|
1325
|
+
return makeErrorResult(`Class name "${input.name}" must be PascalCase`);
|
|
1326
|
+
}
|
|
1327
|
+
if (!isPascalCase(input.port)) {
|
|
1328
|
+
return makeErrorResult(`Port name "${input.port}" must be PascalCase`);
|
|
1329
|
+
}
|
|
1330
|
+
if (input.methods.length === 0) {
|
|
1331
|
+
return makeErrorResult("Adapter requires at least one method");
|
|
1332
|
+
}
|
|
1333
|
+
return makeSuccessResult(scaffoldAdapter(input));
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
// src/tools/scaffold-route.ts
|
|
1337
|
+
import { z as z4 } from "zod";
|
|
1338
|
+
var scaffoldRouteSchema = {
|
|
1339
|
+
useCaseToken: z4.string().describe('Use case port name, e.g. "RegisterUser"'),
|
|
1340
|
+
method: z4.string().describe('HTTP method, e.g. "POST"'),
|
|
1341
|
+
path: z4.string().describe('Route path, e.g. "/users"'),
|
|
1342
|
+
inputMapping: z4.string().describe('Input mapping expression, e.g. "{ email: req.body.email }"'),
|
|
1343
|
+
statusOverride: z4.number().optional().describe("Custom HTTP status (overrides method default)")
|
|
1344
|
+
};
|
|
1345
|
+
function scaffoldRoute(input) {
|
|
1346
|
+
const method = input.method.toLowerCase();
|
|
1347
|
+
const statusOpt = input.statusOverride != null ? `
|
|
1348
|
+
status: ${input.statusOverride},` : "";
|
|
1349
|
+
return `app.${method}('${input.path}', hex.httpAdapter(${input.useCaseToken}, {
|
|
1350
|
+
toInput: (req) => (${input.inputMapping}),${statusOpt}
|
|
1351
|
+
}));
|
|
1352
|
+
`;
|
|
1353
|
+
}
|
|
1354
|
+
function handleScaffoldRoute(input) {
|
|
1355
|
+
if (!isPascalCase(input.useCaseToken)) {
|
|
1356
|
+
return makeErrorResult(`Use case token "${input.useCaseToken}" must be PascalCase`);
|
|
1357
|
+
}
|
|
1358
|
+
return makeSuccessResult(scaffoldRoute(input));
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
// src/tools/scaffold-container-setup.ts
|
|
1362
|
+
import { z as z5 } from "zod";
|
|
1363
|
+
var scaffoldContainerSetupSchema = {
|
|
1364
|
+
bindings: z5.array(z5.object({
|
|
1365
|
+
token: z5.string().describe('Port/token name, e.g. "UserRepository"'),
|
|
1366
|
+
implementation: z5.string().describe('Implementation class name, e.g. "PrismaUserRepository"'),
|
|
1367
|
+
dependencies: z5.array(z5.string()).optional().describe("Token names to resolve as constructor args")
|
|
1368
|
+
})).describe("Bindings to generate")
|
|
1369
|
+
};
|
|
1370
|
+
function scaffoldContainerSetup(input) {
|
|
1371
|
+
const tokenImports = /* @__PURE__ */ new Set();
|
|
1372
|
+
const implImports = /* @__PURE__ */ new Set();
|
|
1373
|
+
for (const b of input.bindings) {
|
|
1374
|
+
tokenImports.add(b.token);
|
|
1375
|
+
implImports.add(b.implementation);
|
|
1376
|
+
for (const dep of b.dependencies ?? []) {
|
|
1377
|
+
tokenImports.add(dep);
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
const lines = [];
|
|
1381
|
+
lines.push(`import { createContainer } from 'beebear';`);
|
|
1382
|
+
for (const token of tokenImports) {
|
|
1383
|
+
lines.push(`import { ${token} } from './domain/ports/${token}.js';`);
|
|
1384
|
+
}
|
|
1385
|
+
for (const impl of implImports) {
|
|
1386
|
+
lines.push(`import { ${impl} } from './infrastructure/${impl}.js';`);
|
|
1387
|
+
}
|
|
1388
|
+
lines.push("");
|
|
1389
|
+
lines.push("const container = createContainer();");
|
|
1390
|
+
lines.push("");
|
|
1391
|
+
for (const b of input.bindings) {
|
|
1392
|
+
const deps = b.dependencies ?? [];
|
|
1393
|
+
if (deps.length === 0) {
|
|
1394
|
+
lines.push(`container.bind(${b.token}, () => new ${b.implementation}());`);
|
|
1395
|
+
} else {
|
|
1396
|
+
const resolves = deps.map((d) => ` container.resolve(${d}),`).join("\n");
|
|
1397
|
+
lines.push(`container.bind(${b.token}, (c) => new ${b.implementation}(
|
|
1398
|
+
${resolves}
|
|
1399
|
+
));`);
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
lines.push("");
|
|
1403
|
+
lines.push("container.validate();");
|
|
1404
|
+
lines.push("");
|
|
1405
|
+
lines.push("export { container };");
|
|
1406
|
+
lines.push("");
|
|
1407
|
+
return lines.join("\n");
|
|
1408
|
+
}
|
|
1409
|
+
function handleScaffoldContainerSetup(input) {
|
|
1410
|
+
if (input.bindings.length === 0) {
|
|
1411
|
+
return makeErrorResult("At least one binding is required");
|
|
1412
|
+
}
|
|
1413
|
+
for (const b of input.bindings) {
|
|
1414
|
+
if (!isPascalCase(b.token)) {
|
|
1415
|
+
return makeErrorResult(`Token "${b.token}" must be PascalCase`);
|
|
1416
|
+
}
|
|
1417
|
+
if (!isPascalCase(b.implementation)) {
|
|
1418
|
+
return makeErrorResult(`Implementation "${b.implementation}" must be PascalCase`);
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
return makeSuccessResult(scaffoldContainerSetup(input));
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
// src/tools/scaffold-entity.ts
|
|
1425
|
+
import { z as z6 } from "zod";
|
|
1426
|
+
var scaffoldEntitySchema = {
|
|
1427
|
+
name: z6.string().describe('PascalCase entity name, e.g. "OrderItem"'),
|
|
1428
|
+
idType: z6.enum(["string", "number"]).describe("Type of the entity ID"),
|
|
1429
|
+
properties: z6.array(z6.object({
|
|
1430
|
+
name: z6.string(),
|
|
1431
|
+
type: z6.string(),
|
|
1432
|
+
readonly: z6.boolean().optional()
|
|
1433
|
+
})).optional().describe("Entity properties")
|
|
1434
|
+
};
|
|
1435
|
+
function scaffoldEntity(input) {
|
|
1436
|
+
const imports = buildImportLines([
|
|
1437
|
+
{ names: ["Entity"], from: "@beebear-plugins/ddd" }
|
|
1438
|
+
]);
|
|
1439
|
+
const props = input.properties ?? [];
|
|
1440
|
+
const ctorParams = [
|
|
1441
|
+
` id: ${input.idType},`,
|
|
1442
|
+
...props.map((p) => {
|
|
1443
|
+
const mod = p.readonly ? "readonly " : "";
|
|
1444
|
+
return ` public ${mod}${p.name}: ${p.type},`;
|
|
1445
|
+
})
|
|
1446
|
+
].join("\n");
|
|
1447
|
+
return `${imports}
|
|
1448
|
+
|
|
1449
|
+
export class ${input.name} extends Entity<${input.idType}> {
|
|
1450
|
+
constructor(
|
|
1451
|
+
${ctorParams}
|
|
1452
|
+
) {
|
|
1453
|
+
super(id);
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
`;
|
|
1457
|
+
}
|
|
1458
|
+
function handleScaffoldEntity(input) {
|
|
1459
|
+
if (!isPascalCase(input.name)) {
|
|
1460
|
+
return makeErrorResult(`Entity name "${input.name}" must be PascalCase`);
|
|
1461
|
+
}
|
|
1462
|
+
return makeSuccessResult(scaffoldEntity(input));
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
// src/tools/scaffold-value-object.ts
|
|
1466
|
+
import { z as z7 } from "zod";
|
|
1467
|
+
var scaffoldValueObjectSchema = {
|
|
1468
|
+
name: z7.string().describe('PascalCase name, e.g. "Money"'),
|
|
1469
|
+
props: z7.array(z7.object({
|
|
1470
|
+
name: z7.string(),
|
|
1471
|
+
type: z7.string()
|
|
1472
|
+
})).describe("Value object properties"),
|
|
1473
|
+
validationRules: z7.array(z7.string()).optional().describe("Validation rules as human-readable strings")
|
|
1474
|
+
};
|
|
1475
|
+
function scaffoldValueObject(input) {
|
|
1476
|
+
const imports = buildImportLines([
|
|
1477
|
+
{ names: ["ValueObject"], from: "@beebear-plugins/ddd" }
|
|
1478
|
+
]);
|
|
1479
|
+
const propsInterface = `${input.name}Props`;
|
|
1480
|
+
const propLines = input.props.map((p) => ` ${p.name}: ${p.type};`).join("\n");
|
|
1481
|
+
const getters = input.props.map((p) => ` get ${p.name}() { return this.props.${p.name}; }`).join("\n");
|
|
1482
|
+
const rules = input.validationRules ?? [];
|
|
1483
|
+
const validateBody = rules.length > 0 ? rules.map((r) => ` // TODO: ${r}`).join("\n") : " // TODO: add validation rules";
|
|
1484
|
+
return `${imports}
|
|
1485
|
+
|
|
1486
|
+
interface ${propsInterface} {
|
|
1487
|
+
${propLines}
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
export class ${input.name} extends ValueObject<${propsInterface}> {
|
|
1491
|
+
protected validate(props: ${propsInterface}) {
|
|
1492
|
+
${validateBody}
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
${getters}
|
|
1496
|
+
}
|
|
1497
|
+
`;
|
|
1498
|
+
}
|
|
1499
|
+
function handleScaffoldValueObject(input) {
|
|
1500
|
+
if (!isPascalCase(input.name)) {
|
|
1501
|
+
return makeErrorResult(`Value object name "${input.name}" must be PascalCase`);
|
|
1502
|
+
}
|
|
1503
|
+
if (input.props.length === 0) {
|
|
1504
|
+
return makeErrorResult("Value object requires at least one property");
|
|
1505
|
+
}
|
|
1506
|
+
return makeSuccessResult(scaffoldValueObject(input));
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
// src/tools/scaffold-aggregate.ts
|
|
1510
|
+
import { z as z8 } from "zod";
|
|
1511
|
+
var scaffoldAggregateSchema = {
|
|
1512
|
+
name: z8.string().describe('PascalCase aggregate name, e.g. "Order"'),
|
|
1513
|
+
idType: z8.enum(["string", "number"]).describe("Type of the aggregate ID"),
|
|
1514
|
+
events: z8.array(z8.object({
|
|
1515
|
+
name: z8.string().describe('Event class name, e.g. "OrderPlaced"'),
|
|
1516
|
+
fields: z8.array(z8.object({
|
|
1517
|
+
name: z8.string(),
|
|
1518
|
+
type: z8.string()
|
|
1519
|
+
})).optional().describe("Event-specific fields")
|
|
1520
|
+
})).optional().describe("Domain events emitted by this aggregate")
|
|
1521
|
+
};
|
|
1522
|
+
function scaffoldAggregate(input) {
|
|
1523
|
+
const imports = buildImportLines([
|
|
1524
|
+
{ names: ["AggregateRoot", "DomainEvent"], from: "@beebear-plugins/ddd" }
|
|
1525
|
+
]);
|
|
1526
|
+
const events = input.events ?? [];
|
|
1527
|
+
const eventClasses = events.map((event) => {
|
|
1528
|
+
const fields = event.fields ?? [];
|
|
1529
|
+
const ctorFields = fields.map((f) => `readonly ${f.name}: ${f.type}`).join(", ");
|
|
1530
|
+
const ctorParams = ctorFields ? `${input.name.toLowerCase()}Id: ${input.idType}, ${ctorFields}` : `${input.name.toLowerCase()}Id: ${input.idType}`;
|
|
1531
|
+
return `export class ${event.name} extends DomainEvent {
|
|
1532
|
+
constructor(${ctorParams}) {
|
|
1533
|
+
super('${event.name}', ${input.name.toLowerCase()}Id);
|
|
1534
|
+
}
|
|
1535
|
+
}`;
|
|
1536
|
+
});
|
|
1537
|
+
const methods = events.map((event) => {
|
|
1538
|
+
const methodName = event.name.charAt(0).toLowerCase() + event.name.slice(1);
|
|
1539
|
+
const fields = event.fields ?? [];
|
|
1540
|
+
const params = fields.map((f) => `${f.name}: ${f.type}`).join(", ");
|
|
1541
|
+
const args = [
|
|
1542
|
+
`this.id`,
|
|
1543
|
+
...fields.map((f) => f.name)
|
|
1544
|
+
].join(", ");
|
|
1545
|
+
return ` ${methodName}(${params}) {
|
|
1546
|
+
// TODO: enforce invariants
|
|
1547
|
+
this.addEvent(new ${event.name}(${args}));
|
|
1548
|
+
}`;
|
|
1549
|
+
});
|
|
1550
|
+
const methodsBlock = methods.length > 0 ? "\n" + methods.join("\n\n") + "\n" : "\n // TODO: add domain methods that emit events via this.addEvent()\n";
|
|
1551
|
+
return `${imports}
|
|
1552
|
+
|
|
1553
|
+
${eventClasses.join("\n\n")}
|
|
1554
|
+
|
|
1555
|
+
export class ${input.name} extends AggregateRoot<${input.idType}> {${methodsBlock}}
|
|
1556
|
+
`;
|
|
1557
|
+
}
|
|
1558
|
+
function handleScaffoldAggregate(input) {
|
|
1559
|
+
if (!isPascalCase(input.name)) {
|
|
1560
|
+
return makeErrorResult(`Aggregate name "${input.name}" must be PascalCase`);
|
|
1561
|
+
}
|
|
1562
|
+
for (const event of input.events ?? []) {
|
|
1563
|
+
if (!isPascalCase(event.name)) {
|
|
1564
|
+
return makeErrorResult(`Event name "${event.name}" must be PascalCase`);
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
return makeSuccessResult(scaffoldAggregate(input));
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
// src/tools/scaffold-event-publisher.ts
|
|
1571
|
+
import { z as z9 } from "zod";
|
|
1572
|
+
var scaffoldEventPublisherSchema = {
|
|
1573
|
+
transport: z9.enum(["rabbitmq", "kafka", "sqs", "outbox"]).describe("Message transport for event publishing")
|
|
1574
|
+
};
|
|
1575
|
+
function generatePort() {
|
|
1576
|
+
const imports = buildImportLines([
|
|
1577
|
+
{ names: ["Port"], from: "beebear" },
|
|
1578
|
+
{ names: ["DomainEvent"], from: "@beebear-plugins/ddd", typeOnly: true }
|
|
1579
|
+
]);
|
|
1580
|
+
return `${imports}
|
|
1581
|
+
|
|
1582
|
+
export interface EventPublisher {
|
|
1583
|
+
publish(events: ReadonlyArray<DomainEvent>): Promise<void>;
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
export const EventPublisher = Port<EventPublisher>('EventPublisher');
|
|
1587
|
+
`;
|
|
1588
|
+
}
|
|
1589
|
+
var ADAPTERS = {
|
|
1590
|
+
rabbitmq: `import type { EventPublisher } from '../../domain/ports/EventPublisher.js';
|
|
1591
|
+
import type { DomainEvent } from '@beebear-plugins/ddd';
|
|
1592
|
+
|
|
1593
|
+
export class RabbitMQEventPublisher implements EventPublisher {
|
|
1594
|
+
constructor(private channel: any) {}
|
|
1595
|
+
|
|
1596
|
+
async publish(events: ReadonlyArray<DomainEvent>) {
|
|
1597
|
+
for (const event of events) {
|
|
1598
|
+
await this.channel.publish(
|
|
1599
|
+
'events',
|
|
1600
|
+
event.eventName,
|
|
1601
|
+
Buffer.from(JSON.stringify(event)),
|
|
1602
|
+
);
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
`,
|
|
1607
|
+
kafka: `import type { EventPublisher } from '../../domain/ports/EventPublisher.js';
|
|
1608
|
+
import type { DomainEvent } from '@beebear-plugins/ddd';
|
|
1609
|
+
|
|
1610
|
+
export class KafkaEventPublisher implements EventPublisher {
|
|
1611
|
+
constructor(private producer: any) {}
|
|
1612
|
+
|
|
1613
|
+
async publish(events: ReadonlyArray<DomainEvent>) {
|
|
1614
|
+
await this.producer.sendBatch({
|
|
1615
|
+
topicMessages: events.map((event) => ({
|
|
1616
|
+
topic: event.eventName,
|
|
1617
|
+
messages: [{
|
|
1618
|
+
key: String(event.aggregateId),
|
|
1619
|
+
value: JSON.stringify(event),
|
|
1620
|
+
}],
|
|
1621
|
+
})),
|
|
1622
|
+
});
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
`,
|
|
1626
|
+
sqs: `import type { EventPublisher } from '../../domain/ports/EventPublisher.js';
|
|
1627
|
+
import type { DomainEvent } from '@beebear-plugins/ddd';
|
|
1628
|
+
|
|
1629
|
+
export class SQSEventPublisher implements EventPublisher {
|
|
1630
|
+
constructor(private sqs: any, private queueUrl: string) {}
|
|
1631
|
+
|
|
1632
|
+
async publish(events: ReadonlyArray<DomainEvent>) {
|
|
1633
|
+
for (const event of events) {
|
|
1634
|
+
await this.sqs.sendMessage({
|
|
1635
|
+
QueueUrl: this.queueUrl,
|
|
1636
|
+
MessageBody: JSON.stringify(event),
|
|
1637
|
+
MessageAttributes: {
|
|
1638
|
+
eventName: { DataType: 'String', StringValue: event.eventName },
|
|
1639
|
+
},
|
|
1640
|
+
});
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
`,
|
|
1645
|
+
outbox: `import type { EventPublisher } from '../../domain/ports/EventPublisher.js';
|
|
1646
|
+
import type { DomainEvent } from '@beebear-plugins/ddd';
|
|
1647
|
+
|
|
1648
|
+
export class OutboxEventPublisher implements EventPublisher {
|
|
1649
|
+
constructor(private db: any) {}
|
|
1650
|
+
|
|
1651
|
+
async publish(events: ReadonlyArray<DomainEvent>) {
|
|
1652
|
+
await this.db.outboxEvents.insertMany(
|
|
1653
|
+
events.map((e) => ({
|
|
1654
|
+
eventName: e.eventName,
|
|
1655
|
+
aggregateId: String(e.aggregateId),
|
|
1656
|
+
payload: JSON.stringify(e),
|
|
1657
|
+
occurredAt: e.occurredAt,
|
|
1658
|
+
published: false,
|
|
1659
|
+
})),
|
|
1660
|
+
);
|
|
1661
|
+
}
|
|
1662
|
+
}
|
|
1663
|
+
`
|
|
1664
|
+
};
|
|
1665
|
+
function scaffoldEventPublisher(input) {
|
|
1666
|
+
const port = generatePort();
|
|
1667
|
+
const adapter = ADAPTERS[input.transport];
|
|
1668
|
+
return `// --- Port (domain/ports/EventPublisher.ts) ---
|
|
1669
|
+
|
|
1670
|
+
${port}
|
|
1671
|
+
// --- Adapter (infrastructure/services/${input.transport}-event-publisher.ts) ---
|
|
1672
|
+
|
|
1673
|
+
${adapter}`;
|
|
1674
|
+
}
|
|
1675
|
+
function handleScaffoldEventPublisher(input) {
|
|
1676
|
+
return makeSuccessResult(scaffoldEventPublisher(input));
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
// src/tools/scaffold-decorator-setup.ts
|
|
1680
|
+
import { z as z10 } from "zod";
|
|
1681
|
+
var scaffoldDecoratorSetupSchema = {
|
|
1682
|
+
implementations: z10.array(z10.object({
|
|
1683
|
+
token: z10.string().describe('Port/token name, e.g. "UserRepository"'),
|
|
1684
|
+
className: z10.string().describe('Implementation class name, e.g. "PrismaUserRepository"'),
|
|
1685
|
+
dependencies: z10.array(z10.string()).optional().describe("Token names for @Inject"),
|
|
1686
|
+
lifecycle: z10.enum(["singleton", "transient", "scoped"]).optional().describe("Lifecycle (default: singleton)")
|
|
1687
|
+
})).describe("Implementations to register with decorators")
|
|
1688
|
+
};
|
|
1689
|
+
function scaffoldDecoratorSetup(input) {
|
|
1690
|
+
const lines = [];
|
|
1691
|
+
lines.push(`import { createContainer, createHexApp } from 'beebear';`);
|
|
1692
|
+
lines.push(`import { Injectable, Inject, withDecorators } from '@beebear-plugins/di-decorators';`);
|
|
1693
|
+
const typeNames = /* @__PURE__ */ new Set();
|
|
1694
|
+
for (const impl of input.implementations) {
|
|
1695
|
+
typeNames.add(impl.token);
|
|
1696
|
+
for (const dep of impl.dependencies ?? []) {
|
|
1697
|
+
typeNames.add(dep);
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
if (typeNames.size > 0) {
|
|
1701
|
+
lines.push(`import type { ${[...typeNames].join(", ")} } from './ports.js';`);
|
|
1702
|
+
}
|
|
1703
|
+
lines.push("");
|
|
1704
|
+
for (const impl of input.implementations) {
|
|
1705
|
+
const deps = impl.dependencies ?? [];
|
|
1706
|
+
const lifecycle = impl.lifecycle ?? "singleton";
|
|
1707
|
+
const lifecycleOpt = lifecycle !== "singleton" ? `, { lifecycle: '${lifecycle}' }` : "";
|
|
1708
|
+
lines.push(`@Injectable(${impl.token}${lifecycleOpt})`);
|
|
1709
|
+
lines.push(`class ${impl.className} implements ${impl.token} {`);
|
|
1710
|
+
if (deps.length > 0) {
|
|
1711
|
+
lines.push(" constructor(");
|
|
1712
|
+
for (const dep of deps) {
|
|
1713
|
+
const paramName = dep.charAt(0).toLowerCase() + dep.slice(1);
|
|
1714
|
+
lines.push(` @Inject(${dep}) private readonly ${paramName}: ${dep},`);
|
|
1715
|
+
}
|
|
1716
|
+
lines.push(" ) {}");
|
|
1717
|
+
}
|
|
1718
|
+
lines.push("");
|
|
1719
|
+
lines.push(" // TODO: implement methods");
|
|
1720
|
+
lines.push("}");
|
|
1721
|
+
lines.push("");
|
|
1722
|
+
}
|
|
1723
|
+
lines.push("const container = withDecorators(createContainer());");
|
|
1724
|
+
lines.push("container.validate();");
|
|
1725
|
+
lines.push("");
|
|
1726
|
+
lines.push("const hex = createHexApp({ container });");
|
|
1727
|
+
lines.push("");
|
|
1728
|
+
return lines.join("\n");
|
|
1729
|
+
}
|
|
1730
|
+
function handleScaffoldDecoratorSetup(input) {
|
|
1731
|
+
if (input.implementations.length === 0) {
|
|
1732
|
+
return makeErrorResult("At least one implementation is required");
|
|
1733
|
+
}
|
|
1734
|
+
for (const impl of input.implementations) {
|
|
1735
|
+
if (!isPascalCase(impl.token)) {
|
|
1736
|
+
return makeErrorResult(`Token "${impl.token}" must be PascalCase`);
|
|
1737
|
+
}
|
|
1738
|
+
if (!isPascalCase(impl.className)) {
|
|
1739
|
+
return makeErrorResult(`Class name "${impl.className}" must be PascalCase`);
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
return makeSuccessResult(scaffoldDecoratorSetup(input));
|
|
1743
|
+
}
|
|
1744
|
+
|
|
1745
|
+
// src/tools/index.ts
|
|
1746
|
+
var tools = [
|
|
1747
|
+
{
|
|
1748
|
+
name: "scaffold_port",
|
|
1749
|
+
description: 'Generate a port interface with its token. Use direction="inbound" for use case ports, "outbound" for dependency ports.',
|
|
1750
|
+
schema: scaffoldPortSchema,
|
|
1751
|
+
handler: handleScaffoldPort
|
|
1752
|
+
},
|
|
1753
|
+
{
|
|
1754
|
+
name: "scaffold_use_case",
|
|
1755
|
+
description: "Generate a use case class implementing a driving (inbound) port.",
|
|
1756
|
+
schema: scaffoldUseCaseSchema,
|
|
1757
|
+
handler: handleScaffoldUseCase
|
|
1758
|
+
},
|
|
1759
|
+
{
|
|
1760
|
+
name: "scaffold_adapter",
|
|
1761
|
+
description: "Generate an adapter class implementing an outbound port.",
|
|
1762
|
+
schema: scaffoldAdapterSchema,
|
|
1763
|
+
handler: handleScaffoldAdapter
|
|
1764
|
+
},
|
|
1765
|
+
{
|
|
1766
|
+
name: "scaffold_route",
|
|
1767
|
+
description: "Generate an HTTP route using hex.httpAdapter().",
|
|
1768
|
+
schema: scaffoldRouteSchema,
|
|
1769
|
+
handler: handleScaffoldRoute
|
|
1770
|
+
},
|
|
1771
|
+
{
|
|
1772
|
+
name: "scaffold_container_setup",
|
|
1773
|
+
description: "Generate container binding code with createContainer(), bind(), and validate().",
|
|
1774
|
+
schema: scaffoldContainerSetupSchema,
|
|
1775
|
+
handler: handleScaffoldContainerSetup
|
|
1776
|
+
},
|
|
1777
|
+
{
|
|
1778
|
+
name: "scaffold_entity",
|
|
1779
|
+
description: "Generate a DDD Entity subclass (@beebear-plugins/ddd).",
|
|
1780
|
+
schema: scaffoldEntitySchema,
|
|
1781
|
+
handler: handleScaffoldEntity
|
|
1782
|
+
},
|
|
1783
|
+
{
|
|
1784
|
+
name: "scaffold_value_object",
|
|
1785
|
+
description: "Generate a DDD ValueObject subclass with validation (@beebear-plugins/ddd).",
|
|
1786
|
+
schema: scaffoldValueObjectSchema,
|
|
1787
|
+
handler: handleScaffoldValueObject
|
|
1788
|
+
},
|
|
1789
|
+
{
|
|
1790
|
+
name: "scaffold_aggregate",
|
|
1791
|
+
description: "Generate a DDD AggregateRoot with domain events (@beebear-plugins/ddd).",
|
|
1792
|
+
schema: scaffoldAggregateSchema,
|
|
1793
|
+
handler: handleScaffoldAggregate
|
|
1794
|
+
},
|
|
1795
|
+
{
|
|
1796
|
+
name: "scaffold_event_publisher",
|
|
1797
|
+
description: "Generate an EventPublisher outbound port and transport adapter (RabbitMQ, Kafka, SQS, or outbox).",
|
|
1798
|
+
schema: scaffoldEventPublisherSchema,
|
|
1799
|
+
handler: handleScaffoldEventPublisher
|
|
1800
|
+
},
|
|
1801
|
+
{
|
|
1802
|
+
name: "scaffold_decorator_setup",
|
|
1803
|
+
description: "Generate decorator-based DI setup using @beebear-plugins/di-decorators.",
|
|
1804
|
+
schema: scaffoldDecoratorSetupSchema,
|
|
1805
|
+
handler: handleScaffoldDecoratorSetup
|
|
1806
|
+
}
|
|
1807
|
+
];
|
|
1808
|
+
function registerTools(server2) {
|
|
1809
|
+
for (const tool of tools) {
|
|
1810
|
+
server2.registerTool(tool.name, { description: tool.description, inputSchema: tool.schema }, tool.handler);
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
// src/prompts/new-project.ts
|
|
1815
|
+
import { z as z11 } from "zod";
|
|
1816
|
+
var newProjectSchema = {
|
|
1817
|
+
framework: z11.enum(["express", "fastify", "hono"]).describe("HTTP framework to use"),
|
|
1818
|
+
name: z11.string().describe("Project name")
|
|
1819
|
+
};
|
|
1820
|
+
function newProjectPrompt(args) {
|
|
1821
|
+
return `# Set Up a New beebear Project: ${args.name}
|
|
1822
|
+
|
|
1823
|
+
## Step 1: Initialize the project
|
|
1824
|
+
|
|
1825
|
+
\`\`\`bash
|
|
1826
|
+
mkdir ${args.name} && cd ${args.name}
|
|
1827
|
+
npm init -y
|
|
1828
|
+
npm install beebear ${args.framework}
|
|
1829
|
+
npm install -D typescript tsup @types/node
|
|
1830
|
+
npx tsc --init --target ES2022 --module ESNext --moduleResolution bundler --strict --outDir dist --rootDir src
|
|
1831
|
+
\`\`\`
|
|
1832
|
+
|
|
1833
|
+
Set \`"type": "module"\` in package.json.
|
|
1834
|
+
|
|
1835
|
+
## Step 2: Create folder structure
|
|
1836
|
+
|
|
1837
|
+
\`\`\`bash
|
|
1838
|
+
mkdir -p src/domain/ports/inbound
|
|
1839
|
+
mkdir -p src/domain/ports/outbound
|
|
1840
|
+
mkdir -p src/domain/use-cases
|
|
1841
|
+
mkdir -p src/domain/errors
|
|
1842
|
+
mkdir -p src/domain/models
|
|
1843
|
+
mkdir -p src/infrastructure/persistence
|
|
1844
|
+
mkdir -p src/infrastructure/http
|
|
1845
|
+
mkdir -p src/infrastructure/services
|
|
1846
|
+
\`\`\`
|
|
1847
|
+
|
|
1848
|
+
## Step 3: Define your first outbound port
|
|
1849
|
+
|
|
1850
|
+
Create \`src/domain/ports/outbound/UserRepository.ts\`:
|
|
1851
|
+
|
|
1852
|
+
\`\`\`ts
|
|
1853
|
+
import { Port } from 'beebear';
|
|
1854
|
+
|
|
1855
|
+
export interface UserRepository {
|
|
1856
|
+
findById(id: string): Promise<{ id: string; name: string } | null>;
|
|
1857
|
+
save(user: { id: string; name: string }): Promise<void>;
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1860
|
+
export const UserRepository = Port<UserRepository>('UserRepository');
|
|
1861
|
+
\`\`\`
|
|
1862
|
+
|
|
1863
|
+
## Step 4: Define your first inbound port (use case)
|
|
1864
|
+
|
|
1865
|
+
Create \`src/domain/ports/inbound/GetUser.ts\`:
|
|
1866
|
+
|
|
1867
|
+
\`\`\`ts
|
|
1868
|
+
import { Port } from 'beebear';
|
|
1869
|
+
import type { UseCase } from 'beebear';
|
|
1870
|
+
|
|
1871
|
+
export interface GetUser extends UseCase<{ id: string }, { id: string; name: string }> {}
|
|
1872
|
+
|
|
1873
|
+
export const GetUser = Port<GetUser>('GetUser');
|
|
1874
|
+
\`\`\`
|
|
1875
|
+
|
|
1876
|
+
## Step 5: Implement the use case
|
|
1877
|
+
|
|
1878
|
+
Create \`src/domain/use-cases/GetUserService.ts\`:
|
|
1879
|
+
|
|
1880
|
+
\`\`\`ts
|
|
1881
|
+
import type { GetUser } from '../ports/inbound/GetUser.js';
|
|
1882
|
+
import type { UserRepository } from '../ports/outbound/UserRepository.js';
|
|
1883
|
+
import { NotFoundError } from 'beebear';
|
|
1884
|
+
|
|
1885
|
+
export class GetUserService implements GetUser {
|
|
1886
|
+
constructor(private readonly userRepository: UserRepository) {}
|
|
1887
|
+
|
|
1888
|
+
async execute(input: { id: string }) {
|
|
1889
|
+
const user = await this.userRepository.findById(input.id);
|
|
1890
|
+
if (!user) throw new NotFoundError('User not found');
|
|
1891
|
+
return user;
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
\`\`\`
|
|
1895
|
+
|
|
1896
|
+
## Step 6: Implement the adapter
|
|
1897
|
+
|
|
1898
|
+
Create \`src/infrastructure/persistence/InMemoryUserRepository.ts\`:
|
|
1899
|
+
|
|
1900
|
+
\`\`\`ts
|
|
1901
|
+
import type { UserRepository } from '../../domain/ports/outbound/UserRepository.js';
|
|
1902
|
+
|
|
1903
|
+
export class InMemoryUserRepository implements UserRepository {
|
|
1904
|
+
private users = new Map<string, { id: string; name: string }>();
|
|
1905
|
+
|
|
1906
|
+
async findById(id: string) {
|
|
1907
|
+
return this.users.get(id) ?? null;
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1910
|
+
async save(user: { id: string; name: string }) {
|
|
1911
|
+
this.users.set(user.id, user);
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
\`\`\`
|
|
1915
|
+
|
|
1916
|
+
## Step 7: Wire everything together
|
|
1917
|
+
|
|
1918
|
+
Create \`src/index.ts\`:
|
|
1919
|
+
|
|
1920
|
+
\`\`\`ts
|
|
1921
|
+
import { createContainer, createHexApp } from 'beebear';
|
|
1922
|
+
import { UserRepository } from './domain/ports/outbound/UserRepository.js';
|
|
1923
|
+
import { GetUser } from './domain/ports/inbound/GetUser.js';
|
|
1924
|
+
import { InMemoryUserRepository } from './infrastructure/persistence/InMemoryUserRepository.js';
|
|
1925
|
+
import { GetUserService } from './domain/use-cases/GetUserService.js';
|
|
1926
|
+
${args.framework === "express" ? "import express from 'express';" : ""}${args.framework === "fastify" ? "import Fastify from 'fastify';" : ""}${args.framework === "hono" ? "import { Hono } from 'hono';" : ""}
|
|
1927
|
+
|
|
1928
|
+
const container = createContainer();
|
|
1929
|
+
container.bind(UserRepository, () => new InMemoryUserRepository());
|
|
1930
|
+
container.bind(GetUser, (c) => new GetUserService(c.resolve(UserRepository)));
|
|
1931
|
+
container.validate();
|
|
1932
|
+
|
|
1933
|
+
const hex = createHexApp({ container, framework: '${args.framework}' });
|
|
1934
|
+
|
|
1935
|
+
${args.framework === "express" ? `const app = express();
|
|
1936
|
+
app.use(express.json());
|
|
1937
|
+
|
|
1938
|
+
app.get('/users/:id', hex.httpAdapter(GetUser, {
|
|
1939
|
+
toInput: (req) => ({ id: req.params.id }),
|
|
1940
|
+
}));
|
|
1941
|
+
|
|
1942
|
+
app.listen(3000, () => console.log('Listening on :3000'));` : ""}${args.framework === "fastify" ? `const app = Fastify();
|
|
1943
|
+
|
|
1944
|
+
app.get('/users/:id', hex.httpAdapter(GetUser, {
|
|
1945
|
+
toInput: (req) => ({ id: (req.params as any).id }),
|
|
1946
|
+
}));
|
|
1947
|
+
|
|
1948
|
+
app.listen({ port: 3000 }).then(() => console.log('Listening on :3000'));` : ""}${args.framework === "hono" ? `const app = new Hono();
|
|
1949
|
+
|
|
1950
|
+
app.get('/users/:id', hex.httpAdapter(GetUser, {
|
|
1951
|
+
toInput: (req) => ({ id: req.param('id') }),
|
|
1952
|
+
}));
|
|
1953
|
+
|
|
1954
|
+
export default app;` : ""}
|
|
1955
|
+
\`\`\`
|
|
1956
|
+
|
|
1957
|
+
## Step 8: Run
|
|
1958
|
+
|
|
1959
|
+
\`\`\`bash
|
|
1960
|
+
npx tsup src/index.ts --format esm
|
|
1961
|
+
node dist/index.js
|
|
1962
|
+
\`\`\`
|
|
1963
|
+
|
|
1964
|
+
You now have a working beebear app with hexagonal architecture: domain logic in the hexagon, infrastructure outside, wired through ports and adapters.
|
|
1965
|
+
`;
|
|
1966
|
+
}
|
|
1967
|
+
|
|
1968
|
+
// src/prompts/add-feature.ts
|
|
1969
|
+
import { z as z12 } from "zod";
|
|
1970
|
+
var addFeatureSchema = {
|
|
1971
|
+
featureName: z12.string().describe('Feature name in PascalCase, e.g. "RegisterUser"'),
|
|
1972
|
+
description: z12.string().describe("What the feature does")
|
|
1973
|
+
};
|
|
1974
|
+
function addFeaturePrompt(args) {
|
|
1975
|
+
return `# Add Feature: ${args.featureName}
|
|
1976
|
+
|
|
1977
|
+
**Description:** ${args.description}
|
|
1978
|
+
|
|
1979
|
+
## Step 1: Define the inbound port
|
|
1980
|
+
|
|
1981
|
+
Create \`src/domain/ports/inbound/${args.featureName}.ts\`:
|
|
1982
|
+
|
|
1983
|
+
\`\`\`ts
|
|
1984
|
+
import { Port } from 'beebear';
|
|
1985
|
+
import type { UseCase } from 'beebear';
|
|
1986
|
+
|
|
1987
|
+
export interface ${args.featureName} extends UseCase<
|
|
1988
|
+
{ /* TODO: define input type */ },
|
|
1989
|
+
{ /* TODO: define output type */ }
|
|
1990
|
+
> {}
|
|
1991
|
+
|
|
1992
|
+
export const ${args.featureName} = Port<${args.featureName}>('${args.featureName}');
|
|
1993
|
+
\`\`\`
|
|
1994
|
+
|
|
1995
|
+
## Step 2: Define outbound ports (if needed)
|
|
1996
|
+
|
|
1997
|
+
If this feature needs to talk to a database, external service, or other infrastructure, define outbound ports:
|
|
1998
|
+
|
|
1999
|
+
\`\`\`ts
|
|
2000
|
+
import { Port } from 'beebear';
|
|
2001
|
+
|
|
2002
|
+
export interface SomeRepository {
|
|
2003
|
+
// TODO: define methods
|
|
2004
|
+
}
|
|
2005
|
+
|
|
2006
|
+
export const SomeRepository = Port<SomeRepository>('SomeRepository');
|
|
2007
|
+
\`\`\`
|
|
2008
|
+
|
|
2009
|
+
## Step 3: Implement the use case
|
|
2010
|
+
|
|
2011
|
+
Create \`src/domain/use-cases/${args.featureName}Service.ts\`:
|
|
2012
|
+
|
|
2013
|
+
\`\`\`ts
|
|
2014
|
+
import type { ${args.featureName} } from '../ports/inbound/${args.featureName}.js';
|
|
2015
|
+
|
|
2016
|
+
export class ${args.featureName}Service implements ${args.featureName} {
|
|
2017
|
+
constructor(
|
|
2018
|
+
// TODO: inject driven ports
|
|
2019
|
+
) {}
|
|
2020
|
+
|
|
2021
|
+
async execute(input: { /* TODO */ }) {
|
|
2022
|
+
// TODO: implement business logic
|
|
2023
|
+
// - Enforce domain rules
|
|
2024
|
+
// - Call driven ports (repositories, services)
|
|
2025
|
+
// - Return result
|
|
2026
|
+
throw new Error('Not implemented');
|
|
2027
|
+
}
|
|
2028
|
+
}
|
|
2029
|
+
\`\`\`
|
|
2030
|
+
|
|
2031
|
+
## Step 4: Implement adapters
|
|
2032
|
+
|
|
2033
|
+
Create adapter classes for each outbound port used by this feature.
|
|
2034
|
+
|
|
2035
|
+
## Step 5: Add container bindings
|
|
2036
|
+
|
|
2037
|
+
In your composition root:
|
|
2038
|
+
|
|
2039
|
+
\`\`\`ts
|
|
2040
|
+
container.bind(SomeRepository, () => new SomeRepositoryImpl());
|
|
2041
|
+
container.bind(${args.featureName}, (c) => new ${args.featureName}Service(
|
|
2042
|
+
c.resolve(SomeRepository),
|
|
2043
|
+
));
|
|
2044
|
+
\`\`\`
|
|
2045
|
+
|
|
2046
|
+
## Step 6: Add HTTP route
|
|
2047
|
+
|
|
2048
|
+
\`\`\`ts
|
|
2049
|
+
app.post('/<path>', hex.httpAdapter(${args.featureName}, {
|
|
2050
|
+
toInput: (req) => ({
|
|
2051
|
+
// TODO: map request to input
|
|
2052
|
+
}),
|
|
2053
|
+
}));
|
|
2054
|
+
\`\`\`
|
|
2055
|
+
|
|
2056
|
+
## Step 7: Test
|
|
2057
|
+
|
|
2058
|
+
1. Unit test the use case with mock adapters
|
|
2059
|
+
2. Integration test through the HTTP route
|
|
2060
|
+
3. Run \`container.validate()\` to catch missing bindings
|
|
2061
|
+
`;
|
|
2062
|
+
}
|
|
2063
|
+
|
|
2064
|
+
// src/prompts/index.ts
|
|
2065
|
+
function registerPrompts(server2) {
|
|
2066
|
+
server2.registerPrompt("new-project", {
|
|
2067
|
+
description: "Set up a new beebear project from scratch",
|
|
2068
|
+
argsSchema: newProjectSchema
|
|
2069
|
+
}, async (args) => ({
|
|
2070
|
+
messages: [{
|
|
2071
|
+
role: "user",
|
|
2072
|
+
content: { type: "text", text: newProjectPrompt(args) }
|
|
2073
|
+
}]
|
|
2074
|
+
}));
|
|
2075
|
+
server2.registerPrompt("add-feature", {
|
|
2076
|
+
description: "Add a new feature to an existing beebear project",
|
|
2077
|
+
argsSchema: addFeatureSchema
|
|
2078
|
+
}, async (args) => ({
|
|
2079
|
+
messages: [{
|
|
2080
|
+
role: "user",
|
|
2081
|
+
content: { type: "text", text: addFeaturePrompt(args) }
|
|
2082
|
+
}]
|
|
2083
|
+
}));
|
|
2084
|
+
}
|
|
2085
|
+
|
|
2086
|
+
// src/index.ts
|
|
2087
|
+
var server = new McpServer({
|
|
2088
|
+
name: "beebear-mcp",
|
|
2089
|
+
version: "0.1.0"
|
|
2090
|
+
});
|
|
2091
|
+
registerResources(server);
|
|
2092
|
+
registerTools(server);
|
|
2093
|
+
registerPrompts(server);
|
|
2094
|
+
var transport = new StdioServerTransport();
|
|
2095
|
+
await server.connect(transport);
|