@azure-net/cli 5.1.1 → 6.0.0-next.3

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.
Files changed (180) hide show
  1. package/README.md +201 -0
  2. package/bin/azure-net.js +236 -221
  3. package/dist/bin/azure-net.d.ts +2 -0
  4. package/dist/src/checks/architecture.d.ts +20 -0
  5. package/dist/src/checks/checkDomain.d.ts +1 -0
  6. package/dist/src/checks/checkFoldersStructure.d.ts +1 -0
  7. package/dist/src/checks/checkHooks.d.ts +1 -0
  8. package/dist/src/checks/checkImports.d.ts +1 -0
  9. package/dist/src/checks/checkInternal.d.ts +1 -0
  10. package/dist/src/checks/checkLayerBoundaries.d.ts +1 -0
  11. package/dist/src/checks/checkLayerImports.d.ts +1 -0
  12. package/dist/src/checks/checkPresenterNames.d.ts +1 -0
  13. package/dist/src/checks/checkProject.d.ts +1 -0
  14. package/dist/src/checks/checkProviderGraph.d.ts +1 -0
  15. package/dist/src/checks/checkProviderNames.d.ts +1 -0
  16. package/dist/src/generate/layers/generateRepository.d.ts +1 -0
  17. package/dist/src/generate/layers/generateRepositoryMethod.d.ts +1 -0
  18. package/dist/src/generate/layers/generateUseCases.d.ts +1 -0
  19. package/dist/src/generate/module/generateDomain.d.ts +8 -0
  20. package/dist/src/generate/module/generateModule.d.ts +1 -0
  21. package/dist/src/generate/module/generateModulePreset.d.ts +1 -0
  22. package/dist/src/generate/module/generatePresenter.d.ts +29 -0
  23. package/dist/src/generate/module/generateRepository.d.ts +15 -0
  24. package/dist/src/generate/module/generateRepositoryMethod.d.ts +2 -0
  25. package/dist/src/generate/module/generateSchemaFromType.d.ts +9 -0
  26. package/dist/src/generate/module/generateStore.d.ts +1 -0
  27. package/dist/src/generate/module/generateTypesJson.d.ts +2 -0
  28. package/dist/src/generate/module/generateUseCases.d.ts +1 -0
  29. package/dist/src/generate/module/repositoryModuleShared.d.ts +89 -0
  30. package/dist/src/generate/routes/generateRoutes.d.ts +14 -0
  31. package/dist/src/generate/ui/generateComponent.d.ts +1 -0
  32. package/dist/src/generate/ui/generateDesignComponent.d.ts +1 -0
  33. package/dist/src/generate/ui/generateWidget.d.ts +1 -0
  34. package/dist/src/git/commit.d.ts +23 -0
  35. package/dist/src/git/push.d.ts +11 -0
  36. package/dist/src/git/runGit.d.ts +2 -0
  37. package/dist/src/init/initAliases.d.ts +12 -0
  38. package/dist/src/init/initEdges.d.ts +2 -0
  39. package/dist/src/init/initStructure.d.ts +1 -0
  40. package/dist/src/install/configureCommitTools.d.ts +1 -0
  41. package/dist/src/install/installFresh.d.ts +1 -0
  42. package/dist/src/migrate/migrate.d.ts +22 -0
  43. package/dist/src/migrate/presenterFactories.d.ts +9 -0
  44. package/dist/src/migrate/presenters.d.ts +13 -0
  45. package/dist/src/migrate/translations.d.ts +8 -0
  46. package/dist/src/plugins/addLint.d.ts +5 -0
  47. package/dist/src/scaffolds/createCoreSchema.d.ts +1 -0
  48. package/dist/src/scaffolds/createDatasource.d.ts +1 -0
  49. package/dist/src/scaffolds/createProgram.d.ts +1 -0
  50. package/dist/src/scaffolds/createResponse.d.ts +1 -0
  51. package/dist/src/scaffolds/createSchemaRule.d.ts +1 -0
  52. package/dist/src/scaffolds/createTranslationManager.d.ts +1 -0
  53. package/{src/scaffolds/index.ts → dist/src/scaffolds/index.d.ts} +0 -2
  54. package/dist/src/scaffolds/registerDatasource.d.ts +2 -0
  55. package/dist/src/scaffolds/updateDefaultFactoryConfig.d.ts +1 -0
  56. package/dist/src/utils/architecture.d.ts +31 -0
  57. package/dist/src/utils/contextUtils.d.ts +6 -0
  58. package/dist/src/utils/fileUtils.d.ts +5 -0
  59. package/dist/src/utils/flattenConfig.d.ts +2 -0
  60. package/dist/src/utils/legacyAliases.d.ts +1 -0
  61. package/dist/src/utils/loadConfig.d.ts +16 -0
  62. package/dist/src/utils/packageImports.d.ts +4 -0
  63. package/dist/src/utils/sharedFoundation.d.ts +20 -0
  64. package/dist/src/utils/viteConfig.d.ts +9 -0
  65. package/package.json +17 -7
  66. package/src/checks/architecture.js +154 -0
  67. package/src/checks/checkDomain.js +124 -154
  68. package/src/checks/checkFoldersStructure.js +64 -52
  69. package/src/checks/checkHooks.js +12 -12
  70. package/src/checks/checkImports.js +26 -142
  71. package/src/checks/checkInternal.js +27 -24
  72. package/src/checks/checkLayerBoundaries.js +22 -197
  73. package/src/checks/checkLayerImports.js +14 -134
  74. package/src/checks/checkPresenterNames.js +156 -143
  75. package/src/checks/checkProject.js +27 -26
  76. package/src/checks/checkProviderGraph.js +182 -166
  77. package/src/checks/checkProviderNames.js +123 -112
  78. package/src/generate/layers/generateRepository.js +1 -109
  79. package/src/generate/layers/generateRepositoryMethod.js +1 -90
  80. package/src/generate/layers/generateUseCases.js +1 -44
  81. package/src/generate/module/generateDomain.js +81 -105
  82. package/src/generate/module/generateModule.js +34 -68
  83. package/src/generate/module/generateModulePreset.js +188 -248
  84. package/src/generate/module/generatePresenter.js +441 -369
  85. package/src/generate/module/generateRepository.js +102 -121
  86. package/src/generate/module/generateRepositoryMethod.js +117 -0
  87. package/src/generate/module/generateSchemaFromType.js +283 -280
  88. package/src/generate/module/generateStore.js +41 -0
  89. package/src/generate/module/generateTypesJson.js +196 -195
  90. package/src/generate/module/generateUseCases.js +47 -55
  91. package/src/generate/module/repositoryModuleShared.js +480 -459
  92. package/src/generate/routes/generateRoutes.js +4 -7
  93. package/src/generate/ui/generateComponent.js +44 -64
  94. package/src/generate/ui/generateDesignComponent.js +21 -41
  95. package/src/generate/ui/generateWidget.js +21 -41
  96. package/src/git/commit.js +67 -0
  97. package/src/git/push.js +19 -0
  98. package/src/git/runGit.js +11 -0
  99. package/src/init/initAliases.js +19 -135
  100. package/src/init/initEdges.js +79 -54
  101. package/src/init/initStructure.js +31 -145
  102. package/src/install/configureCommitTools.js +1 -0
  103. package/src/install/installFresh.js +39 -68
  104. package/src/migrate/migrate.js +1027 -0
  105. package/src/migrate/presenterFactories.js +189 -0
  106. package/src/migrate/presenters.js +373 -0
  107. package/src/migrate/translations.js +213 -0
  108. package/src/plugins/addLint.js +52 -219
  109. package/src/scaffolds/createCoreSchema.js +65 -91
  110. package/src/scaffolds/createDatasource.js +67 -101
  111. package/src/scaffolds/createProgram.js +8 -8
  112. package/src/scaffolds/createResponse.js +29 -29
  113. package/src/scaffolds/createSchemaRule.js +19 -19
  114. package/src/scaffolds/createTranslationManager.js +84 -37
  115. package/src/scaffolds/index.js +0 -2
  116. package/src/scaffolds/registerDatasource.js +59 -0
  117. package/src/scaffolds/updateDefaultFactoryConfig.js +31 -0
  118. package/src/utils/architecture.js +145 -0
  119. package/src/utils/contextUtils.js +32 -65
  120. package/src/utils/fileUtils.js +69 -50
  121. package/src/utils/flattenConfig.js +38 -0
  122. package/src/utils/legacyAliases.js +75 -0
  123. package/src/utils/loadConfig.js +76 -40
  124. package/src/utils/packageImports.js +63 -0
  125. package/src/utils/sharedFoundation.js +36 -42
  126. package/src/utils/viteConfig.js +295 -0
  127. package/.prettierrc +0 -7
  128. package/bin/azure-net.ts +0 -308
  129. package/eslint.config.js +0 -34
  130. package/src/checks/checkDomain.ts +0 -223
  131. package/src/checks/checkFoldersStructure.ts +0 -85
  132. package/src/checks/checkHooks.ts +0 -22
  133. package/src/checks/checkImports.ts +0 -193
  134. package/src/checks/checkInternal.ts +0 -48
  135. package/src/checks/checkLayerBoundaries.ts +0 -255
  136. package/src/checks/checkLayerImports.ts +0 -185
  137. package/src/checks/checkPresenterNames.ts +0 -203
  138. package/src/checks/checkProject.ts +0 -45
  139. package/src/checks/checkProviderGraph.ts +0 -234
  140. package/src/checks/checkProviderNames.ts +0 -165
  141. package/src/generate/layers/generateRepository.ts +0 -123
  142. package/src/generate/layers/generateRepositoryMethod.ts +0 -102
  143. package/src/generate/layers/generateUseCases.ts +0 -50
  144. package/src/generate/layers/repositoryShared.js +0 -506
  145. package/src/generate/layers/repositoryShared.ts +0 -662
  146. package/src/generate/module/generateDomain.ts +0 -147
  147. package/src/generate/module/generateModule.ts +0 -84
  148. package/src/generate/module/generateModulePreset.ts +0 -338
  149. package/src/generate/module/generatePresenter.ts +0 -498
  150. package/src/generate/module/generateRepository.ts +0 -158
  151. package/src/generate/module/generateSchemaFromType.ts +0 -368
  152. package/src/generate/module/generateTypesJson.ts +0 -259
  153. package/src/generate/module/generateUseCases.ts +0 -67
  154. package/src/generate/module/repositoryModuleShared.ts +0 -669
  155. package/src/generate/routes/generateRoutes.ts +0 -275
  156. package/src/generate/ui/generateComponent.ts +0 -100
  157. package/src/generate/ui/generateDesignComponent.ts +0 -71
  158. package/src/generate/ui/generateWidget.ts +0 -71
  159. package/src/init/initAliases.ts +0 -172
  160. package/src/init/initEdges.ts +0 -74
  161. package/src/init/initStructure.ts +0 -172
  162. package/src/install/installFresh.ts +0 -93
  163. package/src/plugins/addLint.ts +0 -274
  164. package/src/scaffolds/createCoreSchema.ts +0 -130
  165. package/src/scaffolds/createDatasource.ts +0 -161
  166. package/src/scaffolds/createDatasourceProvider.js +0 -127
  167. package/src/scaffolds/createDatasourceProvider.ts +0 -161
  168. package/src/scaffolds/createPresenterFactory.js +0 -83
  169. package/src/scaffolds/createPresenterFactory.ts +0 -102
  170. package/src/scaffolds/createProgram.ts +0 -19
  171. package/src/scaffolds/createResponse.ts +0 -66
  172. package/src/scaffolds/createSchemaRule.ts +0 -44
  173. package/src/scaffolds/createTranslationManager.ts +0 -80
  174. package/src/utils/contextUtils.ts +0 -88
  175. package/src/utils/fileUtils.ts +0 -74
  176. package/src/utils/loadConfig.ts +0 -68
  177. package/src/utils/sharedFoundation.ts +0 -70
  178. package/tsconfig.json +0 -19
  179. /package/{src/checks/index.ts → dist/src/checks/index.d.ts} +0 -0
  180. /package/{src/plugins/index.ts → dist/src/plugins/index.d.ts} +0 -0
@@ -1,669 +0,0 @@
1
- import fs from 'node:fs/promises';
2
- import path from 'node:path';
3
- import prompts from 'prompts';
4
- import { loadUserConfig } from '../../utils/loadConfig.js';
5
- import { normalizeContexts } from '../../init/initAliases.js';
6
- import { toCamelCase, toPascalCase } from '../../utils/contextUtils.js';
7
- import { updateIndexTs } from '../../utils/fileUtils.js';
8
- import { getFoundationConstructImportPath, getFoundationConstructPath, getSharedState } from '../../utils/sharedFoundation.js';
9
-
10
- type ContextConfig = { name: string; alias: string };
11
- type TypeLayer = 'ports' | 'model';
12
- type ResponseKind = 'domain' | 'primitive';
13
- type RepositoryMeta = {
14
- className: string;
15
- baseName: string;
16
- repositoryInterfaceName: string;
17
- useCasesClassName: string;
18
- repositoryDependencyName: string;
19
- };
20
- type DomainType = { name: string; layer: TypeLayer };
21
- type MethodTypeRef = { name: string; layer: TypeLayer };
22
- type MethodResponseRef = { kind: ResponseKind; type: string; layer: TypeLayer | null };
23
- type RepositoryMethod = {
24
- name: string;
25
- httpMethod: string;
26
- route: string;
27
- response: MethodResponseRef;
28
- queryType: MethodTypeRef | null;
29
- bodyType: MethodTypeRef | null;
30
- pathParamType: string | null;
31
- };
32
- type DatasourceInfo = { name: string; importPath: string };
33
-
34
- const HTTP_METHODS = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch'];
35
- const MUTATION_METHODS = new Set(['put', 'patch', 'delete']);
36
- const RESERVED_IDENTIFIERS = new Set([
37
- 'break',
38
- 'case',
39
- 'catch',
40
- 'class',
41
- 'const',
42
- 'continue',
43
- 'debugger',
44
- 'default',
45
- 'delete',
46
- 'do',
47
- 'else',
48
- 'enum',
49
- 'export',
50
- 'extends',
51
- 'false',
52
- 'finally',
53
- 'for',
54
- 'function',
55
- 'if',
56
- 'import',
57
- 'in',
58
- 'instanceof',
59
- 'new',
60
- 'null',
61
- 'return',
62
- 'super',
63
- 'switch',
64
- 'this',
65
- 'throw',
66
- 'true',
67
- 'try',
68
- 'typeof',
69
- 'var',
70
- 'void',
71
- 'while',
72
- 'with',
73
- 'as',
74
- 'implements',
75
- 'interface',
76
- 'let',
77
- 'package',
78
- 'private',
79
- 'protected',
80
- 'public',
81
- 'static',
82
- 'yield'
83
- ]);
84
-
85
- const normalizeAlias = (value: unknown, fallback: string): string => {
86
- const raw = String(value ?? '').trim();
87
- if (!raw.length) return fallback;
88
- return raw.startsWith('$') ? raw : `$${raw}`;
89
- };
90
-
91
- const toTypeFileName = (typeName: string): string => String(typeName ?? '').replace(/^I/, '') || 'Type';
92
-
93
- export const ensureRepositoryName = (rawName: unknown): string => {
94
- const normalized = toPascalCase(String(rawName ?? '').trim() || 'Repository');
95
- return normalized.endsWith('Repository') ? normalized : `${normalized}Repository`;
96
- };
97
-
98
- export const getRepositoryMeta = (repositoryName: unknown): RepositoryMeta => {
99
- const className = ensureRepositoryName(repositoryName);
100
- const baseName = className.replace(/Repository$/, '') || 'Repository';
101
- const repositoryInterfaceName = `I${baseName}Repository`;
102
- const useCasesClassName = `${baseName}UseCases`;
103
- const repositoryDependencyNameRaw = toCamelCase(baseName || 'repository');
104
- const repositoryDependencyName = RESERVED_IDENTIFIERS.has(repositoryDependencyNameRaw)
105
- ? `${repositoryDependencyNameRaw}Repository`
106
- : repositoryDependencyNameRaw;
107
-
108
- return {
109
- className,
110
- baseName,
111
- repositoryInterfaceName,
112
- useCasesClassName,
113
- repositoryDependencyName
114
- };
115
- };
116
-
117
- export const getConfigState = async (): Promise<{ contexts: ContextConfig[]; sharedAlias: string; sharedContextName: string }> => {
118
- const config = await loadUserConfig();
119
- const contexts = normalizeContexts(config.contexts);
120
- const { sharedAlias, sharedContext } = await getSharedState();
121
- return { contexts, sharedAlias, sharedContextName: sharedContext.name };
122
- };
123
-
124
- export const selectContext = async (message = 'Select context:'): Promise<string | null> => {
125
- const { contexts } = await getConfigState();
126
- if (!contexts.length) {
127
- console.error('❌ Cannot continue: `contexts` is missing or empty in azure-net.config.ts/js');
128
- return null;
129
- }
130
-
131
- const { context } = await prompts({
132
- type: 'select',
133
- name: 'context',
134
- message,
135
- choices: contexts.map((item) => ({ title: item.name, value: item.name })),
136
- initial: 0
137
- });
138
-
139
- return context ? String(context) : null;
140
- };
141
-
142
- export const resolveContextAlias = (contexts: ContextConfig[], contextName: string): string => {
143
- const found = contexts.find((item) => item.name === contextName);
144
- if (!found) return `$${contextName}`;
145
- return normalizeAlias(found.alias, `$${contextName}`);
146
- };
147
-
148
- export const resolveRepositoriesPath = (contextName: string): string =>
149
- path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'infrastructure', 'http', 'repositories');
150
-
151
- export const resolveDatasourcesPath = (contextName: string): string =>
152
- path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'infrastructure', 'http', 'datasources');
153
-
154
- export const resolveSharedDatasourcesPath = async (): Promise<string> => {
155
- const { sharedContext } = await getSharedState();
156
- return getFoundationConstructPath(sharedContext.name, 'datasource');
157
- };
158
-
159
- export const resolveDomainRootPath = (contextName: string, domainName: string): string =>
160
- path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'domain', domainName);
161
-
162
- export const resolveUseCasesPath = (contextName: string): string =>
163
- path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'application', 'use-cases');
164
-
165
- export const getAvailableTsNames = async (targetPath: string): Promise<string[]> => {
166
- try {
167
- const files = await fs.readdir(targetPath);
168
- return files.filter((item) => item.endsWith('.ts') && item !== 'index.ts').map((item) => item.replace(/\.ts$/, ''));
169
- } catch {
170
- return [];
171
- }
172
- };
173
-
174
- export const selectDatasource = async (contextName: string): Promise<DatasourceInfo | null> => {
175
- const { contexts, sharedAlias } = await getConfigState();
176
- const contextAlias = resolveContextAlias(contexts, contextName);
177
- const sharedDatasources = await getAvailableTsNames(await resolveSharedDatasourcesPath());
178
- const contextDatasources = await getAvailableTsNames(resolveDatasourcesPath(contextName));
179
-
180
- const choices: Array<{ title: string; value: DatasourceInfo }> = [];
181
- for (const datasource of sharedDatasources) {
182
- choices.push({
183
- title: `${datasource} (shared foundation)`,
184
- value: { name: datasource, importPath: getFoundationConstructImportPath(sharedAlias, 'datasource') }
185
- });
186
- }
187
-
188
- for (const datasource of contextDatasources) {
189
- choices.push({
190
- title: `${datasource} (${contextName})`,
191
- value: { name: datasource, importPath: `${contextAlias}/layers/infrastructure/http/datasources` }
192
- });
193
- }
194
-
195
- if (!choices.length) {
196
- console.error(`❌ No datasources found in shared foundation or context "${contextName}".`);
197
- return null;
198
- }
199
-
200
- const { datasource } = await prompts({
201
- type: 'select',
202
- name: 'datasource',
203
- message: 'Select datasource:',
204
- choices,
205
- initial: 0
206
- });
207
-
208
- return datasource ?? null;
209
- };
210
-
211
- export const selectDomain = async (contextName: string): Promise<string | null> => {
212
- const domainPath = path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'domain');
213
- try {
214
- const items = await fs.readdir(domainPath, { withFileTypes: true });
215
- const domains = items.filter((item) => item.isDirectory()).map((item) => item.name);
216
- if (!domains.length) {
217
- console.error(`❌ No domain folders found in ${domainPath}`);
218
- return null;
219
- }
220
-
221
- const { domain } = await prompts({
222
- type: 'select',
223
- name: 'domain',
224
- message: 'Select domain:',
225
- choices: domains.map((item) => ({ title: item, value: item })),
226
- initial: 0
227
- });
228
-
229
- return domain ? String(domain) : null;
230
- } catch {
231
- console.error(`❌ Domain path not found: ${domainPath}`);
232
- return null;
233
- }
234
- };
235
-
236
- const extractInterfaceName = (content: string, fallback: string): string => {
237
- const match = content.match(/export\s+interface\s+([A-Za-z0-9_]+)/);
238
- return match?.[1] ?? fallback;
239
- };
240
-
241
- export const getDomainTypes = async (contextName: string, domainName: string): Promise<DomainType[]> => {
242
- const root = resolveDomainRootPath(contextName, domainName);
243
- const result: DomainType[] = [];
244
- const readLayer = async (layer: TypeLayer): Promise<void> => {
245
- const layerPath = path.join(root, layer);
246
- try {
247
- const files = await fs.readdir(layerPath);
248
- for (const fileName of files) {
249
- if (!fileName.endsWith('.ts') || fileName === 'index.ts') continue;
250
- const absolute = path.join(layerPath, fileName);
251
- const content = await fs.readFile(absolute, 'utf-8');
252
- const fallback = fileName.replace(/\.ts$/, '');
253
- const interfaceName = extractInterfaceName(content, fallback);
254
- result.push({ name: interfaceName, layer });
255
- }
256
- } catch {
257
- // ignore
258
- }
259
- };
260
-
261
- await readLayer('ports');
262
- await readLayer('model');
263
- return result;
264
- };
265
-
266
- const isPrimitiveType = (value: unknown): boolean =>
267
- ['string', 'number', 'boolean', 'unknown', 'void', 'null', 'undefined', 'bigint', 'symbol', 'never'].includes(String(value ?? '').trim());
268
-
269
- const buildResponseSelection = async (domainTypes: DomainType[]): Promise<MethodResponseRef | null> => {
270
- const { isPrimitive } = await prompts({
271
- type: 'confirm',
272
- name: 'isPrimitive',
273
- message: 'Is response type primitive?',
274
- initial: false
275
- });
276
-
277
- if (isPrimitive) {
278
- const { primitiveType } = await prompts({
279
- type: 'text',
280
- name: 'primitiveType',
281
- message: 'Primitive response type:',
282
- validate: (value) => (String(value ?? '').trim().length > 0 ? true : 'Type is required')
283
- });
284
-
285
- return { kind: 'primitive', type: String(primitiveType).trim(), layer: null };
286
- }
287
-
288
- if (!domainTypes.length) {
289
- console.error('❌ Domain has no model/ports types to choose from.');
290
- return null;
291
- }
292
-
293
- const { selectedType } = await prompts({
294
- type: 'select',
295
- name: 'selectedType',
296
- message: 'Select response type:',
297
- choices: domainTypes.map((item) => ({
298
- title: `${item.name} (${item.layer})`,
299
- value: item
300
- })),
301
- initial: 0
302
- });
303
-
304
- if (!selectedType) return null;
305
- return { kind: 'domain', type: selectedType.name, layer: selectedType.layer };
306
- };
307
-
308
- const buildDomainRequestTypeSelection = async (question: string, domainTypes: DomainType[]): Promise<MethodTypeRef | null> => {
309
- if (!domainTypes.length) {
310
- console.error('❌ Domain has no model/ports types to choose from.');
311
- return null;
312
- }
313
-
314
- const { enabled } = await prompts({
315
- type: 'confirm',
316
- name: 'enabled',
317
- message: question,
318
- initial: false
319
- });
320
-
321
- if (!enabled) return null;
322
-
323
- const { selectedType } = await prompts({
324
- type: 'select',
325
- name: 'selectedType',
326
- message: 'Select type:',
327
- choices: domainTypes.map((item) => ({
328
- title: `${item.name} (${item.layer})`,
329
- value: item
330
- })),
331
- initial: 0
332
- });
333
-
334
- return selectedType ?? null;
335
- };
336
-
337
- const buildPathParamTypeSelection = async (): Promise<string | null> => {
338
- const { enabled } = await prompts({
339
- type: 'confirm',
340
- name: 'enabled',
341
- message: 'Has path param?',
342
- initial: false
343
- });
344
-
345
- if (!enabled) return null;
346
-
347
- const { type } = await prompts({
348
- type: 'select',
349
- name: 'type',
350
- message: 'Path param type:',
351
- choices: [
352
- { title: 'string', value: 'string' },
353
- { title: 'number', value: 'number' }
354
- ],
355
- initial: 0
356
- });
357
-
358
- return type ?? 'string';
359
- };
360
-
361
- export const promptMethodDefinition = async (domainTypes: DomainType[]): Promise<RepositoryMethod | null> => {
362
- const { methodNameRaw } = await prompts({
363
- type: 'text',
364
- name: 'methodNameRaw',
365
- message: 'Method name:',
366
- validate: (value) => (String(value ?? '').trim().length > 0 ? true : 'Method name is required')
367
- });
368
-
369
- const { httpMethod } = await prompts({
370
- type: 'select',
371
- name: 'httpMethod',
372
- message: 'HTTP method:',
373
- choices: HTTP_METHODS.map((item) => ({ title: item, value: item })),
374
- initial: 0
375
- });
376
-
377
- const { routeRaw } = await prompts({
378
- type: 'text',
379
- name: 'routeRaw',
380
- message: 'Request path (e.g. /public-route):',
381
- initial: '/public-route',
382
- validate: (value) => {
383
- const raw = String(value ?? '').trim();
384
- if (!raw.length) return 'Path is required';
385
- return raw.startsWith('/') ? true : 'Path must start with "/"';
386
- }
387
- });
388
-
389
- const response = await buildResponseSelection(domainTypes);
390
- if (!response) return null;
391
-
392
- const normalizedMethod = String(httpMethod ?? 'get').toLowerCase();
393
- let queryType = null;
394
- let bodyType = null;
395
- let pathParamType = null;
396
-
397
- if (normalizedMethod === 'get') {
398
- queryType = await buildDomainRequestTypeSelection('Has query params?', domainTypes);
399
- } else if (normalizedMethod === 'post') {
400
- bodyType = await buildDomainRequestTypeSelection('Has request body?', domainTypes);
401
- } else if (MUTATION_METHODS.has(normalizedMethod)) {
402
- pathParamType = await buildPathParamTypeSelection();
403
- bodyType = await buildDomainRequestTypeSelection('Has request body?', domainTypes);
404
- }
405
-
406
- return {
407
- name: toCamelCase(String(methodNameRaw ?? '').trim() || 'method'),
408
- httpMethod: normalizedMethod,
409
- route: String(routeRaw ?? '/public-route').trim() || '/public-route',
410
- response,
411
- queryType,
412
- bodyType,
413
- pathParamType
414
- };
415
- };
416
-
417
- const getResponseTypeName = (method: RepositoryMethod): string => method.response.type;
418
-
419
- const getMethodParams = (method: RepositoryMethod): string => {
420
- const params: string[] = [];
421
- if (method.pathParamType) params.push(`pathParam: ${method.pathParamType}`);
422
- if (method.queryType) params.push(`request: ${method.queryType.name}`);
423
- if (method.bodyType) params.push(`request: ${method.bodyType.name}`);
424
- return params.join(', ');
425
- };
426
-
427
- const getRequestMapping = (method: RepositoryMethod): { callbackParams: string; call: string } => {
428
- const routeWithPath = method.pathParamType ? `${method.route}/\${pathParam}` : method.route;
429
-
430
- if (method.httpMethod === 'get') {
431
- if (method.queryType) {
432
- return {
433
- callbackParams: '{ http, query }',
434
- call: `http.get(\`${routeWithPath}\`, { searchParams: query.toSearchParams(request) })`
435
- };
436
- }
437
-
438
- return {
439
- callbackParams: '{ http }',
440
- call: `http.get(\`${routeWithPath}\`)`
441
- };
442
- }
443
-
444
- if (method.httpMethod === 'post') {
445
- if (method.bodyType) {
446
- return {
447
- callbackParams: '{ http }',
448
- call: `http.post(\`${routeWithPath}\`, { json: request })`
449
- };
450
- }
451
-
452
- return {
453
- callbackParams: '{ http }',
454
- call: `http.post(\`${routeWithPath}\`)`
455
- };
456
- }
457
-
458
- if (method.httpMethod === 'put' || method.httpMethod === 'patch' || method.httpMethod === 'delete') {
459
- const callMethod = method.httpMethod;
460
- if (method.bodyType) {
461
- return {
462
- callbackParams: '{ http }',
463
- call: `http.${callMethod}(\`${routeWithPath}\`, { json: request })`
464
- };
465
- }
466
-
467
- return {
468
- callbackParams: '{ http }',
469
- call: `http.${callMethod}(\`${routeWithPath}\`)`
470
- };
471
- }
472
-
473
- return {
474
- callbackParams: '{ http }',
475
- call: `http.${method.httpMethod}(\`${routeWithPath}\`)`
476
- };
477
- };
478
-
479
- export const buildRepositoryMethodCode = (method: RepositoryMethod): string => {
480
- const params = getMethodParams(method);
481
- const responseType = getResponseTypeName(method);
482
- const mapping = getRequestMapping(method);
483
-
484
- return `\tpublic async ${method.name}(${params}) {\n\t\treturn this.datasource\n\t\t\t.createRequest<${responseType}>((${mapping.callbackParams}) => ${mapping.call})\n\t\t\t.then((res) => res.getData());\n\t}`;
485
- };
486
-
487
- export const buildRepositoryContent = ({
488
- meta,
489
- contextAlias,
490
- domainName,
491
- datasource,
492
- methods
493
- }: {
494
- meta: RepositoryMeta;
495
- contextAlias: string;
496
- domainName: string;
497
- datasource: DatasourceInfo;
498
- methods: RepositoryMethod[];
499
- }): string => {
500
- const typeImports = new Set([meta.repositoryInterfaceName]);
501
- for (const method of methods) {
502
- if (!isPrimitiveType(method.response.type)) typeImports.add(method.response.type);
503
- if (method.queryType) typeImports.add(method.queryType.name);
504
- if (method.bodyType) typeImports.add(method.bodyType.name);
505
- }
506
-
507
- const methodsCode = methods.map((method) => buildRepositoryMethodCode(method)).join('\n\n');
508
- const typeImportLine = typeImports.size
509
- ? `import type { ${Array.from(typeImports).join(', ')} } from '${contextAlias}/layers/domain/${domainName}';\n`
510
- : '';
511
-
512
- return `import { ${datasource.name} } from '${datasource.importPath}';
513
- ${typeImportLine}
514
- export class ${meta.className} implements ${meta.repositoryInterfaceName} {
515
- \tconstructor(private readonly datasource: ${datasource.name}) {}
516
-
517
- ${methodsCode ? `${methodsCode}\n` : ''}
518
- }
519
- `;
520
- };
521
-
522
- export const writeRepositoryInterface = async ({
523
- contextName,
524
- domainName,
525
- meta,
526
- methods
527
- }: {
528
- contextName: string;
529
- domainName: string;
530
- meta: RepositoryMeta;
531
- methods: RepositoryMethod[];
532
- }): Promise<void> => {
533
- const domainPath = resolveDomainRootPath(contextName, domainName);
534
- const portsPath = path.join(domainPath, 'ports');
535
- await fs.mkdir(portsPath, { recursive: true });
536
-
537
- const portsImports = new Set<string>();
538
- const modelImports = new Set<string>();
539
-
540
- for (const method of methods) {
541
- const allTypes: MethodTypeRef[] = [];
542
- if (!isPrimitiveType(method.response.type) && method.response.layer) {
543
- allTypes.push({ name: method.response.type, layer: method.response.layer });
544
- }
545
- if (method.queryType) allTypes.push(method.queryType);
546
- if (method.bodyType) allTypes.push(method.bodyType);
547
-
548
- for (const typeEntry of allTypes) {
549
- if (typeEntry.layer === 'ports') portsImports.add(typeEntry.name);
550
- if (typeEntry.layer === 'model') modelImports.add(typeEntry.name);
551
- }
552
- }
553
-
554
- const imports: string[] = [];
555
- for (const name of Array.from(portsImports)) {
556
- imports.push(`import type { ${name} } from './${toTypeFileName(name)}';`);
557
- }
558
- for (const name of Array.from(modelImports)) {
559
- imports.push(`import type { ${name} } from '../model/${toTypeFileName(name)}';`);
560
- }
561
-
562
- const signatures = methods
563
- .map((method) => {
564
- const responseType = getResponseTypeName(method);
565
- const params = getMethodParams(method);
566
- return `\t${method.name}(${params}): Promise<${responseType}>;`;
567
- })
568
- .join('\n');
569
-
570
- const content = `${imports.join('\n')}${imports.length ? '\n\n' : ''}export interface ${meta.repositoryInterfaceName} {\n${signatures ? `${signatures}\n` : ''}}\n`;
571
- await fs.writeFile(path.join(portsPath, `${toTypeFileName(meta.repositoryInterfaceName)}.ts`), content, 'utf-8');
572
- await updateIndexTs(portsPath);
573
- };
574
-
575
- const parseRepositoryFileForDomain = (content: string, contextAlias: string): string | null => {
576
- const escapedAlias = contextAlias.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
577
- const regex = new RegExp(`from\\s+['"]${escapedAlias}/layers/domain/([^'"]+)['"]`);
578
- const match = content.match(regex);
579
- return match?.[1] ?? null;
580
- };
581
-
582
- const parseRepositoryMethodsFromInterface = (content: string): string[] => {
583
- const methods: string[] = [];
584
- const regex = /(\w+)\(([^)]*)\)\s*:\s*Promise<([^>]+)>;/g;
585
- let match;
586
- while ((match = regex.exec(content)) !== null) {
587
- const methodName = match[1];
588
- if (methodName) methods.push(methodName);
589
- }
590
- return methods;
591
- };
592
-
593
- export const createUseCasesForRepository = async ({
594
- contextName,
595
- contextAlias,
596
- domainName,
597
- repositoryName
598
- }: {
599
- contextName: string;
600
- contextAlias: string;
601
- domainName: string;
602
- repositoryName: string;
603
- }): Promise<boolean> => {
604
- const meta = getRepositoryMeta(repositoryName);
605
- const interfacePath = path.join(
606
- resolveDomainRootPath(contextName, domainName),
607
- 'ports',
608
- `${toTypeFileName(meta.repositoryInterfaceName)}.ts`
609
- );
610
-
611
- let interfaceContent = '';
612
- try {
613
- interfaceContent = await fs.readFile(interfacePath, 'utf-8');
614
- } catch {
615
- console.error(`❌ Repository interface not found: ${interfacePath}`);
616
- return false;
617
- }
618
-
619
- const methods = parseRepositoryMethodsFromInterface(interfaceContent);
620
- const useCasesPath = resolveUseCasesPath(contextName);
621
- await fs.mkdir(useCasesPath, { recursive: true });
622
-
623
- const declares = methods.map((methodName) => `\tdeclare ${methodName}: ${meta.repositoryInterfaceName}['${methodName}'];`).join('\n');
624
-
625
- const content = `import { ClassMirror } from '@azure-net/kit';
626
- import type { ${meta.repositoryInterfaceName} } from '${contextAlias}/layers/domain/${domainName}';
627
-
628
- export class ${meta.useCasesClassName} extends ClassMirror {
629
- \tconstructor(private ${meta.repositoryDependencyName}: ${meta.repositoryInterfaceName}) {
630
- \t\tsuper(${meta.repositoryDependencyName});
631
- \t}
632
-
633
- ${declares ? `${declares}\n` : ''}
634
- }
635
- `;
636
-
637
- await fs.writeFile(path.join(useCasesPath, `${meta.useCasesClassName}.ts`), content, 'utf-8');
638
- await updateIndexTs(useCasesPath);
639
- return true;
640
- };
641
-
642
- export const resolveDomainForRepository = async ({
643
- contextName,
644
- contextAlias,
645
- repositoryName
646
- }: {
647
- contextName: string;
648
- contextAlias: string;
649
- repositoryName: string;
650
- }): Promise<string | null> => {
651
- const repositoryPath = path.join(resolveRepositoriesPath(contextName), `${ensureRepositoryName(repositoryName)}.ts`);
652
- try {
653
- const content = await fs.readFile(repositoryPath, 'utf-8');
654
- return parseRepositoryFileForDomain(content, contextAlias);
655
- } catch {
656
- return null;
657
- }
658
- };
659
-
660
- export const promptMethodsBatch = async (domainTypes: DomainType[], count: number): Promise<RepositoryMethod[] | null> => {
661
- const methods: RepositoryMethod[] = [];
662
- for (let index = 0; index < count; index += 1) {
663
- console.log(`\n🧩 Method ${index + 1} of ${count}`);
664
- const method = await promptMethodDefinition(domainTypes);
665
- if (!method) return null;
666
- methods.push(method);
667
- }
668
- return methods;
669
- };