@domain-first/project-structure 7.2.0 → 8.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.
Files changed (66) hide show
  1. package/README.md +125 -26
  2. package/dist/201.js +87 -338
  3. package/dist/287.js +1235 -575
  4. package/dist/561.js +519 -0
  5. package/dist/711.js +22 -0
  6. package/dist/870.js +438 -0
  7. package/dist/agent-cli.d.ts +379 -0
  8. package/dist/agent-cli.spec.d.ts +1 -0
  9. package/dist/agent-identifiers.d.ts +4 -0
  10. package/dist/agent-requests.d.ts +490 -0
  11. package/dist/config-file.d.ts +231 -26
  12. package/dist/config-file.spec.d.ts +1 -0
  13. package/dist/context-dependencies.d.ts +16 -0
  14. package/dist/dependency-rules.d.ts +17 -17
  15. package/dist/file-system.d.ts +10 -1
  16. package/dist/implementation-choices.d.ts +8 -0
  17. package/dist/implementation-choices.spec.d.ts +1 -0
  18. package/dist/implementation-options-schema.d.ts +14 -0
  19. package/dist/index.cjs +3645 -584
  20. package/dist/index.js +20 -7
  21. package/dist/init.cjs +717 -122
  22. package/dist/init.js +24 -12
  23. package/dist/integration.cjs +3783 -186
  24. package/dist/integration.js +29 -17
  25. package/dist/integrations/rest-endpoint-generator.d.ts +4 -2
  26. package/dist/integrations/storybook.d.ts +1 -0
  27. package/dist/interaction.d.ts +41 -0
  28. package/dist/lint.cjs +165 -41
  29. package/dist/lint.js +22 -7
  30. package/dist/module-move.d.ts +6 -2
  31. package/dist/next-app.d.ts +7 -0
  32. package/dist/react-module-move.d.ts +17 -2
  33. package/dist/react.cjs +5181 -421
  34. package/dist/react.js +72 -60
  35. package/dist/system-implementations.d.ts +6 -0
  36. package/dist/upgrade-steps.d.ts +81 -0
  37. package/dist/upgrade-steps.spec.d.ts +1 -0
  38. package/dist/upgrade.cjs +593 -0
  39. package/dist/upgrade.d.ts +2 -0
  40. package/dist/upgrade.js +235 -0
  41. package/dist/use-cases/add-integration.d.ts +16 -1
  42. package/dist/use-cases/cross-context-dependencies.spec.d.ts +1 -0
  43. package/dist/use-cases/initialize.d.ts +4 -4
  44. package/dist/use-cases/initialize.spec.d.ts +1 -0
  45. package/dist/use-cases/prompt-implementation-type.d.ts +20 -0
  46. package/dist/use-cases/scaffold-react-page.d.ts +3 -1
  47. package/dist/wire-branches.d.ts +26 -0
  48. package/dist/wiring.d.ts +3 -2
  49. package/package.json +3 -2
  50. package/skills/df-ps-implement/SKILL.md +9 -8
  51. package/skills/df-ps-plan-feature/SKILL.md +8 -7
  52. package/skills/df-ps-react/SKILL.md +14 -8
  53. package/skills/df-ps-react/references/generators.md +6 -2
  54. package/skills/df-ps-scaffold/SKILL.md +28 -17
  55. package/skills/df-ps-scaffold/references/agent-mode.md +72 -0
  56. package/skills/df-ps-scaffold/references/agent-operations.md +155 -0
  57. package/skills/df-ps-scaffold/references/choosing-components.md +13 -13
  58. package/skills/df-ps-scaffold/references/generators.md +20 -3
  59. package/skills/df-ps-scaffold/references/units/aggregate.md +4 -3
  60. package/skills/df-ps-scaffold/references/units/bounded-context.md +1 -1
  61. package/skills/df-ps-scaffold/references/units/command-query.md +12 -12
  62. package/skills/df-ps-scaffold/references/units/implementation.md +2 -2
  63. package/skills/df-ps-scaffold/references/units/move-or-rename.md +1 -1
  64. package/skills/df-ps-scaffold/references/units/port.md +7 -4
  65. package/skills/df-ps-scaffold/references/units/use-case.md +1 -1
  66. package/skills/df-ps-scaffold/scripts/drive.mjs +9 -1
@@ -27,10 +27,68 @@ var __webpack_require__ = {};
27
27
  })();
28
28
  var __webpack_exports__ = {};
29
29
  const external_node_util_namespaceObject = require("node:util");
30
+ const external_node_fs_namespaceObject = require("node:fs");
31
+ var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
30
32
  const external_node_path_namespaceObject = require("node:path");
31
33
  var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
32
34
  const external_zod_namespaceObject = require("zod");
33
35
  var external_zod_default = /*#__PURE__*/ __webpack_require__.n(external_zod_namespaceObject);
36
+ const crossContextImplementation = 'cross-context';
37
+ const hasNeighboringBoundedContext = (ownerPath)=>{
38
+ const contextsPath = external_node_path_default().dirname(ownerPath);
39
+ return 'bounded-contexts' === external_node_path_default().basename(contextsPath) && external_node_fs_default().existsSync(contextsPath) && external_node_fs_default().readdirSync(contextsPath, {
40
+ withFileTypes: true
41
+ }).some((entry)=>entry.isDirectory() && entry.name !== external_node_path_default().basename(ownerPath));
42
+ };
43
+ const boundedContextLocation = (file)=>{
44
+ const parts = external_node_path_default().resolve(file).split(external_node_path_default().sep);
45
+ const index = parts.lastIndexOf('bounded-contexts');
46
+ if (-1 === index || parts.length < index + 3) return;
47
+ return {
48
+ root: parts.slice(0, index).join(external_node_path_default().sep),
49
+ name: parts[index + 1],
50
+ segments: parts.slice(index + 2)
51
+ };
52
+ };
53
+ const isCrossContextImplementation = (file)=>{
54
+ const location = boundedContextLocation(file);
55
+ const [layer, kind, label] = location?.segments ?? [];
56
+ return 'infrastructure' === layer && 'application-adapters' === kind && label === crossContextImplementation;
57
+ };
58
+ const crossContextImportAllowed = (from, to)=>{
59
+ const source = boundedContextLocation(from);
60
+ const target = boundedContextLocation(to);
61
+ if (!source || !target || source.name === target.name) return;
62
+ if (source.root !== target.root) return false;
63
+ const [layer, kind] = source.segments;
64
+ const [targetLayer, targetKind] = target.segments;
65
+ if ('wiring' === targetLayer && !external_node_path_default().basename(to).startsWith('wire-')) return false;
66
+ if (/\.(spec|test)\.[^.]+$/.test(to)) return false;
67
+ const suffix = {
68
+ queries: '-query',
69
+ commands: '-command',
70
+ 'use-cases': '-use-case'
71
+ }[targetKind];
72
+ if (!suffix || !new RegExp(`${suffix}(\\.(?:c|m)?[jt]sx?)?$`).test(to)) return false;
73
+ return [
74
+ 'queries',
75
+ 'commands',
76
+ 'use-cases'
77
+ ].includes(targetKind) && (isCrossContextImplementation(from) && 'application' === targetLayer || 'wiring' === layer && 'application-ports' === kind && 'wiring' === targetLayer);
78
+ };
79
+ const moduleId = (module)=>`${boundedContextLocation(module.typeFile)?.name ?? 'shared-kernel'}:${module.typeName}`;
80
+ const unitId = (unit)=>`${unit.kind}:${unit.aggregate ? `${unit.aggregate}/` : ''}${unit.name}`;
81
+ const implementationKinds = [
82
+ 'repositories',
83
+ 'commands',
84
+ 'queries',
85
+ 'ports'
86
+ ];
87
+ const implementationLabelSchema = external_zod_default().string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/);
88
+ const implementationOptionsSchema = external_zod_default().partialRecord(external_zod_default()["enum"](implementationKinds), external_zod_default().object({
89
+ primary: external_zod_default().array(implementationLabelSchema).default([]),
90
+ test: external_zod_default().array(implementationLabelSchema).default([])
91
+ }).strict());
34
92
  const moduleKinds = [
35
93
  'repositories',
36
94
  'domain-services',
@@ -55,7 +113,7 @@ const infrastructure = [
55
113
  'application-ports',
56
114
  'infrastructure-services'
57
115
  ];
58
- const defaultDependencies = {
116
+ const dependency_rules_defaultDependencies = {
59
117
  'domain-services': [
60
118
  'domain-services'
61
119
  ],
@@ -99,7 +157,7 @@ const dependencyRulesSchema = external_zod_default().partialRecord(kindSchema, e
99
157
  remove: external_zod_default().array(kindSchema).optional()
100
158
  })
101
159
  ]));
102
- const dependency_rules_resolveDependencyRules = (config = {})=>{
160
+ const resolveDependencyRules = (config = {})=>{
103
161
  const entries = moduleKinds.map((kind)=>{
104
162
  const override = config[kind];
105
163
  if (Array.isArray(override)) return [
@@ -107,7 +165,7 @@ const dependency_rules_resolveDependencyRules = (config = {})=>{
107
165
  new Set(override)
108
166
  ];
109
167
  const kinds = new Set([
110
- ...defaultDependencies[kind],
168
+ ...dependency_rules_defaultDependencies[kind],
111
169
  ...override?.add ?? []
112
170
  ]);
113
171
  for (const removed of override?.remove ?? [])kinds.delete(removed);
@@ -118,17 +176,41 @@ const dependency_rules_resolveDependencyRules = (config = {})=>{
118
176
  });
119
177
  return Object.fromEntries(entries);
120
178
  };
121
- dependency_rules_resolveDependencyRules();
122
- const external_node_fs_namespaceObject = require("node:fs");
123
- var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
179
+ const defaultDependencyRules = resolveDependencyRules();
180
+ const isModuleKind = (value)=>moduleKinds.includes(value);
181
+ const wiredModuleKind = (wiringKind)=>isModuleKind(wiringKind) ? wiringKind : void 0;
124
182
  const pendingFiles = new Map();
125
183
  const pendingFolders = new Set();
126
184
  const pendingMoves = new Map();
127
185
  const pendingDeletions = new Map();
128
- const filesToOverwrite = ()=>[
186
+ const filesToOverwrite = ({ changedOnly = false } = {})=>[
129
187
  ...pendingFiles
130
- ].filter(([filePath, { replacesFile }])=>replacesFile && external_node_fs_default().existsSync(filePath)).map(([filePath])=>filePath);
131
- const withoutOverwrites = (generate)=>{
188
+ ].filter(([filePath, { replacesFile, content }])=>replacesFile && external_node_fs_default().existsSync(filePath) && (!changedOnly || external_node_fs_default().readFileSync(filePath, 'utf8') !== content)).map(([filePath])=>filePath);
189
+ const pendingChanges = ()=>({
190
+ created: [
191
+ ...new Set([
192
+ ...[
193
+ ...pendingFiles.keys()
194
+ ].filter((file)=>!external_node_fs_default().existsSync(file)),
195
+ ...pendingMoves.keys()
196
+ ])
197
+ ].sort(),
198
+ updated: [
199
+ ...pendingFiles
200
+ ].filter(([file, change])=>external_node_fs_default().existsSync(file) && external_node_fs_default().readFileSync(file, 'utf8') !== change.content).map(([file])=>file).sort(),
201
+ deleted: [
202
+ ...new Set([
203
+ ...pendingDeletions.keys(),
204
+ ...[
205
+ ...pendingMoves.values()
206
+ ].map((move)=>move.sourcePath)
207
+ ])
208
+ ].sort(),
209
+ directories: [
210
+ ...pendingFolders
211
+ ].filter((folder)=>!external_node_fs_default().existsSync(folder)).sort()
212
+ });
213
+ const file_system_withoutOverwrites = (generate)=>{
132
214
  const before = new Map(pendingFiles);
133
215
  const result = generate();
134
216
  for (const [filePath, change] of pendingFiles){
@@ -139,7 +221,7 @@ const withoutOverwrites = (generate)=>{
139
221
  }
140
222
  return result;
141
223
  };
142
- const file_system_discardPendingChanges = ()=>{
224
+ const discardPendingChanges = ()=>{
143
225
  pendingFolders.clear();
144
226
  pendingFiles.clear();
145
227
  pendingMoves.clear();
@@ -173,7 +255,7 @@ const writePendingChanges = ()=>{
173
255
  });
174
256
  for (const [filePath, stopAt] of pendingDeletions)removeEmptyFolders(external_node_path_default().dirname(filePath), stopAt);
175
257
  for (const { sourcePath, stopAt } of pendingMoves.values())removeEmptyFolders(external_node_path_default().dirname(sourcePath), stopAt);
176
- file_system_discardPendingChanges();
258
+ discardPendingChanges();
177
259
  };
178
260
  class FileSystemItem {
179
261
  path;
@@ -289,53 +371,530 @@ const lintChecks = [
289
371
  'react',
290
372
  'clock'
291
373
  ];
292
- const configFileName = 'domain-first.project-structure.config.json';
293
- const configSchema = external_zod_default().object({
294
- rootFolder: external_zod_default().string(),
295
- domainFirstPackages: external_zod_default().array(external_zod_default()["enum"]([
296
- '@domain-first/types',
297
- '@domain-first/errors',
298
- '@domain-first/handlers',
299
- '@domain-first/wire',
300
- '@domain-first/handlers-rest'
301
- ])),
302
- defaultPersistenceLayerImplementation: external_zod_default().string(),
374
+ const config_file_configFileName = 'domain-first.project-structure.config.json';
375
+ const projectConfigSchema = external_zod_default().object({
376
+ rootFolder: external_zod_default().string().min(1)
377
+ }).passthrough();
378
+ const config_file_domainFirstPackages = [
379
+ '@domain-first/types',
380
+ '@domain-first/errors',
381
+ '@domain-first/handlers',
382
+ '@domain-first/wire',
383
+ '@domain-first/handlers-rest'
384
+ ];
385
+ const rulesSchema = external_zod_default().object({
386
+ dependencies: dependencyRulesSchema.optional(),
387
+ lint: external_zod_default().partialRecord(external_zod_default()["enum"](lintChecks), external_zod_default().boolean()).optional()
388
+ });
389
+ const config_file_branchNameSchema = external_zod_default().string().regex(/^[a-z][a-z0-9]*$/, 'Use lowercase letters and digits, e.g. staging.');
390
+ const envBranchesSchema = external_zod_default().object({
391
+ names: external_zod_default().array(config_file_branchNameSchema).min(1),
392
+ test: config_file_branchNameSchema.optional()
393
+ }).refine(({ names })=>new Set(names).size === names.length, {
394
+ message: 'Branch names must be unique.'
395
+ }).refine(({ names, test })=>void 0 === test || names.includes(test), {
396
+ message: 'The test branch must be one of the branches.'
397
+ }).refine(({ names, test })=>void 0 === test || names.length > 1, {
398
+ message: 'The primary implementation needs a branch besides the test one.'
399
+ });
400
+ const backendConfigSchema = external_zod_default().object({
401
+ domainFirstPackages: external_zod_default().array(external_zod_default()["enum"](config_file_domainFirstPackages)),
402
+ envBranches: envBranchesSchema.optional(),
303
403
  withInMemoryDb: external_zod_default().boolean().optional(),
304
- useReact: external_zod_default().boolean(),
305
- storybookFramework: external_zod_default().string().optional(),
306
404
  testingLibrary: external_zod_default().string().optional(),
307
- rules: external_zod_default().object({
308
- dependencies: dependencyRulesSchema.optional(),
309
- lint: external_zod_default().partialRecord(external_zod_default()["enum"](lintChecks), external_zod_default().boolean()).optional()
310
- }).optional()
311
- });
405
+ implementations: implementationOptionsSchema.optional(),
406
+ rules: rulesSchema.optional()
407
+ }).passthrough();
408
+ const reactConfigSchema = external_zod_default().object({
409
+ framework: external_zod_default()["enum"]([
410
+ 'react',
411
+ 'next'
412
+ ]).optional(),
413
+ storybookFramework: external_zod_default().string().optional()
414
+ }).passthrough();
415
+ const frontendConfigSchema = external_zod_default().object({
416
+ react: reactConfigSchema.optional()
417
+ }).passthrough();
418
+ const configSchema = external_zod_default().object({
419
+ project: projectConfigSchema,
420
+ backend: backendConfigSchema.optional(),
421
+ frontend: frontendConfigSchema.optional()
422
+ }).passthrough();
423
+ const isOutdatedConfig = (value)=>'object' == typeof value && null !== value && !Array.isArray(value) && !('project' in value);
424
+ const outdatedConfigMessage = `${config_file_configFileName} uses the format of an earlier major version: run npx df-upgrade.`;
425
+ class ConfigOutdatedError extends Error {
426
+ constructor(){
427
+ super(outdatedConfigMessage);
428
+ }
429
+ }
312
430
  class config_file_ConfigFile {
313
431
  data;
314
432
  constructor(){
315
- const filePath = config_file_ConfigFile.path;
316
- const file = new file_system_File(filePath);
317
- const configObject = JSON.parse(file.data);
318
- this.data = configSchema.parse(configObject);
433
+ const raw = JSON.parse(new file_system_File(config_file_ConfigFile.path).data);
434
+ if (isOutdatedConfig(raw)) throw new ConfigOutdatedError();
435
+ this.data = configSchema.parse(raw);
319
436
  }
320
437
  static get Instance() {
321
438
  return new config_file_ConfigFile();
322
439
  }
440
+ static get backend() {
441
+ const backend = config_file_ConfigFile.Instance.data.backend;
442
+ if (!backend) throw new Error('Backend is not configured: run df-init --section backend.');
443
+ return backend;
444
+ }
323
445
  static get path() {
324
- const { path: root } = new project_root_ProjectRoot();
325
- return external_node_path_default().resolve(root, configFileName);
446
+ return external_node_path_default().resolve(new project_root_ProjectRoot().path, config_file_configFileName);
326
447
  }
327
448
  static get exists() {
328
449
  return new file_system_File(config_file_ConfigFile.path).exists;
329
450
  }
451
+ static get outdated() {
452
+ if (!config_file_ConfigFile.exists) return false;
453
+ try {
454
+ return isOutdatedConfig(JSON.parse(new file_system_File(config_file_ConfigFile.path).data));
455
+ } catch {
456
+ return false;
457
+ }
458
+ }
330
459
  static write = (config)=>{
331
- new file_system_File(config_file_ConfigFile.path).data = JSON.stringify(config, null, '\t');
460
+ config_file_ConfigFile.stage(configSchema.parse(config));
461
+ };
462
+ static update = (sections)=>{
463
+ config_file_ConfigFile.stage(configSchema.parse({
464
+ ...config_file_ConfigFile.Instance.data,
465
+ ...sections
466
+ }));
332
467
  };
468
+ static stage(config) {
469
+ new file_system_File(config_file_ConfigFile.path).update(`${JSON.stringify(config, null, 4)}\n`);
470
+ }
333
471
  }
334
- const prompts_namespaceObject = require("@inquirer/prompts");
335
- const wiring_relativeImport = (fromFile, toFile)=>{
472
+ const configuredDependencyRules = ()=>resolveDependencyRules(config_file_ConfigFile.exists ? config_file_ConfigFile.Instance.data.backend?.rules?.dependencies : void 0);
473
+ class UnknownFormatNaming {
474
+ rawSource;
475
+ camelCase;
476
+ PascalCase;
477
+ constructor(rawSource){
478
+ this.rawSource = rawSource;
479
+ const source = rawSource.trim();
480
+ if (!source.includes('-')) {
481
+ this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
482
+ this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
483
+ }
484
+ const words = source.split('-').filter((word)=>!!word);
485
+ this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
486
+ this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
487
+ }
488
+ get fileName() {
489
+ return this.rawSource;
490
+ }
491
+ get variableName() {
492
+ return this.camelCase;
493
+ }
494
+ get ClassName() {
495
+ return this.PascalCase;
496
+ }
497
+ get withSpaces() {
498
+ return this.fileName.replaceAll('-', ' ');
499
+ }
500
+ }
501
+ const wiring_layers = [
502
+ 'domain',
503
+ 'application',
504
+ 'infrastructure',
505
+ 'presentation'
506
+ ];
507
+ const visibleLayers = {
508
+ domain: [
509
+ 'domain'
510
+ ],
511
+ application: [
512
+ 'domain',
513
+ 'application'
514
+ ],
515
+ infrastructure: [
516
+ 'domain',
517
+ 'application',
518
+ 'infrastructure'
519
+ ],
520
+ presentation: [
521
+ 'application',
522
+ 'presentation'
523
+ ]
524
+ };
525
+ const branchedTypeFiles = {
526
+ repositories: (fileBase)=>[
527
+ 'domain',
528
+ 'aggregates',
529
+ fileBase.replace(/-repository$/, ''),
530
+ `${fileBase}.ts`
531
+ ],
532
+ commands: (fileBase)=>[
533
+ 'application',
534
+ 'commands',
535
+ `${fileBase}.ts`
536
+ ],
537
+ queries: (fileBase)=>[
538
+ 'application',
539
+ 'queries',
540
+ `${fileBase}.ts`
541
+ ],
542
+ 'application-ports': (fileBase)=>[
543
+ 'application',
544
+ 'ports',
545
+ `${fileBase}.ts`
546
+ ]
547
+ };
548
+ const layerOf = (file, contextPath)=>{
549
+ const [firstSegment] = external_node_path_default().relative(contextPath, file).split(external_node_path_default().sep);
550
+ return wiring_layers.find((layer)=>layer === firstSegment);
551
+ };
552
+ const withoutScriptExtension = (file)=>file.replace(/\.(?:c|m)?[jt]s$/, '');
553
+ const namedImportFiles = (source, fromFile, resolve = (specifier, file)=>specifier.startsWith('.') ? external_node_path_default().resolve(external_node_path_default().dirname(file), specifier) : void 0)=>{
554
+ const result = new Map();
555
+ for (const [, names, importPath] of source.matchAll(/import\s*(?:type\s*)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g)){
556
+ const target = resolve(importPath, fromFile);
557
+ if (target) for (const name of names.split(',')){
558
+ const cleanName = name.replace(/^\s*type\s+/, '').trim().split(/\s+as\s+/).at(-1);
559
+ if (cleanName) result.set(cleanName, `${withoutScriptExtension(target)}.ts`);
560
+ }
561
+ }
562
+ return result;
563
+ };
564
+ const isEndpointWire = (wiringRelativePath)=>wiringRelativePath.startsWith([
565
+ 'presentation',
566
+ 'rest'
567
+ ].join(external_node_path_default().sep));
568
+ const wireClassDefinitions = (source)=>[
569
+ ...codeOnly(source).matchAll(/(?:export\s+)?const\s+(\w+)\s*=\s*(?:\w+\(\s*)*wireClass\(\s*(\w+)\s*,/g)
570
+ ].map(([, wireName, className])=>({
571
+ wireName,
572
+ className
573
+ }));
574
+ const wiredClassNames = (source, wireName, initializerStart, branched)=>{
575
+ const definitions = wireClassDefinitions(source);
576
+ if (!branched) return definitions.filter((x)=>x.wireName === wireName).map((x)=>x.className);
577
+ const openIndex = source.indexOf('(', initializerStart);
578
+ const branches = codeOnly(source).slice(openIndex, closingIndex(source, openIndex));
579
+ const referenced = new Set(branches.match(/\w+/g));
580
+ return definitions.filter((x)=>referenced.has(x.wireName)).map((x)=>x.className);
581
+ };
582
+ const readWiredModule = (wireFile, contextPath)=>{
583
+ const wiringRelativePath = external_node_path_default().relative(external_node_path_default().join(contextPath, 'wiring'), wireFile);
584
+ if (isEndpointWire(wiringRelativePath)) return;
585
+ const source = new file_system_File(wireFile).data;
586
+ const wireName = `wire${new UnknownFormatNaming(external_node_path_default().basename(wireFile, '.ts').replace(/^wire-/, '')).ClassName}`;
587
+ const exportMatch = new RegExp(`export\\s+const\\s+${wireName}\\s*=\\s*`).exec(source);
588
+ if (!exportMatch) return;
589
+ const branched = source.slice(exportMatch.index + exportMatch[0].length).startsWith('envBranchedWire(');
590
+ const imports = namedImportFiles(source, wireFile);
591
+ const implementations = wiredClassNames(source, wireName, exportMatch.index + exportMatch[0].length, branched).flatMap((className)=>{
592
+ const file = imports.get(className);
593
+ return file ? [
594
+ {
595
+ className,
596
+ file
597
+ }
598
+ ] : [];
599
+ });
600
+ if (!implementations.length) return;
601
+ const typeName = wireName.slice(4);
602
+ const [wiringFolder] = wiringRelativePath.split(external_node_path_default().sep);
603
+ const typeFileSegments = branchedTypeFiles[wiringFolder]?.(external_node_path_default().basename(wireFile, '.ts').replace(/^wire-/, ''));
604
+ const typeFile = branched ? typeFileSegments && external_node_path_default().join(contextPath, ...typeFileSegments) : implementations[0].file;
605
+ const layer = typeFile && layerOf(typeFile, contextPath);
606
+ const implementationsLayer = layerOf(implementations[0].file, contextPath);
607
+ if (!typeFile || !layer || !implementationsLayer) return;
608
+ return {
609
+ wireName,
610
+ typeName,
611
+ wireFile,
612
+ typeFile,
613
+ layer,
614
+ implementations,
615
+ branched,
616
+ implementationsLayer,
617
+ kind: wiringFolder
618
+ };
619
+ };
620
+ const findWiredModules = (contextPath)=>{
621
+ const result = [];
622
+ const walk = (folderPath)=>{
623
+ if (!external_node_fs_default().existsSync(folderPath)) return;
624
+ for (const entry of external_node_fs_default().readdirSync(folderPath, {
625
+ withFileTypes: true
626
+ })){
627
+ const entryPath = external_node_path_default().join(folderPath, entry.name);
628
+ if (entry.isDirectory()) walk(entryPath);
629
+ else if (/^wire-.*(?<!\.spec)\.ts$/.test(entry.name)) {
630
+ const wiredModule = readWiredModule(entryPath, contextPath);
631
+ if (wiredModule) result.push(wiredModule);
632
+ }
633
+ }
634
+ };
635
+ walk(external_node_path_default().join(contextPath, 'wiring'));
636
+ return result.sort((a, b)=>a.typeName.localeCompare(b.typeName));
637
+ };
638
+ const moduleKindOf = (module)=>wiredModuleKind(module.kind);
639
+ const layerRule = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && ('infrastructure' !== consumer.implementationsLayer || 'application' !== candidate.layer || 'application-ports' === candidate.kind);
640
+ const wiring_implementationType = (consumer, implementation)=>consumer.branched ? external_node_path_default().basename(external_node_path_default().dirname(implementation.file)) : void 0;
641
+ const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && `-${external_node_path_default().basename(candidate.typeFile, '.ts')}-`.includes(`-${implementation}-`);
642
+ const canDependOn = (consumer, candidate, rules = defaultDependencyRules, implementation = consumer.implementations[0])=>{
643
+ const crossContext = crossContextImportAllowed(consumer.wireFile, candidate.wireFile);
644
+ if (void 0 !== crossContext) return crossContext && 'infrastructure' === consumer.implementationsLayer && 'application' === candidate.layer && !!implementation && true === crossContextImportAllowed(implementation.file, candidate.typeFile);
645
+ const consumerKind = moduleKindOf(consumer);
646
+ const candidateKind = moduleKindOf(candidate);
647
+ return consumerKind && candidateKind ? rules[consumerKind].has(candidateKind) : layerRule(consumer, candidate);
648
+ };
649
+ const availableDependencies = (consumer, implementation, candidates, rules = configuredDependencyRules())=>{
650
+ const source = new file_system_File(consumer.wireFile).data;
651
+ const imported = namedImportFiles(source, consumer.wireFile);
652
+ const wired = wiredDependencyNames(source, implementation.className);
653
+ const wiredFiles = new Set(wired.map((name)=>imported.get(name)).filter(Boolean));
654
+ return candidates.filter((candidate)=>candidate.wireFile !== consumer.wireFile && canDependOn(consumer, candidate, rules, implementation) && !wiredFiles.has(candidate.wireFile) && !(wired.includes(candidate.wireName) && !imported.has(candidate.wireName)));
655
+ };
656
+ const relativeImport = (fromFile, toFile)=>{
336
657
  const relativePath = external_node_path_default().relative(external_node_path_default().dirname(fromFile), toFile).replace(/\.ts$/, '').split(external_node_path_default().sep).join('/');
337
658
  return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
338
659
  };
660
+ const codeOnly = (source)=>{
661
+ let result = '';
662
+ let index = 0;
663
+ const blank = (text)=>text.replace(/[^\n]/g, ' ');
664
+ while(index < source.length){
665
+ const pair = source.slice(index, index + 2);
666
+ const char = source[index];
667
+ let end = index + 1;
668
+ if ('//' === pair) {
669
+ const lineEnd = source.indexOf('\n', index);
670
+ end = -1 === lineEnd ? source.length : lineEnd;
671
+ result += blank(source.slice(index, end));
672
+ } else if ('/*' === pair) {
673
+ const commentEnd = source.indexOf('*/', index + 2);
674
+ end = -1 === commentEnd ? source.length : commentEnd + 2;
675
+ result += blank(source.slice(index, end));
676
+ } else if ('=>' === pair) {
677
+ end = index + 2;
678
+ result += ' ';
679
+ } else if ("'" === char || '"' === char || '`' === char) {
680
+ while(end < source.length && source[end] !== char)end += '\\' === source[end] ? 2 : 1;
681
+ end = Math.min(end + 1, source.length);
682
+ result += char + blank(source.slice(index + 1, end - 1));
683
+ result += end - 1 > index ? source[end - 1] : '';
684
+ } else result += char;
685
+ index = end;
686
+ }
687
+ return result;
688
+ };
689
+ const addImport = (source, importLine)=>{
690
+ if (source.split('\n').some((line)=>line.trim() === importLine)) return source;
691
+ const lastImport = [
692
+ ...codeOnly(source).matchAll(/^import\s(?:[^'"]*?from\s*)?['"][^'"]*['"]/gm)
693
+ ].at(-1);
694
+ if (!lastImport) return `${importLine}\n\n${source}`;
695
+ const importEnd = lastImport.index + lastImport[0].length;
696
+ const lineEnd = source.indexOf('\n', importEnd);
697
+ const insertAt = -1 === lineEnd ? source.length : lineEnd;
698
+ return `${source.slice(0, insertAt)}\n${importLine}${source.slice(insertAt)}`;
699
+ };
700
+ const brackets = {
701
+ '(': ')',
702
+ '[': ']',
703
+ '{': '}',
704
+ '<': '>'
705
+ };
706
+ const closingIndex = (source, openIndex)=>{
707
+ const code = codeOnly(source);
708
+ let depth = 0;
709
+ for(let index = openIndex; index < code.length; index++){
710
+ const char = code[index];
711
+ if (char === code[openIndex]) depth++;
712
+ else if (char === brackets[code[openIndex]]) {
713
+ depth--;
714
+ if (0 === depth) return index;
715
+ }
716
+ }
717
+ return -1;
718
+ };
719
+ const topLevelItemRanges = (content)=>{
720
+ const code = codeOnly(content);
721
+ const ranges = [];
722
+ let depth = 0;
723
+ let itemStart = 0;
724
+ for(let index = 0; index <= code.length; index++){
725
+ const char = code[index];
726
+ if (void 0 !== char && char in brackets) depth++;
727
+ else if (Object.values(brackets).includes(char)) depth--;
728
+ if (index === code.length || ',' === char && 0 === depth) {
729
+ const itemCode = code.slice(itemStart, index);
730
+ const first = itemCode.search(/\S/);
731
+ const last = itemCode.search(/\S\s*$/);
732
+ if (-1 !== first) ranges.push({
733
+ start: itemStart + first,
734
+ end: itemStart + last + 1
735
+ });
736
+ itemStart = index + 1;
737
+ }
738
+ }
739
+ return ranges;
740
+ };
741
+ const splitTopLevel = (content)=>topLevelItemRanges(content).map(({ start, end })=>content.slice(start, end));
742
+ const appendItems = (content, items)=>{
743
+ const code = codeOnly(content);
744
+ const lastCode = code.search(/\S\s*$/);
745
+ if (-1 === lastCode) return items.join(', ');
746
+ const trailingComma = ',' === code[lastCode];
747
+ if (!content.includes('\n')) {
748
+ const added = trailingComma ? ` ${items.join(', ')},` : `, ${items.join(', ')}`;
749
+ return content.slice(0, lastCode + 1) + added + content.slice(lastCode + 1);
750
+ }
751
+ const indent = content.match(/\n([ \t]*)\S/)?.[1] ?? '';
752
+ const withComma = trailingComma ? content : `${content.slice(0, lastCode + 1)},${content.slice(lastCode + 1)}`;
753
+ const lineEndIndex = withComma.indexOf('\n', lastCode + 1);
754
+ const lineEnd = -1 === lineEndIndex ? withComma.length : lineEndIndex;
755
+ const added = trailingComma ? items.map((x)=>`\n${indent}${x},`).join('') : items.map((x)=>`\n${indent}${x}`).join(',');
756
+ return withComma.slice(0, lineEnd) + added + withComma.slice(lineEnd);
757
+ };
758
+ const addConstructorParameters = (source, className, parameters)=>{
759
+ const classMatch = new RegExp(`class\\s+${className}\\b[^{]*\\{`).exec(codeOnly(source));
760
+ if (!classMatch) throw new Error(`Class ${className} not found`);
761
+ const bodyStart = classMatch.index + classMatch[0].length;
762
+ const bodyEnd = closingIndex(source, bodyStart - 1);
763
+ const body = source.slice(bodyStart, bodyEnd);
764
+ const constructorIndex = codeOnly(body).search(/\bconstructor\s*\(/);
765
+ const renderParameters = (allParameters, indent)=>1 === allParameters.length ? allParameters[0] : `\n${allParameters.map((x)=>`${indent} ${x}`).join(',\n')}\n${indent}`;
766
+ if (-1 === constructorIndex) {
767
+ const constructorBody = /\bextends\b/.test(classMatch[0]) ? '{\n super()\n }' : '{}';
768
+ const constructorLine = ` constructor(${renderParameters(parameters, ' ')}) ${constructorBody}`;
769
+ const newBody = body.trim() ? `\n${constructorLine}\n${body.replace(/^\s*\n/, '\n')}` : `\n${constructorLine}\n`;
770
+ return source.slice(0, bodyStart) + newBody + source.slice(bodyEnd);
771
+ }
772
+ const openIndex = bodyStart + body.indexOf('(', constructorIndex);
773
+ const closeIndex = closingIndex(source, openIndex);
774
+ const content = source.slice(openIndex + 1, closeIndex);
775
+ if (content.includes('\n')) return source.slice(0, openIndex + 1) + appendItems(content, parameters) + source.slice(closeIndex);
776
+ const lineStart = source.lastIndexOf('\n', openIndex) + 1;
777
+ const indent = source.slice(lineStart).match(/^\s*/)?.[0] ?? '';
778
+ return source.slice(0, openIndex + 1) + renderParameters([
779
+ ...splitTopLevel(content),
780
+ ...parameters
781
+ ], indent) + source.slice(closeIndex);
782
+ };
783
+ const addClassMember = (source, className, member)=>{
784
+ const classMatch = new RegExp(`class\\s+${className}\\b[^{]*\\{`).exec(codeOnly(source));
785
+ if (!classMatch) throw new Error(`Class ${className} not found`);
786
+ const bodyStart = classMatch.index + classMatch[0].length;
787
+ const bodyEnd = closingIndex(source, bodyStart - 1);
788
+ const body = source.slice(bodyStart, bodyEnd).trimEnd();
789
+ const separator = body.trim() ? '\n\n' : '\n';
790
+ return `${source.slice(0, bodyStart)}${body}${separator} ${member}\n${source.slice(bodyEnd)}`;
791
+ };
792
+ const wireListRange = (source, className)=>{
793
+ const match = new RegExp(`wireClass\\(\\s*${className}\\s*,\\s*\\[`).exec(codeOnly(source));
794
+ if (!match) throw new Error(`wireClass(${className}, [...]) not found`);
795
+ const openIndex = match.index + match[0].length - 1;
796
+ return {
797
+ openIndex,
798
+ closeIndex: closingIndex(source, openIndex)
799
+ };
800
+ };
801
+ const wiredDependencyNames = (source, className)=>{
802
+ const { openIndex, closeIndex } = wireListRange(source, className);
803
+ return splitTopLevel(source.slice(openIndex + 1, closeIndex));
804
+ };
805
+ const addWireDependencies = (source, className, wireNames)=>{
806
+ const { openIndex, closeIndex } = wireListRange(source, className);
807
+ return source.slice(0, openIndex + 1) + appendItems(source.slice(openIndex + 1, closeIndex), wireNames) + source.slice(closeIndex);
808
+ };
809
+ const parameterName = (typeName)=>typeName.substring(0, 1).toLowerCase() + typeName.substring(1);
810
+ const dependencyBinding = (source, fromFile, targetFile, originalName, preferredName)=>{
811
+ const existing = [
812
+ ...namedImportFiles(source, fromFile)
813
+ ].find(([, file])=>file === targetFile);
814
+ if (existing) return existing[0];
815
+ let name = preferredName;
816
+ let suffix = 2;
817
+ while(new RegExp(`\\b${name}\\b`).test(codeOnly(source)))name = `${preferredName}${suffix++}`;
818
+ return preferredName === originalName ? originalName : name;
819
+ };
820
+ const importedAs = (name, local)=>name === local ? name : `${name} as ${local}`;
821
+ const wireDependencies = (consumer, implementation, dependencies)=>{
822
+ const wireFile = new file_system_File(consumer.wireFile);
823
+ let wireSource = wireFile.data;
824
+ const classFile = new file_system_File(implementation.file);
825
+ let classSource = classFile.data;
826
+ const bindings = dependencies.map((dependency)=>{
827
+ const crossContext = crossContextImportAllowed(consumer.wireFile, dependency.wireFile);
828
+ const context = crossContext ? boundedContextLocation(dependency.wireFile) : void 0;
829
+ const prefix = context ? new UnknownFormatNaming(context.name).ClassName : '';
830
+ const wireName = dependencyBinding(wireSource, consumer.wireFile, dependency.wireFile, dependency.wireName, context ? `wire${prefix}${dependency.typeName}` : dependency.wireName);
831
+ const typeName = dependencyBinding(classSource, implementation.file, dependency.typeFile, dependency.typeName, `${prefix}${dependency.typeName}`);
832
+ wireSource = addImport(wireSource, `import { ${importedAs(dependency.wireName, wireName)} } from '${relativeImport(consumer.wireFile, dependency.wireFile)}'`);
833
+ classSource = addImport(classSource, `import type { ${importedAs(dependency.typeName, typeName)} } from '${relativeImport(implementation.file, dependency.typeFile)}'`);
834
+ return {
835
+ wireName,
836
+ typeName
837
+ };
838
+ });
839
+ wireFile.update(addWireDependencies(wireSource, implementation.className, bindings.map((x)=>x.wireName)));
840
+ classFile.update(addConstructorParameters(classSource, implementation.className, bindings.map((x)=>`private readonly ${parameterName(x.typeName)}: ${x.typeName}`)));
841
+ };
842
+ const branchesRange = (source, wireName)=>{
843
+ const match = new RegExp(`export\\s+const\\s+${wireName}\\s*=\\s*envBranchedWire\\(\\s*\\{`).exec(codeOnly(source));
844
+ if (!match) throw new Error(`${wireName} = envBranchedWire({...}) not found`);
845
+ const openIndex = match.index + match[0].length - 1;
846
+ return {
847
+ declarationIndex: match.index,
848
+ openIndex,
849
+ closeIndex: closingIndex(source, openIndex)
850
+ };
851
+ };
852
+ const branchItems = (content)=>topLevelItemRanges(content).map(({ start, end })=>{
853
+ const item = content.slice(start, end);
854
+ const colon = codeOnly(item).indexOf(':');
855
+ if (-1 === colon) return {
856
+ key: item,
857
+ valueStart: start,
858
+ end,
859
+ shorthand: true
860
+ };
861
+ const valueStart = start + colon + 1 + item.slice(colon + 1).search(/\S/);
862
+ return {
863
+ key: item.slice(0, colon).trim(),
864
+ valueStart,
865
+ end,
866
+ shorthand: false
867
+ };
868
+ });
869
+ const wireBranches = (source, wireName)=>{
870
+ const { openIndex, closeIndex } = branchesRange(source, wireName);
871
+ const content = source.slice(openIndex + 1, closeIndex);
872
+ return new Map(branchItems(content).map(({ key, valueStart, end })=>[
873
+ key,
874
+ content.slice(valueStart, end)
875
+ ]));
876
+ };
877
+ const setWireBranches = (source, wireName, environments, branchWire)=>{
878
+ const { openIndex, closeIndex } = branchesRange(source, wireName);
879
+ let content = source.slice(openIndex + 1, closeIndex);
880
+ const items = branchItems(content);
881
+ for (const { key, valueStart, end, shorthand } of [
882
+ ...items
883
+ ].reverse())if (environments.includes(key)) content = content.slice(0, valueStart) + (shorthand ? `${key}: ${branchWire}` : branchWire) + content.slice(end);
884
+ const missing = environments.filter((environment)=>!items.some((x)=>x.key === environment));
885
+ if (missing.length) content = appendItems(content, missing.map((environment)=>`${environment}: ${branchWire}`));
886
+ return source.slice(0, openIndex + 1) + content + source.slice(closeIndex);
887
+ };
888
+ const addBranchedImplementation = (source, wireName, implementation)=>{
889
+ const withImport = addImport(source, implementation.importLine);
890
+ const { declarationIndex } = branchesRange(withImport, wireName);
891
+ const withWireClass = `${withImport.slice(0, declarationIndex)}const ${implementation.wireName} = wireClass(${implementation.className}, [])\n\n${withImport.slice(declarationIndex)}`;
892
+ return setWireBranches(withWireClass, wireName, implementation.environments, implementation.wireName);
893
+ };
894
+ const inMemoryImplementationType = 'in-memory';
895
+ const in_memory_db_className = 'InMemoryDbInfrastructureService';
896
+ const in_memory_db_wireName = 'wireInMemoryDbInfrastructureService';
897
+ const in_memory_db_parameterName = 'inMemoryDbInfrastructureService';
339
898
  const inMemoryDbService = `type Entry = {
340
899
  id: unknown;
341
900
  item: any;
@@ -468,9 +1027,9 @@ describe('in memory db', () => {
468
1027
  })
469
1028
  })
470
1029
  `.trim();
471
- const in_memory_db_withWiring = ()=>config_file_ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
1030
+ const in_memory_db_withWiring = ()=>config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
472
1031
  const in_memory_db_sharedFolder = ()=>new file_system_Folder(new project_root_ProjectRoot().path).subitem([
473
- config_file_ConfigFile.Instance.data.rootFolder,
1032
+ config_file_ConfigFile.Instance.data.project.rootFolder,
474
1033
  'shared-kernel'
475
1034
  ]);
476
1035
  const serviceFile = ()=>new file_system_File(in_memory_db_sharedFolder().path).subitem([
@@ -484,7 +1043,7 @@ const in_memory_db_wireFile = ()=>new file_system_File(in_memory_db_sharedFolder
484
1043
  'wire-in-memory-db-infrastructure-service.ts'
485
1044
  ]);
486
1045
  const in_memory_db_scaffoldInMemoryDb = (shared)=>{
487
- const { testingLibrary } = config_file_ConfigFile.Instance.data;
1046
+ const { testingLibrary } = config_file_ConfigFile.backend;
488
1047
  const servicesFolder = shared.subitem([
489
1048
  'infrastructure',
490
1049
  'services'
@@ -497,6 +1056,7 @@ const in_memory_db_scaffoldInMemoryDb = (shared)=>{
497
1056
  ]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
498
1057
  };
499
1058
  const inMemoryDbScaffolded = ()=>serviceFile().exists && (!in_memory_db_withWiring() || in_memory_db_wireFile().exists);
1059
+ const usesInMemoryDb = (implementationType)=>Boolean(config_file_ConfigFile.Instance.data.backend?.withInMemoryDb) && new UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && inMemoryDbScaffolded();
500
1060
  const uncountableEndings = [
501
1061
  'data',
502
1062
  'info',
@@ -512,21 +1072,64 @@ const uncountableEndings = [
512
1072
  'analytics',
513
1073
  'series'
514
1074
  ];
515
- new RegExp(`(${uncountableEndings.join('|')})$`, 'i');
1075
+ const uncountable = new RegExp(`(${uncountableEndings.join('|')})$`, 'i');
1076
+ const plural = (word)=>{
1077
+ if (uncountable.test(word)) return word;
1078
+ if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
1079
+ if (/(^|[^aeiou]|qu)[aeiou]z$/i.test(word)) return `${word}zes`;
1080
+ if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
1081
+ return `${word}s`;
1082
+ };
1083
+ const addInMemoryDbSection = (typeNaming, typeImportTarget)=>{
1084
+ const file = serviceFile();
1085
+ const sectionNaming = new UnknownFormatNaming(plural(typeNaming.fileName));
1086
+ const field = sectionNaming.variableName;
1087
+ if (new RegExp(`\\b${field}\\s*=\\s*this\\.section\\b`).test(file.data)) return field;
1088
+ const withImport = addImport(file.data, `import type { ${typeNaming.ClassName} } from '${relativeImport(file.path, typeImportTarget)}';`);
1089
+ file.update(addClassMember(withImport, in_memory_db_className, `${field} = this.section<${typeNaming.ClassName}>('${sectionNaming.fileName.toUpperCase()}');`));
1090
+ return field;
1091
+ };
1092
+ const inMemoryDbTypeImport = (fromFile)=>`import type { ${in_memory_db_className} } from '${relativeImport(fromFile, serviceFile().path)}'`;
1093
+ const inMemoryDbSectionMembers = (field, derived)=>`
1094
+ private readonly data: ${in_memory_db_className}['${field}']
1095
+
1096
+ constructor(${in_memory_db_parameterName}: ${in_memory_db_className}) {
1097
+ ${derived ? 'super()\n ' : ''}this.data = ${in_memory_db_parameterName}.${field}
1098
+ }
1099
+ `.trim();
1100
+ const keepInMemoryDbSection = (classFile, field)=>{
1101
+ classFile.update(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)).replace('constructor() {}', inMemoryDbSectionMembers(field, false)));
1102
+ };
1103
+ const isInMemoryDb = (module)=>module.wireName === in_memory_db_wireName;
1104
+ const injectInMemoryDb = (classFile, implementationName)=>{
1105
+ classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
1106
+ `private readonly ${in_memory_db_parameterName}: ${in_memory_db_className}`
1107
+ ]));
1108
+ };
1109
+ const wireInMemoryDb = (consumerWireFile, implementationName)=>{
1110
+ consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${in_memory_db_wireName} } from '${relativeImport(consumerWireFile.path, in_memory_db_wireFile().path)}'`), implementationName, [
1111
+ in_memory_db_wireName
1112
+ ]));
1113
+ };
1114
+ const passInMemoryDb = (specFile, implementationName)=>{
1115
+ specFile.update(addImport(specFile.data, `import { ${in_memory_db_className} } from '${relativeImport(specFile.path, serviceFile().path)}'`).replace(`new ${implementationName}()`, `new ${implementationName}(new ${in_memory_db_className}())`));
1116
+ };
516
1117
  const addInMemoryDb = ()=>{
517
1118
  const config = config_file_ConfigFile.Instance.data;
518
- if (!config.withInMemoryDb) config_file_ConfigFile.write({
519
- ...config,
520
- withInMemoryDb: true
1119
+ if (!config_file_ConfigFile.backend.withInMemoryDb) config_file_ConfigFile.update({
1120
+ backend: {
1121
+ ...config_file_ConfigFile.backend,
1122
+ withInMemoryDb: true
1123
+ }
521
1124
  });
522
- withoutOverwrites(()=>in_memory_db_scaffoldInMemoryDb(new file_system_Folder(new project_root_ProjectRoot().path).subitem([
523
- config.rootFolder,
1125
+ file_system_withoutOverwrites(()=>in_memory_db_scaffoldInMemoryDb(new file_system_Folder(new project_root_ProjectRoot().path).subitem([
1126
+ config.project.rootFolder,
524
1127
  'shared-kernel'
525
1128
  ])));
526
1129
  return [];
527
1130
  };
528
- const inMemoryDbApplied = ()=>Boolean(config_file_ConfigFile.Instance.data.withInMemoryDb) && inMemoryDbScaffolded();
529
- const hasDependency = (name)=>{
1131
+ const inMemoryDbApplied = ()=>Boolean(config_file_ConfigFile.Instance.data.backend?.withInMemoryDb) && inMemoryDbScaffolded();
1132
+ const missing_domain_first_packages_hasDependency = (name)=>{
530
1133
  const manifestFile = new file_system_File(external_node_path_default().join(new project_root_ProjectRoot().path, 'package.json'));
531
1134
  if (!manifestFile.exists) return false;
532
1135
  const manifest = JSON.parse(manifestFile.data);
@@ -536,16 +1139,135 @@ const hasDependency = (name)=>{
536
1139
  manifest.optionalDependencies
537
1140
  ].some((dependencies)=>dependencies && Object.hasOwn(dependencies, name));
538
1141
  };
539
- const missingPackages = (packages)=>{
1142
+ const missing_domain_first_packages_missingPackages = (packages)=>{
540
1143
  const missing = [
541
1144
  ...new Set(packages)
542
- ].filter((name)=>!hasDependency(name));
1145
+ ].filter((name)=>!missing_domain_first_packages_hasDependency(name));
543
1146
  return missing.length ? [
544
1147
  `npm i ${missing.join(' ')}`
545
1148
  ] : [];
546
1149
  };
1150
+ const external_node_async_hooks_namespaceObject = require("node:async_hooks");
1151
+ const prompts_namespaceObject = require("@inquirer/prompts");
1152
+ class RequestError extends Error {
1153
+ code;
1154
+ details;
1155
+ constructor(code, message, details){
1156
+ super(message), this.code = code, this.details = details;
1157
+ }
1158
+ }
1159
+ const storage = new external_node_async_hooks_namespaceObject.AsyncLocalStorage();
1160
+ const isNonInteractive = ()=>Boolean(storage.getStore());
1161
+ const runWithAnswers = async (answers, defaults, run)=>storage.run({
1162
+ answers,
1163
+ defaults,
1164
+ used: new Set(),
1165
+ messages: []
1166
+ }, async ()=>{
1167
+ const result = await run();
1168
+ const state = storage.getStore();
1169
+ assertAnswersConsumed();
1170
+ return {
1171
+ result,
1172
+ messages: state.messages
1173
+ };
1174
+ });
1175
+ const assertAnswersConsumed = ()=>{
1176
+ const state = storage.getStore();
1177
+ if (!state) return;
1178
+ const unused = Object.keys(state.answers).filter((key)=>!state.used.has(key));
1179
+ if (unused.length) throw new RequestError('UNUSED_PARAMETERS', 'Some parameters do not apply to this operation.', {
1180
+ fields: unused
1181
+ });
1182
+ };
1183
+ const answerFor = (key, fallback)=>{
1184
+ const state = storage.getStore();
1185
+ if (!state) return;
1186
+ if (Object.hasOwn(state.answers, key)) {
1187
+ state.used.add(key);
1188
+ return state.answers[key];
1189
+ }
1190
+ return Object.hasOwn(state.defaults, key) ? state.defaults[key] : fallback;
1191
+ };
1192
+ const report = (...values)=>{
1193
+ const state = storage.getStore();
1194
+ if (state) state.messages.push(values.map(String).join(' '));
1195
+ else console.log(...values);
1196
+ };
1197
+ const requireKey = (key)=>{
1198
+ if (!key) throw new RequestError('UNSUPPORTED_PROMPT', 'This operation needs an answer that is not supported in non-interactive mode.');
1199
+ return key;
1200
+ };
1201
+ const interaction_missing = (key)=>new RequestError('MISSING_PARAMETER', `Provide ${key}.`, {
1202
+ field: key
1203
+ });
1204
+ const interaction_input = async (config)=>{
1205
+ const { key, ...interactive } = config;
1206
+ if (!isNonInteractive()) return (0, prompts_namespaceObject.input)(interactive);
1207
+ const field = requireKey(key);
1208
+ const value = answerFor(field, config.default);
1209
+ if ('string' != typeof value) throw interaction_missing(field);
1210
+ const valid = await config.validate?.(value);
1211
+ if (void 0 !== valid && true !== valid) throw new RequestError('INVALID_PARAMETER', 'string' == typeof valid ? valid : `Invalid ${field}.`, {
1212
+ field
1213
+ });
1214
+ return value;
1215
+ };
1216
+ const interaction_confirm = async (config)=>{
1217
+ const { key, requestRequired, ...interactive } = config;
1218
+ if (!isNonInteractive()) return (0, prompts_namespaceObject.confirm)(interactive);
1219
+ const field = requireKey(key);
1220
+ const value = answerFor(field, requestRequired ? void 0 : config.default ?? false);
1221
+ if (void 0 === value) throw interaction_missing(field);
1222
+ if ('boolean' != typeof value) throw new RequestError('INVALID_PARAMETER', `${field} must be a boolean.`, {
1223
+ field
1224
+ });
1225
+ return value;
1226
+ };
1227
+ const choicesOf = (config)=>config.choices.filter((choice)=>!(choice instanceof prompts_namespaceObject.Separator)).map((choice)=>'object' == typeof choice && null !== choice && 'value' in choice ? choice : {
1228
+ value: choice
1229
+ });
1230
+ const choiceId = (choice, id)=>id?.(choice.value) ?? choice.value;
1231
+ const resolveChoice = (value, choices, key, id)=>{
1232
+ const matches = choices.filter((choice)=>Object.is(choice.value, value) || choiceId(choice, id) === value);
1233
+ if (1 !== matches.length || matches[0].disabled) throw new RequestError('INVALID_CHOICE', `Invalid or unavailable choice for ${key}.`, {
1234
+ field: key,
1235
+ value,
1236
+ choices: choices.filter((choice)=>!choice.disabled).map((choice)=>choiceId(choice, id))
1237
+ });
1238
+ return matches[0].value;
1239
+ };
1240
+ const interaction_select = async (config)=>{
1241
+ const { key, id, ...interactive } = config;
1242
+ if (!isNonInteractive()) return (0, prompts_namespaceObject.select)(interactive);
1243
+ const field = requireKey(key);
1244
+ const value = answerFor(field, config.default);
1245
+ if (void 0 === value) throw interaction_missing(field);
1246
+ return resolveChoice(value, choicesOf(config), field, id);
1247
+ };
1248
+ const interaction_checkbox = async (config)=>{
1249
+ const { key, id, ...interactive } = config;
1250
+ if (!isNonInteractive()) return (0, prompts_namespaceObject.checkbox)(interactive);
1251
+ const field = requireKey(key);
1252
+ const choices = choicesOf(config);
1253
+ const values = answerFor(field, choices.filter((choice)=>choice.checked && !choice.disabled).map((choice)=>choice.value));
1254
+ if (!Array.isArray(values)) throw new RequestError('INVALID_PARAMETER', `${field} must be an array.`, {
1255
+ field
1256
+ });
1257
+ const selected = values.map((value)=>resolveChoice(value, choices, field, id));
1258
+ if (new Set(selected).size !== selected.length) throw new RequestError('INVALID_PARAMETER', `Duplicate choices for ${field}.`, {
1259
+ field
1260
+ });
1261
+ if (config.required && !selected.length) throw interaction_missing(field);
1262
+ return selected;
1263
+ };
1264
+ const usesNext = ()=>config_file_ConfigFile.exists && config_file_ConfigFile.Instance.data.frontend?.react?.framework === 'next';
1265
+ const nextAppFolder = (root)=>[
1266
+ 'app',
1267
+ 'src/app'
1268
+ ].find((folder)=>new file_system_Folder(external_node_path_default().join(root, folder)).exists) ?? 'app';
547
1269
  const external_node_module_namespaceObject = require("node:module");
548
- const tsconfig_stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
1270
+ const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
549
1271
  const resolveExtends = (fromFile, target)=>{
550
1272
  if (target.startsWith('.') || external_node_path_default().isAbsolute(target)) {
551
1273
  const resolved = external_node_path_default().resolve(external_node_path_default().dirname(fromFile), target);
@@ -564,7 +1286,7 @@ const compilerOption = (configFile, name, seen = new Set())=>{
564
1286
  seen.add(configFile);
565
1287
  let config;
566
1288
  try {
567
- config = JSON.parse(tsconfig_stripJsonComments(external_node_fs_default().readFileSync(configFile, 'utf8')));
1289
+ config = JSON.parse(stripJsonComments(external_node_fs_default().readFileSync(configFile, 'utf8')));
568
1290
  } catch {
569
1291
  return null;
570
1292
  }
@@ -578,6 +1300,28 @@ const compilerOption = (configFile, name, seen = new Set())=>{
578
1300
  if (void 0 !== value) return value;
579
1301
  }
580
1302
  };
1303
+ const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
1304
+ class NestedName {
1305
+ folders;
1306
+ folderName;
1307
+ fileName;
1308
+ ClassName;
1309
+ classNameSegments;
1310
+ constructor(rawSource){
1311
+ const segments = splitSegments(rawSource);
1312
+ this.folders = segments.slice(0, -1);
1313
+ this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
1314
+ this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
1315
+ this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
1316
+ this.ClassName = this.classNameSegments.join('');
1317
+ }
1318
+ static validate = (rawSource)=>{
1319
+ const segments = splitSegments(rawSource);
1320
+ if (!segments.length) return 'Name is required';
1321
+ if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
1322
+ return true;
1323
+ };
1324
+ }
581
1325
  const reactPageContent = (ClassName, { imports = [], body = '<></>' } = {})=>`
582
1326
  ${[
583
1327
  ...imports,
@@ -590,6 +1334,35 @@ export const ${ClassName}Page: FC<${ClassName}PageProps> = (props) => {
590
1334
  return ${body}
591
1335
  }
592
1336
  `.trim();
1337
+ const nextRouteContent = (ClassName, pageImport)=>`
1338
+ import { ${ClassName}Page } from '${pageImport}'
1339
+
1340
+ export default function Page() {
1341
+ return <${ClassName}Page />
1342
+ }
1343
+ `.trim();
1344
+ const scaffoldNextRoute = (name, pageFile)=>{
1345
+ const root = new project_root_ProjectRoot().path;
1346
+ const route = external_node_path_default().join(root, nextAppFolder(root), ...name.folders, name.folderName, 'page.tsx');
1347
+ const relativeRoute = external_node_path_default().relative(root, route).split(external_node_path_default().sep).join('/');
1348
+ const routeFile = new file_system_File(route);
1349
+ if (routeFile.exists) return void report(`${relativeRoute} already exists: render ${name.ClassName}Page there yourself.`);
1350
+ routeFile.data = nextRouteContent(name.ClassName, relativeImport(route, pageFile.path.replace(/\.tsx$/, '')));
1351
+ };
1352
+ const scaffoldReactPage = async (presentationReactFolder)=>{
1353
+ const name = await interaction_input({
1354
+ key: 'name',
1355
+ message: 'Provide name (folders split by "/"):',
1356
+ validate: NestedName.validate
1357
+ });
1358
+ const nestedName = new NestedName(name);
1359
+ const { folders, ClassName, fileName } = nestedName;
1360
+ const pageFile = presentationReactFolder.subitem([
1361
+ 'pages',
1362
+ ...folders
1363
+ ]).createFile(`${fileName}-page.tsx`, reactPageContent(ClassName));
1364
+ if (usesNext()) scaffoldNextRoute(nestedName, pageFile);
1365
+ };
593
1366
  const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
594
1367
  const rootFolderSegments = (rootFolder)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n `).join('');
595
1368
  const openapiExtractor = (rootFolder)=>`import path from 'node:path';
@@ -758,7 +1531,8 @@ const addPackageScripts = async (file, additions)=>{
758
1531
  for (const [name, command] of Object.entries(additions)){
759
1532
  let target = name;
760
1533
  if (Object.hasOwn(scripts, name) && scripts[name] !== command) {
761
- const action = await (0, prompts_namespaceObject.select)({
1534
+ const action = await interaction_select({
1535
+ key: `scriptConflicts.${name}`,
762
1536
  message: `Script "${name}" already exists: ${scripts[name]}`,
763
1537
  choices: [
764
1538
  'Keep existing',
@@ -767,7 +1541,8 @@ const addPackageScripts = async (file, additions)=>{
767
1541
  ]
768
1542
  });
769
1543
  if ('Keep existing' === action) continue;
770
- if ('Use another name' === action) target = await (0, prompts_namespaceObject.input)({
1544
+ if ('Use another name' === action) target = await interaction_input({
1545
+ key: `scriptNames.${name}`,
771
1546
  message: "New script name:",
772
1547
  validate: (value)=>!/^[a-zA-Z0-9:_-]+$/.test(value) || Object.hasOwn(scripts, value) || Object.hasOwn(additions, value) ? "Enter an unused script name (letters, numbers, :, _, -)." : true
773
1548
  });
@@ -843,7 +1618,7 @@ generateOpenAPI(${withExtractor ? 'handlers' : 'restHandlers'}, {
843
1618
  `;
844
1619
  };
845
1620
  const addOpenapi = async ()=>{
846
- const { rootFolder } = config_file_ConfigFile.Instance.data;
1621
+ const { rootFolder } = config_file_ConfigFile.Instance.data.project;
847
1622
  const root = new project_root_ProjectRoot().path;
848
1623
  const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
849
1624
  const manifest = JSON.parse(manifestFile.data);
@@ -851,20 +1626,24 @@ const addOpenapi = async ()=>{
851
1626
  ...manifest.dependencies,
852
1627
  ...manifest.devDependencies
853
1628
  };
854
- const routePrefix = await (0, prompts_namespaceObject.input)({
1629
+ const routePrefix = await interaction_input({
1630
+ key: 'routePrefix',
855
1631
  message: 'Route prefix the REST handlers are served under:',
856
1632
  default: '/api'
857
1633
  });
858
- const outputPath = await (0, prompts_namespaceObject.input)({
1634
+ const outputPath = await interaction_input({
1635
+ key: 'openapiPath',
859
1636
  message: 'OpenAPI document path:',
860
- default: defaultOpenapiPath(Boolean(dependencies.next)),
1637
+ default: defaultOpenapiPath(usesNext()),
861
1638
  validate: (value)=>splitPath(value).length ? true : 'Path is required'
862
1639
  });
863
- const withExtractor = await (0, prompts_namespaceObject.confirm)({
1640
+ const withExtractor = await interaction_confirm({
1641
+ key: 'withExtractor',
864
1642
  message: "Fill operationId, summary and description from the endpoint logic TSDoc?",
865
1643
  default: true
866
1644
  });
867
- const withSwaggerPage = config_file_ConfigFile.Instance.data.useReact && await (0, prompts_namespaceObject.confirm)({
1645
+ const withSwaggerPage = Boolean(config_file_ConfigFile.Instance.data.frontend?.react) && await interaction_confirm({
1646
+ key: 'swaggerPage',
868
1647
  message: 'Add a Swagger UI page?',
869
1648
  default: true
870
1649
  });
@@ -1016,7 +1795,8 @@ const openapiOutputPath = (root)=>{
1016
1795
  return generator.data.match(/outputFile:\s*{\s*path:\s*'([^']+)'/)?.[1];
1017
1796
  };
1018
1797
  const addOrval = async ()=>{
1019
- const { rootFolder, useReact } = config_file_ConfigFile.Instance.data;
1798
+ const { project: { rootFolder }, frontend } = config_file_ConfigFile.Instance.data;
1799
+ const useReact = Boolean(frontend?.react);
1020
1800
  const root = new project_root_ProjectRoot().path;
1021
1801
  const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
1022
1802
  const manifest = JSON.parse(manifestFile.data);
@@ -1024,14 +1804,16 @@ const addOrval = async ()=>{
1024
1804
  ...manifest.dependencies,
1025
1805
  ...manifest.devDependencies
1026
1806
  };
1027
- const withNext = Boolean(dependencies.next);
1807
+ const withNext = usesNext();
1028
1808
  const generatedOpenapiPath = openapiOutputPath(root);
1029
- const openapiPath = await (0, prompts_namespaceObject.input)({
1809
+ const openapiPath = await interaction_input({
1810
+ key: 'openapiPath',
1030
1811
  message: 'OpenAPI document path:',
1031
1812
  default: generatedOpenapiPath ?? defaultOpenapiPath(withNext),
1032
1813
  validate: (value)=>value.trim() ? true : 'Path is required'
1033
1814
  });
1034
- const targets = useReact ? await (0, prompts_namespaceObject.checkbox)({
1815
+ const targets = useReact ? await interaction_checkbox({
1816
+ key: 'targets',
1035
1817
  message: 'Generate:',
1036
1818
  choices: [
1037
1819
  {
@@ -1217,6 +1999,34 @@ const addPlaywright = async ()=>{
1217
1999
  })
1218
2000
  ];
1219
2001
  };
2002
+ const savedImplementations = (kind, purpose)=>[
2003
+ ...new Set(config_file_ConfigFile.Instance.data.backend?.implementations?.[kind]?.[purpose] ?? [])
2004
+ ];
2005
+ const rememberImplementation = (kind, purpose, label)=>{
2006
+ implementationLabelSchema.parse(label);
2007
+ const backend = config_file_ConfigFile.backend;
2008
+ const choices = {
2009
+ ...backend.implementations
2010
+ };
2011
+ const group = choices[kind] ?? {
2012
+ primary: [],
2013
+ test: []
2014
+ };
2015
+ if (group[purpose].includes(label)) return;
2016
+ choices[kind] = {
2017
+ ...group,
2018
+ [purpose]: [
2019
+ ...group[purpose],
2020
+ label
2021
+ ]
2022
+ };
2023
+ config_file_ConfigFile.update({
2024
+ backend: {
2025
+ ...backend,
2026
+ implementations: choices
2027
+ }
2028
+ });
2029
+ };
1220
2030
  const runtimePackages = [
1221
2031
  '@prisma/orm-postgres',
1222
2032
  'temporal-polyfill',
@@ -1294,32 +2104,30 @@ const addPrisma = async ()=>{
1294
2104
  ...manifest.dependencies,
1295
2105
  ...manifest.devDependencies
1296
2106
  };
1297
- const shared = external_node_path_default().resolve(root, config.rootFolder, 'shared-kernel');
2107
+ const shared = external_node_path_default().resolve(root, config.project.rootFolder, 'shared-kernel');
1298
2108
  const prismaFolder = external_node_path_default().join(shared, 'infrastructure/prisma');
1299
2109
  if (dependencies['@prisma/client'] || dependencies.prisma && !/^[~^]?8\./.test(dependencies.prisma) || dependencies['@prisma/orm-mongo'] || dependencies['@prisma/orm-sqlite'] || [
1300
2110
  external_node_path_default().join(root, 'prisma/schema.prisma'),
1301
2111
  external_node_path_default().join(prismaFolder, 'schema.prisma')
1302
2112
  ].some((filePath)=>new file_system_File(filePath).exists)) throw new Error('This preset adds Prisma 8 for PostgreSQL. Migrate the existing Prisma setup separately before using it.');
1303
- const withService = await (0, prompts_namespaceObject.confirm)({
2113
+ const withService = await interaction_confirm({
2114
+ key: 'withService',
1304
2115
  message: 'Create the Prisma infrastructure service in the Shared Kernel?',
1305
2116
  default: true
1306
2117
  });
1307
- const useByDefault = 'prisma' !== config.defaultPersistenceLayerImplementation && await (0, prompts_namespaceObject.confirm)({
1308
- message: 'Use prisma as the default persistence implementation?',
1309
- default: false
1310
- });
1311
- const selected = await addPackageScripts(manifestFile, prismaScripts(config.rootFolder));
2118
+ const selected = await addPackageScripts(manifestFile, prismaScripts(config.project.rootFolder));
1312
2119
  stageFile(external_node_path_default().join(prismaFolder, 'prisma.config.ts'), prismaConfig);
1313
2120
  const contract = new file_system_File(external_node_path_default().join(prismaFolder, 'contract.prisma'));
1314
2121
  if (!contract.exists) contract.data = '// use prisma-8\n\n// Add your application models here before running prisma:emit.\n';
1315
2122
  if (withService) {
1316
2123
  stageFile(external_node_path_default().join(shared, 'infrastructure/services/prisma-infrastructure-service.ts'), prismaService);
1317
- if (config.domainFirstPackages.includes('@domain-first/wire')) stageFile(external_node_path_default().join(shared, 'wiring/infrastructure-services/wire-prisma-infrastructure-service.ts'), prismaWiring);
2124
+ if (config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) stageFile(external_node_path_default().join(shared, 'wiring/infrastructure-services/wire-prisma-infrastructure-service.ts'), prismaWiring);
1318
2125
  }
1319
- if (useByDefault) config_file_ConfigFile.write({
1320
- ...config,
1321
- defaultPersistenceLayerImplementation: 'prisma'
1322
- });
2126
+ for (const kind of [
2127
+ 'repositories',
2128
+ 'commands',
2129
+ 'queries'
2130
+ ])rememberImplementation(kind, 'primary', 'prisma');
1323
2131
  const install = (packages, dev)=>{
1324
2132
  const missing = packages.filter((name)=>!dependencies[name]);
1325
2133
  return missing.length ? [
@@ -1338,39 +2146,153 @@ const addPrisma = async ()=>{
1338
2146
  })
1339
2147
  ];
1340
2148
  };
1341
- class unknown_format_naming_UnknownFormatNaming {
1342
- rawSource;
1343
- camelCase;
1344
- PascalCase;
1345
- constructor(rawSource){
1346
- this.rawSource = rawSource;
1347
- const source = rawSource.trim();
1348
- if (!source.includes('-')) {
1349
- this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
1350
- this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
1351
- }
1352
- const words = source.split('-').filter((word)=>!!word);
1353
- this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
1354
- this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
1355
- }
1356
- get fileName() {
1357
- return this.rawSource;
1358
- }
1359
- get variableName() {
1360
- return this.camelCase;
1361
- }
1362
- get ClassName() {
1363
- return this.PascalCase;
1364
- }
1365
- get withSpaces() {
1366
- return this.fileName.replaceAll('-', ' ');
2149
+ const kindTitles = {
2150
+ repositories: 'Repositories',
2151
+ 'domain-services': 'Domain services',
2152
+ 'application-ports': 'Ports',
2153
+ 'application-services': 'Application services',
2154
+ queries: 'Queries',
2155
+ commands: 'Commands',
2156
+ 'use-cases': 'Use cases',
2157
+ 'infrastructure-services': 'Infrastructure services',
2158
+ 'presentation-services': 'Presentation services'
2159
+ };
2160
+ const groupedChoices = (items, suggested = [])=>{
2161
+ const suggestedChoices = suggested.length ? [
2162
+ new prompts_namespaceObject.Separator('── Suggested'),
2163
+ ...suggested.map((x)=>({
2164
+ name: x.label,
2165
+ value: x,
2166
+ checked: true
2167
+ }))
2168
+ ] : [];
2169
+ const kinds = [
2170
+ ...new Set([
2171
+ ...Object.keys(kindTitles),
2172
+ ...items.map((x)=>x.module.kind)
2173
+ ])
2174
+ ];
2175
+ return [
2176
+ ...suggestedChoices,
2177
+ ...kinds.flatMap((kind)=>{
2178
+ const group = items.filter((x)=>x.module.kind === kind && !suggested.includes(x));
2179
+ return group.length ? [
2180
+ new prompts_namespaceObject.Separator(`── ${kindTitles[kind] ?? kind}`),
2181
+ ...group.map((x)=>({
2182
+ name: x.label,
2183
+ value: x
2184
+ }))
2185
+ ] : [];
2186
+ })
2187
+ ];
2188
+ };
2189
+ const groupedPageSize = 20;
2190
+ const dependencyOptions = (boundedContextFolder)=>{
2191
+ const sharedFolder = new file_system_Folder(new project_root_ProjectRoot().path).subitem([
2192
+ config_file_ConfigFile.Instance.data.project.rootFolder,
2193
+ 'shared-kernel'
2194
+ ]);
2195
+ const isShared = sharedFolder.path === boundedContextFolder.path;
2196
+ const contextsFolder = new file_system_Folder(new project_root_ProjectRoot().path).subitem([
2197
+ config_file_ConfigFile.Instance.data.project.rootFolder,
2198
+ 'bounded-contexts'
2199
+ ]);
2200
+ return [
2201
+ ...findWiredModules(boundedContextFolder.path).map((x)=>({
2202
+ module: x,
2203
+ label: x.typeName
2204
+ })),
2205
+ ...isShared ? [] : findWiredModules(sharedFolder.path).map((x)=>({
2206
+ module: x,
2207
+ label: `${x.typeName} (shared-kernel)`
2208
+ })),
2209
+ ...isShared ? [] : contextsFolder.content.subfolderNames.filter((name)=>name !== boundedContextFolder.name).sort().flatMap((name)=>findWiredModules(contextsFolder.subitem([
2210
+ name
2211
+ ]).path).map((module)=>({
2212
+ module,
2213
+ label: `${module.typeName} (${name})`
2214
+ })))
2215
+ ];
2216
+ };
2217
+ const promptDependencies = async (boundedContextFolder, consumer, implementations = consumer.implementations, customWiring)=>{
2218
+ const options = dependencyOptions(boundedContextFolder);
2219
+ let asked = false;
2220
+ for (const implementation of implementations){
2221
+ const available = availableDependencies(consumer, implementation, options.map((x)=>x.module));
2222
+ const candidates = options.filter((x)=>available.includes(x.module));
2223
+ if (!candidates.length) continue;
2224
+ asked = true;
2225
+ const type = wiring_implementationType(consumer, implementation);
2226
+ const suggested = type ? candidates.filter((x)=>isSuggestedFor(x.module, type)) : [];
2227
+ const dependencies = await interaction_checkbox({
2228
+ key: `dependencies.${implementation.className}`,
2229
+ id: (value)=>moduleId(value.module),
2230
+ message: consumer.branched ? `Dependencies for ${implementation.className}:` : 'Dependencies:',
2231
+ choices: groupedChoices(candidates, suggested),
2232
+ pageSize: groupedPageSize,
2233
+ loop: false
2234
+ });
2235
+ const defaultWired = dependencies.map((x)=>x.module).filter((x)=>!customWiring?.(implementation, x));
2236
+ if (defaultWired.length) wireDependencies(consumer, implementation, defaultWired);
1367
2237
  }
1368
- }
2238
+ return asked;
2239
+ };
2240
+ const wireNewModuleDependencies = async (boundedContextFolder, wireFile, customWiring)=>{
2241
+ const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
2242
+ if (consumer) await promptDependencies(boundedContextFolder, consumer, consumer.implementations, customWiring);
2243
+ };
2244
+ const wireNewImplementationDependencies = async (boundedContextFolder, wireFile, className, customWiring)=>{
2245
+ const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
2246
+ const implementation = consumer?.implementations.find((x)=>x.className === className);
2247
+ if (consumer && implementation) await promptDependencies(boundedContextFolder, consumer, [
2248
+ implementation
2249
+ ], customWiring);
2250
+ };
2251
+ const wireDependency = async (boundedContextFolder)=>{
2252
+ const modules = findWiredModules(boundedContextFolder.path);
2253
+ if (!modules.length) return void report('No wired modules here yet.');
2254
+ const { module: consumer, implementation } = await interaction_select({
2255
+ key: 'module',
2256
+ id: (value)=>`${moduleId(value.module)}:${value.implementation.className}`,
2257
+ message: 'Module:',
2258
+ choices: groupedChoices(modules.flatMap((x)=>x.implementations.map((implementation)=>{
2259
+ const type = wiring_implementationType(x, implementation);
2260
+ return {
2261
+ module: x,
2262
+ label: type ? `${x.typeName} (${type})` : x.typeName,
2263
+ implementation
2264
+ };
2265
+ }))),
2266
+ pageSize: groupedPageSize,
2267
+ loop: false
2268
+ });
2269
+ if (!await promptDependencies(boundedContextFolder, consumer, [
2270
+ implementation
2271
+ ])) report('No dependencies available for this module.');
2272
+ };
2273
+ const promptEndpointHandler = async (boundedContextFolder)=>{
2274
+ const handlers = findWiredModules(boundedContextFolder.path).filter((x)=>[
2275
+ 'queries',
2276
+ 'commands',
2277
+ 'use-cases'
2278
+ ].includes(x.kind)).map((x)=>({
2279
+ module: x,
2280
+ label: x.typeName
2281
+ }));
2282
+ return handlers.length ? (await interaction_select({
2283
+ key: 'handler',
2284
+ id: (value)=>moduleId(value.module),
2285
+ message: 'Handler:',
2286
+ choices: groupedChoices(handlers),
2287
+ pageSize: groupedPageSize,
2288
+ loop: false
2289
+ })).module : void 0;
2290
+ };
1369
2291
  const createPresentationService = (boundedContextFolder, name, classFile)=>{
1370
- const naming = new unknown_format_naming_UnknownFormatNaming(name);
2292
+ const naming = new UnknownFormatNaming(name);
1371
2293
  const className = `${naming.ClassName}PresentationService`;
1372
- const scaffoldUnitTests = Boolean(config_file_ConfigFile.Instance.data.testingLibrary);
1373
- const withWiring = config_file_ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
2294
+ const scaffoldUnitTests = Boolean(config_file_ConfigFile.backend.testingLibrary);
2295
+ const withWiring = config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
1374
2296
  const wiringFolder = boundedContextFolder.subitem([
1375
2297
  'wiring',
1376
2298
  'presentation-services'
@@ -1385,7 +2307,7 @@ export class ${className} {
1385
2307
  }
1386
2308
  `.trim());
1387
2309
  if (scaffoldUnitTests) presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.spec.ts`, `
1388
- import { describe, test, expect, beforeEach } from '${config_file_ConfigFile.Instance.data.testingLibrary}'
2310
+ import { describe, test, expect, beforeEach } from '${config_file_ConfigFile.backend.testingLibrary}'
1389
2311
  ${withWiring ? `import { type ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'
1390
2312
  import { wire${naming.ClassName}PresentationService } from '../../wiring/presentation-services/wire-${naming.fileName}-presentation-service'` : `import { ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'`}
1391
2313
 
@@ -1411,6 +2333,14 @@ export const wire${naming.ClassName}PresentationService = wireClass(
1411
2333
  )
1412
2334
  `.trim());
1413
2335
  };
2336
+ const scaffoldNewPresentationService = async (boundedContextFolder)=>{
2337
+ const name = await interaction_input({
2338
+ key: 'name',
2339
+ message: 'Name: '
2340
+ });
2341
+ const wireFile = createPresentationService(boundedContextFolder, name);
2342
+ if (wireFile) await wireNewModuleDependencies(boundedContextFolder, wireFile);
2343
+ };
1414
2344
  const rest_endpoint_generator_name = 'rest-endpoint-generator';
1415
2345
  const scaffoldRestEndpointGenerator = (sharedFolder, { withNextAdapter = false } = {})=>createPresentationService(sharedFolder, rest_endpoint_generator_name, (className)=>{
1416
2346
  const adapter = withNextAdapter ? 'nextAdapter' : 'adapter';
@@ -1435,7 +2365,7 @@ export class ${className} {
1435
2365
  }
1436
2366
  `.trim();
1437
2367
  });
1438
- const rest_endpoint_generator_findRestEndpointGenerator = (sharedFolder)=>{
2368
+ const findRestEndpointGenerator = (sharedFolder)=>{
1439
2369
  const typeFile = external_node_path_default().join(sharedFolder.path, 'presentation', 'services', `${rest_endpoint_generator_name}-presentation-service.ts`);
1440
2370
  if (!new file_system_File(typeFile).exists) return;
1441
2371
  return {
@@ -1445,10 +2375,6 @@ const rest_endpoint_generator_findRestEndpointGenerator = (sharedFolder)=>{
1445
2375
  wireFile: external_node_path_default().join(sharedFolder.path, 'wiring', 'presentation-services', `wire-${rest_endpoint_generator_name}-presentation-service.ts`)
1446
2376
  };
1447
2377
  };
1448
- const nextAppFolder = (root)=>[
1449
- 'app',
1450
- 'src/app'
1451
- ].find((folder)=>new file_system_Folder(external_node_path_default().join(root, folder)).exists) ?? 'app';
1452
2378
  const nextRoutePath = (root)=>external_node_path_default().posix.join(nextAppFolder(root), 'api/[...path]/route.ts');
1453
2379
  const nextRoute = (restHandlersImport)=>`
1454
2380
  import { nextEndpoints } from '@domain-first/handlers-next'
@@ -1466,8 +2392,9 @@ export const PUT = handler
1466
2392
  export const PATCH = handler
1467
2393
  export const DELETE = handler
1468
2394
  `.trim();
1469
- const scaffoldNextRoute = (root)=>{
1470
- const { rootFolder, domainFirstPackages } = config_file_ConfigFile.Instance.data;
2395
+ const rest_endpoint_generator_scaffoldNextRoute = (root)=>{
2396
+ const { rootFolder } = config_file_ConfigFile.Instance.data.project;
2397
+ const { domainFirstPackages } = config_file_ConfigFile.backend;
1471
2398
  const routePath = nextRoutePath(root);
1472
2399
  const routeFile = external_node_path_default().join(root, routePath);
1473
2400
  if (new file_system_File(routeFile).exists) return [];
@@ -1480,29 +2407,30 @@ const scaffoldNextRoute = (root)=>{
1480
2407
  'presentation',
1481
2408
  'rest'
1482
2409
  ]);
1483
- new file_system_File(routeFile).data = nextRoute(wiring_relativeImport(routeFile, restFolder.path));
2410
+ new file_system_File(routeFile).data = nextRoute(relativeImport(routeFile, restFolder.path));
1484
2411
  return new file_system_File(external_node_path_default().join(restFolder.path, 'index.ts')).exists ? [] : [
1485
2412
  `${routePath} serves restHandlers from ${external_node_path_default().posix.join(rootFolder.replaceAll('\\', '/'), 'presentation/rest/index.ts')}, which appears with the first REST endpoint — generate one with df-scaffold (Presentation → New Handlers-REST Endpoint) and the route compiles`
1486
2413
  ];
1487
2414
  };
1488
- const rest_endpoint_generator_askNextAdapter = async ()=>hasDependency('next') && await (0, prompts_namespaceObject.confirm)({
1489
- message: 'Use Next adapter for REST endpoints'
2415
+ const rest_endpoint_generator_askNextAdapter = async ({ nextSelected } = {})=>(nextSelected ?? usesNext()) && await interaction_confirm({
2416
+ key: 'nextAdapter',
2417
+ message: 'Use @domain-first/handlers-next for REST endpoints'
1490
2418
  });
1491
2419
  const rest_endpoint_generator_scaffoldRestEndpointGeneratorFiles = ({ withNextAdapter })=>{
1492
2420
  const root = new project_root_ProjectRoot().path;
1493
2421
  const generatorExisted = restEndpointGeneratorApplied();
1494
- const routeNotes = withoutOverwrites(()=>{
2422
+ const routeNotes = file_system_withoutOverwrites(()=>{
1495
2423
  scaffoldRestEndpointGenerator(new file_system_Folder(root).subitem([
1496
- config_file_ConfigFile.Instance.data.rootFolder,
2424
+ config_file_ConfigFile.Instance.data.project.rootFolder,
1497
2425
  'shared-kernel'
1498
2426
  ]), {
1499
2427
  withNextAdapter
1500
2428
  });
1501
- return withNextAdapter ? scaffoldNextRoute(root) : [];
2429
+ return withNextAdapter ? rest_endpoint_generator_scaffoldNextRoute(root) : [];
1502
2430
  });
1503
2431
  if (!withNextAdapter) return [];
1504
2432
  return [
1505
- ...missingPackages([
2433
+ ...missing_domain_first_packages_missingPackages([
1506
2434
  '@domain-first/handlers-next'
1507
2435
  ]),
1508
2436
  ...routeNotes,
@@ -1514,21 +2442,22 @@ const rest_endpoint_generator_scaffoldRestEndpointGeneratorFiles = ({ withNextAd
1514
2442
  const addRestEndpointGenerator = async ()=>rest_endpoint_generator_scaffoldRestEndpointGeneratorFiles({
1515
2443
  withNextAdapter: await rest_endpoint_generator_askNextAdapter()
1516
2444
  });
1517
- const restEndpointGeneratorApplied = ()=>Boolean(rest_endpoint_generator_findRestEndpointGenerator(new file_system_Folder(new project_root_ProjectRoot().path).subitem([
1518
- config_file_ConfigFile.Instance.data.rootFolder,
2445
+ const restEndpointGeneratorApplied = ()=>Boolean(findRestEndpointGenerator(new file_system_Folder(new project_root_ProjectRoot().path).subitem([
2446
+ config_file_ConfigFile.Instance.data.project.rootFolder,
1519
2447
  'shared-kernel'
1520
2448
  ])));
2449
+ const storybook_storybookFrameworkPackage = '@storybook/react-vite';
1521
2450
  const storybookFiles = (relativeProjectRoot)=>({
1522
2451
  'main.ts': `import { resolve } from 'node:path';
1523
2452
  import react from '@vitejs/plugin-react';
1524
- import type { StorybookConfig } from '@storybook/react-vite';
2453
+ import type { StorybookConfig } from '${storybook_storybookFrameworkPackage}';
1525
2454
 
1526
2455
  const projectRoot = resolve(import.meta.dirname, ${JSON.stringify(relativeProjectRoot)});
1527
2456
 
1528
2457
  const config: StorybookConfig = {
1529
2458
  stories: ['../**/*.mdx', '../**/*.stories.@(ts|tsx)'],
1530
2459
  framework: {
1531
- name: '@storybook/react-vite',
2460
+ name: '${storybook_storybookFrameworkPackage}',
1532
2461
  options: {}
1533
2462
  },
1534
2463
  core: {
@@ -1550,7 +2479,7 @@ const config: StorybookConfig = {
1550
2479
 
1551
2480
  export default config;
1552
2481
  `,
1553
- 'preview.ts': `import type { Preview } from '@storybook/react-vite';
2482
+ 'preview.ts': `import type { Preview } from '${storybook_storybookFrameworkPackage}';
1554
2483
 
1555
2484
  const preview: Preview = {
1556
2485
  parameters: {
@@ -1574,18 +2503,20 @@ const storybookScripts = (rootFolder)=>{
1574
2503
  'build-storybook': `storybook build -c ${quote(`${folder}/.storybook`)} -o ${quote(`${folder}/storybook-static`)}`
1575
2504
  };
1576
2505
  };
1577
- const addStorybook = async ()=>{
2506
+ const storybook_addStorybook = async ()=>{
1578
2507
  const config = config_file_ConfigFile.Instance.data;
1579
- if ((!config.useReact || config.storybookFramework && '@storybook/react-vite' !== config.storybookFramework) && !await (0, prompts_namespaceObject.confirm)({
1580
- message: 'Configure React scaffolding with @storybook/react-vite?',
2508
+ if ((!config.frontend?.react || config.frontend?.react?.storybookFramework && config.frontend?.react?.storybookFramework !== storybook_storybookFrameworkPackage) && !await interaction_confirm({
2509
+ key: 'configureReact',
2510
+ requestRequired: true,
2511
+ message: `Configure React scaffolding with ${storybook_storybookFrameworkPackage}?`,
1581
2512
  default: false
1582
2513
  })) return [];
1583
2514
  const root = new project_root_ProjectRoot().path;
1584
2515
  const manifestFile = new file_system_File(external_node_path_default().join(root, 'package.json'));
1585
2516
  const manifest = JSON.parse(manifestFile.data);
1586
- const selected = await addPackageScripts(manifestFile, storybookScripts(config.rootFolder));
2517
+ const selected = await addPackageScripts(manifestFile, storybookScripts(config.project.rootFolder));
1587
2518
  const folder = new file_system_Folder(root).subitem([
1588
- config.rootFolder,
2519
+ config.project.rootFolder,
1589
2520
  'presentation',
1590
2521
  'react',
1591
2522
  '.storybook'
@@ -1594,12 +2525,16 @@ const addStorybook = async ()=>{
1594
2525
  const file = new file_system_File(external_node_path_default().join(folder.path, name));
1595
2526
  if (!file.exists || file.data !== content) file.data = content;
1596
2527
  }
1597
- if (!config.useReact || '@storybook/react-vite' !== config.storybookFramework) config_file_ConfigFile.write({
1598
- ...config,
1599
- useReact: true,
1600
- storybookFramework: '@storybook/react-vite'
2528
+ if (!config.frontend?.react || config.frontend?.react?.storybookFramework !== storybook_storybookFrameworkPackage) config_file_ConfigFile.update({
2529
+ frontend: {
2530
+ ...config.frontend,
2531
+ react: {
2532
+ ...config.frontend?.react,
2533
+ storybookFramework: storybook_storybookFrameworkPackage
2534
+ }
2535
+ }
1601
2536
  });
1602
- const buildFolder = external_node_path_default().posix.join(config.rootFolder.replaceAll('\\', '/'), 'presentation/react/storybook-static');
2537
+ const buildFolder = external_node_path_default().posix.join(config.project.rootFolder.replaceAll('\\', '/'), 'presentation/react/storybook-static');
1603
2538
  addGitignoreEntry(root, `/${buildFolder}/`);
1604
2539
  const dependencies = {
1605
2540
  ...manifest.dependencies,
@@ -1607,7 +2542,7 @@ const addStorybook = async ()=>{
1607
2542
  };
1608
2543
  const missing = [
1609
2544
  'storybook',
1610
- '@storybook/react-vite',
2545
+ storybook_storybookFrameworkPackage,
1611
2546
  'vite',
1612
2547
  '@vitejs/plugin-react'
1613
2548
  ].filter((name)=>!dependencies[name]);
@@ -1628,11 +2563,42 @@ const addStorybook = async ()=>{
1628
2563
  })
1629
2564
  ];
1630
2565
  };
1631
- const integrationFolder = 'specs/integration';
1632
- const testcontainersScripts = {
1633
- 'test:integration': `vitest run --config ${integrationFolder}/vitest.config.ts --reporter=dot --silent=passed-only`
2566
+ const wire_branches_defaultEnvBranches = {
2567
+ names: [
2568
+ 'test',
2569
+ 'development',
2570
+ 'production'
2571
+ ],
2572
+ test: 'test'
1634
2573
  };
1635
- const testcontainersVitestConfig = (inlineHandlersNext)=>{
2574
+ const wire_branches_envBranches = ()=>{
2575
+ const configured = config_file_ConfigFile.exists ? config_file_ConfigFile.Instance.data.backend?.envBranches : void 0;
2576
+ const { names, test } = configured ?? wire_branches_defaultEnvBranches;
2577
+ return {
2578
+ names,
2579
+ test,
2580
+ primary: names.filter((name)=>name !== test),
2581
+ custom: Boolean(configured)
2582
+ };
2583
+ };
2584
+ const offersTestImplementation = ()=>{
2585
+ const backend = config_file_ConfigFile.exists ? config_file_ConfigFile.Instance.data.backend : void 0;
2586
+ return !(backend?.domainFirstPackages.includes('@domain-first/wire') && backend.envBranches && void 0 === backend.envBranches.test);
2587
+ };
2588
+ const envBranchedWireArgument = (testWire, primaryWire)=>{
2589
+ const { test, primary } = wire_branches_envBranches();
2590
+ return `{\n${[
2591
+ ...test ? [
2592
+ ` ${test}: ${testWire}`
2593
+ ] : [],
2594
+ ...primary.map((name)=>` ${name}: ${primaryWire}`)
2595
+ ].join(',\n')}\n}`;
2596
+ };
2597
+ const integrationFolder = 'specs/integration';
2598
+ const testcontainersScripts = {
2599
+ 'test:integration': `vitest run --config ${integrationFolder}/vitest.config.ts --reporter=dot --silent=passed-only`
2600
+ };
2601
+ const testcontainersVitestConfig = (inlineHandlersNext)=>{
1636
2602
  const server = inlineHandlersNext ? `,
1637
2603
  server: {
1638
2604
  deps: {
@@ -1761,8 +2727,8 @@ const addTestcontainers = async ()=>{
1761
2727
  ...manifest.devDependencies
1762
2728
  };
1763
2729
  const selected = await addPackageScripts(manifestFile, testcontainersScripts);
1764
- const withPrisma = new file_system_File(external_node_path_default().resolve(root, config.rootFolder, 'shared-kernel/infrastructure/prisma/prisma.config.ts')).exists;
1765
- const migrationCommand = withPrisma ? `npx ${prismaScripts(config.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}` : void 0;
2730
+ const withPrisma = new file_system_File(external_node_path_default().resolve(root, config.project.rootFolder, 'shared-kernel/infrastructure/prisma/prisma.config.ts')).exists;
2731
+ const migrationCommand = withPrisma ? `npx ${prismaScripts(config.project.rootFolder)['prisma:migration:apply'].replace(' --advance-ref db', '')}` : void 0;
1766
2732
  const folder = external_node_path_default().join(root, integrationFolder);
1767
2733
  testcontainers_stageFile(external_node_path_default().join(folder, 'vitest.config.ts'), testcontainersVitestConfig(Boolean(dependencies['@domain-first/handlers-next'])));
1768
2734
  testcontainers_stageFile(external_node_path_default().join(folder, 'global-setup.ts'), testcontainersGlobalSetup(migrationCommand));
@@ -1794,6 +2760,9 @@ const addTestcontainers = async ()=>{
1794
2760
  ...excludedFromUnitTests ? [] : [
1795
2761
  `Add '${integrationFolder}/**' to test.exclude in vitest.config.ts, so unit tests skip integration specs.`
1796
2762
  ],
2763
+ ...wire_branches_envBranches().custom ? [
2764
+ `${integrationFolder} runs with NODE_ENV=development and ${integrationFolder}/setup-env.ts requires it, but your envBranchedWire branches are custom: make currentBranch in shared-kernel/wiring/env-branched-wire.ts return the branch for integration specs, and adjust setup-env.ts.`
2765
+ ] : [],
1797
2766
  'Docker must be running for integration specs.',
1798
2767
  ...describeScripts(selected, {
1799
2768
  'test:integration': `run integration specs from ${integrationFolder} against PostgreSQL in a container`
@@ -1841,8 +2810,10 @@ export default defineConfig({
1841
2810
  };
1842
2811
  const addVitest = async ()=>{
1843
2812
  const config = config_file_ConfigFile.Instance.data;
1844
- if (config.testingLibrary && 'vitest' !== config.testingLibrary && !await (0, prompts_namespaceObject.confirm)({
1845
- message: `Replace testing library "${config.testingLibrary}" with vitest for generated tests?`,
2813
+ if (config_file_ConfigFile.backend.testingLibrary && 'vitest' !== config_file_ConfigFile.backend.testingLibrary && !await interaction_confirm({
2814
+ key: 'replaceTestingLibrary',
2815
+ requestRequired: true,
2816
+ message: `Replace testing library "${config_file_ConfigFile.backend.testingLibrary}" with vitest for generated tests?`,
1846
2817
  default: false
1847
2818
  })) return [];
1848
2819
  const root = new project_root_ProjectRoot().path;
@@ -1854,11 +2825,13 @@ const addVitest = async ()=>{
1854
2825
  };
1855
2826
  const selected = await addPackageScripts(manifestFile, vitestScripts);
1856
2827
  const configFile = new file_system_File(external_node_path_default().join(root, 'vitest.config.ts'));
1857
- const content = vitestConfig(config.rootFolder, Boolean(dependencies['@domain-first/handlers-next']));
2828
+ const content = vitestConfig(config.project.rootFolder, Boolean(dependencies['@domain-first/handlers-next']));
1858
2829
  if (!configFile.exists || configFile.data !== content) configFile.data = content;
1859
- if ('vitest' !== config.testingLibrary) config_file_ConfigFile.write({
1860
- ...config,
1861
- testingLibrary: 'vitest'
2830
+ if ('vitest' !== config_file_ConfigFile.backend.testingLibrary) config_file_ConfigFile.update({
2831
+ backend: {
2832
+ ...config_file_ConfigFile.backend,
2833
+ testingLibrary: 'vitest'
2834
+ }
1862
2835
  });
1863
2836
  addGitignoreEntry(root, '/coverage/');
1864
2837
  const missing = [
@@ -1925,35 +2898,55 @@ const printNextSteps = (nextSteps)=>{
1925
2898
  if (sections.length) console.log(sections.join('\n\n'));
1926
2899
  };
1927
2900
  const savePendingChanges = async ()=>{
1928
- const overwrittenFiles = filesToOverwrite();
2901
+ assertAnswersConsumed();
2902
+ const overwrittenFiles = filesToOverwrite({
2903
+ changedOnly: isNonInteractive()
2904
+ });
2905
+ if (isNonInteractive() && overwrittenFiles.length && !answerFor('overwrite', false)) throw new RequestError('OVERWRITE_REQUIRED', 'Set overwrite to true to replace existing files.', {
2906
+ files: overwrittenFiles.map((file)=>external_node_path_default().relative(new project_root_ProjectRoot().path, file).split(external_node_path_default().sep).join('/'))
2907
+ });
1929
2908
  if (overwrittenFiles.length) {
1930
2909
  const root = new project_root_ProjectRoot().path;
1931
- console.log('These files already exist and will be overwritten:');
1932
- for (const filePath of overwrittenFiles)console.log(` ${external_node_path_default().relative(root, filePath)}`);
1933
- const overwrite = await (0, prompts_namespaceObject.confirm)({
2910
+ report('These files already exist and will be overwritten:');
2911
+ for (const filePath of overwrittenFiles)report(` ${external_node_path_default().relative(root, filePath)}`);
2912
+ const overwrite = await interaction_confirm({
2913
+ key: 'overwrite',
1934
2914
  message: 'Overwrite them?',
1935
2915
  default: false
1936
2916
  });
1937
2917
  if (!overwrite) {
1938
- file_system_discardPendingChanges();
1939
- console.log('Cancelled: nothing was written.');
2918
+ discardPendingChanges();
2919
+ report('Cancelled: nothing was written.');
1940
2920
  return false;
1941
2921
  }
1942
2922
  }
1943
2923
  writePendingChanges();
1944
2924
  return true;
1945
2925
  };
1946
- const withHandlersRest = ()=>config_file_ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/handlers-rest');
2926
+ const withHandlersRest = ()=>config_file_ConfigFile.Instance.data.backend?.domainFirstPackages.includes('@domain-first/handlers-rest') ?? false;
1947
2927
  const created = (...segments)=>new file_system_File(external_node_path_default().join(new project_root_ProjectRoot().path, ...segments)).exists;
1948
- const createdInRoot = (...segments)=>created(config_file_ConfigFile.Instance.data.rootFolder, ...segments);
2928
+ const createdInRoot = (...segments)=>created(config_file_ConfigFile.Instance.data.project.rootFolder, ...segments);
2929
+ const integrationIds = [
2930
+ 'storybook',
2931
+ 'rest-endpoint-generator',
2932
+ 'in-memory-db',
2933
+ 'prisma',
2934
+ 'vitest',
2935
+ 'playwright',
2936
+ 'testcontainers',
2937
+ 'openapi',
2938
+ 'orval'
2939
+ ];
1949
2940
  const integrations = [
1950
2941
  {
2942
+ id: 'storybook',
1951
2943
  name: 'Storybook (React + Vite)',
1952
2944
  group: 'frontend',
1953
- run: addStorybook,
2945
+ run: storybook_addStorybook,
1954
2946
  applied: ()=>createdInRoot('presentation/react/.storybook/main.ts')
1955
2947
  },
1956
2948
  {
2949
+ id: 'rest-endpoint-generator',
1957
2950
  name: 'REST endpoint generator',
1958
2951
  group: 'backend',
1959
2952
  run: addRestEndpointGenerator,
@@ -1961,36 +2954,42 @@ const integrations = [
1961
2954
  applied: restEndpointGeneratorApplied
1962
2955
  },
1963
2956
  {
2957
+ id: 'in-memory-db',
1964
2958
  name: 'In-memory DB',
1965
2959
  group: 'backend',
1966
2960
  run: addInMemoryDb,
1967
2961
  applied: inMemoryDbApplied
1968
2962
  },
1969
2963
  {
2964
+ id: 'prisma',
1970
2965
  name: 'Prisma 8 (PostgreSQL, RC)',
1971
2966
  group: 'backend',
1972
2967
  run: addPrisma,
1973
2968
  applied: ()=>createdInRoot('shared-kernel/infrastructure/prisma/prisma.config.ts')
1974
2969
  },
1975
2970
  {
2971
+ id: 'vitest',
1976
2972
  name: 'Vitest',
1977
2973
  group: 'backend',
1978
2974
  run: addVitest,
1979
2975
  applied: ()=>created('vitest.config.ts')
1980
2976
  },
1981
2977
  {
2978
+ id: 'playwright',
1982
2979
  name: 'Playwright',
1983
2980
  group: 'frontend',
1984
2981
  run: addPlaywright,
1985
2982
  applied: ()=>created('playwright.config.ts')
1986
2983
  },
1987
2984
  {
2985
+ id: 'testcontainers',
1988
2986
  name: 'Integration tests (Testcontainers, PostgreSQL)',
1989
2987
  group: 'backend',
1990
2988
  run: addTestcontainers,
1991
2989
  applied: ()=>created('specs/integration/vitest.config.ts')
1992
2990
  },
1993
2991
  {
2992
+ id: 'openapi',
1994
2993
  name: 'OpenAPI',
1995
2994
  group: 'backend',
1996
2995
  run: addOpenapi,
@@ -1998,6 +2997,7 @@ const integrations = [
1998
2997
  applied: ()=>created(openapiScriptPath)
1999
2998
  },
2000
2999
  {
3000
+ id: 'orval',
2001
3001
  name: 'Orval (API client)',
2002
3002
  group: 'frontend',
2003
3003
  run: addOrval,
@@ -2005,8 +3005,8 @@ const integrations = [
2005
3005
  applied: ()=>createdInRoot('presentation/react/data-layer/orval.config.ts') || createdInRoot('presentation/data-layer/orval.config.ts')
2006
3006
  }
2007
3007
  ];
2008
- const addIntegration = async ()=>{
2009
- const available = integrations.filter(({ available })=>available?.() ?? true).map((value)=>({
3008
+ const addIntegration = async ({ save = true } = {})=>{
3009
+ const available = integrations.filter(({ group, available })=>('backend' !== group || Boolean(config_file_ConfigFile.Instance.data.backend)) && (available?.() ?? true)).map((value)=>({
2010
3010
  value,
2011
3011
  applied: value.applied()
2012
3012
  }));
@@ -2027,16 +3027,213 @@ const addIntegration = async ()=>{
2027
3027
  ...section('New integrations', false),
2028
3028
  ...section('Already applied (select to reapply)', true)
2029
3029
  ];
2030
- const selected = await (0, prompts_namespaceObject.checkbox)({
3030
+ const selected = await interaction_checkbox({
3031
+ key: 'integrations',
3032
+ id: (integration)=>integration.id,
2031
3033
  message: 'Integrations:',
2032
3034
  choices,
2033
3035
  pageSize: choices.length
2034
3036
  });
2035
3037
  const nextSteps = [];
2036
3038
  for (const integration of integrations.filter((value)=>selected.includes(value)))nextSteps.push(...await integration.run());
2037
- if (await savePendingChanges()) printNextSteps(nextSteps);
3039
+ if (save && await savePendingChanges()) printNextSteps(nextSteps);
3040
+ return nextSteps;
3041
+ };
3042
+ const integrationDescriptions = ()=>integrations.map((integration)=>({
3043
+ id: integration.id,
3044
+ name: integration.name,
3045
+ group: integration.group,
3046
+ available: ('backend' !== integration.group || Boolean(config_file_ConfigFile.Instance.data.backend)) && (integration.available?.() ?? true)
3047
+ }));
3048
+ const agent_requests_name = implementationLabelSchema;
3049
+ const agent_requests_nestedName = external_zod_default().string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*(?:\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*)*$/);
3050
+ const agent_requests_id = external_zod_default().string().min(1);
3051
+ const agent_requests_implementation = external_zod_default().strictObject({
3052
+ type: agent_requests_name,
3053
+ save: external_zod_default().boolean().optional().describe('Remember this ordinary type for future runs. Default: false.')
3054
+ });
3055
+ const agent_requests_dependencies = external_zod_default().record(external_zod_default().string().regex(/^[A-Z][A-Za-z0-9]*$/), external_zod_default().array(agent_requests_id)).describe('Implementation/class name -> exact module IDs from --describe. Omitted entries keep suggested dependencies; [] selects none.');
3056
+ const common = {
3057
+ overwrite: external_zod_default().boolean().optional(),
3058
+ dryRun: external_zod_default().boolean().optional()
3059
+ };
3060
+ const agent_requests_owner = {
3061
+ context: agent_requests_name.describe('A bounded-context name, or shared-kernel.')
3062
+ };
3063
+ const agent_requests_wired = {
3064
+ dependencies: agent_requests_dependencies.optional()
3065
+ };
3066
+ const agent_requests_implementations = {
3067
+ implementation: agent_requests_implementation,
3068
+ testImplementation: agent_requests_implementation.optional(),
3069
+ ...agent_requests_wired
3070
+ };
3071
+ const named = {
3072
+ ...common,
3073
+ ...agent_requests_owner,
3074
+ name: agent_requests_name
2038
3075
  };
2039
- new Set([
3076
+ const operation = (value, shape)=>external_zod_default().strictObject({
3077
+ operation: external_zod_default().literal(value),
3078
+ ...shape
3079
+ });
3080
+ const scaffoldRequestSchema = external_zod_default().discriminatedUnion('operation', [
3081
+ operation('bounded-context', {
3082
+ ...common,
3083
+ name: agent_requests_name.refine((value)=>'shared-kernel' !== value, 'shared-kernel is reserved for the Shared Kernel.')
3084
+ }),
3085
+ operation('aggregate', {
3086
+ ...named,
3087
+ withRepository: external_zod_default().boolean().optional(),
3088
+ implementation: agent_requests_implementation.optional(),
3089
+ testImplementation: agent_requests_implementation.optional(),
3090
+ ...agent_requests_wired
3091
+ }),
3092
+ operation('entity', {
3093
+ ...named,
3094
+ aggregate: agent_requests_name.optional()
3095
+ }),
3096
+ operation('value-object', {
3097
+ ...named,
3098
+ aggregate: agent_requests_name.optional()
3099
+ }),
3100
+ operation('error', {
3101
+ ...named,
3102
+ namespace: agent_requests_name.optional()
3103
+ }),
3104
+ operation('error-namespace', named),
3105
+ operation('domain-service', {
3106
+ ...named,
3107
+ ...agent_requests_wired
3108
+ }),
3109
+ operation('application-service', {
3110
+ ...named,
3111
+ ...agent_requests_wired
3112
+ }),
3113
+ operation('infrastructure-service', {
3114
+ ...named,
3115
+ ...agent_requests_wired
3116
+ }),
3117
+ operation('presentation-service', {
3118
+ ...named,
3119
+ ...agent_requests_wired
3120
+ }),
3121
+ operation('use-case', {
3122
+ ...named,
3123
+ ...agent_requests_wired
3124
+ }),
3125
+ operation('command', {
3126
+ ...named,
3127
+ ...agent_requests_implementations
3128
+ }),
3129
+ operation('query', {
3130
+ ...named,
3131
+ ...agent_requests_implementations
3132
+ }),
3133
+ operation('port', {
3134
+ ...named,
3135
+ ...agent_requests_implementations
3136
+ }),
3137
+ operation('implementation', {
3138
+ ...common,
3139
+ ...agent_requests_owner,
3140
+ contract: agent_requests_id.describe('Exact contract ID from --describe.'),
3141
+ implementation: agent_requests_implementation,
3142
+ environments: external_zod_default().array(agent_requests_name).min(1).optional().describe('Required when the contract wire is envBranchedWire; omit it otherwise.'),
3143
+ ...agent_requests_wired
3144
+ }),
3145
+ operation('endpoint', {
3146
+ ...common,
3147
+ ...agent_requests_owner,
3148
+ controller: agent_requests_name,
3149
+ method: external_zod_default()["enum"]([
3150
+ 'get',
3151
+ 'post',
3152
+ 'put',
3153
+ 'patch',
3154
+ 'delete'
3155
+ ]),
3156
+ path: external_zod_default().string().regex(/^(?:\/?(?:[a-zA-Z0-9_-]+|:[a-zA-Z][a-zA-Z0-9_]*))*\/?$/),
3157
+ handler: agent_requests_id.optional().describe('Exact handler module ID from --describe. Required when the context has wired queries, commands or use cases; omit it otherwise.')
3158
+ }),
3159
+ operation('wire-dependency', {
3160
+ ...common,
3161
+ ...agent_requests_owner,
3162
+ module: agent_requests_id.describe('Exact wiring target ID, including implementation class, from --describe.'),
3163
+ dependencies: agent_requests_dependencies
3164
+ }),
3165
+ operation('move', {
3166
+ ...common,
3167
+ ...agent_requests_owner,
3168
+ module: agent_requests_id.describe('Exact unit ID from --describe.'),
3169
+ targetContext: agent_requests_name.optional(),
3170
+ name: agent_requests_name.optional(),
3171
+ aggregate: agent_requests_name.optional()
3172
+ })
3173
+ ]);
3174
+ const reactRequestSchema = external_zod_default().discriminatedUnion('operation', [
3175
+ operation('page', {
3176
+ ...common,
3177
+ name: agent_requests_nestedName
3178
+ }),
3179
+ operation('widget', {
3180
+ ...common,
3181
+ name: agent_requests_nestedName,
3182
+ widgetType: external_zod_default()["enum"]([
3183
+ 'monolithic',
3184
+ 'separated',
3185
+ 'headless'
3186
+ ]).optional()
3187
+ }),
3188
+ operation('ui-kit-component', {
3189
+ ...common,
3190
+ name: agent_requests_name
3191
+ }),
3192
+ operation('shared-hook', {
3193
+ ...common,
3194
+ name: agent_requests_name
3195
+ }),
3196
+ operation('move-page', {
3197
+ ...common,
3198
+ module: agent_requests_nestedName,
3199
+ name: agent_requests_nestedName,
3200
+ moveRoute: external_zod_default().boolean().optional().describe('With Next.js and a route at the page path: move it too (default true). Omit it without such a route.')
3201
+ }),
3202
+ operation('move-widget', {
3203
+ ...common,
3204
+ module: agent_requests_nestedName,
3205
+ name: agent_requests_nestedName
3206
+ })
3207
+ ]);
3208
+ const agent_requests_relativePath = external_zod_default().string().regex(/^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*$/).refine((value)=>!value.split('/').some((part)=>'.' === part || '..' === part), 'Use a project-relative path without . or .. segments.');
3209
+ const integrationRequestSchema = operation('add', {
3210
+ ...common,
3211
+ integrations: external_zod_default().array(external_zod_default()["enum"](integrationIds)).min(1),
3212
+ nextAdapter: external_zod_default().boolean().optional(),
3213
+ configureReact: external_zod_default().boolean().optional(),
3214
+ replaceTestingLibrary: external_zod_default().boolean().optional(),
3215
+ withService: external_zod_default().boolean().optional(),
3216
+ routePrefix: external_zod_default().string().regex(/^\/?[a-zA-Z0-9_/-]*$/).optional(),
3217
+ openapiPath: agent_requests_relativePath.optional(),
3218
+ withExtractor: external_zod_default().boolean().optional(),
3219
+ swaggerPage: external_zod_default().boolean().optional(),
3220
+ targets: external_zod_default().array(external_zod_default()["enum"]([
3221
+ 'hooks',
3222
+ 'client'
3223
+ ])).min(1).optional(),
3224
+ scriptConflicts: external_zod_default().record(agent_requests_id, external_zod_default()["enum"]([
3225
+ 'keep',
3226
+ 'replace',
3227
+ 'rename'
3228
+ ])).optional(),
3229
+ scriptNames: external_zod_default().record(agent_requests_id, external_zod_default().string().regex(/^[a-zA-Z0-9:_-]+$/)).optional()
3230
+ });
3231
+ const requestSchemaFor = (command)=>({
3232
+ 'df-scaffold': scaffoldRequestSchema,
3233
+ 'df-react': reactRequestSchema,
3234
+ 'df-integration': integrationRequestSchema
3235
+ })[command];
3236
+ const ignoredFolders = new Set([
2040
3237
  'node_modules',
2041
3238
  '.git',
2042
3239
  '.next',
@@ -2046,6 +3243,137 @@ new Set([
2046
3243
  'coverage',
2047
3244
  'storybook-static'
2048
3245
  ]);
3246
+ const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
3247
+ const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
3248
+ const module_move_walk = (folder)=>{
3249
+ if (!external_node_fs_default().existsSync(folder)) return [];
3250
+ return external_node_fs_default().readdirSync(folder, {
3251
+ withFileTypes: true
3252
+ }).flatMap((entry)=>{
3253
+ const entryPath = external_node_path_default().join(folder, entry.name);
3254
+ if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : module_move_walk(entryPath);
3255
+ return entry.isFile() ? [
3256
+ entryPath
3257
+ ] : [];
3258
+ });
3259
+ };
3260
+ const toPosix = (value)=>value.split(external_node_path_default().sep).join('/');
3261
+ const readAliases = (projectRoot)=>{
3262
+ const tsconfig = external_node_path_default().join(projectRoot, 'tsconfig.json');
3263
+ if (!external_node_fs_default().existsSync(tsconfig)) return [];
3264
+ try {
3265
+ const { compilerOptions = {} } = JSON.parse(stripJsonComments(external_node_fs_default().readFileSync(tsconfig, 'utf8')));
3266
+ const base = external_node_path_default().resolve(projectRoot, compilerOptions.baseUrl ?? '.');
3267
+ return Object.entries(compilerOptions.paths ?? {}).filter(([pattern, targets])=>pattern.endsWith('*') && targets[0]?.endsWith('*')).map(([pattern, [target]])=>({
3268
+ prefix: pattern.slice(0, -1),
3269
+ target: external_node_path_default().resolve(base, target.slice(0, -1))
3270
+ }));
3271
+ } catch {
3272
+ return [];
3273
+ }
3274
+ };
3275
+ const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
3276
+ const reExportPattern = /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*(['"])([^'"\n]+)\1/g;
3277
+ const importPaths = (file)=>{
3278
+ const withoutExtension = file.replace(codeExtension, '');
3279
+ return 'index' === external_node_path_default().basename(withoutExtension) ? [
3280
+ withoutExtension,
3281
+ external_node_path_default().dirname(withoutExtension)
3282
+ ] : [
3283
+ withoutExtension
3284
+ ];
3285
+ };
3286
+ const projectImports = (projectRoot)=>{
3287
+ const aliases = readAliases(projectRoot);
3288
+ const resolve = (specifier, fromFile)=>{
3289
+ if (specifier.startsWith('.')) return {
3290
+ resolved: external_node_path_default().resolve(external_node_path_default().dirname(fromFile), specifier),
3291
+ alias: void 0
3292
+ };
3293
+ const alias = aliases.find(({ prefix })=>specifier.startsWith(prefix));
3294
+ return alias ? {
3295
+ resolved: external_node_path_default().resolve(alias.target, specifier.slice(alias.prefix.length)),
3296
+ alias
3297
+ } : void 0;
3298
+ };
3299
+ const specifierFor = (fromFile, toPath, alias)=>{
3300
+ const aliased = alias && toPosix(external_node_path_default().relative(alias.target, toPath));
3301
+ if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
3302
+ const relative = toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toPath));
3303
+ return relative.startsWith('.') ? relative : `./${relative}`;
3304
+ };
3305
+ const codeFiles = new Map(module_move_walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
3306
+ file,
3307
+ external_node_fs_default().readFileSync(file, 'utf8')
3308
+ ]));
3309
+ const importsOf = (file)=>[
3310
+ ...(codeFiles.get(file) ?? '').matchAll(specifierPattern)
3311
+ ].map(([, , , specifier])=>resolve(specifier, file)?.resolved).filter((resolved)=>!!resolved);
3312
+ return {
3313
+ resolve,
3314
+ specifierFor,
3315
+ codeFiles,
3316
+ importsOf
3317
+ };
3318
+ };
3319
+ const stageModuleMove = ({ projectRoot, stopAt, moves, movedPath, rename, everyFile = (content)=>content, stopAtFor })=>{
3320
+ const stopFor = (file)=>stopAtFor?.(file) ?? stopAt;
3321
+ const { resolve, specifierFor, codeFiles } = projectImports(projectRoot);
3322
+ const barrels = new Set();
3323
+ const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
3324
+ for(let found = true; found;){
3325
+ found = false;
3326
+ for (const [file, content] of codeFiles){
3327
+ if (moves.has(file) || isBarrel(file)) continue;
3328
+ const reExportsModule = [
3329
+ ...content.matchAll(reExportPattern)
3330
+ ].some(([, , specifier])=>{
3331
+ const resolution = resolve(specifier, file);
3332
+ return !!resolution && (!!movedPath(resolution.resolved) || isBarrel(resolution.resolved));
3333
+ });
3334
+ if (reExportsModule) {
3335
+ for (const importPath of importPaths(file))barrels.add(importPath);
3336
+ found = true;
3337
+ }
3338
+ }
3339
+ }
3340
+ const rewrite = (content, oldFile, newFile)=>{
3341
+ let referencesModule = false;
3342
+ const rewritten = content.replace(specifierPattern, (match, keyword, quote, specifier)=>{
3343
+ const resolution = resolve(specifier, oldFile);
3344
+ if (!resolution) return match;
3345
+ const moved = movedPath(resolution.resolved);
3346
+ if (moved || isBarrel(resolution.resolved)) referencesModule = true;
3347
+ if (!moved && oldFile === newFile) return match;
3348
+ const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
3349
+ return `${keyword}${quote}${next}${quote}`;
3350
+ });
3351
+ const changed = everyFile(rewritten);
3352
+ if (!referencesModule && !moves.has(oldFile)) return changed;
3353
+ return rename(changed, {
3354
+ moved: moves.has(oldFile)
3355
+ });
3356
+ };
3357
+ for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new file_system_File(file).moveTo(newFile, stopFor(file));
3358
+ const updated = [];
3359
+ for (const [file, content] of codeFiles){
3360
+ const newFile = moves.get(file);
3361
+ const next = rewrite(content, file, newFile ?? file);
3362
+ if (newFile && newFile !== file) {
3363
+ new file_system_File(newFile).data = next;
3364
+ new file_system_File(file).delete(stopFor(file));
3365
+ } else if (next !== content) {
3366
+ new file_system_File(file).update(next);
3367
+ if (!newFile) updated.push(file);
3368
+ }
3369
+ }
3370
+ return {
3371
+ moves: [
3372
+ ...moves
3373
+ ].filter(([from, to])=>from !== to),
3374
+ updated
3375
+ };
3376
+ };
2049
3377
  const serviceLayout = (layer)=>({
2050
3378
  title: `${layer[0].toUpperCase()}${layer.slice(1)} services`,
2051
3379
  core: (ClassName)=>`${ClassName}${layer[0].toUpperCase()}${layer.slice(1)}Service`,
@@ -2090,34 +3418,2303 @@ const domainModelLayout = (kind)=>{
2090
3418
  sharedKernel: true
2091
3419
  };
2092
3420
  };
2093
- domainModelLayout('entity'), domainModelLayout('value-object'), serviceLayout('domain'), serviceLayout('application'), serviceLayout('infrastructure'), serviceLayout('presentation'), handlerLayout('command'), handlerLayout('query');
2094
- const help = `Usage: df-integration
3421
+ const aggregateOwnFiles = (name)=>[
3422
+ `${name}.aggregate-root.ts`,
3423
+ `${name}.aggregate-root.spec.ts`,
3424
+ `${name}-repository.ts`,
3425
+ `${name}-repository.spec.ts`,
3426
+ 'index.ts'
3427
+ ];
3428
+ const kindLayouts = {
3429
+ aggregate: {
3430
+ title: 'Aggregates',
3431
+ core: (ClassName)=>`${ClassName}Repository`,
3432
+ files: ({ name }, labels)=>[
3433
+ ...aggregateOwnFiles(name).map((file)=>`domain/aggregates/${name}/${file}`),
3434
+ ...labels.map((label)=>`infrastructure/repositories/${label}/${label}-${name}-repository.ts`),
3435
+ `wiring/repositories/wire-${name}-repository.ts`
3436
+ ],
3437
+ implementations: 'infrastructure/repositories',
3438
+ wired: true,
3439
+ sharedKernel: false
3440
+ },
3441
+ entity: domainModelLayout('entity'),
3442
+ 'value-object': domainModelLayout('value-object'),
3443
+ 'domain-service': serviceLayout('domain'),
3444
+ 'application-service': serviceLayout('application'),
3445
+ 'infrastructure-service': serviceLayout('infrastructure'),
3446
+ 'presentation-service': serviceLayout('presentation'),
3447
+ 'use-case': {
3448
+ title: 'Use cases',
3449
+ core: (ClassName)=>`${ClassName}UseCase`,
3450
+ files: ({ name })=>[
3451
+ `application/use-cases/${name}-use-case.ts`,
3452
+ `application/use-cases/${name}-use-case.spec.ts`,
3453
+ `wiring/use-cases/wire-${name}-use-case.ts`
3454
+ ],
3455
+ wired: true,
3456
+ sharedKernel: false
3457
+ },
3458
+ command: handlerLayout('command'),
3459
+ query: handlerLayout('query'),
3460
+ port: {
3461
+ title: 'Ports',
3462
+ core: (ClassName)=>ClassName,
3463
+ files: ({ name }, labels)=>[
3464
+ `application/ports/${name}.ts`,
3465
+ `application/ports/${name}.spec.ts`,
3466
+ ...labels.map((label)=>`infrastructure/application-adapters/${label}/${label}-${name}.ts`),
3467
+ `wiring/application-ports/wire-${name}.ts`
3468
+ ],
3469
+ implementations: 'infrastructure/application-adapters',
3470
+ wired: true,
3471
+ sharedKernel: true
3472
+ }
3473
+ };
3474
+ const subfolders = (folder)=>external_node_fs_default().existsSync(folder) ? external_node_fs_default().readdirSync(folder, {
3475
+ withFileTypes: true
3476
+ }).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).sort() : [];
3477
+ const namesBySuffix = (folder, suffix)=>external_node_fs_default().existsSync(folder) ? external_node_fs_default().readdirSync(folder).filter((file)=>file.endsWith(suffix) && !file.endsWith('.spec.ts')).map((file)=>file.slice(0, -suffix.length)).sort() : [];
3478
+ const labelsOf = (ownerPath, kind, name)=>{
3479
+ const { implementations } = kindLayouts[kind];
3480
+ if (!implementations) return [];
3481
+ return subfolders(external_node_path_default().join(ownerPath, implementations)).filter((label)=>kindLayouts[kind].files({
3482
+ ownerPath,
3483
+ name
3484
+ }, [
3485
+ label
3486
+ ]).some((file)=>file.startsWith(`${implementations}/`) && external_node_fs_default().existsSync(external_node_path_default().join(ownerPath, file))));
3487
+ };
3488
+ const aggregatesOf = (ownerPath)=>subfolders(external_node_path_default().join(ownerPath, 'domain/aggregates')).filter((name)=>external_node_fs_default().existsSync(external_node_path_default().join(ownerPath, 'domain/aggregates', name, `${name}.aggregate-root.ts`)));
3489
+ const findBackendUnits = (ownerPath)=>{
3490
+ const unit = (kind, name, aggregate)=>({
3491
+ kind,
3492
+ name,
3493
+ ownerPath,
3494
+ aggregate,
3495
+ labels: labelsOf(ownerPath, kind, name)
3496
+ });
3497
+ const aggregates = aggregatesOf(ownerPath);
3498
+ const inAggregates = (kind)=>aggregates.flatMap((aggregate)=>namesBySuffix(external_node_path_default().join(ownerPath, 'domain/aggregates', aggregate, 'entity' === kind ? 'entities' : 'value-objects'), `.${kind}.ts`).map((name)=>unit(kind, name, aggregate)));
3499
+ const at = (folder, suffix, kind)=>namesBySuffix(external_node_path_default().join(ownerPath, folder), suffix).map((name)=>unit(kind, name));
3500
+ return [
3501
+ ...aggregates.map((name)=>unit('aggregate', name)),
3502
+ ...inAggregates('entity'),
3503
+ ...at('domain/entities', '.entity.ts', 'entity'),
3504
+ ...inAggregates('value-object'),
3505
+ ...at('domain/value-objects', '.value-object.ts', 'value-object'),
3506
+ ...at('domain/services', '-domain-service.ts', 'domain-service'),
3507
+ ...at('application/ports', '.ts', 'port'),
3508
+ ...at('application/queries', '-query.ts', 'query'),
3509
+ ...at('application/commands', '-command.ts', 'command'),
3510
+ ...at('application/use-cases', '-use-case.ts', 'use-case'),
3511
+ ...at('application/services', '-application-service.ts', 'application-service'),
3512
+ ...at('infrastructure/services', '-infrastructure-service.ts', 'infrastructure-service'),
3513
+ ...at('presentation/services', '-presentation-service.ts', 'presentation-service')
3514
+ ];
3515
+ };
3516
+ const kebabName = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
3517
+ const lowerFirst = (value)=>value[0].toLowerCase() + value.slice(1);
3518
+ const unitMoves = (unit, target)=>{
3519
+ const layout = kindLayouts[unit.kind];
3520
+ const from = layout.files(unit, unit.labels);
3521
+ const to = layout.files(target, unit.labels);
3522
+ const moves = new Map();
3523
+ from.forEach((file, index)=>{
3524
+ const oldPath = external_node_path_default().join(unit.ownerPath, file);
3525
+ if (external_node_fs_default().existsSync(oldPath)) moves.set(oldPath, external_node_path_default().join(target.ownerPath, to[index]));
3526
+ });
3527
+ if ('aggregate' === unit.kind) {
3528
+ const oldFolder = external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.name);
3529
+ const newFolder = external_node_path_default().join(target.ownerPath, 'domain/aggregates', target.name);
3530
+ const own = new Set(aggregateOwnFiles(unit.name).map((file)=>external_node_path_default().join(oldFolder, file)));
3531
+ for (const file of module_move_walk(oldFolder))if (!own.has(file)) moves.set(file, external_node_path_default().join(newFolder, external_node_path_default().relative(oldFolder, file)));
3532
+ }
3533
+ return moves;
3534
+ };
3535
+ const validateBackendMove = (unit, target, sharedKernelPath)=>{
3536
+ if (!kebabName.test(target.name)) return 'Use kebab-case: lowercase words split by "-", e.g. place-order';
3537
+ if (target.ownerPath === sharedKernelPath && !kindLayouts[unit.kind].sharedKernel) return `${kindLayouts[unit.kind].title} are not part of the Shared Kernel`;
3538
+ if (target.ownerPath === unit.ownerPath && target.name === unit.name && target.aggregate === unit.aggregate) return 'Nothing to change: enter a new name or pick another place';
3539
+ for (const [from, to] of unitMoves(unit, target))if (to !== from && external_node_fs_default().existsSync(to)) return `${external_node_path_default().relative(target.ownerPath, to)} already exists`;
3540
+ return true;
3541
+ };
3542
+ const ownerOf = (rootFolderPath, file)=>{
3543
+ const [area, context] = external_node_path_default().relative(rootFolderPath, file).split(external_node_path_default().sep);
3544
+ if ('bounded-contexts' === area && context) return {
3545
+ context,
3546
+ path: external_node_path_default().join(rootFolderPath, area, context)
3547
+ };
3548
+ if ('shared-kernel' === area) return {
3549
+ context: void 0,
3550
+ path: external_node_path_default().join(rootFolderPath, area)
3551
+ };
3552
+ };
3553
+ const inMemoryDbFile = (rootFolderPath)=>external_node_path_default().join(rootFolderPath, 'shared-kernel/infrastructure/services/in-memory-db-infrastructure-service.ts');
3554
+ const isolationAllows = (rootFolderPath, from, to)=>{
3555
+ const fromOwner = ownerOf(rootFolderPath, from);
3556
+ const toOwner = ownerOf(rootFolderPath, to);
3557
+ if (!fromOwner || !toOwner?.context) return true;
3558
+ if (fromOwner.context) return fromOwner.context === toOwner.context || true === crossContextImportAllowed(from, to);
3559
+ const inside = (folder)=>to === external_node_path_default().join(toOwner.path, folder) || to.startsWith(external_node_path_default().join(toOwner.path, folder) + external_node_path_default().sep);
3560
+ return inside('domain/errors') || from.replace(codeExtension, '') === inMemoryDbFile(rootFolderPath).replace(codeExtension, '') && inside('domain');
3561
+ };
3562
+ const moveBackendUnit = (projectRoot, rootFolderPath, unit, target)=>{
3563
+ const layout = kindLayouts[unit.kind];
3564
+ const moves = unitMoves(unit, target);
3565
+ const withoutExtension = new Map([
3566
+ ...moves
3567
+ ].map(([from, to])=>[
3568
+ from.replace(codeExtension, ''),
3569
+ to.replace(codeExtension, '')
3570
+ ]));
3571
+ const folders = 'aggregate' === unit.kind ? [
3572
+ [
3573
+ external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.name),
3574
+ external_node_path_default().join(target.ownerPath, 'domain/aggregates', target.name)
3575
+ ]
3576
+ ] : [];
3577
+ const movedPath = (candidate)=>{
3578
+ const extension = candidate.match(codeExtension)?.[0];
3579
+ if (extension) return moves.get(candidate);
3580
+ return withoutExtension.get(candidate) ?? folders.find(([from])=>from === candidate)?.[1];
3581
+ };
3582
+ const { codeFiles, importsOf, resolve } = projectImports(projectRoot);
3583
+ const oldNaming = new UnknownFormatNaming(unit.name);
3584
+ const newNaming = new UnknownFormatNaming(target.name);
3585
+ const leavesAggregate = !!unit.aggregate && (unit.aggregate !== target.aggregate || unit.ownerPath !== target.ownerPath);
3586
+ const oldAggregateFolder = unit.aggregate && external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.aggregate);
3587
+ const isOldBarrel = (resolved)=>!!oldAggregateFolder && (resolved === oldAggregateFolder || resolved === external_node_path_default().join(oldAggregateFolder, 'index'));
3588
+ const mainFile = [
3589
+ ...moves.keys()
3590
+ ][0];
3591
+ const newMainFile = moves.get(mainFile);
3592
+ const namedImports = /import\s+(type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\3;?/g;
3593
+ const barrelImporters = leavesAggregate ? [
3594
+ ...codeFiles
3595
+ ].filter(([file, content])=>!moves.has(file) && [
3596
+ ...content.matchAll(namedImports)
3597
+ ].some(([, , names, , specifier])=>isOldBarrel(resolve(specifier, file)?.resolved) && new RegExp(`(?<![\\w$])${oldNaming.ClassName}(?![\\w$])`).test(names))) : [];
3598
+ const violations = [];
3599
+ const relative = (file)=>toPosix(external_node_path_default().relative(projectRoot, file));
3600
+ for (const file of codeFiles.keys()){
3601
+ const from = moves.get(file) ?? file;
3602
+ for (const imported of importsOf(file)){
3603
+ const to = movedPath(imported);
3604
+ if (moves.has(file) || to) {
3605
+ if (!isolationAllows(rootFolderPath, from, to ?? imported)) violations.push([
3606
+ relative(from),
3607
+ relative(to ?? imported)
3608
+ ]);
3609
+ }
3610
+ }
3611
+ }
3612
+ for (const [file] of barrelImporters)if (!isolationAllows(rootFolderPath, file, newMainFile)) violations.push([
3613
+ relative(file),
3614
+ relative(newMainFile)
3615
+ ]);
3616
+ if (violations.length) return {
3617
+ violations
3618
+ };
3619
+ const word = (form)=>`(?<![\\w$])${escapeRegExp(form)}(?![\\w$])`;
3620
+ const oldCore = layout.core(oldNaming.ClassName);
3621
+ const newCore = layout.core(newNaming.ClassName);
3622
+ const prefixes = [
3623
+ ...unit.labels.map((label)=>new UnknownFormatNaming(label).ClassName),
3624
+ ...layout.wired ? [
3625
+ 'wire'
3626
+ ] : []
3627
+ ];
3628
+ const renames = [
3629
+ {
3630
+ pattern: new RegExp(`(?<![\\w$])(${prefixes.map(escapeRegExp).join('|')})?${escapeRegExp(oldCore)}(?![\\w$])`, 'g'),
3631
+ to: `$1${newCore}`
3632
+ },
3633
+ {
3634
+ pattern: new RegExp(word(lowerFirst(oldCore)), 'g'),
3635
+ to: lowerFirst(newCore)
3636
+ },
3637
+ {
3638
+ pattern: new RegExp(`(describe\\(\\s*['"\`])${escapeRegExp(oldNaming.withSpaces)}(?=[ '"\`])`, 'g'),
3639
+ to: `$1${newNaming.withSpaces}`,
3640
+ movedOnly: true
3641
+ }
3642
+ ];
3643
+ if ('aggregate' === unit.kind) renames.push({
3644
+ pattern: new RegExp(word(oldNaming.ClassName), 'g'),
3645
+ to: newNaming.ClassName
3646
+ }, {
3647
+ pattern: new RegExp(word(oldNaming.variableName), 'g'),
3648
+ to: newNaming.variableName,
3649
+ movedOnly: true
3650
+ });
3651
+ if ('entity' === unit.kind || 'value-object' === unit.kind) renames.push({
3652
+ pattern: new RegExp(word(oldNaming.variableName), 'g'),
3653
+ to: newNaming.variableName,
3654
+ movedOnly: true
3655
+ });
3656
+ const oldSection = new UnknownFormatNaming(plural(unit.name));
3657
+ const newSection = new UnknownFormatNaming(plural(target.name));
3658
+ const renamesSection = 'aggregate' === unit.kind && unit.name !== target.name;
3659
+ const everyFile = (content)=>renamesSection ? content.replace(new RegExp(`(InMemoryDbInfrastructureService\\[\\s*['"])${oldSection.variableName}(?=['"]\\s*\\])`, 'g'), `$1${newSection.variableName}`).replace(new RegExp(`(inMemoryDbInfrastructureService\\s*\\.\\s*)${oldSection.variableName}(?![\\w$])`, 'g'), `$1${newSection.variableName}`).replace(new RegExp(`(?<![\\w$.])${oldSection.variableName}(\\s*=\\s*this\\.section<[^>]*>\\(\\s*['"])${oldSection.fileName.toUpperCase()}(?=['"])`, 'g'), `${newSection.variableName}$1${newSection.fileName.toUpperCase()}`) : content;
3660
+ const plan = stageModuleMove({
3661
+ projectRoot,
3662
+ stopAt: rootFolderPath,
3663
+ moves,
3664
+ movedPath,
3665
+ rename: (content, { moved })=>renames.reduce((result, { pattern, to, movedOnly })=>movedOnly && !moved ? result : result.replace(pattern, to), content),
3666
+ everyFile
3667
+ });
3668
+ if (leavesAggregate && oldAggregateFolder) {
3669
+ const indexFile = new file_system_File(external_node_path_default().join(oldAggregateFolder, 'index.ts'));
3670
+ const exportLine = /^export\s+\*\s+from\s+(['"])([^'"\n]+)\1;?\s*$/;
3671
+ indexFile.update(indexFile.data.split('\n').filter((line)=>{
3672
+ const specifier = line.match(exportLine)?.[2];
3673
+ return !specifier || external_node_path_default().resolve(external_node_path_default().dirname(indexFile.path), specifier) !== newMainFile.replace(codeExtension, '');
3674
+ }).join('\n'));
3675
+ if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
3676
+ for (const [file] of barrelImporters){
3677
+ const importer = new file_system_File(file);
3678
+ let content = importer.data;
3679
+ for (const match of content.matchAll(namedImports)){
3680
+ const [statement, typeOnly = '', names, quote, specifier] = match;
3681
+ if (!isOldBarrel(resolve(specifier, file)?.resolved)) continue;
3682
+ const items = names.split(',').map((item)=>item.trim()).filter((item)=>!!item);
3683
+ const own = new RegExp(`^(?:type\\s+)?${newNaming.ClassName}(?:\\s+as\\s+[\\w$]+)?$`);
3684
+ const moved = items.filter((item)=>own.test(item));
3685
+ if (!moved.length) continue;
3686
+ const rest = items.filter((item)=>!own.test(item));
3687
+ const direct = `import ${typeOnly}{ ${moved.join(', ')} } from ${quote}${projectRelative(file, newMainFile)}${quote}`;
3688
+ content = content.replace(statement, rest.length ? `import ${typeOnly}{ ${rest.join(', ')} } from ${quote}${specifier}${quote}\n${direct}` : direct);
3689
+ }
3690
+ importer.update(content);
3691
+ }
3692
+ }
3693
+ if (target.aggregate && (target.aggregate !== unit.aggregate || target.ownerPath !== unit.ownerPath)) {
3694
+ const kindFolder = 'entity' === unit.kind ? 'entities' : 'value-objects';
3695
+ const indexFile = new file_system_File(external_node_path_default().join(target.ownerPath, 'domain/aggregates', target.aggregate, 'index.ts'));
3696
+ indexFile.addLineIfMissing(`export * from './${kindFolder}/${target.name}.${unit.kind}'`);
3697
+ if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
3698
+ }
3699
+ return plan;
3700
+ };
3701
+ const projectRelative = (fromFile, toFile)=>{
3702
+ const relative = toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toFile.replace(codeExtension, '')));
3703
+ return relative.startsWith('.') ? relative : `./${relative}`;
3704
+ };
3705
+ const contractKinds = [
3706
+ 'aggregate',
3707
+ 'command',
3708
+ 'query',
3709
+ 'port'
3710
+ ];
3711
+ const implementations_withWiring = ()=>config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
3712
+ const withHandlers = ()=>config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers');
3713
+ const contractFile = (unit)=>'aggregate' === unit.kind ? `domain/aggregates/${unit.name}/${unit.name}-repository.ts` : kindLayouts[unit.kind].files(unit, [])[0];
3714
+ const findContracts = (ownerPath)=>findBackendUnits(ownerPath).filter((unit)=>contractKinds.includes(unit.kind) && external_node_fs_default().existsSync(external_node_path_default().join(ownerPath, contractFile(unit))));
3715
+ const implementationWireName = (label)=>`wire${new UnknownFormatNaming(label).ClassName}Implementation`;
3716
+ const contractClassName = (unit)=>kindLayouts[unit.kind].core(new UnknownFormatNaming(unit.name).ClassName);
3717
+ const implementationClassName = (unit, label)=>`${new UnknownFormatNaming(label).ClassName}${contractClassName(unit)}`;
3718
+ const implementationFile = (unit, label)=>{
3719
+ const { implementations } = kindLayouts[unit.kind];
3720
+ return kindLayouts[unit.kind].files(unit, [
3721
+ label
3722
+ ]).find((file)=>file.startsWith(`${implementations}/`));
3723
+ };
3724
+ const contractWireFile = (unit)=>kindLayouts[unit.kind].files(unit, []).find((file)=>file.startsWith('wiring/'));
3725
+ const handlerImplementation = (ContractName, ClassName, contractImport)=>withHandlers() ? `
3726
+ import { defineHandler } from '@domain-first/handlers'
3727
+ import { ${ContractName} } from '${contractImport}'
2095
3728
 
2096
- Adds integrations to a Domain-First project: the REST endpoint generator,
2097
- the in-memory DB, Storybook, Prisma, Vitest, Playwright, integration tests,
2098
- OpenAPI and Orval. Several can be selected at once. Changes project files and prints
2099
- the install commands; nothing is installed or run.
3729
+ export class ${ClassName} extends ${ContractName} {
3730
+ constructor() {
3731
+ super()
3732
+ }
2100
3733
 
2101
- Options:
2102
- -h, --help show this help`;
2103
- const { values } = (0, external_node_util_namespaceObject.parseArgs)({
2104
- options: {
2105
- help: {
2106
- type: 'boolean',
2107
- short: 'h',
2108
- default: false
3734
+ handle = defineHandler({
3735
+ inputSchema: ${ContractName}.inputSchema,
3736
+ outputSchema: ${ContractName}.outputSchema,
3737
+ handler: async (input) => {
3738
+ return {}
2109
3739
  }
3740
+ })
3741
+ }
3742
+ `.trim() : `
3743
+ import { ${ContractName} } from '${contractImport}'
3744
+
3745
+ export class ${ClassName} extends ${ContractName} {
3746
+ constructor() {
3747
+ super()
2110
3748
  }
2111
- });
2112
- if (values.help) {
2113
- console.log(help);
2114
- process.exit(0);
2115
3749
  }
2116
- if (!config_file_ConfigFile.exists) {
2117
- console.log('No domain-first.project-structure.config.json found: run df-init first to initialize the project.');
2118
- process.exit(1);
3750
+ `.trim();
3751
+ const createImplementation = (ownerFolder, unit, label)=>{
3752
+ const naming = new UnknownFormatNaming(unit.name);
3753
+ const ContractName = contractClassName(unit);
3754
+ const className = implementationClassName(unit, label);
3755
+ const [folder, fileName] = [
3756
+ external_node_path_default().dirname(implementationFile(unit, label)),
3757
+ external_node_path_default().basename(implementationFile(unit, label))
3758
+ ];
3759
+ const implementationFolder = ownerFolder.subitem(folder.split('/'));
3760
+ const inMemoryDb = !implementations_withWiring() && usesInMemoryDb(label);
3761
+ switch(unit.kind){
3762
+ case 'aggregate':
3763
+ {
3764
+ const contractImport = `../../../domain/aggregates/${unit.name}`;
3765
+ if (inMemoryDb) {
3766
+ const section = addInMemoryDbSection(naming, ownerFolder.subitem([
3767
+ 'domain',
3768
+ 'aggregates',
3769
+ unit.name
3770
+ ]).path);
3771
+ const file = implementationFolder.createFile(fileName, `
3772
+ ${inMemoryDbTypeImport(implementationFolder.subitem([
3773
+ fileName
3774
+ ]).path)}
3775
+ import { ${ContractName} } from '${contractImport}'
3776
+
3777
+ export class ${className} implements ${ContractName} {
3778
+ ${inMemoryDbSectionMembers(section, false)}
3779
+ }
3780
+ `.trim());
3781
+ return {
3782
+ file,
3783
+ className
3784
+ };
3785
+ }
3786
+ const file = implementationFolder.createFile(fileName, `
3787
+ import { ${ContractName} } from '${contractImport}'
3788
+
3789
+ export class ${className} implements ${ContractName} {
3790
+ constructor() {}
3791
+ }
3792
+
3793
+ `.trim());
3794
+ return {
3795
+ file,
3796
+ className
3797
+ };
3798
+ }
3799
+ case 'command':
3800
+ case 'query':
3801
+ {
3802
+ const folderName = 'command' === unit.kind ? 'commands' : 'queries';
3803
+ const file = implementationFolder.createFile(fileName, handlerImplementation(ContractName, className, `../../../application/${folderName}/${naming.fileName}-${unit.kind}`));
3804
+ if (inMemoryDb) injectInMemoryDb(file, className);
3805
+ return {
3806
+ file,
3807
+ className
3808
+ };
3809
+ }
3810
+ case 'port':
3811
+ {
3812
+ const file = implementationFolder.createFile(fileName, `
3813
+ import { ${ContractName} } from '../../../application/ports/${naming.fileName}'
3814
+
3815
+ export class ${className} extends ${ContractName} {
3816
+
2119
3817
  }
2120
- addIntegration();
3818
+ `.trim());
3819
+ return {
3820
+ file,
3821
+ className
3822
+ };
3823
+ }
3824
+ default:
3825
+ throw new Error(`${unit.kind} has no implementations`);
3826
+ }
3827
+ };
3828
+ const inMemoryRepositoryWiring = (ownerFolder, unit, wireFile)=>(implementation, dependency)=>{
3829
+ if ('aggregate' !== unit.kind || !isInMemoryDb(dependency)) return false;
3830
+ keepInMemoryDbSection(new file_system_File(implementation.file), addInMemoryDbSection(new UnknownFormatNaming(unit.name), ownerFolder.subitem([
3831
+ 'domain',
3832
+ 'aggregates',
3833
+ unit.name
3834
+ ]).path));
3835
+ wireInMemoryDb(wireFile, implementation.className);
3836
+ return true;
3837
+ };
3838
+ const react_module_move_nestedName = (folders, fileBase)=>{
3839
+ const prefix = `${folders.join('-')}-`;
3840
+ const last = folders.length && fileBase.startsWith(prefix) ? fileBase.slice(prefix.length) : fileBase;
3841
+ return [
3842
+ ...folders,
3843
+ last
3844
+ ].join('/');
3845
+ };
3846
+ const declaredClassName = (filePath, suffix, name)=>{
3847
+ const content = external_node_fs_default().readFileSync(filePath, 'utf8');
3848
+ const declared = content.match(new RegExp(`export\\s+(?:const|function)\\s+(\\w+)${suffix}\\b`))?.[1];
3849
+ return declared ?? new NestedName(name).ClassName;
3850
+ };
3851
+ const findReactModules = (reactFolder, kind)=>{
3852
+ const modules = 'page' === kind ? module_move_walk(external_node_path_default().join(reactFolder, 'pages')).filter((file)=>file.endsWith('-page.tsx')).map((file)=>{
3853
+ const folders = external_node_path_default().relative(external_node_path_default().join(reactFolder, 'pages'), external_node_path_default().dirname(file)).split(external_node_path_default().sep).filter((segment)=>!!segment);
3854
+ const fileBase = external_node_path_default().basename(file, '-page.tsx');
3855
+ const name = react_module_move_nestedName(folders, fileBase);
3856
+ return {
3857
+ kind,
3858
+ name,
3859
+ path: file,
3860
+ fileBase,
3861
+ ClassName: declaredClassName(file, 'Page', name)
3862
+ };
3863
+ }) : module_move_walk(external_node_path_default().join(reactFolder, 'widgets')).filter((file)=>file.endsWith('-widget.tsx')).map((file)=>{
3864
+ const folder = external_node_path_default().dirname(file);
3865
+ const name = toPosix(external_node_path_default().relative(external_node_path_default().join(reactFolder, 'widgets'), folder));
3866
+ return {
3867
+ kind,
3868
+ name,
3869
+ path: folder,
3870
+ fileBase: external_node_path_default().basename(file, '-widget.tsx'),
3871
+ ClassName: declaredClassName(file, 'Widget', name)
3872
+ };
3873
+ });
3874
+ return modules.sort((a, b)=>a.name.localeCompare(b.name));
3875
+ };
3876
+ const react_module_move_targetPath = (reactFolder, module, rawName)=>{
3877
+ const { folders, folderName, fileName } = new NestedName(rawName);
3878
+ return 'page' === module.kind ? external_node_path_default().join(reactFolder, 'pages', ...folders, `${fileName}-page.tsx`) : external_node_path_default().join(reactFolder, 'widgets', ...folders, folderName);
3879
+ };
3880
+ const validateMove = (reactFolder, module, rawName)=>{
3881
+ const nameError = NestedName.validate(rawName);
3882
+ if (true !== nameError) return nameError;
3883
+ const target = react_module_move_targetPath(reactFolder, module, rawName);
3884
+ if (target !== module.path && external_node_fs_default().existsSync(target)) return `${external_node_path_default().relative(reactFolder, target)} already exists`;
3885
+ if (target.startsWith(`${module.path}${external_node_path_default().sep}`)) return 'A widget cannot be moved into itself';
3886
+ return true;
3887
+ };
3888
+ const routeFolder = (appFolder, rawName)=>{
3889
+ const { folders, folderName } = new NestedName(rawName);
3890
+ return external_node_path_default().join(appFolder, ...folders, folderName);
3891
+ };
3892
+ const routeFiles = (folder)=>external_node_fs_default().existsSync(folder) ? external_node_fs_default().readdirSync(folder, {
3893
+ withFileTypes: true
3894
+ }).filter((entry)=>entry.isFile()).map((entry)=>external_node_path_default().join(folder, entry.name)) : [];
3895
+ const moveReactModule = (projectRoot, reactFolder, module, rawName, route)=>{
3896
+ const newName = new NestedName(rawName);
3897
+ const target = react_module_move_targetPath(reactFolder, module, rawName);
3898
+ const newClassName = newName.ClassName;
3899
+ const renameFile = (name)=>name.replace(new RegExp(`^(use-)?${escapeRegExp(module.fileBase)}(?=[-.])`), (_, use = '')=>`${use}${newName.fileName}`);
3900
+ const oldFolder = 'page' === module.kind ? external_node_path_default().dirname(module.path) : module.path;
3901
+ const newFolder = 'page' === module.kind ? external_node_path_default().dirname(target) : target;
3902
+ const ownsPath = (candidate)=>'page' === module.kind ? external_node_path_default().dirname(candidate) === oldFolder && new RegExp(`^${escapeRegExp(module.fileBase)}-page(?:\\.|$)`).test(external_node_path_default().basename(candidate)) : candidate === oldFolder || candidate.startsWith(`${oldFolder}${external_node_path_default().sep}`);
3903
+ const routeFileSet = new Set(route ? routeFiles(route.from) : []);
3904
+ const routeTarget = (candidate)=>{
3905
+ if (!route) return;
3906
+ const file = [
3907
+ ...routeFileSet
3908
+ ].find((x)=>x === candidate || x.replace(codeExtension, '') === candidate);
3909
+ if (!file) return;
3910
+ const moved = external_node_path_default().join(route.to, external_node_path_default().relative(route.from, file));
3911
+ return file === candidate ? moved : moved.replace(codeExtension, '');
3912
+ };
3913
+ const movedPath = (candidate)=>{
3914
+ const routed = routeTarget(candidate);
3915
+ if (routed) return routed;
3916
+ if (!ownsPath(candidate)) return;
3917
+ const segments = external_node_path_default().relative(oldFolder, candidate).split(external_node_path_default().sep);
3918
+ const last = segments.length - 1;
3919
+ segments[last] = renameFile(segments[last]);
3920
+ return external_node_path_default().join(newFolder, ...segments);
3921
+ };
3922
+ const moduleFiles = 'page' === module.kind ? external_node_fs_default().readdirSync(oldFolder).map((name)=>external_node_path_default().join(oldFolder, name)).filter((file)=>external_node_fs_default().statSync(file).isFile() && ownsPath(file)) : module_move_walk(oldFolder);
3923
+ const moves = new Map([
3924
+ ...moduleFiles,
3925
+ ...routeFileSet
3926
+ ].map((file)=>[
3927
+ file,
3928
+ movedPath(file) ?? file
3929
+ ]));
3930
+ const suffixes = 'page' === module.kind ? 'Page' : 'Widget|UIModel';
3931
+ const classPattern = new RegExp(`(?<![\\w$])(use)?${escapeRegExp(module.ClassName)}(?=${suffixes})`, 'g');
3932
+ const oldTitle = `Widgets/${module.name.split('/').map((segment)=>new NestedName(segment).ClassName).join('/')}`;
3933
+ const titlePattern = new RegExp(`(['"\`])${escapeRegExp(oldTitle)}\\1`, 'g');
3934
+ const newTitle = [
3935
+ 'Widgets',
3936
+ ...newName.classNameSegments
3937
+ ].join('/');
3938
+ return stageModuleMove({
3939
+ projectRoot,
3940
+ stopAt: reactFolder,
3941
+ stopAtFor: (file)=>route && routeFileSet.has(file) ? route.appFolder : void 0,
3942
+ moves,
3943
+ movedPath,
3944
+ rename: (content, { moved })=>{
3945
+ const renamed = content.replace(classPattern, (_, use = '')=>`${use}${newClassName}`);
3946
+ return moved && 'widget' === module.kind ? renamed.replace(titlePattern, (_, quote)=>`${quote}${newTitle}${quote}`) : renamed;
3947
+ }
3948
+ });
3949
+ };
3950
+ const systemImplementationChoices = (kind, crossContext = false)=>{
3951
+ if ('ports' === kind) return crossContext ? [
3952
+ {
3953
+ name: 'System: cross-context (calls handlers in another bounded context)',
3954
+ value: crossContextImplementation
3955
+ }
3956
+ ] : [];
3957
+ return config_file_ConfigFile.exists && usesInMemoryDb('in-memory') ? [
3958
+ {
3959
+ name: 'System: in-memory (uses the shared in-memory database)',
3960
+ value: 'in-memory'
3961
+ }
3962
+ ] : [];
3963
+ };
3964
+ Symbol('create-test-branch');
3965
+ Symbol('no-test-branch');
3966
+ const noAggregate = 'No aggregate';
3967
+ const moveBackendUnitUseCase = async (ownerFolder)=>{
3968
+ const root = new project_root_ProjectRoot().path;
3969
+ const rootFolderPath = external_node_path_default().join(root, config_file_ConfigFile.Instance.data.project.rootFolder);
3970
+ const sharedKernelPath = external_node_path_default().join(rootFolderPath, 'shared-kernel');
3971
+ const units = findBackendUnits(ownerFolder.path);
3972
+ if (!units.length) return void report('No modules generated by df-scaffold were found here.');
3973
+ const unit = await interaction_select({
3974
+ key: 'module',
3975
+ id: unitId,
3976
+ message: 'Module:',
3977
+ choices: Object.keys(kindLayouts).flatMap((kind)=>{
3978
+ const group = units.filter((x)=>x.kind === kind);
3979
+ return group.length ? [
3980
+ new prompts_namespaceObject.Separator(`── ${kindLayouts[group[0].kind].title}`),
3981
+ ...group.map((value)=>({
3982
+ name: value.aggregate ? `${value.name} (${value.aggregate})` : value.name,
3983
+ value
3984
+ }))
3985
+ ] : [];
3986
+ }),
3987
+ pageSize: 20
3988
+ });
3989
+ const placeName = (ownerPath)=>ownerPath === sharedKernelPath ? 'Shared Kernel' : `Bounded Context: ${external_node_path_default().basename(ownerPath)}`;
3990
+ const contexts = new file_system_Folder(rootFolderPath).subitem([
3991
+ 'bounded-contexts'
3992
+ ]).content.subfolderNames.map((name)=>external_node_path_default().join(rootFolderPath, 'bounded-contexts', name));
3993
+ const places = [
3994
+ unit.ownerPath,
3995
+ ...contexts,
3996
+ ...kindLayouts[unit.kind].sharedKernel ? [
3997
+ sharedKernelPath
3998
+ ] : []
3999
+ ].filter((place, index, all)=>all.indexOf(place) === index);
4000
+ const ownerPath = await interaction_select({
4001
+ key: 'targetContext',
4002
+ id: (owner)=>owner === sharedKernelPath ? 'shared-kernel' : external_node_path_default().basename(owner),
4003
+ message: 'Move to:',
4004
+ choices: places.map((value)=>({
4005
+ name: value === unit.ownerPath ? `${placeName(value)} (stays)` : placeName(value),
4006
+ value
4007
+ }))
4008
+ });
4009
+ let aggregate;
4010
+ const aggregates = ownerPath === sharedKernelPath ? [] : aggregatesOf(ownerPath);
4011
+ if (('entity' === unit.kind || 'value-object' === unit.kind) && aggregates.length) {
4012
+ const picked = await interaction_select({
4013
+ key: 'aggregate',
4014
+ message: 'Aggregate:',
4015
+ choices: [
4016
+ noAggregate,
4017
+ ...aggregates
4018
+ ],
4019
+ default: ownerPath === unit.ownerPath && unit.aggregate ? unit.aggregate : noAggregate
4020
+ });
4021
+ aggregate = picked === noAggregate ? void 0 : picked;
4022
+ }
4023
+ const target = (name)=>({
4024
+ ownerPath,
4025
+ aggregate,
4026
+ name: name.trim()
4027
+ });
4028
+ const name = await interaction_input({
4029
+ key: 'name',
4030
+ message: 'New name:',
4031
+ default: unit.name,
4032
+ validate: (value)=>validateBackendMove(unit, target(value), sharedKernelPath)
4033
+ });
4034
+ const result = moveBackendUnit(root, rootFolderPath, unit, target(name));
4035
+ if (result.violations) {
4036
+ if (isNonInteractive()) throw new RequestError('MOVE_NOT_ALLOWED', 'The move would cross bounded-context boundaries.', {
4037
+ violations: result.violations
4038
+ });
4039
+ report([
4040
+ "Nothing was moved: these imports would cross a bounded context boundary.",
4041
+ ...result.violations.map(([from, to])=>` ${from} → ${to}`),
4042
+ 'Give the other context its own query or command, or move what it depends on first.'
4043
+ ].join('\n'));
4044
+ return;
4045
+ }
4046
+ const relative = (file)=>external_node_path_default().relative(root, file);
4047
+ report([
4048
+ 'Files to move:',
4049
+ ...result.moves.map(([from, to])=>` ${relative(from)} → ${relative(to)}`),
4050
+ ...result.updated.length ? [
4051
+ 'Files with updated imports and names:',
4052
+ ...result.updated.map((file)=>` ${relative(file)}`)
4053
+ ] : []
4054
+ ].join('\n'));
4055
+ if (!await interaction_confirm({
4056
+ key: 'apply',
4057
+ message: 'Apply?',
4058
+ default: true
4059
+ })) {
4060
+ discardPendingChanges();
4061
+ report('Cancelled: nothing was written.');
4062
+ }
4063
+ };
4064
+ const promptRouteMove = async (root, page, newName)=>{
4065
+ if (!usesNext()) return;
4066
+ const appFolder = external_node_path_default().join(root, nextAppFolder(root));
4067
+ const from = routeFolder(appFolder, page.name);
4068
+ const to = routeFolder(appFolder, newName);
4069
+ const relative = (file)=>external_node_path_default().relative(root, file).split(external_node_path_default().sep).join('/');
4070
+ const routePage = external_node_path_default().join(from, 'page.tsx');
4071
+ if (from === to || !external_node_fs_default().existsSync(routePage) || !new RegExp(`\\b${page.ClassName}Page\\b`).test(external_node_fs_default().readFileSync(routePage, 'utf8'))) return;
4072
+ if (external_node_fs_default().existsSync(external_node_path_default().join(to, 'page.tsx'))) return void report(`${relative(to)}/page.tsx already exists: the route ${relative(from)} stays.`);
4073
+ const move = await interaction_confirm({
4074
+ key: 'moveRoute',
4075
+ message: `Move the Next.js route too: ${relative(from)} → ${relative(to)}? Its URL changes.`,
4076
+ default: true
4077
+ });
4078
+ return move ? {
4079
+ appFolder,
4080
+ from,
4081
+ to
4082
+ } : void 0;
4083
+ };
4084
+ const moveReactModuleUseCase = async (presentationReactFolder, kind)=>{
4085
+ const reactFolder = presentationReactFolder.path;
4086
+ const modules = findReactModules(reactFolder, kind);
4087
+ if (!modules.length) return void report(`No ${kind}s generated by df-react were found.`);
4088
+ const module = await interaction_select({
4089
+ key: 'module',
4090
+ id: (value)=>value.name,
4091
+ message: 'page' === kind ? 'Page:' : 'Widget:',
4092
+ choices: modules.map((value)=>({
4093
+ name: value.name,
4094
+ value,
4095
+ description: external_node_path_default().relative(reactFolder, value.path)
4096
+ }))
4097
+ });
4098
+ const name = await interaction_input({
4099
+ key: 'name',
4100
+ message: 'New name (folders split by "/"):',
4101
+ default: module.name,
4102
+ validate: (value)=>validateMove(reactFolder, module, value)
4103
+ });
4104
+ const root = new project_root_ProjectRoot().path;
4105
+ const relative = (file)=>external_node_path_default().relative(root, file).split(external_node_path_default().sep).join('/');
4106
+ const route = 'page' === kind ? await promptRouteMove(root, module, name) : void 0;
4107
+ const { moves, updated } = moveReactModule(root, reactFolder, module, name, route);
4108
+ if (!moves.length && !updated.length) return void report('Nothing to change.');
4109
+ report([
4110
+ 'Files to move:',
4111
+ ...moves.map(([from, to])=>` ${relative(from)} → ${relative(to)}`),
4112
+ ...updated.length ? [
4113
+ 'Files with updated imports:',
4114
+ ...updated.map((file)=>` ${relative(file)}`)
4115
+ ] : []
4116
+ ].join('\n'));
4117
+ if (!await interaction_confirm({
4118
+ key: 'apply',
4119
+ message: 'Apply?',
4120
+ default: true
4121
+ })) {
4122
+ discardPendingChanges();
4123
+ report('Cancelled: nothing was written.');
4124
+ }
4125
+ };
4126
+ const enterImplementationTypeOnce = Symbol('enter-implementation-type-once');
4127
+ const implementationTypeEntryChoices = [
4128
+ {
4129
+ name: 'Enter implementation type and save for future use',
4130
+ value: null
4131
+ },
4132
+ {
4133
+ name: 'Enter implementation type for this run only',
4134
+ value: enterImplementationTypeOnce
4135
+ }
4136
+ ];
4137
+ const promptImplementationType = async (message, kind, { existing = [], purpose = 'primary', crossContext = false, remember = true } = {})=>{
4138
+ const roles = 'all' === purpose ? [
4139
+ 'primary',
4140
+ 'test'
4141
+ ] : [
4142
+ purpose
4143
+ ];
4144
+ const saved = [
4145
+ ...new Set(roles.flatMap((role)=>savedImplementations(kind, role)))
4146
+ ].filter((label)=>label !== crossContextImplementation || 'ports' === kind && crossContext);
4147
+ const allowCrossContext = 'ports' === kind && crossContext;
4148
+ const system = systemImplementationChoices(kind, crossContext);
4149
+ const choices = saved.map((label)=>system.find(({ value })=>value === label) ?? {
4150
+ name: label,
4151
+ value: label
4152
+ });
4153
+ for (const choice of system)if (!choices.some(({ value })=>value === choice.value)) choices.push(choice);
4154
+ const defaultType = saved.find((label)=>!existing.includes(label));
4155
+ const preferred = choices.find(({ value })=>value === defaultType && !existing.includes(value)) ?? choices.find(({ value })=>!existing.includes(value));
4156
+ const validateLabel = (value)=>{
4157
+ const label = value.trim();
4158
+ if (!allowCrossContext && label === crossContextImplementation) return 'Cross-context implementations require an application port with a neighboring bounded context.';
4159
+ if (!kebabName.test(label)) return 'Use lowercase kebab-case, e.g. prisma or in-memory.';
4160
+ return existing.includes(label) ? `The ${label} implementation already exists.` : true;
4161
+ };
4162
+ if (isNonInteractive()) {
4163
+ const key = 'test' === purpose ? 'testImplementation' : 'implementation';
4164
+ const implementation = answerFor(key);
4165
+ if (!implementation) throw new RequestError('MISSING_PARAMETER', `Provide ${key}.`, {
4166
+ field: key
4167
+ });
4168
+ const valid = validateLabel(implementation.type);
4169
+ if (true !== valid) throw new RequestError('INVALID_IMPLEMENTATION', valid, {
4170
+ field: key
4171
+ });
4172
+ const label = implementation.type.trim();
4173
+ const saveForFutureUse = implementation.save ?? false;
4174
+ if (remember && saveForFutureUse && !system.some((choice)=>choice.value === label)) rememberImplementation(kind, 'all' === purpose ? 'primary' : purpose, label);
4175
+ return {
4176
+ label,
4177
+ saveForFutureUse
4178
+ };
4179
+ }
4180
+ const type = await interaction_select({
4181
+ message,
4182
+ choices: [
4183
+ ...choices.map((choice)=>({
4184
+ ...choice,
4185
+ disabled: existing.includes(choice.value)
4186
+ })),
4187
+ ...implementationTypeEntryChoices
4188
+ ],
4189
+ default: preferred?.value ?? null
4190
+ });
4191
+ if ('string' == typeof type) return {
4192
+ label: type,
4193
+ saveForFutureUse: true
4194
+ };
4195
+ const saveForFutureUse = type !== enterImplementationTypeOnce;
4196
+ const label = (await interaction_input({
4197
+ message,
4198
+ default: defaultType ?? '',
4199
+ validate: validateLabel
4200
+ })).trim();
4201
+ if (saveForFutureUse && remember && !choices.some(({ value })=>value === label)) rememberImplementation(kind, 'all' === purpose ? 'primary' : purpose, label);
4202
+ return {
4203
+ label,
4204
+ saveForFutureUse
4205
+ };
4206
+ };
4207
+ const scaffoldNewAggregateUseCase = async (boundedContextFolder)=>{
4208
+ const aggregateName = await interaction_input({
4209
+ key: 'name',
4210
+ message: 'Aggregate name:'
4211
+ });
4212
+ const aggregateNaming = new UnknownFormatNaming(aggregateName);
4213
+ const scaffoldUnitTests = Boolean(config_file_ConfigFile.backend.testingLibrary);
4214
+ const withRepository = await interaction_confirm({
4215
+ key: 'withRepository',
4216
+ message: 'With Repository'
4217
+ });
4218
+ const aggregatesFolder = boundedContextFolder.subitem([
4219
+ 'domain',
4220
+ 'aggregates',
4221
+ aggregateName
4222
+ ]);
4223
+ const withTypes = config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/types');
4224
+ aggregatesFolder.createFile(`${aggregateNaming.fileName}.aggregate-root.ts`, withTypes ? `
4225
+ import { domainType } from '@domain-first/types'
4226
+
4227
+ export class ${aggregateNaming.ClassName} extends domainType() {
4228
+
4229
+ }`.trim() : `export class ${aggregateNaming.ClassName} {}`);
4230
+ const barrelFile = aggregatesFolder.createFile("index.ts", `export * from './${aggregateNaming.fileName}.aggregate-root'`);
4231
+ if (scaffoldUnitTests) aggregatesFolder.createFile(`${aggregateNaming.fileName}.aggregate-root.spec.ts`, `
4232
+ import { describe, test, expect, beforeEach } from '${config_file_ConfigFile.backend.testingLibrary}'
4233
+ import { ${aggregateNaming.ClassName} } from './${aggregateNaming.fileName}.aggregate-root'
4234
+
4235
+ let ${aggregateNaming.variableName}: ${aggregateNaming.ClassName}
4236
+
4237
+ beforeEach(() => {
4238
+ ${aggregateNaming.variableName} = ${withTypes ? `${aggregateNaming.ClassName}.of({})` : `new ${aggregateNaming.ClassName}()`}
4239
+ })
4240
+
4241
+ describe('${aggregateNaming.withSpaces}', () => {
4242
+ test('can be instantiated via ${withTypes ? 'of' : 'constructor'}', () => {
4243
+ expect(${aggregateNaming.variableName}).toBeDefined()
4244
+ })
4245
+ })
4246
+ `.trim());
4247
+ if (withRepository) {
4248
+ aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.ts`, `export abstract class ${aggregateNaming.ClassName}Repository { }`);
4249
+ barrelFile.addLine(`export * from './${aggregateNaming.fileName}-repository'`);
4250
+ const { label: infrastructureImplementationType } = await promptImplementationType('Repository infrastructure implementation type:', 'repositories');
4251
+ let addTestImplementation = false;
4252
+ let testImplementationType = '';
4253
+ addTestImplementation = offersTestImplementation() && await interaction_confirm({
4254
+ key: 'withTestImplementation',
4255
+ message: 'Add a test implementation for Repository'
4256
+ });
4257
+ if (addTestImplementation) testImplementationType = (await promptImplementationType('Test Repository infrastructure implementation type:', 'repositories', {
4258
+ purpose: 'test',
4259
+ existing: [
4260
+ infrastructureImplementationType
4261
+ ]
4262
+ })).label;
4263
+ const implementationTypes = [
4264
+ infrastructureImplementationType,
4265
+ testImplementationType
4266
+ ].filter((x)=>!!x);
4267
+ const repository = {
4268
+ kind: 'aggregate',
4269
+ name: aggregateName,
4270
+ ownerPath: boundedContextFolder.path,
4271
+ labels: []
4272
+ };
4273
+ for (const implementation of implementationTypes)createImplementation(boundedContextFolder, repository, new UnknownFormatNaming(implementation).fileName);
4274
+ if (scaffoldUnitTests) {
4275
+ const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
4276
+ const specFile = aggregatesFolder.createFile(`${aggregateNaming.fileName}-repository.spec.ts`, `
4277
+ import { describe, test, expect, beforeEach } from '${config_file_ConfigFile.backend.testingLibrary}'
4278
+ ${config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') ? `import { wire${aggregateNaming.ClassName}Repository } from '../../../wiring/repositories/wire-${aggregateNaming.fileName}-repository'
4279
+ import type { ${aggregateNaming.ClassName}Repository } from './${aggregateNaming.fileName}-repository'` : `import { ${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository } from '../../../infrastructure/repositories/${implementationNaming.fileName}/${implementationNaming.fileName}-${aggregateNaming.fileName}-repository'
4280
+
4281
+ type ${aggregateNaming.ClassName}Repository = ${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository`}
4282
+
4283
+ let ${aggregateNaming.variableName}Repository: ${aggregateNaming.ClassName}Repository
4284
+
4285
+ beforeEach(() => {
4286
+ ${aggregateNaming.variableName}Repository = ${config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') ? `wire${aggregateNaming.ClassName}Repository()` : `new ${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository()`}
4287
+ })
4288
+
4289
+ describe('${aggregateNaming.withSpaces} repository', () => {
4290
+ test('can be ${config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') ? 'wired' : 'created via constructor'}', () => {
4291
+ expect(${aggregateNaming.variableName}Repository).toBeDefined()
4292
+ })
4293
+ })
4294
+ `.trim());
4295
+ if (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') && usesInMemoryDb(infrastructureImplementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${aggregateNaming.ClassName}Repository`);
4296
+ }
4297
+ if (config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
4298
+ const implementationNaming = new UnknownFormatNaming(infrastructureImplementationType);
4299
+ const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
4300
+ const wireFile = boundedContextFolder.subitem([
4301
+ 'wiring',
4302
+ 'repositories'
4303
+ ]).createFile(`wire-${aggregateNaming.fileName}-repository.ts`, `
4304
+ import { wireClass } from '@domain-first/wire'
4305
+ import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
4306
+ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${aggregateNaming.ClassName}Repository } from '../../infrastructure/repositories/${fileName}/${fileName}-${aggregateNaming.fileName}-repository'`).join('\n')}
4307
+
4308
+ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${aggregateNaming.ClassName}Repository, [])`).join('\n\n')}
4309
+
4310
+ export const wire${aggregateNaming.ClassName}Repository = envBranchedWire(${envBranchedWireArgument(`wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation`, `wire${implementationNaming.ClassName}Implementation`)})
4311
+ `.trim());
4312
+ await wireNewModuleDependencies(boundedContextFolder, wireFile, inMemoryRepositoryWiring(boundedContextFolder, repository, wireFile));
4313
+ }
4314
+ }
4315
+ };
4316
+ const scaffoldNewApplicationPort = async (boundedContextFolder)=>{
4317
+ const name = await interaction_input({
4318
+ key: 'name',
4319
+ message: 'Name: '
4320
+ });
4321
+ const naming = new UnknownFormatNaming(name);
4322
+ const scaffoldUnitTests = Boolean(config_file_ConfigFile.backend.testingLibrary);
4323
+ const wiringFolder = boundedContextFolder.subitem([
4324
+ 'wiring',
4325
+ 'application-ports'
4326
+ ]);
4327
+ const applicationPortsFolder = boundedContextFolder.subitem([
4328
+ 'application',
4329
+ 'ports'
4330
+ ]);
4331
+ applicationPortsFolder.createFile(`${naming.fileName}.ts`, `
4332
+ export abstract class ${naming.ClassName} {
4333
+
4334
+ }
4335
+ `.trim());
4336
+ const crossContext = hasNeighboringBoundedContext(boundedContextFolder.path);
4337
+ const { label: implementationType } = await promptImplementationType('Adapter implementation type:', 'ports', {
4338
+ crossContext
4339
+ });
4340
+ const addTestImplementation = offersTestImplementation() && await interaction_confirm({
4341
+ key: 'withTestImplementation',
4342
+ message: 'With test implementation'
4343
+ });
4344
+ let testImplementationType = '';
4345
+ if (addTestImplementation) testImplementationType = (await promptImplementationType('Test adapter implementation type:', 'ports', {
4346
+ existing: [
4347
+ implementationType
4348
+ ],
4349
+ purpose: 'test',
4350
+ crossContext
4351
+ })).label;
4352
+ const implementationTypes = [
4353
+ implementationType,
4354
+ testImplementationType
4355
+ ].filter((x)=>!!x).map((x)=>new UnknownFormatNaming(x).fileName);
4356
+ for (const implementation of implementationTypes)createImplementation(boundedContextFolder, {
4357
+ kind: 'port',
4358
+ name: naming.fileName,
4359
+ ownerPath: boundedContextFolder.path,
4360
+ labels: []
4361
+ }, implementation);
4362
+ if (scaffoldUnitTests) {
4363
+ const implementationNaming = new UnknownFormatNaming(implementationType);
4364
+ applicationPortsFolder.createFile(`${naming.fileName}.spec.ts`, `
4365
+ import { describe, test, expect, beforeEach } from '${config_file_ConfigFile.backend.testingLibrary}'
4366
+ ${config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') ? `import { type ${naming.ClassName} } from './${naming.fileName}'
4367
+ import { wire${naming.ClassName} } from '../../wiring/application-ports/wire-${naming.fileName}'` : `import { ${implementationNaming.ClassName}${naming.ClassName} } from '../../infrastructure/application-adapters/${implementationNaming.fileName}/${implementationNaming.fileName}-${naming.fileName}'
4368
+
4369
+ type ${naming.ClassName} = ${implementationNaming.ClassName}${naming.ClassName}`}
4370
+
4371
+ let ${naming.variableName}: ${naming.ClassName}
4372
+
4373
+ beforeEach(() => {
4374
+ ${naming.variableName} = ${config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') ? `wire${naming.ClassName}()` : `new ${implementationNaming.ClassName}${naming.ClassName}()`}
4375
+ })
4376
+
4377
+ describe('${naming.withSpaces}', () => {
4378
+ test('can be ${config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') ? 'wired' : 'created via constructor'}', () => {
4379
+ expect(${naming.variableName}).toBeDefined()
4380
+ })
4381
+ })
4382
+ `.trim());
4383
+ }
4384
+ if (config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
4385
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}.ts`, `
4386
+ import { wireClass } from '@domain-first/wire'
4387
+ import { envBranchedWire } from '../../../${'shared-kernel' === boundedContextFolder.name ? '' : '../'}shared-kernel/wiring/env-branched-wire'
4388
+ ${implementationTypes.map((x)=>({
4389
+ naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
4390
+ implementation: x
4391
+ })).map(({ naming: { ClassName, fileName }, implementation })=>`import { ${ClassName} } from '../../infrastructure/application-adapters/${implementation}/${fileName}'`).join('\n')}
4392
+
4393
+ ${implementationTypes.map((x)=>({
4394
+ naming: new UnknownFormatNaming(`${x}-${naming.fileName}`),
4395
+ implementation: x
4396
+ })).map(({ naming: { ClassName }, implementation })=>`const wire${new UnknownFormatNaming(implementation).ClassName}Implementation = wireClass(${ClassName}, [])`).join('\n\n')}
4397
+
4398
+ export const wire${naming.ClassName} = envBranchedWire(${envBranchedWireArgument(`wire${new UnknownFormatNaming(`${implementationTypes.at(-1)}-implementation`).ClassName}`, `wire${new UnknownFormatNaming(`${implementationTypes.at(0)}-implementation`).ClassName}`)})
4399
+
4400
+ `.trim());
4401
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
4402
+ }
4403
+ };
4404
+ const scaffoldNewApplicationService = async (boundedContextFolder)=>{
4405
+ const name = await interaction_input({
4406
+ key: 'name',
4407
+ message: 'Name: '
4408
+ });
4409
+ const naming = new UnknownFormatNaming(name);
4410
+ const scaffoldUnitTests = Boolean(config_file_ConfigFile.backend.testingLibrary);
4411
+ const withWiring = config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
4412
+ const wiringFolder = boundedContextFolder.subitem([
4413
+ 'wiring',
4414
+ 'application-services'
4415
+ ]);
4416
+ const applicationServicesFolder = boundedContextFolder.subitem([
4417
+ 'application',
4418
+ 'services'
4419
+ ]);
4420
+ applicationServicesFolder.createFile(`${naming.fileName}-application-service.ts`, `
4421
+ export class ${naming.ClassName}ApplicationService {
4422
+
4423
+ }
4424
+ `.trim());
4425
+ if (scaffoldUnitTests) applicationServicesFolder.createFile(`${naming.fileName}-application-service.spec.ts`, `
4426
+ import { describe, test, expect, beforeEach } from '${config_file_ConfigFile.backend.testingLibrary}'
4427
+ ${withWiring ? `import { type ${naming.ClassName}ApplicationService } from './${naming.fileName}-application-service'
4428
+ import { wire${naming.ClassName}ApplicationService } from '../../wiring/application-services/wire-${naming.fileName}-application-service'` : `import { ${naming.ClassName}ApplicationService } from './${naming.fileName}-application-service'`}
4429
+
4430
+ let ${naming.variableName}ApplicationService: ${naming.ClassName}ApplicationService
4431
+
4432
+ beforeEach(() => {
4433
+ ${naming.variableName}ApplicationService = ${withWiring ? `wire${naming.ClassName}ApplicationService()` : `new ${naming.ClassName}ApplicationService()`}
4434
+ })
4435
+
4436
+ describe('${naming.withSpaces}', () => {
4437
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
4438
+ expect(${naming.variableName}ApplicationService).toBeDefined()
4439
+ })
4440
+ })
4441
+ `.trim());
4442
+ if (withWiring) {
4443
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-application-service.ts`, `
4444
+ import { wireClass } from '@domain-first/wire'
4445
+ import { ${naming.ClassName}ApplicationService } from '../../application/services/${naming.fileName}-application-service'
4446
+
4447
+ export const wire${naming.ClassName}ApplicationService = wireClass(
4448
+ ${naming.ClassName}ApplicationService,
4449
+ []
4450
+ )
4451
+ `.trim());
4452
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
4453
+ }
4454
+ };
4455
+ const scaffoldNewBoundedContextUseCase = async ()=>{
4456
+ const name = await interaction_input({
4457
+ key: 'name',
4458
+ message: 'Name:',
4459
+ validate: (x)=>!!x.length
4460
+ });
4461
+ const { path } = new project_root_ProjectRoot();
4462
+ const rootFolder = new file_system_Folder(path);
4463
+ const folder = rootFolder.subitem([
4464
+ config_file_ConfigFile.Instance.data.project.rootFolder,
4465
+ 'bounded-contexts',
4466
+ name
4467
+ ]);
4468
+ folder.createIfNotExisted();
4469
+ };
4470
+ const scaffoldNewCommand = async (boundedContextFolder)=>{
4471
+ const commandsFolder = boundedContextFolder.subitem([
4472
+ 'application',
4473
+ 'commands'
4474
+ ]);
4475
+ const commandName = await interaction_input({
4476
+ key: 'name',
4477
+ message: 'Name: '
4478
+ });
4479
+ const scaffoldUnitTests = Boolean(config_file_ConfigFile.backend.testingLibrary);
4480
+ const naming = new UnknownFormatNaming(commandName);
4481
+ const withWiring = config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
4482
+ const { label: implementationType } = await promptImplementationType('Command infrastructure implementation type:', 'commands');
4483
+ let addTestImplementation = false;
4484
+ let testImplementationType = '';
4485
+ addTestImplementation = offersTestImplementation() && await interaction_confirm({
4486
+ key: 'withTestImplementation',
4487
+ message: 'Add a test implementation for Command'
4488
+ });
4489
+ if (addTestImplementation) testImplementationType = (await promptImplementationType('Test Command infrastructure implementation type:', 'commands', {
4490
+ existing: [
4491
+ implementationType
4492
+ ],
4493
+ purpose: 'test'
4494
+ })).label;
4495
+ const implementationTypes = [
4496
+ implementationType,
4497
+ testImplementationType
4498
+ ].filter((x)=>!!x);
4499
+ for (const implementation of implementationTypes)createImplementation(boundedContextFolder, {
4500
+ kind: 'command',
4501
+ name: naming.fileName,
4502
+ ownerPath: boundedContextFolder.path,
4503
+ labels: []
4504
+ }, new UnknownFormatNaming(implementation).fileName);
4505
+ if (config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers')) commandsFolder.createFile(`${naming.fileName}-command.ts`, `
4506
+ import type { Handler } from '@domain-first/handlers'
4507
+
4508
+ export abstract class ${naming.ClassName}Command {
4509
+ static inputSchema = {}
4510
+ static outputSchema = {}
4511
+
4512
+ abstract handle: Handler<typeof ${naming.ClassName}Command.inputSchema, typeof ${naming.ClassName}Command.outputSchema>
4513
+ }
4514
+ `.trim());
4515
+ else commandsFolder.createFile(`${naming.fileName}-command.ts`, `
4516
+ export abstract class ${naming.ClassName}Command {
4517
+
4518
+ }`.trim());
4519
+ if (scaffoldUnitTests) {
4520
+ const implementationNaming = new UnknownFormatNaming(implementationType);
4521
+ const specFile = commandsFolder.createFile(`${naming.fileName}-command.spec.ts`, `
4522
+ import { describe, test, expect, beforeEach } from '${config_file_ConfigFile.backend.testingLibrary}'
4523
+ ${withWiring ? `import { type ${naming.ClassName}Command } from './${naming.fileName}-command'
4524
+ import { wire${naming.ClassName}Command } from '../../wiring/commands/wire-${naming.fileName}-command'` : `import { ${implementationNaming.ClassName}${naming.ClassName}Command } from '../../infrastructure/commands/${implementationNaming.fileName}/${implementationNaming.fileName}-${naming.fileName}-command'
4525
+
4526
+ type ${naming.ClassName}Command = ${implementationNaming.ClassName}${naming.ClassName}Command`}
4527
+
4528
+ let ${naming.variableName}Command: ${naming.ClassName}Command
4529
+
4530
+ beforeEach(() => {
4531
+ ${naming.variableName}Command = ${withWiring ? `wire${naming.ClassName}Command()` : `new ${implementationNaming.ClassName}${naming.ClassName}Command()`}
4532
+ })
4533
+
4534
+ describe('${naming.withSpaces} command', () => {
4535
+ test('can be ${withWiring ? 'wired' : 'created via constructor'}', () => {
4536
+ expect(${naming.variableName}Command).toBeDefined()
4537
+ })
4538
+ })
4539
+ `.trim());
4540
+ if (!withWiring && usesInMemoryDb(implementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${naming.ClassName}Command`);
4541
+ }
4542
+ if (config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
4543
+ const implementationNaming = new UnknownFormatNaming(implementationType);
4544
+ const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
4545
+ const wireFile = boundedContextFolder.subitem([
4546
+ 'wiring',
4547
+ 'commands'
4548
+ ]).createFile(`wire-${naming.fileName}-command.ts`, `
4549
+ import { wireClass } from '@domain-first/wire'
4550
+ import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
4551
+ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${naming.ClassName}Command } from '../../infrastructure/commands/${fileName}/${fileName}-${naming.fileName}-command'`).join('\n')}
4552
+
4553
+ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${naming.ClassName}Command, [])`).join('\n\n')}
4554
+
4555
+ export const wire${naming.ClassName}Command = envBranchedWire(${envBranchedWireArgument(`wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation`, `wire${implementationNaming.ClassName}Implementation`)})
4556
+ `.trim());
4557
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
4558
+ }
4559
+ };
4560
+ const scaffold_new_domain_object_noAggregate = 'No aggregate';
4561
+ const scaffoldNewDomainObject = async (boundedContextFolder, kind)=>{
4562
+ const name = await interaction_input({
4563
+ key: 'name',
4564
+ message: 'Name: '
4565
+ });
4566
+ const naming = new UnknownFormatNaming(name);
4567
+ const aggregatesFolder = boundedContextFolder.subitem([
4568
+ 'domain',
4569
+ 'aggregates'
4570
+ ]);
4571
+ const aggregateNames = aggregatesFolder.content.subfolderNames;
4572
+ const aggregate = aggregateNames.length ? await interaction_select({
4573
+ key: 'aggregate',
4574
+ message: 'Aggregate:',
4575
+ choices: [
4576
+ ...aggregateNames,
4577
+ scaffold_new_domain_object_noAggregate
4578
+ ]
4579
+ }) : scaffold_new_domain_object_noAggregate;
4580
+ const kindFolderName = 'entity' === kind ? 'entities' : 'value-objects';
4581
+ const folder = aggregate === scaffold_new_domain_object_noAggregate ? boundedContextFolder.subitem([
4582
+ 'domain',
4583
+ kindFolderName
4584
+ ]) : aggregatesFolder.subitem([
4585
+ aggregate,
4586
+ kindFolderName
4587
+ ]);
4588
+ const fileName = `${naming.fileName}.${kind}`;
4589
+ const withTypes = config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/types');
4590
+ folder.createFile(`${fileName}.ts`, withTypes ? `
4591
+ import { domainType } from '@domain-first/types'
4592
+
4593
+ export class ${naming.ClassName} extends domainType() {
4594
+
4595
+ }`.trim() : `export class ${naming.ClassName} {}`);
4596
+ if (aggregate !== scaffold_new_domain_object_noAggregate) aggregatesFolder.subitem([
4597
+ aggregate
4598
+ ]).file('index.ts').addLineIfMissing(`export * from './${kindFolderName}/${fileName}'`);
4599
+ const { testingLibrary } = config_file_ConfigFile.backend;
4600
+ if (testingLibrary) folder.createFile(`${fileName}.spec.ts`, `
4601
+ import { describe, test, expect, beforeEach } from '${testingLibrary}'
4602
+ import { ${naming.ClassName} } from './${fileName}'
4603
+
4604
+ let ${naming.variableName}: ${naming.ClassName}
4605
+
4606
+ beforeEach(() => {
4607
+ ${naming.variableName} = ${withTypes ? `${naming.ClassName}.of({})` : `new ${naming.ClassName}()`}
4608
+ })
4609
+
4610
+ describe('${naming.withSpaces}', () => {
4611
+ test('can be instantiated via ${withTypes ? 'of' : 'constructor'}', () => {
4612
+ expect(${naming.variableName}).toBeDefined()
4613
+ })
4614
+ })
4615
+ `.trim());
4616
+ };
4617
+ const scaffoldNewDomainService = async (boundedContextFolder)=>{
4618
+ const portName = await interaction_input({
4619
+ key: 'name',
4620
+ message: 'Name:'
4621
+ });
4622
+ const naming = new UnknownFormatNaming(portName);
4623
+ const scaffoldUnitTests = Boolean(config_file_ConfigFile.backend.testingLibrary);
4624
+ const withWiring = config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
4625
+ const domainServicesFolder = boundedContextFolder.subitem([
4626
+ 'domain',
4627
+ 'services'
4628
+ ]);
4629
+ domainServicesFolder.createFile(`${naming.fileName}-domain-service.ts`, `
4630
+ export class ${naming.ClassName}DomainService {
4631
+
4632
+ }
4633
+ `.trim());
4634
+ if (scaffoldUnitTests) domainServicesFolder.createFile(`${naming.fileName}-domain-service.spec.ts`, `
4635
+ import { describe, test, expect, beforeEach } from '${config_file_ConfigFile.backend.testingLibrary}'
4636
+ ${withWiring ? `import { type ${naming.ClassName}DomainService } from './${naming.fileName}-domain-service'
4637
+ import { wire${naming.ClassName}DomainService } from '../../wiring/domain-services/wire-${naming.fileName}-domain-service'` : `import { ${naming.ClassName}DomainService } from './${naming.fileName}-domain-service'`}
4638
+
4639
+ let ${naming.variableName}DomainService: ${naming.ClassName}DomainService
4640
+
4641
+ beforeEach(() => {
4642
+ ${naming.variableName}DomainService = ${withWiring ? `wire${naming.ClassName}DomainService()` : `new ${naming.ClassName}DomainService()`}
4643
+ })
4644
+
4645
+ describe('${naming.withSpaces}', () => {
4646
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
4647
+ expect(${naming.variableName}DomainService).toBeDefined()
4648
+ })
4649
+ })
4650
+ `.trim());
4651
+ if (withWiring) {
4652
+ const wireFile = boundedContextFolder.subitem([
4653
+ 'wiring',
4654
+ 'domain-services'
4655
+ ]).createFile(`wire-${naming.fileName}-domain-service.ts`, `
4656
+ import { wireClass } from '@domain-first/wire'
4657
+ import { ${naming.ClassName}DomainService } from '../../domain/services/${naming.fileName}-domain-service'
4658
+
4659
+ export const wire${naming.ClassName}DomainService = wireClass(
4660
+ ${naming.ClassName}DomainService,
4661
+ []
4662
+ )
4663
+ `.trim());
4664
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
4665
+ }
4666
+ };
4667
+ const errorNames = (boundedContextFolder)=>{
4668
+ const isShared = boundedContextFolder.path === new file_system_Folder(new project_root_ProjectRoot().path).subitem([
4669
+ config_file_ConfigFile.Instance.data.project.rootFolder,
4670
+ 'shared-kernel'
4671
+ ]).path;
4672
+ return {
4673
+ namespace: (namespaceName)=>`${namespaceName}${isShared ? 'SharedKernel' : ''}Errors`,
4674
+ error: (errorName)=>`${errorName}${isShared ? 'SharedKernelError' : ''}`
4675
+ };
4676
+ };
4677
+ const namespacePattern = /export\s+const\s+(\w+)\s*=\s*errorNamespace\b/;
4678
+ const exportedNamespace = (file, fallback)=>namespacePattern.exec(file.data)?.[1] ?? fallback;
4679
+ const rootNamespace = (indexFile, namespace, code)=>{
4680
+ const content = indexFile.exists ? indexFile.data.trim() : '';
4681
+ const existing = namespacePattern.exec(content)?.[1];
4682
+ if (existing) return existing;
4683
+ indexFile.update([
4684
+ "import { errorNamespace } from '@domain-first/errors'",
4685
+ `export const ${namespace} = errorNamespace('${code}')`,
4686
+ content
4687
+ ].filter((x)=>!!x).join('\n\n'));
4688
+ return namespace;
4689
+ };
4690
+ const errorClass = (className, namespace, code)=>`export class ${className} extends ${namespace}.define('${code}') {}`;
4691
+ const scaffoldNewErrorUseCase = async (boundedContextFolder)=>{
4692
+ const currentErrorFolder = boundedContextFolder.subitem([
4693
+ 'domain',
4694
+ 'errors'
4695
+ ]);
4696
+ const names = errorNames(boundedContextFolder);
4697
+ const contextNaming = new UnknownFormatNaming(boundedContextFolder.name);
4698
+ const currentErrorNamespaces = currentErrorFolder.content.fileNames.filter((x)=>'index' !== x);
4699
+ const variants = [
4700
+ 'New error without namespace',
4701
+ ...currentErrorNamespaces.map((x)=>`New error in namespace ${x}`),
4702
+ 'New namespace'
4703
+ ];
4704
+ const selectedVariant = await interaction_select({
4705
+ choices: variants,
4706
+ key: 'errorAction',
4707
+ message: 'Action:'
4708
+ });
4709
+ if ('New error without namespace' === selectedVariant) {
4710
+ const errorName = await interaction_input({
4711
+ key: 'name',
4712
+ message: 'Error name:'
4713
+ });
4714
+ const naming = new UnknownFormatNaming(errorName);
4715
+ const indexFile = currentErrorFolder.file('index.ts');
4716
+ indexFile.addLineIfMissing(errorClass(names.error(naming.ClassName), rootNamespace(indexFile, `${contextNaming.ClassName}Errors`, boundedContextFolder.name), naming.fileName), '\n\n');
4717
+ return;
4718
+ }
4719
+ if ('New namespace' === selectedVariant) {
4720
+ const namespaceName = await interaction_input({
4721
+ key: 'name',
4722
+ message: 'Namespace name:'
4723
+ });
4724
+ const { ClassName, fileName } = new UnknownFormatNaming(namespaceName);
4725
+ if (!currentErrorFolder.file(`${fileName}.ts`).exists) currentErrorFolder.createFile(`${fileName}.ts`, `
4726
+ import { errorNamespace } from '@domain-first/errors'
4727
+
4728
+ export const ${names.namespace(ClassName)} = errorNamespace('${boundedContextFolder.name}').subnamespace('${fileName}')
4729
+ `.trim());
4730
+ currentErrorFolder.file('index.ts').addLineIfMissing(`export * from './${fileName}'`, '\n\n');
4731
+ return;
4732
+ }
4733
+ const namespace = selectedVariant.substring(23);
4734
+ const namespaceNaming = new UnknownFormatNaming(namespace);
4735
+ const errorName = await interaction_input({
4736
+ key: 'name',
4737
+ message: 'Error name:'
4738
+ });
4739
+ const { ClassName, fileName } = new UnknownFormatNaming(errorName);
4740
+ const namespaceFile = currentErrorFolder.file(`${namespace}.ts`);
4741
+ namespaceFile.addLineIfMissing(errorClass(names.error(`${namespaceNaming.ClassName}${ClassName}`), exportedNamespace(namespaceFile, names.namespace(namespaceNaming.ClassName)), fileName), '\n\n');
4742
+ };
4743
+ const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
4744
+ const restPresentationFolder = boundedContextFolder.subitem([
4745
+ 'presentation',
4746
+ 'rest'
4747
+ ]);
4748
+ const controllers = restPresentationFolder.content.subfolderNames;
4749
+ let controller = await interaction_select({
4750
+ key: 'controllerSelection',
4751
+ message: 'Controller: ',
4752
+ choices: [
4753
+ ...controllers,
4754
+ 'New controller'
4755
+ ]
4756
+ });
4757
+ if ('New controller' === controller) {
4758
+ controller = await interaction_input({
4759
+ key: 'controllerName',
4760
+ message: 'Name: '
4761
+ });
4762
+ if (config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
4763
+ boundedContextFolder.subitem([
4764
+ 'wiring',
4765
+ 'presentation',
4766
+ 'rest'
4767
+ ]).file('index.ts').addLine(`export * from './${controller}'`);
4768
+ const sharedRestFolder = boundedContextFolder.subitem([
4769
+ '..',
4770
+ '..',
4771
+ 'presentation',
4772
+ 'rest'
4773
+ ]);
4774
+ sharedRestFolder.file('wires.ts').addLine(`export * from '../../bounded-contexts/${boundedContextFolder.name}/wiring/presentation/rest/${controller}'`);
4775
+ if (!sharedRestFolder.file('index.ts').exists) sharedRestFolder.createFile('index.ts', `
4776
+ import * as wires from './wires'
4777
+
4778
+ const restWires = Object.values(wires)
4779
+
4780
+ export const restHandlers = restWires.map(x => x().handle)
4781
+ `.trim());
4782
+ }
4783
+ }
4784
+ const method = await interaction_select({
4785
+ key: 'method',
4786
+ message: 'Method:',
4787
+ choices: [
4788
+ 'get',
4789
+ 'post',
4790
+ 'patch',
4791
+ 'delete',
4792
+ 'put'
4793
+ ]
4794
+ });
4795
+ const routeSegments = (await interaction_input({
4796
+ key: 'path',
4797
+ message: 'Relative path (split by "/"):'
4798
+ })).split('/').filter((x)=>!!x);
4799
+ const pathParameterAsName = (segment)=>segment.startsWith(':') ? `_${segment.slice(1)}_` : segment;
4800
+ const controllerFolder = restPresentationFolder.subitem([
4801
+ controller
4802
+ ]);
4803
+ const endpointFolder = controllerFolder.subitem(routeSegments.map(pathParameterAsName));
4804
+ const nameBase = `${controller}-${routeSegments.length ? `${routeSegments.map(pathParameterAsName).join('-')}-` : ''}${method}-endpoint`;
4805
+ const endpointClassName = [
4806
+ controller,
4807
+ ...routeSegments,
4808
+ method,
4809
+ 'endpoint'
4810
+ ].map((segment)=>segment.startsWith(':') ? pathParameterAsName(segment) : new UnknownFormatNaming(segment).ClassName).join('');
4811
+ const withWiring = config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
4812
+ const endpointGenerator = findRestEndpointGenerator(boundedContextFolder.subitem([
4813
+ '..',
4814
+ '..',
4815
+ 'shared-kernel'
4816
+ ]));
4817
+ const handler = withWiring ? await promptEndpointHandler(boundedContextFolder) : void 0;
4818
+ const endpointFile = external_node_path_default().join(endpointFolder.path, `${method.toUpperCase()}.ts`);
4819
+ endpointFolder.createFile(`${method.toUpperCase()}.ts`, `
4820
+ ${endpointGenerator ? `import type { ${endpointGenerator.typeName} } from '${relativeImport(endpointFile, endpointGenerator.typeFile)}'` : "import { EndpointGenerator } from '@domain-first/handlers-rest'"}${handler ? `
4821
+ import type { ${handler.typeName} } from '${relativeImport(endpointFile, handler.typeFile)}'` : ''}
4822
+
4823
+ export class ${endpointClassName} {
4824
+ constructor(
4825
+ private readonly endpointGenerator: ${endpointGenerator?.typeName ?? 'EndpointGenerator'},
4826
+ private readonly handler: ${handler?.typeName ?? 'never'}
4827
+ ) {}
4828
+
4829
+ get handle() {
4830
+ return this.endpointGenerator(this.handler.handle, {
4831
+ route: { method: '${method}', path: ['${boundedContextFolder.name}', '${controller}'${routeSegments.length ? `, ${routeSegments.map((x)=>`'${x}'`).join(', ')}` : ''}] },
4832
+ tags: ['${boundedContextFolder.name}: ${controller}'],
4833
+ })
4834
+ }
4835
+ }
4836
+ `.trim());
4837
+ if (withWiring) {
4838
+ const wiringFolder = boundedContextFolder.subitem([
4839
+ 'wiring',
4840
+ 'presentation',
4841
+ 'rest',
4842
+ controller
4843
+ ]);
4844
+ const wireNameBase = `wire-${nameBase}`;
4845
+ const wireNaming = new UnknownFormatNaming(wireNameBase);
4846
+ const wireFile = external_node_path_default().join(wiringFolder.path, `${wireNaming.fileName}.ts`);
4847
+ const dependencies = endpointGenerator ? [
4848
+ endpointGenerator,
4849
+ handler
4850
+ ].filter((x)=>!!x) : [];
4851
+ wiringFolder.createFile(`${wireNaming.fileName}.ts`, `
4852
+ import { wireClass } from '@domain-first/wire'
4853
+ import { ${endpointClassName} } from '${relativeImport(wireFile, endpointFile)}'
4854
+ ${dependencies.map((x)=>`import { ${x.wireName} } from '${relativeImport(wireFile, x.wireFile)}'`).join('\n')}
4855
+
4856
+ export const wire${endpointClassName} = wireClass(
4857
+ ${endpointClassName},
4858
+ [${dependencies.map((x)=>x.wireName).join(', ')}]
4859
+ )
4860
+ `.trim());
4861
+ wiringFolder.file('index.ts').addLineIfMissing(`export * from './${wireNaming.fileName}'`);
4862
+ }
4863
+ };
4864
+ const scaffold_new_implementation_kindTitles = {
4865
+ aggregate: 'Repositories',
4866
+ command: 'Commands',
4867
+ query: 'Queries',
4868
+ port: 'Ports'
4869
+ };
4870
+ const branchesOf = (wireFile, wireName)=>{
4871
+ if (!wireFile.exists) return;
4872
+ try {
4873
+ return wireBranches(wireFile.data, wireName);
4874
+ } catch {
4875
+ return;
4876
+ }
4877
+ };
4878
+ const scaffoldNewImplementation = async (ownerFolder)=>{
4879
+ const contracts = findContracts(ownerFolder.path);
4880
+ if (!contracts.length) return void report('No repositories, commands, queries or ports here yet.');
4881
+ const unit = await interaction_select({
4882
+ key: 'contract',
4883
+ id: unitId,
4884
+ message: 'Contract:',
4885
+ choices: contractKinds.flatMap((kind)=>{
4886
+ const group = contracts.filter((x)=>x.kind === kind);
4887
+ return group.length ? [
4888
+ new prompts_namespaceObject.Separator(`── ${scaffold_new_implementation_kindTitles[kind]}`),
4889
+ ...group.map((value)=>({
4890
+ name: value.labels.length ? `${value.name} (${value.labels.join(', ')})` : value.name,
4891
+ value
4892
+ }))
4893
+ ] : [];
4894
+ }),
4895
+ pageSize: 20
4896
+ });
4897
+ const kind = 'aggregate' === unit.kind ? 'repositories' : 'command' === unit.kind ? 'commands' : 'query' === unit.kind ? 'queries' : 'ports';
4898
+ const { label, saveForFutureUse } = await promptImplementationType('Implementation type:', kind, {
4899
+ existing: unit.labels,
4900
+ purpose: 'all',
4901
+ remember: false,
4902
+ crossContext: 'port' === unit.kind && hasNeighboringBoundedContext(ownerFolder.path)
4903
+ });
4904
+ const { file, className } = createImplementation(ownerFolder, unit, label);
4905
+ const branches = wire_branches_envBranches();
4906
+ const rememberFor = (environments)=>{
4907
+ if (!saveForFutureUse) return;
4908
+ if (systemImplementationChoices(kind, 'port' === unit.kind && hasNeighboringBoundedContext(ownerFolder.path)).some((choice)=>choice.value === label)) return;
4909
+ if (branches.test && environments.includes(branches.test)) rememberImplementation(kind, 'test', label);
4910
+ if (environments.some((environment)=>environment !== branches.test)) rememberImplementation(kind, 'primary', label);
4911
+ };
4912
+ if (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) return void rememberFor(branches.primary);
4913
+ const wireFile = new file_system_File(ownerFolder.path).subitem(contractWireFile(unit).split('/'));
4914
+ const wireName = `wire${contractClassName(unit)}`;
4915
+ const wired = branchesOf(wireFile, wireName);
4916
+ if (!wired) {
4917
+ rememberFor(branches.primary);
4918
+ report(`${wireFile.path} has no ${wireName} = envBranchedWire({...}): wire ${className} there yourself.`);
4919
+ return;
4920
+ }
4921
+ const labelOfWire = new Map(unit.labels.map((x)=>[
4922
+ implementationWireName(x),
4923
+ x
4924
+ ]));
4925
+ const chosenEnvironments = await interaction_checkbox({
4926
+ key: 'environments',
4927
+ message: 'Environments:',
4928
+ choices: [
4929
+ ...new Set([
4930
+ ...branches.test ? [
4931
+ branches.test
4932
+ ] : [],
4933
+ ...branches.primary,
4934
+ ...wired.keys()
4935
+ ])
4936
+ ].map((environment)=>{
4937
+ const current = wired.get(environment);
4938
+ return {
4939
+ name: current ? `${environment} (now: ${labelOfWire.get(current) ?? current})` : environment,
4940
+ value: environment
4941
+ };
4942
+ }),
4943
+ required: true
4944
+ });
4945
+ rememberFor(chosenEnvironments);
4946
+ const before = readWiredModule(wireFile.path, ownerFolder.path);
4947
+ wireFile.update(addBranchedImplementation(wireFile.data, wireName, {
4948
+ importLine: `import { ${className} } from '${relativeImport(wireFile.path, file.path)}'`,
4949
+ className,
4950
+ wireName: implementationWireName(label),
4951
+ environments: chosenEnvironments
4952
+ }));
4953
+ const after = readWiredModule(wireFile.path, ownerFolder.path);
4954
+ const unused = (before?.implementations ?? []).filter((x)=>!after?.implementations.some((y)=>y.className === x.className));
4955
+ for (const implementation of unused)report(`${implementation.className} is no longer used in any environment.`);
4956
+ await wireNewImplementationDependencies(ownerFolder, wireFile, className, inMemoryRepositoryWiring(ownerFolder, unit, wireFile));
4957
+ };
4958
+ const scaffoldNewInfrastructureService = async (boundedContextFolder)=>{
4959
+ const name = await interaction_input({
4960
+ key: 'name',
4961
+ message: 'Name: '
4962
+ });
4963
+ const naming = new UnknownFormatNaming(name);
4964
+ const scaffoldUnitTests = Boolean(config_file_ConfigFile.backend.testingLibrary);
4965
+ const withWiring = config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
4966
+ const wiringFolder = boundedContextFolder.subitem([
4967
+ 'wiring',
4968
+ 'infrastructure-services'
4969
+ ]);
4970
+ const infrastructureServicesFolder = boundedContextFolder.subitem([
4971
+ 'infrastructure',
4972
+ 'services'
4973
+ ]);
4974
+ infrastructureServicesFolder.createFile(`${naming.fileName}-infrastructure-service.ts`, `
4975
+ export class ${naming.ClassName}InfrastructureService {
4976
+
4977
+ }
4978
+ `.trim());
4979
+ if (scaffoldUnitTests) infrastructureServicesFolder.createFile(`${naming.fileName}-infrastructure-service.spec.ts`, `
4980
+ import { describe, test, expect, beforeEach } from '${config_file_ConfigFile.backend.testingLibrary}'
4981
+ ${withWiring ? `import { type ${naming.ClassName}InfrastructureService } from './${naming.fileName}-infrastructure-service'
4982
+ import { wire${naming.ClassName}InfrastructureService } from '../../wiring/infrastructure-services/wire-${naming.fileName}-infrastructure-service'` : `import { ${naming.ClassName}InfrastructureService } from './${naming.fileName}-infrastructure-service'`}
4983
+
4984
+ let ${naming.variableName}InfrastructureService: ${naming.ClassName}InfrastructureService
4985
+
4986
+ beforeEach(() => {
4987
+ ${naming.variableName}InfrastructureService = ${withWiring ? `wire${naming.ClassName}InfrastructureService()` : `new ${naming.ClassName}InfrastructureService()`}
4988
+ })
4989
+
4990
+ describe('${naming.withSpaces}', () => {
4991
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
4992
+ expect(${naming.variableName}InfrastructureService).toBeDefined()
4993
+ })
4994
+ })
4995
+ `.trim());
4996
+ if (withWiring) {
4997
+ const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-infrastructure-service.ts`, `
4998
+ import { wireClass } from '@domain-first/wire'
4999
+ import { ${naming.ClassName}InfrastructureService } from '../../infrastructure/services/${naming.fileName}-infrastructure-service'
5000
+
5001
+ export const wire${naming.ClassName}InfrastructureService = wireClass(
5002
+ ${naming.ClassName}InfrastructureService,
5003
+ []
5004
+ )
5005
+ `.trim());
5006
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
5007
+ }
5008
+ };
5009
+ const scaffoldNewQuery = async (boundedContextFolder)=>{
5010
+ const queriesFolder = boundedContextFolder.subitem([
5011
+ 'application',
5012
+ 'queries'
5013
+ ]);
5014
+ const queryName = await interaction_input({
5015
+ key: 'name',
5016
+ message: 'Name: '
5017
+ });
5018
+ const scaffoldUnitTests = Boolean(config_file_ConfigFile.backend.testingLibrary);
5019
+ const naming = new UnknownFormatNaming(queryName);
5020
+ const withWiring = config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
5021
+ const { label: implementationType } = await promptImplementationType('Query infrastructure implementation type:', 'queries');
5022
+ let addTestImplementation = false;
5023
+ let testImplementationType = '';
5024
+ addTestImplementation = offersTestImplementation() && await interaction_confirm({
5025
+ key: 'withTestImplementation',
5026
+ message: 'Add a test implementation for Query'
5027
+ });
5028
+ if (addTestImplementation) testImplementationType = (await promptImplementationType('Test Query infrastructure implementation type:', 'queries', {
5029
+ existing: [
5030
+ implementationType
5031
+ ],
5032
+ purpose: 'test'
5033
+ })).label;
5034
+ const implementationTypes = [
5035
+ implementationType,
5036
+ testImplementationType
5037
+ ].filter((x)=>!!x);
5038
+ for (const implementation of implementationTypes)createImplementation(boundedContextFolder, {
5039
+ kind: 'query',
5040
+ name: naming.fileName,
5041
+ ownerPath: boundedContextFolder.path,
5042
+ labels: []
5043
+ }, new UnknownFormatNaming(implementation).fileName);
5044
+ if (config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers')) queriesFolder.createFile(`${naming.fileName}-query.ts`, `
5045
+ import type { Handler } from '@domain-first/handlers'
5046
+
5047
+ export abstract class ${naming.ClassName}Query {
5048
+ static inputSchema = {}
5049
+ static outputSchema = {}
5050
+
5051
+ abstract handle: Handler<typeof ${naming.ClassName}Query.inputSchema, typeof ${naming.ClassName}Query.outputSchema>
5052
+ }
5053
+ `.trim());
5054
+ else queriesFolder.createFile(`${naming.fileName}-query.ts`, `
5055
+ export abstract class ${naming.ClassName}Query {
5056
+
5057
+ }`.trim());
5058
+ if (scaffoldUnitTests) {
5059
+ const implementationNaming = new UnknownFormatNaming(implementationType);
5060
+ const specFile = queriesFolder.createFile(`${naming.fileName}-query.spec.ts`, `
5061
+ import { describe, test, expect, beforeEach } from '${config_file_ConfigFile.backend.testingLibrary}'
5062
+ ${withWiring ? `import { type ${naming.ClassName}Query } from './${naming.fileName}-query'
5063
+ import { wire${naming.ClassName}Query } from '../../wiring/queries/wire-${naming.fileName}-query'` : `import { ${implementationNaming.ClassName}${naming.ClassName}Query } from '../../infrastructure/queries/${implementationNaming.fileName}/${implementationNaming.fileName}-${naming.fileName}-query'
5064
+
5065
+ type ${naming.ClassName}Query = ${implementationNaming.ClassName}${naming.ClassName}Query`}
5066
+
5067
+ let ${naming.variableName}Query: ${naming.ClassName}Query
5068
+
5069
+ beforeEach(() => {
5070
+ ${naming.variableName}Query = ${withWiring ? `wire${naming.ClassName}Query()` : `new ${implementationNaming.ClassName}${naming.ClassName}Query()`}
5071
+ })
5072
+
5073
+ describe('${naming.withSpaces} query', () => {
5074
+ test('can be ${withWiring ? 'wired' : 'created via constructor'}', () => {
5075
+ expect(${naming.variableName}Query).toBeDefined()
5076
+ })
5077
+ })
5078
+ `.trim());
5079
+ if (!withWiring && usesInMemoryDb(implementationType)) passInMemoryDb(specFile, `${implementationNaming.ClassName}${naming.ClassName}Query`);
5080
+ }
5081
+ if (config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire')) {
5082
+ const implementationNaming = new UnknownFormatNaming(implementationType);
5083
+ const testImplementationNaming = new UnknownFormatNaming(testImplementationType);
5084
+ const wireFile = boundedContextFolder.subitem([
5085
+ 'wiring',
5086
+ 'queries'
5087
+ ]).createFile(`wire-${naming.fileName}-query.ts`, `
5088
+ import { wireClass } from '@domain-first/wire'
5089
+ import { envBranchedWire } from '../../../../shared-kernel/wiring/env-branched-wire'
5090
+ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName, fileName })=>`import { ${ClassName}${naming.ClassName}Query } from '../../infrastructure/queries/${fileName}/${fileName}-${naming.fileName}-query'`).join('\n')}
5091
+
5092
+ ${implementationTypes.map((x)=>new UnknownFormatNaming(x)).map(({ ClassName })=>`const wire${ClassName}Implementation = wireClass(${ClassName}${naming.ClassName}Query, [])`).join('\n\n')}
5093
+
5094
+ export const wire${naming.ClassName}Query = envBranchedWire(${envBranchedWireArgument(`wire${addTestImplementation ? testImplementationNaming.ClassName : implementationNaming.ClassName}Implementation`, `wire${implementationNaming.ClassName}Implementation`)})
5095
+ `.trim());
5096
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
5097
+ }
5098
+ };
5099
+ const scaffoldNewUseCase = async (boundedContextFolder)=>{
5100
+ const useCasesFolder = boundedContextFolder.subitem([
5101
+ 'application',
5102
+ 'use-cases'
5103
+ ]);
5104
+ const useCaseName = await interaction_input({
5105
+ key: 'name',
5106
+ message: 'Name: '
5107
+ });
5108
+ const naming = new UnknownFormatNaming(useCaseName);
5109
+ const scaffoldUnitTests = Boolean(config_file_ConfigFile.backend.testingLibrary);
5110
+ const withWiring = config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
5111
+ useCasesFolder.createFile(`${naming.fileName}-use-case.ts`, config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers') ? `
5112
+ import { defineHandler } from '@domain-first/handlers'
5113
+
5114
+ export class ${naming.ClassName}UseCase {
5115
+ constructor() {}
5116
+
5117
+ static inputSchema = {}
5118
+ static outputSchema = {}
5119
+
5120
+ handle = defineHandler({
5121
+ inputSchema: ${naming.ClassName}UseCase.inputSchema,
5122
+ outputSchema: ${naming.ClassName}UseCase.outputSchema,
5123
+ handler: async (input) => {
5124
+ return {}
5125
+ }
5126
+ })
5127
+ }
5128
+ `.trim() : `
5129
+ export class ${naming.ClassName}UseCase {
5130
+
5131
+ }
5132
+ `.trim());
5133
+ if (scaffoldUnitTests) useCasesFolder.createFile(`${naming.fileName}-use-case.spec.ts`, `
5134
+ import { describe, test, expect, beforeEach } from '${config_file_ConfigFile.backend.testingLibrary}'
5135
+ ${withWiring ? `import { type ${naming.ClassName}UseCase } from './${naming.fileName}-use-case'
5136
+ import { wire${naming.ClassName}UseCase } from '../../wiring/use-cases/wire-${naming.fileName}-use-case'` : `import { ${naming.ClassName}UseCase } from './${naming.fileName}-use-case'`}
5137
+
5138
+ let ${naming.variableName}UseCase: ${naming.ClassName}UseCase
5139
+
5140
+ beforeEach(() => {
5141
+ ${naming.variableName}UseCase = ${withWiring ? `wire${naming.ClassName}UseCase()` : `new ${naming.ClassName}UseCase()`}
5142
+ })
5143
+
5144
+ describe('${naming.withSpaces} use case', () => {
5145
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
5146
+ expect(${naming.variableName}UseCase).toBeDefined()
5147
+ })
5148
+ })
5149
+ `.trim());
5150
+ if (withWiring) {
5151
+ const wireFile = boundedContextFolder.subitem([
5152
+ 'wiring',
5153
+ 'use-cases'
5154
+ ]).createFile(`wire-${naming.fileName}-use-case.ts`, `
5155
+ import { wireClass } from '@domain-first/wire'
5156
+ import { ${naming.ClassName}UseCase } from '../../application/use-cases/${naming.fileName}-use-case'
5157
+
5158
+ export const wire${naming.ClassName}UseCase = wireClass(
5159
+ ${naming.ClassName}UseCase,
5160
+ []
5161
+ )
5162
+
5163
+ `.trim());
5164
+ await wireNewModuleDependencies(boundedContextFolder, wireFile);
5165
+ }
5166
+ };
5167
+ const scaffoldReactSharedHook = async (presentationReactFolder)=>{
5168
+ const name = await interaction_input({
5169
+ key: 'name',
5170
+ message: 'Name without "use" (e.g. debounce): '
5171
+ });
5172
+ const { ClassName, fileName } = new UnknownFormatNaming(name.trim().replace(/^use-/, ''));
5173
+ presentationReactFolder.subitem([
5174
+ 'hooks'
5175
+ ]).createFile(`use-${fileName}.ts`, `
5176
+ export const use${ClassName} = () => {
5177
+ return {}
5178
+ }
5179
+ `.trim());
5180
+ };
5181
+ const scaffoldReactUIKitComponent = async (presentationReactFolder)=>{
5182
+ const name = await interaction_input({
5183
+ key: 'name',
5184
+ message: 'Name: '
5185
+ });
5186
+ const { ClassName, fileName } = new UnknownFormatNaming(name);
5187
+ const componentFolder = presentationReactFolder.subitem([
5188
+ 'ui-kit',
5189
+ fileName
5190
+ ]);
5191
+ componentFolder.createFile('index.ts', `export * from './${fileName}'`);
5192
+ componentFolder.createFile(`${fileName}.tsx`, `
5193
+ import { type FC } from 'react'
5194
+
5195
+ export type ${ClassName}Props = {}
5196
+
5197
+ export const ${ClassName}: FC<${ClassName}Props> = (props) => {
5198
+ return <></>
5199
+ }
5200
+ `.trim());
5201
+ const { storybookFramework } = config_file_ConfigFile.Instance.data.frontend?.react ?? {};
5202
+ if (storybookFramework) componentFolder.createFile(`${fileName}.stories.tsx`, `
5203
+ import type { Meta, StoryObj } from '${storybookFramework}'
5204
+ import { ${ClassName} } from './${fileName}'
5205
+
5206
+ const meta = {
5207
+ title: 'UI-kit/${ClassName}',
5208
+ component: ${ClassName}
5209
+ } satisfies Meta<typeof ${ClassName}>
5210
+
5211
+ export default meta
5212
+
5213
+ type Story = StoryObj<typeof meta>
5214
+
5215
+ export const Default: Story = {
5216
+ args: {}
5217
+ }
5218
+ `.trim());
5219
+ };
5220
+ const scaffoldReactWidget = async (presentationReactFolder)=>{
5221
+ const widgetName = await interaction_input({
5222
+ key: 'name',
5223
+ message: 'Name (folders split by "/"): ',
5224
+ validate: NestedName.validate
5225
+ });
5226
+ const widgetType = await interaction_select({
5227
+ choices: [
5228
+ 'monolithic',
5229
+ 'with separated ui',
5230
+ 'headless'
5231
+ ],
5232
+ key: 'widgetType',
5233
+ message: 'Type: '
5234
+ });
5235
+ const { folders, folderName, ClassName, fileName, classNameSegments } = new NestedName(widgetName);
5236
+ const folder = presentationReactFolder.subitem([
5237
+ 'widgets',
5238
+ ...folders,
5239
+ folderName
5240
+ ]);
5241
+ const storyTitle = [
5242
+ 'Widgets',
5243
+ ...classNameSegments
5244
+ ].join('/');
5245
+ const widgetFileName = `${fileName}-widget`;
5246
+ const uiFileName = `${fileName}-widget-ui`;
5247
+ const uiModelFileName = `use-${fileName}-ui-model`;
5248
+ folder.createFile('index.ts', `export * from './${widgetFileName}'`);
5249
+ switch(widgetType){
5250
+ case 'monolithic':
5251
+ folder.createFile(`${widgetFileName}.tsx`, `
5252
+ import { type FC } from 'react'
5253
+
5254
+ export type ${ClassName}WidgetProps = {}
5255
+
5256
+ export const ${ClassName}Widget: FC<${ClassName}WidgetProps> = (props) => {
5257
+ return <></>
5258
+ }
5259
+ `.trim());
5260
+ break;
5261
+ case 'with separated ui':
5262
+ {
5263
+ folder.createFile('types.ts', `
5264
+ export type ${ClassName}WidgetProps = { }
5265
+
5266
+ export type ${ClassName}WidgetUIProps = { }
5267
+ `.trim());
5268
+ folder.createFile(`${widgetFileName}.tsx`, `
5269
+ import { type FC } from 'react'
5270
+ import type { ${ClassName}WidgetProps } from './types'
5271
+ import { ${ClassName}WidgetUI } from './ui/${uiFileName}'
5272
+ import { use${ClassName}UIModel } from './hooks/${uiModelFileName}'
5273
+
5274
+ export const ${ClassName}Widget: FC<${ClassName}WidgetProps> = (props) => {
5275
+ const uiModel = use${ClassName}UIModel(props)
5276
+ return <${ClassName}WidgetUI {...uiModel} />
5277
+ }
5278
+
5279
+ export type { ${ClassName}WidgetProps }
5280
+ `.trim());
5281
+ folder.subitem([
5282
+ 'ui'
5283
+ ]).createFile(`${uiFileName}.tsx`, `
5284
+ import { FC } from 'react'
5285
+ import type { ${ClassName}WidgetUIProps } from '../types'
5286
+
5287
+ export const ${ClassName}WidgetUI: FC<${ClassName}WidgetUIProps> = (props) => {
5288
+ return <></>
5289
+ }
5290
+ `.trim());
5291
+ const { storybookFramework } = config_file_ConfigFile.Instance.data.frontend?.react ?? {};
5292
+ if (storybookFramework) folder.subitem([
5293
+ 'ui'
5294
+ ]).createFile(`${uiFileName}.stories.tsx`, `
5295
+ import type { Meta, StoryObj } from '${storybookFramework}'
5296
+ import { ${ClassName}WidgetUI } from './${uiFileName}'
5297
+
5298
+ const meta = {
5299
+ title: '${storyTitle}',
5300
+ component: ${ClassName}WidgetUI
5301
+ } satisfies Meta<typeof ${ClassName}WidgetUI>
5302
+
5303
+ export default meta
5304
+
5305
+ type Story = StoryObj<typeof meta>
5306
+
5307
+ export const Default: Story = {
5308
+ args: {}
5309
+ }
5310
+ `.trim());
5311
+ folder.subitem([
5312
+ 'hooks'
5313
+ ]).createFile(`${uiModelFileName}.ts`, `
5314
+ import type { ${ClassName}WidgetProps, ${ClassName}WidgetUIProps } from '../types'
5315
+
5316
+ export const use${ClassName}UIModel = (widgetProps: ${ClassName}WidgetProps): ${ClassName}WidgetUIProps => {
5317
+ return {}
5318
+ }
5319
+ `.trim());
5320
+ break;
5321
+ }
5322
+ case 'headless':
5323
+ folder.createFile('types.ts', `
5324
+ import { type FC } from 'react'
5325
+
5326
+ export type ${ClassName}WidgetUIProps = { }
5327
+
5328
+ export type ${ClassName}WidgetProps = {
5329
+ UI: FC<${ClassName}WidgetUIProps>
5330
+ }
5331
+
5332
+ `.trim());
5333
+ folder.createFile(`${widgetFileName}.tsx`, `
5334
+ import { type FC } from 'react'
5335
+ import type { ${ClassName}WidgetProps } from './types'
5336
+ import { use${ClassName}UIModel } from './hooks/${uiModelFileName}'
5337
+
5338
+ export const ${ClassName}Widget: FC<${ClassName}WidgetProps> = (props) => {
5339
+ const uiModel = use${ClassName}UIModel(props)
5340
+ return <props.UI {...uiModel} />
5341
+ }
5342
+
5343
+ export type { ${ClassName}WidgetProps }
5344
+ `.trim());
5345
+ folder.subitem([
5346
+ 'hooks'
5347
+ ]).createFile(`${uiModelFileName}.ts`, `
5348
+ import type { ${ClassName}WidgetProps, ${ClassName}WidgetUIProps } from '../types'
5349
+
5350
+ export const use${ClassName}UIModel = (widgetProps: Omit<${ClassName}WidgetProps, 'UI'>): ${ClassName}WidgetUIProps => {
5351
+ return {}
5352
+ }
5353
+ `.trim());
5354
+ break;
5355
+ }
5356
+ };
5357
+ const requireProject = ()=>{
5358
+ try {
5359
+ return new project_root_ProjectRoot().path;
5360
+ } catch {
5361
+ throw new RequestError('PROJECT_NOT_FOUND', 'Run inside a project with package.json.');
5362
+ }
5363
+ };
5364
+ const ownerFolders = (root)=>{
5365
+ const source = new file_system_Folder(root).subitem([
5366
+ config_file_ConfigFile.Instance.data.project.rootFolder
5367
+ ]);
5368
+ return [
5369
+ {
5370
+ name: 'shared-kernel',
5371
+ folder: source.subitem([
5372
+ 'shared-kernel'
5373
+ ])
5374
+ },
5375
+ ...source.subitem([
5376
+ 'bounded-contexts'
5377
+ ]).content.subfolderNames.sort().map((name)=>({
5378
+ name,
5379
+ folder: source.subitem([
5380
+ 'bounded-contexts',
5381
+ name
5382
+ ])
5383
+ }))
5384
+ ];
5385
+ };
5386
+ const ownerFor = (context)=>{
5387
+ const owner = ownerFolders(requireProject()).find((owner)=>owner.name === context);
5388
+ if (!owner) throw new RequestError('CONTEXT_NOT_FOUND', `Unknown context: ${context}.`, {
5389
+ context
5390
+ });
5391
+ return owner.folder;
5392
+ };
5393
+ const precondition = (command)=>{
5394
+ requireProject();
5395
+ if (!config_file_ConfigFile.exists) throw new RequestError('CONFIG_NOT_FOUND', 'Ask the project owner to run df-init.');
5396
+ if (config_file_ConfigFile.outdated) throw new RequestError('CONFIG_OUTDATED', 'The config has the format of an earlier major version: ask the project owner to run df-upgrade.');
5397
+ if ('df-scaffold' === command && !config_file_ConfigFile.Instance.data.backend) throw new RequestError('BACKEND_NOT_CONFIGURED', 'Ask the project owner to run df-init --section backend.');
5398
+ if ('df-react' === command && !config_file_ConfigFile.Instance.data.frontend?.react) throw new RequestError('FRONTEND_NOT_CONFIGURED', 'Ask the project owner to run df-init --section frontend.');
5399
+ };
5400
+ const describeAgentCommand = (command)=>{
5401
+ let root;
5402
+ try {
5403
+ root = new project_root_ProjectRoot().path;
5404
+ } catch {}
5405
+ const configStatus = root && config_file_ConfigFile.exists ? config_file_ConfigFile.outdated ? 'outdated' : 'current' : 'missing';
5406
+ const configured = 'current' === configStatus;
5407
+ const config = configured ? config_file_ConfigFile.Instance.data : void 0;
5408
+ const owners = configured ? ownerFolders(root) : [];
5409
+ const modules = owners.flatMap((owner)=>findWiredModules(owner.folder.path));
5410
+ const relative = (file)=>external_node_path_default().relative(root, file).split(external_node_path_default().sep).join('/');
5411
+ return {
5412
+ schemaVersion: 1,
5413
+ command,
5414
+ requestSchema: external_zod_default().toJSONSchema(requestSchemaFor(command)),
5415
+ project: root ? {
5416
+ root,
5417
+ configured,
5418
+ configStatus,
5419
+ config,
5420
+ contexts: owners.map((owner)=>({
5421
+ name: owner.name,
5422
+ units: findBackendUnits(owner.folder.path).map((unit)=>({
5423
+ id: unitId(unit),
5424
+ kind: unit.kind,
5425
+ name: unit.name,
5426
+ aggregate: unit.aggregate,
5427
+ implementations: unit.labels
5428
+ })),
5429
+ contracts: findContracts(owner.folder.path).map((unit)=>({
5430
+ id: unitId(unit),
5431
+ kind: unit.kind,
5432
+ implementations: unit.labels
5433
+ })),
5434
+ modules: findWiredModules(owner.folder.path).map((module)=>({
5435
+ id: moduleId(module),
5436
+ kind: module.kind,
5437
+ file: relative(module.typeFile),
5438
+ implementations: module.implementations.map((implementation)=>({
5439
+ className: implementation.className,
5440
+ target: `${moduleId(module)}:${implementation.className}`,
5441
+ dependencies: availableDependencies(module, implementation, 'shared-kernel' === owner.name ? modules.filter((module)=>moduleId(module).startsWith('shared-kernel:')) : modules).map(moduleId)
5442
+ }))
5443
+ })),
5444
+ implementationTypes: config?.backend ? Object.fromEntries(implementationKinds.map((kind)=>[
5445
+ kind,
5446
+ {
5447
+ primary: savedImplementations(kind, 'primary'),
5448
+ test: savedImplementations(kind, 'test'),
5449
+ system: systemImplementationChoices(kind, 'shared-kernel' !== owner.name && hasNeighboringBoundedContext(owner.folder.path))
5450
+ }
5451
+ ])) : void 0
5452
+ })),
5453
+ integrations: integrationDescriptionsSafe(configured),
5454
+ reactModules: config?.frontend?.react ? [
5455
+ 'page',
5456
+ 'widget'
5457
+ ].flatMap((kind)=>findReactModules(external_node_path_default().join(root, config.project.rootFolder, 'presentation/react'), kind).map((module)=>({
5458
+ kind,
5459
+ name: module.name,
5460
+ file: relative(module.path)
5461
+ }))) : []
5462
+ } : null
5463
+ };
5464
+ };
5465
+ const integrationDescriptionsSafe = (configured)=>configured ? integrationDescriptions() : [];
5466
+ const answersFor = (command, request, owner)=>{
5467
+ const answers = {};
5468
+ const defaults = {
5469
+ overwrite: request.overwrite ?? false,
5470
+ apply: true,
5471
+ withRepository: false,
5472
+ widgetType: 'with separated ui'
5473
+ };
5474
+ const ignored = new Set([
5475
+ 'operation',
5476
+ 'context',
5477
+ 'overwrite',
5478
+ 'dryRun',
5479
+ 'dependencies',
5480
+ "scriptConflicts",
5481
+ "scriptNames",
5482
+ 'namespace'
5483
+ ]);
5484
+ for (const [key, value] of Object.entries(request))if (!ignored.has(key)) answers[key] = value;
5485
+ for (const [implementation, ids] of Object.entries(request.dependencies ?? {}))answers[`dependencies.${implementation}`] = ids;
5486
+ for (const [script, action] of Object.entries(request.scriptConflicts ?? {}))answers[`scriptConflicts.${script}`] = ({
5487
+ keep: 'Keep existing',
5488
+ replace: 'Replace',
5489
+ rename: 'Use another name'
5490
+ })[action];
5491
+ for (const [script, name] of Object.entries(request.scriptNames ?? {}))answers[`scriptNames.${script}`] = name;
5492
+ defaults.withTestImplementation = Boolean(request.testImplementation);
5493
+ if ('entity' === request.operation || 'value-object' === request.operation) defaults.aggregate = 'No aggregate';
5494
+ if ('separated' === request.widgetType) answers.widgetType = 'with separated ui';
5495
+ if ('df-scaffold' === command) {
5496
+ if ('error' === request.operation || 'error-namespace' === request.operation) defaults.errorAction = 'error-namespace' === request.operation ? 'New namespace' : request.namespace ? `New error in namespace ${request.namespace}` : 'New error without namespace';
5497
+ if ('endpoint' === request.operation) {
5498
+ delete answers.controller;
5499
+ const existing = owner.subitem([
5500
+ 'presentation',
5501
+ 'rest'
5502
+ ]).content.subfolderNames.includes(request.controller);
5503
+ answers.controllerSelection = existing ? request.controller : 'New controller';
5504
+ if (!existing) answers.controllerName = request.controller;
5505
+ }
5506
+ if ('move' === request.operation) defaults.targetContext = request.context;
5507
+ }
5508
+ return {
5509
+ answers,
5510
+ defaults
5511
+ };
5512
+ };
5513
+ const executeScaffold = async (request, owner)=>{
5514
+ if ('shared-kernel' === request.context && [
5515
+ 'aggregate',
5516
+ 'use-case',
5517
+ 'command',
5518
+ 'query',
5519
+ 'endpoint'
5520
+ ].includes(request.operation)) throw new RequestError('OPERATION_NOT_AVAILABLE', 'This operation requires a bounded context.');
5521
+ if ('aggregate' === request.operation && !request.withRepository && (request.implementation || request.testImplementation || request.dependencies)) throw new RequestError('INVALID_REQUEST', 'Repository options require withRepository: true.');
5522
+ if ('error' === request.operation && request.namespace && !owner.subitem([
5523
+ 'domain',
5524
+ 'errors'
5525
+ ]).content.fileNames.includes(request.namespace)) throw new RequestError('TARGET_NOT_FOUND', `Unknown namespace: ${request.namespace}.`);
5526
+ if ('implementation' === request.operation && !findContracts(owner.path).length) throw new RequestError('TARGET_NOT_FOUND', 'No contracts in this context.');
5527
+ if ('move' === request.operation && !findBackendUnits(owner.path).length) throw new RequestError('TARGET_NOT_FOUND', 'No modules in this context.');
5528
+ if ('wire-dependency' === request.operation && (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') || !findWiredModules(owner.path).length)) throw new RequestError('TARGET_NOT_FOUND', 'No wired modules in this context.');
5529
+ if ('endpoint' === request.operation) {
5530
+ if (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers-rest') || !findRestEndpointGenerator(new file_system_Folder(requireProject()).subitem([
5531
+ config_file_ConfigFile.Instance.data.project.rootFolder,
5532
+ 'shared-kernel'
5533
+ ]))) throw new RequestError('REST_NOT_CONFIGURED', 'Add the REST endpoint generator integration first.');
5534
+ }
5535
+ if (('entity' === request.operation || 'value-object' === request.operation) && request.aggregate && !owner.subitem([
5536
+ 'domain',
5537
+ 'aggregates'
5538
+ ]).content.subfolderNames.includes(request.aggregate)) throw new RequestError('TARGET_NOT_FOUND', `Unknown aggregate: ${request.aggregate}.`);
5539
+ const actions = {
5540
+ aggregate: ()=>scaffoldNewAggregateUseCase(owner),
5541
+ entity: ()=>scaffoldNewDomainObject(owner, 'entity'),
5542
+ 'value-object': ()=>scaffoldNewDomainObject(owner, 'value-object'),
5543
+ error: ()=>scaffoldNewErrorUseCase(owner),
5544
+ 'error-namespace': ()=>scaffoldNewErrorUseCase(owner),
5545
+ 'domain-service': ()=>scaffoldNewDomainService(owner),
5546
+ 'application-service': ()=>scaffoldNewApplicationService(owner),
5547
+ 'infrastructure-service': ()=>scaffoldNewInfrastructureService(owner),
5548
+ 'presentation-service': ()=>scaffoldNewPresentationService(owner),
5549
+ 'use-case': ()=>scaffoldNewUseCase(owner),
5550
+ command: ()=>scaffoldNewCommand(owner),
5551
+ query: ()=>scaffoldNewQuery(owner),
5552
+ port: ()=>scaffoldNewApplicationPort(owner),
5553
+ implementation: ()=>scaffoldNewImplementation(owner),
5554
+ endpoint: ()=>scaffoldNewHandlersRestEndpoint(owner),
5555
+ 'wire-dependency': ()=>wireDependency(owner),
5556
+ move: ()=>moveBackendUnitUseCase(owner)
5557
+ };
5558
+ return actions[request.operation]();
5559
+ };
5560
+ const executeReact = async (request)=>{
5561
+ const folder = new file_system_Folder(requireProject()).subitem([
5562
+ config_file_ConfigFile.Instance.data.project.rootFolder,
5563
+ 'presentation/react'
5564
+ ]);
5565
+ if (request.operation.startsWith('move-') && !findReactModules(folder.path, 'move-page' === request.operation ? 'page' : 'widget').length) throw new RequestError('TARGET_NOT_FOUND', 'No React modules to move.');
5566
+ const actions = {
5567
+ page: ()=>scaffoldReactPage(folder),
5568
+ widget: ()=>scaffoldReactWidget(folder),
5569
+ 'ui-kit-component': ()=>scaffoldReactUIKitComponent(folder),
5570
+ 'shared-hook': ()=>scaffoldReactSharedHook(folder),
5571
+ 'move-page': ()=>moveReactModuleUseCase(folder, 'page'),
5572
+ 'move-widget': ()=>moveReactModuleUseCase(folder, 'widget')
5573
+ };
5574
+ return actions[request.operation]();
5575
+ };
5576
+ const executeAgentRequest = async (command, value)=>{
5577
+ discardPendingChanges();
5578
+ try {
5579
+ const parsed = requestSchemaFor(command).safeParse(value);
5580
+ if (!parsed.success) throw new RequestError('INVALID_REQUEST', 'Request does not match the operation schema.', {
5581
+ issues: parsed.error.issues.map((issue)=>({
5582
+ field: issue.path.join('.'),
5583
+ message: issue.message
5584
+ }))
5585
+ });
5586
+ const request = parsed.data;
5587
+ precondition(command);
5588
+ const root = requireProject();
5589
+ const owner = 'df-scaffold' === command && 'bounded-context' !== request.operation ? ownerFor(request.context) : void 0;
5590
+ const { answers, defaults } = answersFor(command, request, owner);
5591
+ const execution = await runWithAnswers(answers, defaults, async ()=>{
5592
+ let nextSteps = [];
5593
+ if ('df-scaffold' === command) if ('bounded-context' === request.operation) await scaffoldNewBoundedContextUseCase();
5594
+ else await executeScaffold(request, owner);
5595
+ else if ('df-react' === command) await executeReact(request);
5596
+ else nextSteps = await addIntegration({
5597
+ save: false
5598
+ });
5599
+ assertAnswersConsumed();
5600
+ const relative = (file)=>external_node_path_default().relative(root, file).split(external_node_path_default().sep).join('/');
5601
+ const planned = pendingChanges();
5602
+ const files = {
5603
+ created: planned.created.map(relative),
5604
+ updated: planned.updated.map(relative),
5605
+ deleted: planned.deleted.map(relative)
5606
+ };
5607
+ const directories = planned.directories.map(relative);
5608
+ const overwriteRequired = filesToOverwrite({
5609
+ changedOnly: true
5610
+ }).map(relative);
5611
+ if (request.dryRun) discardPendingChanges();
5612
+ else if (!await savePendingChanges()) throw new RequestError('CANCELLED', 'Nothing was written.');
5613
+ return {
5614
+ schemaVersion: 1,
5615
+ ok: true,
5616
+ operation: request.operation,
5617
+ dryRun: request.dryRun ?? false,
5618
+ files,
5619
+ directories,
5620
+ overwriteRequired,
5621
+ nextSteps
5622
+ };
5623
+ });
5624
+ return {
5625
+ ...execution.result,
5626
+ messages: execution.messages
5627
+ };
5628
+ } catch (error) {
5629
+ discardPendingChanges();
5630
+ throw error;
5631
+ }
5632
+ };
5633
+ const agentError = (error)=>({
5634
+ schemaVersion: 1,
5635
+ ok: false,
5636
+ error: {
5637
+ code: error instanceof RequestError ? error.code : error instanceof external_zod_default().ZodError ? 'INVALID_CONFIG' : 'OPERATION_FAILED',
5638
+ message: error instanceof Error ? error.message : String(error),
5639
+ ...error instanceof RequestError && error.details ? {
5640
+ details: error.details
5641
+ } : {}
5642
+ }
5643
+ });
5644
+ const runCLI = async (command, interactive)=>{
5645
+ const args = process.argv.slice(2);
5646
+ const machine = args.some((arg)=>'--request' === arg || arg.startsWith('--request=') || '--describe' === arg || arg.startsWith('--describe='));
5647
+ if (!machine) {
5648
+ if ('df-scaffold' === command && args.some((arg)=>'--help' !== arg && '-h' !== arg)) throw new RequestError('INVALID_ARGUMENTS', 'Use --request <json|->, --describe, or run without arguments.');
5649
+ await interactive();
5650
+ return;
5651
+ }
5652
+ try {
5653
+ const { values } = (0, external_node_util_namespaceObject.parseArgs)({
5654
+ args,
5655
+ options: {
5656
+ request: {
5657
+ type: 'string'
5658
+ },
5659
+ describe: {
5660
+ type: 'boolean'
5661
+ }
5662
+ }
5663
+ });
5664
+ if (values.describe && void 0 !== values.request) throw new RequestError('INVALID_ARGUMENTS', 'Choose --describe or --request.');
5665
+ if (values.describe) console.log(JSON.stringify(describeAgentCommand(command)));
5666
+ else {
5667
+ let value;
5668
+ try {
5669
+ value = JSON.parse('-' === values.request ? external_node_fs_default().readFileSync(0, 'utf8') : values.request);
5670
+ } catch {
5671
+ throw new RequestError('INVALID_JSON', 'Provide valid JSON in --request, or use --request - with JSON on stdin.');
5672
+ }
5673
+ console.log(JSON.stringify(await executeAgentRequest(command, value)));
5674
+ }
5675
+ } catch (error) {
5676
+ console.log(JSON.stringify(agentError(error)));
5677
+ process.exitCode = 1;
5678
+ }
5679
+ };
5680
+ runCLI('df-integration', async ()=>{
5681
+ const help = `Usage: df-integration
5682
+
5683
+ Adds integrations to a Domain-First project: the REST endpoint generator,
5684
+ the in-memory DB, Storybook, Prisma, Vitest, Playwright, integration tests,
5685
+ OpenAPI and Orval. Several can be selected at once. Changes project files and prints
5686
+ the install commands; nothing is installed or run.
5687
+
5688
+ Options:
5689
+ --request <json|-> execute an operation without prompts; - reads stdin
5690
+ --describe output request schema and project IDs as JSON
5691
+ -h, --help show this help`;
5692
+ const { values } = (0, external_node_util_namespaceObject.parseArgs)({
5693
+ options: {
5694
+ help: {
5695
+ type: 'boolean',
5696
+ short: 'h',
5697
+ default: false
5698
+ }
5699
+ }
5700
+ });
5701
+ if (values.help) {
5702
+ console.log(help);
5703
+ process.exit(0);
5704
+ }
5705
+ if (!config_file_ConfigFile.exists) {
5706
+ console.log('No domain-first.project-structure.config.json found: run df-init first to initialize the project.');
5707
+ process.exit(1);
5708
+ }
5709
+ if (config_file_ConfigFile.outdated) {
5710
+ console.log(outdatedConfigMessage);
5711
+ process.exit(1);
5712
+ }
5713
+ await addIntegration();
5714
+ }).catch((error)=>{
5715
+ console.error(error);
5716
+ process.exitCode = 1;
5717
+ });
2121
5718
  for(var __rspack_i in __webpack_exports__)exports[__rspack_i] = __webpack_exports__[__rspack_i];
2122
5719
  Object.defineProperty(exports, '__esModule', {
2123
5720
  value: true