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,155 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ENTITY_RESERVED_FIELDS = void 0;
4
+ exports.singleValueObject = singleValueObject;
5
+ exports.compositeValueObject = compositeValueObject;
6
+ exports.valueObjectSpec = valueObjectSpec;
7
+ exports.entityFile = entityFile;
8
+ exports.entitySpec = entitySpec;
9
+ exports.eventMemberType = eventMemberType;
10
+ exports.customUseCase = customUseCase;
11
+ exports.customUseCaseSpec = customUseCaseSpec;
12
+ exports.domainService = domainService;
13
+ exports.domainServiceSpec = domainServiceSpec;
14
+ exports.eventHandler = eventHandler;
15
+ exports.eventHandlerSpec = eventHandlerSpec;
16
+ const names_1 = require("../core/names");
17
+ const project_1 = require("../core/project");
18
+ const code_1 = require("./code");
19
+ const field_code_1 = require("./field-code");
20
+ function enumDeclarations(owner, fields) {
21
+ return fields
22
+ .filter((field) => field.type === 'enum')
23
+ .flatMap((field) => {
24
+ const { constName, typeName } = (0, field_code_1.enumNames)(owner, field);
25
+ return [
26
+ `export const ${constName} = [${field.values.map((value) => `'${value}'`).join(', ')}] as const;`,
27
+ `export type ${typeName} = (typeof ${constName})[number];`,
28
+ '',
29
+ ];
30
+ });
31
+ }
32
+ /** The input of `create`: the same as the props unless some fields are optional. */
33
+ function createPropsDeclaration(n, fields) {
34
+ if (!fields.some((field) => field.optional || field.defaultValue !== undefined)) {
35
+ return [`export type Create${n.pascal}Props = ${n.pascal}Props;`];
36
+ }
37
+ return [`export interface Create${n.pascal}Props {`, ...(0, code_1.indent)(fields.map((field) => (0, field_code_1.inputMember)(n, field))), '}'];
38
+ }
39
+ // =============================================================================================
40
+ // Value Object
41
+ // =============================================================================================
42
+ /** A value object holding one value (`--type`). */
43
+ function singleValueObject(project, file, n, context, given) {
44
+ // The value is named after the class ("PriorityValue"), so an enum type never collides with it.
45
+ const field = { ...given, names: (0, names_1.namesFromWords)([...n.words, 'value']) };
46
+ const imp = (0, code_1.importer)(project, file);
47
+ const s = (0, project_1.sharedPaths)(project);
48
+ const type = (0, field_code_1.baseType)(n, field);
49
+ const valueGetter = field.type === 'date'
50
+ ? ['get value(): Date {', ' return new Date(this.props.value.getTime());', '}']
51
+ : [`get value(): ${type} {`, ' return this.props.value;', '}'];
52
+ const toStringBody = field.type === 'date' ? 'return this.props.value.toISOString();' : 'return String(this.props.value);';
53
+ return (0, code_1.lines)(`import { ValueObject } from ${imp(s.valueObject)};`, `import { Guard } from ${imp(s.guard)};`, '', enumDeclarations(n, [field]), `interface ${n.pascal}Props {`, ` value: ${type};`, '}', '', '/**', ` * ${n.pascal} — Value Object of the ${context.pascal} context.`, ' *', ` * - no identity: two ${n.pascal} objects with the same value are equal`, ' * - immutable: to "change" it, create a new one', ` * - always valid: the rules are checked in \`create\`, so an invalid ${n.pascal} cannot exist`, ' */', `export class ${n.pascal} extends ValueObject<${n.pascal}Props> {`, ` private constructor(props: ${n.pascal}Props) {`, ' super(props);', ' }', '', ` static create(value: ${type}): ${n.pascal} {`, ` const checked = ${(0, field_code_1.guardCall)(n, field, 'value', n.camel)};`, ` // Add the rules that make a ${n.pascal} valid here (format, length, range, ...).`, ` return new ${n.pascal}({ value: checked });`, ' }', '', (0, code_1.indent)(valueGetter), '', ' toString(): string {', ` ${toStringBody}`, ' }', '}');
54
+ }
55
+ /** A value object made of several values (`--fields`). */
56
+ function compositeValueObject(project, file, n, context, fields) {
57
+ const imp = (0, code_1.importer)(project, file);
58
+ const s = (0, project_1.sharedPaths)(project);
59
+ return (0, code_1.lines)(`import { ValueObject } from ${imp(s.valueObject)};`, `import { Guard } from ${imp(s.guard)};`, '', enumDeclarations(n, fields), `export interface ${n.pascal}Props {`, (0, code_1.indent)(fields.map((field) => (0, field_code_1.stateMember)(n, field))), '}', '', createPropsDeclaration(n, fields), '', '/**', ` * ${n.pascal} — Value Object of the ${context.pascal} context.`, ' *', ` * - no identity: two ${n.pascal} objects with the same values are equal`, ' * - immutable: to "change" it, create a new one', ` * - always valid: the rules are checked in \`create\`, so an invalid ${n.pascal} cannot exist`, ' */', `export class ${n.pascal} extends ValueObject<${n.pascal}Props> {`, ` private constructor(props: ${n.pascal}Props) {`, ' super(props);', ' }', '', ` static create(input: Create${n.pascal}Props): ${n.pascal} {`, ` const props: ${n.pascal}Props = {`, (0, code_1.indent)(fields.map((field) => `${field.names.camel}: ${(0, field_code_1.inputGuardCall)(n, field, 'input')},`), 6), ' };', ' // Add the rules that involve several values here, e.g. "end must be after start".', ` return new ${n.pascal}(props);`, ' }', '', fields.flatMap((field, index) => [...(0, code_1.indent)((0, field_code_1.getter)(n, field)), ...(index < fields.length - 1 ? [''] : [])]), '}');
60
+ }
61
+ function valueObjectSpec(project, file, voFile, n, fields, single) {
62
+ const imp = (0, code_1.importer)(project, file);
63
+ const s = (0, project_1.sharedPaths)(project);
64
+ const header = [
65
+ ...(0, code_1.testImports)(project.config.testRunner),
66
+ `import { DomainError } from ${imp(s.domainError)};`,
67
+ `import { ${n.pascal} } from ${imp(voFile)};`,
68
+ '',
69
+ ];
70
+ if (single) {
71
+ const valid = (0, field_code_1.sample)(single);
72
+ const other = (0, field_code_1.otherSample)(single);
73
+ return (0, code_1.lines)(header, `describe('${n.pascal} value object', () => {`, " it('is created from a valid value', () => {", ` const ${n.camel} = ${n.pascal}.create(${valid.domain});`, '', ` ${(0, field_code_1.sameAsSample)(single, `${n.camel}.value`, valid)}`, ' });', '', " it('rejects an invalid value', () => {", ` assert.throws(() => ${n.pascal}.create(${(0, field_code_1.invalidDomainValue)(single)}), DomainError);`, ' });', '', " it('is equal to another one with the same value — and only then', () => {", ` assert.ok(${n.pascal}.create(${valid.domain}).equals(${n.pascal}.create(${valid.domain})));`, other ? ` assert.ok(!${n.pascal}.create(${valid.domain}).equals(${n.pascal}.create(${other.domain})));` : null, ' });', '});');
74
+ }
75
+ const list = fields ?? [];
76
+ const first = list[0];
77
+ const changeable = list.find((field) => (0, field_code_1.otherSample)(field) !== null);
78
+ return (0, code_1.lines)(header.slice(0, -2), `import { ${n.pascal}, type Create${n.pascal}Props } from ${imp(voFile)};`, '', `const validInput = (): Create${n.pascal}Props => ({`, (0, code_1.indent)(list.map((field) => `${field.names.camel}: ${(0, field_code_1.sample)(field).domain},`)), '});', '', `describe('${n.pascal} value object', () => {`, " it('is created from valid values', () => {", ` const ${n.camel} = ${n.pascal}.create(validInput());`, '', (0, code_1.indent)(list.map((field) => (0, field_code_1.sameAsSample)(field, `${n.camel}.${field.names.camel}`, (0, field_code_1.sample)(field))), 4), ' });', '', ` it('rejects an invalid ${first.names.human}', () => {`, ` assert.throws(() => ${n.pascal}.create({ ...validInput(), ${first.names.camel}: ${(0, field_code_1.invalidDomainValue)(first)} }), DomainError);`, ' });', '', " it('is equal to another one with the same values — and only then', () => {", ` assert.ok(${n.pascal}.create(validInput()).equals(${n.pascal}.create(validInput())));`, changeable
79
+ ? ` assert.ok(!${n.pascal}.create(validInput()).equals(${n.pascal}.create({ ...validInput(), ${changeable.names.camel}: ${(0, field_code_1.otherSample)(changeable)?.domain} })));`
80
+ : null, ' });', '});');
81
+ }
82
+ // =============================================================================================
83
+ // Entity (inside an aggregate)
84
+ // =============================================================================================
85
+ exports.ENTITY_RESERVED_FIELDS = ['id', 'props', 'equals', 'validate', 'constructor'];
86
+ function entityFile(project, file, n, aggregate, fields) {
87
+ const imp = (0, code_1.importer)(project, file);
88
+ const s = (0, project_1.sharedPaths)(project);
89
+ return (0, code_1.lines)(`import { Entity } from ${imp(s.entity)};`, `import { Guard } from ${imp(s.guard)};`, '', enumDeclarations(n, fields), `export interface ${n.pascal}Props {`, (0, code_1.indent)(fields.map((field) => (0, field_code_1.stateMember)(n, field))), '}', '', createPropsDeclaration(n, fields), '', '/**', ` * ${n.pascal} — Entity inside the ${aggregate.pascal} aggregate.`, ' *', ` * It has its own identity, but it is never loaded or saved on its own: only the ${aggregate.pascal}`, ' * aggregate root creates and changes it. Give it methods for its behaviour, and call them', ` * from ${aggregate.pascal} — code outside the aggregate never changes a ${n.pascal} directly.`, ' */', `export class ${n.pascal} extends Entity<string> {`, ` private props: ${n.pascal}Props;`, '', ` private constructor(id: string, props: ${n.pascal}Props) {`, ' super(id);', ' this.props = props;', ' }', '', ` static create(id: string, input: Create${n.pascal}Props): ${n.pascal} {`, ` return new ${n.pascal}(id, ${n.pascal}.validate(input));`, ' }', '', ` /** Rebuilds a ${n.pascal} from storage, without re-checking the rules. */`, ` static rehydrate(id: string, props: ${n.pascal}Props): ${n.pascal} {`, ` return new ${n.pascal}(id, { ...props });`, ' }', '', fields.flatMap((field) => [...(0, code_1.indent)((0, field_code_1.getter)(n, field)), '']), ` private static validate(input: Create${n.pascal}Props): ${n.pascal}Props {`, ' return {', (0, code_1.indent)(fields.map((field) => `${field.names.camel}: ${(0, field_code_1.inputGuardCall)(n, field, 'input')},`), 6), ' };', ' }', '}');
90
+ }
91
+ function entitySpec(project, file, entityFilePath, n, fields) {
92
+ const imp = (0, code_1.importer)(project, file);
93
+ const s = (0, project_1.sharedPaths)(project);
94
+ const first = fields[0];
95
+ const changeable = fields.find((field) => (0, field_code_1.otherSample)(field) !== null);
96
+ return (0, code_1.lines)((0, code_1.testImports)(project.config.testRunner), `import { DomainError } from ${imp(s.domainError)};`, `import { ${n.pascal}, type Create${n.pascal}Props } from ${imp(entityFilePath)};`, '', `const validInput = (): Create${n.pascal}Props => ({`, (0, code_1.indent)(fields.map((field) => `${field.names.camel}: ${(0, field_code_1.sample)(field).domain},`)), '});', '', `describe('${n.pascal} entity', () => {`, " it('is created from valid input', () => {", ` const ${n.camel} = ${n.pascal}.create('${n.kebab}-1', validInput());`, '', ` assert.equal(${n.camel}.id, '${n.kebab}-1');`, (0, code_1.indent)(fields.map((field) => (0, field_code_1.sameAsSample)(field, `${n.camel}.${field.names.camel}`, (0, field_code_1.sample)(field))), 4), ' });', '', ` it('rejects an invalid ${first.names.human}', () => {`, ` assert.throws(() => ${n.pascal}.create('${n.kebab}-1', { ...validInput(), ${first.names.camel}: ${(0, field_code_1.invalidDomainValue)(first)} }), DomainError);`, ' });', '', " it('is identified by its id, not by its data', () => {", ` const a = ${n.pascal}.create('same-id', validInput());`, changeable
97
+ ? ` const b = ${n.pascal}.create('same-id', { ...validInput(), ${changeable.names.camel}: ${(0, field_code_1.otherSample)(changeable)?.domain} });`
98
+ : ` const b = ${n.pascal}.create('same-id', validInput());`, '', ' assert.ok(a.equals(b));', ` assert.ok(!a.equals(${n.pascal}.create('other-id', validInput())));`, ' });', '});');
99
+ }
100
+ // =============================================================================================
101
+ // Domain Event (custom)
102
+ // =============================================================================================
103
+ /** TypeScript type of an event member. Enum values are written inline: 'a' | 'b'. */
104
+ function eventMemberType(field) {
105
+ const type = field.type === 'enum'
106
+ ? field.values.map((value) => `'${value}'`).join(' | ')
107
+ : (0, field_code_1.baseType)({ words: [], kebab: '', pascal: '', camel: '', constant: '', human: '' }, field);
108
+ return field.optional ? `${type} | null` : type;
109
+ }
110
+ // =============================================================================================
111
+ // Use case (custom)
112
+ // =============================================================================================
113
+ function customUseCase(project, file, n, aggregate) {
114
+ const imp = (0, code_1.importer)(project, file);
115
+ const s = (0, project_1.sharedPaths)(project);
116
+ if (!aggregate) {
117
+ return (0, code_1.lines)(`export interface ${n.pascal}Input {`, ' // The data this use case needs, e.g. ids and values from the request.', '}', '', '/**', ` * Use case: ${n.human}.`, ' * It orchestrates only: load aggregates through their ports, call ONE behaviour,', ' * save, then publish the recorded events. The business rules live in the domain.', ' */', `export class ${n.pascal}UseCase {`, ` async execute(input: ${n.pascal}Input): Promise<void> {`, ' void input;', ' }', '}');
118
+ }
119
+ const a = aggregate.names;
120
+ const repo = aggregate.plural.camel;
121
+ return (0, code_1.lines)(`import type { ${a.pascal}Repository } from ${imp(aggregate.portsIndex)};`, `import type { EventBus } from ${imp(s.eventBus)};`, `import { NotFoundError } from ${imp(s.domainError)};`, '', `export interface ${n.pascal}Input {`, ` ${a.camel}Id: string;`, '}', '', '/**', ` * Use case: ${n.human}.`, ` * It orchestrates only: load the ${a.pascal}, call ONE behaviour on it, save it, publish its events.`, ` * The business rules belong to the ${a.pascal} aggregate, not here.`, ' */', `export class ${n.pascal}UseCase {`, ` private readonly ${repo}: ${a.pascal}Repository;`, ' private readonly events: EventBus;', '', ` constructor(${repo}: ${a.pascal}Repository, events: EventBus) {`, ` this.${repo} = ${repo};`, ' this.events = events;', ' }', '', ` async execute(input: ${n.pascal}Input): Promise<void> {`, ` const ${a.camel} = await this.${repo}.findById(input.${a.camel}Id);`, ` if (!${a.camel}) throw new NotFoundError('${a.pascal}', input.${a.camel}Id);`, '', ` // Call the behaviour here, e.g. ${a.camel}.complete(...). Add the method to ${a.pascal} first.`, '', ` await this.${repo}.save(${a.camel});`, ` await this.events.publish(${a.camel}.pullEvents());`, ' }', '}');
122
+ }
123
+ function customUseCaseSpec(project, file, useCaseFile, n, aggregate) {
124
+ const imp = (0, code_1.importer)(project, file);
125
+ const s = (0, project_1.sharedPaths)(project);
126
+ if (!aggregate) {
127
+ return (0, code_1.lines)((0, code_1.testImports)(project.config.testRunner, false), '', `describe('${n.pascal}UseCase', () => {`, ` it.todo('${n.human}: describe the expected outcome');`, " it.todo('publishes nothing when a business rule is broken');", '});');
128
+ }
129
+ const a = aggregate.names;
130
+ return (0, code_1.lines)((0, code_1.testImports)(project.config.testRunner), `import { NotFoundError } from ${imp(s.domainError)};`, `import { RecordingEventBus } from ${imp(s.recordingEventBus)};`, `import { InMemory${a.pascal}Repository } from ${imp(aggregate.repositoryFile)};`, `import { ${n.pascal}UseCase } from ${imp(useCaseFile)};`, '', `describe('${n.pascal}UseCase', () => {`, ` it('fails with NotFoundError when the ${a.human} does not exist', async () => {`, ` const useCase = new ${n.pascal}UseCase(new InMemory${a.pascal}Repository(), new RecordingEventBus());`, '', ` await assert.rejects(useCase.execute({ ${a.camel}Id: 'missing-id' }), NotFoundError);`, ' });', '', ` it.todo('${n.human}: changes the ${a.human} and publishes the resulting event');`, " it.todo('saves and publishes nothing when a business rule is broken');", '});');
131
+ }
132
+ // =============================================================================================
133
+ // Domain service
134
+ // =============================================================================================
135
+ function domainService(n, context) {
136
+ return (0, code_1.lines)('/**', ` * ${n.pascal}Service — Domain Service of the ${context.pascal} context.`, ' *', ' * For business logic that involves several aggregates and belongs to none of them.', ' * - stateless: nothing is stored on `this` between calls', ' * - named from the Ubiquitous Language', ' * - pure domain logic: no database, no HTTP, no email — the use case loads what it needs', ' */', `export class ${n.pascal}Service {`, ' // Add a method named after what the business does, e.g.', ' // findBestMatch(visit: Visit, candidates: Caregiver[]): Caregiver { ... }', '}');
137
+ }
138
+ function domainServiceSpec(project, file, serviceFile, n) {
139
+ const imp = (0, code_1.importer)(project, file);
140
+ return (0, code_1.lines)((0, code_1.testImports)(project.config.testRunner), `import { ${n.pascal}Service } from ${imp(serviceFile)};`, '', `describe('${n.pascal}Service', () => {`, " it('is stateless', () => {", ` assert.deepEqual(Object.keys(new ${n.pascal}Service()), []);`, ' });', '', " it.todo('describe the rule it applies, with the aggregates it receives');", '});');
141
+ }
142
+ // =============================================================================================
143
+ // Event handler (reacts to an event, possibly from another context)
144
+ // =============================================================================================
145
+ function eventHandler(project, file, className, event, context) {
146
+ const imp = (0, code_1.importer)(project, file);
147
+ const sameContext = event.contextPascal === context.pascal;
148
+ return (0, code_1.lines)(`import type { ${event.className} } from ${imp(event.file)};`, '', '/**', ` * ${className} — ${context.pascal} reacts to ${event.className}${sameContext ? '' : ` (published by ${event.contextPascal})`}.`, ' *', sameContext
149
+ ? ' * Use it for side effects that must not live inside the aggregate (notify, project, sync...).'
150
+ : ` * ${context.pascal} never calls ${event.contextPascal}: it reacts to what ${event.contextPascal} announced.`, " * Keep it thin: translate the event into a call to one of this context's own use cases.", ` * It is subscribed to the event bus in ${context.kebab}.module.ts.`, ' */', `export class ${className} {`, ` async handle(event: ${event.className}): Promise<void> {`, ' // e.g. await this.createInvoice.execute({ visitId: event.aggregateId });', ' void event;', ' }', '}');
151
+ }
152
+ function eventHandlerSpec(project, file, handlerFile, className, eventClassName) {
153
+ const imp = (0, code_1.importer)(project, file);
154
+ return (0, code_1.lines)((0, code_1.testImports)(project.config.testRunner), `import { ${className} } from ${imp(handlerFile)};`, '', `describe('${className}', () => {`, " it('exposes handle(event) for the event bus', () => {", ` assert.equal(typeof new ${className}().handle, 'function');`, ' });', '', ` it.todo('reacts to ${eventClassName}: describe the expected outcome');`, '});');
155
+ }
@@ -0,0 +1,14 @@
1
+ import type { Project, TestRunner } from '../core/project';
2
+ /** Joins lines, dropping `false`/`null`/`undefined` entries (for optional parts of a template). */
3
+ export declare function lines(...parts: (string | string[] | false | null | undefined)[]): string;
4
+ /** Indents every non-empty line by `spaces`. */
5
+ export declare function indent(block: string[] | string, spaces?: number): string[];
6
+ /** Import-specifier helper bound to one generated file. */
7
+ export declare function importer(project: Project, fromFile: string): (target: string) => string;
8
+ /**
9
+ * The first lines of a generated test file. The assertions always come from node:assert, so the
10
+ * same test body works with Vitest, Jest and the Node test runner; only describe/it differ.
11
+ */
12
+ export declare function testImports(runner: TestRunner, usesAssert?: boolean): string[];
13
+ /** Sorts import lines: node: built-ins and packages first, then relative paths. */
14
+ export declare function sortImports(imports: string[]): string[];
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.lines = lines;
4
+ exports.indent = indent;
5
+ exports.importer = importer;
6
+ exports.testImports = testImports;
7
+ exports.sortImports = sortImports;
8
+ const project_1 = require("../core/project");
9
+ /** Joins lines, dropping `false`/`null`/`undefined` entries (for optional parts of a template). */
10
+ function lines(...parts) {
11
+ const out = [];
12
+ for (const part of parts) {
13
+ if (part === false || part === null || part === undefined)
14
+ continue;
15
+ if (Array.isArray(part))
16
+ out.push(...part);
17
+ else
18
+ out.push(part);
19
+ }
20
+ return `${out.join('\n')}\n`;
21
+ }
22
+ /** Indents every non-empty line by `spaces`. */
23
+ function indent(block, spaces = 2) {
24
+ const list = Array.isArray(block) ? block : block.replace(/\n$/, '').split('\n');
25
+ const pad = ' '.repeat(spaces);
26
+ return list.map((line) => (line.trim() === '' ? '' : `${pad}${line}`));
27
+ }
28
+ /** Import-specifier helper bound to one generated file. */
29
+ function importer(project, fromFile) {
30
+ return (target) => `'${(0, project_1.importPath)(project, fromFile, target)}'`;
31
+ }
32
+ /**
33
+ * The first lines of a generated test file. The assertions always come from node:assert, so the
34
+ * same test body works with Vitest, Jest and the Node test runner; only describe/it differ.
35
+ */
36
+ function testImports(runner, usesAssert = true) {
37
+ const out = [];
38
+ if (usesAssert)
39
+ out.push(`import assert from 'node:assert/strict';`);
40
+ if (runner === 'vitest')
41
+ out.push(`import { describe, it } from 'vitest';`);
42
+ if (runner === 'node')
43
+ out.push(`import { describe, it } from 'node:test';`);
44
+ return out;
45
+ }
46
+ /** Sorts import lines: node: built-ins and packages first, then relative paths. */
47
+ function sortImports(imports) {
48
+ const unique = [...new Set(imports)];
49
+ const isRelative = (line) => /from '\./.test(line) || /from '\.\./.test(line);
50
+ return [...unique.filter((line) => !isRelative(line)), ...unique.filter(isRelative)];
51
+ }
@@ -0,0 +1,47 @@
1
+ import type { DefaultValue, Field } from '../core/fields';
2
+ import type { Names } from '../core/names';
3
+ import type { AggregatePaths, CommandPaths, ContextPaths, Project } from '../core/project';
4
+ import type { CommandSpec } from '../model/types';
5
+ /** Everything the templates of one command need. */
6
+ export interface CommandModel {
7
+ project: Project;
8
+ context: ContextPaths;
9
+ aggregate: AggregatePaths;
10
+ /** All fields of the aggregate (the state field is `managed`). */
11
+ fields: Field[];
12
+ command: CommandSpec;
13
+ paths: CommandPaths;
14
+ }
15
+ export declare function article(word: string): string;
16
+ export declare const stateFieldOf: (fields: Field[]) => Field | null;
17
+ /** Type of a command parameter or event member: enum values are written inline ('a' | 'b'). */
18
+ export declare function inlineType(owner: Names, field: Field): string;
19
+ export declare const useCaseClass: (m: {
20
+ aggregate: AggregatePaths;
21
+ command: CommandSpec;
22
+ }) => string;
23
+ export declare const inputType: (m: {
24
+ aggregate: AggregatePaths;
25
+ command: CommandSpec;
26
+ }) => string;
27
+ export declare const parserFunction: (m: {
28
+ aggregate: AggregatePaths;
29
+ command: CommandSpec;
30
+ }) => string;
31
+ /** The behaviour method, indented for the class body. */
32
+ export declare function commandMethod(owner: Names, fields: Field[], command: CommandSpec): string[];
33
+ /** TypeScript expression of a literal set by a command. */
34
+ export declare function literalExpr(value: DefaultValue | null): string;
35
+ /** The guard every state change uses, indented for the class body. */
36
+ export declare function ensureStateMethod(owner: Names, state: Field, stateType: string): string[];
37
+ export declare function commandUseCase(m: CommandModel): string;
38
+ export declare function commandRequest(m: CommandModel): string | null;
39
+ /** The route of a command, indented for the router function body. */
40
+ export declare function commandRoute(m: CommandModel): string[];
41
+ export declare function commandRouterImports(m: CommandModel, routerFile: string): string[];
42
+ export declare function commandFacadeEntry(m: CommandModel): {
43
+ imports: string[];
44
+ entry: string;
45
+ };
46
+ export declare function commandUseCaseSpec(m: CommandModel): string;
47
+ export declare function commandRouterSpec(m: CommandModel, route: string): string;