@domain-first/project-structure 2.18.1 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -190,6 +190,27 @@ class ConfigFile {
190
190
  new File(ConfigFile.path).data = JSON.stringify(config, null, '\t');
191
191
  };
192
192
  }
193
+ const printNextSteps = (nextSteps)=>{
194
+ const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
195
+ const commands = nextSteps.filter(isCommand);
196
+ const notes = nextSteps.filter((line)=>!isCommand(line));
197
+ const sections = [];
198
+ if (commands.length) sections.push([
199
+ 'Run these commands to install the required dependencies:',
200
+ ...commands.map((line)=>styleText([
201
+ 'bold',
202
+ 'cyan'
203
+ ], line))
204
+ ].join('\n'));
205
+ if (notes.length) sections.push([
206
+ 'Additional information:',
207
+ ...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + styleText([
208
+ 'bold',
209
+ 'cyan'
210
+ ], path)))
211
+ ].join('\n'));
212
+ if (sections.length) console.log(sections.join('\n\n'));
213
+ };
193
214
  const savePendingChanges = async ()=>{
194
215
  const overwrittenFiles = filesToOverwrite();
195
216
  if (overwrittenFiles.length) {
@@ -1132,97 +1153,7 @@ const addIntegration = async ()=>{
1132
1153
  }))
1133
1154
  });
1134
1155
  const nextSteps = await integration.run();
1135
- if (await savePendingChanges()) {
1136
- const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
1137
- const commands = nextSteps.filter(isCommand);
1138
- const notes = nextSteps.filter((line)=>!isCommand(line));
1139
- const sections = [];
1140
- if (commands.length) sections.push([
1141
- 'Run these commands to install the required dependencies:',
1142
- ...commands.map((line)=>styleText([
1143
- 'bold',
1144
- 'cyan'
1145
- ], line))
1146
- ].join('\n'));
1147
- if (notes.length) sections.push([
1148
- 'Additional information:',
1149
- ...notes.map((line)=>line.replace(/^(\s*Add )(!\S+)/, (_, prefix, path)=>prefix + styleText([
1150
- 'bold',
1151
- 'cyan'
1152
- ], path)))
1153
- ].join('\n'));
1154
- if (sections.length) console.log(sections.join('\n\n'));
1155
- }
1156
- };
1157
- const initializeUseCase = async ()=>{
1158
- const rootFolderName = await input({
1159
- message: 'Root folder (use "/" for inner folders):',
1160
- default: 'src'
1161
- });
1162
- const domainFirstPackages = await prompts_checkbox({
1163
- message: '@domain-first packages',
1164
- choices: [
1165
- '@domain-first/types',
1166
- '@domain-first/errors',
1167
- '@domain-first/handlers',
1168
- '@domain-first/wire',
1169
- '@domain-first/handlers-rest'
1170
- ]
1171
- });
1172
- const defaultPersistenceLayerImplementation = await input({
1173
- message: 'Default persistence layer implementation:'
1174
- });
1175
- const useReact = await prompts_confirm({
1176
- message: 'Use React'
1177
- });
1178
- let storybookFramework;
1179
- const withStorybook = useReact ? await prompts_confirm({
1180
- message: 'Use Storybook'
1181
- }) : false;
1182
- if (withStorybook) storybookFramework = await input({
1183
- message: 'Storybook framework package:',
1184
- default: '@storybook/react-vite'
1185
- });
1186
- let testingLibrary;
1187
- const withTests = await prompts_confirm({
1188
- message: 'Scaffold unit tests'
1189
- });
1190
- if (withTests) testingLibrary = await input({
1191
- message: 'Unit testing library:',
1192
- default: 'vitest'
1193
- });
1194
- ConfigFile.write({
1195
- rootFolder: rootFolderName,
1196
- domainFirstPackages,
1197
- defaultPersistenceLayerImplementation,
1198
- useReact,
1199
- storybookFramework,
1200
- testingLibrary
1201
- });
1202
- const { path } = new ProjectRoot();
1203
- const rootFolder = new Folder(path);
1204
- if (domainFirstPackages.includes('@domain-first/wire')) rootFolder.subitem([
1205
- rootFolderName,
1206
- 'shared',
1207
- 'wiring'
1208
- ]).createFile('env-branched-wire.ts', `
1209
- import { branchedWire } from '@domain-first/wire'
1210
-
1211
- export const envBranchedWire = branchedWire(() => {
1212
- return process.env.NODE_ENV ?? 'development' as 'test' | 'development' | 'production'
1213
- });
1214
- `.trim());
1215
- if (domainFirstPackages.includes('@domain-first/errors')) rootFolder.subitem([
1216
- rootFolderName,
1217
- 'shared'
1218
- ]).subitem([
1219
- 'domain',
1220
- 'errors'
1221
- ]).createFile('index.ts', `
1222
- import { errorNamespace } from '@domain-first/errors'
1223
-
1224
- export const SharedErrors = errorNamespace('shared')
1225
- `.trim());
1156
+ if (await savePendingChanges()) printNextSteps(nextSteps);
1226
1157
  };
1227
1158
  class UnknownFormatNaming {
1228
1159
  rawSource;
@@ -1252,328 +1183,65 @@ class UnknownFormatNaming {
1252
1183
  return this.fileName.replaceAll('-', ' ');
1253
1184
  }
1254
1185
  }
1255
- const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
1256
- class NestedName {
1257
- folders;
1258
- folderName;
1259
- fileName;
1260
- ClassName;
1261
- classNameSegments;
1262
- constructor(rawSource){
1263
- const segments = splitSegments(rawSource);
1264
- this.folders = segments.slice(0, -1);
1265
- this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
1266
- this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
1267
- this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
1268
- this.ClassName = this.classNameSegments.join('');
1269
- }
1270
- static validate = (rawSource)=>{
1271
- const segments = splitSegments(rawSource);
1272
- if (!segments.length) return 'Name is required';
1273
- if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
1274
- return true;
1275
- };
1276
- }
1277
- const ignoredFolders = new Set([
1278
- 'node_modules',
1279
- '.git',
1280
- '.next',
1281
- 'dist',
1282
- 'build',
1283
- 'out',
1284
- 'coverage',
1285
- 'storybook-static'
1286
- ]);
1287
- const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
1288
- const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1289
- const react_module_move_walk = (folder)=>{
1290
- if (!node_fs.existsSync(folder)) return [];
1291
- return node_fs.readdirSync(folder, {
1292
- withFileTypes: true
1293
- }).flatMap((entry)=>{
1294
- const entryPath = node_path.join(folder, entry.name);
1295
- if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : react_module_move_walk(entryPath);
1296
- return entry.isFile() ? [
1297
- entryPath
1298
- ] : [];
1299
- });
1300
- };
1301
- const toPosix = (value)=>value.split(node_path.sep).join('/');
1302
- const nestedName = (folders, fileBase)=>{
1303
- const prefix = `${folders.join('-')}-`;
1304
- const last = folders.length && fileBase.startsWith(prefix) ? fileBase.slice(prefix.length) : fileBase;
1305
- return [
1306
- ...folders,
1307
- last
1308
- ].join('/');
1309
- };
1310
- const declaredClassName = (filePath, suffix, name)=>{
1311
- const content = node_fs.readFileSync(filePath, 'utf8');
1312
- const declared = content.match(new RegExp(`export\\s+(?:const|function)\\s+(\\w+)${suffix}\\b`))?.[1];
1313
- return declared ?? new NestedName(name).ClassName;
1314
- };
1315
- const findReactModules = (reactFolder, kind)=>{
1316
- const modules = 'page' === kind ? react_module_move_walk(node_path.join(reactFolder, 'pages')).filter((file)=>file.endsWith('-page.tsx')).map((file)=>{
1317
- const folders = node_path.relative(node_path.join(reactFolder, 'pages'), node_path.dirname(file)).split(node_path.sep).filter((segment)=>!!segment);
1318
- const fileBase = node_path.basename(file, '-page.tsx');
1319
- const name = nestedName(folders, fileBase);
1320
- return {
1321
- kind,
1322
- name,
1323
- path: file,
1324
- fileBase,
1325
- ClassName: declaredClassName(file, 'Page', name)
1326
- };
1327
- }) : react_module_move_walk(node_path.join(reactFolder, 'widgets')).filter((file)=>file.endsWith('-widget.tsx')).map((file)=>{
1328
- const folder = node_path.dirname(file);
1329
- const name = toPosix(node_path.relative(node_path.join(reactFolder, 'widgets'), folder));
1330
- return {
1331
- kind,
1332
- name,
1333
- path: folder,
1334
- fileBase: node_path.basename(file, '-widget.tsx'),
1335
- ClassName: declaredClassName(file, 'Widget', name)
1336
- };
1337
- });
1338
- return modules.sort((a, b)=>a.name.localeCompare(b.name));
1186
+ const wiring_layers = [
1187
+ 'domain',
1188
+ 'application',
1189
+ 'infrastructure',
1190
+ 'presentation'
1191
+ ];
1192
+ const visibleLayers = {
1193
+ domain: [
1194
+ 'domain'
1195
+ ],
1196
+ application: [
1197
+ 'domain',
1198
+ 'application'
1199
+ ],
1200
+ infrastructure: [
1201
+ 'domain',
1202
+ 'infrastructure'
1203
+ ],
1204
+ presentation: [
1205
+ 'application',
1206
+ 'presentation'
1207
+ ]
1339
1208
  };
1340
- const react_module_move_targetPath = (reactFolder, module, rawName)=>{
1341
- const { folders, folderName, fileName } = new NestedName(rawName);
1342
- return 'page' === module.kind ? node_path.join(reactFolder, 'pages', ...folders, `${fileName}-page.tsx`) : node_path.join(reactFolder, 'widgets', ...folders, folderName);
1209
+ const branchedTypeFiles = {
1210
+ repositories: (fileBase)=>[
1211
+ 'domain',
1212
+ 'aggregates',
1213
+ fileBase.replace(/-repository$/, ''),
1214
+ `${fileBase}.ts`
1215
+ ],
1216
+ commands: (fileBase)=>[
1217
+ 'application',
1218
+ 'commands',
1219
+ 'execution',
1220
+ `${fileBase}.ts`
1221
+ ],
1222
+ queries: (fileBase)=>[
1223
+ 'application',
1224
+ 'queries',
1225
+ 'execution',
1226
+ `${fileBase}.ts`
1227
+ ],
1228
+ 'application-ports': (fileBase)=>[
1229
+ 'application',
1230
+ 'ports',
1231
+ `${fileBase}.ts`
1232
+ ]
1343
1233
  };
1344
- const validateMove = (reactFolder, module, rawName)=>{
1345
- const nameError = NestedName.validate(rawName);
1346
- if (true !== nameError) return nameError;
1347
- const target = react_module_move_targetPath(reactFolder, module, rawName);
1348
- if (target !== module.path && node_fs.existsSync(target)) return `${node_path.relative(reactFolder, target)} already exists`;
1349
- if (target.startsWith(`${module.path}${node_path.sep}`)) return 'A widget cannot be moved into itself';
1350
- return true;
1234
+ const layerOf = (file, contextPath)=>{
1235
+ const [firstSegment] = node_path.relative(contextPath, file).split(node_path.sep);
1236
+ return wiring_layers.find((layer)=>layer === firstSegment);
1351
1237
  };
1352
- const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
1353
- const readAliases = (projectRoot)=>{
1354
- const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
1355
- if (!node_fs.existsSync(tsconfig)) return [];
1356
- try {
1357
- const { compilerOptions = {} } = JSON.parse(stripJsonComments(node_fs.readFileSync(tsconfig, 'utf8')));
1358
- const base = node_path.resolve(projectRoot, compilerOptions.baseUrl ?? '.');
1359
- return Object.entries(compilerOptions.paths ?? {}).filter(([pattern, targets])=>pattern.endsWith('*') && targets[0]?.endsWith('*')).map(([pattern, [target]])=>({
1360
- prefix: pattern.slice(0, -1),
1361
- target: node_path.resolve(base, target.slice(0, -1))
1362
- }));
1363
- } catch {
1364
- return [];
1238
+ const namedImports = (source, fromFile)=>{
1239
+ const result = new Map();
1240
+ for (const [, names, importPath] of source.matchAll(/import\s*(?:type\s*)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g))for (const name of names.split(',')){
1241
+ const cleanName = name.replace(/^\s*type\s+/, '').trim();
1242
+ if (cleanName) result.set(cleanName, `${node_path.resolve(node_path.dirname(fromFile), importPath)}.ts`);
1365
1243
  }
1366
- };
1367
- const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
1368
- const reExportPattern = /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*(['"])([^'"\n]+)\1/g;
1369
- const importPaths = (file)=>{
1370
- const withoutExtension = file.replace(codeExtension, '');
1371
- return 'index' === node_path.basename(withoutExtension) ? [
1372
- withoutExtension,
1373
- node_path.dirname(withoutExtension)
1374
- ] : [
1375
- withoutExtension
1376
- ];
1377
- };
1378
- const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
1379
- const newName = new NestedName(rawName);
1380
- const target = react_module_move_targetPath(reactFolder, module, rawName);
1381
- const newClassName = newName.ClassName;
1382
- const renameFile = (name)=>name.replace(new RegExp(`^(use-)?${escapeRegExp(module.fileBase)}(?=[-.])`), (_, use = '')=>`${use}${newName.fileName}`);
1383
- const oldFolder = 'page' === module.kind ? node_path.dirname(module.path) : module.path;
1384
- const newFolder = 'page' === module.kind ? node_path.dirname(target) : target;
1385
- const ownsPath = (candidate)=>'page' === module.kind ? node_path.dirname(candidate) === oldFolder && new RegExp(`^${escapeRegExp(module.fileBase)}-page(?:\\.|$)`).test(node_path.basename(candidate)) : candidate === oldFolder || candidate.startsWith(`${oldFolder}${node_path.sep}`);
1386
- const movedPath = (candidate)=>{
1387
- if (!ownsPath(candidate)) return;
1388
- const segments = node_path.relative(oldFolder, candidate).split(node_path.sep);
1389
- const last = segments.length - 1;
1390
- segments[last] = renameFile(segments[last]);
1391
- return node_path.join(newFolder, ...segments);
1392
- };
1393
- const moduleFiles = 'page' === module.kind ? node_fs.readdirSync(oldFolder).map((name)=>node_path.join(oldFolder, name)).filter((file)=>node_fs.statSync(file).isFile() && ownsPath(file)) : react_module_move_walk(oldFolder);
1394
- const moves = new Map(moduleFiles.map((file)=>[
1395
- file,
1396
- movedPath(file) ?? file
1397
- ]));
1398
- const aliases = readAliases(projectRoot);
1399
- const resolve = (specifier, fromFile)=>{
1400
- if (specifier.startsWith('.')) return {
1401
- resolved: node_path.resolve(node_path.dirname(fromFile), specifier),
1402
- alias: void 0
1403
- };
1404
- const alias = aliases.find(({ prefix })=>specifier.startsWith(prefix));
1405
- return alias ? {
1406
- resolved: node_path.resolve(alias.target, specifier.slice(alias.prefix.length)),
1407
- alias
1408
- } : void 0;
1409
- };
1410
- const specifierFor = (fromFile, toPath, alias)=>{
1411
- const aliased = alias && toPosix(node_path.relative(alias.target, toPath));
1412
- if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
1413
- const relative = toPosix(node_path.relative(node_path.dirname(fromFile), toPath));
1414
- return relative.startsWith('.') ? relative : `./${relative}`;
1415
- };
1416
- const suffixes = 'page' === module.kind ? 'Page' : 'Widget|UIModel';
1417
- const classPattern = new RegExp(`(?<![\\w$])(use)?${escapeRegExp(module.ClassName)}(?=${suffixes})`, 'g');
1418
- const oldTitle = `Widgets/${module.name.split('/').map((segment)=>new NestedName(segment).ClassName).join('/')}`;
1419
- const titlePattern = new RegExp(`(['"\`])${escapeRegExp(oldTitle)}\\1`, 'g');
1420
- const newTitle = [
1421
- 'Widgets',
1422
- ...newName.classNameSegments
1423
- ].join('/');
1424
- const codeFiles = new Map(react_module_move_walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
1425
- file,
1426
- node_fs.readFileSync(file, 'utf8')
1427
- ]));
1428
- const barrels = new Set();
1429
- const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
1430
- for(let found = true; found;){
1431
- found = false;
1432
- for (const [file, content] of codeFiles){
1433
- if (moves.has(file) || isBarrel(file)) continue;
1434
- const reExportsModule = [
1435
- ...content.matchAll(reExportPattern)
1436
- ].some(([, , specifier])=>{
1437
- const resolution = resolve(specifier, file);
1438
- return !!resolution && (!!movedPath(resolution.resolved) || isBarrel(resolution.resolved));
1439
- });
1440
- if (reExportsModule) {
1441
- for (const importPath of importPaths(file))barrels.add(importPath);
1442
- found = true;
1443
- }
1444
- }
1445
- }
1446
- const rewrite = (content, oldFile, newFile)=>{
1447
- let referencesModule = false;
1448
- const rewritten = content.replace(specifierPattern, (match, keyword, quote, specifier)=>{
1449
- const resolution = resolve(specifier, oldFile);
1450
- if (!resolution) return match;
1451
- const moved = movedPath(resolution.resolved);
1452
- if (moved || isBarrel(resolution.resolved)) referencesModule = true;
1453
- if (!moved && oldFile === newFile) return match;
1454
- const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
1455
- return `${keyword}${quote}${next}${quote}`;
1456
- });
1457
- if (!referencesModule && !moves.has(oldFile)) return content;
1458
- const renamed = rewritten.replace(classPattern, (_, use = '')=>`${use}${newClassName}`);
1459
- return moves.has(oldFile) && 'widget' === module.kind ? renamed.replace(titlePattern, (_, quote)=>`${quote}${newTitle}${quote}`) : renamed;
1460
- };
1461
- for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new File(file).moveTo(newFile, reactFolder);
1462
- const updated = [];
1463
- for (const [file, content] of codeFiles){
1464
- const newFile = moves.get(file);
1465
- const next = rewrite(content, file, newFile ?? file);
1466
- if (newFile && newFile !== file) {
1467
- new File(newFile).data = next;
1468
- new File(file).delete(reactFolder);
1469
- } else if (next !== content) {
1470
- new File(file).update(next);
1471
- if (!newFile) updated.push(file);
1472
- }
1473
- }
1474
- return {
1475
- moves: [
1476
- ...moves
1477
- ].filter(([from, to])=>from !== to),
1478
- updated
1479
- };
1480
- };
1481
- const moveReactModuleUseCase = async (presentationReactFolder, kind)=>{
1482
- const reactFolder = presentationReactFolder.path;
1483
- const modules = findReactModules(reactFolder, kind);
1484
- if (!modules.length) return void console.log(`No ${kind}s generated by df-ps were found.`);
1485
- const module = await prompts_select({
1486
- message: 'page' === kind ? 'Page:' : 'Widget:',
1487
- choices: modules.map((value)=>({
1488
- name: value.name,
1489
- value,
1490
- description: node_path.relative(reactFolder, value.path)
1491
- }))
1492
- });
1493
- const name = await input({
1494
- message: 'New name (folders split by "/"):',
1495
- default: module.name,
1496
- validate: (value)=>validateMove(reactFolder, module, value)
1497
- });
1498
- const root = new ProjectRoot().path;
1499
- const { moves, updated } = moveReactModule(root, reactFolder, module, name);
1500
- if (!moves.length && !updated.length) return void console.log('Nothing to change.');
1501
- const relative = (file)=>node_path.relative(root, file);
1502
- console.log([
1503
- 'Files to move:',
1504
- ...moves.map(([from, to])=>` ${relative(from)} → ${relative(to)}`),
1505
- ...updated.length ? [
1506
- 'Files with updated imports:',
1507
- ...updated.map((file)=>` ${relative(file)}`)
1508
- ] : []
1509
- ].join('\n'));
1510
- if (!await prompts_confirm({
1511
- message: 'Apply?',
1512
- default: true
1513
- })) {
1514
- discardPendingChanges();
1515
- console.log('Cancelled: nothing was written.');
1516
- }
1517
- };
1518
- const wiring_layers = [
1519
- 'domain',
1520
- 'application',
1521
- 'infrastructure',
1522
- 'presentation'
1523
- ];
1524
- const visibleLayers = {
1525
- domain: [
1526
- 'domain'
1527
- ],
1528
- application: [
1529
- 'domain',
1530
- 'application'
1531
- ],
1532
- infrastructure: [
1533
- 'domain',
1534
- 'infrastructure'
1535
- ],
1536
- presentation: [
1537
- 'application',
1538
- 'presentation'
1539
- ]
1540
- };
1541
- const branchedTypeFiles = {
1542
- repositories: (fileBase)=>[
1543
- 'domain',
1544
- 'aggregates',
1545
- fileBase.replace(/-repository$/, ''),
1546
- `${fileBase}.ts`
1547
- ],
1548
- commands: (fileBase)=>[
1549
- 'application',
1550
- 'commands',
1551
- 'execution',
1552
- `${fileBase}.ts`
1553
- ],
1554
- queries: (fileBase)=>[
1555
- 'application',
1556
- 'queries',
1557
- 'execution',
1558
- `${fileBase}.ts`
1559
- ],
1560
- 'application-ports': (fileBase)=>[
1561
- 'application',
1562
- 'ports',
1563
- `${fileBase}.ts`
1564
- ]
1565
- };
1566
- const layerOf = (file, contextPath)=>{
1567
- const [firstSegment] = node_path.relative(contextPath, file).split(node_path.sep);
1568
- return wiring_layers.find((layer)=>layer === firstSegment);
1569
- };
1570
- const namedImports = (source, fromFile)=>{
1571
- const result = new Map();
1572
- for (const [, names, importPath] of source.matchAll(/import\s*(?:type\s*)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g))for (const name of names.split(',')){
1573
- const cleanName = name.replace(/^\s*type\s+/, '').trim();
1574
- if (cleanName) result.set(cleanName, `${node_path.resolve(node_path.dirname(fromFile), importPath)}.ts`);
1575
- }
1576
- return result;
1244
+ return result;
1577
1245
  };
1578
1246
  const isEndpointWire = (wiringRelativePath)=>wiringRelativePath.startsWith([
1579
1247
  'presentation',
@@ -1661,7 +1329,6 @@ const kindRules = {
1661
1329
  };
1662
1330
  const wiring_implementationType = (consumer, implementation)=>consumer.branched ? node_path.basename(node_path.dirname(implementation.file)) : void 0;
1663
1331
  const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && `-${node_path.basename(candidate.typeFile, '.ts')}-`.includes(`-${implementation}-`);
1664
- const isSuggestedEndpointGenerator = (candidate)=>candidate.typeName.toLowerCase().includes('endpoint');
1665
1332
  const canDependOn = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && (kindRules[consumer.kind]?.(candidate, consumer) ?? true);
1666
1333
  const availableDependencies = (consumer, implementation, candidates)=>{
1667
1334
  const wired = wiredDependencyNames(new File(consumer.wireFile).data, implementation.className);
@@ -1876,78 +1543,524 @@ const contextAndSharedModules = (boundedContextFolder)=>{
1876
1543
  }))
1877
1544
  ];
1878
1545
  };
1879
- const promptDependencies = async (boundedContextFolder, consumer, implementations = consumer.implementations)=>{
1880
- const options = contextAndSharedModules(boundedContextFolder);
1881
- let asked = false;
1882
- for (const implementation of implementations){
1883
- const available = availableDependencies(consumer, implementation, options.map((x)=>x.module));
1884
- const candidates = options.filter((x)=>available.includes(x.module));
1885
- if (!candidates.length) continue;
1886
- asked = true;
1887
- const type = wiring_implementationType(consumer, implementation);
1888
- const suggested = type ? candidates.filter((x)=>isSuggestedFor(x.module, type)) : [];
1889
- const dependencies = await prompts_checkbox({
1890
- message: consumer.branched ? `Dependencies for ${implementation.className}:` : 'Dependencies:',
1891
- choices: groupedChoices(candidates, suggested),
1892
- pageSize: groupedPageSize,
1893
- loop: false
1546
+ const promptDependencies = async (boundedContextFolder, consumer, implementations = consumer.implementations)=>{
1547
+ const options = contextAndSharedModules(boundedContextFolder);
1548
+ let asked = false;
1549
+ for (const implementation of implementations){
1550
+ const available = availableDependencies(consumer, implementation, options.map((x)=>x.module));
1551
+ const candidates = options.filter((x)=>available.includes(x.module));
1552
+ if (!candidates.length) continue;
1553
+ asked = true;
1554
+ const type = wiring_implementationType(consumer, implementation);
1555
+ const suggested = type ? candidates.filter((x)=>isSuggestedFor(x.module, type)) : [];
1556
+ const dependencies = await prompts_checkbox({
1557
+ message: consumer.branched ? `Dependencies for ${implementation.className}:` : 'Dependencies:',
1558
+ choices: groupedChoices(candidates, suggested),
1559
+ pageSize: groupedPageSize,
1560
+ loop: false
1561
+ });
1562
+ if (dependencies.length) wireDependencies(consumer, implementation, dependencies.map((x)=>x.module));
1563
+ }
1564
+ return asked;
1565
+ };
1566
+ const wireNewModuleDependencies = async (boundedContextFolder, wireFile)=>{
1567
+ const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
1568
+ if (consumer) await promptDependencies(boundedContextFolder, consumer);
1569
+ };
1570
+ const wireDependency = async (boundedContextFolder)=>{
1571
+ const modules = findWiredModules(boundedContextFolder.path);
1572
+ if (!modules.length) return void console.log('No wired modules here yet.');
1573
+ const { module: consumer, implementation } = await prompts_select({
1574
+ message: 'Module:',
1575
+ choices: groupedChoices(modules.flatMap((x)=>x.implementations.map((implementation)=>{
1576
+ const type = wiring_implementationType(x, implementation);
1577
+ return {
1578
+ module: x,
1579
+ label: type ? `${x.typeName} (${type})` : x.typeName,
1580
+ implementation
1581
+ };
1582
+ }))),
1583
+ pageSize: groupedPageSize,
1584
+ loop: false
1585
+ });
1586
+ if (!await promptDependencies(boundedContextFolder, consumer, [
1587
+ implementation
1588
+ ])) console.log('No dependencies available for this module.');
1589
+ };
1590
+ const promptEndpointHandler = async (boundedContextFolder)=>{
1591
+ const handlers = findWiredModules(boundedContextFolder.path).filter((x)=>[
1592
+ 'queries',
1593
+ 'commands',
1594
+ 'use-cases'
1595
+ ].includes(x.kind)).map((x)=>({
1596
+ module: x,
1597
+ label: x.typeName
1598
+ }));
1599
+ return handlers.length ? (await prompts_select({
1600
+ message: 'Handler:',
1601
+ choices: groupedChoices(handlers),
1602
+ pageSize: groupedPageSize,
1603
+ loop: false
1604
+ })).module : void 0;
1605
+ };
1606
+ const createPresentationService = (boundedContextFolder, name, classFile)=>{
1607
+ const naming = new UnknownFormatNaming(name);
1608
+ const className = `${naming.ClassName}PresentationService`;
1609
+ const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
1610
+ const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
1611
+ const wiringFolder = boundedContextFolder.subitem([
1612
+ 'wiring',
1613
+ 'presentation-services'
1614
+ ]);
1615
+ const presentationServicesFolder = boundedContextFolder.subitem([
1616
+ 'presentation',
1617
+ 'services'
1618
+ ]);
1619
+ presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.ts`, classFile?.(className) ?? `
1620
+ export class ${className} {
1621
+
1622
+ }
1623
+ `.trim());
1624
+ if (scaffoldUnitTests) presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.spec.ts`, `
1625
+ import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
1626
+ ${withWiring ? `import { type ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'
1627
+ import { wire${naming.ClassName}PresentationService } from '../../wiring/presentation-services/wire-${naming.fileName}-presentation-service'` : `import { ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'`}
1628
+
1629
+ let ${naming.variableName}PresentationService: ${naming.ClassName}PresentationService
1630
+
1631
+ beforeEach(() => {
1632
+ ${naming.variableName}PresentationService = ${withWiring ? `wire${naming.ClassName}PresentationService()` : `new ${naming.ClassName}PresentationService()`}
1633
+ })
1634
+
1635
+ describe('${naming.withSpaces}', () => {
1636
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
1637
+ expect(${naming.variableName}PresentationService).toBeDefined()
1638
+ })
1639
+ })
1640
+ `.trim());
1641
+ if (withWiring) return wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
1642
+ import { wireClass } from '@domain-first/wire'
1643
+ import { ${naming.ClassName}PresentationService } from '../../presentation/services/${naming.fileName}-presentation-service'
1644
+
1645
+ export const wire${naming.ClassName}PresentationService = wireClass(
1646
+ ${naming.ClassName}PresentationService,
1647
+ []
1648
+ )
1649
+ `.trim());
1650
+ };
1651
+ const scaffoldNewPresentationService = async (boundedContextFolder)=>{
1652
+ const name = await input({
1653
+ message: 'Name: '
1654
+ });
1655
+ const wireFile = createPresentationService(boundedContextFolder, name);
1656
+ if (wireFile) await wireNewModuleDependencies(boundedContextFolder, wireFile);
1657
+ };
1658
+ const rest_endpoint_generator_name = 'rest-endpoint-generator';
1659
+ const scaffoldRestEndpointGenerator = (sharedFolder, { withNextAdapter = false } = {})=>createPresentationService(sharedFolder, rest_endpoint_generator_name, (className)=>{
1660
+ const adapter = withNextAdapter ? 'nextAdapter' : 'adapter';
1661
+ return `
1662
+ import {
1663
+ ${withNextAdapter ? '' : ' type Adapter,\n'} type EndpointGenerator,
1664
+ type ErrorStatuses,
1665
+ createEndpoint,
1666
+ InputMappingError,
1667
+ RequestParsingError
1668
+ } from '@domain-first/handlers-rest'
1669
+ ${withNextAdapter ? "import { nextAdapter } from '@domain-first/handlers-next'" : `
1670
+ /**
1671
+ * The adapter of your HTTP framework.
1672
+ */
1673
+ const adapter = undefined as unknown as Adapter<any[], any>`}
1674
+
1675
+ export class ${className} {
1676
+ /**
1677
+ * Default errors of a client request, to spread into a generator's
1678
+ * own checks.
1679
+ */
1680
+ private get defaultClientRequestErrors(): ErrorStatuses[number]['checks'] {
1681
+ return [RequestParsingError.is, InputMappingError.is]
1682
+ }
1683
+
1684
+ get withoutGuards(): EndpointGenerator {
1685
+ return createEndpoint({
1686
+ errorStatuses: {
1687
+ 400: {
1688
+ checks: this.defaultClientRequestErrors,
1689
+ description: 'Invalid request'
1690
+ }
1691
+ }
1692
+ })(${adapter}) as EndpointGenerator
1693
+ }
1694
+ }
1695
+ `.trim();
1696
+ });
1697
+ const findRestEndpointGenerator = (sharedFolder)=>{
1698
+ const typeFile = node_path.join(sharedFolder.path, 'presentation', 'services', `${rest_endpoint_generator_name}-presentation-service.ts`);
1699
+ if (!new File(typeFile).exists) return;
1700
+ return {
1701
+ typeName: 'RestEndpointGeneratorPresentationService',
1702
+ typeFile,
1703
+ wireName: 'wireRestEndpointGeneratorPresentationService',
1704
+ wireFile: node_path.join(sharedFolder.path, 'wiring', 'presentation-services', `wire-${rest_endpoint_generator_name}-presentation-service.ts`)
1705
+ };
1706
+ };
1707
+ const hasDependency = (root, name)=>{
1708
+ const manifestFile = new File(node_path.join(root, 'package.json'));
1709
+ if (!manifestFile.exists) return false;
1710
+ const manifest = JSON.parse(manifestFile.data);
1711
+ return [
1712
+ manifest.dependencies,
1713
+ manifest.devDependencies,
1714
+ manifest.optionalDependencies
1715
+ ].some((dependencies)=>dependencies && Object.hasOwn(dependencies, name));
1716
+ };
1717
+ const initializeUseCase = async ()=>{
1718
+ const nextSteps = [];
1719
+ const rootFolderName = await input({
1720
+ message: 'Root folder (use "/" for inner folders):',
1721
+ default: 'src'
1722
+ });
1723
+ const domainFirstPackages = await prompts_checkbox({
1724
+ message: '@domain-first packages',
1725
+ choices: [
1726
+ '@domain-first/types',
1727
+ '@domain-first/errors',
1728
+ '@domain-first/handlers',
1729
+ '@domain-first/wire',
1730
+ '@domain-first/handlers-rest'
1731
+ ]
1732
+ });
1733
+ const withNextAdapter = domainFirstPackages.includes('@domain-first/handlers-rest') && hasDependency(new ProjectRoot().path, 'next') && await prompts_confirm({
1734
+ message: 'Use Next adapter for REST endpoints'
1735
+ });
1736
+ const defaultPersistenceLayerImplementation = await input({
1737
+ message: 'Default persistence layer implementation:'
1738
+ });
1739
+ const useReact = await prompts_confirm({
1740
+ message: 'Use React'
1741
+ });
1742
+ let storybookFramework;
1743
+ const withStorybook = useReact ? await prompts_confirm({
1744
+ message: 'Use Storybook'
1745
+ }) : false;
1746
+ if (withStorybook) storybookFramework = await input({
1747
+ message: 'Storybook framework package:',
1748
+ default: '@storybook/react-vite'
1749
+ });
1750
+ let testingLibrary;
1751
+ const withTests = await prompts_confirm({
1752
+ message: 'Scaffold unit tests'
1753
+ });
1754
+ if (withTests) testingLibrary = await input({
1755
+ message: 'Unit testing library:',
1756
+ default: 'vitest'
1757
+ });
1758
+ ConfigFile.write({
1759
+ rootFolder: rootFolderName,
1760
+ domainFirstPackages,
1761
+ defaultPersistenceLayerImplementation,
1762
+ useReact,
1763
+ storybookFramework,
1764
+ testingLibrary
1765
+ });
1766
+ const { path } = new ProjectRoot();
1767
+ const rootFolder = new Folder(path);
1768
+ if (domainFirstPackages.includes('@domain-first/wire')) rootFolder.subitem([
1769
+ rootFolderName,
1770
+ 'shared',
1771
+ 'wiring'
1772
+ ]).createFile('env-branched-wire.ts', `
1773
+ import { branchedWire } from '@domain-first/wire'
1774
+
1775
+ export const envBranchedWire = branchedWire(() => {
1776
+ return process.env.NODE_ENV ?? 'development' as 'test' | 'development' | 'production'
1777
+ });
1778
+ `.trim());
1779
+ if (domainFirstPackages.includes('@domain-first/errors')) rootFolder.subitem([
1780
+ rootFolderName,
1781
+ 'shared'
1782
+ ]).subitem([
1783
+ 'domain',
1784
+ 'errors'
1785
+ ]).createFile('index.ts', `
1786
+ import { errorNamespace } from '@domain-first/errors'
1787
+
1788
+ export const SharedErrors = errorNamespace('shared')
1789
+ `.trim());
1790
+ if (domainFirstPackages.includes('@domain-first/handlers-rest')) {
1791
+ scaffoldRestEndpointGenerator(rootFolder.subitem([
1792
+ rootFolderName,
1793
+ 'shared'
1794
+ ]), {
1795
+ withNextAdapter
1796
+ });
1797
+ if (withNextAdapter && !hasDependency(path, '@domain-first/handlers-next')) nextSteps.push('npm i @domain-first/handlers-next');
1798
+ }
1799
+ return nextSteps;
1800
+ };
1801
+ const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
1802
+ class NestedName {
1803
+ folders;
1804
+ folderName;
1805
+ fileName;
1806
+ ClassName;
1807
+ classNameSegments;
1808
+ constructor(rawSource){
1809
+ const segments = splitSegments(rawSource);
1810
+ this.folders = segments.slice(0, -1);
1811
+ this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
1812
+ this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
1813
+ this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
1814
+ this.ClassName = this.classNameSegments.join('');
1815
+ }
1816
+ static validate = (rawSource)=>{
1817
+ const segments = splitSegments(rawSource);
1818
+ if (!segments.length) return 'Name is required';
1819
+ if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
1820
+ return true;
1821
+ };
1822
+ }
1823
+ const ignoredFolders = new Set([
1824
+ 'node_modules',
1825
+ '.git',
1826
+ '.next',
1827
+ 'dist',
1828
+ 'build',
1829
+ 'out',
1830
+ 'coverage',
1831
+ 'storybook-static'
1832
+ ]);
1833
+ const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
1834
+ const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1835
+ const react_module_move_walk = (folder)=>{
1836
+ if (!node_fs.existsSync(folder)) return [];
1837
+ return node_fs.readdirSync(folder, {
1838
+ withFileTypes: true
1839
+ }).flatMap((entry)=>{
1840
+ const entryPath = node_path.join(folder, entry.name);
1841
+ if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : react_module_move_walk(entryPath);
1842
+ return entry.isFile() ? [
1843
+ entryPath
1844
+ ] : [];
1845
+ });
1846
+ };
1847
+ const toPosix = (value)=>value.split(node_path.sep).join('/');
1848
+ const nestedName = (folders, fileBase)=>{
1849
+ const prefix = `${folders.join('-')}-`;
1850
+ const last = folders.length && fileBase.startsWith(prefix) ? fileBase.slice(prefix.length) : fileBase;
1851
+ return [
1852
+ ...folders,
1853
+ last
1854
+ ].join('/');
1855
+ };
1856
+ const declaredClassName = (filePath, suffix, name)=>{
1857
+ const content = node_fs.readFileSync(filePath, 'utf8');
1858
+ const declared = content.match(new RegExp(`export\\s+(?:const|function)\\s+(\\w+)${suffix}\\b`))?.[1];
1859
+ return declared ?? new NestedName(name).ClassName;
1860
+ };
1861
+ const findReactModules = (reactFolder, kind)=>{
1862
+ const modules = 'page' === kind ? react_module_move_walk(node_path.join(reactFolder, 'pages')).filter((file)=>file.endsWith('-page.tsx')).map((file)=>{
1863
+ const folders = node_path.relative(node_path.join(reactFolder, 'pages'), node_path.dirname(file)).split(node_path.sep).filter((segment)=>!!segment);
1864
+ const fileBase = node_path.basename(file, '-page.tsx');
1865
+ const name = nestedName(folders, fileBase);
1866
+ return {
1867
+ kind,
1868
+ name,
1869
+ path: file,
1870
+ fileBase,
1871
+ ClassName: declaredClassName(file, 'Page', name)
1872
+ };
1873
+ }) : react_module_move_walk(node_path.join(reactFolder, 'widgets')).filter((file)=>file.endsWith('-widget.tsx')).map((file)=>{
1874
+ const folder = node_path.dirname(file);
1875
+ const name = toPosix(node_path.relative(node_path.join(reactFolder, 'widgets'), folder));
1876
+ return {
1877
+ kind,
1878
+ name,
1879
+ path: folder,
1880
+ fileBase: node_path.basename(file, '-widget.tsx'),
1881
+ ClassName: declaredClassName(file, 'Widget', name)
1882
+ };
1883
+ });
1884
+ return modules.sort((a, b)=>a.name.localeCompare(b.name));
1885
+ };
1886
+ const react_module_move_targetPath = (reactFolder, module, rawName)=>{
1887
+ const { folders, folderName, fileName } = new NestedName(rawName);
1888
+ return 'page' === module.kind ? node_path.join(reactFolder, 'pages', ...folders, `${fileName}-page.tsx`) : node_path.join(reactFolder, 'widgets', ...folders, folderName);
1889
+ };
1890
+ const validateMove = (reactFolder, module, rawName)=>{
1891
+ const nameError = NestedName.validate(rawName);
1892
+ if (true !== nameError) return nameError;
1893
+ const target = react_module_move_targetPath(reactFolder, module, rawName);
1894
+ if (target !== module.path && node_fs.existsSync(target)) return `${node_path.relative(reactFolder, target)} already exists`;
1895
+ if (target.startsWith(`${module.path}${node_path.sep}`)) return 'A widget cannot be moved into itself';
1896
+ return true;
1897
+ };
1898
+ const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
1899
+ const readAliases = (projectRoot)=>{
1900
+ const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
1901
+ if (!node_fs.existsSync(tsconfig)) return [];
1902
+ try {
1903
+ const { compilerOptions = {} } = JSON.parse(stripJsonComments(node_fs.readFileSync(tsconfig, 'utf8')));
1904
+ const base = node_path.resolve(projectRoot, compilerOptions.baseUrl ?? '.');
1905
+ return Object.entries(compilerOptions.paths ?? {}).filter(([pattern, targets])=>pattern.endsWith('*') && targets[0]?.endsWith('*')).map(([pattern, [target]])=>({
1906
+ prefix: pattern.slice(0, -1),
1907
+ target: node_path.resolve(base, target.slice(0, -1))
1908
+ }));
1909
+ } catch {
1910
+ return [];
1911
+ }
1912
+ };
1913
+ const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
1914
+ const reExportPattern = /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*(['"])([^'"\n]+)\1/g;
1915
+ const importPaths = (file)=>{
1916
+ const withoutExtension = file.replace(codeExtension, '');
1917
+ return 'index' === node_path.basename(withoutExtension) ? [
1918
+ withoutExtension,
1919
+ node_path.dirname(withoutExtension)
1920
+ ] : [
1921
+ withoutExtension
1922
+ ];
1923
+ };
1924
+ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
1925
+ const newName = new NestedName(rawName);
1926
+ const target = react_module_move_targetPath(reactFolder, module, rawName);
1927
+ const newClassName = newName.ClassName;
1928
+ const renameFile = (name)=>name.replace(new RegExp(`^(use-)?${escapeRegExp(module.fileBase)}(?=[-.])`), (_, use = '')=>`${use}${newName.fileName}`);
1929
+ const oldFolder = 'page' === module.kind ? node_path.dirname(module.path) : module.path;
1930
+ const newFolder = 'page' === module.kind ? node_path.dirname(target) : target;
1931
+ const ownsPath = (candidate)=>'page' === module.kind ? node_path.dirname(candidate) === oldFolder && new RegExp(`^${escapeRegExp(module.fileBase)}-page(?:\\.|$)`).test(node_path.basename(candidate)) : candidate === oldFolder || candidate.startsWith(`${oldFolder}${node_path.sep}`);
1932
+ const movedPath = (candidate)=>{
1933
+ if (!ownsPath(candidate)) return;
1934
+ const segments = node_path.relative(oldFolder, candidate).split(node_path.sep);
1935
+ const last = segments.length - 1;
1936
+ segments[last] = renameFile(segments[last]);
1937
+ return node_path.join(newFolder, ...segments);
1938
+ };
1939
+ const moduleFiles = 'page' === module.kind ? node_fs.readdirSync(oldFolder).map((name)=>node_path.join(oldFolder, name)).filter((file)=>node_fs.statSync(file).isFile() && ownsPath(file)) : react_module_move_walk(oldFolder);
1940
+ const moves = new Map(moduleFiles.map((file)=>[
1941
+ file,
1942
+ movedPath(file) ?? file
1943
+ ]));
1944
+ const aliases = readAliases(projectRoot);
1945
+ const resolve = (specifier, fromFile)=>{
1946
+ if (specifier.startsWith('.')) return {
1947
+ resolved: node_path.resolve(node_path.dirname(fromFile), specifier),
1948
+ alias: void 0
1949
+ };
1950
+ const alias = aliases.find(({ prefix })=>specifier.startsWith(prefix));
1951
+ return alias ? {
1952
+ resolved: node_path.resolve(alias.target, specifier.slice(alias.prefix.length)),
1953
+ alias
1954
+ } : void 0;
1955
+ };
1956
+ const specifierFor = (fromFile, toPath, alias)=>{
1957
+ const aliased = alias && toPosix(node_path.relative(alias.target, toPath));
1958
+ if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
1959
+ const relative = toPosix(node_path.relative(node_path.dirname(fromFile), toPath));
1960
+ return relative.startsWith('.') ? relative : `./${relative}`;
1961
+ };
1962
+ const suffixes = 'page' === module.kind ? 'Page' : 'Widget|UIModel';
1963
+ const classPattern = new RegExp(`(?<![\\w$])(use)?${escapeRegExp(module.ClassName)}(?=${suffixes})`, 'g');
1964
+ const oldTitle = `Widgets/${module.name.split('/').map((segment)=>new NestedName(segment).ClassName).join('/')}`;
1965
+ const titlePattern = new RegExp(`(['"\`])${escapeRegExp(oldTitle)}\\1`, 'g');
1966
+ const newTitle = [
1967
+ 'Widgets',
1968
+ ...newName.classNameSegments
1969
+ ].join('/');
1970
+ const codeFiles = new Map(react_module_move_walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
1971
+ file,
1972
+ node_fs.readFileSync(file, 'utf8')
1973
+ ]));
1974
+ const barrels = new Set();
1975
+ const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
1976
+ for(let found = true; found;){
1977
+ found = false;
1978
+ for (const [file, content] of codeFiles){
1979
+ if (moves.has(file) || isBarrel(file)) continue;
1980
+ const reExportsModule = [
1981
+ ...content.matchAll(reExportPattern)
1982
+ ].some(([, , specifier])=>{
1983
+ const resolution = resolve(specifier, file);
1984
+ return !!resolution && (!!movedPath(resolution.resolved) || isBarrel(resolution.resolved));
1985
+ });
1986
+ if (reExportsModule) {
1987
+ for (const importPath of importPaths(file))barrels.add(importPath);
1988
+ found = true;
1989
+ }
1990
+ }
1991
+ }
1992
+ const rewrite = (content, oldFile, newFile)=>{
1993
+ let referencesModule = false;
1994
+ const rewritten = content.replace(specifierPattern, (match, keyword, quote, specifier)=>{
1995
+ const resolution = resolve(specifier, oldFile);
1996
+ if (!resolution) return match;
1997
+ const moved = movedPath(resolution.resolved);
1998
+ if (moved || isBarrel(resolution.resolved)) referencesModule = true;
1999
+ if (!moved && oldFile === newFile) return match;
2000
+ const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
2001
+ return `${keyword}${quote}${next}${quote}`;
1894
2002
  });
1895
- if (dependencies.length) wireDependencies(consumer, implementation, dependencies.map((x)=>x.module));
2003
+ if (!referencesModule && !moves.has(oldFile)) return content;
2004
+ const renamed = rewritten.replace(classPattern, (_, use = '')=>`${use}${newClassName}`);
2005
+ return moves.has(oldFile) && 'widget' === module.kind ? renamed.replace(titlePattern, (_, quote)=>`${quote}${newTitle}${quote}`) : renamed;
2006
+ };
2007
+ for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new File(file).moveTo(newFile, reactFolder);
2008
+ const updated = [];
2009
+ for (const [file, content] of codeFiles){
2010
+ const newFile = moves.get(file);
2011
+ const next = rewrite(content, file, newFile ?? file);
2012
+ if (newFile && newFile !== file) {
2013
+ new File(newFile).data = next;
2014
+ new File(file).delete(reactFolder);
2015
+ } else if (next !== content) {
2016
+ new File(file).update(next);
2017
+ if (!newFile) updated.push(file);
2018
+ }
1896
2019
  }
1897
- return asked;
1898
- };
1899
- const wireNewModuleDependencies = async (boundedContextFolder, wireFile)=>{
1900
- const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
1901
- if (consumer) await promptDependencies(boundedContextFolder, consumer);
1902
- };
1903
- const wireDependency = async (boundedContextFolder)=>{
1904
- const modules = findWiredModules(boundedContextFolder.path);
1905
- if (!modules.length) return void console.log('No wired modules here yet.');
1906
- const { module: consumer, implementation } = await prompts_select({
1907
- message: 'Module:',
1908
- choices: groupedChoices(modules.flatMap((x)=>x.implementations.map((implementation)=>{
1909
- const type = wiring_implementationType(x, implementation);
1910
- return {
1911
- module: x,
1912
- label: type ? `${x.typeName} (${type})` : x.typeName,
1913
- implementation
1914
- };
1915
- }))),
1916
- pageSize: groupedPageSize,
1917
- loop: false
1918
- });
1919
- if (!await promptDependencies(boundedContextFolder, consumer, [
1920
- implementation
1921
- ])) console.log('No dependencies available for this module.');
1922
- };
1923
- const promptEndpointDependencies = async (boundedContextFolder)=>{
1924
- const options = contextAndSharedModules(boundedContextFolder);
1925
- const generators = options.filter((x)=>'presentation-services' === x.module.kind);
1926
- const handlers = findWiredModules(boundedContextFolder.path).filter((x)=>[
1927
- 'queries',
1928
- 'commands',
1929
- 'use-cases'
1930
- ].includes(x.kind)).map((x)=>({
1931
- module: x,
1932
- label: x.typeName
1933
- }));
1934
- const endpointGenerator = generators.length ? (await prompts_select({
1935
- message: 'Endpoint generator:',
1936
- choices: groupedChoices(generators, generators.filter((x)=>isSuggestedEndpointGenerator(x.module))),
1937
- pageSize: groupedPageSize,
1938
- loop: false
1939
- })).module : void 0;
1940
- const handler = handlers.length ? (await prompts_select({
1941
- message: 'Handler:',
1942
- choices: groupedChoices(handlers),
1943
- pageSize: groupedPageSize,
1944
- loop: false
1945
- })).module : void 0;
1946
2020
  return {
1947
- endpointGenerator,
1948
- handler
2021
+ moves: [
2022
+ ...moves
2023
+ ].filter(([from, to])=>from !== to),
2024
+ updated
1949
2025
  };
1950
2026
  };
2027
+ const moveReactModuleUseCase = async (presentationReactFolder, kind)=>{
2028
+ const reactFolder = presentationReactFolder.path;
2029
+ const modules = findReactModules(reactFolder, kind);
2030
+ if (!modules.length) return void console.log(`No ${kind}s generated by df-ps were found.`);
2031
+ const module = await prompts_select({
2032
+ message: 'page' === kind ? 'Page:' : 'Widget:',
2033
+ choices: modules.map((value)=>({
2034
+ name: value.name,
2035
+ value,
2036
+ description: node_path.relative(reactFolder, value.path)
2037
+ }))
2038
+ });
2039
+ const name = await input({
2040
+ message: 'New name (folders split by "/"):',
2041
+ default: module.name,
2042
+ validate: (value)=>validateMove(reactFolder, module, value)
2043
+ });
2044
+ const root = new ProjectRoot().path;
2045
+ const { moves, updated } = moveReactModule(root, reactFolder, module, name);
2046
+ if (!moves.length && !updated.length) return void console.log('Nothing to change.');
2047
+ const relative = (file)=>node_path.relative(root, file);
2048
+ console.log([
2049
+ 'Files to move:',
2050
+ ...moves.map(([from, to])=>` ${relative(from)} → ${relative(to)}`),
2051
+ ...updated.length ? [
2052
+ 'Files with updated imports:',
2053
+ ...updated.map((file)=>` ${relative(file)}`)
2054
+ ] : []
2055
+ ].join('\n'));
2056
+ if (!await prompts_confirm({
2057
+ message: 'Apply?',
2058
+ default: true
2059
+ })) {
2060
+ discardPendingChanges();
2061
+ console.log('Cancelled: nothing was written.');
2062
+ }
2063
+ };
1951
2064
  const scaffoldNewAggregateUseCase = async (boundedContextFolder)=>{
1952
2065
  const aggregateName = await input({
1953
2066
  message: 'Aggregate name:'
@@ -2644,10 +2757,12 @@ export const restHandlers = restWires.map(x => x().handle)
2644
2757
  'endpoint'
2645
2758
  ].map((segment)=>segment.startsWith(':') ? pathParameterAsName(segment) : new UnknownFormatNaming(segment).ClassName).join('');
2646
2759
  const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
2647
- const { endpointGenerator, handler } = withWiring ? await promptEndpointDependencies(boundedContextFolder) : {
2648
- endpointGenerator: void 0,
2649
- handler: void 0
2650
- };
2760
+ const endpointGenerator = findRestEndpointGenerator(boundedContextFolder.subitem([
2761
+ '..',
2762
+ '..',
2763
+ 'shared'
2764
+ ]));
2765
+ const handler = withWiring ? await promptEndpointHandler(boundedContextFolder) : void 0;
2651
2766
  const endpointFile = node_path.join(endpointFolder.path, `${method.toUpperCase()}.ts`);
2652
2767
  endpointFolder.createFile(`${method.toUpperCase()}.ts`, `
2653
2768
  ${endpointGenerator ? `import type { ${endpointGenerator.typeName} } from '${relativeImport(endpointFile, endpointGenerator.typeFile)}'` : "import { EndpointGenerator } from '@domain-first/handlers-rest'"}${handler ? `
@@ -2744,56 +2859,6 @@ export const wire${naming.ClassName}InfrastructureService = wireClass(
2744
2859
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2745
2860
  }
2746
2861
  };
2747
- const scaffoldNewPresentationService = async (boundedContextFolder)=>{
2748
- const name = await input({
2749
- message: 'Name: '
2750
- });
2751
- const naming = new UnknownFormatNaming(name);
2752
- const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
2753
- const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
2754
- const wiringFolder = boundedContextFolder.subitem([
2755
- 'wiring',
2756
- 'presentation-services'
2757
- ]);
2758
- const presentationServicesFolder = boundedContextFolder.subitem([
2759
- 'presentation',
2760
- 'services'
2761
- ]);
2762
- presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.ts`, `
2763
- export class ${naming.ClassName}PresentationService {
2764
-
2765
- }
2766
- `.trim());
2767
- if (scaffoldUnitTests) presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.spec.ts`, `
2768
- import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
2769
- ${withWiring ? `import { type ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'
2770
- import { wire${naming.ClassName}PresentationService } from '../../wiring/presentation-services/wire-${naming.fileName}-presentation-service'` : `import { ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'`}
2771
-
2772
- let ${naming.variableName}PresentationService: ${naming.ClassName}PresentationService
2773
-
2774
- beforeEach(() => {
2775
- ${naming.variableName}PresentationService = ${withWiring ? `wire${naming.ClassName}PresentationService()` : `new ${naming.ClassName}PresentationService()`}
2776
- })
2777
-
2778
- describe('${naming.withSpaces}', () => {
2779
- test('can be ${withWiring ? 'wired' : 'created'}', () => {
2780
- expect(${naming.variableName}PresentationService).toBeDefined()
2781
- })
2782
- })
2783
- `.trim());
2784
- if (withWiring) {
2785
- const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
2786
- import { wireClass } from '@domain-first/wire'
2787
- import { ${naming.ClassName}PresentationService } from '../../presentation/services/${naming.fileName}-presentation-service'
2788
-
2789
- export const wire${naming.ClassName}PresentationService = wireClass(
2790
- ${naming.ClassName}PresentationService,
2791
- []
2792
- )
2793
- `.trim());
2794
- await wireNewModuleDependencies(boundedContextFolder, wireFile);
2795
- }
2796
- };
2797
2862
  const scaffoldNewQuery = async (boundedContextFolder)=>{
2798
2863
  const queriesFolder = boundedContextFolder.subitem([
2799
2864
  'application',
@@ -3263,7 +3328,11 @@ export const use${ClassName}UIModel = (widgetProps: Omit<${ClassName}WidgetProps
3263
3328
  }
3264
3329
  };
3265
3330
  const main = async ()=>{
3266
- if (!ConfigFile.exists) return void await initializeUseCase();
3331
+ if (!ConfigFile.exists) {
3332
+ const nextSteps = await initializeUseCase();
3333
+ if (await savePendingChanges()) printNextSteps(nextSteps);
3334
+ return;
3335
+ }
3267
3336
  const rootPath = new ProjectRoot().path;
3268
3337
  const currentBoundedContextOptions = new Folder(rootPath).subitem([
3269
3338
  ConfigFile.Instance.data.rootFolder,