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,227 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.enumNames = enumNames;
4
+ exports.baseType = baseType;
5
+ exports.stateType = stateType;
6
+ exports.inputMember = inputMember;
7
+ exports.defaultExpr = defaultExpr;
8
+ exports.initialState = initialState;
9
+ exports.stateMember = stateMember;
10
+ exports.guardCall = guardCall;
11
+ exports.inputGuardCall = inputGuardCall;
12
+ exports.getter = getter;
13
+ exports.plainType = plainType;
14
+ exports.toPlain = toPlain;
15
+ exports.fromPlain = fromPlain;
16
+ exports.parserName = parserName;
17
+ exports.parserExpr = parserExpr;
18
+ exports.enumSample = enumSample;
19
+ exports.sample = sample;
20
+ exports.otherSample = otherSample;
21
+ exports.invalidDomainValue = invalidDomainValue;
22
+ exports.sameAsSample = sameAsSample;
23
+ const names_1 = require("../core/names");
24
+ /** Code snippets for one field of an aggregate, entity, value object or event. */
25
+ const q = (value) => `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
26
+ /** For an enum field: the exported list of values and its type, e.g. VISIT_STATUSES / VisitStatus. */
27
+ function enumNames(owner, field) {
28
+ const startsWithOwner = field.names.pascal.startsWith(owner.pascal);
29
+ const words = startsWithOwner ? field.names.words : [...owner.words, ...field.names.words];
30
+ return { typeName: (0, names_1.namesFromWords)(words).pascal, constName: (0, names_1.pluralize)((0, names_1.namesFromWords)(words)).constant };
31
+ }
32
+ function baseType(owner, field) {
33
+ switch (field.type) {
34
+ case 'string':
35
+ return 'string';
36
+ case 'number':
37
+ case 'integer':
38
+ return 'number';
39
+ case 'boolean':
40
+ return 'boolean';
41
+ case 'date':
42
+ return 'Date';
43
+ case 'enum':
44
+ return enumNames(owner, field).typeName;
45
+ }
46
+ }
47
+ /** Type stored inside the object: optional fields hold null when empty. */
48
+ function stateType(owner, field) {
49
+ const type = baseType(owner, field);
50
+ return field.optional ? `${type} | null` : type;
51
+ }
52
+ /** Member of a "create" input: optional fields may be left out or null; fields with a default may be left out. */
53
+ function inputMember(owner, field) {
54
+ const type = baseType(owner, field);
55
+ if (field.optional)
56
+ return `${field.names.camel}?: ${type} | null;`;
57
+ if (field.defaultValue !== undefined)
58
+ return `${field.names.camel}?: ${type};`;
59
+ return `${field.names.camel}: ${type};`;
60
+ }
61
+ /** TypeScript expression of a field's default value ("now" refers to a `now: Date` variable in scope). */
62
+ function defaultExpr(field) {
63
+ const value = field.defaultValue;
64
+ if (value === undefined)
65
+ return null;
66
+ if (typeof value === 'object')
67
+ return 'now';
68
+ if (typeof value === 'string')
69
+ return q(value);
70
+ return String(value);
71
+ }
72
+ /** The value a managed field (state machine) starts with: its default, or its first value. */
73
+ function initialState(field) {
74
+ return typeof field.defaultValue === 'string' ? field.defaultValue : field.values[0];
75
+ }
76
+ function stateMember(owner, field) {
77
+ return `${field.names.camel}: ${stateType(owner, field)};`;
78
+ }
79
+ /** Guard call that validates and normalizes `valueExpr`. */
80
+ function guardCall(owner, field, valueExpr, label = field.names.camel) {
81
+ const name = q(label);
82
+ const check = (expr) => {
83
+ switch (field.type) {
84
+ case 'string':
85
+ return `Guard.text(${expr}, ${name})`;
86
+ case 'number':
87
+ return `Guard.number(${expr}, ${name})`;
88
+ case 'integer':
89
+ return `Guard.integer(${expr}, ${name})`;
90
+ case 'boolean':
91
+ return `Guard.boolean(${expr}, ${name})`;
92
+ case 'date':
93
+ return `Guard.date(${expr}, ${name})`;
94
+ case 'enum':
95
+ return `Guard.oneOf(${expr}, ${enumNames(owner, field).constName}, ${name})`;
96
+ }
97
+ };
98
+ return field.optional ? `Guard.optional(${valueExpr}, (value) => ${check('value')})` : check(valueExpr);
99
+ }
100
+ /** Guard call for a create/update input, falling back to the default when the value is missing. */
101
+ function inputGuardCall(owner, field, source) {
102
+ const value = `${source}.${field.names.camel}`;
103
+ const fallback = defaultExpr(field);
104
+ return guardCall(owner, field, fallback === null ? value : `${value} ?? ${fallback}`);
105
+ }
106
+ /** Read-only getter. Dates are copied, so callers cannot change the object from outside. */
107
+ function getter(owner, field, source = 'this.props') {
108
+ const name = field.names.camel;
109
+ const type = stateType(owner, field);
110
+ let body;
111
+ if (field.type === 'date') {
112
+ body = field.optional
113
+ ? `return ${source}.${name} === null ? null : new Date(${source}.${name}.getTime());`
114
+ : `return new Date(${source}.${name}.getTime());`;
115
+ }
116
+ else {
117
+ body = `return ${source}.${name};`;
118
+ }
119
+ return [`get ${name}(): ${type} {`, ` ${body}`, '}'];
120
+ }
121
+ /** Type in plain JSON data (DTOs, records): dates become ISO 8601 strings. */
122
+ function plainType(owner, field) {
123
+ const type = field.type === 'date' ? 'string' : baseType(owner, field);
124
+ return field.optional ? `${type} | null` : type;
125
+ }
126
+ /** Expression that turns the object's value into plain data. */
127
+ function toPlain(field, objectExpr) {
128
+ const value = `${objectExpr}.${field.names.camel}`;
129
+ if (field.type !== 'date')
130
+ return value;
131
+ return field.optional ? `${value}?.toISOString() ?? null` : `${value}.toISOString()`;
132
+ }
133
+ /** Expression that turns plain data back into the object's value. */
134
+ function fromPlain(field, recordExpr) {
135
+ const value = `${recordExpr}.${field.names.camel}`;
136
+ if (field.type !== 'date')
137
+ return value;
138
+ return field.optional ? `${value} === null ? null : new Date(${value})` : `new Date(${value})`;
139
+ }
140
+ /** Name of the request-body parser for this field (imported from shared/http/request-body). */
141
+ function parserName(field) {
142
+ switch (field.type) {
143
+ case 'string':
144
+ return 'asText';
145
+ case 'number':
146
+ return 'asNumber';
147
+ case 'integer':
148
+ return 'asInteger';
149
+ case 'boolean':
150
+ return 'asBoolean';
151
+ case 'date':
152
+ return 'asDate';
153
+ case 'enum':
154
+ return 'asOneOf';
155
+ }
156
+ }
157
+ function parserExpr(owner, field) {
158
+ return field.type === 'enum' ? `asOneOf(${enumNames(owner, field).constName})` : parserName(field);
159
+ }
160
+ const DATE_A = '2026-01-10T09:00:00.000Z';
161
+ const DATE_B = '2026-02-20T15:30:00.000Z';
162
+ /** A sample for one specific enum value (e.g. the state a test starts from). */
163
+ function enumSample(value) {
164
+ return { domain: q(value), plain: q(value) };
165
+ }
166
+ function sample(field) {
167
+ switch (field.type) {
168
+ case 'string': {
169
+ const text = q(`Example ${field.names.human}`);
170
+ return { domain: text, plain: text };
171
+ }
172
+ case 'number':
173
+ return { domain: '42.5', plain: '42.5' };
174
+ case 'integer':
175
+ return { domain: '7', plain: '7' };
176
+ case 'boolean':
177
+ return { domain: 'true', plain: 'true' };
178
+ case 'date':
179
+ return { domain: `new Date(${q(DATE_A)})`, plain: q(DATE_A) };
180
+ case 'enum':
181
+ return { domain: q(field.values[0]), plain: q(field.values[0]) };
182
+ }
183
+ }
184
+ /** A different valid value (to test updates), or null when the field has only one possible value. */
185
+ function otherSample(field) {
186
+ switch (field.type) {
187
+ case 'string': {
188
+ const text = q(`Updated ${field.names.human}`);
189
+ return { domain: text, plain: text };
190
+ }
191
+ case 'number':
192
+ return { domain: '43.5', plain: '43.5' };
193
+ case 'integer':
194
+ return { domain: '8', plain: '8' };
195
+ case 'boolean':
196
+ return { domain: 'false', plain: 'false' };
197
+ case 'date':
198
+ return { domain: `new Date(${q(DATE_B)})`, plain: q(DATE_B) };
199
+ case 'enum':
200
+ return field.values.length > 1 ? { domain: q(field.values[1]), plain: q(field.values[1]) } : null;
201
+ }
202
+ }
203
+ /** A value of the right TypeScript type that breaks the domain rule (for "rejects" tests). */
204
+ function invalidDomainValue(field) {
205
+ switch (field.type) {
206
+ case 'string':
207
+ return `' '`;
208
+ case 'number':
209
+ return 'Number.NaN';
210
+ case 'integer':
211
+ return '1.5';
212
+ case 'boolean':
213
+ return `'yes' as never`;
214
+ case 'date':
215
+ return `new Date('not a date')`;
216
+ case 'enum':
217
+ return `'not-a-valid-value' as never`;
218
+ }
219
+ }
220
+ /** Expression comparing a getter value with a domain sample (Dates compare by time). */
221
+ function sameAsSample(field, actualExpr, sampleValue) {
222
+ if (field.type === 'date') {
223
+ const actual = field.optional ? `${actualExpr}?.getTime()` : `${actualExpr}.getTime()`;
224
+ return `assert.equal(${actual}, ${sampleValue.domain}.getTime());`;
225
+ }
226
+ return `assert.equal(${actualExpr}, ${sampleValue.domain});`;
227
+ }
@@ -0,0 +1,25 @@
1
+ import type { Field } from '../core/fields';
2
+ import type { AggregatePaths, ContextPaths, Project } from '../core/project';
3
+ export declare const quoteIdent: (name: string) => string;
4
+ export interface PostgresModel {
5
+ project: Project;
6
+ context: ContextPaths;
7
+ paths: AggregatePaths;
8
+ fields: Field[];
9
+ /** The file without extension. */
10
+ file: string;
11
+ specFile: string;
12
+ }
13
+ export declare function tableName(m: {
14
+ context: ContextPaths;
15
+ paths: AggregatePaths;
16
+ }): string;
17
+ /** CREATE SCHEMA + CREATE TABLE for the aggregate: one schema per bounded context. */
18
+ export declare function createTableSql(m: {
19
+ context: ContextPaths;
20
+ paths: AggregatePaths;
21
+ fields: Field[];
22
+ }): string;
23
+ export declare function postgresRepository(m: PostgresModel): string;
24
+ /** Integration test: runs only when DATABASE_URL points to a PostgreSQL database. */
25
+ export declare function postgresRepositorySpec(m: PostgresModel): string;
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.quoteIdent = void 0;
4
+ exports.tableName = tableName;
5
+ exports.createTableSql = createTableSql;
6
+ exports.postgresRepository = postgresRepository;
7
+ exports.postgresRepositorySpec = postgresRepositorySpec;
8
+ const project_1 = require("../core/project");
9
+ const code_1 = require("./code");
10
+ const field_code_1 = require("./field-code");
11
+ /** A PostgreSQL adapter for an aggregate's repository port (node-postgres). */
12
+ const PG_RESERVED = new Set(('all analyse analyze and any array as asc asymmetric both case cast check collate column constraint create ' +
13
+ 'current_date current_role current_time current_timestamp current_user default deferrable desc distinct do else ' +
14
+ 'end except false fetch for foreign from grant group having in initially intersect into lateral leading limit ' +
15
+ 'localtime localtimestamp not null offset on only or order placing primary references returning select ' +
16
+ 'session_user some symmetric table then to trailing true union unique user using variadic when where window with').split(' '));
17
+ const quoteIdent = (name) => (PG_RESERVED.has(name) || /[^a-z0-9_]/.test(name) ? `"${name}"` : name);
18
+ exports.quoteIdent = quoteIdent;
19
+ const column = (field) => (0, exports.quoteIdent)(field.names.words.join('_'));
20
+ function tableName(m) {
21
+ return `${(0, exports.quoteIdent)(m.context.names.words.join('_'))}.${(0, exports.quoteIdent)(m.paths.plural.words.join('_'))}`;
22
+ }
23
+ function sqlType(field) {
24
+ switch (field.type) {
25
+ case 'string':
26
+ case 'enum':
27
+ return 'text';
28
+ case 'number':
29
+ return 'double precision';
30
+ case 'integer':
31
+ return 'integer';
32
+ case 'boolean':
33
+ return 'boolean';
34
+ case 'date':
35
+ return 'timestamptz';
36
+ }
37
+ }
38
+ /** CREATE SCHEMA + CREATE TABLE for the aggregate: one schema per bounded context. */
39
+ function createTableSql(m) {
40
+ const schema = (0, exports.quoteIdent)(m.context.names.words.join('_'));
41
+ const table = tableName(m);
42
+ const columns = [
43
+ 'id text PRIMARY KEY',
44
+ ...m.fields.map((field) => {
45
+ const parts = [column(field), sqlType(field)];
46
+ if (!field.optional)
47
+ parts.push('NOT NULL');
48
+ if (field.type === 'enum')
49
+ parts.push(`CHECK (${column(field)} IN (${field.values.map((value) => `'${value}'`).join(', ')}))`);
50
+ return parts.join(' ');
51
+ }),
52
+ 'created_at timestamptz NOT NULL',
53
+ 'updated_at timestamptz NOT NULL',
54
+ ];
55
+ const index = `${m.paths.plural.words.join('_')}_created_at_idx`;
56
+ return [
57
+ `CREATE SCHEMA IF NOT EXISTS ${schema};`,
58
+ '',
59
+ `CREATE TABLE IF NOT EXISTS ${table} (`,
60
+ columns.map((line, i) => ` ${line}${i < columns.length - 1 ? ',' : ''}`).join('\n'),
61
+ ');',
62
+ '',
63
+ `CREATE INDEX IF NOT EXISTS ${index} ON ${table} (created_at, id);`,
64
+ '',
65
+ ].join('\n');
66
+ }
67
+ function rowType(m, field) {
68
+ const base = field.type === 'date'
69
+ ? 'Date | string'
70
+ : field.type === 'enum'
71
+ ? (0, field_code_1.enumNames)(m.paths.names, field).typeName
72
+ : field.type === 'boolean'
73
+ ? 'boolean'
74
+ : field.type === 'string'
75
+ ? 'string'
76
+ : 'number';
77
+ return field.optional ? `${base} | null` : base;
78
+ }
79
+ function fromRowExpr(field) {
80
+ const value = `row.${field.names.words.join('_')}`;
81
+ if (field.type !== 'date')
82
+ return value;
83
+ return field.optional ? `${value} === null ? null : new Date(${value}).toISOString()` : `new Date(${value}).toISOString()`;
84
+ }
85
+ function postgresRepository(m) {
86
+ const n = m.paths.names;
87
+ const file = (0, project_1.ts)(m.file);
88
+ const imp = (0, code_1.importer)(m.project, file);
89
+ const s = (0, project_1.sharedPaths)(m.project);
90
+ const constName = `${m.paths.plural.constant}_TABLE_SQL`;
91
+ const table = tableName(m);
92
+ const columns = ['id', ...m.fields.map(column), 'created_at', 'updated_at'];
93
+ const values = ['record.id', ...m.fields.map((field) => `record.${field.names.camel}`), 'record.createdAt', 'record.updatedAt'];
94
+ const placeholders = columns.map((_, i) => `$${i + 1}`).join(', ');
95
+ const updates = columns.slice(1).map((col) => `${col} = EXCLUDED.${col}`);
96
+ const enumTypes = m.fields.filter((field) => field.type === 'enum').map((field) => (0, field_code_1.enumNames)(n, field).typeName);
97
+ return (0, code_1.lines)("import type { Pool } from 'pg';", `import type { ${[n.pascal, ...enumTypes].join(', ')} } from ${imp(m.paths.index)};`, `import type { ${n.pascal}Repository } from ${imp(m.context.portsIndex)};`, `import type { Page, PageQuery } from ${imp(s.pagination)};`, `import { ${n.pascal}Mapper, type ${n.pascal}Record } from ${imp(m.paths.mapper)};`, '', `/** The table of ${m.paths.plural.human} (one PostgreSQL schema per bounded context). Also in migrations/. */`, `export const ${constName} = \``, createTableSql(m).trimEnd(), '`;', '', `/** A row of ${table}: snake_case columns, dates as Date (node-postgres) or ISO strings. */`, `interface ${n.pascal}Row {`, ' id: string;', (0, code_1.indent)(m.fields.map((field) => `${field.names.words.join('_')}: ${rowType(m, field)};`)), ' created_at: Date | string;', ' updated_at: Date | string;', '}', '', `function toRecord(row: ${n.pascal}Row): ${n.pascal}Record {`, ' return {', ' id: row.id,', (0, code_1.indent)(m.fields.map((field) => `${field.names.camel}: ${fromRowExpr(field)},`), 4), ' createdAt: new Date(row.created_at).toISOString(),', ' updatedAt: new Date(row.updated_at).toISOString(),', ' };', '}', '', '/**', ` * Adapter: stores ${m.paths.plural.human} in PostgreSQL with node-postgres ("npm install pg").`, ` * Use it in ${m.context.names.kebab}.module.ts instead of InMemory${n.pascal}Repository.`, ' */', `export class Postgres${n.pascal}Repository implements ${n.pascal}Repository {`, ' private readonly pool: Pool;', '', ' constructor(pool: Pool) {', ' this.pool = pool;', ' }', '', ` async findById(id: string): Promise<${n.pascal} | null> {`, ` const { rows } = await this.pool.query<${n.pascal}Row>('SELECT * FROM ${table} WHERE id = $1', [id]);`, ` return rows[0] ? ${n.pascal}Mapper.toDomain(toRecord(rows[0])) : null;`, ' }', '', ` async findAll({ limit, offset }: PageQuery): Promise<Page<${n.pascal}>> {`, ' const [page, count] = await Promise.all([', ` this.pool.query<${n.pascal}Row>('SELECT * FROM ${table} ORDER BY created_at, id LIMIT $1 OFFSET $2', [limit, offset]),`, ` this.pool.query<{ total: string | number }>('SELECT count(*) AS total FROM ${table}'),`, ' ]);', ' return {', ` items: page.rows.map((row) => ${n.pascal}Mapper.toDomain(toRecord(row))),`, ' total: Number(count.rows[0]?.total ?? 0),', ' limit,', ' offset,', ' };', ' }', '', ` async save(${n.camel}: ${n.pascal}): Promise<void> {`, ` const record = ${n.pascal}Mapper.toRecord(${n.camel});`, ' await this.pool.query(', ` \`INSERT INTO ${table} (${columns.join(', ')})`, ` VALUES (${placeholders})`, ` ON CONFLICT (id) DO UPDATE SET ${updates.join(', ')}\`,`, ` [${values.join(', ')}],`, ' );', ' }', '', ` async delete(${n.camel}: ${n.pascal}): Promise<void> {`, ` await this.pool.query('DELETE FROM ${table} WHERE id = $1', [${n.camel}.id]);`, ' }', '}');
98
+ }
99
+ /** Integration test: runs only when DATABASE_URL points to a PostgreSQL database. */
100
+ function postgresRepositorySpec(m) {
101
+ const n = m.paths.names;
102
+ const file = (0, project_1.ts)(m.specFile);
103
+ const imp = (0, code_1.importer)(m.project, file);
104
+ const constName = `${m.paths.plural.constant}_TABLE_SQL`;
105
+ const inputs = m.fields.filter((field) => !field.managed);
106
+ const table = tableName(m);
107
+ return (0, code_1.lines)((0, code_1.sortImports)([
108
+ ...(0, code_1.testImports)(m.project.config.testRunner),
109
+ "import pg from 'pg';",
110
+ `import { ${n.pascal}, type Create${n.pascal}Props } from ${imp(m.paths.index)};`,
111
+ `import { Postgres${n.pascal}Repository, ${constName} } from ${imp(m.file)};`,
112
+ ]), '', 'const url = process.env.DATABASE_URL;', 'const suite = url ? describe : describe.skip;', '', `const validInput = (): Create${n.pascal}Props => ({`, (0, code_1.indent)(inputs.map((field) => `${field.names.camel}: ${(0, field_code_1.sample)(field).domain},`)), '});', '', `suite('Postgres${n.pascal}Repository (set DATABASE_URL to run)', () => {`, ` it('saves, finds, lists and deletes ${m.paths.plural.human}', async () => {`, ' const pool = new pg.Pool({ connectionString: url });', ' try {', ` await pool.query(${constName});`, ` await pool.query('DELETE FROM ${table}');`, ` const repository = new Postgres${n.pascal}Repository(pool);`, ` const ${n.camel} = ${n.pascal}.create('${n.kebab}-1', validInput());`, '', ` await repository.save(${n.camel});`, ` await repository.save(${n.camel}); // saving twice updates`, ` const found = await repository.findById('${n.kebab}-1');`, ' const page = await repository.findAll({ limit: 10, offset: 0 });', '', ' assert.ok(found);', ` assert.ok(found.equals(${n.camel}));`, (0, code_1.indent)(inputs.map((field) => (0, field_code_1.sameAsSample)(field, `found.${field.names.camel}`, (0, field_code_1.sample)(field))), 6), ' assert.equal(page.total, 1);', '', ` await repository.delete(${n.camel});`, ` assert.equal(await repository.findById('${n.kebab}-1'), null);`, ' } finally {', ' await pool.end();', ' }', ' });', '});');
113
+ }
@@ -0,0 +1,20 @@
1
+ import type { DddConfig, Project } from '../core/project';
2
+ /** src/contexts.ts — mounts every bounded context on one router. */
3
+ export declare function contextsRegistry(project: Project): string;
4
+ export declare function configFile(config: DddConfig): string;
5
+ /** Versions written into a new project's package.json (all tested together). */
6
+ export declare const VERSIONS: {
7
+ express: string;
8
+ typesExpress: string;
9
+ typesNode: string;
10
+ tsx: string;
11
+ typescript: string;
12
+ /** ts-jest does not support TypeScript 7 yet. */
13
+ typescriptForJest: string;
14
+ vitest: string;
15
+ jest: string;
16
+ tsJest: string;
17
+ typesJest: string;
18
+ };
19
+ /** Every file of a new project (except the shared kernel, written separately). */
20
+ export declare function newProjectFiles(project: Project, packageName: string): Map<string, string>;
@@ -0,0 +1,153 @@
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.VERSIONS = void 0;
37
+ exports.contextsRegistry = contextsRegistry;
38
+ exports.configFile = configFile;
39
+ exports.newProjectFiles = newProjectFiles;
40
+ const path = __importStar(require("node:path"));
41
+ const project_1 = require("../core/project");
42
+ const markers_1 = require("../core/markers");
43
+ const code_1 = require("./code");
44
+ /** src/contexts.ts — mounts every bounded context on one router. */
45
+ function contextsRegistry(project) {
46
+ const file = (0, project_1.ts)((0, project_1.contextsFile)(project));
47
+ const imp = (0, code_1.importer)(project, file);
48
+ const s = (0, project_1.sharedPaths)(project);
49
+ return (0, code_1.lines)("import { Router } from 'express';", `import type { EventBus } from ${imp(s.eventBus)};`, `// ${markers_1.MARKERS.imports} — generated imports are added above this line`, '', 'export interface ContextsDeps {', ' eventBus: EventBus;', '}', '', '/**', ' * Mounts every Bounded Context. `ddd-express context <name>` registers new ones here.', ' * Contexts never call each other directly: they react to the events of other contexts', ' * through the event bus.', ' */', 'export function createContextsRouter(deps: ContextsDeps): Router {', ' const router = Router();', '', ` // ${markers_1.MARKERS.contexts} — generated contexts are mounted above this line`, '', ' return router;', '}');
50
+ }
51
+ function configFile(config) {
52
+ return `${JSON.stringify(config, null, 2)}\n`;
53
+ }
54
+ /** Versions written into a new project's package.json (all tested together). */
55
+ exports.VERSIONS = {
56
+ express: '^5.1.0',
57
+ typesExpress: '^5.0.3',
58
+ typesNode: '^22.13.0',
59
+ tsx: '^4.20.0',
60
+ typescript: '^7.0.2',
61
+ /** ts-jest does not support TypeScript 7 yet. */
62
+ typescriptForJest: '^6.0.3',
63
+ vitest: '^5.1.0',
64
+ jest: '^30.0.0',
65
+ tsJest: '^29.4.0',
66
+ typesJest: '^30.0.0',
67
+ };
68
+ /** Every file of a new project (except the shared kernel, written separately). */
69
+ function newProjectFiles(project, packageName) {
70
+ const runner = project.config.testRunner;
71
+ const esm = project.config.moduleSystem === 'esm';
72
+ const srcDir = project.config.srcDir.replace(/\\/g, '/').replace(/\/+$/, '');
73
+ const files = new Map();
74
+ const at = (rel) => path.join(project.root, rel);
75
+ const s = (0, project_1.sharedPaths)(project);
76
+ // ------------------------------------------------------------------------- package.json
77
+ const testScripts = {
78
+ vitest: { test: 'vitest run', 'test:watch': 'vitest' },
79
+ jest: { test: 'jest', 'test:watch': 'jest --watch' },
80
+ node: { test: `node --import tsx --test "${srcDir}/**/*.spec.ts"` },
81
+ };
82
+ const devDependencies = {
83
+ '@types/express': exports.VERSIONS.typesExpress,
84
+ '@types/node': exports.VERSIONS.typesNode,
85
+ tsx: exports.VERSIONS.tsx,
86
+ typescript: runner === 'jest' ? exports.VERSIONS.typescriptForJest : exports.VERSIONS.typescript,
87
+ };
88
+ if (runner === 'vitest')
89
+ devDependencies.vitest = exports.VERSIONS.vitest;
90
+ if (runner === 'jest') {
91
+ devDependencies.jest = exports.VERSIONS.jest;
92
+ devDependencies['ts-jest'] = exports.VERSIONS.tsJest;
93
+ devDependencies['@types/jest'] = exports.VERSIONS.typesJest;
94
+ }
95
+ const pkg = {
96
+ name: packageName,
97
+ version: '0.1.0',
98
+ private: true,
99
+ type: esm ? 'module' : 'commonjs',
100
+ scripts: {
101
+ dev: `tsx watch ${srcDir}/server.ts`,
102
+ build: 'tsc -p tsconfig.build.json',
103
+ start: 'node dist/server.js',
104
+ ...testScripts[runner],
105
+ typecheck: 'tsc --noEmit',
106
+ },
107
+ dependencies: { express: exports.VERSIONS.express },
108
+ devDependencies: Object.fromEntries(Object.entries(devDependencies).sort(([a], [b]) => a.localeCompare(b))),
109
+ engines: { node: '>=22.12' },
110
+ };
111
+ files.set(at('package.json'), `${JSON.stringify(pkg, null, 2)}\n`);
112
+ // ------------------------------------------------------------------------------ tsconfig
113
+ const tsconfig = {
114
+ compilerOptions: {
115
+ target: 'ES2022',
116
+ module: 'NodeNext',
117
+ moduleResolution: 'NodeNext',
118
+ lib: ['ES2022'],
119
+ types: runner === 'jest' ? ['node', 'jest'] : ['node'],
120
+ strict: true,
121
+ esModuleInterop: true,
122
+ skipLibCheck: true,
123
+ isolatedModules: true,
124
+ forceConsistentCasingInFileNames: true,
125
+ sourceMap: true,
126
+ outDir: 'dist',
127
+ rootDir: srcDir,
128
+ },
129
+ include: [srcDir],
130
+ };
131
+ files.set(at('tsconfig.json'), `${JSON.stringify(tsconfig, null, 2)}\n`);
132
+ files.set(at('tsconfig.build.json'), `${JSON.stringify({ extends: './tsconfig.json', exclude: [`${srcDir}/**/*.spec.ts`, `${srcDir}/shared/testing`] }, null, 2)}\n`);
133
+ if (runner === 'jest') {
134
+ files.set(at('jest.config.js'), (0, code_1.lines)("/** @type {import('jest').Config} */", 'module.exports = {', " testEnvironment: 'node',", ` roots: ['<rootDir>/${srcDir}'],`, " testMatch: ['**/*.spec.ts'],", " transform: { '^.+\\\\.ts$': ['ts-jest', { tsconfig: 'tsconfig.json' }] },", '};'));
135
+ }
136
+ files.set(at('.gitignore'), (0, code_1.lines)('node_modules', 'dist', 'coverage', '.env', '*.log'));
137
+ // ----------------------------------------------------------------------------- src files
138
+ const appFile = at(`${srcDir}/app.ts`);
139
+ const appImp = (0, code_1.importer)(project, appFile);
140
+ files.set(appFile, (0, code_1.lines)("import express from 'express';", `import type { EventBus } from ${appImp(s.eventBus)};`, `import { InMemoryEventBus } from ${appImp(s.inMemoryEventBus)};`, `import { errorHandler, notFoundHandler } from ${appImp(s.errorHandler)};`, `import { createContextsRouter } from ${appImp((0, project_1.contextsFile)(project))};`, '', 'export interface AppDeps {', ' /** Swap the in-memory bus for a message broker adapter (RabbitMQ, Kafka, ...) when you need one. */', ' eventBus?: EventBus;', '}', '', '/** Builds the Express app. Kept separate from server.ts so tests can start it on any port. */', 'export function createApp(deps: AppDeps = {}): express.Express {', ' const eventBus = deps.eventBus ?? new InMemoryEventBus();', ' const app = express();', " app.disable('x-powered-by');", ' app.use(express.json());', '', " app.get('/health', (_req, res) => {", " res.json({ status: 'ok' });", ' });', ' app.use(createContextsRouter({ eventBus }));', '', ' app.use(notFoundHandler);', ' app.use(errorHandler);', ' return app;', '}'));
141
+ const serverFile = at(`${srcDir}/server.ts`);
142
+ const serverImp = (0, code_1.importer)(project, serverFile);
143
+ files.set(serverFile, (0, code_1.lines)(`import { createApp } from ${serverImp(appFile.replace(/\.ts$/, ''))};`, '', 'const port = Number(process.env.PORT ?? 3000);', '', 'createApp().listen(port, () => {', ' console.log(`API listening on http://localhost:${port}`);', '});'));
144
+ const appSpecFile = at(`${srcDir}/app.spec.ts`);
145
+ const specImp = (0, code_1.importer)(project, appSpecFile);
146
+ files.set(appSpecFile, (0, code_1.lines)((0, code_1.testImports)(runner), `import { call, withTestServer } from ${specImp(s.testServer)};`, `import { createApp } from ${specImp(appFile.replace(/\.ts$/, ''))};`, '', "describe('app', () => {", " it('GET /health → 200', async () => {", ' await withTestServer(createApp(), async (url) => {', ' const res = await call(`${url}/health`);', ' assert.equal(res.status, 200);', " assert.deepEqual(res.body, { status: 'ok' });", ' });', ' });', '', " it('unknown route → 404 with a JSON error', async () => {", ' await withTestServer(createApp(), async (url) => {', ' const res = await call(`${url}/nothing-here`);', ' assert.equal(res.status, 404);', " assert.equal(res.body.error, 'NotFoundError');", ' });', ' });', '});'));
147
+ files.set(at('README.md'), projectReadme(packageName, runner, srcDir));
148
+ return files;
149
+ }
150
+ function projectReadme(name, runner, srcDir) {
151
+ const watch = runner === 'node' ? '' : '\nnpm run test:watch # tests in watch mode';
152
+ return (0, code_1.lines)(`# ${name}`, '', 'An Express + TypeScript API organised with **Domain-Driven Design**, generated by [ddd-express](https://www.npmjs.com/package/ddd-express).', '', '## Run', '', '```bash', 'npm install', 'npm run dev # http://localhost:3000/health', `npm test${watch}`, 'npm run build && npm start', '```', '', '## Add to the domain', '', '```bash', '# a bounded context with an aggregate, its use cases, REST routes and tests', 'npx ddd-express module visit --context scheduling --fields "clientId:string, scheduledStart:date, notes?:string, status:enum(scheduled|completed|cancelled)"', '', '# building blocks inside a context', 'npx ddd-express value-object VisitTime --context scheduling --fields "start:date, end:date"', 'npx ddd-express event VisitCompleted --context scheduling --fields "durationMinutes:integer"', 'npx ddd-express use-case CompleteVisit --context scheduling', 'npx ddd-express handler CreateInvoice --context billing --on VisitCompleted', '```', '', '## Layout', '', '```', `${srcDir}/`, ' app.ts Express app: JSON, contexts, error handling', ' contexts.ts mounts every bounded context', ' shared/ building blocks: Entity, AggregateRoot, ValueObject, DomainEvent, Guard, EventBus...', ' <context>/', ' GLOSSARY.md the Ubiquitous Language of this context', ' domain/ aggregates, entities, value objects, events, services, ports — no Express, no DB', ' application/ use cases and event handlers', ' infrastructure/ adapters: http (Express routes), persistence (repositories)', '```');
153
+ }
@@ -0,0 +1,6 @@
1
+ import type { Project } from '../core/project';
2
+ /**
3
+ * The shared kernel: the small building blocks every bounded context uses.
4
+ * Returns { absolute file path → content }.
5
+ */
6
+ export declare function sharedKernelFiles(project: Project): Map<string, string>;