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,552 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.Engine = void 0;
37
+ exports.relativeFile = relativeFile;
38
+ exports.normalizeRoute = normalizeRoute;
39
+ const fs = __importStar(require("node:fs"));
40
+ const path = __importStar(require("node:path"));
41
+ const errors_1 = require("../core/errors");
42
+ const fields_1 = require("../core/fields");
43
+ const markers_1 = require("../core/markers");
44
+ const names_1 = require("../core/names");
45
+ const project_1 = require("../core/project");
46
+ const commands_1 = require("../model/commands");
47
+ const source_1 = require("../scan/source");
48
+ const aggregate_1 = require("../templates/aggregate");
49
+ const building_blocks_1 = require("../templates/building-blocks");
50
+ const code_1 = require("../templates/code");
51
+ const command_1 = require("../templates/command");
52
+ const context_1 = require("../templates/context");
53
+ const postgres_1 = require("../templates/postgres");
54
+ const common_1 = require("./common");
55
+ function relativeFile(project, file) {
56
+ return path.relative(project.root, file).split(path.sep).join('/');
57
+ }
58
+ function normalizeRoute(route) {
59
+ const cleaned = `/${route.trim().replace(/^\/+|\/+$/g, '')}`;
60
+ if (!/^\/[A-Za-z0-9/_-]*$/.test(cleaned) || cleaned.includes('//') || cleaned === '/') {
61
+ throw new errors_1.CliError(`Invalid route "${route}".`, 'Example: /visits');
62
+ }
63
+ return cleaned;
64
+ }
65
+ /** Generates code into one project. Used by every command and by `apply`. */
66
+ class Engine {
67
+ project;
68
+ writer;
69
+ outcome;
70
+ foundationChecked = false;
71
+ constructor(project, writer, title = '') {
72
+ this.project = project;
73
+ this.writer = writer;
74
+ this.outcome = (0, common_1.newOutcome)(title, writer);
75
+ }
76
+ // ------------------------------------------------------------------------------ basics
77
+ /** Shared kernel + contexts registry + config, written once when missing. */
78
+ foundation() {
79
+ if (this.foundationChecked)
80
+ return;
81
+ this.foundationChecked = true;
82
+ if ((0, common_1.ensureFoundation)(this.project, this.writer)) {
83
+ this.outcome.notes.push('Added the shared kernel (src/shared) and src/contexts.ts on this first run.');
84
+ }
85
+ }
86
+ /** The context, created (and mounted) when it does not exist. */
87
+ context(names) {
88
+ this.foundation();
89
+ return (0, common_1.ensureContext)(this.project, this.writer, names, this.outcome).context;
90
+ }
91
+ /** An existing context: --context, or the only one of the project. Writes nothing. */
92
+ requireContext(given) {
93
+ let names;
94
+ if (given)
95
+ names = (0, common_1.contextNames)(given);
96
+ else {
97
+ const contexts = (0, project_1.findContexts)(this.project);
98
+ if (contexts.length === 1)
99
+ names = (0, common_1.contextNames)(contexts[0]);
100
+ else if (contexts.length === 0) {
101
+ throw new errors_1.CliError('This project has no bounded context yet.', 'Create one first: ddd-express module <aggregate> --context <name> (or: ddd-express context <name>)');
102
+ }
103
+ else {
104
+ throw new errors_1.CliError('Which bounded context? This project has several.', `Pass --context with one of: ${contexts.join(', ')}.`);
105
+ }
106
+ }
107
+ const context = (0, project_1.contextPaths)(this.project, names);
108
+ if (!this.writer.exists((0, project_1.ts)(context.module))) {
109
+ const known = (0, project_1.findContexts)(this.project);
110
+ throw new errors_1.CliError(`Bounded context "${names.kebab}" does not exist.`, known.length > 0
111
+ ? `Existing contexts: ${known.join(', ')}. To create it: ddd-express context ${names.kebab}`
112
+ : `Create it first: ddd-express context ${names.kebab}`);
113
+ }
114
+ return context;
115
+ }
116
+ aggregates(context) {
117
+ return (0, project_1.findAggregates)(context, (file) => this.writer.exists(file));
118
+ }
119
+ /** --aggregate, or the only aggregate of the context. */
120
+ resolveAggregate(context, given, purpose) {
121
+ const existing = this.aggregates(context);
122
+ if (given) {
123
+ const names = (0, names_1.toNames)(given, 'aggregate name');
124
+ if (!existing.includes(names.kebab)) {
125
+ throw new errors_1.CliError(`Aggregate "${names.kebab}" not found in the ${context.names.kebab} context.`, existing.length > 0
126
+ ? `Aggregates there: ${existing.join(', ')}.`
127
+ : `Create it with: ddd-express module <name> --context ${context.names.kebab}`);
128
+ }
129
+ return names;
130
+ }
131
+ if (existing.length === 1)
132
+ return (0, names_1.toNames)(existing[0], 'aggregate name');
133
+ if (existing.length === 0) {
134
+ throw new errors_1.CliError(`The ${context.names.kebab} context has no aggregate yet.`, `${purpose} Create one first: ddd-express module <name> --context ${context.names.kebab}`);
135
+ }
136
+ throw new errors_1.CliError('Which aggregate?', `Pass --aggregate with one of: ${existing.join(', ')}.`);
137
+ }
138
+ wire(context, wiring) {
139
+ const file = (0, project_1.ts)(context.module);
140
+ let done = false;
141
+ this.writer.update(file, (current) => {
142
+ if (current.includes(wiring.key)) {
143
+ done = true;
144
+ return null;
145
+ }
146
+ const withImports = (0, markers_1.addImports)(current, wiring.imports);
147
+ const wired = withImports && (0, markers_1.insertAboveMarker)(withImports, markers_1.MARKERS.wiring, wiring.block, 'blank');
148
+ if (!wired)
149
+ return null;
150
+ done = true;
151
+ return wired;
152
+ });
153
+ if (!done) {
154
+ this.outcome.warnings.push(`Could not wire it into ${this.writer.relative(file)} (marker "${markers_1.MARKERS.wiring}" not found). Add it yourself:`, ...wiring.imports.map((line) => ` ${line}`), ...wiring.block.replace(/\n$/, '').split('\n'));
155
+ }
156
+ }
157
+ barrel(barrel, line) {
158
+ this.writer.update(barrel, (current) => (0, markers_1.ensureLine)(current, line), () => line);
159
+ }
160
+ glossary(context, term, kind, human) {
161
+ const row = (0, context_1.glossaryRow)(term, kind, context.names, human);
162
+ this.writer.update(context.glossary, (current) => (current.includes(`| **${term}** |`) ? null : (0, markers_1.ensureLine)(current, row)));
163
+ }
164
+ /** Inserts `snippet` above `marker` in `file`; reports when the marker is missing. */
165
+ insert(file, marker, snippet, gap, imports = []) {
166
+ let done = false;
167
+ this.writer.update(file, (current) => {
168
+ const withImports = imports.length > 0 ? (0, markers_1.addImports)(current, imports) : current;
169
+ if (withImports === null)
170
+ return null;
171
+ const next = (0, markers_1.insertAboveMarker)(withImports, marker, snippet, gap);
172
+ if (next === null)
173
+ return null;
174
+ done = true;
175
+ return next;
176
+ });
177
+ return done;
178
+ }
179
+ // ------------------------------------------------------------------------- aggregates
180
+ /** Generates an aggregate with everything around it (and its commands). */
181
+ aggregate(contextName, names, fields, rawCommands, options) {
182
+ (0, names_1.assertNotReserved)(names, 'aggregate name');
183
+ if (names.kebab === 'shared')
184
+ throw new errors_1.CliError('"shared" is reserved for the shared kernel; pick another name.');
185
+ const reserved = fields.find((field) => aggregate_1.AGGREGATE_RESERVED_FIELDS.includes(field.names.camel));
186
+ if (reserved)
187
+ throw new errors_1.CliError(`${names.pascal}: the field "${reserved.names.camel}" is managed by the generated code.`);
188
+ const workFields = fields.map((field) => ({ ...field, managed: false }));
189
+ (0, commands_1.markStateField)(workFields, rawCommands, names.pascal);
190
+ if ((0, fields_1.inputFields)(workFields).length === 0) {
191
+ throw new errors_1.CliError(`${names.pascal} needs at least one field besides its state.`);
192
+ }
193
+ if (workFields.some((field) => field.managed && field.defaultValue !== undefined && typeof field.defaultValue !== 'string')) {
194
+ throw new errors_1.CliError(`${names.pascal}: invalid default for the state field.`);
195
+ }
196
+ const preview = (0, project_1.contextPaths)(this.project, contextName);
197
+ const commands = [];
198
+ for (const raw of rawCommands) {
199
+ if (commands.some((command) => command.names.camel === raw.names.camel)) {
200
+ throw new errors_1.CliError(`${names.pascal}: the command "${raw.names.camel}" is declared twice.`);
201
+ }
202
+ const declared = raw.emits ? options.declaredEvents?.get((0, names_1.toNames)(raw.emits.name, 'event', ['event']).pascal) ?? null : null;
203
+ commands.push((0, commands_1.resolveCommand)(raw, { names, fields: workFields }, declared ? { fields: declared } : null));
204
+ }
205
+ const ownEvents = [`${names.pascal}Created`, `${names.pascal}Updated`, `${names.pascal}Deleted`];
206
+ const clash = commands.find((command) => command.emits && ownEvents.includes(command.emits.names.pascal));
207
+ if (clash)
208
+ throw new errors_1.CliError(`${names.pascal}: ${clash.emits?.names.pascal} is already recorded by the generated CRUD.`);
209
+ const previewPaths = (0, project_1.aggregatePaths)(preview, names);
210
+ if (this.writer.exists((0, project_1.ts)(previewPaths.file)) && !options.force) {
211
+ throw new errors_1.CliError(`${names.pascal} already exists in ${contextName.kebab} (${relativeFile(this.project, (0, project_1.ts)(previewPaths.file))}).`, 'Use --force to regenerate its files (your changes to them would be lost).');
212
+ }
213
+ const route = normalizeRoute(options.route ?? `/${previewPaths.plural.kebab}`);
214
+ // everything is valid: write
215
+ const context = this.context(contextName);
216
+ const paths = (0, project_1.aggregatePaths)(context, names);
217
+ const model = { project: this.project, context, paths, fields: workFields, commands, route };
218
+ // domain
219
+ this.writer.create((0, project_1.ts)(paths.file), (0, aggregate_1.aggregateFile)(model));
220
+ this.writer.create((0, project_1.ts)(paths.index), (0, aggregate_1.aggregateIndex)(model));
221
+ for (const [file, content] of (0, aggregate_1.aggregateEvents)(model))
222
+ this.writer.create(file, content);
223
+ for (const target of [paths.createdEvent, paths.updatedEvent, paths.deletedEvent]) {
224
+ const className = (0, names_1.namesFromWords)((0, names_1.splitWords)(path.basename(target).replace(/\.event$/, ''))).pascal;
225
+ this.barrel((0, project_1.ts)(context.eventsIndex), `export { ${className} } from ${(0, code_1.importer)(this.project, (0, project_1.ts)(context.eventsIndex))(target)};`);
226
+ }
227
+ for (const command of commands)
228
+ this.commandEvent(context, names, command);
229
+ this.writer.create((0, project_1.ts)(paths.port), (0, aggregate_1.portFile)(model));
230
+ this.barrel((0, project_1.ts)(context.portsIndex), `export type { ${names.pascal}Repository } from ${(0, code_1.importer)(this.project, (0, project_1.ts)(context.portsIndex))(paths.port)};`);
231
+ // application
232
+ this.writer.create((0, project_1.ts)(paths.dto), (0, aggregate_1.dtoFile)(model));
233
+ for (const [file, content] of (0, aggregate_1.useCaseFiles)(model))
234
+ this.writer.create(file, content);
235
+ for (const command of (0, aggregate_1.commandModels)(model))
236
+ this.writer.create((0, project_1.ts)(command.paths.useCase), (0, command_1.commandUseCase)(command));
237
+ this.writer.create((0, project_1.ts)(paths.useCases), (0, aggregate_1.facadeFile)(model));
238
+ // infrastructure
239
+ this.writer.create((0, project_1.ts)(paths.mapper), (0, aggregate_1.mapperFile)(model));
240
+ this.writer.create((0, project_1.ts)(paths.repository), (0, aggregate_1.repositoryFile)(model));
241
+ this.writer.create((0, project_1.ts)(paths.request), (0, aggregate_1.requestFile)(model));
242
+ for (const command of (0, aggregate_1.commandModels)(model)) {
243
+ const request = (0, command_1.commandRequest)(command);
244
+ if (request)
245
+ this.writer.create((0, project_1.ts)(command.paths.request), request);
246
+ }
247
+ this.writer.create((0, project_1.ts)(paths.router), (0, aggregate_1.routerFile)(model));
248
+ // tests
249
+ if (!options.skipTests) {
250
+ this.writer.create((0, project_1.ts)(paths.spec), (0, aggregate_1.aggregateSpec)(model));
251
+ this.writer.create((0, project_1.ts)(paths.useCasesSpec), (0, aggregate_1.useCasesSpec)(model));
252
+ this.writer.create((0, project_1.ts)(paths.routerSpec), (0, aggregate_1.routerSpec)(model));
253
+ for (const command of (0, aggregate_1.commandModels)(model)) {
254
+ this.writer.create((0, project_1.ts)(command.paths.useCaseSpec), (0, command_1.commandUseCaseSpec)(command));
255
+ this.writer.create((0, project_1.ts)(command.paths.routerSpec), (0, command_1.commandRouterSpec)(command, route));
256
+ }
257
+ }
258
+ this.wire(context, (0, aggregate_1.wiringFor)(model));
259
+ this.glossary(context, names.pascal, 'Aggregate root', names.human);
260
+ for (const command of commands) {
261
+ if (command.emits)
262
+ this.glossary(context, command.emits.names.pascal, 'Domain event', command.emits.names.human);
263
+ }
264
+ return model;
265
+ }
266
+ /** The event class a command records (created when missing). */
267
+ commandEvent(context, aggregate, command) {
268
+ if (!command.emits)
269
+ return;
270
+ const event = command.emits.names;
271
+ const file = path.join(context.events, `${event.kebab}.event`);
272
+ if (!this.writer.exists((0, project_1.ts)(file))) {
273
+ this.writer.create((0, project_1.ts)(file), (0, aggregate_1.eventFile)(this.project, (0, project_1.ts)(file), event.pascal, context.names.pascal, [`Recorded when ${aggregate.pascal}.${command.names.camel}() succeeds.`], command.emits.payload.map((item) => ({ name: item.name, type: eventPayloadType(aggregate, item.field) }))));
274
+ }
275
+ this.barrel((0, project_1.ts)(context.eventsIndex), `export { ${event.pascal} } from ${(0, code_1.importer)(this.project, (0, project_1.ts)(context.eventsIndex))(file)};`);
276
+ }
277
+ /** Adds a behaviour to an existing aggregate (method, event, use case, route, tests). */
278
+ command(context, aggregateNames, raw, options, declaredEvents) {
279
+ const paths = (0, project_1.aggregatePaths)(context, aggregateNames);
280
+ const source = this.writer.read((0, project_1.ts)(paths.file));
281
+ if (source === null)
282
+ throw new errors_1.CliError(`Aggregate ${aggregateNames.pascal} not found in ${context.names.kebab}.`);
283
+ const shape = (0, source_1.readAggregate)(source, aggregateNames.pascal);
284
+ if (!shape) {
285
+ throw new errors_1.CliError(`${relativeFile(this.project, (0, project_1.ts)(paths.file))} does not look like a generated aggregate.`, 'Commands can be added to aggregates generated by ddd-express.');
286
+ }
287
+ for (const required of [markers_1.MARKERS.behaviour]) {
288
+ if (!source.includes(required)) {
289
+ throw new errors_1.CliError(`Marker "${required}" not found in ${relativeFile(this.project, (0, project_1.ts)(paths.file))}.`, 'Restore the marker comment and run again.');
290
+ }
291
+ }
292
+ const fields = shape.fields.map((field) => ({ ...field }));
293
+ if ((raw.from || raw.to) && !fields.some((field) => field.managed)) {
294
+ const marked = (0, commands_1.markStateField)(fields, [raw], aggregateNames.pascal);
295
+ if (marked) {
296
+ this.outcome.warnings.push(`${aggregateNames.pascal}.${marked.names.camel} can still be set through create/update (PATCH). To make it change only through behaviour, declare the command in domain.ddd and regenerate the aggregate.`);
297
+ }
298
+ }
299
+ const declared = raw.emits ? declaredEvents?.get((0, names_1.toNames)(raw.emits.name, 'event', ['event']).pascal) ?? null : null;
300
+ const command = (0, commands_1.resolveCommand)(raw, { names: aggregateNames, fields, existingMethods: shape.methods }, declared ? { fields: declared } : null);
301
+ const route = this.routeOf(context, aggregateNames) ?? `/${paths.plural.kebab}`;
302
+ const model = {
303
+ project: this.project,
304
+ context,
305
+ aggregate: paths,
306
+ fields,
307
+ command,
308
+ paths: (0, project_1.commandPaths)(context, paths, command.names),
309
+ };
310
+ if (this.writer.exists((0, project_1.ts)(model.paths.useCase)) && !options.force) {
311
+ throw new errors_1.CliError(`${relativeFile(this.project, (0, project_1.ts)(model.paths.useCase))} already exists.`, 'Use --force to regenerate it.');
312
+ }
313
+ // event
314
+ this.commandEvent(context, aggregateNames, command);
315
+ // method on the aggregate (+ the state guard the first time)
316
+ const aggregateFilePath = (0, project_1.ts)(paths.file);
317
+ const imp = (0, code_1.importer)(this.project, aggregateFilePath);
318
+ const imports = [];
319
+ if (command.emits && !source.includes(`import { ${command.emits.names.pascal} }`)) {
320
+ imports.push(`import { ${command.emits.names.pascal} } from ${imp(`${context.events}/${command.emits.names.kebab}.event`)};`);
321
+ }
322
+ let methodBlock = (0, command_1.commandMethod)(aggregateNames, fields, command).join('\n');
323
+ const state = fields.find((field) => field.managed) ?? null;
324
+ if (command.transition && state && !shape.hasEnsureState) {
325
+ if (!source.includes('import { DomainError }')) {
326
+ imports.push(`import { DomainError } from ${imp(`${this.project.shared}/domain/domain.error`)};`);
327
+ }
328
+ methodBlock += `\n\n${(0, command_1.ensureStateMethod)(aggregateNames, state, (0, aggregate_1.stateTypeName)({ paths }, state)).join('\n')}`;
329
+ }
330
+ if (!this.insert(aggregateFilePath, markers_1.MARKERS.behaviour, methodBlock, 'blank', imports)) {
331
+ throw new errors_1.CliError(`Could not add the method to ${relativeFile(this.project, aggregateFilePath)}.`);
332
+ }
333
+ // use case + facade
334
+ this.writer.create((0, project_1.ts)(model.paths.useCase), (0, command_1.commandUseCase)(model));
335
+ const facade = (0, command_1.commandFacadeEntry)(model);
336
+ if (!this.insert((0, project_1.ts)(paths.useCases), markers_1.MARKERS.useCases, facade.entry, 'none', facade.imports)) {
337
+ this.outcome.warnings.push(`Add to ${relativeFile(this.project, (0, project_1.ts)(paths.useCases))}:`, ` ${facade.entry.trim()}`);
338
+ }
339
+ // HTTP
340
+ const request = (0, command_1.commandRequest)(model);
341
+ if (request)
342
+ this.writer.create((0, project_1.ts)(model.paths.request), request);
343
+ const routerPath = (0, project_1.ts)(paths.router);
344
+ if (!this.insert(routerPath, markers_1.MARKERS.routes, (0, command_1.commandRoute)(model).join('\n'), 'blank', (0, command_1.commandRouterImports)(model, routerPath))) {
345
+ this.outcome.warnings.push(`Add the route to ${relativeFile(this.project, routerPath)} (marker "${markers_1.MARKERS.routes}" not found).`);
346
+ }
347
+ // tests
348
+ if (!options.skipTests) {
349
+ this.writer.create((0, project_1.ts)(model.paths.useCaseSpec), (0, command_1.commandUseCaseSpec)(model));
350
+ this.writer.create((0, project_1.ts)(model.paths.routerSpec), (0, command_1.commandRouterSpec)(model, route));
351
+ }
352
+ if (command.emits)
353
+ this.glossary(context, command.emits.names.pascal, 'Domain event', command.emits.names.human);
354
+ return command;
355
+ }
356
+ /** The mount path of an aggregate's router, read from the context module. */
357
+ routeOf(context, aggregate) {
358
+ const source = this.writer.read((0, project_1.ts)(context.module));
359
+ if (!source)
360
+ return null;
361
+ const plural = (0, project_1.aggregatePaths)(context, aggregate).plural.pascal;
362
+ const match = new RegExp(`router\\.use\\(\\s*'([^']+)',\\s*create${plural}Router\\(`).exec(source);
363
+ return match ? match[1] : null;
364
+ }
365
+ // ------------------------------------------------------------------------- adapters
366
+ /** A PostgreSQL repository for an existing aggregate, its migration and an integration test. */
367
+ postgres(context, aggregateNames, options) {
368
+ const paths = (0, project_1.aggregatePaths)(context, aggregateNames);
369
+ const source = this.writer.read((0, project_1.ts)(paths.file));
370
+ const shape = source ? (0, source_1.readAggregate)(source, aggregateNames.pascal) : null;
371
+ if (!shape)
372
+ throw new errors_1.CliError(`${aggregateNames.pascal} in ${context.names.kebab} is not a generated aggregate.`);
373
+ const file = path.join(context.persistence, `postgres-${aggregateNames.kebab}.repository`);
374
+ if (this.writer.exists((0, project_1.ts)(file)) && !options.force) {
375
+ throw new errors_1.CliError(`${relativeFile(this.project, (0, project_1.ts)(file))} already exists.`, 'Use --force to regenerate it.');
376
+ }
377
+ const model = { project: this.project, context, paths, fields: shape.fields, file, specFile: `${file}.spec` };
378
+ this.foundation();
379
+ this.writer.create((0, project_1.ts)(file), (0, postgres_1.postgresRepository)(model));
380
+ if (!options.skipTests)
381
+ this.writer.create((0, project_1.ts)(model.specFile), (0, postgres_1.postgresRepositorySpec)(model));
382
+ const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14);
383
+ const migration = path.join(this.project.root, 'migrations', `${stamp}_create_${context.names.words.join('_')}_${paths.plural.words.join('_')}.sql`);
384
+ const existing = fs.existsSync(path.dirname(migration))
385
+ ? fs.readdirSync(path.dirname(migration)).find((name) => name.endsWith(`_create_${context.names.words.join('_')}_${paths.plural.words.join('_')}.sql`))
386
+ : undefined;
387
+ if (!existing)
388
+ this.writer.create(migration, `-- ${aggregateNames.pascal} (${context.names.pascal})\n${(0, postgres_1.createTableSql)(model)}`);
389
+ return { file: relativeFile(this.project, (0, project_1.ts)(file)), migration: relativeFile(this.project, existing ? path.join(path.dirname(migration), existing) : migration) };
390
+ }
391
+ // --------------------------------------------------------------------- building blocks
392
+ valueObject(context, names, single, fields, options) {
393
+ (0, names_1.assertNotReserved)(names, 'value object name');
394
+ if ([single, ...fields].some((field) => field && typeof field.defaultValue === 'object')) {
395
+ throw new errors_1.CliError(`${names.pascal}: "= now" is only supported on aggregate fields.`);
396
+ }
397
+ const file = path.join(context.valueObjects, names.kebab);
398
+ if (this.writer.exists((0, project_1.ts)(file)) && !options.force) {
399
+ throw new errors_1.CliError(`${names.pascal} already exists (${relativeFile(this.project, (0, project_1.ts)(file))}).`, 'Use --force to regenerate it.');
400
+ }
401
+ this.foundation();
402
+ this.writer.create((0, project_1.ts)(file), single
403
+ ? (0, building_blocks_1.singleValueObject)(this.project, (0, project_1.ts)(file), names, context.names, single)
404
+ : (0, building_blocks_1.compositeValueObject)(this.project, (0, project_1.ts)(file), names, context.names, fields));
405
+ this.barrel((0, project_1.ts)(context.valueObjectsIndex), `export { ${names.pascal} } from ${(0, code_1.importer)(this.project, (0, project_1.ts)(context.valueObjectsIndex))(file)};`);
406
+ if (!options.skipTests) {
407
+ const spec = `${file}.spec`;
408
+ this.writer.create((0, project_1.ts)(spec), (0, building_blocks_1.valueObjectSpec)(this.project, (0, project_1.ts)(spec), file, names, single ? null : fields, single));
409
+ }
410
+ this.glossary(context, names.pascal, 'Value object', names.human);
411
+ }
412
+ entity(context, aggregate, names, fields, options) {
413
+ (0, names_1.assertNotReserved)(names, 'entity name');
414
+ if (aggregate.kebab === names.kebab)
415
+ throw new errors_1.CliError('An entity cannot have the same name as its aggregate.');
416
+ const reserved = fields.find((field) => building_blocks_1.ENTITY_RESERVED_FIELDS.includes(field.names.camel));
417
+ if (reserved)
418
+ throw new errors_1.CliError(`${names.pascal}: the field "${reserved.names.camel}" is managed by the generated code.`);
419
+ if (fields.some((field) => typeof field.defaultValue === 'object')) {
420
+ throw new errors_1.CliError(`${names.pascal}: "= now" is only supported on aggregate fields.`);
421
+ }
422
+ const aggPaths = (0, project_1.aggregatePaths)(context, aggregate);
423
+ const file = path.join(aggPaths.dir, names.kebab);
424
+ if (this.writer.exists((0, project_1.ts)(file)) && !options.force) {
425
+ throw new errors_1.CliError(`${names.pascal} already exists (${relativeFile(this.project, (0, project_1.ts)(file))}).`, 'Use --force to regenerate it.');
426
+ }
427
+ this.foundation();
428
+ this.writer.create((0, project_1.ts)(file), (0, building_blocks_1.entityFile)(this.project, (0, project_1.ts)(file), names, aggregate, fields));
429
+ const barrelImp = (0, code_1.importer)(this.project, (0, project_1.ts)(aggPaths.index));
430
+ this.barrel((0, project_1.ts)(aggPaths.index), `export { ${names.pascal} } from ${barrelImp(file)};`);
431
+ this.barrel((0, project_1.ts)(aggPaths.index), `export type { ${names.pascal}Props, Create${names.pascal}Props } from ${barrelImp(file)};`);
432
+ if (!options.skipTests) {
433
+ const spec = `${file}.spec`;
434
+ this.writer.create((0, project_1.ts)(spec), (0, building_blocks_1.entitySpec)(this.project, (0, project_1.ts)(spec), file, names, fields));
435
+ }
436
+ this.glossary(context, names.pascal, `Entity inside ${aggregate.pascal}`, names.human);
437
+ }
438
+ event(context, names, fields, options) {
439
+ (0, names_1.assertNotReserved)(names, 'event name');
440
+ const file = path.join(context.events, `${names.kebab}.event`);
441
+ if (this.writer.exists((0, project_1.ts)(file)) && !options.force) {
442
+ throw new errors_1.CliError(`${names.pascal} already exists (${relativeFile(this.project, (0, project_1.ts)(file))}).`, 'Use --force to regenerate it.');
443
+ }
444
+ this.foundation();
445
+ this.writer.create((0, project_1.ts)(file), (0, aggregate_1.eventFile)(this.project, (0, project_1.ts)(file), names.pascal, context.names.pascal, ['Describe the business fact it records.'], fields.map((field) => ({ name: field.names.camel, type: (0, building_blocks_1.eventMemberType)(field) }))));
446
+ this.barrel((0, project_1.ts)(context.eventsIndex), `export { ${names.pascal} } from ${(0, code_1.importer)(this.project, (0, project_1.ts)(context.eventsIndex))(file)};`);
447
+ this.glossary(context, names.pascal, 'Domain event', names.human);
448
+ }
449
+ useCase(context, names, aggregate, options) {
450
+ (0, names_1.assertNotReserved)(names, 'use case name');
451
+ const file = path.join(context.application, `${names.kebab}.use-case`);
452
+ if (this.writer.exists((0, project_1.ts)(file)) && !options.force) {
453
+ throw new errors_1.CliError(`${names.pascal}UseCase already exists (${relativeFile(this.project, (0, project_1.ts)(file))}).`, 'Use --force to regenerate it.');
454
+ }
455
+ this.foundation();
456
+ const aggPaths = aggregate ? (0, project_1.aggregatePaths)(context, aggregate) : null;
457
+ this.writer.create((0, project_1.ts)(file), (0, building_blocks_1.customUseCase)(this.project, (0, project_1.ts)(file), names, aggregate && aggPaths ? { names: aggregate, plural: aggPaths.plural, portsIndex: context.portsIndex } : null));
458
+ if (!options.skipTests) {
459
+ const spec = `${file}.spec`;
460
+ this.writer.create((0, project_1.ts)(spec), (0, building_blocks_1.customUseCaseSpec)(this.project, (0, project_1.ts)(spec), file, names, aggregate && aggPaths ? { names: aggregate, repositoryFile: aggPaths.repository } : null));
461
+ }
462
+ return aggPaths;
463
+ }
464
+ service(context, names, options) {
465
+ (0, names_1.assertNotReserved)(names, 'domain service name');
466
+ const file = path.join(context.services, `${names.kebab}.service`);
467
+ if (this.writer.exists((0, project_1.ts)(file)) && !options.force) {
468
+ throw new errors_1.CliError(`${names.pascal}Service already exists (${relativeFile(this.project, (0, project_1.ts)(file))}).`, 'Use --force to regenerate it.');
469
+ }
470
+ this.foundation();
471
+ this.writer.create((0, project_1.ts)(file), (0, building_blocks_1.domainService)(names, context.names));
472
+ if (!options.skipTests) {
473
+ const spec = `${file}.spec`;
474
+ this.writer.create((0, project_1.ts)(spec), (0, building_blocks_1.domainServiceSpec)(this.project, (0, project_1.ts)(spec), file, names));
475
+ }
476
+ this.glossary(context, `${names.pascal}Service`, 'Domain service', names.human);
477
+ }
478
+ /** Where an event class lives: --from, or the one context that has it. */
479
+ findEvent(event, from) {
480
+ const candidates = from ? [(0, common_1.contextNames)(from).kebab] : (0, project_1.findContexts)(this.project);
481
+ const found = [];
482
+ for (const kebab of candidates) {
483
+ const ctx = (0, project_1.contextPaths)(this.project, (0, names_1.toNames)(kebab, 'context'));
484
+ const file = path.join(ctx.events, `${event.kebab}.event`);
485
+ if (this.writer.exists((0, project_1.ts)(file)))
486
+ found.push({ context: ctx.names, file });
487
+ }
488
+ if (found.length === 1)
489
+ return found[0];
490
+ if (found.length > 1) {
491
+ throw new errors_1.CliError(`${event.pascal} exists in several contexts.`, `Pass --from with one of: ${found.map((item) => item.context.kebab).join(', ')}.`);
492
+ }
493
+ throw new errors_1.CliError(`Domain event ${event.pascal} not found${from ? ` in the ${(0, common_1.contextNames)(from).kebab} context` : ''}.`, `Create it first: ddd-express event ${event.pascal} --context <context>`);
494
+ }
495
+ /** Handler class and file for "<Name> on <Event>". */
496
+ handlerNames(name, event) {
497
+ if (!name)
498
+ return { className: `On${event.pascal}Handler`, fileBase: `on-${event.kebab}` };
499
+ let words = (0, names_1.splitWords)(name);
500
+ if (words[words.length - 1] === 'handler')
501
+ words = words.slice(0, -1);
502
+ const suffix = ['on', ...event.words];
503
+ if (words.length > suffix.length && words.slice(-suffix.length).join(' ') === suffix.join(' ')) {
504
+ words = words.slice(0, -suffix.length);
505
+ }
506
+ const base = (0, names_1.toNames)(words.join('-'), 'handler name');
507
+ return { className: `${base.pascal}On${event.pascal}`, fileBase: `${base.kebab}-on-${event.kebab}` };
508
+ }
509
+ handler(context, name, event, from, options) {
510
+ const found = this.findEvent(event, from);
511
+ const { className, fileBase } = this.handlerNames(name, event);
512
+ const file = path.join(context.application, `${fileBase}.handler`);
513
+ if (this.writer.exists((0, project_1.ts)(file)) && !options.force) {
514
+ throw new errors_1.CliError(`${className} already exists (${relativeFile(this.project, (0, project_1.ts)(file))}).`, 'Use --force to regenerate it.');
515
+ }
516
+ this.foundation();
517
+ this.writer.create((0, project_1.ts)(file), (0, building_blocks_1.eventHandler)(this.project, (0, project_1.ts)(file), className, { className: event.pascal, file: found.file, contextPascal: found.context.pascal }, context.names));
518
+ if (!options.skipTests) {
519
+ const spec = `${file}.spec`;
520
+ this.writer.create((0, project_1.ts)(spec), (0, building_blocks_1.eventHandlerSpec)(this.project, (0, project_1.ts)(spec), file, className, event.pascal));
521
+ }
522
+ const imp = (0, code_1.importer)(this.project, (0, project_1.ts)(context.module));
523
+ const variable = className.charAt(0).toLowerCase() + className.slice(1);
524
+ this.wire(context, {
525
+ key: `const ${variable} = `,
526
+ imports: [`import { ${event.pascal} } from ${imp(found.file)};`, `import { ${className} } from ${imp(file)};`],
527
+ block: [
528
+ ` // ${className}: reacts to ${event.pascal}${found.context.kebab === context.names.kebab ? '' : ` (from ${found.context.pascal})`}`,
529
+ ` const ${variable} = new ${className}();`,
530
+ ` deps.eventBus.subscribe(${event.pascal}, (event) => ${variable}.handle(event));`,
531
+ '',
532
+ ].join('\n'),
533
+ });
534
+ return relativeFile(this.project, (0, project_1.ts)(file));
535
+ }
536
+ /** Import path from an aggregate file of `context` to its value objects barrel (for hints). */
537
+ valueObjectImportHint(context) {
538
+ return (0, project_1.importPath)(this.project, path.join(context.domain, 'aggregate', 'aggregate.ts'), context.valueObjectsIndex);
539
+ }
540
+ /** Is there an aggregate file for `names` in another context? (for a gentle warning) */
541
+ aggregateElsewhere(context, names) {
542
+ return (0, project_1.findContexts)(this.project)
543
+ .filter((other) => other !== context.names.kebab)
544
+ .filter((other) => fs.existsSync((0, project_1.ts)((0, project_1.aggregatePaths)((0, project_1.contextPaths)(this.project, (0, names_1.toNames)(other, 'context')), names).file)));
545
+ }
546
+ }
547
+ exports.Engine = Engine;
548
+ /** Type of an event member that carries an aggregate field or a command parameter. */
549
+ function eventPayloadType(owner, field) {
550
+ const type = (0, command_1.inlineType)(owner, field);
551
+ return field.optional ? `${type} | null` : type;
552
+ }
@@ -0,0 +1,10 @@
1
+ import { type CommonOptions, type Outcome } from './common';
2
+ export interface NewOptions extends CommonOptions {
3
+ install: boolean;
4
+ /** Path of a domain.ddd to generate the project from. */
5
+ model?: string;
6
+ /** Name of a bundled example model (healthcare, shop). */
7
+ example?: string;
8
+ }
9
+ export declare function generateNew(name: string | undefined, options: NewOptions): Outcome;
10
+ export declare function generateInit(options: CommonOptions): Outcome;