slicejs-cli 3.3.0 → 3.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.
Files changed (33) hide show
  1. package/LICENSE +21 -21
  2. package/client.js +664 -626
  3. package/commands/Print.js +167 -167
  4. package/commands/Validations.js +103 -103
  5. package/commands/build/build.js +40 -40
  6. package/commands/buildProduction/buildProduction.js +579 -579
  7. package/commands/bundle/bundle.js +235 -235
  8. package/commands/createComponent/VisualComponentTemplate.js +55 -55
  9. package/commands/createComponent/createComponent.js +126 -126
  10. package/commands/deleteComponent/deleteComponent.js +77 -77
  11. package/commands/doctor/doctor.js +369 -369
  12. package/commands/getComponent/getComponent.js +747 -747
  13. package/commands/init/init.js +265 -261
  14. package/commands/listComponents/listComponents.js +175 -175
  15. package/commands/startServer/startServer.js +264 -264
  16. package/commands/startServer/watchServer.js +79 -79
  17. package/commands/types/types.js +16 -9
  18. package/commands/utils/LocalCliDelegation.js +53 -53
  19. package/commands/utils/PathHelper.js +68 -68
  20. package/commands/utils/VersionChecker.js +167 -167
  21. package/commands/utils/bundling/BundleGenerator.js +2292 -2292
  22. package/commands/utils/bundling/DependencyAnalyzer.js +933 -933
  23. package/commands/utils/updateManager.js +453 -453
  24. package/package.json +46 -46
  25. package/post.js +66 -65
  26. package/tests/bundle-generator.test.js +708 -708
  27. package/tests/bundle-v2-register-output.test.js +470 -470
  28. package/tests/client-launcher-contract.test.js +211 -211
  29. package/tests/client-update-flow-contract.test.js +272 -272
  30. package/tests/dependency-analyzer.test.js +24 -24
  31. package/tests/local-cli-delegation.test.js +79 -79
  32. package/tests/update-manager-notifications.test.js +88 -88
  33. package/.github/workflows/docs-render-cicd.yml +0 -65
package/client.js CHANGED
@@ -1,393 +1,431 @@
1
- #!/usr/bin/env node
2
- import { program } from "commander";
3
- import inquirer from "inquirer";
4
- import initializeProject from "./commands/init/init.js";
5
- import createComponent from "./commands/createComponent/createComponent.js";
6
- import listComponents from "./commands/listComponents/listComponents.js";
7
- import deleteComponent from "./commands/deleteComponent/deleteComponent.js";
8
- import getComponent, { listComponents as listRemoteComponents, syncComponents } from "./commands/getComponent/getComponent.js";
9
- import startServer from "./commands/startServer/startServer.js";
10
- import runDiagnostics from "./commands/doctor/doctor.js";
11
- import versionChecker from "./commands/utils/VersionChecker.js";
12
- import updateManager from "./commands/utils/updateManager.js";
13
- import fs from "fs";
14
- import path from "path";
15
- import { fileURLToPath } from "url";
16
- import { getConfigPath, getProjectRoot } from "./commands/utils/PathHelper.js";
17
- import { exec, spawnSync } from "node:child_process";
18
- import { promisify } from "util";
1
+ #!/usr/bin/env node
2
+ import { program } from "commander";
3
+ import inquirer from "inquirer";
4
+ import initializeProject from "./commands/init/init.js";
5
+ import createComponent from "./commands/createComponent/createComponent.js";
6
+ import listComponents from "./commands/listComponents/listComponents.js";
7
+ import deleteComponent from "./commands/deleteComponent/deleteComponent.js";
8
+ import getComponent, { listComponents as listRemoteComponents, syncComponents } from "./commands/getComponent/getComponent.js";
9
+ import startServer from "./commands/startServer/startServer.js";
10
+ import runDiagnostics from "./commands/doctor/doctor.js";
11
+ import versionChecker from "./commands/utils/VersionChecker.js";
12
+ import updateManager from "./commands/utils/updateManager.js";
13
+ import fs from "fs";
14
+ import path from "path";
15
+ import { fileURLToPath } from "url";
16
+ import { getConfigPath, getProjectRoot } from "./commands/utils/PathHelper.js";
17
+ import { exec, spawnSync } from "node:child_process";
18
+ import { promisify } from "util";
19
19
  import validations from "./commands/Validations.js";
20
20
  import Print from "./commands/Print.js";
21
21
  import build from './commands/build/build.js';
22
22
  import { runGenerateTypes } from './commands/types/types.js';
23
- import { cleanBundles, bundleInfo } from './commands/bundle/bundle.js';
24
- import {
25
- isLocalDelegationDisabled,
26
- findNearestLocalCliEntry,
27
- resolveLocalCliCandidate,
28
- shouldDelegateToLocalCli
29
- } from './commands/utils/LocalCliDelegation.js';
30
-
31
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
32
-
33
- const loadConfig = () => {
34
- try {
35
- const configPath = getConfigPath(import.meta.url);
36
- const rawData = fs.readFileSync(configPath, "utf-8");
37
- return JSON.parse(rawData);
38
- } catch {
39
- return null;
40
- }
41
- };
42
-
43
- const getCategories = () => {
44
- const config = loadConfig();
45
- return config && config.paths?.components ? Object.keys(config.paths.components) : [];
46
- };
47
-
48
- // Function to run version check for all commands
49
- async function runWithVersionCheck(commandFunction, ...args) {
50
- try {
51
- const execAsync = promisify(exec);
52
- await (async () => {
53
- try {
54
- const info = await updateManager.detectCliInstall();
55
- if (info && info.type === 'global') {
56
- const projectRoot = getProjectRoot(import.meta.url);
57
- const pkgPath = path.join(projectRoot, 'package.json');
58
- let hasPkg = fs.existsSync(pkgPath);
59
- if (!hasPkg) {
60
- const { confirmInit } = await inquirer.prompt([
61
- {
62
- type: 'confirm',
63
- name: 'confirmInit',
64
- message: 'No package.json found. Initialize npm in this project now?',
65
- default: true
66
- }
67
- ]);
68
- if (confirmInit) {
69
- await execAsync('npm init -y', { cwd: projectRoot });
70
- hasPkg = true;
71
- }
72
- }
73
- if (hasPkg) {
74
- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
75
- const hasFramework = pkg.dependencies?.['slicejs-web-framework'];
76
- if (!hasFramework) {
77
- const { confirm } = await inquirer.prompt([
78
- {
79
- type: 'confirm',
80
- name: 'confirm',
81
- message: 'slicejs-web-framework is not installed in this project. Install it now?',
82
- default: true
83
- }
84
- ]);
85
- if (confirm) {
86
- await updateManager.updatePackage('slicejs-web-framework');
87
- }
88
- }
89
- }
90
- }
91
- } catch {}
92
- })();
93
-
94
- updateManager.notifyAvailableUpdates().catch(() => {});
95
-
96
- const result = await commandFunction(...args);
97
-
98
- setTimeout(() => {
99
- versionChecker.checkForUpdates(false);
100
- }, 100);
101
-
102
- return result;
103
- } catch (error) {
104
- Print.error(`Command execution: ${error.message}`);
105
- return false;
106
- }
107
- }
108
-
109
- function maybeDelegateToLocalCli() {
110
- if (isLocalDelegationDisabled(process.env)) {
111
- return;
112
- }
113
-
114
- const currentEntryPath = fileURLToPath(import.meta.url);
115
- const localEntryPath = findNearestLocalCliEntry(process.cwd(), resolveLocalCliCandidate);
116
-
117
- if (!shouldDelegateToLocalCli(currentEntryPath, localEntryPath)) {
118
- return;
119
- }
120
-
121
- const child = spawnSync(
122
- process.execPath,
123
- [localEntryPath, ...process.argv.slice(2)],
124
- {
125
- stdio: 'inherit',
126
- cwd: process.cwd(),
127
- env: process.env
128
- }
129
- );
130
-
131
- process.exit(child.status ?? 1);
132
- }
133
-
134
- maybeDelegateToLocalCli();
135
-
136
- const sliceClient = program;
137
-
138
- try {
139
- const pkgPath = path.join(__dirname, "./package.json");
140
- const pkgRaw = fs.readFileSync(pkgPath, "utf-8");
141
- const pkg = JSON.parse(pkgRaw);
142
- sliceClient.version(pkg.version).description("CLI for managing Slice.js framework components");
143
- } catch {
144
- sliceClient.version("0.0.0").description("CLI for managing Slice.js framework components");
145
- }
146
-
147
- // INIT COMMAND
148
- sliceClient
149
- .command("init")
150
- .description("Initialize a new Slice.js project")
151
- .action(async () => {
152
- await runWithVersionCheck(() => {
153
- initializeProject();
154
- return Promise.resolve();
155
- });
156
- });
157
-
158
- // VERSION COMMAND
159
- sliceClient
160
- .command("version")
161
- .alias("v")
162
- .description("Show version information and check for updates")
163
- .action(async () => {
164
- await versionChecker.showVersionInfo();
165
- });
166
-
167
- // BUILD COMMAND
168
- const buildCommand = sliceClient.command("build")
169
- .description("Build Slice.js project for production")
170
- .action(async (options) => {
171
- const prevEnv = process.env.NODE_ENV;
172
- process.env.NODE_ENV = 'production';
173
- try {
174
- await runWithVersionCheck(async () => {
175
- await build(options);
176
- });
177
- } finally {
178
- process.env.NODE_ENV = prevEnv;
179
- }
180
- });
181
-
182
- buildCommand
183
- .command("clean")
184
- .description("Remove all generated bundles")
185
- .action(async () => {
186
- await cleanBundles();
187
- });
188
-
189
- buildCommand
190
- .command("info")
191
- .description("Show information about generated bundles")
192
- .action(async () => {
193
- await bundleInfo();
194
- });
195
-
196
- buildCommand
197
- .option("-a, --analyze", "Analyze project dependencies without bundling")
198
- .option("-v, --verbose", "Show detailed output")
199
- .option("--no-minify", "Disable minification (enabled by default)")
200
- .option("--no-obfuscate", "Disable obfuscation (enabled by default, no prop mangling)")
201
- .option("--preview", "Start preview server after build")
202
- .option("--serve", "Start preview server without building")
203
- .option("--skip-clean", "Skip cleaning dist before build");
204
-
205
- // DEV COMMAND (DEVELOPMENT)
206
- sliceClient
207
- .command("dev")
208
- .description("Start development server with hot reload enabled by default")
209
- .option("-p, --port <port>", "Port for development server", 3000)
210
- .option("--no-hmr", "Disable hot module reload (enabled by default)")
211
- .action(async (options) => {
212
- const prevEnv = process.env.NODE_ENV;
213
- process.env.NODE_ENV = 'development';
214
- try {
215
- await runWithVersionCheck(async () => {
216
- await startServer({
217
- mode: 'development',
218
- port: parseInt(options.port),
219
- watch: options.hmr
220
- });
221
- });
222
- } finally {
223
- process.env.NODE_ENV = prevEnv;
224
- }
225
- });
226
-
227
- // START COMMAND - PRODUCTION MODE
228
- sliceClient
229
- .command("start")
230
- .description("Serve production files from dist/ (requires prior slice build)")
231
- .option("-p, --port <port>", "Port for server", 3000)
232
- .action(async (options) => {
233
- const prevEnv = process.env.NODE_ENV;
234
- process.env.NODE_ENV = 'production';
235
- try {
236
- await runWithVersionCheck(async () => {
237
- await startServer({
238
- mode: 'production',
239
- port: parseInt(options.port)
240
- });
241
- });
242
- } finally {
243
- process.env.NODE_ENV = prevEnv;
244
- }
245
- });
246
-
247
- // COMPONENT COMMAND GROUP - For local component management
248
- const componentCommand = sliceClient.command("component").alias("comp").description("Manage local project components");
249
-
250
- // CREATE LOCAL COMPONENT
251
- componentCommand
252
- .command("create")
253
- .alias("new")
254
- .description("Create a new component in your local project")
255
- .action(async () => {
256
- await runWithVersionCheck(async () => {
257
- const categories = getCategories();
258
- if (categories.length === 0) {
259
- Print.error("No categories found in your project configuration");
260
- Print.info("Run 'slice init' to initialize your project first");
261
- Print.commandExample("Initialize project", "slice init");
262
- return;
263
- }
264
-
265
- const answers = await inquirer.prompt([
266
- {
267
- type: "input",
268
- name: "componentName",
269
- message: "Enter the component name:",
270
- validate: (input) => {
271
- if (!input) return "Component name cannot be empty";
272
- if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(input)) {
273
- return "Component name must start with a letter and contain only alphanumeric characters";
274
- }
275
- return true;
276
- },
277
- },
278
- {
279
- type: "list",
280
- name: "category",
281
- message: "Select the component category:",
282
- choices: categories,
283
- }
284
- ]);
285
-
286
- const result = createComponent(answers.componentName, answers.category);
287
- if (result) {
288
- Print.success(`Component '${answers.componentName}' created successfully in category '${answers.category}'`);
289
- Print.info("Listing updated components:");
290
- listComponents();
291
- }
292
- });
293
- });
294
-
295
- // LIST LOCAL COMPONENTS
296
- componentCommand
297
- .command("list")
298
- .alias("ls")
299
- .description("List all components in your local project")
300
- .action(async () => {
301
- await runWithVersionCheck(() => {
302
- listComponents();
303
- return Promise.resolve();
304
- });
305
- });
306
-
307
- // DELETE LOCAL COMPONENT
308
- componentCommand
309
- .command("delete")
310
- .alias("remove")
311
- .description("Delete a component from your local project")
312
- .action(async () => {
313
- await runWithVersionCheck(async () => {
314
- const categories = getCategories();
315
- if (categories.length === 0) {
316
- Print.error("No categories available. Check your configuration");
317
- Print.info("Run 'slice init' to initialize your project");
318
- return;
319
- }
320
-
321
- try {
322
- // Paso 1: Seleccionar categoría
323
- const categoryAnswer = await inquirer.prompt([
324
- {
325
- type: "list",
326
- name: "category",
327
- message: "Select the component category:",
328
- choices: categories,
329
- }
330
- ]);
331
-
332
- // Paso 2: Listar componentes de esa categoría
333
- const config = loadConfig();
334
- if (!config) {
335
- Print.error("Could not load configuration");
336
- return;
337
- }
338
-
339
- const categoryPath = config.paths.components[categoryAnswer.category].path;
340
- const fullPath = path.join(__dirname, "../../src", categoryPath);
341
-
342
- if (!fs.existsSync(fullPath)) {
343
- Print.error(`Category path does not exist: ${categoryPath}`);
344
- return;
345
- }
346
-
347
- const components = fs.readdirSync(fullPath).filter(item => {
348
- const itemPath = path.join(fullPath, item);
349
- return fs.statSync(itemPath).isDirectory();
350
- });
351
-
352
- if (components.length === 0) {
353
- Print.info(`No components found in category '${categoryAnswer.category}'`);
354
- return;
355
- }
356
-
357
- // Paso 3: Seleccionar componente a eliminar
358
- const componentAnswer = await inquirer.prompt([
359
- {
360
- type: "list",
361
- name: "componentName",
362
- message: "Select the component to delete:",
363
- choices: components,
364
- },
365
- {
366
- type: "confirm",
367
- name: "confirm",
368
- message: (answers) => `Are you sure you want to delete '${answers.componentName}'?`,
369
- default: false,
370
- }
371
- ]);
372
-
373
- if (!componentAnswer.confirm) {
374
- Print.info("Delete operation cancelled");
375
- return;
376
- }
377
-
378
- // Paso 4: Eliminar el componente
379
- if (deleteComponent(componentAnswer.componentName, categoryAnswer.category)) {
380
- Print.success(`Component ${componentAnswer.componentName} deleted successfully`);
381
- Print.info("Listing updated components:");
382
- listComponents();
383
- }
384
- } catch (error) {
385
- Print.error(`Deleting component: ${error.message}`);
386
- }
387
- });
388
- });
389
-
390
- // REGISTRY COMMAND GROUP - For component registry operations
23
+ import { cleanBundles, bundleInfo } from './commands/bundle/bundle.js';
24
+ import {
25
+ isLocalDelegationDisabled,
26
+ findNearestLocalCliEntry,
27
+ resolveLocalCliCandidate,
28
+ shouldDelegateToLocalCli
29
+ } from './commands/utils/LocalCliDelegation.js';
30
+
31
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
32
+
33
+ const loadConfig = () => {
34
+ try {
35
+ const configPath = getConfigPath(import.meta.url);
36
+ const rawData = fs.readFileSync(configPath, "utf-8");
37
+ return JSON.parse(rawData);
38
+ } catch {
39
+ return null;
40
+ }
41
+ };
42
+
43
+ const getCategories = () => {
44
+ const config = loadConfig();
45
+ return config && config.paths?.components ? Object.keys(config.paths.components) : [];
46
+ };
47
+
48
+ // Function to run version check for all commands
49
+ async function runWithVersionCheck(commandFunction, ...args) {
50
+ try {
51
+ const execAsync = promisify(exec);
52
+ await (async () => {
53
+ try {
54
+ const info = await updateManager.detectCliInstall();
55
+ if (info && info.type === 'global') {
56
+ const projectRoot = getProjectRoot(import.meta.url);
57
+ const pkgPath = path.join(projectRoot, 'package.json');
58
+ let hasPkg = fs.existsSync(pkgPath);
59
+ if (!hasPkg) {
60
+ const { confirmInit } = await inquirer.prompt([
61
+ {
62
+ type: 'confirm',
63
+ name: 'confirmInit',
64
+ message: 'No package.json found. Initialize npm in this project now?',
65
+ default: true
66
+ }
67
+ ]);
68
+ if (confirmInit) {
69
+ await execAsync('npm init -y', { cwd: projectRoot });
70
+ hasPkg = true;
71
+ }
72
+ }
73
+ if (hasPkg) {
74
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
75
+ const hasFramework = pkg.dependencies?.['slicejs-web-framework'];
76
+ if (!hasFramework) {
77
+ const { confirm } = await inquirer.prompt([
78
+ {
79
+ type: 'confirm',
80
+ name: 'confirm',
81
+ message: 'slicejs-web-framework is not installed in this project. Install it now?',
82
+ default: true
83
+ }
84
+ ]);
85
+ if (confirm) {
86
+ await updateManager.updatePackage('slicejs-web-framework');
87
+ }
88
+ }
89
+ }
90
+ }
91
+ } catch {}
92
+ })();
93
+
94
+ updateManager.notifyAvailableUpdates().catch(() => {});
95
+
96
+ const result = await commandFunction(...args);
97
+
98
+ setTimeout(() => {
99
+ versionChecker.checkForUpdates(false);
100
+ }, 100);
101
+
102
+ return result;
103
+ } catch (error) {
104
+ Print.error(`Command execution: ${error.message}`);
105
+ return false;
106
+ }
107
+ }
108
+
109
+ function maybeDelegateToLocalCli() {
110
+ if (isLocalDelegationDisabled(process.env)) {
111
+ return;
112
+ }
113
+
114
+ const currentEntryPath = fileURLToPath(import.meta.url);
115
+ const localEntryPath = findNearestLocalCliEntry(process.cwd(), resolveLocalCliCandidate);
116
+
117
+ if (!shouldDelegateToLocalCli(currentEntryPath, localEntryPath)) {
118
+ return;
119
+ }
120
+
121
+ const child = spawnSync(
122
+ process.execPath,
123
+ [localEntryPath, ...process.argv.slice(2)],
124
+ {
125
+ stdio: 'inherit',
126
+ cwd: process.cwd(),
127
+ env: process.env
128
+ }
129
+ );
130
+
131
+ process.exit(child.status ?? 1);
132
+ }
133
+
134
+ maybeDelegateToLocalCli();
135
+
136
+ const sliceClient = program;
137
+
138
+ try {
139
+ const pkgPath = path.join(__dirname, "./package.json");
140
+ const pkgRaw = fs.readFileSync(pkgPath, "utf-8");
141
+ const pkg = JSON.parse(pkgRaw);
142
+ sliceClient.version(pkg.version).description("CLI for managing Slice.js framework components");
143
+ } catch {
144
+ sliceClient.version("0.0.0").description("CLI for managing Slice.js framework components");
145
+ }
146
+
147
+ // INIT COMMAND
148
+ sliceClient
149
+ .command("init")
150
+ .description("Initialize a new Slice.js project")
151
+ .action(async () => {
152
+ await runWithVersionCheck(() => {
153
+ initializeProject();
154
+ return Promise.resolve();
155
+ });
156
+ });
157
+
158
+ // VERSION COMMAND
159
+ sliceClient
160
+ .command("version")
161
+ .alias("v")
162
+ .description("Show version information and check for updates")
163
+ .action(async () => {
164
+ await versionChecker.showVersionInfo();
165
+ });
166
+
167
+ // BUILD COMMAND
168
+ const buildCommand = sliceClient.command("build")
169
+ .description("Build Slice.js project for production")
170
+ .action(async (options) => {
171
+ const prevEnv = process.env.NODE_ENV;
172
+ process.env.NODE_ENV = 'production';
173
+ try {
174
+ await runWithVersionCheck(async () => {
175
+ await build(options);
176
+ });
177
+ } finally {
178
+ process.env.NODE_ENV = prevEnv;
179
+ }
180
+ });
181
+
182
+ buildCommand
183
+ .command("clean")
184
+ .description("Remove all generated bundles")
185
+ .action(async () => {
186
+ await cleanBundles();
187
+ });
188
+
189
+ buildCommand
190
+ .command("info")
191
+ .description("Show information about generated bundles")
192
+ .action(async () => {
193
+ await bundleInfo();
194
+ });
195
+
196
+ buildCommand
197
+ .option("-a, --analyze", "Analyze project dependencies without bundling")
198
+ .option("-v, --verbose", "Show detailed output")
199
+ .option("--no-minify", "Disable minification (enabled by default)")
200
+ .option("--no-obfuscate", "Disable obfuscation (enabled by default, no prop mangling)")
201
+ .option("--preview", "Start preview server after build")
202
+ .option("--serve", "Start preview server without building")
203
+ .option("--skip-clean", "Skip cleaning dist before build");
204
+
205
+ // DEV COMMAND (DEVELOPMENT)
206
+ sliceClient
207
+ .command("dev")
208
+ .description("Start development server with hot reload enabled by default")
209
+ .option("-p, --port <port>", "Port for development server", 3000)
210
+ .option("--no-hmr", "Disable hot module reload (enabled by default)")
211
+ .action(async (options) => {
212
+ const prevEnv = process.env.NODE_ENV;
213
+ process.env.NODE_ENV = 'development';
214
+ try {
215
+ await runWithVersionCheck(async () => {
216
+ await startServer({
217
+ mode: 'development',
218
+ port: parseInt(options.port),
219
+ watch: options.hmr
220
+ });
221
+ });
222
+ } finally {
223
+ process.env.NODE_ENV = prevEnv;
224
+ }
225
+ });
226
+
227
+ // START COMMAND - PRODUCTION MODE
228
+ sliceClient
229
+ .command("start")
230
+ .description("Serve production files from dist/ (requires prior slice build)")
231
+ .option("-p, --port <port>", "Port for server", 3000)
232
+ .action(async (options) => {
233
+ const prevEnv = process.env.NODE_ENV;
234
+ process.env.NODE_ENV = 'production';
235
+ try {
236
+ await runWithVersionCheck(async () => {
237
+ await startServer({
238
+ mode: 'production',
239
+ port: parseInt(options.port)
240
+ });
241
+ });
242
+ } finally {
243
+ process.env.NODE_ENV = prevEnv;
244
+ }
245
+ });
246
+
247
+ // COMPONENT COMMAND GROUP - For local component management
248
+ const componentCommand = sliceClient.command("component").alias("comp").description("Manage local project components");
249
+
250
+ // CREATE LOCAL COMPONENT
251
+ componentCommand
252
+ .command("create [name]")
253
+ .alias("new")
254
+ .description("Create a new component in your local project")
255
+ .option("-c, --category <category>", "Component category (e.g. Visual, Service, AppComponents). Skips the prompt when provided.")
256
+ .action(async (name, options) => {
257
+ await runWithVersionCheck(async () => {
258
+ const categories = getCategories();
259
+ if (categories.length === 0) {
260
+ Print.error("No categories found in your project configuration");
261
+ Print.info("Run 'slice init' to initialize your project first");
262
+ Print.commandExample("Initialize project", "slice init");
263
+ return;
264
+ }
265
+
266
+ let componentName = name;
267
+ let category = options.category;
268
+
269
+ // Prompt only for the values not supplied on the command line. Passing both
270
+ // a name and --category runs fully non-interactively (handy for scripts/agents).
271
+ const prompts = [];
272
+ if (!componentName) {
273
+ prompts.push({
274
+ type: "input",
275
+ name: "componentName",
276
+ message: "Enter the component name:",
277
+ validate: (input) => {
278
+ if (!input) return "Component name cannot be empty";
279
+ if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(input)) {
280
+ return "Component name must start with a letter and contain only alphanumeric characters";
281
+ }
282
+ return true;
283
+ },
284
+ });
285
+ }
286
+ if (!category) {
287
+ prompts.push({
288
+ type: "list",
289
+ name: "category",
290
+ message: "Select the component category:",
291
+ choices: categories,
292
+ });
293
+ }
294
+
295
+ if (prompts.length > 0) {
296
+ const answers = await inquirer.prompt(prompts);
297
+ componentName = componentName ?? answers.componentName;
298
+ category = category ?? answers.category;
299
+ }
300
+
301
+ // createComponent validates the name and the category (and reports a clear
302
+ // error listing valid categories if --category is wrong).
303
+ const result = createComponent(componentName, category);
304
+ if (result) {
305
+ Print.success(`Component '${componentName}' created successfully in category '${category}'`);
306
+ Print.info("Listing updated components:");
307
+ listComponents();
308
+ }
309
+ });
310
+ });
311
+
312
+ // LIST LOCAL COMPONENTS
313
+ componentCommand
314
+ .command("list")
315
+ .alias("ls")
316
+ .description("List all components in your local project")
317
+ .action(async () => {
318
+ await runWithVersionCheck(() => {
319
+ listComponents();
320
+ return Promise.resolve();
321
+ });
322
+ });
323
+
324
+ // DELETE LOCAL COMPONENT
325
+ componentCommand
326
+ .command("delete [name]")
327
+ .alias("remove")
328
+ .description("Delete a component from your local project")
329
+ .option("-c, --category <category>", "Component category. Skips the category prompt when provided.")
330
+ .option("-y, --yes", "Skip the confirmation prompt (for non-interactive use)")
331
+ .action(async (name, options) => {
332
+ await runWithVersionCheck(async () => {
333
+ const categories = getCategories();
334
+ if (categories.length === 0) {
335
+ Print.error("No categories available. Check your configuration");
336
+ Print.info("Run 'slice init' to initialize your project");
337
+ return;
338
+ }
339
+
340
+ try {
341
+ let category = options.category;
342
+ let componentName = name;
343
+
344
+ // Resolve category (prompt only if not provided)
345
+ if (!category) {
346
+ const categoryAnswer = await inquirer.prompt([
347
+ {
348
+ type: "list",
349
+ name: "category",
350
+ message: "Select the component category:",
351
+ choices: categories,
352
+ }
353
+ ]);
354
+ category = categoryAnswer.category;
355
+ }
356
+
357
+ const config = loadConfig();
358
+ if (!config) {
359
+ Print.error("Could not load configuration");
360
+ return;
361
+ }
362
+
363
+ if (!config.paths.components[category]) {
364
+ Print.error(`Invalid category: '${category}'`);
365
+ Print.info(`Available categories: ${categories.join(", ")}`);
366
+ return;
367
+ }
368
+
369
+ const categoryPath = config.paths.components[category].path;
370
+ const fullPath = path.join(__dirname, "../../src", categoryPath);
371
+
372
+ if (!fs.existsSync(fullPath)) {
373
+ Print.error(`Category path does not exist: ${categoryPath}`);
374
+ return;
375
+ }
376
+
377
+ // Resolve component name (prompt with a list only if not provided)
378
+ if (!componentName) {
379
+ const components = fs.readdirSync(fullPath).filter(item => {
380
+ const itemPath = path.join(fullPath, item);
381
+ return fs.statSync(itemPath).isDirectory();
382
+ });
383
+
384
+ if (components.length === 0) {
385
+ Print.info(`No components found in category '${category}'`);
386
+ return;
387
+ }
388
+
389
+ const componentAnswer = await inquirer.prompt([
390
+ {
391
+ type: "list",
392
+ name: "componentName",
393
+ message: "Select the component to delete:",
394
+ choices: components,
395
+ }
396
+ ]);
397
+ componentName = componentAnswer.componentName;
398
+ }
399
+
400
+ // Confirm unless --yes was passed (passing name + --category + --yes is fully non-interactive)
401
+ if (!options.yes) {
402
+ const { confirm } = await inquirer.prompt([
403
+ {
404
+ type: "confirm",
405
+ name: "confirm",
406
+ message: `Are you sure you want to delete '${componentName}' from '${category}'?`,
407
+ default: false,
408
+ }
409
+ ]);
410
+ if (!confirm) {
411
+ Print.info("Delete operation cancelled");
412
+ return;
413
+ }
414
+ }
415
+
416
+ // deleteComponent validates the name/category and that the component exists.
417
+ if (deleteComponent(componentName, category)) {
418
+ Print.success(`Component ${componentName} deleted successfully`);
419
+ Print.info("Listing updated components:");
420
+ listComponents();
421
+ }
422
+ } catch (error) {
423
+ Print.error(`Deleting component: ${error.message}`);
424
+ }
425
+ });
426
+ });
427
+
428
+ // REGISTRY COMMAND GROUP - For component registry operations
391
429
  const registryCommand = sliceClient.command("registry").alias("reg").description("Manage components from official Slice.js repository");
392
430
 
393
431
  // TYPES COMMAND GROUP - TypeScript declarations from static props
@@ -410,248 +448,248 @@ typesCommand
410
448
  });
411
449
  });
412
450
  });
413
-
414
- // GET COMPONENTS FROM REGISTRY
415
- registryCommand
416
- .command("get [components...]")
417
- .description("Download and install components from official repository")
418
- .option("-f, --force", "Force overwrite existing components")
419
- .option("-s, --service", "Install Service components instead of Visual")
420
- .action(async (components, options) => {
421
- await runWithVersionCheck(async () => {
422
- await getComponent(components, {
423
- force: options.force,
424
- service: options.service
425
- });
426
- });
427
- });
428
-
429
- // LIST REGISTRY COMPONENTS
430
- registryCommand
431
- .command("list")
432
- .alias("ls")
433
- .description("List all available components in the official repository")
434
- .action(async () => {
435
- await runWithVersionCheck(async () => {
436
- await listRemoteComponents();
437
- });
438
- });
439
-
440
- // SYNC COMPONENTS FROM REGISTRY
441
- registryCommand
442
- .command("sync")
443
- .description("Update all local components to latest versions from repository")
444
- .option("-f, --force", "Force update without confirmation")
445
- .action(async (options) => {
446
- await runWithVersionCheck(async () => {
447
- await syncComponents({
448
- force: options.force
449
- });
450
- });
451
- });
452
-
453
- // SHORTCUTS - Top-level convenient commands
454
- sliceClient
455
- .command("get [components...]")
456
- .description("Quick install components from registry")
457
- .option("-f, --force", "Force overwrite existing components")
458
- .option("-s, --service", "Install Service components instead of Visual")
459
- .action(async (components, options) => {
460
- await runWithVersionCheck(async () => {
461
- if (!components || components.length === 0) {
462
- Print.info("Use 'slice registry list' to see available components");
463
- Print.commandExample("Get multiple components", "slice get Button Card Input");
464
- Print.commandExample("Get service component", "slice get FetchManager --service");
465
- Print.commandExample("Browse components", "slice browse");
466
- return;
467
- }
468
-
469
- await getComponent(components, {
470
- force: options.force,
471
- service: options.service
472
- });
473
- });
474
- });
475
-
476
- sliceClient
477
- .command("browse")
478
- .description("Quick browse available components")
479
- .action(async () => {
480
- await runWithVersionCheck(async () => {
481
- await listRemoteComponents();
482
- });
483
- });
484
-
485
- sliceClient
486
- .command("sync")
487
- .description("Quick sync local components to latest versions")
488
- .option("-f, --force", "Force update without confirmation")
489
- .action(async (options) => {
490
- await runWithVersionCheck(async () => {
491
- await syncComponents({
492
- force: options.force
493
- });
494
- });
495
- });
496
-
497
- // LIST COMMAND - Quick shortcut for listing local components
498
- sliceClient
499
- .command("list")
500
- .description("Quick list all local components (alias for component list)")
501
- .action(async () => {
502
- await runWithVersionCheck(() => {
503
- listComponents();
504
- return Promise.resolve();
505
- });
506
- });
507
-
508
- // UPDATE COMMAND
509
- sliceClient
510
- .command("update")
511
- .alias("upgrade")
512
- .description("Update CLI and framework to latest versions")
513
- .option("-y, --yes", "Skip confirmation and update all packages automatically")
514
- .option("--cli", "Update only the Slice.js CLI")
515
- .option("-f, --framework", "Update only the Slice.js Framework")
516
- .action(async (options) => {
517
- await updateManager.checkAndPromptUpdates(options);
518
- });
519
-
520
- // DOCTOR COMMAND - Diagnose project issues
521
- sliceClient
522
- .command("doctor")
523
- .alias("diagnose")
524
- .description("Run diagnostics to check project health")
525
- .action(async () => {
526
- await runWithVersionCheck(async () => {
527
- await runDiagnostics();
528
- });
529
- });
530
-
531
- // POSTINSTALL COMMAND - Manual alternative to postinstall
532
- sliceClient
533
- .command("postinstall")
534
- .description("Configure npm scripts in package.json (alternative to postinstall for --ignore-scripts users)")
535
- .action(() => {
536
- const isGlobal = process.env.npm_config_global === 'true';
537
- if (isGlobal) {
538
- console.log('⚠️ Global installation of slicejs-cli detected.');
539
- console.log(' We strongly recommend using a local installation to avoid version mismatches.');
540
- console.log(' Uninstall global: npm uninstall -g slicejs-cli');
541
- return;
542
- }
543
-
544
- const projectRoot = getProjectRoot(import.meta.url);
545
- const pkgPath = path.join(projectRoot, 'package.json');
546
-
547
- const sliceScripts = {
548
- 'slice:dev': 'slice dev',
549
- 'slice:start': 'slice start',
550
- 'slice:create': 'slice component create',
551
- 'slice:list': 'slice component list',
552
- 'slice:delete': 'slice component delete',
553
- 'slice:init': 'slice init',
554
- 'slice:get': 'slice get',
555
- 'slice:browse': 'slice browse',
556
- 'slice:sync': 'slice sync',
557
- 'slice:version': 'slice version',
558
- 'slice:update': 'slice update',
559
- };
560
-
561
- try {
562
- let pkg = {};
563
- if (fs.existsSync(pkgPath)) {
564
- pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
565
- } else {
566
- pkg = {
567
- name: path.basename(projectRoot),
568
- version: '1.0.0',
569
- description: 'Slice.js project',
570
- scripts: {}
571
- };
572
- }
573
-
574
- pkg.scripts = pkg.scripts || {};
575
- let addedCount = 0;
576
- for (const [script, command] of Object.entries(sliceScripts)) {
577
- if (!pkg.scripts[script]) {
578
- pkg.scripts[script] = command;
579
- addedCount++;
580
- }
581
- }
582
-
583
- fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2), 'utf-8');
584
- console.log(`✅ slicejs-cli installed successfully. Added ${addedCount} npm scripts to package.json.`);
585
- console.log(' Run: npm run slice:dev');
586
- } catch (err) {
587
- console.log('✅ slicejs-cli installed successfully.');
588
- console.log(' Could not auto-configure scripts:', err.message);
589
- console.log(' Run: npx slice dev');
590
- }
591
- });
592
-
593
- // Enhanced help
594
- sliceClient
595
- .option("--no-version-check", "Skip version check for this command")
596
- .configureHelp({
597
- sortSubcommands: true,
598
- subcommandTerm: (cmd) => cmd.name() + ' ' + cmd.usage()
599
- });
600
-
601
-
602
- // Custom help - SIMPLIFICADO para development only
603
- sliceClient.addHelpText('after', `
604
- Common Usage Examples:
605
- slice init - Initialize new Slice.js project
606
- slice dev - Start development server
607
- slice build - Build production output (bundles + dist)
608
- slice start - Start production server
609
- slice get Button Card Input - Install Visual components from registry
610
- slice get FetchManager -s - Install Service component from registry
611
- slice browse - Browse all available components
612
- slice sync - Update local components to latest versions
613
- slice component create - Create new local component
614
- slice list - List all local components
615
- slice doctor - Run project diagnostics
616
- slice types generate - Generate TypeScript typings for slice.build
451
+
452
+ // GET COMPONENTS FROM REGISTRY
453
+ registryCommand
454
+ .command("get [components...]")
455
+ .description("Download and install components from official repository")
456
+ .option("-f, --force", "Force overwrite existing components")
457
+ .option("-s, --service", "Install Service components instead of Visual")
458
+ .action(async (components, options) => {
459
+ await runWithVersionCheck(async () => {
460
+ await getComponent(components, {
461
+ force: options.force,
462
+ service: options.service
463
+ });
464
+ });
465
+ });
466
+
467
+ // LIST REGISTRY COMPONENTS
468
+ registryCommand
469
+ .command("list")
470
+ .alias("ls")
471
+ .description("List all available components in the official repository")
472
+ .action(async () => {
473
+ await runWithVersionCheck(async () => {
474
+ await listRemoteComponents();
475
+ });
476
+ });
477
+
478
+ // SYNC COMPONENTS FROM REGISTRY
479
+ registryCommand
480
+ .command("sync")
481
+ .description("Update all local components to latest versions from repository")
482
+ .option("-f, --force", "Force update without confirmation")
483
+ .action(async (options) => {
484
+ await runWithVersionCheck(async () => {
485
+ await syncComponents({
486
+ force: options.force
487
+ });
488
+ });
489
+ });
490
+
491
+ // SHORTCUTS - Top-level convenient commands
492
+ sliceClient
493
+ .command("get [components...]")
494
+ .description("Quick install components from registry")
495
+ .option("-f, --force", "Force overwrite existing components")
496
+ .option("-s, --service", "Install Service components instead of Visual")
497
+ .action(async (components, options) => {
498
+ await runWithVersionCheck(async () => {
499
+ if (!components || components.length === 0) {
500
+ Print.info("Use 'slice registry list' to see available components");
501
+ Print.commandExample("Get multiple components", "slice get Button Card Input");
502
+ Print.commandExample("Get service component", "slice get FetchManager --service");
503
+ Print.commandExample("Browse components", "slice browse");
504
+ return;
505
+ }
506
+
507
+ await getComponent(components, {
508
+ force: options.force,
509
+ service: options.service
510
+ });
511
+ });
512
+ });
513
+
514
+ sliceClient
515
+ .command("browse")
516
+ .description("Quick browse available components")
517
+ .action(async () => {
518
+ await runWithVersionCheck(async () => {
519
+ await listRemoteComponents();
520
+ });
521
+ });
522
+
523
+ sliceClient
524
+ .command("sync")
525
+ .description("Quick sync local components to latest versions")
526
+ .option("-f, --force", "Force update without confirmation")
527
+ .action(async (options) => {
528
+ await runWithVersionCheck(async () => {
529
+ await syncComponents({
530
+ force: options.force
531
+ });
532
+ });
533
+ });
534
+
535
+ // LIST COMMAND - Quick shortcut for listing local components
536
+ sliceClient
537
+ .command("list")
538
+ .description("Quick list all local components (alias for component list)")
539
+ .action(async () => {
540
+ await runWithVersionCheck(() => {
541
+ listComponents();
542
+ return Promise.resolve();
543
+ });
544
+ });
545
+
546
+ // UPDATE COMMAND
547
+ sliceClient
548
+ .command("update")
549
+ .alias("upgrade")
550
+ .description("Update CLI and framework to latest versions")
551
+ .option("-y, --yes", "Skip confirmation and update all packages automatically")
552
+ .option("--cli", "Update only the Slice.js CLI")
553
+ .option("-f, --framework", "Update only the Slice.js Framework")
554
+ .action(async (options) => {
555
+ await updateManager.checkAndPromptUpdates(options);
556
+ });
557
+
558
+ // DOCTOR COMMAND - Diagnose project issues
559
+ sliceClient
560
+ .command("doctor")
561
+ .alias("diagnose")
562
+ .description("Run diagnostics to check project health")
563
+ .action(async () => {
564
+ await runWithVersionCheck(async () => {
565
+ await runDiagnostics();
566
+ });
567
+ });
568
+
569
+ // POSTINSTALL COMMAND - Manual alternative to postinstall
570
+ sliceClient
571
+ .command("postinstall")
572
+ .description("Configure npm scripts in package.json (alternative to postinstall for --ignore-scripts users)")
573
+ .action(() => {
574
+ const isGlobal = process.env.npm_config_global === 'true';
575
+ if (isGlobal) {
576
+ console.log('⚠️ Global installation of slicejs-cli detected.');
577
+ console.log(' We strongly recommend using a local installation to avoid version mismatches.');
578
+ console.log(' Uninstall global: npm uninstall -g slicejs-cli');
579
+ return;
580
+ }
581
+
582
+ const projectRoot = getProjectRoot(import.meta.url);
583
+ const pkgPath = path.join(projectRoot, 'package.json');
584
+
585
+ const sliceScripts = {
586
+ 'slice:dev': 'slice dev',
587
+ 'slice:start': 'slice start',
588
+ 'slice:create': 'slice component create',
589
+ 'slice:list': 'slice component list',
590
+ 'slice:delete': 'slice component delete',
591
+ 'slice:init': 'slice init',
592
+ 'slice:get': 'slice get',
593
+ 'slice:browse': 'slice browse',
594
+ 'slice:sync': 'slice sync',
595
+ 'slice:version': 'slice version',
596
+ 'slice:update': 'slice update',
597
+ };
598
+
599
+ try {
600
+ let pkg = {};
601
+ if (fs.existsSync(pkgPath)) {
602
+ pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
603
+ } else {
604
+ pkg = {
605
+ name: path.basename(projectRoot),
606
+ version: '1.0.0',
607
+ description: 'Slice.js project',
608
+ scripts: {}
609
+ };
610
+ }
611
+
612
+ pkg.scripts = pkg.scripts || {};
613
+ let addedCount = 0;
614
+ for (const [script, command] of Object.entries(sliceScripts)) {
615
+ if (!pkg.scripts[script]) {
616
+ pkg.scripts[script] = command;
617
+ addedCount++;
618
+ }
619
+ }
620
+
621
+ fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2), 'utf-8');
622
+ console.log(`✅ slicejs-cli installed successfully. Added ${addedCount} npm scripts to package.json.`);
623
+ console.log(' Run: npm run slice:dev');
624
+ } catch (err) {
625
+ console.log('✅ slicejs-cli installed successfully.');
626
+ console.log(' Could not auto-configure scripts:', err.message);
627
+ console.log(' Run: npx slice dev');
628
+ }
629
+ });
630
+
631
+ // Enhanced help
632
+ sliceClient
633
+ .option("--no-version-check", "Skip version check for this command")
634
+ .configureHelp({
635
+ sortSubcommands: true,
636
+ subcommandTerm: (cmd) => cmd.name() + ' ' + cmd.usage()
637
+ });
638
+
639
+
640
+ // Custom help - SIMPLIFICADO para development only
641
+ sliceClient.addHelpText('after', `
642
+ Common Usage Examples:
643
+ slice init - Initialize new Slice.js project
644
+ slice dev - Start development server
645
+ slice build - Build production output (bundles + dist)
646
+ slice start - Start production server
647
+ slice get Button Card Input - Install Visual components from registry
648
+ slice get FetchManager -s - Install Service component from registry
649
+ slice browse - Browse all available components
650
+ slice sync - Update local components to latest versions
651
+ slice component create - Create new local component
652
+ slice list - List all local components
653
+ slice doctor - Run project diagnostics
654
+ slice types generate - Generate TypeScript typings for slice.build
617
655
  slice postinstall - Show post-install setup guide
618
-
619
- Command Categories:
620
- • init, dev, start - Project lifecycle (development only)
621
- • get, browse, sync, list - Quick shortcuts
656
+
657
+ Command Categories:
658
+ • init, dev, start - Project lifecycle (development only)
659
+ • get, browse, sync, list - Quick shortcuts
622
660
  • component <cmd> - Local component management
623
661
  • registry <cmd> - Official repository operations
624
662
  • types generate - Type declarations from static props
625
663
  • version, update, doctor, setup - Maintenance commands
626
-
627
- Development Workflow:
628
- • slice init - Initialize project
629
- • slice dev - Start development server (serves from /src)
630
- • slice build - Build production output to /dist (includes bundles)
631
- • slice start - Serve production build from /dist
632
-
633
- More info: https://slice-js-docs.vercel.app/
634
- `);
635
-
636
- // Default action with better messaging
637
- if (!process.argv.slice(2).length) {
638
- Print.newLine();
639
- Print.info("Start with: slice init");
640
- Print.commandExample("Development", "slice dev");
641
- Print.commandExample("View available components", "slice browse");
642
- Print.info("Use 'slice --help' for full help");
643
- }
644
-
645
- // Error handling for unknown commands
646
- program.on('command:*', () => {
647
- Print.error('Invalid command. See available commands above');
648
- Print.info("Use 'slice --help' for help");
649
- process.exit(1);
650
- });
651
-
652
- // HELP Command
653
- const helpCommand = sliceClient.command("help").description("Display help information for Slice.js CLI").action(() => {
654
- sliceClient.outputHelp();
655
- });
656
-
657
- program.parse();
664
+
665
+ Development Workflow:
666
+ • slice init - Initialize project
667
+ • slice dev - Start development server (serves from /src)
668
+ • slice build - Build production output to /dist (includes bundles)
669
+ • slice start - Serve production build from /dist
670
+
671
+ More info: https://slice-js-docs.vercel.app/
672
+ `);
673
+
674
+ // Default action with better messaging
675
+ if (!process.argv.slice(2).length) {
676
+ Print.newLine();
677
+ Print.info("Start with: slice init");
678
+ Print.commandExample("Development", "slice dev");
679
+ Print.commandExample("View available components", "slice browse");
680
+ Print.info("Use 'slice --help' for full help");
681
+ }
682
+
683
+ // Error handling for unknown commands
684
+ program.on('command:*', () => {
685
+ Print.error('Invalid command. See available commands above');
686
+ Print.info("Use 'slice --help' for help");
687
+ process.exit(1);
688
+ });
689
+
690
+ // HELP Command
691
+ const helpCommand = sliceClient.command("help").description("Display help information for Slice.js CLI").action(() => {
692
+ sliceClient.outputHelp();
693
+ });
694
+
695
+ program.parse();