clarusjs 0.16.0 → 0.17.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 (62) 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 +12 -7
  12. package/dist/compiler/index.js +32 -5
  13. package/dist/compiler/ir.d.ts +14 -0
  14. package/dist/compiler/ir.js +76 -10
  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/dom.d.ts +32 -2
  28. package/dist/runtime/dom.js +164 -44
  29. package/dist/runtime/hot.js +3 -2
  30. package/dist/runtime/index.d.ts +1 -1
  31. package/dist/runtime/index.js +1 -1
  32. package/dist/runtime/loader.js +18 -6
  33. package/dist/runtime/motion.d.ts +59 -0
  34. package/dist/runtime/motion.js +339 -0
  35. package/dist/runtime/navigate.d.ts +2 -0
  36. package/dist/runtime/navigate.js +7 -1
  37. package/dist/runtime/navigation.d.ts +44 -0
  38. package/dist/runtime/navigation.js +69 -3
  39. package/dist/runtime/signals.d.ts +2 -0
  40. package/dist/runtime/signals.js +31 -0
  41. package/dist/seo.d.ts +140 -0
  42. package/dist/seo.js +64 -0
  43. package/dist/server/handler.d.ts +1 -0
  44. package/dist/server/handler.js +1 -0
  45. package/dist/server/head.js +5 -0
  46. package/dist/vite/cloudflare.d.ts +3 -0
  47. package/dist/vite/cloudflare.js +55 -0
  48. package/dist/vite/env.d.ts +19 -0
  49. package/dist/vite/env.js +34 -0
  50. package/dist/vite/headers.d.ts +27 -0
  51. package/dist/vite/headers.js +70 -0
  52. package/dist/vite/manifest.d.ts +11 -1
  53. package/dist/vite/manifest.js +10 -1
  54. package/dist/vite/netlify.d.ts +5 -2
  55. package/dist/vite/netlify.js +4 -2
  56. package/dist/vite/node.d.ts +4 -0
  57. package/dist/vite/node.js +9 -2
  58. package/dist/vite/plugin.d.ts +25 -2
  59. package/dist/vite/plugin.js +84 -9
  60. package/dist/vite/vercel.d.ts +3 -0
  61. package/dist/vite/vercel.js +53 -0
  62. package/package.json +14 -1
@@ -41,7 +41,7 @@ export function htmlExpr(nodes, rw = asWritten, top) {
41
41
  }
42
42
  if (n.kind === 'for') {
43
43
  const list = wrapExpr(rw.expr(n.list));
44
- const row = `(${rowParams(n)}) => ${htmlExpr(n.nodes, rw.without([n.item, ...FOR_IMPLICIT]), ctx)}`;
44
+ const row = `(${rowParams(n)}) => ${htmlExpr(n.nodes, rw.without([n.item, ...FOR_IMPLICIT, ...n.aliases.map((a) => a.name)]), ctx)}`;
45
45
  const empty = n.empty ? `() => ${htmlExpr(n.empty, rw, ctx)}` : 'null';
46
46
  if (n.block >= 0)
47
47
  return `__cl_forHtml(${n.block}, ${list}, ${row}, ${empty})`;
@@ -64,9 +64,10 @@ export function htmlExpr(nodes, rw = asWritten, top) {
64
64
  }
65
65
  export function componentCall(n, rw, ctx) {
66
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(', ');
67
+ const untracked = (body) => (ctx ? body : `__cl_untrack(() => ${body})`);
67
68
  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)}`),
69
+ ...(n.children.length ? [`"default": (_, __cl_cx) => ${untracked(htmlExpr(n.children, rw, ctx))}`] : []),
70
+ ...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
71
  ];
71
72
  const slotsArg = slots.length ? `{ ${slots.join(', ')} }` : undefined;
72
73
  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 +112,20 @@ const DERIVED = {
111
112
  export function rowNames(n, events = []) {
112
113
  const rowEvents = events.filter((e) => e.scope === `f${n.block}` || e.scope?.startsWith(`f${n.block}.`)).map((e) => e.handler);
113
114
  const text = JSON.stringify(n.nodes) + JSON.stringify(rowEvents);
114
- const has = (name) => new RegExp(`(?<![\\w$.])\\${name}(?![\\w$])`).test(text);
115
+ const has = (name) => n.aliases.some((a) => a.of === name) || new RegExp(`(?<![\\w$.])\\${name}(?![\\w$])`).test(text);
115
116
  const used = Object.keys(DERIVED).filter(has);
116
117
  return has('$count') || used.includes('$last') ? ['$count', ...used] : used;
117
118
  }
118
119
  export function rowParams(n) {
119
120
  const names = rowNames(n);
121
+ const aliases = n.aliases.map((a) => `${a.name} = ${a.of}`);
120
122
  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(', ');
123
+ return [n.item, '$index', ...(aliases.length ? ['__cl_list', ...aliases] : [])].join(', ');
124
+ return [n.item, '$index', '__cl_list', '$count = __cl_list.length', ...names.filter((x) => x !== '$count').map((x) => `${x} = ${DERIVED[x]}`), ...aliases].join(', ');
123
125
  }
124
126
  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()')})`);
127
+ return [
128
+ ...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
+ ...n.aliases.map((a) => `const ${a.name} = ${a.of}`),
130
+ ];
126
131
  }
@@ -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
+ }
@@ -77,6 +77,10 @@ export type IRNode = {
77
77
  nodes: IRNode[];
78
78
  }[];
79
79
  block: number;
80
+ transition?: {
81
+ name: string | null;
82
+ options: string | null;
83
+ };
80
84
  } | {
81
85
  kind: 'await';
82
86
  expr: string;
@@ -95,15 +99,25 @@ export type IRNode = {
95
99
  item: string;
96
100
  list: string;
97
101
  track: string | null;
102
+ aliases: {
103
+ name: string;
104
+ of: string;
105
+ }[];
98
106
  nodes: IRNode[];
99
107
  empty: IRNode[] | null;
100
108
  block: number;
109
+ transition?: {
110
+ name: string | null;
111
+ options: string | null;
112
+ };
101
113
  };
114
+ /** An element's (type.mods)="handler"; mods are #444's modifiers, as written. */
102
115
  export type IREvent = {
103
116
  index: number;
104
117
  type: string;
105
118
  handler: string;
106
119
  scope?: string;
120
+ mods?: string[];
107
121
  };
108
122
  export type ComponentIR = {
109
123
  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);
@@ -426,6 +462,10 @@ export function lower(parsed, file, source, options = {}) {
426
462
  else if (a.kind === 'event') {
427
463
  if (!stateful)
428
464
  fail('event bindings need a <script> with state; this component is static', a.start);
465
+ const { type, mods } = splitEvent(a.name);
466
+ const wrong = modifierError(type, mods);
467
+ if (wrong)
468
+ fail(wrong, a.start);
429
469
  checkHandler(a.expr, file, source, a.start);
430
470
  const found = source.indexOf(a.expr, a.start);
431
471
  const exprStart = found === -1 ? a.start : found;
@@ -491,8 +531,10 @@ export function lower(parsed, file, source, options = {}) {
491
531
  if (elementEvents.length) {
492
532
  const index = eventElementCount++;
493
533
  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 });
534
+ for (const a of elementEvents) {
535
+ const { type, mods } = splitEvent(a.name);
536
+ events.push({ index, type, handler: a.kind === 'event' ? a.expr : '', scope: scopeKey, ...(mods.length ? { mods } : {}) });
537
+ }
496
538
  }
497
539
  emitStatic('>');
498
540
  const iconBody = iconBodies.get(node);
@@ -536,6 +578,30 @@ export function lower(parsed, file, source, options = {}) {
536
578
  warnings,
537
579
  };
538
580
  }
581
+ function wiredIn(nodes) {
582
+ for (const n of nodes) {
583
+ if (n.type === 'element') {
584
+ for (const a of n.attrs) {
585
+ if (a.kind === 'event')
586
+ return { what: `(${a.name})`, start: a.start };
587
+ if (a.kind === 'model')
588
+ return { what: `[(${a.name})]`, start: a.start };
589
+ if (a.kind === 'prop' && (a.name === 'use' || a.name === 'engine'))
590
+ return { what: `[${a.name}]`, start: a.start };
591
+ }
592
+ }
593
+ const inner = n.type === 'element' || n.type === 'fill' ? [n.children]
594
+ : n.type === 'if' ? n.branches.map((b) => b.children)
595
+ : n.type === 'for' ? [n.children, n.empty ?? []]
596
+ : n.type === 'await' ? [n.pending, n.then?.children ?? [], n.catch?.children ?? []]
597
+ : [];
598
+ for (const list of inner) {
599
+ const found = wiredIn(list);
600
+ if (found)
601
+ return found;
602
+ }
603
+ }
604
+ }
539
605
  function slotParamsCheck(params, file, source, at) {
540
606
  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
607
  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
+ }
@@ -42,6 +42,17 @@ export type AwaitBranch = {
42
42
  nameStart: number;
43
43
  children: TemplateNode[];
44
44
  };
45
+ /**
46
+ * `@transition (name, options) { … }` around an @if or a @for: its argument expressions as written (null: none).
47
+ * @see https://clarusjs.com/guide/animations#transition
48
+ */
49
+ export type Transition = {
50
+ name: string | null;
51
+ nameStart: number;
52
+ options: string | null;
53
+ optionsStart: number;
54
+ start: number;
55
+ };
45
56
  /**
46
57
  * A node of a template's syntax tree: an element, text, a `{{ }}` hole, an `@if`, an `@for`, a slot fill…
47
58
  * @see https://clarusjs.com/reference/compiler#parse
@@ -73,6 +84,8 @@ export type TemplateNode = {
73
84
  children: TemplateNode[];
74
85
  }[];
75
86
  start: number;
87
+ /** `@transition (name, options) { @if … }` around it: the argument expressions as written (null: none). */
88
+ transition?: Transition;
76
89
  } | {
77
90
  type: 'await';
78
91
  expr: string;
@@ -97,9 +110,11 @@ export type TemplateNode = {
97
110
  itemStart: number;
98
111
  listStart: number;
99
112
  trackStart: number;
113
+ aliases: ForAlias[];
100
114
  children: TemplateNode[];
101
115
  empty: TemplateNode[] | null;
102
116
  start: number;
117
+ transition?: Transition;
103
118
  };
104
119
  /**
105
120
  * An `@input` (or `@model`) declaration: its name, type text, default, and offsets.
@@ -200,6 +215,12 @@ export type ParsedFile = {
200
215
  };
201
216
  nodes: TemplateNode[];
202
217
  };
218
+ /** `let name = $index` in a @for header: another name for a row's implicit value, for a nested loop to reach. */
219
+ export type ForAlias = {
220
+ name: string;
221
+ of: string;
222
+ start: number;
223
+ };
203
224
  /** The names a @for row has besides its item: $index, $count, $first, $last, $even, $odd. */
204
225
  export declare const FOR_IMPLICIT: string[];
205
226
  /**
@@ -228,3 +249,5 @@ export declare function fragmentRoot(nodes: TemplateNode[]): boolean;
228
249
  export declare function parse(source: string, file: string): ParsedFile;
229
250
  /** Local names an import clause binds: `{ a, b as c, type T }` → a, c; `x` → x. */
230
251
  export declare function importNames(clause: string): string[];
252
+ /** A component name in kebab case, as a tag: uiButton and UiButton → ui-button, XMLViewer → xml-viewer. */
253
+ export declare function kebabOf(name: string): string;