clarusjs 0.7.0 → 0.8.1
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/check/generate.d.ts +6 -0
- package/dist/check/generate.js +12 -22
- package/dist/cli/check.js +58 -15
- package/dist/cli/explain.js +0 -1
- package/dist/cli/index.js +0 -1
- package/dist/compiler/emit-client.js +1 -11
- package/dist/compiler/emit-server.js +1 -2
- package/dist/compiler/errors.js +0 -1
- package/dist/compiler/html-expr.js +2 -7
- package/dist/compiler/index.js +10 -8
- package/dist/compiler/ir.d.ts +1 -0
- package/dist/compiler/ir.js +9 -14
- package/dist/compiler/parse.d.ts +1 -0
- package/dist/compiler/parse.js +18 -19
- package/dist/compiler/script.js +2 -31
- package/dist/compiler/shared.js +0 -5
- package/dist/runtime/dom.js +4 -1
- package/dist/runtime/fragments.d.ts +1 -1
- package/dist/runtime/fragments.js +10 -30
- package/dist/runtime/html.d.ts +2 -0
- package/dist/runtime/html.js +4 -0
- package/dist/runtime/loader.js +41 -2
- package/dist/runtime/navigate.d.ts +38 -0
- package/dist/runtime/navigate.js +88 -0
- package/dist/runtime/navigation.d.ts +88 -0
- package/dist/runtime/navigation.js +165 -0
- package/dist/runtime/router.d.ts +8 -1
- package/dist/runtime/router.js +32 -42
- package/dist/runtime/server.d.ts +1 -1
- package/dist/runtime/server.js +1 -1
- package/dist/server/handler.d.ts +18 -0
- package/dist/server/handler.js +80 -53
- package/dist/server/head.d.ts +36 -0
- package/dist/server/head.js +129 -0
- package/dist/server/manifest.js +0 -3
- package/dist/server/modes.js +0 -5
- package/dist/server/views.js +0 -7
- package/dist/vite/aliases.d.ts +10 -0
- package/dist/vite/aliases.js +42 -0
- package/dist/vite/build.d.ts +9 -0
- package/dist/vite/build.js +43 -17
- package/dist/vite/links.d.ts +2 -0
- package/dist/vite/links.js +11 -10
- package/dist/vite/manifest.js +2 -10
- package/dist/vite/netlify.js +1 -7
- package/dist/vite/plugin.d.ts +35 -0
- package/dist/vite/plugin.js +162 -88
- package/dist/vite/redirects.d.ts +10 -0
- package/dist/vite/redirects.js +41 -0
- package/dist/vite/sitemap.d.ts +11 -0
- package/dist/vite/sitemap.js +31 -0
- package/package.json +18 -2
package/dist/check/generate.d.ts
CHANGED
|
@@ -25,3 +25,9 @@ export declare function viewsDeclaration(views: {
|
|
|
25
25
|
file: string;
|
|
26
26
|
source: string;
|
|
27
27
|
}[]): string;
|
|
28
|
+
/**
|
|
29
|
+
* .clarusjs/routes.d.ts: every page's route → its params, for href() from clarusjs/navigation. A page is any file
|
|
30
|
+
* under src/pages but scripts (.ts/.js, so .load.ts too), styles and data, and _-prefixed files (partials). Markdown
|
|
31
|
+
* and other page sources count, though check only type-checks .tscl pages (#142).
|
|
32
|
+
*/
|
|
33
|
+
export declare function routesDeclaration(files: string[]): string;
|
package/dist/check/generate.js
CHANGED
|
@@ -1,12 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
// TypeScript that has the same meaning (@if → if, @for → for…of, a component → an object typed as its Inputs), and
|
|
3
|
-
// every copied span is recorded so tsc's errors can be mapped back to the template. Pure: string in, string out.
|
|
1
|
+
import { routeFromFile } from '../server/handler.js';
|
|
4
2
|
import { parse } from '../compiler/parse.js';
|
|
5
3
|
import { splitImports } from '../compiler/script.js';
|
|
6
|
-
/**
|
|
7
|
-
* `loader`: the module specifier of the page's .load.ts when it exports load(); what it returns is checked against
|
|
8
|
-
* the page's inputs. `loaderSpan` is where that check sits in the generated code, so its errors can say so.
|
|
9
|
-
*/
|
|
10
4
|
export function generateTs(source, file, options = {}) {
|
|
11
5
|
const parsed = parse(source, file);
|
|
12
6
|
const mappings = [];
|
|
@@ -14,7 +8,6 @@ export function generateTs(source, file, options = {}) {
|
|
|
14
8
|
const emit = (text) => { code += text; };
|
|
15
9
|
const copy = (text, sourceStart) => { mappings.push([code.length, text.length, sourceStart, true]); code += text; };
|
|
16
10
|
const point = (text, sourceStart) => { mappings.push([code.length, text.length, sourceStart, false]); code += text; };
|
|
17
|
-
// Where a trimmed expression starts in the source, searching from `from`.
|
|
18
11
|
const at = (text, from) => source.indexOf(text, from);
|
|
19
12
|
const components = new Map(parsed.imports.map((imp) => [imp.name, imp]));
|
|
20
13
|
const alias = (name) => `__cl_I_${name.replace(/-/g, '$')}`;
|
|
@@ -56,8 +49,7 @@ export function generateTs(source, file, options = {}) {
|
|
|
56
49
|
emit('}\n');
|
|
57
50
|
let loaderSpan;
|
|
58
51
|
if (options.loader) {
|
|
59
|
-
|
|
60
|
-
emit('declare const __cl_loaded: Awaited<ReturnType<typeof __cl_load>>\n');
|
|
52
|
+
emit('declare const __cl_loaded: Exclude<Awaited<ReturnType<typeof __cl_load>>, Response>\n');
|
|
61
53
|
const start = code.length;
|
|
62
54
|
point('const __cl_from_load: Partial<Inputs> = __cl_loaded', 0);
|
|
63
55
|
loaderSpan = [start, code.length];
|
|
@@ -79,7 +71,7 @@ export function generateTs(source, file, options = {}) {
|
|
|
79
71
|
}
|
|
80
72
|
if (parsed.script && script) {
|
|
81
73
|
copy(script.body, parsed.script.start);
|
|
82
|
-
emit('\n;\n');
|
|
74
|
+
emit('\n;\n');
|
|
83
75
|
}
|
|
84
76
|
const use = (expr, start) => {
|
|
85
77
|
emit(' __cl_use((');
|
|
@@ -130,8 +122,6 @@ export function generateTs(source, file, options = {}) {
|
|
|
130
122
|
case 'element': {
|
|
131
123
|
const component = components.get(node.tag);
|
|
132
124
|
if (component) {
|
|
133
|
-
// An object literal typed as the child's Inputs: unknown props are excess properties, missing ones are
|
|
134
|
-
// reported on the variable, which maps to the tag.
|
|
135
125
|
emit(' { const ');
|
|
136
126
|
point('__cl_p', node.start);
|
|
137
127
|
emit(`: ${alias(node.tag)} = { `);
|
|
@@ -170,7 +160,6 @@ export function generateTs(source, file, options = {}) {
|
|
|
170
160
|
emit('}\n');
|
|
171
161
|
return { code, mappings, loaderSpan };
|
|
172
162
|
}
|
|
173
|
-
/** The template offset for an offset in the virtual file, or null when it falls in generated scaffolding. */
|
|
174
163
|
export function toSourceOffset(mappings, virtualOffset) {
|
|
175
164
|
for (const [v, length, s, exact] of mappings) {
|
|
176
165
|
if (virtualOffset >= v && virtualOffset < v + Math.max(length, 1))
|
|
@@ -178,7 +167,6 @@ export function toSourceOffset(mappings, virtualOffset) {
|
|
|
178
167
|
}
|
|
179
168
|
return null;
|
|
180
169
|
}
|
|
181
|
-
/** 'src/components' + '../domain/user' → 'src/domain/user' (POSIX, no fs). */
|
|
182
170
|
function joinPath(dir, rel) {
|
|
183
171
|
const out = dir.split('/').filter(Boolean);
|
|
184
172
|
for (const part of rel.split('/')) {
|
|
@@ -189,11 +177,6 @@ function joinPath(dir, rel) {
|
|
|
189
177
|
}
|
|
190
178
|
return out.join('/');
|
|
191
179
|
}
|
|
192
|
-
/**
|
|
193
|
-
* .clarusjs/views.d.ts: view name → inputs, as declarations only, so an app's own tsconfig can include it. Each view's
|
|
194
|
-
* inputs are written inline in a namespace; its `@import type`s become import() types with paths relative to
|
|
195
|
-
* .clarusjs/ (where this file lives). Views that don't parse are left out (check reports them).
|
|
196
|
-
*/
|
|
197
180
|
export function viewsDeclaration(views) {
|
|
198
181
|
const lines = ['// Generated by clarusjs check: view name → inputs, for render() from clarusjs/views. Declarations only.'];
|
|
199
182
|
const entries = [];
|
|
@@ -208,7 +191,6 @@ export function viewsDeclaration(views) {
|
|
|
208
191
|
const ns = `__cl_v${i}`;
|
|
209
192
|
const body = [];
|
|
210
193
|
for (const t of parsed.typeImports) {
|
|
211
|
-
// Relative paths are written from .clarusjs/, one level below the project root.
|
|
212
194
|
const from = t.from.startsWith('.') ? `../${joinPath(file.split('/').slice(0, -1).join('/'), t.from)}` : t.from;
|
|
213
195
|
const clause = t.clause.trim();
|
|
214
196
|
if (clause.startsWith('{')) {
|
|
@@ -218,7 +200,6 @@ export function viewsDeclaration(views) {
|
|
|
218
200
|
}
|
|
219
201
|
}
|
|
220
202
|
else if (!clause.startsWith('*')) {
|
|
221
|
-
// ponytail: `* as N` type imports aren't carried into the registry; use named type imports for inputs.
|
|
222
203
|
body.push(` type ${clause} = import(${JSON.stringify(from)}).default`);
|
|
223
204
|
}
|
|
224
205
|
}
|
|
@@ -232,3 +213,12 @@ export function viewsDeclaration(views) {
|
|
|
232
213
|
lines.push("declare module 'clarusjs/views' {", ' interface Views {', ...entries, ' }', '}', 'export {}', '');
|
|
233
214
|
return lines.join('\n');
|
|
234
215
|
}
|
|
216
|
+
export function routesDeclaration(files) {
|
|
217
|
+
const pages = files.filter((f) => f.startsWith('src/pages/') && !/\.(m?[jt]s|css|json)$/.test(f) && !/(^|\/)_[^/]*$/.test(f));
|
|
218
|
+
const routes = [...new Set(pages.map((f) => routeFromFile(`/${f}`)))].sort();
|
|
219
|
+
const entries = routes.map((route) => {
|
|
220
|
+
const keys = [...route.matchAll(/\[([^\]]+)\]/g)].map((m) => m[1]);
|
|
221
|
+
return ` ${JSON.stringify(route)}: ${keys.length ? `{ ${keys.map((k) => `${k}: string`).join('; ')} }` : '{}'}`;
|
|
222
|
+
});
|
|
223
|
+
return ['// Generated by clarusjs check: every page route → its params, for href() from clarusjs/navigation.', "declare module 'clarusjs/navigation' {", ' interface Routes {', ...entries, ' }', '}', 'export {}', ''].join('\n');
|
|
224
|
+
}
|
package/dist/cli/check.js
CHANGED
|
@@ -1,20 +1,25 @@
|
|
|
1
|
-
// `clarusjs check`: type-check every .tscl file in a project (and the .ts it uses) with the project's TypeScript,
|
|
2
|
-
// reporting each error at file.tscl:line:col.
|
|
3
1
|
import { spawnSync } from 'node:child_process';
|
|
4
|
-
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
5
3
|
import { createRequire } from 'node:module';
|
|
6
4
|
import { basename, dirname, relative, resolve, sep } from 'node:path';
|
|
7
5
|
import { ClarusError } from '../compiler/errors.js';
|
|
8
|
-
import { generateTs, toSourceOffset, viewsDeclaration } from '../check/generate.js';
|
|
9
|
-
import { findClarusFiles } from '../vite/build.js';
|
|
6
|
+
import { generateTs, routesDeclaration, toSourceOffset, viewsDeclaration } from '../check/generate.js';
|
|
7
|
+
import { findClarusFiles, reachableComponents } from '../vite/build.js';
|
|
8
|
+
import { projectAliases } from '../vite/aliases.js';
|
|
10
9
|
const VIRTUAL = '.clarusjs/virtual';
|
|
11
10
|
const posix = (path) => path.split(sep).join('/');
|
|
12
|
-
|
|
11
|
+
function packageInfo(file) {
|
|
12
|
+
for (let dir = dirname(file); dir !== dirname(dir); dir = dirname(dir)) {
|
|
13
|
+
const json = resolve(dir, 'package.json');
|
|
14
|
+
if (existsSync(json))
|
|
15
|
+
return { name: JSON.parse(readFileSync(json, 'utf8')).name ?? basename(dir), dir };
|
|
16
|
+
}
|
|
17
|
+
return { name: '_', dir: dirname(file) };
|
|
18
|
+
}
|
|
13
19
|
function position(text, offset) {
|
|
14
20
|
const before = text.slice(0, offset);
|
|
15
21
|
return { line: before.split('\n').length, column: offset - before.lastIndexOf('\n') };
|
|
16
22
|
}
|
|
17
|
-
/** Where the project's TypeScript lives (overridable for tests and monorepos). */
|
|
18
23
|
function typescriptDir(root, override) {
|
|
19
24
|
if (override)
|
|
20
25
|
return override;
|
|
@@ -30,7 +35,6 @@ export function check(options) {
|
|
|
30
35
|
const file = posix(relative(root, path));
|
|
31
36
|
const source = readFileSync(path, 'utf8');
|
|
32
37
|
try {
|
|
33
|
-
// A page's .load.ts that exports load(): what it returns is checked against the page's inputs.
|
|
34
38
|
const loaderPath = path.replace(/\.tscl$/, '.load.ts');
|
|
35
39
|
const hasLoad = existsSync(loaderPath) && /export\s+(async\s+)?function\s+load\b|export\s+(const|let)\s+load\b/.test(readFileSync(loaderPath, 'utf8'));
|
|
36
40
|
const { code, mappings, loaderSpan } = generateTs(source, file, hasLoad ? { loader: `./${basename(loaderPath)}` } : {});
|
|
@@ -46,16 +50,52 @@ export function check(options) {
|
|
|
46
50
|
diagnostics.push({ file, line: err.line, column: err.column, code: 'clarus', message });
|
|
47
51
|
}
|
|
48
52
|
}
|
|
49
|
-
|
|
50
|
-
|
|
53
|
+
const appRoot = realpathSync(root);
|
|
54
|
+
const paths = {};
|
|
55
|
+
const virtualOf = new Map();
|
|
56
|
+
const components = reachableComponents(root, findClarusFiles(resolve(root, 'src')), (p) => readFileSync(p, 'utf8'), ['.tscl'], projectAliases(root));
|
|
57
|
+
for (const path of components.filter((p) => !p.startsWith(resolve(appRoot, 'src') + sep))) {
|
|
58
|
+
const pkg = packageInfo(path);
|
|
59
|
+
const vpath = resolve(virtualRoot, '_pkg', pkg.name, `${relative(pkg.dir, path)}.ts`);
|
|
60
|
+
virtualOf.set(path, vpath);
|
|
61
|
+
const source = readFileSync(path, 'utf8').replace(/^(@import\b.*?\bfrom\s+)(['"])(\.{1,2}\/[^'"]*)\2/gm, (all, head, q, spec) => spec.endsWith('.tscl') ? all : `${head}${q}${posix(resolve(dirname(path), spec))}${q}`);
|
|
62
|
+
try {
|
|
63
|
+
const { code, mappings } = generateTs(source, posix(relative(root, path)));
|
|
64
|
+
mkdirSync(dirname(vpath), { recursive: true });
|
|
65
|
+
writeFileSync(vpath, code);
|
|
66
|
+
generated.set(vpath, { file: posix(relative(root, path)), source, code, mappings, fromPackage: true });
|
|
67
|
+
}
|
|
68
|
+
catch (err) {
|
|
69
|
+
if (!(err instanceof ClarusError))
|
|
70
|
+
throw err;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const require = createRequire(resolve(root, 'package.json'));
|
|
74
|
+
for (const path of components) {
|
|
75
|
+
for (const m of readFileSync(path, 'utf8').matchAll(/^@import\s+[A-Za-z_$][\w-]*\s+from\s+(['"])([^'"./][^'"]*\.tscl)\1/gm)) {
|
|
76
|
+
try {
|
|
77
|
+
const target = virtualOf.get(realpathSync(require.resolve(m[2])));
|
|
78
|
+
if (target)
|
|
79
|
+
paths[`${m[2]}.ts`] = [`./${posix(relative(resolve(root, '.clarusjs'), target))}`];
|
|
80
|
+
}
|
|
81
|
+
catch { }
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const fromCheck = (path) => { const rel = posix(relative(resolve(root, '.clarusjs'), path)); return rel.startsWith('.') ? rel : `./${rel}`; };
|
|
85
|
+
for (const alias of projectAliases(root)) {
|
|
86
|
+
const tail = alias.exact ? '' : '*';
|
|
87
|
+
const mirror = resolve(virtualRoot, relative(root, alias.replacement));
|
|
88
|
+
paths[alias.find + tail] = [fromCheck(alias.replacement) + (alias.exact ? '' : '/') + tail, fromCheck(mirror) + (alias.exact ? '' : '/') + tail].map((p) => p.replace(/\/\/\*$/, '/*'));
|
|
89
|
+
}
|
|
51
90
|
mkdirSync(resolve(root, '.clarusjs'), { recursive: true });
|
|
52
91
|
const sources = findClarusFiles(resolve(root, 'src')).map((path) => ({ file: posix(relative(root, path)), source: readFileSync(path, 'utf8') }));
|
|
53
92
|
writeFileSync(resolve(root, '.clarusjs/views.d.ts'), viewsDeclaration(sources));
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
const
|
|
93
|
+
const walk = (dir) => (existsSync(dir) ? readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(resolve(dir, e.name)) : [resolve(dir, e.name)])) : []);
|
|
94
|
+
writeFileSync(resolve(root, '.clarusjs/routes.d.ts'), routesDeclaration(walk(resolve(root, 'src/pages')).map((path) => posix(relative(root, path)))));
|
|
95
|
+
const own = ['tsconfig.json', 'jsconfig.json'].find((name) => existsSync(resolve(root, name)));
|
|
96
|
+
const hasConfig = own !== undefined;
|
|
57
97
|
const config = {
|
|
58
|
-
...(hasConfig ? { extends:
|
|
98
|
+
...(hasConfig ? { extends: `../${own}` } : {}),
|
|
59
99
|
compilerOptions: {
|
|
60
100
|
...(hasConfig ? {} : { strict: true, target: 'ES2023', module: 'ESNext', moduleResolution: 'Bundler', lib: ['ES2023', 'DOM', 'DOM.Iterable'] }),
|
|
61
101
|
noEmit: true,
|
|
@@ -63,8 +103,9 @@ export function check(options) {
|
|
|
63
103
|
noImplicitAny: false,
|
|
64
104
|
skipLibCheck: true,
|
|
65
105
|
rootDirs: ['..', './virtual'],
|
|
106
|
+
paths,
|
|
66
107
|
},
|
|
67
|
-
include: ['../src', './virtual', './views.d.ts'],
|
|
108
|
+
include: ['../src', './virtual', './views.d.ts', './routes.d.ts'],
|
|
68
109
|
};
|
|
69
110
|
const configPath = resolve(root, '.clarusjs/tsconfig.check.json');
|
|
70
111
|
mkdirSync(dirname(configPath), { recursive: true });
|
|
@@ -79,6 +120,8 @@ export function check(options) {
|
|
|
79
120
|
continue;
|
|
80
121
|
const path = resolve(root, m[1]);
|
|
81
122
|
const g = generated.get(path);
|
|
123
|
+
if (g?.fromPackage || (!g && (!resolve(path).startsWith(resolve(root) + sep) || path.includes(`${sep}node_modules${sep}`))))
|
|
124
|
+
continue;
|
|
82
125
|
if (!g) {
|
|
83
126
|
diagnostics.push({ file: posix(relative(root, path)), line: Number(m[2]), column: Number(m[3]), code: m[4], message: m[5] });
|
|
84
127
|
continue;
|
package/dist/cli/explain.js
CHANGED
package/dist/cli/index.js
CHANGED
|
@@ -22,7 +22,6 @@ export function emitClient(ir) {
|
|
|
22
22
|
hasBlocks && 'block as __cl_block',
|
|
23
23
|
hasFors && 'forBlock as __cl_for',
|
|
24
24
|
hasRegions && 'region as __cl_region',
|
|
25
|
-
// Branch and row HTML is rendered in the browser with the same helpers as on the server.
|
|
26
25
|
rendersHtml && 'escape as __cl_escape',
|
|
27
26
|
rendersHtml && all.some((n) => n.kind === 'attr') && 'attrHtml as __cl_attrHtml',
|
|
28
27
|
rendersHtml && hasBlocks && 'blockHtml as __cl_blockHtml',
|
|
@@ -30,8 +29,6 @@ export function emitClient(ir) {
|
|
|
30
29
|
hasRegions && 'regionHtml as __cl_regionHtml',
|
|
31
30
|
].filter(Boolean);
|
|
32
31
|
let out = used.length ? `import { ${used.join(', ')} } from 'clarusjs/runtime'\n` : '';
|
|
33
|
-
// Child components render in the browser too (in branches, rows and regions): import their server render
|
|
34
|
-
// functions through the plugin's ?render query.
|
|
35
32
|
const usedComponents = new Set(all.flatMap((n) => (n.kind === 'component' ? [n.name] : [])));
|
|
36
33
|
for (const imp of ir.imports) {
|
|
37
34
|
if (usedComponents.has(imp.name))
|
|
@@ -50,18 +47,12 @@ export function emitClient(ir) {
|
|
|
50
47
|
out += '\n' + lines.map((l) => ` ${l}\n`).join('');
|
|
51
48
|
return out + '}\n';
|
|
52
49
|
}
|
|
53
|
-
/** Rewrites expressions for the browser: reads of `signals` become `.get()`. */
|
|
54
50
|
function rewriter(signals) {
|
|
55
51
|
return {
|
|
56
52
|
expr: (e) => rewriteClientExpr(e, signals),
|
|
57
53
|
without: (names) => rewriter(new Map([...signals].filter(([name]) => !names.includes(name)))),
|
|
58
54
|
};
|
|
59
55
|
}
|
|
60
|
-
/**
|
|
61
|
-
* Code that wires one scope: the top level, an @if branch, a @for row or @empty content. Holes, attributes and
|
|
62
|
-
* events directly in `nodes` are wired here; nested blocks and lists get their own calls, whose branches and rows
|
|
63
|
-
* wire themselves. `ctx` names the island (top level) or the row range the scope's markers are looked up in.
|
|
64
|
-
*/
|
|
65
56
|
function wiring(ir, nodes, scope, ctx, signals, depth) {
|
|
66
57
|
const rw = rewriter(signals);
|
|
67
58
|
const lines = [];
|
|
@@ -76,7 +67,7 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
|
|
|
76
67
|
}
|
|
77
68
|
for (const e of ir.events.filter((ev) => ev.scope === scope)) {
|
|
78
69
|
const body = rewriteClient(e.handler, signals).trim();
|
|
79
|
-
const end = body.includes('//') ? '\n ' : ' ';
|
|
70
|
+
const end = body.includes('//') ? '\n ' : ' ';
|
|
80
71
|
lines.push(`__cl_on(${ctx}, ${e.index}, ${JSON.stringify(e.type)}, ($event) => { ${body}${end}})`);
|
|
81
72
|
}
|
|
82
73
|
const fn = (args, inner) => inner.length ? `(${args}) => {\n${inner.map((l) => ` ${l}`).join('\n')}\n }` : `(${args}) => {}`;
|
|
@@ -90,7 +81,6 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
|
|
|
90
81
|
lines.push(`__cl_block(${ctx}, ${n.block}, () => ${whichExpr(n, rw)}, [\n${branches.join('\n')}\n ])`);
|
|
91
82
|
}
|
|
92
83
|
if (n.kind === 'for' && n.block >= 0) {
|
|
93
|
-
// In row HTML `item` and `$index` are plain values; while wiring a row they are that row's signals.
|
|
94
84
|
const rowCtx = `__cl_c${depth + 1}`;
|
|
95
85
|
const loop = [n.item, '$index'];
|
|
96
86
|
const rowSignals = new Map([...signals, ...loop.map((name) => [name, 'state'])]);
|
|
@@ -5,6 +5,7 @@ export function emitServer(ir, clientUrl, renderImports = false) {
|
|
|
5
5
|
const all = walk(ir.nodes);
|
|
6
6
|
const runtime = [
|
|
7
7
|
'escape as __cl_escape',
|
|
8
|
+
all.some((n) => n.kind === 'hole' && n.json) && 'json as __cl_json',
|
|
8
9
|
ir.stateful && 'island as __cl_island',
|
|
9
10
|
all.some((n) => n.kind === 'attr') && 'attr as __cl_attrHtml',
|
|
10
11
|
all.some((n) => n.kind === 'if' && n.block >= 0) && 'blockHtml as __cl_blockHtml',
|
|
@@ -35,14 +36,12 @@ export function emitServer(ir, clientUrl, renderImports = false) {
|
|
|
35
36
|
: ` return ${html}\n`;
|
|
36
37
|
return out + '}\n';
|
|
37
38
|
}
|
|
38
|
-
/** Content for a slot this component doesn't have is an error (at render, so a build fails naming it). */
|
|
39
39
|
function unknownSlotCheck(ir) {
|
|
40
40
|
const known = [...new Set(walk(ir.nodes).flatMap((n) => (n.kind === 'slot' ? [n.name] : [])))];
|
|
41
41
|
const noDefault = JSON.stringify(`[clarusjs] <${ir.name}> has no <slot /> for the content passed to it`);
|
|
42
42
|
const noNamed = JSON.stringify(`[clarusjs] <${ir.name}> has no slot "`);
|
|
43
43
|
return ` for (const __cl_k in __cl_slots) if (!${JSON.stringify(known)}.includes(__cl_k)) throw new Error(__cl_k === "default" ? ${noDefault} : ${noNamed} + __cl_k + '"')\n`;
|
|
44
44
|
}
|
|
45
|
-
/** The component's state() values after its script ran: the island's starting point in the browser. */
|
|
46
45
|
function stateArg(ir) {
|
|
47
46
|
const names = [...ir.signals].filter(([, kind]) => kind === 'state').map(([name]) => name);
|
|
48
47
|
return names.length ? `{ ${names.join(', ')} }` : 'undefined';
|
package/dist/compiler/errors.js
CHANGED
|
@@ -11,7 +11,6 @@ export function htmlExpr(nodes, rw = asWritten) {
|
|
|
11
11
|
return `__cl_attrHtml(${JSON.stringify(n.name)}, ${attrValueExpr(n.value, rw.expr)}${tagArg(n)})`;
|
|
12
12
|
if (n.kind === 'if') {
|
|
13
13
|
if (n.block === -1) {
|
|
14
|
-
// Outside islands: a plain choice, no markers.
|
|
15
14
|
const last = n.branches[n.branches.length - 1];
|
|
16
15
|
let expr = last.cond === null ? `(${htmlExpr(last.nodes, rw)})` : '""';
|
|
17
16
|
const conditional = last.cond === null ? n.branches.slice(0, -1) : n.branches;
|
|
@@ -28,19 +27,19 @@ export function htmlExpr(nodes, rw = asWritten) {
|
|
|
28
27
|
const empty = n.empty ? `() => ${htmlExpr(n.empty, rw)}` : 'null';
|
|
29
28
|
if (n.block >= 0)
|
|
30
29
|
return `__cl_forHtml(${n.block}, ${list}, ${row}, ${empty})`;
|
|
31
|
-
// Outside islands: a plain loop, no markers.
|
|
32
30
|
return `((__cl_l) => __cl_l.length ? __cl_l.map(${row}).join("") : ${n.empty ? `(${htmlExpr(n.empty, rw)})` : '""'})([...(${list} ?? [])])`;
|
|
33
31
|
}
|
|
34
32
|
if (n.kind === 'component') {
|
|
35
33
|
const call = componentCall(n, rw);
|
|
36
34
|
return n.region >= 0 ? `__cl_regionHtml(${n.region}, () => ${call})` : call;
|
|
37
35
|
}
|
|
36
|
+
if (n.json)
|
|
37
|
+
return `__cl_json(${wrapExpr(rw.expr(n.expr))})`;
|
|
38
38
|
const value = `__cl_escape(${wrapExpr(rw.expr(n.expr))})`;
|
|
39
39
|
return n.reactive ? `"<!--[${n.index}-->" + ${value} + "<!--]-->"` : value;
|
|
40
40
|
});
|
|
41
41
|
return parts.length ? parts.join(' + ') : '""';
|
|
42
42
|
}
|
|
43
|
-
/** `render_child({ props }, { slots })` for a component node. */
|
|
44
43
|
export function componentCall(n, rw) {
|
|
45
44
|
const props = n.props.map((p) => `${p.name}: ${wrapExpr(rw.expr(p.expr))}`).join(', ');
|
|
46
45
|
const slots = [
|
|
@@ -52,7 +51,6 @@ export function componentCall(n, rw) {
|
|
|
52
51
|
return `${renderName(n.name)}({ ${props} }, ${slotsArg ?? 'undefined'}, { attach: ${JSON.stringify(n.attach)} })`;
|
|
53
52
|
return slotsArg ? `${renderName(n.name)}({ ${props} }, ${slotsArg})` : `${renderName(n.name)}({ ${props} })`;
|
|
54
53
|
}
|
|
55
|
-
/** Index of the branch an @if picks: `(a ? 0 : b ? 1 : 2)`, or -1 when nothing matches and there is no @else. */
|
|
56
54
|
export function whichExpr(n, rw) {
|
|
57
55
|
let expr = n.branches[n.branches.length - 1].cond === null ? String(n.branches.length - 1) : '-1';
|
|
58
56
|
for (let i = n.branches.length - 1; i >= 0; i--) {
|
|
@@ -62,17 +60,14 @@ export function whichExpr(n, rw) {
|
|
|
62
60
|
}
|
|
63
61
|
return `(${expr})`;
|
|
64
62
|
}
|
|
65
|
-
/** JS expression for an attribute's value: the bound expression, or the parts joined (null/undefined join as ''). */
|
|
66
63
|
export function attrValueExpr(value, rewrite) {
|
|
67
64
|
if ('expr' in value)
|
|
68
65
|
return `(${rewrite(value.expr)})`;
|
|
69
66
|
return `[${value.parts.map((p) => (typeof p === 'string' ? JSON.stringify(p) : `(${rewrite(p.expr)})`)).join(', ')}].join("")`;
|
|
70
67
|
}
|
|
71
|
-
/** The element's tag, passed only for attributes whose meaning depends on it (SVG animation values). */
|
|
72
68
|
export function tagArg(n) {
|
|
73
69
|
return ['to', 'from', 'values', 'by'].includes(n.name.toLowerCase()) ? `, ${JSON.stringify(n.tag)}` : '';
|
|
74
70
|
}
|
|
75
|
-
/** Every node, including those inside @if branches, @for bodies and component children. */
|
|
76
71
|
export function walk(nodes) {
|
|
77
72
|
return nodes.flatMap((n) => [
|
|
78
73
|
n,
|
package/dist/compiler/index.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
// Public compiler entry. Pure: string in, string out.
|
|
2
1
|
import { emitClient } from './emit-client.js';
|
|
3
2
|
import { emitServer } from './emit-server.js';
|
|
4
3
|
import { lower } from './ir.js';
|
|
@@ -8,13 +7,18 @@ export function compile(source, options) {
|
|
|
8
7
|
const parsed = parse(source, options.file);
|
|
9
8
|
let css = '';
|
|
10
9
|
if (parsed.styles.some((s) => !s.global)) {
|
|
11
|
-
// Native @scope: rules apply inside the component's top-level elements (style those with :scope) and stop at
|
|
12
|
-
// the next component's elements. The top-level elements are marked so the scope can find them.
|
|
13
10
|
const id = options.scope ?? scopeId(options.file);
|
|
14
11
|
const components = new Set(parsed.imports.map((imp) => imp.name));
|
|
15
12
|
markRoots(parsed.nodes, id, components);
|
|
16
|
-
for (const s of parsed.styles)
|
|
17
|
-
|
|
13
|
+
for (const s of parsed.styles) {
|
|
14
|
+
if (s.global) {
|
|
15
|
+
css += s.css;
|
|
16
|
+
continue;
|
|
17
|
+
}
|
|
18
|
+
const head = /^(?:\s*@(?:reference|import)\b[^;{]*;)+/.exec(s.css)?.[0] ?? '';
|
|
19
|
+
const statements = head.split(';').map((x) => x.trim()).filter(Boolean).map((x) => `${x};\n`).join('');
|
|
20
|
+
css += `${statements}@scope ([data-cl-c="${id}"]) to ([data-cl-c]) {${s.css.slice(head.length).replace(/\s*$/, '')}\n}\n`;
|
|
21
|
+
}
|
|
18
22
|
}
|
|
19
23
|
else {
|
|
20
24
|
css = parsed.styles.map((s) => s.css).join('');
|
|
@@ -26,15 +30,13 @@ export function compile(source, options) {
|
|
|
26
30
|
throw new Error(`[clarusjs] ${options.file}: clientUrl is required to compile a stateful component for the server`);
|
|
27
31
|
return { code: emitServer(ir, options.clientUrl ?? '', options.renderImports), stateful: ir.stateful, css };
|
|
28
32
|
}
|
|
29
|
-
/** 'src/components/card.tscl' → 'card-<short hash of the path>'. */
|
|
30
33
|
export function scopeId(file) {
|
|
31
|
-
let h = 0x811c9dc5;
|
|
34
|
+
let h = 0x811c9dc5;
|
|
32
35
|
for (let i = 0; i < file.length; i++)
|
|
33
36
|
h = Math.imul(h ^ file.charCodeAt(i), 0x01000193);
|
|
34
37
|
const name = (file.split(/[\\/]/).pop() ?? 'c').replace(/\.tscl$/, '').replace(/[^\w-]/g, '') || 'c';
|
|
35
38
|
return `${name}-${(h >>> 0).toString(36)}`;
|
|
36
39
|
}
|
|
37
|
-
/** The component's top-level HTML elements (also inside top-level @if/@for) get data-cl-c="id". */
|
|
38
40
|
function markRoots(nodes, id, components) {
|
|
39
41
|
for (const node of nodes) {
|
|
40
42
|
if (node.type === 'element' && !components.has(node.tag) && node.tag !== 'slot') {
|
package/dist/compiler/ir.d.ts
CHANGED
package/dist/compiler/ir.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
// Syntax tree → IR: static HTML chunks, holes (reactive or not), child components, events. Build-time checks live here.
|
|
2
1
|
import { ClarusError } from './errors.js';
|
|
3
2
|
import { importNames } from './parse.js';
|
|
4
3
|
import { analyzeScript, checkExpr, checkHandler, referencesNames, scriptNames, splitImports } from './script.js';
|
|
@@ -9,11 +8,8 @@ export function lower(parsed, file, source) {
|
|
|
9
8
|
const stateful = !!parsed.script;
|
|
10
9
|
const split = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : { imports: [], body: '' };
|
|
11
10
|
const signals = parsed.script ? analyzeScript(split.body, file, source, parsed.script.start) : new Map();
|
|
12
|
-
// A hole is reactive if it reads anything the script declares: a signal directly, or a function/value that may read one.
|
|
13
|
-
// text()'s effect tracks the real dependencies, so over-marking only costs a pair of comment markers.
|
|
14
11
|
const scriptScope = parsed.script ? new Set([...signals.keys(), ...scriptNames(parsed.script.code)]) : new Set();
|
|
15
12
|
for (const d of parsed.dataImports) {
|
|
16
|
-
// In an island the import is bundled for the browser, like a script import.
|
|
17
13
|
if (stateful && d.from.startsWith('node:'))
|
|
18
14
|
fail(`\`${d.from}\` can't be imported in an island: its imports are bundled for the browser`, d.start);
|
|
19
15
|
if (stateful)
|
|
@@ -22,7 +18,7 @@ export function lower(parsed, file, source) {
|
|
|
22
18
|
}
|
|
23
19
|
const components = new Set(parsed.imports.map((i) => i.name));
|
|
24
20
|
const nodes = [];
|
|
25
|
-
let out = nodes;
|
|
21
|
+
let out = nodes;
|
|
26
22
|
const events = [];
|
|
27
23
|
let holeCount = 0;
|
|
28
24
|
let eventElementCount = 0;
|
|
@@ -30,8 +26,8 @@ export function lower(parsed, file, source) {
|
|
|
30
26
|
let blockCount = 0;
|
|
31
27
|
let forCount = 0;
|
|
32
28
|
let regionCount = 0;
|
|
33
|
-
let loopNames = new Set();
|
|
34
|
-
let scopeKey;
|
|
29
|
+
let loopNames = new Set();
|
|
30
|
+
let scopeKey;
|
|
35
31
|
const emitStatic = (html) => {
|
|
36
32
|
const last = out[out.length - 1];
|
|
37
33
|
if (last?.kind === 'static')
|
|
@@ -42,7 +38,6 @@ export function lower(parsed, file, source) {
|
|
|
42
38
|
for (const input of parsed.inputs)
|
|
43
39
|
if (input.default !== undefined)
|
|
44
40
|
checkExpr(input.default, file, source, input.start);
|
|
45
|
-
// Elements whose content is raw text: comment markers inside them would be literal text, not Comment nodes.
|
|
46
41
|
const RAW_TEXT = new Set(['textarea', 'title', 'style']);
|
|
47
42
|
function visit(node, rawText) {
|
|
48
43
|
if (node.type === 'text')
|
|
@@ -97,6 +92,12 @@ export function lower(parsed, file, source) {
|
|
|
97
92
|
return emitStatic(node.value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'));
|
|
98
93
|
if (node.type === 'expr') {
|
|
99
94
|
checkExpr(node.expr, file, source, node.start);
|
|
95
|
+
if (node.json) {
|
|
96
|
+
if (stateful)
|
|
97
|
+
fail('JSON-LD is rendered on the server: put it in a component without a <script> (a layout or page)', node.start);
|
|
98
|
+
out.push({ kind: 'hole', expr: node.expr, reactive: false, index: -1, json: true });
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
100
101
|
const reactive = stateful && (referencesNames(node.expr, scriptScope) || referencesNames(node.expr, loopNames));
|
|
101
102
|
if (reactive && rawText)
|
|
102
103
|
fail(`reactive {{ }} inside <${rawText}> is not supported yet (it cannot hold update markers)`, node.start);
|
|
@@ -112,7 +113,6 @@ export function lower(parsed, file, source) {
|
|
|
112
113
|
props.push({ name: a.name, expr: a.expr });
|
|
113
114
|
}
|
|
114
115
|
else if (a.kind === 'static' && a.name === 'attach') {
|
|
115
|
-
// When the island's code loads in the browser (see runtime/loader.ts).
|
|
116
116
|
if (typeof a.value !== 'string' || !ATTACH_MODES.includes(a.value))
|
|
117
117
|
fail(`attach must be one of ${ATTACH_MODES.join(', ')}`, a.start);
|
|
118
118
|
attach = a.value;
|
|
@@ -120,7 +120,6 @@ export function lower(parsed, file, source) {
|
|
|
120
120
|
else
|
|
121
121
|
fail(`component <${node.tag}> only takes [prop] bindings and attach="…"`, a.start);
|
|
122
122
|
}
|
|
123
|
-
// Content is rendered here, in this component's scope, and handed to the child for its slots.
|
|
124
123
|
const hasContent = node.children.some((c) => c.type !== 'text' || c.value.trim());
|
|
125
124
|
const readsState = props.some((p) => referencesNames(p.expr, scriptScope) || referencesNames(p.expr, loopNames));
|
|
126
125
|
const region = stateful && (hasContent || readsState) ? regionCount++ : -1;
|
|
@@ -144,7 +143,6 @@ export function lower(parsed, file, source) {
|
|
|
144
143
|
fills.push({ name: child.name, nodes: lowerList(child.children) });
|
|
145
144
|
}
|
|
146
145
|
const rest = node.children.filter((c) => c.type !== 'fill');
|
|
147
|
-
// Whitespace around @slot blocks is not content for the default slot.
|
|
148
146
|
const children = rest.every((c) => c.type === 'text' && !c.value.trim()) ? [] : lowerList(rest);
|
|
149
147
|
scopeKey = parentScope;
|
|
150
148
|
out.push({ kind: 'component', name: node.tag, props, children, fills, region, ...(attach ? { attach } : {}) });
|
|
@@ -160,7 +158,6 @@ export function lower(parsed, file, source) {
|
|
|
160
158
|
else
|
|
161
159
|
fail('<slot> only takes name="…"', a.start);
|
|
162
160
|
}
|
|
163
|
-
// Fallback content belongs to this component: its holes read this component's inputs.
|
|
164
161
|
const fallback = [];
|
|
165
162
|
const parent = out;
|
|
166
163
|
out = fallback;
|
|
@@ -183,7 +180,6 @@ export function lower(parsed, file, source) {
|
|
|
183
180
|
else {
|
|
184
181
|
if (/^on/i.test(a.name))
|
|
185
182
|
fail(`use (${a.name.slice(2).toLowerCase()}) for events, not an ${a.name} attribute`, a.start);
|
|
186
|
-
// srcdoc is a whole HTML document: binding data into it is HTML injection, so it stays static.
|
|
187
183
|
if (a.name.toLowerCase() === 'srcdoc')
|
|
188
184
|
fail('srcdoc cannot be bound; write it as a static attribute', a.start);
|
|
189
185
|
const exprs = a.kind === 'prop' ? [{ expr: a.expr, start: a.start }] : a.parts.filter((p) => typeof p !== 'string');
|
|
@@ -197,7 +193,6 @@ export function lower(parsed, file, source) {
|
|
|
197
193
|
out.push(node_);
|
|
198
194
|
}
|
|
199
195
|
}
|
|
200
|
-
// One marker per element for its reactive attributes, one for its events.
|
|
201
196
|
if (dynamic.length) {
|
|
202
197
|
const index = attrElementCount++;
|
|
203
198
|
for (const d of dynamic)
|