slicejs-cli 3.8.0 → 4.0.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.
- package/client.js +5 -0
- package/commands/build/build.js +51 -1
- package/commands/bundle/bundle.js +4 -1
- package/commands/doctor/doctor.js +115 -68
- package/commands/getComponent/getComponent.js +11 -1
- package/commands/types/types.js +86 -22
- package/commands/utils/analyzeSource.js +18 -10
- package/commands/utils/bundling/BundleGenerator.js +791 -145
- package/commands/utils/bundling/DependencyAnalyzer.js +42 -7
- package/commands/utils/bundling/ExternalModuleBundler.js +298 -0
- package/commands/utils/compressAssets.js +103 -0
- package/package.json +2 -1
package/client.js
CHANGED
|
@@ -277,6 +277,11 @@ buildCommand
|
|
|
277
277
|
.option("--no-obfuscate", "Disable obfuscation (enabled by default, no prop mangling)")
|
|
278
278
|
.option("--preview", "Start preview server after build")
|
|
279
279
|
.option("--serve", "Start preview server without building")
|
|
280
|
+
.option("--strict-external", "Fail the build if a node_modules dependency cannot be resolved")
|
|
281
|
+
.option("--no-validate", "Skip component prop validation before building")
|
|
282
|
+
.option("--sourcemap", "Emit a source map (.map) next to each minified bundle")
|
|
283
|
+
.option("--hash-filenames", "Add a content hash to bundle filenames for immutable CDN caching")
|
|
284
|
+
.option("--compress", "Precompress dist assets to .gz and .br (brotli) for static serving")
|
|
280
285
|
.option("--skip-clean", "Skip cleaning dist before build");
|
|
281
286
|
|
|
282
287
|
// DEV COMMAND (DEVELOPMENT)
|
package/commands/build/build.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import bundle from '../bundle/bundle.js';
|
|
2
2
|
import buildProduction, { serveProductionBuild } from '../buildProduction/buildProduction.js';
|
|
3
|
+
import { loadConfigSync } from '../utils/loadConfig.js';
|
|
4
|
+
import { validateComponentProps } from '../types/types.js';
|
|
5
|
+
import { getProjectRoot, getDistPath } from '../utils/PathHelper.js';
|
|
6
|
+
import { precompressDirectory } from '../utils/compressAssets.js';
|
|
3
7
|
import Print from '../Print.js';
|
|
4
8
|
|
|
5
9
|
export default async function build(options = {}) {
|
|
@@ -15,6 +19,38 @@ export default async function build(options = {}) {
|
|
|
15
19
|
return true;
|
|
16
20
|
}
|
|
17
21
|
|
|
22
|
+
// Hard-fail before producing a bundle: ContextManager reactivity (setState →
|
|
23
|
+
// watch/bind) is delivered through EventManager, and EventManager is only
|
|
24
|
+
// bundled when events.enabled is true. context on + events off would ship a
|
|
25
|
+
// bundle where every context watcher is silently dead — catch it here so the
|
|
26
|
+
// broken bundle never gets built.
|
|
27
|
+
const config = loadConfigSync(import.meta.url);
|
|
28
|
+
if (config?.context?.enabled && !config?.events?.enabled) {
|
|
29
|
+
Print.error('sliceConfig: context.enabled requires events.enabled.');
|
|
30
|
+
Print.info('ContextManager reactivity (setState → watch/bind) runs through EventManager, which is only bundled when events.enabled is true. Set "events": { "enabled": true } in sliceConfig.json.');
|
|
31
|
+
process.exit(1);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Validate component static props before building (same checks as `slice
|
|
35
|
+
// doctor`). Definition errors fail the build so a broken component contract
|
|
36
|
+
// never ships; style issues warn but don't block. Skip with --no-validate.
|
|
37
|
+
if (options.validate !== false) {
|
|
38
|
+
const { errors, warnings } = await validateComponentProps({ projectRoot: getProjectRoot(import.meta.url) });
|
|
39
|
+
|
|
40
|
+
for (const w of warnings) {
|
|
41
|
+
Print.warning(`Props: ${w.component}.${w.prop} — ${w.message}`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (errors.length > 0) {
|
|
45
|
+
Print.error(`Build blocked: ${errors.length} component prop error(s) found.`);
|
|
46
|
+
for (const e of errors) {
|
|
47
|
+
Print.info(` ${e.component}.${e.prop} — ${e.message}`);
|
|
48
|
+
}
|
|
49
|
+
Print.info('Fix the component prop definitions above, or run "slice build --no-validate" to bypass (not recommended).');
|
|
50
|
+
process.exit(1);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
18
54
|
const success = await buildProduction({
|
|
19
55
|
...options,
|
|
20
56
|
minify,
|
|
@@ -29,9 +65,23 @@ export default async function build(options = {}) {
|
|
|
29
65
|
verbose: options.verbose,
|
|
30
66
|
minify,
|
|
31
67
|
obfuscate,
|
|
32
|
-
output: 'dist'
|
|
68
|
+
output: 'dist',
|
|
69
|
+
strictExternal: options.strictExternal,
|
|
70
|
+
sourcemap: options.sourcemap,
|
|
71
|
+
hashFilenames: options.hashFilenames
|
|
33
72
|
});
|
|
34
73
|
|
|
74
|
+
if (options.compress) {
|
|
75
|
+
Print.info('Precompressing assets (gzip + brotli)...');
|
|
76
|
+
const stats = await precompressDirectory(getDistPath(import.meta.url));
|
|
77
|
+
if (stats.files > 0) {
|
|
78
|
+
const pct = (n) => `${Math.round((1 - n / stats.originalBytes) * 100)}%`;
|
|
79
|
+
Print.info(`Precompressed ${stats.files} file(s): ${(stats.originalBytes / 1024).toFixed(0)} KB → gzip ${(stats.gzipBytes / 1024).toFixed(0)} KB (${pct(stats.gzipBytes)}), brotli ${(stats.brotliBytes / 1024).toFixed(0)} KB (${pct(stats.brotliBytes)})`);
|
|
80
|
+
} else {
|
|
81
|
+
Print.info('No compressible assets found to precompress.');
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
35
85
|
if (options.preview) {
|
|
36
86
|
await serveProductionBuild(options.port);
|
|
37
87
|
}
|
|
@@ -47,7 +47,10 @@ export default async function bundle(options = {}) {
|
|
|
47
47
|
const generator = new BundleGenerator(import.meta.url, analysisData, {
|
|
48
48
|
minify: !!options.minify,
|
|
49
49
|
obfuscate: !!options.obfuscate,
|
|
50
|
-
output: options.output || 'src'
|
|
50
|
+
output: options.output || 'src',
|
|
51
|
+
strictExternal: !!options.strictExternal,
|
|
52
|
+
sourcemap: !!options.sourcemap,
|
|
53
|
+
hashFilenames: !!options.hashFilenames
|
|
51
54
|
});
|
|
52
55
|
const result = await generator.generate();
|
|
53
56
|
|
|
@@ -7,7 +7,10 @@ import Print from '../Print.js';
|
|
|
7
7
|
import { getProjectRoot, getSrcPath, getApiPath, getConfigPath, getPath, getComponentsJsPath } from '../utils/PathHelper.js';
|
|
8
8
|
import { resolvePackageManager, installCommand } from '../utils/PackageManager.js';
|
|
9
9
|
import updateManager from '../utils/updateManager.js';
|
|
10
|
-
import { parseComponentsRegistry,
|
|
10
|
+
import { parseComponentsRegistry, validateComponentProps } from '../types/types.js';
|
|
11
|
+
import { parse as parseModule } from '@babel/parser';
|
|
12
|
+
import traverse from '@babel/traverse';
|
|
13
|
+
import ExternalModuleBundler from '../utils/bundling/ExternalModuleBundler.js';
|
|
11
14
|
|
|
12
15
|
/**
|
|
13
16
|
* Checks the Node.js version
|
|
@@ -322,93 +325,135 @@ async function checkComponents() {
|
|
|
322
325
|
* Uses the same Babel parsing as slice types generate.
|
|
323
326
|
*/
|
|
324
327
|
async function checkComponentProps() {
|
|
325
|
-
const issues = [];
|
|
326
328
|
const registryPath = getComponentsJsPath(import.meta.url);
|
|
327
|
-
const configPath = getConfigPath(import.meta.url);
|
|
328
|
-
|
|
329
329
|
if (!await fs.pathExists(registryPath)) {
|
|
330
330
|
return { pass: true, message: 'No components to check' };
|
|
331
331
|
}
|
|
332
332
|
|
|
333
333
|
try {
|
|
334
|
-
|
|
335
|
-
const
|
|
336
|
-
|
|
334
|
+
// Same validation `slice build` runs, so doctor and build agree exactly.
|
|
335
|
+
const { errors, warnings, checkedCount } = await validateComponentProps({
|
|
336
|
+
projectRoot: getProjectRoot(import.meta.url)
|
|
337
|
+
});
|
|
337
338
|
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
339
|
+
const issues = [
|
|
340
|
+
...errors.map((e) => ({ ...e, severity: 'error' })),
|
|
341
|
+
...warnings.map((w) => ({ ...w, severity: 'warning' }))
|
|
342
|
+
];
|
|
341
343
|
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
if (await fs.pathExists(configPath)) {
|
|
345
|
-
try {
|
|
346
|
-
const config = await fs.readJson(configPath);
|
|
347
|
-
if (config.paths?.components) {
|
|
348
|
-
for (const [cat, catMeta] of Object.entries(config.paths.components)) {
|
|
349
|
-
categoryPathCache.set(cat, catMeta.path?.replace(/^[/\\]+/, '') || '');
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
} catch {}
|
|
344
|
+
if (issues.length === 0) {
|
|
345
|
+
return { pass: true, message: `${checkedCount} components checked, props look good` };
|
|
353
346
|
}
|
|
354
347
|
|
|
355
|
-
const
|
|
356
|
-
const
|
|
348
|
+
const componentCount = new Set(issues.map((i) => i.component)).size;
|
|
349
|
+
const errorNote = errors.length > 0 ? ` (${errors.length} would block "slice build")` : '';
|
|
350
|
+
return {
|
|
351
|
+
warn: true,
|
|
352
|
+
message: `${issues.length} prop issue(s) across ${componentCount} component(s)${errorNote}`,
|
|
353
|
+
suggestion: issues
|
|
354
|
+
.map((i) => ` [${i.severity}] ${i.component}.${i.prop}: ${i.message}`)
|
|
355
|
+
.join('\n'),
|
|
356
|
+
issues
|
|
357
|
+
};
|
|
358
|
+
} catch (error) {
|
|
359
|
+
return { warn: true, message: `Cannot check props: ${error.message}` };
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** Package root of a bare specifier: 'lodash/fp' -> 'lodash', '@s/p/x' -> '@s/p'. */
|
|
364
|
+
function packageRootOf(spec) {
|
|
365
|
+
const parts = spec.split('/');
|
|
366
|
+
return spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
|
|
367
|
+
}
|
|
357
368
|
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
369
|
+
/** Collects bare (node_modules) import specifiers from a module's source. */
|
|
370
|
+
function extractBareImports(source) {
|
|
371
|
+
const found = new Set();
|
|
372
|
+
const add = (spec) => {
|
|
373
|
+
if (typeof spec === 'string' && ExternalModuleBundler.isBareSpecifier(spec)) found.add(spec);
|
|
374
|
+
};
|
|
375
|
+
try {
|
|
376
|
+
const ast = parseModule(source, { sourceType: 'module', plugins: ['jsx'] });
|
|
377
|
+
traverse.default(ast, {
|
|
378
|
+
ImportDeclaration(p) { add(p.node.source?.value); },
|
|
379
|
+
ExportNamedDeclaration(p) { if (p.node.source) add(p.node.source.value); },
|
|
380
|
+
ExportAllDeclaration(p) { add(p.node.source?.value); },
|
|
381
|
+
CallExpression(p) {
|
|
382
|
+
if (p.node.callee?.type === 'Import' && p.node.arguments?.[0]?.type === 'StringLiteral') {
|
|
383
|
+
add(p.node.arguments[0].value);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
});
|
|
387
|
+
} catch { /* unparseable → skip */ }
|
|
388
|
+
return found;
|
|
389
|
+
}
|
|
363
390
|
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
391
|
+
/**
|
|
392
|
+
* Verifies that every node_modules package imported by a component is actually
|
|
393
|
+
* installed. Bare imports are resolved from node_modules at build/dev time, so a
|
|
394
|
+
* missing package would fail there — this surfaces it early.
|
|
395
|
+
*/
|
|
396
|
+
async function checkExternalDependencies() {
|
|
397
|
+
const registryPath = getComponentsJsPath(import.meta.url);
|
|
398
|
+
const configPath = getConfigPath(import.meta.url);
|
|
399
|
+
const projectRoot = getProjectRoot(import.meta.url);
|
|
367
400
|
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
401
|
+
if (!await fs.pathExists(registryPath)) {
|
|
402
|
+
return { pass: true, message: 'No components to check' };
|
|
403
|
+
}
|
|
371
404
|
|
|
372
|
-
|
|
405
|
+
try {
|
|
406
|
+
const content = await fs.readFile(registryPath, 'utf-8');
|
|
407
|
+
const entries = Object.entries(parseComponentsRegistry(content, registryPath));
|
|
373
408
|
|
|
374
|
-
|
|
375
|
-
if (
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
409
|
+
const categoryPathCache = new Map();
|
|
410
|
+
if (await fs.pathExists(configPath)) {
|
|
411
|
+
try {
|
|
412
|
+
const config = await fs.readJson(configPath);
|
|
413
|
+
for (const [cat, catMeta] of Object.entries(config.paths?.components || {})) {
|
|
414
|
+
categoryPathCache.set(cat, catMeta.path?.replace(/^[/\\]+/, '') || '');
|
|
415
|
+
}
|
|
416
|
+
} catch { /* config issues reported elsewhere */ }
|
|
380
417
|
}
|
|
381
|
-
|
|
382
|
-
|
|
418
|
+
|
|
419
|
+
const usedBy = new Map(); // packageRoot -> Set(component names)
|
|
420
|
+
for (const [compName, meta] of entries) {
|
|
421
|
+
const category = typeof meta === 'string' ? meta : (meta.category || '');
|
|
422
|
+
const relPath = categoryPathCache.get(category);
|
|
423
|
+
if (!relPath) continue;
|
|
424
|
+
const jsPath = getSrcPath(import.meta.url, relPath, compName, `${compName}.js`);
|
|
425
|
+
if (!await fs.pathExists(jsPath)) continue;
|
|
426
|
+
|
|
427
|
+
const source = await fs.readFile(jsPath, 'utf-8');
|
|
428
|
+
for (const spec of extractBareImports(source)) {
|
|
429
|
+
const root = packageRootOf(spec);
|
|
430
|
+
if (!usedBy.has(root)) usedBy.set(root, new Set());
|
|
431
|
+
usedBy.get(root).add(compName);
|
|
432
|
+
}
|
|
383
433
|
}
|
|
384
|
-
|
|
385
|
-
|
|
434
|
+
|
|
435
|
+
if (usedBy.size === 0) {
|
|
436
|
+
return { pass: true, message: 'No external (node_modules) imports' };
|
|
386
437
|
}
|
|
387
|
-
|
|
388
|
-
|
|
438
|
+
|
|
439
|
+
const missing = [];
|
|
440
|
+
for (const root of usedBy.keys()) {
|
|
441
|
+
const pkgJson = path.join(projectRoot, 'node_modules', root, 'package.json');
|
|
442
|
+
if (!await fs.pathExists(pkgJson)) missing.push(root);
|
|
389
443
|
}
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
issues.push({ component: compName, prop: propName, message: `"${propName}" allowedValues type mismatch (expected ${propMeta.type})` });
|
|
394
|
-
}
|
|
444
|
+
|
|
445
|
+
if (missing.length === 0) {
|
|
446
|
+
return { pass: true, message: `${usedBy.size} external package(s) imported, all installed` };
|
|
395
447
|
}
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
448
|
|
|
399
|
-
|
|
400
|
-
|
|
449
|
+
return {
|
|
450
|
+
warn: true,
|
|
451
|
+
message: `${missing.length} imported package(s) not in node_modules: ${missing.sort().join(', ')}`,
|
|
452
|
+
details: missing.sort().map((m) => `Install "${m}" — used by: ${Array.from(usedBy.get(m)).sort().join(', ')}`)
|
|
453
|
+
};
|
|
454
|
+
} catch (error) {
|
|
455
|
+
return { warn: true, message: `Cannot check external dependencies: ${error.message}` };
|
|
401
456
|
}
|
|
402
|
-
|
|
403
|
-
return {
|
|
404
|
-
warn: true,
|
|
405
|
-
message: `${issues.length} prop issue(s) across ${new Set(issues.map(i => i.component)).size} component(s)`,
|
|
406
|
-
suggestion: issues.map(i => ` ${i.component}.${i.prop}: ${i.message}`).join('\n'),
|
|
407
|
-
issues
|
|
408
|
-
};
|
|
409
|
-
} catch (error) {
|
|
410
|
-
return { warn: true, message: `Cannot check props: ${error.message}` };
|
|
411
|
-
}
|
|
412
457
|
}
|
|
413
458
|
|
|
414
459
|
/**
|
|
@@ -421,7 +466,8 @@ export {
|
|
|
421
466
|
checkPort,
|
|
422
467
|
checkDependencies,
|
|
423
468
|
checkComponents,
|
|
424
|
-
checkComponentProps
|
|
469
|
+
checkComponentProps,
|
|
470
|
+
checkExternalDependencies
|
|
425
471
|
};
|
|
426
472
|
|
|
427
473
|
export default async function runDiagnostics() {
|
|
@@ -437,7 +483,8 @@ export default async function runDiagnostics() {
|
|
|
437
483
|
{ name: 'Package Manager', fn: checkPackageManagerSetup },
|
|
438
484
|
{ name: 'Dependencies', fn: checkDependencies },
|
|
439
485
|
{ name: 'Components', fn: checkComponents },
|
|
440
|
-
{ name: 'Component Props', fn: checkComponentProps }
|
|
486
|
+
{ name: 'Component Props', fn: checkComponentProps },
|
|
487
|
+
{ name: 'External Dependencies', fn: checkExternalDependencies }
|
|
441
488
|
];
|
|
442
489
|
|
|
443
490
|
const results = [];
|
|
@@ -418,7 +418,17 @@ filterOfficialComponents(allComponents) {
|
|
|
418
418
|
// Given the source of a just-installed module, install everything it needs.
|
|
419
419
|
// `repoRelPath` anchors relative-import resolution to the repo's Components root.
|
|
420
420
|
async resolveDependencies(jsText, repoRelPath, seen, force = false) {
|
|
421
|
-
const { builds, imports } = analyzeSource(jsText);
|
|
421
|
+
const { builds, imports, bareImports } = analyzeSource(jsText);
|
|
422
|
+
|
|
423
|
+
// Bare (node_modules) imports can't be fetched from the registry — they are
|
|
424
|
+
// npm packages the user must install. Surface each one once.
|
|
425
|
+
for (const spec of bareImports || []) {
|
|
426
|
+
const root = spec.startsWith('@') ? spec.split('/').slice(0, 2).join('/') : spec.split('/')[0];
|
|
427
|
+
this._reportedExternal ??= new Set();
|
|
428
|
+
if (this._reportedExternal.has(root)) continue;
|
|
429
|
+
this._reportedExternal.add(root);
|
|
430
|
+
Print.warning(`↳ npm package required: "${root}" — install it in your project (e.g. "pnpm add ${root}")`);
|
|
431
|
+
}
|
|
422
432
|
|
|
423
433
|
// 1) Component dependencies via slice.build('X').
|
|
424
434
|
for (const name of builds) {
|
package/commands/types/types.js
CHANGED
|
@@ -481,22 +481,13 @@ const DEFAULT_EDITOR_INCLUDE = ['src/Components/**/*.js', 'src/**/*.d.ts'];
|
|
|
481
481
|
const DEFAULT_EDITOR_EXCLUDE = ['node_modules', 'dist', 'src/libs/**', 'tests/**'];
|
|
482
482
|
const NOISY_INCLUDE_PATTERNS = new Set(['src/**/*.js', 'api/**/*.js', 'tests/**/*.js']);
|
|
483
483
|
|
|
484
|
+
// Vendored static assets live under src/public/. Exclude them from type-check
|
|
485
|
+
// coverage (they aren't app source).
|
|
484
486
|
const readPublicFolderExcludes = async (projectRoot) => {
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
try {
|
|
489
|
-
const raw = await fs.readFile(configPath, 'utf8');
|
|
490
|
-
const parsed = JSON.parse(raw);
|
|
491
|
-
const folders = Array.isArray(parsed?.publicFolders) ? parsed.publicFolders : [];
|
|
492
|
-
return folders
|
|
493
|
-
.map((folder) => String(folder || '').trim())
|
|
494
|
-
.filter(Boolean)
|
|
495
|
-
.map((folder) => folder.replace(/^[/\\]+/, ''))
|
|
496
|
-
.map((folder) => `src/${folder}/**`);
|
|
497
|
-
} catch {
|
|
498
|
-
return [];
|
|
487
|
+
if (await fs.pathExists(joinRoot(projectRoot, 'src', 'public'))) {
|
|
488
|
+
return ['src/public/**'];
|
|
499
489
|
}
|
|
490
|
+
return [];
|
|
500
491
|
};
|
|
501
492
|
|
|
502
493
|
const collectJavaScriptFiles = async (dirPath) => {
|
|
@@ -528,12 +519,10 @@ const ensureNoCheckInPublicVendorFiles = async (projectRoot) => {
|
|
|
528
519
|
return { updatedFiles: 0, scannedFiles: 0 };
|
|
529
520
|
}
|
|
530
521
|
|
|
531
|
-
|
|
532
|
-
const candidateDirs =
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
.map((folder) => folder.replace(/^[/\\]+/, ''))
|
|
536
|
-
.map((folder) => joinRoot(projectRoot, 'src', folder));
|
|
522
|
+
// Vendored JS under src/public/ gets // @ts-nocheck so it isn't type-checked.
|
|
523
|
+
const candidateDirs = [];
|
|
524
|
+
const publicDir = joinRoot(projectRoot, 'src', 'public');
|
|
525
|
+
if (await fs.pathExists(publicDir)) candidateDirs.push(publicDir);
|
|
537
526
|
|
|
538
527
|
const uniqueDirs = Array.from(new Set(candidateDirs));
|
|
539
528
|
let scannedFiles = 0;
|
|
@@ -768,6 +757,77 @@ const loadComponentStaticProps = async ({ projectRoot, registryMap }) => {
|
|
|
768
757
|
return componentPropsMap;
|
|
769
758
|
};
|
|
770
759
|
|
|
760
|
+
const PROP_VALID_TYPES = new Set(['string', 'number', 'boolean', 'object', 'array', 'function', 'any']);
|
|
761
|
+
|
|
762
|
+
/**
|
|
763
|
+
* Validates every registered component's static props. Shared by `slice doctor`
|
|
764
|
+
* and `slice build`.
|
|
765
|
+
*
|
|
766
|
+
* Returns issues split by severity:
|
|
767
|
+
* - errors: the definition is wrong and will misbehave at runtime
|
|
768
|
+
* (unknown type, schema/items/allowedValues type mismatch).
|
|
769
|
+
* - warnings: style / best-practice (type "any", required-without-default).
|
|
770
|
+
*
|
|
771
|
+
* @param {{ projectRoot: string }} options
|
|
772
|
+
* @returns {Promise<{ errors: Array, warnings: Array, checkedCount: number }>}
|
|
773
|
+
*/
|
|
774
|
+
const validateComponentProps = async ({ projectRoot }) => {
|
|
775
|
+
const errors = [];
|
|
776
|
+
const warnings = [];
|
|
777
|
+
let checkedCount = 0;
|
|
778
|
+
|
|
779
|
+
const registryPath = getComponentsJsPath(import.meta.url, projectRoot);
|
|
780
|
+
let registryContent;
|
|
781
|
+
try {
|
|
782
|
+
registryContent = await fs.readFile(registryPath, 'utf8');
|
|
783
|
+
} catch {
|
|
784
|
+
return { errors, warnings, checkedCount }; // no registry → nothing to validate
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
const registryMap = parseComponentsRegistry(registryContent, registryPath);
|
|
788
|
+
const configPath = getConfigPath(import.meta.url, projectRoot);
|
|
789
|
+
const categoryPathCache = new Map();
|
|
790
|
+
|
|
791
|
+
for (const [componentName, category] of Object.entries(registryMap)) {
|
|
792
|
+
if (!categoryPathCache.has(category)) {
|
|
793
|
+
let catPath = null;
|
|
794
|
+
try { catPath = await readCategoryPathFromConfig(configPath, category); } catch { /* config issues reported elsewhere */ }
|
|
795
|
+
categoryPathCache.set(category, catPath);
|
|
796
|
+
}
|
|
797
|
+
const categoryPath = categoryPathCache.get(category);
|
|
798
|
+
if (!categoryPath) continue;
|
|
799
|
+
|
|
800
|
+
const componentFile = joinRoot(projectRoot, 'src', categoryPath, componentName, `${componentName}.js`);
|
|
801
|
+
if (!(await fs.pathExists(componentFile))) continue;
|
|
802
|
+
|
|
803
|
+
let source;
|
|
804
|
+
try { source = await fs.readFile(componentFile, 'utf8'); } catch { continue; }
|
|
805
|
+
|
|
806
|
+
const props = extractStaticPropsFromSource(source, componentFile);
|
|
807
|
+
if (!props) continue;
|
|
808
|
+
checkedCount++;
|
|
809
|
+
|
|
810
|
+
for (const [prop, meta] of Object.entries(props)) {
|
|
811
|
+
const err = (message) => errors.push({ component: componentName, prop, message });
|
|
812
|
+
const warn = (message) => warnings.push({ component: componentName, prop, message });
|
|
813
|
+
|
|
814
|
+
if (!PROP_VALID_TYPES.has(meta.type)) err(`unknown type "${meta.type}"`);
|
|
815
|
+
if (meta.schema && meta.type !== 'object') err(`has "schema" but type is "${meta.type}" (should be "object")`);
|
|
816
|
+
if (meta.items && meta.type !== 'array') err(`has "items" but type is "${meta.type}" (should be "array")`);
|
|
817
|
+
if (Array.isArray(meta.allowedValues) && meta.allowedValues.length > 0 && meta.type !== 'any') {
|
|
818
|
+
if (meta.allowedValues.some((v) => typeof v !== meta.type)) {
|
|
819
|
+
err(`allowedValues type mismatch (expected all ${meta.type})`);
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
if (meta.type === 'any') warn('uses type "any" — specify a concrete type');
|
|
824
|
+
if (meta.required && meta.type !== 'boolean') warn('is required but has no default value');
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
return { errors, warnings, checkedCount };
|
|
829
|
+
};
|
|
830
|
+
|
|
771
831
|
const generateTypesFile = async ({ projectRoot, outputPath }) => {
|
|
772
832
|
const registryPath = getComponentsJsPath(import.meta.url, projectRoot);
|
|
773
833
|
let registryContent;
|
|
@@ -846,10 +906,13 @@ const ensureEditorConfigForTypes = async ({ projectRoot, outputPath }) => {
|
|
|
846
906
|
})();
|
|
847
907
|
|
|
848
908
|
const writeDefaultJsconfig = async () => {
|
|
909
|
+
// Include the public/ excludes up front so a freshly written jsconfig is
|
|
910
|
+
// already in its desired state (the next run reports it as unchanged).
|
|
911
|
+
const publicExcludes = await readPublicFolderExcludes(projectRoot);
|
|
849
912
|
const jsconfig = {
|
|
850
913
|
compilerOptions: { ...DEFAULT_EDITOR_COMPILER_OPTIONS },
|
|
851
914
|
include: [...DEFAULT_EDITOR_INCLUDE, declarationGlob],
|
|
852
|
-
exclude: [...DEFAULT_EDITOR_EXCLUDE]
|
|
915
|
+
exclude: Array.from(new Set([...DEFAULT_EDITOR_EXCLUDE, ...publicExcludes]))
|
|
853
916
|
};
|
|
854
917
|
await fs.writeFile(jsconfigPath, `${JSON.stringify(jsconfig, null, 2)}\n`, 'utf8');
|
|
855
918
|
};
|
|
@@ -954,7 +1017,7 @@ const runGenerateTypes = async ({ projectRoot, outputPath }) => {
|
|
|
954
1017
|
Print.warning(`Unexpected editor config setup error: ${editorConfig.errorMessage}`);
|
|
955
1018
|
}
|
|
956
1019
|
if (publicVendorSuppression.updatedFiles > 0) {
|
|
957
|
-
Print.info(`Added // @ts-nocheck to ${publicVendorSuppression.updatedFiles} vendor JS files
|
|
1020
|
+
Print.info(`Added // @ts-nocheck to ${publicVendorSuppression.updatedFiles} vendor JS files under src/public/.`);
|
|
958
1021
|
}
|
|
959
1022
|
return result;
|
|
960
1023
|
};
|
|
@@ -966,6 +1029,7 @@ export {
|
|
|
966
1029
|
generateDeclarationContent,
|
|
967
1030
|
generateTypesFile,
|
|
968
1031
|
parseComponentsRegistry,
|
|
1032
|
+
validateComponentProps,
|
|
969
1033
|
collectEventRegistry,
|
|
970
1034
|
collectEventGraph,
|
|
971
1035
|
buildEventManifest,
|
|
@@ -14,17 +14,27 @@
|
|
|
14
14
|
import { parse } from '@babel/parser';
|
|
15
15
|
import traverse from '@babel/traverse';
|
|
16
16
|
|
|
17
|
+
/** True for bare node_modules specifiers (not relative/absolute/URL/subpath-#). */
|
|
18
|
+
function isBare(spec) {
|
|
19
|
+
return typeof spec === 'string' && spec.length > 0 &&
|
|
20
|
+
!spec.startsWith('.') && !spec.startsWith('/') && !spec.startsWith('#') &&
|
|
21
|
+
!/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(spec);
|
|
22
|
+
}
|
|
23
|
+
|
|
17
24
|
/**
|
|
18
25
|
* @param {string} sourceText
|
|
19
|
-
* @returns {{ builds: Set<string>, imports: string[] }}
|
|
26
|
+
* @returns {{ builds: Set<string>, imports: string[], bareImports: string[] }}
|
|
20
27
|
*/
|
|
21
28
|
export function analyzeSource(sourceText) {
|
|
22
29
|
const builds = new Set();
|
|
23
30
|
const imports = new Set();
|
|
31
|
+
const bareImports = new Set();
|
|
24
32
|
|
|
25
33
|
const addImport = (node) => {
|
|
26
34
|
const src = node?.source?.value;
|
|
27
|
-
if (typeof src
|
|
35
|
+
if (typeof src !== 'string') return;
|
|
36
|
+
if (src.startsWith('.')) imports.add(src);
|
|
37
|
+
else if (isBare(src)) bareImports.add(src);
|
|
28
38
|
};
|
|
29
39
|
|
|
30
40
|
try {
|
|
@@ -45,13 +55,11 @@ export function analyzeSource(sourceText) {
|
|
|
45
55
|
return;
|
|
46
56
|
}
|
|
47
57
|
|
|
48
|
-
// dynamic import('./x.js')
|
|
49
|
-
if (
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
) {
|
|
54
|
-
imports.add(args[0].value);
|
|
58
|
+
// dynamic import('./x.js') or import('some-pkg')
|
|
59
|
+
if (callee.type === 'Import' && args[0]?.type === 'StringLiteral') {
|
|
60
|
+
const spec = args[0].value;
|
|
61
|
+
if (spec.startsWith('.')) imports.add(spec);
|
|
62
|
+
else if (isBare(spec)) bareImports.add(spec);
|
|
55
63
|
}
|
|
56
64
|
},
|
|
57
65
|
|
|
@@ -63,7 +71,7 @@ export function analyzeSource(sourceText) {
|
|
|
63
71
|
// Unparseable source → discover nothing; the component still installs as-is.
|
|
64
72
|
}
|
|
65
73
|
|
|
66
|
-
return { builds, imports: Array.from(imports) };
|
|
74
|
+
return { builds, imports: Array.from(imports), bareImports: Array.from(bareImports) };
|
|
67
75
|
}
|
|
68
76
|
|
|
69
77
|
export default analyzeSource;
|