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