@domain-first/project-structure 2.11.0 → 2.13.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/dist/index.js CHANGED
@@ -1,13 +1,18 @@
1
1
  #!/usr/bin/env node
2
+ import { Separator, checkbox as prompts_checkbox, confirm as prompts_confirm, input, select as prompts_select } from "@inquirer/prompts";
2
3
  import node_path from "node:path";
3
- import { checkbox as prompts_checkbox, confirm as prompts_confirm, input, select as prompts_select } from "@inquirer/prompts";
4
4
  import zod from "zod";
5
5
  import node_fs from "node:fs";
6
+ import { styleText } from "node:util";
6
7
  const pendingFiles = new Map();
7
8
  const pendingFolders = new Set();
8
9
  const filesToOverwrite = ()=>[
9
10
  ...pendingFiles
10
11
  ].filter(([filePath, { replacesFile }])=>replacesFile && node_fs.existsSync(filePath)).map(([filePath])=>filePath);
12
+ const discardPendingChanges = ()=>{
13
+ pendingFolders.clear();
14
+ pendingFiles.clear();
15
+ };
11
16
  const writePendingChanges = ()=>{
12
17
  for (const folderPath of pendingFolders)node_fs.mkdirSync(folderPath, {
13
18
  recursive: true
@@ -18,8 +23,7 @@ const writePendingChanges = ()=>{
18
23
  });
19
24
  node_fs.writeFileSync(filePath, content, 'utf8');
20
25
  }
21
- pendingFolders.clear();
22
- pendingFiles.clear();
26
+ discardPendingChanges();
23
27
  };
24
28
  class FileSystemItem {
25
29
  path;
@@ -83,6 +87,12 @@ class File extends FileSystemItem {
83
87
  replacesFile: true
84
88
  });
85
89
  }
90
+ update = (content)=>{
91
+ pendingFiles.set(this.path, {
92
+ content,
93
+ replacesFile: pendingFiles.get(this.path)?.replacesFile ?? false
94
+ });
95
+ };
86
96
  addLine = (newLine, separator = '\n')=>{
87
97
  const content = this.exists ? this.data : '';
88
98
  pendingFiles.set(this.path, {
@@ -149,6 +159,347 @@ class ConfigFile {
149
159
  new File(ConfigFile.path).data = JSON.stringify(config, null, '\t');
150
160
  };
151
161
  }
162
+ const savePendingChanges = async ()=>{
163
+ const overwrittenFiles = filesToOverwrite();
164
+ if (overwrittenFiles.length) {
165
+ const root = new ProjectRoot().path;
166
+ console.log('These files already exist and will be overwritten:');
167
+ for (const filePath of overwrittenFiles)console.log(` ${node_path.relative(root, filePath)}`);
168
+ const overwrite = await prompts_confirm({
169
+ message: 'Overwrite them?',
170
+ default: false
171
+ });
172
+ if (!overwrite) {
173
+ discardPendingChanges();
174
+ console.log('Cancelled: nothing was written.');
175
+ return false;
176
+ }
177
+ }
178
+ writePendingChanges();
179
+ return true;
180
+ };
181
+ const missingDomainFirstPackages = ()=>{
182
+ const packages = ConfigFile.Instance.data.domainFirstPackages;
183
+ const manifest = JSON.parse(new File(node_path.join(new ProjectRoot().path, 'package.json')).data);
184
+ const dependencies = {
185
+ ...manifest.dependencies,
186
+ ...manifest.devDependencies,
187
+ ...manifest.optionalDependencies
188
+ };
189
+ const missing = [
190
+ ...new Set(packages)
191
+ ].filter((name)=>!Object.hasOwn(dependencies, name));
192
+ return missing.length ? [
193
+ 'Install missing domain-first packages (run from the project package directory):',
194
+ ` npm i ${missing.join(' ')}`
195
+ ] : [
196
+ 'All configured domain-first packages are already declared in package.json.'
197
+ ];
198
+ };
199
+ const addPackageScripts = async (file, additions)=>{
200
+ const original = file.data;
201
+ const manifest = JSON.parse(original);
202
+ const scripts = {
203
+ ...manifest.scripts
204
+ };
205
+ const selected = {};
206
+ for (const [name, command] of Object.entries(additions)){
207
+ let target = name;
208
+ if (Object.hasOwn(scripts, name) && scripts[name] !== command) {
209
+ const action = await prompts_select({
210
+ message: `Script "${name}" already exists: ${scripts[name]}`,
211
+ choices: [
212
+ 'Keep existing',
213
+ 'Replace',
214
+ 'Use another name'
215
+ ]
216
+ });
217
+ if ('Keep existing' === action) continue;
218
+ if ('Use another name' === action) target = await input({
219
+ message: "New script name:",
220
+ validate: (value)=>!/^[a-zA-Z0-9:_-]+$/.test(value) || Object.hasOwn(scripts, value) || Object.hasOwn(additions, value) ? "Enter an unused script name (letters, numbers, :, _, -)." : true
221
+ });
222
+ }
223
+ scripts[target] = command;
224
+ selected[name] = target;
225
+ }
226
+ if (JSON.stringify(manifest.scripts) !== JSON.stringify(scripts)) {
227
+ manifest.scripts = scripts;
228
+ const indent = original.match(/\n([\t ]+)"/)?.[1] ?? ' ';
229
+ file.update(`${JSON.stringify(manifest, null, indent)}\n`);
230
+ }
231
+ return selected;
232
+ };
233
+ const runtimePackages = [
234
+ '@prisma/orm-postgres',
235
+ 'temporal-polyfill',
236
+ 'dotenv'
237
+ ];
238
+ const developmentPackages = [
239
+ 'prisma',
240
+ '@prisma/cli-engine'
241
+ ];
242
+ const prismaScripts = (rootFolder)=>{
243
+ const config = JSON.stringify(node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'shared/infrastructure/prisma/prisma.config.ts'));
244
+ const emit = `prisma contract emit --config ${config}`;
245
+ return {
246
+ 'prisma:emit': emit,
247
+ 'prisma:migration:plan': `${emit} && prisma migration plan --config ${config}`,
248
+ 'prisma:migration:apply': `prisma db migrate --advance-ref db --config ${config}`
249
+ };
250
+ };
251
+ const prismaConfig = `import 'dotenv/config';
252
+ import { definePrismaConfig } from '@prisma/cli-engine';
253
+ import { defineConfig as ormConfig } from '@prisma/orm-postgres/config';
254
+
255
+ export default definePrismaConfig({
256
+ orm: ormConfig({
257
+ contract: './contract.prisma',
258
+ migrations: { dir: './migrations' },
259
+ db: {
260
+ connection: process.env.DATABASE_URL
261
+ }
262
+ })
263
+ });
264
+ `;
265
+ const prismaService = `import 'temporal-polyfill/global';
266
+ import postgres from '@prisma/orm-postgres/runtime';
267
+ import type {} from 'temporal-polyfill/types/global';
268
+ import type { Contract } from '../prisma/contract.d';
269
+ import contractJson from '../prisma/contract.json' with { type: 'json' };
270
+
271
+ type PrismaClient = ReturnType<typeof postgres<Contract>>;
272
+
273
+ const globalForPrisma = globalThis as typeof globalThis & {
274
+ prismaClient?: PrismaClient;
275
+ };
276
+
277
+ // Reuse the client across development hot reloads.
278
+ const prismaClient = globalForPrisma.prismaClient ??
279
+ postgres<Contract>({ contractJson, url: process.env.DATABASE_URL });
280
+
281
+ if (process.env.NODE_ENV !== 'production') {
282
+ globalForPrisma.prismaClient = prismaClient;
283
+ }
284
+
285
+ export class PrismaInfrastructureService {
286
+ readonly orm = prismaClient.orm.public;
287
+ }
288
+ `;
289
+ const prismaWiring = `import { wireClass } from '@domain-first/wire';
290
+ import { PrismaInfrastructureService } from '../../infrastructure/services/prisma-infrastructure-service';
291
+
292
+ export const wirePrismaInfrastructureService = wireClass(
293
+ PrismaInfrastructureService,
294
+ []
295
+ );
296
+ `;
297
+ const stageFile = (filePath, content)=>{
298
+ const file = new File(filePath);
299
+ if (!file.exists || file.data !== content) file.data = content;
300
+ };
301
+ const addPrisma = async ()=>{
302
+ const config = ConfigFile.Instance.data;
303
+ const root = new ProjectRoot().path;
304
+ const manifestFile = new File(node_path.join(root, 'package.json'));
305
+ const manifest = JSON.parse(manifestFile.data);
306
+ const dependencies = {
307
+ ...manifest.dependencies,
308
+ ...manifest.devDependencies
309
+ };
310
+ const shared = node_path.resolve(root, config.rootFolder, 'shared');
311
+ const prismaFolder = node_path.join(shared, 'infrastructure/prisma');
312
+ if (dependencies['@prisma/client'] || dependencies.prisma && !/^[~^]?8\./.test(dependencies.prisma) || dependencies['@prisma/orm-mongo'] || dependencies['@prisma/orm-sqlite'] || [
313
+ node_path.join(root, 'prisma/schema.prisma'),
314
+ node_path.join(prismaFolder, 'schema.prisma')
315
+ ].some((filePath)=>new File(filePath).exists)) throw new Error('This preset adds Prisma 8 for PostgreSQL. Migrate the existing Prisma setup separately before using it.');
316
+ const withService = await prompts_confirm({
317
+ message: 'Create shared Prisma infrastructure service?',
318
+ default: true
319
+ });
320
+ const useByDefault = 'prisma' !== config.defaultPersistenceLayerImplementation && await prompts_confirm({
321
+ message: 'Use prisma as the default persistence implementation?',
322
+ default: false
323
+ });
324
+ const selected = await addPackageScripts(manifestFile, prismaScripts(config.rootFolder));
325
+ stageFile(node_path.join(prismaFolder, 'prisma.config.ts'), prismaConfig);
326
+ const contract = new File(node_path.join(prismaFolder, 'contract.prisma'));
327
+ if (!contract.exists) contract.data = '// use prisma-8\n\n// Add your application models here before running prisma:emit.\n';
328
+ if (withService) {
329
+ stageFile(node_path.join(shared, 'infrastructure/services/prisma-infrastructure-service.ts'), prismaService);
330
+ if (config.domainFirstPackages.includes('@domain-first/wire')) stageFile(node_path.join(shared, 'wiring/infrastructure-services/wire-prisma-infrastructure-service.ts'), prismaWiring);
331
+ }
332
+ if (useByDefault) ConfigFile.write({
333
+ ...config,
334
+ defaultPersistenceLayerImplementation: 'prisma'
335
+ });
336
+ const install = (packages, dev)=>{
337
+ const missing = packages.filter((name)=>!dependencies[name]);
338
+ return missing.length ? [
339
+ ` npm install${dev ? ' --save-dev' : ''} ${missing.join(' ')}`
340
+ ] : [];
341
+ };
342
+ const scriptCommand = (name)=>selected[name] ? `npm run ${selected[name]}` : prismaScripts(config.rootFolder)[name];
343
+ const relativeFolder = node_path.relative(root, prismaFolder).split(node_path.sep).join('/');
344
+ return [
345
+ 'Prisma 8 configuration saved (PostgreSQL, RC preset).',
346
+ 'Next steps (run from the project package directory):',
347
+ ...install(runtimePackages, false),
348
+ ...install(developmentPackages, true),
349
+ ' Existing dependency versions were kept.',
350
+ ' Use Node.js 22.18+ and TypeScript 5.9+ with ESM and JSON import support.',
351
+ ' Set DATABASE_URL in your project environment (.env for the CLI); load it in the application runtime too.',
352
+ ` Add your models to ${relativeFolder}/contract.prisma.`,
353
+ ` Emit the contract before compiling or importing the service: ${scriptCommand('prisma:emit')}`,
354
+ ` Plan migrations: ${scriptCommand('prisma:migration:plan')}`,
355
+ ` Review the generated migrations, then apply: ${scriptCommand('prisma:migration:apply')}`
356
+ ];
357
+ };
358
+ const storybookFiles = (relativeProjectRoot)=>({
359
+ 'main.ts': `import { resolve } from 'node:path';
360
+ import react from '@vitejs/plugin-react';
361
+ import type { StorybookConfig } from '@storybook/react-vite';
362
+
363
+ const projectRoot = resolve(import.meta.dirname, ${JSON.stringify(relativeProjectRoot)});
364
+
365
+ const config: StorybookConfig = {
366
+ stories: ['../**/*.mdx', '../**/*.stories.@(ts|tsx)'],
367
+ framework: {
368
+ name: '@storybook/react-vite',
369
+ options: {}
370
+ },
371
+ core: {
372
+ disableTelemetry: true
373
+ },
374
+ async viteFinal(viteConfig) {
375
+ const { mergeConfig } = await import('vite');
376
+
377
+ return mergeConfig(viteConfig, {
378
+ plugins: [react()],
379
+ resolve: {
380
+ alias: {
381
+ '@': projectRoot
382
+ }
383
+ }
384
+ });
385
+ }
386
+ };
387
+
388
+ export default config;
389
+ `,
390
+ 'preview.ts': `import type { Preview } from '@storybook/react-vite';
391
+
392
+ const preview: Preview = {
393
+ parameters: {
394
+ controls: {
395
+ matchers: {
396
+ color: /(background|color)$/i,
397
+ date: /Date$/i
398
+ }
399
+ }
400
+ }
401
+ };
402
+
403
+ export default preview;
404
+ `
405
+ });
406
+ const storybookScripts = (rootFolder)=>{
407
+ const folder = node_path.posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/react');
408
+ const quote = (value)=>JSON.stringify(value);
409
+ return {
410
+ storybook: `storybook dev -p 6006 -c ${quote(`${folder}/.storybook`)}`,
411
+ 'build-storybook': `storybook build -c ${quote(`${folder}/.storybook`)} -o ${quote(`${folder}/storybook-static`)}`
412
+ };
413
+ };
414
+ const addStorybook = async ()=>{
415
+ const config = ConfigFile.Instance.data;
416
+ if ((!config.useReact || config.storybookFramework && '@storybook/react-vite' !== config.storybookFramework) && !await prompts_confirm({
417
+ message: 'Configure React scaffolding with @storybook/react-vite?',
418
+ default: false
419
+ })) return [];
420
+ const root = new ProjectRoot().path;
421
+ const manifestFile = new File(node_path.join(root, 'package.json'));
422
+ const manifest = JSON.parse(manifestFile.data);
423
+ const selected = await addPackageScripts(manifestFile, storybookScripts(config.rootFolder));
424
+ const folder = new Folder(root).subitem([
425
+ config.rootFolder,
426
+ 'presentation',
427
+ 'react',
428
+ '.storybook'
429
+ ]);
430
+ for (const [name, content] of Object.entries(storybookFiles(node_path.relative(folder.path, root).split(node_path.sep).join('/')))){
431
+ const file = new File(node_path.join(folder.path, name));
432
+ if (!file.exists || file.data !== content) file.data = content;
433
+ }
434
+ if (!config.useReact || '@storybook/react-vite' !== config.storybookFramework) ConfigFile.write({
435
+ ...config,
436
+ useReact: true,
437
+ storybookFramework: '@storybook/react-vite'
438
+ });
439
+ const dependencies = {
440
+ ...manifest.dependencies,
441
+ ...manifest.devDependencies
442
+ };
443
+ const missing = [
444
+ 'storybook',
445
+ '@storybook/react-vite',
446
+ 'vite',
447
+ '@vitejs/plugin-react'
448
+ ].filter((name)=>!dependencies[name]);
449
+ const missingReact = [
450
+ 'react',
451
+ 'react-dom'
452
+ ].filter((name)=>!dependencies[name]);
453
+ return [
454
+ 'Storybook configuration saved (React + Vite).',
455
+ 'Next steps (run from the project package directory):',
456
+ ...missing.length ? [
457
+ ` npm install --save-dev ${missing.join(' ')}`
458
+ ] : [],
459
+ ...missingReact.length ? [
460
+ ` npm install ${missingReact.join(' ')}`
461
+ ] : [],
462
+ ' Existing dependency versions were kept; ensure Storybook packages are compatible.',
463
+ ' Add your CSS imports to .storybook/preview.ts using relative paths or the @/ alias (project root).',
464
+ ' Generate a UI-kit component or widget UI to create a story.',
465
+ ...selected.storybook ? [
466
+ ` npm run ${selected.storybook}`
467
+ ] : [],
468
+ ...selected['build-storybook'] ? [
469
+ ` npm run ${selected['build-storybook']}`
470
+ ] : []
471
+ ];
472
+ };
473
+ const integrations = [
474
+ {
475
+ name: 'Storybook (React + Vite)',
476
+ run: addStorybook
477
+ },
478
+ {
479
+ name: 'Prisma 8 (PostgreSQL, RC)',
480
+ run: addPrisma
481
+ },
482
+ {
483
+ name: 'Missing domain-first packages',
484
+ run: missingDomainFirstPackages
485
+ }
486
+ ];
487
+ const addIntegration = async ()=>{
488
+ const index = await prompts_select({
489
+ message: 'Integration:',
490
+ choices: integrations.map((integration, value)=>({
491
+ name: integration.name,
492
+ value
493
+ }))
494
+ });
495
+ const nextSteps = await integrations[index].run();
496
+ if (await savePendingChanges()) {
497
+ if (nextSteps.length) console.log(nextSteps.map((line)=>/^\s*npm (?:i|install)\b/.test(line) ? styleText([
498
+ 'bold',
499
+ 'cyan'
500
+ ], line) : line).join('\n'));
501
+ }
502
+ };
152
503
  const initializeUseCase = async ()=>{
153
504
  const rootFolderName = await input({
154
505
  message: 'Root folder (use "/" for inner folders):',
@@ -247,6 +598,439 @@ class UnknownFormatNaming {
247
598
  return this.fileName.replaceAll('-', ' ');
248
599
  }
249
600
  }
601
+ const wiring_layers = [
602
+ 'domain',
603
+ 'application',
604
+ 'infrastructure',
605
+ 'presentation'
606
+ ];
607
+ const visibleLayers = {
608
+ domain: [
609
+ 'domain'
610
+ ],
611
+ application: [
612
+ 'domain',
613
+ 'application'
614
+ ],
615
+ infrastructure: [
616
+ 'domain',
617
+ 'infrastructure'
618
+ ],
619
+ presentation: [
620
+ 'application',
621
+ 'presentation'
622
+ ]
623
+ };
624
+ const branchedTypeFiles = {
625
+ repositories: (fileBase)=>[
626
+ 'domain',
627
+ 'aggregates',
628
+ fileBase.replace(/-repository$/, ''),
629
+ `${fileBase}.ts`
630
+ ],
631
+ commands: (fileBase)=>[
632
+ 'application',
633
+ 'commands',
634
+ 'execution',
635
+ `${fileBase}.ts`
636
+ ],
637
+ queries: (fileBase)=>[
638
+ 'application',
639
+ 'queries',
640
+ 'execution',
641
+ `${fileBase}.ts`
642
+ ],
643
+ 'application-ports': (fileBase)=>[
644
+ 'application',
645
+ 'ports',
646
+ `${fileBase}.ts`
647
+ ]
648
+ };
649
+ const layerOf = (file, contextPath)=>{
650
+ const [firstSegment] = node_path.relative(contextPath, file).split(node_path.sep);
651
+ return wiring_layers.find((layer)=>layer === firstSegment);
652
+ };
653
+ const namedImports = (source, fromFile)=>{
654
+ const result = new Map();
655
+ for (const [, names, importPath] of source.matchAll(/import\s*(?:type\s*)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g))for (const name of names.split(',')){
656
+ const cleanName = name.replace(/^\s*type\s+/, '').trim();
657
+ if (cleanName) result.set(cleanName, `${node_path.resolve(node_path.dirname(fromFile), importPath)}.ts`);
658
+ }
659
+ return result;
660
+ };
661
+ const isEndpointWire = (wiringRelativePath)=>wiringRelativePath.startsWith([
662
+ 'presentation',
663
+ 'rest'
664
+ ].join(node_path.sep));
665
+ const wireClassDefinitions = (source)=>[
666
+ ...codeOnly(source).matchAll(/(?:export\s+)?const\s+(\w+)\s*=\s*(?:\w+\(\s*)*wireClass\(\s*(\w+)\s*,/g)
667
+ ].map(([, wireName, className])=>({
668
+ wireName,
669
+ className
670
+ }));
671
+ const wiredClassNames = (source, wireName, initializerStart, branched)=>{
672
+ const definitions = wireClassDefinitions(source);
673
+ if (!branched) return definitions.filter((x)=>x.wireName === wireName).map((x)=>x.className);
674
+ const openIndex = source.indexOf('(', initializerStart);
675
+ const branches = codeOnly(source).slice(openIndex, closingIndex(source, openIndex));
676
+ const referenced = new Set(branches.match(/\w+/g));
677
+ return definitions.filter((x)=>referenced.has(x.wireName)).map((x)=>x.className);
678
+ };
679
+ const readWiredModule = (wireFile, contextPath)=>{
680
+ const wiringRelativePath = node_path.relative(node_path.join(contextPath, 'wiring'), wireFile);
681
+ if (isEndpointWire(wiringRelativePath)) return;
682
+ const source = new File(wireFile).data;
683
+ const wireName = `wire${new UnknownFormatNaming(node_path.basename(wireFile, '.ts').replace(/^wire-/, '')).ClassName}`;
684
+ const exportMatch = new RegExp(`export\\s+const\\s+${wireName}\\s*=\\s*`).exec(source);
685
+ if (!exportMatch) return;
686
+ const branched = source.slice(exportMatch.index + exportMatch[0].length).startsWith('envBranchedWire(');
687
+ const imports = namedImports(source, wireFile);
688
+ const implementations = wiredClassNames(source, wireName, exportMatch.index + exportMatch[0].length, branched).flatMap((className)=>{
689
+ const file = imports.get(className);
690
+ return file ? [
691
+ {
692
+ className,
693
+ file
694
+ }
695
+ ] : [];
696
+ });
697
+ if (!implementations.length) return;
698
+ const typeName = wireName.slice(4);
699
+ const [wiringFolder] = wiringRelativePath.split(node_path.sep);
700
+ const typeFileSegments = branchedTypeFiles[wiringFolder]?.(node_path.basename(wireFile, '.ts').replace(/^wire-/, ''));
701
+ const typeFile = branched ? typeFileSegments && node_path.join(contextPath, ...typeFileSegments) : implementations[0].file;
702
+ const layer = typeFile && layerOf(typeFile, contextPath);
703
+ const implementationsLayer = layerOf(implementations[0].file, contextPath);
704
+ if (!typeFile || !layer || !implementationsLayer) return;
705
+ return {
706
+ wireName,
707
+ typeName,
708
+ wireFile,
709
+ typeFile,
710
+ layer,
711
+ implementations,
712
+ branched,
713
+ implementationsLayer,
714
+ kind: wiringFolder
715
+ };
716
+ };
717
+ const findWiredModules = (contextPath)=>{
718
+ const result = [];
719
+ const walk = (folderPath)=>{
720
+ if (!node_fs.existsSync(folderPath)) return;
721
+ for (const entry of node_fs.readdirSync(folderPath, {
722
+ withFileTypes: true
723
+ })){
724
+ const entryPath = node_path.join(folderPath, entry.name);
725
+ if (entry.isDirectory()) walk(entryPath);
726
+ else if (/^wire-.*(?<!\.spec)\.ts$/.test(entry.name)) {
727
+ const wiredModule = readWiredModule(entryPath, contextPath);
728
+ if (wiredModule) result.push(wiredModule);
729
+ }
730
+ }
731
+ };
732
+ walk(node_path.join(contextPath, 'wiring'));
733
+ return result.sort((a, b)=>a.typeName.localeCompare(b.typeName));
734
+ };
735
+ const isCommandOrQuery = (module)=>'commands' === module.kind || 'queries' === module.kind;
736
+ const isExecution = (module)=>isCommandOrQuery(module) && 'execution' === node_path.basename(node_path.dirname(module.typeFile));
737
+ const commandOrQueryRule = (candidate, consumer)=>isExecution(consumer) ? !isCommandOrQuery(candidate) : 'application' !== candidate.layer || isExecution(candidate);
738
+ const kindRules = {
739
+ 'application-services': (candidate)=>'application' !== candidate.layer || 'application-ports' === candidate.kind,
740
+ 'use-cases': (candidate)=>'use-cases' !== candidate.kind,
741
+ repositories: (candidate)=>'repositories' !== candidate.kind,
742
+ commands: commandOrQueryRule,
743
+ queries: commandOrQueryRule
744
+ };
745
+ const wiring_implementationType = (consumer, implementation)=>consumer.branched ? node_path.basename(node_path.dirname(implementation.file)) : void 0;
746
+ const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && `-${node_path.basename(candidate.typeFile, '.ts')}-`.includes(`-${implementation}-`);
747
+ const isSuggestedEndpointGenerator = (candidate)=>candidate.typeName.toLowerCase().includes('endpoint');
748
+ const canDependOn = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && (kindRules[consumer.kind]?.(candidate, consumer) ?? true);
749
+ const availableDependencies = (consumer, implementation, candidates)=>{
750
+ const wired = wiredDependencyNames(new File(consumer.wireFile).data, implementation.className);
751
+ return candidates.filter((candidate)=>candidate.wireFile !== consumer.wireFile && canDependOn(consumer, candidate) && !wired.includes(candidate.wireName));
752
+ };
753
+ const relativeImport = (fromFile, toFile)=>{
754
+ const relativePath = node_path.relative(node_path.dirname(fromFile), toFile).replace(/\.ts$/, '').split(node_path.sep).join('/');
755
+ return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
756
+ };
757
+ const codeOnly = (source)=>{
758
+ let result = '';
759
+ let index = 0;
760
+ const blank = (text)=>text.replace(/[^\n]/g, ' ');
761
+ while(index < source.length){
762
+ const pair = source.slice(index, index + 2);
763
+ const char = source[index];
764
+ let end = index + 1;
765
+ if ('//' === pair) {
766
+ const lineEnd = source.indexOf('\n', index);
767
+ end = -1 === lineEnd ? source.length : lineEnd;
768
+ result += blank(source.slice(index, end));
769
+ } else if ('/*' === pair) {
770
+ const commentEnd = source.indexOf('*/', index + 2);
771
+ end = -1 === commentEnd ? source.length : commentEnd + 2;
772
+ result += blank(source.slice(index, end));
773
+ } else if ('=>' === pair) {
774
+ end = index + 2;
775
+ result += ' ';
776
+ } else if ("'" === char || '"' === char || '`' === char) {
777
+ while(end < source.length && source[end] !== char)end += '\\' === source[end] ? 2 : 1;
778
+ end = Math.min(end + 1, source.length);
779
+ result += char + blank(source.slice(index + 1, end - 1));
780
+ result += end - 1 > index ? source[end - 1] : '';
781
+ } else result += char;
782
+ index = end;
783
+ }
784
+ return result;
785
+ };
786
+ const addImport = (source, importLine)=>{
787
+ if (source.split('\n').some((line)=>line.trim() === importLine)) return source;
788
+ const lastImport = [
789
+ ...codeOnly(source).matchAll(/^import\s(?:[^'"]*?from\s*)?['"][^'"]*['"]/gm)
790
+ ].at(-1);
791
+ if (!lastImport) return `${importLine}\n\n${source}`;
792
+ const importEnd = lastImport.index + lastImport[0].length;
793
+ const lineEnd = source.indexOf('\n', importEnd);
794
+ const insertAt = -1 === lineEnd ? source.length : lineEnd;
795
+ return `${source.slice(0, insertAt)}\n${importLine}${source.slice(insertAt)}`;
796
+ };
797
+ const brackets = {
798
+ '(': ')',
799
+ '[': ']',
800
+ '{': '}',
801
+ '<': '>'
802
+ };
803
+ const closingIndex = (source, openIndex)=>{
804
+ const code = codeOnly(source);
805
+ let depth = 0;
806
+ for(let index = openIndex; index < code.length; index++){
807
+ const char = code[index];
808
+ if (char === code[openIndex]) depth++;
809
+ else if (char === brackets[code[openIndex]]) {
810
+ depth--;
811
+ if (0 === depth) return index;
812
+ }
813
+ }
814
+ return -1;
815
+ };
816
+ const splitTopLevel = (content)=>{
817
+ const code = codeOnly(content);
818
+ const items = [];
819
+ let depth = 0;
820
+ let itemStart = 0;
821
+ for(let index = 0; index <= code.length; index++){
822
+ const char = code[index];
823
+ if (void 0 !== char && char in brackets) depth++;
824
+ else if (Object.values(brackets).includes(char)) depth--;
825
+ if (index === code.length || ',' === char && 0 === depth) {
826
+ const item = content.slice(itemStart, index);
827
+ const itemCode = code.slice(itemStart, index);
828
+ const first = itemCode.search(/\S/);
829
+ const last = itemCode.search(/\S\s*$/);
830
+ if (-1 !== first) items.push(item.slice(first, last + 1));
831
+ itemStart = index + 1;
832
+ }
833
+ }
834
+ return items;
835
+ };
836
+ const appendItems = (content, items)=>{
837
+ const code = codeOnly(content);
838
+ const lastCode = code.search(/\S\s*$/);
839
+ if (-1 === lastCode) return items.join(', ');
840
+ const trailingComma = ',' === code[lastCode];
841
+ if (!content.includes('\n')) {
842
+ const added = trailingComma ? ` ${items.join(', ')},` : `, ${items.join(', ')}`;
843
+ return content.slice(0, lastCode + 1) + added + content.slice(lastCode + 1);
844
+ }
845
+ const indent = content.match(/\n([ \t]*)\S/)?.[1] ?? '';
846
+ const withComma = trailingComma ? content : `${content.slice(0, lastCode + 1)},${content.slice(lastCode + 1)}`;
847
+ const lineEndIndex = withComma.indexOf('\n', lastCode + 1);
848
+ const lineEnd = -1 === lineEndIndex ? withComma.length : lineEndIndex;
849
+ const added = trailingComma ? items.map((x)=>`\n${indent}${x},`).join('') : items.map((x)=>`\n${indent}${x}`).join(',');
850
+ return withComma.slice(0, lineEnd) + added + withComma.slice(lineEnd);
851
+ };
852
+ const addConstructorParameters = (source, className, parameters)=>{
853
+ const classMatch = new RegExp(`class\\s+${className}\\b[^{]*\\{`).exec(codeOnly(source));
854
+ if (!classMatch) throw new Error(`Class ${className} not found`);
855
+ const bodyStart = classMatch.index + classMatch[0].length;
856
+ const bodyEnd = closingIndex(source, bodyStart - 1);
857
+ const body = source.slice(bodyStart, bodyEnd);
858
+ const constructorIndex = codeOnly(body).search(/\bconstructor\s*\(/);
859
+ const renderParameters = (allParameters, indent)=>1 === allParameters.length ? allParameters[0] : `\n${allParameters.map((x)=>`${indent} ${x}`).join(',\n')}\n${indent}`;
860
+ if (-1 === constructorIndex) {
861
+ const constructorBody = /\bextends\b/.test(classMatch[0]) ? '{\n super()\n }' : '{}';
862
+ const constructorLine = ` constructor(${renderParameters(parameters, ' ')}) ${constructorBody}`;
863
+ const newBody = body.trim() ? `\n${constructorLine}\n${body.replace(/^\s*\n/, '\n')}` : `\n${constructorLine}\n`;
864
+ return source.slice(0, bodyStart) + newBody + source.slice(bodyEnd);
865
+ }
866
+ const openIndex = bodyStart + body.indexOf('(', constructorIndex);
867
+ const closeIndex = closingIndex(source, openIndex);
868
+ const content = source.slice(openIndex + 1, closeIndex);
869
+ if (content.includes('\n')) return source.slice(0, openIndex + 1) + appendItems(content, parameters) + source.slice(closeIndex);
870
+ const lineStart = source.lastIndexOf('\n', openIndex) + 1;
871
+ const indent = source.slice(lineStart).match(/^\s*/)?.[0] ?? '';
872
+ return source.slice(0, openIndex + 1) + renderParameters([
873
+ ...splitTopLevel(content),
874
+ ...parameters
875
+ ], indent) + source.slice(closeIndex);
876
+ };
877
+ const wireListRange = (source, className)=>{
878
+ const match = new RegExp(`wireClass\\(\\s*${className}\\s*,\\s*\\[`).exec(codeOnly(source));
879
+ if (!match) throw new Error(`wireClass(${className}, [...]) not found`);
880
+ const openIndex = match.index + match[0].length - 1;
881
+ return {
882
+ openIndex,
883
+ closeIndex: closingIndex(source, openIndex)
884
+ };
885
+ };
886
+ const wiredDependencyNames = (source, className)=>{
887
+ const { openIndex, closeIndex } = wireListRange(source, className);
888
+ return splitTopLevel(source.slice(openIndex + 1, closeIndex));
889
+ };
890
+ const addWireDependencies = (source, className, wireNames)=>{
891
+ const { openIndex, closeIndex } = wireListRange(source, className);
892
+ return source.slice(0, openIndex + 1) + appendItems(source.slice(openIndex + 1, closeIndex), wireNames) + source.slice(closeIndex);
893
+ };
894
+ const parameterName = (typeName)=>typeName.substring(0, 1).toLowerCase() + typeName.substring(1);
895
+ const wireDependencies = (consumer, implementation, dependencies)=>{
896
+ const wireFile = new File(consumer.wireFile);
897
+ let wireSource = wireFile.data;
898
+ for (const dependency of dependencies)wireSource = addImport(wireSource, `import { ${dependency.wireName} } from '${relativeImport(consumer.wireFile, dependency.wireFile)}'`);
899
+ wireFile.update(addWireDependencies(wireSource, implementation.className, dependencies.map((x)=>x.wireName)));
900
+ const classFile = new File(implementation.file);
901
+ let classSource = classFile.data;
902
+ for (const dependency of dependencies)classSource = addImport(classSource, `import type { ${dependency.typeName} } from '${relativeImport(implementation.file, dependency.typeFile)}'`);
903
+ classFile.update(addConstructorParameters(classSource, implementation.className, dependencies.map((x)=>`private readonly ${parameterName(x.typeName)}: ${x.typeName}`)));
904
+ };
905
+ const kindTitles = {
906
+ repositories: 'Repositories',
907
+ 'domain-services': 'Domain services',
908
+ 'application-ports': 'Ports',
909
+ 'application-services': 'Application services',
910
+ queries: 'Queries',
911
+ commands: 'Commands',
912
+ 'use-cases': 'Use cases',
913
+ 'infrastructure-services': 'Infrastructure services',
914
+ 'presentation-services': 'Presentation services'
915
+ };
916
+ const groupedChoices = (items, suggested = [])=>{
917
+ const suggestedChoices = suggested.length ? [
918
+ new Separator('── Suggested'),
919
+ ...suggested.map((x)=>({
920
+ name: x.label,
921
+ value: x
922
+ }))
923
+ ] : [];
924
+ const kinds = [
925
+ ...new Set([
926
+ ...Object.keys(kindTitles),
927
+ ...items.map((x)=>x.module.kind)
928
+ ])
929
+ ];
930
+ return [
931
+ ...suggestedChoices,
932
+ ...kinds.flatMap((kind)=>{
933
+ const group = items.filter((x)=>x.module.kind === kind && !suggested.includes(x));
934
+ return group.length ? [
935
+ new Separator(`── ${kindTitles[kind] ?? kind}`),
936
+ ...group.map((x)=>({
937
+ name: x.label,
938
+ value: x
939
+ }))
940
+ ] : [];
941
+ })
942
+ ];
943
+ };
944
+ const groupedPageSize = 20;
945
+ const contextAndSharedModules = (boundedContextFolder)=>{
946
+ const sharedFolder = new Folder(new ProjectRoot().path).subitem([
947
+ ConfigFile.Instance.data.rootFolder,
948
+ 'shared'
949
+ ]);
950
+ const isShared = sharedFolder.path === boundedContextFolder.path;
951
+ return [
952
+ ...findWiredModules(boundedContextFolder.path).map((x)=>({
953
+ module: x,
954
+ label: x.typeName
955
+ })),
956
+ ...isShared ? [] : findWiredModules(sharedFolder.path).map((x)=>({
957
+ module: x,
958
+ label: `${x.typeName} (shared)`
959
+ }))
960
+ ];
961
+ };
962
+ const promptDependencies = async (boundedContextFolder, consumer, implementations = consumer.implementations)=>{
963
+ const options = contextAndSharedModules(boundedContextFolder);
964
+ let asked = false;
965
+ for (const implementation of implementations){
966
+ const available = availableDependencies(consumer, implementation, options.map((x)=>x.module));
967
+ const candidates = options.filter((x)=>available.includes(x.module));
968
+ if (!candidates.length) continue;
969
+ asked = true;
970
+ const type = wiring_implementationType(consumer, implementation);
971
+ const suggested = type ? candidates.filter((x)=>isSuggestedFor(x.module, type)) : [];
972
+ const dependencies = await prompts_checkbox({
973
+ message: consumer.branched ? `Dependencies for ${implementation.className}:` : 'Dependencies:',
974
+ choices: groupedChoices(candidates, suggested),
975
+ pageSize: groupedPageSize,
976
+ loop: false
977
+ });
978
+ if (dependencies.length) wireDependencies(consumer, implementation, dependencies.map((x)=>x.module));
979
+ }
980
+ return asked;
981
+ };
982
+ const wireNewModuleDependencies = async (boundedContextFolder, wireFile)=>{
983
+ const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
984
+ if (consumer) await promptDependencies(boundedContextFolder, consumer);
985
+ };
986
+ const wireDependency = async (boundedContextFolder)=>{
987
+ const modules = findWiredModules(boundedContextFolder.path);
988
+ if (!modules.length) return void console.log('No wired modules here yet.');
989
+ const { module: consumer, implementation } = await prompts_select({
990
+ message: 'Module:',
991
+ choices: groupedChoices(modules.flatMap((x)=>x.implementations.map((implementation)=>{
992
+ const type = wiring_implementationType(x, implementation);
993
+ return {
994
+ module: x,
995
+ label: type ? `${x.typeName} (${type})` : x.typeName,
996
+ implementation
997
+ };
998
+ }))),
999
+ pageSize: groupedPageSize,
1000
+ loop: false
1001
+ });
1002
+ if (!await promptDependencies(boundedContextFolder, consumer, [
1003
+ implementation
1004
+ ])) console.log('No dependencies available for this module.');
1005
+ };
1006
+ const promptEndpointDependencies = async (boundedContextFolder)=>{
1007
+ const options = contextAndSharedModules(boundedContextFolder);
1008
+ const generators = options.filter((x)=>'presentation-services' === x.module.kind);
1009
+ const handlers = findWiredModules(boundedContextFolder.path).filter((x)=>[
1010
+ 'queries',
1011
+ 'commands',
1012
+ 'use-cases'
1013
+ ].includes(x.kind)).map((x)=>({
1014
+ module: x,
1015
+ label: x.typeName
1016
+ }));
1017
+ const endpointGenerator = generators.length ? (await prompts_select({
1018
+ message: 'Endpoint generator:',
1019
+ choices: groupedChoices(generators, generators.filter((x)=>isSuggestedEndpointGenerator(x.module))),
1020
+ pageSize: groupedPageSize,
1021
+ loop: false
1022
+ })).module : void 0;
1023
+ const handler = handlers.length ? (await prompts_select({
1024
+ message: 'Handler:',
1025
+ choices: groupedChoices(handlers),
1026
+ pageSize: groupedPageSize,
1027
+ loop: false
1028
+ })).module : void 0;
1029
+ return {
1030
+ endpointGenerator,
1031
+ handler
1032
+ };
1033
+ };
250
1034
  const scaffoldNewAggregateUseCase = async (boundedContextFolder)=>{
251
1035
  const aggregateName = await input({
252
1036
  message: 'Aggregate name:'
@@ -346,7 +1130,7 @@ describe('${aggregateNaming.withSpaces} repository', () => {
346
1130
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
347
1131
  const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
348
1132
  const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
349
- boundedContextFolder.subitem([
1133
+ const wireFile = boundedContextFolder.subitem([
350
1134
  'wiring',
351
1135
  'repositories'
352
1136
  ]).createFile(`wire-${aggregateNaming.fileName}-repository.ts`, `
@@ -362,6 +1146,7 @@ export const wire${aggregateNaming.ClassName}Repository = envBranchedWire({
362
1146
  production: wire${implementationNaming.ClassName}Implementation
363
1147
  })
364
1148
  `.trim());
1149
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
365
1150
  }
366
1151
  }
367
1152
  };
@@ -438,18 +1223,19 @@ describe('${naming.withSpaces}', () => {
438
1223
  })
439
1224
  `.trim());
440
1225
  }
441
- if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) wiringFolder.createFile(`wire-${naming.fileName}.ts`, `
1226
+ if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
1227
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}.ts`, `
442
1228
  import { wireClass } from '@domain-first/wire'
443
1229
  import { envBranchedWire } from '../../../${'shared' === boundedContextFolder.name ? '' : '../'}shared/wiring/env-branched-wire'
444
1230
  ${implementationTypes.map((x)=>({
445
- naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
446
- implementation: x
447
- })).map(({ naming: { ClassName, fileName }, implementation })=>`import { ${ClassName} } from '../../infrastructure/application-adapters/${implementation}/${fileName}'`).join('\n')}
1231
+ naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
1232
+ implementation: x
1233
+ })).map(({ naming: { ClassName, fileName }, implementation })=>`import { ${ClassName} } from '../../infrastructure/application-adapters/${implementation}/${fileName}'`).join('\n')}
448
1234
 
449
1235
  ${implementationTypes.map((x)=>({
450
- naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
451
- implementation: x
452
- })).map(({ naming: { ClassName }, implementation })=>`const wire${new UnknownFormatNaming(implementation).ClassName}Implementation = wireClass(${ClassName}, [])`).join('\n\n')}
1236
+ naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
1237
+ implementation: x
1238
+ })).map(({ naming: { ClassName }, implementation })=>`const wire${new UnknownFormatNaming(implementation).ClassName}Implementation = wireClass(${ClassName}, [])`).join('\n\n')}
453
1239
 
454
1240
  export const wire${naming.ClassName} = envBranchedWire({
455
1241
  test: wire${new UnknownFormatNaming(`${implementationTypes.at(-1)}-implementation`).ClassName},
@@ -458,6 +1244,8 @@ export const wire${naming.ClassName} = envBranchedWire({
458
1244
  })
459
1245
 
460
1246
  `.trim());
1247
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1248
+ }
461
1249
  };
462
1250
  const scaffoldNewApplicationService = async (boundedContextFolder)=>{
463
1251
  const name = await input({
@@ -496,7 +1284,8 @@ describe('${naming.withSpaces}', () => {
496
1284
  })
497
1285
  })
498
1286
  `.trim());
499
- if (withWiring) wiringFolder.createFile(`wire-${naming.fileName}-application-service.ts`, `
1287
+ if (withWiring) {
1288
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-application-service.ts`, `
500
1289
  import { wireClass } from '@domain-first/wire'
501
1290
  import { ${naming.ClassName}ApplicationService } from '../../application/services/${naming.fileName}-application-service'
502
1291
 
@@ -505,6 +1294,8 @@ export const wire${naming.ClassName}ApplicationService = wireClass(
505
1294
  []
506
1295
  )
507
1296
  `.trim());
1297
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1298
+ }
508
1299
  };
509
1300
  const scaffoldNewBoundedContextUseCase = async ()=>{
510
1301
  const name = await input({
@@ -645,7 +1436,7 @@ describe('${naming.withSpaces} command', () => {
645
1436
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
646
1437
  const implementationNaming = new UnknownFormatNaming(implementationType);
647
1438
  const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
648
- boundedContextFolder.subitem([
1439
+ const wireFile = boundedContextFolder.subitem([
649
1440
  'wiring',
650
1441
  'commands'
651
1442
  ]).createFile(`wire-${naming.fileName}-command.ts`, `
@@ -661,6 +1452,7 @@ export const wire${naming.ClassName}Command = envBranchedWire({
661
1452
  production: wire${implementationNaming.ClassName}Implementation
662
1453
  })
663
1454
  `.trim());
1455
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
664
1456
  }
665
1457
  return;
666
1458
  }
@@ -718,6 +1510,10 @@ test('can be ${withWiring ? 'wired' : 'created via constructor'}', () => {
718
1510
  })
719
1511
  })
720
1512
  `.trim());
1513
+ if (withWiring) await wireNewModuleDependencies(boundedContextFolder, boundedContextFolder.subitem([
1514
+ 'wiring',
1515
+ 'commands'
1516
+ ]).file(`wire-${naming.fileName}-command.ts`));
721
1517
  };
722
1518
  const noAggregate = 'No aggregate';
723
1519
  const scaffoldNewDomainObject = async (boundedContextFolder, kind)=>{
@@ -806,10 +1602,11 @@ describe('${naming.withSpaces}', () => {
806
1602
  })
807
1603
  })
808
1604
  `.trim());
809
- if (withWiring) boundedContextFolder.subitem([
810
- 'wiring',
811
- 'domain-services'
812
- ]).createFile(`wire-${naming.fileName}-domain-service.ts`, `
1605
+ if (withWiring) {
1606
+ const wireFile = boundedContextFolder.subitem([
1607
+ 'wiring',
1608
+ 'domain-services'
1609
+ ]).createFile(`wire-${naming.fileName}-domain-service.ts`, `
813
1610
  import { wireClass } from '@domain-first/wire'
814
1611
  import { ${naming.ClassName}DomainService } from '../../domain/services/${naming.fileName}-domain-service'
815
1612
 
@@ -818,6 +1615,8 @@ export const wire${naming.ClassName}DomainService = wireClass(
818
1615
  []
819
1616
  )
820
1617
  `.trim());
1618
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1619
+ }
821
1620
  };
822
1621
  const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
823
1622
  const currentErrorFolder = boundedContextFolder.subitem([
@@ -912,33 +1711,40 @@ export const restHandlers = restWires.map(x => x().handle)
912
1711
  'put'
913
1712
  ]
914
1713
  });
915
- const path = (await input({
1714
+ const routeSegments = (await input({
916
1715
  message: 'Relative path (split by "/"):'
917
1716
  })).split('/').filter((x)=>!!x);
918
1717
  const controllerFolder = restPresentationFolder.subitem([
919
1718
  controller
920
1719
  ]);
921
- const endpointFolder = controllerFolder.subitem(path);
922
- const nameBase = `${controller}-${path.length ? `${path.join('-')}-` : ''}${method}-endpoint`;
1720
+ const endpointFolder = controllerFolder.subitem(routeSegments);
1721
+ const nameBase = `${controller}-${routeSegments.length ? `${routeSegments.join('-')}-` : ''}${method}-endpoint`;
923
1722
  const endpointNaming = new UnknownFormatNaming(nameBase);
1723
+ const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
1724
+ const { endpointGenerator, handler } = withWiring ? await promptEndpointDependencies(boundedContextFolder) : {
1725
+ endpointGenerator: void 0,
1726
+ handler: void 0
1727
+ };
1728
+ const endpointFile = node_path.join(endpointFolder.path, `${method.toUpperCase()}.ts`);
924
1729
  endpointFolder.createFile(`${method.toUpperCase()}.ts`, `
925
- import { EndpointGenerator } from '@domain-first/handlers-rest'
1730
+ ${endpointGenerator ? `import type { ${endpointGenerator.typeName} } from '${relativeImport(endpointFile, endpointGenerator.typeFile)}'` : "import { EndpointGenerator } from '@domain-first/handlers-rest'"}${handler ? `
1731
+ import type { ${handler.typeName} } from '${relativeImport(endpointFile, handler.typeFile)}'` : ''}
926
1732
 
927
1733
  export class ${endpointNaming.ClassName} {
928
1734
  constructor(
929
- private readonly endpointGenerator: EndpointGenerator,
930
- private readonly handler: never
1735
+ private readonly endpointGenerator: ${endpointGenerator?.typeName ?? 'EndpointGenerator'},
1736
+ private readonly handler: ${handler?.typeName ?? 'never'}
931
1737
  ) {}
932
1738
 
933
1739
  get handle() {
934
1740
  return this.endpointGenerator(this.handler.handle, {
935
- route: { method: '${method}', path: ['${boundedContextFolder.name}', '${controller}'${path.length ? `, ${path.map((x)=>`'${x}'`).join(', ')}` : ''}] },
1741
+ route: { method: '${method}', path: ['${boundedContextFolder.name}', '${controller}'${routeSegments.length ? `, ${routeSegments.map((x)=>`'${x}'`).join(', ')}` : ''}] },
936
1742
  tags: ['${boundedContextFolder.name}: ${controller}'],
937
1743
  })
938
1744
  }
939
1745
  }
940
1746
  `.trim());
941
- if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
1747
+ if (withWiring) {
942
1748
  const wiringFolder = boundedContextFolder.subitem([
943
1749
  'wiring',
944
1750
  'presentation',
@@ -947,13 +1753,19 @@ export class ${endpointNaming.ClassName} {
947
1753
  ]);
948
1754
  const wireNameBase = `wire-${nameBase}`;
949
1755
  const wireNaming = new UnknownFormatNaming(wireNameBase);
1756
+ const wireFile = node_path.join(wiringFolder.path, `${wireNaming.fileName}.ts`);
1757
+ const dependencies = endpointGenerator ? [
1758
+ endpointGenerator,
1759
+ handler
1760
+ ].filter((x)=>!!x) : [];
950
1761
  wiringFolder.createFile(`${wireNaming.fileName}.ts`, `
951
1762
  import { wireClass } from '@domain-first/wire'
952
- import { ${endpointNaming.ClassName} } from '../../../../presentation/rest/${controller}/${path.length ? `${path.join('/')}/` : ''}${method.toUpperCase()}'
1763
+ import { ${endpointNaming.ClassName} } from '${relativeImport(wireFile, endpointFile)}'
1764
+ ${dependencies.map((x)=>`import { ${x.wireName} } from '${relativeImport(wireFile, x.wireFile)}'`).join('\n')}
953
1765
 
954
1766
  export const wire${endpointNaming.ClassName} = wireClass(
955
1767
  ${endpointNaming.ClassName},
956
- []
1768
+ [${dependencies.map((x)=>x.wireName).join(', ')}]
957
1769
  )
958
1770
  `.trim());
959
1771
  wiringFolder.file('index.ts').addLine(`export * from './${wireNaming.fileName}'`);
@@ -996,7 +1808,8 @@ describe('${naming.withSpaces}', () => {
996
1808
  })
997
1809
  })
998
1810
  `.trim());
999
- if (withWiring) wiringFolder.createFile(`wire-${naming.fileName}-infrastructure-service.ts`, `
1811
+ if (withWiring) {
1812
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-infrastructure-service.ts`, `
1000
1813
  import { wireClass } from '@domain-first/wire'
1001
1814
  import { ${naming.ClassName}InfrastructureService } from '../../infrastructure/services/${naming.fileName}-infrastructure-service'
1002
1815
 
@@ -1005,6 +1818,8 @@ export const wire${naming.ClassName}InfrastructureService = wireClass(
1005
1818
  []
1006
1819
  )
1007
1820
  `.trim());
1821
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1822
+ }
1008
1823
  };
1009
1824
  const scaffoldNewPresentationService = async (boundedContextFolder)=>{
1010
1825
  const name = await input({
@@ -1043,7 +1858,8 @@ describe('${naming.withSpaces}', () => {
1043
1858
  })
1044
1859
  })
1045
1860
  `.trim());
1046
- if (withWiring) wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
1861
+ if (withWiring) {
1862
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
1047
1863
  import { wireClass } from '@domain-first/wire'
1048
1864
  import { ${naming.ClassName}PresentationService } from '../../presentation/services/${naming.fileName}-presentation-service'
1049
1865
 
@@ -1052,6 +1868,8 @@ export const wire${naming.ClassName}PresentationService = wireClass(
1052
1868
  []
1053
1869
  )
1054
1870
  `.trim());
1871
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1872
+ }
1055
1873
  };
1056
1874
  const scaffoldNewQuery = async (boundedContextFolder)=>{
1057
1875
  const queriesFolder = boundedContextFolder.subitem([
@@ -1170,7 +1988,7 @@ describe('${naming.withSpaces} query', () => {
1170
1988
  if (ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire')) {
1171
1989
  const implementationNaming = new UnknownFormatNaming(implementationType);
1172
1990
  const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
1173
- boundedContextFolder.subitem([
1991
+ const wireFile = boundedContextFolder.subitem([
1174
1992
  'wiring',
1175
1993
  'queries'
1176
1994
  ]).createFile(`wire-${naming.fileName}-query.ts`, `
@@ -1186,6 +2004,7 @@ export const wire${naming.ClassName}Query = envBranchedWire({
1186
2004
  production: wire${implementationNaming.ClassName}Implementation
1187
2005
  })
1188
2006
  `.trim());
2007
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
1189
2008
  }
1190
2009
  return;
1191
2010
  }
@@ -1243,6 +2062,10 @@ test('can be ${withWiring ? 'wired' : 'created via constructor'}', () => {
1243
2062
  })
1244
2063
  })
1245
2064
  `.trim());
2065
+ if (withWiring) await wireNewModuleDependencies(boundedContextFolder, boundedContextFolder.subitem([
2066
+ 'wiring',
2067
+ 'queries'
2068
+ ]).file(`wire-${naming.fileName}-query.ts`));
1246
2069
  };
1247
2070
  const scaffoldNewUseCase = async (boundedContextFolder)=>{
1248
2071
  const useCasesFolder = boundedContextFolder.subitem([
@@ -1294,10 +2117,11 @@ describe('${naming.withSpaces} use case', () => {
1294
2117
  })
1295
2118
  })
1296
2119
  `.trim());
1297
- if (withWiring) boundedContextFolder.subitem([
1298
- 'wiring',
1299
- 'use-cases'
1300
- ]).createFile(`wire-${naming.fileName}-use-case.ts`, `
2120
+ if (withWiring) {
2121
+ const wireFile = boundedContextFolder.subitem([
2122
+ 'wiring',
2123
+ 'use-cases'
2124
+ ]).createFile(`wire-${naming.fileName}-use-case.ts`, `
1301
2125
  import { wireClass } from '@domain-first/wire'
1302
2126
  import { ${naming.ClassName}UseCase } from '../../application/use-cases/${naming.fileName}-use-case'
1303
2127
 
@@ -1307,6 +2131,8 @@ export const wire${naming.ClassName}UseCase = wireClass(
1307
2131
  )
1308
2132
 
1309
2133
  `.trim());
2134
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
2135
+ }
1310
2136
  };
1311
2137
  const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
1312
2138
  class NestedName {
@@ -1557,7 +2383,11 @@ const main = async ()=>{
1557
2383
  name: 'Shared Layer',
1558
2384
  action: 'Scaffold in bounded context'
1559
2385
  },
1560
- scaffoldNewBoundedContext
2386
+ scaffoldNewBoundedContext,
2387
+ {
2388
+ name: 'Add integration',
2389
+ action: 'Add integration'
2390
+ }
1561
2391
  ].filter((x)=>!!x);
1562
2392
  const result = await prompts_select({
1563
2393
  message: '@domain-first/project-structure',
@@ -1565,6 +2395,8 @@ const main = async ()=>{
1565
2395
  });
1566
2396
  const { action, name } = options.find((x)=>x.name === result);
1567
2397
  switch(action){
2398
+ case 'Add integration':
2399
+ return void await addIntegration();
1568
2400
  case 'Scaffold React module':
1569
2401
  {
1570
2402
  const reactFolder = new Folder(rootPath).subitem([
@@ -1613,9 +2445,11 @@ const main = async ()=>{
1613
2445
  'Domain',
1614
2446
  'Application',
1615
2447
  'Infrastructure',
1616
- 'Presentation'
1617
- ]
2448
+ 'Presentation',
2449
+ ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? 'Wire dependency' : void 0
2450
+ ].filter((x)=>!!x)
1618
2451
  });
2452
+ if ('Wire dependency' === layer) return void await wireDependency(boundedContextFolder);
1619
2453
  if ('Domain' === layer) {
1620
2454
  const operation = await prompts_select({
1621
2455
  message: 'Domain layer operation:',
@@ -1709,17 +2543,6 @@ const main = async ()=>{
1709
2543
  };
1710
2544
  const run = async ()=>{
1711
2545
  await main();
1712
- const overwrittenFiles = filesToOverwrite();
1713
- if (overwrittenFiles.length) {
1714
- const root = new ProjectRoot().path;
1715
- console.log('These files already exist and will be overwritten:');
1716
- for (const filePath of overwrittenFiles)console.log(` ${node_path.relative(root, filePath)}`);
1717
- const overwrite = await prompts_confirm({
1718
- message: 'Overwrite them?',
1719
- default: false
1720
- });
1721
- if (!overwrite) return void console.log('Cancelled: nothing was written.');
1722
- }
1723
- writePendingChanges();
2546
+ await savePendingChanges();
1724
2547
  };
1725
2548
  run();