@domain-first/project-structure 8.2.0 → 8.3.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/react.cjs CHANGED
@@ -3216,6 +3216,11 @@ const scaffoldRequestSchema = external_zod_default().discriminatedUnion('operati
3216
3216
  module: agent_requests_id.describe('Exact wiring target ID, including implementation class, from --describe.'),
3217
3217
  dependencies: agent_requests_dependencies
3218
3218
  }),
3219
+ operation('delete', {
3220
+ ...common,
3221
+ ...agent_requests_owner,
3222
+ module: agent_requests_id.describe('Exact unit ID from --describe. Refused while other files use it.')
3223
+ }),
3219
3224
  operation('move', {
3220
3225
  ...common,
3221
3226
  ...agent_requests_owner,
@@ -3253,6 +3258,15 @@ const reactRequestSchema = external_zod_default().discriminatedUnion('operation'
3253
3258
  name: agent_requests_nestedName,
3254
3259
  moveRoute: external_zod_default().boolean().optional().describe('With Next.js and a route at the page path: move it too (default true). Omit it without such a route.')
3255
3260
  }),
3261
+ operation('delete-page', {
3262
+ ...common,
3263
+ module: agent_requests_nestedName,
3264
+ deleteRoute: external_zod_default().boolean().optional().describe("With Next.js and the page's own route: delete it too (default true). Omit it without such a route.")
3265
+ }),
3266
+ operation('delete-widget', {
3267
+ ...common,
3268
+ module: agent_requests_nestedName
3269
+ }),
3256
3270
  operation('move-widget', {
3257
3271
  ...common,
3258
3272
  module: agent_requests_nestedName,
@@ -3756,6 +3770,75 @@ const projectRelative = (fromFile, toFile)=>{
3756
3770
  const relative = toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toFile.replace(codeExtension, '')));
3757
3771
  return relative.startsWith('.') ? relative : `./${relative}`;
3758
3772
  };
3773
+ const importSpecifier = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"\n]+)\1/g;
3774
+ const backend_module_move_importLine = /^\s*(?:import|export)\b[^'"\n]*\bfrom\s*(['"])([^'"\n]+)\1;?\s*$/;
3775
+ const deleteBackendUnit = (projectRoot, rootFolderPath, unit)=>{
3776
+ const files = [
3777
+ ...unitMoves(unit, unit).keys()
3778
+ ];
3779
+ const fileSet = new Set(files);
3780
+ const stems = new Set(files.map((file)=>file.replace(codeExtension, '')));
3781
+ const aggregateFolder = 'aggregate' === unit.kind ? external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.name) : void 0;
3782
+ const parentAggregate = unit.aggregate ? external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.aggregate) : void 0;
3783
+ const isUnit = (resolved)=>stems.has(resolved) || !!aggregateFolder && (resolved === aggregateFolder || resolved.startsWith(`${aggregateFolder}${external_node_path_default().sep}`));
3784
+ const isParentBarrel = (resolved)=>!!parentAggregate && (resolved === parentAggregate || resolved === external_node_path_default().join(parentAggregate, 'index'));
3785
+ const { codeFiles, resolve } = projectImports(projectRoot);
3786
+ const resolved = (specifier, file)=>resolve(specifier, file)?.resolved;
3787
+ const withoutUnitImports = (content, file)=>content.split('\n').filter((line)=>{
3788
+ const specifier = line.match(backend_module_move_importLine)?.[2];
3789
+ const target = specifier && resolved(specifier, file);
3790
+ return !(target && isUnit(target));
3791
+ }).join('\n');
3792
+ const cleaned = new Map();
3793
+ const inMemoryDb = inMemoryDbFile(rootFolderPath);
3794
+ if ('aggregate' === unit.kind && codeFiles.has(inMemoryDb)) {
3795
+ const section = new UnknownFormatNaming(plural(unit.name));
3796
+ const original = codeFiles.get(inMemoryDb);
3797
+ const content = withoutUnitImports(original.replace(new RegExp(`^[ \\t]*${escapeRegExp(section.variableName)}\\s*=\\s*this\\.section<[^\\n]*\\n?`, 'm'), ''), inMemoryDb);
3798
+ if (content !== original) cleaned.set(inMemoryDb, content);
3799
+ }
3800
+ if (parentAggregate) {
3801
+ const index = external_node_path_default().join(parentAggregate, 'index.ts');
3802
+ const original = codeFiles.get(index);
3803
+ if (void 0 !== original) {
3804
+ const content = withoutUnitImports(original, index);
3805
+ if (content !== original) cleaned.set(index, content);
3806
+ }
3807
+ }
3808
+ const ClassName = new UnknownFormatNaming(unit.name).ClassName;
3809
+ const namedImports = /import\s+(?:type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\2/g;
3810
+ const usedBy = [];
3811
+ const relative = (file)=>toPosix(external_node_path_default().relative(projectRoot, file));
3812
+ for (const [file, original] of codeFiles){
3813
+ if (fileSet.has(file)) continue;
3814
+ const content = cleaned.get(file) ?? original;
3815
+ for (const [, , specifier] of content.matchAll(importSpecifier)){
3816
+ const target = resolved(specifier, file);
3817
+ if (target && isUnit(target)) usedBy.push([
3818
+ relative(file),
3819
+ relative(target)
3820
+ ]);
3821
+ }
3822
+ for (const [, names, , specifier] of content.matchAll(namedImports)){
3823
+ const target = resolved(specifier, file);
3824
+ if (target && isParentBarrel(target) && new RegExp(`(?<![\\w$])${ClassName}(?![\\w$])`).test(names)) usedBy.push([
3825
+ relative(file),
3826
+ `${relative(target)} (${ClassName})`
3827
+ ]);
3828
+ }
3829
+ }
3830
+ if (usedBy.length) return {
3831
+ usedBy
3832
+ };
3833
+ for (const file of files)new file_system_File(file).delete(rootFolderPath);
3834
+ for (const [file, content] of cleaned)new file_system_File(file).update(content);
3835
+ return {
3836
+ deleted: files,
3837
+ updated: [
3838
+ ...cleaned.keys()
3839
+ ]
3840
+ };
3841
+ };
3759
3842
  const contractKinds = [
3760
3843
  'aggregate',
3761
3844
  'command',
@@ -3939,7 +4022,7 @@ const validateMove = (reactFolder, module, rawName)=>{
3939
4022
  if (target.startsWith(`${module.path}${external_node_path_default().sep}`)) return 'A widget cannot be moved into itself';
3940
4023
  return true;
3941
4024
  };
3942
- const routeFolder = (appFolder, rawName)=>{
4025
+ const react_module_move_routeFolder = (appFolder, rawName)=>{
3943
4026
  const { folders, folderName } = new NestedName(rawName);
3944
4027
  return external_node_path_default().join(appFolder, ...folders, folderName);
3945
4028
  };
@@ -4001,6 +4084,51 @@ const moveReactModule = (projectRoot, reactFolder, module, rawName, route)=>{
4001
4084
  }
4002
4085
  });
4003
4086
  };
4087
+ const pageRouteFolder = (appFolder, page)=>{
4088
+ const folder = react_module_move_routeFolder(appFolder, page.name);
4089
+ const routePage = external_node_path_default().join(folder, 'page.tsx');
4090
+ return external_node_fs_default().existsSync(routePage) && new RegExp(`(?<![\\w$])${page.ClassName}Page(?![\\w$])`).test(external_node_fs_default().readFileSync(routePage, 'utf8')) ? folder : void 0;
4091
+ };
4092
+ const reactModuleFiles = (module)=>{
4093
+ if ('widget' === module.kind) return module_move_walk(module.path);
4094
+ const folder = external_node_path_default().dirname(module.path);
4095
+ const own = new RegExp(`^${escapeRegExp(module.fileBase)}-page(?:\\.|$)`);
4096
+ return external_node_fs_default().readdirSync(folder, {
4097
+ withFileTypes: true
4098
+ }).filter((entry)=>entry.isFile() && own.test(entry.name)).map((entry)=>external_node_path_default().join(folder, entry.name));
4099
+ };
4100
+ const react_module_move_importSpecifier = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"\n]+)\1/g;
4101
+ const deleteReactModule = (projectRoot, reactFolder, module, route)=>{
4102
+ const moduleFiles = reactModuleFiles(module);
4103
+ const routeFileList = route ? routeFiles(route.folder) : [];
4104
+ const own = new Set([
4105
+ ...moduleFiles,
4106
+ ...routeFileList
4107
+ ]);
4108
+ const stems = new Set(moduleFiles.map((file)=>file.replace(codeExtension, '')));
4109
+ const isModule = (resolved)=>stems.has(resolved) || 'widget' === module.kind && (resolved === module.path || resolved.startsWith(`${module.path}${external_node_path_default().sep}`));
4110
+ const { codeFiles, resolve } = projectImports(projectRoot);
4111
+ const relative = (file)=>toPosix(external_node_path_default().relative(projectRoot, file));
4112
+ const usedBy = [];
4113
+ for (const [file, content] of codeFiles)if (!own.has(file)) for (const [, , specifier] of content.matchAll(react_module_move_importSpecifier)){
4114
+ const target = resolve(specifier, file)?.resolved;
4115
+ if (target && isModule(target)) usedBy.push([
4116
+ relative(file),
4117
+ relative(target)
4118
+ ]);
4119
+ }
4120
+ if (usedBy.length) return {
4121
+ usedBy
4122
+ };
4123
+ for (const file of moduleFiles)new file_system_File(file).delete(reactFolder);
4124
+ for (const file of routeFileList)new file_system_File(file).delete(route.appFolder);
4125
+ return {
4126
+ deleted: [
4127
+ ...moduleFiles,
4128
+ ...routeFileList
4129
+ ]
4130
+ };
4131
+ };
4004
4132
  const systemImplementationChoices = (kind, crossContext = false)=>{
4005
4133
  if ('ports' === kind) return crossContext ? [
4006
4134
  {
@@ -4015,6 +4143,108 @@ const systemImplementationChoices = (kind, crossContext = false)=>{
4015
4143
  }
4016
4144
  ] : [];
4017
4145
  };
4146
+ const deleteBackendUnitUseCase = async (ownerFolder)=>{
4147
+ const root = new project_root_ProjectRoot().path;
4148
+ const rootFolderPath = external_node_path_default().join(root, config_file_ConfigFile.Instance.data.project.rootFolder);
4149
+ const units = findBackendUnits(ownerFolder.path);
4150
+ if (!units.length) return void report('No modules generated by df-scaffold were found here.');
4151
+ const unit = await interaction_select({
4152
+ key: 'module',
4153
+ id: unitId,
4154
+ message: 'Module to delete:',
4155
+ choices: Object.keys(kindLayouts).flatMap((kind)=>{
4156
+ const group = units.filter((x)=>x.kind === kind);
4157
+ return group.length ? [
4158
+ new prompts_namespaceObject.Separator(`── ${kindLayouts[group[0].kind].title}`),
4159
+ ...group.map((value)=>({
4160
+ name: value.aggregate ? `${value.name} (${value.aggregate})` : value.name,
4161
+ value
4162
+ }))
4163
+ ] : [];
4164
+ }),
4165
+ pageSize: 20
4166
+ });
4167
+ const result = deleteBackendUnit(root, rootFolderPath, unit);
4168
+ if (result.usedBy) {
4169
+ if (isNonInteractive()) throw new RequestError('DELETE_NOT_ALLOWED', 'Other files still use the module.', {
4170
+ usedBy: result.usedBy
4171
+ });
4172
+ report([
4173
+ 'Nothing was deleted: these files still use it.',
4174
+ ...result.usedBy.map(([file, used])=>` ${file} → ${used}`),
4175
+ 'Remove those uses first (Wire dependency edits wiring; imports and constructor parameters are yours).'
4176
+ ].join('\n'));
4177
+ return;
4178
+ }
4179
+ const relative = (file)=>external_node_path_default().relative(root, file);
4180
+ report([
4181
+ 'Files to delete:',
4182
+ ...result.deleted.map((file)=>` ${relative(file)}`),
4183
+ ...result.updated.length ? [
4184
+ 'Files to update:',
4185
+ ...result.updated.map((file)=>` ${relative(file)}`)
4186
+ ] : []
4187
+ ].join('\n'));
4188
+ if (!await interaction_confirm({
4189
+ key: 'apply',
4190
+ message: 'Delete?',
4191
+ default: false
4192
+ })) {
4193
+ discardPendingChanges();
4194
+ report('Cancelled: nothing was deleted.');
4195
+ }
4196
+ };
4197
+ const deleteReactModuleUseCase = async (presentationReactFolder, kind)=>{
4198
+ const reactFolder = presentationReactFolder.path;
4199
+ const modules = findReactModules(reactFolder, kind);
4200
+ if (!modules.length) return void report(`No ${kind}s generated by df-react were found.`);
4201
+ const module = await interaction_select({
4202
+ key: 'module',
4203
+ id: (value)=>value.name,
4204
+ message: 'page' === kind ? 'Page to delete:' : 'Widget to delete:',
4205
+ choices: modules.map((value)=>({
4206
+ name: value.name,
4207
+ value,
4208
+ description: external_node_path_default().relative(reactFolder, value.path)
4209
+ }))
4210
+ });
4211
+ const root = new project_root_ProjectRoot().path;
4212
+ const relative = (file)=>external_node_path_default().relative(root, file).split(external_node_path_default().sep).join('/');
4213
+ const appFolder = external_node_path_default().join(root, nextAppFolder(root));
4214
+ const routeFolder = 'page' === kind && usesNext() ? pageRouteFolder(appFolder, module) : void 0;
4215
+ const withRoute = !!routeFolder && await interaction_confirm({
4216
+ key: 'deleteRoute',
4217
+ message: `Delete its Next.js route too: ${relative(routeFolder)}? Its URL stops working.`,
4218
+ default: true
4219
+ });
4220
+ const result = deleteReactModule(root, reactFolder, module, withRoute && routeFolder ? {
4221
+ appFolder,
4222
+ folder: routeFolder
4223
+ } : void 0);
4224
+ if (result.usedBy) {
4225
+ if (isNonInteractive()) throw new RequestError('DELETE_NOT_ALLOWED', `Other files still use the ${kind}.`, {
4226
+ usedBy: result.usedBy
4227
+ });
4228
+ report([
4229
+ 'Nothing was deleted: these files still use it.',
4230
+ ...result.usedBy.map(([file, used])=>` ${file} → ${used}`),
4231
+ 'Remove those uses first.'
4232
+ ].join('\n'));
4233
+ return;
4234
+ }
4235
+ report([
4236
+ 'Files to delete:',
4237
+ ...result.deleted.map((file)=>` ${relative(file)}`)
4238
+ ].join('\n'));
4239
+ if (!await interaction_confirm({
4240
+ key: 'apply',
4241
+ message: 'Delete?',
4242
+ default: false
4243
+ })) {
4244
+ discardPendingChanges();
4245
+ report('Cancelled: nothing was deleted.');
4246
+ }
4247
+ };
4018
4248
  Symbol('create-test-branch');
4019
4249
  Symbol('no-test-branch');
4020
4250
  const noAggregate = 'No aggregate';
@@ -4118,11 +4348,10 @@ const moveBackendUnitUseCase = async (ownerFolder)=>{
4118
4348
  const promptRouteMove = async (root, page, newName)=>{
4119
4349
  if (!usesNext()) return;
4120
4350
  const appFolder = external_node_path_default().join(root, nextAppFolder(root));
4121
- const from = routeFolder(appFolder, page.name);
4122
- const to = routeFolder(appFolder, newName);
4351
+ const from = pageRouteFolder(appFolder, page);
4352
+ const to = react_module_move_routeFolder(appFolder, newName);
4123
4353
  const relative = (file)=>external_node_path_default().relative(root, file).split(external_node_path_default().sep).join('/');
4124
- const routePage = external_node_path_default().join(from, 'page.tsx');
4125
- if (from === to || !external_node_fs_default().existsSync(routePage) || !new RegExp(`\\b${page.ClassName}Page\\b`).test(external_node_fs_default().readFileSync(routePage, 'utf8'))) return;
4354
+ if (!from || from === to) return;
4126
4355
  if (external_node_fs_default().existsSync(external_node_path_default().join(to, 'page.tsx'))) return void report(`${relative(to)}/page.tsx already exists: the route ${relative(from)} stays.`);
4127
4356
  const move = await interaction_confirm({
4128
4357
  key: 'moveRoute',
@@ -5578,7 +5807,7 @@ const executeScaffold = async (request, owner)=>{
5578
5807
  'errors'
5579
5808
  ]).content.fileNames.includes(request.namespace)) throw new RequestError('TARGET_NOT_FOUND', `Unknown namespace: ${request.namespace}.`);
5580
5809
  if ('implementation' === request.operation && !findContracts(owner.path).length) throw new RequestError('TARGET_NOT_FOUND', 'No contracts in this context.');
5581
- if ('move' === request.operation && !findBackendUnits(owner.path).length) throw new RequestError('TARGET_NOT_FOUND', 'No modules in this context.');
5810
+ if (('move' === request.operation || 'delete' === request.operation) && !findBackendUnits(owner.path).length) throw new RequestError('TARGET_NOT_FOUND', 'No modules in this context.');
5582
5811
  if ('wire-dependency' === request.operation && (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire') || !findWiredModules(owner.path).length)) throw new RequestError('TARGET_NOT_FOUND', 'No wired modules in this context.');
5583
5812
  if ('endpoint' === request.operation) {
5584
5813
  if (!config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/handlers-rest') || !findRestEndpointGenerator(new file_system_Folder(requireProject()).subitem([
@@ -5607,7 +5836,8 @@ const executeScaffold = async (request, owner)=>{
5607
5836
  implementation: ()=>scaffoldNewImplementation(owner),
5608
5837
  endpoint: ()=>scaffoldNewHandlersRestEndpoint(owner),
5609
5838
  'wire-dependency': ()=>wireDependency(owner),
5610
- move: ()=>moveBackendUnitUseCase(owner)
5839
+ move: ()=>moveBackendUnitUseCase(owner),
5840
+ delete: ()=>deleteBackendUnitUseCase(owner)
5611
5841
  };
5612
5842
  return actions[request.operation]();
5613
5843
  };
@@ -5616,14 +5846,16 @@ const executeReact = async (request)=>{
5616
5846
  config_file_ConfigFile.Instance.data.project.rootFolder,
5617
5847
  'presentation/react'
5618
5848
  ]);
5619
- if (request.operation.startsWith('move-') && !findReactModules(folder.path, 'move-page' === request.operation ? 'page' : 'widget').length) throw new RequestError('TARGET_NOT_FOUND', 'No React modules to move.');
5849
+ if (/^(move|delete)-/.test(request.operation) && !findReactModules(folder.path, request.operation.endsWith('-page') ? 'page' : 'widget').length) throw new RequestError('TARGET_NOT_FOUND', `No React ${request.operation.endsWith('-page') ? 'pages' : 'widgets'} here.`);
5620
5850
  const actions = {
5621
5851
  page: ()=>scaffoldReactPage(folder),
5622
5852
  widget: ()=>scaffoldReactWidget(folder),
5623
5853
  'ui-kit-component': ()=>scaffoldReactUIKitComponent(folder),
5624
5854
  'shared-hook': ()=>scaffoldReactSharedHook(folder),
5625
5855
  'move-page': ()=>moveReactModuleUseCase(folder, 'page'),
5626
- 'move-widget': ()=>moveReactModuleUseCase(folder, 'widget')
5856
+ 'move-widget': ()=>moveReactModuleUseCase(folder, 'widget'),
5857
+ 'delete-page': ()=>deleteReactModuleUseCase(folder, 'page'),
5858
+ 'delete-widget': ()=>deleteReactModuleUseCase(folder, 'widget')
5627
5859
  };
5628
5860
  return actions[request.operation]();
5629
5861
  };
@@ -5781,7 +6013,9 @@ Options:
5781
6013
  'New UI-kit component',
5782
6014
  'New shared hook',
5783
6015
  'Move or rename widget',
5784
- 'Move or rename page'
6016
+ 'Move or rename page',
6017
+ 'Delete widget',
6018
+ 'Delete page'
5785
6019
  ]
5786
6020
  });
5787
6021
  switch(action){
@@ -5797,6 +6031,10 @@ Options:
5797
6031
  return void await moveReactModuleUseCase(reactFolder, 'widget');
5798
6032
  case 'Move or rename page':
5799
6033
  return void await moveReactModuleUseCase(reactFolder, 'page');
6034
+ case 'Delete widget':
6035
+ return void await deleteReactModuleUseCase(reactFolder, 'widget');
6036
+ case 'Delete page':
6037
+ return void await deleteReactModuleUseCase(reactFolder, 'page');
5800
6038
  default:
5801
6039
  return;
5802
6040
  }
package/dist/react.js CHANGED
@@ -3,7 +3,7 @@ import { parseArgs } from "node:util";
3
3
  import { select as prompts_select } from "@inquirer/prompts";
4
4
  import { runCLI } from "./561.js";
5
5
  import { outdatedConfigMessage, ProjectRoot, ConfigFile, Folder } from "./870.js";
6
- import { scaffoldReactWidget, moveReactModuleUseCase, scaffoldReactPage, scaffoldReactUIKitComponent, scaffoldReactSharedHook, savePendingChanges } from "./287.js";
6
+ import { scaffoldReactWidget, moveReactModuleUseCase, deleteReactModuleUseCase, scaffoldReactPage, scaffoldReactUIKitComponent, scaffoldReactSharedHook, savePendingChanges } from "./287.js";
7
7
  runCLI('df-react', async ()=>{
8
8
  const help = `Usage: df-react
9
9
 
@@ -54,7 +54,9 @@ Options:
54
54
  'New UI-kit component',
55
55
  'New shared hook',
56
56
  'Move or rename widget',
57
- 'Move or rename page'
57
+ 'Move or rename page',
58
+ 'Delete widget',
59
+ 'Delete page'
58
60
  ]
59
61
  });
60
62
  switch(action){
@@ -70,6 +72,10 @@ Options:
70
72
  return void await moveReactModuleUseCase(reactFolder, 'widget');
71
73
  case 'Move or rename page':
72
74
  return void await moveReactModuleUseCase(reactFolder, 'page');
75
+ case 'Delete widget':
76
+ return void await deleteReactModuleUseCase(reactFolder, 'widget');
77
+ case 'Delete page':
78
+ return void await deleteReactModuleUseCase(reactFolder, 'page');
73
79
  default:
74
80
  return;
75
81
  }
@@ -0,0 +1,6 @@
1
+ import type { Folder } from '../file-system';
2
+ /**
3
+ * Deletes a unit of a bounded context or the Shared Kernel with every file
4
+ * of it, once nothing else in the project imports it.
5
+ */
6
+ export declare const deleteBackendUnitUseCase: (ownerFolder: Folder) => Promise<void>;
@@ -0,0 +1,8 @@
1
+ import { type Folder } from '../file-system';
2
+ import { type ReactModuleKind } from '../react-module-move';
3
+ /**
4
+ * Deletes a page or widget with its files once nothing else imports it.
5
+ * With Next.js, a page's own route can go with it: its URL stops working,
6
+ * so it is asked.
7
+ */
8
+ export declare const deleteReactModuleUseCase: (presentationReactFolder: Folder, kind: ReactModuleKind) => Promise<void>;
@@ -1,4 +1,6 @@
1
1
  export * from './add-integration';
2
+ export * from './delete-backend-unit';
3
+ export * from './delete-react-module';
2
4
  export * from './initialize';
3
5
  export * from './move-backend-unit';
4
6
  export * from './move-react-module';
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": "8.2.0",
4
+ "version": "8.3.0",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -41,7 +41,7 @@ A business element goes to UI-kit only when several widgets contain the same ele
41
41
 
42
42
  ## Running df-react
43
43
 
44
- Prefer `npx df-react --describe` and `npx df-react --request` JSON. The installed schema lists operations (`page`, `widget`, `ui-kit-component`, `shared-hook`, `move-page`, `move-widget`), fields and current React modules. For example:
44
+ Prefer `npx df-react --describe` and `npx df-react --request` JSON. The installed schema lists operations (`page`, `widget`, `ui-kit-component`, `shared-hook`, `move-page`, `move-widget`, `delete-page`, `delete-widget`), fields and current React modules. For example:
45
45
 
46
46
  ```bash
47
47
  npx df-react --request '{"operation":"widget","name":"cart","widgetType":"separated"}'
@@ -54,13 +54,15 @@ node <df-ps-scaffold-skill-dir>/scripts/drive.mjs --bin df-react [--cwd <dir>] [
54
54
  node <df-ps-scaffold-skill-dir>/scripts/drive.mjs --bin df-react "pick:New widget" text:cart "pick:with separated ui"
55
55
  ```
56
56
 
57
- Steps and checks are the same as for `df-scaffold` ("Legacy interactive driver" in `df-ps-scaffold`). Its menu: `New widget`, `New page`, `New UI-kit component`, `New shared hook`, `Move or rename widget`, `Move or rename page`. Prompts and output of each: `references/generators.md`.
57
+ Steps and checks are the same as for `df-scaffold` ("Legacy interactive driver" in `df-ps-scaffold`). Its menu: `New widget`, `New page`, `New UI-kit component`, `New shared hook`, `Move or rename widget`, `Move or rename page`, `Delete widget`, `Delete page`. Prompts and output of each: `references/generators.md`.
58
58
 
59
59
  If the CLI cannot run, report the failure and give the user the prepared JSON command (a menu path only for a legacy CLI). Never hand-write its output.
60
60
 
61
61
  ### Moving and renaming
62
62
 
63
- Moving or renaming a page or widget is a df-react run (`Move or rename page` / `Move or rename widget`): it creates the files at the new paths, so it needs an approved plan. With Next.js, moving a page can also move its App Router route and so change its URL: state in the plan whether the route moves (`moveRoute`), and ask the user when the request doesn't say. Don't move, rename, or copy their files by hand, and don't rename their `<Name>Page…`, `<Name>Widget…`, or `use<Name>UIModel` by hand: df-react keeps file names, code names, story titles, and imports in sync. List each move as a run: old → new name, the files to move (`→`), and the files whose imports change (`~`).
63
+ Moving or renaming a page or widget is a df-react run (`Move or rename page` / `Move or rename widget`): it creates the files at the new paths, so it needs an approved plan. With Next.js, moving a page can also move its App Router route and so change its URL: state in the plan whether the route moves (`moveRoute`), and ask the user when the request doesn't say. Don't move, rename, or copy their files by hand, and don't rename their `<Name>Page…`, `<Name>Widget…`, or `use<Name>UIModel` by hand: df-react keeps file names, code names, story titles, and imports in sync. List each move as a plan row (Type `page move` / `widget move`, Name `old → new`).
64
+
65
+ Deleting a page or widget is a df-react run too (`Delete page` / `Delete widget`, JSON `delete-page` / `delete-widget`) and needs an approved plan (Type `page delete` / `widget delete`). It is refused while other files import the module (`DELETE_NOT_ALLOWED` with `details.usedBy`): remove those uses first, or delete the importing module first. With Next.js, deleting a page can also delete its own route and so its URL: state it in the plan (`deleteRoute`), and ask the user when the request doesn't say. Never delete their files by hand.
64
66
 
65
67
  ### Files you may create by hand
66
68
 
@@ -25,6 +25,10 @@ Page and widget names may have folders before them: `text:admin/panel/users` →
25
25
 
26
26
  Move or rename a page or a widget only with df-react, never by hand: `"pick:Move or rename widget" "pick:admin/users" text:team/users "yes"` (`Move or rename page` for pages; the list shows nested names, the default new name is the current one). It moves the widget folder (or the page with its `<name>-page.*` files), renames files and `<Name>Widget…` / `use<Name>UIModel` / `<Name>Page…` to the new name, updates a generated story title and every import of the module (relative and `tsconfig` aliases; importers of barrels re-exporting it get the renamed classes), and fixes relative imports inside it. Before `Apply?` it prints the files to move and to update; check them. An existing target or a move into itself is rejected.
27
27
 
28
+ ## Delete page / widget
29
+
30
+ Delete a page or a widget only with df-react: `"pick:Delete widget" "pick:orders/filters" yes` (`Delete page` for pages; with Next.js and the page's own route, a `yes`/`no` for deleting the route comes before `Delete?`). It deletes the widget folder (or the page with its `<name>-page.*` files) and, if confirmed, the route folder's own files. It refuses while other files import the module and lists them; nothing changes then.
31
+
28
32
  ## New UI-kit component
29
33
 
30
34
  `"pick:New UI-kit" text:date-picker` → `…/react/ui-kit/n/`:
@@ -88,7 +88,7 @@ Reply "ok" to start.
88
88
  - **Scaffolding** has one block per owner, in run order: new contexts first, marked `(new)` (and `(provisional)` with the reason when ownership is a reversible default), then existing contexts, `shared-kernel`, React last.
89
89
  - **Why here**: one short sentence on why this owner, not another: the data or rule the context owns; for `shared-kernel`, why several contexts share it; for React, why the UI changes.
90
90
  - **What will be scaffolded**: one table per owner, one row per `df-scaffold`/`df-react` run. Layers in order domain → application → infrastructure → presentation, the layer in bold only on its first row. Repositories go with their aggregate in domain; commands, queries and ports in application (their implementations are Details); endpoints and React modules in presentation.
91
- - **Type**: the unit: aggregate, entity, value object, error, error namespace, service, port, command, query, use case, implementation, endpoint, wire dependency, move; for React: page, widget, ui-kit component, hook, page move, widget move.
91
+ - **Type**: the unit: aggregate, entity, value object, error, error namespace, service, port, command, query, use case, implementation, endpoint, wire dependency, move, delete; for React: page, widget, ui-kit component, hook, page move, widget move, page delete, widget delete.
92
92
  - **Name**: the entered name; for a move `old → new`; for an implementation the contract; for wire dependency the module.
93
93
  - **Details**: only what changes behavior: implementation types (`(saved)` when saved for future runs), the test implementation, dependencies (`deps: OrderRepository`), environments, widget type, the endpoint's handler, whether a Next.js route moves (`route moves: /a → /b`). No file paths, no CLI menu paths.
94
94
  - **Why**: at most six words: why this kind of module (`choosing-components.md`).
@@ -117,11 +117,11 @@ Anything else (helpers, types, constants, mappers, wiring, barrels): put it in a
117
117
 
118
118
  If the CLI cannot run, report the failure and give the user the prepared JSON command to run themselves (the menu path and answers only for a legacy CLI). Never hand-write its output. Missing generated files are only recreated by re-running the generator, as an approved overwrite.
119
119
 
120
- Moving or renaming a module (aggregate, entity, value object, service, port, query, command, use case) is a df-scaffold run, `Move or rename` (`references/units/move-or-rename.md`); a page or widget, a df-react run (`df-ps-react`). Never by hand: it creates files at the new paths, so it needs an approved plan.
120
+ Moving or renaming a module (aggregate, entity, value object, service, port, query, command, use case) is a df-scaffold run, `Move or rename` (`references/units/move-or-rename.md`); a page or widget, a df-react run (`df-ps-react`). Never by hand: it creates files at the new paths, so it needs an approved plan. Deleting a module is a df-scaffold run too, `Delete` (`references/units/delete.md`): it removes files, so it needs an approved plan as well.
121
121
 
122
122
  ### 3. New dependencies only through df-scaffold
123
123
 
124
- With `@domain-first/wire`, every new dependency of a wired class (a constructor parameter plus its wire) is added by `df-scaffold`: the generator's `Dependencies:` step for a new module, `Wire dependency` for an existing one, and the `Handler:` pick for an endpoint (its generator is added automatically). Don't add constructor parameters or wire entries by hand, and don't reorder or remove the ones `df-scaffold` added.
124
+ With `@domain-first/wire`, every new dependency of a wired class (a constructor parameter plus its wire) is added by `df-scaffold`: the generator's `Dependencies:` step for a new module, `Wire dependency` for an existing one, and the `Handler:` pick for an endpoint (its generator is added automatically). Don't add constructor parameters or wire entries by hand, and don't reorder or remove the ones `df-scaffold` added. The one exception: an approved plan removes a dependency (from the wire and the constructor together), e.g. before deleting the module it points to.
125
125
 
126
126
  - List each module's dependencies in its plan row's Details (`deps: OrderRepository`); for an existing module, add a `wire dependency` row.
127
127
  - A dependency the CLI doesn't offer is forbidden by the project's dependency rules (the defaults, changed by `backend.rules.dependencies` in the config) or by context isolation: change the design (a port, a query or command, an infrastructure service) instead of adding it by hand.
@@ -150,6 +150,7 @@ One file per unit in `references/units/`: when to choose it, how to generate it
150
150
  | REST endpoint | `endpoint.md` | Presentation → New Handlers-REST Endpoint |
151
151
  | Dependency of an existing module | `wire-dependency.md` | Wire dependency |
152
152
  | Moving or renaming a module | `move-or-rename.md` | Move or rename |
153
+ | Deleting a module | `delete.md` | Delete |
153
154
  | React modules | `df-ps-react` skill | `df-react` |
154
155
 
155
156
  ## Preparing runs
@@ -198,7 +199,7 @@ Check every run: exit code 0, no `WARNING`/`ABORTED`, and exactly the files its
198
199
  | Infrastructure | New Service, New Implementation | New Service, New Implementation |
199
200
  | Presentation | New Handlers-REST Endpoint (needs handlers-rest), New Service | New Service |
200
201
 
201
- With `@domain-first/wire`, the layer menu of a context and of the Shared Kernel also has `Wire dependency`: it adds dependencies to an existing wired module. Every layer menu has `Move or rename`.
202
+ With `@domain-first/wire`, the layer menu of a context and of the Shared Kernel also has `Wire dependency`: it adds dependencies to an existing wired module. Every layer menu has `Move or rename` and `Delete`.
202
203
 
203
204
  The main menu also has `Scaffold new bounded context`. React modules come from a separate CLI, `df-react`: see `df-ps-react`.
204
205
 
@@ -67,6 +67,7 @@ Compare the reported changes with the approved plan, then implement the generate
67
67
  | `CONTEXT_NOT_FOUND`, `TARGET_NOT_FOUND`, `REST_NOT_CONFIGURED` | Create the required context, aggregate, namespace, contract, handler or integration first if that work is authorized; otherwise report the missing prerequisite. A dry run of a prerequisite does not create it. |
68
68
  | `OVERWRITE_REQUIRED` | Preview and inspect the listed paths. Use `overwrite: true` only for replacements already within the approved plan; obtain any required plan change first. |
69
69
  | `MOVE_NOT_ALLOWED` | Review the boundary violations and change the design or move prerequisites first. Do not perform the move by hand. |
70
+ | `DELETE_NOT_ALLOWED` | `details.usedBy` lists `[file, import]` pairs still using the module. Remove those uses first if the plan covers it, or report them; never delete the files by hand. |
70
71
  | `CANCELLED`, `OPERATION_FAILED`, `UNSUPPORTED_PROMPT` | Inspect the message and report the failed operation or unsupported CLI path. Do not treat this as permission to switch to interactive execution or write output by hand. |
71
72
 
72
73
  Failures discard the operation's staged changes. Success can still have follow-up notes: inspect `messages`/`nextSteps` for manual adapter connection, integration installation, custom wiring or an implementation no longer selected by any environment. Check the actual generated files before implementing business logic.
@@ -28,6 +28,7 @@ All operations support `dryRun` and `overwrite`. Except `bounded-context`, they
28
28
  | `endpoint` | `controller`, `method`, `path` | REST package and generator must exist. With wiring and selectable handlers, provide `handler`. Without selectable handlers, omit it; the generated handler remains `never` and needs a later approved generator rerun. |
29
29
  | `wire-dependency` | `module`, `dependencies` | `module` is a wiring target ID, not a contract/unit ID. Adds only eligible dependencies not already wired to that implementation. |
30
30
  | `move` | `module` | `module` is a unit ID. Optional `name`, `targetContext`, `aggregate`; omitted name/context keep the existing ones. A same-owner entity/value-object keeps its aggregate by default. The target aggregate must exist; the target context must be a discovered, allowed destination for that unit kind. Illegal cross-context imports reject the move. |
31
+ | `delete` | `module` | `module` is a unit ID. Deletes every file of the unit and its generated references (aggregate barrel re-export, in-memory DB section). Refused with `DELETE_NOT_ALLOWED` and `details.usedBy` while other files import it; nothing changes. |
31
32
 
32
33
  `implementation` and `testImplementation` contain `type` and optional `save` (default false). Explicit types can be new ordinary names; they need not already be saved. Saving is independent for primary and test roles. The test type must differ from the primary type. Adding a new implementation remembers a saved type according to the selected environments: `test` or primary for other environments. Branches are `backend.envBranches.names` from the config (`test`, `development`, `production` when absent), with `backend.envBranches.test` as the test one; additional names must be offered by the existing branched wire. Custom branches without `test` take no test implementations: omit `testImplementation`. Without usable branching, omit `environments` and follow the returned wiring note.
33
34
 
@@ -118,6 +119,8 @@ The owner configures frontend first. React and Next.js use the same operations.
118
119
  | `shared-hook` | `name` | Single kebab-case name, preferably without `use-`; a leading `use-` is stripped. |
119
120
  | `move-page` | `module`, `name` | `module` is the existing nested page name from discovery; `name` is the target nested name. With Next.js and a route at the page path that renders the page, `moveRoute` (default true) moves that route folder's own files to the new path, changing the URL; `false` keeps the route with its import updated. Omit `moveRoute` when there is no such route. |
120
121
  | `move-widget` | `module`, `name` | Same for widgets. Files, imports, code names and generated story titles follow the move. |
122
+ | `delete-page` | `module` | Deletes the page and its `<name>-page.*` files. With Next.js and the page's own route, `deleteRoute` (default true) deletes that route folder's own files too; `false` keeps the route, which still imports the page, so the delete is refused. Omit `deleteRoute` without such a route. |
123
+ | `delete-widget` | `module` | Deletes the widget folder. Refused with `DELETE_NOT_ALLOWED` and `details.usedBy` while other files import it. |
121
124
 
122
125
  All support `dryRun` and `overwrite`. Use CLI moves even for a rename or folder regrouping; an existing target or a move into itself is rejected.
123
126
 
@@ -0,0 +1,19 @@
1
+ # Delete
2
+
3
+ When: a module is no longer needed. Never delete module files by hand: the CLI removes every file of the module and what the generators added for it elsewhere, and refuses while anything still uses it.
4
+
5
+ ## Generate (context and Shared Kernel)
6
+
7
+ Prompts: `Module to delete:` (select, grouped by kind as in Move or rename) → `Delete?` (default No).
8
+
9
+ `… "pick:Delete" pick:orders yes`
10
+
11
+ JSON: `{ "operation": "delete", "context": "sales", "module": "query:orders" }`.
12
+
13
+ Deleted: the files of the unit, as Move or rename moves them (an aggregate with its whole folder, entities and value objects inside included). Cleaned up: an entity's or value object's `export *` in its aggregate's `index.ts`, and an aggregate's in-memory DB section with its import.
14
+
15
+ Refused while other files import the module: other modules, their wires and specs, or importers of the aggregate barrel that name an entity or value object. The CLI prints `Nothing was deleted: these files still use it.` with each `file → import` (JSON: `DELETE_NOT_ALLOWED` with `details.usedBy`) and changes nothing. Remove the uses first: delete the dependent module first, or remove the dependency from its wire and constructor together, which needs the approved plan (rule 3 exception).
16
+
17
+ ## In the plan
18
+
19
+ A delete is a row of its owner: Type `delete`, Name the module, Why the reason it goes. List the uses that have to go first under Writing by hand.
@@ -222,6 +222,7 @@ const created = [...after.keys()].filter((p) => !before.has(p)).map(rel);
222
222
  const changed = [...after.keys()]
223
223
  .filter((p) => before.has(p) && before.get(p) !== after.get(p))
224
224
  .map(rel);
225
+ const deleted = [...before.keys()].filter((p) => !after.has(p)).map(rel);
225
226
 
226
227
  const plain = stripAnsi(output);
227
228
  const answered = [...plain.matchAll(/✔\s*([^\n]*)/g)].map((m) => m[1].trim());
@@ -240,6 +241,10 @@ console.log('\ncreated:');
240
241
  for (const file of created) console.log(` + ${file}`);
241
242
  console.log('\nchanged:');
242
243
  for (const file of changed) console.log(` ~ ${file}`);
244
+ if (deleted.length) {
245
+ console.log('\ndeleted:');
246
+ for (const file of deleted) console.log(` - ${file}`);
247
+ }
243
248
  if (code !== 0 || unansweredPrompt || aborted) {
244
249
  console.log('\nraw output (tail):');
245
250
  console.log(plain.split('\n').slice(-15).join('\n'));