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
@@ -0,0 +1,74 @@
1
+ // Lifecycle conventions that are statically visible in a component file. All
2
+ // three are advisories: the app still runs, but the cleanup is not what the
3
+ // author thinks it is.
4
+
5
+ import { parse } from '@babel/parser';
6
+ import traverse from '@babel/traverse';
7
+
8
+ const DEAD_TEARDOWN_NAMES = new Set(['destroy', 'dispose', 'teardown']);
9
+
10
+ /**
11
+ * @returns {{
12
+ * asyncBeforeDestroy: boolean,
13
+ * deadTeardown: string|null,
14
+ * globalListener: number|null
15
+ * }}
16
+ */
17
+ export function auditComponentLifecycle(source) {
18
+ let ast;
19
+ try {
20
+ ast = parse(source, { sourceType: 'module', plugins: ['classProperties'] });
21
+ } catch {
22
+ return { asyncBeforeDestroy: false, deadTeardown: null, globalListener: null };
23
+ }
24
+
25
+ let extendsHTMLElement = false;
26
+ let beforeDestroy = null;
27
+ const methods = [];
28
+ let addsWithoutOptions = 0;
29
+ let removes = 0;
30
+
31
+ const visit = typeof traverse === 'function' ? traverse : traverse.default;
32
+
33
+ visit(ast, {
34
+ Class(path) {
35
+ if (path.node.superClass?.name === 'HTMLElement') extendsHTMLElement = true;
36
+ },
37
+ ClassMethod(path) {
38
+ const name = path.node.key?.name;
39
+ if (!name) return;
40
+ methods.push({ name, params: path.node.params.length });
41
+ if (name === 'beforeDestroy') beforeDestroy = path.node;
42
+ },
43
+ CallExpression(path) {
44
+ const callee = path.node.callee;
45
+ if (callee?.type !== 'MemberExpression' || callee.computed) return;
46
+ const property = callee.property?.name;
47
+ const receiver = callee.object?.name;
48
+
49
+ if (property === 'removeEventListener') {
50
+ removes += 1;
51
+ return;
52
+ }
53
+
54
+ if (property !== 'addEventListener') return;
55
+ if (receiver !== 'window' && receiver !== 'document') return;
56
+
57
+ // `{ once: true }` and `{ signal }` clean themselves up.
58
+ const options = path.node.arguments?.[2];
59
+ if (options?.type !== 'ObjectExpression') addsWithoutOptions += 1;
60
+ }
61
+ });
62
+
63
+ if (!extendsHTMLElement) {
64
+ return { asyncBeforeDestroy: false, deadTeardown: null, globalListener: null };
65
+ }
66
+
67
+ const dead = methods.find((method) => DEAD_TEARDOWN_NAMES.has(method.name) && method.params === 0);
68
+
69
+ return {
70
+ asyncBeforeDestroy: Boolean(beforeDestroy?.async),
71
+ deadTeardown: dead && !beforeDestroy ? dead.name : null,
72
+ globalListener: addsWithoutOptions > 0 && removes === 0 ? addsWithoutOptions : null
73
+ };
74
+ }
@@ -1,103 +1,103 @@
1
- // commands/utils/compressAssets.js
2
- //
3
- // Precompresses text assets in a built `dist/` tree to `.gz` (gzip) and `.br`
4
- // (brotli) siblings, so a static server can serve the already-compressed file
5
- // directly (with Content-Encoding) instead of compressing on every request.
6
- // Brotli is run at maximum quality — that only makes sense offline, which is
7
- // exactly what a build step is.
8
- //
9
- // Uses Node's built-in `zlib` only — no external dependency (team rule: no new
10
- // deps without confirmation, and none is needed here).
11
-
12
- import fs from 'fs-extra';
13
- import path from 'path';
14
- import zlib from 'node:zlib';
15
-
16
- // Text-ish assets that compress well and are safe to serve pre-encoded. Binary
17
- // assets already compressed (png/jpg/woff2/…) are intentionally excluded.
18
- export const COMPRESSIBLE_EXTENSIONS = new Set([
19
- '.js', '.mjs', '.cjs', '.css', '.html', '.htm',
20
- '.json', '.svg', '.xml', '.txt', '.map', '.webmanifest'
21
- ]);
22
-
23
- // Files below this size don't benefit — the encoding overhead and the extra
24
- // request negotiation aren't worth it, so the server should serve the original.
25
- const DEFAULT_MIN_SIZE = 1024;
26
-
27
- export function isCompressibleFile(filePath) {
28
- const ext = path.extname(filePath).toLowerCase();
29
- return COMPRESSIBLE_EXTENSIONS.has(ext);
30
- }
31
-
32
- /** Deterministic max-level gzip of a buffer. */
33
- export function gzipBuffer(buffer) {
34
- return zlib.gzipSync(buffer, { level: zlib.constants.Z_BEST_COMPRESSION });
35
- }
36
-
37
- /** Deterministic max-quality brotli of a buffer (size hint aids the encoder). */
38
- export function brotliBuffer(buffer) {
39
- return zlib.brotliCompressSync(buffer, {
40
- params: {
41
- [zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY,
42
- [zlib.constants.BROTLI_PARAM_SIZE_HINT]: buffer.length
43
- }
44
- });
45
- }
46
-
47
- async function* walkFiles(dir) {
48
- const entries = await fs.readdir(dir, { withFileTypes: true });
49
- for (const entry of entries) {
50
- const full = path.join(dir, entry.name);
51
- if (entry.isDirectory()) {
52
- yield* walkFiles(full);
53
- } else if (entry.isFile()) {
54
- yield full;
55
- }
56
- }
57
- }
58
-
59
- /**
60
- * Walks `dir` and writes a `.gz` and `.br` next to every compressible file over
61
- * `minSize`. Already-compressed siblings (`.gz`/`.br`) are skipped so re-runs
62
- * don't recurse. Best-effort per file: a failure on one file is logged and
63
- * skipped, not fatal.
64
- * @param {string} dir directory to precompress (e.g. the dist root)
65
- * @param {object} [options]
66
- * @param {number} [options.minSize] minimum original size to compress (bytes)
67
- * @returns {Promise<{ files: number, originalBytes: number, gzipBytes: number, brotliBytes: number }>}
68
- */
69
- export async function precompressDirectory(dir, options = {}) {
70
- const minSize = typeof options.minSize === 'number' ? options.minSize : DEFAULT_MIN_SIZE;
71
- const stats = { files: 0, originalBytes: 0, gzipBytes: 0, brotliBytes: 0 };
72
-
73
- if (!await fs.pathExists(dir)) {
74
- return stats;
75
- }
76
-
77
- for await (const filePath of walkFiles(dir)) {
78
- const ext = path.extname(filePath).toLowerCase();
79
- if (ext === '.gz' || ext === '.br') continue; // never recompress an artifact
80
- if (!COMPRESSIBLE_EXTENSIONS.has(ext)) continue;
81
-
82
- try {
83
- const buffer = await fs.readFile(filePath);
84
- if (buffer.length < minSize) continue;
85
-
86
- const gz = gzipBuffer(buffer);
87
- const br = brotliBuffer(buffer);
88
- await fs.writeFile(`${filePath}.gz`, gz);
89
- await fs.writeFile(`${filePath}.br`, br);
90
-
91
- stats.files += 1;
92
- stats.originalBytes += buffer.length;
93
- stats.gzipBytes += gz.length;
94
- stats.brotliBytes += br.length;
95
- } catch (error) {
96
- console.warn(`Warning: could not precompress ${filePath}: ${error.message}`);
97
- }
98
- }
99
-
100
- return stats;
101
- }
102
-
103
- export default precompressDirectory;
1
+ // commands/utils/compressAssets.js
2
+ //
3
+ // Precompresses text assets in a built `dist/` tree to `.gz` (gzip) and `.br`
4
+ // (brotli) siblings, so a static server can serve the already-compressed file
5
+ // directly (with Content-Encoding) instead of compressing on every request.
6
+ // Brotli is run at maximum quality — that only makes sense offline, which is
7
+ // exactly what a build step is.
8
+ //
9
+ // Uses Node's built-in `zlib` only — no external dependency (team rule: no new
10
+ // deps without confirmation, and none is needed here).
11
+
12
+ import fs from 'fs-extra';
13
+ import path from 'path';
14
+ import zlib from 'node:zlib';
15
+
16
+ // Text-ish assets that compress well and are safe to serve pre-encoded. Binary
17
+ // assets already compressed (png/jpg/woff2/…) are intentionally excluded.
18
+ export const COMPRESSIBLE_EXTENSIONS = new Set([
19
+ '.js', '.mjs', '.cjs', '.css', '.html', '.htm',
20
+ '.json', '.svg', '.xml', '.txt', '.map', '.webmanifest'
21
+ ]);
22
+
23
+ // Files below this size don't benefit — the encoding overhead and the extra
24
+ // request negotiation aren't worth it, so the server should serve the original.
25
+ const DEFAULT_MIN_SIZE = 1024;
26
+
27
+ export function isCompressibleFile(filePath) {
28
+ const ext = path.extname(filePath).toLowerCase();
29
+ return COMPRESSIBLE_EXTENSIONS.has(ext);
30
+ }
31
+
32
+ /** Deterministic max-level gzip of a buffer. */
33
+ export function gzipBuffer(buffer) {
34
+ return zlib.gzipSync(buffer, { level: zlib.constants.Z_BEST_COMPRESSION });
35
+ }
36
+
37
+ /** Deterministic max-quality brotli of a buffer (size hint aids the encoder). */
38
+ export function brotliBuffer(buffer) {
39
+ return zlib.brotliCompressSync(buffer, {
40
+ params: {
41
+ [zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY,
42
+ [zlib.constants.BROTLI_PARAM_SIZE_HINT]: buffer.length
43
+ }
44
+ });
45
+ }
46
+
47
+ async function* walkFiles(dir) {
48
+ const entries = await fs.readdir(dir, { withFileTypes: true });
49
+ for (const entry of entries) {
50
+ const full = path.join(dir, entry.name);
51
+ if (entry.isDirectory()) {
52
+ yield* walkFiles(full);
53
+ } else if (entry.isFile()) {
54
+ yield full;
55
+ }
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Walks `dir` and writes a `.gz` and `.br` next to every compressible file over
61
+ * `minSize`. Already-compressed siblings (`.gz`/`.br`) are skipped so re-runs
62
+ * don't recurse. Best-effort per file: a failure on one file is logged and
63
+ * skipped, not fatal.
64
+ * @param {string} dir directory to precompress (e.g. the dist root)
65
+ * @param {object} [options]
66
+ * @param {number} [options.minSize] minimum original size to compress (bytes)
67
+ * @returns {Promise<{ files: number, originalBytes: number, gzipBytes: number, brotliBytes: number }>}
68
+ */
69
+ export async function precompressDirectory(dir, options = {}) {
70
+ const minSize = typeof options.minSize === 'number' ? options.minSize : DEFAULT_MIN_SIZE;
71
+ const stats = { files: 0, originalBytes: 0, gzipBytes: 0, brotliBytes: 0 };
72
+
73
+ if (!await fs.pathExists(dir)) {
74
+ return stats;
75
+ }
76
+
77
+ for await (const filePath of walkFiles(dir)) {
78
+ const ext = path.extname(filePath).toLowerCase();
79
+ if (ext === '.gz' || ext === '.br') continue; // never recompress an artifact
80
+ if (!COMPRESSIBLE_EXTENSIONS.has(ext)) continue;
81
+
82
+ try {
83
+ const buffer = await fs.readFile(filePath);
84
+ if (buffer.length < minSize) continue;
85
+
86
+ const gz = gzipBuffer(buffer);
87
+ const br = brotliBuffer(buffer);
88
+ await fs.writeFile(`${filePath}.gz`, gz);
89
+ await fs.writeFile(`${filePath}.br`, br);
90
+
91
+ stats.files += 1;
92
+ stats.originalBytes += buffer.length;
93
+ stats.gzipBytes += gz.length;
94
+ stats.brotliBytes += br.length;
95
+ } catch (error) {
96
+ console.warn(`Warning: could not precompress ${filePath}: ${error.message}`);
97
+ }
98
+ }
99
+
100
+ return stats;
101
+ }
102
+
103
+ export default precompressDirectory;
@@ -0,0 +1,83 @@
1
+ // Component CSS is loaded globally: a selector that does not start with the
2
+ // component's own tag leaks into every page that uses the bundle. The framework
3
+ // documents this as a convention (component-styles.md), and it is the one class
4
+ // of invariant neither ESLint (no CSS) nor `slice build` ever looked at.
5
+ //
6
+ // Advisory, not a blocker: a `.about` class is ugly but harmless, and portaled
7
+ // widgets legitimately style nodes they append to <body>. `/* slice:unscoped */`
8
+ // opts a file out when that is deliberate.
9
+
10
+ /** The tag a component registers, or null for JS-only components. */
11
+ export function componentTagFromSource(source) {
12
+ const match = String(source).match(/customElements\.define\(\s*['"]([^'"]+)['"]/);
13
+ return match ? match[1] : null;
14
+ }
15
+
16
+ const AT_RULE_WITH_RULES = /^@(media|supports|layer|container|document)\b/i;
17
+
18
+ /**
19
+ * Top-level selectors that are not scoped under `tag` (or `:host`).
20
+ * At-rules that contain rules are walked; `@keyframes`/`@font-face` are skipped.
21
+ */
22
+ export function findUnscopedSelectors(css, tag) {
23
+ const source = String(css);
24
+ if (/\/\*[\s\S]*?slice:unscoped[\s\S]*?\*\//.test(source)) return [];
25
+ if (!tag) return [];
26
+
27
+ const clean = source.replace(/\/\*[\s\S]*?\*\//g, '');
28
+ const unscoped = [];
29
+
30
+ const isScoped = (selector) => {
31
+ const first = selector.split(',')[0].trim();
32
+ return first.startsWith(tag) || first.startsWith(':host');
33
+ };
34
+
35
+ const walk = (text) => {
36
+ let index = 0;
37
+ let selectorStart = 0;
38
+
39
+ while (index < text.length) {
40
+ const char = text[index];
41
+
42
+ if (char === '{') {
43
+ const selector = text.slice(selectorStart, index).trim();
44
+ const close = findClosingBrace(text, index);
45
+ const body = text.slice(index + 1, close);
46
+
47
+ if (selector.startsWith('@')) {
48
+ if (AT_RULE_WITH_RULES.test(selector)) walk(body);
49
+ // @keyframes / @font-face / @page: nothing to check inside
50
+ } else if (selector && !isScoped(selector)) {
51
+ unscoped.push(selector.replace(/\s+/g, ' '));
52
+ }
53
+
54
+ index = close + 1;
55
+ selectorStart = index;
56
+ continue;
57
+ }
58
+
59
+ if (char === '}') {
60
+ index += 1;
61
+ selectorStart = index;
62
+ continue;
63
+ }
64
+
65
+ index += 1;
66
+ }
67
+ };
68
+
69
+ walk(clean);
70
+ return unscoped;
71
+ }
72
+
73
+ function findClosingBrace(text, openIndex) {
74
+ let depth = 0;
75
+ for (let i = openIndex; i < text.length; i += 1) {
76
+ if (text[i] === '{') depth += 1;
77
+ if (text[i] === '}') {
78
+ depth -= 1;
79
+ if (depth === 0) return i;
80
+ }
81
+ }
82
+ return text.length; // unbalanced CSS: treat the rest as the body
83
+ }
@@ -1,31 +1,31 @@
1
- import fs from 'fs-extra';
2
- import { getConfigPath } from './PathHelper.js';
3
- import Print from '../Print.js';
4
-
5
- export async function loadConfig(moduleUrl) {
6
- try {
7
- const configPath = getConfigPath(moduleUrl);
8
- if (!await fs.pathExists(configPath)) {
9
- return null;
10
- }
11
- const rawData = await fs.readFile(configPath, 'utf-8');
12
- return JSON.parse(rawData);
13
- } catch (error) {
14
- Print.error(`Error loading configuration: ${error.message}`);
15
- return null;
16
- }
17
- }
18
-
19
- export function loadConfigSync(moduleUrl) {
20
- try {
21
- const configPath = getConfigPath(moduleUrl);
22
- if (!fs.existsSync(configPath)) {
23
- return null;
24
- }
25
- const rawData = fs.readFileSync(configPath, 'utf-8');
26
- return JSON.parse(rawData);
27
- } catch (error) {
28
- Print.error(`Error loading configuration: ${error.message}`);
29
- return null;
30
- }
31
- }
1
+ import fs from 'fs-extra';
2
+ import { getConfigPath } from './PathHelper.js';
3
+ import Print from '../Print.js';
4
+
5
+ export async function loadConfig(moduleUrl) {
6
+ try {
7
+ const configPath = getConfigPath(moduleUrl);
8
+ if (!await fs.pathExists(configPath)) {
9
+ return null;
10
+ }
11
+ const rawData = await fs.readFile(configPath, 'utf-8');
12
+ return JSON.parse(rawData);
13
+ } catch (error) {
14
+ Print.error(`Error loading configuration: ${error.message}`);
15
+ return null;
16
+ }
17
+ }
18
+
19
+ export function loadConfigSync(moduleUrl) {
20
+ try {
21
+ const configPath = getConfigPath(moduleUrl);
22
+ if (!fs.existsSync(configPath)) {
23
+ return null;
24
+ }
25
+ const rawData = fs.readFileSync(configPath, 'utf-8');
26
+ return JSON.parse(rawData);
27
+ } catch (error) {
28
+ Print.error(`Error loading configuration: ${error.message}`);
29
+ return null;
30
+ }
31
+ }
@@ -0,0 +1,66 @@
1
+ // Minimal semver range check for the ranges this project actually uses:
2
+ // `^`, `~`, exact, `>=`/`<=`/`>`/`<`, `||`, and `*`/`x`/`latest`.
3
+ //
4
+ // It exists because a published CLI declared `slicejs-web-framework@^3.5.0`
5
+ // while shipping a 4.x feature set: installing it gave users a 3.x runtime and
6
+ // nothing complained. `release-check` uses it for the CLI, `slice doctor` uses
7
+ // it for whatever a project declares.
8
+ //
9
+ // An unknown comparator returns true on purpose: a form we do not understand is
10
+ // not evidence of a mismatch.
11
+
12
+ const parse = (value) => {
13
+ const match = String(value ?? '').trim().replace(/^[~^<>=v\s]+/, '').match(/^(\d+)\.(\d+)\.(\d+)/);
14
+ return match ? { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]) } : null;
15
+ };
16
+
17
+ const compare = (a, b) => (a.major - b.major) || (a.minor - b.minor) || (a.patch - b.patch);
18
+
19
+ export function parseVersion(value) {
20
+ return parse(value);
21
+ }
22
+
23
+ export function satisfies(range, version) {
24
+ const target = parse(version);
25
+ if (!target) return false;
26
+
27
+ return String(range).split('||').some((alternative) => {
28
+ const comparators = alternative.trim().split(/\s+/).filter(Boolean);
29
+ if (!comparators.length) return true;
30
+
31
+ return comparators.every((comparator) => {
32
+ if (comparator === '*' || comparator === 'x' || comparator === 'latest') return true;
33
+
34
+ const operator = (comparator.match(/^(\^|~|>=|<=|>|<|=)?/) || [])[1] || '';
35
+ const base = parse(comparator.slice(operator.length));
36
+ if (!base) return true;
37
+
38
+ if (operator === '^') {
39
+ if (target.major !== base.major) return false;
40
+ if (base.major === 0 && target.minor !== base.minor) return false;
41
+ return compare(target, base) >= 0;
42
+ }
43
+ if (operator === '~') {
44
+ return target.major === base.major && target.minor === base.minor && compare(target, base) >= 0;
45
+ }
46
+
47
+ const diff = compare(target, base);
48
+ if (operator === '>=') return diff >= 0;
49
+ if (operator === '>') return diff > 0;
50
+ if (operator === '<=') return diff <= 0;
51
+ if (operator === '<') return diff < 0;
52
+ return diff === 0;
53
+ });
54
+ });
55
+ }
56
+
57
+ /**
58
+ * `null` when the range accepts the version or the range is not a plain semver
59
+ * range (git/file/link specs, `workspace:*`), which callers must skip.
60
+ */
61
+ export function rangeMismatch(range, version) {
62
+ const spec = String(range ?? '').trim();
63
+ if (!spec || /^(file:|link:|workspace:|git|https?:|npm:)/.test(spec)) return null;
64
+ if (!parse(version)) return null;
65
+ return satisfies(spec, version) ? null : spec;
66
+ }
@@ -0,0 +1,72 @@
1
+ // Validates sliceConfig.json against the schema the framework publishes
2
+ // (`sliceConfig.schema.json`). The schema shipped since 4.x and nothing ever read
3
+ // it, so `"port": "3001"` (a string is a pipe path for listen()) or
4
+ // `"enabled": "false"` (truthy) went through unnoticed.
5
+ //
6
+ // Only what the schema actually declares is checked: type, required and nested
7
+ // properties. Unknown keys are not flagged, because the schema is deliberately
8
+ // open (`additionalProperties: true`) and lags behind new options.
9
+
10
+ import fs from 'fs-extra';
11
+ import path from 'node:path';
12
+
13
+ const TYPES = {
14
+ object: (value) => value !== null && typeof value === 'object' && !Array.isArray(value),
15
+ array: Array.isArray,
16
+ string: (value) => typeof value === 'string',
17
+ number: (value) => typeof value === 'number' && Number.isFinite(value),
18
+ integer: (value) => Number.isInteger(value),
19
+ boolean: (value) => typeof value === 'boolean',
20
+ null: (value) => value === null
21
+ };
22
+
23
+ /** The schema from the installed framework, or null when it is not available. */
24
+ export async function loadConfigSchema(projectRoot) {
25
+ const file = path.join(projectRoot, 'node_modules', 'slicejs-web-framework', 'sliceConfig.schema.json');
26
+ try {
27
+ return JSON.parse(await fs.readFile(file, 'utf8'));
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+
33
+ /** @returns {{path: string, message: string}[]} */
34
+ export function validateAgainstSchema(value, schema, at = 'sliceConfig') {
35
+ const issues = [];
36
+
37
+ if (schema?.type) {
38
+ const expected = Array.isArray(schema.type) ? schema.type : [schema.type];
39
+ const matches = expected.some((type) => (TYPES[type] ? TYPES[type](value) : true));
40
+ if (!matches) {
41
+ issues.push({ path: at, message: `is ${describe(value)}, expected ${expected.join(' or ')}` });
42
+ return issues; // a wrong type makes every nested check meaningless
43
+ }
44
+ }
45
+
46
+ if (Array.isArray(schema?.enum) && !schema.enum.some((option) => option === value)) {
47
+ issues.push({ path: at, message: `must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(', ')}` });
48
+ }
49
+
50
+ for (const required of schema?.required || []) {
51
+ if (value?.[required] === undefined) issues.push({ path: `${at}.${required}`, message: 'is required' });
52
+ }
53
+
54
+ if (TYPES.object(value)) {
55
+ for (const [key, child] of Object.entries(schema?.properties || {})) {
56
+ if (value[key] !== undefined) issues.push(...validateAgainstSchema(value[key], child, `${at}.${key}`));
57
+ }
58
+ }
59
+
60
+ if (Array.isArray(value) && schema?.items) {
61
+ value.forEach((item, index) => issues.push(...validateAgainstSchema(item, schema.items, `${at}[${index}]`)));
62
+ }
63
+
64
+ return issues;
65
+ }
66
+
67
+ function describe(value) {
68
+ if (value === null) return 'null';
69
+ if (Array.isArray(value)) return 'an array';
70
+ if (typeof value === 'number') return Number.isInteger(value) ? 'an integer' : 'a number';
71
+ return `a ${typeof value} (${JSON.stringify(value)})`;
72
+ }
@@ -1,48 +1,48 @@
1
- // commands/utils/sliceScripts.js
2
- //
3
- // Single source of truth for the slice:* package scripts configured by the CLI.
4
- // Used by the `slice postinstall` command in
5
- // client.js, and `slice init` — so the three can never drift apart (they did:
6
- // client.js was missing slice:types, and none of them had slice:build).
7
-
8
- import fs from 'fs';
9
-
10
- /**
11
- * Reads a project's package.json and verifies it contains all SLICE_SCRIPTS.
12
- * Returns { missing: string[] } where each entry is the script name not found.
13
- */
14
- export function verifySliceScriptsInPackageJson(pkgPath) {
15
- const missing = [];
16
- try {
17
- if (!fs.existsSync(pkgPath)) {
18
- return { missing: Object.keys(SLICE_SCRIPTS) };
19
- }
20
- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
21
- const scripts = pkg.scripts || {};
22
- for (const script of Object.keys(SLICE_SCRIPTS)) {
23
- if (!scripts[script]) {
24
- missing.push(script);
25
- }
26
- }
27
- } catch {
28
- return { missing: Object.keys(SLICE_SCRIPTS) };
29
- }
30
- return { missing };
31
- }
32
-
33
- export const SLICE_SCRIPTS = {
34
- 'slice:init': 'node ./node_modules/slicejs-cli/client.js init',
35
- 'slice:dev': 'node ./node_modules/slicejs-cli/client.js dev',
36
- 'slice:build': 'node ./node_modules/slicejs-cli/client.js build',
37
- 'slice:start': 'node ./node_modules/slicejs-cli/client.js start',
38
- 'slice:create': 'node ./node_modules/slicejs-cli/client.js component create',
39
- 'slice:list': 'node ./node_modules/slicejs-cli/client.js component list',
40
- 'slice:delete': 'node ./node_modules/slicejs-cli/client.js component delete',
41
- 'slice:get': 'node ./node_modules/slicejs-cli/client.js get',
42
- 'slice:browse': 'node ./node_modules/slicejs-cli/client.js browse',
43
- 'slice:sync': 'node ./node_modules/slicejs-cli/client.js sync',
44
- 'slice:doctor': 'node ./node_modules/slicejs-cli/client.js doctor',
45
- 'slice:version': 'node ./node_modules/slicejs-cli/client.js version',
46
- 'slice:help': 'node ./node_modules/slicejs-cli/client.js --help',
47
- 'slice:types': 'node ./node_modules/slicejs-cli/client.js types generate',
48
- };
1
+ // commands/utils/sliceScripts.js
2
+ //
3
+ // Single source of truth for the slice:* package scripts configured by the CLI.
4
+ // Used by the `slice postinstall` command in
5
+ // client.js, and `slice init` — so the three can never drift apart (they did:
6
+ // client.js was missing slice:types, and none of them had slice:build).
7
+
8
+ import fs from 'fs';
9
+
10
+ /**
11
+ * Reads a project's package.json and verifies it contains all SLICE_SCRIPTS.
12
+ * Returns { missing: string[] } where each entry is the script name not found.
13
+ */
14
+ export function verifySliceScriptsInPackageJson(pkgPath) {
15
+ const missing = [];
16
+ try {
17
+ if (!fs.existsSync(pkgPath)) {
18
+ return { missing: Object.keys(SLICE_SCRIPTS) };
19
+ }
20
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
21
+ const scripts = pkg.scripts || {};
22
+ for (const script of Object.keys(SLICE_SCRIPTS)) {
23
+ if (!scripts[script]) {
24
+ missing.push(script);
25
+ }
26
+ }
27
+ } catch {
28
+ return { missing: Object.keys(SLICE_SCRIPTS) };
29
+ }
30
+ return { missing };
31
+ }
32
+
33
+ export const SLICE_SCRIPTS = {
34
+ 'slice:init': 'node ./node_modules/slicejs-cli/client.js init',
35
+ 'slice:dev': 'node ./node_modules/slicejs-cli/client.js dev',
36
+ 'slice:build': 'node ./node_modules/slicejs-cli/client.js build',
37
+ 'slice:start': 'node ./node_modules/slicejs-cli/client.js start',
38
+ 'slice:create': 'node ./node_modules/slicejs-cli/client.js component create',
39
+ 'slice:list': 'node ./node_modules/slicejs-cli/client.js component list',
40
+ 'slice:delete': 'node ./node_modules/slicejs-cli/client.js component delete',
41
+ 'slice:get': 'node ./node_modules/slicejs-cli/client.js get',
42
+ 'slice:browse': 'node ./node_modules/slicejs-cli/client.js browse',
43
+ 'slice:sync': 'node ./node_modules/slicejs-cli/client.js sync',
44
+ 'slice:doctor': 'node ./node_modules/slicejs-cli/client.js doctor',
45
+ 'slice:version': 'node ./node_modules/slicejs-cli/client.js version',
46
+ 'slice:help': 'node ./node_modules/slicejs-cli/client.js --help',
47
+ 'slice:types': 'node ./node_modules/slicejs-cli/client.js types generate',
48
+ };