ddd-express 0.0.0-stage → 1.0.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/CHANGELOG.md +34 -0
- package/LICENSE +21 -0
- package/README.ar.md +117 -0
- package/README.md +314 -2
- package/dist/analyze/check.d.ts +74 -0
- package/dist/analyze/check.js +503 -0
- package/dist/analyze/document.d.ts +26 -0
- package/dist/analyze/document.js +126 -0
- package/dist/analyze/map.d.ts +19 -0
- package/dist/analyze/map.js +283 -0
- package/dist/analyze/openapi.d.ts +7 -0
- package/dist/analyze/openapi.js +236 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +12 -0
- package/dist/core/errors.d.ts +5 -0
- package/dist/core/errors.js +13 -0
- package/dist/core/fields.d.ts +38 -0
- package/dist/core/fields.js +233 -0
- package/dist/core/markers.d.ts +25 -0
- package/dist/core/markers.js +60 -0
- package/dist/core/names.d.ts +30 -0
- package/dist/core/names.js +168 -0
- package/dist/core/output.d.ts +21 -0
- package/dist/core/output.js +29 -0
- package/dist/core/project.d.ts +135 -0
- package/dist/core/project.js +287 -0
- package/dist/core/writer.d.ts +39 -0
- package/dist/core/writer.js +138 -0
- package/dist/generators/analyze.d.ts +16 -0
- package/dist/generators/analyze.js +174 -0
- package/dist/generators/apply.d.ts +28 -0
- package/dist/generators/apply.js +234 -0
- package/dist/generators/common.d.ts +49 -0
- package/dist/generators/common.js +173 -0
- package/dist/generators/domain.d.ts +30 -0
- package/dist/generators/domain.js +198 -0
- package/dist/generators/engine.d.ts +71 -0
- package/dist/generators/engine.js +552 -0
- package/dist/generators/project.d.ts +10 -0
- package/dist/generators/project.js +214 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +14 -0
- package/dist/model/commands.d.ts +28 -0
- package/dist/model/commands.js +228 -0
- package/dist/model/examples.d.ts +6 -0
- package/dist/model/examples.js +152 -0
- package/dist/model/parser.d.ts +28 -0
- package/dist/model/parser.js +222 -0
- package/dist/model/types.d.ts +98 -0
- package/dist/model/types.js +2 -0
- package/dist/model/validate.d.ts +30 -0
- package/dist/model/validate.js +215 -0
- package/dist/run.d.ts +4 -0
- package/dist/run.js +506 -0
- package/dist/scan/project-scan.d.ts +77 -0
- package/dist/scan/project-scan.js +226 -0
- package/dist/scan/source.d.ts +60 -0
- package/dist/scan/source.js +274 -0
- package/dist/templates/aggregate.d.ts +51 -0
- package/dist/templates/aggregate.js +407 -0
- package/dist/templates/building-blocks.d.ts +30 -0
- package/dist/templates/building-blocks.js +155 -0
- package/dist/templates/code.d.ts +14 -0
- package/dist/templates/code.js +51 -0
- package/dist/templates/command.d.ts +47 -0
- package/dist/templates/command.js +376 -0
- package/dist/templates/context.d.ts +16 -0
- package/dist/templates/context.js +43 -0
- package/dist/templates/field-code.d.ts +47 -0
- package/dist/templates/field-code.js +227 -0
- package/dist/templates/postgres.d.ts +25 -0
- package/dist/templates/postgres.js +113 -0
- package/dist/templates/project.d.ts +20 -0
- package/dist/templates/project.js +153 -0
- package/dist/templates/shared-kernel.d.ts +6 -0
- package/dist/templates/shared-kernel.js +44 -0
- package/package.json +58 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 1.0.0
|
|
4
|
+
|
|
5
|
+
First release.
|
|
6
|
+
|
|
7
|
+
### Model
|
|
8
|
+
- `domain.ddd`, a small language for the domain: contexts, aggregates, fields (with optional fields, defaults,
|
|
9
|
+
value lists), entities, value objects, events, services and policies between contexts.
|
|
10
|
+
- Behaviour with state machines: `command checkOut(durationMinutes: integer): in_progress -> completed sets ... emits VisitCompleted(...)`.
|
|
11
|
+
- Every mistake reported with its line number before anything is written.
|
|
12
|
+
- `apply`: additive and idempotent generation from the model. `model` writes a starter or an example
|
|
13
|
+
(`healthcare`, `shop`); `new --example` / `new --model` build a whole project.
|
|
14
|
+
|
|
15
|
+
### Generate
|
|
16
|
+
- `new` (Vitest/ESM, Jest/CommonJS or node:test/ESM) and `init` for existing projects.
|
|
17
|
+
- `module`: aggregate root, Created/Updated/Deleted events, repository port, in-memory adapter and mapper,
|
|
18
|
+
create/get/list/update/delete use cases, use-case facade, DTO, Express router, request validation and tests.
|
|
19
|
+
- `command`: adds a behaviour to an existing aggregate — method, state guard, event, use case, route, request
|
|
20
|
+
parser and tests.
|
|
21
|
+
- `context`, `value-object`, `entity`, `event`, `use-case`, `service`, `handler`.
|
|
22
|
+
- `adapter postgres`: node-postgres repository (one schema per context, upsert, paging), migration, integration test.
|
|
23
|
+
|
|
24
|
+
### Guard and document
|
|
25
|
+
- `check`: zero-config architecture rules — domain/application isolation, context boundaries, shared kernel,
|
|
26
|
+
aggregate references, event naming, silent state changes, ubiquitous language (`--fix`), anemic aggregates.
|
|
27
|
+
`--strict`, `--json`, configurable in `ddd.config.json`.
|
|
28
|
+
- `map`: context map, event flow and life-cycle diagrams (Mermaid) with behaviour/event/glossary tables, read from
|
|
29
|
+
the code — Markdown, HTML or JSON.
|
|
30
|
+
- `openapi`: OpenAPI 3.1 for every route, or an interactive API reference page.
|
|
31
|
+
|
|
32
|
+
### Generated code
|
|
33
|
+
- No dependency besides Express; strict TypeScript 5–7; Express 4 and 5; ESM and CommonJS.
|
|
34
|
+
- Tests use `node:assert`, so they run unchanged on Vitest, Jest and the Node test runner.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Moustafa Aboulazm
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.ar.md
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
<div dir="rtl">
|
|
2
|
+
|
|
3
|
+
# ddd-express — الدليل بالعربي
|
|
4
|
+
|
|
5
|
+
أداة سطر أوامر (CLI) للـ **Domain-Driven Design** مع **Express + TypeScript**، ومش معتمدة على أي package غير Express.
|
|
6
|
+
|
|
7
|
+
الأداة مش بتعمل scaffolding وبس، هي بتغطي الدورة كلها:
|
|
8
|
+
|
|
9
|
+
1. **التصميم (Model):** تكتب الـ domain كله في ملف واحد اسمه `domain.ddd`: الـ contexts والـ aggregates والـ state machines والـ commands والـ events والـ policies.
|
|
10
|
+
2. **التوليد (Generate):** أمر `apply` بيحوّل الملف لكود: aggregates بتحمي القواعد بتاعتها، وevents، وuse cases، وREST routes، وrequest validation، وrepository ports وadapters، **ومعاهم الـ tests**.
|
|
11
|
+
3. **الحراسة (Guard):** أمر `check` بيمنع أي حاجة تكسر الـ architecture من غير أي config، زي الـ layers وحدود الـ contexts والـ Ubiquitous Language، ويرجع exit code 1 في الـ CI.
|
|
12
|
+
4. **التوثيق (Document):** أمر `map` بيرسم الـ context map والـ event flow ودورة حياة كل aggregate من الكود نفسه، وأمر `openapi` بيطلّع OpenAPI 3.1.
|
|
13
|
+
|
|
14
|
+
## البداية السريعة
|
|
15
|
+
|
|
16
|
+
</div>
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npx ddd-express new clinic-api --example healthcare
|
|
20
|
+
cd clinic-api && npm install
|
|
21
|
+
npm test # حوالي 200 test كلهم ناجحين
|
|
22
|
+
npm run dev # http://localhost:3000
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
<div dir="rtl">
|
|
26
|
+
|
|
27
|
+
النتيجة API لشركة رعاية منزلية فيها 4 bounded contexts: Scheduling وBilling وPayroll وNotifications. الزيارة بتمشي من `scheduled` لـ `in_progress` لـ `completed`، ولما الزيارة تخلص، الـ Billing والـ Payroll والـ Notifications بيتفاعلوا معاها عن طريق الـ domain events، من غير ما أي context يكلّم التاني بشكل مباشر.
|
|
28
|
+
|
|
29
|
+
## ملف الـ domain
|
|
30
|
+
|
|
31
|
+
</div>
|
|
32
|
+
|
|
33
|
+
```ruby
|
|
34
|
+
context Scheduling
|
|
35
|
+
aggregate Visit
|
|
36
|
+
clientId: string
|
|
37
|
+
scheduledStart: date
|
|
38
|
+
status: scheduled | in_progress | completed | cancelled = scheduled
|
|
39
|
+
|
|
40
|
+
command checkIn: scheduled -> in_progress emits VisitStarted
|
|
41
|
+
command checkOut(durationMinutes: integer): in_progress -> completed emits VisitCompleted(clientId, durationMinutes)
|
|
42
|
+
command cancel(reason: string): scheduled, in_progress -> cancelled emits VisitCancelled(reason)
|
|
43
|
+
|
|
44
|
+
context Billing
|
|
45
|
+
aggregate Invoice
|
|
46
|
+
visitId: string
|
|
47
|
+
amount: number
|
|
48
|
+
|
|
49
|
+
on Scheduling.VisitCompleted -> CreateInvoice
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
<div dir="rtl">
|
|
53
|
+
|
|
54
|
+
بعدها تشغّل:
|
|
55
|
+
|
|
56
|
+
</div>
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
npx ddd-express apply
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
<div dir="rtl">
|
|
63
|
+
|
|
64
|
+
كل command في الملف بيطلع منه الآتي:
|
|
65
|
+
|
|
66
|
+
1. أولًا الـ method جوه الـ aggregate، ومعاها guard على الحالة. يعني `checkOut` مش هتشتغل غير لو الزيارة `in_progress`، وفي أي حالة تانية بترجع 422.
|
|
67
|
+
2. ثانيًا الـ domain event.
|
|
68
|
+
3. ثالثًا الـ use case.
|
|
69
|
+
4. رابعًا الـ route، زي `POST /visits/:id/check-out`، ومعاه validation للـ body.
|
|
70
|
+
5. أخيرًا الـ tests: الحالة الناجحة، والحالة المرفوضة، والـ input الغلط، والـ id اللي مش موجود.
|
|
71
|
+
|
|
72
|
+
- الـ state field بيتغير عن طريق الـ behaviour بس، ومش موجود في الـ create ولا في الـ PATCH.
|
|
73
|
+
- أمر `apply` بيضيف الجديد بس، ومش بيمسح ولا بيعيد كتابة أي حاجة في الكود بتاعك.
|
|
74
|
+
- مرجع اللغة كاملة موجود في [docs/model-language.md](docs/model-language.md).
|
|
75
|
+
|
|
76
|
+
## الأوامر
|
|
77
|
+
|
|
78
|
+
| الأمر | وظيفته |
|
|
79
|
+
|---|---|
|
|
80
|
+
| `new <name>` | مشروع جديد، ومعاه `--example healthcare` أو `shop` |
|
|
81
|
+
| `init` | يضيف الأساس لمشروع Express موجود |
|
|
82
|
+
| `model` | يكتب ملف `domain.ddd` تبدأ منه |
|
|
83
|
+
| `apply` | يولّد كل حاجة في الـ model ومش موجودة في الكود |
|
|
84
|
+
| `module <name>` | aggregate كامل بكل اللي حواليه من غير ملف model |
|
|
85
|
+
| `command "<syntax>"` | يضيف behaviour لـ aggregate موجود، بنفس syntax الملف |
|
|
86
|
+
| `value-object` `entity` `event` `use-case` `service` | building blocks منفصلة |
|
|
87
|
+
| `handler --on <Event>` | يتفاعل مع event من نفس الـ context أو من context تاني |
|
|
88
|
+
| `adapter postgres` | repository لـ PostgreSQL، ومعاه migration وintegration test |
|
|
89
|
+
| `check` | حارس الـ architecture |
|
|
90
|
+
| `map` | documentation حية بالـ diagrams |
|
|
91
|
+
| `openapi` | OpenAPI 3.1، أو صفحة API reference تفاعلية |
|
|
92
|
+
|
|
93
|
+
## الطبقات ماشية إزاي
|
|
94
|
+
|
|
95
|
+
1. أولًا الـ request بيدخل على الـ router في `infrastructure/http`، وهناك بيتعمل check على **شكل** الـ request. لو الشكل غلط بيرجع 400 ومعاه كل المشاكل مرة واحدة.
|
|
96
|
+
2. ثانيًا الـ use case بيعمل load للـ aggregate عن طريق الـ port.
|
|
97
|
+
3. ثالثًا الـ aggregate هو اللي بيعمل check على **الـ business rules**. لو قاعدة اتكسرت بيرجع 422.
|
|
98
|
+
4. رابعًا الـ use case بيعمل save الأول، **وبعدها** بيعمل publish للـ events، فمحدش يسمع عن تغيير ما اتحفظش.
|
|
99
|
+
5. أخيرًا الـ handlers في الـ contexts التانية بتسمع الـ events دي من الـ EventBus.
|
|
100
|
+
|
|
101
|
+
- الـ domain مش بيعمل import لأي حاجة من Express أو من الـ database.
|
|
102
|
+
- لو عايز تغيّر الـ database، ده سطر واحد في ملف `<context>.module.ts`.
|
|
103
|
+
|
|
104
|
+
## الأمان
|
|
105
|
+
|
|
106
|
+
- الأداة مش بتكتب فوق أي ملف إلا لو استخدمت `--force`، وتقدر تشوف هتعمل إيه الأول بـ `--dry-run`.
|
|
107
|
+
- لو الـ model فيه أخطاء، بتطلعلك كلها برقم السطر قبل ما يتكتب أي ملف.
|
|
108
|
+
- فيه comments زي `// ddd-express:behaviour` جوه الملفات، والأداة بتضيف الكود الجديد فوقها، فخليها موجودة.
|
|
109
|
+
|
|
110
|
+
## الكورس
|
|
111
|
+
|
|
112
|
+
الـ structure ماشي على نفس شكل repo الكورس العربي للـ Domain-Driven Design:
|
|
113
|
+
[ddd-home-healthcare](https://github.com/Moustafa1997/ddd-home-healthcare).
|
|
114
|
+
|
|
115
|
+
صاحب المكتبة: [مصطفى أبوالعزم](https://github.com/Moustafa1997) — والرخصة MIT.
|
|
116
|
+
|
|
117
|
+
</div>
|
package/README.md
CHANGED
|
@@ -1,3 +1,315 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="https://raw.githubusercontent.com/Moustafa1997/ddd-express/main/assets/logo.svg" alt="ddd-express" width="520">
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
<p align="center">
|
|
6
|
+
<b>Model your domain. Get a running, tested Express API. Keep the architecture honest.</b>
|
|
7
|
+
</p>
|
|
8
|
+
|
|
9
|
+
<p align="center">
|
|
10
|
+
<a href="https://www.npmjs.com/package/ddd-express"><img src="https://img.shields.io/npm/v/ddd-express.svg?color=4f7cff" alt="npm"></a>
|
|
11
|
+
<a href="https://github.com/Moustafa1997/ddd-express/actions"><img src="https://github.com/Moustafa1997/ddd-express/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
|
|
12
|
+
<img src="https://img.shields.io/badge/dependencies-0-46d3a7" alt="zero dependencies">
|
|
13
|
+
<img src="https://img.shields.io/node/v/ddd-express.svg" alt="node">
|
|
14
|
+
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT"></a>
|
|
15
|
+
</p>
|
|
16
|
+
|
|
17
|
+
<p align="center">
|
|
18
|
+
<a href="#quick-start">Quick start</a> ·
|
|
19
|
+
<a href="#the-domain-model-file">Model file</a> ·
|
|
20
|
+
<a href="#commands">Commands</a> ·
|
|
21
|
+
<a href="#guard-the-architecture">check</a> ·
|
|
22
|
+
<a href="#living-documentation">map</a> ·
|
|
23
|
+
<a href="docs/model-language.md">Language reference</a> ·
|
|
24
|
+
<a href="README.ar.md">بالعربي</a>
|
|
25
|
+
</p>
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
`ddd-express` is a zero-dependency CLI for **Domain-Driven Design** with **Express + TypeScript**. It covers the
|
|
30
|
+
whole loop — not just scaffolding:
|
|
31
|
+
|
|
32
|
+
| | |
|
|
33
|
+
|---|---|
|
|
34
|
+
| **Model** | Describe bounded contexts, aggregates, state machines, behaviour, events and policies in one readable file: `domain.ddd`. |
|
|
35
|
+
| **Generate** | `apply` turns the model into code: aggregates that protect their rules, events, use cases, REST routes, request validation, repository ports and adapters — **and the tests**. Change the model, apply again: only what is new is added. |
|
|
36
|
+
| **Guard** | `check` enforces the DDD architecture with zero config: layers, context boundaries, ubiquitous language. Exit code 1 in CI. |
|
|
37
|
+
| **Document** | `map` draws the context map, the event flow and the life cycle of every aggregate — from the code. `openapi` writes the OpenAPI 3.1 spec. |
|
|
38
|
+
|
|
39
|
+
The generated code compiles under `strict` TypeScript (5, 6 and 7), runs on Express 4 or 5, works with
|
|
40
|
+
Vitest, Jest or the Node test runner, and depends on nothing but Express.
|
|
41
|
+
|
|
42
|
+
## Quick start
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
npx ddd-express new clinic-api --example healthcare
|
|
46
|
+
cd clinic-api && npm install
|
|
47
|
+
npm test # ~200 generated tests, all green
|
|
48
|
+
npm run dev # http://localhost:3000
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
That is a home-healthcare API with 4 bounded contexts — Scheduling, Billing, Payroll, Notifications — where a
|
|
52
|
+
visit goes `scheduled → in_progress → completed`, and completing a visit makes Billing, Payroll and
|
|
53
|
+
Notifications react through domain events:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
curl -X POST localhost:3000/visits -H 'content-type: application/json' \
|
|
57
|
+
-d '{"clientId":"c-1","scheduledStart":"2026-12-10T09:00:00Z"}' # 201, status: scheduled
|
|
58
|
+
curl -X POST localhost:3000/visits/<id>/check-out \
|
|
59
|
+
-H 'content-type: application/json' -d '{"durationMinutes":45}' # 422 — not checked in yet
|
|
60
|
+
curl -X POST localhost:3000/visits/<id>/check-in # 200, status: in_progress
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Starting from scratch instead? `npx ddd-express new my-api` gives you an empty, ready project with a starter
|
|
64
|
+
`domain.ddd`. Adding DDD to an existing Express app? Run `npx ddd-express init` inside it.
|
|
65
|
+
|
|
66
|
+
## The domain model file
|
|
67
|
+
|
|
68
|
+
`domain.ddd` reads like the output of an Event Storming session:
|
|
69
|
+
|
|
70
|
+
```ruby
|
|
71
|
+
context Scheduling
|
|
72
|
+
aggregate Visit
|
|
73
|
+
clientId: string
|
|
74
|
+
caregiverId?: string
|
|
75
|
+
scheduledStart: date
|
|
76
|
+
status: scheduled | in_progress | completed | cancelled = scheduled
|
|
77
|
+
|
|
78
|
+
command checkIn: scheduled -> in_progress emits VisitStarted
|
|
79
|
+
command checkOut(durationMinutes: integer): in_progress -> completed emits VisitCompleted(clientId, durationMinutes)
|
|
80
|
+
command cancel(reason: string): scheduled, in_progress -> cancelled emits VisitCancelled(reason)
|
|
81
|
+
|
|
82
|
+
value VisitTime
|
|
83
|
+
start: date
|
|
84
|
+
end: date
|
|
85
|
+
|
|
86
|
+
context Billing
|
|
87
|
+
aggregate Invoice
|
|
88
|
+
visitId: string
|
|
89
|
+
amount: number
|
|
90
|
+
paid: boolean = false
|
|
91
|
+
|
|
92
|
+
command pay(paidAt: date) sets paid = true emits InvoicePaid(amount, paidAt)
|
|
93
|
+
|
|
94
|
+
on Scheduling.VisitCompleted -> CreateInvoice
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
npx ddd-express apply
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
For **every command** you get the behaviour on the aggregate, a guard on the state machine, the domain event,
|
|
102
|
+
a use case, a `POST /visits/:id/check-out` route with request validation, and tests for the happy path,
|
|
103
|
+
the refused transition, bad input and unknown ids:
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
/**
|
|
107
|
+
* Check out.
|
|
108
|
+
* status: in_progress → completed.
|
|
109
|
+
* Records VisitCompleted.
|
|
110
|
+
*/
|
|
111
|
+
checkOut(durationMinutes: number, now: Date = new Date()): void {
|
|
112
|
+
this.ensureState(['in_progress'], 'check out');
|
|
113
|
+
const args = {
|
|
114
|
+
durationMinutes: Guard.integer(durationMinutes, 'durationMinutes'),
|
|
115
|
+
};
|
|
116
|
+
// Add the business rules of "check out" here (throw a DomainError to refuse).
|
|
117
|
+
this.props = { ...this.props, status: 'completed', updatedAt: now };
|
|
118
|
+
this.record(new VisitCompleted(this.id, this.props.clientId, args.durationMinutes));
|
|
119
|
+
}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
The state field can only change through behaviour: it is not part of create or `PATCH`. Every policy
|
|
123
|
+
(`on Scheduling.VisitCompleted -> CreateInvoice`) becomes a handler in Billing, subscribed to the event bus —
|
|
124
|
+
Billing knows Scheduling's events, never its aggregates or use cases.
|
|
125
|
+
|
|
126
|
+
`apply` is **additive and idempotent**: it adds new contexts, aggregates, commands, events, value objects,
|
|
127
|
+
services and policies, and never deletes or rewrites your code. Full syntax: [docs/model-language.md](docs/model-language.md).
|
|
128
|
+
|
|
129
|
+
## What the code looks like
|
|
130
|
+
|
|
131
|
+
```
|
|
132
|
+
src/
|
|
133
|
+
├── app.ts Express app: JSON, contexts, error handling
|
|
134
|
+
├── contexts.ts mounts every bounded context
|
|
135
|
+
├── shared/ Entity, AggregateRoot, ValueObject, DomainEvent, Guard, EventBus, HTTP helpers
|
|
136
|
+
└── scheduling/ ← one bounded context
|
|
137
|
+
├── GLOSSARY.md its Ubiquitous Language
|
|
138
|
+
├── scheduling.module.ts composition root: adapters → use cases → routes, event subscriptions
|
|
139
|
+
├── domain/ plain TypeScript — no Express, no database
|
|
140
|
+
│ ├── visit/ aggregate root (+ entities)
|
|
141
|
+
│ ├── events/ VisitStarted, VisitCompleted, ...
|
|
142
|
+
│ ├── ports/ VisitRepository (interface)
|
|
143
|
+
│ ├── value-objects/ VisitTime, ...
|
|
144
|
+
│ └── services/ domain services
|
|
145
|
+
├── application/ use cases (create, get, list, update, delete + one per behaviour), DTOs, handlers
|
|
146
|
+
└── infrastructure/
|
|
147
|
+
├── http/ Express router + request validation (shape → 400)
|
|
148
|
+
└── persistence/ in-memory adapter + mapper (PostgreSQL adapter with `ddd-express adapter postgres`)
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
```mermaid
|
|
152
|
+
flowchart LR
|
|
153
|
+
HTTP -->|shape checked: 400| R[Router]
|
|
154
|
+
R --> UC[Use case]
|
|
155
|
+
UC -->|load / save| P[(Repository port)]
|
|
156
|
+
A[(In-memory / PostgreSQL adapter)] -. implements .-> P
|
|
157
|
+
UC --> AG[Aggregate]
|
|
158
|
+
AG -->|rules broken: 422| UC
|
|
159
|
+
UC -->|after save| BUS{{Event bus}}
|
|
160
|
+
BUS --> H[Handlers in other contexts]
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
- The **domain** imports nothing from Express or a database.
|
|
164
|
+
- The request layer checks the **shape** of a request (400 with every problem listed); the aggregate checks the
|
|
165
|
+
**business rules** (422). `NotFoundError` → 404, `ConflictError` → 409.
|
|
166
|
+
- Events are published **after** the save, so nobody hears about a change that was not stored.
|
|
167
|
+
- Swapping storage is one line in the context's module file.
|
|
168
|
+
|
|
169
|
+
## Commands
|
|
170
|
+
|
|
171
|
+
| Command | What it does |
|
|
172
|
+
|---|---|
|
|
173
|
+
| `new <name> [--example healthcare\|shop] [--model file]` | New Express + TypeScript API (Vitest/ESM by default; `--test-runner jest\|node`) |
|
|
174
|
+
| `init` | Add the foundation to an existing Express project (detects runner and ESM/CommonJS) |
|
|
175
|
+
| `model [--example name]` | Write a `domain.ddd` to start from |
|
|
176
|
+
| `apply [file]` | Generate everything the model has and the code does not |
|
|
177
|
+
| `module <name> --fields "..."` | One aggregate with its whole vertical slice, without a model file |
|
|
178
|
+
| `command "<syntax>" --aggregate <name>` | Add a behaviour to an existing aggregate — same syntax as in `domain.ddd` |
|
|
179
|
+
| `value-object`, `entity`, `event`, `use-case`, `service` | Single building blocks |
|
|
180
|
+
| `handler [Name] --on <Event>` | React to an event of this or another context, subscribed automatically |
|
|
181
|
+
| `adapter postgres --aggregate <name>` | PostgreSQL repository (node-postgres), migration and integration test |
|
|
182
|
+
| `check [--fix] [--strict] [--json]` | Architecture guard |
|
|
183
|
+
| `map [--format md\|html\|json]` | Living documentation |
|
|
184
|
+
| `openapi [--format json\|html]` | OpenAPI 3.1 spec, or an interactive API reference page |
|
|
185
|
+
|
|
186
|
+
Every generator supports `--dry-run`, `--force` and `--skip-tests`. `ddd-express <command> --help` shows all
|
|
187
|
+
options and examples.
|
|
188
|
+
|
|
189
|
+
### Fields
|
|
190
|
+
|
|
191
|
+
```
|
|
192
|
+
fullName: string notes?: string price: number quantity: integer
|
|
193
|
+
paid: boolean = false birthDate: date joinedAt: date = now status: draft | sent | paid = draft
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
`?` makes a field optional (it may be left out, `null` clears it). `= value` sets a default. A list of values
|
|
197
|
+
(`draft | sent | paid`) is an enum; the field that commands move between states becomes the state machine.
|
|
198
|
+
|
|
199
|
+
## Guard the architecture
|
|
200
|
+
|
|
201
|
+
```bash
|
|
202
|
+
npx ddd-express check
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
```
|
|
206
|
+
src/scheduling/domain/visit/visit.ts
|
|
207
|
+
1 error domain-isolation The domain imports the package "express".
|
|
208
|
+
→ Keep frameworks and databases out of the domain: move this code to infrastructure/.
|
|
209
|
+
src/billing/application/create-invoice-on-visit-completed.handler.ts
|
|
210
|
+
1 error context-boundaries The billing context reaches into scheduling (scheduling/domain/visit/index.ts).
|
|
211
|
+
→ React to scheduling's events (ddd-express handler ... --on <Event>), or import its public index.ts.
|
|
212
|
+
src/billing/GLOSSARY.md
|
|
213
|
+
warning ubiquitous-language "InvoicePaid" (domain event) is not in the Ubiquitous Language.
|
|
214
|
+
|
|
215
|
+
✖ 2 errors, 1 warning
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
| Rule | |
|
|
219
|
+
|---|---|
|
|
220
|
+
| `domain-isolation` | The domain depends only on itself, the shared domain kernel and pure libraries |
|
|
221
|
+
| `application-isolation` | Use cases depend on ports — never on adapters, Express or a database |
|
|
222
|
+
| `context-boundaries` | A context never reaches into another one; only its events or public `index.ts` |
|
|
223
|
+
| `shared-kernel` | The shared kernel knows no context |
|
|
224
|
+
| `aggregate-references` | Aggregates reference each other by id |
|
|
225
|
+
| `event-naming` | Events are facts in the past tense |
|
|
226
|
+
| `silent-state-change` | A state change records an event |
|
|
227
|
+
| `ubiquitous-language` | Every domain building block is in its context's `GLOSSARY.md` (`--fix` adds the rows) |
|
|
228
|
+
| `anemic-aggregate` | Suggests behaviour for aggregates that only have CRUD |
|
|
229
|
+
|
|
230
|
+
No configuration needed; tune it in `ddd.config.json` if you want. Details: [docs/architecture-rules.md](docs/architecture-rules.md).
|
|
231
|
+
|
|
232
|
+
## Living documentation
|
|
233
|
+
|
|
234
|
+
```bash
|
|
235
|
+
npx ddd-express map # docs/DOMAIN.md — GitHub renders the diagrams
|
|
236
|
+
npx ddd-express map --format html # docs/domain.html
|
|
237
|
+
npx ddd-express openapi --format html # docs/api.html — interactive API reference
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
`map` reads the code — not a separate model — so it never goes stale. It draws:
|
|
241
|
+
|
|
242
|
+
```mermaid
|
|
243
|
+
flowchart LR
|
|
244
|
+
ctx_billing["<b>Billing</b><br/>Invoice"]
|
|
245
|
+
ctx_notifications["<b>Notifications</b><br/>Message"]
|
|
246
|
+
ctx_payroll["<b>Payroll</b><br/>Timesheet"]
|
|
247
|
+
ctx_scheduling["<b>Scheduling</b><br/>Caregiver · Visit"]
|
|
248
|
+
ctx_scheduling -->|"VisitCompleted"| ctx_billing
|
|
249
|
+
ctx_scheduling -->|"VisitCompleted<br/>VisitCancelled"| ctx_notifications
|
|
250
|
+
ctx_scheduling -->|"VisitCompleted"| ctx_payroll
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
```mermaid
|
|
254
|
+
stateDiagram-v2
|
|
255
|
+
[*] --> scheduled
|
|
256
|
+
scheduled --> in_progress: checkIn
|
|
257
|
+
in_progress --> completed: checkOut
|
|
258
|
+
scheduled --> cancelled: cancel
|
|
259
|
+
in_progress --> cancelled: cancel
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
…plus the event flow (behaviour → event → policy, in Event Storming colours), and for every context its
|
|
263
|
+
glossary, aggregates, fields, behaviour, events and routes.
|
|
264
|
+
|
|
265
|
+
## Configuration
|
|
266
|
+
|
|
267
|
+
`ddd.config.json` is written on the first run with what was detected:
|
|
268
|
+
|
|
269
|
+
```json
|
|
270
|
+
{
|
|
271
|
+
"srcDir": "src",
|
|
272
|
+
"testRunner": "vitest",
|
|
273
|
+
"moduleSystem": "esm",
|
|
274
|
+
"check": {
|
|
275
|
+
"rules": { "anemic-aggregate": "off" },
|
|
276
|
+
"allowInDomain": ["decimal.js"],
|
|
277
|
+
"ignore": ["src/legacy"]
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
## Safe by design
|
|
283
|
+
|
|
284
|
+
- Never overwrites a file unless you pass `--force`; `--dry-run` shows the plan first.
|
|
285
|
+
- Generated files keep marker comments (`// ddd-express:behaviour`, `// ddd-express:routes`, ...). New code is
|
|
286
|
+
inserted above them, so you can keep editing those files.
|
|
287
|
+
- Names the generated code needs (`Page`, `Router`, ...) and fields it manages (`id`, `createdAt`, ...) are refused
|
|
288
|
+
with a clear message, and a model with mistakes is reported line by line before anything is written.
|
|
289
|
+
|
|
290
|
+
## Learn more
|
|
291
|
+
|
|
292
|
+
- [The model language](docs/model-language.md) — every statement, with examples
|
|
293
|
+
- [Architecture rules](docs/architecture-rules.md) — what `check` enforces and why
|
|
294
|
+
- [The generated code](docs/generated-code.md) — how the pieces fit, and how to extend them
|
|
295
|
+
- [Example models](src/model/examples.ts): `healthcare`, `shop`
|
|
296
|
+
|
|
297
|
+
## Requirements
|
|
298
|
+
|
|
299
|
+
Node.js 22+ for the CLI; generated projects target Node 22.12+ (current LTS). TypeScript `strict`,
|
|
300
|
+
`esModuleInterop` on (the default).
|
|
301
|
+
|
|
302
|
+
## Contributing
|
|
303
|
+
|
|
304
|
+
Issues and pull requests are welcome: [CONTRIBUTING.md](CONTRIBUTING.md) explains the checks every change passes,
|
|
305
|
+
and [RELEASING.md](RELEASING.md) how versions reach npm.
|
|
306
|
+
|
|
307
|
+
## Credits
|
|
308
|
+
|
|
309
|
+
Created by [Moustafa Aboulazm](https://github.com/Moustafa1997). The structure follows the companion repository
|
|
310
|
+
of his Arabic Domain-Driven Design course, [ddd-home-healthcare](https://github.com/Moustafa1997/ddd-home-healthcare),
|
|
311
|
+
and the ideas of Eric Evans' *Domain-Driven Design* and Vlad Khononov's *Learning Domain-Driven Design*.
|
|
312
|
+
|
|
313
|
+
## License
|
|
314
|
+
|
|
315
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { Project } from '../core/project';
|
|
2
|
+
import type { Writer } from '../core/writer';
|
|
3
|
+
import { type ScannedProject } from '../scan/project-scan';
|
|
4
|
+
export type Severity = 'error' | 'warning' | 'info';
|
|
5
|
+
export declare const RULES: {
|
|
6
|
+
readonly 'domain-isolation': {
|
|
7
|
+
readonly severity: Severity;
|
|
8
|
+
readonly summary: 'The domain layer depends only on itself, the shared domain kernel and pure libraries.';
|
|
9
|
+
};
|
|
10
|
+
readonly 'application-isolation': {
|
|
11
|
+
readonly severity: Severity;
|
|
12
|
+
readonly summary: 'Use cases depend on the domain and on ports — never on adapters, Express or a database.';
|
|
13
|
+
};
|
|
14
|
+
readonly 'context-boundaries': {
|
|
15
|
+
readonly severity: Severity;
|
|
16
|
+
readonly summary: "A bounded context never reaches into another one; it may only use the other's events or public index.";
|
|
17
|
+
};
|
|
18
|
+
readonly 'shared-kernel': {
|
|
19
|
+
readonly severity: Severity;
|
|
20
|
+
readonly summary: 'The shared kernel knows no bounded context, and its domain part knows no adapter.';
|
|
21
|
+
};
|
|
22
|
+
readonly 'aggregate-references': {
|
|
23
|
+
readonly severity: Severity;
|
|
24
|
+
readonly summary: 'An aggregate references other aggregates by id, not by importing them.';
|
|
25
|
+
};
|
|
26
|
+
readonly 'event-naming': {
|
|
27
|
+
readonly severity: Severity;
|
|
28
|
+
readonly summary: 'Domain events are facts: named in the past tense (VisitCompleted, not CompleteVisit).';
|
|
29
|
+
};
|
|
30
|
+
readonly 'silent-state-change': {
|
|
31
|
+
readonly severity: Severity;
|
|
32
|
+
readonly summary: 'A behaviour that changes the state records an event, so other contexts can react.';
|
|
33
|
+
};
|
|
34
|
+
readonly 'ubiquitous-language': {
|
|
35
|
+
readonly severity: Severity;
|
|
36
|
+
readonly summary: 'Every aggregate, entity, value object, event and service is in the GLOSSARY.md of its context.';
|
|
37
|
+
};
|
|
38
|
+
readonly 'anemic-aggregate': {
|
|
39
|
+
readonly severity: Severity;
|
|
40
|
+
readonly summary: 'An aggregate with behaviour (not only create/update/delete) captures the business language.';
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
export type RuleId = keyof typeof RULES;
|
|
44
|
+
export interface Finding {
|
|
45
|
+
rule: RuleId;
|
|
46
|
+
severity: Severity;
|
|
47
|
+
file: string;
|
|
48
|
+
line?: number;
|
|
49
|
+
message: string;
|
|
50
|
+
hint?: string;
|
|
51
|
+
}
|
|
52
|
+
export interface CheckConfig {
|
|
53
|
+
rules?: Partial<Record<RuleId, Severity | 'off'>>;
|
|
54
|
+
/** Packages the domain may import (e.g. "decimal.js"). */
|
|
55
|
+
allowInDomain?: string[];
|
|
56
|
+
/** Path prefixes (relative to the project root) to skip. */
|
|
57
|
+
ignore?: string[];
|
|
58
|
+
}
|
|
59
|
+
export interface CheckResult {
|
|
60
|
+
findings: Finding[];
|
|
61
|
+
filesChecked: number;
|
|
62
|
+
contexts: number;
|
|
63
|
+
}
|
|
64
|
+
export declare function loadCheckConfig(project: Project): CheckConfig;
|
|
65
|
+
/** Runs every architecture rule on the project. */
|
|
66
|
+
export declare function checkProject(project: Project, config?: CheckConfig, scan?: ScannedProject): CheckResult;
|
|
67
|
+
/** Domain terms of a context that its glossary does not mention. */
|
|
68
|
+
export declare function missingTerms(scan: ScannedProject, contextName: string): {
|
|
69
|
+
term: string;
|
|
70
|
+
kind: string;
|
|
71
|
+
human: string;
|
|
72
|
+
}[];
|
|
73
|
+
/** Adds the missing terms to every GLOSSARY.md. Returns how many rows were added. */
|
|
74
|
+
export declare function fixGlossaries(project: Project, writer: Writer, scan?: ScannedProject): number;
|