@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,309 +1,312 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import prompts from 'prompts';
4
- import { getConfigState, resolveContextAlias, selectContext } from './repositoryModuleShared.js';
4
+ import ts from 'typescript';
5
+ import { selectWorkspace } from '../../utils/architecture.js';
5
6
  const listDirectories = async (targetPath) => {
6
- try {
7
- const items = await fs.readdir(targetPath, { withFileTypes: true });
8
- return items.filter((item) => item.isDirectory()).map((item) => item.name);
9
- } catch {
10
- return [];
11
- }
7
+ try {
8
+ const items = await fs.readdir(targetPath, { withFileTypes: true });
9
+ return items.filter((item) => item.isDirectory()).map((item) => item.name);
10
+ }
11
+ catch {
12
+ return [];
13
+ }
12
14
  };
13
15
  const listSchemaFiles = async (targetPath) => {
14
- try {
15
- const files = await fs.readdir(targetPath);
16
- return files.filter((item) => item.endsWith('.ts') && item !== 'index.ts');
17
- } catch {
18
- return [];
19
- }
16
+ try {
17
+ const files = await fs.readdir(targetPath);
18
+ return files.filter((item) => item.endsWith('.ts') && item !== 'index.ts');
19
+ }
20
+ catch {
21
+ return [];
22
+ }
20
23
  };
21
24
  const resolveAliasMap = async () => {
22
- const { contexts } = await getConfigState();
23
- const map = new Map();
24
- for (const context of contexts) {
25
- const alias = resolveContextAlias(contexts, context.name);
26
- map.set(alias, path.join(process.cwd(), 'src', 'app', context.name));
27
- }
28
- return map;
25
+ const map = new Map([
26
+ ['#contexts', path.join(process.cwd(), 'src/app/Contexts')],
27
+ ['#presentation', path.join(process.cwd(), 'src/app/Presentation')],
28
+ ['#platform', path.join(process.cwd(), 'src/app/Platform')]
29
+ ]);
30
+ return map;
29
31
  };
30
32
  const resolveImportToFile = async (fromFile, importPath, aliasMap) => {
31
- const rawImport = String(importPath ?? '').trim();
32
- if (!rawImport.length) return null;
33
- let absolute = '';
34
- if (rawImport.startsWith('.')) {
35
- absolute = path.resolve(path.dirname(fromFile), rawImport);
36
- } else {
37
- const alias = Array.from(aliasMap.keys()).find((key) => rawImport === key || rawImport.startsWith(`${key}/`));
38
- if (!alias) return null;
39
- const suffix = rawImport === alias ? '' : rawImport.slice(alias.length + 1);
40
- absolute = path.join(aliasMap.get(alias), suffix);
41
- }
42
- const tsCandidate = absolute.endsWith('.ts') ? absolute : `${absolute}.ts`;
43
- try {
44
- await fs.access(tsCandidate);
45
- return tsCandidate;
46
- } catch {
47
- const indexCandidate = path.join(absolute, 'index.ts');
48
- try {
49
- await fs.access(indexCandidate);
50
- return indexCandidate;
51
- } catch {
52
- return null;
53
- }
54
- }
33
+ const rawImport = String(importPath ?? '').trim();
34
+ if (!rawImport.length)
35
+ return null;
36
+ let absolute = '';
37
+ if (rawImport.startsWith('.')) {
38
+ absolute = path.resolve(path.dirname(fromFile), rawImport);
39
+ }
40
+ else {
41
+ const alias = Array.from(aliasMap.keys()).find((key) => rawImport === key || rawImport.startsWith(`${key}/`));
42
+ if (!alias)
43
+ return null;
44
+ const suffix = rawImport === alias ? '' : rawImport.slice(alias.length + 1);
45
+ absolute = path.join(aliasMap.get(alias), suffix);
46
+ }
47
+ const tsCandidate = absolute.endsWith('.ts') ? absolute : `${absolute}.ts`;
48
+ try {
49
+ await fs.access(tsCandidate);
50
+ return tsCandidate;
51
+ }
52
+ catch {
53
+ const indexCandidate = path.join(absolute, 'index.ts');
54
+ try {
55
+ await fs.access(indexCandidate);
56
+ return indexCandidate;
57
+ }
58
+ catch {
59
+ return null;
60
+ }
61
+ }
55
62
  };
56
63
  const extractSchemaTypeName = (content) => {
57
- const typeMatch = content.match(/=\s*[A-Za-z0-9_]+<\s*([^>]+?)\s*>\s*\(\)/m);
58
- if (!typeMatch) return null;
59
- return String(typeMatch[1]).trim();
64
+ const typeMatch = content.match(/=\s*[A-Za-z0-9_]+<\s*([^>]+?)\s*>\s*\(\)/m);
65
+ if (!typeMatch)
66
+ return null;
67
+ return String(typeMatch[1]).trim();
60
68
  };
61
69
  const findTypeImportPath = (content, typeName) => {
62
- const importRegex = /import\s+type\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/g;
63
- let match;
64
- while ((match = importRegex.exec(content)) !== null) {
65
- const importedList = match[1];
66
- const sourcePath = match[2];
67
- if (!importedList || !sourcePath) continue;
68
- const imported = importedList
69
- .split(',')
70
- .map((item) => item.trim())
71
- .filter(Boolean);
72
- if (imported.includes(typeName)) {
73
- return sourcePath;
74
- }
75
- }
76
- return null;
70
+ const importRegex = /import\s+type\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/g;
71
+ let match;
72
+ while ((match = importRegex.exec(content)) !== null) {
73
+ const importedList = match[1];
74
+ const sourcePath = match[2];
75
+ if (!importedList || !sourcePath)
76
+ continue;
77
+ const imported = importedList
78
+ .split(',')
79
+ .map((item) => item.trim())
80
+ .filter(Boolean);
81
+ if (imported.includes(typeName)) {
82
+ return sourcePath;
83
+ }
84
+ }
85
+ return null;
77
86
  };
78
87
  const extractInterfaceBody = (content, interfaceName) => {
79
- const declarationRegex = new RegExp(`export\\s+interface\\s+${interfaceName}\\s*\\{`);
80
- const declarationMatch = content.match(declarationRegex);
81
- if (!declarationMatch || declarationMatch.index === undefined) return null;
82
- const openBraceIndex = content.indexOf('{', declarationMatch.index);
83
- if (openBraceIndex === -1) return null;
84
- let depth = 0;
85
- let closeBraceIndex = -1;
86
- for (let index = openBraceIndex; index < content.length; index += 1) {
87
- const char = content[index];
88
- if (char === '{') depth += 1;
89
- if (char === '}') {
90
- depth -= 1;
91
- if (depth === 0) {
92
- closeBraceIndex = index;
93
- break;
94
- }
95
- }
96
- }
97
- if (closeBraceIndex === -1) return null;
98
- return content.slice(openBraceIndex + 1, closeBraceIndex);
88
+ const source = ts.createSourceFile('Domain.ts', content, ts.ScriptTarget.Latest, true);
89
+ const declaration = source.statements.find((node) => ts.isInterfaceDeclaration(node) && node.name.text === interfaceName);
90
+ return declaration ? content.slice(declaration.members.pos, declaration.end - 1) : null;
99
91
  };
100
92
  const resolveRelativeExportPath = async (fromFile, exportPath) => {
101
- const absolute = path.resolve(path.dirname(fromFile), exportPath);
102
- const tsCandidate = absolute.endsWith('.ts') ? absolute : `${absolute}.ts`;
103
- try {
104
- await fs.access(tsCandidate);
105
- return tsCandidate;
106
- } catch {
107
- const indexCandidate = path.join(absolute, 'index.ts');
108
- try {
109
- await fs.access(indexCandidate);
110
- return indexCandidate;
111
- } catch {
112
- return null;
113
- }
114
- }
93
+ const absolute = path.resolve(path.dirname(fromFile), exportPath);
94
+ const tsCandidate = absolute.endsWith('.ts') ? absolute : `${absolute}.ts`;
95
+ try {
96
+ await fs.access(tsCandidate);
97
+ return tsCandidate;
98
+ }
99
+ catch {
100
+ const indexCandidate = path.join(absolute, 'index.ts');
101
+ try {
102
+ await fs.access(indexCandidate);
103
+ return indexCandidate;
104
+ }
105
+ catch {
106
+ return null;
107
+ }
108
+ }
115
109
  };
116
110
  const findInterfaceBodyByExportGraph = async (entryFilePath, interfaceName, visited = new Set()) => {
117
- const resolvedPath = path.resolve(entryFilePath);
118
- if (visited.has(resolvedPath)) return null;
119
- visited.add(resolvedPath);
120
- let content = '';
121
- try {
122
- content = await fs.readFile(resolvedPath, 'utf-8');
123
- } catch {
124
- return null;
125
- }
126
- const direct = extractInterfaceBody(content, interfaceName);
127
- if (direct) return direct;
128
- const exportRegex = /export\s+(?:\*|\{[^}]+\})\s+from\s+['"]([^'"]+)['"]/g;
129
- let match;
130
- while ((match = exportRegex.exec(content)) !== null) {
131
- const exportPath = match[1];
132
- if (!exportPath || !exportPath.startsWith('.')) continue;
133
- const nextPath = await resolveRelativeExportPath(resolvedPath, exportPath);
134
- if (!nextPath) continue;
135
- const nested = await findInterfaceBodyByExportGraph(nextPath, interfaceName, visited);
136
- if (nested) return nested;
137
- }
138
- return null;
111
+ const resolvedPath = path.resolve(entryFilePath);
112
+ if (visited.has(resolvedPath))
113
+ return null;
114
+ visited.add(resolvedPath);
115
+ let content = '';
116
+ try {
117
+ content = await fs.readFile(resolvedPath, 'utf-8');
118
+ }
119
+ catch {
120
+ return null;
121
+ }
122
+ const direct = extractInterfaceBody(content, interfaceName);
123
+ if (direct !== null)
124
+ return direct;
125
+ const exportRegex = /export\s+(?:\*|\{[^}]+\})\s+from\s+['"]([^'"]+)['"]/g;
126
+ let match;
127
+ while ((match = exportRegex.exec(content)) !== null) {
128
+ const exportPath = match[1];
129
+ if (!exportPath || !exportPath.startsWith('.'))
130
+ continue;
131
+ const nextPath = await resolveRelativeExportPath(resolvedPath, exportPath);
132
+ if (!nextPath)
133
+ continue;
134
+ const nested = await findInterfaceBodyByExportGraph(nextPath, interfaceName, visited);
135
+ if (nested !== null)
136
+ return nested;
137
+ }
138
+ return null;
139
139
  };
140
140
  const findInterfaceBodyByScan = async (rootDir, interfaceName) => {
141
- const queue = [rootDir];
142
- while (queue.length) {
143
- const current = queue.shift();
144
- if (!current) continue;
145
- let entries = [];
146
- try {
147
- entries = await fs.readdir(current, { withFileTypes: true });
148
- } catch {
149
- continue;
150
- }
151
- for (const entry of entries) {
152
- const absolute = path.join(current, entry.name);
153
- if (entry.isDirectory()) {
154
- queue.push(absolute);
155
- continue;
156
- }
157
- if (!entry.isFile() || !entry.name.endsWith('.ts')) continue;
158
- const content = await fs.readFile(absolute, 'utf-8');
159
- const body = extractInterfaceBody(content, interfaceName);
160
- if (body) return body;
161
- }
162
- }
163
- return null;
141
+ const queue = [rootDir];
142
+ while (queue.length) {
143
+ const current = queue.shift();
144
+ if (!current)
145
+ continue;
146
+ let entries = [];
147
+ try {
148
+ entries = await fs.readdir(current, { withFileTypes: true });
149
+ }
150
+ catch {
151
+ continue;
152
+ }
153
+ for (const entry of entries) {
154
+ const absolute = path.join(current, entry.name);
155
+ if (entry.isDirectory()) {
156
+ queue.push(absolute);
157
+ continue;
158
+ }
159
+ if (!entry.isFile() || !entry.name.endsWith('.ts'))
160
+ continue;
161
+ const content = await fs.readFile(absolute, 'utf-8');
162
+ const body = extractInterfaceBody(content, interfaceName);
163
+ if (body !== null)
164
+ return body;
165
+ }
166
+ }
167
+ return null;
164
168
  };
165
- const extractRuleKeys = (body) => {
166
- const keys = [];
167
- const keyRegex = /^\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*:/gm;
168
- let match;
169
- while ((match = keyRegex.exec(body)) !== null) {
170
- const key = match[1];
171
- if (key) keys.push(key);
172
- }
173
- return Array.from(new Set(keys));
174
- };
175
- const extractInterfaceFields = (body) => {
176
- const fields = [];
177
- const fieldRegex = /^\s*(?:readonly\s+)?([A-Za-z_$][A-Za-z0-9_$]*)(\?)?\s*:\s*([^;]+);/gm;
178
- let match;
179
- while ((match = fieldRegex.exec(body)) !== null) {
180
- const name = match[1];
181
- const optionalMark = match[2];
182
- const type = String(match[3] ?? '').trim();
183
- if (!name || !type) continue;
184
- fields.push({
185
- name,
186
- optional: optionalMark === '?',
187
- type
188
- });
189
- }
190
- const unique = new Map();
191
- for (const field of fields) {
192
- if (!unique.has(field.name)) unique.set(field.name, field);
193
- }
194
- return Array.from(unique.values());
169
+ export const extractInterfaceFields = (body) => {
170
+ const source = ts.createSourceFile('Type.ts', 'interface IType {' + body + '}', ts.ScriptTarget.Latest, true);
171
+ const declaration = source.statements.find(ts.isInterfaceDeclaration);
172
+ return (declaration?.members.flatMap((member) => {
173
+ if (!ts.isPropertySignature(member) ||
174
+ !member.type ||
175
+ (!ts.isIdentifier(member.name) && !ts.isStringLiteral(member.name) && !ts.isNumericLiteral(member.name)))
176
+ return [];
177
+ return [{ name: member.name.text, optional: Boolean(member.questionToken), type: member.type.getText(source) }];
178
+ }) ?? []);
195
179
  };
196
180
  const buildRulesArray = (field) => {
197
- const ruleCalls = [];
198
- if (!field.optional) {
199
- ruleCalls.push('rules.required()');
200
- }
201
- if (field.type === 'string') {
202
- ruleCalls.push('rules.string()');
203
- } else if (field.type === 'number') {
204
- ruleCalls.push('rules.number()');
205
- }
206
- return `[${ruleCalls.join(', ')}]`;
181
+ const ruleCalls = [];
182
+ if (!field.optional) {
183
+ ruleCalls.push('rules.required()');
184
+ }
185
+ if (field.type === 'string') {
186
+ ruleCalls.push('rules.string()');
187
+ }
188
+ else if (field.type === 'number') {
189
+ ruleCalls.push('rules.number()');
190
+ }
191
+ return `[${ruleCalls.join(', ')}]`;
207
192
  };
208
- const updateRulesObject = (schemaContent, fields) => {
209
- const rulesRegex = /\.rules\(\(rules\)\s*=>\s*\(\{([\s\S]*?)\}\)\)/m;
210
- const match = schemaContent.match(rulesRegex);
211
- if (!match) return null;
212
- const currentBody = match[1] ?? '';
213
- const existingKeys = new Set(extractRuleKeys(currentBody));
214
- const newLines = fields.filter((field) => !existingKeys.has(field.name)).map((field) => `\t\t${field.name}: ${buildRulesArray(field)},`);
215
- if (!newLines.length) return schemaContent;
216
- const trimmedBody = currentBody.trimEnd();
217
- const nextBody = trimmedBody.length ? `${trimmedBody}\n${newLines.join('\n')}\n\t` : `\n${newLines.join('\n')}\n\t`;
218
- return schemaContent.replace(rulesRegex, `.rules((rules) => ({${nextBody}}))`);
193
+ export const updateRulesObject = (content, fields) => {
194
+ const source = ts.createSourceFile('Schema.ts', content, ts.ScriptTarget.Latest, true);
195
+ let object;
196
+ const unwrap = (node) => (ts.isParenthesizedExpression(node) ? unwrap(node.expression) : node);
197
+ const visit = (node) => {
198
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === 'rules') {
199
+ const argument = node.arguments[0];
200
+ if (argument && ts.isArrowFunction(argument) && !ts.isBlock(argument.body)) {
201
+ const body = unwrap(argument.body);
202
+ if (ts.isObjectLiteralExpression(body))
203
+ object ??= body;
204
+ }
205
+ }
206
+ ts.forEachChild(node, visit);
207
+ };
208
+ visit(source);
209
+ if (!object)
210
+ return null;
211
+ const names = new Set(object.properties.flatMap((property) => property.name && (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name) || ts.isNumericLiteral(property.name))
212
+ ? [property.name.text]
213
+ : []));
214
+ const additions = fields
215
+ .filter((field) => !names.has(field.name))
216
+ .map((field) => '\t\t' + JSON.stringify(field.name) + ': ' + buildRulesArray(field) + ',');
217
+ if (!additions.length)
218
+ return content;
219
+ const last = object.properties.at(-1);
220
+ let result = content.slice(0, object.end - 1) + '\n' + additions.join('\n') + '\n\t' + content.slice(object.end - 1);
221
+ if (last && !object.properties.hasTrailingComma)
222
+ result = result.slice(0, last.end) + ',' + result.slice(last.end);
223
+ return result;
219
224
  };
220
225
  export default async function generateSchemaFromType() {
221
- const contextName = await selectContext('Select context for schema update:');
222
- if (!contextName) {
223
- process.exitCode = 1;
224
- return;
225
- }
226
- const presentationPath = path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'presentation');
227
- const presenterFolders = await listDirectories(presentationPath);
228
- if (!presenterFolders.length) {
229
- console.error(`❌ No presenter folders found in ${presentationPath}`);
230
- process.exitCode = 1;
231
- return;
232
- }
233
- const { presenterFolder } = await prompts({
234
- type: 'select',
235
- name: 'presenterFolder',
236
- message: 'Select presenter folder:',
237
- choices: presenterFolders.map((item) => ({ title: item, value: item })),
238
- initial: 0
239
- });
240
- if (!presenterFolder) {
241
- process.exitCode = 1;
242
- return;
243
- }
244
- const schemaFolderPath = path.join(presentationPath, String(presenterFolder), 'schema');
245
- const schemas = await listSchemaFiles(schemaFolderPath);
246
- if (!schemas.length) {
247
- console.error(`❌ No schemas found in ${schemaFolderPath}`);
248
- process.exitCode = 1;
249
- return;
250
- }
251
- const { schemaFile } = await prompts({
252
- type: 'select',
253
- name: 'schemaFile',
254
- message: 'Select schema file:',
255
- choices: schemas.map((item) => ({ title: item, value: item })),
256
- initial: 0
257
- });
258
- if (!schemaFile) {
259
- process.exitCode = 1;
260
- return;
261
- }
262
- const schemaPath = path.join(schemaFolderPath, String(schemaFile));
263
- const schemaContent = await fs.readFile(schemaPath, 'utf-8');
264
- const typeName = extractSchemaTypeName(schemaContent);
265
- if (!typeName) {
266
- console.error('❌ Unable to resolve schema generic type.');
267
- process.exitCode = 1;
268
- return;
269
- }
270
- const importPath = findTypeImportPath(schemaContent, typeName);
271
- if (!importPath) {
272
- console.error(`❌ Unable to find import for type "${typeName}".`);
273
- process.exitCode = 1;
274
- return;
275
- }
276
- const aliasMap = await resolveAliasMap();
277
- const typeFilePath = await resolveImportToFile(schemaPath, importPath, aliasMap);
278
- if (!typeFilePath) {
279
- console.error(`❌ Unable to resolve type file path from import "${importPath}".`);
280
- process.exitCode = 1;
281
- return;
282
- }
283
- let interfaceBody = await findInterfaceBodyByExportGraph(typeFilePath, typeName);
284
- if (!interfaceBody) {
285
- interfaceBody = await findInterfaceBodyByScan(path.dirname(typeFilePath), typeName);
286
- }
287
- if (!interfaceBody) {
288
- console.error(`❌ Interface "${typeName}" not found in ${typeFilePath}`);
289
- process.exitCode = 1;
290
- return;
291
- }
292
- const interfaceFields = extractInterfaceFields(interfaceBody);
293
- if (!interfaceFields.length) {
294
- console.log('ℹ️ Interface has no explicit keys to transfer into rules.');
295
- return;
296
- }
297
- const updatedSchemaContent = updateRulesObject(schemaContent, interfaceFields);
298
- if (!updatedSchemaContent) {
299
- console.error('❌ Could not locate `.rules((rules) => ({}))` block in schema file.');
300
- process.exitCode = 1;
301
- return;
302
- }
303
- if (updatedSchemaContent === schemaContent) {
304
- console.log('ℹ️ Rules already include all keys from type.');
305
- return;
306
- }
307
- await fs.writeFile(schemaPath, updatedSchemaContent, 'utf-8');
308
- console.log(`✅ Schema updated from type: ${schemaPath}`);
226
+ const workspace = await selectWorkspace();
227
+ if (!workspace)
228
+ return;
229
+ const presentationPath = path.join(workspace.path, 'Scopes');
230
+ const presenterFolders = await listDirectories(presentationPath);
231
+ if (!presenterFolders.length) {
232
+ console.error(`❌ No presenter folders found in ${presentationPath}`);
233
+ process.exitCode = 1;
234
+ return;
235
+ }
236
+ const { presenterFolder } = await prompts({
237
+ type: 'select',
238
+ name: 'presenterFolder',
239
+ message: 'Select presenter folder:',
240
+ choices: presenterFolders.map((item) => ({ title: item, value: item })),
241
+ initial: 0
242
+ });
243
+ if (!presenterFolder) {
244
+ process.exitCode = 1;
245
+ return;
246
+ }
247
+ const schemaFolderPath = path.join(presentationPath, String(presenterFolder), 'Schema');
248
+ const schemas = await listSchemaFiles(schemaFolderPath);
249
+ if (!schemas.length) {
250
+ console.error(`❌ No schemas found in ${schemaFolderPath}`);
251
+ process.exitCode = 1;
252
+ return;
253
+ }
254
+ const { schemaFile } = await prompts({
255
+ type: 'select',
256
+ name: 'schemaFile',
257
+ message: 'Select schema file:',
258
+ choices: schemas.map((item) => ({ title: item, value: item })),
259
+ initial: 0
260
+ });
261
+ if (!schemaFile) {
262
+ process.exitCode = 1;
263
+ return;
264
+ }
265
+ const schemaPath = path.join(schemaFolderPath, String(schemaFile));
266
+ const schemaContent = await fs.readFile(schemaPath, 'utf-8');
267
+ const typeName = extractSchemaTypeName(schemaContent);
268
+ if (!typeName) {
269
+ console.error('❌ Unable to resolve schema generic type.');
270
+ process.exitCode = 1;
271
+ return;
272
+ }
273
+ const importPath = findTypeImportPath(schemaContent, typeName);
274
+ if (!importPath) {
275
+ console.error(`❌ Unable to find import for type "${typeName}".`);
276
+ process.exitCode = 1;
277
+ return;
278
+ }
279
+ const aliasMap = await resolveAliasMap();
280
+ const typeFilePath = await resolveImportToFile(schemaPath, importPath, aliasMap);
281
+ if (!typeFilePath) {
282
+ console.error(`❌ Unable to resolve type file path from import "${importPath}".`);
283
+ process.exitCode = 1;
284
+ return;
285
+ }
286
+ let interfaceBody = await findInterfaceBodyByExportGraph(typeFilePath, typeName);
287
+ if (interfaceBody === null) {
288
+ interfaceBody = await findInterfaceBodyByScan(path.dirname(typeFilePath), typeName);
289
+ }
290
+ if (interfaceBody === null) {
291
+ console.error(`❌ Interface "${typeName}" not found in ${typeFilePath}`);
292
+ process.exitCode = 1;
293
+ return;
294
+ }
295
+ const interfaceFields = extractInterfaceFields(interfaceBody);
296
+ if (!interfaceFields.length) {
297
+ console.log('ℹ️ Interface has no explicit keys to transfer into rules.');
298
+ return;
299
+ }
300
+ const updatedSchemaContent = updateRulesObject(schemaContent, interfaceFields);
301
+ if (!updatedSchemaContent) {
302
+ console.error('❌ Could not locate `.rules((rules) => ({}))` block in schema file.');
303
+ process.exitCode = 1;
304
+ return;
305
+ }
306
+ if (updatedSchemaContent === schemaContent) {
307
+ console.log('ℹ️ Rules already include all keys from type.');
308
+ return;
309
+ }
310
+ await fs.writeFile(schemaPath, updatedSchemaContent, 'utf-8');
311
+ console.log(`✅ Schema updated from type: ${schemaPath}`);
309
312
  }
@@ -0,0 +1,41 @@
1
+ import path from 'node:path';
2
+ import prompts from 'prompts';
3
+ import { selectWorkspace, selectScope, normalizePascalName } from '../../utils/architecture.js';
4
+ import { writeIfNotExists, updateIndexTs } from '../../utils/fileUtils.js';
5
+ export default async function generateStore() {
6
+ const workspace = await selectWorkspace();
7
+ if (!workspace)
8
+ return;
9
+ const scope = await selectScope(workspace);
10
+ if (!scope)
11
+ return;
12
+ const answer = await prompts({
13
+ type: 'text',
14
+ name: 'name',
15
+ message: 'State class name:',
16
+ validate: (value) => {
17
+ try {
18
+ normalizePascalName(value);
19
+ return true;
20
+ }
21
+ catch (error) {
22
+ return error.message;
23
+ }
24
+ }
25
+ });
26
+ if (!answer.name)
27
+ return;
28
+ const name = normalizePascalName(String(answer.name));
29
+ const directory = path.join(workspace.path, 'Scopes', scope);
30
+ await writeIfNotExists(path.join(directory, `${name}.svelte.ts`), `import { RegisterProvider } from '@azure-net/kit/delivery';
31
+
32
+ export class ${name} {
33
+ value = $state<string | null>(null);
34
+ set = (value: string | null) => { this.value = value; };
35
+ reset = () => { this.value = null; };
36
+ }
37
+
38
+ export const use${name} = RegisterProvider(() => new ${name}(), 'singleton');
39
+ `);
40
+ await updateIndexTs(directory);
41
+ }