@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/upgrade.cjs CHANGED
@@ -214,7 +214,8 @@ class File extends FileSystemItem {
214
214
  });
215
215
  };
216
216
  addLineIfMissing = (newLine, separator = '\n')=>{
217
- const alreadyAdded = this.exists && this.data.split('\n').some((line)=>line.trim() === newLine.trim());
217
+ const normalized = (line)=>line.trim().replace(/;$/, '');
218
+ const alreadyAdded = this.exists && this.data.split('\n').some((line)=>normalized(line) === normalized(newLine));
218
219
  if (!alreadyAdded) this.addLine(newLine, separator);
219
220
  };
220
221
  }
@@ -360,6 +361,375 @@ const hasDependency = (name)=>{
360
361
  manifest.optionalDependencies
361
362
  ].some((dependencies)=>dependencies && Object.hasOwn(dependencies, name));
362
363
  };
364
+ const openapiExtractorPath = "scripts/extract-open-api-data-from-endpoint.ts";
365
+ const rootFolderSegments = (rootFolder, indent = 20)=>rootFolder.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment && '.' !== segment).map((segment)=>`'${segment}',\n${' '.repeat(indent)}`).join('');
366
+ const legacyEndpointFileLookup = (rootFolder)=>` // The controller, if any, is the first folder of the path:
367
+ // context-root endpoints live right in presentation/rest.
368
+ const [currentBoundedContext, ...relativePath] = routeMetadata.path;
369
+
370
+ if (!currentBoundedContext) {
371
+ return undefined;
372
+ }
373
+
374
+ const endpointFile = project.getSourceFile(
375
+ path.join(
376
+ ${rootFolderSegments(rootFolder)}'bounded-contexts',
377
+ currentBoundedContext,
378
+ 'presentation',
379
+ 'rest',
380
+ ...relativePath.map(pathParameterAsName),
381
+ \`\${routeMetadata.method.toUpperCase()}.ts\`
382
+ )
383
+ );
384
+ `;
385
+ const endpointFileLookup = (rootFolder)=>` const [currentBoundedContext, ...relativePath] = routeMetadata.path;
386
+
387
+ if (!currentBoundedContext) {
388
+ return undefined;
389
+ }
390
+
391
+ // A controller is the first folder of the path; other routes
392
+ // belong to the context root in presentation/rest/(root).
393
+ const restFolder = path.join(
394
+ ${rootFolderSegments(rootFolder, 16)}'bounded-contexts',
395
+ currentBoundedContext,
396
+ 'presentation',
397
+ 'rest'
398
+ );
399
+ const endpointPath = [
400
+ ...relativePath.map(pathParameterAsName),
401
+ \`\${routeMetadata.method.toUpperCase()}.ts\`
402
+ ];
403
+ const endpointFile =
404
+ project.getSourceFile(path.join(restFolder, ...endpointPath)) ??
405
+ project.getSourceFile(
406
+ path.join(restFolder, '(root)', ...endpointPath)
407
+ );
408
+ `;
409
+ require("node:module");
410
+ const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
411
+ const ignoredFolders = new Set([
412
+ 'node_modules',
413
+ '.git',
414
+ '.next',
415
+ 'dist',
416
+ 'build',
417
+ 'out',
418
+ 'coverage',
419
+ 'storybook-static'
420
+ ]);
421
+ const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
422
+ const walk = (folder)=>{
423
+ if (!external_node_fs_default().existsSync(folder)) return [];
424
+ return external_node_fs_default().readdirSync(folder, {
425
+ withFileTypes: true
426
+ }).flatMap((entry)=>{
427
+ const entryPath = external_node_path_default().join(folder, entry.name);
428
+ if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : walk(entryPath);
429
+ return entry.isFile() ? [
430
+ entryPath
431
+ ] : [];
432
+ });
433
+ };
434
+ const toPosix = (value)=>value.split(external_node_path_default().sep).join('/');
435
+ const readAliases = (projectRoot)=>{
436
+ const tsconfig = external_node_path_default().join(projectRoot, 'tsconfig.json');
437
+ if (!external_node_fs_default().existsSync(tsconfig)) return [];
438
+ try {
439
+ const { compilerOptions = {} } = JSON.parse(stripJsonComments(external_node_fs_default().readFileSync(tsconfig, 'utf8')));
440
+ const base = external_node_path_default().resolve(projectRoot, compilerOptions.baseUrl ?? '.');
441
+ return Object.entries(compilerOptions.paths ?? {}).filter(([pattern, targets])=>pattern.endsWith('*') && targets[0]?.endsWith('*')).map(([pattern, [target]])=>({
442
+ prefix: pattern.slice(0, -1),
443
+ target: external_node_path_default().resolve(base, target.slice(0, -1))
444
+ }));
445
+ } catch {
446
+ return [];
447
+ }
448
+ };
449
+ const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
450
+ const reExportPattern = /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*(['"])([^'"\n]+)\1/g;
451
+ const importPaths = (file)=>{
452
+ const withoutExtension = file.replace(codeExtension, '');
453
+ return 'index' === external_node_path_default().basename(withoutExtension) ? [
454
+ withoutExtension,
455
+ external_node_path_default().dirname(withoutExtension)
456
+ ] : [
457
+ withoutExtension
458
+ ];
459
+ };
460
+ const projectImports = (projectRoot)=>{
461
+ const aliases = readAliases(projectRoot);
462
+ const resolve = (specifier, fromFile)=>{
463
+ if (specifier.startsWith('.')) return {
464
+ resolved: external_node_path_default().resolve(external_node_path_default().dirname(fromFile), specifier),
465
+ alias: void 0
466
+ };
467
+ const alias = aliases.find(({ prefix })=>specifier.startsWith(prefix));
468
+ return alias ? {
469
+ resolved: external_node_path_default().resolve(alias.target, specifier.slice(alias.prefix.length)),
470
+ alias
471
+ } : void 0;
472
+ };
473
+ const specifierFor = (fromFile, toPath, alias)=>{
474
+ const aliased = alias && toPosix(external_node_path_default().relative(alias.target, toPath));
475
+ if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
476
+ const relative = toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toPath));
477
+ return relative.startsWith('.') ? relative : `./${relative}`;
478
+ };
479
+ const codeFiles = new Map(walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
480
+ file,
481
+ external_node_fs_default().readFileSync(file, 'utf8')
482
+ ]));
483
+ const importsOf = (file)=>[
484
+ ...(codeFiles.get(file) ?? '').matchAll(specifierPattern)
485
+ ].map(([, , , specifier])=>resolve(specifier, file)?.resolved).filter((resolved)=>!!resolved);
486
+ return {
487
+ resolve,
488
+ specifierFor,
489
+ codeFiles,
490
+ importsOf
491
+ };
492
+ };
493
+ const stageModuleMove = ({ projectRoot, stopAt, moves, movedPath, rename, everyFile = (content)=>content, stopAtFor })=>{
494
+ const stopFor = (file)=>stopAtFor?.(file) ?? stopAt;
495
+ const { resolve, specifierFor, codeFiles } = projectImports(projectRoot);
496
+ const barrels = new Set();
497
+ const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
498
+ for(let found = true; found;){
499
+ found = false;
500
+ for (const [file, content] of codeFiles){
501
+ if (moves.has(file) || isBarrel(file)) continue;
502
+ const reExportsModule = [
503
+ ...content.matchAll(reExportPattern)
504
+ ].some(([, , specifier])=>{
505
+ const resolution = resolve(specifier, file);
506
+ return !!resolution && (!!movedPath(resolution.resolved) || isBarrel(resolution.resolved));
507
+ });
508
+ if (reExportsModule) {
509
+ for (const importPath of importPaths(file))barrels.add(importPath);
510
+ found = true;
511
+ }
512
+ }
513
+ }
514
+ const rewrite = (content, oldFile, newFile)=>{
515
+ let referencesModule = false;
516
+ const rewritten = content.replace(specifierPattern, (match, keyword, quote, specifier)=>{
517
+ const resolution = resolve(specifier, oldFile);
518
+ if (!resolution) return match;
519
+ const moved = movedPath(resolution.resolved);
520
+ if (moved || isBarrel(resolution.resolved)) referencesModule = true;
521
+ if (!moved && oldFile === newFile) return match;
522
+ const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
523
+ return `${keyword}${quote}${next}${quote}`;
524
+ });
525
+ const changed = everyFile(rewritten);
526
+ if (!referencesModule && !moves.has(oldFile)) return changed;
527
+ return rename(changed, {
528
+ moved: moves.has(oldFile)
529
+ });
530
+ };
531
+ for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new File(file).moveTo(newFile, stopFor(file));
532
+ const updated = [];
533
+ for (const [file, content] of codeFiles){
534
+ const newFile = moves.get(file);
535
+ const next = rewrite(content, file, newFile ?? file);
536
+ if (newFile && newFile !== file) {
537
+ new File(newFile).data = next;
538
+ new File(file).delete(stopFor(file));
539
+ } else if (next !== content) {
540
+ new File(file).update(next);
541
+ if (!newFile) updated.push(file);
542
+ }
543
+ }
544
+ return {
545
+ moves: [
546
+ ...moves
547
+ ].filter(([from, to])=>from !== to),
548
+ updated
549
+ };
550
+ };
551
+ const isPathParameterName = (name)=>name.startsWith(':') || /^_.+_$/.test(name);
552
+ const endpointFileNames = new Set([
553
+ 'get',
554
+ 'post',
555
+ 'put',
556
+ 'patch',
557
+ 'delete'
558
+ ].map((method)=>`${method.toUpperCase()}.ts`));
559
+ const rest_layout_entries = (folder)=>external_node_fs_default().existsSync(folder) ? external_node_fs_default().readdirSync(folder, {
560
+ withFileTypes: true
561
+ }) : [];
562
+ const subfolders = (folder)=>rest_layout_entries(folder).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name);
563
+ const restFolders = (boundedContextFolder)=>({
564
+ presentation: external_node_path_default().join(boundedContextFolder, 'presentation', 'rest'),
565
+ wiring: external_node_path_default().join(boundedContextFolder, 'wiring', 'presentation', 'rest')
566
+ });
567
+ const legacyRootEndpoints = (boundedContextFolder)=>{
568
+ const { presentation, wiring } = restFolders(boundedContextFolder);
569
+ return {
570
+ endpointFiles: rest_layout_entries(presentation).filter((entry)=>entry.isFile() && endpointFileNames.has(entry.name)).map((entry)=>external_node_path_default().join(presentation, entry.name)),
571
+ parameterFolders: subfolders(presentation).filter(isPathParameterName).map((name)=>external_node_path_default().join(presentation, name)),
572
+ 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))
573
+ };
574
+ };
575
+ const hasLegacyRootEndpoints = (boundedContextFolder)=>Object.values(legacyRootEndpoints(boundedContextFolder)).some((paths)=>paths.length > 0);
576
+ const rootFolderOf = ({ config })=>{
577
+ const project = config.project;
578
+ const rootFolder = 'object' == typeof project && null !== project ? project.rootFolder : void 0;
579
+ return 'string' == typeof rootFolder ? rootFolder : void 0;
580
+ };
581
+ const contextFolders = (context)=>{
582
+ const rootFolder = rootFolderOf(context);
583
+ if (!rootFolder) return [];
584
+ const contexts = external_node_path_default().join(new ProjectRoot().path, rootFolder, 'bounded-contexts');
585
+ return external_node_fs_default().existsSync(contexts) ? external_node_fs_default().readdirSync(contexts, {
586
+ withFileTypes: true
587
+ }).filter((entry)=>entry.isDirectory()).map((entry)=>external_node_path_default().join(contexts, entry.name)) : [];
588
+ };
589
+ const legacyContexts = (context)=>contextFolders(context).filter(hasLegacyRootEndpoints);
590
+ const upgrade_rest_root_relative = (file)=>toPosix(external_node_path_default().relative(new ProjectRoot().path, file));
591
+ const intoRoot = (folder, file)=>external_node_path_default().join(folder, "(root)", external_node_path_default().relative(folder, file));
592
+ const rootMoves = (contextFolder)=>{
593
+ const { presentation, wiring } = restFolders(contextFolder);
594
+ const { endpointFiles, parameterFolders, wireFiles } = legacyRootEndpoints(contextFolder);
595
+ return {
596
+ files: [
597
+ ...[
598
+ ...endpointFiles,
599
+ ...parameterFolders.flatMap(walk)
600
+ ].map((file)=>[
601
+ file,
602
+ intoRoot(presentation, file)
603
+ ]),
604
+ ...wireFiles.map((file)=>[
605
+ file,
606
+ intoRoot(wiring, file)
607
+ ])
608
+ ],
609
+ folders: parameterFolders.map((folder)=>[
610
+ folder,
611
+ intoRoot(presentation, folder)
612
+ ])
613
+ };
614
+ };
615
+ const exportPattern = /^export\s+\*\s+from\s+(['"])([^'"]+)\1;?\s*$/;
616
+ const exportedSpecifier = (line)=>line.trim().match(exportPattern)?.[2];
617
+ const regroupExports = (file, isRootWire, groupSpecifier)=>{
618
+ const lines = file.exists ? file.data.split('\n') : [];
619
+ const rootWires = lines.filter((line)=>{
620
+ const specifier = exportedSpecifier(line);
621
+ return !!specifier && isRootWire(specifier);
622
+ });
623
+ const first = rootWires.length ? lines.indexOf(rootWires[0]) : lines.length - [
624
+ ...lines
625
+ ].reverse().findIndex((line)=>!!line.trim());
626
+ const kept = lines.filter((line)=>!rootWires.includes(line));
627
+ if (!kept.some((line)=>exportedSpecifier(line) === groupSpecifier)) kept.splice(first, 0, `export * from '${groupSpecifier}'`);
628
+ file.update(kept.join('\n'));
629
+ return rootWires;
630
+ };
631
+ const restRootControllerStep = {
632
+ id: 'rest-root-controller',
633
+ kind: 'optional',
634
+ title: "Move context-root REST endpoints to presentation/rest/(root)/",
635
+ detect: (context)=>legacyContexts(context).length > 0,
636
+ plan: (context)=>legacyContexts(context).flatMap((contextFolder)=>{
637
+ const name = external_node_path_default().basename(contextFolder);
638
+ const { wiring } = restFolders(contextFolder);
639
+ const { files } = rootMoves(contextFolder);
640
+ const wired = files.some(([file])=>file.startsWith(wiring));
641
+ return [
642
+ ...files.map(([from, to])=>`${upgrade_rest_root_relative(from)} → ${upgrade_rest_root_relative(to)}`),
643
+ ...wired ? [
644
+ `${upgrade_rest_root_relative(external_node_path_default().join(wiring, 'index.ts'))}: the context-root lines → one line for ./(root)`,
645
+ `${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), added if missing`
646
+ ] : [],
647
+ 'Imports of the moved files are rewritten'
648
+ ];
649
+ }),
650
+ apply: (context)=>{
651
+ const contexts = legacyContexts(context);
652
+ const projectRoot = new ProjectRoot().path;
653
+ const moves = new Map();
654
+ const folders = [];
655
+ for (const contextFolder of contexts){
656
+ const planned = rootMoves(contextFolder);
657
+ for (const [from, to] of planned.files){
658
+ 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.`);
659
+ moves.set(from, to);
660
+ }
661
+ folders.push(...planned.folders);
662
+ }
663
+ const withoutExtension = new Map([
664
+ ...moves
665
+ ].map(([from, to])=>[
666
+ from.replace(codeExtension, ''),
667
+ to.replace(codeExtension, '')
668
+ ]));
669
+ stageModuleMove({
670
+ projectRoot,
671
+ stopAt: projectRoot,
672
+ stopAtFor: (file)=>contexts.flatMap((folder)=>Object.values(restFolders(folder))).find((folder)=>file.startsWith(`${folder}${external_node_path_default().sep}`)),
673
+ moves,
674
+ movedPath: (candidate)=>{
675
+ const moved = moves.get(candidate) ?? withoutExtension.get(candidate);
676
+ if (moved) return moved;
677
+ const folder = folders.find(([from])=>candidate === from || candidate.startsWith(`${from}${external_node_path_default().sep}`));
678
+ return folder ? folder[1] + candidate.slice(folder[0].length) : void 0;
679
+ },
680
+ rename: (content)=>content
681
+ });
682
+ const sharedWires = new File(external_node_path_default().join(projectRoot, rootFolderOf(context), 'presentation', 'rest', 'wires.ts'));
683
+ for (const contextFolder of contexts){
684
+ const name = external_node_path_default().basename(contextFolder);
685
+ const { wiring } = restFolders(contextFolder);
686
+ const movedWires = legacyRootEndpoints(contextFolder).wireFiles;
687
+ if (!movedWires.length) continue;
688
+ const listed = regroupExports(new File(external_node_path_default().join(wiring, 'index.ts')), (specifier)=>specifier.startsWith("./(root)/"), "./(root)").map((line)=>line.replace("./(root)/", './'));
689
+ const unlisted = movedWires.map((file)=>`./${external_node_path_default().basename(file, '.ts')}`).filter((specifier)=>!listed.some((line)=>exportedSpecifier(line) === specifier)).map((specifier)=>`export * from '${specifier}'`);
690
+ new File(external_node_path_default().join(wiring, "(root)", 'index.ts')).data = [
691
+ ...listed,
692
+ ...unlisted
693
+ ].join('\n');
694
+ const wiringPath = `bounded-contexts/${name}/wiring/presentation/rest/(root)`;
695
+ regroupExports(sharedWires, (specifier)=>specifier.includes(`${wiringPath}/`), `../../${wiringPath}`);
696
+ }
697
+ }
698
+ };
699
+ const extractorFile = ()=>new File(external_node_path_default().join(new ProjectRoot().path, openapiExtractorPath));
700
+ const openapiExtractorRootStep = {
701
+ id: 'openapi-extractor-root',
702
+ kind: 'optional',
703
+ title: "Let the OpenAPI extractor find endpoints in presentation/rest/(root)/",
704
+ detect: (context)=>{
705
+ const rootFolder = rootFolderOf(context);
706
+ const file = extractorFile();
707
+ return !!rootFolder && file.exists && file.data.includes(legacyEndpointFileLookup(rootFolder));
708
+ },
709
+ plan: ()=>[
710
+ `${openapiExtractorPath}: the endpoint file is looked up in the controller folder, then in (root)/`
711
+ ],
712
+ apply: (context)=>{
713
+ const rootFolder = rootFolderOf(context);
714
+ const file = extractorFile();
715
+ file.update(file.data.replace(legacyEndpointFileLookup(rootFolder), endpointFileLookup(rootFolder)));
716
+ }
717
+ };
718
+ const openapiExtractorManualStep = {
719
+ id: 'openapi-extractor-manual',
720
+ kind: 'manual',
721
+ title: 'Update the OpenAPI extractor by hand',
722
+ detect: (context)=>{
723
+ const rootFolder = rootFolderOf(context);
724
+ const file = extractorFile();
725
+ if (!rootFolder || !file.exists) return false;
726
+ const data = file.data;
727
+ 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)")));
728
+ },
729
+ plan: ()=>[
730
+ `${openapiExtractorPath} doesn't look up endpoints in presentation/rest/(root)/: compare it with the one npx df-integration scaffolds for openapi`
731
+ ]
732
+ };
363
733
  const record = (value)=>'object' != typeof value || null === value || Array.isArray(value) ? {} : value;
364
734
  const flatConfigSchema = external_zod_default().object({
365
735
  rootFolder: external_zod_default().string().min(1),
@@ -476,13 +846,17 @@ const persistenceStep = {
476
846
  const upgradeSteps = [
477
847
  sectionsStep,
478
848
  frameworkStep,
479
- persistenceStep
849
+ persistenceStep,
850
+ restRootControllerStep,
851
+ openapiExtractorRootStep,
852
+ openapiExtractorManualStep
480
853
  ];
481
854
  const skillsNote = 'Update the agent skills to this version: npx df-skills';
482
855
  const planUpgrade = async (config, acceptOptional = ()=>true, steps = upgradeSteps)=>{
483
856
  const context = {
484
857
  config: structuredClone(record(config))
485
858
  };
859
+ const original = JSON.stringify(context.config);
486
860
  const planned = [];
487
861
  for (const step of steps){
488
862
  if (!step.detect(context)) continue;
@@ -496,18 +870,20 @@ const planUpgrade = async (config, acceptOptional = ()=>true, steps = upgradeSte
496
870
  }
497
871
  }
498
872
  const changed = planned.some(({ step })=>'manual' !== step.kind);
873
+ const configChanged = JSON.stringify(context.config) !== original;
499
874
  return {
500
875
  planned,
501
876
  changed,
502
- config: changed ? configSchema.parse(context.config) : void 0
877
+ config: configChanged ? configSchema.parse(context.config) : void 0
503
878
  };
504
879
  };
505
880
  const help = `Usage: df-upgrade [--dry-run] [--yes]
506
881
 
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.
882
+ Brings the project up to date after upgrading @domain-first/project-structure.
883
+ Finds the steps the project needs, shows what each one changes, asks once
884
+ and applies them together. Other commands refuse a config of an earlier
885
+ major version until it is upgraded; optional steps move generated code to
886
+ the current layout.
511
887
 
512
888
  Options:
513
889
  --dry-run show the plan without writing anything
@@ -580,7 +956,7 @@ const run = async ()=>{
580
956
  }
581
957
  if (config) config_file_ConfigFile.write(config);
582
958
  writePendingChanges();
583
- console.log(`\nUpgraded ${configFileName}.`);
959
+ console.log(config ? `\nUpgraded ${configFileName}.` : '\nUpgraded.');
584
960
  console.log('\nDo it yourself:');
585
961
  for (const note of manual)console.log(` ${note}`);
586
962
  };
package/dist/upgrade.js CHANGED
@@ -3,8 +3,166 @@ 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 exportedSpecifier = (line)=>line.trim().match(exportPattern)?.[2];
50
+ const regroupExports = (file, isRootWire, groupSpecifier)=>{
51
+ const lines = file.exists ? file.data.split('\n') : [];
52
+ const rootWires = lines.filter((line)=>{
53
+ const specifier = exportedSpecifier(line);
54
+ return !!specifier && isRootWire(specifier);
55
+ });
56
+ const first = rootWires.length ? lines.indexOf(rootWires[0]) : lines.length - [
57
+ ...lines
58
+ ].reverse().findIndex((line)=>!!line.trim());
59
+ const kept = lines.filter((line)=>!rootWires.includes(line));
60
+ if (!kept.some((line)=>exportedSpecifier(line) === groupSpecifier)) kept.splice(first, 0, `export * from '${groupSpecifier}'`);
61
+ file.update(kept.join('\n'));
62
+ return rootWires;
63
+ };
64
+ const restRootControllerStep = {
65
+ id: 'rest-root-controller',
66
+ kind: 'optional',
67
+ title: "Move context-root REST endpoints to presentation/rest/(root)/",
68
+ detect: (context)=>legacyContexts(context).length > 0,
69
+ plan: (context)=>legacyContexts(context).flatMap((contextFolder)=>{
70
+ const name = node_path.basename(contextFolder);
71
+ const { wiring } = restFolders(contextFolder);
72
+ const { files } = rootMoves(contextFolder);
73
+ const wired = files.some(([file])=>file.startsWith(wiring));
74
+ return [
75
+ ...files.map(([from, to])=>`${relative(from)} → ${relative(to)}`),
76
+ ...wired ? [
77
+ `${relative(node_path.join(wiring, 'index.ts'))}: the context-root lines → one line for ./(root)`,
78
+ `${relative(node_path.join(new ProjectRoot().path, rootFolderOf(context), 'presentation', 'rest', 'wires.ts'))}: the ${name} context-root lines → one line for (root), added if missing`
79
+ ] : [],
80
+ 'Imports of the moved files are rewritten'
81
+ ];
82
+ }),
83
+ apply: (context)=>{
84
+ const contexts = legacyContexts(context);
85
+ const projectRoot = new ProjectRoot().path;
86
+ const moves = new Map();
87
+ const folders = [];
88
+ for (const contextFolder of contexts){
89
+ const planned = rootMoves(contextFolder);
90
+ for (const [from, to] of planned.files){
91
+ if (node_fs.existsSync(to)) throw new Error(`${relative(to)} already exists: move ${relative(from)} by hand, then run df-upgrade again.`);
92
+ moves.set(from, to);
93
+ }
94
+ folders.push(...planned.folders);
95
+ }
96
+ const withoutExtension = new Map([
97
+ ...moves
98
+ ].map(([from, to])=>[
99
+ from.replace(codeExtension, ''),
100
+ to.replace(codeExtension, '')
101
+ ]));
102
+ stageModuleMove({
103
+ projectRoot,
104
+ stopAt: projectRoot,
105
+ stopAtFor: (file)=>contexts.flatMap((folder)=>Object.values(restFolders(folder))).find((folder)=>file.startsWith(`${folder}${node_path.sep}`)),
106
+ moves,
107
+ movedPath: (candidate)=>{
108
+ const moved = moves.get(candidate) ?? withoutExtension.get(candidate);
109
+ if (moved) return moved;
110
+ const folder = folders.find(([from])=>candidate === from || candidate.startsWith(`${from}${node_path.sep}`));
111
+ return folder ? folder[1] + candidate.slice(folder[0].length) : void 0;
112
+ },
113
+ rename: (content)=>content
114
+ });
115
+ const sharedWires = new File(node_path.join(projectRoot, rootFolderOf(context), 'presentation', 'rest', 'wires.ts'));
116
+ for (const contextFolder of contexts){
117
+ const name = node_path.basename(contextFolder);
118
+ const { wiring } = restFolders(contextFolder);
119
+ const movedWires = legacyRootEndpoints(contextFolder).wireFiles;
120
+ if (!movedWires.length) continue;
121
+ const listed = regroupExports(new File(node_path.join(wiring, 'index.ts')), (specifier)=>specifier.startsWith("./(root)/"), "./(root)").map((line)=>line.replace("./(root)/", './'));
122
+ const unlisted = movedWires.map((file)=>`./${node_path.basename(file, '.ts')}`).filter((specifier)=>!listed.some((line)=>exportedSpecifier(line) === specifier)).map((specifier)=>`export * from '${specifier}'`);
123
+ new File(node_path.join(wiring, "(root)", 'index.ts')).data = [
124
+ ...listed,
125
+ ...unlisted
126
+ ].join('\n');
127
+ const wiringPath = `bounded-contexts/${name}/wiring/presentation/rest/(root)`;
128
+ regroupExports(sharedWires, (specifier)=>specifier.includes(`${wiringPath}/`), `../../${wiringPath}`);
129
+ }
130
+ }
131
+ };
132
+ const extractorFile = ()=>new File(node_path.join(new ProjectRoot().path, openapiExtractorPath));
133
+ const openapiExtractorRootStep = {
134
+ id: 'openapi-extractor-root',
135
+ kind: 'optional',
136
+ title: "Let the OpenAPI extractor find endpoints in presentation/rest/(root)/",
137
+ detect: (context)=>{
138
+ const rootFolder = rootFolderOf(context);
139
+ const file = extractorFile();
140
+ return !!rootFolder && file.exists && file.data.includes(legacyEndpointFileLookup(rootFolder));
141
+ },
142
+ plan: ()=>[
143
+ `${openapiExtractorPath}: the endpoint file is looked up in the controller folder, then in (root)/`
144
+ ],
145
+ apply: (context)=>{
146
+ const rootFolder = rootFolderOf(context);
147
+ const file = extractorFile();
148
+ file.update(file.data.replace(legacyEndpointFileLookup(rootFolder), endpointFileLookup(rootFolder)));
149
+ }
150
+ };
151
+ const openapiExtractorManualStep = {
152
+ id: 'openapi-extractor-manual',
153
+ kind: 'manual',
154
+ title: 'Update the OpenAPI extractor by hand',
155
+ detect: (context)=>{
156
+ const rootFolder = rootFolderOf(context);
157
+ const file = extractorFile();
158
+ if (!rootFolder || !file.exists) return false;
159
+ const data = file.data;
160
+ 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)")));
161
+ },
162
+ plan: ()=>[
163
+ `${openapiExtractorPath} doesn't look up endpoints in presentation/rest/(root)/: compare it with the one npx df-integration scaffolds for openapi`
164
+ ]
165
+ };
8
166
  const record = (value)=>'object' != typeof value || null === value || Array.isArray(value) ? {} : value;
9
167
  const flatConfigSchema = zod.object({
10
168
  rootFolder: zod.string().min(1),
@@ -121,13 +279,17 @@ const persistenceStep = {
121
279
  const upgradeSteps = [
122
280
  sectionsStep,
123
281
  frameworkStep,
124
- persistenceStep
282
+ persistenceStep,
283
+ restRootControllerStep,
284
+ openapiExtractorRootStep,
285
+ openapiExtractorManualStep
125
286
  ];
126
287
  const skillsNote = 'Update the agent skills to this version: npx df-skills';
127
288
  const planUpgrade = async (config, acceptOptional = ()=>true, steps = upgradeSteps)=>{
128
289
  const context = {
129
290
  config: structuredClone(record(config))
130
291
  };
292
+ const original = JSON.stringify(context.config);
131
293
  const planned = [];
132
294
  for (const step of steps){
133
295
  if (!step.detect(context)) continue;
@@ -141,18 +303,20 @@ const planUpgrade = async (config, acceptOptional = ()=>true, steps = upgradeSte
141
303
  }
142
304
  }
143
305
  const changed = planned.some(({ step })=>'manual' !== step.kind);
306
+ const configChanged = JSON.stringify(context.config) !== original;
144
307
  return {
145
308
  planned,
146
309
  changed,
147
- config: changed ? configSchema.parse(context.config) : void 0
310
+ config: configChanged ? configSchema.parse(context.config) : void 0
148
311
  };
149
312
  };
150
313
  const help = `Usage: df-upgrade [--dry-run] [--yes]
151
314
 
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.
315
+ Brings the project up to date after upgrading @domain-first/project-structure.
316
+ Finds the steps the project needs, shows what each one changes, asks once
317
+ and applies them together. Other commands refuse a config of an earlier
318
+ major version until it is upgraded; optional steps move generated code to
319
+ the current layout.
156
320
 
157
321
  Options:
158
322
  --dry-run show the plan without writing anything
@@ -225,7 +389,7 @@ const run = async ()=>{
225
389
  }
226
390
  if (config) ConfigFile.write(config);
227
391
  writePendingChanges();
228
- console.log(`\nUpgraded ${configFileName}.`);
392
+ console.log(config ? `\nUpgraded ${configFileName}.` : '\nUpgraded.');
229
393
  console.log('\nDo it yourself:');
230
394
  for (const note of manual)console.log(` ${note}`);
231
395
  };
@@ -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>;