ddd-express 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/LICENSE +21 -0
- package/README.ar.md +117 -0
- package/README.md +314 -2
- package/dist/analyze/check.d.ts +74 -0
- package/dist/analyze/check.js +503 -0
- package/dist/analyze/document.d.ts +26 -0
- package/dist/analyze/document.js +126 -0
- package/dist/analyze/map.d.ts +19 -0
- package/dist/analyze/map.js +283 -0
- package/dist/analyze/openapi.d.ts +7 -0
- package/dist/analyze/openapi.js +236 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +12 -0
- package/dist/core/errors.d.ts +5 -0
- package/dist/core/errors.js +13 -0
- package/dist/core/fields.d.ts +38 -0
- package/dist/core/fields.js +233 -0
- package/dist/core/markers.d.ts +25 -0
- package/dist/core/markers.js +60 -0
- package/dist/core/names.d.ts +30 -0
- package/dist/core/names.js +168 -0
- package/dist/core/output.d.ts +21 -0
- package/dist/core/output.js +29 -0
- package/dist/core/project.d.ts +135 -0
- package/dist/core/project.js +287 -0
- package/dist/core/writer.d.ts +39 -0
- package/dist/core/writer.js +138 -0
- package/dist/generators/analyze.d.ts +16 -0
- package/dist/generators/analyze.js +174 -0
- package/dist/generators/apply.d.ts +28 -0
- package/dist/generators/apply.js +234 -0
- package/dist/generators/common.d.ts +49 -0
- package/dist/generators/common.js +173 -0
- package/dist/generators/domain.d.ts +30 -0
- package/dist/generators/domain.js +198 -0
- package/dist/generators/engine.d.ts +71 -0
- package/dist/generators/engine.js +552 -0
- package/dist/generators/project.d.ts +10 -0
- package/dist/generators/project.js +214 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +14 -0
- package/dist/model/commands.d.ts +28 -0
- package/dist/model/commands.js +228 -0
- package/dist/model/examples.d.ts +6 -0
- package/dist/model/examples.js +152 -0
- package/dist/model/parser.d.ts +28 -0
- package/dist/model/parser.js +222 -0
- package/dist/model/types.d.ts +98 -0
- package/dist/model/types.js +2 -0
- package/dist/model/validate.d.ts +30 -0
- package/dist/model/validate.js +215 -0
- package/dist/run.d.ts +4 -0
- package/dist/run.js +506 -0
- package/dist/scan/project-scan.d.ts +77 -0
- package/dist/scan/project-scan.js +226 -0
- package/dist/scan/source.d.ts +60 -0
- package/dist/scan/source.js +274 -0
- package/dist/templates/aggregate.d.ts +51 -0
- package/dist/templates/aggregate.js +407 -0
- package/dist/templates/building-blocks.d.ts +30 -0
- package/dist/templates/building-blocks.js +155 -0
- package/dist/templates/code.d.ts +14 -0
- package/dist/templates/code.js +51 -0
- package/dist/templates/command.d.ts +47 -0
- package/dist/templates/command.js +376 -0
- package/dist/templates/context.d.ts +16 -0
- package/dist/templates/context.js +43 -0
- package/dist/templates/field-code.d.ts +47 -0
- package/dist/templates/field-code.js +227 -0
- package/dist/templates/postgres.d.ts +25 -0
- package/dist/templates/postgres.js +113 -0
- package/dist/templates/project.d.ts +20 -0
- package/dist/templates/project.js +153 -0
- package/dist/templates/shared-kernel.d.ts +6 -0
- package/dist/templates/shared-kernel.js +44 -0
- package/package.json +58 -4
|
@@ -0,0 +1,214 @@
|
|
|
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.generateNew = generateNew;
|
|
37
|
+
exports.generateInit = generateInit;
|
|
38
|
+
const node_child_process_1 = require("node:child_process");
|
|
39
|
+
const fs = __importStar(require("node:fs"));
|
|
40
|
+
const path = __importStar(require("node:path"));
|
|
41
|
+
const errors_1 = require("../core/errors");
|
|
42
|
+
const project_1 = require("../core/project");
|
|
43
|
+
const writer_1 = require("../core/writer");
|
|
44
|
+
const examples_1 = require("../model/examples");
|
|
45
|
+
const parser_1 = require("../model/parser");
|
|
46
|
+
const validate_1 = require("../model/validate");
|
|
47
|
+
const project_2 = require("../templates/project");
|
|
48
|
+
const apply_1 = require("./apply");
|
|
49
|
+
const engine_1 = require("./engine");
|
|
50
|
+
const common_1 = require("./common");
|
|
51
|
+
function generateNew(name, options) {
|
|
52
|
+
if (!name)
|
|
53
|
+
throw new errors_1.CliError('Missing project name.', 'Example: npx ddd-express new my-api');
|
|
54
|
+
const root = path.resolve(options.cwd, name);
|
|
55
|
+
const packageName = path
|
|
56
|
+
.basename(root)
|
|
57
|
+
.toLowerCase()
|
|
58
|
+
.replace(/[^a-z0-9._-]+/g, '-')
|
|
59
|
+
.replace(/^[._-]+|[._-]+$/g, '');
|
|
60
|
+
if (!packageName)
|
|
61
|
+
throw new errors_1.CliError(`"${name}" is not a usable project name.`);
|
|
62
|
+
if (fs.existsSync(root) && fs.readdirSync(root).length > 0 && !options.force) {
|
|
63
|
+
throw new errors_1.CliError(`The folder "${name}" already exists and is not empty.`, 'Pick another name, or run "ddd-express init" inside an existing project.');
|
|
64
|
+
}
|
|
65
|
+
if (options.model && options.example)
|
|
66
|
+
throw new errors_1.CliError('Use either --model or --example, not both.');
|
|
67
|
+
let modelSource = null;
|
|
68
|
+
if (options.example)
|
|
69
|
+
modelSource = (0, apply_1.exampleModel)(options.example);
|
|
70
|
+
if (options.model) {
|
|
71
|
+
const file = path.resolve(options.cwd, options.model);
|
|
72
|
+
if (!fs.existsSync(file))
|
|
73
|
+
throw new errors_1.CliError(`Model file not found: ${options.model}`);
|
|
74
|
+
modelSource = fs.readFileSync(file, 'utf8');
|
|
75
|
+
}
|
|
76
|
+
// check the model before writing anything
|
|
77
|
+
const resolved = modelSource ? (0, validate_1.validateModel)((0, parser_1.parseModel)(modelSource, options.model ? path.basename(options.model) : apply_1.MODEL_FILE)) : null;
|
|
78
|
+
const testRunner = options.testRunner ?? 'vitest';
|
|
79
|
+
// Jest + TypeScript is far simpler with CommonJS; everything else uses native ESM.
|
|
80
|
+
const moduleSystem = options.moduleSystem ?? (testRunner === 'jest' ? 'commonjs' : 'esm');
|
|
81
|
+
const config = { srcDir: options.srcDir ?? 'src', testRunner, moduleSystem };
|
|
82
|
+
const project = {
|
|
83
|
+
root,
|
|
84
|
+
config,
|
|
85
|
+
hasConfigFile: true,
|
|
86
|
+
src: path.resolve(root, config.srcDir),
|
|
87
|
+
shared: path.resolve(root, config.srcDir, 'shared'),
|
|
88
|
+
packageJson: null,
|
|
89
|
+
};
|
|
90
|
+
const writer = new writer_1.Writer({ root: options.cwd, dryRun: options.dryRun, force: options.force });
|
|
91
|
+
const outcome = (0, common_1.newOutcome)(`New project ${packageName} (${testRunner}, ${moduleSystem})`, writer);
|
|
92
|
+
for (const [file, content] of (0, project_2.newProjectFiles)(project, packageName))
|
|
93
|
+
writer.create(file, content);
|
|
94
|
+
(0, common_1.ensureFoundation)(project, writer);
|
|
95
|
+
writer.create(path.join(root, apply_1.MODEL_FILE), modelSource ?? examples_1.STARTER_MODEL);
|
|
96
|
+
let summaryLine = null;
|
|
97
|
+
if (resolved) {
|
|
98
|
+
const engine = new engine_1.Engine(project, writer);
|
|
99
|
+
const summary = (0, apply_1.applyModel)(engine, resolved, { force: false, skipTests: options.skipTests });
|
|
100
|
+
summaryLine = (0, apply_1.describeSummary)(summary);
|
|
101
|
+
outcome.warnings.push(...engine.outcome.warnings);
|
|
102
|
+
}
|
|
103
|
+
const relRoot = path.relative(options.cwd, root) || '.';
|
|
104
|
+
let installed = false;
|
|
105
|
+
if (options.install && !options.dryRun) {
|
|
106
|
+
const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
|
107
|
+
const result = (0, node_child_process_1.spawnSync)(npm, ['install'], { cwd: root, stdio: 'inherit', shell: process.platform === 'win32' });
|
|
108
|
+
installed = result.status === 0;
|
|
109
|
+
if (!installed)
|
|
110
|
+
outcome.warnings.push('npm install failed — run it yourself inside the project folder.');
|
|
111
|
+
}
|
|
112
|
+
if (summaryLine)
|
|
113
|
+
outcome.notes.push(summaryLine, '');
|
|
114
|
+
outcome.notes.push(`cd ${relRoot}`, ...(installed ? [] : ['npm install']), 'npm test', 'npm run dev # http://localhost:3000/health', '', resolved
|
|
115
|
+
? `Your domain lives in ${apply_1.MODEL_FILE}: change it, then run "npx ddd-express apply".`
|
|
116
|
+
: `Describe your domain in ${apply_1.MODEL_FILE} and run "npx ddd-express apply" — or add a module directly:`, ...(resolved
|
|
117
|
+
? ['See it: npx ddd-express map · guard it: npx ddd-express check']
|
|
118
|
+
: ['npx ddd-express module visit --context scheduling --fields "clientId: string, scheduledStart: date, notes?: string"']));
|
|
119
|
+
return outcome;
|
|
120
|
+
}
|
|
121
|
+
// =============================================================================================
|
|
122
|
+
// ddd-express init
|
|
123
|
+
// =============================================================================================
|
|
124
|
+
/** Reads a tsconfig.json that may contain comments and trailing commas. */
|
|
125
|
+
function readJsonc(file) {
|
|
126
|
+
if (!fs.existsSync(file))
|
|
127
|
+
return null;
|
|
128
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
129
|
+
let out = '';
|
|
130
|
+
let inString = false;
|
|
131
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
132
|
+
const char = text[i];
|
|
133
|
+
const next = text[i + 1];
|
|
134
|
+
if (inString) {
|
|
135
|
+
out += char;
|
|
136
|
+
if (char === '\\') {
|
|
137
|
+
out += next ?? '';
|
|
138
|
+
i += 1;
|
|
139
|
+
}
|
|
140
|
+
else if (char === '"') {
|
|
141
|
+
inString = false;
|
|
142
|
+
}
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (char === '"') {
|
|
146
|
+
inString = true;
|
|
147
|
+
out += char;
|
|
148
|
+
}
|
|
149
|
+
else if (char === '/' && next === '/') {
|
|
150
|
+
while (i < text.length && text[i] !== '\n')
|
|
151
|
+
i += 1;
|
|
152
|
+
out += '\n';
|
|
153
|
+
}
|
|
154
|
+
else if (char === '/' && next === '*') {
|
|
155
|
+
i += 2;
|
|
156
|
+
while (i < text.length && !(text[i] === '*' && text[i + 1] === '/'))
|
|
157
|
+
i += 1;
|
|
158
|
+
i += 1;
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
out += char;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
return JSON.parse(out.replace(/,(\s*[}\]])/g, '$1'));
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function generateInit(options) {
|
|
172
|
+
const { project, writer } = (0, common_1.openProject)(options);
|
|
173
|
+
const outcome = (0, common_1.newOutcome)(`Initialised DDD in ${project.packageJson?.name ?? path.basename(project.root)} ` +
|
|
174
|
+
`(${project.config.testRunner}, ${project.config.moduleSystem}, ${project.config.srcDir}/)`, writer);
|
|
175
|
+
// With --test-runner/--src/--module-system, init (re)writes ddd.config.json.
|
|
176
|
+
const configPath = path.join(project.root, project_1.CONFIG_FILE);
|
|
177
|
+
const hasOverrides = options.srcDir !== undefined || options.testRunner !== undefined || options.moduleSystem !== undefined;
|
|
178
|
+
if (hasOverrides && writer.exists(configPath))
|
|
179
|
+
writer.update(configPath, () => (0, project_2.configFile)(project.config));
|
|
180
|
+
const customized = (0, common_1.customizedSharedFiles)(project, writer);
|
|
181
|
+
(0, common_1.ensureFoundation)(project, writer);
|
|
182
|
+
if (writer.changes.length === 0)
|
|
183
|
+
outcome.notes.push('Everything was already in place.');
|
|
184
|
+
if (customized.length > 0) {
|
|
185
|
+
outcome.warnings.push('These files already existed and were kept. The generated code expects the ddd-express versions: compare them, or use --src to keep the DDD code in another folder.', ...customized.map((file) => ` ${file}`));
|
|
186
|
+
}
|
|
187
|
+
// --- warnings about the environment
|
|
188
|
+
const pkg = project.packageJson;
|
|
189
|
+
if (!(0, project_1.hasDependency)(pkg, 'express'))
|
|
190
|
+
outcome.warnings.push('express is not a dependency yet: npm install express');
|
|
191
|
+
if (!(0, project_1.hasDependency)(pkg, '@types/express')) {
|
|
192
|
+
outcome.warnings.push('@types/express is missing: npm install -D @types/express @types/node');
|
|
193
|
+
}
|
|
194
|
+
if (project.config.testRunner === 'node' && !(0, project_1.hasDependency)(pkg, 'tsx')) {
|
|
195
|
+
outcome.warnings.push('Generated tests use the Node test runner through tsx: npm install -D tsx', ` and add a script: "test": "node --import tsx --test \\"${project.config.srcDir}/**/*.spec.ts\\""`);
|
|
196
|
+
}
|
|
197
|
+
const tsconfig = readJsonc(path.join(project.root, 'tsconfig.json'));
|
|
198
|
+
const compilerOptions = (tsconfig?.compilerOptions ?? {});
|
|
199
|
+
if (tsconfig && compilerOptions.esModuleInterop !== true) {
|
|
200
|
+
outcome.warnings.push('Set "esModuleInterop": true in tsconfig.json (the generated tests import express by default).');
|
|
201
|
+
}
|
|
202
|
+
if (project.config.moduleSystem === 'esm') {
|
|
203
|
+
const resolution = String(compilerOptions.moduleResolution ?? compilerOptions.module ?? '').toLowerCase();
|
|
204
|
+
if (resolution && !['nodenext', 'node16', 'bundler', 'node18', 'node20'].includes(resolution)) {
|
|
205
|
+
outcome.warnings.push('For ESM, use "module": "NodeNext" (or "moduleResolution": "Bundler") in tsconfig.json.');
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
// --- how to mount the contexts
|
|
209
|
+
const appFile = path.join(project.src, 'app.ts');
|
|
210
|
+
const imp = (target) => (0, project_1.importPath)(project, appFile, target);
|
|
211
|
+
const s = (0, project_1.sharedPaths)(project);
|
|
212
|
+
outcome.notes.push(`Mount the bounded contexts in your Express app (e.g. ${project.config.srcDir}/app.ts):`, '', ` import { createContextsRouter } from '${imp((0, project_1.contextsFile)(project))}';`, ` import { InMemoryEventBus } from '${imp(s.inMemoryEventBus)}';`, ` import { errorHandler, notFoundHandler } from '${imp(s.errorHandler)}';`, '', ' app.use(express.json());', ' app.use(createContextsRouter({ eventBus: new InMemoryEventBus() }));', ' app.use(notFoundHandler); // optional: JSON 404 for unknown routes', ' app.use(errorHandler); // after all routes', '', 'Then generate your first module:', ' npx ddd-express module visit --context scheduling --fields "clientId:string, scheduledStart:date"');
|
|
213
|
+
return outcome;
|
|
214
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Programmatic API. Most people use the CLI (`npx ddd-express ...`); this lets tools and tests
|
|
3
|
+
* run the same commands from code.
|
|
4
|
+
*/
|
|
5
|
+
export { run, version } from './run';
|
|
6
|
+
export type { Io } from './core/output';
|
|
7
|
+
export { CliError } from './core/errors';
|
|
8
|
+
export { parseFields } from './core/fields';
|
|
9
|
+
export type { Field, FieldType } from './core/fields';
|
|
10
|
+
export type { DddConfig, TestRunner, ModuleSystem } from './core/project';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseFields = exports.CliError = exports.version = exports.run = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Programmatic API. Most people use the CLI (`npx ddd-express ...`); this lets tools and tests
|
|
6
|
+
* run the same commands from code.
|
|
7
|
+
*/
|
|
8
|
+
var run_1 = require("./run");
|
|
9
|
+
Object.defineProperty(exports, "run", { enumerable: true, get: function () { return run_1.run; } });
|
|
10
|
+
Object.defineProperty(exports, "version", { enumerable: true, get: function () { return run_1.version; } });
|
|
11
|
+
var errors_1 = require("./core/errors");
|
|
12
|
+
Object.defineProperty(exports, "CliError", { enumerable: true, get: function () { return errors_1.CliError; } });
|
|
13
|
+
var fields_1 = require("./core/fields");
|
|
14
|
+
Object.defineProperty(exports, "parseFields", { enumerable: true, get: function () { return fields_1.parseFields; } });
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type Field } from '../core/fields';
|
|
2
|
+
import { type Names } from '../core/names';
|
|
3
|
+
import type { CommandSpec, RawCommand } from './types';
|
|
4
|
+
/** Method names an aggregate already has; a command cannot use them. */
|
|
5
|
+
export declare const RESERVED_METHODS: Set<string>;
|
|
6
|
+
/**
|
|
7
|
+
* Parses the model syntax of a command:
|
|
8
|
+
*
|
|
9
|
+
* name[(param: type, ...)] [: from[, from...] -> to] [emits Event[(name, ...)]]
|
|
10
|
+
*
|
|
11
|
+
* e.g. complete(durationMinutes: integer): in_progress -> completed emits VisitCompleted
|
|
12
|
+
*/
|
|
13
|
+
export declare function parseCommand(text: string, line?: number): RawCommand;
|
|
14
|
+
export interface AggregateShape {
|
|
15
|
+
names: Names;
|
|
16
|
+
fields: Field[];
|
|
17
|
+
/** Commands that already exist (method names), to detect clashes. */
|
|
18
|
+
existingMethods?: string[];
|
|
19
|
+
}
|
|
20
|
+
/** Resolves a command against the aggregate: state field, assignments and event payload. */
|
|
21
|
+
export declare function resolveCommand(raw: RawCommand, aggregate: AggregateShape, declaredEvent?: {
|
|
22
|
+
fields: Field[];
|
|
23
|
+
} | null): CommandSpec;
|
|
24
|
+
/**
|
|
25
|
+
* Picks the state field of an aggregate from its commands: the enum field all transitions use,
|
|
26
|
+
* preferring one named "status" or "state". Marks it as managed. Returns the field, or null.
|
|
27
|
+
*/
|
|
28
|
+
export declare function markStateField(fields: Field[], commands: RawCommand[], aggregate: string): Field | null;
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RESERVED_METHODS = void 0;
|
|
4
|
+
exports.parseCommand = parseCommand;
|
|
5
|
+
exports.resolveCommand = resolveCommand;
|
|
6
|
+
exports.markStateField = markStateField;
|
|
7
|
+
const errors_1 = require("../core/errors");
|
|
8
|
+
const fields_1 = require("../core/fields");
|
|
9
|
+
const names_1 = require("../core/names");
|
|
10
|
+
/** Method names an aggregate already has; a command cannot use them. */
|
|
11
|
+
exports.RESERVED_METHODS = new Set([
|
|
12
|
+
'create',
|
|
13
|
+
'rehydrate',
|
|
14
|
+
'update',
|
|
15
|
+
'delete',
|
|
16
|
+
'validate',
|
|
17
|
+
'toInput',
|
|
18
|
+
'ensureState',
|
|
19
|
+
'equals',
|
|
20
|
+
'record',
|
|
21
|
+
'pullEvents',
|
|
22
|
+
'peekEvents',
|
|
23
|
+
'constructor',
|
|
24
|
+
'props',
|
|
25
|
+
'id',
|
|
26
|
+
// keys of the use-case facade
|
|
27
|
+
'get',
|
|
28
|
+
'list',
|
|
29
|
+
]);
|
|
30
|
+
/** Parameter names the generated method uses for its own variables. */
|
|
31
|
+
const RESERVED_PARAMS = new Set(['now', 'args', 'id']);
|
|
32
|
+
/** Reads "(...)" starting at `start` (which must be "("); returns the inside and the index after ")". */
|
|
33
|
+
function readParens(text, start) {
|
|
34
|
+
let depth = 0;
|
|
35
|
+
for (let i = start; i < text.length; i += 1) {
|
|
36
|
+
if (text[i] === '(')
|
|
37
|
+
depth += 1;
|
|
38
|
+
if (text[i] === ')') {
|
|
39
|
+
depth -= 1;
|
|
40
|
+
if (depth === 0)
|
|
41
|
+
return { inside: text.slice(start + 1, i), end: i + 1 };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
throw new errors_1.CliError(`Missing ")" in "${text}".`);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Parses the model syntax of a command:
|
|
48
|
+
*
|
|
49
|
+
* name[(param: type, ...)] [: from[, from...] -> to] [emits Event[(name, ...)]]
|
|
50
|
+
*
|
|
51
|
+
* e.g. complete(durationMinutes: integer): in_progress -> completed emits VisitCompleted
|
|
52
|
+
*/
|
|
53
|
+
function parseCommand(text, line = 0) {
|
|
54
|
+
const source = text.trim();
|
|
55
|
+
const nameMatch = /^([A-Za-z][A-Za-z0-9_-]*)/.exec(source);
|
|
56
|
+
if (!nameMatch)
|
|
57
|
+
throw new errors_1.CliError(`A command starts with its name, e.g. "complete": got "${source}".`);
|
|
58
|
+
const names = (0, names_1.toNames)(nameMatch[1], 'command name');
|
|
59
|
+
let rest = source.slice(nameMatch[0].length).trim();
|
|
60
|
+
let params = [];
|
|
61
|
+
if (rest.startsWith('(')) {
|
|
62
|
+
const { inside, end } = readParens(rest, 0);
|
|
63
|
+
params = (0, fields_1.splitTopLevel)(inside).map((token) => (0, fields_1.parseField)(token));
|
|
64
|
+
const reserved = params.find((param) => RESERVED_PARAMS.has(param.names.camel));
|
|
65
|
+
if (reserved)
|
|
66
|
+
throw new errors_1.CliError(`"${reserved.names.camel}" cannot be a parameter name (the generated code uses it).`);
|
|
67
|
+
const withDefault = params.find((param) => param.defaultValue !== undefined);
|
|
68
|
+
if (withDefault)
|
|
69
|
+
throw new errors_1.CliError(`Parameter "${withDefault.names.camel}" cannot have a default; make it optional with "?".`);
|
|
70
|
+
const duplicate = params.find((param, index) => params.findIndex((other) => other.names.camel === param.names.camel) !== index);
|
|
71
|
+
if (duplicate)
|
|
72
|
+
throw new errors_1.CliError(`Parameter "${duplicate.names.camel}" is declared twice.`);
|
|
73
|
+
rest = rest.slice(end).trim();
|
|
74
|
+
}
|
|
75
|
+
let from = null;
|
|
76
|
+
let to = null;
|
|
77
|
+
if (rest.startsWith(':')) {
|
|
78
|
+
rest = rest.slice(1).trim();
|
|
79
|
+
const arrow = rest.indexOf('->');
|
|
80
|
+
if (arrow === -1)
|
|
81
|
+
throw new errors_1.CliError(`A state change is written "from -> to", e.g. ": scheduled -> completed".`);
|
|
82
|
+
from = rest
|
|
83
|
+
.slice(0, arrow)
|
|
84
|
+
.split(',')
|
|
85
|
+
.map((state) => state.trim())
|
|
86
|
+
.filter(Boolean);
|
|
87
|
+
const after = rest.slice(arrow + 2).trim();
|
|
88
|
+
const toMatch = /^([A-Za-z][A-Za-z0-9_-]*)/.exec(after);
|
|
89
|
+
if (!toMatch || from.length === 0)
|
|
90
|
+
throw new errors_1.CliError(`A state change is written "from -> to", e.g. ": scheduled -> completed".`);
|
|
91
|
+
to = toMatch[1];
|
|
92
|
+
rest = after.slice(toMatch[0].length).trim();
|
|
93
|
+
}
|
|
94
|
+
const sets = [];
|
|
95
|
+
if (/^sets\b/.test(rest)) {
|
|
96
|
+
rest = rest.slice('sets'.length).trim();
|
|
97
|
+
const emitsAt = rest.search(/\s+emits\b/);
|
|
98
|
+
const segment = emitsAt === -1 ? rest : rest.slice(0, emitsAt);
|
|
99
|
+
rest = emitsAt === -1 ? '' : rest.slice(emitsAt).trim();
|
|
100
|
+
for (const assignment of (0, fields_1.splitTopLevel)(segment)) {
|
|
101
|
+
const equals = assignment.indexOf('=');
|
|
102
|
+
if (equals === -1)
|
|
103
|
+
throw new errors_1.CliError(`Write "sets field = value", e.g. "sets paid = true": got "${assignment}".`);
|
|
104
|
+
sets.push({ name: (0, fields_1.fieldNames)(assignment.slice(0, equals).trim()).camel, raw: assignment.slice(equals + 1).trim() });
|
|
105
|
+
}
|
|
106
|
+
if (sets.length === 0)
|
|
107
|
+
throw new errors_1.CliError('Write at least one "field = value" after "sets".');
|
|
108
|
+
}
|
|
109
|
+
let emits = null;
|
|
110
|
+
if (/^emits\b/.test(rest)) {
|
|
111
|
+
rest = rest.slice('emits'.length).trim();
|
|
112
|
+
const eventMatch = /^([A-Za-z][A-Za-z0-9_-]*)/.exec(rest);
|
|
113
|
+
if (!eventMatch)
|
|
114
|
+
throw new errors_1.CliError('Write the event after "emits", e.g. "emits VisitCompleted".');
|
|
115
|
+
rest = rest.slice(eventMatch[0].length).trim();
|
|
116
|
+
let fields = null;
|
|
117
|
+
if (rest.startsWith('(')) {
|
|
118
|
+
const { inside, end } = readParens(rest, 0);
|
|
119
|
+
fields = (0, fields_1.splitTopLevel)(inside).map((name) => (0, fields_1.fieldNames)(name).camel);
|
|
120
|
+
rest = rest.slice(end).trim();
|
|
121
|
+
}
|
|
122
|
+
emits = { name: eventMatch[1], fields };
|
|
123
|
+
}
|
|
124
|
+
if (rest !== '') {
|
|
125
|
+
throw new errors_1.CliError(`Unexpected "${rest}" in command "${names.camel}".`, 'Syntax: name(param: type, ...): from -> to sets field = value emits EventName(field, ...) — every part after the name is optional.');
|
|
126
|
+
}
|
|
127
|
+
if (fields_1.JS_KEYWORDS.has(names.camel))
|
|
128
|
+
throw new errors_1.CliError(`"${names.camel}" is a JavaScript keyword; pick another command name.`);
|
|
129
|
+
if (exports.RESERVED_METHODS.has(names.camel)) {
|
|
130
|
+
throw new errors_1.CliError(`"${names.camel}" cannot be a command name: the aggregate already has a method with that name.`);
|
|
131
|
+
}
|
|
132
|
+
return { line, text: source, names, params, from, to, emits, sets };
|
|
133
|
+
}
|
|
134
|
+
/** Resolves a command against the aggregate: state field, assignments and event payload. */
|
|
135
|
+
function resolveCommand(raw, aggregate, declaredEvent = null) {
|
|
136
|
+
const where = `command ${raw.names.camel} of ${aggregate.names.pascal}`;
|
|
137
|
+
if (aggregate.fields.some((field) => field.names.camel === raw.names.camel)) {
|
|
138
|
+
throw new errors_1.CliError(`${where}: the name clashes with the field "${raw.names.camel}".`);
|
|
139
|
+
}
|
|
140
|
+
// State change
|
|
141
|
+
let transition = null;
|
|
142
|
+
if (raw.from && raw.to) {
|
|
143
|
+
const state = aggregate.fields.find((field) => field.managed) ?? null;
|
|
144
|
+
if (!state)
|
|
145
|
+
throw new errors_1.CliError(`${where}: there is no state field to change.`);
|
|
146
|
+
for (const value of [...raw.from, raw.to]) {
|
|
147
|
+
if (!state.values.includes(value)) {
|
|
148
|
+
throw new errors_1.CliError(`${where}: "${value}" is not a ${state.names.camel} of ${aggregate.names.pascal}.`, `Possible values: ${state.values.join(', ')}.`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
transition = { from: [...new Set(raw.from)], to: raw.to };
|
|
152
|
+
}
|
|
153
|
+
// Parameters that update a field with the same name
|
|
154
|
+
const assigns = [];
|
|
155
|
+
for (const param of raw.params) {
|
|
156
|
+
const field = aggregate.fields.find((candidate) => candidate.names.camel === param.names.camel);
|
|
157
|
+
if (!field)
|
|
158
|
+
continue;
|
|
159
|
+
if (field.managed) {
|
|
160
|
+
throw new errors_1.CliError(`${where}: "${param.names.camel}" changes only through state changes (": from -> to").`);
|
|
161
|
+
}
|
|
162
|
+
if (field.type !== param.type || field.values.join('|') !== param.values.join('|')) {
|
|
163
|
+
throw new errors_1.CliError(`${where}: parameter "${param.names.camel}" must have the same type as the field.`);
|
|
164
|
+
}
|
|
165
|
+
if (!field.optional && param.optional) {
|
|
166
|
+
throw new errors_1.CliError(`${where}: parameter "${param.names.camel}" cannot be optional because the field is required.`);
|
|
167
|
+
}
|
|
168
|
+
assigns.push(param.names.camel);
|
|
169
|
+
}
|
|
170
|
+
// Fields set to a fixed value
|
|
171
|
+
const sets = [];
|
|
172
|
+
for (const assignment of raw.sets) {
|
|
173
|
+
const field = aggregate.fields.find((candidate) => candidate.names.camel === assignment.name);
|
|
174
|
+
if (!field)
|
|
175
|
+
throw new errors_1.CliError(`${where}: "sets ${assignment.name}" — ${aggregate.names.pascal} has no field "${assignment.name}".`);
|
|
176
|
+
if (field.managed)
|
|
177
|
+
throw new errors_1.CliError(`${where}: "${assignment.name}" changes only through state changes (": from -> to").`);
|
|
178
|
+
if (assigns.includes(assignment.name)) {
|
|
179
|
+
throw new errors_1.CliError(`${where}: "${assignment.name}" is already set by the parameter with the same name.`);
|
|
180
|
+
}
|
|
181
|
+
if (sets.some((existing) => existing.name === assignment.name))
|
|
182
|
+
throw new errors_1.CliError(`${where}: "${assignment.name}" is set twice.`);
|
|
183
|
+
sets.push({ name: assignment.name, field, value: (0, fields_1.parseLiteral)(assignment.raw, field) });
|
|
184
|
+
}
|
|
185
|
+
// Event payload
|
|
186
|
+
let emits = null;
|
|
187
|
+
if (raw.emits) {
|
|
188
|
+
const eventNames = (0, names_1.toNames)(raw.emits.name, 'event name', ['event']);
|
|
189
|
+
const wanted = raw.emits.fields ??
|
|
190
|
+
(declaredEvent ? declaredEvent.fields.map((field) => field.names.camel) : raw.params.map((param) => param.names.camel));
|
|
191
|
+
const payload = wanted.map((name) => {
|
|
192
|
+
const param = raw.params.find((candidate) => candidate.names.camel === name);
|
|
193
|
+
if (param)
|
|
194
|
+
return { name, source: 'param', field: param };
|
|
195
|
+
const field = aggregate.fields.find((candidate) => candidate.names.camel === name);
|
|
196
|
+
if (field)
|
|
197
|
+
return { name, source: 'field', field };
|
|
198
|
+
throw new errors_1.CliError(`${where}: the event ${eventNames.pascal} carries "${name}", which is neither a parameter nor a field.`);
|
|
199
|
+
});
|
|
200
|
+
if (['aggregateId', 'occurredAt', 'eventName'].some((reserved) => wanted.includes(reserved))) {
|
|
201
|
+
throw new errors_1.CliError(`${where}: aggregateId, occurredAt and eventName are already part of every event.`);
|
|
202
|
+
}
|
|
203
|
+
emits = { names: eventNames, payload };
|
|
204
|
+
}
|
|
205
|
+
if (aggregate.existingMethods?.includes(raw.names.camel)) {
|
|
206
|
+
throw new errors_1.CliError(`${aggregate.names.pascal} already has a "${raw.names.camel}" method.`);
|
|
207
|
+
}
|
|
208
|
+
return { names: raw.names, params: raw.params, transition, emits, assigns, sets };
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Picks the state field of an aggregate from its commands: the enum field all transitions use,
|
|
212
|
+
* preferring one named "status" or "state". Marks it as managed. Returns the field, or null.
|
|
213
|
+
*/
|
|
214
|
+
function markStateField(fields, commands, aggregate) {
|
|
215
|
+
const states = new Set(commands.flatMap((command) => [...(command.from ?? []), ...(command.to ? [command.to] : [])]));
|
|
216
|
+
if (states.size === 0)
|
|
217
|
+
return null;
|
|
218
|
+
const candidates = fields.filter((field) => field.type === 'enum' && [...states].every((state) => field.values.includes(state)));
|
|
219
|
+
const preferred = candidates.find((field) => ['status', 'state'].includes(field.names.camel)) ?? candidates[0];
|
|
220
|
+
if (!preferred || (candidates.length > 1 && !['status', 'state'].includes(preferred.names.camel))) {
|
|
221
|
+
throw new errors_1.CliError(`${aggregate}: the state changes use ${[...states].join(', ')}, but ${candidates.length === 0 ? 'no field lists all of them' : 'several fields could hold them'}.`, 'Declare one state field, e.g. "status: draft | sent | paid = draft".');
|
|
222
|
+
}
|
|
223
|
+
if (preferred.optional) {
|
|
224
|
+
throw new errors_1.CliError(`${aggregate}: the state field "${preferred.names.camel}" cannot be optional.`);
|
|
225
|
+
}
|
|
226
|
+
preferred.managed = true;
|
|
227
|
+
return preferred;
|
|
228
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Models shipped with ddd-express: a starter, and complete examples to learn from. */
|
|
2
|
+
export declare const STARTER_MODEL = "# domain.ddd \u2014 your whole domain in one file.\n# Change it, then run: npx ddd-express apply\n# apply only ADDS what is missing (contexts, aggregates, commands, events...); it never deletes your code.\n# Language reference: https://github.com/Moustafa1997/ddd-express/blob/main/docs/model-language.md\n\ncontext Catalog\n aggregate Product\n name: string\n price: number\n description?: string\n status: draft | published | archived = draft\n\n command publish: draft -> published emits ProductPublished\n command reprice(price: number) emits ProductRepriced\n command archive: draft, published -> archived emits ProductArchived\n";
|
|
3
|
+
export declare const EXAMPLES: Record<string, {
|
|
4
|
+
description: string;
|
|
5
|
+
model: string;
|
|
6
|
+
}>;
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/** Models shipped with ddd-express: a starter, and complete examples to learn from. */
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.EXAMPLES = exports.STARTER_MODEL = void 0;
|
|
5
|
+
exports.STARTER_MODEL = `# domain.ddd — your whole domain in one file.
|
|
6
|
+
# Change it, then run: npx ddd-express apply
|
|
7
|
+
# apply only ADDS what is missing (contexts, aggregates, commands, events...); it never deletes your code.
|
|
8
|
+
# Language reference: https://github.com/Moustafa1997/ddd-express/blob/main/docs/model-language.md
|
|
9
|
+
|
|
10
|
+
context Catalog
|
|
11
|
+
aggregate Product
|
|
12
|
+
name: string
|
|
13
|
+
price: number
|
|
14
|
+
description?: string
|
|
15
|
+
status: draft | published | archived = draft
|
|
16
|
+
|
|
17
|
+
command publish: draft -> published emits ProductPublished
|
|
18
|
+
command reprice(price: number) emits ProductRepriced
|
|
19
|
+
command archive: draft, published -> archived emits ProductArchived
|
|
20
|
+
`;
|
|
21
|
+
exports.EXAMPLES = {
|
|
22
|
+
healthcare: {
|
|
23
|
+
description: 'Home healthcare: scheduling, billing, payroll and notifications (4 contexts)',
|
|
24
|
+
model: `# Home healthcare — a company sends caregivers to clients' homes for visits.
|
|
25
|
+
# It is the domain of the Arabic DDD course (github.com/Moustafa1997/ddd-home-healthcare).
|
|
26
|
+
#
|
|
27
|
+
# npx ddd-express new clinic-api --example healthcare
|
|
28
|
+
#
|
|
29
|
+
# Change this file, then run: npx ddd-express apply
|
|
30
|
+
|
|
31
|
+
context Scheduling
|
|
32
|
+
aggregate Visit
|
|
33
|
+
clientId: string
|
|
34
|
+
caregiverId?: string
|
|
35
|
+
scheduledStart: date
|
|
36
|
+
notes?: string
|
|
37
|
+
status: scheduled | in_progress | completed | cancelled = scheduled
|
|
38
|
+
|
|
39
|
+
command assignCaregiver(caregiverId: string): scheduled -> scheduled emits CaregiverAssigned
|
|
40
|
+
command checkIn: scheduled -> in_progress emits VisitStarted
|
|
41
|
+
command checkOut(durationMinutes: integer): in_progress -> completed emits VisitCompleted(clientId, caregiverId, durationMinutes)
|
|
42
|
+
command cancel(reason: string): scheduled, in_progress -> cancelled emits VisitCancelled(clientId, reason)
|
|
43
|
+
|
|
44
|
+
aggregate Caregiver
|
|
45
|
+
fullName: string
|
|
46
|
+
phone: string
|
|
47
|
+
postcodeArea: string
|
|
48
|
+
active: boolean = true
|
|
49
|
+
|
|
50
|
+
command deactivate sets active = false emits CaregiverDeactivated
|
|
51
|
+
|
|
52
|
+
value VisitTime
|
|
53
|
+
start: date
|
|
54
|
+
end: date
|
|
55
|
+
|
|
56
|
+
service CaregiverMatching
|
|
57
|
+
|
|
58
|
+
context Billing
|
|
59
|
+
aggregate Invoice
|
|
60
|
+
visitId: string
|
|
61
|
+
clientId: string
|
|
62
|
+
amount: number
|
|
63
|
+
currency: EGP | GBP | USD = GBP
|
|
64
|
+
status: draft | issued | paid | voided = draft
|
|
65
|
+
|
|
66
|
+
command issue: draft -> issued emits InvoiceIssued(visitId, amount)
|
|
67
|
+
command pay(paidAt: date): issued -> paid emits InvoicePaid(amount, paidAt)
|
|
68
|
+
command cancel(reason: string): draft, issued -> voided emits InvoiceVoided(reason)
|
|
69
|
+
|
|
70
|
+
on Scheduling.VisitCompleted -> CreateInvoice
|
|
71
|
+
|
|
72
|
+
context Payroll
|
|
73
|
+
aggregate Timesheet
|
|
74
|
+
caregiverId: string
|
|
75
|
+
weekStarting: date
|
|
76
|
+
minutesWorked: integer = 0
|
|
77
|
+
status: open | approved = open
|
|
78
|
+
|
|
79
|
+
command approve: open -> approved emits TimesheetApproved(caregiverId, minutesWorked)
|
|
80
|
+
|
|
81
|
+
on Scheduling.VisitCompleted -> RecordWorkedMinutes
|
|
82
|
+
|
|
83
|
+
context Notifications
|
|
84
|
+
aggregate Message
|
|
85
|
+
recipient: string
|
|
86
|
+
channel: sms | email = sms
|
|
87
|
+
body: string
|
|
88
|
+
status: queued | sent | failed = queued
|
|
89
|
+
|
|
90
|
+
command markSent: queued -> sent emits MessageSent
|
|
91
|
+
command markFailed(reason: string): queued -> failed emits MessageFailed(reason)
|
|
92
|
+
|
|
93
|
+
on Scheduling.VisitCompleted -> NotifyFamily
|
|
94
|
+
on Scheduling.VisitCancelled -> NotifyFamily
|
|
95
|
+
`,
|
|
96
|
+
},
|
|
97
|
+
shop: {
|
|
98
|
+
description: 'Online shop: catalog, ordering and shipping (3 contexts)',
|
|
99
|
+
model: `# Online shop — products, orders and shipments.
|
|
100
|
+
#
|
|
101
|
+
# npx ddd-express new shop-api --example shop
|
|
102
|
+
#
|
|
103
|
+
# Change this file, then run: npx ddd-express apply
|
|
104
|
+
|
|
105
|
+
context Catalog
|
|
106
|
+
aggregate Product
|
|
107
|
+
sku: string
|
|
108
|
+
name: string
|
|
109
|
+
price: number
|
|
110
|
+
stock: integer = 0
|
|
111
|
+
status: draft | published | archived = draft
|
|
112
|
+
|
|
113
|
+
command publish: draft -> published emits ProductPublished
|
|
114
|
+
command restock(stock: integer) emits ProductRestocked(stock)
|
|
115
|
+
command archive: draft, published -> archived emits ProductArchived
|
|
116
|
+
|
|
117
|
+
value Money
|
|
118
|
+
amount: number
|
|
119
|
+
currency: EGP | USD | EUR
|
|
120
|
+
|
|
121
|
+
context Ordering
|
|
122
|
+
aggregate Order
|
|
123
|
+
customerId: string
|
|
124
|
+
total: number
|
|
125
|
+
shippingAddress: string
|
|
126
|
+
status: cart | placed | paid | cancelled = cart
|
|
127
|
+
|
|
128
|
+
entity OrderLine
|
|
129
|
+
productId: string
|
|
130
|
+
quantity: integer
|
|
131
|
+
unitPrice: number
|
|
132
|
+
|
|
133
|
+
command place: cart -> placed emits OrderPlaced(customerId, total)
|
|
134
|
+
command pay(paymentReference: string): placed -> paid emits OrderPaid(total, paymentReference)
|
|
135
|
+
command cancel(reason: string): cart, placed -> cancelled emits OrderCancelled(reason)
|
|
136
|
+
|
|
137
|
+
service Pricing
|
|
138
|
+
|
|
139
|
+
context Shipping
|
|
140
|
+
aggregate Shipment
|
|
141
|
+
orderId: string
|
|
142
|
+
address: string
|
|
143
|
+
carrier?: string
|
|
144
|
+
status: pending | dispatched | delivered = pending
|
|
145
|
+
|
|
146
|
+
command dispatch(carrier: string): pending -> dispatched emits ShipmentDispatched(carrier)
|
|
147
|
+
command deliver: dispatched -> delivered emits ShipmentDelivered
|
|
148
|
+
|
|
149
|
+
on Ordering.OrderPaid -> CreateShipment
|
|
150
|
+
`,
|
|
151
|
+
},
|
|
152
|
+
};
|