@domain-first/project-structure 8.5.1 → 8.6.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/upgrade.cjs CHANGED
@@ -360,6 +360,368 @@ const hasDependency = (name)=>{
360
360
  manifest.optionalDependencies
361
361
  ].some((dependencies)=>dependencies && Object.hasOwn(dependencies, name));
362
362
  };
363
+ const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
364
+ const rootFolderSegments = (rootFolder, indent = 20)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n${' '.repeat(indent)}`).join('');
365
+ const legacyEndpointFileLookup = (rootFolder)=>` // The controller, if any, is the first folder of the path:
366
+ // context-root endpoints live right in presentation/rest.
367
+ const [currentBoundedContext, ...relativePath] = routeMetadata.path;
368
+
369
+ if (!currentBoundedContext) {
370
+ return undefined;
371
+ }
372
+
373
+ const endpointFile = project.getSourceFile(
374
+ path.join(
375
+ ${rootFolderSegments(rootFolder)}'bounded-contexts',
376
+ currentBoundedContext,
377
+ 'presentation',
378
+ 'rest',
379
+ ...relativePath.map(pathParameterAsName),
380
+ \`\${routeMetadata.method.toUpperCase()}.ts\`
381
+ )
382
+ );
383
+ `;
384
+ const endpointFileLookup = (rootFolder)=>` const [currentBoundedContext, ...relativePath] = routeMetadata.path;
385
+
386
+ if (!currentBoundedContext) {
387
+ return undefined;
388
+ }
389
+
390
+ // A controller is the first folder of the path; other routes
391
+ // belong to the context root in presentation/rest/(root).
392
+ const restFolder = path.join(
393
+ ${rootFolderSegments(rootFolder, 16)}'bounded-contexts',
394
+ currentBoundedContext,
395
+ 'presentation',
396
+ 'rest'
397
+ );
398
+ const endpointPath = [
399
+ ...relativePath.map(pathParameterAsName),
400
+ \`\${routeMetadata.method.toUpperCase()}.ts\`
401
+ ];
402
+ const endpointFile =
403
+ project.getSourceFile(path.join(restFolder, ...endpointPath)) ??
404
+ project.getSourceFile(
405
+ path.join(restFolder, '(root)', ...endpointPath)
406
+ );
407
+ `;
408
+ require("node:module");
409
+ const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
410
+ const ignoredFolders = new Set([
411
+ 'node_modules',
412
+ '.git',
413
+ '.next',
414
+ 'dist',
415
+ 'build',
416
+ 'out',
417
+ 'coverage',
418
+ 'storybook-static'
419
+ ]);
420
+ const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
421
+ const walk = (folder)=>{
422
+ if (!external_node_fs_default().existsSync(folder)) return [];
423
+ return external_node_fs_default().readdirSync(folder, {
424
+ withFileTypes: true
425
+ }).flatMap((entry)=>{
426
+ const entryPath = external_node_path_default().join(folder, entry.name);
427
+ if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : walk(entryPath);
428
+ return entry.isFile() ? [
429
+ entryPath
430
+ ] : [];
431
+ });
432
+ };
433
+ const toPosix = (value)=>value.split(external_node_path_default().sep).join('/');
434
+ const readAliases = (projectRoot)=>{
435
+ const tsconfig = external_node_path_default().join(projectRoot, 'tsconfig.json');
436
+ if (!external_node_fs_default().existsSync(tsconfig)) return [];
437
+ try {
438
+ const { compilerOptions = {} } = JSON.parse(stripJsonComments(external_node_fs_default().readFileSync(tsconfig, 'utf8')));
439
+ const base = external_node_path_default().resolve(projectRoot, compilerOptions.baseUrl ?? '.');
440
+ return Object.entries(compilerOptions.paths ?? {}).filter(([pattern, targets])=>pattern.endsWith('*') && targets[0]?.endsWith('*')).map(([pattern, [target]])=>({
441
+ prefix: pattern.slice(0, -1),
442
+ target: external_node_path_default().resolve(base, target.slice(0, -1))
443
+ }));
444
+ } catch {
445
+ return [];
446
+ }
447
+ };
448
+ const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
449
+ const reExportPattern = /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*(['"])([^'"\n]+)\1/g;
450
+ const importPaths = (file)=>{
451
+ const withoutExtension = file.replace(codeExtension, '');
452
+ return 'index' === external_node_path_default().basename(withoutExtension) ? [
453
+ withoutExtension,
454
+ external_node_path_default().dirname(withoutExtension)
455
+ ] : [
456
+ withoutExtension
457
+ ];
458
+ };
459
+ const projectImports = (projectRoot)=>{
460
+ const aliases = readAliases(projectRoot);
461
+ const resolve = (specifier, fromFile)=>{
462
+ if (specifier.startsWith('.')) return {
463
+ resolved: external_node_path_default().resolve(external_node_path_default().dirname(fromFile), specifier),
464
+ alias: void 0
465
+ };
466
+ const alias = aliases.find(({ prefix })=>specifier.startsWith(prefix));
467
+ return alias ? {
468
+ resolved: external_node_path_default().resolve(alias.target, specifier.slice(alias.prefix.length)),
469
+ alias
470
+ } : void 0;
471
+ };
472
+ const specifierFor = (fromFile, toPath, alias)=>{
473
+ const aliased = alias && toPosix(external_node_path_default().relative(alias.target, toPath));
474
+ if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
475
+ const relative = toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toPath));
476
+ return relative.startsWith('.') ? relative : `./${relative}`;
477
+ };
478
+ const codeFiles = new Map(walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
479
+ file,
480
+ external_node_fs_default().readFileSync(file, 'utf8')
481
+ ]));
482
+ const importsOf = (file)=>[
483
+ ...(codeFiles.get(file) ?? '').matchAll(specifierPattern)
484
+ ].map(([, , , specifier])=>resolve(specifier, file)?.resolved).filter((resolved)=>!!resolved);
485
+ return {
486
+ resolve,
487
+ specifierFor,
488
+ codeFiles,
489
+ importsOf
490
+ };
491
+ };
492
+ const stageModuleMove = ({ projectRoot, stopAt, moves, movedPath, rename, everyFile = (content)=>content, stopAtFor })=>{
493
+ const stopFor = (file)=>stopAtFor?.(file) ?? stopAt;
494
+ const { resolve, specifierFor, codeFiles } = projectImports(projectRoot);
495
+ const barrels = new Set();
496
+ const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
497
+ for(let found = true; found;){
498
+ found = false;
499
+ for (const [file, content] of codeFiles){
500
+ if (moves.has(file) || isBarrel(file)) continue;
501
+ const reExportsModule = [
502
+ ...content.matchAll(reExportPattern)
503
+ ].some(([, , specifier])=>{
504
+ const resolution = resolve(specifier, file);
505
+ return !!resolution && (!!movedPath(resolution.resolved) || isBarrel(resolution.resolved));
506
+ });
507
+ if (reExportsModule) {
508
+ for (const importPath of importPaths(file))barrels.add(importPath);
509
+ found = true;
510
+ }
511
+ }
512
+ }
513
+ const rewrite = (content, oldFile, newFile)=>{
514
+ let referencesModule = false;
515
+ const rewritten = content.replace(specifierPattern, (match, keyword, quote, specifier)=>{
516
+ const resolution = resolve(specifier, oldFile);
517
+ if (!resolution) return match;
518
+ const moved = movedPath(resolution.resolved);
519
+ if (moved || isBarrel(resolution.resolved)) referencesModule = true;
520
+ if (!moved && oldFile === newFile) return match;
521
+ const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
522
+ return `${keyword}${quote}${next}${quote}`;
523
+ });
524
+ const changed = everyFile(rewritten);
525
+ if (!referencesModule && !moves.has(oldFile)) return changed;
526
+ return rename(changed, {
527
+ moved: moves.has(oldFile)
528
+ });
529
+ };
530
+ for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new File(file).moveTo(newFile, stopFor(file));
531
+ const updated = [];
532
+ for (const [file, content] of codeFiles){
533
+ const newFile = moves.get(file);
534
+ const next = rewrite(content, file, newFile ?? file);
535
+ if (newFile && newFile !== file) {
536
+ new File(newFile).data = next;
537
+ new File(file).delete(stopFor(file));
538
+ } else if (next !== content) {
539
+ new File(file).update(next);
540
+ if (!newFile) updated.push(file);
541
+ }
542
+ }
543
+ return {
544
+ moves: [
545
+ ...moves
546
+ ].filter(([from, to])=>from !== to),
547
+ updated
548
+ };
549
+ };
550
+ const isPathParameterName = (name)=>name.startsWith(':') || /^_.+_$/.test(name);
551
+ const endpointFileNames = new Set([
552
+ 'get',
553
+ 'post',
554
+ 'put',
555
+ 'patch',
556
+ 'delete'
557
+ ].map((method)=>`${method.toUpperCase()}.ts`));
558
+ const rest_layout_entries = (folder)=>external_node_fs_default().existsSync(folder) ? external_node_fs_default().readdirSync(folder, {
559
+ withFileTypes: true
560
+ }) : [];
561
+ const subfolders = (folder)=>rest_layout_entries(folder).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name);
562
+ const restFolders = (boundedContextFolder)=>({
563
+ presentation: external_node_path_default().join(boundedContextFolder, 'presentation', 'rest'),
564
+ wiring: external_node_path_default().join(boundedContextFolder, 'wiring', 'presentation', 'rest')
565
+ });
566
+ const legacyRootEndpoints = (boundedContextFolder)=>{
567
+ const { presentation, wiring } = restFolders(boundedContextFolder);
568
+ return {
569
+ endpointFiles: rest_layout_entries(presentation).filter((entry)=>entry.isFile() && endpointFileNames.has(entry.name)).map((entry)=>external_node_path_default().join(presentation, entry.name)),
570
+ parameterFolders: subfolders(presentation).filter(isPathParameterName).map((name)=>external_node_path_default().join(presentation, name)),
571
+ 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))
572
+ };
573
+ };
574
+ const hasLegacyRootEndpoints = (boundedContextFolder)=>Object.values(legacyRootEndpoints(boundedContextFolder)).some((paths)=>paths.length > 0);
575
+ const rootFolderOf = ({ config })=>{
576
+ const project = config.project;
577
+ const rootFolder = 'object' == typeof project && null !== project ? project.rootFolder : void 0;
578
+ return 'string' == typeof rootFolder ? rootFolder : void 0;
579
+ };
580
+ const contextFolders = (context)=>{
581
+ const rootFolder = rootFolderOf(context);
582
+ if (!rootFolder) return [];
583
+ const contexts = external_node_path_default().join(new ProjectRoot().path, rootFolder, 'bounded-contexts');
584
+ return external_node_fs_default().existsSync(contexts) ? external_node_fs_default().readdirSync(contexts, {
585
+ withFileTypes: true
586
+ }).filter((entry)=>entry.isDirectory()).map((entry)=>external_node_path_default().join(contexts, entry.name)) : [];
587
+ };
588
+ const legacyContexts = (context)=>contextFolders(context).filter(hasLegacyRootEndpoints);
589
+ const upgrade_rest_root_relative = (file)=>toPosix(external_node_path_default().relative(new ProjectRoot().path, file));
590
+ const intoRoot = (folder, file)=>external_node_path_default().join(folder, "(root)", external_node_path_default().relative(folder, file));
591
+ const rootMoves = (contextFolder)=>{
592
+ const { presentation, wiring } = restFolders(contextFolder);
593
+ const { endpointFiles, parameterFolders, wireFiles } = legacyRootEndpoints(contextFolder);
594
+ return {
595
+ files: [
596
+ ...[
597
+ ...endpointFiles,
598
+ ...parameterFolders.flatMap(walk)
599
+ ].map((file)=>[
600
+ file,
601
+ intoRoot(presentation, file)
602
+ ]),
603
+ ...wireFiles.map((file)=>[
604
+ file,
605
+ intoRoot(wiring, file)
606
+ ])
607
+ ],
608
+ folders: parameterFolders.map((folder)=>[
609
+ folder,
610
+ intoRoot(presentation, folder)
611
+ ])
612
+ };
613
+ };
614
+ const exportPattern = /^export\s+\*\s+from\s+(['"])([^'"]+)\1;?\s*$/;
615
+ const regroupExports = (file, isRootWire, groupLine)=>{
616
+ if (!file.exists) return [];
617
+ const lines = file.data.split('\n');
618
+ const rootWires = lines.filter((line)=>{
619
+ const specifier = line.trim().match(exportPattern)?.[2];
620
+ return !!specifier && isRootWire(specifier);
621
+ });
622
+ if (!rootWires.length) return [];
623
+ const first = lines.indexOf(rootWires[0]);
624
+ const kept = lines.filter((line)=>!rootWires.includes(line));
625
+ if (!kept.some((line)=>line.trim() === groupLine)) kept.splice(first, 0, groupLine);
626
+ file.update(kept.join('\n'));
627
+ return rootWires;
628
+ };
629
+ const restRootControllerStep = {
630
+ id: 'rest-root-controller',
631
+ kind: 'optional',
632
+ title: "Move context-root REST endpoints to presentation/rest/(root)/",
633
+ detect: (context)=>legacyContexts(context).length > 0,
634
+ plan: (context)=>legacyContexts(context).flatMap((contextFolder)=>{
635
+ const name = external_node_path_default().basename(contextFolder);
636
+ const { wiring } = restFolders(contextFolder);
637
+ const { files } = rootMoves(contextFolder);
638
+ const wired = files.some(([file])=>file.startsWith(wiring));
639
+ return [
640
+ ...files.map(([from, to])=>`${upgrade_rest_root_relative(from)} → ${upgrade_rest_root_relative(to)}`),
641
+ ...wired ? [
642
+ `${upgrade_rest_root_relative(external_node_path_default().join(wiring, 'index.ts'))}: one line for ./(root)`,
643
+ `${upgrade_rest_root_relative(external_node_path_default().join(new ProjectRoot().path, rootFolderOf(context), 'presentation', 'rest', 'wires.ts'))}: the ${name} context-root lines → one line for (root)`
644
+ ] : [],
645
+ 'Imports of the moved files are rewritten'
646
+ ];
647
+ }),
648
+ apply: (context)=>{
649
+ const contexts = legacyContexts(context);
650
+ const projectRoot = new ProjectRoot().path;
651
+ const moves = new Map();
652
+ const folders = [];
653
+ for (const contextFolder of contexts){
654
+ const planned = rootMoves(contextFolder);
655
+ for (const [from, to] of planned.files){
656
+ if (external_node_fs_default().existsSync(to)) throw new Error(`${upgrade_rest_root_relative(to)} already exists: move ${upgrade_rest_root_relative(from)} by hand, then run df-upgrade again.`);
657
+ moves.set(from, to);
658
+ }
659
+ folders.push(...planned.folders);
660
+ }
661
+ const withoutExtension = new Map([
662
+ ...moves
663
+ ].map(([from, to])=>[
664
+ from.replace(codeExtension, ''),
665
+ to.replace(codeExtension, '')
666
+ ]));
667
+ stageModuleMove({
668
+ projectRoot,
669
+ stopAt: projectRoot,
670
+ stopAtFor: (file)=>contexts.flatMap((folder)=>Object.values(restFolders(folder))).find((folder)=>file.startsWith(`${folder}${external_node_path_default().sep}`)),
671
+ moves,
672
+ movedPath: (candidate)=>{
673
+ const moved = moves.get(candidate) ?? withoutExtension.get(candidate);
674
+ if (moved) return moved;
675
+ const folder = folders.find(([from])=>candidate === from || candidate.startsWith(`${from}${external_node_path_default().sep}`));
676
+ return folder ? folder[1] + candidate.slice(folder[0].length) : void 0;
677
+ },
678
+ rename: (content)=>content
679
+ });
680
+ const sharedWires = new File(external_node_path_default().join(projectRoot, rootFolderOf(context), 'presentation', 'rest', 'wires.ts'));
681
+ for (const contextFolder of contexts){
682
+ const name = external_node_path_default().basename(contextFolder);
683
+ const { wiring } = restFolders(contextFolder);
684
+ const rootWires = regroupExports(new File(external_node_path_default().join(wiring, 'index.ts')), (specifier)=>specifier.startsWith("./(root)/"), "export * from './(root)'");
685
+ if (rootWires.length) new File(external_node_path_default().join(wiring, "(root)", 'index.ts')).data = rootWires.map((line)=>line.replace("./(root)/", './')).join('\n');
686
+ const wiringPath = `bounded-contexts/${name}/wiring/presentation/rest/(root)`;
687
+ regroupExports(sharedWires, (specifier)=>specifier.includes(`${wiringPath}/`), `export * from '../../${wiringPath}'`);
688
+ }
689
+ }
690
+ };
691
+ const extractorFile = ()=>new File(external_node_path_default().join(new ProjectRoot().path, openapiExtractorPath));
692
+ const openapiExtractorRootStep = {
693
+ id: 'openapi-extractor-root',
694
+ kind: 'optional',
695
+ title: "Let the OpenAPI extractor find endpoints in presentation/rest/(root)/",
696
+ detect: (context)=>{
697
+ const rootFolder = rootFolderOf(context);
698
+ const file = extractorFile();
699
+ return !!rootFolder && file.exists && file.data.includes(legacyEndpointFileLookup(rootFolder));
700
+ },
701
+ plan: ()=>[
702
+ `${openapiExtractorPath}: the endpoint file is looked up in the controller folder, then in (root)/`
703
+ ],
704
+ apply: (context)=>{
705
+ const rootFolder = rootFolderOf(context);
706
+ const file = extractorFile();
707
+ file.update(file.data.replace(legacyEndpointFileLookup(rootFolder), endpointFileLookup(rootFolder)));
708
+ }
709
+ };
710
+ const openapiExtractorManualStep = {
711
+ id: 'openapi-extractor-manual',
712
+ kind: 'manual',
713
+ title: 'Update the OpenAPI extractor by hand',
714
+ detect: (context)=>{
715
+ const rootFolder = rootFolderOf(context);
716
+ const file = extractorFile();
717
+ if (!rootFolder || !file.exists) return false;
718
+ const data = file.data;
719
+ return !data.includes(endpointFileLookup(rootFolder)) && !data.includes(legacyEndpointFileLookup(rootFolder)) && contextFolders(context).some((folder)=>hasLegacyRootEndpoints(folder) || external_node_fs_default().existsSync(external_node_path_default().join(restFolders(folder).presentation, "(root)")));
720
+ },
721
+ plan: ()=>[
722
+ `${openapiExtractorPath} doesn't look up endpoints in presentation/rest/(root)/: compare it with the one npx df-integration scaffolds for openapi`
723
+ ]
724
+ };
363
725
  const record = (value)=>'object' != typeof value || null === value || Array.isArray(value) ? {} : value;
364
726
  const flatConfigSchema = external_zod_default().object({
365
727
  rootFolder: external_zod_default().string().min(1),
@@ -476,13 +838,17 @@ const persistenceStep = {
476
838
  const upgradeSteps = [
477
839
  sectionsStep,
478
840
  frameworkStep,
479
- persistenceStep
841
+ persistenceStep,
842
+ restRootControllerStep,
843
+ openapiExtractorRootStep,
844
+ openapiExtractorManualStep
480
845
  ];
481
846
  const skillsNote = 'Update the agent skills to this version: npx df-skills';
482
847
  const planUpgrade = async (config, acceptOptional = ()=>true, steps = upgradeSteps)=>{
483
848
  const context = {
484
849
  config: structuredClone(record(config))
485
850
  };
851
+ const original = JSON.stringify(context.config);
486
852
  const planned = [];
487
853
  for (const step of steps){
488
854
  if (!step.detect(context)) continue;
@@ -496,18 +862,20 @@ const planUpgrade = async (config, acceptOptional = ()=>true, steps = upgradeSte
496
862
  }
497
863
  }
498
864
  const changed = planned.some(({ step })=>'manual' !== step.kind);
865
+ const configChanged = JSON.stringify(context.config) !== original;
499
866
  return {
500
867
  planned,
501
868
  changed,
502
- config: changed ? configSchema.parse(context.config) : void 0
869
+ config: configChanged ? configSchema.parse(context.config) : void 0
503
870
  };
504
871
  };
505
872
  const help = `Usage: df-upgrade [--dry-run] [--yes]
506
873
 
507
- Brings the project up to date after upgrading @domain-first/project-structure
508
- to a new major version. Finds the steps the project needs, shows what each
509
- one changes, asks once and applies them together. Other commands refuse a
510
- config of an earlier major version until it is upgraded.
874
+ Brings the project up to date after upgrading @domain-first/project-structure.
875
+ Finds the steps the project needs, shows what each one changes, asks once
876
+ and applies them together. Other commands refuse a config of an earlier
877
+ major version until it is upgraded; optional steps move generated code to
878
+ the current layout.
511
879
 
512
880
  Options:
513
881
  --dry-run show the plan without writing anything
@@ -580,7 +948,7 @@ const run = async ()=>{
580
948
  }
581
949
  if (config) config_file_ConfigFile.write(config);
582
950
  writePendingChanges();
583
- console.log(`\nUpgraded ${configFileName}.`);
951
+ console.log(config ? `\nUpgraded ${configFileName}.` : '\nUpgraded.');
584
952
  console.log('\nDo it yourself:');
585
953
  for (const note of manual)console.log(` ${note}`);
586
954
  };
package/dist/upgrade.js CHANGED
@@ -3,8 +3,159 @@ import node_path from "node:path";
3
3
  import { parseArgs } from "node:util";
4
4
  import { confirm as prompts_confirm } from "@inquirer/prompts";
5
5
  import zod from "zod";
6
- import { implementationLabelSchema, domainFirstPackages as config_file_domainFirstPackages, configSchema, discardPendingChanges, rulesSchema, ConfigFile, isOutdatedConfig, writePendingChanges, File, configFileName, ProjectRoot } from "./870.js";
7
- import { hasDependency } from "./711.js";
6
+ import node_fs from "node:fs";
7
+ import { implementationLabelSchema, domainFirstPackages as config_file_domainFirstPackages, discardPendingChanges, configSchema, rulesSchema, ConfigFile, isOutdatedConfig, writePendingChanges, File, configFileName, ProjectRoot } from "./780.js";
8
+ import { restFolders, openapiExtractorPath, legacyEndpointFileLookup, walk, hasLegacyRootEndpoints, endpointFileLookup, hasDependency, stageModuleMove, legacyRootEndpoints, toPosix, codeExtension } from "./526.js";
9
+ const rootFolderOf = ({ config })=>{
10
+ const project = config.project;
11
+ const rootFolder = 'object' == typeof project && null !== project ? project.rootFolder : void 0;
12
+ return 'string' == typeof rootFolder ? rootFolder : void 0;
13
+ };
14
+ const contextFolders = (context)=>{
15
+ const rootFolder = rootFolderOf(context);
16
+ if (!rootFolder) return [];
17
+ const contexts = node_path.join(new ProjectRoot().path, rootFolder, 'bounded-contexts');
18
+ return node_fs.existsSync(contexts) ? node_fs.readdirSync(contexts, {
19
+ withFileTypes: true
20
+ }).filter((entry)=>entry.isDirectory()).map((entry)=>node_path.join(contexts, entry.name)) : [];
21
+ };
22
+ const legacyContexts = (context)=>contextFolders(context).filter(hasLegacyRootEndpoints);
23
+ const relative = (file)=>toPosix(node_path.relative(new ProjectRoot().path, file));
24
+ const intoRoot = (folder, file)=>node_path.join(folder, "(root)", node_path.relative(folder, file));
25
+ const rootMoves = (contextFolder)=>{
26
+ const { presentation, wiring } = restFolders(contextFolder);
27
+ const { endpointFiles, parameterFolders, wireFiles } = legacyRootEndpoints(contextFolder);
28
+ return {
29
+ files: [
30
+ ...[
31
+ ...endpointFiles,
32
+ ...parameterFolders.flatMap(walk)
33
+ ].map((file)=>[
34
+ file,
35
+ intoRoot(presentation, file)
36
+ ]),
37
+ ...wireFiles.map((file)=>[
38
+ file,
39
+ intoRoot(wiring, file)
40
+ ])
41
+ ],
42
+ folders: parameterFolders.map((folder)=>[
43
+ folder,
44
+ intoRoot(presentation, folder)
45
+ ])
46
+ };
47
+ };
48
+ const exportPattern = /^export\s+\*\s+from\s+(['"])([^'"]+)\1;?\s*$/;
49
+ const regroupExports = (file, isRootWire, groupLine)=>{
50
+ if (!file.exists) return [];
51
+ const lines = file.data.split('\n');
52
+ const rootWires = lines.filter((line)=>{
53
+ const specifier = line.trim().match(exportPattern)?.[2];
54
+ return !!specifier && isRootWire(specifier);
55
+ });
56
+ if (!rootWires.length) return [];
57
+ const first = lines.indexOf(rootWires[0]);
58
+ const kept = lines.filter((line)=>!rootWires.includes(line));
59
+ if (!kept.some((line)=>line.trim() === groupLine)) kept.splice(first, 0, groupLine);
60
+ file.update(kept.join('\n'));
61
+ return rootWires;
62
+ };
63
+ const restRootControllerStep = {
64
+ id: 'rest-root-controller',
65
+ kind: 'optional',
66
+ title: "Move context-root REST endpoints to presentation/rest/(root)/",
67
+ detect: (context)=>legacyContexts(context).length > 0,
68
+ plan: (context)=>legacyContexts(context).flatMap((contextFolder)=>{
69
+ const name = node_path.basename(contextFolder);
70
+ const { wiring } = restFolders(contextFolder);
71
+ const { files } = rootMoves(contextFolder);
72
+ const wired = files.some(([file])=>file.startsWith(wiring));
73
+ return [
74
+ ...files.map(([from, to])=>`${relative(from)} → ${relative(to)}`),
75
+ ...wired ? [
76
+ `${relative(node_path.join(wiring, 'index.ts'))}: one line for ./(root)`,
77
+ `${relative(node_path.join(new ProjectRoot().path, rootFolderOf(context), 'presentation', 'rest', 'wires.ts'))}: the ${name} context-root lines → one line for (root)`
78
+ ] : [],
79
+ 'Imports of the moved files are rewritten'
80
+ ];
81
+ }),
82
+ apply: (context)=>{
83
+ const contexts = legacyContexts(context);
84
+ const projectRoot = new ProjectRoot().path;
85
+ const moves = new Map();
86
+ const folders = [];
87
+ for (const contextFolder of contexts){
88
+ const planned = rootMoves(contextFolder);
89
+ for (const [from, to] of planned.files){
90
+ if (node_fs.existsSync(to)) throw new Error(`${relative(to)} already exists: move ${relative(from)} by hand, then run df-upgrade again.`);
91
+ moves.set(from, to);
92
+ }
93
+ folders.push(...planned.folders);
94
+ }
95
+ const withoutExtension = new Map([
96
+ ...moves
97
+ ].map(([from, to])=>[
98
+ from.replace(codeExtension, ''),
99
+ to.replace(codeExtension, '')
100
+ ]));
101
+ stageModuleMove({
102
+ projectRoot,
103
+ stopAt: projectRoot,
104
+ stopAtFor: (file)=>contexts.flatMap((folder)=>Object.values(restFolders(folder))).find((folder)=>file.startsWith(`${folder}${node_path.sep}`)),
105
+ moves,
106
+ movedPath: (candidate)=>{
107
+ const moved = moves.get(candidate) ?? withoutExtension.get(candidate);
108
+ if (moved) return moved;
109
+ const folder = folders.find(([from])=>candidate === from || candidate.startsWith(`${from}${node_path.sep}`));
110
+ return folder ? folder[1] + candidate.slice(folder[0].length) : void 0;
111
+ },
112
+ rename: (content)=>content
113
+ });
114
+ const sharedWires = new File(node_path.join(projectRoot, rootFolderOf(context), 'presentation', 'rest', 'wires.ts'));
115
+ for (const contextFolder of contexts){
116
+ const name = node_path.basename(contextFolder);
117
+ const { wiring } = restFolders(contextFolder);
118
+ const rootWires = regroupExports(new File(node_path.join(wiring, 'index.ts')), (specifier)=>specifier.startsWith("./(root)/"), "export * from './(root)'");
119
+ if (rootWires.length) new File(node_path.join(wiring, "(root)", 'index.ts')).data = rootWires.map((line)=>line.replace("./(root)/", './')).join('\n');
120
+ const wiringPath = `bounded-contexts/${name}/wiring/presentation/rest/(root)`;
121
+ regroupExports(sharedWires, (specifier)=>specifier.includes(`${wiringPath}/`), `export * from '../../${wiringPath}'`);
122
+ }
123
+ }
124
+ };
125
+ const extractorFile = ()=>new File(node_path.join(new ProjectRoot().path, openapiExtractorPath));
126
+ const openapiExtractorRootStep = {
127
+ id: 'openapi-extractor-root',
128
+ kind: 'optional',
129
+ title: "Let the OpenAPI extractor find endpoints in presentation/rest/(root)/",
130
+ detect: (context)=>{
131
+ const rootFolder = rootFolderOf(context);
132
+ const file = extractorFile();
133
+ return !!rootFolder && file.exists && file.data.includes(legacyEndpointFileLookup(rootFolder));
134
+ },
135
+ plan: ()=>[
136
+ `${openapiExtractorPath}: the endpoint file is looked up in the controller folder, then in (root)/`
137
+ ],
138
+ apply: (context)=>{
139
+ const rootFolder = rootFolderOf(context);
140
+ const file = extractorFile();
141
+ file.update(file.data.replace(legacyEndpointFileLookup(rootFolder), endpointFileLookup(rootFolder)));
142
+ }
143
+ };
144
+ const openapiExtractorManualStep = {
145
+ id: 'openapi-extractor-manual',
146
+ kind: 'manual',
147
+ title: 'Update the OpenAPI extractor by hand',
148
+ detect: (context)=>{
149
+ const rootFolder = rootFolderOf(context);
150
+ const file = extractorFile();
151
+ if (!rootFolder || !file.exists) return false;
152
+ const data = file.data;
153
+ return !data.includes(endpointFileLookup(rootFolder)) && !data.includes(legacyEndpointFileLookup(rootFolder)) && contextFolders(context).some((folder)=>hasLegacyRootEndpoints(folder) || node_fs.existsSync(node_path.join(restFolders(folder).presentation, "(root)")));
154
+ },
155
+ plan: ()=>[
156
+ `${openapiExtractorPath} doesn't look up endpoints in presentation/rest/(root)/: compare it with the one npx df-integration scaffolds for openapi`
157
+ ]
158
+ };
8
159
  const record = (value)=>'object' != typeof value || null === value || Array.isArray(value) ? {} : value;
9
160
  const flatConfigSchema = zod.object({
10
161
  rootFolder: zod.string().min(1),
@@ -121,13 +272,17 @@ const persistenceStep = {
121
272
  const upgradeSteps = [
122
273
  sectionsStep,
123
274
  frameworkStep,
124
- persistenceStep
275
+ persistenceStep,
276
+ restRootControllerStep,
277
+ openapiExtractorRootStep,
278
+ openapiExtractorManualStep
125
279
  ];
126
280
  const skillsNote = 'Update the agent skills to this version: npx df-skills';
127
281
  const planUpgrade = async (config, acceptOptional = ()=>true, steps = upgradeSteps)=>{
128
282
  const context = {
129
283
  config: structuredClone(record(config))
130
284
  };
285
+ const original = JSON.stringify(context.config);
131
286
  const planned = [];
132
287
  for (const step of steps){
133
288
  if (!step.detect(context)) continue;
@@ -141,18 +296,20 @@ const planUpgrade = async (config, acceptOptional = ()=>true, steps = upgradeSte
141
296
  }
142
297
  }
143
298
  const changed = planned.some(({ step })=>'manual' !== step.kind);
299
+ const configChanged = JSON.stringify(context.config) !== original;
144
300
  return {
145
301
  planned,
146
302
  changed,
147
- config: changed ? configSchema.parse(context.config) : void 0
303
+ config: configChanged ? configSchema.parse(context.config) : void 0
148
304
  };
149
305
  };
150
306
  const help = `Usage: df-upgrade [--dry-run] [--yes]
151
307
 
152
- Brings the project up to date after upgrading @domain-first/project-structure
153
- to a new major version. Finds the steps the project needs, shows what each
154
- one changes, asks once and applies them together. Other commands refuse a
155
- config of an earlier major version until it is upgraded.
308
+ Brings the project up to date after upgrading @domain-first/project-structure.
309
+ Finds the steps the project needs, shows what each one changes, asks once
310
+ and applies them together. Other commands refuse a config of an earlier
311
+ major version until it is upgraded; optional steps move generated code to
312
+ the current layout.
156
313
 
157
314
  Options:
158
315
  --dry-run show the plan without writing anything
@@ -225,7 +382,7 @@ const run = async ()=>{
225
382
  }
226
383
  if (config) ConfigFile.write(config);
227
384
  writePendingChanges();
228
- console.log(`\nUpgraded ${configFileName}.`);
385
+ console.log(config ? `\nUpgraded ${configFileName}.` : '\nUpgraded.');
229
386
  console.log('\nDo it yourself:');
230
387
  for (const note of manual)console.log(` ${note}`);
231
388
  };
@@ -1,2 +1,8 @@
1
1
  import type { Folder } from '../file-system';
2
+ /**
3
+ * The answer value of the context-root controller, kept from 8.5 so
4
+ * recorded answers still select it.
5
+ */
6
+ export declare const rootControllerChoice = "No controller (context root)";
7
+ export declare const legacyRootEndpointsMessage: (context: string) => string;
2
8
  export declare const scaffoldNewHandlersRestEndpoint: (boundedContextFolder: Folder) => 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": "8.5.1",
4
+ "version": "8.6.0",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -40,7 +40,7 @@ npx df-integration --request '{"operation":"add","integrations":["storybook"]}'
40
40
  - `dependencies`: implementation/class name → array of qualified module IDs. Omitted entries keep the generator's checked suggestions; `[]` explicitly selects none when that selection applies. When wiring is off or no candidates exist, omit the group; see the [dependency conditions](agent-operations.md#dependency-keys-and-system-implementations). Every supplied dependency group must apply to the operation. Different primary/test implementations have independent lists.
41
41
  - Aggregate repositories require `withRepository: true` and an `implementation`. Without it, aggregate creation makes no repository.
42
42
  - New implementations use a `contract` ID and, with a branched wire, an explicit `environments` array. Moves use a `module` unit ID and optional `targetContext`, `aggregate` and `name`. `wire-dependency` uses a wiring target ID in `module` plus its `dependencies` entry.
43
- - Endpoints use `controller`, lowercase `method`, relative `path` and a qualified `handler` ID when a wired handler is available. A new controller is created when its name does not exist; omit `controller` for an endpoint at the context root (`/<context>`, `/<context>/:id`).
43
+ - Endpoints use `controller`, lowercase `method`, relative `path` and a qualified `handler` ID when a wired handler is available. A new controller is created when its name does not exist; omit `controller` for the context-root controller `(root)` (`/<context>`, `/<context>/:id`, `/<context>/from-scratch`).
44
44
  - Integration-specific fields and script conflict decisions are in the integration request schema. Conflicts require explicit decisions, e.g. `"scriptConflicts": { "storybook": "keep" }`. Configuration changes that require confirmation interactively also require their explicit request field.
45
45
 
46
46
  ## Check the result