clarusjs 0.7.0 → 0.8.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.
Files changed (41) hide show
  1. package/dist/check/generate.js +1 -21
  2. package/dist/cli/check.js +44 -11
  3. package/dist/cli/explain.js +0 -1
  4. package/dist/cli/index.js +0 -1
  5. package/dist/compiler/emit-client.js +1 -11
  6. package/dist/compiler/emit-server.js +1 -2
  7. package/dist/compiler/errors.js +0 -1
  8. package/dist/compiler/html-expr.js +2 -7
  9. package/dist/compiler/index.js +10 -8
  10. package/dist/compiler/ir.d.ts +1 -0
  11. package/dist/compiler/ir.js +9 -14
  12. package/dist/compiler/parse.d.ts +1 -0
  13. package/dist/compiler/parse.js +18 -19
  14. package/dist/compiler/script.js +2 -31
  15. package/dist/compiler/shared.js +0 -5
  16. package/dist/runtime/fragments.js +8 -3
  17. package/dist/runtime/html.d.ts +2 -0
  18. package/dist/runtime/html.js +4 -0
  19. package/dist/runtime/loader.js +39 -2
  20. package/dist/runtime/router.d.ts +1 -1
  21. package/dist/runtime/router.js +9 -8
  22. package/dist/runtime/server.d.ts +1 -1
  23. package/dist/runtime/server.js +1 -1
  24. package/dist/server/handler.d.ts +10 -0
  25. package/dist/server/handler.js +48 -48
  26. package/dist/server/head.d.ts +36 -0
  27. package/dist/server/head.js +129 -0
  28. package/dist/server/manifest.js +0 -3
  29. package/dist/server/modes.js +0 -5
  30. package/dist/server/views.js +0 -7
  31. package/dist/vite/build.d.ts +8 -0
  32. package/dist/vite/build.js +42 -17
  33. package/dist/vite/links.d.ts +2 -0
  34. package/dist/vite/links.js +11 -10
  35. package/dist/vite/manifest.js +2 -10
  36. package/dist/vite/netlify.js +1 -7
  37. package/dist/vite/plugin.d.ts +29 -0
  38. package/dist/vite/plugin.js +99 -73
  39. package/dist/vite/sitemap.d.ts +11 -0
  40. package/dist/vite/sitemap.js +31 -0
  41. package/package.json +4 -2
@@ -1,12 +1,5 @@
1
- // .tscl → virtual TypeScript for type checking (it never runs). Template expressions are copied verbatim inside
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.
4
1
  import { parse } from '../compiler/parse.js';
5
2
  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
3
  export function generateTs(source, file, options = {}) {
11
4
  const parsed = parse(source, file);
12
5
  const mappings = [];
@@ -14,7 +7,6 @@ export function generateTs(source, file, options = {}) {
14
7
  const emit = (text) => { code += text; };
15
8
  const copy = (text, sourceStart) => { mappings.push([code.length, text.length, sourceStart, true]); code += text; };
16
9
  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
10
  const at = (text, from) => source.indexOf(text, from);
19
11
  const components = new Map(parsed.imports.map((imp) => [imp.name, imp]));
20
12
  const alias = (name) => `__cl_I_${name.replace(/-/g, '$')}`;
@@ -56,7 +48,6 @@ export function generateTs(source, file, options = {}) {
56
48
  emit('}\n');
57
49
  let loaderSpan;
58
50
  if (options.loader) {
59
- // Params and defaults fill the rest, so load() may return any subset of the inputs, each with the right type.
60
51
  emit('declare const __cl_loaded: Awaited<ReturnType<typeof __cl_load>>\n');
61
52
  const start = code.length;
62
53
  point('const __cl_from_load: Partial<Inputs> = __cl_loaded', 0);
@@ -79,7 +70,7 @@ export function generateTs(source, file, options = {}) {
79
70
  }
80
71
  if (parsed.script && script) {
81
72
  copy(script.body, parsed.script.start);
82
- emit('\n;\n'); // the script may end without a semicolon; what follows must not continue its last statement
73
+ emit('\n;\n');
83
74
  }
84
75
  const use = (expr, start) => {
85
76
  emit(' __cl_use((');
@@ -130,8 +121,6 @@ export function generateTs(source, file, options = {}) {
130
121
  case 'element': {
131
122
  const component = components.get(node.tag);
132
123
  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
124
  emit(' { const ');
136
125
  point('__cl_p', node.start);
137
126
  emit(`: ${alias(node.tag)} = { `);
@@ -170,7 +159,6 @@ export function generateTs(source, file, options = {}) {
170
159
  emit('}\n');
171
160
  return { code, mappings, loaderSpan };
172
161
  }
173
- /** The template offset for an offset in the virtual file, or null when it falls in generated scaffolding. */
174
162
  export function toSourceOffset(mappings, virtualOffset) {
175
163
  for (const [v, length, s, exact] of mappings) {
176
164
  if (virtualOffset >= v && virtualOffset < v + Math.max(length, 1))
@@ -178,7 +166,6 @@ export function toSourceOffset(mappings, virtualOffset) {
178
166
  }
179
167
  return null;
180
168
  }
181
- /** 'src/components' + '../domain/user' → 'src/domain/user' (POSIX, no fs). */
182
169
  function joinPath(dir, rel) {
183
170
  const out = dir.split('/').filter(Boolean);
184
171
  for (const part of rel.split('/')) {
@@ -189,11 +176,6 @@ function joinPath(dir, rel) {
189
176
  }
190
177
  return out.join('/');
191
178
  }
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
179
  export function viewsDeclaration(views) {
198
180
  const lines = ['// Generated by clarusjs check: view name → inputs, for render() from clarusjs/views. Declarations only.'];
199
181
  const entries = [];
@@ -208,7 +190,6 @@ export function viewsDeclaration(views) {
208
190
  const ns = `__cl_v${i}`;
209
191
  const body = [];
210
192
  for (const t of parsed.typeImports) {
211
- // Relative paths are written from .clarusjs/, one level below the project root.
212
193
  const from = t.from.startsWith('.') ? `../${joinPath(file.split('/').slice(0, -1).join('/'), t.from)}` : t.from;
213
194
  const clause = t.clause.trim();
214
195
  if (clause.startsWith('{')) {
@@ -218,7 +199,6 @@ export function viewsDeclaration(views) {
218
199
  }
219
200
  }
220
201
  else if (!clause.startsWith('*')) {
221
- // ponytail: `* as N` type imports aren't carried into the registry; use named type imports for inputs.
222
202
  body.push(` type ${clause} = import(${JSON.stringify(from)}).default`);
223
203
  }
224
204
  }
package/dist/cli/check.js CHANGED
@@ -1,20 +1,24 @@
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, 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
6
  import { generateTs, toSourceOffset, viewsDeclaration } from '../check/generate.js';
9
- import { findClarusFiles } from '../vite/build.js';
7
+ import { findClarusFiles, reachableComponents } from '../vite/build.js';
10
8
  const VIRTUAL = '.clarusjs/virtual';
11
9
  const posix = (path) => path.split(sep).join('/');
12
- /** Line and column (1-based) of an offset in `text`. */
10
+ function packageInfo(file) {
11
+ for (let dir = dirname(file); dir !== dirname(dir); dir = dirname(dir)) {
12
+ const json = resolve(dir, 'package.json');
13
+ if (existsSync(json))
14
+ return { name: JSON.parse(readFileSync(json, 'utf8')).name ?? basename(dir), dir };
15
+ }
16
+ return { name: '_', dir: dirname(file) };
17
+ }
13
18
  function position(text, offset) {
14
19
  const before = text.slice(0, offset);
15
20
  return { line: before.split('\n').length, column: offset - before.lastIndexOf('\n') };
16
21
  }
17
- /** Where the project's TypeScript lives (overridable for tests and monorepos). */
18
22
  function typescriptDir(root, override) {
19
23
  if (override)
20
24
  return override;
@@ -30,7 +34,6 @@ export function check(options) {
30
34
  const file = posix(relative(root, path));
31
35
  const source = readFileSync(path, 'utf8');
32
36
  try {
33
- // A page's .load.ts that exports load(): what it returns is checked against the page's inputs.
34
37
  const loaderPath = path.replace(/\.tscl$/, '.load.ts');
35
38
  const hasLoad = existsSync(loaderPath) && /export\s+(async\s+)?function\s+load\b|export\s+(const|let)\s+load\b/.test(readFileSync(loaderPath, 'utf8'));
36
39
  const { code, mappings, loaderSpan } = generateTs(source, file, hasLoad ? { loader: `./${basename(loaderPath)}` } : {});
@@ -46,13 +49,40 @@ export function check(options) {
46
49
  diagnostics.push({ file, line: err.line, column: err.column, code: 'clarus', message });
47
50
  }
48
51
  }
49
- // The view registry: every view's name → its inputs, so render(name, props) is checked. Declarations only, so apps
50
- // can add .clarusjs/views.d.ts to their own tsconfig's include and get the same types in their editor.
52
+ const appRoot = realpathSync(root);
53
+ const paths = {};
54
+ const virtualOf = new Map();
55
+ const components = reachableComponents(root, findClarusFiles(resolve(root, 'src')), (p) => readFileSync(p, 'utf8'), ['.tscl']);
56
+ for (const path of components.filter((p) => !p.startsWith(resolve(appRoot, 'src') + sep))) {
57
+ const pkg = packageInfo(path);
58
+ const vpath = resolve(virtualRoot, '_pkg', pkg.name, `${relative(pkg.dir, path)}.ts`);
59
+ virtualOf.set(path, vpath);
60
+ 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}`);
61
+ try {
62
+ const { code, mappings } = generateTs(source, posix(relative(root, path)));
63
+ mkdirSync(dirname(vpath), { recursive: true });
64
+ writeFileSync(vpath, code);
65
+ generated.set(vpath, { file: posix(relative(root, path)), source, code, mappings, fromPackage: true });
66
+ }
67
+ catch (err) {
68
+ if (!(err instanceof ClarusError))
69
+ throw err;
70
+ }
71
+ }
72
+ const require = createRequire(resolve(root, 'package.json'));
73
+ for (const path of components) {
74
+ for (const m of readFileSync(path, 'utf8').matchAll(/^@import\s+[A-Za-z_$][\w-]*\s+from\s+(['"])([^'"./][^'"]*\.tscl)\1/gm)) {
75
+ try {
76
+ const target = virtualOf.get(realpathSync(require.resolve(m[2])));
77
+ if (target)
78
+ paths[`${m[2]}.ts`] = [`./${posix(relative(resolve(root, '.clarusjs'), target))}`];
79
+ }
80
+ catch { }
81
+ }
82
+ }
51
83
  mkdirSync(resolve(root, '.clarusjs'), { recursive: true });
52
84
  const sources = findClarusFiles(resolve(root, 'src')).map((path) => ({ file: posix(relative(root, path)), source: readFileSync(path, 'utf8') }));
53
85
  writeFileSync(resolve(root, '.clarusjs/views.d.ts'), viewsDeclaration(sources));
54
- // The project's own settings, plus what checking templates needs. Scripts are JavaScript, so untyped parameters
55
- // are expected (noImplicitAny off). rootDirs lets virtual files and real sources import each other.
56
86
  const hasConfig = existsSync(resolve(root, 'tsconfig.json'));
57
87
  const config = {
58
88
  ...(hasConfig ? { extends: '../tsconfig.json' } : {}),
@@ -63,6 +93,7 @@ export function check(options) {
63
93
  noImplicitAny: false,
64
94
  skipLibCheck: true,
65
95
  rootDirs: ['..', './virtual'],
96
+ paths,
66
97
  },
67
98
  include: ['../src', './virtual', './views.d.ts'],
68
99
  };
@@ -79,6 +110,8 @@ export function check(options) {
79
110
  continue;
80
111
  const path = resolve(root, m[1]);
81
112
  const g = generated.get(path);
113
+ if (g?.fromPackage || (!g && (!resolve(path).startsWith(resolve(root) + sep) || path.includes(`${sep}node_modules${sep}`))))
114
+ continue;
82
115
  if (!g) {
83
116
  diagnostics.push({ file: posix(relative(root, path)), line: Number(m[2]), column: Number(m[3]), code: m[4], message: m[5] });
84
117
  continue;
@@ -1,4 +1,3 @@
1
- // `clarusjs explain [route]`: where each part of a built route runs, in plain words, from dist/clarusjs-manifest.json.
2
1
  import { readFileSync } from 'node:fs';
3
2
  import { resolve } from 'node:path';
4
3
  const WHEN = {
package/dist/cli/index.js CHANGED
@@ -1,5 +1,4 @@
1
1
  #!/usr/bin/env node
2
- // The clarusjs command line. Node only: nothing here is reachable from a browser bundle.
3
2
  import { Command } from 'commander';
4
3
  import { check } from './check.js';
5
4
  import { explain } from './explain.js';
@@ -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 ' : ' '; // a trailing line comment must not swallow the closing `})`
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';
@@ -1,4 +1,3 @@
1
- /** A compile error pointing at a place in a .tscl file. Message format: `file:line:column text` (1-based). */
2
1
  export class ClarusError extends Error {
3
2
  file;
4
3
  line;
@@ -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,
@@ -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
- css += s.global ? s.css : `@scope ([data-cl-c="${id}"]) to ([data-cl-c]) {${s.css.replace(/\s*$/, '')}\n}\n`;
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; // FNV-1a
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') {
@@ -8,6 +8,7 @@ export type IRNode = {
8
8
  expr: string;
9
9
  reactive: boolean;
10
10
  index: number;
11
+ json?: true;
11
12
  } | {
12
13
  kind: 'component';
13
14
  name: string;
@@ -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; // where lowering writes; switched while lowering a component's children
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(); // @for item and $index names in scope: they make holes inside rows reactive
34
- let scopeKey; // the @if branch being lowered, for events
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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'));
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)
@@ -36,6 +36,7 @@ export type TemplateNode = {
36
36
  type: 'expr';
37
37
  expr: string;
38
38
  start: number;
39
+ json?: true;
39
40
  } | {
40
41
  type: 'raw';
41
42
  value: string;