@domain-first/project-structure 8.5.1 → 8.6.1

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
@@ -346,7 +346,8 @@ class file_system_File extends FileSystemItem {
346
346
  });
347
347
  };
348
348
  addLineIfMissing = (newLine, separator = '\n')=>{
349
- const alreadyAdded = this.exists && this.data.split('\n').some((line)=>line.trim() === newLine.trim());
349
+ const normalized = (line)=>line.trim().replace(/;$/, '');
350
+ const alreadyAdded = this.exists && this.data.split('\n').some((line)=>normalized(line) === normalized(newLine));
350
351
  if (!alreadyAdded) this.addLine(newLine, separator);
351
352
  };
352
353
  }
@@ -1419,7 +1420,31 @@ const scaffoldReactPage = async (presentationReactFolder)=>{
1419
1420
  if (usesNext()) scaffoldNextRoute(nestedName, pageFile);
1420
1421
  };
1421
1422
  const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
1422
- const rootFolderSegments = (rootFolder)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n `).join('');
1423
+ const rootFolderSegments = (rootFolder, indent = 20)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n${' '.repeat(indent)}`).join('');
1424
+ const endpointFileLookup = (rootFolder)=>` const [currentBoundedContext, ...relativePath] = routeMetadata.path;
1425
+
1426
+ if (!currentBoundedContext) {
1427
+ return undefined;
1428
+ }
1429
+
1430
+ // A controller is the first folder of the path; other routes
1431
+ // belong to the context root in presentation/rest/(root).
1432
+ const restFolder = path.join(
1433
+ ${rootFolderSegments(rootFolder, 16)}'bounded-contexts',
1434
+ currentBoundedContext,
1435
+ 'presentation',
1436
+ 'rest'
1437
+ );
1438
+ const endpointPath = [
1439
+ ...relativePath.map(pathParameterAsName),
1440
+ \`\${routeMetadata.method.toUpperCase()}.ts\`
1441
+ ];
1442
+ const endpointFile =
1443
+ project.getSourceFile(path.join(restFolder, ...endpointPath)) ??
1444
+ project.getSourceFile(
1445
+ path.join(restFolder, '(root)', ...endpointPath)
1446
+ );
1447
+ `;
1423
1448
  const openapiExtractor = (rootFolder)=>`import path from 'node:path';
1424
1449
  import {
1425
1450
  type DocNode,
@@ -1531,25 +1556,7 @@ export const createOpenApiDataFromEndpointLogicExtractor = ({
1531
1556
  path: readonly string[];
1532
1557
  }): OpenApiData | undefined => {
1533
1558
  try {
1534
- // The controller, if any, is the first folder of the path:
1535
- // context-root endpoints live right in presentation/rest.
1536
- const [currentBoundedContext, ...relativePath] = routeMetadata.path;
1537
-
1538
- if (!currentBoundedContext) {
1539
- return undefined;
1540
- }
1541
-
1542
- const endpointFile = project.getSourceFile(
1543
- path.join(
1544
- ${rootFolderSegments(rootFolder)}'bounded-contexts',
1545
- currentBoundedContext,
1546
- 'presentation',
1547
- 'rest',
1548
- ...relativePath.map(pathParameterAsName),
1549
- \`\${routeMetadata.method.toUpperCase()}.ts\`
1550
- )
1551
- );
1552
-
1559
+ ${endpointFileLookup(rootFolder)}
1553
1560
  if (!endpointFile) {
1554
1561
  return undefined;
1555
1562
  }
@@ -3200,7 +3207,7 @@ const scaffoldRequestSchema = external_zod_default().discriminatedUnion('operati
3200
3207
  agent_requests_operation('endpoint', {
3201
3208
  ...common,
3202
3209
  ...agent_requests_owner,
3203
- controller: agent_requests_name.optional().describe('Omit for an endpoint at the context root (`/<context>`); then path is empty or starts with a :param.'),
3210
+ controller: agent_requests_name.optional().describe('Omit for the context-root controller (root): `/<context>/<path>`.'),
3204
3211
  method: external_zod_default()["enum"]([
3205
3212
  'get',
3206
3213
  'post',
@@ -4236,6 +4243,35 @@ const deleteReactModule = (projectRoot, reactFolder, module, route)=>{
4236
4243
  ]
4237
4244
  };
4238
4245
  };
4246
+ const rootControllerFolder = '(root)';
4247
+ const pathParameterAsName = (segment)=>segment.startsWith(':') ? `_${segment.slice(1)}_` : segment;
4248
+ const isPathParameterName = (name)=>name.startsWith(':') || /^_.+_$/.test(name);
4249
+ const endpointFileNames = new Set([
4250
+ 'get',
4251
+ 'post',
4252
+ 'put',
4253
+ 'patch',
4254
+ 'delete'
4255
+ ].map((method)=>`${method.toUpperCase()}.ts`));
4256
+ const rest_layout_entries = (folder)=>external_node_fs_default().existsSync(folder) ? external_node_fs_default().readdirSync(folder, {
4257
+ withFileTypes: true
4258
+ }) : [];
4259
+ const rest_layout_subfolders = (folder)=>rest_layout_entries(folder).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name);
4260
+ const restFolders = (boundedContextFolder)=>({
4261
+ presentation: external_node_path_default().join(boundedContextFolder, 'presentation', 'rest'),
4262
+ wiring: external_node_path_default().join(boundedContextFolder, 'wiring', 'presentation', 'rest')
4263
+ });
4264
+ const restControllers = (boundedContextFolder)=>rest_layout_subfolders(restFolders(boundedContextFolder).presentation).filter((name)=>name !== rootControllerFolder && !isPathParameterName(name));
4265
+ const rootStaticSegments = (boundedContextFolder)=>rest_layout_subfolders(external_node_path_default().join(restFolders(boundedContextFolder).presentation, rootControllerFolder)).filter((name)=>!isPathParameterName(name));
4266
+ const legacyRootEndpoints = (boundedContextFolder)=>{
4267
+ const { presentation, wiring } = restFolders(boundedContextFolder);
4268
+ return {
4269
+ endpointFiles: rest_layout_entries(presentation).filter((entry)=>entry.isFile() && endpointFileNames.has(entry.name)).map((entry)=>external_node_path_default().join(presentation, entry.name)),
4270
+ parameterFolders: rest_layout_subfolders(presentation).filter(isPathParameterName).map((name)=>external_node_path_default().join(presentation, name)),
4271
+ wireFiles: rest_layout_entries(wiring).filter((entry)=>entry.isFile() && 'index.ts' !== entry.name && /\.ts$/.test(entry.name)).map((entry)=>external_node_path_default().join(wiring, entry.name))
4272
+ };
4273
+ };
4274
+ const hasLegacyRootEndpoints = (boundedContextFolder)=>Object.values(legacyRootEndpoints(boundedContextFolder)).some((paths)=>paths.length > 0);
4239
4275
  const systemImplementationChoices = (kind, crossContext = false)=>{
4240
4276
  if ('ports' === kind) return crossContext ? [
4241
4277
  {
@@ -5131,45 +5167,48 @@ export const ${names.namespace(ClassName)} = errorNamespace('${boundedContextFol
5131
5167
  namespaceFile.addLineIfMissing(errorClass(names.error(`${namespaceNaming.ClassName}${ClassName}`), exportedNamespace(namespaceFile, names.namespace(namespaceNaming.ClassName)), fileName), '\n\n');
5132
5168
  };
5133
5169
  const newController = 'New controller';
5134
- const withoutController = 'No controller (context root)';
5135
- const pathParameterAsName = (segment)=>segment.startsWith(':') ? `_${segment.slice(1)}_` : segment;
5136
- const isPathParameterName = (name)=>name.startsWith(':') || /^_.+_$/.test(name);
5170
+ const rootControllerChoice = 'No controller (context root)';
5137
5171
  const sharedRestFolder = (boundedContextFolder)=>boundedContextFolder.subitem([
5138
5172
  '..',
5139
5173
  '..',
5140
5174
  'presentation',
5141
5175
  'rest'
5142
5176
  ]);
5177
+ const legacyRootEndpointsMessage = (context)=>`${context} keeps its context-root endpoints in the 8.5 layout (presentation/rest/<METHOD>.ts, _param_/). Run npx df-upgrade to move them to presentation/rest/(root)/ first.`;
5143
5178
  const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
5179
+ const context = boundedContextFolder.name;
5144
5180
  const restPresentationFolder = boundedContextFolder.subitem([
5145
5181
  'presentation',
5146
5182
  'rest'
5147
5183
  ]);
5148
- const controllers = restPresentationFolder.content.subfolderNames.filter((x)=>!isPathParameterName(x));
5184
+ const controllers = restControllers(boundedContextFolder.path);
5185
+ const rootSegments = rootStaticSegments(boundedContextFolder.path);
5149
5186
  let controllerChoice = await interaction_select({
5150
5187
  key: 'controllerSelection',
5151
5188
  message: 'Controller: ',
5152
5189
  choices: [
5190
+ {
5191
+ value: rootControllerChoice,
5192
+ name: `(root) — /${context}`
5193
+ },
5153
5194
  ...controllers,
5154
- newController,
5155
- withoutController
5195
+ newController
5156
5196
  ]
5157
5197
  });
5198
+ if (controllerChoice === rootControllerChoice && hasLegacyRootEndpoints(boundedContextFolder.path)) throw new RequestError('UPGRADE_REQUIRED', legacyRootEndpointsMessage(context));
5158
5199
  if (controllerChoice === newController) controllerChoice = await interaction_input({
5159
5200
  key: 'controllerName',
5160
5201
  message: 'Name: ',
5161
- validate: (value)=>value.trim() ? isPathParameterName(value) || value.includes('/') ? 'A controller is one static path segment' : true : `Name is required; pick "${withoutController}" for an endpoint at the context root`
5202
+ validate: (value)=>{
5203
+ if (!value.trim()) return 'Name is required; pick "(root)" for an endpoint at the context root';
5204
+ if (isPathParameterName(value) || value.includes('/') || /[()]/.test(value)) return 'A controller is one static path segment';
5205
+ if (value === context) return `"${value}" is the context itself: pick "(root)" for /${context}`;
5206
+ if (rootSegments.includes(value)) return `/${context}/${value} belongs to the context root ((root)/${value}): add the endpoint there`;
5207
+ return true;
5208
+ }
5162
5209
  });
5163
- const controller = controllerChoice === withoutController ? void 0 : controllerChoice;
5210
+ const controller = controllerChoice === rootControllerChoice ? void 0 : controllerChoice;
5164
5211
  const withWiring = config_file_ConfigFile.backend.domainFirstPackages.includes('@domain-first/wire');
5165
- if (controller && !controllers.includes(controller) && withWiring) {
5166
- boundedContextFolder.subitem([
5167
- 'wiring',
5168
- 'presentation',
5169
- 'rest'
5170
- ]).file('index.ts').addLine(`export * from './${controller}'`);
5171
- sharedRestFolder(boundedContextFolder).file('wires.ts').addLine(`export * from '../../bounded-contexts/${boundedContextFolder.name}/wiring/presentation/rest/${controller}'`);
5172
- }
5173
5212
  const method = await interaction_select({
5174
5213
  key: 'method',
5175
5214
  message: 'Method:',
@@ -5186,10 +5225,16 @@ const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
5186
5225
  message: 'Relative path (split by "/"):',
5187
5226
  validate: (value)=>{
5188
5227
  const [first] = value.split('/').filter((x)=>!!x);
5189
- return controller || !first || first.startsWith(':') ? true : `Without a controller, the path is empty or starts with a path parameter; "${first}" is a controller`;
5228
+ return controller || !first || first.startsWith(':') || !controllers.includes(first) ? true : `/${context}/${first} belongs to controller "${first}": add the endpoint there`;
5190
5229
  }
5191
5230
  })).split('/').filter((x)=>!!x);
5231
+ const group = controller ?? "(root)";
5192
5232
  const folderSegments = [
5233
+ group,
5234
+ ...routeSegments
5235
+ ];
5236
+ const routePath = [
5237
+ context,
5193
5238
  ...controller ? [
5194
5239
  controller
5195
5240
  ] : [],
@@ -5197,7 +5242,7 @@ const scaffoldNewHandlersRestEndpoint = async (boundedContextFolder)=>{
5197
5242
  ];
5198
5243
  const endpointFolder = restPresentationFolder.subitem(folderSegments.map(pathParameterAsName));
5199
5244
  const nameSegments = [
5200
- controller ?? boundedContextFolder.name,
5245
+ controller ?? context,
5201
5246
  ...routeSegments
5202
5247
  ];
5203
5248
  const nameBase = `${[
@@ -5228,11 +5273,8 @@ export class ${endpointClassName} {
5228
5273
 
5229
5274
  get handle() {
5230
5275
  return this.endpointGenerator(this.handler.handle, {
5231
- route: { method: '${method}', path: [${[
5232
- boundedContextFolder.name,
5233
- ...folderSegments
5234
- ].map((x)=>`'${x}'`).join(', ')}] },
5235
- tags: ['${boundedContextFolder.name}${controller ? `: ${controller}` : ''}'],
5276
+ route: { method: '${method}', path: [${routePath.map((x)=>`'${x}'`).join(', ')}] },
5277
+ tags: ['${context}${controller ? `: ${controller}` : ''}'],
5236
5278
  })
5237
5279
  }
5238
5280
  }
@@ -5242,9 +5284,7 @@ export class ${endpointClassName} {
5242
5284
  'wiring',
5243
5285
  'presentation',
5244
5286
  'rest',
5245
- ...controller ? [
5246
- controller
5247
- ] : []
5287
+ group
5248
5288
  ]);
5249
5289
  const wireNameBase = `wire-${nameBase}`;
5250
5290
  const wireNaming = new UnknownFormatNaming(wireNameBase);
@@ -5264,7 +5304,12 @@ export const wire${endpointClassName} = wireClass(
5264
5304
  )
5265
5305
  `.trim());
5266
5306
  wiringFolder.file('index.ts').addLineIfMissing(`export * from './${wireNaming.fileName}'`);
5267
- if (!controller) sharedRestFolder(boundedContextFolder).file('wires.ts').addLineIfMissing(`export * from '../../bounded-contexts/${boundedContextFolder.name}/wiring/presentation/rest/${wireNaming.fileName}'`);
5307
+ boundedContextFolder.subitem([
5308
+ 'wiring',
5309
+ 'presentation',
5310
+ 'rest'
5311
+ ]).file('index.ts').addLineIfMissing(`export * from './${group}'`);
5312
+ sharedRestFolder(boundedContextFolder).file('wires.ts').addLineIfMissing(`export * from '../../bounded-contexts/${context}/wiring/presentation/rest/${group}'`);
5268
5313
  const restHandlersFile = sharedRestFolder(boundedContextFolder).file('index.ts');
5269
5314
  if (!restHandlersFile.exists) sharedRestFolder(boundedContextFolder).createFile('index.ts', `
5270
5315
  import * as wires from './wires'
@@ -5912,12 +5957,9 @@ const answersFor = (command, request, owner)=>{
5912
5957
  if ('error' === request.operation || 'error-namespace' === request.operation) defaults.errorAction = 'error-namespace' === request.operation ? 'New namespace' : request.namespace ? `New error in namespace ${request.namespace}` : 'New error without namespace';
5913
5958
  if ('endpoint' === request.operation) {
5914
5959
  delete answers.controller;
5915
- if (void 0 === request.controller) answers.controllerSelection = 'No controller (context root)';
5960
+ if (void 0 === request.controller) answers.controllerSelection = rootControllerChoice;
5916
5961
  else {
5917
- const existing = owner.subitem([
5918
- 'presentation',
5919
- 'rest'
5920
- ]).content.subfolderNames.includes(request.controller);
5962
+ const existing = restControllers(owner.path).includes(request.controller);
5921
5963
  answers.controllerSelection = existing ? request.controller : 'New controller';
5922
5964
  if (!existing) answers.controllerName = request.controller;
5923
5965
  }
package/dist/react.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { parseArgs } from "node:util";
3
3
  import { select as prompts_select } from "@inquirer/prompts";
4
4
  import { runCLI } from "./561.js";
5
- import { outdatedConfigMessage, ProjectRoot, ConfigFile, Folder } from "./870.js";
5
+ import { outdatedConfigMessage, ProjectRoot, ConfigFile, Folder } from "./780.js";
6
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
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Folder of the context-root controller (`/<context>/...`) in
3
+ * `presentation/rest/` and `wiring/presentation/rest/`. Like a Next.js route
4
+ * group, it is not a segment of the route.
5
+ */
6
+ export declare const rootControllerFolder = "(root)";
7
+ /**
8
+ * Path parameters (`:id`) can't be part of file and folder names
9
+ * everywhere (Windows), so they are named `_id_` there.
10
+ */
11
+ export declare const pathParameterAsName: (segment: string) => string;
12
+ export declare const isPathParameterName: (name: string) => boolean;
13
+ export declare const restFolders: (boundedContextFolder: string) => {
14
+ presentation: string;
15
+ wiring: string;
16
+ };
17
+ /** Static subfolders of `presentation/rest/`, except `(root)`. */
18
+ export declare const restControllers: (boundedContextFolder: string) => string[];
19
+ /**
20
+ * Static first segments of the context-root endpoints: each one is the
21
+ * start of `/<context>/<segment>`, which a controller of that name would
22
+ * share.
23
+ */
24
+ export declare const rootStaticSegments: (boundedContextFolder: string) => string[];
25
+ /**
26
+ * Context-root endpoints of 8.5 lived right in `presentation/rest/`
27
+ * (`GET.ts`, `_id_/`), their wires right in `wiring/presentation/rest/`.
28
+ */
29
+ export declare const legacyRootEndpoints: (boundedContextFolder: string) => {
30
+ endpointFiles: string[];
31
+ parameterFolders: string[];
32
+ wireFiles: string[];
33
+ };
34
+ export declare const hasLegacyRootEndpoints: (boundedContextFolder: string) => boolean;
@@ -0,0 +1,8 @@
1
+ import type { UpgradeStep } from './upgrade-steps';
2
+ export declare const restRootControllerStep: UpgradeStep;
3
+ export declare const openapiExtractorRootStep: UpgradeStep;
4
+ /**
5
+ * An extractor changed by hand, or of an earlier version, misses the
6
+ * context-root endpoints once they are in `(root)/`.
7
+ */
8
+ export declare const openapiExtractorManualStep: UpgradeStep;
@@ -9,6 +9,7 @@ export type UpgradeContext = {
9
9
  /**
10
10
  * - `required`: other commands refuse to run until it is applied.
11
11
  * - `optional`: changes generated code the user may have edited; asked one by one.
12
+ * Staged file changes are written with the config.
12
13
  * - `manual`: a note about what the user does themselves; changes nothing.
13
14
  */
14
15
  export type UpgradeStepKind = 'required' | 'optional' | 'manual';