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,376 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parserFunction = exports.inputType = exports.useCaseClass = exports.stateFieldOf = void 0;
4
+ exports.article = article;
5
+ exports.inlineType = inlineType;
6
+ exports.commandMethod = commandMethod;
7
+ exports.literalExpr = literalExpr;
8
+ exports.ensureStateMethod = ensureStateMethod;
9
+ exports.commandUseCase = commandUseCase;
10
+ exports.commandRequest = commandRequest;
11
+ exports.commandRoute = commandRoute;
12
+ exports.commandRouterImports = commandRouterImports;
13
+ exports.commandFacadeEntry = commandFacadeEntry;
14
+ exports.commandUseCaseSpec = commandUseCaseSpec;
15
+ exports.commandRouterSpec = commandRouterSpec;
16
+ const project_1 = require("../core/project");
17
+ const code_1 = require("./code");
18
+ const field_code_1 = require("./field-code");
19
+ const q = (value) => `'${value}'`;
20
+ function article(word) {
21
+ return /^[aeiou]/i.test(word) ? 'an' : 'a';
22
+ }
23
+ const stateFieldOf = (fields) => fields.find((field) => field.managed) ?? null;
24
+ exports.stateFieldOf = stateFieldOf;
25
+ /** Type of a command parameter or event member: enum values are written inline ('a' | 'b'). */
26
+ function inlineType(owner, field) {
27
+ return field.type === 'enum' ? field.values.map(q).join(' | ') : (0, field_code_1.baseType)(owner, field);
28
+ }
29
+ function paramSignature(owner, field) {
30
+ const type = inlineType(owner, field);
31
+ return field.optional ? `${field.names.camel}?: ${type} | null` : `${field.names.camel}: ${type}`;
32
+ }
33
+ /** Guard for a parameter; enum values are listed inline. */
34
+ function paramGuard(owner, field, valueExpr) {
35
+ if (field.type !== 'enum')
36
+ return (0, field_code_1.guardCall)(owner, field, valueExpr);
37
+ const check = (expr) => `Guard.oneOf(${expr}, [${field.values.map(q).join(', ')}], '${field.names.camel}')`;
38
+ return field.optional ? `Guard.optional(${valueExpr}, (value) => ${check('value')})` : check(valueExpr);
39
+ }
40
+ const useCaseClass = (m) => `${m.command.names.pascal}${m.aggregate.names.pascal}UseCase`;
41
+ exports.useCaseClass = useCaseClass;
42
+ const inputType = (m) => `${m.command.names.pascal}${m.aggregate.names.pascal}Input`;
43
+ exports.inputType = inputType;
44
+ const parserFunction = (m) => `parse${m.command.names.pascal}${m.aggregate.names.pascal}Body`;
45
+ exports.parserFunction = parserFunction;
46
+ // =============================================================================================
47
+ // The method on the aggregate
48
+ // =============================================================================================
49
+ /** The behaviour method, indented for the class body. */
50
+ function commandMethod(owner, fields, command) {
51
+ const state = (0, exports.stateFieldOf)(fields);
52
+ const params = command.params;
53
+ const used = new Set([
54
+ ...command.assigns,
55
+ ...(command.emits?.payload.filter((item) => item.source === 'param').map((item) => item.name) ?? []),
56
+ ]);
57
+ const changesState = Boolean(command.transition && state) || command.assigns.length > 0 || command.sets.length > 0;
58
+ const signatureParts = [
59
+ ...params.map((param) => paramSignature(owner, param)),
60
+ ...(changesState ? ['now: Date = new Date()'] : []),
61
+ ];
62
+ const signature = signatureParts.join(', ');
63
+ const doc = [`/**`, ` * ${capitalize(command.names.human)}.`];
64
+ if (command.transition && state) {
65
+ doc.push(` * ${state.names.camel}: ${command.transition.from.join(', ')} → ${command.transition.to}.`);
66
+ }
67
+ if (command.emits)
68
+ doc.push(` * Records ${command.emits.names.pascal}.`);
69
+ doc.push(' */');
70
+ const body = [];
71
+ if (command.transition) {
72
+ body.push(`this.ensureState([${command.transition.from.map(q).join(', ')}], '${command.names.human}');`);
73
+ }
74
+ if (params.length > 0 && used.size > 0) {
75
+ body.push('const args = {');
76
+ for (const param of params)
77
+ body.push(` ${param.names.camel}: ${paramGuard(owner, param, param.names.camel)},`);
78
+ body.push('};');
79
+ }
80
+ else {
81
+ for (const param of params)
82
+ body.push(`${paramGuard(owner, param, param.names.camel)};`);
83
+ }
84
+ body.push(`// Add the business rules of "${command.names.human}" here (throw a DomainError to refuse).`);
85
+ const changes = [];
86
+ if (command.transition && state)
87
+ changes.push(`${state.names.camel}: '${command.transition.to}'`);
88
+ for (const name of command.assigns)
89
+ changes.push(`${name}: args.${name}`);
90
+ for (const set of command.sets)
91
+ changes.push(`${set.name}: ${literalExpr(set.value)}`);
92
+ if (changes.length > 0)
93
+ body.push(`this.props = { ...this.props, ${changes.join(', ')}, updatedAt: now };`);
94
+ if (command.emits) {
95
+ const values = command.emits.payload.map((item) => item.source === 'param' ? `args.${item.name}` : `this.props.${item.name}`);
96
+ body.push(`this.record(new ${command.emits.names.pascal}(${['this.id', ...values].join(', ')}));`);
97
+ }
98
+ const opening = `${command.names.camel}(${signature}): void {`;
99
+ const head = opening.length + 2 <= 100
100
+ ? [opening]
101
+ : [
102
+ `${command.names.camel}(`,
103
+ ...signatureParts.map((part) => ` ${part},`),
104
+ '): void {',
105
+ ];
106
+ return (0, code_1.indent)([...doc, ...head, ...(0, code_1.indent)(body), '}']);
107
+ }
108
+ const capitalize = (text) => text.charAt(0).toUpperCase() + text.slice(1);
109
+ /** TypeScript expression of a literal set by a command. */
110
+ function literalExpr(value) {
111
+ if (value === null)
112
+ return 'null';
113
+ if (typeof value === 'object')
114
+ return 'now';
115
+ if (typeof value === 'string')
116
+ return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
117
+ return String(value);
118
+ }
119
+ /** The guard every state change uses, indented for the class body. */
120
+ function ensureStateMethod(owner, state, stateType) {
121
+ return (0, code_1.indent)([
122
+ `/** Allows a behaviour only in the given states — the state machine of ${article(owner.human)} ${owner.pascal}. */`,
123
+ `private ensureState(allowed: readonly ${stateType}[], behaviour: string): void {`,
124
+ ` if (!allowed.includes(this.props.${state.names.camel})) {`,
125
+ ' throw new DomainError(',
126
+ ` \`Cannot \${behaviour} ${article(owner.human)} ${owner.human} that is \${this.props.${state.names.camel}} (allowed when: \${allowed.join(', ')})\`,`,
127
+ ' );',
128
+ ' }',
129
+ '}',
130
+ ]);
131
+ }
132
+ // =============================================================================================
133
+ // Use case, request parser, router block, facade entry
134
+ // =============================================================================================
135
+ function commandUseCase(m) {
136
+ const a = m.aggregate.names;
137
+ const file = (0, project_1.ts)(m.paths.useCase);
138
+ const imp = (0, code_1.importer)(m.project, file);
139
+ const s = (0, project_1.sharedPaths)(m.project);
140
+ const params = m.command.params;
141
+ const repo = m.aggregate.plural.camel;
142
+ const args = params.map((param) => `input.${param.names.camel}`).join(', ');
143
+ return (0, code_1.lines)(`import type { ${a.pascal}Repository } from ${imp(m.context.portsIndex)};`, `import type { EventBus } from ${imp(s.eventBus)};`, `import { NotFoundError } from ${imp(s.domainError)};`, `import { to${a.pascal}Dto, type ${a.pascal}Dto } from ${imp(m.aggregate.dto)};`, '', params.length > 0 && [
144
+ `export interface ${(0, exports.inputType)(m)} {`,
145
+ ...(0, code_1.indent)(params.map((param) => `${paramSignature(a, param)};`)),
146
+ '}',
147
+ '',
148
+ ], '/**', ` * Use case: ${m.command.names.human} ${article(a.human)} ${a.pascal}.`, ' * Load → call the behaviour → save → publish. The rules live in the aggregate.', ' */', `export class ${(0, exports.useCaseClass)(m)} {`, ` private readonly ${repo}: ${a.pascal}Repository;`, ' private readonly events: EventBus;', '', ` constructor(${repo}: ${a.pascal}Repository, events: EventBus) {`, ` this.${repo} = ${repo};`, ' this.events = events;', ' }', '', params.length > 0
149
+ ? ` async execute(id: string, input: ${(0, exports.inputType)(m)}): Promise<${a.pascal}Dto> {`
150
+ : ` async execute(id: string): Promise<${a.pascal}Dto> {`, ` const ${a.camel} = await this.${repo}.findById(id);`, ` if (!${a.camel}) throw new NotFoundError('${a.pascal}', id);`, ` ${a.camel}.${m.command.names.camel}(${args});`, ` await this.${repo}.save(${a.camel});`, ` await this.events.publish(${a.camel}.pullEvents());`, ` return to${a.pascal}Dto(${a.camel});`, ' }', '}');
151
+ }
152
+ function paramParser(field) {
153
+ switch (field.type) {
154
+ case 'string':
155
+ return 'asText';
156
+ case 'number':
157
+ return 'asNumber';
158
+ case 'integer':
159
+ return 'asInteger';
160
+ case 'boolean':
161
+ return 'asBoolean';
162
+ case 'date':
163
+ return 'asDate';
164
+ case 'enum':
165
+ return `asOneOf([${field.values.map(q).join(', ')}] as const)`;
166
+ }
167
+ }
168
+ function commandRequest(m) {
169
+ const params = m.command.params;
170
+ if (params.length === 0)
171
+ return null;
172
+ const file = (0, project_1.ts)(m.paths.request);
173
+ const imp = (0, code_1.importer)(m.project, file);
174
+ const parsers = [...new Set(params.map((param) => paramParser(param).replace(/\(.*$/, '')))].sort();
175
+ return (0, code_1.lines)(`import { RequestBody, ${parsers.join(', ')} } from ${imp((0, project_1.sharedPaths)(m.project).requestBody)};`, `import type { ${(0, exports.inputType)(m)} } from ${imp(m.paths.useCase)};`, '', `/** POST /:id/${m.command.names.kebab} body → ${(0, exports.inputType)(m)}. Shape only — the ${m.aggregate.names.pascal} checks the rules. */`, `export function ${(0, exports.parserFunction)(m)}(raw: unknown): ${(0, exports.inputType)(m)} {`, ' const body = new RequestBody(raw);', ` const input: ${(0, exports.inputType)(m)} = {`, ...(0, code_1.indent)(params.map((param) => `${param.names.camel}: body.${param.optional ? 'optional' : 'required'}('${param.names.camel}', ${paramParser(param)}),`), 4), ' };', ' body.assertValid();', ' return input;', '}');
176
+ }
177
+ /** The route of a command, indented for the router function body. */
178
+ function commandRoute(m) {
179
+ const call = m.command.params.length > 0
180
+ ? [`const input = ${(0, exports.parserFunction)(m)}(req.body);`, `res.json(await useCases.${m.command.names.camel}.execute(routeParam(req, 'id'), input));`]
181
+ : [`res.json(await useCases.${m.command.names.camel}.execute(routeParam(req, 'id')));`];
182
+ return (0, code_1.indent)([
183
+ 'router.post(',
184
+ ` '/:id/${m.command.names.kebab}',`,
185
+ ' asyncHandler(async (req, res) => {',
186
+ ...(0, code_1.indent)(call, 4),
187
+ ' }),',
188
+ ');',
189
+ ]);
190
+ }
191
+ function commandRouterImports(m, routerFile) {
192
+ if (m.command.params.length === 0)
193
+ return [];
194
+ const imp = (0, code_1.importer)(m.project, routerFile);
195
+ return [`import { ${(0, exports.parserFunction)(m)} } from ${imp(m.paths.request)};`];
196
+ }
197
+ function commandFacadeEntry(m) {
198
+ const imp = (0, code_1.importer)(m.project, (0, project_1.ts)(m.aggregate.useCases));
199
+ return {
200
+ imports: [`import { ${(0, exports.useCaseClass)(m)} } from ${imp(m.paths.useCase)};`],
201
+ entry: ` ${m.command.names.camel}: new ${(0, exports.useCaseClass)(m)}(${m.aggregate.plural.camel}, events),`,
202
+ };
203
+ }
204
+ // =============================================================================================
205
+ // Tests
206
+ // =============================================================================================
207
+ function givenHelper(m) {
208
+ const a = m.aggregate.names;
209
+ const state = (0, exports.stateFieldOf)(m.fields);
210
+ const stateType = state ? `'${state.values.join("' | '")}'` : null;
211
+ return [
212
+ `/** ${capitalize(article(a.human))} ${a.human} already stored${state ? ' in the given state' : ''} (rehydrate skips the rules, like loading from the database). */`,
213
+ state
214
+ ? `async function given${a.pascal}(repository: InMemory${a.pascal}Repository, ${state.names.camel}: ${stateType}): Promise<string> {`
215
+ : `async function given${a.pascal}(repository: InMemory${a.pascal}Repository): Promise<string> {`,
216
+ ` const ${a.camel} = ${a.pascal}.rehydrate('${a.kebab}-1', {`,
217
+ ...(0, code_1.indent)(m.fields.map((field) => field.managed ? `${field.names.camel},` : `${field.names.camel}: ${(0, field_code_1.sample)(field).domain},`), 4),
218
+ " createdAt: new Date('2026-01-01T08:00:00.000Z'),",
219
+ " updatedAt: new Date('2026-01-01T08:00:00.000Z'),",
220
+ ' });',
221
+ ` await repository.save(${a.camel});`,
222
+ ` return ${a.camel}.id;`,
223
+ '}',
224
+ ];
225
+ }
226
+ function callArgs(m, valid = true) {
227
+ const params = m.command.params;
228
+ if (params.length === 0)
229
+ return '';
230
+ const entries = params.map((param, index) => {
231
+ const value = !valid && index === 0 ? (0, field_code_1.invalidDomainValue)(param) : (0, field_code_1.sample)(param).domain;
232
+ return `${param.names.camel}: ${value}`;
233
+ });
234
+ return `, { ${entries.join(', ')} }`;
235
+ }
236
+ /** Expected value of a field after the command, as plain JSON (for DTO assertions). */
237
+ function expectedPayloadSample(m, name, source) {
238
+ const state = (0, exports.stateFieldOf)(m.fields);
239
+ if (source === 'param')
240
+ return (0, field_code_1.sample)(m.command.params.find((param) => param.names.camel === name));
241
+ if (m.command.assigns.includes(name))
242
+ return (0, field_code_1.sample)(m.command.params.find((param) => param.names.camel === name));
243
+ const set = m.command.sets.find((item) => item.name === name);
244
+ if (set && set.value !== null && typeof set.value !== 'object') {
245
+ const expr = literalExpr(set.value);
246
+ return { domain: expr, plain: expr };
247
+ }
248
+ if (state && name === state.names.camel && m.command.transition)
249
+ return (0, field_code_1.enumSample)(m.command.transition.to);
250
+ if (state && name === state.names.camel)
251
+ return (0, field_code_1.enumSample)((0, field_code_1.initialState)(state));
252
+ return (0, field_code_1.sample)(m.fields.find((field) => field.names.camel === name));
253
+ }
254
+ function commandUseCaseSpec(m) {
255
+ const a = m.aggregate.names;
256
+ const c = m.command;
257
+ const file = (0, project_1.ts)(m.paths.useCaseSpec);
258
+ const imp = (0, code_1.importer)(m.project, file);
259
+ const s = (0, project_1.sharedPaths)(m.project);
260
+ const state = (0, exports.stateFieldOf)(m.fields);
261
+ const from = c.transition ? c.transition.from[0] : state ? (0, field_code_1.initialState)(state) : null;
262
+ const refused = c.transition && state ? state.values.find((value) => !c.transition?.from.includes(value)) ?? null : null;
263
+ const fromArg = state ? `, '${from}'` : '';
264
+ const checksPayload = Boolean(c.emits && c.emits.payload.length > 0);
265
+ const eventImports = c.emits && checksPayload
266
+ ? [`import { ${c.emits.names.pascal} } from ${imp(`${m.context.events}/${c.emits.names.kebab}.event`)};`]
267
+ : [];
268
+ const errors = refused || c.params.length > 0 ? 'DomainError, NotFoundError' : 'NotFoundError';
269
+ const happyAsserts = [];
270
+ if (c.transition && state)
271
+ happyAsserts.push(`assert.equal(result.${state.names.camel}, '${c.transition.to}');`);
272
+ for (const name of c.assigns) {
273
+ const field = m.fields.find((candidate) => candidate.names.camel === name);
274
+ happyAsserts.push(`assert.deepEqual(result.${name}, ${(0, field_code_1.sample)(field).plain});`);
275
+ }
276
+ for (const set of c.sets) {
277
+ if (set.value === null)
278
+ happyAsserts.push(`assert.equal(result.${set.name}, null);`);
279
+ else if (typeof set.value === 'object')
280
+ happyAsserts.push(`assert.equal(typeof result.${set.name}, 'string');`);
281
+ else
282
+ happyAsserts.push(`assert.equal(result.${set.name}, ${literalExpr(set.value)});`);
283
+ }
284
+ const usesResult = happyAsserts.some((line) => line.includes('result.'));
285
+ if (c.emits) {
286
+ happyAsserts.push(`assert.deepEqual(events.names, ['${c.emits.names.pascal}']);`);
287
+ if (c.emits.payload.length > 0) {
288
+ happyAsserts.push('const [event] = events.published;', `assert.ok(event instanceof ${c.emits.names.pascal});`);
289
+ for (const item of c.emits.payload) {
290
+ happyAsserts.push((0, field_code_1.sameAsSample)(item.field, `event.${item.name}`, expectedPayloadSample(m, item.name, item.source)));
291
+ }
292
+ }
293
+ }
294
+ else {
295
+ happyAsserts.push('assert.deepEqual(events.names, []);');
296
+ }
297
+ return (0, code_1.lines)((0, code_1.sortImports)([
298
+ ...(0, code_1.testImports)(m.project.config.testRunner),
299
+ `import { ${errors} } from ${imp(s.domainError)};`,
300
+ `import { RecordingEventBus } from ${imp(s.recordingEventBus)};`,
301
+ `import { ${a.pascal} } from ${imp(m.aggregate.index)};`,
302
+ ...eventImports,
303
+ `import { InMemory${a.pascal}Repository } from ${imp(m.aggregate.repository)};`,
304
+ `import { create${a.pascal}UseCases } from ${imp(m.aggregate.useCases)};`,
305
+ ]), '', 'function setup() {', ` const repository = new InMemory${a.pascal}Repository();`, ' const events = new RecordingEventBus();', ` return { repository, events, useCases: create${a.pascal}UseCases(repository, events) };`, '}', '', givenHelper(m), '', `describe('${capitalize(c.names.human)} ${article(a.human)} ${a.human}', () => {`, ` it('${c.names.human}: ${article(a.human)} ${a.human}${from && c.transition ? ` that is ${from} becomes ${c.transition.to}` : ' is changed'}${c.emits ? `, then ${c.emits.names.pascal} is published` : ''}', async () => {`, ' const { repository, events, useCases } = setup();', ` const id = await given${a.pascal}(repository${fromArg});`, '', usesResult
306
+ ? ` const result = await useCases.${c.names.camel}.execute(id${callArgs(m)});`
307
+ : ` await useCases.${c.names.camel}.execute(id${callArgs(m)});`, '', ...(0, code_1.indent)(happyAsserts, 4), ' });', refused && [
308
+ '',
309
+ ` it('refuses when the ${a.human} is ${refused}, and publishes nothing', async () => {`,
310
+ ' const { repository, events, useCases } = setup();',
311
+ ` const id = await given${a.pascal}(repository, '${refused}');`,
312
+ '',
313
+ ` await assert.rejects(useCases.${c.names.camel}.execute(id${callArgs(m)}), DomainError);`,
314
+ '',
315
+ ` assert.equal((await useCases.get.execute(id)).${state?.names.camel}, '${refused}');`,
316
+ ' assert.deepEqual(events.names, []);',
317
+ ' });',
318
+ ], c.params.length > 0 && [
319
+ '',
320
+ ` it('rejects an invalid ${c.params[0].names.human}', async () => {`,
321
+ ' const { repository, events, useCases } = setup();',
322
+ ` const id = await given${a.pascal}(repository${fromArg});`,
323
+ '',
324
+ ` await assert.rejects(useCases.${c.names.camel}.execute(id${callArgs(m, false)}), DomainError);`,
325
+ ' assert.deepEqual(events.names, []);',
326
+ ' });',
327
+ ], '', ` it('fails with NotFoundError for an unknown ${a.human}', async () => {`, ' const { useCases } = setup();', '', ` await assert.rejects(useCases.${c.names.camel}.execute('missing-id'${callArgs(m)}), NotFoundError);`, ' });', '});');
328
+ }
329
+ function commandRouterSpec(m, route) {
330
+ const a = m.aggregate.names;
331
+ const c = m.command;
332
+ const file = (0, project_1.ts)(m.paths.routerSpec);
333
+ const imp = (0, code_1.importer)(m.project, file);
334
+ const s = (0, project_1.sharedPaths)(m.project);
335
+ const state = (0, exports.stateFieldOf)(m.fields);
336
+ const from = c.transition ? c.transition.from[0] : state ? (0, field_code_1.initialState)(state) : null;
337
+ const refused = c.transition && state ? state.values.find((value) => !c.transition?.from.includes(value)) ?? null : null;
338
+ const fromArg = state ? `, '${from}'` : '';
339
+ const required = c.params.find((param) => !param.optional);
340
+ const body = c.params.length > 0
341
+ ? `{ ${c.params.map((param) => `${param.names.camel}: ${(0, field_code_1.sample)(param).plain}`).join(', ')} }`
342
+ : null;
343
+ const send = (target, sentBody) => sentBody ? `call(\`\${url}/${target}/${c.names.kebab}\`, { method: 'POST', body: ${sentBody} })` : `call(\`\${url}/${target}/${c.names.kebab}\`, { method: 'POST' })`;
344
+ return (0, code_1.lines)((0, code_1.sortImports)([
345
+ ...(0, code_1.testImports)(m.project.config.testRunner),
346
+ `import { InMemoryEventBus } from ${imp(s.inMemoryEventBus)};`,
347
+ `import { call, createTestApp, withTestServer } from ${imp(s.testServer)};`,
348
+ `import { ${a.pascal} } from ${imp(m.aggregate.index)};`,
349
+ `import { InMemory${a.pascal}Repository } from ${imp(m.aggregate.repository)};`,
350
+ `import { create${a.pascal}UseCases } from ${imp(m.aggregate.useCases)};`,
351
+ `import { create${m.aggregate.plural.pascal}Router } from ${imp(m.aggregate.router)};`,
352
+ ]), '', givenHelper(m), '', `async function withApi(test: (url: string, repository: InMemory${a.pascal}Repository) => Promise<void>): Promise<void> {`, ` const repository = new InMemory${a.pascal}Repository();`, ` const router = create${m.aggregate.plural.pascal}Router(create${a.pascal}UseCases(repository, new InMemoryEventBus()));`, ` await withTestServer(createTestApp((app) => app.use('${route}', router)), (url) => test(\`\${url}${route}\`, repository));`, '}', '', `describe('POST ${route}/:id/${c.names.kebab}', () => {`, " it('→ 200 with the changed resource', async () => {", ' await withApi(async (url, repository) => {', ` const id = await given${a.pascal}(repository${fromArg});`, '', ` const res = await ${send('${id}', body)};`, '', ' assert.equal(res.status, 200);', c.transition && state ? ` assert.equal(res.body.${state.names.camel}, '${c.transition.to}');` : null, ' });', ' });', refused && [
353
+ '',
354
+ ` it('→ 422 when the ${a.human} is ${refused}', async () => {`,
355
+ ' await withApi(async (url, repository) => {',
356
+ ` const id = await given${a.pascal}(repository, '${refused}');`,
357
+ '',
358
+ ` const res = await ${send('${id}', body)};`,
359
+ '',
360
+ ' assert.equal(res.status, 422);',
361
+ ' });',
362
+ ' });',
363
+ ], required && [
364
+ '',
365
+ " it('→ 400 when the body is malformed', async () => {",
366
+ ' await withApi(async (url, repository) => {',
367
+ ` const id = await given${a.pascal}(repository${fromArg});`,
368
+ '',
369
+ ` const res = await ${send('${id}', '{}')};`,
370
+ '',
371
+ ' assert.equal(res.status, 400);',
372
+ ` assert.ok(res.body.details.includes('${required.names.camel} is required'));`,
373
+ ' });',
374
+ ' });',
375
+ ], '', ` it('→ 404 for an unknown ${a.human}', async () => {`, ' await withApi(async (url) => {', ` const res = await ${send('missing-id', body)};`, '', ' assert.equal(res.status, 404);', ' });', ' });', '});');
376
+ }
@@ -0,0 +1,16 @@
1
+ import type { Names } from '../core/names';
2
+ import type { ContextPaths, Project } from '../core/project';
3
+ export declare const moduleFactoryName: (context: Names) => string;
4
+ export declare const moduleDepsName: (context: Names) => string;
5
+ /** <context>/<context>.module.ts — the composition root of one bounded context. */
6
+ export declare function contextModule(project: Project, context: ContextPaths): string;
7
+ /** <context>/index.ts — what the rest of the app may import from this context. */
8
+ export declare function contextIndex(project: Project, context: ContextPaths): string;
9
+ /** <context>/GLOSSARY.md — the Ubiquitous Language of the context. */
10
+ export declare function contextGlossary(context: Names): string;
11
+ export declare function glossaryRow(term: string, kind: string, context: Names, human: string): string;
12
+ /** Lines that mount a context in src/contexts.ts. */
13
+ export declare function registryInsertion(project: Project, context: ContextPaths): {
14
+ imports: string[];
15
+ mount: string;
16
+ };
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.moduleDepsName = exports.moduleFactoryName = void 0;
4
+ exports.contextModule = contextModule;
5
+ exports.contextIndex = contextIndex;
6
+ exports.contextGlossary = contextGlossary;
7
+ exports.glossaryRow = glossaryRow;
8
+ exports.registryInsertion = registryInsertion;
9
+ const project_1 = require("../core/project");
10
+ const markers_1 = require("../core/markers");
11
+ const code_1 = require("./code");
12
+ const moduleFactoryName = (context) => `create${context.pascal}Module`;
13
+ exports.moduleFactoryName = moduleFactoryName;
14
+ const moduleDepsName = (context) => `${context.pascal}ModuleDeps`;
15
+ exports.moduleDepsName = moduleDepsName;
16
+ /** <context>/<context>.module.ts — the composition root of one bounded context. */
17
+ function contextModule(project, context) {
18
+ const file = (0, project_1.ts)(context.module);
19
+ const imp = (0, code_1.importer)(project, file);
20
+ const n = context.names;
21
+ return (0, code_1.lines)("import { Router } from 'express';", `import type { EventBus } from ${imp((0, project_1.sharedPaths)(project).eventBus)};`, `// ${markers_1.MARKERS.imports} — generated imports are added above this line`, '', `export interface ${(0, exports.moduleDepsName)(n)} {`, ' eventBus: EventBus;', '}', '', '/**', ` * ${n.pascal} — Bounded Context.`, ' *', ' * This function is its composition root: the only place that chooses the adapters', ' * (in-memory, Postgres, MongoDB, ...) and hands them to the use cases.', ' *', ' * domain/ aggregates, entities, value objects, events, domain services, ports', ' * (plain TypeScript: no Express, no database)', ' * application/ use cases and event handlers that orchestrate the domain', ' * infrastructure/ adapters: http (Express routes) and persistence (repositories)', ' */', `export function ${(0, exports.moduleFactoryName)(n)}(deps: ${(0, exports.moduleDepsName)(n)}): Router {`, ' const router = Router();', '', ` // ${markers_1.MARKERS.wiring} — generated wiring is added above this line`, '', ' return router;', '}');
22
+ }
23
+ /** <context>/index.ts — what the rest of the app may import from this context. */
24
+ function contextIndex(project, context) {
25
+ const imp = (0, code_1.importer)(project, (0, project_1.ts)(context.index));
26
+ const n = context.names;
27
+ return (0, code_1.lines)(`export { ${(0, exports.moduleFactoryName)(n)} } from ${imp(context.module)};`, `export type { ${(0, exports.moduleDepsName)(n)} } from ${imp(context.module)};`);
28
+ }
29
+ /** <context>/GLOSSARY.md — the Ubiquitous Language of the context. */
30
+ function contextGlossary(context) {
31
+ return (0, code_1.lines)(`# ${context.pascal} — Ubiquitous Language`, '', `The words the business uses in **${context.pascal}**, and exactly what each one means here.`, 'The same word can mean something different in another Bounded Context — that is intentional.', 'Use these words everywhere: in conversations, in class and method names, and in tests.', '', '| Term | Meaning in this context |', '|---|---|');
32
+ }
33
+ function glossaryRow(term, kind, context, human) {
34
+ return `| **${term}** | ${kind}. _Describe what "${human}" means in ${context.pascal}._ |`;
35
+ }
36
+ /** Lines that mount a context in src/contexts.ts. */
37
+ function registryInsertion(project, context) {
38
+ const imp = (0, code_1.importer)(project, (0, project_1.ts)((0, project_1.contextsFile)(project)));
39
+ return {
40
+ imports: [`import { ${(0, exports.moduleFactoryName)(context.names)} } from ${imp(context.index)};`],
41
+ mount: ` router.use(${(0, exports.moduleFactoryName)(context.names)}(deps));`,
42
+ };
43
+ }
@@ -0,0 +1,47 @@
1
+ import type { Field } from '../core/fields';
2
+ import { type Names } from '../core/names';
3
+ /** For an enum field: the exported list of values and its type, e.g. VISIT_STATUSES / VisitStatus. */
4
+ export declare function enumNames(owner: Names, field: Field): {
5
+ constName: string;
6
+ typeName: string;
7
+ };
8
+ export declare function baseType(owner: Names, field: Field): string;
9
+ /** Type stored inside the object: optional fields hold null when empty. */
10
+ export declare function stateType(owner: Names, field: Field): string;
11
+ /** Member of a "create" input: optional fields may be left out or null; fields with a default may be left out. */
12
+ export declare function inputMember(owner: Names, field: Field): string;
13
+ /** TypeScript expression of a field's default value ("now" refers to a `now: Date` variable in scope). */
14
+ export declare function defaultExpr(field: Field): string | null;
15
+ /** The value a managed field (state machine) starts with: its default, or its first value. */
16
+ export declare function initialState(field: Field): string;
17
+ export declare function stateMember(owner: Names, field: Field): string;
18
+ /** Guard call that validates and normalizes `valueExpr`. */
19
+ export declare function guardCall(owner: Names, field: Field, valueExpr: string, label?: string): string;
20
+ /** Guard call for a create/update input, falling back to the default when the value is missing. */
21
+ export declare function inputGuardCall(owner: Names, field: Field, source: string): string;
22
+ /** Read-only getter. Dates are copied, so callers cannot change the object from outside. */
23
+ export declare function getter(owner: Names, field: Field, source?: string): string[];
24
+ /** Type in plain JSON data (DTOs, records): dates become ISO 8601 strings. */
25
+ export declare function plainType(owner: Names, field: Field): string;
26
+ /** Expression that turns the object's value into plain data. */
27
+ export declare function toPlain(field: Field, objectExpr: string): string;
28
+ /** Expression that turns plain data back into the object's value. */
29
+ export declare function fromPlain(field: Field, recordExpr: string): string;
30
+ /** Name of the request-body parser for this field (imported from shared/http/request-body). */
31
+ export declare function parserName(field: Field): string;
32
+ export declare function parserExpr(owner: Names, field: Field): string;
33
+ export interface Sample {
34
+ /** TypeScript expression in domain terms (Date objects). */
35
+ domain: string;
36
+ /** TypeScript expression in JSON terms (ISO strings), for HTTP bodies and DTOs. */
37
+ plain: string;
38
+ }
39
+ /** A sample for one specific enum value (e.g. the state a test starts from). */
40
+ export declare function enumSample(value: string): Sample;
41
+ export declare function sample(field: Field): Sample;
42
+ /** A different valid value (to test updates), or null when the field has only one possible value. */
43
+ export declare function otherSample(field: Field): Sample | null;
44
+ /** A value of the right TypeScript type that breaks the domain rule (for "rejects" tests). */
45
+ export declare function invalidDomainValue(field: Field): string;
46
+ /** Expression comparing a getter value with a domain sample (Dates compare by time). */
47
+ export declare function sameAsSample(field: Field, actualExpr: string, sampleValue: Sample): string;