slicejs-cli 4.1.1 → 4.2.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 +16 -2
- package/commands/build/build.js +18 -1
- package/commands/buildProduction/buildProduction.js +82 -81
- package/commands/types/types.js +116 -7
- package/commands/utils/JsMinifier.js +230 -0
- package/commands/utils/SourceDiagnostics.js +201 -0
- package/commands/utils/bundling/BundleGenerator.js +622 -59
- package/package.json +1 -1
package/client.js
CHANGED
|
@@ -89,6 +89,11 @@ async function runWithVersionCheck(commandFunction, ...args) {
|
|
|
89
89
|
} catch (error) {
|
|
90
90
|
Print.error(`Command execution: ${error.message}`);
|
|
91
91
|
console.error(error.stack);
|
|
92
|
+
// A command that threw must not report success. This used to swallow the
|
|
93
|
+
// error and return normally, so `slice build` printed a red failure and
|
|
94
|
+
// still exited 0 — CI read that as a passing build and shipped it.
|
|
95
|
+
// process.exitCode (not process.exit) lets buffered output flush first.
|
|
96
|
+
process.exitCode = 1;
|
|
92
97
|
return false;
|
|
93
98
|
}
|
|
94
99
|
}
|
|
@@ -253,7 +258,11 @@ const buildCommand = sliceClient.command("build")
|
|
|
253
258
|
.description("Build Slice.js project for production")
|
|
254
259
|
.action(async (options) => {
|
|
255
260
|
await withNodeEnv('production', () => runWithVersionCheck(async () => {
|
|
256
|
-
|
|
261
|
+
// build() reports failure by returning false (degraded files, missing
|
|
262
|
+
// build dependencies) rather than throwing, so it needs its own exit code.
|
|
263
|
+
const ok = await build(options);
|
|
264
|
+
if (ok === false) process.exitCode = 1;
|
|
265
|
+
return ok;
|
|
257
266
|
}));
|
|
258
267
|
});
|
|
259
268
|
|
|
@@ -278,7 +287,12 @@ buildCommand
|
|
|
278
287
|
.option("--no-obfuscate", "Disable obfuscation (enabled by default, no prop mangling)")
|
|
279
288
|
.option("--preview", "Start preview server after build")
|
|
280
289
|
.option("--serve", "Start preview server without building")
|
|
281
|
-
|
|
290
|
+
// Strict is the default now. `--strict-external` is kept so existing CI
|
|
291
|
+
// scripts keep working — commander rejects unknown options, so dropping it
|
|
292
|
+
// would break them outright. It is a no-op that asks for the default.
|
|
293
|
+
.option("--strict-external", "Fail the build if a node_modules dependency cannot be resolved (default)")
|
|
294
|
+
.option("--no-strict-external", "Allow the build to continue when a node_modules dependency cannot be resolved")
|
|
295
|
+
.option("--allow-unoptimized", "Succeed even if some files could not be minified and shipped as-is")
|
|
282
296
|
.option("--no-validate", "Skip component prop validation before building")
|
|
283
297
|
.option("--sourcemap", "Emit a source map (.map) next to each minified bundle")
|
|
284
298
|
.option("--hash-filenames", "Add a content hash to bundle filenames for immutable CDN caching")
|
package/commands/build/build.js
CHANGED
|
@@ -35,7 +35,24 @@ export default async function build(options = {}) {
|
|
|
35
35
|
// doctor`). Definition errors fail the build so a broken component contract
|
|
36
36
|
// never ships; style issues warn but don't block. Skip with --no-validate.
|
|
37
37
|
if (options.validate !== false) {
|
|
38
|
-
const { errors, warnings } = await validateComponentProps({ projectRoot: getProjectRoot(import.meta.url) });
|
|
38
|
+
const { errors, warnings, sourceErrors, sourceWarnings } = await validateComponentProps({ projectRoot: getProjectRoot(import.meta.url) });
|
|
39
|
+
|
|
40
|
+
// Source-level problems first: they cover every registered component,
|
|
41
|
+
// including ones no route reaches — which the bundler never sees at all.
|
|
42
|
+
if (sourceErrors.length > 0) {
|
|
43
|
+
Print.error(`Build blocked: ${sourceErrors.length} component source error(s) found.`);
|
|
44
|
+
for (const e of sourceErrors) {
|
|
45
|
+
Print.newLine();
|
|
46
|
+
Print.info(` ${e.component}: ${e.message}`);
|
|
47
|
+
}
|
|
48
|
+
Print.newLine();
|
|
49
|
+
Print.info('Fix the components above. These files cannot be bundled or loaded as they are.');
|
|
50
|
+
process.exit(1);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
for (const w of sourceWarnings) {
|
|
54
|
+
Print.warning(`${w.component}: ${w.message}`);
|
|
55
|
+
}
|
|
39
56
|
|
|
40
57
|
for (const w of warnings) {
|
|
41
58
|
Print.warning(`Props: ${w.component}.${w.prop} — ${w.message}`);
|
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
import fs from 'fs-extra';
|
|
4
4
|
import path from 'path';
|
|
5
5
|
import { createRequire } from 'module';
|
|
6
|
-
import { minify as terserMinify } from 'terser';
|
|
7
6
|
import { minify } from 'html-minifier-terser';
|
|
8
7
|
import CleanCSS from 'clean-css';
|
|
9
8
|
import Print from '../Print.js';
|
|
9
|
+
import { minifyJs, sourceFileOptions, componentsRegistryOptions } from '../utils/JsMinifier.js';
|
|
10
|
+
import { describeSyntaxError } from '../utils/SourceDiagnostics.js';
|
|
10
11
|
import { getSrcPath, getDistPath, getConfigPath, getProjectRoot } from '../utils/PathHelper.js';
|
|
11
12
|
import { resolvePackageManager, runScriptCommand } from '../utils/PackageManager.js';
|
|
12
13
|
|
|
@@ -43,8 +44,14 @@ async function checkBuildDependencies() {
|
|
|
43
44
|
Print.success('Build dependencies available');
|
|
44
45
|
return true;
|
|
45
46
|
} catch (error) {
|
|
46
|
-
|
|
47
|
-
|
|
47
|
+
// This used to return true, so a build with no minifier installed reported
|
|
48
|
+
// success while shipping every file unoptimized. They are declared
|
|
49
|
+
// dependencies of the CLI — if they are missing the install is broken, and
|
|
50
|
+
// saying so beats producing a build nobody knows is unoptimized.
|
|
51
|
+
Print.error(`Build dependencies missing: ${error.message}`);
|
|
52
|
+
Print.info('Reinstall the project dependencies, then build again.');
|
|
53
|
+
Print.info('To build anyway with files copied unoptimized, pass --allow-unoptimized.');
|
|
54
|
+
return false;
|
|
48
55
|
}
|
|
49
56
|
}
|
|
50
57
|
|
|
@@ -146,8 +153,12 @@ async function copyFrameworkRuntime() {
|
|
|
146
153
|
* Processes a complete directory
|
|
147
154
|
*/
|
|
148
155
|
async function processDirectory(srcPath, distPath, baseSrcPath, options) {
|
|
149
|
-
|
|
150
|
-
|
|
156
|
+
// Sorted, not raw readdir order: readdir gives no ordering guarantee and it
|
|
157
|
+
// varies by filesystem, so an unstable walk would make build output and its
|
|
158
|
+
// logs differ between machines. Cheap insurance for reproducible builds and
|
|
159
|
+
// any content-hash caching built on them.
|
|
160
|
+
const items = (await fs.readdir(srcPath)).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
161
|
+
|
|
151
162
|
for (const item of items) {
|
|
152
163
|
const srcItemPath = path.join(srcPath, item);
|
|
153
164
|
const distItemPath = path.join(distPath, item);
|
|
@@ -162,6 +173,40 @@ async function processDirectory(srcPath, distPath, baseSrcPath, options) {
|
|
|
162
173
|
}
|
|
163
174
|
}
|
|
164
175
|
|
|
176
|
+
// Files that could not be optimized and were copied through instead. A build
|
|
177
|
+
// that quietly degrades is worse than one that fails: every one of the bundler
|
|
178
|
+
// bugs found so far shipped unoptimized output behind a red line nobody read.
|
|
179
|
+
// Reset per build (buildProduction) and reported before it returns.
|
|
180
|
+
let degradations = [];
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
function resetDegradations() {
|
|
184
|
+
degradations = [];
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
function recordDegradation(entry) {
|
|
189
|
+
degradations.push(entry);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Prints what fell back, if anything.
|
|
194
|
+
* @returns {boolean} true when the build was fully optimized
|
|
195
|
+
*/
|
|
196
|
+
function reportDegradations() {
|
|
197
|
+
if (degradations.length === 0) return true;
|
|
198
|
+
|
|
199
|
+
Print.newLine();
|
|
200
|
+
Print.error(`${degradations.length} file(s) could not be optimized and were copied unoptimized:`);
|
|
201
|
+
for (const { file, reason } of degradations) {
|
|
202
|
+
console.log(` • ${file}: ${reason}`);
|
|
203
|
+
}
|
|
204
|
+
Print.newLine();
|
|
205
|
+
Print.info('These files ship as-is: unminified, comments and all. Fix the cause, or');
|
|
206
|
+
Print.info('pass --allow-unoptimized to accept it and let the build succeed.');
|
|
207
|
+
return false;
|
|
208
|
+
}
|
|
209
|
+
|
|
165
210
|
/**
|
|
166
211
|
* Processes an individual file
|
|
167
212
|
*/
|
|
@@ -223,7 +268,14 @@ async function processFile(srcFilePath, distFilePath, options) {
|
|
|
223
268
|
Print.info(`📄 Copied: ${fileName} (${sizeKB} KB)`);
|
|
224
269
|
}
|
|
225
270
|
} catch (error) {
|
|
271
|
+
// Copying the source through keeps the build usable, but the file ships
|
|
272
|
+
// unoptimized — and this used to be the whole story: a red line in the
|
|
273
|
+
// middle of a green build. Record it so the build can report and fail on it.
|
|
226
274
|
Print.error(`Processing ${fileName}: ${error.message}`);
|
|
275
|
+
recordDegradation({
|
|
276
|
+
file: path.relative(getSrcPath(import.meta.url), srcFilePath) || fileName,
|
|
277
|
+
reason: error.message
|
|
278
|
+
});
|
|
227
279
|
await fs.copy(srcFilePath, distFilePath);
|
|
228
280
|
}
|
|
229
281
|
}
|
|
@@ -235,19 +287,7 @@ async function processComponentsFile(srcPath, distPath) {
|
|
|
235
287
|
const content = await fs.readFile(srcPath, 'utf8');
|
|
236
288
|
const originalSize = Buffer.byteLength(content, 'utf8');
|
|
237
289
|
|
|
238
|
-
const result = await
|
|
239
|
-
compress: false,
|
|
240
|
-
mangle: false,
|
|
241
|
-
format: {
|
|
242
|
-
comments: false,
|
|
243
|
-
beautify: false,
|
|
244
|
-
indent_level: 0
|
|
245
|
-
}
|
|
246
|
-
});
|
|
247
|
-
|
|
248
|
-
if (result.error) {
|
|
249
|
-
throw new Error(`Terser error in components.js: ${result.error}`);
|
|
250
|
-
}
|
|
290
|
+
const result = await minifyJs(content, componentsRegistryOptions);
|
|
251
291
|
|
|
252
292
|
await fs.writeFile(distPath, result.code, 'utf8');
|
|
253
293
|
|
|
@@ -263,67 +303,19 @@ async function processComponentsFile(srcPath, distPath) {
|
|
|
263
303
|
async function minifyJavaScript(srcPath, distPath) {
|
|
264
304
|
const content = await fs.readFile(srcPath, 'utf8');
|
|
265
305
|
const originalSize = Buffer.byteLength(content, 'utf8');
|
|
266
|
-
|
|
267
|
-
const result = await terserMinify(content, {
|
|
268
|
-
compress: {
|
|
269
|
-
drop_console: false,
|
|
270
|
-
drop_debugger: true,
|
|
271
|
-
pure_funcs: [],
|
|
272
|
-
passes: 1,
|
|
273
|
-
unused: false,
|
|
274
|
-
side_effects: false,
|
|
275
|
-
reduce_vars: false,
|
|
276
|
-
collapse_vars: false
|
|
277
|
-
},
|
|
278
|
-
mangle: {
|
|
279
|
-
reserved: [
|
|
280
|
-
// Core Slice
|
|
281
|
-
'slice', 'Slice', 'SliceJS', 'window', 'document',
|
|
282
|
-
// Main classes
|
|
283
|
-
'Controller', 'StylesManager', 'Router', 'Logger', 'Debugger',
|
|
284
|
-
// Slice methods
|
|
285
|
-
'getClass', 'isProduction', 'getComponent', 'build', 'setTheme', 'attachTemplate',
|
|
286
|
-
// Controller
|
|
287
|
-
'componentCategories', 'templates', 'classes', 'requestedStyles', 'activeComponents',
|
|
288
|
-
'registerComponent', 'registerComponentsRecursively', 'loadTemplateToComponent',
|
|
289
|
-
'fetchText', 'setComponentProps', 'verifyComponentIds', 'destroyComponent',
|
|
290
|
-
// StylesManager
|
|
291
|
-
'componentStyles', 'themeManager', 'init', 'appendComponentStyles', 'registerComponentStyles',
|
|
292
|
-
// Router
|
|
293
|
-
'routes', 'pathToRouteMap', 'activeRoute', 'navigate', 'matchRoute', 'handleRoute',
|
|
294
|
-
'onRouteChange', 'loadInitialRoute', 'renderRoutesComponentsInPage',
|
|
295
|
-
// Propiedades de componentes
|
|
296
|
-
'sliceId', 'sliceType', 'sliceConfig', 'debuggerProps', 'parentComponent',
|
|
297
|
-
'value', 'customColor', 'icon', 'layout', 'view', 'items', 'columns', 'rows',
|
|
298
|
-
'onClickCallback', 'props',
|
|
299
|
-
// Custom Elements
|
|
300
|
-
'customElements', 'define', 'HTMLElement',
|
|
301
|
-
// Critical DOM APIs
|
|
302
|
-
'addEventListener', 'removeEventListener', 'querySelector', 'querySelectorAll',
|
|
303
|
-
'appendChild', 'removeChild', 'innerHTML', 'textContent', 'style', 'classList',
|
|
304
|
-
// Lifecycle
|
|
305
|
-
'beforeMount', 'afterMount', 'beforeDestroy', 'afterDestroy',
|
|
306
|
-
'mount', 'unmount', 'destroy', 'update', 'start', 'stop',
|
|
307
|
-
// Browser APIs
|
|
308
|
-
'fetch', 'setTimeout', 'clearTimeout', 'localStorage', 'history', 'pushState',
|
|
309
|
-
// Exports/Imports
|
|
310
|
-
'default', 'export', 'import', 'from', 'await', 'async',
|
|
311
|
-
// Nombres de componentes
|
|
312
|
-
'Button', 'Grid', 'Layout', 'HomePage', 'NotFound', 'Loading', 'TreeView', 'Link',
|
|
313
|
-
'FetchManager'
|
|
314
|
-
],
|
|
315
|
-
properties: { regex: /^_/ }
|
|
316
|
-
},
|
|
317
|
-
format: {
|
|
318
|
-
comments: false,
|
|
319
|
-
beautify: false
|
|
320
|
-
},
|
|
321
|
-
keep_fnames: true,
|
|
322
|
-
keep_classnames: true
|
|
323
|
-
});
|
|
324
306
|
|
|
325
|
-
|
|
326
|
-
|
|
307
|
+
let result;
|
|
308
|
+
try {
|
|
309
|
+
result = await minifyJs(content, sourceFileOptions);
|
|
310
|
+
} catch (minifyError) {
|
|
311
|
+
// Terser reports its own parse failures without a location and in its own
|
|
312
|
+
// vocabulary ("Unexpected token punc «(»"). When the file simply does not
|
|
313
|
+
// parse, say so against the developer's source instead.
|
|
314
|
+
const diagnosis = describeSyntaxError(content, srcPath);
|
|
315
|
+
if (!diagnosis.ok) {
|
|
316
|
+
throw new Error(`Syntax error at ${diagnosis.message}\nFix the source above.`);
|
|
317
|
+
}
|
|
318
|
+
throw minifyError;
|
|
327
319
|
}
|
|
328
320
|
|
|
329
321
|
await fs.writeFile(distPath, result.code, 'utf8');
|
|
@@ -472,7 +464,8 @@ async function analyzeBuild() {
|
|
|
472
464
|
export default async function buildProduction(options = {}) {
|
|
473
465
|
const startTime = Date.now();
|
|
474
466
|
const packageManager = resolvePackageManager(getProjectRoot(import.meta.url)).name;
|
|
475
|
-
|
|
467
|
+
resetDegradations();
|
|
468
|
+
|
|
476
469
|
try {
|
|
477
470
|
Print.title('🔨 Building Slice.js project for production...');
|
|
478
471
|
Print.newLine();
|
|
@@ -511,8 +504,14 @@ export default async function buildProduction(options = {}) {
|
|
|
511
504
|
await createOptimizedBundle();
|
|
512
505
|
await generateBuildStats(srcDir, distDir);
|
|
513
506
|
|
|
507
|
+
const fullyOptimized = reportDegradations();
|
|
508
|
+
if (!fullyOptimized && !options.allowUnoptimized) {
|
|
509
|
+
Print.error('Build failed: not every file could be optimized (see above).');
|
|
510
|
+
return false;
|
|
511
|
+
}
|
|
512
|
+
|
|
514
513
|
const buildTime = ((Date.now() - startTime) / 1000).toFixed(1);
|
|
515
|
-
|
|
514
|
+
|
|
516
515
|
Print.newLine();
|
|
517
516
|
Print.success(`✨ Slice.js production build completed in ${buildTime}s`);
|
|
518
517
|
Print.info('Your optimized project is ready in the /dist directory');
|
|
@@ -585,7 +584,9 @@ export async function buildCommand(options = {}) {
|
|
|
585
584
|
const config = loadConfig();
|
|
586
585
|
const defaultPort = config?.server?.port || 3001;
|
|
587
586
|
|
|
588
|
-
|
|
587
|
+
// Missing minifiers are fatal unless the caller explicitly accepts an
|
|
588
|
+
// unoptimized build.
|
|
589
|
+
if (!await checkBuildDependencies() && !options.allowUnoptimized) {
|
|
589
590
|
return false;
|
|
590
591
|
}
|
|
591
592
|
|
package/commands/types/types.js
CHANGED
|
@@ -5,6 +5,12 @@ import traverse from '@babel/traverse';
|
|
|
5
5
|
|
|
6
6
|
import Print from '../Print.js';
|
|
7
7
|
import { getConfigPath, getComponentsJsPath, joinRoot } from '../utils/PathHelper.js';
|
|
8
|
+
import {
|
|
9
|
+
describeSyntaxError,
|
|
10
|
+
findUnresolvedRelativeImports,
|
|
11
|
+
hasDefaultExport,
|
|
12
|
+
findUnknownComponentBuilds
|
|
13
|
+
} from '../utils/SourceDiagnostics.js';
|
|
8
14
|
|
|
9
15
|
const TYPE_MAP = {
|
|
10
16
|
string: 'string',
|
|
@@ -137,7 +143,7 @@ const payloadToTs = (payload) => {
|
|
|
137
143
|
} else if (value && typeof value === 'object' && typeof value.type === 'string') {
|
|
138
144
|
tsType = PAYLOAD_TYPE_MAP[value.type.toLowerCase()] || 'unknown';
|
|
139
145
|
}
|
|
140
|
-
return `${key}: ${tsType}`;
|
|
146
|
+
return `${tsPropertyKey(key)}: ${tsType}`;
|
|
141
147
|
})
|
|
142
148
|
.join('; ');
|
|
143
149
|
return inner.length > 0 ? `{ ${inner} }` : 'Record<string, unknown>';
|
|
@@ -465,7 +471,43 @@ const typeFromProp = (propMeta) => {
|
|
|
465
471
|
return TYPE_MAP[propMeta.type] || 'unknown';
|
|
466
472
|
};
|
|
467
473
|
|
|
468
|
-
|
|
474
|
+
/**
|
|
475
|
+
* True when `name` can be written as a bare TypeScript property key or
|
|
476
|
+
* identifier. Anything else has to be quoted (or escaped, for a type name).
|
|
477
|
+
* @param {string} name
|
|
478
|
+
* @returns {boolean}
|
|
479
|
+
*/
|
|
480
|
+
const isSafeTsIdentifier = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(String(name));
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* Property key for a declaration line: bare when it can be, quoted otherwise.
|
|
484
|
+
* `data-id` and `my-btn` are legal keys but only in quoted form; emitting them
|
|
485
|
+
* bare produced a .d.ts that does not parse, which silently took out editor
|
|
486
|
+
* tooling for the whole project (jsconfig includes the generated file).
|
|
487
|
+
* @param {string} name
|
|
488
|
+
* @returns {string}
|
|
489
|
+
*/
|
|
490
|
+
const tsPropertyKey = (name) => (isSafeTsIdentifier(name) ? String(name) : JSON.stringify(String(name)));
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* Interface name for a component.
|
|
494
|
+
*
|
|
495
|
+
* A component's registered name need not be a valid identifier — `my-btn` used
|
|
496
|
+
* to yield `export interface my-btnProps`, which is a syntax error. Characters
|
|
497
|
+
* outside [A-Za-z0-9_$] are hex-escaped rather than dropped, so two distinct
|
|
498
|
+
* component names can never collapse onto the same interface (the same reason
|
|
499
|
+
* BundleGenerator.toSafeIdentifier escapes instead of replacing).
|
|
500
|
+
*
|
|
501
|
+
* @param {string} componentName
|
|
502
|
+
* @returns {string}
|
|
503
|
+
*/
|
|
504
|
+
const interfaceNameFor = (componentName) => {
|
|
505
|
+
const raw = String(componentName);
|
|
506
|
+
if (isSafeTsIdentifier(raw)) return `${raw}Props`;
|
|
507
|
+
const encoded = raw.replace(/[^A-Za-z0-9_$]/g, (char) => `_${char.charCodeAt(0).toString(16)}_`);
|
|
508
|
+
// Prefixed so a name starting with a digit still yields a valid identifier.
|
|
509
|
+
return `SliceComponent_${encoded}Props`;
|
|
510
|
+
};
|
|
469
511
|
const DYNAMIC_FALLBACK_PROP = '__dynamicPropsFallback';
|
|
470
512
|
|
|
471
513
|
const DEFAULT_EDITOR_COMPILER_OPTIONS = {
|
|
@@ -553,7 +595,9 @@ const generateEventRegistryLines = (eventRegistry) => {
|
|
|
553
595
|
const lines = [];
|
|
554
596
|
lines.push('export interface SliceEventRegistry {');
|
|
555
597
|
for (const name of names) {
|
|
556
|
-
|
|
598
|
+
// JSON.stringify, not a hand-rolled quote: an event name containing a quote
|
|
599
|
+
// would otherwise terminate the string early.
|
|
600
|
+
lines.push(` ${JSON.stringify(name)}: ${payloadToTs(events[name].payload)};`);
|
|
557
601
|
}
|
|
558
602
|
lines.push('}');
|
|
559
603
|
lines.push('');
|
|
@@ -612,7 +656,7 @@ const generateDeclarationContent = (componentPropsMap, eventRegistry = {}) => {
|
|
|
612
656
|
if (!isDynamicFallback) {
|
|
613
657
|
for (const [propName, propMeta] of Object.entries(sortedProps)) {
|
|
614
658
|
const optionalMark = propMeta.required ? '' : '?';
|
|
615
|
-
lines.push(` ${propName}${optionalMark}: ${typeFromProp(propMeta)};`);
|
|
659
|
+
lines.push(` ${tsPropertyKey(propName)}${optionalMark}: ${typeFromProp(propMeta)};`);
|
|
616
660
|
}
|
|
617
661
|
}
|
|
618
662
|
lines.push('}');
|
|
@@ -621,7 +665,7 @@ const generateDeclarationContent = (componentPropsMap, eventRegistry = {}) => {
|
|
|
621
665
|
|
|
622
666
|
lines.push('export interface SliceComponentPropsMap {');
|
|
623
667
|
for (const componentName of Object.keys(componentsSorted)) {
|
|
624
|
-
lines.push(` ${componentName}: ${interfaceNameFor(componentName)};`);
|
|
668
|
+
lines.push(` ${tsPropertyKey(componentName)}: ${interfaceNameFor(componentName)};`);
|
|
625
669
|
}
|
|
626
670
|
lines.push('}');
|
|
627
671
|
lines.push('');
|
|
@@ -771,9 +815,25 @@ const PROP_VALID_TYPES = new Set(['string', 'number', 'boolean', 'object', 'arra
|
|
|
771
815
|
* @param {{ projectRoot: string }} options
|
|
772
816
|
* @returns {Promise<{ errors: Array, warnings: Array, checkedCount: number }>}
|
|
773
817
|
*/
|
|
818
|
+
/**
|
|
819
|
+
* Walks every component registered in components.js.
|
|
820
|
+
*
|
|
821
|
+
* Note this covers MORE than the bundler does: the bundler only ever sees
|
|
822
|
+
* components reachable from a route, so a registered-but-unused component with a
|
|
823
|
+
* syntax error, a missing default export or a broken import was never checked
|
|
824
|
+
* anywhere — it failed the first time somebody navigated to it.
|
|
825
|
+
*
|
|
826
|
+
* @returns {Promise<{errors: object[], warnings: object[], sourceErrors: object[], checkedCount: number}>}
|
|
827
|
+
*/
|
|
774
828
|
const validateComponentProps = async ({ projectRoot }) => {
|
|
775
829
|
const errors = [];
|
|
776
830
|
const warnings = [];
|
|
831
|
+
// Problems with the file itself rather than with a prop definition. Kept
|
|
832
|
+
// separate because they are reported differently (they carry a file and a
|
|
833
|
+
// position, not a prop name).
|
|
834
|
+
const sourceErrors = [];
|
|
835
|
+
// Reported but not blocking — see findUnknownComponentBuilds below.
|
|
836
|
+
const sourceWarnings = [];
|
|
777
837
|
let checkedCount = 0;
|
|
778
838
|
|
|
779
839
|
const registryPath = getComponentsJsPath(import.meta.url, projectRoot);
|
|
@@ -781,10 +841,11 @@ const validateComponentProps = async ({ projectRoot }) => {
|
|
|
781
841
|
try {
|
|
782
842
|
registryContent = await fs.readFile(registryPath, 'utf8');
|
|
783
843
|
} catch {
|
|
784
|
-
return { errors, warnings, checkedCount }; // no registry → nothing to validate
|
|
844
|
+
return { errors, warnings, sourceErrors, sourceWarnings, checkedCount }; // no registry → nothing to validate
|
|
785
845
|
}
|
|
786
846
|
|
|
787
847
|
const registryMap = parseComponentsRegistry(registryContent, registryPath);
|
|
848
|
+
const registeredNames = new Set(Object.keys(registryMap));
|
|
788
849
|
const configPath = getConfigPath(import.meta.url, projectRoot);
|
|
789
850
|
const categoryPathCache = new Map();
|
|
790
851
|
|
|
@@ -803,6 +864,54 @@ const validateComponentProps = async ({ projectRoot }) => {
|
|
|
803
864
|
let source;
|
|
804
865
|
try { source = await fs.readFile(componentFile, 'utf8'); } catch { continue; }
|
|
805
866
|
|
|
867
|
+
const syntax = describeSyntaxError(source, componentFile);
|
|
868
|
+
if (!syntax.ok) {
|
|
869
|
+
sourceErrors.push({ component: componentName, message: `Syntax error at ${syntax.message}` });
|
|
870
|
+
continue; // nothing further can be said about a file that does not parse
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
// Being in components.js means "this is a component", and the runtime loads
|
|
874
|
+
// one with `const { default: myClass } = await import(...)` (Slice.getClass).
|
|
875
|
+
// Without a default export that entry can never resolve, so it is a broken
|
|
876
|
+
// registration, not a style issue.
|
|
877
|
+
//
|
|
878
|
+
// components.js is auto-generated by scanning directories, so a plain module
|
|
879
|
+
// parked at <Category>/<Name>/<Name>.js gets registered by accident. The fix
|
|
880
|
+
// is to move it out of the components tree — it is a module, not a component.
|
|
881
|
+
if (hasDefaultExport(source) === false) {
|
|
882
|
+
sourceErrors.push({
|
|
883
|
+
component: componentName,
|
|
884
|
+
message: `${componentFile}: no default export, but it is registered as a component. `
|
|
885
|
+
+ `Slice loads components with \`const { default: myClass } = await import(...)\`, so `
|
|
886
|
+
+ `slice.build('${componentName}') can never resolve. Add a default export, or — if this `
|
|
887
|
+
+ 'is a plain module of constants/helpers — move it out of the components tree so it '
|
|
888
|
+
+ 'stops being auto-registered.'
|
|
889
|
+
});
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
const unresolved = findUnresolvedRelativeImports(source, path.dirname(componentFile));
|
|
893
|
+
if (unresolved.length > 0) {
|
|
894
|
+
sourceErrors.push({
|
|
895
|
+
component: componentName,
|
|
896
|
+
message: `${componentFile}: cannot resolve ${unresolved.map((s2) => `"${s2}"`).join(', ')}. `
|
|
897
|
+
+ 'An unresolved relative import silently becomes `undefined` at runtime.'
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
// A warning, not an error: components legitimately build OPTIONAL ones. The
|
|
902
|
+
// framework's own Button does `if (this.icon) slice.build('Icon', ...)`, and
|
|
903
|
+
// a project that never passes an icon has no reason to install Icon. So an
|
|
904
|
+
// unregistered name is a likely typo, not a certain one.
|
|
905
|
+
const unknownBuilds = findUnknownComponentBuilds(source, registeredNames);
|
|
906
|
+
if (unknownBuilds.length > 0) {
|
|
907
|
+
sourceWarnings.push({
|
|
908
|
+
component: componentName,
|
|
909
|
+
message: `builds ${unknownBuilds.map((n) => `"${n}"`).join(', ')}, not registered in `
|
|
910
|
+
+ 'components.js. If that is a typo it will silently render nothing; if the component '
|
|
911
|
+
+ 'is optional, ignore this.'
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
|
|
806
915
|
const props = extractStaticPropsFromSource(source, componentFile);
|
|
807
916
|
if (!props) continue;
|
|
808
917
|
checkedCount++;
|
|
@@ -825,7 +934,7 @@ const validateComponentProps = async ({ projectRoot }) => {
|
|
|
825
934
|
}
|
|
826
935
|
}
|
|
827
936
|
|
|
828
|
-
return { errors, warnings, checkedCount };
|
|
937
|
+
return { errors, warnings, sourceErrors, sourceWarnings, checkedCount };
|
|
829
938
|
};
|
|
830
939
|
|
|
831
940
|
const generateTypesFile = async ({ projectRoot, outputPath }) => {
|