clarusjs 0.10.0 → 0.11.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/lint.d.ts +82 -0
- package/dist/compiler/lint.js +177 -0
- 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 +196 -106
- 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;
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Island HMR (#53), dev only: a compiled island module that changed calls swap() with its new URL. The page is
|
|
2
|
+
// rendered again by the dev server, each of that component's islands gets its new HTML and the new module, and its
|
|
3
|
+
// state (and that of islands nested in it) carries over by name. Anything that doesn't line up is a full reload.
|
|
4
|
+
// Never part of a build: only dev client modules import it (the plugin's `hot` compile option).
|
|
5
|
+
import { parse, stringify } from './serialize.js';
|
|
6
|
+
/** Swap the islands of the component at `url` (the new module's URL, `…?import&t=…`) in place. */
|
|
7
|
+
export async function swap(url) {
|
|
8
|
+
const next = new URL(url, location.href);
|
|
9
|
+
const pathOf = (el) => new URL(el.getAttribute('src') ?? '', location.href).pathname;
|
|
10
|
+
// The outermost islands of this component: one nested in another is swapped with it.
|
|
11
|
+
const mine = (root) => [...root.querySelectorAll('cl-island')].filter((el) => pathOf(el) === next.pathname && !el.parentElement?.closest(`cl-island[src="${CSS.escape(el.getAttribute('src'))}"]`));
|
|
12
|
+
const old = mine(document);
|
|
13
|
+
if (!old.length)
|
|
14
|
+
return;
|
|
15
|
+
try {
|
|
16
|
+
const res = await fetch(location.href, { headers: { accept: 'text/html' } });
|
|
17
|
+
if (!res.ok)
|
|
18
|
+
throw new Error(`${res.status}`);
|
|
19
|
+
const fresh = mine(new DOMParser().parseFromString(await res.text(), 'text/html'));
|
|
20
|
+
if (fresh.length !== old.length)
|
|
21
|
+
throw new Error('the islands moved');
|
|
22
|
+
old.forEach((el, i) => {
|
|
23
|
+
// The island's own attributes (props a parent island may have changed, attach mode), the new markup and module.
|
|
24
|
+
const swapped = el.cloneNode(false);
|
|
25
|
+
swapped.removeAttribute('data-cl-ready');
|
|
26
|
+
swapped.removeAttribute('data-cl-error');
|
|
27
|
+
swapped.setAttribute('src', next.pathname + next.search);
|
|
28
|
+
swapped.replaceChildren(...[...fresh[i].childNodes].map((n) => document.importNode(n, true)));
|
|
29
|
+
swapped.setAttribute('s', fresh[i].getAttribute('s') ?? '{}');
|
|
30
|
+
// State: what the server rendered with, then what the running version had, island by island in page order.
|
|
31
|
+
const before = [el, ...el.querySelectorAll('cl-island')];
|
|
32
|
+
const after = [swapped, ...swapped.querySelectorAll('cl-island')];
|
|
33
|
+
if (before.length === after.length) {
|
|
34
|
+
before.forEach((b, j) => {
|
|
35
|
+
const state = pathOf(b) === pathOf(after[j]) ? b.__cl_hot?.() : undefined;
|
|
36
|
+
if (state)
|
|
37
|
+
after[j].setAttribute('s', stringify({ ...parse(after[j].getAttribute('s') ?? '{}'), ...state }));
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
el.replaceWith(swapped);
|
|
41
|
+
});
|
|
42
|
+
// The loader disposes the replaced islands (no longer in the page) and attaches the new ones.
|
|
43
|
+
await globalThis.__clAttach?.(document);
|
|
44
|
+
if (document.querySelector('cl-island[data-cl-error]'))
|
|
45
|
+
throw new Error('the new version failed to attach');
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
console.warn('[clarusjs] reloading: the changed island could not be swapped in place', err);
|
|
49
|
+
location.reload();
|
|
50
|
+
}
|
|
51
|
+
}
|
package/dist/runtime/server.d.ts
CHANGED
|
@@ -14,3 +14,13 @@ export declare const attr: typeof attrHtml;
|
|
|
14
14
|
* @internal clarusjs's own server code calls this; apps don't.
|
|
15
15
|
*/
|
|
16
16
|
export declare function toBrowser(value: unknown, path?: string, seen?: Set<object>): string;
|
|
17
|
+
/**
|
|
18
|
+
* The data a component's loader returned for the page being rendered (#97), or nothing outside such a render. Read by
|
|
19
|
+
* compiled components that have a loader. @internal
|
|
20
|
+
*/
|
|
21
|
+
export declare function loaded(key: string): object;
|
|
22
|
+
/**
|
|
23
|
+
* Render with component loaders' results available to `loaded()`. Rendering is synchronous, so one render's data never
|
|
24
|
+
* reaches another's; the previous data is restored afterwards, even when the render throws. @internal
|
|
25
|
+
*/
|
|
26
|
+
export declare function withLoaded<T>(data: Map<string, object>, render: () => T): T;
|
package/dist/runtime/server.js
CHANGED
|
@@ -31,3 +31,25 @@ export function toBrowser(value, path = '', seen = new Set()) {
|
|
|
31
31
|
}
|
|
32
32
|
return path ? '' : stringify(value);
|
|
33
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* The data a component's loader returned for the page being rendered (#97), or nothing outside such a render. Read by
|
|
36
|
+
* compiled components that have a loader. @internal
|
|
37
|
+
*/
|
|
38
|
+
export function loaded(key) {
|
|
39
|
+
return globalThis.__clLoaded?.get(key) ?? {};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Render with component loaders' results available to `loaded()`. Rendering is synchronous, so one render's data never
|
|
43
|
+
* reaches another's; the previous data is restored afterwards, even when the render throws. @internal
|
|
44
|
+
*/
|
|
45
|
+
export function withLoaded(data, render) {
|
|
46
|
+
const scope = globalThis;
|
|
47
|
+
const outer = scope.__clLoaded;
|
|
48
|
+
scope.__clLoaded = data;
|
|
49
|
+
try {
|
|
50
|
+
return render();
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
scope.__clLoaded = outer;
|
|
54
|
+
}
|
|
55
|
+
}
|