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