clarusjs 0.13.0 → 0.15.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 (53) hide show
  1. package/dist/check/generate.d.ts +2 -5
  2. package/dist/check/generate.js +148 -13
  3. package/dist/cli/check.d.ts +4 -0
  4. package/dist/cli/check.js +3 -1
  5. package/dist/cli/mapper.js +19 -1
  6. package/dist/cli/project.d.ts +4 -0
  7. package/dist/cli/project.js +1 -1
  8. package/dist/compiler/class-style.d.ts +1 -1
  9. package/dist/compiler/class-style.js +6 -2
  10. package/dist/compiler/components.d.ts +32 -0
  11. package/dist/compiler/components.js +63 -0
  12. package/dist/compiler/emit-client.js +33 -4
  13. package/dist/compiler/emit-server.js +21 -11
  14. package/dist/compiler/html-expr.d.ts +11 -2
  15. package/dist/compiler/html-expr.js +38 -20
  16. package/dist/compiler/icon.d.ts +1 -1
  17. package/dist/compiler/icon.js +4 -0
  18. package/dist/compiler/index.d.ts +13 -1
  19. package/dist/compiler/index.js +64 -2
  20. package/dist/compiler/ir.d.ts +39 -0
  21. package/dist/compiler/ir.js +104 -11
  22. package/dist/compiler/lint.js +12 -1
  23. package/dist/compiler/parse.d.ts +44 -0
  24. package/dist/compiler/parse.js +93 -10
  25. package/dist/compiler/script.d.ts +21 -1
  26. package/dist/compiler/script.js +58 -3
  27. package/dist/compiler/shared.d.ts +6 -0
  28. package/dist/compiler/shared.js +14 -0
  29. package/dist/fetch/index.d.ts +157 -3
  30. package/dist/fetch/index.js +135 -14
  31. package/dist/forms/index.js +15 -3
  32. package/dist/runtime/attrs.d.ts +6 -0
  33. package/dist/runtime/attrs.js +16 -0
  34. package/dist/runtime/dom.d.ts +42 -1
  35. package/dist/runtime/dom.js +152 -23
  36. package/dist/runtime/html.d.ts +6 -0
  37. package/dist/runtime/html.js +12 -0
  38. package/dist/runtime/index.d.ts +1 -1
  39. package/dist/runtime/index.js +1 -1
  40. package/dist/runtime/loader.js +32 -6
  41. package/dist/runtime/router.d.ts +6 -1
  42. package/dist/runtime/router.js +1 -1
  43. package/dist/runtime/server.d.ts +20 -2
  44. package/dist/runtime/server.js +48 -8
  45. package/dist/server/handler.d.ts +28 -1
  46. package/dist/server/handler.js +48 -2
  47. package/dist/server/modes.d.ts +2 -0
  48. package/dist/server/modes.js +5 -1
  49. package/dist/server/views.d.ts +1 -1
  50. package/dist/server/views.js +1 -1
  51. package/dist/vite/plugin.d.ts +19 -0
  52. package/dist/vite/plugin.js +61 -14
  53. package/package.json +1 -1
@@ -1,20 +1,27 @@
1
- import { htmlExpr, walk } from './html-expr.js';
1
+ import { asWritten, htmlExpr, walk } from './html-expr.js';
2
2
  import { rewriteServer } from './script.js';
3
- import { indentScript, inputsLine, renderName } from './shared.js';
3
+ import { contextLines, indentScript, inputsLine, renderName } from './shared.js';
4
4
  export function emitServer(ir, clientUrl, renderImports = false, loader) {
5
5
  const all = walk(ir.nodes);
6
+ const html = htmlExpr(ir.nodes, asWritten, { island: ir.stateful ? ir.name : null, top: true });
6
7
  const runtime = [
7
8
  'escape as __cl_escape',
8
9
  all.some((n) => n.kind === 'hole' && n.json) && 'json as __cl_json',
9
10
  ir.stateful && 'island as __cl_island',
10
11
  all.some((n) => n.kind === 'attr' && n.name !== '...') && 'attr as __cl_attrHtml',
11
- all.some((n) => n.kind === 'attr' && n.name === '...') && 'spreadHtml as __cl_spreadHtml',
12
+ html.includes('__cl_spreadHtml(') && 'spreadHtml as __cl_spreadHtml',
13
+ html.includes('__cl_passedHtml(') && 'passedHtml as __cl_passedHtml',
12
14
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_classValue(')) && 'classValue as __cl_classValue',
13
15
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_styleValue(')) && 'styleValue as __cl_styleValue',
14
- all.some((n) => n.kind === 'if' && n.block >= 0) && 'blockHtml as __cl_blockHtml',
16
+ all.some((n) => (n.kind === 'if' || n.kind === 'await') && n.block >= 0) && 'blockHtml as __cl_blockHtml',
17
+ all.some((n) => n.kind === 'await' && n.block < 0) && 'awaitHtml as __cl_awaitHtml',
15
18
  all.some((n) => n.kind === 'for' && n.block >= 0) && 'forHtml as __cl_forHtml',
16
19
  all.some((n) => n.kind === 'component' && n.region >= 0) && 'regionHtml as __cl_regionHtml',
20
+ all.some((n) => n.kind === 'slot') && 'slot as __cl_slot',
17
21
  loader && 'loaded as __cl_loaded',
22
+ html.includes('__cl_join(') && 'join as __cl_join',
23
+ html.includes('__cl_sync(') && 'sync as __cl_sync',
24
+ html.includes('__cl_attrs') && 'passed as __cl_passed',
18
25
  ].filter(Boolean).join(', ');
19
26
  let out = `import { ${runtime} } from 'clarusjs/runtime/server'\n`;
20
27
  for (const imp of ir.imports)
@@ -23,21 +30,24 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
23
30
  out += `import ${d.clause} from '${d.from}'\n`;
24
31
  for (const line of ir.scriptImports)
25
32
  out += `${line}\n`;
26
- const html = htmlExpr(ir.nodes);
33
+ for (const line of ir.server?.imports ?? [])
34
+ out += `${line}\n`;
27
35
  const props = `{ ${[...ir.inputs.map((i) => i.name), '...(__cl_opts?.class && { __cl_class: __cl_opts.class })'].join(', ')} }`;
28
- out += `\nexport function render(__cl_props = {}, __cl_slots, __cl_opts) {\n`;
29
- if (ir.stateful)
30
- out += ` if (__cl_slots !== undefined) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> does not accept children yet`)})\n`;
31
- else {
32
- out += unknownSlotCheck(ir);
36
+ out += `\nexport ${ir.server?.awaits ? 'async ' : ''}function render(__cl_props = {}, __cl_slots, __cl_opts) {\n`;
37
+ out += unknownSlotCheck(ir);
38
+ if (!ir.stateful)
33
39
  out += ` if (__cl_opts?.attach) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> has no <script>, so attach="`)} + __cl_opts.attach + '" does nothing')\n`;
34
- }
35
40
  if (loader)
36
41
  out += ` __cl_props = { ...__cl_loaded(${JSON.stringify(loader)}), ...__cl_props }\n`;
37
42
  out += inputsLine(ir);
38
43
  out += ` const __cl_class = __cl_opts?.class ? " " + __cl_opts.class : ""\n`;
44
+ if (html.includes('__cl_attrs'))
45
+ out += ` const __cl_attrs = __cl_passed(__cl_props, ${JSON.stringify(ir.inputs.map((i) => i.name))})\n`;
46
+ out += contextLines(ir, '__cl_opts?.cx');
39
47
  if (ir.script)
40
48
  out += indentScript(rewriteServer(ir.script));
49
+ if (ir.server)
50
+ out += indentScript(ir.server.body);
41
51
  out += ir.stateful
42
52
  ? ` return __cl_island(${JSON.stringify(ir.name)}, ${JSON.stringify(clientUrl)}, ${props}, ${html}, ${stateArg(ir)}, __cl_opts?.attach, __cl_opts?.paths)\n`
43
53
  : ` return ${html}\n`;
@@ -8,11 +8,20 @@ export type Rewriter = {
8
8
  without(names: string[]): Rewriter;
9
9
  };
10
10
  export declare const asWritten: Rewriter;
11
- export declare function htmlExpr(nodes: IRNode[], rw?: Rewriter): string;
11
+ /**
12
+ * Server output only (#430): `island` is the component's name when it's an island, null when it isn't. Outside
13
+ * islands, a level that calls a component or places a slot joins its parts with __cl_join (a string, or a promise
14
+ * when an awaiting component is in it); inside an island, a component call is checked not to be a promise.
15
+ */
16
+ export type ServerCtx = {
17
+ island: string | null;
18
+ top?: boolean;
19
+ };
20
+ export declare function htmlExpr(nodes: IRNode[], rw?: Rewriter, top?: ServerCtx): string;
12
21
  /** `render_child({ props }, { slots })` for a component node. */
13
22
  export declare function componentCall(n: Extract<IRNode, {
14
23
  kind: 'component';
15
- }>, rw: Rewriter): string;
24
+ }>, rw: Rewriter, ctx?: ServerCtx): string;
16
25
  /** Index of the branch an @if picks: `(a ? 0 : b ? 1 : 2)`, or -1 when nothing matches and there is no @else. */
17
26
  export declare function whichExpr(n: Extract<IRNode, {
18
27
  kind: 'if';
@@ -2,14 +2,21 @@ import { FOR_IMPLICIT } from './parse.js';
2
2
  import { renderName } from './shared.js';
3
3
  import { wrapExpr } from './script.js';
4
4
  export const asWritten = { expr: (e) => e, without: () => asWritten };
5
- export function htmlExpr(nodes, rw = asWritten) {
5
+ const mayWait = (nodes) => walk(nodes).some((n) => n.kind === 'component' || n.kind === 'slot' || (n.kind === 'await' && n.block < 0));
6
+ export function htmlExpr(nodes, rw = asWritten, top) {
7
+ const ctx = top?.top ? { island: top.island } : top;
6
8
  const parts = nodes.map((n) => {
7
9
  if (n.kind === 'static')
8
10
  return JSON.stringify(n.html);
9
- if (n.kind === 'slot')
10
- return `(__cl_slots?.[${JSON.stringify(n.name)}] ?? ${n.fallback.length ? `(${htmlExpr(n.fallback, rw)})` : '""'})`;
11
- if (n.kind === 'connect')
11
+ if (n.kind === 'slot') {
12
+ const data = n.props.length ? `{ ${n.props.map((p) => `${p.name === '__proto__' ? '["__proto__"]' : p.name}: ${wrapExpr(rw.expr(p.expr))}`).join(', ')} }` : 'undefined';
13
+ const placed = `__cl_slot(__cl_slots?.[${JSON.stringify(n.name)}], ${data}, () => ${n.fallback.length ? htmlExpr(n.fallback, rw, ctx) : '""'}, __cl_cx)`;
14
+ return ctx?.island ? `__cl_join(["<!--[s-->", ${placed}, "<!--]s-->"])` : placed;
15
+ }
16
+ if (n.kind === 'connect' || n.kind === 'use')
12
17
  return '""';
18
+ if (n.kind === 'attr' && n.name === '...' && 'expr' in n.value && n.value.expr === '__cl_attrs')
19
+ return `__cl_passedHtml(__cl_attrs, ${JSON.stringify((n.skip ?? []).filter((x) => /^(id|role|tabindex|hidden|lang|dir|(data|aria)-.+)$/.test(x)))})`;
13
20
  if (n.kind === 'attr' && n.name === '...')
14
21
  return `__cl_spreadHtml(${attrValueExpr(n.value, rw.expr)}, ${JSON.stringify(n.skip ?? [])}, ${JSON.stringify(n.tag)}${rw === asWritten && n.where ? `, ${JSON.stringify(n.where)}` : ''})`;
15
22
  if (n.kind === 'attr')
@@ -17,25 +24,33 @@ export function htmlExpr(nodes, rw = asWritten) {
17
24
  if (n.kind === 'if') {
18
25
  if (n.block === -1) {
19
26
  const last = n.branches[n.branches.length - 1];
20
- let expr = last.cond === null ? `(${htmlExpr(last.nodes, rw)})` : '""';
27
+ let expr = last.cond === null ? `(${htmlExpr(last.nodes, rw, ctx)})` : '""';
21
28
  const conditional = last.cond === null ? n.branches.slice(0, -1) : n.branches;
22
29
  for (const b of [...conditional].reverse())
23
- expr = `(${wrapExpr(rw.expr(b.cond))} ? (${htmlExpr(b.nodes, rw)}) : ${expr})`;
30
+ expr = `(${wrapExpr(rw.expr(b.cond))} ? (${htmlExpr(b.nodes, rw, ctx)}) : ${expr})`;
24
31
  return expr;
25
32
  }
26
- const branches = n.branches.map((b) => `() => ${htmlExpr(b.nodes, rw)}`).join(', ');
33
+ const branches = n.branches.map((b) => `() => ${htmlExpr(b.nodes, rw, ctx)}`).join(', ');
27
34
  return `__cl_blockHtml(${n.block}, ${whichExpr(n, rw)}, [${branches}])`;
28
35
  }
36
+ if (n.kind === 'await') {
37
+ if (n.block >= 0)
38
+ return `__cl_blockHtml(${n.block}, 0, [() => ${htmlExpr(n.pending, rw, ctx)}])`;
39
+ const branch = (b) => (b ? `(${b.name}) => ${htmlExpr(b.nodes, rw.without([b.name]), ctx)}` : 'null');
40
+ return `__cl_awaitHtml(${wrapExpr(rw.expr(n.expr))}, ${branch(n.then)}, ${branch(n.catch)})`;
41
+ }
29
42
  if (n.kind === 'for') {
30
43
  const list = wrapExpr(rw.expr(n.list));
31
- const row = `(${rowParams(n)}) => ${htmlExpr(n.nodes, rw.without([n.item, ...FOR_IMPLICIT]))}`;
32
- const empty = n.empty ? `() => ${htmlExpr(n.empty, rw)}` : 'null';
44
+ const row = `(${rowParams(n)}) => ${htmlExpr(n.nodes, rw.without([n.item, ...FOR_IMPLICIT]), ctx)}`;
45
+ const empty = n.empty ? `() => ${htmlExpr(n.empty, rw, ctx)}` : 'null';
33
46
  if (n.block >= 0)
34
47
  return `__cl_forHtml(${n.block}, ${list}, ${row}, ${empty})`;
35
- return `((__cl_l) => __cl_l.length ? __cl_l.map(${row}).join("") : ${n.empty ? `(${htmlExpr(n.empty, rw)})` : '""'})([...(${list} ?? [])])`;
48
+ const rows = ctx && !ctx.island && mayWait(n.nodes) ? `__cl_join(__cl_l.map(${row}))` : `__cl_l.map(${row}).join("")`;
49
+ return `((__cl_l) => __cl_l.length ? ${rows} : ${n.empty ? `(${htmlExpr(n.empty, rw, ctx)})` : '""'})([...(${list} ?? [])])`;
36
50
  }
37
51
  if (n.kind === 'component') {
38
- const call = componentCall(n, rw);
52
+ const plain = componentCall(n, rw, ctx);
53
+ const call = ctx?.island ? `__cl_sync(${plain}, ${JSON.stringify(n.name)}, ${JSON.stringify(ctx.island)})` : plain;
39
54
  return n.region >= 0 ? `__cl_regionHtml(${n.region}, () => ${call})` : call;
40
55
  }
41
56
  if (n.json)
@@ -43,16 +58,18 @@ export function htmlExpr(nodes, rw = asWritten) {
43
58
  const value = `__cl_escape(${wrapExpr(rw.expr(n.expr))})`;
44
59
  return n.reactive ? `"<!--[${n.index}-->" + ${value} + "<!--]-->"` : value;
45
60
  });
61
+ if (ctx && (!ctx.island || (top?.top && nodes.some((n) => n.kind === 'slot'))) && mayWait(nodes))
62
+ return `__cl_join([${parts.join(', ')}])`;
46
63
  return parts.length ? parts.join(' + ') : '""';
47
64
  }
48
- export function componentCall(n, rw) {
49
- const props = n.props.map((p) => (p.name === '...' ? `...${wrapExpr(rw.expr(p.expr))}` : `${p.name}: ${wrapExpr(rw.expr(p.expr))}`)).join(', ');
65
+ export function componentCall(n, rw, ctx) {
66
+ const props = n.props.map((p) => (p.name === '...' ? `...${wrapExpr(rw.expr(p.expr))}` : `${/^[A-Za-z_$][\w$]*$/.test(p.name) ? p.name : JSON.stringify(p.name)}: ${wrapExpr(rw.expr(p.expr))}`)).join(', ');
50
67
  const slots = [
51
- ...(n.children.length ? [`"default": ${htmlExpr(n.children, rw)}`] : []),
52
- ...n.fills.map((f) => `${JSON.stringify(f.name)}: ${htmlExpr(f.nodes, rw)}`),
68
+ ...(n.children.length ? [`"default": (_, __cl_cx) => ${htmlExpr(n.children, rw, ctx)}`] : []),
69
+ ...n.fills.map((f) => `${JSON.stringify(f.name)}: (${f.params ?? '_'}, __cl_cx) => ${htmlExpr(f.nodes, rw, ctx)}`),
53
70
  ];
54
71
  const slotsArg = slots.length ? `{ ${slots.join(', ')} }` : undefined;
55
- 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(', ')} }`] : [])];
72
+ const opts = ['cx: __cl_cx', ...(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(', ')} }`] : [])];
56
73
  if (opts.length)
57
74
  return `${renderName(n.name)}({ ${props} }, ${slotsArg ?? 'undefined'}, { ${opts.join(', ')} })`;
58
75
  return slotsArg ? `${renderName(n.name)}({ ${props} }, ${slotsArg})` : `${renderName(n.name)}({ ${props} })`;
@@ -78,10 +95,11 @@ export function walk(nodes) {
78
95
  return nodes.flatMap((n) => [
79
96
  n,
80
97
  ...(n.kind === 'if' ? n.branches.flatMap((b) => walk(b.nodes))
81
- : n.kind === 'for' ? [...walk(n.nodes), ...walk(n.empty ?? [])]
82
- : n.kind === 'component' ? [...walk(n.children), ...n.fills.flatMap((f) => walk(f.nodes))]
83
- : n.kind === 'slot' ? walk(n.fallback)
84
- : []),
98
+ : n.kind === 'await' ? [...walk(n.pending), ...walk(n.then?.nodes ?? []), ...walk(n.catch?.nodes ?? [])]
99
+ : n.kind === 'for' ? [...walk(n.nodes), ...walk(n.empty ?? [])]
100
+ : n.kind === 'component' ? [...walk(n.children), ...n.fills.flatMap((f) => walk(f.nodes))]
101
+ : n.kind === 'slot' ? walk(n.fallback)
102
+ : []),
85
103
  ]);
86
104
  }
87
105
  const DERIVED = {
@@ -1,6 +1,6 @@
1
1
  import type { IconLookup } from '../icons.ts';
2
2
  import { ClarusError } from './errors.ts';
3
- import type { ParsedFile, TemplateNode } from './parse.ts';
3
+ import { type ParsedFile, type TemplateNode } from './parse.ts';
4
4
  /**
5
5
  * Finds an icon by `set:name` for `<icon>`: `resolveIcon` from clarusjs/icons, bound to the file being compiled.
6
6
  * @see https://clarusjs.com/guide/icons
@@ -1,4 +1,5 @@
1
1
  import { ClarusError } from './errors.js';
2
+ import { awaitLists } from './parse.js';
2
3
  const LABELS = new Set(['aria-label', 'aria-labelledby']);
3
4
  export function iconElement(node, file, source, icon) {
4
5
  const fail = (text) => { throw new ClarusError(text, file, source, node.start); };
@@ -72,6 +73,9 @@ export function checkIcons(parsed, file, source, icon) {
72
73
  }
73
74
  else if (node.type === 'fill')
74
75
  walk(node.children);
76
+ else if (node.type === 'await')
77
+ for (const kids of awaitLists(node))
78
+ walk(kids);
75
79
  }
76
80
  };
77
81
  walk(parsed.nodes);
@@ -1,10 +1,12 @@
1
1
  import { ClarusError } from './errors.ts';
2
+ import { type ComponentNames } from './components.ts';
2
3
  export { ClarusError } from './errors.ts';
3
4
  export { parse } from './parse.ts';
5
+ export { componentIndex, COMPONENT_DIRS, type ComponentNames } from './components.ts';
4
6
  export { checkIcons, type IconResolver } from './icon.ts';
5
7
  import type { IconResolver } from './icon.ts';
6
8
  export { lint, lintRules, type LintRule, type LintLevel, type LintConfig, type LintMessage, type LintRuleDef, type LintContext, type LintElement } from './lint.ts';
7
- export type { ParsedFile, InputDecl, ImportDecl, TemplateNode, Attr } from './parse.ts';
9
+ export type { ParsedFile, InputDecl, EventDecl, ImportDecl, TemplateNode, Attr } from './parse.ts';
8
10
  /**
9
11
  * `renderImports`: import child components' render functions with `?render`, for a render module that runs in the
10
12
  * browser (a client route's page, or a component re-rendered inside an island).
@@ -16,6 +18,16 @@ export type { ParsedFile, InputDecl, ImportDecl, TemplateNode, Attr } from './pa
16
18
  * @see https://clarusjs.com/reference/compiler#compile
17
19
  */
18
20
  export type CompileOptions = {
21
+ /**
22
+ * The page's layouts (#456), outermost first, as import specifiers: its folder and config layouts, which the plugin
23
+ * finds. The page's template is wrapped in them (each gets the route's `path` and `params`); `@layout none` skips them.
24
+ */
25
+ layouts?: string[];
26
+ /**
27
+ * Automatic imports (#458): tag names → component paths, from `componentIndex()`. A tag the template uses that's
28
+ * here and not imported by the file is imported; other hyphenated tags stay HTML.
29
+ */
30
+ components?: ComponentNames;
19
31
  file: string;
20
32
  target: 'server' | 'client';
21
33
  clientUrl?: string;
@@ -1,17 +1,24 @@
1
1
  import { emitClient } from './emit-client.js';
2
2
  import { ClarusError } from './errors.js';
3
3
  import { emitServer } from './emit-server.js';
4
- import { lower } from './ir.js';
5
- import { parse } from './parse.js';
4
+ import { lower, SPREAD_REFUSED } from './ir.js';
5
+ import { autoImport } from './components.js';
6
+ import { awaitLists, parse } from './parse.js';
6
7
  export { ClarusError } from './errors.js';
7
8
  export { parse } from './parse.js';
9
+ export { componentIndex, COMPONENT_DIRS } from './components.js';
8
10
  import { foldClass } from './class-style.js';
9
11
  export { checkIcons } from './icon.js';
10
12
  export { lint, lintRules } from './lint.js';
11
13
  export function compile(source, options) {
12
14
  const parsed = parse(source, options.file);
15
+ if (options.components)
16
+ autoImport(parsed, options.components, options.file, source);
17
+ if (options.layouts?.length && parsed.layout !== 'none')
18
+ wrapInLayouts(parsed, options.layouts, options.file, source);
13
19
  const warnings = [];
14
20
  const id = options.scope ?? scopeId(options.file);
21
+ fallThrough(parsed);
15
22
  foldClass(parsed.nodes, new Set(parsed.imports.map((imp) => imp.name)));
16
23
  markRoots(parsed.nodes, `cl-c-${id}`, new Set(parsed.imports.map((imp) => imp.name)), parsed.styles.some((st) => st.mode === 'scoped'));
17
24
  let css = '';
@@ -27,6 +34,8 @@ export function compile(source, options) {
27
34
  const statements = head.split(';').map((x) => x.trim()).filter(Boolean).map((x) => `${x};\n`).join('');
28
35
  css += `${statements}@scope (.cl-c-${id}) to ([class*="cl-c-"]:not(.cl-c-${id}) > *) {${s.css.slice(head.length).replace(/\s*$/, '')}\n}\n`;
29
36
  }
37
+ if (options.renderImports && parsed.serverScript)
38
+ throw new ClarusError('<script server> runs on the server only, and this component renders in the browser (a client route, or a child of an island, which re-renders it): make the route static or server, or render the component outside the island', options.file, source, parsed.serverScript.tag);
30
39
  const ir = lower(parsed, options.file, source, { collapseWhitespace: options.collapseWhitespace, icon: options.icon });
31
40
  warnings.push(...ir.warnings);
32
41
  if (options.target === 'client')
@@ -55,6 +64,9 @@ function markSlotContent(nodes, cls, components) {
55
64
  if (node.empty)
56
65
  markSlotContent(node.empty, cls, components);
57
66
  }
67
+ else if (node.type === 'await')
68
+ for (const kids of awaitLists(node))
69
+ markSlotContent(kids, cls, components);
58
70
  else if (node.type === 'element' && components.has(node.tag))
59
71
  markSlotContent(node.children, cls, components);
60
72
  else if (node.type === 'element' && !UNMARKED.has(node.tag)) {
@@ -71,6 +83,36 @@ function markSlotContent(nodes, cls, components) {
71
83
  }
72
84
  }
73
85
  }
86
+ const ID_LISTS = ['aria-describedby', 'aria-labelledby', 'aria-controls', 'aria-owns'];
87
+ function fallThrough(parsed) {
88
+ const meaningful = parsed.nodes.filter((n) => !(n.type === 'text' && !n.value.trim()) && !(n.type === 'element' && UNMARKED.has(n.tag)));
89
+ const root = meaningful[0];
90
+ if (meaningful.length !== 1 || root?.type !== 'element' || SPREAD_REFUSED.has(root.tag.toLowerCase()))
91
+ return;
92
+ if (root.attrs.some((a) => a.kind === 'prop' && a.name === '...'))
93
+ return;
94
+ const island = !!parsed.script || parsed.inputs.some((i) => i.model);
95
+ if (island && parsed.imports.some((i) => i.name === root.tag))
96
+ return;
97
+ root.attrs.push({ kind: 'prop', name: '...', expr: '__cl_attrs', start: root.start });
98
+ for (const [i, a] of root.attrs.entries()) {
99
+ if (a.kind !== 'static' || typeof a.value !== 'string' || !ID_LISTS.includes(a.name.toLowerCase()))
100
+ continue;
101
+ const more = `__cl_attrs[${JSON.stringify(a.name)}] == null ? "" : " " + __cl_attrs[${JSON.stringify(a.name)}]`;
102
+ root.attrs[i] = { kind: 'interp', name: a.name, parts: [a.value, { expr: more, start: a.start }], start: a.start };
103
+ }
104
+ if (parsed.imports.some((i) => i.name === root.tag))
105
+ return;
106
+ if (root.attrs.some((a) => (a.name === 'style' || a.name.startsWith('style.')) && a.kind !== 'event' && a.kind !== 'static'))
107
+ return;
108
+ const style = root.attrs.findIndex((a) => a.name === 'style' && a.kind !== 'event');
109
+ const ownStyle = root.attrs[style];
110
+ if (ownStyle?.kind === 'static' && typeof ownStyle.value === 'string') {
111
+ root.attrs[style] = { kind: 'interp', name: 'style', parts: [ownStyle.value, { expr: '__cl_attrs.style == null ? "" : "; " + __cl_attrs.style', start: ownStyle.start }], start: ownStyle.start };
112
+ }
113
+ else if (!ownStyle)
114
+ root.attrs.push({ kind: 'prop', name: 'style', expr: '__cl_attrs.style', start: root.start });
115
+ }
74
116
  function markRoots(nodes, cls, components, slots = false) {
75
117
  for (const node of nodes) {
76
118
  if (node.type === 'element' && !components.has(node.tag) && !UNMARKED.has(node.tag)) {
@@ -99,5 +141,25 @@ function markRoots(nodes, cls, components, slots = false) {
99
141
  if (node.empty)
100
142
  markRoots(node.empty, cls, components, slots);
101
143
  }
144
+ else if (node.type === 'await') {
145
+ for (const kids of awaitLists(node))
146
+ markRoots(kids, cls, components, slots);
147
+ }
148
+ }
149
+ }
150
+ function wrapInLayouts(parsed, layouts, file, source) {
151
+ if (parsed.script || parsed.inputs.some((i) => i.model)) {
152
+ throw new ClarusError('this page is an island (it has a <script> or a @model input), and folder or config layouts can\'t wrap an island yet: move the script into a component the page uses, or add @layout none', file, source, 0);
153
+ }
154
+ let nodes = parsed.nodes;
155
+ for (let k = layouts.length - 1; k >= 0; k--) {
156
+ const name = `__cl_layout_${k}`;
157
+ parsed.imports.push({ name, from: layouts[k], start: 0 });
158
+ const attrs = [
159
+ { kind: 'prop', name: 'path', expr: "__cl_opts?.route?.path ?? ''", start: 0 },
160
+ { kind: 'prop', name: 'params', expr: '__cl_opts?.route?.params ?? {}', start: 0 },
161
+ ];
162
+ nodes = [{ type: 'element', tag: name, attrs, children: nodes, start: 0 }];
102
163
  }
164
+ parsed.nodes = nodes;
103
165
  }
@@ -22,9 +22,14 @@ export type IRNode = {
22
22
  name: string;
23
23
  set: string;
24
24
  }[];
25
+ listens?: {
26
+ name: string;
27
+ handler: string;
28
+ }[];
25
29
  children: IRNode[];
26
30
  fills: {
27
31
  name: string;
32
+ params?: string;
28
33
  nodes: IRNode[];
29
34
  }[];
30
35
  region: number;
@@ -37,6 +42,10 @@ export type IRNode = {
37
42
  } | {
38
43
  kind: 'slot';
39
44
  name: string;
45
+ props: {
46
+ name: string;
47
+ expr: string;
48
+ }[];
40
49
  fallback: IRNode[];
41
50
  } | {
42
51
  kind: 'attr';
@@ -57,6 +66,10 @@ export type IRNode = {
57
66
  kind: 'connect';
58
67
  expr: string;
59
68
  index: number;
69
+ } | {
70
+ kind: 'use';
71
+ expr: string;
72
+ index: number;
60
73
  } | {
61
74
  kind: 'if';
62
75
  branches: {
@@ -64,6 +77,19 @@ export type IRNode = {
64
77
  nodes: IRNode[];
65
78
  }[];
66
79
  block: number;
80
+ } | {
81
+ kind: 'await';
82
+ expr: string;
83
+ pending: IRNode[];
84
+ then: {
85
+ name: string;
86
+ nodes: IRNode[];
87
+ } | null;
88
+ catch: {
89
+ name: string;
90
+ nodes: IRNode[];
91
+ } | null;
92
+ block: number;
67
93
  } | {
68
94
  kind: 'for';
69
95
  item: string;
@@ -86,14 +112,27 @@ export type ComponentIR = {
86
112
  imports: ImportDecl[];
87
113
  script?: string;
88
114
  scriptImports: string[];
115
+ /** <script server> (#430): its hoisted imports, its body (run at the top of render), and whether it awaits. */
116
+ server?: {
117
+ imports: string[];
118
+ body: string;
119
+ awaits: boolean;
120
+ };
89
121
  dataImports: DataImport[];
90
122
  signals: Signals;
91
123
  stateful: boolean;
92
124
  nodes: IRNode[];
93
125
  events: IREvent[];
126
+ /** The component sends events to its parent (@event, #442): its script gets emit(). */
127
+ sends: boolean;
128
+ /** @context declarations (#465): values read from the components around this one. */
129
+ contexts: InputDecl[];
130
+ /** The script calls provide() (#465): this component adds to the context its children render with. */
131
+ provides: boolean;
94
132
  /** Things that compile but likely aren't meant (located, not thrown). */
95
133
  warnings: ClarusError[];
96
134
  };
135
+ export declare const SPREAD_REFUSED: Set<string>;
97
136
  export declare function lower(parsed: ParsedFile, file: string, source: string, options?: {
98
137
  collapseWhitespace?: boolean;
99
138
  icon?: IconResolver;