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.
Files changed (77) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/LICENSE +21 -0
  3. package/README.ar.md +117 -0
  4. package/README.md +314 -2
  5. package/dist/analyze/check.d.ts +74 -0
  6. package/dist/analyze/check.js +503 -0
  7. package/dist/analyze/document.d.ts +26 -0
  8. package/dist/analyze/document.js +126 -0
  9. package/dist/analyze/map.d.ts +19 -0
  10. package/dist/analyze/map.js +283 -0
  11. package/dist/analyze/openapi.d.ts +7 -0
  12. package/dist/analyze/openapi.js +236 -0
  13. package/dist/cli.d.ts +2 -0
  14. package/dist/cli.js +12 -0
  15. package/dist/core/errors.d.ts +5 -0
  16. package/dist/core/errors.js +13 -0
  17. package/dist/core/fields.d.ts +38 -0
  18. package/dist/core/fields.js +233 -0
  19. package/dist/core/markers.d.ts +25 -0
  20. package/dist/core/markers.js +60 -0
  21. package/dist/core/names.d.ts +30 -0
  22. package/dist/core/names.js +168 -0
  23. package/dist/core/output.d.ts +21 -0
  24. package/dist/core/output.js +29 -0
  25. package/dist/core/project.d.ts +135 -0
  26. package/dist/core/project.js +287 -0
  27. package/dist/core/writer.d.ts +39 -0
  28. package/dist/core/writer.js +138 -0
  29. package/dist/generators/analyze.d.ts +16 -0
  30. package/dist/generators/analyze.js +174 -0
  31. package/dist/generators/apply.d.ts +28 -0
  32. package/dist/generators/apply.js +234 -0
  33. package/dist/generators/common.d.ts +49 -0
  34. package/dist/generators/common.js +173 -0
  35. package/dist/generators/domain.d.ts +30 -0
  36. package/dist/generators/domain.js +198 -0
  37. package/dist/generators/engine.d.ts +71 -0
  38. package/dist/generators/engine.js +552 -0
  39. package/dist/generators/project.d.ts +10 -0
  40. package/dist/generators/project.js +214 -0
  41. package/dist/index.d.ts +10 -0
  42. package/dist/index.js +14 -0
  43. package/dist/model/commands.d.ts +28 -0
  44. package/dist/model/commands.js +228 -0
  45. package/dist/model/examples.d.ts +6 -0
  46. package/dist/model/examples.js +152 -0
  47. package/dist/model/parser.d.ts +28 -0
  48. package/dist/model/parser.js +222 -0
  49. package/dist/model/types.d.ts +98 -0
  50. package/dist/model/types.js +2 -0
  51. package/dist/model/validate.d.ts +30 -0
  52. package/dist/model/validate.js +215 -0
  53. package/dist/run.d.ts +4 -0
  54. package/dist/run.js +506 -0
  55. package/dist/scan/project-scan.d.ts +77 -0
  56. package/dist/scan/project-scan.js +226 -0
  57. package/dist/scan/source.d.ts +60 -0
  58. package/dist/scan/source.js +274 -0
  59. package/dist/templates/aggregate.d.ts +51 -0
  60. package/dist/templates/aggregate.js +407 -0
  61. package/dist/templates/building-blocks.d.ts +30 -0
  62. package/dist/templates/building-blocks.js +155 -0
  63. package/dist/templates/code.d.ts +14 -0
  64. package/dist/templates/code.js +51 -0
  65. package/dist/templates/command.d.ts +47 -0
  66. package/dist/templates/command.js +376 -0
  67. package/dist/templates/context.d.ts +16 -0
  68. package/dist/templates/context.js +43 -0
  69. package/dist/templates/field-code.d.ts +47 -0
  70. package/dist/templates/field-code.js +227 -0
  71. package/dist/templates/postgres.d.ts +25 -0
  72. package/dist/templates/postgres.js +113 -0
  73. package/dist/templates/project.d.ts +20 -0
  74. package/dist/templates/project.js +153 -0
  75. package/dist/templates/shared-kernel.d.ts +6 -0
  76. package/dist/templates/shared-kernel.js +44 -0
  77. package/package.json +58 -4
@@ -0,0 +1,283 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fieldType = fieldType;
4
+ exports.summaryCounts = summaryCounts;
5
+ exports.contextMapDiagram = contextMapDiagram;
6
+ exports.eventFlowDiagram = eventFlowDiagram;
7
+ exports.stateDiagram = stateDiagram;
8
+ exports.buildMap = buildMap;
9
+ const document_1 = require("./document");
10
+ const id = (...parts) => parts.join('_').replace(/[^A-Za-z0-9_]/g, '_');
11
+ const label = (text) => text.replace(/"/g, '#quot;');
12
+ function fieldType(field) {
13
+ const base = field.type === 'enum' ? field.values.join(' | ') : field.type;
14
+ return field.optional ? `${base}?` : base;
15
+ }
16
+ function fieldNotes(field, aggregate) {
17
+ const notes = [];
18
+ if (field.managed)
19
+ notes.push(`state (starts as \`${aggregate?.initialState ?? field.values[0]}\`, changed by behaviour)`);
20
+ else if (field.optional)
21
+ notes.push('optional');
22
+ if (field.defaultValue !== undefined && !field.managed) {
23
+ notes.push(`default \`${typeof field.defaultValue === 'object' ? 'now' : String(field.defaultValue)}\``);
24
+ }
25
+ return notes.join(', ');
26
+ }
27
+ const plural = (count, word, many = `${word}s`) => `**${count}** ${count === 1 ? word : many}`;
28
+ function summaryCounts(scan) {
29
+ const aggregates = scan.contexts.flatMap((context) => context.aggregates);
30
+ return {
31
+ contexts: scan.contexts.length,
32
+ aggregates: aggregates.length,
33
+ behaviours: aggregates.reduce((sum, aggregate) => sum + aggregate.commands.length, 0),
34
+ events: scan.contexts.reduce((sum, context) => sum + context.events.length, 0),
35
+ policies: scan.contexts.reduce((sum, context) => sum + context.handlers.length, 0),
36
+ valueObjects: scan.contexts.reduce((sum, context) => sum + context.valueObjects.length, 0),
37
+ };
38
+ }
39
+ /** Bounded contexts and the events that flow between them. */
40
+ function contextMapDiagram(scan) {
41
+ const lines = ['flowchart LR'];
42
+ for (const context of scan.contexts) {
43
+ const aggregates = context.aggregates.map((aggregate) => aggregate.name).join(' · ');
44
+ lines.push(` ${id('ctx', context.name)}["<b>${label(context.pascal)}</b>${aggregates ? `<br/>${label(aggregates)}` : ''}"]`);
45
+ }
46
+ const edges = new Map();
47
+ for (const context of scan.contexts) {
48
+ for (const handler of context.handlers) {
49
+ if (!handler.eventContext || handler.eventContext === context.name)
50
+ continue;
51
+ const key = `${handler.eventContext}>${context.name}`;
52
+ if (!edges.has(key))
53
+ edges.set(key, new Set());
54
+ edges.get(key)?.add(handler.event);
55
+ }
56
+ }
57
+ for (const [key, events] of edges) {
58
+ const [from, to] = key.split('>');
59
+ lines.push(` ${id('ctx', from)} -->|"${[...events].map(label).join('<br/>')}"| ${id('ctx', to)}`);
60
+ }
61
+ lines.push(' classDef context fill:#e8f1ff,stroke:#4a78c2,color:#0b2a5a');
62
+ lines.push(` class ${scan.contexts.map((context) => id('ctx', context.name)).join(',') || 'none'} context`);
63
+ return lines.join('\n');
64
+ }
65
+ /** Event Storming view: behaviour → domain event → policy, grouped by context. */
66
+ function eventFlowDiagram(scan) {
67
+ const lines = ['flowchart LR'];
68
+ const commands = [];
69
+ const events = [];
70
+ const policies = [];
71
+ const handled = new Set(scan.contexts.flatMap((context) => context.handlers.map((handler) => `${handler.eventContext ?? ''}:${handler.event}`)));
72
+ let edges = 0;
73
+ for (const context of scan.contexts) {
74
+ const body = [];
75
+ for (const aggregate of context.aggregates) {
76
+ for (const command of aggregate.commands) {
77
+ if (command.events.length === 0)
78
+ continue;
79
+ const commandId = id('cmd', context.name, aggregate.name, command.name);
80
+ body.push(` ${commandId}["${label(`${aggregate.name}.${command.name}()`)}"]`);
81
+ commands.push(commandId);
82
+ for (const event of command.events) {
83
+ const eventId = id('evt', context.name, event);
84
+ if (!events.includes(eventId)) {
85
+ body.push(` ${eventId}{{"${label(event)}"}}`);
86
+ events.push(eventId);
87
+ }
88
+ body.push(` ${commandId} --> ${eventId}`);
89
+ edges += 1;
90
+ }
91
+ }
92
+ }
93
+ // events that only CRUD publishes but someone handles
94
+ for (const event of context.events) {
95
+ const eventId = id('evt', context.name, event.name);
96
+ if (!events.includes(eventId) && handled.has(`${context.name}:${event.name}`)) {
97
+ body.push(` ${eventId}{{"${label(event.name)}"}}`);
98
+ events.push(eventId);
99
+ }
100
+ }
101
+ for (const handler of context.handlers) {
102
+ const handlerId = id('pol', context.name, handler.className);
103
+ body.push(` ${handlerId}[["${label(handler.className)}"]]`);
104
+ policies.push(handlerId);
105
+ }
106
+ if (body.length > 0)
107
+ lines.push(` subgraph ${id('ctx', context.name)} ["${label(context.pascal)}"]`, ...body, ' end');
108
+ }
109
+ for (const context of scan.contexts) {
110
+ for (const handler of context.handlers) {
111
+ const eventId = id('evt', handler.eventContext ?? context.name, handler.event);
112
+ if (!events.includes(eventId))
113
+ continue;
114
+ lines.push(` ${eventId} --> ${id('pol', context.name, handler.className)}`);
115
+ edges += 1;
116
+ }
117
+ }
118
+ if (edges === 0)
119
+ return null;
120
+ lines.push(' classDef command fill:#a8d1ff,stroke:#3b7dd8,color:#06213d');
121
+ lines.push(' classDef event fill:#ffcf8a,stroke:#e08a00,color:#3d2600');
122
+ lines.push(' classDef policy fill:#e3c8ff,stroke:#8a4fd8,color:#2b0f4d');
123
+ if (commands.length > 0)
124
+ lines.push(` class ${commands.join(',')} command`);
125
+ if (events.length > 0)
126
+ lines.push(` class ${events.join(',')} event`);
127
+ if (policies.length > 0)
128
+ lines.push(` class ${policies.join(',')} policy`);
129
+ return lines.join('\n');
130
+ }
131
+ /** The life cycle of an aggregate with a state field. */
132
+ function stateDiagram(aggregate) {
133
+ if (!aggregate.stateField)
134
+ return null;
135
+ const state = aggregate.fields.find((field) => field.names.camel === aggregate.stateField);
136
+ if (!state)
137
+ return null;
138
+ const transitions = aggregate.commands.filter((command) => command.to);
139
+ if (transitions.length === 0)
140
+ return null;
141
+ const lines = ['stateDiagram-v2', ` [*] --> ${aggregate.initialState ?? state.values[0]}`];
142
+ for (const command of transitions) {
143
+ const from = command.from.length > 0 ? command.from : state.values;
144
+ for (const source of from)
145
+ lines.push(` ${source} --> ${command.to}: ${command.name}`);
146
+ }
147
+ const reachable = new Set([aggregate.initialState ?? state.values[0], ...transitions.map((command) => command.to)]);
148
+ const outgoing = new Set(transitions.flatMap((command) => (command.from.length > 0 ? command.from : state.values)));
149
+ for (const value of reachable)
150
+ if (!outgoing.has(value))
151
+ lines.push(` ${value} --> [*]`);
152
+ return lines.join('\n');
153
+ }
154
+ function aggregateBlocks(context, aggregate, basePath) {
155
+ const blocks = [];
156
+ const route = aggregate.route ? `${basePath}${context.prefix}${aggregate.route}` : null;
157
+ blocks.push({ kind: 'heading', level: 3, text: `${aggregate.name} — aggregate root`, id: (0, document_1.slug)(`${context.pascal}-${aggregate.name}`) });
158
+ blocks.push({
159
+ kind: 'paragraph',
160
+ text: [
161
+ route ? `Routes under \`${route}\`.` : 'Not exposed over HTTP.',
162
+ aggregate.entities.length > 0 ? `Entities: ${aggregate.entities.map((name) => `**${name}**`).join(', ')}.` : '',
163
+ `Source: \`${aggregate.file}\`.`,
164
+ ]
165
+ .filter(Boolean)
166
+ .join(' '),
167
+ });
168
+ blocks.push({
169
+ kind: 'table',
170
+ header: ['Field', 'Type', 'Notes'],
171
+ rows: aggregate.fields.map((field) => [`\`${field.names.camel}\``, fieldType(field), fieldNotes(field, aggregate)]),
172
+ });
173
+ if (aggregate.commands.length > 0) {
174
+ blocks.push({ kind: 'heading', level: 4, text: 'Behaviour' });
175
+ blocks.push({
176
+ kind: 'table',
177
+ header: ['Behaviour', 'Allowed when', 'Becomes', 'Records', 'HTTP'],
178
+ rows: aggregate.commands.map((command) => [
179
+ `\`${command.name}(${command.params.map((param) => param.names.camel).join(', ')})\``,
180
+ command.from.length > 0 ? command.from.map((state) => `\`${state}\``).join(', ') : 'always',
181
+ command.to ? `\`${command.to}\`` : '—',
182
+ command.events.join(', ') || '—',
183
+ command.route && route ? `\`POST ${route}${command.route.replace(/^\/:id/, '/:id')}\`` : '—',
184
+ ]),
185
+ });
186
+ }
187
+ const diagram = stateDiagram(aggregate);
188
+ if (diagram) {
189
+ blocks.push({ kind: 'heading', level: 4, text: 'Life cycle' });
190
+ blocks.push({ kind: 'mermaid', code: diagram });
191
+ }
192
+ return blocks;
193
+ }
194
+ function buildMap(scan, generatedOn) {
195
+ const counts = summaryCounts(scan);
196
+ const blocks = [
197
+ { kind: 'heading', level: 1, text: `Domain map — ${scan.name}` },
198
+ {
199
+ kind: 'note',
200
+ text: `Generated from the code by [ddd-express](https://www.npmjs.com/package/ddd-express) on ${generatedOn}. Do not edit by hand — run \`npx ddd-express map\` again.`,
201
+ },
202
+ {
203
+ kind: 'paragraph',
204
+ text: [
205
+ plural(counts.contexts, 'bounded context'),
206
+ plural(counts.aggregates, 'aggregate'),
207
+ plural(counts.behaviours, 'behaviour'),
208
+ plural(counts.events, 'domain event'),
209
+ plural(counts.policies, 'policy', 'policies'),
210
+ plural(counts.valueObjects, 'value object'),
211
+ ].join(' · '),
212
+ },
213
+ ];
214
+ if (scan.contexts.length === 0) {
215
+ blocks.push({ kind: 'paragraph', text: 'No bounded context yet. Start with `npx ddd-express apply` or `npx ddd-express module <name>`.' });
216
+ return blocks;
217
+ }
218
+ blocks.push({ kind: 'heading', level: 2, text: 'Context map' });
219
+ blocks.push({
220
+ kind: 'paragraph',
221
+ text: 'Each box is a bounded context with its aggregates. An arrow means: the context on the right reacts to events of the context on the left — they never call each other.',
222
+ });
223
+ blocks.push({ kind: 'mermaid', code: contextMapDiagram(scan) });
224
+ const flow = eventFlowDiagram(scan);
225
+ if (flow) {
226
+ blocks.push({ kind: 'heading', level: 2, text: 'Event flow' });
227
+ blocks.push({
228
+ kind: 'paragraph',
229
+ text: 'Event Storming colours: behaviour (blue) → domain event (orange) → policy that reacts (purple).',
230
+ });
231
+ blocks.push({ kind: 'mermaid', code: flow });
232
+ }
233
+ for (const context of scan.contexts) {
234
+ blocks.push({ kind: 'heading', level: 2, text: context.pascal, id: (0, document_1.slug)(`context-${context.name}`) });
235
+ if (context.glossary.terms.length > 0) {
236
+ blocks.push({ kind: 'heading', level: 4, text: 'Ubiquitous language' });
237
+ blocks.push({
238
+ kind: 'table',
239
+ header: ['Term', 'Meaning'],
240
+ rows: context.glossary.terms.map((term) => [`**${term.term}**`, term.meaning]),
241
+ });
242
+ }
243
+ for (const aggregate of context.aggregates)
244
+ blocks.push(...aggregateBlocks(context, aggregate, scan.basePath));
245
+ if (context.events.length > 0) {
246
+ const raisedBy = (event) => context.aggregates.flatMap((aggregate) => aggregate.commands.filter((command) => command.events.includes(event)).map((command) => `${aggregate.name}.${command.name}()`));
247
+ const handledBy = (event) => scan.contexts.flatMap((other) => other.handlers
248
+ .filter((handler) => handler.event === event && (handler.eventContext ?? other.name) === context.name)
249
+ .map((handler) => `${handler.className} (${other.pascal})`));
250
+ blocks.push({ kind: 'heading', level: 4, text: 'Domain events' });
251
+ blocks.push({
252
+ kind: 'table',
253
+ header: ['Event', 'Carries', 'Recorded by', 'Handled by'],
254
+ rows: context.events.map((event) => [
255
+ `**${event.name}**`,
256
+ ['aggregateId', ...event.fields.map((field) => field.names.camel)].map((name) => `\`${name}\``).join(', '),
257
+ raisedBy(event.name).join(', ') || (/(Created|Updated|Deleted)$/.test(event.name) ? 'create / update / delete' : '—'),
258
+ handledBy(event.name).join(', ') || '—',
259
+ ]),
260
+ });
261
+ }
262
+ if (context.handlers.length > 0) {
263
+ blocks.push({ kind: 'heading', level: 4, text: 'Reacts to' });
264
+ blocks.push({
265
+ kind: 'table',
266
+ header: ['Event', 'Published by', 'Handler'],
267
+ rows: context.handlers.map((handler) => [
268
+ handler.event,
269
+ handler.eventContext ? scan.contexts.find((item) => item.name === handler.eventContext)?.pascal ?? handler.eventContext : '?',
270
+ `**${handler.className}**`,
271
+ ]),
272
+ });
273
+ }
274
+ const extras = [];
275
+ if (context.valueObjects.length > 0)
276
+ extras.push(`Value objects: ${context.valueObjects.map((name) => `**${name}**`).join(', ')}`);
277
+ if (context.services.length > 0)
278
+ extras.push(`Domain services: ${context.services.map((name) => `**${name}**`).join(', ')}`);
279
+ if (extras.length > 0)
280
+ blocks.push({ kind: 'list', items: extras });
281
+ }
282
+ return blocks;
283
+ }
@@ -0,0 +1,7 @@
1
+ import type { ScannedProject } from '../scan/project-scan';
2
+ type Json = Record<string, unknown>;
3
+ /** OpenAPI 3.1 document of every route the generated code exposes. */
4
+ export declare function buildOpenApi(scan: ScannedProject): Json;
5
+ /** A standalone HTML page that renders the OpenAPI document (Scalar API reference, from a CDN). */
6
+ export declare function apiReferenceHtml(spec: Json, title: string): string;
7
+ export {};
@@ -0,0 +1,236 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildOpenApi = buildOpenApi;
4
+ exports.apiReferenceHtml = apiReferenceHtml;
5
+ const names_1 = require("../core/names");
6
+ function fieldSchema(field, nullable) {
7
+ let schema;
8
+ switch (field.type) {
9
+ case 'string':
10
+ schema = { type: 'string', minLength: 1 };
11
+ break;
12
+ case 'number':
13
+ schema = { type: 'number' };
14
+ break;
15
+ case 'integer':
16
+ schema = { type: 'integer' };
17
+ break;
18
+ case 'boolean':
19
+ schema = { type: 'boolean' };
20
+ break;
21
+ case 'date':
22
+ schema = { type: 'string', format: 'date-time' };
23
+ break;
24
+ case 'enum':
25
+ schema = { type: 'string', enum: [...field.values] };
26
+ break;
27
+ }
28
+ if (nullable) {
29
+ schema = { ...schema, type: [schema.type, 'null'] };
30
+ if (Array.isArray(schema.enum))
31
+ schema.enum = [...schema.enum, null];
32
+ }
33
+ if (field.defaultValue !== undefined && typeof field.defaultValue !== 'object')
34
+ schema.default = field.defaultValue;
35
+ return schema;
36
+ }
37
+ const ref = (name) => ({ $ref: `#/components/schemas/${name}` });
38
+ const json = (schema) => ({ 'application/json': { schema } });
39
+ const errors = (...codes) => Object.fromEntries(codes.map((code) => [code, { $ref: `#/components/responses/${{ '400': 'BadRequest', '404': 'NotFound', '422': 'BusinessRuleBroken' }[code]}` }]));
40
+ function objectSchema(fields, options) {
41
+ const required = fields.filter(options.required).map((field) => field.names.camel);
42
+ return {
43
+ type: 'object',
44
+ properties: Object.fromEntries(fields.map((field) => [field.names.camel, fieldSchema(field, options.nullable(field))])),
45
+ ...(required.length > 0 ? { required } : {}),
46
+ additionalProperties: false,
47
+ };
48
+ }
49
+ function addAggregate(spec, context, aggregate, basePath) {
50
+ if (!aggregate.route)
51
+ return null;
52
+ const names = (0, names_1.namesFromWords)((0, names_1.splitWords)(aggregate.kebab));
53
+ const plural = (0, names_1.pluralize)(names);
54
+ const tag = aggregate.name;
55
+ const base = `${basePath}${context.prefix}${aggregate.route}`;
56
+ const inputs = aggregate.fields.filter((field) => !field.managed);
57
+ const schemas = spec.components.schemas;
58
+ const paths = spec.paths;
59
+ schemas[aggregate.name] = {
60
+ type: 'object',
61
+ description: `${aggregate.name} — aggregate root of the ${context.pascal} context.`,
62
+ properties: {
63
+ id: { type: 'string' },
64
+ ...Object.fromEntries(aggregate.fields.map((field) => [field.names.camel, fieldSchema(field, field.optional)])),
65
+ createdAt: { type: 'string', format: 'date-time' },
66
+ updatedAt: { type: 'string', format: 'date-time' },
67
+ },
68
+ required: ['id', ...aggregate.fields.map((field) => field.names.camel), 'createdAt', 'updatedAt'],
69
+ };
70
+ schemas[`${aggregate.name}Page`] = {
71
+ type: 'object',
72
+ properties: {
73
+ items: { type: 'array', items: ref(aggregate.name) },
74
+ total: { type: 'integer', minimum: 0 },
75
+ limit: { type: 'integer', minimum: 1 },
76
+ offset: { type: 'integer', minimum: 0 },
77
+ },
78
+ required: ['items', 'total', 'limit', 'offset'],
79
+ };
80
+ schemas[`Create${aggregate.name}Input`] = objectSchema(inputs, {
81
+ required: (field) => !field.optional && field.defaultValue === undefined,
82
+ nullable: (field) => field.optional,
83
+ });
84
+ schemas[`Update${aggregate.name}Input`] = objectSchema(inputs, { required: () => false, nullable: (field) => field.optional });
85
+ const idParam = { name: 'id', in: 'path', required: true, schema: { type: 'string' } };
86
+ const collection = {};
87
+ const item = {};
88
+ if (aggregate.crud.create) {
89
+ collection.post = {
90
+ tags: [tag],
91
+ operationId: `create${aggregate.name}`,
92
+ summary: `Create ${articleFor(names.human)} ${names.human}`,
93
+ requestBody: { required: true, content: json(ref(`Create${aggregate.name}Input`)) },
94
+ responses: {
95
+ '201': {
96
+ description: 'Created',
97
+ headers: { Location: { description: 'URL of the new resource', schema: { type: 'string' } } },
98
+ content: json(ref(aggregate.name)),
99
+ },
100
+ ...errors('400', '422'),
101
+ },
102
+ };
103
+ }
104
+ if (aggregate.crud.list) {
105
+ collection.get = {
106
+ tags: [tag],
107
+ operationId: `list${plural.pascal}`,
108
+ summary: `List ${plural.human}, page by page`,
109
+ parameters: [
110
+ { name: 'limit', in: 'query', schema: { type: 'integer', minimum: 1, maximum: 100, default: 20 } },
111
+ { name: 'offset', in: 'query', schema: { type: 'integer', minimum: 0, default: 0 } },
112
+ ],
113
+ responses: { '200': { description: 'A page', content: json(ref(`${aggregate.name}Page`)) }, ...errors('400') },
114
+ };
115
+ }
116
+ if (aggregate.crud.get) {
117
+ item.get = {
118
+ tags: [tag],
119
+ operationId: `get${aggregate.name}`,
120
+ summary: `Get ${articleFor(names.human)} ${names.human}`,
121
+ parameters: [idParam],
122
+ responses: { '200': { description: 'Found', content: json(ref(aggregate.name)) }, ...errors('404') },
123
+ };
124
+ }
125
+ if (aggregate.crud.update) {
126
+ item.patch = {
127
+ tags: [tag],
128
+ operationId: `update${aggregate.name}`,
129
+ summary: `Change ${articleFor(names.human)} ${names.human} (only the fields sent)`,
130
+ parameters: [idParam],
131
+ requestBody: { required: true, content: json(ref(`Update${aggregate.name}Input`)) },
132
+ responses: { '200': { description: 'Changed', content: json(ref(aggregate.name)) }, ...errors('400', '404', '422') },
133
+ };
134
+ }
135
+ if (aggregate.crud.delete) {
136
+ item.delete = {
137
+ tags: [tag],
138
+ operationId: `delete${aggregate.name}`,
139
+ summary: `Delete ${articleFor(names.human)} ${names.human}`,
140
+ parameters: [idParam],
141
+ responses: { '204': { description: 'Deleted' }, ...errors('404') },
142
+ };
143
+ }
144
+ if (Object.keys(collection).length > 0)
145
+ paths[base] = collection;
146
+ if (Object.keys(item).length > 0)
147
+ paths[`${base}/{id}`] = item;
148
+ for (const command of aggregate.commands) {
149
+ if (!command.route)
150
+ continue;
151
+ const commandNames = (0, names_1.namesFromWords)((0, names_1.splitWords)(command.name));
152
+ const inputName = `${commandNames.pascal}${aggregate.name}Input`;
153
+ const description = [
154
+ command.from.length > 0 ? `Allowed when \`${aggregate.stateField}\` is ${command.from.map((state) => `\`${state}\``).join(' or ')}.` : '',
155
+ command.to ? `Sets \`${aggregate.stateField}\` to \`${command.to}\`.` : '',
156
+ command.events.length > 0 ? `Records ${command.events.join(', ')}.` : '',
157
+ ]
158
+ .filter(Boolean)
159
+ .join(' ');
160
+ if (command.params.length > 0) {
161
+ schemas[inputName] = objectSchema(command.params, { required: (field) => !field.optional, nullable: (field) => field.optional });
162
+ }
163
+ const operation = {
164
+ tags: [tag],
165
+ operationId: `${command.name}${aggregate.name}`,
166
+ summary: `${capitalize(commandNames.human)} ${articleFor(names.human)} ${names.human}`,
167
+ ...(description ? { description } : {}),
168
+ parameters: [idParam],
169
+ ...(command.params.length > 0 ? { requestBody: { required: true, content: json(ref(inputName)) } } : {}),
170
+ responses: {
171
+ '200': { description: 'Done', content: json(ref(aggregate.name)) },
172
+ ...errors(...(command.params.length > 0 ? ['400', '404', '422'] : ['404', '422'])),
173
+ },
174
+ };
175
+ paths[`${base}${command.route.replace(/:id/g, '{id}')}`] = { post: operation };
176
+ }
177
+ return tag;
178
+ }
179
+ const capitalize = (text) => text.charAt(0).toUpperCase() + text.slice(1);
180
+ const articleFor = (word) => (/^[aeiou]/i.test(word) ? 'an' : 'a');
181
+ /** OpenAPI 3.1 document of every route the generated code exposes. */
182
+ function buildOpenApi(scan) {
183
+ const spec = {
184
+ openapi: '3.1.0',
185
+ info: {
186
+ title: scan.name,
187
+ version: scan.version,
188
+ description: `Generated from the code by ddd-express. Bounded contexts: ${scan.contexts.map((context) => context.pascal).join(', ') || 'none yet'}.`,
189
+ },
190
+ tags: [],
191
+ paths: {},
192
+ components: {
193
+ schemas: {
194
+ Error: {
195
+ type: 'object',
196
+ properties: {
197
+ error: { type: 'string', description: 'Error type, e.g. DomainError' },
198
+ message: { type: 'string' },
199
+ details: { type: 'array', items: { type: 'string' }, description: 'Every problem of a malformed request' },
200
+ },
201
+ required: ['error', 'message'],
202
+ },
203
+ },
204
+ responses: {
205
+ BadRequest: { description: 'The request is malformed (types, required or unknown fields).', content: json(ref('Error')) },
206
+ NotFound: { description: 'Not found.', content: json(ref('Error')) },
207
+ BusinessRuleBroken: { description: 'A business rule of the domain refused the change.', content: json(ref('Error')) },
208
+ },
209
+ },
210
+ };
211
+ for (const context of scan.contexts) {
212
+ for (const aggregate of context.aggregates) {
213
+ const tag = addAggregate(spec, context, aggregate, scan.basePath);
214
+ if (tag)
215
+ spec.tags.push({ name: tag, description: `${context.pascal} context` });
216
+ }
217
+ }
218
+ return spec;
219
+ }
220
+ /** A standalone HTML page that renders the OpenAPI document (Scalar API reference, from a CDN). */
221
+ function apiReferenceHtml(spec, title) {
222
+ const data = JSON.stringify(spec).replace(/</g, '\\u003c');
223
+ return `<!DOCTYPE html>
224
+ <html lang="en">
225
+ <head>
226
+ <meta charset="utf-8">
227
+ <meta name="viewport" content="width=device-width, initial-scale=1">
228
+ <title>${title.replace(/</g, '&lt;')} — API reference</title>
229
+ </head>
230
+ <body>
231
+ <script id="api-reference" type="application/json">${data}</script>
232
+ <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
233
+ </body>
234
+ </html>
235
+ `;
236
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const run_1 = require("./run");
5
+ try {
6
+ process.exitCode = (0, run_1.run)(process.argv.slice(2));
7
+ }
8
+ catch (error) {
9
+ console.error(error);
10
+ console.error('\nddd-express hit an unexpected error. Please report it: https://github.com/Moustafa1997/ddd-express/issues');
11
+ process.exitCode = 1;
12
+ }
@@ -0,0 +1,5 @@
1
+ /** An expected problem (bad input, missing project...) shown to the user without a stack trace. */
2
+ export declare class CliError extends Error {
3
+ readonly hint?: string;
4
+ constructor(message: string, hint?: string);
5
+ }
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CliError = void 0;
4
+ /** An expected problem (bad input, missing project...) shown to the user without a stack trace. */
5
+ class CliError extends Error {
6
+ hint;
7
+ constructor(message, hint) {
8
+ super(message);
9
+ this.name = 'CliError';
10
+ this.hint = hint;
11
+ }
12
+ }
13
+ exports.CliError = CliError;
@@ -0,0 +1,38 @@
1
+ import { type Names } from './names';
2
+ export type FieldType = 'string' | 'number' | 'integer' | 'boolean' | 'date' | 'enum';
3
+ /** A literal default value. For date fields the only default is "now". */
4
+ export type DefaultValue = string | number | boolean | {
5
+ now: true;
6
+ };
7
+ export interface Field {
8
+ names: Names;
9
+ type: FieldType;
10
+ /** May be missing/null. */
11
+ optional: boolean;
12
+ /** Allowed values, only for enum fields. */
13
+ values: string[];
14
+ /** Used when the value is not given on creation. */
15
+ defaultValue?: DefaultValue;
16
+ /** Changed only by commands (the state of a state machine): not part of create/update input. */
17
+ managed?: boolean;
18
+ }
19
+ export declare const JS_KEYWORDS: Set<string>;
20
+ export declare const SUPPORTED_TYPES_HELP: string;
21
+ /** Splits on `separator` when it is not inside parentheses or quotes. */
22
+ export declare function splitTopLevel(input: string, separator?: string): string[];
23
+ export declare function fieldNames(raw: string): Names;
24
+ /** A literal for a field ("= value" in a model): null is allowed for optional fields. */
25
+ export declare function parseLiteral(raw: string, field: Field): DefaultValue | null;
26
+ /**
27
+ * Parses one field: "name[?]: type [= default]".
28
+ * Types: string number integer boolean date, "a | b | c" or "enum(a|b|c)".
29
+ */
30
+ export declare function parseField(token: string, reserved?: readonly string[]): Field;
31
+ /**
32
+ * Parses --fields "clientId:string, scheduledStart:date, notes?:string, status:enum(planned|done)".
33
+ * `reserved` lists names the target class already uses (id, createdAt, ...).
34
+ */
35
+ export declare function parseFields(input: string | undefined, reserved?: readonly string[]): Field[];
36
+ /** Fields that callers provide (state-machine fields are changed by commands only). */
37
+ export declare const inputFields: (fields: Field[]) => Field[];
38
+ export declare const hasDefault: (field: Field) => boolean;