@storytype/cli 0.3.0 → 0.4.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.
package/README.md CHANGED
@@ -206,6 +206,23 @@ Estrutura Atomic Design: 40/50 (80%)
206
206
  - ⚠️ **40-59%** - Projeto precisa de melhorias significativas.
207
207
  - 🔧 **0-39%** - Projeto precisa de reestruturação.
208
208
 
209
+ ### `storytype completion <shell>`
210
+
211
+ Print the shell completion script for `bash`, `zsh` or `fish`. Activate it with one line in your shell profile; the script is generated from the CLI's own command definitions, so new flags and commands are completed without any edit.
212
+
213
+ ```bash
214
+ # bash (~/.bashrc)
215
+ eval "$(storytype completion bash)"
216
+
217
+ # zsh (~/.zshrc, after compinit)
218
+ eval "$(storytype completion zsh)"
219
+
220
+ # fish
221
+ storytype completion fish > ~/.config/fish/completions/storytype.fish
222
+ ```
223
+
224
+ Completes commands and aliases, the flags of each command, the level names accepted by `generate`, and directories for `[path]`. `--dirs-only` and `--files-only` are opposites, so one is no longer offered once the other is on the line.
225
+
209
226
  ## Monorepo Support
210
227
 
211
228
  The `normalize` and `analyze` commands fully support monorepo structures:
@@ -1,9 +1,16 @@
1
+ // src/analyzer.ts
2
+ import chalk from "chalk";
3
+ import fs2 from "fs-extra";
4
+ import ora from "ora";
5
+ import path2 from "path";
6
+
1
7
  // src/component-detector.ts
2
8
  import fs from "fs-extra";
3
9
  import path from "path";
4
10
  var COMPONENT_EXTENSIONS = [".vue", ".tsx", ".ts"];
5
11
  var BARREL_FILES = ["index.ts", "index.tsx", "index.js", "index.jsx"];
6
12
  var DECLARATION_PATTERNS = [".d.ts", ".d.tsx", ".d.mts", ".d.cts"];
13
+ var COMPONENT_DIRECTORIES = ["components", "views"];
7
14
  var IGNORED_DIRECTORIES = [
8
15
  "node_modules",
9
16
  "dist",
@@ -25,6 +32,7 @@ var COMPONENT_FILE_ROLE_KEYS = Object.keys(
25
32
  );
26
33
  var TEST_PATTERNS = COMPONENT_FILE_ROLES.test;
27
34
  var STORY_PATTERNS = COMPONENT_FILE_ROLES.stories;
35
+ var UI_SIBLING_SUFFIXES = [...COMPONENT_FILE_ROLES.stories, ".vue"];
28
36
  var AUXILIARY_PATTERNS = [
29
37
  ...COMPONENT_FILE_ROLES.types,
30
38
  ...COMPONENT_FILE_ROLES.mock,
@@ -78,8 +86,22 @@ function isComponentEntry(filePath) {
78
86
  if (!fileName.endsWith(".ts")) return true;
79
87
  const dirPath = path.dirname(filePath);
80
88
  const baseName = getComponentBaseName(fileName);
81
- if (toKebabCase(baseName) === toKebabCase(path.basename(dirPath))) return true;
82
- return isPascalCase(baseName) && findAtomicLevel(dirPath) !== null;
89
+ const namesItsFolder = toKebabCase(baseName) === toKebabCase(path.basename(dirPath));
90
+ if (isPascalCase(baseName)) return namesItsFolder || findAtomicLevel(dirPath) !== null;
91
+ return namesItsFolder && (isInComponentTree(dirPath) || hasUiSibling(dirPath, baseName));
92
+ }
93
+ function isInComponentTree(dirPath) {
94
+ const parent = path.basename(path.dirname(dirPath));
95
+ return isAtomicLevel(parent) || COMPONENT_DIRECTORIES.includes(parent.toLowerCase());
96
+ }
97
+ function hasUiSibling(dirPath, baseName) {
98
+ try {
99
+ return fs.readdirSync(dirPath).some(
100
+ (name) => getComponentBaseName(name) === baseName && UI_SIBLING_SUFFIXES.some((suffix) => name.endsWith(suffix))
101
+ );
102
+ } catch {
103
+ return false;
104
+ }
83
105
  }
84
106
  function toAtomicLevel(dirName) {
85
107
  const normalized = dirName.toLowerCase();
@@ -298,10 +320,6 @@ function walkDirectories(rootDir, visit) {
298
320
  }
299
321
 
300
322
  // src/analyzer.ts
301
- import chalk from "chalk";
302
- import fs2 from "fs-extra";
303
- import ora from "ora";
304
- import path2 from "path";
305
323
  async function analyzeProject(projectPath = process.cwd()) {
306
324
  const spinner = ora("Analisando projeto...").start();
307
325
  try {
@@ -761,6 +779,7 @@ export {
761
779
  BARREL_FILES,
762
780
  ATOMIC_LEVELS,
763
781
  ATOMIC_LEVEL_KEYS,
782
+ ATOMIC_LEVEL_ALIASES,
764
783
  toAtomicLevelFromAlias,
765
784
  atomicLevelDir,
766
785
  detectProjectLanguage,
package/dist/cli.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  ATOMIC_LEVELS,
4
+ ATOMIC_LEVEL_ALIASES,
4
5
  ATOMIC_LEVEL_KEYS,
5
6
  BARREL_FILES,
6
7
  analyzeProject,
@@ -14,15 +15,416 @@ import {
14
15
  toAtomicLevelFromAlias,
15
16
  toKebabCase,
16
17
  toPascalCase
17
- } from "./chunk-PNYCPIWD.js";
18
+ } from "./chunk-G73DMA4C.js";
18
19
 
19
- // src/cli.ts
20
+ // src/program.ts
20
21
  import chalk from "chalk";
21
- import { Command } from "commander";
22
+ import { Argument, Command, Option } from "commander";
22
23
  import path4 from "path";
23
24
 
24
25
  // package.json
25
- var version = "0.3.0";
26
+ var version = "0.4.0";
27
+
28
+ // src/completion/Completion.ts
29
+ function renderCompletion(program, shell) {
30
+ const spec = describeProgram(program);
31
+ switch (shell) {
32
+ case "bash":
33
+ return renderBash(spec);
34
+ case "zsh":
35
+ return renderZsh(spec);
36
+ case "fish":
37
+ return renderFish(spec);
38
+ }
39
+ }
40
+ function describeProgram(program) {
41
+ const help = program.createHelp();
42
+ const commands = help.visibleCommands(program);
43
+ const commandWords2 = commands.flatMap((cmd) => [cmd.name(), ...cmd.aliases()]);
44
+ return {
45
+ name: program.name(),
46
+ options: describeOptions(help.visibleOptions(program), program),
47
+ commands: commands.map((cmd) => ({
48
+ name: cmd.name(),
49
+ aliases: cmd.aliases(),
50
+ description: cmd.description(),
51
+ options: describeOptions(help.visibleOptions(cmd), cmd),
52
+ arguments: cmd.registeredArguments.map((arg) => describeArgument(arg, commandWords2))
53
+ }))
54
+ };
55
+ }
56
+ function describeOptions(options, cmd) {
57
+ const byAttribute = new Map(cmd.options.map((option) => [option.attributeName(), option]));
58
+ const conflicts = /* @__PURE__ */ new Map();
59
+ for (const option of cmd.options) {
60
+ for (const attribute of option.conflictsWith ?? []) {
61
+ const other = byAttribute.get(attribute);
62
+ if (!other) continue;
63
+ conflicts.set(option, (conflicts.get(option) ?? /* @__PURE__ */ new Set()).add(other));
64
+ conflicts.set(other, (conflicts.get(other) ?? /* @__PURE__ */ new Set()).add(option));
65
+ }
66
+ }
67
+ return options.filter((option) => option.long !== void 0).map((option) => {
68
+ const long = option.long;
69
+ const excludes = [
70
+ ...spellings(option),
71
+ ...[...conflicts.get(option) ?? []].flatMap(spellings)
72
+ ];
73
+ return {
74
+ long,
75
+ short: option.short,
76
+ description: option.description,
77
+ value: option.required || option.optional ? valueCompletion(valueName(option)) : void 0,
78
+ excludes
79
+ };
80
+ });
81
+ }
82
+ function spellings(option) {
83
+ return [option.short, option.long].filter((flag) => flag !== void 0);
84
+ }
85
+ function valueName(option) {
86
+ const match = option.flags.match(/[<[]([^>\]]+)[>\]]/);
87
+ return match?.[1] ?? "";
88
+ }
89
+ function describeArgument(arg, commandWords2) {
90
+ return {
91
+ name: arg.name(),
92
+ required: arg.required,
93
+ value: arg.argChoices ? { kind: "words", words: arg.argChoices } : valueCompletion(arg.name(), commandWords2)
94
+ };
95
+ }
96
+ function valueCompletion(name, commandWords2 = []) {
97
+ switch (name) {
98
+ case "type":
99
+ return { kind: "words", words: Object.keys(ATOMIC_LEVEL_ALIASES) };
100
+ case "path":
101
+ return { kind: "directories" };
102
+ case "command":
103
+ return { kind: "words", words: commandWords2 };
104
+ default:
105
+ return { kind: "none" };
106
+ }
107
+ }
108
+ function commandWords(command) {
109
+ return [command.name, ...command.aliases];
110
+ }
111
+ function optionWords(options) {
112
+ return options.flatMap((option) => option.short ? [option.short, option.long] : [option.long]);
113
+ }
114
+ function plainText(text) {
115
+ return text.replace(/['\\]/g, "");
116
+ }
117
+ function renderBash(spec) {
118
+ const fn = `_${spec.name}`;
119
+ const commandCases = spec.commands.map((command) => renderBashCommandCase(fn, command)).join("\n");
120
+ return `# ${spec.name} bash completion - generated by \`${spec.name} completion bash\`
121
+ # Activate with: eval "$(${spec.name} completion bash)"
122
+
123
+ ${fn}_dirs() {
124
+ local IFS=$'\\n'
125
+ COMPREPLY=( $(compgen -d -- "$1") )
126
+ type compopt >/dev/null 2>&1 && compopt -o filenames
127
+ }
128
+
129
+ ${fn}_words() {
130
+ COMPREPLY=( $(compgen -W "$1" -- "$2") )
131
+ }
132
+
133
+ # Offer the words in $1 that are not yet on the line and not excluded by
134
+ # one that is. $2 holds "flag:excluded" pairs.
135
+ ${fn}_options() {
136
+ local offered='' word pair used seen
137
+ for word in $1; do
138
+ seen=''
139
+ for used in "\${COMP_WORDS[@]:1:COMP_CWORD-1}"; do
140
+ [[ "$used" == "$word" ]] && seen=1
141
+ for pair in $2; do
142
+ [[ "$pair" == "$used:$word" ]] && seen=1
143
+ done
144
+ done
145
+ [[ -z "$seen" ]] && offered="$offered $word"
146
+ done
147
+ COMPREPLY=( $(compgen -W "$offered" -- "$3") )
148
+ }
149
+
150
+ ${fn}() {
151
+ local cur prev
152
+ COMPREPLY=()
153
+ cur="\${COMP_WORDS[COMP_CWORD]}"
154
+ prev="\${COMP_WORDS[COMP_CWORD-1]}"
155
+
156
+ # The subcommand is the first word that is not an option
157
+ local i cmd=''
158
+ for ((i = 1; i < COMP_CWORD; i++)); do
159
+ case "\${COMP_WORDS[i]}" in
160
+ -*) ;;
161
+ *) cmd="\${COMP_WORDS[i]}"; break ;;
162
+ esac
163
+ done
164
+
165
+ if [[ -z "$cmd" ]]; then
166
+ if [[ "$cur" == -* ]]; then
167
+ ${fn}_options '${optionWords(spec.options).join(" ")}' '${bashExcludePairs(spec.options)}' "$cur"
168
+ else
169
+ ${fn}_words '${spec.commands.flatMap(commandWords).join(" ")}' "$cur"
170
+ fi
171
+ return 0
172
+ fi
173
+
174
+ # Per command: its flags, the flags that take a value, the exclusion pairs
175
+ # and what each positional argument completes with
176
+ local opts='' valopts='' excludes=''
177
+ local -a args
178
+ args=()
179
+ case "$cmd" in
180
+ ${commandCases}
181
+ *) return 0 ;;
182
+ esac
183
+
184
+ if [[ "$cur" == -* ]]; then
185
+ ${fn}_options "$opts" "$excludes" "$cur"
186
+ return 0
187
+ fi
188
+
189
+ # Positional index of the word being completed: skip options and their values
190
+ local pos=0 j
191
+ for ((j = i + 1; j < COMP_CWORD; j++)); do
192
+ case "\${COMP_WORDS[j]}" in
193
+ -*) ;;
194
+ *)
195
+ case " $valopts " in
196
+ *" \${COMP_WORDS[j-1]} "*) ;;
197
+ *) pos=$((pos + 1)) ;;
198
+ esac
199
+ ;;
200
+ esac
201
+ done
202
+
203
+ ${fn}_value "\${args[pos]}" "$cur"
204
+ return 0
205
+ }
206
+
207
+ # $1 is "directories", "words:<space separated list>" or empty
208
+ ${fn}_value() {
209
+ case "$1" in
210
+ directories) ${fn}_dirs "$2" ;;
211
+ words:*) ${fn}_words "\${1#words:}" "$2" ;;
212
+ *) ;;
213
+ esac
214
+ }
215
+
216
+ complete -F ${fn} ${spec.name}
217
+ `;
218
+ }
219
+ function renderBashCommandCase(fn, command) {
220
+ const valueOptions = command.options.filter((option) => option.value !== void 0);
221
+ const valueCases = valueOptions.map(
222
+ (option) => ` ${optionWords([option]).join("|")}) ${fn}_value '${bashValue(option.value)}' "$cur"; return 0 ;;`
223
+ ).join("\n");
224
+ const prevCase = valueOptions.length > 0 ? ` case "$prev" in
225
+ ${valueCases}
226
+ esac
227
+ ` : "";
228
+ return ` ${commandWords(command).join("|")})
229
+ ${prevCase} opts='${optionWords(command.options).join(" ")}'
230
+ valopts='${optionWords(valueOptions).join(" ")}'
231
+ excludes='${bashExcludePairs(command.options)}'
232
+ args=(${command.arguments.map((arg) => `'${bashValue(arg.value)}'`).join(" ")})
233
+ ;;`;
234
+ }
235
+ function bashValue(value) {
236
+ switch (value.kind) {
237
+ case "directories":
238
+ return "directories";
239
+ case "words":
240
+ return `words:${value.words.join(" ")}`;
241
+ case "none":
242
+ return "";
243
+ }
244
+ }
245
+ function bashExcludePairs(options) {
246
+ return options.flatMap(
247
+ (option) => optionWords([option]).flatMap(
248
+ (word) => option.excludes.filter((excluded) => excluded !== word).map((excluded) => `${word}:${excluded}`)
249
+ )
250
+ ).join(" ");
251
+ }
252
+ function renderZsh(spec) {
253
+ const fn = `_${spec.name}`;
254
+ const commandCases = spec.commands.map(
255
+ (command) => ` ${commandWords(command).join("|")})
256
+ _arguments \\
257
+ ${[
258
+ ...zshOptionSpecs(command.options),
259
+ ...command.arguments.map(
260
+ (arg, index) => ` '${index + 1}:${zshText(arg.name)}:${zshAction(arg.value)}'`
261
+ )
262
+ ].join(" \\\n")} && ret=0
263
+ ;;`
264
+ ).join("\n");
265
+ const commandList = spec.commands.flatMap(
266
+ (command) => commandWords(command).map((word) => ` '${word}:${zshText(command.description)}'`)
267
+ ).join("\n");
268
+ return `#compdef ${spec.name}
269
+ # ${spec.name} zsh completion - generated by \`${spec.name} completion zsh\`
270
+ # Activate with: eval "$(${spec.name} completion zsh)" (after compinit)
271
+
272
+ ${fn}_commands() {
273
+ local -a commands
274
+ commands=(
275
+ ${commandList}
276
+ )
277
+ _describe -t commands '${spec.name} command' commands
278
+ }
279
+
280
+ ${fn}() {
281
+ local curcontext="$curcontext" state line ret=1
282
+ typeset -A opt_args
283
+
284
+ _arguments -C \\
285
+ ${[...zshOptionSpecs(spec.options), ` '1: :${fn}_commands'`, ` '*:: :->args'`].join(" \\\n")} && ret=0
286
+
287
+ case $state in
288
+ args)
289
+ case $words[1] in
290
+ ${commandCases}
291
+ esac
292
+ ;;
293
+ esac
294
+
295
+ return ret
296
+ }
297
+
298
+ compdef ${fn} ${spec.name}
299
+ `;
300
+ }
301
+ function zshOptionSpecs(options) {
302
+ return options.flatMap(
303
+ (option) => optionWords([option]).map((word) => {
304
+ const exclusion = [.../* @__PURE__ */ new Set([word, ...option.excludes])].join(" ");
305
+ const value = option.value ? `:${zshText(valueLabel(option))}:${zshAction(option.value)}` : "";
306
+ return ` '(${exclusion})${word}[${zshText(option.description)}]${value}'`;
307
+ })
308
+ );
309
+ }
310
+ function valueLabel(option) {
311
+ return option.long.replace(/^--/, "");
312
+ }
313
+ function zshAction(value) {
314
+ switch (value.kind) {
315
+ case "directories":
316
+ return "_directories";
317
+ case "words":
318
+ return `(${value.words.join(" ")})`;
319
+ case "none":
320
+ return "( )";
321
+ }
322
+ }
323
+ function zshText(text) {
324
+ return plainText(text).replace(/\[/g, "(").replace(/\]/g, ")").replace(/:/g, " -");
325
+ }
326
+ function renderFish(spec) {
327
+ const name = spec.name;
328
+ const lines = [];
329
+ const complete = (condition, rest) => lines.push(`complete -c ${name} -n '${condition}' ${rest}`);
330
+ for (const command of spec.commands) {
331
+ for (const word of commandWords(command)) {
332
+ complete(`__${name}_needs_command`, `-a ${word} -d '${fishText(command.description)}'`);
333
+ }
334
+ }
335
+ for (const option of spec.options) {
336
+ complete(`__${name}_needs_command`, fishOption(option));
337
+ }
338
+ for (const command of spec.commands) {
339
+ const using = `__${name}_using_command ${commandWords(command).join(" ")}`;
340
+ const valueOptions = optionWords(command.options.filter((option) => option.value !== void 0));
341
+ for (const option of command.options) {
342
+ const notSeen = option.excludes.filter((flag) => flag !== option.long && flag !== option.short).map((flag) => `; and not __fish_seen_argument ${fishFlag(flag)}`).join("");
343
+ complete(`${using}${notSeen}`, fishOption(option));
344
+ }
345
+ command.arguments.forEach((arg, index) => {
346
+ const values = fishValues(arg.value);
347
+ if (!values) return;
348
+ complete(`${using}; and __${name}_positional ${[index, ...valueOptions].join(" ")}`, values);
349
+ });
350
+ }
351
+ return `# ${name} fish completion - generated by \`${name} completion fish\`
352
+ # Activate with: ${name} completion fish > ~/.config/fish/completions/${name}.fish
353
+
354
+ # True while no subcommand has been typed yet
355
+ function __${name}_needs_command
356
+ set -l tokens (commandline -opc)
357
+ set -e tokens[1]
358
+ for token in $tokens
359
+ string match -q -- '-*' $token; or return 1
360
+ end
361
+ return 0
362
+ end
363
+
364
+ # True when the subcommand on the line is one of the given names
365
+ function __${name}_using_command
366
+ set -l tokens (commandline -opc)
367
+ set -e tokens[1]
368
+ for token in $tokens
369
+ string match -q -- '-*' $token; and continue
370
+ contains -- $token $argv
371
+ return $status
372
+ end
373
+ return 1
374
+ end
375
+
376
+ # True when the word being completed is the positional argument at INDEX
377
+ # (zero-based) of the subcommand. The remaining arguments name the flags that
378
+ # take a value, so their values are not counted as positionals.
379
+ function __${name}_positional
380
+ set -l index $argv[1]
381
+ set -e argv[1]
382
+ set -l tokens (commandline -opc)
383
+ set -e tokens[1]
384
+ set -l count 0
385
+ set -l previous ''
386
+ set -l in_command 0
387
+ for token in $tokens
388
+ if test $in_command -eq 0
389
+ string match -q -- '-*' $token; or set in_command 1
390
+ else if string match -q -- '-*' $token
391
+ else if not contains -- $previous $argv
392
+ set count (math $count + 1)
393
+ end
394
+ set previous $token
395
+ end
396
+ test $count -eq $index
397
+ end
398
+
399
+ complete -c ${name} -f
400
+ ${lines.join("\n")}
401
+ `;
402
+ }
403
+ function fishOption(option) {
404
+ const flags = [option.short ? `-s ${option.short.slice(1)}` : "", `-l ${option.long.slice(2)}`].filter(Boolean).join(" ");
405
+ const values = option.value ? fishValues(option.value) : "";
406
+ const value = option.value ? ` -r${values ? ` ${values}` : ""}` : "";
407
+ return `${flags}${value} -d '${fishText(option.description)}'`;
408
+ }
409
+ function fishValues(value) {
410
+ switch (value.kind) {
411
+ case "directories":
412
+ return "-a '(__fish_complete_directories)'";
413
+ case "words":
414
+ return `-a '${value.words.join(" ")}'`;
415
+ case "none":
416
+ return "";
417
+ }
418
+ }
419
+ function fishFlag(flag) {
420
+ return flag.startsWith("--") ? `-l ${flag.slice(2)}` : `-s ${flag.slice(1)}`;
421
+ }
422
+ function fishText(text) {
423
+ return plainText(text);
424
+ }
425
+
426
+ // src/completion/Completion.types.ts
427
+ var COMPLETION_SHELLS = ["bash", "zsh", "fish"];
26
428
 
27
429
  // src/generate/Generate.ts
28
430
  import fs2 from "fs-extra";
@@ -499,168 +901,178 @@ async function applyImportReferences(components) {
499
901
  }
500
902
  }
501
903
 
502
- // src/cli.ts
503
- var program = new Command();
904
+ // src/program.ts
504
905
  function totalChanges(report) {
505
906
  return report.directoriesToRename + report.componentsToPromote + report.filesToRename + report.filesToCreate;
506
907
  }
507
- program.name("storytype").description("Ferramenta CLI para criar componentes Storytype").version(version);
508
- program.command("generate <type> <name>").alias("g").description("Gerar um novo componente (atom, molecule, organism, template, page)").option("-p, --path <path>", "Caminho customizado para o componente").action(async (type, name, options) => {
509
- const level = toAtomicLevelFromAlias(type);
510
- if (!level) {
511
- console.error(chalk.red(`Tipo de componente inv\xE1lido: ${type}`));
512
- console.log(chalk.yellow(`Tipos v\xE1lidos: ${ATOMIC_LEVEL_KEYS.join(", ")}`));
513
- console.log(
514
- chalk.gray(
515
- "(singular, plural e os nomes em portugu\xEAs tamb\xE9m s\xE3o aceitos: atomo, atomos, ...)"
516
- )
517
- );
518
- process.exit(1);
519
- }
520
- console.log(chalk.blue(`Gerando componente ${type}: ${name}`));
521
- try {
522
- const result = await generateComponent({
523
- name,
524
- type: level,
525
- path: options.path
526
- });
527
- if (result.success) {
528
- console.log(chalk.green("\u2713 Componente gerado com sucesso!"));
529
- console.log(chalk.gray("\nArquivos criados:"));
530
- result.files.forEach((file) => {
531
- console.log(chalk.gray(` - ${file}`));
532
- });
533
- } else {
534
- console.error(chalk.red(`\u2717 Erro: ${result.error}`));
535
- process.exit(1);
536
- }
537
- } catch (error) {
538
- console.error(chalk.red("Erro ao gerar componente:"), error);
539
- process.exit(1);
540
- }
541
- });
542
- program.command("normalize [path]").description(
543
- "Normalizar estrutura de componentes (diret\xF3rios em kebab-case, arquivos em PascalCase)"
544
- ).option("-d, --dry-run", "Mostrar mudan\xE7as sem execut\xE1-las").option("--dirs-only", "Normalizar apenas nomes de diret\xF3rios").option("--files-only", "Normalizar apenas nomes de arquivos").option("-v, --verbose", "Mostrar sa\xEDda detalhada").action(
545
- async (targetPath, options) => {
546
- if (options?.dirsOnly && options?.filesOnly) {
547
- console.error(chalk.red("\u2717 --dirs-only e --files-only sao opostos: escolha um."));
908
+ function createProgram() {
909
+ const program = new Command();
910
+ program.name("storytype").description("Ferramenta CLI para criar componentes Storytype").version(version);
911
+ program.command("generate <type> <name>").alias("g").description("Gerar um novo componente (atom, molecule, organism, template, page)").option("-p, --path <path>", "Caminho customizado para o componente").action(async (type, name, options) => {
912
+ const level = toAtomicLevelFromAlias(type);
913
+ if (!level) {
914
+ console.error(chalk.red(`Tipo de componente inv\xE1lido: ${type}`));
915
+ console.log(chalk.yellow(`Tipos v\xE1lidos: ${ATOMIC_LEVEL_KEYS.join(", ")}`));
916
+ console.log(
917
+ chalk.gray(
918
+ "(singular, plural e os nomes em portugu\xEAs tamb\xE9m s\xE3o aceitos: atomo, atomos, ...)"
919
+ )
920
+ );
548
921
  process.exit(1);
549
922
  }
550
- const scope = options?.dirsOnly ? "dirs" : options?.filesOnly ? "files" : "all";
923
+ console.log(chalk.blue(`Gerando componente ${type}: ${name}`));
551
924
  try {
552
- console.log(chalk.blue("Analisando estrutura de componentes..."));
553
- const result = await normalizeComponents({
554
- path: targetPath || process.cwd(),
555
- dryRun: options?.dryRun || false,
556
- scope,
557
- verbose: options?.verbose || false
925
+ const result = await generateComponent({
926
+ name,
927
+ type: level,
928
+ path: options.path
558
929
  });
559
930
  if (result.success) {
560
- console.log(chalk.green("\n\u2713 An\xE1lise completa!"));
561
- console.log(chalk.gray(`
931
+ console.log(chalk.green("\u2713 Componente gerado com sucesso!"));
932
+ console.log(chalk.gray("\nArquivos criados:"));
933
+ result.files.forEach((file) => {
934
+ console.log(chalk.gray(` - ${file}`));
935
+ });
936
+ } else {
937
+ console.error(chalk.red(`\u2717 Erro: ${result.error}`));
938
+ process.exit(1);
939
+ }
940
+ } catch (error) {
941
+ console.error(chalk.red("Erro ao gerar componente:"), error);
942
+ process.exit(1);
943
+ }
944
+ });
945
+ program.command("normalize [path]").description(
946
+ "Normalizar estrutura de componentes (diret\xF3rios em kebab-case, arquivos em PascalCase)"
947
+ ).option("-d, --dry-run", "Mostrar mudan\xE7as sem execut\xE1-las").addOption(
948
+ new Option("--dirs-only", "Normalizar apenas nomes de diret\xF3rios").conflicts("filesOnly")
949
+ ).addOption(
950
+ new Option("--files-only", "Normalizar apenas nomes de arquivos").conflicts("dirsOnly")
951
+ ).option("-v, --verbose", "Mostrar sa\xEDda detalhada").action(
952
+ async (targetPath, options) => {
953
+ const scope = options?.dirsOnly ? "dirs" : options?.filesOnly ? "files" : "all";
954
+ try {
955
+ console.log(chalk.blue("Analisando estrutura de componentes..."));
956
+ const result = await normalizeComponents({
957
+ path: targetPath || process.cwd(),
958
+ dryRun: options?.dryRun || false,
959
+ scope,
960
+ verbose: options?.verbose || false
961
+ });
962
+ if (result.success) {
963
+ console.log(chalk.green("\n\u2713 An\xE1lise completa!"));
964
+ console.log(chalk.gray(`
562
965
  Componentes encontrados: ${result.components.length}`));
563
- console.log(chalk.gray(`Diret\xF3rios a renomear: ${result.directoriesToRename}`));
564
- console.log(
565
- chalk.gray(`Componentes a mover para pasta pr\xF3pria: ${result.componentsToPromote}`)
566
- );
567
- console.log(chalk.gray(`Arquivos a renomear: ${result.filesToRename}`));
568
- console.log(chalk.gray(`Arquivos a criar: ${result.filesToCreate}`));
569
- if (result.importsToUpdate > 0) {
570
- console.log(chalk.gray(`Imports a atualizar: ${result.importsToUpdate}`));
571
- }
572
- if (result.skippedDirectories.length > 0 && (options?.dryRun || options?.verbose)) {
573
- console.log(chalk.gray(`Diret\xF3rios ignorados: ${result.skippedDirectories.length}`));
574
- }
575
- const cwd = process.cwd();
576
- const relativePath = (absolutePath) => {
577
- const rel = path4.relative(cwd, absolutePath);
578
- return rel.startsWith("..") ? absolutePath : rel;
579
- };
580
- if ((options?.dryRun || options?.verbose) && totalChanges(result) > 0) {
581
- console.log(chalk.cyan("\n\u{1F4CB} Mudan\xE7as detalhadas:\n"));
582
- result.components.forEach((comp) => {
583
- const hasChanges = comp.action !== "none" || comp.missingFiles.length > 0 || comp.files.some((f) => f.currentPath !== f.targetPath);
584
- if (hasChanges) {
585
- console.log(chalk.bold(`
966
+ console.log(chalk.gray(`Diret\xF3rios a renomear: ${result.directoriesToRename}`));
967
+ console.log(
968
+ chalk.gray(`Componentes a mover para pasta pr\xF3pria: ${result.componentsToPromote}`)
969
+ );
970
+ console.log(chalk.gray(`Arquivos a renomear: ${result.filesToRename}`));
971
+ console.log(chalk.gray(`Arquivos a criar: ${result.filesToCreate}`));
972
+ if (result.importsToUpdate > 0) {
973
+ console.log(chalk.gray(`Imports a atualizar: ${result.importsToUpdate}`));
974
+ }
975
+ if (result.skippedDirectories.length > 0 && (options?.dryRun || options?.verbose)) {
976
+ console.log(chalk.gray(`Diret\xF3rios ignorados: ${result.skippedDirectories.length}`));
977
+ }
978
+ const cwd = process.cwd();
979
+ const relativePath = (absolutePath) => {
980
+ const rel = path4.relative(cwd, absolutePath);
981
+ return rel.startsWith("..") ? absolutePath : rel;
982
+ };
983
+ if ((options?.dryRun || options?.verbose) && totalChanges(result) > 0) {
984
+ console.log(chalk.cyan("\n\u{1F4CB} Mudan\xE7as detalhadas:\n"));
985
+ result.components.forEach((comp) => {
986
+ const hasChanges = comp.action !== "none" || comp.missingFiles.length > 0 || comp.files.some((f) => f.currentPath !== f.targetPath);
987
+ if (hasChanges) {
988
+ console.log(chalk.bold(`
586
989
  Componente: ${comp.componentName}`));
587
- if (comp.action === "promote") {
588
- console.log(chalk.yellow(` \u{1F4E6} Mover para pasta pr\xF3pria:`));
589
- console.log(chalk.gray(` ${relativePath(comp.currentPath)}/`));
590
- console.log(chalk.gray(` \u2192 ${relativePath(comp.targetPath)}/`));
591
- }
592
- if (comp.action === "rename") {
593
- console.log(chalk.yellow(` \u{1F4C1} Renomear diret\xF3rio:`));
594
- console.log(chalk.gray(` ${relativePath(comp.currentPath)}`));
595
- console.log(chalk.gray(` \u2192 ${relativePath(comp.targetPath)}`));
596
- }
597
- const filesToRename = comp.files.filter((f) => f.currentPath !== f.targetPath);
598
- if (filesToRename.length > 0) {
599
- const label = comp.action === "promote" ? "Mover" : "Renomear";
600
- console.log(
601
- chalk.yellow(` \u{1F4C4} ${label} arquivo${filesToRename.length > 1 ? "s" : ""}:`)
602
- );
603
- filesToRename.forEach((file) => {
604
- console.log(chalk.gray(` ${relativePath(file.currentPath)}`));
605
- console.log(chalk.gray(` \u2192 ${relativePath(file.targetPath)}`));
606
- });
990
+ if (comp.action === "promote") {
991
+ console.log(chalk.yellow(` \u{1F4E6} Mover para pasta pr\xF3pria:`));
992
+ console.log(chalk.gray(` ${relativePath(comp.currentPath)}/`));
993
+ console.log(chalk.gray(` \u2192 ${relativePath(comp.targetPath)}/`));
994
+ }
995
+ if (comp.action === "rename") {
996
+ console.log(chalk.yellow(` \u{1F4C1} Renomear diret\xF3rio:`));
997
+ console.log(chalk.gray(` ${relativePath(comp.currentPath)}`));
998
+ console.log(chalk.gray(` \u2192 ${relativePath(comp.targetPath)}`));
999
+ }
1000
+ const filesToRename = comp.files.filter((f) => f.currentPath !== f.targetPath);
1001
+ if (filesToRename.length > 0) {
1002
+ const label = comp.action === "promote" ? "Mover" : "Renomear";
1003
+ console.log(
1004
+ chalk.yellow(` \u{1F4C4} ${label} arquivo${filesToRename.length > 1 ? "s" : ""}:`)
1005
+ );
1006
+ filesToRename.forEach((file) => {
1007
+ console.log(chalk.gray(` ${relativePath(file.currentPath)}`));
1008
+ console.log(chalk.gray(` \u2192 ${relativePath(file.targetPath)}`));
1009
+ });
1010
+ }
1011
+ if (comp.missingFiles.length > 0) {
1012
+ console.log(
1013
+ chalk.green(` \u2728 Criar arquivo${comp.missingFiles.length > 1 ? "s" : ""}:`)
1014
+ );
1015
+ comp.missingFiles.forEach((fileName) => {
1016
+ const targetDir = comp.action === "none" ? comp.currentPath : comp.targetPath;
1017
+ const fullPath = `${targetDir}/${fileName}`;
1018
+ console.log(chalk.gray(` ${relativePath(fullPath)}`));
1019
+ });
1020
+ }
607
1021
  }
608
- if (comp.missingFiles.length > 0) {
609
- console.log(
610
- chalk.green(` \u2728 Criar arquivo${comp.missingFiles.length > 1 ? "s" : ""}:`)
611
- );
612
- comp.missingFiles.forEach((fileName) => {
613
- const targetDir = comp.action === "none" ? comp.currentPath : comp.targetPath;
614
- const fullPath = `${targetDir}/${fileName}`;
615
- console.log(chalk.gray(` ${relativePath(fullPath)}`));
616
- });
617
- }
618
- }
619
- });
620
- result.importReferences.forEach((ref) => {
621
- console.log(chalk.yellow(` \u{1F517} Atualizar import:`));
622
- console.log(chalk.gray(` ${relativePath(ref.filePath)}`));
623
- console.log(chalk.gray(` ${ref.currentImport} \u2192 ${ref.newImport}`));
624
- });
625
- }
626
- if (result.skippedDirectories.length > 0 && (options?.dryRun || options?.verbose)) {
627
- console.log(chalk.yellow("\n\u26A0\uFE0F Diret\xF3rios ignorados:\n"));
628
- result.skippedDirectories.forEach((skip) => {
629
- console.log(chalk.gray(` \u2022 ${relativePath(skip.path)}`));
630
- console.log(chalk.dim(` Motivo: ${skip.reason}`));
631
- });
632
- }
633
- if (options?.dryRun) {
634
- console.log(chalk.yellow("\n\u26A0\uFE0F Modo dry-run: nenhuma mudan\xE7a foi feita"));
635
- console.log(chalk.gray("Execute sem --dry-run para aplicar as mudan\xE7as\n"));
636
- } else if (totalChanges(result) > 0) {
637
- console.log(chalk.green("\n\u2713 Normaliza\xE7\xE3o conclu\xEDda com sucesso!"));
1022
+ });
1023
+ result.importReferences.forEach((ref) => {
1024
+ console.log(chalk.yellow(` \u{1F517} Atualizar import:`));
1025
+ console.log(chalk.gray(` ${relativePath(ref.filePath)}`));
1026
+ console.log(chalk.gray(` ${ref.currentImport} \u2192 ${ref.newImport}`));
1027
+ });
1028
+ }
1029
+ if (result.skippedDirectories.length > 0 && (options?.dryRun || options?.verbose)) {
1030
+ console.log(chalk.yellow("\n\u26A0\uFE0F Diret\xF3rios ignorados:\n"));
1031
+ result.skippedDirectories.forEach((skip) => {
1032
+ console.log(chalk.gray(` \u2022 ${relativePath(skip.path)}`));
1033
+ console.log(chalk.dim(` Motivo: ${skip.reason}`));
1034
+ });
1035
+ }
1036
+ if (options?.dryRun) {
1037
+ console.log(chalk.yellow("\n\u26A0\uFE0F Modo dry-run: nenhuma mudan\xE7a foi feita"));
1038
+ console.log(chalk.gray("Execute sem --dry-run para aplicar as mudan\xE7as\n"));
1039
+ } else if (totalChanges(result) > 0) {
1040
+ console.log(chalk.green("\n\u2713 Normaliza\xE7\xE3o conclu\xEDda com sucesso!"));
1041
+ } else {
1042
+ console.log(
1043
+ chalk.green("\n\u2713 Todos os componentes j\xE1 est\xE3o estruturados corretamente!")
1044
+ );
1045
+ }
638
1046
  } else {
639
- console.log(
640
- chalk.green("\n\u2713 Todos os componentes j\xE1 est\xE3o estruturados corretamente!")
641
- );
642
- }
643
- } else {
644
- console.error(chalk.red(`
1047
+ console.error(chalk.red(`
645
1048
  \u2717 Erro: ${result.error}`));
1049
+ process.exit(1);
1050
+ }
1051
+ } catch (error) {
1052
+ console.error(chalk.red("Erro ao normalizar componentes:"), error);
646
1053
  process.exit(1);
647
1054
  }
1055
+ }
1056
+ );
1057
+ program.command("init").description("Inicializar Storytype no seu projeto").action(() => {
1058
+ console.log("Inicializando Storytype...");
1059
+ });
1060
+ program.command("analyze [path]").alias("audit").description("Analisar e pontuar projeto baseado nas melhores pr\xE1ticas Storytype").option("-v, --verbose", "Mostrar problemas por arquivo e como corrigir cada um").action(async (projectPath, options) => {
1061
+ try {
1062
+ const result = await analyzeProject(projectPath);
1063
+ displayResults(result, { verbose: options?.verbose });
648
1064
  } catch (error) {
649
- console.error(chalk.red("Erro ao normalizar componentes:"), error);
1065
+ console.error("Erro ao analisar projeto:", error);
650
1066
  process.exit(1);
651
1067
  }
652
- }
653
- );
654
- program.command("init").description("Inicializar Storytype no seu projeto").action(() => {
655
- console.log("Inicializando Storytype...");
656
- });
657
- program.command("analyze [path]").alias("audit").description("Analisar e pontuar projeto baseado nas melhores pr\xE1ticas Storytype").option("-v, --verbose", "Mostrar problemas por arquivo e como corrigir cada um").action(async (projectPath, options) => {
658
- try {
659
- const result = await analyzeProject(projectPath);
660
- displayResults(result, { verbose: options?.verbose });
661
- } catch (error) {
662
- console.error("Erro ao analisar projeto:", error);
663
- process.exit(1);
664
- }
665
- });
666
- program.parse();
1068
+ });
1069
+ program.command("completion").description("Imprimir o script de autocomplete do shell (bash, zsh ou fish)").addArgument(
1070
+ new Argument("<shell>", "shell para o qual gerar o script").choices(COMPLETION_SHELLS)
1071
+ ).action((shell) => {
1072
+ process.stdout.write(renderCompletion(program, shell));
1073
+ });
1074
+ return program;
1075
+ }
1076
+
1077
+ // src/cli.ts
1078
+ createProgram().parse();
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  analyzeProject,
3
3
  displayResults
4
- } from "./chunk-PNYCPIWD.js";
4
+ } from "./chunk-G73DMA4C.js";
5
5
 
6
6
  // src/index.ts
7
7
  async function generateComponent(options) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storytype/cli",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "CLI tool for scaffolding Storytype components and analyzing project structure",
5
5
  "keywords": [
6
6
  "cli",