domain-driver 0.0.5 → 0.1.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.
@@ -1,68 +1,93 @@
1
- import * as fs from 'fs';
2
1
  import * as path from 'path';
2
+ import { ensureFeatureExists, writeFileSafe, fileExists, resolveImport } from '../utils';
3
3
 
4
4
  type ServiceAction = 'List' | 'Create' | 'Update' | 'Delete' | 'Show';
5
5
 
6
6
  const SERVICE_ACTIONS: ServiceAction[] = ['List', 'Create', 'Update', 'Delete', 'Show'];
7
7
 
8
- function renderService(action: ServiceAction, name: string): string {
8
+ function renderService(action: ServiceAction, name: string, feature: string): string {
9
+ const typePath = resolveImport(feature, `types/${name}.types`);
10
+ const repoPath = (op: string) => resolveImport(feature, `repositories/${op}${name}.repository`);
11
+ const schemaPath = (op: string) => resolveImport(feature, `schemas/${op}${name}.schema`);
12
+
9
13
  switch (action) {
10
14
  case 'List':
11
- return `export class List${name}Service {
12
- async handle() {
13
- // fetch all ${name}
15
+ return `import { ${name} } from '${typePath}';
16
+ import { List${name}Repository } from '${repoPath('List')}';
17
+
18
+ const repository = new List${name}Repository();
19
+
20
+ export class List${name}Service {
21
+ async handle(): Promise<${name}[]> {
22
+ return repository.handle();
14
23
  }
15
24
  }
16
25
  `;
17
26
  case 'Show':
18
- return `export class Show${name}Service {
19
- async handle(id: string) {
20
- // fetch single ${name}
27
+ return `import { ${name} } from '${typePath}';
28
+ import { Show${name}Repository } from '${repoPath('Show')}';
29
+
30
+ const repository = new Show${name}Repository();
31
+
32
+ export class Show${name}Service {
33
+ async handle(id: string): Promise<${name}> {
34
+ return repository.handle(id);
21
35
  }
22
36
  }
23
37
  `;
24
38
  case 'Create':
25
- return `export class Create${name}Service {
26
- async handle(data: unknown) {
27
- // create ${name}
39
+ return `import { ${name} } from '${typePath}';
40
+ import { Create${name} } from '${schemaPath('Create')}';
41
+ import { Create${name}Repository } from '${repoPath('Create')}';
42
+
43
+ const repository = new Create${name}Repository();
44
+
45
+ export class Create${name}Service {
46
+ async handle(data: Create${name}): Promise<${name}> {
47
+ return repository.handle(data);
28
48
  }
29
49
  }
30
50
  `;
31
51
  case 'Update':
32
- return `export class Update${name}Service {
33
- async handle(id: string, data: unknown) {
34
- // update ${name}
52
+ return `import { ${name} } from '${typePath}';
53
+ import { Update${name} } from '${schemaPath('Update')}';
54
+ import { Update${name}Repository } from '${repoPath('Update')}';
55
+
56
+ const repository = new Update${name}Repository();
57
+
58
+ export class Update${name}Service {
59
+ async handle(id: string, data: Update${name}): Promise<${name}> {
60
+ return repository.handle(id, data);
35
61
  }
36
62
  }
37
63
  `;
38
64
  case 'Delete':
39
- return `export class Delete${name}Service {
40
- async handle(id: string) {
41
- // delete ${name}
65
+ return `import { Delete${name}Repository } from '${repoPath('Delete')}';
66
+
67
+ const repository = new Delete${name}Repository();
68
+
69
+ export class Delete${name}Service {
70
+ async handle(id: string): Promise<void> {
71
+ return repository.handle(id);
42
72
  }
43
73
  }
44
74
  `;
45
75
  }
46
76
  }
47
77
 
48
- export function makeService(feature: string, name: string) {
49
- const base = path.join(process.cwd(), 'app', feature, 'services');
50
-
51
- if (!fs.existsSync(base)) {
52
- console.error(`❌ Feature "${feature}" does not exist. Run make:feature ${feature} first.`);
53
- process.exit(1);
54
- }
78
+ export function makeService(feature: string, name: string): void {
79
+ const base = ensureFeatureExists(feature, 'services');
55
80
 
56
81
  for (const action of SERVICE_ACTIONS) {
57
82
  const filePath = path.join(base, `${action}${name}.service.ts`);
58
83
 
59
- if (fs.existsSync(filePath)) {
84
+ if (fileExists(filePath)) {
60
85
  console.warn(`⚠️ Skipping "${action}${name}.service.ts" — already exists`);
61
86
  continue;
62
87
  }
63
88
 
64
- fs.writeFileSync(filePath, renderService(action, name));
89
+ writeFileSafe(filePath, renderService(action, name, feature));
65
90
  }
66
91
 
67
92
  console.log(`✅ Services for "${name}" created at ${base}`);
68
- }
93
+ }
@@ -0,0 +1,25 @@
1
+ import * as path from 'path';
2
+ import { ensureFeatureExists, writeFileSafe, fileExists } from '../utils';
3
+
4
+ function renderTypes(name: string): string {
5
+ return `export interface ${name} {
6
+ id: string;
7
+ // add ${name} fields here
8
+ createdAt: string;
9
+ updatedAt: string;
10
+ }
11
+ `;
12
+ }
13
+
14
+ export function makeTypes(feature: string, name: string): void {
15
+ const base = ensureFeatureExists(feature, 'types');
16
+ const filePath = path.join(base, `${name}.types.ts`);
17
+
18
+ if (fileExists(filePath)) {
19
+ console.warn(`⚠️ Skipping "${name}.types.ts" — already exists`);
20
+ return;
21
+ }
22
+
23
+ writeFileSafe(filePath, renderTypes(name));
24
+ console.log(`✅ Types for "${name}" created at ${filePath}`);
25
+ }
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { Command } from 'commander';
2
3
  import { makeFeature } from './commands/feature';
3
4
  import { makeComponent } from './commands/component';
4
5
  import { makeHook } from './commands/hook';
@@ -6,70 +7,120 @@ import { makeService } from './commands/service';
6
7
  import { makeSchema } from './commands/schema';
7
8
  import { makeRepository } from './commands/repository';
8
9
  import { makeContainer } from './commands/container';
10
+ import { makeTypes } from './commands/types';
9
11
 
10
- const [,, command, feature, name] = process.argv;
12
+ const program = new Command();
11
13
 
12
- if (!command || !feature) {
13
- console.error('Usage: domain-driver <command> [options]');
14
- process.exit(1);
15
- }
14
+ program
15
+ .name('domain-driver')
16
+ .description('CLI scaffolding tool for domain-driven development in Next.js')
17
+ .version('0.1.0');
16
18
 
17
- switch (command) {
18
- case 'make:feature':
19
- const all = process.argv.includes('-a') || process.argv.includes('-A');
20
- makeFeature(feature, all).then(() => {});
21
- break;
19
+ program
20
+ .command('make:feature <name>')
21
+ .description('Scaffold a full feature folder structure')
22
+ .option('-a, --all', 'Scaffold all files inside each folder')
23
+ .action(async (name: string, options: { all?: boolean }) => {
24
+ try {
25
+ await makeFeature(name, options.all ?? false);
26
+ } catch (error: unknown) {
27
+ const message = error instanceof Error ? error.message : 'Unknown error';
28
+ console.error(`❌ ${message}`);
29
+ process.exit(1);
30
+ }
31
+ });
32
+
33
+ program
34
+ .command('make:component <feature> <name>')
35
+ .description('Scaffold a component inside an existing feature')
36
+ .argument('[type]', 'Component type: client or server', 'client')
37
+ .action((feature: string, name: string, type: string) => {
38
+ try {
39
+ const componentType = type === 'server' ? 'server' : 'client';
40
+ makeComponent(feature, name, componentType);
41
+ } catch (error: unknown) {
42
+ const message = error instanceof Error ? error.message : 'Unknown error';
43
+ console.error(`❌ ${message}`);
44
+ process.exit(1);
45
+ }
46
+ });
22
47
 
23
- case 'make:component':
24
- if (!name) {
25
- console.error('Usage: domain-driver make:component <feature> <name> [client|server]');
48
+ program
49
+ .command('make:container <feature> <name>')
50
+ .description('Scaffold a smart container component inside an existing feature')
51
+ .action((feature: string, name: string) => {
52
+ try {
53
+ makeContainer(feature, name);
54
+ } catch (error: unknown) {
55
+ const message = error instanceof Error ? error.message : 'Unknown error';
56
+ console.error(`❌ ${message}`);
26
57
  process.exit(1);
27
58
  }
28
- const type = (process.argv[5] as 'client' | 'server') || 'client';
29
- makeComponent(feature, name, type);
30
- break;
59
+ });
31
60
 
32
- case 'make:hook':
33
- if (!name) {
34
- console.error('Usage: domain-driver make:hook <feature> <name>');
61
+ program
62
+ .command('make:hook <feature> <name>')
63
+ .description('Scaffold a custom hook inside an existing feature')
64
+ .action((feature: string, name: string) => {
65
+ try {
66
+ makeHook(feature, name);
67
+ } catch (error: unknown) {
68
+ const message = error instanceof Error ? error.message : 'Unknown error';
69
+ console.error(`❌ ${message}`);
35
70
  process.exit(1);
36
71
  }
37
- makeHook(feature, name);
38
- break;
72
+ });
39
73
 
40
- case 'make:service':
41
- if (!name) {
42
- console.error('Usage: domain-driver make:service <feature> <name>');
74
+ program
75
+ .command('make:service <feature> <name>')
76
+ .description('Scaffold single-responsibility service files inside an existing feature')
77
+ .action((feature: string, name: string) => {
78
+ try {
79
+ makeService(feature, name);
80
+ } catch (error: unknown) {
81
+ const message = error instanceof Error ? error.message : 'Unknown error';
82
+ console.error(`❌ ${message}`);
43
83
  process.exit(1);
44
84
  }
45
- makeService(feature, name);
46
- break;
85
+ });
47
86
 
48
- case 'make:schema':
49
- if (!name) {
50
- console.error('Usage: domain-driver make:schema <feature> <name>');
87
+ program
88
+ .command('make:repository <feature> <name>')
89
+ .description('Scaffold single-responsibility repository files inside an existing feature')
90
+ .action((feature: string, name: string) => {
91
+ try {
92
+ makeRepository(feature, name);
93
+ } catch (error: unknown) {
94
+ const message = error instanceof Error ? error.message : 'Unknown error';
95
+ console.error(`❌ ${message}`);
51
96
  process.exit(1);
52
97
  }
53
- makeSchema(feature, name);
54
- break;
98
+ });
55
99
 
56
- case 'make:repository':
57
- if (!name) {
58
- console.error('Usage: domain-driver make:repository <feature> <name>');
100
+ program
101
+ .command('make:schema <feature> <name>')
102
+ .description('Scaffold Zod schemas for create and update operations')
103
+ .action((feature: string, name: string) => {
104
+ try {
105
+ makeSchema(feature, name);
106
+ } catch (error: unknown) {
107
+ const message = error instanceof Error ? error.message : 'Unknown error';
108
+ console.error(`❌ ${message}`);
59
109
  process.exit(1);
60
110
  }
61
- makeRepository(feature, name);
62
- break;
111
+ });
63
112
 
64
- case 'make:container':
65
- if (!name) {
66
- console.error('Usage: domain-driver make:container <feature> <name>');
113
+ program
114
+ .command('make:types <feature> <name>')
115
+ .description('Scaffold a types file inside an existing feature')
116
+ .action((feature: string, name: string) => {
117
+ try {
118
+ makeTypes(feature, name);
119
+ } catch (error: unknown) {
120
+ const message = error instanceof Error ? error.message : 'Unknown error';
121
+ console.error(`❌ ${message}`);
67
122
  process.exit(1);
68
123
  }
69
- makeContainer(feature, name);
70
- break;
124
+ });
71
125
 
72
- default:
73
- console.error(`Unknown command: ${command}`);
74
- process.exit(1);
75
- }
126
+ program.parse();
package/src/utils.ts ADDED
@@ -0,0 +1,115 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+
4
+ export function toPascalCase(name: string): string {
5
+ return name
6
+ .split('-')
7
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
8
+ .join('');
9
+ }
10
+
11
+ export function featureBasePath(feature: string): string {
12
+ return path.join(process.cwd(), 'app', feature);
13
+ }
14
+
15
+ export function ensureFeatureExists(feature: string, subdir: string): string {
16
+ const base = path.join(featureBasePath(feature), subdir);
17
+
18
+ if (!fs.existsSync(base)) {
19
+ throw new Error(
20
+ `Feature "${feature}" does not exist. Run: domain-driver make:feature ${feature}`
21
+ );
22
+ }
23
+
24
+ return base;
25
+ }
26
+
27
+ export function writeFileSafe(filePath: string, content: string): void {
28
+ try {
29
+ fs.writeFileSync(filePath, content);
30
+ } catch (error: unknown) {
31
+ const message = error instanceof Error ? error.message : 'Unknown error';
32
+ throw new Error(`Failed to write ${filePath}: ${message}`);
33
+ }
34
+ }
35
+
36
+ export function mkdirSafe(dirPath: string): void {
37
+ try {
38
+ fs.mkdirSync(dirPath, { recursive: true });
39
+ } catch (error: unknown) {
40
+ const message = error instanceof Error ? error.message : 'Unknown error';
41
+ throw new Error(`Failed to create directory ${dirPath}: ${message}`);
42
+ }
43
+ }
44
+
45
+ export function fileExists(filePath: string): boolean {
46
+ return fs.existsSync(filePath);
47
+ }
48
+
49
+ interface AliasConfig {
50
+ alias: string | null;
51
+ appDir: string;
52
+ }
53
+
54
+ let cachedAlias: AliasConfig | undefined;
55
+
56
+ export function detectAlias(): AliasConfig {
57
+ if (cachedAlias) return cachedAlias;
58
+
59
+ const tsconfigPath = path.join(process.cwd(), 'tsconfig.json');
60
+
61
+ if (!fs.existsSync(tsconfigPath)) {
62
+ cachedAlias = { alias: null, appDir: 'app' };
63
+ return cachedAlias;
64
+ }
65
+
66
+ try {
67
+ const raw = fs.readFileSync(tsconfigPath, 'utf-8');
68
+ const stripped = raw.replace(/\/\/.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '');
69
+ const tsconfig = JSON.parse(stripped);
70
+ const paths = tsconfig?.compilerOptions?.paths;
71
+
72
+ if (paths) {
73
+ for (const [key, values] of Object.entries(paths)) {
74
+ const targets = values as string[];
75
+ const hasAppMapping = targets.some(
76
+ (v) => v === './app/*' || v === 'app/*' || v === './src/app/*' || v === 'src/app/*'
77
+ );
78
+ if (hasAppMapping && key.endsWith('/*')) {
79
+ const prefix = key.slice(0, -1);
80
+ const appDir = targets[0].replace('/*', '').replace('./', '');
81
+ cachedAlias = { alias: prefix, appDir };
82
+ return cachedAlias;
83
+ }
84
+
85
+ const hasSrcMapping = targets.some(
86
+ (v) => v === './src/*' || v === 'src/*' || v === './*'
87
+ );
88
+ if (hasSrcMapping && key.endsWith('/*')) {
89
+ const prefix = key.slice(0, -1);
90
+ cachedAlias = { alias: prefix, appDir: 'app' };
91
+ return cachedAlias;
92
+ }
93
+ }
94
+ }
95
+ } catch {
96
+ // tsconfig parse failed, fall back to relative imports
97
+ }
98
+
99
+ cachedAlias = { alias: null, appDir: 'app' };
100
+ return cachedAlias;
101
+ }
102
+
103
+ export function resetAliasCache(): void {
104
+ cachedAlias = undefined;
105
+ }
106
+
107
+ export function resolveImport(fromFeature: string, relativePath: string, fromRoot: boolean = false): string {
108
+ const { alias } = detectAlias();
109
+
110
+ if (alias) {
111
+ return `${alias}app/${fromFeature}/${relativePath}`;
112
+ }
113
+
114
+ return fromRoot ? `./${relativePath}` : `../${relativePath}`;
115
+ }
package/tsconfig.json CHANGED
@@ -9,5 +9,5 @@
9
9
  "types": ["node"]
10
10
  },
11
11
  "include": ["src/**/*"],
12
- "exclude": ["node_modules", "dist"]
12
+ "exclude": ["node_modules", "dist", "src/**/__tests__/**"]
13
13
  }
@@ -0,0 +1,7 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ include: ['src/**/__tests__/**/*.test.ts'],
6
+ },
7
+ });