@domain-first/project-structure 2.15.1 → 2.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -203,6 +203,19 @@ Enable `useReact` and choose **Scaffold React module** from the main menu. Modul
203
203
 
204
204
  Page and widget names can include folders split by `/`. For example, a page named `admin/panel/users` is created at `pages/admin/panel/admin-panel-users-page.tsx` as `AdminPanelUsersPage`, and a widget with the same name at `widgets/admin/panel/users/admin-panel-users-widget.tsx` as `AdminPanelUsersWidget` with the story title `Widgets/Admin/Panel/Users`. The widget folder uses only the last segment; file names and code names use the whole path.
205
205
 
206
+ To move or rename a page or a widget, choose **Move or rename page** or
207
+ **Move or rename widget**, pick it from the list and enter a new name with
208
+ folders. A widget moves with its whole folder (assets included), and a page with
209
+ the files next to it that share its name, such as `<name>-page.module.css`. File
210
+ names, `<Name>Page`, `<Name>Widget…` and `use<Name>UIModel` follow the new name,
211
+ and so does a generated story title. Imports of the module are updated across
212
+ the project, both relative ones and `tsconfig.json` `paths` aliases such as `@/`,
213
+ and relative imports inside the module are adjusted to its new location. The CLI
214
+ lists the files to move and to update and asks before writing; emptied folders
215
+ are removed. Entering the same name renames files made before file names used
216
+ the whole path, for example `pages/admin/users-page.tsx` to
217
+ `pages/admin/admin-users-page.tsx`.
218
+
206
219
  ### Project integrations
207
220
 
208
221
  Choose **Add integration → Storybook (React + Vite)** to configure Storybook.
@@ -22,6 +22,15 @@ export declare class Folder extends FileSystemItem {
22
22
  }
23
23
  export declare class File extends FileSystemItem {
24
24
  get exists(): boolean;
25
+ /**
26
+ * Folders emptied by the deletion are removed too, up to `stopAt`
27
+ * (exclusive), which must contain the file.
28
+ */
29
+ delete: (stopAt: string) => void;
30
+ /**
31
+ * Moves the file as is, without reading it, so binary files survive.
32
+ */
33
+ moveTo: (targetPath: string, stopAt: string) => void;
25
34
  get data(): string;
26
35
  set data(content: string);
27
36
  /**
package/dist/index.cjs CHANGED
@@ -35,12 +35,23 @@ const external_node_fs_namespaceObject = require("node:fs");
35
35
  var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
36
36
  const pendingFiles = new Map();
37
37
  const pendingFolders = new Set();
38
+ const pendingMoves = new Map();
39
+ const pendingDeletions = new Map();
38
40
  const filesToOverwrite = ()=>[
39
41
  ...pendingFiles
40
42
  ].filter(([filePath, { replacesFile }])=>replacesFile && external_node_fs_default().existsSync(filePath)).map(([filePath])=>filePath);
41
43
  const discardPendingChanges = ()=>{
42
44
  pendingFolders.clear();
43
45
  pendingFiles.clear();
46
+ pendingMoves.clear();
47
+ pendingDeletions.clear();
48
+ };
49
+ const removeEmptyFolders = (folderPath, stopAt)=>{
50
+ let current = folderPath;
51
+ while(current.startsWith(`${stopAt}${external_node_path_default().sep}`) && external_node_fs_default().existsSync(current) && !external_node_fs_default().readdirSync(current).length){
52
+ external_node_fs_default().rmdirSync(current);
53
+ current = external_node_path_default().dirname(current);
54
+ }
44
55
  };
45
56
  const writePendingChanges = ()=>{
46
57
  for (const folderPath of pendingFolders)external_node_fs_default().mkdirSync(folderPath, {
@@ -52,6 +63,17 @@ const writePendingChanges = ()=>{
52
63
  });
53
64
  external_node_fs_default().writeFileSync(filePath, content, 'utf8');
54
65
  }
66
+ for (const [targetPath, { sourcePath }] of pendingMoves){
67
+ external_node_fs_default().mkdirSync(external_node_path_default().dirname(targetPath), {
68
+ recursive: true
69
+ });
70
+ external_node_fs_default().renameSync(sourcePath, targetPath);
71
+ }
72
+ for (const filePath of pendingDeletions.keys())external_node_fs_default().rmSync(filePath, {
73
+ force: true
74
+ });
75
+ for (const [filePath, stopAt] of pendingDeletions)removeEmptyFolders(external_node_path_default().dirname(filePath), stopAt);
76
+ for (const { sourcePath, stopAt } of pendingMoves.values())removeEmptyFolders(external_node_path_default().dirname(sourcePath), stopAt);
55
77
  discardPendingChanges();
56
78
  };
57
79
  class FileSystemItem {
@@ -102,8 +124,17 @@ class Folder extends FileSystemItem {
102
124
  }
103
125
  class File extends FileSystemItem {
104
126
  get exists() {
105
- return pendingFiles.has(this.path) || external_node_fs_default().existsSync(this.path);
127
+ return pendingFiles.has(this.path) || pendingMoves.has(this.path) || external_node_fs_default().existsSync(this.path) && !pendingDeletions.has(this.path);
106
128
  }
129
+ delete = (stopAt)=>{
130
+ pendingDeletions.set(this.path, stopAt);
131
+ };
132
+ moveTo = (targetPath, stopAt)=>{
133
+ pendingMoves.set(targetPath, {
134
+ sourcePath: this.path,
135
+ stopAt
136
+ });
137
+ };
107
138
  get data() {
108
139
  const pendingFile = pendingFiles.get(this.path);
109
140
  if (pendingFile) return pendingFile.content;
@@ -1073,6 +1104,241 @@ class UnknownFormatNaming {
1073
1104
  return this.fileName.replaceAll('-', ' ');
1074
1105
  }
1075
1106
  }
1107
+ const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
1108
+ class NestedName {
1109
+ folders;
1110
+ folderName;
1111
+ fileName;
1112
+ ClassName;
1113
+ classNameSegments;
1114
+ constructor(rawSource){
1115
+ const segments = splitSegments(rawSource);
1116
+ this.folders = segments.slice(0, -1);
1117
+ this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
1118
+ this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
1119
+ this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
1120
+ this.ClassName = this.classNameSegments.join('');
1121
+ }
1122
+ static validate = (rawSource)=>{
1123
+ const segments = splitSegments(rawSource);
1124
+ if (!segments.length) return 'Name is required';
1125
+ if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
1126
+ return true;
1127
+ };
1128
+ }
1129
+ const ignoredFolders = new Set([
1130
+ 'node_modules',
1131
+ '.git',
1132
+ '.next',
1133
+ 'dist',
1134
+ 'build',
1135
+ 'out',
1136
+ 'coverage',
1137
+ 'storybook-static'
1138
+ ]);
1139
+ const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
1140
+ const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1141
+ const react_module_move_walk = (folder)=>{
1142
+ if (!external_node_fs_default().existsSync(folder)) return [];
1143
+ return external_node_fs_default().readdirSync(folder, {
1144
+ withFileTypes: true
1145
+ }).flatMap((entry)=>{
1146
+ const entryPath = external_node_path_default().join(folder, entry.name);
1147
+ if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : react_module_move_walk(entryPath);
1148
+ return entry.isFile() ? [
1149
+ entryPath
1150
+ ] : [];
1151
+ });
1152
+ };
1153
+ const toPosix = (value)=>value.split(external_node_path_default().sep).join('/');
1154
+ const nestedName = (folders, fileBase)=>{
1155
+ const prefix = `${folders.join('-')}-`;
1156
+ const last = folders.length && fileBase.startsWith(prefix) ? fileBase.slice(prefix.length) : fileBase;
1157
+ return [
1158
+ ...folders,
1159
+ last
1160
+ ].join('/');
1161
+ };
1162
+ const declaredClassName = (filePath, suffix, name)=>{
1163
+ const content = external_node_fs_default().readFileSync(filePath, 'utf8');
1164
+ const declared = content.match(new RegExp(`export\\s+(?:const|function)\\s+(\\w+)${suffix}\\b`))?.[1];
1165
+ return declared ?? new NestedName(name).ClassName;
1166
+ };
1167
+ const findReactModules = (reactFolder, kind)=>{
1168
+ const modules = 'page' === kind ? react_module_move_walk(external_node_path_default().join(reactFolder, 'pages')).filter((file)=>file.endsWith('-page.tsx')).map((file)=>{
1169
+ 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);
1170
+ const fileBase = external_node_path_default().basename(file, '-page.tsx');
1171
+ const name = nestedName(folders, fileBase);
1172
+ return {
1173
+ kind,
1174
+ name,
1175
+ path: file,
1176
+ fileBase,
1177
+ ClassName: declaredClassName(file, 'Page', name)
1178
+ };
1179
+ }) : react_module_move_walk(external_node_path_default().join(reactFolder, 'widgets')).filter((file)=>file.endsWith('-widget.tsx')).map((file)=>{
1180
+ const folder = external_node_path_default().dirname(file);
1181
+ const name = toPosix(external_node_path_default().relative(external_node_path_default().join(reactFolder, 'widgets'), folder));
1182
+ return {
1183
+ kind,
1184
+ name,
1185
+ path: folder,
1186
+ fileBase: external_node_path_default().basename(file, '-widget.tsx'),
1187
+ ClassName: declaredClassName(file, 'Widget', name)
1188
+ };
1189
+ });
1190
+ return modules.sort((a, b)=>a.name.localeCompare(b.name));
1191
+ };
1192
+ const react_module_move_targetPath = (reactFolder, module, rawName)=>{
1193
+ const { folders, folderName, fileName } = new NestedName(rawName);
1194
+ return 'page' === module.kind ? external_node_path_default().join(reactFolder, 'pages', ...folders, `${fileName}-page.tsx`) : external_node_path_default().join(reactFolder, 'widgets', ...folders, folderName);
1195
+ };
1196
+ const validateMove = (reactFolder, module, rawName)=>{
1197
+ const nameError = NestedName.validate(rawName);
1198
+ if (true !== nameError) return nameError;
1199
+ const target = react_module_move_targetPath(reactFolder, module, rawName);
1200
+ if (target !== module.path && external_node_fs_default().existsSync(target)) return `${external_node_path_default().relative(reactFolder, target)} already exists`;
1201
+ if (target.startsWith(`${module.path}${external_node_path_default().sep}`)) return 'A widget cannot be moved into itself';
1202
+ return true;
1203
+ };
1204
+ const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
1205
+ const readAliases = (projectRoot)=>{
1206
+ const tsconfig = external_node_path_default().join(projectRoot, 'tsconfig.json');
1207
+ if (!external_node_fs_default().existsSync(tsconfig)) return [];
1208
+ try {
1209
+ const { compilerOptions = {} } = JSON.parse(stripJsonComments(external_node_fs_default().readFileSync(tsconfig, 'utf8')));
1210
+ const base = external_node_path_default().resolve(projectRoot, compilerOptions.baseUrl ?? '.');
1211
+ return Object.entries(compilerOptions.paths ?? {}).filter(([pattern, targets])=>pattern.endsWith('*') && targets[0]?.endsWith('*')).map(([pattern, [target]])=>({
1212
+ prefix: pattern.slice(0, -1),
1213
+ target: external_node_path_default().resolve(base, target.slice(0, -1))
1214
+ }));
1215
+ } catch {
1216
+ return [];
1217
+ }
1218
+ };
1219
+ const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
1220
+ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
1221
+ const newName = new NestedName(rawName);
1222
+ const target = react_module_move_targetPath(reactFolder, module, rawName);
1223
+ const newClassName = newName.ClassName;
1224
+ const renameFile = (name)=>name.replace(new RegExp(`^(use-)?${escapeRegExp(module.fileBase)}(?=[-.])`), (_, use = '')=>`${use}${newName.fileName}`);
1225
+ const oldFolder = 'page' === module.kind ? external_node_path_default().dirname(module.path) : module.path;
1226
+ const newFolder = 'page' === module.kind ? external_node_path_default().dirname(target) : target;
1227
+ 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}`);
1228
+ const movedPath = (candidate)=>{
1229
+ if (!ownsPath(candidate)) return;
1230
+ const segments = external_node_path_default().relative(oldFolder, candidate).split(external_node_path_default().sep);
1231
+ const last = segments.length - 1;
1232
+ segments[last] = renameFile(segments[last]);
1233
+ return external_node_path_default().join(newFolder, ...segments);
1234
+ };
1235
+ 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)) : react_module_move_walk(oldFolder);
1236
+ const moves = new Map(moduleFiles.map((file)=>[
1237
+ file,
1238
+ movedPath(file) ?? file
1239
+ ]));
1240
+ const aliases = readAliases(projectRoot);
1241
+ const resolve = (specifier, fromFile)=>{
1242
+ if (specifier.startsWith('.')) return {
1243
+ resolved: external_node_path_default().resolve(external_node_path_default().dirname(fromFile), specifier),
1244
+ alias: void 0
1245
+ };
1246
+ const alias = aliases.find(({ prefix })=>specifier.startsWith(prefix));
1247
+ return alias ? {
1248
+ resolved: external_node_path_default().resolve(alias.target, specifier.slice(alias.prefix.length)),
1249
+ alias
1250
+ } : void 0;
1251
+ };
1252
+ const specifierFor = (fromFile, toPath, alias)=>{
1253
+ const aliased = alias && toPosix(external_node_path_default().relative(alias.target, toPath));
1254
+ if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
1255
+ const relative = toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toPath));
1256
+ return relative.startsWith('.') ? relative : `./${relative}`;
1257
+ };
1258
+ const suffixes = 'page' === module.kind ? 'Page' : 'Widget|UIModel';
1259
+ const classPattern = new RegExp(`(?<![\\w$])(use)?${escapeRegExp(module.ClassName)}(?=${suffixes})`, 'g');
1260
+ const oldTitle = `Widgets/${module.name.split('/').map((segment)=>new NestedName(segment).ClassName).join('/')}`;
1261
+ const titlePattern = new RegExp(`(['"\`])${escapeRegExp(oldTitle)}\\1`, 'g');
1262
+ const newTitle = [
1263
+ 'Widgets',
1264
+ ...newName.classNameSegments
1265
+ ].join('/');
1266
+ const rewrite = (content, oldFile, newFile)=>{
1267
+ let referencesModule = false;
1268
+ const rewritten = content.replace(specifierPattern, (match, keyword, quote, specifier)=>{
1269
+ const resolution = resolve(specifier, oldFile);
1270
+ if (!resolution) return match;
1271
+ const moved = movedPath(resolution.resolved);
1272
+ if (moved) referencesModule = true;
1273
+ if (!moved && oldFile === newFile) return match;
1274
+ const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
1275
+ return `${keyword}${quote}${next}${quote}`;
1276
+ });
1277
+ if (!referencesModule && !moves.has(oldFile)) return content;
1278
+ const renamed = rewritten.replace(classPattern, (_, use = '')=>`${use}${newClassName}`);
1279
+ return moves.has(oldFile) && 'widget' === module.kind ? renamed.replace(titlePattern, (_, quote)=>`${quote}${newTitle}${quote}`) : renamed;
1280
+ };
1281
+ const updated = [];
1282
+ for (const file of react_module_move_walk(projectRoot)){
1283
+ const newFile = moves.get(file);
1284
+ if (!codeExtension.test(file)) {
1285
+ if (newFile && newFile !== file) new File(file).moveTo(newFile, reactFolder);
1286
+ continue;
1287
+ }
1288
+ const content = external_node_fs_default().readFileSync(file, 'utf8');
1289
+ const next = rewrite(content, file, newFile ?? file);
1290
+ if (newFile && newFile !== file) {
1291
+ new File(newFile).data = next;
1292
+ new File(file).delete(reactFolder);
1293
+ } else if (next !== content) {
1294
+ new File(file).update(next);
1295
+ if (!newFile) updated.push(file);
1296
+ }
1297
+ }
1298
+ return {
1299
+ moves: [
1300
+ ...moves
1301
+ ].filter(([from, to])=>from !== to),
1302
+ updated
1303
+ };
1304
+ };
1305
+ const moveReactModuleUseCase = async (presentationReactFolder, kind)=>{
1306
+ const reactFolder = presentationReactFolder.path;
1307
+ const modules = findReactModules(reactFolder, kind);
1308
+ if (!modules.length) return void console.log(`No ${kind}s generated by df-ps were found.`);
1309
+ const module = await (0, prompts_namespaceObject.select)({
1310
+ message: 'page' === kind ? 'Page:' : 'Widget:',
1311
+ choices: modules.map((value)=>({
1312
+ name: value.name,
1313
+ value,
1314
+ description: external_node_path_default().relative(reactFolder, value.path)
1315
+ }))
1316
+ });
1317
+ const name = await (0, prompts_namespaceObject.input)({
1318
+ message: 'New name (folders split by "/"):',
1319
+ default: module.name,
1320
+ validate: (value)=>validateMove(reactFolder, module, value)
1321
+ });
1322
+ const root = new ProjectRoot().path;
1323
+ const { moves, updated } = moveReactModule(root, reactFolder, module, name);
1324
+ if (!moves.length && !updated.length) return void console.log('Nothing to change.');
1325
+ const relative = (file)=>external_node_path_default().relative(root, file);
1326
+ console.log([
1327
+ 'Files to move:',
1328
+ ...moves.map(([from, to])=>` ${relative(from)} → ${relative(to)}`),
1329
+ ...updated.length ? [
1330
+ 'Files with updated imports:',
1331
+ ...updated.map((file)=>` ${relative(file)}`)
1332
+ ] : []
1333
+ ].join('\n'));
1334
+ if (!await (0, prompts_namespaceObject.confirm)({
1335
+ message: 'Apply?',
1336
+ default: true
1337
+ })) {
1338
+ discardPendingChanges();
1339
+ console.log('Cancelled: nothing was written.');
1340
+ }
1341
+ };
1076
1342
  const wiring_layers = [
1077
1343
  'domain',
1078
1344
  'application',
@@ -2609,28 +2875,6 @@ export const wire${naming.ClassName}UseCase = wireClass(
2609
2875
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2610
2876
  }
2611
2877
  };
2612
- const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
2613
- class NestedName {
2614
- folders;
2615
- folderName;
2616
- fileName;
2617
- ClassName;
2618
- classNameSegments;
2619
- constructor(rawSource){
2620
- const segments = splitSegments(rawSource);
2621
- this.folders = segments.slice(0, -1);
2622
- this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
2623
- this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
2624
- this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
2625
- this.ClassName = this.classNameSegments.join('');
2626
- }
2627
- static validate = (rawSource)=>{
2628
- const segments = splitSegments(rawSource);
2629
- if (!segments.length) return 'Name is required';
2630
- if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
2631
- return true;
2632
- };
2633
- }
2634
2878
  const scaffoldReactPage = async (presentationReactFolder)=>{
2635
2879
  const name = await (0, prompts_namespaceObject.input)({
2636
2880
  message: 'Provide name (folders split by "/"):',
@@ -2887,7 +3131,9 @@ const main = async ()=>{
2887
3131
  'New widget',
2888
3132
  'New page',
2889
3133
  'New UI-kit component',
2890
- 'New shared hook'
3134
+ 'New shared hook',
3135
+ 'Move or rename widget',
3136
+ 'Move or rename page'
2891
3137
  ]
2892
3138
  });
2893
3139
  switch(action){
@@ -2899,6 +3145,10 @@ const main = async ()=>{
2899
3145
  return void await scaffoldReactUIKitComponent(reactFolder);
2900
3146
  case 'New shared hook':
2901
3147
  return void await scaffoldReactSharedHook(reactFolder);
3148
+ case 'Move or rename widget':
3149
+ return void await moveReactModuleUseCase(reactFolder, 'widget');
3150
+ case 'Move or rename page':
3151
+ return void await moveReactModuleUseCase(reactFolder, 'page');
2902
3152
  default:
2903
3153
  return;
2904
3154
  }
package/dist/index.js CHANGED
@@ -6,12 +6,23 @@ import node_fs from "node:fs";
6
6
  import { styleText } from "node:util";
7
7
  const pendingFiles = new Map();
8
8
  const pendingFolders = new Set();
9
+ const pendingMoves = new Map();
10
+ const pendingDeletions = new Map();
9
11
  const filesToOverwrite = ()=>[
10
12
  ...pendingFiles
11
13
  ].filter(([filePath, { replacesFile }])=>replacesFile && node_fs.existsSync(filePath)).map(([filePath])=>filePath);
12
14
  const discardPendingChanges = ()=>{
13
15
  pendingFolders.clear();
14
16
  pendingFiles.clear();
17
+ pendingMoves.clear();
18
+ pendingDeletions.clear();
19
+ };
20
+ const removeEmptyFolders = (folderPath, stopAt)=>{
21
+ let current = folderPath;
22
+ while(current.startsWith(`${stopAt}${node_path.sep}`) && node_fs.existsSync(current) && !node_fs.readdirSync(current).length){
23
+ node_fs.rmdirSync(current);
24
+ current = node_path.dirname(current);
25
+ }
15
26
  };
16
27
  const writePendingChanges = ()=>{
17
28
  for (const folderPath of pendingFolders)node_fs.mkdirSync(folderPath, {
@@ -23,6 +34,17 @@ const writePendingChanges = ()=>{
23
34
  });
24
35
  node_fs.writeFileSync(filePath, content, 'utf8');
25
36
  }
37
+ for (const [targetPath, { sourcePath }] of pendingMoves){
38
+ node_fs.mkdirSync(node_path.dirname(targetPath), {
39
+ recursive: true
40
+ });
41
+ node_fs.renameSync(sourcePath, targetPath);
42
+ }
43
+ for (const filePath of pendingDeletions.keys())node_fs.rmSync(filePath, {
44
+ force: true
45
+ });
46
+ for (const [filePath, stopAt] of pendingDeletions)removeEmptyFolders(node_path.dirname(filePath), stopAt);
47
+ for (const { sourcePath, stopAt } of pendingMoves.values())removeEmptyFolders(node_path.dirname(sourcePath), stopAt);
26
48
  discardPendingChanges();
27
49
  };
28
50
  class FileSystemItem {
@@ -73,8 +95,17 @@ class Folder extends FileSystemItem {
73
95
  }
74
96
  class File extends FileSystemItem {
75
97
  get exists() {
76
- return pendingFiles.has(this.path) || node_fs.existsSync(this.path);
98
+ return pendingFiles.has(this.path) || pendingMoves.has(this.path) || node_fs.existsSync(this.path) && !pendingDeletions.has(this.path);
77
99
  }
100
+ delete = (stopAt)=>{
101
+ pendingDeletions.set(this.path, stopAt);
102
+ };
103
+ moveTo = (targetPath, stopAt)=>{
104
+ pendingMoves.set(targetPath, {
105
+ sourcePath: this.path,
106
+ stopAt
107
+ });
108
+ };
78
109
  get data() {
79
110
  const pendingFile = pendingFiles.get(this.path);
80
111
  if (pendingFile) return pendingFile.content;
@@ -1043,6 +1074,241 @@ class UnknownFormatNaming {
1043
1074
  return this.fileName.replaceAll('-', ' ');
1044
1075
  }
1045
1076
  }
1077
+ const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
1078
+ class NestedName {
1079
+ folders;
1080
+ folderName;
1081
+ fileName;
1082
+ ClassName;
1083
+ classNameSegments;
1084
+ constructor(rawSource){
1085
+ const segments = splitSegments(rawSource);
1086
+ this.folders = segments.slice(0, -1);
1087
+ this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
1088
+ this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
1089
+ this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
1090
+ this.ClassName = this.classNameSegments.join('');
1091
+ }
1092
+ static validate = (rawSource)=>{
1093
+ const segments = splitSegments(rawSource);
1094
+ if (!segments.length) return 'Name is required';
1095
+ if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
1096
+ return true;
1097
+ };
1098
+ }
1099
+ const ignoredFolders = new Set([
1100
+ 'node_modules',
1101
+ '.git',
1102
+ '.next',
1103
+ 'dist',
1104
+ 'build',
1105
+ 'out',
1106
+ 'coverage',
1107
+ 'storybook-static'
1108
+ ]);
1109
+ const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
1110
+ const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1111
+ const react_module_move_walk = (folder)=>{
1112
+ if (!node_fs.existsSync(folder)) return [];
1113
+ return node_fs.readdirSync(folder, {
1114
+ withFileTypes: true
1115
+ }).flatMap((entry)=>{
1116
+ const entryPath = node_path.join(folder, entry.name);
1117
+ if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : react_module_move_walk(entryPath);
1118
+ return entry.isFile() ? [
1119
+ entryPath
1120
+ ] : [];
1121
+ });
1122
+ };
1123
+ const toPosix = (value)=>value.split(node_path.sep).join('/');
1124
+ const nestedName = (folders, fileBase)=>{
1125
+ const prefix = `${folders.join('-')}-`;
1126
+ const last = folders.length && fileBase.startsWith(prefix) ? fileBase.slice(prefix.length) : fileBase;
1127
+ return [
1128
+ ...folders,
1129
+ last
1130
+ ].join('/');
1131
+ };
1132
+ const declaredClassName = (filePath, suffix, name)=>{
1133
+ const content = node_fs.readFileSync(filePath, 'utf8');
1134
+ const declared = content.match(new RegExp(`export\\s+(?:const|function)\\s+(\\w+)${suffix}\\b`))?.[1];
1135
+ return declared ?? new NestedName(name).ClassName;
1136
+ };
1137
+ const findReactModules = (reactFolder, kind)=>{
1138
+ const modules = 'page' === kind ? react_module_move_walk(node_path.join(reactFolder, 'pages')).filter((file)=>file.endsWith('-page.tsx')).map((file)=>{
1139
+ const folders = node_path.relative(node_path.join(reactFolder, 'pages'), node_path.dirname(file)).split(node_path.sep).filter((segment)=>!!segment);
1140
+ const fileBase = node_path.basename(file, '-page.tsx');
1141
+ const name = nestedName(folders, fileBase);
1142
+ return {
1143
+ kind,
1144
+ name,
1145
+ path: file,
1146
+ fileBase,
1147
+ ClassName: declaredClassName(file, 'Page', name)
1148
+ };
1149
+ }) : react_module_move_walk(node_path.join(reactFolder, 'widgets')).filter((file)=>file.endsWith('-widget.tsx')).map((file)=>{
1150
+ const folder = node_path.dirname(file);
1151
+ const name = toPosix(node_path.relative(node_path.join(reactFolder, 'widgets'), folder));
1152
+ return {
1153
+ kind,
1154
+ name,
1155
+ path: folder,
1156
+ fileBase: node_path.basename(file, '-widget.tsx'),
1157
+ ClassName: declaredClassName(file, 'Widget', name)
1158
+ };
1159
+ });
1160
+ return modules.sort((a, b)=>a.name.localeCompare(b.name));
1161
+ };
1162
+ const react_module_move_targetPath = (reactFolder, module, rawName)=>{
1163
+ const { folders, folderName, fileName } = new NestedName(rawName);
1164
+ return 'page' === module.kind ? node_path.join(reactFolder, 'pages', ...folders, `${fileName}-page.tsx`) : node_path.join(reactFolder, 'widgets', ...folders, folderName);
1165
+ };
1166
+ const validateMove = (reactFolder, module, rawName)=>{
1167
+ const nameError = NestedName.validate(rawName);
1168
+ if (true !== nameError) return nameError;
1169
+ const target = react_module_move_targetPath(reactFolder, module, rawName);
1170
+ if (target !== module.path && node_fs.existsSync(target)) return `${node_path.relative(reactFolder, target)} already exists`;
1171
+ if (target.startsWith(`${module.path}${node_path.sep}`)) return 'A widget cannot be moved into itself';
1172
+ return true;
1173
+ };
1174
+ const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
1175
+ const readAliases = (projectRoot)=>{
1176
+ const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
1177
+ if (!node_fs.existsSync(tsconfig)) return [];
1178
+ try {
1179
+ const { compilerOptions = {} } = JSON.parse(stripJsonComments(node_fs.readFileSync(tsconfig, 'utf8')));
1180
+ const base = node_path.resolve(projectRoot, compilerOptions.baseUrl ?? '.');
1181
+ return Object.entries(compilerOptions.paths ?? {}).filter(([pattern, targets])=>pattern.endsWith('*') && targets[0]?.endsWith('*')).map(([pattern, [target]])=>({
1182
+ prefix: pattern.slice(0, -1),
1183
+ target: node_path.resolve(base, target.slice(0, -1))
1184
+ }));
1185
+ } catch {
1186
+ return [];
1187
+ }
1188
+ };
1189
+ const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
1190
+ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
1191
+ const newName = new NestedName(rawName);
1192
+ const target = react_module_move_targetPath(reactFolder, module, rawName);
1193
+ const newClassName = newName.ClassName;
1194
+ const renameFile = (name)=>name.replace(new RegExp(`^(use-)?${escapeRegExp(module.fileBase)}(?=[-.])`), (_, use = '')=>`${use}${newName.fileName}`);
1195
+ const oldFolder = 'page' === module.kind ? node_path.dirname(module.path) : module.path;
1196
+ const newFolder = 'page' === module.kind ? node_path.dirname(target) : target;
1197
+ 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}`);
1198
+ const movedPath = (candidate)=>{
1199
+ if (!ownsPath(candidate)) return;
1200
+ const segments = node_path.relative(oldFolder, candidate).split(node_path.sep);
1201
+ const last = segments.length - 1;
1202
+ segments[last] = renameFile(segments[last]);
1203
+ return node_path.join(newFolder, ...segments);
1204
+ };
1205
+ 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);
1206
+ const moves = new Map(moduleFiles.map((file)=>[
1207
+ file,
1208
+ movedPath(file) ?? file
1209
+ ]));
1210
+ const aliases = readAliases(projectRoot);
1211
+ const resolve = (specifier, fromFile)=>{
1212
+ if (specifier.startsWith('.')) return {
1213
+ resolved: node_path.resolve(node_path.dirname(fromFile), specifier),
1214
+ alias: void 0
1215
+ };
1216
+ const alias = aliases.find(({ prefix })=>specifier.startsWith(prefix));
1217
+ return alias ? {
1218
+ resolved: node_path.resolve(alias.target, specifier.slice(alias.prefix.length)),
1219
+ alias
1220
+ } : void 0;
1221
+ };
1222
+ const specifierFor = (fromFile, toPath, alias)=>{
1223
+ const aliased = alias && toPosix(node_path.relative(alias.target, toPath));
1224
+ if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
1225
+ const relative = toPosix(node_path.relative(node_path.dirname(fromFile), toPath));
1226
+ return relative.startsWith('.') ? relative : `./${relative}`;
1227
+ };
1228
+ const suffixes = 'page' === module.kind ? 'Page' : 'Widget|UIModel';
1229
+ const classPattern = new RegExp(`(?<![\\w$])(use)?${escapeRegExp(module.ClassName)}(?=${suffixes})`, 'g');
1230
+ const oldTitle = `Widgets/${module.name.split('/').map((segment)=>new NestedName(segment).ClassName).join('/')}`;
1231
+ const titlePattern = new RegExp(`(['"\`])${escapeRegExp(oldTitle)}\\1`, 'g');
1232
+ const newTitle = [
1233
+ 'Widgets',
1234
+ ...newName.classNameSegments
1235
+ ].join('/');
1236
+ const rewrite = (content, oldFile, newFile)=>{
1237
+ let referencesModule = false;
1238
+ const rewritten = content.replace(specifierPattern, (match, keyword, quote, specifier)=>{
1239
+ const resolution = resolve(specifier, oldFile);
1240
+ if (!resolution) return match;
1241
+ const moved = movedPath(resolution.resolved);
1242
+ if (moved) referencesModule = true;
1243
+ if (!moved && oldFile === newFile) return match;
1244
+ const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
1245
+ return `${keyword}${quote}${next}${quote}`;
1246
+ });
1247
+ if (!referencesModule && !moves.has(oldFile)) return content;
1248
+ const renamed = rewritten.replace(classPattern, (_, use = '')=>`${use}${newClassName}`);
1249
+ return moves.has(oldFile) && 'widget' === module.kind ? renamed.replace(titlePattern, (_, quote)=>`${quote}${newTitle}${quote}`) : renamed;
1250
+ };
1251
+ const updated = [];
1252
+ for (const file of react_module_move_walk(projectRoot)){
1253
+ const newFile = moves.get(file);
1254
+ if (!codeExtension.test(file)) {
1255
+ if (newFile && newFile !== file) new File(file).moveTo(newFile, reactFolder);
1256
+ continue;
1257
+ }
1258
+ const content = node_fs.readFileSync(file, 'utf8');
1259
+ const next = rewrite(content, file, newFile ?? file);
1260
+ if (newFile && newFile !== file) {
1261
+ new File(newFile).data = next;
1262
+ new File(file).delete(reactFolder);
1263
+ } else if (next !== content) {
1264
+ new File(file).update(next);
1265
+ if (!newFile) updated.push(file);
1266
+ }
1267
+ }
1268
+ return {
1269
+ moves: [
1270
+ ...moves
1271
+ ].filter(([from, to])=>from !== to),
1272
+ updated
1273
+ };
1274
+ };
1275
+ const moveReactModuleUseCase = async (presentationReactFolder, kind)=>{
1276
+ const reactFolder = presentationReactFolder.path;
1277
+ const modules = findReactModules(reactFolder, kind);
1278
+ if (!modules.length) return void console.log(`No ${kind}s generated by df-ps were found.`);
1279
+ const module = await prompts_select({
1280
+ message: 'page' === kind ? 'Page:' : 'Widget:',
1281
+ choices: modules.map((value)=>({
1282
+ name: value.name,
1283
+ value,
1284
+ description: node_path.relative(reactFolder, value.path)
1285
+ }))
1286
+ });
1287
+ const name = await input({
1288
+ message: 'New name (folders split by "/"):',
1289
+ default: module.name,
1290
+ validate: (value)=>validateMove(reactFolder, module, value)
1291
+ });
1292
+ const root = new ProjectRoot().path;
1293
+ const { moves, updated } = moveReactModule(root, reactFolder, module, name);
1294
+ if (!moves.length && !updated.length) return void console.log('Nothing to change.');
1295
+ const relative = (file)=>node_path.relative(root, file);
1296
+ console.log([
1297
+ 'Files to move:',
1298
+ ...moves.map(([from, to])=>` ${relative(from)} → ${relative(to)}`),
1299
+ ...updated.length ? [
1300
+ 'Files with updated imports:',
1301
+ ...updated.map((file)=>` ${relative(file)}`)
1302
+ ] : []
1303
+ ].join('\n'));
1304
+ if (!await prompts_confirm({
1305
+ message: 'Apply?',
1306
+ default: true
1307
+ })) {
1308
+ discardPendingChanges();
1309
+ console.log('Cancelled: nothing was written.');
1310
+ }
1311
+ };
1046
1312
  const wiring_layers = [
1047
1313
  'domain',
1048
1314
  'application',
@@ -2579,28 +2845,6 @@ export const wire${naming.ClassName}UseCase = wireClass(
2579
2845
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2580
2846
  }
2581
2847
  };
2582
- const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
2583
- class NestedName {
2584
- folders;
2585
- folderName;
2586
- fileName;
2587
- ClassName;
2588
- classNameSegments;
2589
- constructor(rawSource){
2590
- const segments = splitSegments(rawSource);
2591
- this.folders = segments.slice(0, -1);
2592
- this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
2593
- this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
2594
- this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
2595
- this.ClassName = this.classNameSegments.join('');
2596
- }
2597
- static validate = (rawSource)=>{
2598
- const segments = splitSegments(rawSource);
2599
- if (!segments.length) return 'Name is required';
2600
- if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
2601
- return true;
2602
- };
2603
- }
2604
2848
  const scaffoldReactPage = async (presentationReactFolder)=>{
2605
2849
  const name = await input({
2606
2850
  message: 'Provide name (folders split by "/"):',
@@ -2857,7 +3101,9 @@ const main = async ()=>{
2857
3101
  'New widget',
2858
3102
  'New page',
2859
3103
  'New UI-kit component',
2860
- 'New shared hook'
3104
+ 'New shared hook',
3105
+ 'Move or rename widget',
3106
+ 'Move or rename page'
2861
3107
  ]
2862
3108
  });
2863
3109
  switch(action){
@@ -2869,6 +3115,10 @@ const main = async ()=>{
2869
3115
  return void await scaffoldReactUIKitComponent(reactFolder);
2870
3116
  case 'New shared hook':
2871
3117
  return void await scaffoldReactSharedHook(reactFolder);
3118
+ case 'Move or rename widget':
3119
+ return void await moveReactModuleUseCase(reactFolder, 'widget');
3120
+ case 'Move or rename page':
3121
+ return void await moveReactModuleUseCase(reactFolder, 'page');
2872
3122
  default:
2873
3123
  return;
2874
3124
  }
@@ -0,0 +1,24 @@
1
+ export type ReactModuleKind = 'page' | 'widget';
2
+ export type ReactModule = {
3
+ kind: ReactModuleKind;
4
+ /** Nested name, e.g. `admin/users`. */
5
+ name: string;
6
+ /** The page file or the widget folder. */
7
+ path: string;
8
+ /** The name part of file names, e.g. `admin-users` in `admin-users-page.tsx`. */
9
+ fileBase: string;
10
+ ClassName: string;
11
+ };
12
+ export declare const findReactModules: (reactFolder: string, kind: ReactModuleKind) => ReactModule[];
13
+ export declare const validateMove: (reactFolder: string, module: ReactModule, rawName: string) => string | true;
14
+ export type MovePlan = {
15
+ /** Old path → new path of every file of the module. */
16
+ moves: [string, string][];
17
+ /** Other files with references to the module. */
18
+ updated: string[];
19
+ };
20
+ /**
21
+ * Stages the move with pending changes: files of the module, its imports
22
+ * of other files, and every import of it in the project.
23
+ */
24
+ export declare const moveReactModule: (projectRoot: string, reactFolder: string, module: ReactModule, rawName: string) => MovePlan;
@@ -0,0 +1 @@
1
+ export {};
@@ -1,5 +1,6 @@
1
1
  export * from './add-integration';
2
2
  export * from './initialize';
3
+ export * from './move-react-module';
3
4
  export * from './scaffold-new-aggregate';
4
5
  export * from './scaffold-new-application-port';
5
6
  export * from './scaffold-new-application-service';
@@ -0,0 +1,3 @@
1
+ import { type Folder } from '../file-system';
2
+ import { type ReactModuleKind } from '../react-module-move';
3
+ export declare const moveReactModuleUseCase: (presentationReactFolder: Folder, kind: ReactModuleKind) => Promise<void>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@domain-first/project-structure",
3
3
  "description": "Build and manage your Domain-First project structure with CLI",
4
- "version": "2.15.1",
4
+ "version": "2.16.0",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",