clarusjs 0.16.0 → 0.18.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 (64) hide show
  1. package/dist/check/generate.js +97 -8
  2. package/dist/cli/check.d.ts +3 -0
  3. package/dist/cli/check.js +55 -3
  4. package/dist/cli/explain.js +3 -0
  5. package/dist/cli/index.js +21 -3
  6. package/dist/cli/project.d.ts +5 -0
  7. package/dist/cli/project.js +1 -1
  8. package/dist/compiler/emit-client.js +33 -8
  9. package/dist/compiler/events.d.ts +9 -0
  10. package/dist/compiler/events.js +46 -0
  11. package/dist/compiler/html-expr.js +14 -7
  12. package/dist/compiler/index.js +32 -5
  13. package/dist/compiler/ir.d.ts +15 -0
  14. package/dist/compiler/ir.js +87 -11
  15. package/dist/compiler/lint.d.ts +6 -2
  16. package/dist/compiler/lint.js +114 -5
  17. package/dist/compiler/loops.d.ts +13 -0
  18. package/dist/compiler/loops.js +49 -0
  19. package/dist/compiler/parse.d.ts +23 -0
  20. package/dist/compiler/parse.js +149 -1
  21. package/dist/compiler/script.d.ts +2 -0
  22. package/dist/compiler/script.js +78 -1
  23. package/dist/forms/index.js +35 -15
  24. package/dist/forms/types.d.ts +7 -0
  25. package/dist/node/serve.d.ts +26 -0
  26. package/dist/node/serve.js +150 -0
  27. package/dist/runtime/attrs.d.ts +13 -0
  28. package/dist/runtime/attrs.js +13 -0
  29. package/dist/runtime/dom.d.ts +32 -2
  30. package/dist/runtime/dom.js +170 -45
  31. package/dist/runtime/hot.js +3 -2
  32. package/dist/runtime/index.d.ts +2 -2
  33. package/dist/runtime/index.js +2 -2
  34. package/dist/runtime/loader.js +26 -7
  35. package/dist/runtime/motion.d.ts +59 -0
  36. package/dist/runtime/motion.js +339 -0
  37. package/dist/runtime/navigate.d.ts +2 -0
  38. package/dist/runtime/navigate.js +7 -1
  39. package/dist/runtime/navigation.d.ts +44 -0
  40. package/dist/runtime/navigation.js +69 -3
  41. package/dist/runtime/signals.d.ts +2 -0
  42. package/dist/runtime/signals.js +31 -0
  43. package/dist/seo.d.ts +140 -0
  44. package/dist/seo.js +64 -0
  45. package/dist/server/handler.d.ts +1 -0
  46. package/dist/server/handler.js +1 -0
  47. package/dist/server/head.js +5 -0
  48. package/dist/vite/cloudflare.d.ts +3 -0
  49. package/dist/vite/cloudflare.js +55 -0
  50. package/dist/vite/env.d.ts +19 -0
  51. package/dist/vite/env.js +34 -0
  52. package/dist/vite/headers.d.ts +27 -0
  53. package/dist/vite/headers.js +70 -0
  54. package/dist/vite/manifest.d.ts +11 -1
  55. package/dist/vite/manifest.js +10 -1
  56. package/dist/vite/netlify.d.ts +5 -2
  57. package/dist/vite/netlify.js +4 -2
  58. package/dist/vite/node.d.ts +4 -0
  59. package/dist/vite/node.js +9 -2
  60. package/dist/vite/plugin.d.ts +25 -2
  61. package/dist/vite/plugin.js +84 -9
  62. package/dist/vite/vercel.d.ts +3 -0
  63. package/dist/vite/vercel.js +53 -0
  64. package/package.json +14 -1
@@ -19,6 +19,8 @@ export function htmlExpr(nodes, rw = asWritten, top) {
19
19
  return `__cl_passedHtml(__cl_attrs, ${JSON.stringify((n.skip ?? []).filter((x) => x !== 'engine' && x !== 'use' && !x.includes('.')))})`;
20
20
  if (n.kind === 'attr' && n.name === '...')
21
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)}` : ''})`;
22
+ if (n.kind === 'attr' && n.content)
23
+ return '""';
22
24
  if (n.kind === 'attr')
23
25
  return `__cl_attrHtml(${JSON.stringify(n.name)}, ${attrValueExpr(n.value, rw.expr)}${tagArg(n)})`;
24
26
  if (n.kind === 'if') {
@@ -41,7 +43,7 @@ export function htmlExpr(nodes, rw = asWritten, top) {
41
43
  }
42
44
  if (n.kind === 'for') {
43
45
  const list = wrapExpr(rw.expr(n.list));
44
- const row = `(${rowParams(n)}) => ${htmlExpr(n.nodes, rw.without([n.item, ...FOR_IMPLICIT]), ctx)}`;
46
+ const row = `(${rowParams(n)}) => ${htmlExpr(n.nodes, rw.without([n.item, ...FOR_IMPLICIT, ...n.aliases.map((a) => a.name)]), ctx)}`;
45
47
  const empty = n.empty ? `() => ${htmlExpr(n.empty, rw, ctx)}` : 'null';
46
48
  if (n.block >= 0)
47
49
  return `__cl_forHtml(${n.block}, ${list}, ${row}, ${empty})`;
@@ -64,9 +66,10 @@ export function htmlExpr(nodes, rw = asWritten, top) {
64
66
  }
65
67
  export function componentCall(n, rw, ctx) {
66
68
  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(', ');
69
+ const untracked = (body) => (ctx ? body : `__cl_untrack(() => ${body})`);
67
70
  const slots = [
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)}`),
71
+ ...(n.children.length ? [`"default": (_, __cl_cx) => ${untracked(htmlExpr(n.children, rw, ctx))}`] : []),
72
+ ...n.fills.map((f) => `${JSON.stringify(f.name)}: (${f.params ?? '_'}, __cl_cx) => ${f.params ? htmlExpr(f.nodes, rw, ctx) : untracked(htmlExpr(f.nodes, rw, ctx))}`),
70
73
  ];
71
74
  const slotsArg = slots.length ? `{ ${slots.join(', ')} }` : undefined;
72
75
  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(', ')} }`] : [])];
@@ -111,16 +114,20 @@ const DERIVED = {
111
114
  export function rowNames(n, events = []) {
112
115
  const rowEvents = events.filter((e) => e.scope === `f${n.block}` || e.scope?.startsWith(`f${n.block}.`)).map((e) => e.handler);
113
116
  const text = JSON.stringify(n.nodes) + JSON.stringify(rowEvents);
114
- const has = (name) => new RegExp(`(?<![\\w$.])\\${name}(?![\\w$])`).test(text);
117
+ const has = (name) => n.aliases.some((a) => a.of === name) || new RegExp(`(?<![\\w$.])\\${name}(?![\\w$])`).test(text);
115
118
  const used = Object.keys(DERIVED).filter(has);
116
119
  return has('$count') || used.includes('$last') ? ['$count', ...used] : used;
117
120
  }
118
121
  export function rowParams(n) {
119
122
  const names = rowNames(n);
123
+ const aliases = n.aliases.map((a) => `${a.name} = ${a.of}`);
120
124
  if (!names.length)
121
- return `${n.item}, $index`;
122
- return [n.item, '$index', '__cl_list', '$count = __cl_list.length', ...names.filter((x) => x !== '$count').map((x) => `${x} = ${DERIVED[x]}`)].join(', ');
125
+ return [n.item, '$index', ...(aliases.length ? ['__cl_list', ...aliases] : [])].join(', ');
126
+ return [n.item, '$index', '__cl_list', '$count = __cl_list.length', ...names.filter((x) => x !== '$count').map((x) => `${x} = ${DERIVED[x]}`), ...aliases].join(', ');
123
127
  }
124
128
  export function rowDerived(n, events = []) {
125
- 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()')})`);
129
+ return [
130
+ ...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()')})`),
131
+ ...n.aliases.map((a) => `const ${a.name} = ${a.of}`),
132
+ ];
126
133
  }
@@ -13,12 +13,17 @@ export { checkIcons } from './icon.js';
13
13
  export { applyFixes, lint, lintRules } from './lint.js';
14
14
  export function compile(source, options) {
15
15
  const parsed = parse(source, options.file);
16
+ if (options.layouts?.length && parsed.layout !== 'none' && (parsed.script || parsed.inputs.some((i) => i.model)))
17
+ return compileIslandPage(parsed, source, options);
18
+ return compileParsed(parsed, source, options);
19
+ }
20
+ function compileParsed(parsed, source, options) {
16
21
  checkExtends(parsed, options.file, source);
17
22
  const fragmentRoot = unwrapFragments(parsed, options.file, source);
18
23
  if (options.components)
19
24
  autoImport(parsed, options.components, options.file, source);
20
25
  if (options.layouts?.length && parsed.layout !== 'none')
21
- wrapInLayouts(parsed, options.layouts, options.file, source);
26
+ wrapInLayouts(parsed, options.layouts);
22
27
  const warnings = [];
23
28
  const id = options.scope ?? scopeId(options.file);
24
29
  if (!fragmentRoot)
@@ -234,10 +239,7 @@ function markRoots(nodes, cls, components, slots = false) {
234
239
  }
235
240
  }
236
241
  }
237
- function wrapInLayouts(parsed, layouts, file, source) {
238
- if (parsed.script || parsed.inputs.some((i) => i.model)) {
239
- 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);
240
- }
242
+ function wrapInLayouts(parsed, layouts) {
241
243
  let nodes = parsed.nodes;
242
244
  for (let k = layouts.length - 1; k >= 0; k--) {
243
245
  const name = `__cl_layout_${k}`;
@@ -250,3 +252,28 @@ function wrapInLayouts(parsed, layouts, file, source) {
250
252
  }
251
253
  parsed.nodes = nodes;
252
254
  }
255
+ const SELF = '\0clarusjs-page';
256
+ function compileIslandPage(parsed, source, options) {
257
+ const fill = parsed.nodes.find((n) => n.type === 'fill');
258
+ if (fill)
259
+ throw new ClarusError("this island page can't fill its layouts' slots: its content is inside the island (put it in the layout, or move the script into a component the page uses)", options.file, source, fill.start);
260
+ if (options.renderImports)
261
+ throw new ClarusError('this page is an island (it has a <script> or a @model input), and its layouts are rendered in the browser here (a client route): make the route static or server, move the script into a component the page uses, or add @layout none', options.file, source, 0);
262
+ const page = compileParsed(parsed, source, { ...options, layouts: undefined });
263
+ if (options.target === 'client')
264
+ return page;
265
+ const outer = parse('', options.file);
266
+ outer.imports.push({ name: '__cl_page', from: SELF, start: 0 });
267
+ outer.nodes = [{ type: 'element', tag: '__cl_page', attrs: [{ kind: 'prop', name: '...', expr: '__cl_props', start: 0 }], children: [], start: 0 }];
268
+ wrapInLayouts(outer, options.layouts);
269
+ const wrapper = compileParsed(outer, '', { ...options, layouts: undefined, loader: undefined });
270
+ const inner = page.code.replace(/^export (async )?function render\(/m, '$1function __cl_page_render(');
271
+ const [innerHead, ...innerRest] = inner.split('\n');
272
+ const [outerHead, ...outerRest] = wrapper.code.split('\n');
273
+ const names = (line) => /\{(.*)\}/.exec(line)[1].split(',').map((x) => x.trim()).filter(Boolean);
274
+ const runtime = `import { ${[...new Set([...names(innerHead), ...names(outerHead)])].join(', ')} } from 'clarusjs/runtime/server'`;
275
+ const selfImport = outerRest.findIndex((l) => l.endsWith(` from '${SELF}'`));
276
+ const self = /render as (\w+)/.exec(outerRest[selfImport])[1];
277
+ outerRest.splice(selfImport, 1, `const ${self} = __cl_page_render`);
278
+ return { code: [runtime, ...innerRest, ...outerRest].join('\n'), stateful: page.stateful, css: page.css, warnings: [...page.warnings, ...wrapper.warnings] };
279
+ }
@@ -62,6 +62,7 @@ export type IRNode = {
62
62
  tag: string;
63
63
  skip?: string[];
64
64
  where?: string;
65
+ content?: true;
65
66
  } | {
66
67
  kind: 'connect';
67
68
  expr: string;
@@ -77,6 +78,10 @@ export type IRNode = {
77
78
  nodes: IRNode[];
78
79
  }[];
79
80
  block: number;
81
+ transition?: {
82
+ name: string | null;
83
+ options: string | null;
84
+ };
80
85
  } | {
81
86
  kind: 'await';
82
87
  expr: string;
@@ -95,15 +100,25 @@ export type IRNode = {
95
100
  item: string;
96
101
  list: string;
97
102
  track: string | null;
103
+ aliases: {
104
+ name: string;
105
+ of: string;
106
+ }[];
98
107
  nodes: IRNode[];
99
108
  empty: IRNode[] | null;
100
109
  block: number;
110
+ transition?: {
111
+ name: string | null;
112
+ options: string | null;
113
+ };
101
114
  };
115
+ /** An element's (type.mods)="handler"; mods are #444's modifiers, as written. */
102
116
  export type IREvent = {
103
117
  index: number;
104
118
  type: string;
105
119
  handler: string;
106
120
  scope?: string;
121
+ mods?: string[];
107
122
  };
108
123
  export type ComponentIR = {
109
124
  file: string;
@@ -1,7 +1,9 @@
1
+ import { modifierError, splitEvent } from './events.js';
1
2
  import { extendedAttrs } from './element-attrs.js';
2
3
  import { parseExpressionAt } from 'acorn';
3
4
  import { iconElement } from './icon.js';
4
5
  import { ClarusError } from './errors.js';
6
+ import { outerIndexIn } from './loops.js';
5
7
  import { FOR_IMPLICIT, importNames } from './parse.js';
6
8
  import { analyzeScript, providesIn, mutationsOf, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, serverScriptParts, splitImports } from './script.js';
7
9
  const ATTACH_MODES = ['load', 'idle', 'visible', 'interaction'];
@@ -10,7 +12,10 @@ const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input'
10
12
  const iconBodies = new WeakMap();
11
13
  export function lower(parsed, file, source, options = {}) {
12
14
  const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
13
- const stateful = !!parsed.script || parsed.inputs.some((i) => i.model);
15
+ const outer = outerIndexIn(parsed.nodes);
16
+ if (outer)
17
+ fail(outer.message, outer.start);
18
+ let stateful = !!parsed.script || parsed.inputs.some((i) => i.model);
14
19
  if (parsed.events.length && !parsed.script)
15
20
  fail('@event needs a <script> that sends it with emit(\'name\', value)', parsed.events[0].start);
16
21
  if (parsed.contexts.length && stateful)
@@ -121,6 +126,15 @@ export function lower(parsed, file, source, options = {}) {
121
126
  if (node.type === 'fill')
122
127
  return fail('@slot only works directly inside a component tag', node.start);
123
128
  if (node.type === 'if') {
129
+ const tr = node.transition;
130
+ if (tr) {
131
+ if (!stateful)
132
+ fail('@transition runs in the browser: this component needs a <script> or a @model input (an island)', tr.start);
133
+ if (tr.name !== null)
134
+ checkExpr(tr.name, file, source, tr.nameStart);
135
+ if (tr.options !== null)
136
+ checkExpr(tr.options, file, source, tr.optionsStart);
137
+ }
124
138
  const block = stateful ? blockCount++ : -1;
125
139
  const parent = out;
126
140
  const parentScope = scopeKey;
@@ -136,7 +150,7 @@ export function lower(parsed, file, source, options = {}) {
136
150
  });
137
151
  out = parent;
138
152
  scopeKey = parentScope;
139
- out.push({ kind: 'if', branches, block });
153
+ out.push({ kind: 'if', branches, block, ...(tr ? { transition: { name: tr.name, options: tr.options } } : {}) });
140
154
  return;
141
155
  }
142
156
  if (node.type === 'await') {
@@ -161,6 +175,15 @@ export function lower(parsed, file, source, options = {}) {
161
175
  return;
162
176
  }
163
177
  if (node.type === 'for') {
178
+ const tr = node.transition;
179
+ if (tr) {
180
+ if (!stateful)
181
+ fail('@transition runs in the browser: this component needs a <script> or a @model input (an island)', tr.start);
182
+ if (tr.name !== null)
183
+ checkExpr(tr.name, file, source, tr.nameStart);
184
+ if (tr.options !== null)
185
+ checkExpr(tr.options, file, source, tr.optionsStart);
186
+ }
164
187
  checkExpr(node.list, file, source, node.listStart);
165
188
  if (node.track !== null)
166
189
  checkExpr(node.track, file, source, node.trackStart);
@@ -177,16 +200,16 @@ export function lower(parsed, file, source, options = {}) {
177
200
  children.forEach((child) => visit(child, rawText));
178
201
  return list;
179
202
  };
180
- if (node.track !== null && referencesNames(node.track, new Set(FOR_IMPLICIT.filter((x) => x !== '$index'))))
203
+ if (node.track !== null && referencesNames(node.track, new Set([...FOR_IMPLICIT.filter((x) => x !== '$index'), ...node.aliases.filter((a) => a.of !== '$index').map((a) => a.name)])))
181
204
  fail('track can use the item and $index, not $count, $first, $last, $even or $odd (a key must not change when the list grows)', node.trackStart);
182
205
  if (block >= 0 && node.track === null)
183
206
  warnings.push(new ClarusError('@for without track: rows are matched by position, so a row\'s state moves to another item when the list changes order; add track item.id (or another unique key)', file, source, node.start));
184
- const nodes = lowerInto(node.children, `f${block}`, new Set([...parentLoop, node.item, ...FOR_IMPLICIT]));
207
+ const nodes = lowerInto(node.children, `f${block}`, new Set([...parentLoop, node.item, ...FOR_IMPLICIT, ...node.aliases.map((a) => a.name)]));
185
208
  const empty = node.empty ? lowerInto(node.empty, `f${block}e`, parentLoop) : null;
186
209
  out = parent;
187
210
  scopeKey = parentScope;
188
211
  loopNames = parentLoop;
189
- out.push({ kind: 'for', item: node.item, list: node.list, track: node.track, nodes, empty, block });
212
+ out.push({ kind: 'for', item: node.item, list: node.list, track: node.track, aliases: node.aliases.map(({ name, of }) => ({ name, of })), nodes, empty, block, ...(tr ? { transition: { name: tr.name, options: tr.options } } : {}) });
190
213
  return;
191
214
  }
192
215
  if (node.type === 'raw')
@@ -251,6 +274,8 @@ export function lower(parsed, file, source, options = {}) {
251
274
  else if (a.kind === 'event') {
252
275
  if (!stateful)
253
276
  fail('event bindings need a <script> with state; this component is static', a.start);
277
+ if (a.name.includes('.'))
278
+ fail(`(${a.name}): modifiers are for elements' DOM events; handle it in the handler`, a.start);
254
279
  checkHandler(a.expr, file, source, a.start);
255
280
  listens.push({ name: a.name, handler: a.expr });
256
281
  }
@@ -291,12 +316,23 @@ export function lower(parsed, file, source, options = {}) {
291
316
  continue;
292
317
  if (fills.some((f) => f.name === child.name))
293
318
  fail(`slot "${child.name}" is filled twice`, child.start);
319
+ let nodes;
294
320
  if (child.params !== undefined) {
295
- if (stateful)
296
- fail(`@slot('${child.name}', …) receives data from the slot, which isn't supported inside an island yet: render this component outside the island, or pass the data as props`, child.start);
297
321
  slotParamsCheck(child.params, file, source, child.paramsStart);
322
+ if (stateful) {
323
+ const wired = wiredIn(child.children);
324
+ if (wired)
325
+ fail(`a fill that receives data inside an island shows the data it receives: ${wired.what} would need that data in the browser, which isn't supported yet. Move it outside the @slot, or render this component outside the island`, wired.start);
326
+ stateful = false;
327
+ nodes = lowerList(child.children);
328
+ stateful = true;
329
+ }
330
+ else
331
+ nodes = lowerList(child.children);
298
332
  }
299
- fills.push({ name: child.name, ...(child.params !== undefined ? { params: child.params } : {}), nodes: lowerList(child.children) });
333
+ else
334
+ nodes = lowerList(child.children);
335
+ fills.push({ name: child.name, ...(child.params !== undefined ? { params: child.params } : {}), nodes });
300
336
  }
301
337
  const rest = node.children.filter((c) => c.type !== 'fill');
302
338
  const children = rest.every((c) => c.type === 'text' && !c.value.trim()) ? [] : lowerList(rest);
@@ -419,6 +455,7 @@ export function lower(parsed, file, source, options = {}) {
419
455
  emitStatic(`<${node.tag}`);
420
456
  const elementEvents = attrs.filter((a) => a.kind === 'event');
421
457
  const dynamic = [];
458
+ let textareaValue;
422
459
  let engine = false;
423
460
  for (const a of attrs) {
424
461
  if (a.kind === 'static')
@@ -426,6 +463,10 @@ export function lower(parsed, file, source, options = {}) {
426
463
  else if (a.kind === 'event') {
427
464
  if (!stateful)
428
465
  fail('event bindings need a <script> with state; this component is static', a.start);
466
+ const { type, mods } = splitEvent(a.name);
467
+ const wrong = modifierError(type, mods);
468
+ if (wrong)
469
+ fail(wrong, a.start);
429
470
  checkHandler(a.expr, file, source, a.start);
430
471
  const found = source.indexOf(a.expr, a.start);
431
472
  const exprStart = found === -1 ? a.start : found;
@@ -476,7 +517,10 @@ export function lower(parsed, file, source, options = {}) {
476
517
  checkExpr(e.expr, file, source, e.start);
477
518
  const reactive = stateful && exprs.some((e) => referencesNames(e.expr, scriptScope) || referencesNames(e.expr, loopNames));
478
519
  const value = a.kind === 'prop' ? { expr: a.expr } : { parts: a.parts.map((p) => (typeof p === 'string' ? p : { expr: p.expr })) };
479
- const node_ = { kind: 'attr', name: a.name, value, reactive, index: -1, tag: node.tag };
520
+ const content = node.tag === 'textarea' && a.name === 'value';
521
+ const node_ = { kind: 'attr', name: a.name, value, reactive, index: -1, tag: node.tag, ...(content ? { content: true } : {}) };
522
+ if (content)
523
+ textareaValue = a.kind === 'prop' ? a.expr : `[${a.parts.map((p) => (typeof p === 'string' ? JSON.stringify(p) : `(${p.expr})`)).join(', ')}].join('')`;
480
524
  if (reactive)
481
525
  dynamic.push(node_);
482
526
  out.push(node_);
@@ -491,10 +535,18 @@ export function lower(parsed, file, source, options = {}) {
491
535
  if (elementEvents.length) {
492
536
  const index = eventElementCount++;
493
537
  emitStatic(` data-cl-e="${index}"`);
494
- for (const a of elementEvents)
495
- events.push({ index, type: a.name, handler: a.kind === 'event' ? a.expr : '', scope: scopeKey });
538
+ for (const a of elementEvents) {
539
+ const { type, mods } = splitEvent(a.name);
540
+ events.push({ index, type, handler: a.kind === 'event' ? a.expr : '', scope: scopeKey, ...(mods.length ? { mods } : {}) });
541
+ }
496
542
  }
497
543
  emitStatic('>');
544
+ if (textareaValue !== undefined) {
545
+ emitStatic('\n');
546
+ out.push({ kind: 'hole', expr: textareaValue, reactive: false, index: -1 });
547
+ emitStatic('</textarea>');
548
+ return;
549
+ }
498
550
  const iconBody = iconBodies.get(node);
499
551
  if (iconBody !== undefined)
500
552
  emitStatic(iconBody);
@@ -536,6 +588,30 @@ export function lower(parsed, file, source, options = {}) {
536
588
  warnings,
537
589
  };
538
590
  }
591
+ function wiredIn(nodes) {
592
+ for (const n of nodes) {
593
+ if (n.type === 'element') {
594
+ for (const a of n.attrs) {
595
+ if (a.kind === 'event')
596
+ return { what: `(${a.name})`, start: a.start };
597
+ if (a.kind === 'model')
598
+ return { what: `[(${a.name})]`, start: a.start };
599
+ if (a.kind === 'prop' && (a.name === 'use' || a.name === 'engine'))
600
+ return { what: `[${a.name}]`, start: a.start };
601
+ }
602
+ }
603
+ const inner = n.type === 'element' || n.type === 'fill' ? [n.children]
604
+ : n.type === 'if' ? n.branches.map((b) => b.children)
605
+ : n.type === 'for' ? [n.children, n.empty ?? []]
606
+ : n.type === 'await' ? [n.pending, n.then?.children ?? [], n.catch?.children ?? []]
607
+ : [];
608
+ for (const list of inner) {
609
+ const found = wiredIn(list);
610
+ if (found)
611
+ return found;
612
+ }
613
+ }
614
+ }
539
615
  function slotParamsCheck(params, file, source, at) {
540
616
  const bad = () => { throw new ClarusError('a fill names what its slot passes like a function parameter: @slot(\'row\', { item }) or @slot(\'row\', props)', file, source, at); };
541
617
  try {
@@ -3,7 +3,7 @@ import { type ParsedFile, type TemplateNode } from './parse.ts';
3
3
  * The built-in rules' names.
4
4
  * @see https://clarusjs.com/guide/lint#rules
5
5
  */
6
- export type LintRule = 'unused-input' | 'unused-import' | 'img-alt' | 'label-field' | 'accessible-name' | 'one-root';
6
+ export type LintRule = 'unused-input' | 'unused-import' | 'img-alt' | 'label-field' | 'accessible-name' | 'one-root' | 'for-shadow' | 'server-env-in-browser';
7
7
  /**
8
8
  * Each rule's level, built-in or a project's, keyed by rule name.
9
9
  * @see https://clarusjs.com/guide/lint#warnings-and-errors
@@ -62,6 +62,8 @@ export type LintContext = {
62
62
  reads(name: string): boolean;
63
63
  /** A finding at `start`, an offset in the source (an element's, an attribute's, an @input's). */
64
64
  report(start: number, message: string, fix?: LintFix): void;
65
+ /** The prefixes of the environment variables Vite sends to the browser (its `envPrefix`; default `['VITE_']`). */
66
+ envPrefix: string[];
65
67
  };
66
68
  /**
67
69
  * A lint rule: a name (used in levels and ignore comments) and a check over one file.
@@ -91,7 +93,9 @@ export declare const lintRules: LintRuleDef[];
91
93
  * ```
92
94
  * @see https://clarusjs.com/reference/compiler#lint
93
95
  */
94
- export declare function lint(source: string, file: string, config?: LintConfig, extra?: LintRuleDef[]): LintMessage[];
96
+ export declare function lint(source: string, file: string, config?: LintConfig, extra?: LintRuleDef[], options?: {
97
+ envPrefix?: string | string[];
98
+ }): LintMessage[];
95
99
  /**
96
100
  * The source with the findings' fixes applied. Overlapping fixes: the first one (by position) wins; run lint again for
97
101
  * the rest.
@@ -1,5 +1,7 @@
1
1
  import { ClarusError } from './errors.js';
2
- import { awaitLists, importNames, parse, rootNodes } from './parse.js';
2
+ import { awaitLists, importNames, kebabOf, parse, rootNodes } from './parse.js';
3
+ import { scriptNames } from './script.js';
4
+ import { tokenizer } from 'acorn';
3
5
  const FIELDS = new Set(['input', 'select', 'textarea', 'meter', 'output', 'progress']);
4
6
  const IGNORE_RE = /\{\{--\s*clarusjs-ignore\b([\w\s,-]*?)\s*--\}\}/g;
5
7
  function* elements(nodes) {
@@ -23,6 +25,32 @@ function* elements(nodes) {
23
25
  yield* elements(kids);
24
26
  }
25
27
  }
28
+ function* fors(nodes) {
29
+ for (const n of nodes) {
30
+ if (n.type === 'element' || n.type === 'fill')
31
+ yield* fors(n.children);
32
+ else if (n.type === 'if')
33
+ for (const b of n.branches)
34
+ yield* fors(b.children);
35
+ else if (n.type === 'for') {
36
+ yield n;
37
+ yield* fors(n.children);
38
+ if (n.empty)
39
+ yield* fors(n.empty);
40
+ }
41
+ else if (n.type === 'await')
42
+ for (const kids of awaitLists(n))
43
+ yield* fors(kids);
44
+ }
45
+ }
46
+ function namesIn(code) {
47
+ try {
48
+ return code ? scriptNames(code) : new Set();
49
+ }
50
+ catch {
51
+ return new Set();
52
+ }
53
+ }
26
54
  function* expressions(nodes) {
27
55
  for (const n of nodes) {
28
56
  if (n.type === 'expr')
@@ -39,13 +67,22 @@ function* expressions(nodes) {
39
67
  }
40
68
  yield* expressions(n.children);
41
69
  }
42
- else if (n.type === 'if')
70
+ else if (n.type === 'if') {
71
+ if (n.transition?.name)
72
+ yield n.transition.name;
73
+ if (n.transition?.options)
74
+ yield n.transition.options;
43
75
  for (const b of n.branches) {
44
76
  if (b.cond)
45
77
  yield b.cond;
46
78
  yield* expressions(b.children);
47
79
  }
80
+ }
48
81
  else if (n.type === 'for') {
82
+ if (n.transition?.name)
83
+ yield n.transition.name;
84
+ if (n.transition?.options)
85
+ yield n.transition.options;
49
86
  yield n.list;
50
87
  if (n.track)
51
88
  yield n.track;
@@ -86,6 +123,43 @@ function named(nodes, components) {
86
123
  });
87
124
  }
88
125
  export const lintRules = [
126
+ {
127
+ name: 'server-env-in-browser',
128
+ check({ parsed, elements, report, envPrefix }) {
129
+ const scripts = [
130
+ ...(parsed.script ? [parsed.script] : []),
131
+ ...elements.filter((e) => e.tag === 'script' && !e.attrs.some((a) => a.name === 'type' && a.kind === 'static' && a.value !== 'module' && a.value !== 'text/javascript'))
132
+ .flatMap((e) => e.children.flatMap((c) => (c.type === 'text' ? [{ code: c.value, start: c.start }] : []))),
133
+ ];
134
+ const sent = (name) => envPrefix.some((p) => name.startsWith(p)) || /^(MODE|DEV|PROD|SSR|BASE_URL)$/.test(name);
135
+ const prefixes = envPrefix.join(' or ');
136
+ for (const { code, start } of scripts) {
137
+ let tokens;
138
+ try {
139
+ tokens = [...tokenizer(code, { ecmaVersion: 'latest', sourceType: 'module' })];
140
+ }
141
+ catch {
142
+ continue;
143
+ }
144
+ const is = (i, label, value) => tokens[i]?.type.label === label && (value === undefined || tokens[i].value === value);
145
+ const dot = (i) => is(i, '.') || is(i, '?.');
146
+ for (let i = 0; i < tokens.length; i++) {
147
+ if (is(i, 'name', 'process') && !dot(i - 1) && dot(i + 1) && is(i + 2, 'name', 'env')) {
148
+ const name = dot(i + 3) && is(i + 4, 'name') ? String(tokens[i + 4].value) : undefined;
149
+ if (name === 'NODE_ENV')
150
+ continue;
151
+ report(start + tokens[i].start, `process.env runs in the browser here, where it doesn't exist: read ${name ?? 'it'} in <script server> or a load(), or name it ${envPrefix[0]}${name ?? 'NAME'} to send it to the browser`);
152
+ }
153
+ if (is(i, 'import') && dot(i + 1) && is(i + 2, 'name', 'meta') && dot(i + 3) && is(i + 4, 'name', 'env') && dot(i + 5) && is(i + 6, 'name')) {
154
+ const name = String(tokens[i + 6].value);
155
+ if (sent(name))
156
+ continue;
157
+ report(start + tokens[i].start, `import.meta.env.${name} is never sent to the browser (only ${prefixes} variables are): read it in <script server> or a load(), or name it ${envPrefix[0]}${name}`);
158
+ }
159
+ }
160
+ }
161
+ },
162
+ },
89
163
  {
90
164
  name: 'one-root',
91
165
  check({ file, source, parsed, report }) {
@@ -138,6 +212,16 @@ export const lintRules = [
138
212
  report(at.start, 'a component renders one root element, for what a parent passes it (attributes, class, events) to land on: wrap these in an element, or in <fragment> if no element is wanted', fix);
139
213
  },
140
214
  },
215
+ {
216
+ name: 'multi-word-name',
217
+ check({ parsed, report }) {
218
+ for (const i of parsed.imports) {
219
+ if (kebabOf(i.name).includes('-'))
220
+ continue;
221
+ report(i.start, `'${i.name}' is one word: give components two or more (e.g. app${i.name[0].toUpperCase()}${i.name.slice(1)}), so the tag has a kebab-case form and can't be mistaken for an HTML element`);
222
+ }
223
+ },
224
+ },
141
225
  {
142
226
  name: 'unused-input',
143
227
  check({ parsed, reads, report }) {
@@ -160,6 +244,30 @@ export const lintRules = [
160
244
  }
161
245
  },
162
246
  },
247
+ {
248
+ name: 'for-shadow',
249
+ check({ parsed, report }) {
250
+ const declared = new Map();
251
+ const add = (name, what) => { if (!declared.has(name))
252
+ declared.set(name, what); };
253
+ for (const n of namesIn(parsed.script?.code))
254
+ add(n, `the script's ${n}`);
255
+ for (const n of namesIn(parsed.serverScript?.code))
256
+ add(n, `the server script's ${n}`);
257
+ for (const i of parsed.inputs)
258
+ add(i.name, `@${i.model ? 'model' : 'input'} ${i.name}`);
259
+ for (const i of parsed.imports)
260
+ add(i.name, `the import ${i.name}`);
261
+ for (const d of parsed.dataImports)
262
+ for (const n of importNames(d.clause))
263
+ add(n, `the import ${n}`);
264
+ for (const f of fors(parsed.nodes)) {
265
+ const what = declared.get(f.item);
266
+ if (what)
267
+ report(f.itemStart, `the row's ${f.item} hides ${what} inside this @for: rename one of them`);
268
+ }
269
+ },
270
+ },
163
271
  {
164
272
  name: 'img-alt',
165
273
  check({ elements, report }) {
@@ -192,7 +300,7 @@ export const lintRules = [
192
300
  },
193
301
  },
194
302
  ];
195
- export function lint(source, file, config = {}, extra = []) {
303
+ export function lint(source, file, config = {}, extra = [], options = {}) {
196
304
  const parsed = parse(source, file);
197
305
  const corpus = [
198
306
  ...expressions(parsed.nodes),
@@ -215,7 +323,8 @@ export function lint(source, file, config = {}, extra = []) {
215
323
  parsed,
216
324
  elements: [...elements(parsed.nodes)],
217
325
  components: new Set(parsed.imports.map((i) => i.name)),
218
- reads: (name) => new RegExp(`(?<![\\w$.])${name.replace(/\$/g, '\\$')}(?![\\w$])`).test(corpus),
326
+ reads: (name) => new RegExp(`(?<![\\w$])(?<!(?<!\\.\\.)\\.)${name.replace(/\$/g, '\\$')}(?![\\w$])`).test(corpus),
327
+ envPrefix: [options.envPrefix ?? 'VITE_'].flat(),
219
328
  };
220
329
  const out = [];
221
330
  const add = (rule, severity, start, message, fix) => {
@@ -226,7 +335,7 @@ export function lint(source, file, config = {}, extra = []) {
226
335
  out.push({ rule, severity, message, file, line, column, start, ...(fix ? { fix } : {}) });
227
336
  };
228
337
  for (const rule of [...lintRules, ...extra]) {
229
- const level = config[rule.name] ?? 'warn';
338
+ const level = config[rule.name] ?? (rule.name === 'server-env-in-browser' ? 'error' : 'warn');
230
339
  if (level === 'off')
231
340
  continue;
232
341
  try {
@@ -0,0 +1,13 @@
1
+ import { type TemplateNode } from './parse.ts';
2
+ /** An enclosing @for, outermost first: its item and its list as written. */
3
+ export type Loop = {
4
+ item: string;
5
+ list: string;
6
+ };
7
+ /** Why `expr` indexes an outer loop's list with the inner loop's $index, or null. `loops`: outermost first. */
8
+ export declare function outerIndexError(expr: string, loops: Loop[]): string | null;
9
+ /** The first expression in `nodes` that indexes an outer loop's list with an inner $index: why, and where. */
10
+ export declare function outerIndexIn(nodes: TemplateNode[], loops?: Loop[]): {
11
+ message: string;
12
+ start: number;
13
+ } | null;
@@ -0,0 +1,49 @@
1
+ import { awaitLists } from './parse.js';
2
+ export function outerIndexError(expr, loops) {
3
+ const inner = loops.at(-1);
4
+ expr = expr.replace(/'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"/g, '""');
5
+ for (const loop of loops.slice(0, -1)) {
6
+ if (loop.list === inner.list)
7
+ continue;
8
+ const escaped = loop.list.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\s+/g, '\\s*');
9
+ if (new RegExp(`(?<![\\w$.])${escaped}\\s*\\[\\s*\\$index\\s*\\]`).test(expr)) {
10
+ return `$index here is the inner @for's, not the one over ${loop.list}: name that one's index, @for (${loop.item} of ${loop.list}; …; let i = $index), and write ${loop.list}[i]`;
11
+ }
12
+ }
13
+ return null;
14
+ }
15
+ export function outerIndexIn(nodes, loops = []) {
16
+ const test = (expr, start, around = loops) => { const why = around.length > 1 && outerIndexError(expr, around); return why ? { message: why, start } : null; };
17
+ for (const n of nodes) {
18
+ let found = null;
19
+ if (n.type === 'expr')
20
+ found = test(n.expr, n.start);
21
+ else if (n.type === 'element') {
22
+ for (const a of n.attrs) {
23
+ if (a.kind === 'interp')
24
+ for (const p of a.parts)
25
+ found ??= typeof p === 'string' ? null : test(p.expr, p.start);
26
+ else if (a.kind !== 'static')
27
+ found ??= test(a.expr, a.start);
28
+ }
29
+ found ??= outerIndexIn(n.children, loops);
30
+ }
31
+ else if (n.type === 'if')
32
+ for (const b of n.branches)
33
+ found ??= (b.cond !== null ? test(b.cond, b.condStart) : null) ?? outerIndexIn(b.children, loops);
34
+ else if (n.type === 'for') {
35
+ const inside = [...loops, { item: n.item, list: n.list }];
36
+ found = test(n.list, n.listStart) ?? (n.track !== null ? test(n.track, n.trackStart, inside) : null) ?? outerIndexIn(n.children, inside) ?? (n.empty ? outerIndexIn(n.empty, loops) : null);
37
+ }
38
+ else if (n.type === 'fill')
39
+ found = outerIndexIn(n.children, loops);
40
+ else if (n.type === 'await') {
41
+ found = test(n.expr, n.exprStart);
42
+ for (const kids of awaitLists(n))
43
+ found ??= outerIndexIn(kids, loops);
44
+ }
45
+ if (found)
46
+ return found;
47
+ }
48
+ return null;
49
+ }