@storytype/cli 0.2.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,307 @@
1
- // src/analyzer.ts
1
+ // src/component-detector.ts
2
2
  import fs from "fs-extra";
3
3
  import path from "path";
4
+ var COMPONENT_EXTENSIONS = [".vue", ".tsx", ".ts"];
5
+ var BARREL_FILES = ["index.ts", "index.tsx", "index.js", "index.jsx"];
6
+ var DECLARATION_PATTERNS = [".d.ts", ".d.tsx", ".d.mts", ".d.cts"];
7
+ var IGNORED_DIRECTORIES = [
8
+ "node_modules",
9
+ "dist",
10
+ "dist-storybook",
11
+ "storybook-static",
12
+ "build",
13
+ "out",
14
+ "coverage"
15
+ ];
16
+ var COMPONENT_FILE_ROLES = {
17
+ types: [".types.ts", ".types.tsx"],
18
+ test: [".spec.ts", ".spec.tsx", ".test.ts", ".test.tsx"],
19
+ stories: [".stories.ts", ".stories.tsx", ".story.ts", ".story.tsx"],
20
+ mock: [".mock.ts", ".mock.tsx", ".mocks.ts", ".mocks.tsx"],
21
+ controller: [".controller.ts", ".controller.tsx"]
22
+ };
23
+ var COMPONENT_FILE_ROLE_KEYS = Object.keys(
24
+ COMPONENT_FILE_ROLES
25
+ );
26
+ var TEST_PATTERNS = COMPONENT_FILE_ROLES.test;
27
+ var STORY_PATTERNS = COMPONENT_FILE_ROLES.stories;
28
+ var AUXILIARY_PATTERNS = [
29
+ ...COMPONENT_FILE_ROLES.types,
30
+ ...COMPONENT_FILE_ROLES.mock,
31
+ ...COMPONENT_FILE_ROLES.controller
32
+ ];
33
+ var ALL_ROLE_SUFFIXES = COMPONENT_FILE_ROLE_KEYS.flatMap(
34
+ (role) => COMPONENT_FILE_ROLES[role]
35
+ );
36
+ var ROLE_SUFFIX_PATTERN = new RegExp(
37
+ `\\.(${COMPONENT_FILE_ROLE_KEYS.flatMap(
38
+ (role) => COMPONENT_FILE_ROLES[role].map((suffix) => suffix.split(".")[1])
39
+ ).filter((word, index, words) => words.indexOf(word) === index).join("|")})\\.(ts|tsx|js|jsx)$`
40
+ );
41
+ var ATOMIC_LEVELS = {
42
+ atoms: { order: 1, dir: { en: "atoms", pt: "atomos" } },
43
+ molecules: { order: 2, dir: { en: "molecules", pt: "moleculas" } },
44
+ organisms: { order: 3, dir: { en: "organisms", pt: "organismos" } },
45
+ templates: { order: 4, dir: { en: "templates", pt: "templates" } },
46
+ pages: { order: 5, dir: { en: "pages", pt: "paginas" } }
47
+ };
48
+ var ATOMIC_LEVEL_KEYS = Object.keys(
49
+ ATOMIC_LEVELS
50
+ );
51
+ var PROJECT_LANGUAGES = ["en", "pt"];
52
+ var ATOMIC_LEVEL_ALIASES = Object.fromEntries(
53
+ ATOMIC_LEVEL_KEYS.flatMap(
54
+ (level) => PROJECT_LANGUAGES.flatMap((language) => {
55
+ const plural = ATOMIC_LEVELS[level].dir[language];
56
+ const singular = plural.replace(/s$/, "");
57
+ return [plural, singular].map((alias) => [alias, level]);
58
+ })
59
+ )
60
+ );
61
+ function toAtomicLevelFromAlias(input) {
62
+ return ATOMIC_LEVEL_ALIASES[stripAccents(input.toLowerCase())] ?? null;
63
+ }
64
+ function stripAccents(input) {
65
+ return input.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
66
+ }
67
+ function isComponentFile(fileName) {
68
+ const extension = fileName.slice(fileName.lastIndexOf("."));
69
+ if (!COMPONENT_EXTENSIONS.includes(extension)) return false;
70
+ const playsAnotherRole = ALL_ROLE_SUFFIXES.some((suffix) => fileName.endsWith(suffix));
71
+ const isDeclaration = DECLARATION_PATTERNS.some((suffix) => fileName.endsWith(suffix));
72
+ const isBarrel = BARREL_FILES.includes(fileName);
73
+ return !playsAnotherRole && !isDeclaration && !isBarrel;
74
+ }
75
+ function isComponentEntry(filePath) {
76
+ const fileName = path.basename(filePath);
77
+ if (!isComponentFile(fileName)) return false;
78
+ if (!fileName.endsWith(".ts")) return true;
79
+ const dirPath = path.dirname(filePath);
80
+ const baseName = getComponentBaseName(fileName);
81
+ if (toKebabCase(baseName) === toKebabCase(path.basename(dirPath))) return true;
82
+ return isPascalCase(baseName) && findAtomicLevel(dirPath) !== null;
83
+ }
84
+ function toAtomicLevel(dirName) {
85
+ const normalized = dirName.toLowerCase();
86
+ return ATOMIC_LEVEL_KEYS.find(
87
+ (level) => PROJECT_LANGUAGES.some((language) => ATOMIC_LEVELS[level].dir[language] === normalized)
88
+ ) ?? null;
89
+ }
90
+ function isAtomicLevel(dirName) {
91
+ return toAtomicLevel(dirName) !== null;
92
+ }
93
+ function atomicLevelDir(level, language) {
94
+ return ATOMIC_LEVELS[level].dir[language];
95
+ }
96
+ function findAtomicLevelDirs(componentsDir) {
97
+ const found = [];
98
+ for (const level of ATOMIC_LEVEL_KEYS) {
99
+ const dirName = PROJECT_LANGUAGES.map((language) => ATOMIC_LEVELS[level].dir[language]).find(
100
+ (candidate) => isDirectory(path.join(componentsDir, candidate))
101
+ );
102
+ if (dirName) found.push({ level, dirName });
103
+ }
104
+ return found;
105
+ }
106
+ function detectProjectLanguage(componentsDir) {
107
+ const counts = { en: 0, pt: 0 };
108
+ for (const { level, dirName } of findAtomicLevelDirs(componentsDir)) {
109
+ for (const language of PROJECT_LANGUAGES) {
110
+ const isShared = PROJECT_LANGUAGES.every(
111
+ (other) => ATOMIC_LEVELS[level].dir[other] === dirName
112
+ );
113
+ if (!isShared && ATOMIC_LEVELS[level].dir[language] === dirName) counts[language] += 1;
114
+ }
115
+ }
116
+ return counts.pt > counts.en ? "pt" : "en";
117
+ }
118
+ function findComponentsDirectory(projectPath) {
119
+ const conventionalPaths = [
120
+ path.join(projectPath, "src", "components"),
121
+ path.join(projectPath, "components"),
122
+ path.join(projectPath, "src", "views"),
123
+ path.join(projectPath, "app", "components")
124
+ ];
125
+ const conventional = conventionalPaths.find((candidate) => isDirectory(candidate));
126
+ if (conventional) return conventional;
127
+ return findComponentDirectories(projectPath).length > 0 ? projectPath : null;
128
+ }
129
+ function isDirectory(candidate) {
130
+ try {
131
+ return fs.statSync(candidate).isDirectory();
132
+ } catch {
133
+ return false;
134
+ }
135
+ }
136
+ function isIgnoredDirectory(dirName) {
137
+ return dirName.startsWith(".") || IGNORED_DIRECTORIES.includes(dirName);
138
+ }
139
+ function toKebabCase(str) {
140
+ return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/([A-Z])([A-Z][a-z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
141
+ }
142
+ function isPascalCase(str) {
143
+ return /^[A-Z][a-zA-Z0-9]*$/.test(str);
144
+ }
145
+ function toPascalCase(str) {
146
+ if (isPascalCase(str)) {
147
+ return str;
148
+ }
149
+ const withHyphens = str.replace(/([a-z])([A-Z])/g, "$1-$2");
150
+ return withHyphens.split(/[-_\s]+/).map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join("");
151
+ }
152
+ function getComponentBaseName(filePath) {
153
+ return path.basename(filePath).replace(ROLE_SUFFIX_PATTERN, "").replace(/\.(ts|tsx|js|jsx|vue)$/, "");
154
+ }
155
+ function getFileType(fileName) {
156
+ if (BARREL_FILES.includes(fileName)) return "index";
157
+ const role = COMPONENT_FILE_ROLE_KEYS.find(
158
+ (candidate) => COMPONENT_FILE_ROLES[candidate].some((suffix) => fileName.endsWith(suffix))
159
+ );
160
+ if (role) return role;
161
+ return isComponentFile(fileName) ? "component" : "other";
162
+ }
163
+ var COMPONENT_FILE_SET = [
164
+ { role: "index", completesFolder: true },
165
+ { role: "types", completesFolder: true },
166
+ { role: "test", completesFolder: true },
167
+ { role: "stories", completesFolder: false },
168
+ { role: "mock", completesFolder: false }
169
+ ];
170
+ function componentFileSet(componentName) {
171
+ return COMPONENT_FILE_SET.map(({ role, completesFolder }) => {
172
+ const accepted = role === "index" ? [...BARREL_FILES] : COMPONENT_FILE_ROLES[role].map(
173
+ (suffix) => `${componentName}${suffix}`
174
+ );
175
+ return {
176
+ role,
177
+ // The first accepted name is the canonical one
178
+ fileName: accepted[0],
179
+ accepted,
180
+ completesFolder
181
+ };
182
+ });
183
+ }
184
+ function toExpectedFileName(fileName) {
185
+ const type = getFileType(fileName);
186
+ if (type === "index" || type === "other") return fileName;
187
+ const baseName = getComponentBaseName(fileName);
188
+ return `${toPascalCase(baseName)}${fileName.slice(baseName.length)}`;
189
+ }
190
+ function findComponentFiles(rootDir) {
191
+ const files = [];
192
+ walkDirectories(rootDir, (dirPath, entries) => {
193
+ for (const entry of entries) {
194
+ const filePath = path.join(dirPath, entry.name);
195
+ if (entry.isFile() && isComponentEntry(filePath)) {
196
+ files.push(filePath);
197
+ }
198
+ }
199
+ return void 0;
200
+ });
201
+ return files;
202
+ }
203
+ function findComponentDirectories(rootDir) {
204
+ const directories = [];
205
+ walkDirectories(rootDir, (dirPath, entries) => {
206
+ if (entries.some((e) => e.isFile() && isComponentEntry(path.join(dirPath, e.name)))) {
207
+ directories.push(dirPath);
208
+ return "skip-children";
209
+ }
210
+ });
211
+ return directories;
212
+ }
213
+ function findFilesMatching(rootDir, patterns) {
214
+ const files = [];
215
+ walkDirectories(rootDir, (dirPath, entries) => {
216
+ for (const entry of entries) {
217
+ if (entry.isFile() && patterns.some((pattern) => entry.name.includes(pattern))) {
218
+ files.push(path.join(dirPath, entry.name));
219
+ }
220
+ }
221
+ return void 0;
222
+ });
223
+ return files;
224
+ }
225
+ function detectComponents(rootDir) {
226
+ const components = [];
227
+ walkDirectories(rootDir, (dirPath, entries) => {
228
+ const fileNames = entries.filter((e) => e.isFile()).map((e) => e.name);
229
+ const entryFiles = fileNames.filter((fileName) => isComponentEntry(path.join(dirPath, fileName))).sort();
230
+ if (entryFiles.length === 0) return;
231
+ const dirName = path.basename(dirPath);
232
+ const holdsOneComponent = entryFiles.length === 1 && !isAtomicLevel(dirName);
233
+ if (holdsOneComponent) {
234
+ components.push(ownedComponent(dirPath, dirName, entryFiles[0], fileNames));
235
+ return;
236
+ }
237
+ for (const entryFile of entryFiles) {
238
+ components.push(promotedComponent(dirPath, entryFile, fileNames));
239
+ }
240
+ });
241
+ return components;
242
+ }
243
+ function promotedComponent(containerDir, entryFile, fileNames) {
244
+ const baseName = getComponentBaseName(entryFile);
245
+ const name = toPascalCase(baseName);
246
+ const ownFiles = fileNames.filter((fileName) => getComponentBaseName(fileName) === baseName);
247
+ return {
248
+ name,
249
+ currentDir: containerDir,
250
+ targetDir: path.join(containerDir, toKebabCase(name)),
251
+ entryPath: path.join(containerDir, entryFile),
252
+ files: ownFiles.map((fileName) => describeFile(containerDir, fileName)),
253
+ atomicLevel: findAtomicLevel(containerDir),
254
+ action: "promote"
255
+ };
256
+ }
257
+ function ownedComponent(dirPath, dirName, entryFile, fileNames) {
258
+ const expectedDirName = toKebabCase(dirName);
259
+ return {
260
+ name: toPascalCase(getComponentBaseName(entryFile)),
261
+ currentDir: dirPath,
262
+ targetDir: dirName === expectedDirName ? dirPath : path.join(path.dirname(dirPath), expectedDirName),
263
+ entryPath: path.join(dirPath, entryFile),
264
+ files: fileNames.map((fileName) => describeFile(dirPath, fileName)),
265
+ atomicLevel: findAtomicLevel(dirPath),
266
+ action: dirName === expectedDirName ? "none" : "rename"
267
+ };
268
+ }
269
+ function describeFile(dirPath, fileName) {
270
+ return {
271
+ path: path.join(dirPath, fileName),
272
+ name: fileName,
273
+ targetName: toExpectedFileName(fileName),
274
+ type: getFileType(fileName)
275
+ };
276
+ }
277
+ function findAtomicLevel(dirPath) {
278
+ for (const segment of dirPath.split(path.sep).reverse()) {
279
+ const level = toAtomicLevel(segment);
280
+ if (level) return level;
281
+ }
282
+ return null;
283
+ }
284
+ function walkDirectories(rootDir, visit) {
285
+ if (!fs.existsSync(rootDir)) return;
286
+ let entries;
287
+ try {
288
+ entries = fs.readdirSync(rootDir, { withFileTypes: true });
289
+ } catch {
290
+ return;
291
+ }
292
+ if (visit(rootDir, entries) === "skip-children") return;
293
+ for (const entry of entries) {
294
+ if (entry.isDirectory() && !isIgnoredDirectory(entry.name)) {
295
+ walkDirectories(path.join(rootDir, entry.name), visit);
296
+ }
297
+ }
298
+ }
299
+
300
+ // src/analyzer.ts
4
301
  import chalk from "chalk";
302
+ import fs2 from "fs-extra";
5
303
  import ora from "ora";
6
- var ATOMIC_LEVELS = ["atoms", "molecules", "organisms", "templates", "pages"];
7
- var COMPONENT_EXTENSIONS = [".vue", ".tsx", ".ts"];
8
- var STORY_PATTERNS = [".stories.ts", ".stories.tsx", ".story.ts", ".story.tsx"];
9
- var TEST_PATTERNS = [".spec.ts", ".spec.tsx", ".test.ts", ".test.tsx"];
304
+ import path2 from "path";
10
305
  async function analyzeProject(projectPath = process.cwd()) {
11
306
  const spinner = ora("Analisando projeto...").start();
12
307
  try {
@@ -52,22 +347,20 @@ async function analyzeStructure(projectPath, spinner) {
52
347
  items
53
348
  };
54
349
  }
55
- const foundLevels = ATOMIC_LEVELS.filter(
56
- (level) => fs.existsSync(path.join(componentsPath, level))
57
- );
350
+ const foundLevels = findAtomicLevelDirs(componentsPath);
58
351
  items.push({
59
352
  name: "Diret\xF3rio de componentes",
60
353
  passed: true,
61
354
  points: 10,
62
355
  maxPoints: 10,
63
- message: `Encontrado em: ${path.relative(projectPath, componentsPath)}`
356
+ message: `Encontrado em: ${path2.relative(projectPath, componentsPath)}`
64
357
  });
65
358
  items.push({
66
359
  name: "N\xEDveis Atomic Design",
67
360
  passed: foundLevels.length >= 3,
68
361
  points: foundLevels.length * 5,
69
- maxPoints: 25,
70
- message: `Encontrados: ${foundLevels.join(", ") || "nenhum"} (${foundLevels.length}/5)`
362
+ maxPoints: ATOMIC_LEVEL_KEYS.length * 5,
363
+ message: `Encontrados: ${foundLevels.map((l) => l.dirName).join(", ") || "nenhum"} (${foundLevels.length}/${ATOMIC_LEVEL_KEYS.length})`
71
364
  });
72
365
  const totalComponents = countComponents(componentsPath);
73
366
  const wellOrganized = foundLevels.length >= 3 && totalComponents >= 3;
@@ -91,7 +384,7 @@ async function analyzeStructure(projectPath, spinner) {
91
384
  async function analyzeTypeScript(projectPath, spinner) {
92
385
  spinner.text = "Analisando uso de TypeScript...";
93
386
  const items = [];
94
- const hasTsConfig = fs.existsSync(path.join(projectPath, "tsconfig.json"));
387
+ const hasTsConfig = fs2.existsSync(path2.join(projectPath, "tsconfig.json"));
95
388
  items.push({
96
389
  name: "Configura\xE7\xE3o TypeScript",
97
390
  passed: hasTsConfig,
@@ -115,8 +408,8 @@ async function analyzeTypeScript(projectPath, spinner) {
115
408
  message: `${typescript}/${total} componentes (${Math.round(tsPercentage)}%)`,
116
409
  fileIssues: nonTsComponents.map((f) => ({
117
410
  file: f,
118
- issue: f.endsWith(".vue") ? `Arquivo .vue n\xE3o usa TypeScript: "${path.basename(f)}"` : `Arquivo n\xE3o usa TypeScript: "${path.basename(f)}"`,
119
- fix: f.endsWith(".vue") ? `Adicione lang="ts" ao script: <script setup lang="ts">` : `Renomeie para "${path.basename(f, path.extname(f))}.ts" e adicione tipagem`
411
+ issue: f.endsWith(".vue") ? `Arquivo .vue n\xE3o usa TypeScript: "${path2.basename(f)}"` : `Arquivo n\xE3o usa TypeScript: "${path2.basename(f)}"`,
412
+ fix: f.endsWith(".vue") ? `Adicione lang="ts" ao script: <script setup lang="ts">` : `Renomeie para "${path2.basename(f, path2.extname(f))}.ts" e adicione tipagem`
120
413
  }))
121
414
  });
122
415
  } else {
@@ -128,7 +421,7 @@ async function analyzeTypeScript(projectPath, spinner) {
128
421
  message: "Diret\xF3rio de componentes n\xE3o encontrado"
129
422
  });
130
423
  }
131
- const hasTypesDir = componentsPath && fs.existsSync(path.join(componentsPath, "types"));
424
+ const hasTypesDir = componentsPath && fs2.existsSync(path2.join(componentsPath, "types"));
132
425
  const hasTypesFiles = componentsPath && hasFilesWithPattern(componentsPath, /types\.ts$/i);
133
426
  items.push({
134
427
  name: "Arquivos de tipos",
@@ -176,8 +469,8 @@ async function analyzeTestsAndStories(projectPath, spinner) {
176
469
  };
177
470
  }
178
471
  const componentFiles = findAllComponents(componentsPath);
179
- const testFiles = findFilesByPattern(componentsPath, TEST_PATTERNS);
180
- const storyFiles = findFilesByPattern(componentsPath, STORY_PATTERNS);
472
+ const testFiles = findFilesMatching(componentsPath, TEST_PATTERNS);
473
+ const storyFiles = findFilesMatching(componentsPath, STORY_PATTERNS);
181
474
  const testFileBases = new Set(testFiles.map((f) => stripTestSuffix(f, TEST_PATTERNS)));
182
475
  const storyFileBases = new Set(storyFiles.map((f) => stripTestSuffix(f, STORY_PATTERNS)));
183
476
  const componentsMissingTests = componentFiles.filter((f) => !testFileBases.has(stripExt(f)));
@@ -193,7 +486,7 @@ async function analyzeTestsAndStories(projectPath, spinner) {
193
486
  fileIssues: componentsMissingTests.map((f) => ({
194
487
  file: f,
195
488
  issue: "Sem arquivo de teste",
196
- fix: `Crie ${path.join(path.dirname(f), path.basename(f, path.extname(f)) + ".spec.ts")}`
489
+ fix: `Crie ${path2.join(path2.dirname(f), path2.basename(f, path2.extname(f)) + ".spec.ts")}`
197
490
  }))
198
491
  });
199
492
  items.push({
@@ -205,7 +498,7 @@ async function analyzeTestsAndStories(projectPath, spinner) {
205
498
  fileIssues: componentsMissingStories.map((f) => ({
206
499
  file: f,
207
500
  issue: "Sem arquivo de story",
208
- fix: `Crie ${path.join(path.dirname(f), path.basename(f, path.extname(f)) + ".stories.ts")}`
501
+ fix: `Crie ${path2.join(path2.dirname(f), path2.basename(f, path2.extname(f)) + ".stories.ts")}`
209
502
  }))
210
503
  });
211
504
  const score = items.reduce((sum, item) => sum + item.points, 0);
@@ -247,20 +540,8 @@ async function analyzeNaming(projectPath, spinner) {
247
540
  };
248
541
  }
249
542
  const componentFiles = findAllComponents(componentsPath);
250
- const getComponentBaseName = (file) => {
251
- const fileName = path.basename(file);
252
- return fileName.replace(/\.(types|stories|story|spec|test)\.(ts|tsx|js|jsx)$/, "").replace(/\.(ts|tsx|js|jsx|vue)$/, "");
253
- };
254
- const pascalCaseFiles = componentFiles.filter((file) => {
255
- const baseName = getComponentBaseName(file);
256
- if (baseName === "index") return true;
257
- return /^[A-Z][a-zA-Z0-9]*$/.test(baseName);
258
- });
259
- const nonPascalFiles = componentFiles.filter((file) => {
260
- const baseName = getComponentBaseName(file);
261
- if (baseName === "index") return false;
262
- return !/^[A-Z][a-zA-Z0-9]*$/.test(baseName);
263
- });
543
+ const pascalCaseFiles = componentFiles.filter((file) => isPascalCase(getComponentBaseName(file)));
544
+ const nonPascalFiles = componentFiles.filter((file) => !isPascalCase(getComponentBaseName(file)));
264
545
  const pascalCasePercentage = componentFiles.length > 0 ? pascalCaseFiles.length / componentFiles.length * 100 : 0;
265
546
  items.push({
266
547
  name: "Conven\xE7\xE3o PascalCase",
@@ -268,39 +549,33 @@ async function analyzeNaming(projectPath, spinner) {
268
549
  points: Math.round(pascalCasePercentage / 100 * 10),
269
550
  maxPoints: 10,
270
551
  message: `${pascalCaseFiles.length}/${componentFiles.length} componentes (${Math.round(pascalCasePercentage)}%)`,
271
- fileIssues: nonPascalFiles.map((f) => {
272
- const oldName = path.basename(f);
273
- const baseName = getComponentBaseName(f);
274
- const pascalName = baseName.replace(/[-_](.)/g, (_, c) => c.toUpperCase()).replace(/^(.)/, (_, c) => c.toUpperCase());
275
- const suffix = oldName.replace(
276
- new RegExp(`^${baseName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`),
277
- ""
278
- );
279
- const newName = `${pascalName}${suffix}`;
280
- return {
281
- file: f,
282
- oldName,
283
- newName
284
- };
285
- }).filter(({ oldName, newName }) => oldName !== newName).map(({ file, oldName, newName }) => ({
552
+ // `toExpectedFileName` is the same rule `normalize` applies, so the
553
+ // suggested name is exactly the name normalize would produce
554
+ fileIssues: nonPascalFiles.map((f) => ({
555
+ file: f,
556
+ oldName: path2.basename(f),
557
+ newName: toExpectedFileName(path2.basename(f))
558
+ })).filter(({ oldName, newName }) => oldName !== newName).map(({ file, oldName, newName }) => ({
286
559
  file,
287
560
  issue: `Nome em formato incorreto: "${oldName}"`,
288
561
  fix: `Renomeie para "${newName}"`
289
562
  }))
290
563
  });
291
- const folderedComponents = componentFiles.filter((file) => {
292
- const dir = path.dirname(file);
293
- const fileName = path.basename(file, path.extname(file));
294
- const parentFolder = path.basename(dir);
295
- return fileName === parentFolder || fileName === "index";
296
- });
297
- const folderOrganization = componentFiles.length > 0 ? folderedComponents.length / componentFiles.length * 100 : 0;
564
+ const detected = detectComponents(componentsPath);
565
+ const looseComponents = detected.filter((c) => c.action === "promote");
566
+ const folderedCount = detected.length - looseComponents.length;
567
+ const folderOrganization = detected.length > 0 ? folderedCount / detected.length * 100 : 0;
298
568
  items.push({
299
569
  name: "Organiza\xE7\xE3o por pastas",
300
570
  passed: folderOrganization >= 60,
301
571
  points: Math.round(folderOrganization / 100 * 5),
302
572
  maxPoints: 5,
303
- message: `${folderedComponents.length}/${componentFiles.length} componentes (${Math.round(folderOrganization)}%)`
573
+ message: `${folderedCount}/${detected.length} componentes (${Math.round(folderOrganization)}%)`,
574
+ fileIssues: looseComponents.map((component) => ({
575
+ file: component.entryPath,
576
+ issue: "Componente sem pasta pr\xF3pria",
577
+ fix: `Mova para ${component.targetDir}/ (ou rode: storytype normalize)`
578
+ }))
304
579
  });
305
580
  const score = items.reduce((sum, item) => sum + item.points, 0);
306
581
  const maxScore = items.reduce((sum, item) => sum + item.maxPoints, 0);
@@ -315,7 +590,7 @@ async function analyzeNaming(projectPath, spinner) {
315
590
  async function analyzeDocumentation(projectPath, spinner) {
316
591
  spinner.text = "Analisando documenta\xE7\xE3o...";
317
592
  const items = [];
318
- const hasReadme = fs.existsSync(path.join(projectPath, "README.md"));
593
+ const hasReadme = fs2.existsSync(path2.join(projectPath, "README.md"));
319
594
  items.push({
320
595
  name: "README.md principal",
321
596
  passed: hasReadme,
@@ -323,7 +598,7 @@ async function analyzeDocumentation(projectPath, spinner) {
323
598
  maxPoints: 5,
324
599
  message: hasReadme ? "README.md encontrado" : "README.md n\xE3o encontrado"
325
600
  });
326
- const hasComponentDocs = fs.existsSync(path.join(projectPath, "docs")) || fs.existsSync(path.join(projectPath, "documentation"));
601
+ const hasComponentDocs = fs2.existsSync(path2.join(projectPath, "docs")) || fs2.existsSync(path2.join(projectPath, "documentation"));
327
602
  items.push({
328
603
  name: "Documenta\xE7\xE3o do projeto",
329
604
  passed: hasComponentDocs,
@@ -341,74 +616,18 @@ async function analyzeDocumentation(projectPath, spinner) {
341
616
  items
342
617
  };
343
618
  }
344
- function findComponentsDirectory(projectPath) {
345
- const possiblePaths = [
346
- path.join(projectPath, "src", "components"),
347
- path.join(projectPath, "components"),
348
- path.join(projectPath, "src", "views"),
349
- path.join(projectPath, "app", "components")
350
- ];
351
- for (const p of possiblePaths) {
352
- if (fs.existsSync(p)) {
353
- return p;
354
- }
355
- }
356
- return null;
357
- }
358
619
  function countComponents(dir) {
359
620
  return findAllComponents(dir).length;
360
621
  }
361
622
  function findAllComponents(dir) {
362
- const components = [];
363
- function walk(currentDir) {
364
- if (!fs.existsSync(currentDir)) return;
365
- const entries = fs.readdirSync(currentDir, { withFileTypes: true });
366
- for (const entry of entries) {
367
- const fullPath = path.join(currentDir, entry.name);
368
- if (entry.isDirectory()) {
369
- if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
370
- walk(fullPath);
371
- } else if (entry.isFile()) {
372
- const ext = path.extname(entry.name);
373
- if (COMPONENT_EXTENSIONS.includes(ext)) {
374
- const isTest = TEST_PATTERNS.some((pattern) => entry.name.includes(pattern));
375
- const isStory = STORY_PATTERNS.some((pattern) => entry.name.includes(pattern));
376
- if (!isTest && !isStory) {
377
- components.push(fullPath);
378
- }
379
- }
380
- }
381
- }
382
- }
383
- walk(dir);
384
- return components;
385
- }
386
- function findFilesByPattern(dir, patterns) {
387
- const files = [];
388
- function walk(currentDir) {
389
- if (!fs.existsSync(currentDir)) return;
390
- const entries = fs.readdirSync(currentDir, { withFileTypes: true });
391
- for (const entry of entries) {
392
- const fullPath = path.join(currentDir, entry.name);
393
- if (entry.isDirectory()) {
394
- if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
395
- walk(fullPath);
396
- } else if (entry.isFile()) {
397
- if (patterns.some((pattern) => entry.name.includes(pattern))) {
398
- files.push(fullPath);
399
- }
400
- }
401
- }
402
- }
403
- walk(dir);
404
- return files;
623
+ return findComponentFiles(dir);
405
624
  }
406
625
  function hasFilesWithPattern(dir, pattern) {
407
626
  function walk(currentDir) {
408
- if (!fs.existsSync(currentDir)) return false;
409
- const entries = fs.readdirSync(currentDir, { withFileTypes: true });
627
+ if (!fs2.existsSync(currentDir)) return false;
628
+ const entries = fs2.readdirSync(currentDir, { withFileTypes: true });
410
629
  for (const entry of entries) {
411
- const fullPath = path.join(currentDir, entry.name);
630
+ const fullPath = path2.join(currentDir, entry.name);
412
631
  if (entry.isDirectory()) {
413
632
  if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
414
633
  if (walk(fullPath)) return true;
@@ -434,7 +653,7 @@ function stripTestSuffix(filePath, patterns) {
434
653
  function isVueFileUsingTypeScript(filePath) {
435
654
  try {
436
655
  if (!filePath.endsWith(".vue")) return false;
437
- const content = fs.readFileSync(filePath, "utf-8");
656
+ const content = fs2.readFileSync(filePath, "utf-8");
438
657
  if (/<script\s+setup\s+lang=["']ts["']/.test(content)) return true;
439
658
  if (/<script\s+lang=["']ts["']\s+setup/.test(content)) return true;
440
659
  if (/<script\s+lang=["']ts["']/.test(content)) return true;
@@ -539,6 +758,18 @@ function generateRecommendations(result) {
539
758
  }
540
759
 
541
760
  export {
761
+ BARREL_FILES,
762
+ ATOMIC_LEVELS,
763
+ ATOMIC_LEVEL_KEYS,
764
+ toAtomicLevelFromAlias,
765
+ atomicLevelDir,
766
+ detectProjectLanguage,
767
+ findComponentsDirectory,
768
+ isIgnoredDirectory,
769
+ toKebabCase,
770
+ toPascalCase,
771
+ componentFileSet,
772
+ detectComponents,
542
773
  analyzeProject,
543
774
  displayResults
544
775
  };