slicejs-cli 1.0.57 → 2.0.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/client.js CHANGED
@@ -1,64 +1,147 @@
1
1
  import { program } from "commander";
2
+ import inquirer from "inquirer";
2
3
  import initializeProject from "./commands/init/init.js";
3
4
  import createComponent from "./commands/createComponent/createComponent.js";
4
- import modifyComponent from "./commands/modifyComponent/modifyComponent.js";
5
5
  import listComponents from "./commands/listComponents/listComponents.js";
6
6
  import deleteComponent from "./commands/deleteComponent/deleteComponent.js";
7
+ import fs from "fs";
8
+ import path from "path";
9
+ import { fileURLToPath } from "url";
10
+ import validations from "./commands/Validations.js";
11
+
12
+
13
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
14
+
15
+ const loadConfig = () => {
16
+ try {
17
+ const configPath = path.join(__dirname, "../../src/sliceConfig.json");
18
+ const rawData = fs.readFileSync(configPath, "utf-8");
19
+ return JSON.parse(rawData);
20
+ } catch (error) {
21
+ console.error(`Error loading configuration: ${error.message}`);
22
+ return null;
23
+ }
24
+ };
25
+
26
+ const getCategories = () => {
27
+ const config = loadConfig();
28
+ return config && config.paths?.components ? Object.keys(config.paths.components) : [];
29
+ };
7
30
 
8
31
  const sliceClient = program;
9
32
 
10
- sliceClient
11
- .version('1.0.0')
12
- .description('Client for managing framework components');
33
+ sliceClient.version("1.0.0").description("CLI for managing framework components");
13
34
 
35
+
36
+ // INIT COMMAND
14
37
  sliceClient
15
- .command('init')
16
- .description('Initialize the project')
17
- .action(() => {
18
- initializeProject("basic");
19
- });
20
-
21
- sliceClient
22
- .command('create <componentName>')
23
- .description('Create a new component')
24
- .option('-category <category>', 'Specify the category of the component')
25
- .option('-properties <properties>', 'Specify properties for the component (comma-separated)')
26
- .option('-methods <methods>', 'Specify methods for the component (comma-separated)')
27
- .action((componentName, options) => {
28
- const { Category, Properties, Methods } = options;
29
- const propertiesList = Properties ? Properties.split(',') : [];
30
- const methodsList = Methods ? Methods.split(',') : [];
31
- if( createComponent(componentName, Category, propertiesList, methodsList)) listComponents();
32
- });
33
-
34
- // Comando para modificar un componente
35
- sliceClient
36
- .command('modify <componentName>')
37
- .description('Modify an existing component')
38
- .option('-category <category>', 'Component category')
39
- .option('-add <addProperties>', 'Add Properties to the component (comma-separated)')
40
- .option('-remove <removeProperties>', 'Remove Properties from the component (comma-separated)')
41
- .action((componentName, options) => {
42
- const { Add, Remove,Category } = options;
43
- const addProperties = Add ? Add.split(',') : [];
44
- const removeProperties = Remove ? Remove.split(',') : [];
45
- modifyComponent(componentName,Category, addProperties, removeProperties)
46
- });
47
-
48
- sliceClient.command('delete <componentName>')
49
- .description('Delete an existing component')
50
- .option('-category <category>', 'Component category')
51
- .action((componentName, options) => {
52
- const { Category } = options;
53
- if(deleteComponent(componentName, Category)) listComponents();
54
- });
55
-
56
- // Comando para listar todos los componentes
57
- sliceClient
58
- .command('list')
59
- .description('List all components')
60
- .action(() => {
61
- listComponents();
62
- });
38
+ .command("init")
39
+ .description("Initialize the project")
40
+ .action(() => {
41
+ initializeProject("basic");
42
+ });
43
+
44
+ // COMPONENT COMMAND GROUP
45
+ const componentCommand = sliceClient.command("component").description("Manage components");
46
+
47
+ // CREATE COMPONENT
48
+ componentCommand
49
+ .command("create")
50
+ .description("Create a new component")
51
+ .action(async () => {
52
+ const categories = getCategories();
53
+ if (categories.length === 0) {
54
+ console.error("No categories available. Check your configuration.");
55
+ return;
56
+ }
57
+
58
+ const answers = await inquirer.prompt([
59
+ {
60
+ type: "input",
61
+ name: "componentName",
62
+ message: "Enter the component name:",
63
+ validate: (input) => (input ? true : "Component name cannot be empty"),
64
+ },
65
+ {
66
+ type: "list",
67
+ name: "category",
68
+ message: "Select the component category:",
69
+ choices: categories,
70
+ }])
71
+
72
+ if(validations.getCategoryType(answers.category)==='Visual'){
73
+ const properties = await inquirer.prompt([
74
+ {
75
+ type: "input",
76
+ name: "properties",
77
+ message: "Enter the properties (comma separated):",
78
+ validate: (input) => (input ? true : "Properties cannot be empty"),
79
+ },
80
+ ]);
81
+ answers.properties = properties.properties.split(",").map((prop) => prop.trim());
82
+ } else {
83
+ answers.properties = [];
84
+ }
85
+
86
+ if (createComponent(answers.componentName, answers.category, answers.properties)) {
87
+ listComponents();
88
+ }
89
+ });
90
+
91
+
92
+ // DELETE COMPONENT
93
+ componentCommand
94
+ .command("delete")
95
+ .description("Delete an existing component")
96
+ .action(async () => {
97
+ const categories = getCategories();
98
+ if (categories.length === 0) {
99
+ console.error("No categories available. Check your configuration.");
100
+ return;
101
+ }
102
+
103
+ const answers = await inquirer.prompt([
104
+ {
105
+ type: "input",
106
+ name: "componentName",
107
+ message: "Enter the component name to delete:",
108
+ validate: (input) => (input ? true : "Component name cannot be empty"),
109
+ },
110
+ {
111
+ type: "list",
112
+ name: "category",
113
+ message: "Select the component category:",
114
+ choices: categories,
115
+ },
116
+ ]);
117
+
118
+ const confirm = await inquirer.prompt([
119
+ {
120
+ type: "confirm",
121
+ name: "confirmation",
122
+ message: `Are you sure you want to delete ${answers.componentName}?`,
123
+ },
124
+ ]);
125
+
126
+ if (!confirm.confirmation) {
127
+
128
+ return;
129
+ }
130
+
131
+
132
+ if (deleteComponent(answers.componentName, answers.category)) {
133
+ listComponents();
134
+ }
135
+
136
+
137
+ });
138
+
139
+ // LIST COMPONENTS
140
+ componentCommand
141
+ .command("list")
142
+ .description("List all components")
143
+ .action(() => {
144
+ listComponents();
145
+ });
63
146
 
64
- sliceClient.parse(process.argv);
147
+ sliceClient.parse(process.argv);
@@ -1,29 +1,56 @@
1
- export default class Validations{
2
- constructor(){}
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { fileURLToPath } from 'url';
3
4
 
4
- static isValidComponentName(componentName) {
5
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
6
+
7
+ class Validations {
8
+ constructor() {
9
+ this.config = this.loadConfig(); // Cargamos la configuración solo una vez al instanciar
10
+ this.categories = this.config?.paths?.components;
11
+
12
+ }
13
+
14
+ isValidComponentName(componentName) {
5
15
  // Expresión regular para verificar si el nombre contiene caracteres especiales
6
16
  const regex = /^[a-zA-Z][a-zA-Z0-9]*$/;
7
17
  return regex.test(componentName);
8
18
  }
9
19
 
10
- static isValidCategory(category){
11
- const categoryVariations = {
12
- 'Service': ['service', 'servicio', 'serv', 's'],
13
- 'Visual': ['visual', 'vis', 'v'],
14
- 'Structural': ['structural', 'estructural', 'est', 'st']
15
- };
16
-
17
- let categoryIsValid = false;
18
- Object.keys(categoryVariations).forEach(validCategory => {
19
- if (categoryVariations[validCategory].includes(category.toLowerCase())) {
20
- category = validCategory
21
- categoryIsValid = true;
22
- }
23
- });
24
-
25
- return ({isValid: categoryIsValid, category: category})
20
+ loadConfig() {
21
+ try {
22
+ const configPath = path.join(__dirname, '../../../src/sliceConfig.json');
23
+ const rawData = fs.readFileSync(configPath, 'utf-8');
24
+ return JSON.parse(rawData);
25
+ } catch (error) {
26
+ console.error(`Error cargando configuración: ${error.message}`);
27
+ return null;
28
+ }
29
+ }
30
+
31
+ getCategories() {
32
+ return this.categories; // Usamos las categorías cargadas en el constructor
33
+ }
34
+
35
+ getCategoryPath(category) {
36
+ return this.categories[category].path;
37
+ }
38
+
39
+ getCategoryType(category){
40
+ return this.categories[category].type;
41
+ }
42
+
43
+ isValidCategory(category) {
44
+ const availableCategories = Object.keys(this.categories).map(cat => cat.toLowerCase());
45
+
46
+ if (availableCategories.includes(category.toLowerCase())) {
47
+ return { isValid: true, category };
48
+ } else {
49
+ return { isValid: false, category: null };
50
+ }
26
51
  }
52
+ }
27
53
 
54
+ const validations = new Validations();
28
55
 
29
- }
56
+ export default validations;
@@ -29,10 +29,8 @@ customElements.define("slice-${componentName.toLowerCase()}", ${componentName});
29
29
  `;
30
30
  }
31
31
 
32
- static service(componentName, methods) {
33
- const methodDefinitions = methods.map(method => `
34
- ${method}() {}
35
- `).join('\n');
32
+ static service(componentName) {
33
+
36
34
 
37
35
  return `export default class ${componentName} {
38
36
  constructor(props) {
@@ -42,8 +40,6 @@ customElements.define("slice-${componentName.toLowerCase()}", ${componentName});
42
40
  init() {
43
41
  // Método init
44
42
  }
45
-
46
- ${methodDefinitions}
47
43
  }
48
44
  `;
49
45
  }
@@ -7,8 +7,7 @@ import Validations from '../Validations.js';
7
7
  import Print from '../Print.js';
8
8
  const __dirname = path.dirname(new URL(import.meta.url).pathname);
9
9
 
10
- function createComponent(componentName, category, properties, methods) {
11
-
10
+ function createComponent(componentName, category, properties) {
12
11
  if (!componentName) {
13
12
  Print.error('Component name is required');
14
13
  return;
@@ -32,28 +31,30 @@ function createComponent(componentName, category, properties, methods) {
32
31
  const className = componentName.charAt(0).toUpperCase() + componentName.slice(1);
33
32
  const fileName = `${className}.js`;
34
33
  let template;
34
+
35
+ const type = Validations.getCategoryType(category);
36
+
35
37
 
36
- if(category==='Visual'){
38
+ if(type==='Visual'){
37
39
  template = componentTemplates.visual(className, properties);
38
40
  }
39
41
 
40
- if(category==='Service'){
41
- template = componentTemplates.service(className, methods);
42
+ if(type==='Service'){
43
+ template = componentTemplates.service(className);
42
44
  }
43
45
 
44
- //RUTA PARA CUANDO SE COLOQUE DE USUARIO
45
- // ../../../../src/Components
46
+ const categoryPath = Validations.getCategoryPath(category);
47
+
46
48
 
47
49
  // Determinar la ruta del archivo
48
- let componentDir = path.join(__dirname, '../../../../src/Components', category, className);
50
+ let componentDir = path.join(__dirname, '../../../../src/', categoryPath, className);
49
51
  componentDir=componentDir.slice(1);
50
- // Asegurarse de que el directorio del componente exista
51
52
  fs.ensureDirSync(componentDir);
52
53
 
54
+
53
55
  // Determinar la ruta del archivo
54
56
  let componentPath = path.join(componentDir, fileName);
55
-
56
-
57
+
57
58
 
58
59
  // Verificar si el archivo ya existe
59
60
  if (fs.existsSync(componentPath)) {
@@ -61,10 +62,12 @@ function createComponent(componentName, category, properties, methods) {
61
62
  return;
62
63
  }
63
64
 
65
+
66
+
64
67
  // Escribir el código del componente en el archivo
65
68
  fs.writeFileSync(componentPath, template);
66
69
 
67
- if(category==='Visual'){
70
+ if(type==='Visual'){
68
71
  fs.writeFileSync(`${componentDir}/${className}.css`, '');
69
72
  fs.writeFileSync(`${componentDir}/${className}.html`, `<div>${componentName}</div>`);
70
73
  }
@@ -22,17 +22,12 @@ function deleteComponent(componentName, category) {
22
22
  return;
23
23
  }
24
24
  category = flagCategory.category;
25
-
26
- // Determinar la ruta del archivo
27
- //RUTA PARA CUANDO SE COLOQUE DE USUARIO
28
- // ../../../../src/Components
29
- //PARA DEVELOPERS
30
- // ../../../../Slice/Components
31
25
 
26
+ const categoryPath = Validations.getCategoryPath(category);
27
+
32
28
 
33
-
34
29
  // Construir la ruta del directorio del componente
35
- let componentDir = path.join(__dirname, '../../../../src/Components', category, componentName);
30
+ let componentDir = path.join(__dirname, '../../../../src/', categoryPath, componentName);
36
31
  componentDir = componentDir.slice(1);
37
32
 
38
33
  // Verificar si el directorio del componente existe
@@ -11,7 +11,7 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
11
11
  */
12
12
  const loadConfig = () => {
13
13
  try {
14
- const configPath = path.join(__dirname, '../../../../Slice/sliceConfig.json');
14
+ const configPath = path.join(__dirname, '../../../../src/sliceConfig.json');
15
15
  const rawData = fs.readFileSync(configPath, 'utf-8');
16
16
  return JSON.parse(rawData);
17
17
  } catch (error) {
@@ -28,7 +28,6 @@ const loadConfig = () => {
28
28
  const listComponents = (folderPath) => {
29
29
  try {
30
30
  const result = fs.readdirSync(folderPath)
31
- console.log(`Leyendo carpeta ${folderPath}: ${result.length} archivos encontrados`);
32
31
  return result;
33
32
  } catch (error) {
34
33
  console.error(`Error leyendo carpeta ${folderPath}: ${error.message}`);
@@ -71,7 +70,7 @@ function listComponentsReal(){
71
70
  const components = getComponents();
72
71
 
73
72
  // Ruta donde se generará components.js
74
- const outputPath = path.join(__dirname, '../../../../Slice/Components/components.js');
73
+ const outputPath = path.join(__dirname, '../../../../src/Components/components.js');
75
74
 
76
75
  // Generar archivo components.js con los componentes detectados
77
76
  fs.writeFileSync(outputPath, `const components = ${JSON.stringify(components, null, 2)}; export default components;`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "slicejs-cli",
3
- "version": "1.0.57",
3
+ "version": "2.0.0",
4
4
  "description": "Command client for developing web applications with Slice.js framework",
5
5
  "main": "client.js",
6
6
  "scripts": {
@@ -13,11 +13,15 @@
13
13
  "client",
14
14
  "cli"
15
15
  ],
16
+ "bin":{
17
+ "slice": "client.js"
18
+ },
16
19
  "author": "vkneider",
17
20
  "type": "module",
18
21
  "license": "ISC",
19
22
  "dependencies": {
20
23
  "commander": "^12.0.0",
21
- "fs-extra": "^11.2.0"
24
+ "fs-extra": "^11.2.0",
25
+ "inquirer": "^12.4.2"
22
26
  }
23
27
  }