clarusjs 0.8.1 → 0.10.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 (61) hide show
  1. package/dist/check/generate.d.ts +20 -4
  2. package/dist/check/generate.js +157 -21
  3. package/dist/cli/check.d.ts +13 -0
  4. package/dist/cli/check.js +65 -18
  5. package/dist/cli/index.js +9 -3
  6. package/dist/cli/mapper.d.ts +25 -0
  7. package/dist/cli/mapper.js +65 -0
  8. package/dist/cli/project.d.ts +5 -0
  9. package/dist/cli/project.js +21 -0
  10. package/dist/compiler/emit-client.js +33 -9
  11. package/dist/compiler/emit-server.js +3 -2
  12. package/dist/compiler/errors.d.ts +14 -1
  13. package/dist/compiler/html-expr.d.ts +21 -0
  14. package/dist/compiler/html-expr.js +29 -3
  15. package/dist/compiler/index.d.ts +28 -3
  16. package/dist/compiler/index.js +36 -24
  17. package/dist/compiler/ir.d.ts +19 -1
  18. package/dist/compiler/ir.js +261 -11
  19. package/dist/compiler/parse.d.ts +52 -1
  20. package/dist/compiler/parse.js +145 -6
  21. package/dist/compiler/script.d.ts +22 -1
  22. package/dist/compiler/script.js +108 -5
  23. package/dist/fetch/index.d.ts +149 -0
  24. package/dist/fetch/index.js +312 -0
  25. package/dist/forms/index.d.ts +26 -0
  26. package/dist/forms/index.js +374 -0
  27. package/dist/forms/types.d.ts +111 -0
  28. package/dist/forms/types.js +1 -0
  29. package/dist/runtime/attrs.js +10 -2
  30. package/dist/runtime/dom.d.ts +26 -11
  31. package/dist/runtime/dom.js +102 -14
  32. package/dist/runtime/env.d.ts +14 -0
  33. package/dist/runtime/env.js +14 -0
  34. package/dist/runtime/html.d.ts +9 -7
  35. package/dist/runtime/html.js +12 -7
  36. package/dist/runtime/index.d.ts +3 -2
  37. package/dist/runtime/index.js +3 -2
  38. package/dist/runtime/loader.d.ts +1 -1
  39. package/dist/runtime/loader.js +36 -5
  40. package/dist/runtime/navigate.d.ts +5 -0
  41. package/dist/runtime/navigation.d.ts +85 -13
  42. package/dist/runtime/navigation.js +77 -11
  43. package/dist/runtime/router.js +10 -1
  44. package/dist/runtime/serialize.d.ts +1 -1
  45. package/dist/runtime/serialize.js +1 -1
  46. package/dist/runtime/server.d.ts +9 -2
  47. package/dist/runtime/server.js +23 -5
  48. package/dist/runtime/signals.d.ts +98 -3
  49. package/dist/runtime/signals.js +112 -6
  50. package/dist/server/handler.d.ts +14 -1
  51. package/dist/server/handler.js +2 -2
  52. package/dist/server/head.d.ts +4 -1
  53. package/dist/server/manifest.d.ts +14 -1
  54. package/dist/server/views.d.ts +64 -6
  55. package/dist/server/views.js +46 -0
  56. package/dist/vite/build.d.ts +1 -1
  57. package/dist/vite/manifest.d.ts +12 -0
  58. package/dist/vite/plugin.d.ts +30 -2
  59. package/dist/vite/plugin.js +17 -2
  60. package/dist/vite/sitemap.d.ts +1 -0
  61. package/package.json +19 -1
@@ -0,0 +1,21 @@
1
+ import { resolve } from 'node:path';
2
+ async function flatten(plugins) {
3
+ const value = await plugins;
4
+ if (Array.isArray(value))
5
+ return (await Promise.all(value.map(flatten))).flat();
6
+ return value && typeof value === 'object' ? [value] : [];
7
+ }
8
+ export async function loadProject(root) {
9
+ let vite;
10
+ try {
11
+ vite = await import('vite');
12
+ }
13
+ catch {
14
+ return { sources: [], viteAliases: undefined };
15
+ }
16
+ const loaded = await vite.loadConfigFromFile({ command: 'build', mode: 'production' }, undefined, resolve(root), 'silent');
17
+ if (!loaded)
18
+ return { sources: [], viteAliases: undefined };
19
+ const plugin = (await flatten(loaded.config.plugins)).find((p) => p.name === 'clarusjs');
20
+ return { sources: plugin?.api?.sources ?? [], viteAliases: loaded.config.resolve?.alias };
21
+ }
@@ -1,5 +1,6 @@
1
- import { attrValueExpr, componentCall, htmlExpr, tagArg, walk, whichExpr } from './html-expr.js';
2
- import { rewriteClient, rewriteClientExpr, wrapExpr } from './script.js';
1
+ import { FOR_IMPLICIT } from './parse.js';
2
+ import { attrValueExpr, componentCall, htmlExpr, tagArg, walk, whichExpr, rowNames, rowParams, rowDerived } from './html-expr.js';
3
+ import { formName, rewriteClient, rewriteClientExpr, wrapExpr } from './script.js';
3
4
  import { indentScript, inputsLine, renderName } from './shared.js';
4
5
  export function emitClient(ir) {
5
6
  if (!ir.stateful)
@@ -12,7 +13,7 @@ export function emitClient(ir) {
12
13
  const hasRegions = all.some((n) => n.kind === 'component' && n.region >= 0);
13
14
  const rendersHtml = hasBlocks || hasFors || hasRegions;
14
15
  const used = [
15
- kinds.has('state') && 'state',
16
+ (kinds.has('state') || kinds.has('input')) && 'state',
16
17
  kinds.has('derived') && 'derived',
17
18
  kinds.has('shared') && 'shared',
18
19
  hasHoles && 'holes as __cl_holes',
@@ -21,7 +22,11 @@ export function emitClient(ir) {
21
22
  all.some((n) => n.kind === 'attr' && n.reactive) && 'attr as __cl_attr',
22
23
  hasBlocks && 'block as __cl_block',
23
24
  hasFors && 'forBlock as __cl_for',
25
+ all.some((n) => n.kind === 'for' && n.block >= 0 && rowNames(n, ir.events).some((x) => x !== '$count')) && 'derived as __cl_derived',
24
26
  hasRegions && 'region as __cl_region',
27
+ all.some((n) => n.kind === 'component' && !!n.models?.length) && 'model as __cl_model',
28
+ kinds.has('model') && 'modelInput as __cl_modelInput',
29
+ ir.inputs.some((i) => kinds.has('input') || i.model) && 'batch as __cl_batch',
25
30
  rendersHtml && 'escape as __cl_escape',
26
31
  rendersHtml && all.some((n) => n.kind === 'attr') && 'attrHtml as __cl_attrHtml',
27
32
  rendersHtml && hasBlocks && 'blockHtml as __cl_blockHtml',
@@ -36,15 +41,27 @@ export function emitClient(ir) {
36
41
  }
37
42
  for (const d of ir.dataImports)
38
43
  out += `import ${d.clause} from '${d.from}'\n`;
44
+ if (all.some((n) => n.kind === 'connect'))
45
+ out += `import { connect as __cl_connect } from 'clarusjs/forms'\n`;
39
46
  for (const line of ir.scriptImports)
40
47
  out += `${line}\n`;
41
48
  out += `\nexport function attach(__cl_root, __cl_props = {}, __cl_state) {\n`;
42
- out += inputsLine(ir);
49
+ out += ` const __cl_class = __cl_props.__cl_class ? " " + __cl_props.__cl_class : ""\n`;
50
+ const inputs = ir.inputs.filter((i) => ir.signals.get(i.name) === 'input' || ir.signals.get(i.name) === 'model');
51
+ const value = (i, from) => i.default === undefined ? `${from}.${i.name}` : `${from}.${i.name} === undefined ? (${rewriteClientExpr(i.default, ir.signals)}) : ${from}.${i.name}`;
52
+ for (const i of inputs) {
53
+ out += i.model
54
+ ? ` const ${i.name} = __cl_modelInput(__cl_root, ${JSON.stringify(i.name)}, ${value(i, '__cl_props')})\n`
55
+ : ` const ${i.name} = state(${value(i, '__cl_props')})\n`;
56
+ }
57
+ out += inputsLine({ ...ir, inputs: ir.inputs.filter((i) => !inputs.includes(i)) });
43
58
  if (ir.script)
44
- out += indentScript(rewriteClient(ir.script, ir.signals, { stateFromServer: true }));
59
+ out += indentScript(rewriteClient(ir.script, ir.signals, { stateFromServer: true, forms: formName(ir.scriptImports) }));
45
60
  const lines = wiring(ir, ir.nodes, undefined, '__cl_root', ir.signals, 0);
46
61
  if (lines.length)
47
62
  out += '\n' + lines.map((l) => ` ${l}\n`).join('');
63
+ if (inputs.length)
64
+ out += ` return (__cl_p) => __cl_batch(() => {\n${inputs.map((i) => ` ${i.name}.${i.model ? 'own' : 'set'}(${value(i, '__cl_p')})\n`).join('')} })\n`;
48
65
  return out + '}\n';
49
66
  }
50
67
  function rewriter(signals) {
@@ -64,6 +81,8 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
64
81
  for (const a of nodes) {
65
82
  if (a.kind === 'attr' && a.reactive)
66
83
  lines.push(`__cl_attr(${ctx}, ${a.index}, ${JSON.stringify(a.name)}, () => ${attrValueExpr(a.value, rw.expr)}${tagArg(a)})`);
84
+ if (a.kind === 'connect')
85
+ lines.push(`__cl_connect(${ctx}, ${a.index}, () => ${wrapExpr(rw.expr(a.expr))})`);
67
86
  }
68
87
  for (const e of ir.events.filter((ev) => ev.scope === scope)) {
69
88
  const body = rewriteClient(e.handler, signals).trim();
@@ -75,6 +94,8 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
75
94
  if (n.kind === 'component' && n.region >= 0) {
76
95
  const content = [...n.children, ...n.fills.flatMap((f) => f.nodes)];
77
96
  lines.push(`__cl_region(${ctx}, ${n.region}, () => ${componentCall(n, rw)}, ${fn('', wiring(ir, content, `c${n.region}`, ctx, signals, depth))})`);
97
+ for (const m of n.models ?? [])
98
+ lines.push(`__cl_model(${ctx}, ${n.region}, ${JSON.stringify(m.name)}, (__cl_v) => { ${rewriteClient(m.set, signals).trim()} })`);
78
99
  }
79
100
  if (n.kind === 'if' && n.block >= 0) {
80
101
  const branches = n.branches.map((b, i) => ` { html: () => ${htmlExpr(b.nodes, rw)}, wire: ${fn('', wiring(ir, b.nodes, `${n.block}.${i}`, ctx, signals, depth))} },`);
@@ -82,11 +103,14 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
82
103
  }
83
104
  if (n.kind === 'for' && n.block >= 0) {
84
105
  const rowCtx = `__cl_c${depth + 1}`;
85
- const loop = [n.item, '$index'];
86
- const rowSignals = new Map([...signals, ...loop.map((name) => [name, 'state'])]);
87
- const plain = rw.without(loop);
106
+ const names = rowNames(n, ir.events);
107
+ const derivedNames = names.filter((x) => x !== '$count');
108
+ const loop = [n.item, '$index', ...(names.length ? ['$count'] : [])];
109
+ const rowSignals = new Map([...signals, ...loop.map((name) => [name, 'state']), ...derivedNames.map((name) => [name, 'derived'])]);
110
+ const plain = rw.without([n.item, ...FOR_IMPLICIT]);
88
111
  const key = n.track === null ? '$index' : wrapExpr(plain.expr(n.track));
89
- const row = `{\n html: (${n.item}, $index) => ${htmlExpr(n.nodes, plain)},\n wire: ${fn(`${rowCtx}, ${n.item}, $index`, wiring(ir, n.nodes, `f${n.block}`, rowCtx, rowSignals, depth + 1))},\n }`;
112
+ const wire = [...rowDerived(n, ir.events), ...wiring(ir, n.nodes, `f${n.block}`, rowCtx, rowSignals, depth + 1)];
113
+ const row = `{\n html: (${rowParams(n)}) => ${htmlExpr(n.nodes, plain)},\n wire: ${fn(`${rowCtx}, ${loop.join(', ')}`, wire)},\n }`;
90
114
  const empty = n.empty
91
115
  ? `{\n html: () => ${htmlExpr(n.empty, rw)},\n wire: ${fn(rowCtx, wiring(ir, n.empty, `f${n.block}e`, rowCtx, signals, depth + 1))},\n }`
92
116
  : 'null';
@@ -20,7 +20,7 @@ export function emitServer(ir, clientUrl, renderImports = false) {
20
20
  for (const line of ir.scriptImports)
21
21
  out += `${line}\n`;
22
22
  const html = htmlExpr(ir.nodes);
23
- const props = `{ ${ir.inputs.map((i) => i.name).join(', ')} }`.replace('{ }', '{}');
23
+ const props = `{ ${[...ir.inputs.map((i) => i.name), '...(__cl_opts?.class && { __cl_class: __cl_opts.class })'].join(', ')} }`;
24
24
  out += `\nexport function render(__cl_props = {}, __cl_slots, __cl_opts) {\n`;
25
25
  if (ir.stateful)
26
26
  out += ` if (__cl_slots !== undefined) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> does not accept children yet`)})\n`;
@@ -29,10 +29,11 @@ export function emitServer(ir, clientUrl, renderImports = false) {
29
29
  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
30
  }
31
31
  out += inputsLine(ir);
32
+ out += ` const __cl_class = __cl_opts?.class ? " " + __cl_opts.class : ""\n`;
32
33
  if (ir.script)
33
34
  out += indentScript(rewriteServer(ir.script));
34
35
  out += ir.stateful
35
- ? ` return __cl_island(${JSON.stringify(ir.name)}, ${JSON.stringify(clientUrl)}, ${props}, ${html}, ${stateArg(ir)}, __cl_opts?.attach)\n`
36
+ ? ` return __cl_island(${JSON.stringify(ir.name)}, ${JSON.stringify(clientUrl)}, ${props}, ${html}, ${stateArg(ir)}, __cl_opts?.attach, __cl_opts?.paths)\n`
36
37
  : ` return ${html}\n`;
37
38
  return out + '}\n';
38
39
  }
@@ -1,4 +1,17 @@
1
- /** A compile error pointing at a place in a .tscl file. Message format: `file:line:column text` (1-based). */
1
+ /**
2
+ * A compile error pointing at a place in a .tscl file. Message format: `file:line:column text` (1-based), with the
3
+ * parts as `file`, `line` and `column`. `compile()` and `parse()` throw it; `compile()`'s warnings are ones too.
4
+ * @example
5
+ * ```ts
6
+ * try {
7
+ * compile(source, { file, target: 'server' })
8
+ * } catch (err) {
9
+ * if (err instanceof ClarusError) report(err.file, err.line, err.column, err.message)
10
+ * else throw err
11
+ * }
12
+ * ```
13
+ * @see https://clarusjs.com/reference/compiler#claruserror
14
+ */
2
15
  export declare class ClarusError extends Error {
3
16
  file: string;
4
17
  line: number;
@@ -27,3 +27,24 @@ export declare function tagArg(n: Extract<IRNode, {
27
27
  }>): string;
28
28
  /** Every node, including those inside @if branches, @for bodies and component children. */
29
29
  export declare function walk(nodes: IRNode[]): IRNode[];
30
+ /** The @for implicit names a row's template uses, besides `$index`: `$count` and those derived from it. */
31
+ export declare function rowNames(n: Extract<IRNode, {
32
+ kind: 'for';
33
+ }>, events?: {
34
+ handler: string;
35
+ scope?: string;
36
+ }[]): string[];
37
+ /**
38
+ * A row's parameters: the item and `$index`, then (when used) the list, `$count` and the names derived from them as
39
+ * default values, so every caller passes (item, index, list) and a plain Array.map works too.
40
+ */
41
+ export declare function rowParams(n: Extract<IRNode, {
42
+ kind: 'for';
43
+ }>): string;
44
+ /** In a row's wiring: the derived names, from the row's $index and the list's $count signals. */
45
+ export declare function rowDerived(n: Extract<IRNode, {
46
+ kind: 'for';
47
+ }>, events?: {
48
+ handler: string;
49
+ scope?: string;
50
+ }[]): string[];
@@ -1,3 +1,4 @@
1
+ import { FOR_IMPLICIT } from './parse.js';
1
2
  import { renderName } from './shared.js';
2
3
  import { wrapExpr } from './script.js';
3
4
  export const asWritten = { expr: (e) => e, without: () => asWritten };
@@ -7,6 +8,8 @@ export function htmlExpr(nodes, rw = asWritten) {
7
8
  return JSON.stringify(n.html);
8
9
  if (n.kind === 'slot')
9
10
  return `(__cl_slots?.[${JSON.stringify(n.name)}] ?? ${n.fallback.length ? `(${htmlExpr(n.fallback, rw)})` : '""'})`;
11
+ if (n.kind === 'connect')
12
+ return '""';
10
13
  if (n.kind === 'attr')
11
14
  return `__cl_attrHtml(${JSON.stringify(n.name)}, ${attrValueExpr(n.value, rw.expr)}${tagArg(n)})`;
12
15
  if (n.kind === 'if') {
@@ -23,7 +26,7 @@ export function htmlExpr(nodes, rw = asWritten) {
23
26
  }
24
27
  if (n.kind === 'for') {
25
28
  const list = wrapExpr(rw.expr(n.list));
26
- const row = `(${n.item}, $index) => ${htmlExpr(n.nodes, rw.without([n.item, '$index']))}`;
29
+ const row = `(${rowParams(n)}) => ${htmlExpr(n.nodes, rw.without([n.item, ...FOR_IMPLICIT]))}`;
27
30
  const empty = n.empty ? `() => ${htmlExpr(n.empty, rw)}` : 'null';
28
31
  if (n.block >= 0)
29
32
  return `__cl_forHtml(${n.block}, ${list}, ${row}, ${empty})`;
@@ -47,8 +50,9 @@ export function componentCall(n, rw) {
47
50
  ...n.fills.map((f) => `${JSON.stringify(f.name)}: ${htmlExpr(f.nodes, rw)}`),
48
51
  ];
49
52
  const slotsArg = slots.length ? `{ ${slots.join(', ')} }` : undefined;
50
- if (n.attach)
51
- return `${renderName(n.name)}({ ${props} }, ${slotsArg ?? 'undefined'}, { attach: ${JSON.stringify(n.attach)} })`;
53
+ const opts = [...(n.attach ? [`attach: ${JSON.stringify(n.attach)}`] : []), ...(n.class ? [`class: ${JSON.stringify(n.class)}`] : []), ...(n.paths ? [`paths: { ${n.paths.map((p) => `${JSON.stringify(p.name)}: ${wrapExpr(rw.expr(p.expr))}`).join(', ')} }`] : [])];
54
+ if (opts.length)
55
+ return `${renderName(n.name)}({ ${props} }, ${slotsArg ?? 'undefined'}, { ${opts.join(', ')} })`;
52
56
  return slotsArg ? `${renderName(n.name)}({ ${props} }, ${slotsArg})` : `${renderName(n.name)}({ ${props} })`;
53
57
  }
54
58
  export function whichExpr(n, rw) {
@@ -78,3 +82,25 @@ export function walk(nodes) {
78
82
  : []),
79
83
  ]);
80
84
  }
85
+ const DERIVED = {
86
+ $first: '$index === 0',
87
+ $last: '$index === $count - 1',
88
+ $even: '$index % 2 === 0',
89
+ $odd: '$index % 2 === 1',
90
+ };
91
+ export function rowNames(n, events = []) {
92
+ const rowEvents = events.filter((e) => e.scope === `f${n.block}` || e.scope?.startsWith(`f${n.block}.`)).map((e) => e.handler);
93
+ const text = JSON.stringify(n.nodes) + JSON.stringify(rowEvents);
94
+ const has = (name) => new RegExp(`(?<![\\w$.])\\${name}(?![\\w$])`).test(text);
95
+ const used = Object.keys(DERIVED).filter(has);
96
+ return has('$count') || used.includes('$last') ? ['$count', ...used] : used;
97
+ }
98
+ export function rowParams(n) {
99
+ const names = rowNames(n);
100
+ if (!names.length)
101
+ return `${n.item}, $index`;
102
+ return [n.item, '$index', '__cl_list', '$count = __cl_list.length', ...names.filter((x) => x !== '$count').map((x) => `${x} = ${DERIVED[x]}`)].join(', ');
103
+ }
104
+ export function rowDerived(n, events = []) {
105
+ return rowNames(n, events).filter((x) => x !== '$count').map((x) => `const ${x} = __cl_derived(() => ${DERIVED[x].replace(/\$index/g, '$index.get()').replace(/\$count/g, '$count.get()')})`);
106
+ }
@@ -1,22 +1,47 @@
1
+ import { ClarusError } from './errors.ts';
1
2
  export { ClarusError } from './errors.ts';
3
+ export { parse } from './parse.ts';
4
+ export type { ParsedFile, InputDecl, ImportDecl, TemplateNode, Attr } from './parse.ts';
2
5
  /**
3
6
  * `renderImports`: import child components' render functions with `?render`, for a render module that runs in the
4
7
  * browser (a client route's page, or a component re-rendered inside an island).
5
8
  */
6
- /** `scope`: the id that scopes this component's styles (default: from the file name). */
9
+ /**
10
+ * `compile()`'s options: the file (for errors and the style scope), the target (`'server'` renders HTML, `'client'`
11
+ * attaches an island), and for the server target the island's client URL.
12
+ * `scope`: the id that scopes this component's styles (default: from the file name).
13
+ * @see https://clarusjs.com/reference/compiler#compile
14
+ */
7
15
  export type CompileOptions = {
8
16
  file: string;
9
17
  target: 'server' | 'client';
10
18
  clientUrl?: string;
11
19
  renderImports?: boolean;
12
20
  scope?: string;
21
+ collapseWhitespace?: boolean;
13
22
  };
14
- /** `css`: the component's stylesheet (scoped blocks wrapped in @scope, global ones as written); '' without <style>. */
23
+ /**
24
+ * `css`: the component's stylesheet (`<style scoped>` blocks wrapped in @scope, the others as written); '' without
25
+ * <style>. `warnings`: things that compile but likely aren't meant (each a located ClarusError, not thrown).
26
+ * @see https://clarusjs.com/reference/compiler#compile
27
+ */
15
28
  export type CompileResult = {
16
29
  code: string;
17
30
  stateful: boolean;
18
31
  css: string;
32
+ warnings: ClarusError[];
19
33
  };
34
+ /**
35
+ * Compile a `.tscl` component: for the server, a module whose `render(props)` returns its HTML; for the client, an
36
+ * island's `attach(root, props)` (or `export {}` when it has no script). Pure: strings in, strings out. Throws a
37
+ * located `ClarusError` for a template it can't compile.
38
+ * @example
39
+ * ```ts
40
+ * import { compile } from 'clarusjs/compiler'
41
+ * const { code, css, stateful, warnings } = compile(source, { file: 'src/components/card.tscl', target: 'server', clientUrl: '/card.js' })
42
+ * ```
43
+ * @see https://clarusjs.com/reference/compiler#compile
44
+ */
20
45
  export declare function compile(source: string, options: CompileOptions): CompileResult;
21
- /** 'src/components/card.tscl' → 'card-<short hash of the path>'. */
46
+ /** 'src/components/card.tscl' → 'card-<short hash of the path>'. @internal */
22
47
  export declare function scopeId(file: string): string;
@@ -1,34 +1,35 @@
1
1
  import { emitClient } from './emit-client.js';
2
+ import { ClarusError } from './errors.js';
2
3
  import { emitServer } from './emit-server.js';
3
4
  import { lower } from './ir.js';
4
5
  import { parse } from './parse.js';
5
6
  export { ClarusError } from './errors.js';
7
+ export { parse } from './parse.js';
6
8
  export function compile(source, options) {
7
9
  const parsed = parse(source, options.file);
10
+ const warnings = [];
11
+ const id = options.scope ?? scopeId(options.file);
12
+ markRoots(parsed.nodes, `cl-c-${id}`, new Set(parsed.imports.map((imp) => imp.name)));
8
13
  let css = '';
9
- if (parsed.styles.some((s) => !s.global)) {
10
- const id = options.scope ?? scopeId(options.file);
11
- const components = new Set(parsed.imports.map((imp) => imp.name));
12
- markRoots(parsed.nodes, id, components);
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`;
14
+ for (const s of parsed.styles) {
15
+ if (s.mode === 'plain') {
16
+ warnings.push(new ClarusError('a plain <style> is global: add `scoped` to scope it to this component (it used to be scoped by default), or `global` to keep it global without this warning', options.file, source, s.tag));
21
17
  }
18
+ if (s.mode !== 'scoped') {
19
+ css += s.css;
20
+ continue;
21
+ }
22
+ const head = /^(?:\s*@(?:reference|import)\b[^;{]*;)+/.exec(s.css)?.[0] ?? '';
23
+ const statements = head.split(';').map((x) => x.trim()).filter(Boolean).map((x) => `${x};\n`).join('');
24
+ css += `${statements}@scope (.cl-c-${id}) to ([class*="cl-c-"]:not(.cl-c-${id}) > *) {${s.css.slice(head.length).replace(/\s*$/, '')}\n}\n`;
22
25
  }
23
- else {
24
- css = parsed.styles.map((s) => s.css).join('');
25
- }
26
- const ir = lower(parsed, options.file, source);
26
+ const ir = lower(parsed, options.file, source, { collapseWhitespace: options.collapseWhitespace });
27
+ warnings.push(...ir.warnings);
27
28
  if (options.target === 'client')
28
- return { code: emitClient(ir), stateful: ir.stateful, css };
29
+ return { code: emitClient(ir), stateful: ir.stateful, css, warnings };
29
30
  if (ir.stateful && !options.clientUrl)
30
31
  throw new Error(`[clarusjs] ${options.file}: clientUrl is required to compile a stateful component for the server`);
31
- return { code: emitServer(ir, options.clientUrl ?? '', options.renderImports), stateful: ir.stateful, css };
32
+ return { code: emitServer(ir, options.clientUrl ?? '', options.renderImports), stateful: ir.stateful, css, warnings };
32
33
  }
33
34
  export function scopeId(file) {
34
35
  let h = 0x811c9dc5;
@@ -37,19 +38,30 @@ export function scopeId(file) {
37
38
  const name = (file.split(/[\\/]/).pop() ?? 'c').replace(/\.tscl$/, '').replace(/[^\w-]/g, '') || 'c';
38
39
  return `${name}-${(h >>> 0).toString(36)}`;
39
40
  }
40
- function markRoots(nodes, id, components) {
41
+ const UNMARKED = new Set(['slot', 'cl-head', 'script', 'style', 'html', 'title', 'meta', 'link', 'base']);
42
+ function markRoots(nodes, cls, components) {
41
43
  for (const node of nodes) {
42
- if (node.type === 'element' && !components.has(node.tag) && node.tag !== 'slot') {
43
- node.attrs.push({ kind: 'static', name: 'data-cl-c', value: id, start: node.start });
44
+ if (node.type === 'element' && !components.has(node.tag) && !UNMARKED.has(node.tag)) {
45
+ const at = node.attrs.findIndex((a) => a.name === 'class');
46
+ const own = node.attrs[at];
47
+ const passed = { expr: '__cl_class', start: node.start };
48
+ if (!own)
49
+ node.attrs.push({ kind: 'interp', name: 'class', parts: [cls, passed], start: node.start });
50
+ else if (own.kind === 'static')
51
+ node.attrs[at] = { kind: 'interp', name: 'class', parts: [own.value === true || !own.value ? cls : `${own.value} ${cls}`, passed], start: own.start };
52
+ else if (own.kind === 'interp')
53
+ own.parts.push(` ${cls}`, passed);
54
+ else if (own.kind === 'prop')
55
+ node.attrs[at] = { kind: 'interp', name: 'class', parts: [{ expr: own.expr, start: own.start }, ` ${cls}`, passed], start: own.start };
44
56
  }
45
57
  else if (node.type === 'if') {
46
58
  for (const b of node.branches)
47
- markRoots(b.children, id, components);
59
+ markRoots(b.children, cls, components);
48
60
  }
49
61
  else if (node.type === 'for') {
50
- markRoots(node.children, id, components);
62
+ markRoots(node.children, cls, components);
51
63
  if (node.empty)
52
- markRoots(node.empty, id, components);
64
+ markRoots(node.empty, cls, components);
53
65
  }
54
66
  }
55
67
  }
@@ -1,3 +1,4 @@
1
+ import { ClarusError } from './errors.ts';
1
2
  import { type DataImport, type ImportDecl, type InputDecl, type ParsedFile } from './parse.ts';
2
3
  import { type Signals } from './script.ts';
3
4
  export type IRNode = {
@@ -16,6 +17,10 @@ export type IRNode = {
16
17
  name: string;
17
18
  expr: string;
18
19
  }[];
20
+ models?: {
21
+ name: string;
22
+ set: string;
23
+ }[];
19
24
  children: IRNode[];
20
25
  fills: {
21
26
  name: string;
@@ -23,6 +28,11 @@ export type IRNode = {
23
28
  }[];
24
29
  region: number;
25
30
  attach?: string;
31
+ paths?: {
32
+ name: string;
33
+ expr: string;
34
+ }[];
35
+ class?: string;
26
36
  } | {
27
37
  kind: 'slot';
28
38
  name: string;
@@ -40,6 +50,10 @@ export type IRNode = {
40
50
  reactive: boolean;
41
51
  index: number;
42
52
  tag: string;
53
+ } | {
54
+ kind: 'connect';
55
+ expr: string;
56
+ index: number;
43
57
  } | {
44
58
  kind: 'if';
45
59
  branches: {
@@ -74,5 +88,9 @@ export type ComponentIR = {
74
88
  stateful: boolean;
75
89
  nodes: IRNode[];
76
90
  events: IREvent[];
91
+ /** Things that compile but likely aren't meant (located, not thrown). */
92
+ warnings: ClarusError[];
77
93
  };
78
- export declare function lower(parsed: ParsedFile, file: string, source: string): ComponentIR;
94
+ export declare function lower(parsed: ParsedFile, file: string, source: string, options?: {
95
+ collapseWhitespace?: boolean;
96
+ }): ComponentIR;