@azure-net/cli 5.1.0 → 6.0.0-next.2

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