clarusjs 0.10.0 → 0.12.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/dist/cli/check.d.ts +7 -0
- package/dist/cli/check.js +14 -6
- package/dist/cli/explain.js +1 -1
- package/dist/cli/index.js +6 -3
- package/dist/cli/project.d.ts +7 -2
- package/dist/cli/project.js +4 -3
- package/dist/compiler/emit-client.d.ts +2 -1
- package/dist/compiler/emit-client.js +9 -2
- package/dist/compiler/emit-server.d.ts +1 -1
- package/dist/compiler/emit-server.js +4 -1
- package/dist/compiler/index.d.ts +3 -0
- package/dist/compiler/index.js +3 -2
- package/dist/compiler/ir.js +11 -5
- package/dist/compiler/lint.d.ts +82 -0
- package/dist/compiler/lint.js +177 -0
- package/dist/compiler/script.d.ts +10 -0
- package/dist/compiler/script.js +61 -0
- package/dist/forms/index.js +4 -1
- package/dist/runtime/hot.d.ts +2 -0
- package/dist/runtime/hot.js +51 -0
- package/dist/runtime/server.d.ts +10 -0
- package/dist/runtime/server.js +22 -0
- package/dist/server/handler.d.ts +101 -4
- package/dist/server/handler.js +232 -9
- package/dist/vite/aliases.js +3 -3
- package/dist/vite/build.d.ts +1 -0
- package/dist/vite/build.js +1 -1
- package/dist/vite/manifest.d.ts +3 -0
- package/dist/vite/manifest.js +2 -2
- package/dist/vite/node.js +4 -1
- package/dist/vite/plugin.d.ts +18 -2
- package/dist/vite/plugin.js +204 -107
- package/package.json +1 -1
package/dist/cli/check.d.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
import { type LintConfig, type LintRuleDef } from '../compiler/lint.ts';
|
|
2
|
+
/** A type error, a template error, or a lint finding (#304: `code` is the rule, usually a warning). */
|
|
1
3
|
export type Diagnostic = {
|
|
2
4
|
file: string;
|
|
3
5
|
line: number;
|
|
4
6
|
column: number;
|
|
7
|
+
severity: 'error' | 'warning';
|
|
5
8
|
code: string;
|
|
6
9
|
message: string;
|
|
7
10
|
};
|
|
@@ -22,9 +25,13 @@ export type CheckSource = {
|
|
|
22
25
|
addDependency(file: string): void;
|
|
23
26
|
}): string;
|
|
24
27
|
};
|
|
28
|
+
/** `lint`: the plugin's rule levels; `lintRules`: the project's own rules; `strict`: warnings fail too. */
|
|
25
29
|
export declare function check(options: {
|
|
26
30
|
root: string;
|
|
27
31
|
typescript?: string;
|
|
28
32
|
sources?: CheckSource[];
|
|
29
33
|
viteAliases?: unknown;
|
|
34
|
+
lint?: LintConfig;
|
|
35
|
+
lintRules?: LintRuleDef[];
|
|
36
|
+
strict?: boolean;
|
|
30
37
|
}): CheckResult;
|
package/dist/cli/check.js
CHANGED
|
@@ -3,6 +3,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync,
|
|
|
3
3
|
import { createRequire } from 'node:module';
|
|
4
4
|
import { basename, dirname, relative, resolve, sep } from 'node:path';
|
|
5
5
|
import { ClarusError } from '../compiler/errors.js';
|
|
6
|
+
import { lint } from '../compiler/lint.js';
|
|
6
7
|
import { generateTs, routesDeclaration, toSourceOffset, viewsDeclaration } from '../check/generate.js';
|
|
7
8
|
import { findClarusFiles, reachableComponents } from '../vite/build.js';
|
|
8
9
|
import { projectAliases, resolveAlias } from '../vite/aliases.js';
|
|
@@ -65,10 +66,17 @@ export function check(options) {
|
|
|
65
66
|
source = src.toTscl(original, path, { route: routeFromFile(`/${file}`), root, addDependency: () => { } });
|
|
66
67
|
}
|
|
67
68
|
catch (err) {
|
|
68
|
-
diagnostics.push({ file, line: 1, column: 1, code: 'clarus', message: err.message });
|
|
69
|
+
diagnostics.push({ file, line: 1, column: 1, severity: 'error', code: 'clarus', message: err.message });
|
|
69
70
|
continue;
|
|
70
71
|
}
|
|
71
72
|
views.push({ file, source });
|
|
73
|
+
if (!src) {
|
|
74
|
+
try {
|
|
75
|
+
for (const m of lint(source, file, options.lint, options.lintRules))
|
|
76
|
+
diagnostics.push({ file, line: m.line, column: m.column, severity: m.severity, code: m.rule, message: m.message });
|
|
77
|
+
}
|
|
78
|
+
catch { }
|
|
79
|
+
}
|
|
72
80
|
try {
|
|
73
81
|
const loader = loaderOf(path);
|
|
74
82
|
const { code, mappings, loaderSpan } = generateTs(source, file, loader ? { loader } : {});
|
|
@@ -83,7 +91,7 @@ export function check(options) {
|
|
|
83
91
|
const message = err.message.slice(`${err.file}:${err.line}:${err.column} `.length);
|
|
84
92
|
const lines = source.split('\n');
|
|
85
93
|
const at = src ? inSource(original, source, lines.slice(0, err.line - 1).reduce((n, l) => n + l.length + 1, 0) + err.column - 1) : null;
|
|
86
|
-
diagnostics.push({ file, ...(src ? (at === null ? { line: 1, column: 1 } : position(original, at)) : { line: err.line, column: err.column }), code: 'clarus', message });
|
|
94
|
+
diagnostics.push({ file, ...(src ? (at === null ? { line: 1, column: 1 } : position(original, at)) : { line: err.line, column: err.column }), severity: 'error', code: 'clarus', message });
|
|
87
95
|
}
|
|
88
96
|
}
|
|
89
97
|
const appRoot = realpathSync(root);
|
|
@@ -168,7 +176,7 @@ export function check(options) {
|
|
|
168
176
|
if (g?.fromPackage || (!g && (!resolve(path).startsWith(resolve(root) + sep) || path.includes(`${sep}node_modules${sep}`))))
|
|
169
177
|
continue;
|
|
170
178
|
if (!g) {
|
|
171
|
-
diagnostics.push({ file: posix(relative(root, path)), line: Number(m[2]), column: Number(m[3]), code: m[4], message: m[5] });
|
|
179
|
+
diagnostics.push({ file: posix(relative(root, path)), line: Number(m[2]), column: Number(m[3]), severity: 'error', code: m[4], message: m[5] });
|
|
172
180
|
continue;
|
|
173
181
|
}
|
|
174
182
|
const lines = g.code.split('\n');
|
|
@@ -179,13 +187,13 @@ export function check(options) {
|
|
|
179
187
|
const at = source === null ? { line: 1, column: 1 } : position(g.original ?? g.source, source);
|
|
180
188
|
const fromLoader = g.loaderSpan && offset >= g.loaderSpan[0] && offset < g.loaderSpan[1];
|
|
181
189
|
const message = fromLoader ? `load() returns a value that doesn't fit this page's inputs: ${m[5]}` : source === null ? `${m[5]} (in generated code)` : m[5];
|
|
182
|
-
diagnostics.push({ file: g.file, ...at, code: m[4], message });
|
|
190
|
+
diagnostics.push({ file: g.file, ...at, severity: 'error', code: m[4], message });
|
|
183
191
|
}
|
|
184
192
|
diagnostics.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column);
|
|
185
193
|
return {
|
|
186
194
|
diagnostics,
|
|
187
|
-
exitCode: diagnostics.
|
|
188
|
-
text: diagnostics.map((d) => `${d.file}:${d.line}:${d.column}
|
|
195
|
+
exitCode: diagnostics.some((d) => d.severity === 'error' || options.strict) ? 1 : 0,
|
|
196
|
+
text: diagnostics.map((d) => `${d.file}:${d.line}:${d.column} ${d.severity} ${d.code}: ${d.message}`).join('\n'),
|
|
189
197
|
json: JSON.stringify(diagnostics, null, 2),
|
|
190
198
|
};
|
|
191
199
|
}
|
package/dist/cli/explain.js
CHANGED
|
@@ -13,7 +13,7 @@ function describe(path, r) {
|
|
|
13
13
|
return [
|
|
14
14
|
path,
|
|
15
15
|
...row('Rendered', ['on every request, by dist/server/index.mjs']),
|
|
16
|
-
...row('Data', [r.loader === 'request' ?
|
|
16
|
+
...row('Data', [r.loader === 'request' ? `load() runs on every request${r.cookies ? ', and reads cookies' : ''}` : 'no loader']),
|
|
17
17
|
...row('Islands', ['decided per request']),
|
|
18
18
|
].join('\n');
|
|
19
19
|
}
|
package/dist/cli/index.js
CHANGED
|
@@ -7,16 +7,19 @@ import { serve } from './mapper.js';
|
|
|
7
7
|
const program = new Command('clarusjs').description('clarusjs: clear, compiled views');
|
|
8
8
|
program
|
|
9
9
|
.command('check')
|
|
10
|
-
.description('type-check every .tscl file under src/ and every page (Markdown pages too), reporting
|
|
10
|
+
.description('type-check and lint every .tscl file under src/ and every page (Markdown pages too), reporting each finding where it is written')
|
|
11
11
|
.argument('[dir]', 'project folder', '.')
|
|
12
12
|
.option('--json', 'print diagnostics as JSON')
|
|
13
|
+
.option('--strict', 'fail on lint warnings too')
|
|
13
14
|
.action(async (dir, options) => {
|
|
14
|
-
const result = check({ root: dir, ...(await loadProject(dir)) });
|
|
15
|
+
const result = check({ root: dir, ...(await loadProject(dir)), strict: options.strict });
|
|
15
16
|
if (options.json)
|
|
16
17
|
console.log(result.json);
|
|
17
18
|
else if (result.diagnostics.length) {
|
|
19
|
+
const count = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
|
|
20
|
+
const errors = result.diagnostics.filter((d) => d.severity === 'error').length;
|
|
18
21
|
console.log(result.text);
|
|
19
|
-
console.log(`\n${result.diagnostics.length
|
|
22
|
+
console.log(`\n${[errors && count(errors, 'error'), result.diagnostics.length - errors && count(result.diagnostics.length - errors, 'warning')].filter(Boolean).join(', ')}`);
|
|
20
23
|
}
|
|
21
24
|
else
|
|
22
25
|
console.log('No errors.');
|
package/dist/cli/project.d.ts
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import type { CheckSource } from './check.ts';
|
|
2
|
-
|
|
2
|
+
import type { LintConfig, LintRuleDef } from '../compiler/lint.ts';
|
|
3
|
+
type Project = {
|
|
3
4
|
sources: CheckSource[];
|
|
4
5
|
viteAliases: unknown;
|
|
5
|
-
|
|
6
|
+
lint: LintConfig | undefined;
|
|
7
|
+
lintRules: LintRuleDef[];
|
|
8
|
+
};
|
|
9
|
+
export declare function loadProject(root: string): Promise<Project>;
|
|
10
|
+
export {};
|
package/dist/cli/project.js
CHANGED
|
@@ -5,17 +5,18 @@ async function flatten(plugins) {
|
|
|
5
5
|
return (await Promise.all(value.map(flatten))).flat();
|
|
6
6
|
return value && typeof value === 'object' ? [value] : [];
|
|
7
7
|
}
|
|
8
|
+
const none = { sources: [], viteAliases: undefined, lint: undefined, lintRules: [] };
|
|
8
9
|
export async function loadProject(root) {
|
|
9
10
|
let vite;
|
|
10
11
|
try {
|
|
11
12
|
vite = await import('vite');
|
|
12
13
|
}
|
|
13
14
|
catch {
|
|
14
|
-
return
|
|
15
|
+
return none;
|
|
15
16
|
}
|
|
16
17
|
const loaded = await vite.loadConfigFromFile({ command: 'build', mode: 'production' }, undefined, resolve(root), 'silent');
|
|
17
18
|
if (!loaded)
|
|
18
|
-
return
|
|
19
|
+
return none;
|
|
19
20
|
const plugin = (await flatten(loaded.config.plugins)).find((p) => p.name === 'clarusjs');
|
|
20
|
-
return { sources: plugin?.api?.sources ?? [], viteAliases: loaded.config.resolve?.alias };
|
|
21
|
+
return { sources: plugin?.api?.sources ?? [], viteAliases: loaded.config.resolve?.alias, lint: plugin?.api?.lint, lintRules: plugin?.api?.lintRules ?? [] };
|
|
21
22
|
}
|
|
@@ -1,2 +1,3 @@
|
|
|
1
1
|
import type { ComponentIR } from './ir.ts';
|
|
2
|
-
|
|
2
|
+
/** `hot`: in dev, the module that swaps a changed island in place (#53); its updates are accepted. */
|
|
3
|
+
export declare function emitClient(ir: ComponentIR, hot?: string): string;
|
|
@@ -2,7 +2,7 @@ import { FOR_IMPLICIT } from './parse.js';
|
|
|
2
2
|
import { attrValueExpr, componentCall, htmlExpr, tagArg, walk, whichExpr, rowNames, rowParams, rowDerived } from './html-expr.js';
|
|
3
3
|
import { formName, rewriteClient, rewriteClientExpr, wrapExpr } from './script.js';
|
|
4
4
|
import { indentScript, inputsLine, renderName } from './shared.js';
|
|
5
|
-
export function emitClient(ir) {
|
|
5
|
+
export function emitClient(ir, hot) {
|
|
6
6
|
if (!ir.stateful)
|
|
7
7
|
return 'export {}\n';
|
|
8
8
|
const kinds = new Set(ir.signals.values());
|
|
@@ -34,6 +34,8 @@ export function emitClient(ir) {
|
|
|
34
34
|
hasRegions && 'regionHtml as __cl_regionHtml',
|
|
35
35
|
].filter(Boolean);
|
|
36
36
|
let out = used.length ? `import { ${used.join(', ')} } from 'clarusjs/runtime'\n` : '';
|
|
37
|
+
if (hot)
|
|
38
|
+
out += `import { swap as __cl_swap } from ${JSON.stringify(hot)}\n`;
|
|
37
39
|
const usedComponents = new Set(all.flatMap((n) => (n.kind === 'component' ? [n.name] : [])));
|
|
38
40
|
for (const imp of ir.imports) {
|
|
39
41
|
if (usedComponents.has(imp.name))
|
|
@@ -60,9 +62,14 @@ export function emitClient(ir) {
|
|
|
60
62
|
const lines = wiring(ir, ir.nodes, undefined, '__cl_root', ir.signals, 0);
|
|
61
63
|
if (lines.length)
|
|
62
64
|
out += '\n' + lines.map((l) => ` ${l}\n`).join('');
|
|
65
|
+
if (hot)
|
|
66
|
+
out += ` __cl_root.__cl_hot = () => ({ ${[...ir.signals].filter(([, kind]) => kind === 'state').map(([name]) => `${name}: ${name}.get()`).join(', ')} })\n`;
|
|
63
67
|
if (inputs.length)
|
|
64
68
|
out += ` return (__cl_p) => __cl_batch(() => {\n${inputs.map((i) => ` ${i.name}.${i.model ? 'own' : 'set'}(${value(i, '__cl_p')})\n`).join('')} })\n`;
|
|
65
|
-
|
|
69
|
+
out += '}\n';
|
|
70
|
+
if (hot)
|
|
71
|
+
out += `\nif (import.meta.hot) { import.meta.hot.accept(); if (import.meta.hot.data.cl) __cl_swap(import.meta.url); import.meta.hot.data.cl = 1 }\n`;
|
|
72
|
+
return out;
|
|
66
73
|
}
|
|
67
74
|
function rewriter(signals) {
|
|
68
75
|
return {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import type { ComponentIR } from './ir.ts';
|
|
2
|
-
export declare function emitServer(ir: ComponentIR, clientUrl: string, renderImports?: boolean): string;
|
|
2
|
+
export declare function emitServer(ir: ComponentIR, clientUrl: string, renderImports?: boolean, loader?: string): string;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { htmlExpr, walk } from './html-expr.js';
|
|
2
2
|
import { rewriteServer } from './script.js';
|
|
3
3
|
import { indentScript, inputsLine, renderName } from './shared.js';
|
|
4
|
-
export function emitServer(ir, clientUrl, renderImports = false) {
|
|
4
|
+
export function emitServer(ir, clientUrl, renderImports = false, loader) {
|
|
5
5
|
const all = walk(ir.nodes);
|
|
6
6
|
const runtime = [
|
|
7
7
|
'escape as __cl_escape',
|
|
@@ -11,6 +11,7 @@ export function emitServer(ir, clientUrl, renderImports = false) {
|
|
|
11
11
|
all.some((n) => n.kind === 'if' && n.block >= 0) && 'blockHtml as __cl_blockHtml',
|
|
12
12
|
all.some((n) => n.kind === 'for' && n.block >= 0) && 'forHtml as __cl_forHtml',
|
|
13
13
|
all.some((n) => n.kind === 'component' && n.region >= 0) && 'regionHtml as __cl_regionHtml',
|
|
14
|
+
loader && 'loaded as __cl_loaded',
|
|
14
15
|
].filter(Boolean).join(', ');
|
|
15
16
|
let out = `import { ${runtime} } from 'clarusjs/runtime/server'\n`;
|
|
16
17
|
for (const imp of ir.imports)
|
|
@@ -28,6 +29,8 @@ export function emitServer(ir, clientUrl, renderImports = false) {
|
|
|
28
29
|
out += unknownSlotCheck(ir);
|
|
29
30
|
out += ` if (__cl_opts?.attach) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> has no <script>, so attach="`)} + __cl_opts.attach + '" does nothing')\n`;
|
|
30
31
|
}
|
|
32
|
+
if (loader)
|
|
33
|
+
out += ` __cl_props = { ...__cl_loaded(${JSON.stringify(loader)}), ...__cl_props }\n`;
|
|
31
34
|
out += inputsLine(ir);
|
|
32
35
|
out += ` const __cl_class = __cl_opts?.class ? " " + __cl_opts.class : ""\n`;
|
|
33
36
|
if (ir.script)
|
package/dist/compiler/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ClarusError } from './errors.ts';
|
|
2
2
|
export { ClarusError } from './errors.ts';
|
|
3
3
|
export { parse } from './parse.ts';
|
|
4
|
+
export { lint, lintRules, type LintRule, type LintLevel, type LintConfig, type LintMessage, type LintRuleDef, type LintContext, type LintElement } from './lint.ts';
|
|
4
5
|
export type { ParsedFile, InputDecl, ImportDecl, TemplateNode, Attr } from './parse.ts';
|
|
5
6
|
/**
|
|
6
7
|
* `renderImports`: import child components' render functions with `?render`, for a render module that runs in the
|
|
@@ -19,6 +20,8 @@ export type CompileOptions = {
|
|
|
19
20
|
renderImports?: boolean;
|
|
20
21
|
scope?: string;
|
|
21
22
|
collapseWhitespace?: boolean;
|
|
23
|
+
loader?: string;
|
|
24
|
+
hot?: string;
|
|
22
25
|
};
|
|
23
26
|
/**
|
|
24
27
|
* `css`: the component's stylesheet (`<style scoped>` blocks wrapped in @scope, the others as written); '' without
|
package/dist/compiler/index.js
CHANGED
|
@@ -5,6 +5,7 @@ import { lower } from './ir.js';
|
|
|
5
5
|
import { parse } from './parse.js';
|
|
6
6
|
export { ClarusError } from './errors.js';
|
|
7
7
|
export { parse } from './parse.js';
|
|
8
|
+
export { lint, lintRules } from './lint.js';
|
|
8
9
|
export function compile(source, options) {
|
|
9
10
|
const parsed = parse(source, options.file);
|
|
10
11
|
const warnings = [];
|
|
@@ -26,10 +27,10 @@ export function compile(source, options) {
|
|
|
26
27
|
const ir = lower(parsed, options.file, source, { collapseWhitespace: options.collapseWhitespace });
|
|
27
28
|
warnings.push(...ir.warnings);
|
|
28
29
|
if (options.target === 'client')
|
|
29
|
-
return { code: emitClient(ir), stateful: ir.stateful, css, warnings };
|
|
30
|
+
return { code: emitClient(ir, options.hot), stateful: ir.stateful, css, warnings };
|
|
30
31
|
if (ir.stateful && !options.clientUrl)
|
|
31
32
|
throw new Error(`[clarusjs] ${options.file}: clientUrl is required to compile a stateful component for the server`);
|
|
32
|
-
return { code: emitServer(ir, options.clientUrl ?? '', options.renderImports), stateful: ir.stateful, css, warnings };
|
|
33
|
+
return { code: emitServer(ir, options.clientUrl ?? '', options.renderImports, options.loader), stateful: ir.stateful, css, warnings };
|
|
33
34
|
}
|
|
34
35
|
export function scopeId(file) {
|
|
35
36
|
let h = 0x811c9dc5;
|
package/dist/compiler/ir.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { parseExpressionAt } from 'acorn';
|
|
2
2
|
import { ClarusError } from './errors.js';
|
|
3
3
|
import { FOR_IMPLICIT, importNames } from './parse.js';
|
|
4
|
-
import { analyzeScript, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, splitImports } from './script.js';
|
|
4
|
+
import { analyzeScript, mutationsOf, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, splitImports } from './script.js';
|
|
5
5
|
const ATTACH_MODES = ['load', 'idle', 'visible', 'interaction'];
|
|
6
6
|
const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
|
|
7
7
|
export function lower(parsed, file, source, options = {}) {
|
|
@@ -49,6 +49,10 @@ export function lower(parsed, file, source, options = {}) {
|
|
|
49
49
|
if (parsed.script && inputNames.size)
|
|
50
50
|
for (const w of writesTo(parsed.script.code, inputNames))
|
|
51
51
|
readOnly(w.name, parsed.script.start + w.start);
|
|
52
|
+
const stateNames = new Set(signals.keys());
|
|
53
|
+
if (parsed.script)
|
|
54
|
+
for (const m of mutationsOf(parsed.script.code, stateNames))
|
|
55
|
+
warnings.push(new ClarusError(m.message, file, source, parsed.script.start + m.start));
|
|
52
56
|
for (const d of parsed.dataImports) {
|
|
53
57
|
if (stateful && d.from.startsWith('node:'))
|
|
54
58
|
fail(`\`${d.from}\` can't be imported in an island: its imports are bundled for the browser`, d.start);
|
|
@@ -326,12 +330,14 @@ export function lower(parsed, file, source, options = {}) {
|
|
|
326
330
|
if (!stateful)
|
|
327
331
|
fail('event bindings need a <script> with state; this component is static', a.start);
|
|
328
332
|
checkHandler(a.expr, file, source, a.start);
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
333
|
+
const found = source.indexOf(a.expr, a.start);
|
|
334
|
+
const exprStart = found === -1 ? a.start : found;
|
|
335
|
+
if (inputNames.size)
|
|
332
336
|
for (const w of writesTo(a.expr, inputNames))
|
|
333
337
|
readOnly(w.name, exprStart + w.start);
|
|
334
|
-
|
|
338
|
+
if (found !== -1)
|
|
339
|
+
for (const m of mutationsOf(a.expr, stateNames))
|
|
340
|
+
warnings.push(new ClarusError(m.message, file, source, exprStart + m.start));
|
|
335
341
|
}
|
|
336
342
|
else if (a.kind === 'prop' && a.name === 'engine') {
|
|
337
343
|
if (!stateful)
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { type ParsedFile, type TemplateNode } from './parse.ts';
|
|
2
|
+
/**
|
|
3
|
+
* The built-in rules' names.
|
|
4
|
+
* @see https://clarusjs.com/guide/lint#rules
|
|
5
|
+
*/
|
|
6
|
+
export type LintRule = 'unused-input' | 'unused-import' | 'img-alt' | 'label-field' | 'accessible-name';
|
|
7
|
+
/**
|
|
8
|
+
* Each rule's level, built-in or a project's, keyed by rule name.
|
|
9
|
+
* @see https://clarusjs.com/guide/lint#warnings-and-errors
|
|
10
|
+
*/
|
|
11
|
+
export type LintConfig = Partial<Record<LintRule, LintLevel>> & Record<string, LintLevel>;
|
|
12
|
+
/**
|
|
13
|
+
* A rule's level: 'warn' (the default), 'error', or 'off'.
|
|
14
|
+
* @see https://clarusjs.com/guide/lint#warnings-and-errors
|
|
15
|
+
*/
|
|
16
|
+
export type LintLevel = 'off' | 'warn' | 'error';
|
|
17
|
+
/**
|
|
18
|
+
* A finding, at its 1-based line and column (`start`: its offset in the source).
|
|
19
|
+
* @see https://clarusjs.com/reference/compiler#lint
|
|
20
|
+
*/
|
|
21
|
+
export type LintMessage = {
|
|
22
|
+
rule: string;
|
|
23
|
+
severity: 'warning' | 'error';
|
|
24
|
+
message: string;
|
|
25
|
+
file: string;
|
|
26
|
+
line: number;
|
|
27
|
+
column: number;
|
|
28
|
+
start: number;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* A template element, as `parse` returns it.
|
|
32
|
+
* @see https://clarusjs.com/guide/lint#writing-a-rule
|
|
33
|
+
*/
|
|
34
|
+
export type LintElement = Extract<TemplateNode, {
|
|
35
|
+
type: 'element';
|
|
36
|
+
}>;
|
|
37
|
+
/**
|
|
38
|
+
* What a rule's check() gets: the file, its syntax tree, every element in it, and report().
|
|
39
|
+
* @see https://clarusjs.com/guide/lint#writing-a-rule
|
|
40
|
+
*/
|
|
41
|
+
export type LintContext = {
|
|
42
|
+
file: string;
|
|
43
|
+
source: string;
|
|
44
|
+
parsed: ParsedFile;
|
|
45
|
+
/** Every element, in branches, rows, empty content and slot fills too, in source order. */
|
|
46
|
+
elements: LintElement[];
|
|
47
|
+
/** The names of the components this file imports (their tags). */
|
|
48
|
+
components: Set<string>;
|
|
49
|
+
/** Whether the template, the script, or an input's type or default reads `name`. */
|
|
50
|
+
reads(name: string): boolean;
|
|
51
|
+
/** A finding at `start`, an offset in the source (an element's, an attribute's, an @input's). */
|
|
52
|
+
report(start: number, message: string): void;
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* A lint rule: a name (used in levels and ignore comments) and a check over one file.
|
|
56
|
+
* @see https://clarusjs.com/guide/lint#writing-a-rule
|
|
57
|
+
*/
|
|
58
|
+
export type LintRuleDef = {
|
|
59
|
+
name: string;
|
|
60
|
+
check(context: LintContext): void;
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* The built-in rules, each written as a project's own would be.
|
|
64
|
+
* @example
|
|
65
|
+
* ```ts
|
|
66
|
+
* import { lintRules } from 'clarusjs/compiler'
|
|
67
|
+
* console.log(lintRules.map((r) => r.name)) // ['unused-input', 'unused-import', …]
|
|
68
|
+
* ```
|
|
69
|
+
* @see https://clarusjs.com/guide/lint#rules
|
|
70
|
+
*/
|
|
71
|
+
export declare const lintRules: LintRuleDef[];
|
|
72
|
+
/**
|
|
73
|
+
* Lint a `.tscl` file's template with the built-in rules and `extra` ones, at the levels in `config`. Throws a
|
|
74
|
+
* located `ClarusError` for a syntax error, as `parse` does.
|
|
75
|
+
* @example
|
|
76
|
+
* ```ts
|
|
77
|
+
* import { lint } from 'clarusjs/compiler'
|
|
78
|
+
* for (const m of lint(source, 'src/components/card.tscl')) console.log(`${m.line}:${m.column} ${m.rule}: ${m.message}`)
|
|
79
|
+
* ```
|
|
80
|
+
* @see https://clarusjs.com/reference/compiler#lint
|
|
81
|
+
*/
|
|
82
|
+
export declare function lint(source: string, file: string, config?: LintConfig, extra?: LintRuleDef[]): LintMessage[];
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { ClarusError } from './errors.js';
|
|
2
|
+
import { importNames, parse } from './parse.js';
|
|
3
|
+
const FIELDS = new Set(['input', 'select', 'textarea', 'meter', 'output', 'progress']);
|
|
4
|
+
const IGNORE_RE = /\{\{--\s*clarusjs-ignore\b([\w\s,-]*?)\s*--\}\}/g;
|
|
5
|
+
function* elements(nodes) {
|
|
6
|
+
for (const n of nodes) {
|
|
7
|
+
if (n.type === 'element') {
|
|
8
|
+
yield n;
|
|
9
|
+
yield* elements(n.children);
|
|
10
|
+
}
|
|
11
|
+
else if (n.type === 'if')
|
|
12
|
+
for (const b of n.branches)
|
|
13
|
+
yield* elements(b.children);
|
|
14
|
+
else if (n.type === 'for') {
|
|
15
|
+
yield* elements(n.children);
|
|
16
|
+
if (n.empty)
|
|
17
|
+
yield* elements(n.empty);
|
|
18
|
+
}
|
|
19
|
+
else if (n.type === 'fill')
|
|
20
|
+
yield* elements(n.children);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function* expressions(nodes) {
|
|
24
|
+
for (const n of nodes) {
|
|
25
|
+
if (n.type === 'expr')
|
|
26
|
+
yield n.expr;
|
|
27
|
+
else if (n.type === 'element') {
|
|
28
|
+
for (const a of n.attrs) {
|
|
29
|
+
if (a.kind === 'interp')
|
|
30
|
+
for (const p of a.parts) {
|
|
31
|
+
if (typeof p !== 'string')
|
|
32
|
+
yield p.expr;
|
|
33
|
+
}
|
|
34
|
+
else if (a.kind !== 'static')
|
|
35
|
+
yield a.expr;
|
|
36
|
+
}
|
|
37
|
+
yield* expressions(n.children);
|
|
38
|
+
}
|
|
39
|
+
else if (n.type === 'if')
|
|
40
|
+
for (const b of n.branches) {
|
|
41
|
+
if (b.cond)
|
|
42
|
+
yield b.cond;
|
|
43
|
+
yield* expressions(b.children);
|
|
44
|
+
}
|
|
45
|
+
else if (n.type === 'for') {
|
|
46
|
+
yield n.list;
|
|
47
|
+
if (n.track)
|
|
48
|
+
yield n.track;
|
|
49
|
+
yield* expressions(n.children);
|
|
50
|
+
if (n.empty)
|
|
51
|
+
yield* expressions(n.empty);
|
|
52
|
+
}
|
|
53
|
+
else if (n.type === 'fill')
|
|
54
|
+
yield* expressions(n.children);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const has = (el, name) => el.attrs.some((a) => a.name === name);
|
|
58
|
+
const labelled = (el) => has(el, 'aria-label') || has(el, 'aria-labelledby') || has(el, 'title');
|
|
59
|
+
function named(nodes, components) {
|
|
60
|
+
return nodes.some((n) => {
|
|
61
|
+
if (n.type === 'text')
|
|
62
|
+
return n.value.trim() !== '';
|
|
63
|
+
if (n.type === 'expr' || n.type === 'raw')
|
|
64
|
+
return true;
|
|
65
|
+
if (n.type === 'if')
|
|
66
|
+
return n.branches.some((b) => named(b.children, components));
|
|
67
|
+
if (n.type === 'for')
|
|
68
|
+
return named(n.children, components);
|
|
69
|
+
if (n.type !== 'element')
|
|
70
|
+
return false;
|
|
71
|
+
if (components.has(n.tag) || n.tag === 'slot' || n.tag === 'title' || labelled(n))
|
|
72
|
+
return true;
|
|
73
|
+
if (n.tag === 'img')
|
|
74
|
+
return n.attrs.some((a) => a.name === 'alt' && !(a.kind === 'static' && (a.value === true || a.value.trim() === '')));
|
|
75
|
+
return named(n.children, components);
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
export const lintRules = [
|
|
79
|
+
{
|
|
80
|
+
name: 'unused-input',
|
|
81
|
+
check({ parsed, reads, report }) {
|
|
82
|
+
for (const i of parsed.inputs)
|
|
83
|
+
if (!reads(i.name))
|
|
84
|
+
report(i.start, `@${i.model ? 'model' : 'input'} ${i.name} is never used`);
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
{
|
|
88
|
+
name: 'unused-import',
|
|
89
|
+
check({ parsed, elements, reads, report }) {
|
|
90
|
+
const tags = new Set(elements.map((e) => e.tag));
|
|
91
|
+
for (const i of parsed.imports)
|
|
92
|
+
if (!tags.has(i.name) && !reads(i.name))
|
|
93
|
+
report(i.start, `'${i.name}' is imported but never used as <${i.name}>`);
|
|
94
|
+
for (const d of parsed.dataImports) {
|
|
95
|
+
const unused = importNames(d.clause).filter((name) => !reads(name));
|
|
96
|
+
if (unused.length)
|
|
97
|
+
report(d.start, `${unused.map((n) => `'${n}'`).join(', ')} ${unused.length === 1 ? 'is' : 'are'} imported but never used`);
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
name: 'img-alt',
|
|
103
|
+
check({ elements, report }) {
|
|
104
|
+
for (const el of elements)
|
|
105
|
+
if (el.tag === 'img' && !has(el, 'alt'))
|
|
106
|
+
report(el.start, '<img> without alt: describe the image, or use alt="" when it is decoration');
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
name: 'label-field',
|
|
111
|
+
check({ elements: all, components, report }) {
|
|
112
|
+
for (const el of all) {
|
|
113
|
+
if (el.tag !== 'label' || has(el, 'for'))
|
|
114
|
+
continue;
|
|
115
|
+
if (![...elements(el.children)].some((e) => FIELDS.has(e.tag) || components.has(e.tag) || e.tag === 'slot')) {
|
|
116
|
+
report(el.start, '<label> names no field: put the field inside it, or point to one with for="id"');
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
},
|
|
121
|
+
{
|
|
122
|
+
name: 'accessible-name',
|
|
123
|
+
check({ elements, components, report }) {
|
|
124
|
+
for (const el of elements) {
|
|
125
|
+
if (el.tag !== 'button' && !(el.tag === 'a' && has(el, 'href')))
|
|
126
|
+
continue;
|
|
127
|
+
if (!labelled(el) && !named(el.children, components))
|
|
128
|
+
report(el.start, `<${el.tag}> has no accessible name: give it text, aria-label or title`);
|
|
129
|
+
}
|
|
130
|
+
},
|
|
131
|
+
},
|
|
132
|
+
];
|
|
133
|
+
export function lint(source, file, config = {}, extra = []) {
|
|
134
|
+
const parsed = parse(source, file);
|
|
135
|
+
const corpus = [
|
|
136
|
+
...expressions(parsed.nodes),
|
|
137
|
+
parsed.script?.code ?? '',
|
|
138
|
+
...parsed.inputs.flatMap((i) => [i.type, i.default ?? '']),
|
|
139
|
+
...parsed.types.map((t) => t.type),
|
|
140
|
+
].join('\n');
|
|
141
|
+
const lineOf = (offset) => source.slice(0, offset).split('\n').length;
|
|
142
|
+
const ignored = new Map();
|
|
143
|
+
for (const m of source.matchAll(IGNORE_RE)) {
|
|
144
|
+
const names = m[1].split(/[\s,]+/).filter(Boolean);
|
|
145
|
+
const line = lineOf(m.index + m[0].length);
|
|
146
|
+
for (const l of [line, line + 1])
|
|
147
|
+
ignored.set(l, names.length ? new Set(names) : 'all');
|
|
148
|
+
}
|
|
149
|
+
const base = {
|
|
150
|
+
file,
|
|
151
|
+
source,
|
|
152
|
+
parsed,
|
|
153
|
+
elements: [...elements(parsed.nodes)],
|
|
154
|
+
components: new Set(parsed.imports.map((i) => i.name)),
|
|
155
|
+
reads: (name) => new RegExp(`(?<![\\w$.])${name.replace(/\$/g, '\\$')}(?![\\w$])`).test(corpus),
|
|
156
|
+
};
|
|
157
|
+
const out = [];
|
|
158
|
+
const add = (rule, severity, start, message) => {
|
|
159
|
+
const { line, column } = new ClarusError(message, file, source, start);
|
|
160
|
+
const skip = ignored.get(line);
|
|
161
|
+
if (skip === 'all' || skip?.has(rule))
|
|
162
|
+
return;
|
|
163
|
+
out.push({ rule, severity, message, file, line, column, start });
|
|
164
|
+
};
|
|
165
|
+
for (const rule of [...lintRules, ...extra]) {
|
|
166
|
+
const level = config[rule.name] ?? 'warn';
|
|
167
|
+
if (level === 'off')
|
|
168
|
+
continue;
|
|
169
|
+
try {
|
|
170
|
+
rule.check({ ...base, report: (start, message) => add(rule.name, level === 'error' ? 'error' : 'warning', start, message) });
|
|
171
|
+
}
|
|
172
|
+
catch (err) {
|
|
173
|
+
add(rule.name, 'error', 0, `the rule failed: ${err.message}`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return out.sort((a, b) => a.start - b.start);
|
|
177
|
+
}
|
|
@@ -46,6 +46,16 @@ export declare function rewriteClient(code: string, signals: Signals, options?:
|
|
|
46
46
|
export declare function rewriteClientExpr(expr: string, signals: Signals): string;
|
|
47
47
|
export declare function rewriteServer(code: string): string;
|
|
48
48
|
export declare function referencesSignal(expr: string, signals: Signals): boolean;
|
|
49
|
+
/**
|
|
50
|
+
* State changed in place (#350): a mutating method called on one of `names` (`items.push(x)`), or one of its properties
|
|
51
|
+
* written, incremented or deleted (`form.a = 1`). Nothing notifies, so the page doesn't update. Skips places where a
|
|
52
|
+
* local declaration shadows the name. Each with where it starts in `code` and what to write instead.
|
|
53
|
+
*/
|
|
54
|
+
export declare function mutationsOf(code: string, names: Set<string>): {
|
|
55
|
+
name: string;
|
|
56
|
+
start: number;
|
|
57
|
+
message: string;
|
|
58
|
+
}[];
|
|
49
59
|
/** Does `expr` read any of `names`? */
|
|
50
60
|
/**
|
|
51
61
|
* Assignments and ++/-- to any of `names` in a script or event handler, skipping places where a local declaration
|
package/dist/compiler/script.js
CHANGED
|
@@ -367,6 +367,67 @@ export function rewriteServer(code) {
|
|
|
367
367
|
export function referencesSignal(expr, signals) {
|
|
368
368
|
return referencesNames(expr, new Set(signals.keys()));
|
|
369
369
|
}
|
|
370
|
+
const MUTATORS = {
|
|
371
|
+
push: (n) => `${n} = [...${n}, …]`,
|
|
372
|
+
unshift: (n) => `${n} = […, ...${n}]`,
|
|
373
|
+
pop: (n) => `${n} = ${n}.slice(0, -1)`,
|
|
374
|
+
shift: (n) => `${n} = ${n}.slice(1)`,
|
|
375
|
+
splice: (n) => `${n} = ${n}.toSpliced(…)`,
|
|
376
|
+
sort: (n) => `${n} = ${n}.toSorted(…)`,
|
|
377
|
+
reverse: (n) => `${n} = ${n}.toReversed()`,
|
|
378
|
+
fill: (n) => `${n} = ${n}.map(…)`,
|
|
379
|
+
copyWithin: (n) => `${n} = [...${n}]`,
|
|
380
|
+
set: (n) => `${n} = new Map(${n}).set(…)`,
|
|
381
|
+
add: (n) => `${n} = new Set(${n}).add(…)`,
|
|
382
|
+
delete: (n) => `a copy without it: ${n} = new Map(${n}), then delete from that`,
|
|
383
|
+
clear: (n) => `${n} = new Map() or new Set()`,
|
|
384
|
+
};
|
|
385
|
+
function rootOf(node) {
|
|
386
|
+
let n = node;
|
|
387
|
+
while (n.type === 'MemberExpression')
|
|
388
|
+
n = n.object;
|
|
389
|
+
return n.type === 'Identifier' ? n : undefined;
|
|
390
|
+
}
|
|
391
|
+
function chain(node) {
|
|
392
|
+
if (node.type === 'Identifier')
|
|
393
|
+
return node.name;
|
|
394
|
+
if (node.type !== 'MemberExpression')
|
|
395
|
+
return '…';
|
|
396
|
+
return node.computed ? `${chain(node.object)}[…]` : `${chain(node.object)}.${node.property.name}`;
|
|
397
|
+
}
|
|
398
|
+
export function mutationsOf(code, names) {
|
|
399
|
+
const found = [];
|
|
400
|
+
const say = (name, start, what, instead) => found.push({ name, start, message: `${what} changes ${name} in place, so the page won't update: assign a new value instead (${instead})` });
|
|
401
|
+
const visit = (active, entered) => (node, parent, key) => {
|
|
402
|
+
if (!entered.has(node)) {
|
|
403
|
+
const shadowed = [...scopeNames(node)].filter((n) => active.has(n));
|
|
404
|
+
if (shadowed.length) {
|
|
405
|
+
entered.add(node);
|
|
406
|
+
print(node, code, visit(new Set([...active].filter((n) => !shadowed.includes(n))), entered), parent, key);
|
|
407
|
+
return '';
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
if (node.type === 'CallExpression' && node.callee.type === 'MemberExpression' && !node.callee.computed) {
|
|
411
|
+
const method = node.callee.property.name;
|
|
412
|
+
const root = rootOf(node.callee.object);
|
|
413
|
+
if (root && active.has(root.name) && Object.hasOwn(MUTATORS, method)) {
|
|
414
|
+
say(root.name, node.start, `${chain(node.callee.object)}.${method}()`, MUTATORS[method](root.name));
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
const target = node.type === 'AssignmentExpression' ? node.left : node.type === 'UpdateExpression' ? node.argument : node.type === 'UnaryExpression' && node.operator === 'delete' ? node.argument : null;
|
|
418
|
+
if (target?.type === 'MemberExpression') {
|
|
419
|
+
const root = rootOf(target);
|
|
420
|
+
if (root && active.has(root.name)) {
|
|
421
|
+
const what = node.type === 'AssignmentExpression' ? `${chain(target)} ${node.operator} …` : node.type === 'UpdateExpression' ? `${chain(target)}${node.operator}` : `delete ${chain(target)}`;
|
|
422
|
+
const direct = target.object.type === 'Identifier' && !target.computed;
|
|
423
|
+
say(root.name, node.start, what, direct ? `${root.name} = { ...${root.name}, ${target.property.name}: … }` : `${root.name} = { ...${root.name}, … }`);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
return undefined;
|
|
427
|
+
};
|
|
428
|
+
print(parseScript(code), code, visit(names, new WeakSet()));
|
|
429
|
+
return found;
|
|
430
|
+
}
|
|
370
431
|
export function writesTo(code, names) {
|
|
371
432
|
const found = [];
|
|
372
433
|
const visit = (active, entered) => (node, parent, key) => {
|