@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,368 +0,0 @@
1
- import fs from 'node:fs/promises';
2
- import path from 'node:path';
3
- import prompts from 'prompts';
4
- import { getConfigState, resolveContextAlias, selectContext } from './repositoryModuleShared.js';
5
-
6
- const listDirectories = async (targetPath: string): Promise<string[]> => {
7
- try {
8
- const items = await fs.readdir(targetPath, { withFileTypes: true });
9
- return items.filter((item) => item.isDirectory()).map((item) => item.name);
10
- } catch {
11
- return [];
12
- }
13
- };
14
-
15
- const listSchemaFiles = async (targetPath: string): Promise<string[]> => {
16
- try {
17
- const files = await fs.readdir(targetPath);
18
- return files.filter((item) => item.endsWith('.ts') && item !== 'index.ts');
19
- } catch {
20
- return [];
21
- }
22
- };
23
-
24
- const resolveAliasMap = async (): Promise<Map<string, string>> => {
25
- const { contexts } = await getConfigState();
26
- const map = new Map<string, string>();
27
-
28
- for (const context of contexts) {
29
- const alias = resolveContextAlias(contexts, context.name);
30
- map.set(alias, path.join(process.cwd(), 'src', 'app', context.name));
31
- }
32
-
33
- return map;
34
- };
35
-
36
- const resolveImportToFile = async (fromFile: string, importPath: string, aliasMap: Map<string, string>): Promise<string | null> => {
37
- const rawImport = String(importPath ?? '').trim();
38
- if (!rawImport.length) return null;
39
-
40
- let absolute = '';
41
- if (rawImport.startsWith('.')) {
42
- absolute = path.resolve(path.dirname(fromFile), rawImport);
43
- } else {
44
- const alias = Array.from(aliasMap.keys()).find((key) => rawImport === key || rawImport.startsWith(`${key}/`));
45
- if (!alias) return null;
46
- const suffix = rawImport === alias ? '' : rawImport.slice(alias.length + 1);
47
- absolute = path.join(aliasMap.get(alias) as string, suffix);
48
- }
49
-
50
- const tsCandidate = absolute.endsWith('.ts') ? absolute : `${absolute}.ts`;
51
- try {
52
- await fs.access(tsCandidate);
53
- return tsCandidate;
54
- } catch {
55
- const indexCandidate = path.join(absolute, 'index.ts');
56
- try {
57
- await fs.access(indexCandidate);
58
- return indexCandidate;
59
- } catch {
60
- return null;
61
- }
62
- }
63
- };
64
-
65
- const extractSchemaTypeName = (content: string): string | null => {
66
- const typeMatch = content.match(/=\s*[A-Za-z0-9_]+<\s*([^>]+?)\s*>\s*\(\)/m);
67
- if (!typeMatch) return null;
68
- return String(typeMatch[1]).trim();
69
- };
70
-
71
- const findTypeImportPath = (content: string, typeName: string): string | null => {
72
- const importRegex = /import\s+type\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/g;
73
- let match: RegExpExecArray | null;
74
- while ((match = importRegex.exec(content)) !== null) {
75
- const importedList = match[1];
76
- const sourcePath = match[2];
77
- if (!importedList || !sourcePath) continue;
78
- const imported = importedList
79
- .split(',')
80
- .map((item) => item.trim())
81
- .filter(Boolean);
82
- if (imported.includes(typeName)) {
83
- return sourcePath;
84
- }
85
- }
86
- return null;
87
- };
88
-
89
- const extractInterfaceBody = (content: string, interfaceName: string): string | null => {
90
- const declarationRegex = new RegExp(`export\\s+interface\\s+${interfaceName}\\s*\\{`);
91
- const declarationMatch = content.match(declarationRegex);
92
- if (!declarationMatch || declarationMatch.index === undefined) return null;
93
-
94
- const openBraceIndex = content.indexOf('{', declarationMatch.index);
95
- if (openBraceIndex === -1) return null;
96
-
97
- let depth = 0;
98
- let closeBraceIndex = -1;
99
- for (let index = openBraceIndex; index < content.length; index += 1) {
100
- const char = content[index];
101
- if (char === '{') depth += 1;
102
- if (char === '}') {
103
- depth -= 1;
104
- if (depth === 0) {
105
- closeBraceIndex = index;
106
- break;
107
- }
108
- }
109
- }
110
-
111
- if (closeBraceIndex === -1) return null;
112
- return content.slice(openBraceIndex + 1, closeBraceIndex);
113
- };
114
-
115
- const resolveRelativeExportPath = async (fromFile: string, exportPath: string): Promise<string | null> => {
116
- const absolute = path.resolve(path.dirname(fromFile), exportPath);
117
- const tsCandidate = absolute.endsWith('.ts') ? absolute : `${absolute}.ts`;
118
- try {
119
- await fs.access(tsCandidate);
120
- return tsCandidate;
121
- } catch {
122
- const indexCandidate = path.join(absolute, 'index.ts');
123
- try {
124
- await fs.access(indexCandidate);
125
- return indexCandidate;
126
- } catch {
127
- return null;
128
- }
129
- }
130
- };
131
-
132
- const findInterfaceBodyByExportGraph = async (
133
- entryFilePath: string,
134
- interfaceName: string,
135
- visited: Set<string> = new Set()
136
- ): Promise<string | null> => {
137
- const resolvedPath = path.resolve(entryFilePath);
138
- if (visited.has(resolvedPath)) return null;
139
- visited.add(resolvedPath);
140
-
141
- let content = '';
142
- try {
143
- content = await fs.readFile(resolvedPath, 'utf-8');
144
- } catch {
145
- return null;
146
- }
147
-
148
- const direct = extractInterfaceBody(content, interfaceName);
149
- if (direct) return direct;
150
-
151
- const exportRegex = /export\s+(?:\*|\{[^}]+\})\s+from\s+['"]([^'"]+)['"]/g;
152
- let match: RegExpExecArray | null;
153
- while ((match = exportRegex.exec(content)) !== null) {
154
- const exportPath = match[1];
155
- if (!exportPath || !exportPath.startsWith('.')) continue;
156
- const nextPath = await resolveRelativeExportPath(resolvedPath, exportPath);
157
- if (!nextPath) continue;
158
- const nested = await findInterfaceBodyByExportGraph(nextPath, interfaceName, visited);
159
- if (nested) return nested;
160
- }
161
-
162
- return null;
163
- };
164
-
165
- const findInterfaceBodyByScan = async (rootDir: string, interfaceName: string): Promise<string | null> => {
166
- const queue: string[] = [rootDir];
167
- while (queue.length) {
168
- const current = queue.shift();
169
- if (!current) continue;
170
- let entries: import('node:fs').Dirent[] = [];
171
- try {
172
- entries = await fs.readdir(current, { withFileTypes: true });
173
- } catch {
174
- continue;
175
- }
176
-
177
- for (const entry of entries) {
178
- const absolute = path.join(current, entry.name);
179
- if (entry.isDirectory()) {
180
- queue.push(absolute);
181
- continue;
182
- }
183
- if (!entry.isFile() || !entry.name.endsWith('.ts')) continue;
184
- const content = await fs.readFile(absolute, 'utf-8');
185
- const body = extractInterfaceBody(content, interfaceName);
186
- if (body) return body;
187
- }
188
- }
189
- return null;
190
- };
191
-
192
- type InterfaceField = {
193
- name: string;
194
- optional: boolean;
195
- type: string;
196
- };
197
-
198
- const extractRuleKeys = (body: string): string[] => {
199
- const keys: string[] = [];
200
- const keyRegex = /^\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*:/gm;
201
- let match: RegExpExecArray | null;
202
- while ((match = keyRegex.exec(body)) !== null) {
203
- const key = match[1];
204
- if (key) keys.push(key);
205
- }
206
- return Array.from(new Set(keys));
207
- };
208
-
209
- const extractInterfaceFields = (body: string): InterfaceField[] => {
210
- const fields: InterfaceField[] = [];
211
- const fieldRegex = /^\s*(?:readonly\s+)?([A-Za-z_$][A-Za-z0-9_$]*)(\?)?\s*:\s*([^;]+);/gm;
212
- let match: RegExpExecArray | null;
213
- while ((match = fieldRegex.exec(body)) !== null) {
214
- const name = match[1];
215
- const optionalMark = match[2];
216
- const type = String(match[3] ?? '').trim();
217
- if (!name || !type) continue;
218
- fields.push({
219
- name,
220
- optional: optionalMark === '?',
221
- type
222
- });
223
- }
224
-
225
- const unique = new Map<string, InterfaceField>();
226
- for (const field of fields) {
227
- if (!unique.has(field.name)) unique.set(field.name, field);
228
- }
229
- return Array.from(unique.values());
230
- };
231
-
232
- const buildRulesArray = (field: InterfaceField): string => {
233
- const ruleCalls: string[] = [];
234
- if (!field.optional) {
235
- ruleCalls.push('rules.required()');
236
- }
237
-
238
- if (field.type === 'string') {
239
- ruleCalls.push('rules.string()');
240
- } else if (field.type === 'number') {
241
- ruleCalls.push('rules.number()');
242
- }
243
-
244
- return `[${ruleCalls.join(', ')}]`;
245
- };
246
-
247
- const updateRulesObject = (schemaContent: string, fields: InterfaceField[]): string | null => {
248
- const rulesRegex = /\.rules\(\(rules\)\s*=>\s*\(\{([\s\S]*?)\}\)\)/m;
249
- const match = schemaContent.match(rulesRegex);
250
- if (!match) return null;
251
-
252
- const currentBody = match[1] ?? '';
253
- const existingKeys = new Set(extractRuleKeys(currentBody));
254
- const newLines = fields.filter((field) => !existingKeys.has(field.name)).map((field) => `\t\t${field.name}: ${buildRulesArray(field)},`);
255
-
256
- if (!newLines.length) return schemaContent;
257
-
258
- const trimmedBody = currentBody.trimEnd();
259
- const nextBody = trimmedBody.length ? `${trimmedBody}\n${newLines.join('\n')}\n\t` : `\n${newLines.join('\n')}\n\t`;
260
-
261
- return schemaContent.replace(rulesRegex, `.rules((rules) => ({${nextBody}}))`);
262
- };
263
-
264
- export default async function generateSchemaFromType(): Promise<void> {
265
- const contextName = await selectContext('Select context for schema update:');
266
- if (!contextName) {
267
- process.exitCode = 1;
268
- return;
269
- }
270
-
271
- const presentationPath = path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'presentation');
272
- const presenterFolders = await listDirectories(presentationPath);
273
- if (!presenterFolders.length) {
274
- console.error(`❌ No presenter folders found in ${presentationPath}`);
275
- process.exitCode = 1;
276
- return;
277
- }
278
-
279
- const { presenterFolder } = await prompts({
280
- type: 'select',
281
- name: 'presenterFolder',
282
- message: 'Select presenter folder:',
283
- choices: presenterFolders.map((item) => ({ title: item, value: item })),
284
- initial: 0
285
- });
286
-
287
- if (!presenterFolder) {
288
- process.exitCode = 1;
289
- return;
290
- }
291
-
292
- const schemaFolderPath = path.join(presentationPath, String(presenterFolder), 'schema');
293
- const schemas = await listSchemaFiles(schemaFolderPath);
294
- if (!schemas.length) {
295
- console.error(`❌ No schemas found in ${schemaFolderPath}`);
296
- process.exitCode = 1;
297
- return;
298
- }
299
-
300
- const { schemaFile } = await prompts({
301
- type: 'select',
302
- name: 'schemaFile',
303
- message: 'Select schema file:',
304
- choices: schemas.map((item) => ({ title: item, value: item })),
305
- initial: 0
306
- });
307
-
308
- if (!schemaFile) {
309
- process.exitCode = 1;
310
- return;
311
- }
312
-
313
- const schemaPath = path.join(schemaFolderPath, String(schemaFile));
314
- const schemaContent = await fs.readFile(schemaPath, 'utf-8');
315
-
316
- const typeName = extractSchemaTypeName(schemaContent);
317
- if (!typeName) {
318
- console.error('❌ Unable to resolve schema generic type.');
319
- process.exitCode = 1;
320
- return;
321
- }
322
-
323
- const importPath = findTypeImportPath(schemaContent, typeName);
324
- if (!importPath) {
325
- console.error(`❌ Unable to find import for type "${typeName}".`);
326
- process.exitCode = 1;
327
- return;
328
- }
329
-
330
- const aliasMap = await resolveAliasMap();
331
- const typeFilePath = await resolveImportToFile(schemaPath, importPath, aliasMap);
332
- if (!typeFilePath) {
333
- console.error(`❌ Unable to resolve type file path from import "${importPath}".`);
334
- process.exitCode = 1;
335
- return;
336
- }
337
-
338
- let interfaceBody = await findInterfaceBodyByExportGraph(typeFilePath, typeName);
339
- if (!interfaceBody) {
340
- interfaceBody = await findInterfaceBodyByScan(path.dirname(typeFilePath), typeName);
341
- }
342
- if (!interfaceBody) {
343
- console.error(`❌ Interface "${typeName}" not found in ${typeFilePath}`);
344
- process.exitCode = 1;
345
- return;
346
- }
347
-
348
- const interfaceFields = extractInterfaceFields(interfaceBody);
349
- if (!interfaceFields.length) {
350
- console.log('ℹ️ Interface has no explicit keys to transfer into rules.');
351
- return;
352
- }
353
-
354
- const updatedSchemaContent = updateRulesObject(schemaContent, interfaceFields);
355
- if (!updatedSchemaContent) {
356
- console.error('❌ Could not locate `.rules((rules) => ({}))` block in schema file.');
357
- process.exitCode = 1;
358
- return;
359
- }
360
-
361
- if (updatedSchemaContent === schemaContent) {
362
- console.log('ℹ️ Rules already include all keys from type.');
363
- return;
364
- }
365
-
366
- await fs.writeFile(schemaPath, updatedSchemaContent, 'utf-8');
367
- console.log(`✅ Schema updated from type: ${schemaPath}`);
368
- }
@@ -1,259 +0,0 @@
1
- import fs from 'node:fs/promises';
2
- import path from 'node:path';
3
- import prompts from 'prompts';
4
- import { selectContext } from './repositoryModuleShared.js';
5
-
6
- type InterfaceDeclaration = {
7
- name: string;
8
- openBraceIndex: number;
9
- closeBraceIndex: number;
10
- body: string;
11
- };
12
-
13
- const isValidIdentifier = (value: string): boolean => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(value);
14
-
15
- const toPropertyName = (key: string): string => (isValidIdentifier(key) ? key : `'${String(key).replace(/'/g, "\\'")}'`);
16
-
17
- const getIndent = (level: number): string => '\t'.repeat(level);
18
-
19
- const normalizeObjectInput = (rawValue: unknown): string => {
20
- let input = String(rawValue ?? '').trim();
21
- if (input.endsWith(';')) {
22
- input = input.slice(0, -1).trim();
23
- }
24
-
25
- const openCurly = (input.match(/\{/g) ?? []).length;
26
- const closeCurly = (input.match(/\}/g) ?? []).length;
27
- if (openCurly > closeCurly) {
28
- input += '}'.repeat(openCurly - closeCurly);
29
- }
30
-
31
- return input;
32
- };
33
-
34
- const parseObjectInput = (rawValue: unknown): Record<string, unknown> => {
35
- const input = normalizeObjectInput(rawValue);
36
- if (!input.length) {
37
- throw new Error('Input is empty');
38
- }
39
-
40
- try {
41
- const parsed = JSON.parse(input);
42
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
43
- throw new Error('Input root must be an object');
44
- }
45
- return parsed as Record<string, unknown>;
46
- } catch {
47
- // fallback to JS object literal
48
- }
49
-
50
- const parsed = new Function(`"use strict"; return (${input});`)();
51
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
52
- throw new Error('Input root must be an object');
53
- }
54
- return parsed as Record<string, unknown>;
55
- };
56
-
57
- const stringifyType = (value: unknown, level = 1): string => {
58
- if (value === null) return 'null';
59
-
60
- const valueType = typeof value;
61
- if (valueType === 'string') return 'string';
62
- if (valueType === 'number') return Number.isFinite(value as number) ? 'number' : 'unknown';
63
- if (valueType === 'boolean') return 'boolean';
64
- if (valueType === 'bigint') return 'bigint';
65
- if (valueType === 'undefined') return 'undefined';
66
-
67
- if (Array.isArray(value)) {
68
- if (!value.length) return 'unknown[]';
69
-
70
- const itemTypes = Array.from(new Set(value.map((item) => stringifyType(item, level + 1))));
71
- if (itemTypes.length === 1) {
72
- const single = itemTypes[0] ?? 'unknown';
73
- if (single.includes('\n')) return `Array<${single}>`;
74
- return `${single}[]`;
75
- }
76
-
77
- const union = itemTypes.join(' | ');
78
- if (union.includes('\n')) return `Array<${union}>`;
79
- return `(${union})[]`;
80
- }
81
-
82
- if (valueType === 'object') {
83
- const entries = Object.entries(value as Record<string, unknown>);
84
- if (!entries.length) return 'Record<string, unknown>';
85
-
86
- const lines = entries.map(([entryKey, entryValue]) => {
87
- const propertyType = stringifyType(entryValue, level + 1);
88
- return `${getIndent(level + 1)}${toPropertyName(entryKey)}: ${propertyType};`;
89
- });
90
-
91
- return `{\n${lines.join('\n')}\n${getIndent(level)}}`;
92
- }
93
-
94
- return 'unknown';
95
- };
96
-
97
- const findInterfaceDeclaration = (content: string): InterfaceDeclaration | null => {
98
- const declarationMatch = content.match(/export\s+interface\s+([A-Za-z0-9_]+)\s*\{/);
99
- if (!declarationMatch || declarationMatch.index === undefined) return null;
100
-
101
- const name = declarationMatch[1] ?? 'Interface';
102
- const openBraceIndex = content.indexOf('{', declarationMatch.index);
103
- if (openBraceIndex === -1) return null;
104
-
105
- let depth = 0;
106
- let closeBraceIndex = -1;
107
- for (let index = openBraceIndex; index < content.length; index += 1) {
108
- const char = content[index];
109
- if (char === '{') depth += 1;
110
- if (char === '}') {
111
- depth -= 1;
112
- if (depth === 0) {
113
- closeBraceIndex = index;
114
- break;
115
- }
116
- }
117
- }
118
-
119
- if (closeBraceIndex === -1) return null;
120
-
121
- const body = content.slice(openBraceIndex + 1, closeBraceIndex);
122
- return {
123
- name,
124
- openBraceIndex,
125
- closeBraceIndex,
126
- body
127
- };
128
- };
129
-
130
- const extractExistingRootKeys = (body: string): Set<string> => {
131
- const keys = new Set<string>();
132
- const keyRegex = /^\s*([A-Za-z_$][A-Za-z0-9_$]*)\??\s*:/gm;
133
- let match: RegExpExecArray | null;
134
- while ((match = keyRegex.exec(body)) !== null) {
135
- const key = match[1];
136
- if (key) keys.add(key);
137
- }
138
- return keys;
139
- };
140
-
141
- const listDomains = async (contextName: string): Promise<string[]> => {
142
- const domainRoot = path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'domain');
143
- try {
144
- const items = await fs.readdir(domainRoot, { withFileTypes: true });
145
- return items.filter((item) => item.isDirectory()).map((item) => item.name);
146
- } catch {
147
- return [];
148
- }
149
- };
150
-
151
- const listModelFiles = async (contextName: string, domainName: string): Promise<Array<{ name: string; path: string }>> => {
152
- const modelRoot = path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'domain', domainName, 'model');
153
- try {
154
- const files = await fs.readdir(modelRoot);
155
- return files
156
- .filter((fileName) => fileName.endsWith('.ts') && fileName !== 'index.ts')
157
- .map((fileName) => ({
158
- name: fileName.replace(/\.ts$/, ''),
159
- path: path.join(modelRoot, fileName)
160
- }));
161
- } catch {
162
- return [];
163
- }
164
- };
165
-
166
- export default async function generateTypesJson(): Promise<void> {
167
- const contextName = await selectContext('Select context for model update:');
168
- if (!contextName) {
169
- process.exitCode = 1;
170
- return;
171
- }
172
-
173
- const domains = await listDomains(contextName);
174
- if (!domains.length) {
175
- console.error(`❌ No domains found in context "${contextName}".`);
176
- process.exitCode = 1;
177
- return;
178
- }
179
-
180
- const { domainName } = await prompts({
181
- type: 'select',
182
- name: 'domainName',
183
- message: 'Select domain:',
184
- choices: domains.map((item) => ({ title: item, value: item })),
185
- initial: 0
186
- });
187
-
188
- if (!domainName) {
189
- process.exitCode = 1;
190
- return;
191
- }
192
-
193
- const models = await listModelFiles(contextName, String(domainName));
194
- if (!models.length) {
195
- console.error(`❌ No model files found in domain "${domainName}".`);
196
- process.exitCode = 1;
197
- return;
198
- }
199
-
200
- const { modelPath } = await prompts({
201
- type: 'select',
202
- name: 'modelPath',
203
- message: 'Select model:',
204
- choices: models.map((item) => ({ title: item.name, value: item.path })),
205
- initial: 0
206
- });
207
-
208
- if (!modelPath) {
209
- process.exitCode = 1;
210
- return;
211
- }
212
-
213
- const { rawJson } = await prompts({
214
- type: 'text',
215
- name: 'rawJson',
216
- message: 'Paste JSON or JS object (single line):',
217
- validate: (value: string) => {
218
- try {
219
- parseObjectInput(value);
220
- return true;
221
- } catch {
222
- return 'Invalid JSON/JS object';
223
- }
224
- }
225
- });
226
-
227
- if (!rawJson) {
228
- process.exitCode = 1;
229
- return;
230
- }
231
-
232
- const parsedJson = parseObjectInput(rawJson);
233
- const content = await fs.readFile(String(modelPath), 'utf-8');
234
- const interfaceDeclaration = findInterfaceDeclaration(content);
235
- if (!interfaceDeclaration) {
236
- console.error(`❌ Unable to parse interface in ${modelPath}`);
237
- process.exitCode = 1;
238
- return;
239
- }
240
-
241
- const existingKeys = extractExistingRootKeys(interfaceDeclaration.body);
242
- const generatedLines = Object.entries(parsedJson)
243
- .filter(([key]) => !existingKeys.has(key))
244
- .map(([key, value]) => `${getIndent(1)}${toPropertyName(key)}: ${stringifyType(value, 1)};`);
245
-
246
- if (!generatedLines.length) {
247
- console.log('ℹ️ No new keys to add. Model already contains all JSON keys.');
248
- return;
249
- }
250
-
251
- const trimmedBody = interfaceDeclaration.body.trimEnd();
252
- const bodyPrefix = trimmedBody.length ? `${trimmedBody}\n` : '';
253
- const newBody = `${bodyPrefix}${generatedLines.join('\n')}\n`;
254
-
255
- const updatedContent = `${content.slice(0, interfaceDeclaration.openBraceIndex + 1)}${newBody}${content.slice(interfaceDeclaration.closeBraceIndex)}`;
256
- await fs.writeFile(String(modelPath), updatedContent, 'utf-8');
257
-
258
- console.log(`✅ Model updated: ${modelPath}`);
259
- }
@@ -1,67 +0,0 @@
1
- import prompts from 'prompts';
2
- import {
3
- createUseCasesForRepository,
4
- getAvailableTsNames,
5
- getConfigState,
6
- resolveContextAlias,
7
- resolveDomainForRepository,
8
- resolveRepositoriesPath,
9
- selectContext
10
- } from './repositoryModuleShared.js';
11
-
12
- export default async function generateUseCases(): Promise<void> {
13
- const contextName = await selectContext('Select context for UseCases:');
14
- if (!contextName) {
15
- process.exitCode = 1;
16
- return;
17
- }
18
-
19
- const repositoriesPath = resolveRepositoriesPath(contextName);
20
- const repositories = await getAvailableTsNames(repositoriesPath);
21
- if (!repositories.length) {
22
- console.error(`❌ No repositories found in ${repositoriesPath}`);
23
- process.exitCode = 1;
24
- return;
25
- }
26
-
27
- const { repositoryName } = await prompts({
28
- type: 'select',
29
- name: 'repositoryName',
30
- message: 'Select repository:',
31
- choices: repositories.map((item) => ({ title: item, value: item })),
32
- initial: 0
33
- });
34
-
35
- if (!repositoryName) {
36
- process.exitCode = 1;
37
- return;
38
- }
39
-
40
- const { contexts } = await getConfigState();
41
- const contextAlias = resolveContextAlias(contexts, contextName);
42
- const domainName = await resolveDomainForRepository({
43
- contextName,
44
- contextAlias,
45
- repositoryName: String(repositoryName)
46
- });
47
-
48
- if (!domainName) {
49
- console.error('❌ Unable to resolve domain from repository imports.');
50
- process.exitCode = 1;
51
- return;
52
- }
53
-
54
- const created = await createUseCasesForRepository({
55
- contextName,
56
- contextAlias,
57
- domainName,
58
- repositoryName: String(repositoryName)
59
- });
60
-
61
- if (!created) {
62
- process.exitCode = 1;
63
- return;
64
- }
65
-
66
- console.log(`✅ UseCases generated for ${repositoryName}`);
67
- }