@domain-first/project-structure 3.3.2 → 4.1.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/README.md CHANGED
@@ -101,7 +101,7 @@ export class PlaceOrderUseCase {
101
101
  }
102
102
  ```
103
103
 
104
- Commands and queries come in two modes. **Execution** creates an abstract contract in `application/` and implementations in `infrastructure/`, like a repository. **Orchestrator** creates one application class that coordinates execution commands and queries.
104
+ Commands and queries come in two modes. **Execution** creates an abstract contract in `application/` and implementations in `infrastructure/`, like a repository. **Orchestrator** creates one application class that coordinates execution commands and queries (an orchestrator query, execution queries and repositories only, reading methods only). A query only reads and never changes data; any change is a command.
105
105
 
106
106
  ### How to switch implementations
107
107
 
@@ -166,26 +166,28 @@ const adapter = undefined as unknown as Adapter<any[], any>
166
166
  export class RestEndpointGeneratorPresentationService {
167
167
  /**
168
168
  * Default errors of a client request, to spread into a generator's
169
- * own checks.
169
+ * own error mappings.
170
170
  */
171
- private get defaultClientRequestErrors(): ErrorStatuses[number]['checks'] {
172
- return [RequestParsingError.is, InputMappingError.is]
171
+ private get defaultClientRequestErrors(): ErrorMapping[] {
172
+ return [
173
+ httpStatus(400, {
174
+ code: 'INVALID_REQUEST',
175
+ description: 'Invalid request',
176
+ message: (error) => error.message,
177
+ match: [RequestParsingError, InputMappingError]
178
+ })
179
+ ]
173
180
  }
174
181
 
175
182
  get withoutGuards(): EndpointGenerator {
176
183
  return createEndpoint({
177
- errorStatuses: {
178
- 400: {
179
- checks: this.defaultClientRequestErrors,
180
- description: 'Invalid request'
181
- }
182
- }
184
+ errors: this.defaultClientRequestErrors
183
185
  })(adapter) as EndpointGenerator
184
186
  }
185
187
  }
186
188
  ```
187
189
 
188
- Set the module-level `adapter` constant above the class to the adapter of your HTTP framework; the class uses it through closure. If you connected the Next adapter during initialization, the file imports `nextAdapter` from `@domain-first/handlers-next` instead, with nothing to set. Each generating method is a getter returning `EndpointGenerator`: add one per kind of endpoint (for example `withAuth`, with its `context` and error statuses). Reuse the default checks there and add your own: `checks: [...this.defaultClientRequestErrors, MyError.is]`. A new endpoint calls `this.endpointGenerator(...)` and doesn't compile on purpose: choose the getter yourself in its `get handle()`, e.g. `this.endpointGenerator.withoutGuards(...)`.
190
+ Set the module-level `adapter` constant above the class to the adapter of your HTTP framework; the class uses it through closure. If you connected the Next adapter during initialization, the file imports `nextAdapter` from `@domain-first/handlers-next` instead, with nothing to set. Each generating method is a getter returning `EndpointGenerator`: add one per kind of endpoint (for example `withAuth`, with its `context` and error mappings). Reuse the default mappings there and add your own: `errors: [httpError(MyError, 404), ...this.defaultClientRequestErrors]`. A new endpoint calls `this.endpointGenerator(...)` and doesn't compile on purpose: choose the getter yourself in its `get handle()`, e.g. `this.endpointGenerator.withoutGuards(...)`.
189
191
 
190
192
  With wiring, the endpoint takes the generator and a handler you pick from the context's queries, commands and use cases, and all endpoints are collected as `restHandlers` in `src/presentation/rest/index.ts`. Connect them to your HTTP server.
191
193
 
@@ -205,6 +207,14 @@ Choose **Add integration** to configure Storybook, Prisma 8, Vitest, Playwright,
205
207
 
206
208
  **Missing domain-first packages** prints the `npm i` command for packages from the config that are not in `package.json`.
207
209
 
210
+ ### How to check the rules
211
+
212
+ ```
213
+ npx df-lint
214
+ ```
215
+
216
+ It reports what breaks the Domain-First rules: imports between bounded contexts, imports against the layers, queries using commands, wired dependencies the CLI wouldn't offer, React modules importing what they shouldn't, and reading the time without the clock port. It exits with 1 when something is found, so you can run it in CI.
217
+
208
218
  ### How to teach your coding agent
209
219
 
210
220
  The package ships skills that teach coding agents to plan features, scaffold with `df-ps` and implement the generated code.
package/dist/533.js ADDED
@@ -0,0 +1,569 @@
1
+ import node_path from "node:path";
2
+ import zod from "zod";
3
+ import node_fs from "node:fs";
4
+ import { createRequire } from "node:module";
5
+ const pendingFiles = new Map();
6
+ const pendingFolders = new Set();
7
+ const pendingMoves = new Map();
8
+ const pendingDeletions = new Map();
9
+ const filesToOverwrite = ()=>[
10
+ ...pendingFiles
11
+ ].filter(([filePath, { replacesFile }])=>replacesFile && node_fs.existsSync(filePath)).map(([filePath])=>filePath);
12
+ const discardPendingChanges = ()=>{
13
+ pendingFolders.clear();
14
+ pendingFiles.clear();
15
+ pendingMoves.clear();
16
+ pendingDeletions.clear();
17
+ };
18
+ const removeEmptyFolders = (folderPath, stopAt)=>{
19
+ let current = folderPath;
20
+ while(current.startsWith(`${stopAt}${node_path.sep}`) && node_fs.existsSync(current) && !node_fs.readdirSync(current).length){
21
+ node_fs.rmdirSync(current);
22
+ current = node_path.dirname(current);
23
+ }
24
+ };
25
+ const writePendingChanges = ()=>{
26
+ for (const folderPath of pendingFolders)node_fs.mkdirSync(folderPath, {
27
+ recursive: true
28
+ });
29
+ for (const [filePath, { content }] of pendingFiles){
30
+ node_fs.mkdirSync(node_path.dirname(filePath), {
31
+ recursive: true
32
+ });
33
+ node_fs.writeFileSync(filePath, content, 'utf8');
34
+ }
35
+ for (const [targetPath, { sourcePath }] of pendingMoves){
36
+ node_fs.mkdirSync(node_path.dirname(targetPath), {
37
+ recursive: true
38
+ });
39
+ node_fs.renameSync(sourcePath, targetPath);
40
+ }
41
+ for (const filePath of pendingDeletions.keys())node_fs.rmSync(filePath, {
42
+ force: true
43
+ });
44
+ for (const [filePath, stopAt] of pendingDeletions)removeEmptyFolders(node_path.dirname(filePath), stopAt);
45
+ for (const { sourcePath, stopAt } of pendingMoves.values())removeEmptyFolders(node_path.dirname(sourcePath), stopAt);
46
+ discardPendingChanges();
47
+ };
48
+ class FileSystemItem {
49
+ path;
50
+ constructor(path){
51
+ this.path = path;
52
+ }
53
+ subitem = (relativePath)=>new this.constructor(node_path.resolve(this.path, ...relativePath));
54
+ get exists() {
55
+ return node_fs.existsSync(this.path);
56
+ }
57
+ }
58
+ class Folder extends FileSystemItem {
59
+ createIfNotExisted = ()=>{
60
+ pendingFolders.add(this.path);
61
+ };
62
+ get content() {
63
+ if (!this.exists) return {
64
+ subfolderNames: [],
65
+ fileNames: []
66
+ };
67
+ const content = node_fs.readdirSync(this.path, {
68
+ withFileTypes: true
69
+ });
70
+ return {
71
+ subfolderNames: content.filter((x)=>x.isDirectory()).map((x)=>x.name),
72
+ fileNames: content.filter((x)=>!x.isDirectory()).map((x)=>node_path.parse(x.name).name)
73
+ };
74
+ }
75
+ get name() {
76
+ return node_path.basename(this.path);
77
+ }
78
+ createFile = (name, content)=>{
79
+ this.createIfNotExisted();
80
+ const file = new File(this.path).subitem([
81
+ name
82
+ ]);
83
+ file.data = content;
84
+ return file;
85
+ };
86
+ file = (name)=>{
87
+ this.createIfNotExisted();
88
+ const file = new File(this.path).subitem([
89
+ name
90
+ ]);
91
+ return file;
92
+ };
93
+ }
94
+ class File extends FileSystemItem {
95
+ get exists() {
96
+ return pendingFiles.has(this.path) || pendingMoves.has(this.path) || node_fs.existsSync(this.path) && !pendingDeletions.has(this.path);
97
+ }
98
+ delete = (stopAt)=>{
99
+ pendingDeletions.set(this.path, stopAt);
100
+ };
101
+ moveTo = (targetPath, stopAt)=>{
102
+ pendingMoves.set(targetPath, {
103
+ sourcePath: this.path,
104
+ stopAt
105
+ });
106
+ };
107
+ get data() {
108
+ const pendingFile = pendingFiles.get(this.path);
109
+ if (pendingFile) return pendingFile.content;
110
+ if (!this.exists) throw new Error('File does not exist');
111
+ return node_fs.readFileSync(this.path, 'utf-8');
112
+ }
113
+ set data(content) {
114
+ pendingFiles.set(this.path, {
115
+ content,
116
+ replacesFile: true
117
+ });
118
+ }
119
+ update = (content)=>{
120
+ pendingFiles.set(this.path, {
121
+ content,
122
+ replacesFile: pendingFiles.get(this.path)?.replacesFile ?? false
123
+ });
124
+ };
125
+ addLine = (newLine, separator = '\n')=>{
126
+ const content = this.exists ? this.data : '';
127
+ pendingFiles.set(this.path, {
128
+ content: [
129
+ content.trim(),
130
+ newLine.trim()
131
+ ].filter((x)=>!!x).join(separator),
132
+ replacesFile: pendingFiles.get(this.path)?.replacesFile ?? false
133
+ });
134
+ };
135
+ addLineIfMissing = (newLine, separator = '\n')=>{
136
+ const alreadyAdded = this.exists && this.data.split('\n').some((line)=>line.trim() === newLine.trim());
137
+ if (!alreadyAdded) this.addLine(newLine, separator);
138
+ };
139
+ }
140
+ class ProjectRoot {
141
+ path;
142
+ constructor(){
143
+ let dir = process.cwd();
144
+ while(dir !== node_path.parse(dir).root){
145
+ if (node_fs.existsSync(node_path.join(dir, 'package.json'))) {
146
+ this.path = dir;
147
+ return;
148
+ }
149
+ dir = node_path.dirname(dir);
150
+ }
151
+ throw new Error('No package.json was found');
152
+ }
153
+ }
154
+ const configFileName = 'domain-first.project-structure.config.json';
155
+ const configSchema = zod.object({
156
+ rootFolder: zod.string(),
157
+ domainFirstPackages: zod.array(zod["enum"]([
158
+ '@domain-first/types',
159
+ '@domain-first/errors',
160
+ '@domain-first/handlers',
161
+ '@domain-first/wire',
162
+ '@domain-first/handlers-rest'
163
+ ])),
164
+ defaultPersistenceLayerImplementation: zod.string(),
165
+ withInMemoryDb: zod.boolean().optional(),
166
+ useReact: zod.boolean(),
167
+ storybookFramework: zod.string().optional(),
168
+ testingLibrary: zod.string().optional()
169
+ });
170
+ class ConfigFile {
171
+ data;
172
+ constructor(){
173
+ const filePath = ConfigFile.path;
174
+ const file = new File(filePath);
175
+ const configObject = JSON.parse(file.data);
176
+ this.data = configSchema.parse(configObject);
177
+ }
178
+ static get Instance() {
179
+ return new ConfigFile();
180
+ }
181
+ static get path() {
182
+ const { path: root } = new ProjectRoot();
183
+ return node_path.resolve(root, configFileName);
184
+ }
185
+ static get exists() {
186
+ return new File(ConfigFile.path).exists;
187
+ }
188
+ static write = (config)=>{
189
+ new File(ConfigFile.path).data = JSON.stringify(config, null, '\t');
190
+ };
191
+ }
192
+ const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
193
+ const resolveExtends = (fromFile, target)=>{
194
+ if (target.startsWith('.') || node_path.isAbsolute(target)) {
195
+ const resolved = node_path.resolve(node_path.dirname(fromFile), target);
196
+ return resolved.endsWith('.json') ? resolved : `${resolved}.json`;
197
+ }
198
+ const require = createRequire(fromFile);
199
+ for (const candidate of [
200
+ target,
201
+ `${target}/tsconfig.json`
202
+ ])try {
203
+ return require.resolve(candidate);
204
+ } catch {}
205
+ };
206
+ const compilerOption = (configFile, name, seen = new Set())=>{
207
+ if (seen.has(configFile) || !node_fs.existsSync(configFile)) return null;
208
+ seen.add(configFile);
209
+ let config;
210
+ try {
211
+ config = JSON.parse(stripJsonComments(node_fs.readFileSync(configFile, 'utf8')));
212
+ } catch {
213
+ return null;
214
+ }
215
+ if (config.compilerOptions && name in config.compilerOptions) return config.compilerOptions[name];
216
+ const parents = [
217
+ config.extends ?? []
218
+ ].flat().reverse();
219
+ for (const parent of parents){
220
+ const parentFile = resolveExtends(configFile, parent);
221
+ const value = parentFile ? compilerOption(parentFile, name, seen) : null;
222
+ if (void 0 !== value) return value;
223
+ }
224
+ };
225
+ class UnknownFormatNaming {
226
+ rawSource;
227
+ camelCase;
228
+ PascalCase;
229
+ constructor(rawSource){
230
+ this.rawSource = rawSource;
231
+ const source = rawSource.trim();
232
+ if (!source.includes('-')) {
233
+ this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
234
+ this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
235
+ }
236
+ const words = source.split('-').filter((word)=>!!word);
237
+ this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
238
+ this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
239
+ }
240
+ get fileName() {
241
+ return this.rawSource;
242
+ }
243
+ get variableName() {
244
+ return this.camelCase;
245
+ }
246
+ get ClassName() {
247
+ return this.PascalCase;
248
+ }
249
+ get withSpaces() {
250
+ return this.fileName.replaceAll('-', ' ');
251
+ }
252
+ }
253
+ const wiring_layers = [
254
+ 'domain',
255
+ 'application',
256
+ 'infrastructure',
257
+ 'presentation'
258
+ ];
259
+ const visibleLayers = {
260
+ domain: [
261
+ 'domain'
262
+ ],
263
+ application: [
264
+ 'domain',
265
+ 'application'
266
+ ],
267
+ infrastructure: [
268
+ 'domain',
269
+ 'application',
270
+ 'infrastructure'
271
+ ],
272
+ presentation: [
273
+ 'application',
274
+ 'presentation'
275
+ ]
276
+ };
277
+ const branchedTypeFiles = {
278
+ repositories: (fileBase)=>[
279
+ 'domain',
280
+ 'aggregates',
281
+ fileBase.replace(/-repository$/, ''),
282
+ `${fileBase}.ts`
283
+ ],
284
+ commands: (fileBase)=>[
285
+ 'application',
286
+ 'commands',
287
+ 'execution',
288
+ `${fileBase}.ts`
289
+ ],
290
+ queries: (fileBase)=>[
291
+ 'application',
292
+ 'queries',
293
+ 'execution',
294
+ `${fileBase}.ts`
295
+ ],
296
+ 'application-ports': (fileBase)=>[
297
+ 'application',
298
+ 'ports',
299
+ `${fileBase}.ts`
300
+ ]
301
+ };
302
+ const layerOf = (file, contextPath)=>{
303
+ const [firstSegment] = node_path.relative(contextPath, file).split(node_path.sep);
304
+ return wiring_layers.find((layer)=>layer === firstSegment);
305
+ };
306
+ const namedImports = (source, fromFile)=>{
307
+ const result = new Map();
308
+ for (const [, names, importPath] of source.matchAll(/import\s*(?:type\s*)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g))for (const name of names.split(',')){
309
+ const cleanName = name.replace(/^\s*type\s+/, '').trim();
310
+ if (cleanName) result.set(cleanName, `${node_path.resolve(node_path.dirname(fromFile), importPath)}.ts`);
311
+ }
312
+ return result;
313
+ };
314
+ const isEndpointWire = (wiringRelativePath)=>wiringRelativePath.startsWith([
315
+ 'presentation',
316
+ 'rest'
317
+ ].join(node_path.sep));
318
+ const wireClassDefinitions = (source)=>[
319
+ ...codeOnly(source).matchAll(/(?:export\s+)?const\s+(\w+)\s*=\s*(?:\w+\(\s*)*wireClass\(\s*(\w+)\s*,/g)
320
+ ].map(([, wireName, className])=>({
321
+ wireName,
322
+ className
323
+ }));
324
+ const wiredClassNames = (source, wireName, initializerStart, branched)=>{
325
+ const definitions = wireClassDefinitions(source);
326
+ if (!branched) return definitions.filter((x)=>x.wireName === wireName).map((x)=>x.className);
327
+ const openIndex = source.indexOf('(', initializerStart);
328
+ const branches = codeOnly(source).slice(openIndex, closingIndex(source, openIndex));
329
+ const referenced = new Set(branches.match(/\w+/g));
330
+ return definitions.filter((x)=>referenced.has(x.wireName)).map((x)=>x.className);
331
+ };
332
+ const readWiredModule = (wireFile, contextPath)=>{
333
+ const wiringRelativePath = node_path.relative(node_path.join(contextPath, 'wiring'), wireFile);
334
+ if (isEndpointWire(wiringRelativePath)) return;
335
+ const source = new File(wireFile).data;
336
+ const wireName = `wire${new UnknownFormatNaming(node_path.basename(wireFile, '.ts').replace(/^wire-/, '')).ClassName}`;
337
+ const exportMatch = new RegExp(`export\\s+const\\s+${wireName}\\s*=\\s*`).exec(source);
338
+ if (!exportMatch) return;
339
+ const branched = source.slice(exportMatch.index + exportMatch[0].length).startsWith('envBranchedWire(');
340
+ const imports = namedImports(source, wireFile);
341
+ const implementations = wiredClassNames(source, wireName, exportMatch.index + exportMatch[0].length, branched).flatMap((className)=>{
342
+ const file = imports.get(className);
343
+ return file ? [
344
+ {
345
+ className,
346
+ file
347
+ }
348
+ ] : [];
349
+ });
350
+ if (!implementations.length) return;
351
+ const typeName = wireName.slice(4);
352
+ const [wiringFolder] = wiringRelativePath.split(node_path.sep);
353
+ const typeFileSegments = branchedTypeFiles[wiringFolder]?.(node_path.basename(wireFile, '.ts').replace(/^wire-/, ''));
354
+ const typeFile = branched ? typeFileSegments && node_path.join(contextPath, ...typeFileSegments) : implementations[0].file;
355
+ const layer = typeFile && layerOf(typeFile, contextPath);
356
+ const implementationsLayer = layerOf(implementations[0].file, contextPath);
357
+ if (!typeFile || !layer || !implementationsLayer) return;
358
+ return {
359
+ wireName,
360
+ typeName,
361
+ wireFile,
362
+ typeFile,
363
+ layer,
364
+ implementations,
365
+ branched,
366
+ implementationsLayer,
367
+ kind: wiringFolder
368
+ };
369
+ };
370
+ const findWiredModules = (contextPath)=>{
371
+ const result = [];
372
+ const walk = (folderPath)=>{
373
+ if (!node_fs.existsSync(folderPath)) return;
374
+ for (const entry of node_fs.readdirSync(folderPath, {
375
+ withFileTypes: true
376
+ })){
377
+ const entryPath = node_path.join(folderPath, entry.name);
378
+ if (entry.isDirectory()) walk(entryPath);
379
+ else if (/^wire-.*(?<!\.spec)\.ts$/.test(entry.name)) {
380
+ const wiredModule = readWiredModule(entryPath, contextPath);
381
+ if (wiredModule) result.push(wiredModule);
382
+ }
383
+ }
384
+ };
385
+ walk(node_path.join(contextPath, 'wiring'));
386
+ return result.sort((a, b)=>a.typeName.localeCompare(b.typeName));
387
+ };
388
+ const isCommandOrQuery = (module)=>'commands' === module.kind || 'queries' === module.kind;
389
+ const isExecution = (module)=>isCommandOrQuery(module) && 'execution' === node_path.basename(node_path.dirname(module.typeFile));
390
+ const commandOrQueryRule = (candidate, consumer)=>isExecution(consumer) ? !isCommandOrQuery(candidate) : 'application' !== candidate.layer || isExecution(candidate) && ('commands' === consumer.kind || 'queries' === candidate.kind);
391
+ const layerRules = {
392
+ infrastructure: (candidate)=>'application' !== candidate.layer || 'application-ports' === candidate.kind
393
+ };
394
+ const kindRules = {
395
+ 'application-services': (candidate)=>'application' !== candidate.layer || 'application-ports' === candidate.kind,
396
+ 'use-cases': (candidate)=>'use-cases' !== candidate.kind,
397
+ repositories: (candidate)=>'repositories' !== candidate.kind,
398
+ commands: commandOrQueryRule,
399
+ queries: commandOrQueryRule
400
+ };
401
+ const implementationType = (consumer, implementation)=>consumer.branched ? node_path.basename(node_path.dirname(implementation.file)) : void 0;
402
+ const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && `-${node_path.basename(candidate.typeFile, '.ts')}-`.includes(`-${implementation}-`);
403
+ const canDependOn = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && (layerRules[consumer.implementationsLayer]?.(candidate) ?? true) && (kindRules[consumer.kind]?.(candidate, consumer) ?? true);
404
+ const availableDependencies = (consumer, implementation, candidates)=>{
405
+ const wired = wiredDependencyNames(new File(consumer.wireFile).data, implementation.className);
406
+ return candidates.filter((candidate)=>candidate.wireFile !== consumer.wireFile && canDependOn(consumer, candidate) && !wired.includes(candidate.wireName));
407
+ };
408
+ const relativeImport = (fromFile, toFile)=>{
409
+ const relativePath = node_path.relative(node_path.dirname(fromFile), toFile).replace(/\.ts$/, '').split(node_path.sep).join('/');
410
+ return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
411
+ };
412
+ const codeOnly = (source)=>{
413
+ let result = '';
414
+ let index = 0;
415
+ const blank = (text)=>text.replace(/[^\n]/g, ' ');
416
+ while(index < source.length){
417
+ const pair = source.slice(index, index + 2);
418
+ const char = source[index];
419
+ let end = index + 1;
420
+ if ('//' === pair) {
421
+ const lineEnd = source.indexOf('\n', index);
422
+ end = -1 === lineEnd ? source.length : lineEnd;
423
+ result += blank(source.slice(index, end));
424
+ } else if ('/*' === pair) {
425
+ const commentEnd = source.indexOf('*/', index + 2);
426
+ end = -1 === commentEnd ? source.length : commentEnd + 2;
427
+ result += blank(source.slice(index, end));
428
+ } else if ('=>' === pair) {
429
+ end = index + 2;
430
+ result += ' ';
431
+ } else if ("'" === char || '"' === char || '`' === char) {
432
+ while(end < source.length && source[end] !== char)end += '\\' === source[end] ? 2 : 1;
433
+ end = Math.min(end + 1, source.length);
434
+ result += char + blank(source.slice(index + 1, end - 1));
435
+ result += end - 1 > index ? source[end - 1] : '';
436
+ } else result += char;
437
+ index = end;
438
+ }
439
+ return result;
440
+ };
441
+ const addImport = (source, importLine)=>{
442
+ if (source.split('\n').some((line)=>line.trim() === importLine)) return source;
443
+ const lastImport = [
444
+ ...codeOnly(source).matchAll(/^import\s(?:[^'"]*?from\s*)?['"][^'"]*['"]/gm)
445
+ ].at(-1);
446
+ if (!lastImport) return `${importLine}\n\n${source}`;
447
+ const importEnd = lastImport.index + lastImport[0].length;
448
+ const lineEnd = source.indexOf('\n', importEnd);
449
+ const insertAt = -1 === lineEnd ? source.length : lineEnd;
450
+ return `${source.slice(0, insertAt)}\n${importLine}${source.slice(insertAt)}`;
451
+ };
452
+ const brackets = {
453
+ '(': ')',
454
+ '[': ']',
455
+ '{': '}',
456
+ '<': '>'
457
+ };
458
+ const closingIndex = (source, openIndex)=>{
459
+ const code = codeOnly(source);
460
+ let depth = 0;
461
+ for(let index = openIndex; index < code.length; index++){
462
+ const char = code[index];
463
+ if (char === code[openIndex]) depth++;
464
+ else if (char === brackets[code[openIndex]]) {
465
+ depth--;
466
+ if (0 === depth) return index;
467
+ }
468
+ }
469
+ return -1;
470
+ };
471
+ const splitTopLevel = (content)=>{
472
+ const code = codeOnly(content);
473
+ const items = [];
474
+ let depth = 0;
475
+ let itemStart = 0;
476
+ for(let index = 0; index <= code.length; index++){
477
+ const char = code[index];
478
+ if (void 0 !== char && char in brackets) depth++;
479
+ else if (Object.values(brackets).includes(char)) depth--;
480
+ if (index === code.length || ',' === char && 0 === depth) {
481
+ const item = content.slice(itemStart, index);
482
+ const itemCode = code.slice(itemStart, index);
483
+ const first = itemCode.search(/\S/);
484
+ const last = itemCode.search(/\S\s*$/);
485
+ if (-1 !== first) items.push(item.slice(first, last + 1));
486
+ itemStart = index + 1;
487
+ }
488
+ }
489
+ return items;
490
+ };
491
+ const appendItems = (content, items)=>{
492
+ const code = codeOnly(content);
493
+ const lastCode = code.search(/\S\s*$/);
494
+ if (-1 === lastCode) return items.join(', ');
495
+ const trailingComma = ',' === code[lastCode];
496
+ if (!content.includes('\n')) {
497
+ const added = trailingComma ? ` ${items.join(', ')},` : `, ${items.join(', ')}`;
498
+ return content.slice(0, lastCode + 1) + added + content.slice(lastCode + 1);
499
+ }
500
+ const indent = content.match(/\n([ \t]*)\S/)?.[1] ?? '';
501
+ const withComma = trailingComma ? content : `${content.slice(0, lastCode + 1)},${content.slice(lastCode + 1)}`;
502
+ const lineEndIndex = withComma.indexOf('\n', lastCode + 1);
503
+ const lineEnd = -1 === lineEndIndex ? withComma.length : lineEndIndex;
504
+ const added = trailingComma ? items.map((x)=>`\n${indent}${x},`).join('') : items.map((x)=>`\n${indent}${x}`).join(',');
505
+ return withComma.slice(0, lineEnd) + added + withComma.slice(lineEnd);
506
+ };
507
+ const addConstructorParameters = (source, className, parameters)=>{
508
+ const classMatch = new RegExp(`class\\s+${className}\\b[^{]*\\{`).exec(codeOnly(source));
509
+ if (!classMatch) throw new Error(`Class ${className} not found`);
510
+ const bodyStart = classMatch.index + classMatch[0].length;
511
+ const bodyEnd = closingIndex(source, bodyStart - 1);
512
+ const body = source.slice(bodyStart, bodyEnd);
513
+ const constructorIndex = codeOnly(body).search(/\bconstructor\s*\(/);
514
+ const renderParameters = (allParameters, indent)=>1 === allParameters.length ? allParameters[0] : `\n${allParameters.map((x)=>`${indent} ${x}`).join(',\n')}\n${indent}`;
515
+ if (-1 === constructorIndex) {
516
+ const constructorBody = /\bextends\b/.test(classMatch[0]) ? '{\n super()\n }' : '{}';
517
+ const constructorLine = ` constructor(${renderParameters(parameters, ' ')}) ${constructorBody}`;
518
+ const newBody = body.trim() ? `\n${constructorLine}\n${body.replace(/^\s*\n/, '\n')}` : `\n${constructorLine}\n`;
519
+ return source.slice(0, bodyStart) + newBody + source.slice(bodyEnd);
520
+ }
521
+ const openIndex = bodyStart + body.indexOf('(', constructorIndex);
522
+ const closeIndex = closingIndex(source, openIndex);
523
+ const content = source.slice(openIndex + 1, closeIndex);
524
+ if (content.includes('\n')) return source.slice(0, openIndex + 1) + appendItems(content, parameters) + source.slice(closeIndex);
525
+ const lineStart = source.lastIndexOf('\n', openIndex) + 1;
526
+ const indent = source.slice(lineStart).match(/^\s*/)?.[0] ?? '';
527
+ return source.slice(0, openIndex + 1) + renderParameters([
528
+ ...splitTopLevel(content),
529
+ ...parameters
530
+ ], indent) + source.slice(closeIndex);
531
+ };
532
+ const addClassMember = (source, className, member)=>{
533
+ const classMatch = new RegExp(`class\\s+${className}\\b[^{]*\\{`).exec(codeOnly(source));
534
+ if (!classMatch) throw new Error(`Class ${className} not found`);
535
+ const bodyStart = classMatch.index + classMatch[0].length;
536
+ const bodyEnd = closingIndex(source, bodyStart - 1);
537
+ const body = source.slice(bodyStart, bodyEnd).trimEnd();
538
+ const separator = body.trim() ? '\n\n' : '\n';
539
+ return `${source.slice(0, bodyStart)}${body}${separator} ${member}\n${source.slice(bodyEnd)}`;
540
+ };
541
+ const wireListRange = (source, className)=>{
542
+ const match = new RegExp(`wireClass\\(\\s*${className}\\s*,\\s*\\[`).exec(codeOnly(source));
543
+ if (!match) throw new Error(`wireClass(${className}, [...]) not found`);
544
+ const openIndex = match.index + match[0].length - 1;
545
+ return {
546
+ openIndex,
547
+ closeIndex: closingIndex(source, openIndex)
548
+ };
549
+ };
550
+ const wiredDependencyNames = (source, className)=>{
551
+ const { openIndex, closeIndex } = wireListRange(source, className);
552
+ return splitTopLevel(source.slice(openIndex + 1, closeIndex));
553
+ };
554
+ const addWireDependencies = (source, className, wireNames)=>{
555
+ const { openIndex, closeIndex } = wireListRange(source, className);
556
+ return source.slice(0, openIndex + 1) + appendItems(source.slice(openIndex + 1, closeIndex), wireNames) + source.slice(closeIndex);
557
+ };
558
+ const parameterName = (typeName)=>typeName.substring(0, 1).toLowerCase() + typeName.substring(1);
559
+ const wireDependencies = (consumer, implementation, dependencies)=>{
560
+ const wireFile = new File(consumer.wireFile);
561
+ let wireSource = wireFile.data;
562
+ for (const dependency of dependencies)wireSource = addImport(wireSource, `import { ${dependency.wireName} } from '${relativeImport(consumer.wireFile, dependency.wireFile)}'`);
563
+ wireFile.update(addWireDependencies(wireSource, implementation.className, dependencies.map((x)=>x.wireName)));
564
+ const classFile = new File(implementation.file);
565
+ let classSource = classFile.data;
566
+ for (const dependency of dependencies)classSource = addImport(classSource, `import type { ${dependency.typeName} } from '${relativeImport(implementation.file, dependency.typeFile)}'`);
567
+ classFile.update(addConstructorParameters(classSource, implementation.className, dependencies.map((x)=>`private readonly ${parameterName(x.typeName)}: ${x.typeName}`)));
568
+ };
569
+ export { ConfigFile, File, Folder, ProjectRoot, UnknownFormatNaming, addClassMember, addConstructorParameters, addImport, addWireDependencies, availableDependencies, canDependOn, compilerOption, discardPendingChanges, filesToOverwrite, findWiredModules, implementationType, isSuggestedFor, readWiredModule, relativeImport, stripJsonComments, wireDependencies, wiredDependencyNames, writePendingChanges };
package/dist/index.cjs CHANGED
@@ -1464,7 +1464,7 @@ const findWiredModules = (contextPath)=>{
1464
1464
  };
1465
1465
  const isCommandOrQuery = (module)=>'commands' === module.kind || 'queries' === module.kind;
1466
1466
  const isExecution = (module)=>isCommandOrQuery(module) && 'execution' === external_node_path_default().basename(external_node_path_default().dirname(module.typeFile));
1467
- const commandOrQueryRule = (candidate, consumer)=>isExecution(consumer) ? !isCommandOrQuery(candidate) : 'application' !== candidate.layer || isExecution(candidate);
1467
+ const commandOrQueryRule = (candidate, consumer)=>isExecution(consumer) ? !isCommandOrQuery(candidate) : 'application' !== candidate.layer || isExecution(candidate) && ('commands' === consumer.kind || 'queries' === candidate.kind);
1468
1468
  const layerRules = {
1469
1469
  infrastructure: (candidate)=>'application' !== candidate.layer || 'application-ports' === candidate.kind
1470
1470
  };
@@ -2024,8 +2024,9 @@ const scaffoldRestEndpointGenerator = (sharedFolder, { withNextAdapter = false }
2024
2024
  return `
2025
2025
  import {
2026
2026
  ${withNextAdapter ? '' : ' type Adapter,\n'} type EndpointGenerator,
2027
- type ErrorStatuses,
2027
+ type ErrorMapping,
2028
2028
  createEndpoint,
2029
+ httpStatus,
2029
2030
  InputMappingError,
2030
2031
  RequestParsingError
2031
2032
  } from '@domain-first/handlers-rest'
@@ -2038,20 +2039,22 @@ const adapter = undefined as unknown as Adapter<any[], any>`}
2038
2039
  export class ${className} {
2039
2040
  /**
2040
2041
  * Default errors of a client request, to spread into a generator's
2041
- * own checks.
2042
+ * own error mappings.
2042
2043
  */
2043
- private get defaultClientRequestErrors(): ErrorStatuses[number]['checks'] {
2044
- return [RequestParsingError.is, InputMappingError.is]
2044
+ private get defaultClientRequestErrors(): ErrorMapping[] {
2045
+ return [
2046
+ httpStatus(400, {
2047
+ code: 'INVALID_REQUEST',
2048
+ description: 'Invalid request',
2049
+ message: (error) => error.message,
2050
+ match: [RequestParsingError, InputMappingError]
2051
+ })
2052
+ ]
2045
2053
  }
2046
2054
 
2047
2055
  get withoutGuards(): EndpointGenerator {
2048
2056
  return createEndpoint({
2049
- errorStatuses: {
2050
- 400: {
2051
- checks: this.defaultClientRequestErrors,
2052
- description: 'Invalid request'
2053
- }
2054
- }
2057
+ errors: this.defaultClientRequestErrors
2055
2058
  })(${adapter}) as EndpointGenerator
2056
2059
  }
2057
2060
  }