slicejs-cli 4.2.0 → 4.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 (49) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +260 -257
  3. package/client.js +927 -780
  4. package/commands/Print.js +163 -163
  5. package/commands/Validations.js +92 -92
  6. package/commands/build/build.js +97 -107
  7. package/commands/buildProduction/buildProduction.js +613 -613
  8. package/commands/bundle/bundle.js +251 -239
  9. package/commands/createComponent/VisualComponentTemplate.js +55 -55
  10. package/commands/createComponent/createComponent.js +128 -128
  11. package/commands/deleteComponent/deleteComponent.js +81 -81
  12. package/commands/docs/docs.js +365 -0
  13. package/commands/doctor/doctor.js +677 -563
  14. package/commands/getComponent/getComponent.js +842 -842
  15. package/commands/init/init.js +526 -475
  16. package/commands/lint/lint.js +75 -0
  17. package/commands/lint/types.js +85 -0
  18. package/commands/listComponents/listComponents.js +172 -172
  19. package/commands/seo/check.js +91 -0
  20. package/commands/seo/images.js +586 -0
  21. package/commands/seo/sitemap.js +106 -0
  22. package/commands/seo/support.js +130 -0
  23. package/commands/setup/lint.js +151 -0
  24. package/commands/skill/skill.js +236 -236
  25. package/commands/startServer/startServer.js +240 -240
  26. package/commands/startServer/watchServer.js +66 -66
  27. package/commands/typecheck/typecheck.js +83 -0
  28. package/commands/types/types.js +1378 -1097
  29. package/commands/utils/JsMinifier.js +230 -230
  30. package/commands/utils/LocalCliDelegation.js +78 -53
  31. package/commands/utils/PackageManager.js +148 -148
  32. package/commands/utils/PathHelper.js +87 -75
  33. package/commands/utils/ProjectValidation.js +274 -0
  34. package/commands/utils/SourceDiagnostics.js +201 -201
  35. package/commands/utils/VersionChecker.js +169 -169
  36. package/commands/utils/analyzeSource.js +77 -77
  37. package/commands/utils/bundling/BundleGenerator.js +3748 -3776
  38. package/commands/utils/bundling/DependencyAnalyzer.js +976 -976
  39. package/commands/utils/bundling/ExternalModuleBundler.js +298 -298
  40. package/commands/utils/componentAudit.js +74 -0
  41. package/commands/utils/compressAssets.js +103 -103
  42. package/commands/utils/cssScope.js +83 -0
  43. package/commands/utils/loadConfig.js +31 -31
  44. package/commands/utils/semver.js +66 -0
  45. package/commands/utils/sliceConfigSchema.js +72 -0
  46. package/commands/utils/sliceScripts.js +48 -48
  47. package/commands/utils/updateManager.js +471 -471
  48. package/eslint-config.js +128 -0
  49. package/package.json +19 -13
package/client.js CHANGED
@@ -1,798 +1,945 @@
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 { addSkill, statusSkill, updateSkill } from "./commands/skill/skill.js";
10
- import startServer from "./commands/startServer/startServer.js";
11
- import runDiagnostics from "./commands/doctor/doctor.js";
12
- import versionChecker from "./commands/utils/VersionChecker.js";
13
- import updateManager from "./commands/utils/updateManager.js";
14
- import fs from "fs";
15
- import path from "path";
16
- import { fileURLToPath } from "url";
17
- import { getProjectRoot, getSrcPath, getPath } from "./commands/utils/PathHelper.js";
18
- import { loadConfigSync as sharedLoadConfigSync } from "./commands/utils/loadConfig.js";
19
- import { spawnSync } from "node:child_process";
20
- import validations from "./commands/Validations.js";
21
- import Print from "./commands/Print.js";
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 { addSkill, statusSkill, updateSkill } from "./commands/skill/skill.js";
10
+ import startServer from "./commands/startServer/startServer.js";
11
+ import runDiagnostics from "./commands/doctor/doctor.js";
12
+ import seoCheck from "./commands/seo/check.js";
13
+ import seoSitemap from "./commands/seo/sitemap.js";
14
+ import seoImages from "./commands/seo/images.js";
15
+ import versionChecker from "./commands/utils/VersionChecker.js";
16
+ import updateManager from "./commands/utils/updateManager.js";
17
+ import fs from "fs";
18
+ import path from "path";
19
+ import { fileURLToPath } from "url";
20
+ import { getProjectRoot, getSrcPath, getPath } from "./commands/utils/PathHelper.js";
21
+ import { loadConfigSync as sharedLoadConfigSync } from "./commands/utils/loadConfig.js";
22
+ import { spawnSync } from "node:child_process";
23
+ import validations from "./commands/Validations.js";
24
+ import Print from "./commands/Print.js";
22
25
  import build from './commands/build/build.js';
23
- import { runGenerateTypes } from './commands/types/types.js';
24
- import { cleanBundles, bundleInfo } from './commands/bundle/bundle.js';
25
- import {
26
- isLocalDelegationDisabled,
27
- findNearestLocalCliEntry,
28
- resolveLocalCliCandidate,
29
- shouldDelegateToLocalCli
30
- } from './commands/utils/LocalCliDelegation.js';
31
- import {
32
- detectPackageManager,
33
- getAvailablePackageManagers,
34
- isPackageManagerAvailable,
35
- resolvePackageManager,
36
- runScriptCommand,
37
- SUPPORTED_PACKAGE_MANAGERS
38
- } from './commands/utils/PackageManager.js';
39
- import { SLICE_SCRIPTS, verifySliceScriptsInPackageJson } from './commands/utils/sliceScripts.js';
40
-
41
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
42
-
43
- const getCategories = () => {
44
- const config = sharedLoadConfigSync(import.meta.url);
45
- return config && config.paths?.components ? Object.keys(config.paths.components) : [];
46
- };
47
-
48
- // Helper to validate port number
49
- function parsePort(value) {
50
- if (!value) return undefined;
51
- const port = parseInt(value, 10);
52
- if (isNaN(port) || port < 1 || port > 65535) {
53
- Print.error(`Invalid port: "${value}". Must be a number between 1 and 65535.`);
54
- process.exit(1);
55
- }
56
- return port;
57
- }
58
-
59
- async function withNodeEnv(env, fn) {
60
- const prevEnv = process.env.NODE_ENV;
61
- process.env.NODE_ENV = env;
62
- listComponents();
63
- try {
64
- return await fn();
65
- } finally {
66
- process.env.NODE_ENV = prevEnv;
67
- }
68
- }
69
-
70
- // Function to run version check for all commands
71
- async function runWithVersionCheck(commandFunction, ...args) {
72
- try {
73
- const globalOpts = program.opts();
74
- const skipVersionCheck = globalOpts.noVersionCheck === false;
75
-
76
- if (!skipVersionCheck) {
77
- updateManager.notifyAvailableUpdates().catch(() => {});
78
- }
79
-
80
- const result = await commandFunction(...args);
81
-
82
- if (!skipVersionCheck) {
83
- setTimeout(() => {
84
- versionChecker.checkForUpdates(false);
85
- }, 100);
86
- }
87
-
88
- return result;
89
- } catch (error) {
90
- Print.error(`Command execution: ${error.message}`);
91
- console.error(error.stack);
92
- // A command that threw must not report success. This used to swallow the
93
- // error and return normally, so `slice build` printed a red failure and
94
- // still exited 0 — CI read that as a passing build and shipped it.
95
- // process.exitCode (not process.exit) lets buffered output flush first.
96
- process.exitCode = 1;
97
- return false;
98
- }
99
- }
100
-
101
- function maybeDelegateToLocalCli() {
102
- if (isLocalDelegationDisabled(process.env)) {
103
- return;
104
- }
105
-
106
- const currentEntryPath = fileURLToPath(import.meta.url);
107
- const localEntryPath = findNearestLocalCliEntry(process.cwd(), resolveLocalCliCandidate);
108
-
109
- if (!shouldDelegateToLocalCli(currentEntryPath, localEntryPath)) {
110
- return;
111
- }
112
-
113
- const child = spawnSync(
114
- process.execPath,
115
- [localEntryPath, ...process.argv.slice(2)],
116
- {
117
- stdio: 'inherit',
118
- cwd: process.cwd(),
119
- env: { ...process.env, SLICE_NO_LOCAL_DELEGATION: '1' }
120
- }
121
- );
122
-
123
- process.exit(child.status ?? 1);
124
- }
125
-
126
- maybeDelegateToLocalCli();
127
-
128
- const sliceClient = program;
129
-
130
- try {
131
- const pkgPath = path.join(__dirname, "./package.json");
132
- const pkgRaw = fs.readFileSync(pkgPath, "utf-8");
133
- const pkg = JSON.parse(pkgRaw);
134
- sliceClient.version(pkg.version).description("CLI for managing Slice.js framework components");
135
- } catch {
136
- sliceClient.version("0.0.0").description("CLI for managing Slice.js framework components");
137
- }
138
-
139
- // INIT COMMAND
26
+ import lintCommand from './commands/lint/lint.js';
27
+ import typecheckCommand from './commands/typecheck/typecheck.js';
28
+ import setupLintCommand from './commands/setup/lint.js';
29
+ import { runGenerateTypes } from './commands/types/types.js';
30
+ import { runDocsGet, runDocsList, runDocsSearch } from './commands/docs/docs.js';
31
+ import { cleanBundles, bundleInfo } from './commands/bundle/bundle.js';
32
+ import {
33
+ isLocalDelegationDisabled,
34
+ isNonDelegatingCommand,
35
+ findNearestLocalCliEntry,
36
+ resolveLocalCliCandidate,
37
+ shouldDelegateToLocalCli
38
+ } from './commands/utils/LocalCliDelegation.js';
39
+ import {
40
+ detectPackageManager,
41
+ getAvailablePackageManagers,
42
+ isPackageManagerAvailable,
43
+ resolvePackageManager,
44
+ runScriptCommand,
45
+ SUPPORTED_PACKAGE_MANAGERS
46
+ } from './commands/utils/PackageManager.js';
47
+ import { SLICE_SCRIPTS, verifySliceScriptsInPackageJson } from './commands/utils/sliceScripts.js';
48
+
49
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
50
+
51
+ const getCategories = () => {
52
+ const config = sharedLoadConfigSync(import.meta.url);
53
+ return config && config.paths?.components ? Object.keys(config.paths.components) : [];
54
+ };
55
+
56
+ // Helper to validate port number
57
+ function parsePort(value) {
58
+ if (!value) return undefined;
59
+ const port = parseInt(value, 10);
60
+ if (isNaN(port) || port < 1 || port > 65535) {
61
+ Print.error(`Invalid port: "${value}". Must be a number between 1 and 65535.`);
62
+ process.exit(1);
63
+ }
64
+ return port;
65
+ }
66
+
67
+ async function withNodeEnv(env, fn) {
68
+ const prevEnv = process.env.NODE_ENV;
69
+ process.env.NODE_ENV = env;
70
+ listComponents();
71
+ try {
72
+ return await fn();
73
+ } finally {
74
+ process.env.NODE_ENV = prevEnv;
75
+ }
76
+ }
77
+
78
+ // Function to run version check for all commands
79
+ async function runWithVersionCheck(commandFunction, ...args) {
80
+ try {
81
+ const globalOpts = program.opts();
82
+ // Commander stores a negated `--no-version-check` option as `versionCheck`.
83
+ // Keep the old property check for compatibility with callers that construct
84
+ // program options directly.
85
+ const skipVersionCheck = globalOpts.versionCheck === false || globalOpts.noVersionCheck === false;
86
+
87
+ if (!skipVersionCheck) {
88
+ updateManager.notifyAvailableUpdates().catch(() => {});
89
+ }
90
+
91
+ const result = await commandFunction(...args);
92
+
93
+ if (!skipVersionCheck) {
94
+ setTimeout(() => {
95
+ versionChecker.checkForUpdates(false);
96
+ }, 100);
97
+ }
98
+
99
+ return result;
100
+ } catch (error) {
101
+ Print.error(`Command execution: ${error.message}`);
102
+ console.error(error.stack);
103
+ // A command that threw must not report success. This used to swallow the
104
+ // error and return normally, so `slice build` printed a red failure and
105
+ // still exited 0 — CI read that as a passing build and shipped it.
106
+ // process.exitCode (not process.exit) lets buffered output flush first.
107
+ process.exitCode = 1;
108
+ return false;
109
+ }
110
+ }
111
+
112
+ function maybeDelegateToLocalCli() {
113
+ if (isLocalDelegationDisabled(process.env)) {
114
+ return;
115
+ }
116
+
117
+ // `init` must run on the CLI the user invoked (a global install, `npx`,
118
+ // `pnpm dlx slicejs-cli@latest`). Delegating to a copy found by walking up
119
+ // from the current folder would scaffold with an unrelated project's
120
+ // version, and a version that cannot install the framework fails halfway
121
+ // while still walking the success path.
122
+ if (isNonDelegatingCommand(process.argv.slice(2))) {
123
+ return;
124
+ }
125
+
126
+ const currentEntryPath = fileURLToPath(import.meta.url);
127
+ const localEntryPath = findNearestLocalCliEntry(process.cwd(), resolveLocalCliCandidate);
128
+
129
+ if (!shouldDelegateToLocalCli(currentEntryPath, localEntryPath)) {
130
+ return;
131
+ }
132
+
133
+ const child = spawnSync(
134
+ process.execPath,
135
+ [localEntryPath, ...process.argv.slice(2)],
136
+ {
137
+ stdio: 'inherit',
138
+ cwd: process.cwd(),
139
+ env: { ...process.env, SLICE_NO_LOCAL_DELEGATION: '1' }
140
+ }
141
+ );
142
+
143
+ process.exit(child.status ?? 1);
144
+ }
145
+
146
+ maybeDelegateToLocalCli();
147
+
148
+ const sliceClient = program;
149
+
150
+ try {
151
+ const pkgPath = path.join(__dirname, "./package.json");
152
+ const pkgRaw = fs.readFileSync(pkgPath, "utf-8");
153
+ const pkg = JSON.parse(pkgRaw);
154
+ sliceClient.version(pkg.version).description("CLI for managing Slice.js framework components");
155
+ } catch {
156
+ sliceClient.version("0.0.0").description("CLI for managing Slice.js framework components");
157
+ }
158
+
159
+ // INIT COMMAND
160
+ sliceClient
161
+ .command("init")
162
+ .description("Initialize a new Slice.js project")
163
+ .argument("[name]", "Project name (defaults to my-slice-app)")
164
+ .option("-y, --yes", "Skip prompts")
165
+ .option("--pm <packageManager>", "Package manager to use (pnpm or npm). Auto-detected when omitted")
166
+ .action(async (name, options) => {
167
+ let projectName = name ? name.trim().toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '').replace(/-+/g, '-').replace(/^-|-$/g, '') : 'my-slice-app';
168
+ if (!options.yes) {
169
+ const answers = await inquirer.prompt([
170
+ {
171
+ type: 'input',
172
+ name: 'projectName',
173
+ message: 'What is the name of your project?',
174
+ default: projectName,
175
+ filter: (input) => input.trim()
176
+ .toLowerCase()
177
+ .replace(/\s+/g, '-')
178
+ .replace(/[^a-z0-9-]/g, '')
179
+ .replace(/-+/g, '-')
180
+ .replace(/^-|-$/g, ''),
181
+ validate: (input) => {
182
+ if (!input || !input.trim()) return 'Project name cannot be empty';
183
+ if (input.includes('/') || input.includes('\\')) return 'Use a simple name, not a path';
184
+ return true;
185
+ }
186
+ }
187
+ ]);
188
+ projectName = answers.projectName;
189
+ }
190
+
191
+ // Resolve the package manager: --pm flag → detection → interactive prompt.
192
+ // Detection here has no project root yet (the folder is new), so it relies on
193
+ // npm_config_user_agent (npx / pnpm dlx / PM scripts) or a single available binary.
194
+ let packageManager = options.pm;
195
+ if (packageManager && !SUPPORTED_PACKAGE_MANAGERS.includes(packageManager)) {
196
+ Print.error(`Unsupported package manager "${packageManager}". Use one of: ${SUPPORTED_PACKAGE_MANAGERS.join(', ')}`);
197
+ return;
198
+ }
199
+ if (packageManager && !isPackageManagerAvailable(packageManager)) {
200
+ Print.error(`Package manager "${packageManager}" is not available on this system`);
201
+ return;
202
+ }
203
+ if (!packageManager) {
204
+ const detected = detectPackageManager(null);
205
+ if (detected) {
206
+ packageManager = detected.name;
207
+ } else if (!options.yes) {
208
+ const available = getAvailablePackageManagers();
209
+ if (available.length === 0) {
210
+ Print.error('No package manager found (pnpm or npm). Install one and retry.');
211
+ return;
212
+ }
213
+ const { pm } = await inquirer.prompt([
214
+ {
215
+ type: 'list',
216
+ name: 'pm',
217
+ message: 'Which package manager do you want to use?',
218
+ choices: available,
219
+ default: available.includes('pnpm') ? 'pnpm' : available[0]
220
+ }
221
+ ]);
222
+ packageManager = pm;
223
+ } else {
224
+ const available = getAvailablePackageManagers();
225
+ packageManager = available.includes('pnpm') ? 'pnpm' : available[0];
226
+ if (!packageManager) {
227
+ Print.error('No package manager found (pnpm or npm). Install one and retry.');
228
+ return;
229
+ }
230
+ }
231
+ }
232
+
233
+ const projectDir = path.resolve(projectName);
234
+
235
+ if (fs.existsSync(projectDir)) {
236
+ const contents = fs.readdirSync(projectDir);
237
+ if (contents.length > 0) {
238
+ if (options.yes) {
239
+ Print.error(`Directory "${projectName}" already exists and is not empty. Aborting.`);
240
+ return;
241
+ }
242
+ const { overwrite } = await inquirer.prompt([
243
+ {
244
+ type: 'confirm',
245
+ name: 'overwrite',
246
+ message: `Directory "${projectName}" already exists and is not empty. Continue?`,
247
+ default: false
248
+ }
249
+ ]);
250
+ if (!overwrite) {
251
+ Print.info('Initialization cancelled.');
252
+ return;
253
+ }
254
+ }
255
+ } else {
256
+ fs.mkdirSync(projectDir, { recursive: true });
257
+ }
258
+
259
+ process.chdir(projectDir);
260
+ process.env.INIT_CWD = projectDir;
261
+
262
+ await runWithVersionCheck(async () => {
263
+ await initializeProject({ packageManager });
264
+ });
265
+ });
266
+
267
+ // VERSION COMMAND
268
+ sliceClient
269
+ .command("version")
270
+ .alias("v")
271
+ .description("Show version information and check for updates")
272
+ .action(async () => {
273
+ await versionChecker.showVersionInfo();
274
+ });
275
+
276
+ // BUILD COMMAND
277
+ const buildCommand = sliceClient.command("build")
278
+ .description("Build Slice.js project for production")
279
+ .action(async (options) => {
280
+ await withNodeEnv('production', () => runWithVersionCheck(async () => {
281
+ // build() reports failure by returning false (degraded files, missing
282
+ // build dependencies) rather than throwing, so it needs its own exit code.
283
+ const ok = await build(options);
284
+ if (ok === false) process.exitCode = 1;
285
+ return ok;
286
+ }));
287
+ });
288
+
289
+ buildCommand
290
+ .command("clean")
291
+ .description("Remove all generated bundles")
292
+ .action(async () => {
293
+ await cleanBundles();
294
+ });
295
+
296
+ buildCommand
297
+ .command("info")
298
+ .description("Show information about generated bundles")
299
+ .action(async () => {
300
+ await bundleInfo();
301
+ });
302
+
303
+ buildCommand
304
+ .option("-a, --analyze", "Analyze project dependencies without bundling")
305
+ .option("-v, --verbose", "Show detailed output")
306
+ .option("--no-minify", "Disable minification (enabled by default)")
307
+ .option("--no-obfuscate", "Disable obfuscation (enabled by default, no prop mangling)")
308
+ .option("--preview", "Start preview server after build")
309
+ .option("--serve", "Start preview server without building")
310
+ // Strict is the default now. `--strict-external` is kept so existing CI
311
+ // scripts keep working — commander rejects unknown options, so dropping it
312
+ // would break them outright. It is a no-op that asks for the default.
313
+ .option("--strict-external", "Fail the build if a node_modules dependency cannot be resolved (default)")
314
+ .option("--no-strict-external", "Allow the build to continue when a node_modules dependency cannot be resolved")
315
+ .option("--allow-unoptimized", "Succeed even if some files could not be minified and shipped as-is")
316
+ .option("--no-validate", "Skip component prop validation before building")
317
+ .option("--sourcemap", "Emit a source map (.map) next to each minified bundle")
318
+ .option("--hash-filenames", "Add a content hash to bundle filenames for immutable CDN caching")
319
+ .option("--compress", "Precompress dist assets to .gz and .br (brotli) for static serving")
320
+ .option("--skip-clean", "Skip cleaning dist before build");
321
+
322
+ // DEV COMMAND (DEVELOPMENT)
323
+ sliceClient
324
+ .command("dev")
325
+ .description("Start development server with hot reload enabled by default")
326
+ .option("-p, --port <port>", "Port for development server")
327
+ .option("--no-hmr", "Disable hot module reload (enabled by default)")
328
+ .action(async (options) => {
329
+ await withNodeEnv('development', () => runWithVersionCheck(async () => {
330
+ await startServer({
331
+ mode: 'development',
332
+ port: parsePort(options.port),
333
+ watch: options.hmr
334
+ });
335
+ }));
336
+ });
337
+
338
+ // START COMMAND - PRODUCTION MODE
339
+ sliceClient
340
+ .command("start")
341
+ .description("Serve production files from dist/ (requires prior slice build)")
342
+ .option("-p, --port <port>", "Port for server")
343
+ .action(async (options) => {
344
+ await withNodeEnv('production', () => runWithVersionCheck(async () => {
345
+ await startServer({
346
+ mode: 'production',
347
+ port: parsePort(options.port)
348
+ });
349
+ }));
350
+ });
351
+
352
+ // COMPONENT COMMAND GROUP - For local component management
353
+ const componentCommand = sliceClient.command("component").alias("comp").description("Manage local project components");
354
+
355
+ // CREATE LOCAL COMPONENT
356
+ componentCommand
357
+ .command("create [name]")
358
+ .alias("new")
359
+ .description("Create a new component in your local project")
360
+ .option("-c, --category <category>", "Component category (e.g. Visual, Service, AppComponents). Skips the prompt when provided.")
361
+ .action(async (name, options) => {
362
+ await runWithVersionCheck(async () => {
363
+ const categories = getCategories();
364
+ if (categories.length === 0) {
365
+ Print.error("No categories found in your project configuration");
366
+ Print.info("Run 'slice init' to initialize your project first");
367
+ Print.commandExample("Initialize project", "slice init");
368
+ return;
369
+ }
370
+
371
+ let componentName = name;
372
+ let category = options.category;
373
+
374
+ // Prompt only for the values not supplied on the command line. Passing both
375
+ // a name and --category runs fully non-interactively (handy for scripts/agents).
376
+ const prompts = [];
377
+ if (!componentName) {
378
+ prompts.push({
379
+ type: "input",
380
+ name: "componentName",
381
+ message: "Enter the component name:",
382
+ validate: (input) => {
383
+ if (!input) return "Component name cannot be empty";
384
+ if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(input)) {
385
+ return "Component name must start with a letter and contain only alphanumeric characters";
386
+ }
387
+ return true;
388
+ },
389
+ });
390
+ }
391
+ if (!category) {
392
+ prompts.push({
393
+ type: "list",
394
+ name: "category",
395
+ message: "Select the component category:",
396
+ choices: categories,
397
+ });
398
+ }
399
+
400
+ if (prompts.length > 0) {
401
+ const answers = await inquirer.prompt(prompts);
402
+ componentName = componentName ?? answers.componentName;
403
+ category = category ?? answers.category;
404
+ }
405
+
406
+ // createComponent validates the name and the category (and reports a clear
407
+ // error listing valid categories if --category is wrong).
408
+ const result = createComponent(componentName, category);
409
+ if (result) {
410
+ Print.success(`Component '${componentName}' created successfully in category '${category}'`);
411
+ Print.info("Listing updated components:");
412
+ listComponents();
413
+ }
414
+ });
415
+ });
416
+
417
+ // LIST LOCAL COMPONENTS
418
+ componentCommand
419
+ .command("list")
420
+ .alias("ls")
421
+ .description("List all components in your local project")
422
+ .action(async () => {
423
+ await runWithVersionCheck(() => {
424
+ listComponents();
425
+ return Promise.resolve();
426
+ });
427
+ });
428
+
429
+ // DELETE LOCAL COMPONENT
430
+ componentCommand
431
+ .command("delete [name]")
432
+ .alias("remove")
433
+ .description("Delete a component from your local project")
434
+ .option("-c, --category <category>", "Component category. Skips the category prompt when provided.")
435
+ .option("-y, --yes", "Skip the confirmation prompt (for non-interactive use)")
436
+ .action(async (name, options) => {
437
+ await runWithVersionCheck(async () => {
438
+ const categories = getCategories();
439
+ if (categories.length === 0) {
440
+ Print.error("No categories available. Check your configuration");
441
+ Print.info("Run 'slice init' to initialize your project");
442
+ return;
443
+ }
444
+
445
+ try {
446
+ let category = options.category;
447
+ let componentName = name;
448
+
449
+ // Resolve category (prompt only if not provided)
450
+ if (!category) {
451
+ const categoryAnswer = await inquirer.prompt([
452
+ {
453
+ type: "list",
454
+ name: "category",
455
+ message: "Select the component category:",
456
+ choices: categories,
457
+ }
458
+ ]);
459
+ category = categoryAnswer.category;
460
+ }
461
+
462
+ const config = sharedLoadConfigSync(import.meta.url);
463
+ if (!config) {
464
+ Print.error("Could not load configuration");
465
+ return;
466
+ }
467
+
468
+ if (!config.paths.components[category]) {
469
+ Print.error(`Invalid category: '${category}'`);
470
+ Print.info(`Available categories: ${categories.join(", ")}`);
471
+ return;
472
+ }
473
+
474
+ const categoryPath = config.paths.components[category].path;
475
+ const fullPath = getSrcPath(import.meta.url, categoryPath);
476
+
477
+ if (!fs.existsSync(fullPath)) {
478
+ Print.error(`Category path does not exist: ${categoryPath}`);
479
+ return;
480
+ }
481
+
482
+ // Resolve component name (prompt with a list only if not provided)
483
+ if (!componentName) {
484
+ const components = fs.readdirSync(fullPath).filter(item => {
485
+ const itemPath = path.join(fullPath, item);
486
+ return fs.statSync(itemPath).isDirectory();
487
+ });
488
+
489
+ if (components.length === 0) {
490
+ Print.info(`No components found in category '${category}'`);
491
+ return;
492
+ }
493
+
494
+ const componentAnswer = await inquirer.prompt([
495
+ {
496
+ type: "list",
497
+ name: "componentName",
498
+ message: "Select the component to delete:",
499
+ choices: components,
500
+ }
501
+ ]);
502
+ componentName = componentAnswer.componentName;
503
+ }
504
+
505
+ // Confirm unless --yes was passed (passing name + --category + --yes is fully non-interactive)
506
+ if (!options.yes) {
507
+ const { confirm } = await inquirer.prompt([
508
+ {
509
+ type: "confirm",
510
+ name: "confirm",
511
+ message: `Are you sure you want to delete '${componentName}' from '${category}'?`,
512
+ default: false,
513
+ }
514
+ ]);
515
+ if (!confirm) {
516
+ Print.info("Delete operation cancelled");
517
+ return;
518
+ }
519
+ }
520
+
521
+ // deleteComponent validates the name/category and that the component exists.
522
+ if (deleteComponent(componentName, category)) {
523
+ Print.success(`Component ${componentName} deleted successfully`);
524
+ Print.info("Listing updated components:");
525
+ listComponents();
526
+ }
527
+ } catch (error) {
528
+ Print.error(`Deleting component: ${error.message}`);
529
+ }
530
+ });
531
+ });
532
+
533
+ // REGISTRY COMMAND GROUP - For component registry operations
534
+ const registryCommand = sliceClient.command("registry").alias("reg").description("Manage components from official Slice.js repository");
535
+
536
+ // SKILL COMMAND GROUP - Claude Code skill fetched from the docs repo
537
+ const skillCommand = sliceClient.command("skill").description("Manage the Slice.js Claude Code skill (fetched from the official docs repo)");
538
+
539
+ skillCommand
540
+ .command("add")
541
+ .alias("install")
542
+ .description("Install the slice-js-developer skill into .claude/skills/")
543
+ .option("-f, --force", "Overwrite an already-installed skill without prompting")
544
+ .action(async (options) => {
545
+ await runWithVersionCheck(async () => {
546
+ await addSkill({ force: options.force });
547
+ });
548
+ });
549
+
550
+ // DOCUMENTATION COMMAND GROUP - Framework and Slice.js Components docs
551
+ const docsCommand = sliceClient.command("docs").description("Search and retrieve Slice.js documentation");
552
+
553
+ docsCommand
554
+ .command("list")
555
+ .description("List documentation from the framework, Components catalog, or both")
556
+ .option("-s, --source <source>", "Documentation source: framework, components, or all", "all")
557
+ .option("--json", "Print machine-readable JSON")
558
+ .action(async (options) => {
559
+ await runWithVersionCheck(async () => {
560
+ await runDocsList(options);
561
+ });
562
+ });
563
+
564
+ docsCommand
565
+ .command("search <query>")
566
+ .description("Search framework and Slice.js Components documentation")
567
+ .option("-s, --source <source>", "Documentation source: framework, components, or all", "all")
568
+ .option("-m, --max-results <number>", "Maximum number of results", "5")
569
+ .option("--snippets-per-doc <number>", "Maximum snippets per result", "3")
570
+ .option("--json", "Print machine-readable JSON")
571
+ .action(async (query, options) => {
572
+ await runWithVersionCheck(async () => {
573
+ await runDocsSearch(query, options);
574
+ });
575
+ });
576
+
577
+ docsCommand
578
+ .command("get <ids...>")
579
+ .description("Retrieve the authored Markdown for one or more documents")
580
+ .option("-s, --source <source>", "Documentation source: framework, components, or all", "all")
581
+ .option("--stdout", "Print only the authored Markdown")
582
+ .option("--json", "Print machine-readable JSON")
583
+ .action(async (ids, options) => {
584
+ await runWithVersionCheck(async () => {
585
+ await runDocsGet(ids, options);
586
+ });
587
+ });
588
+
589
+ skillCommand
590
+ .command("update")
591
+ .description("Update the installed skill to the latest compatible version")
592
+ .action(async () => {
593
+ await runWithVersionCheck(async () => {
594
+ await updateSkill();
595
+ });
596
+ });
597
+
598
+ skillCommand
599
+ .command("status")
600
+ .description("Show installed vs latest skill version")
601
+ .action(async () => {
602
+ await runWithVersionCheck(async () => {
603
+ await statusSkill();
604
+ });
605
+ });
606
+
607
+ // TYPES COMMAND GROUP - TypeScript declarations from static props
608
+ const typesCommand = sliceClient.command("types").description("Generate TypeScript declarations from component static props");
609
+
610
+ typesCommand
611
+ .command("generate")
612
+ .description("Generate src/slice-build.generated.d.ts for slice.build autocomplete")
613
+ .option("-o, --output <path>", "Custom output path", "src/slice-build.generated.d.ts")
614
+ .action(async (options) => {
615
+ await runWithVersionCheck(async () => {
616
+ const projectRoot = getProjectRoot(import.meta.url);
617
+ const outputPath = path.isAbsolute(options.output)
618
+ ? options.output
619
+ : path.join(projectRoot, options.output);
620
+
621
+ await runGenerateTypes({
622
+ projectRoot,
623
+ outputPath
624
+ });
625
+ });
626
+ });
627
+
628
+ // GET COMPONENTS FROM REGISTRY
629
+ registryCommand
630
+ .command("get [components...]")
631
+ .description("Download and install components from official repository")
632
+ .option("-f, --force", "Force overwrite existing components")
633
+ .option("-s, --service", "Install Service components instead of Visual")
634
+ .option("--no-deps", "Do not resolve and install component dependencies")
635
+ .action(async (components, options) => {
636
+ await runWithVersionCheck(async () => {
637
+ await getComponent(components, {
638
+ force: options.force,
639
+ service: options.service,
640
+ deps: options.deps
641
+ });
642
+ });
643
+ });
644
+
645
+ // LIST REGISTRY COMPONENTS
646
+ registryCommand
647
+ .command("list")
648
+ .alias("ls")
649
+ .description("List all available components in the official repository")
650
+ .action(async () => {
651
+ await runWithVersionCheck(async () => {
652
+ await listRemoteComponents();
653
+ });
654
+ });
655
+
656
+ // SYNC COMPONENTS FROM REGISTRY
657
+ registryCommand
658
+ .command("sync")
659
+ .description("Update all local components to latest versions from repository")
660
+ .option("-f, --force", "Force update without confirmation")
661
+ .action(async (options) => {
662
+ await runWithVersionCheck(async () => {
663
+ await syncComponents({
664
+ force: options.force
665
+ });
666
+ });
667
+ });
668
+
669
+ // SHORTCUTS - Top-level convenient commands
670
+ sliceClient
671
+ .command("get [components...]")
672
+ .description("Quick install components from registry")
673
+ .option("-f, --force", "Force overwrite existing components")
674
+ .option("-s, --service", "Install Service components instead of Visual")
675
+ .option("--no-deps", "Do not resolve and install component dependencies")
676
+ .action(async (components, options) => {
677
+ await runWithVersionCheck(async () => {
678
+ if (!components || components.length === 0) {
679
+ Print.info("Use 'slice registry list' to see available components");
680
+ Print.commandExample("Get multiple components", "slice get Button Card Input");
681
+ Print.commandExample("Get service component", "slice get FetchManager --service");
682
+ Print.commandExample("Browse components", "slice browse");
683
+ return;
684
+ }
685
+
686
+ await getComponent(components, {
687
+ force: options.force,
688
+ service: options.service,
689
+ deps: options.deps
690
+ });
691
+ });
692
+ });
693
+
694
+ sliceClient
695
+ .command("browse")
696
+ .description("Quick browse available components")
697
+ .action(async () => {
698
+ await runWithVersionCheck(async () => {
699
+ await listRemoteComponents();
700
+ });
701
+ });
702
+
703
+ sliceClient
704
+ .command("sync")
705
+ .description("Quick sync local components to latest versions")
706
+ .option("-f, --force", "Force update without confirmation")
707
+ .action(async (options) => {
708
+ await runWithVersionCheck(async () => {
709
+ await syncComponents({
710
+ force: options.force
711
+ });
712
+ });
713
+ });
714
+
715
+ // LIST COMMAND - Quick shortcut for listing local components
716
+ sliceClient
717
+ .command("list")
718
+ .description("Quick list all local components (alias for component list)")
719
+ .action(async () => {
720
+ await runWithVersionCheck(() => {
721
+ listComponents();
722
+ return Promise.resolve();
723
+ });
724
+ });
725
+
726
+ // DOCTOR COMMAND - Diagnose project issues
727
+ sliceClient
728
+ .command("doctor")
729
+ .alias("diagnose")
730
+ .description("Run diagnostics to check project health")
731
+ .action(async () => {
732
+ await runWithVersionCheck(async () => {
733
+ await runDiagnostics();
734
+ });
735
+ });
736
+
737
+ // LINT COMMAND - runs the project's ESLint, with the shared config available
738
+ // as `slicejs-cli/eslint-config.js`. The CLI does not bundle ESLint itself.
140
739
  sliceClient
141
- .command("init")
142
- .description("Initialize a new Slice.js project")
143
- .argument("[name]", "Project name (defaults to my-slice-app)")
144
- .option("-y, --yes", "Skip prompts")
145
- .option("--pm <packageManager>", "Package manager to use (pnpm or npm). Auto-detected when omitted")
146
- .action(async (name, options) => {
147
- let projectName = name ? name.trim().toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '').replace(/-+/g, '-').replace(/^-|-$/g, '') : 'my-slice-app';
148
- if (!options.yes) {
149
- const answers = await inquirer.prompt([
150
- {
151
- type: 'input',
152
- name: 'projectName',
153
- message: 'What is the name of your project?',
154
- default: projectName,
155
- filter: (input) => input.trim()
156
- .toLowerCase()
157
- .replace(/\s+/g, '-')
158
- .replace(/[^a-z0-9-]/g, '')
159
- .replace(/-+/g, '-')
160
- .replace(/^-|-$/g, ''),
161
- validate: (input) => {
162
- if (!input || !input.trim()) return 'Project name cannot be empty';
163
- if (input.includes('/') || input.includes('\\')) return 'Use a simple name, not a path';
164
- return true;
165
- }
166
- }
167
- ]);
168
- projectName = answers.projectName;
169
- }
170
-
171
- // Resolve the package manager: --pm flag → detection → interactive prompt.
172
- // Detection here has no project root yet (the folder is new), so it relies on
173
- // npm_config_user_agent (npx / pnpm dlx / PM scripts) or a single available binary.
174
- let packageManager = options.pm;
175
- if (packageManager && !SUPPORTED_PACKAGE_MANAGERS.includes(packageManager)) {
176
- Print.error(`Unsupported package manager "${packageManager}". Use one of: ${SUPPORTED_PACKAGE_MANAGERS.join(', ')}`);
177
- return;
178
- }
179
- if (packageManager && !isPackageManagerAvailable(packageManager)) {
180
- Print.error(`Package manager "${packageManager}" is not available on this system`);
181
- return;
182
- }
183
- if (!packageManager) {
184
- const detected = detectPackageManager(null);
185
- if (detected) {
186
- packageManager = detected.name;
187
- } else if (!options.yes) {
188
- const available = getAvailablePackageManagers();
189
- if (available.length === 0) {
190
- Print.error('No package manager found (pnpm or npm). Install one and retry.');
191
- return;
192
- }
193
- const { pm } = await inquirer.prompt([
194
- {
195
- type: 'list',
196
- name: 'pm',
197
- message: 'Which package manager do you want to use?',
198
- choices: available,
199
- default: available.includes('pnpm') ? 'pnpm' : available[0]
200
- }
201
- ]);
202
- packageManager = pm;
203
- } else {
204
- const available = getAvailablePackageManagers();
205
- packageManager = available.includes('pnpm') ? 'pnpm' : available[0];
206
- if (!packageManager) {
207
- Print.error('No package manager found (pnpm or npm). Install one and retry.');
208
- return;
209
- }
210
- }
211
- }
212
-
213
- const projectDir = path.resolve(projectName);
214
-
215
- if (fs.existsSync(projectDir)) {
216
- const contents = fs.readdirSync(projectDir);
217
- if (contents.length > 0) {
218
- if (options.yes) {
219
- Print.error(`Directory "${projectName}" already exists and is not empty. Aborting.`);
220
- return;
221
- }
222
- const { overwrite } = await inquirer.prompt([
223
- {
224
- type: 'confirm',
225
- name: 'overwrite',
226
- message: `Directory "${projectName}" already exists and is not empty. Continue?`,
227
- default: false
228
- }
229
- ]);
230
- if (!overwrite) {
231
- Print.info('Initialization cancelled.');
232
- return;
233
- }
234
- }
235
- } else {
236
- fs.mkdirSync(projectDir, { recursive: true });
237
- }
238
-
239
- process.chdir(projectDir);
240
- process.env.INIT_CWD = projectDir;
241
-
740
+ .command("lint [paths...]")
741
+ .description("Run ESLint in this project")
742
+ .option("--fix", "Apply automatic fixes")
743
+ .option("--no-types", "Do not refresh the generated declarations")
744
+ .action(async (paths, options) => {
242
745
  await runWithVersionCheck(async () => {
243
- await initializeProject({ packageManager });
746
+ await lintCommand({ paths, fix: options.fix, types: options.types }, getProjectRoot(import.meta.url));
244
747
  });
245
748
  });
246
749
 
247
- // VERSION COMMAND
248
- sliceClient
249
- .command("version")
250
- .alias("v")
251
- .description("Show version information and check for updates")
252
- .action(async () => {
253
- await versionChecker.showVersionInfo();
254
- });
750
+ const setupCommand = sliceClient
751
+ .command("setup")
752
+ .description("Add optional tooling to an existing project");
255
753
 
256
- // BUILD COMMAND
257
- const buildCommand = sliceClient.command("build")
258
- .description("Build Slice.js project for production")
754
+ setupCommand
755
+ .command("lint")
756
+ .description("Install ESLint and add the shared Slice config")
757
+ .option("--dry-run", "Show what would change, write nothing")
758
+ .option("--with-types", "Also install TypeScript and add a typecheck script")
259
759
  .action(async (options) => {
260
- await withNodeEnv('production', () => runWithVersionCheck(async () => {
261
- // build() reports failure by returning false (degraded files, missing
262
- // build dependencies) rather than throwing, so it needs its own exit code.
263
- const ok = await build(options);
264
- if (ok === false) process.exitCode = 1;
265
- return ok;
266
- }));
267
- });
268
-
269
- buildCommand
270
- .command("clean")
271
- .description("Remove all generated bundles")
272
- .action(async () => {
273
- await cleanBundles();
274
- });
275
-
276
- buildCommand
277
- .command("info")
278
- .description("Show information about generated bundles")
279
- .action(async () => {
280
- await bundleInfo();
281
- });
282
-
283
- buildCommand
284
- .option("-a, --analyze", "Analyze project dependencies without bundling")
285
- .option("-v, --verbose", "Show detailed output")
286
- .option("--no-minify", "Disable minification (enabled by default)")
287
- .option("--no-obfuscate", "Disable obfuscation (enabled by default, no prop mangling)")
288
- .option("--preview", "Start preview server after build")
289
- .option("--serve", "Start preview server without building")
290
- // Strict is the default now. `--strict-external` is kept so existing CI
291
- // scripts keep working — commander rejects unknown options, so dropping it
292
- // would break them outright. It is a no-op that asks for the default.
293
- .option("--strict-external", "Fail the build if a node_modules dependency cannot be resolved (default)")
294
- .option("--no-strict-external", "Allow the build to continue when a node_modules dependency cannot be resolved")
295
- .option("--allow-unoptimized", "Succeed even if some files could not be minified and shipped as-is")
296
- .option("--no-validate", "Skip component prop validation before building")
297
- .option("--sourcemap", "Emit a source map (.map) next to each minified bundle")
298
- .option("--hash-filenames", "Add a content hash to bundle filenames for immutable CDN caching")
299
- .option("--compress", "Precompress dist assets to .gz and .br (brotli) for static serving")
300
- .option("--skip-clean", "Skip cleaning dist before build");
301
-
302
- // DEV COMMAND (DEVELOPMENT)
303
- sliceClient
304
- .command("dev")
305
- .description("Start development server with hot reload enabled by default")
306
- .option("-p, --port <port>", "Port for development server")
307
- .option("--no-hmr", "Disable hot module reload (enabled by default)")
308
- .action(async (options) => {
309
- await withNodeEnv('development', () => runWithVersionCheck(async () => {
310
- await startServer({
311
- mode: 'development',
312
- port: parsePort(options.port),
313
- watch: options.hmr
314
- });
315
- }));
316
- });
317
-
318
- // START COMMAND - PRODUCTION MODE
319
- sliceClient
320
- .command("start")
321
- .description("Serve production files from dist/ (requires prior slice build)")
322
- .option("-p, --port <port>", "Port for server")
323
- .action(async (options) => {
324
- await withNodeEnv('production', () => runWithVersionCheck(async () => {
325
- await startServer({
326
- mode: 'production',
327
- port: parsePort(options.port)
328
- });
329
- }));
330
- });
331
-
332
- // COMPONENT COMMAND GROUP - For local component management
333
- const componentCommand = sliceClient.command("component").alias("comp").description("Manage local project components");
334
-
335
- // CREATE LOCAL COMPONENT
336
- componentCommand
337
- .command("create [name]")
338
- .alias("new")
339
- .description("Create a new component in your local project")
340
- .option("-c, --category <category>", "Component category (e.g. Visual, Service, AppComponents). Skips the prompt when provided.")
341
- .action(async (name, options) => {
342
- await runWithVersionCheck(async () => {
343
- const categories = getCategories();
344
- if (categories.length === 0) {
345
- Print.error("No categories found in your project configuration");
346
- Print.info("Run 'slice init' to initialize your project first");
347
- Print.commandExample("Initialize project", "slice init");
348
- return;
349
- }
350
-
351
- let componentName = name;
352
- let category = options.category;
353
-
354
- // Prompt only for the values not supplied on the command line. Passing both
355
- // a name and --category runs fully non-interactively (handy for scripts/agents).
356
- const prompts = [];
357
- if (!componentName) {
358
- prompts.push({
359
- type: "input",
360
- name: "componentName",
361
- message: "Enter the component name:",
362
- validate: (input) => {
363
- if (!input) return "Component name cannot be empty";
364
- if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(input)) {
365
- return "Component name must start with a letter and contain only alphanumeric characters";
366
- }
367
- return true;
368
- },
369
- });
370
- }
371
- if (!category) {
372
- prompts.push({
373
- type: "list",
374
- name: "category",
375
- message: "Select the component category:",
376
- choices: categories,
377
- });
378
- }
379
-
380
- if (prompts.length > 0) {
381
- const answers = await inquirer.prompt(prompts);
382
- componentName = componentName ?? answers.componentName;
383
- category = category ?? answers.category;
384
- }
385
-
386
- // createComponent validates the name and the category (and reports a clear
387
- // error listing valid categories if --category is wrong).
388
- const result = createComponent(componentName, category);
389
- if (result) {
390
- Print.success(`Component '${componentName}' created successfully in category '${category}'`);
391
- Print.info("Listing updated components:");
392
- listComponents();
393
- }
394
- });
395
- });
396
-
397
- // LIST LOCAL COMPONENTS
398
- componentCommand
399
- .command("list")
400
- .alias("ls")
401
- .description("List all components in your local project")
402
- .action(async () => {
403
- await runWithVersionCheck(() => {
404
- listComponents();
405
- return Promise.resolve();
406
- });
407
- });
408
-
409
- // DELETE LOCAL COMPONENT
410
- componentCommand
411
- .command("delete [name]")
412
- .alias("remove")
413
- .description("Delete a component from your local project")
414
- .option("-c, --category <category>", "Component category. Skips the category prompt when provided.")
415
- .option("-y, --yes", "Skip the confirmation prompt (for non-interactive use)")
416
- .action(async (name, options) => {
417
760
  await runWithVersionCheck(async () => {
418
- const categories = getCategories();
419
- if (categories.length === 0) {
420
- Print.error("No categories available. Check your configuration");
421
- Print.info("Run 'slice init' to initialize your project");
422
- return;
423
- }
424
-
425
- try {
426
- let category = options.category;
427
- let componentName = name;
428
-
429
- // Resolve category (prompt only if not provided)
430
- if (!category) {
431
- const categoryAnswer = await inquirer.prompt([
432
- {
433
- type: "list",
434
- name: "category",
435
- message: "Select the component category:",
436
- choices: categories,
437
- }
438
- ]);
439
- category = categoryAnswer.category;
440
- }
441
-
442
- const config = sharedLoadConfigSync(import.meta.url);
443
- if (!config) {
444
- Print.error("Could not load configuration");
445
- return;
446
- }
447
-
448
- if (!config.paths.components[category]) {
449
- Print.error(`Invalid category: '${category}'`);
450
- Print.info(`Available categories: ${categories.join(", ")}`);
451
- return;
452
- }
453
-
454
- const categoryPath = config.paths.components[category].path;
455
- const fullPath = getSrcPath(import.meta.url, categoryPath);
456
-
457
- if (!fs.existsSync(fullPath)) {
458
- Print.error(`Category path does not exist: ${categoryPath}`);
459
- return;
460
- }
461
-
462
- // Resolve component name (prompt with a list only if not provided)
463
- if (!componentName) {
464
- const components = fs.readdirSync(fullPath).filter(item => {
465
- const itemPath = path.join(fullPath, item);
466
- return fs.statSync(itemPath).isDirectory();
467
- });
468
-
469
- if (components.length === 0) {
470
- Print.info(`No components found in category '${category}'`);
471
- return;
472
- }
473
-
474
- const componentAnswer = await inquirer.prompt([
475
- {
476
- type: "list",
477
- name: "componentName",
478
- message: "Select the component to delete:",
479
- choices: components,
480
- }
481
- ]);
482
- componentName = componentAnswer.componentName;
483
- }
484
-
485
- // Confirm unless --yes was passed (passing name + --category + --yes is fully non-interactive)
486
- if (!options.yes) {
487
- const { confirm } = await inquirer.prompt([
488
- {
489
- type: "confirm",
490
- name: "confirm",
491
- message: `Are you sure you want to delete '${componentName}' from '${category}'?`,
492
- default: false,
493
- }
494
- ]);
495
- if (!confirm) {
496
- Print.info("Delete operation cancelled");
497
- return;
498
- }
499
- }
500
-
501
- // deleteComponent validates the name/category and that the component exists.
502
- if (deleteComponent(componentName, category)) {
503
- Print.success(`Component ${componentName} deleted successfully`);
504
- Print.info("Listing updated components:");
505
- listComponents();
506
- }
507
- } catch (error) {
508
- Print.error(`Deleting component: ${error.message}`);
509
- }
510
- });
511
- });
512
-
513
- // REGISTRY COMMAND GROUP - For component registry operations
514
- const registryCommand = sliceClient.command("registry").alias("reg").description("Manage components from official Slice.js repository");
515
-
516
- // SKILL COMMAND GROUP - Claude Code skill fetched from the docs repo
517
- const skillCommand = sliceClient.command("skill").description("Manage the Slice.js Claude Code skill (fetched from the official docs repo)");
518
-
519
- skillCommand
520
- .command("add")
521
- .alias("install")
522
- .description("Install the slice-js-developer skill into .claude/skills/")
523
- .option("-f, --force", "Overwrite an already-installed skill without prompting")
524
- .action(async (options) => {
525
- await runWithVersionCheck(async () => {
526
- await addSkill({ force: options.force });
527
- });
528
- });
529
-
530
- skillCommand
531
- .command("update")
532
- .description("Update the installed skill to the latest compatible version")
533
- .action(async () => {
534
- await runWithVersionCheck(async () => {
535
- await updateSkill();
536
- });
537
- });
538
-
539
- skillCommand
540
- .command("status")
541
- .description("Show installed vs latest skill version")
542
- .action(async () => {
543
- await runWithVersionCheck(async () => {
544
- await statusSkill();
545
- });
546
- });
547
-
548
- // TYPES COMMAND GROUP - TypeScript declarations from static props
549
- const typesCommand = sliceClient.command("types").description("Generate TypeScript declarations from component static props");
550
-
551
- typesCommand
552
- .command("generate")
553
- .description("Generate src/slice-build.generated.d.ts for slice.build autocomplete")
554
- .option("-o, --output <path>", "Custom output path", "src/slice-build.generated.d.ts")
555
- .action(async (options) => {
556
- await runWithVersionCheck(async () => {
557
- const projectRoot = getProjectRoot(import.meta.url);
558
- const outputPath = path.isAbsolute(options.output)
559
- ? options.output
560
- : path.join(projectRoot, options.output);
561
-
562
- await runGenerateTypes({
563
- projectRoot,
564
- outputPath
565
- });
566
- });
567
- });
568
-
569
- // GET COMPONENTS FROM REGISTRY
570
- registryCommand
571
- .command("get [components...]")
572
- .description("Download and install components from official repository")
573
- .option("-f, --force", "Force overwrite existing components")
574
- .option("-s, --service", "Install Service components instead of Visual")
575
- .option("--no-deps", "Do not resolve and install component dependencies")
576
- .action(async (components, options) => {
577
- await runWithVersionCheck(async () => {
578
- await getComponent(components, {
579
- force: options.force,
580
- service: options.service,
581
- deps: options.deps
582
- });
583
- });
584
- });
585
-
586
- // LIST REGISTRY COMPONENTS
587
- registryCommand
588
- .command("list")
589
- .alias("ls")
590
- .description("List all available components in the official repository")
591
- .action(async () => {
592
- await runWithVersionCheck(async () => {
593
- await listRemoteComponents();
594
- });
595
- });
596
-
597
- // SYNC COMPONENTS FROM REGISTRY
598
- registryCommand
599
- .command("sync")
600
- .description("Update all local components to latest versions from repository")
601
- .option("-f, --force", "Force update without confirmation")
602
- .action(async (options) => {
603
- await runWithVersionCheck(async () => {
604
- await syncComponents({
605
- force: options.force
606
- });
607
- });
608
- });
609
-
610
- // SHORTCUTS - Top-level convenient commands
611
- sliceClient
612
- .command("get [components...]")
613
- .description("Quick install components from registry")
614
- .option("-f, --force", "Force overwrite existing components")
615
- .option("-s, --service", "Install Service components instead of Visual")
616
- .option("--no-deps", "Do not resolve and install component dependencies")
617
- .action(async (components, options) => {
618
- await runWithVersionCheck(async () => {
619
- if (!components || components.length === 0) {
620
- Print.info("Use 'slice registry list' to see available components");
621
- Print.commandExample("Get multiple components", "slice get Button Card Input");
622
- Print.commandExample("Get service component", "slice get FetchManager --service");
623
- Print.commandExample("Browse components", "slice browse");
624
- return;
625
- }
626
-
627
- await getComponent(components, {
628
- force: options.force,
629
- service: options.service,
630
- deps: options.deps
631
- });
761
+ await setupLintCommand(options, getProjectRoot(import.meta.url));
632
762
  });
633
763
  });
634
764
 
765
+ // TYPECHECK COMMAND - the compiler step. ESLint does not type-check; this runs
766
+ // the project tsc over the jsconfig that `slice types generate` maintains.
635
767
  sliceClient
636
- .command("browse")
637
- .description("Quick browse available components")
638
- .action(async () => {
639
- await runWithVersionCheck(async () => {
640
- await listRemoteComponents();
641
- });
642
- });
643
-
644
- sliceClient
645
- .command("sync")
646
- .description("Quick sync local components to latest versions")
647
- .option("-f, --force", "Force update without confirmation")
768
+ .command("typecheck")
769
+ .description("Type-check the project with its own TypeScript (jsconfig.json)")
770
+ .option("-p, --project <path>", "Config file (default: jsconfig.json, then tsconfig.json)")
771
+ .option("--no-types", "Do not refresh the generated declarations")
648
772
  .action(async (options) => {
649
773
  await runWithVersionCheck(async () => {
650
- await syncComponents({
651
- force: options.force
652
- });
774
+ await typecheckCommand(options, getProjectRoot(import.meta.url));
653
775
  });
654
776
  });
655
777
 
656
- // LIST COMMAND - Quick shortcut for listing local components
657
- sliceClient
658
- .command("list")
659
- .description("Quick list all local components (alias for component list)")
660
- .action(async () => {
661
- await runWithVersionCheck(() => {
662
- listComponents();
663
- return Promise.resolve();
664
- });
665
- });
666
-
667
- // DOCTOR COMMAND - Diagnose project issues
668
- sliceClient
669
- .command("doctor")
670
- .alias("diagnose")
671
- .description("Run diagnostics to check project health")
672
- .action(async () => {
673
- await runWithVersionCheck(async () => {
674
- await runDiagnostics();
675
- });
676
- });
677
-
678
- // POSTINSTALL COMMAND - Configure npm scripts in existing project
679
- sliceClient
680
- .command("postinstall")
681
- .description("Configure npm scripts in package.json (useful when adding slicejs-cli to an existing project)")
682
- .action(() => {
683
- const pnpmHome = process.env.PNPM_HOME;
684
- const cliEntryPath = fileURLToPath(import.meta.url);
685
- const isGlobal = process.env.npm_config_global === 'true'
686
- || (pnpmHome && cliEntryPath.startsWith(pnpmHome));
687
- if (isGlobal) {
688
- console.log('⚠️ Global installation of slicejs-cli detected.');
689
- console.log(' We strongly recommend using a local installation to avoid version mismatches.');
690
- console.log(` Uninstall global: ${pnpmHome ? 'pnpm remove -g slicejs-cli' : 'npm uninstall -g slicejs-cli'}`);
691
- return;
692
- }
693
-
694
- const projectRoot = getProjectRoot(import.meta.url);
695
- const pkgPath = path.join(projectRoot, 'package.json');
696
- const packageManager = resolvePackageManager(projectRoot).name;
697
-
698
- const sliceScripts = SLICE_SCRIPTS;
699
-
700
- try {
701
- let pkg = {};
702
- if (fs.existsSync(pkgPath)) {
703
- pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
704
- } else {
705
- pkg = {
706
- name: path.basename(projectRoot),
707
- version: '1.0.0',
708
- description: 'Slice.js project',
709
- scripts: {}
710
- };
711
- }
712
-
713
- pkg.scripts = pkg.scripts || {};
714
- let addedCount = 0;
715
- for (const [script, command] of Object.entries(sliceScripts)) {
716
- if (!pkg.scripts[script]) {
717
- pkg.scripts[script] = command;
718
- addedCount++;
719
- }
720
- }
721
-
722
- fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2), 'utf-8');
723
- console.log(`✅ slicejs-cli installed successfully. Added ${addedCount} package scripts to package.json.`);
724
- console.log(` Run: ${runScriptCommand(packageManager, 'slice:dev')}`);
725
- } catch (err) {
726
- console.log('✅ slicejs-cli installed successfully.');
727
- console.log(' Could not auto-configure scripts:', err.message);
728
- console.log(` Configure scripts manually and run: ${runScriptCommand(packageManager, 'slice:dev')}`);
729
- }
730
- });
731
-
732
- // Enhanced help
733
- sliceClient
734
- .option("--no-version-check", "Skip version check for this command")
735
- .configureHelp({
736
- sortSubcommands: true,
737
- subcommandTerm: (cmd) => cmd.name() + ' ' + cmd.usage()
738
- });
739
-
740
-
741
- // Custom help - SIMPLIFIED for development only
742
- sliceClient.addHelpText('after', `
743
- Common Usage Examples:
744
- slice init - Initialize new Slice.js project
745
- slice dev - Start development server
746
- slice build - Build production output (bundles + dist)
747
- slice start - Start production server
748
- slice get Button Card Input - Install Visual components from registry
749
- slice get FetchManager -s - Install Service component from registry
750
- slice browse - Browse all available components
751
- slice sync - Update local components to latest versions
752
- slice component create - Create new local component
753
- slice list - List all local components
754
- slice doctor - Run project diagnostics
755
- slice types generate - Generate TypeScript typings for slice.build
756
- slice skill add - Install the Slice.js Claude Code skill
757
- slice postinstall - Configure npm scripts in package.json
758
-
759
- Command Categories:
760
- • init, dev, start - Project lifecycle (development only)
761
- • get, browse, sync, list - Quick shortcuts
762
- • component <cmd> - Local component management
763
- • registry <cmd> - Official repository operations
764
- • types generate - Type declarations from static props
765
- • skill <cmd> - Claude Code skill (add / update / status)
766
- • version, doctor, setup - Maintenance commands
767
-
768
- Development Workflow:
769
- • slice init - Initialize project
770
- • slice dev - Start development server (serves from /src)
771
- • slice build - Build production output to /dist (includes bundles)
772
- • slice start - Serve production build from /dist
773
-
774
- More info: https://slice-js-docs.vercel.app/
775
- `);
776
-
777
- // Default action with better messaging
778
- if (!process.argv.slice(2).length) {
779
- Print.newLine();
780
- Print.info("Start with: slice init");
781
- Print.commandExample("Development", "slice dev");
782
- Print.commandExample("View available components", "slice browse");
783
- Print.info("Use 'slice --help' for full help");
784
- }
785
-
786
- // Error handling for unknown commands
787
- program.on('command:*', () => {
788
- Print.error('Invalid command. See available commands above');
789
- Print.info("Use 'slice --help' for help");
790
- process.exit(1);
791
- });
792
-
793
- // HELP Command
794
- const helpCommand = sliceClient.command("help").description("Display help information for Slice.js CLI").action(() => {
795
- sliceClient.outputHelp();
796
- });
797
-
798
- program.parse();
778
+ // SEO COMMANDS — the artifacts are committed, so they are written on demand and
779
+ // guarded in CI rather than generated at request time.
780
+ const seoCommand = sliceClient
781
+ .command("seo")
782
+ .description("SEO helpers: sitemap/robots generation and seo.json validation");
783
+
784
+ seoCommand
785
+ .command("sitemap")
786
+ .description("Write public/sitemap.xml (and robots.txt) from seo.json")
787
+ .option("--yes", "overwrite existing files without asking")
788
+ .option("--dry-run", "show what would change, write nothing")
789
+ .action(async (options) => {
790
+ await runWithVersionCheck(async () => {
791
+ await seoSitemap(options, getProjectRoot(import.meta.url));
792
+ });
793
+ });
794
+
795
+ seoCommand
796
+ .command("check")
797
+ .description("Validate seo.json and the committed sitemap (exit 1 on drift)")
798
+ .action(async () => {
799
+ await runWithVersionCheck(async () => {
800
+ await seoCheck({}, getProjectRoot(import.meta.url));
801
+ });
802
+ });
803
+
804
+ seoCommand
805
+ .command("images")
806
+ .alias("og")
807
+ .description("Generate the 1200x630 social card each route advertises")
808
+ .option("--only <routes>", "comma-separated routes to render")
809
+ .option("--base-url <url>", "use a running server instead of booting one")
810
+ .option("--check", "verify the committed cards, no browser")
811
+ .option("--dry-run", "capture and compose, write nothing")
812
+ .option("--selector <css>", "element to capture instead of the viewport")
813
+ .option("--out <dir>", "write the cards somewhere else (default: from seo.json)")
814
+ .option("--runner <file>", "module exporting prepare(page, route) / capture")
815
+ .option("--storage-state <file>", "Playwright storage state for a logged-in capture")
816
+ .action(async (options) => {
817
+ await runWithVersionCheck(async () => {
818
+ await seoImages(options, getProjectRoot(import.meta.url));
819
+ });
820
+ });
821
+
822
+ // POSTINSTALL COMMAND - Configure npm scripts in existing project
823
+ sliceClient
824
+ .command("postinstall")
825
+ .description("Configure npm scripts in package.json (useful when adding slicejs-cli to an existing project)")
826
+ .action(() => {
827
+ const pnpmHome = process.env.PNPM_HOME;
828
+ const cliEntryPath = fileURLToPath(import.meta.url);
829
+ const isGlobal = process.env.npm_config_global === 'true'
830
+ || (pnpmHome && cliEntryPath.startsWith(pnpmHome));
831
+ if (isGlobal) {
832
+ console.log('⚠️ Global installation of slicejs-cli detected.');
833
+ console.log(' We strongly recommend using a local installation to avoid version mismatches.');
834
+ console.log(` Uninstall global: ${pnpmHome ? 'pnpm remove -g slicejs-cli' : 'npm uninstall -g slicejs-cli'}`);
835
+ return;
836
+ }
837
+
838
+ const projectRoot = getProjectRoot(import.meta.url);
839
+ const pkgPath = path.join(projectRoot, 'package.json');
840
+ const packageManager = resolvePackageManager(projectRoot).name;
841
+
842
+ const sliceScripts = SLICE_SCRIPTS;
843
+
844
+ try {
845
+ let pkg = {};
846
+ if (fs.existsSync(pkgPath)) {
847
+ pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
848
+ } else {
849
+ pkg = {
850
+ name: path.basename(projectRoot),
851
+ version: '1.0.0',
852
+ description: 'Slice.js project',
853
+ scripts: {}
854
+ };
855
+ }
856
+
857
+ pkg.scripts = pkg.scripts || {};
858
+ let addedCount = 0;
859
+ for (const [script, command] of Object.entries(sliceScripts)) {
860
+ if (!pkg.scripts[script]) {
861
+ pkg.scripts[script] = command;
862
+ addedCount++;
863
+ }
864
+ }
865
+
866
+ fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2), 'utf-8');
867
+ console.log(`✅ slicejs-cli installed successfully. Added ${addedCount} package scripts to package.json.`);
868
+ console.log(` Run: ${runScriptCommand(packageManager, 'slice:dev')}`);
869
+ } catch (err) {
870
+ console.log('✅ slicejs-cli installed successfully.');
871
+ console.log(' Could not auto-configure scripts:', err.message);
872
+ console.log(` Configure scripts manually and run: ${runScriptCommand(packageManager, 'slice:dev')}`);
873
+ }
874
+ });
875
+
876
+ // Enhanced help
877
+ sliceClient
878
+ .option("--no-version-check", "Skip version check for this command")
879
+ .configureHelp({
880
+ sortSubcommands: true,
881
+ subcommandTerm: (cmd) => cmd.name() + ' ' + cmd.usage()
882
+ });
883
+
884
+
885
+ // Custom help - SIMPLIFIED for development only
886
+ sliceClient.addHelpText('after', `
887
+ Common Usage Examples:
888
+ slice init - Initialize new Slice.js project
889
+ slice dev - Start development server
890
+ slice build - Build production output (bundles + dist)
891
+ slice start - Start production server
892
+ slice get Button Card Input - Install Visual components from registry
893
+ slice get FetchManager -s - Install Service component from registry
894
+ slice browse - Browse all available components
895
+ slice sync - Update local components to latest versions
896
+ slice component create - Create new local component
897
+ slice list - List all local components
898
+ slice doctor - Run project diagnostics
899
+ slice lint - Run ESLint with the shared Slice config
900
+ slice typecheck - Type-check with the project's TypeScript
901
+ slice setup lint - Add ESLint (and --with-types for typecheck)
902
+ slice types generate - Generate TypeScript typings for slice.build
903
+ slice skill add - Install the Slice.js Claude Code skill
904
+ slice postinstall - Configure npm scripts in package.json
905
+
906
+ Command Categories:
907
+ • init, dev, start - Project lifecycle (development only)
908
+ • get, browse, sync, list - Quick shortcuts
909
+ • component <cmd> - Local component management
910
+ • registry <cmd> - Official repository operations
911
+ • types generate - Type declarations from static props
912
+ • skill <cmd> - Claude Code skill (add / update / status)
913
+ • version, doctor, setup - Maintenance commands
914
+
915
+ Development Workflow:
916
+ • slice init - Initialize project
917
+ • slice dev - Start development server (serves from /src)
918
+ • slice build - Build production output to /dist (includes bundles)
919
+ • slice start - Serve production build from /dist
920
+
921
+ More info: https://slice-js-docs.vercel.app/
922
+ `);
923
+
924
+ // Default action with better messaging
925
+ if (!process.argv.slice(2).length) {
926
+ Print.newLine();
927
+ Print.info("Start with: slice init");
928
+ Print.commandExample("Development", "slice dev");
929
+ Print.commandExample("View available components", "slice browse");
930
+ Print.info("Use 'slice --help' for full help");
931
+ }
932
+
933
+ // Error handling for unknown commands
934
+ program.on('command:*', () => {
935
+ Print.error('Invalid command. See available commands above');
936
+ Print.info("Use 'slice --help' for help");
937
+ process.exit(1);
938
+ });
939
+
940
+ // HELP Command
941
+ const helpCommand = sliceClient.command("help").description("Display help information for Slice.js CLI").action(() => {
942
+ sliceClient.outputHelp();
943
+ });
944
+
945
+ program.parse();