clarusjs 0.15.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 (75) hide show
  1. package/dist/check/generate.js +115 -13
  2. package/dist/cli/check.d.ts +9 -2
  3. package/dist/cli/check.js +91 -15
  4. package/dist/cli/explain.js +3 -0
  5. package/dist/cli/index.js +24 -3
  6. package/dist/cli/mapper.js +6 -1
  7. package/dist/cli/project.d.ts +7 -0
  8. package/dist/cli/project.js +1 -1
  9. package/dist/compiler/components.d.ts +29 -0
  10. package/dist/compiler/components.js +18 -0
  11. package/dist/compiler/element-attrs.d.ts +7 -0
  12. package/dist/compiler/element-attrs.js +32 -0
  13. package/dist/compiler/emit-client.js +39 -9
  14. package/dist/compiler/emit-server.js +1 -1
  15. package/dist/compiler/events.d.ts +9 -0
  16. package/dist/compiler/events.js +46 -0
  17. package/dist/compiler/html-expr.js +13 -8
  18. package/dist/compiler/index.d.ts +2 -2
  19. package/dist/compiler/index.js +126 -12
  20. package/dist/compiler/ir.d.ts +18 -0
  21. package/dist/compiler/ir.js +79 -10
  22. package/dist/compiler/lint.d.ts +31 -3
  23. package/dist/compiler/lint.js +177 -8
  24. package/dist/compiler/loops.d.ts +13 -0
  25. package/dist/compiler/loops.js +49 -0
  26. package/dist/compiler/parse.d.ts +40 -0
  27. package/dist/compiler/parse.js +164 -1
  28. package/dist/compiler/script.d.ts +2 -0
  29. package/dist/compiler/script.js +78 -1
  30. package/dist/forms/index.js +35 -15
  31. package/dist/forms/types.d.ts +7 -0
  32. package/dist/node/serve.d.ts +26 -0
  33. package/dist/node/serve.js +150 -0
  34. package/dist/runtime/attrs.d.ts +1 -1
  35. package/dist/runtime/attrs.js +8 -5
  36. package/dist/runtime/dom.d.ts +40 -4
  37. package/dist/runtime/dom.js +200 -49
  38. package/dist/runtime/hot.js +3 -2
  39. package/dist/runtime/index.d.ts +1 -1
  40. package/dist/runtime/index.js +1 -1
  41. package/dist/runtime/loader.js +39 -7
  42. package/dist/runtime/motion.d.ts +59 -0
  43. package/dist/runtime/motion.js +339 -0
  44. package/dist/runtime/navigate.d.ts +2 -0
  45. package/dist/runtime/navigate.js +7 -1
  46. package/dist/runtime/navigation.d.ts +44 -0
  47. package/dist/runtime/navigation.js +69 -3
  48. package/dist/runtime/signals.d.ts +2 -0
  49. package/dist/runtime/signals.js +31 -0
  50. package/dist/seo.d.ts +140 -0
  51. package/dist/seo.js +64 -0
  52. package/dist/server/handler.d.ts +1 -0
  53. package/dist/server/handler.js +1 -0
  54. package/dist/server/head.js +5 -0
  55. package/dist/vite/build.d.ts +9 -2
  56. package/dist/vite/build.js +20 -5
  57. package/dist/vite/cloudflare.d.ts +3 -0
  58. package/dist/vite/cloudflare.js +55 -0
  59. package/dist/vite/env.d.ts +19 -0
  60. package/dist/vite/env.js +34 -0
  61. package/dist/vite/headers.d.ts +27 -0
  62. package/dist/vite/headers.js +70 -0
  63. package/dist/vite/libraries.d.ts +32 -0
  64. package/dist/vite/libraries.js +77 -0
  65. package/dist/vite/manifest.d.ts +11 -1
  66. package/dist/vite/manifest.js +10 -1
  67. package/dist/vite/netlify.d.ts +5 -2
  68. package/dist/vite/netlify.js +4 -2
  69. package/dist/vite/node.d.ts +4 -0
  70. package/dist/vite/node.js +9 -2
  71. package/dist/vite/plugin.d.ts +30 -3
  72. package/dist/vite/plugin.js +97 -28
  73. package/dist/vite/vercel.d.ts +3 -0
  74. package/dist/vite/vercel.js +53 -0
  75. package/package.json +14 -1
@@ -1,6 +1,9 @@
1
+ import { modifierError, splitEvent } from './events.js';
2
+ import { extendedAttrs } from './element-attrs.js';
1
3
  import { parseExpressionAt } from 'acorn';
2
4
  import { iconElement } from './icon.js';
3
5
  import { ClarusError } from './errors.js';
6
+ import { outerIndexIn } from './loops.js';
4
7
  import { FOR_IMPLICIT, importNames } from './parse.js';
5
8
  import { analyzeScript, providesIn, mutationsOf, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, serverScriptParts, splitImports } from './script.js';
6
9
  const ATTACH_MODES = ['load', 'idle', 'visible', 'interaction'];
@@ -9,7 +12,10 @@ const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input'
9
12
  const iconBodies = new WeakMap();
10
13
  export function lower(parsed, file, source, options = {}) {
11
14
  const fail = (text, at) => { throw new ClarusError(text, file, source, at); };
12
- 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);
13
19
  if (parsed.events.length && !parsed.script)
14
20
  fail('@event needs a <script> that sends it with emit(\'name\', value)', parsed.events[0].start);
15
21
  if (parsed.contexts.length && stateful)
@@ -120,6 +126,15 @@ export function lower(parsed, file, source, options = {}) {
120
126
  if (node.type === 'fill')
121
127
  return fail('@slot only works directly inside a component tag', node.start);
122
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
+ }
123
138
  const block = stateful ? blockCount++ : -1;
124
139
  const parent = out;
125
140
  const parentScope = scopeKey;
@@ -135,7 +150,7 @@ export function lower(parsed, file, source, options = {}) {
135
150
  });
136
151
  out = parent;
137
152
  scopeKey = parentScope;
138
- out.push({ kind: 'if', branches, block });
153
+ out.push({ kind: 'if', branches, block, ...(tr ? { transition: { name: tr.name, options: tr.options } } : {}) });
139
154
  return;
140
155
  }
141
156
  if (node.type === 'await') {
@@ -160,6 +175,15 @@ export function lower(parsed, file, source, options = {}) {
160
175
  return;
161
176
  }
162
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
+ }
163
187
  checkExpr(node.list, file, source, node.listStart);
164
188
  if (node.track !== null)
165
189
  checkExpr(node.track, file, source, node.trackStart);
@@ -176,16 +200,16 @@ export function lower(parsed, file, source, options = {}) {
176
200
  children.forEach((child) => visit(child, rawText));
177
201
  return list;
178
202
  };
179
- 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)])))
180
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);
181
205
  if (block >= 0 && node.track === null)
182
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));
183
- 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)]));
184
208
  const empty = node.empty ? lowerInto(node.empty, `f${block}e`, parentLoop) : null;
185
209
  out = parent;
186
210
  scopeKey = parentScope;
187
211
  loopNames = parentLoop;
188
- 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 } } : {}) });
189
213
  return;
190
214
  }
191
215
  if (node.type === 'raw')
@@ -250,6 +274,8 @@ export function lower(parsed, file, source, options = {}) {
250
274
  else if (a.kind === 'event') {
251
275
  if (!stateful)
252
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);
253
279
  checkHandler(a.expr, file, source, a.start);
254
280
  listens.push({ name: a.name, handler: a.expr });
255
281
  }
@@ -290,12 +316,23 @@ export function lower(parsed, file, source, options = {}) {
290
316
  continue;
291
317
  if (fills.some((f) => f.name === child.name))
292
318
  fail(`slot "${child.name}" is filled twice`, child.start);
319
+ let nodes;
293
320
  if (child.params !== undefined) {
294
- if (stateful)
295
- 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);
296
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);
297
332
  }
298
- 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 });
299
336
  }
300
337
  const rest = node.children.filter((c) => c.type !== 'fill');
301
338
  const children = rest.every((c) => c.type === 'text' && !c.value.trim()) ? [] : lowerList(rest);
@@ -425,6 +462,10 @@ export function lower(parsed, file, source, options = {}) {
425
462
  else if (a.kind === 'event') {
426
463
  if (!stateful)
427
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);
428
469
  checkHandler(a.expr, file, source, a.start);
429
470
  const found = source.indexOf(a.expr, a.start);
430
471
  const exprStart = found === -1 ? a.start : found;
@@ -490,8 +531,10 @@ export function lower(parsed, file, source, options = {}) {
490
531
  if (elementEvents.length) {
491
532
  const index = eventElementCount++;
492
533
  emitStatic(` data-cl-e="${index}"`);
493
- for (const a of elementEvents)
494
- 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
+ }
495
538
  }
496
539
  emitStatic('>');
497
540
  const iconBody = iconBodies.get(node);
@@ -518,6 +561,7 @@ export function lower(parsed, file, source, options = {}) {
518
561
  file,
519
562
  name: file.split('/').pop().replace(/\.tscl$/, ''),
520
563
  inputs: parsed.inputs,
564
+ ...(parsed.extends ? { extends: Object.keys(extendedAttrs(parsed.extends.tag)) } : {}),
521
565
  imports: parsed.imports,
522
566
  script: parsed.script ? split.body : undefined,
523
567
  scriptImports: split.imports.map((imp) => imp.text),
@@ -528,11 +572,36 @@ export function lower(parsed, file, source, options = {}) {
528
572
  nodes,
529
573
  events,
530
574
  sends: parsed.events.length > 0,
575
+ sendNames: parsed.events.map((e) => e.name),
531
576
  contexts: parsed.contexts,
532
577
  provides,
533
578
  warnings,
534
579
  };
535
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
+ }
536
605
  function slotParamsCheck(params, file, source, at) {
537
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); };
538
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';
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
@@ -26,6 +26,18 @@ export type LintMessage = {
26
26
  line: number;
27
27
  column: number;
28
28
  start: number;
29
+ fix?: LintFix;
30
+ };
31
+ /**
32
+ * An edit that fixes a finding: the source from `start` to `end` (offsets) becomes `text`. `clarusjs check --fix` and
33
+ * the ESLint plugin apply them.
34
+ * @since 0.16.0
35
+ * @see https://clarusjs.com/guide/lint#fixes
36
+ */
37
+ export type LintFix = {
38
+ start: number;
39
+ end: number;
40
+ text: string;
29
41
  };
30
42
  /**
31
43
  * A template element, as `parse` returns it.
@@ -49,7 +61,9 @@ export type LintContext = {
49
61
  /** Whether the template, the script, or an input's type or default reads `name`. */
50
62
  reads(name: string): boolean;
51
63
  /** A finding at `start`, an offset in the source (an element's, an attribute's, an @input's). */
52
- report(start: number, message: string): void;
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[];
53
67
  };
54
68
  /**
55
69
  * A lint rule: a name (used in levels and ignore comments) and a check over one file.
@@ -79,4 +93,18 @@ export declare const lintRules: LintRuleDef[];
79
93
  * ```
80
94
  * @see https://clarusjs.com/reference/compiler#lint
81
95
  */
82
- 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[];
99
+ /**
100
+ * The source with the findings' fixes applied. Overlapping fixes: the first one (by position) wins; run lint again for
101
+ * the rest.
102
+ * @example
103
+ * ```ts
104
+ * import { applyFixes, lint } from 'clarusjs/compiler'
105
+ * const fixed = applyFixes(source, lint(source, 'src/components/card.tscl'))
106
+ * ```
107
+ * @since 0.16.0
108
+ * @see https://clarusjs.com/reference/compiler#applyfixes
109
+ */
110
+ export declare function applyFixes(source: string, messages: readonly LintMessage[]): string;
@@ -1,5 +1,7 @@
1
1
  import { ClarusError } from './errors.js';
2
- import { awaitLists, importNames, parse } 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,105 @@ 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
+ },
163
+ {
164
+ name: 'one-root',
165
+ check({ file, source, parsed, report }) {
166
+ if (/(^|[\\/])(pages|layouts)[\\/]/.test(file))
167
+ return;
168
+ const top = rootNodes;
169
+ const nodes = top(parsed.nodes);
170
+ if (nodes.some((n) => n.type === 'element' && n.tag === 'html'))
171
+ return;
172
+ const element = (list) => list.length === 1 && list[0].type === 'element';
173
+ if (element(nodes))
174
+ return;
175
+ const one = (list) => element(list) && list[0].tag !== 'fragment';
176
+ const [first] = nodes;
177
+ if (nodes.length === 1 && first.type === 'if' && first.branches.at(-1).cond === null && first.branches.every((b) => one(top(b.children))))
178
+ return;
179
+ const at = nodes.length > 1 && (first.type === 'element') ? nodes[1] : first;
180
+ if (!at)
181
+ return;
182
+ const last = nodes.at(-1);
183
+ const blocks = [...parsed.styles.map((st) => st.tag), parsed.serverScript?.tag ?? -1, parsed.script ? source.lastIndexOf('<script', parsed.script.start) : -1];
184
+ const after = [...parsed.nodes.map((n) => n.start), ...blocks].filter((x) => x > last.start);
185
+ const rawEnd = after.length ? Math.min(...after) : source.length;
186
+ const end = source.slice(0, rawEnd).trimEnd().length;
187
+ const declared = Object.entries(parsed).flatMap(([key, value]) => {
188
+ if (['nodes', 'script', 'serverScript', 'styles'].includes(key))
189
+ return [];
190
+ if (typeof value === 'number')
191
+ return [value];
192
+ const items = Array.isArray(value) ? value : [value];
193
+ return items.flatMap((d) => (d && typeof d === 'object' && typeof d.start === 'number' ? [d.start] : []));
194
+ });
195
+ const inside = (x) => x > first.start && x < end;
196
+ const moving = new Set([...blocks, ...declared].filter(inside));
197
+ const cuts = [...new Set([first.start, ...parsed.nodes.map((n) => n.start).filter(inside), ...moving])].sort((a, b) => a - b);
198
+ const pieces = cuts.map((c, i) => ({ c, text: source.slice(c, cuts[i + 1] ?? end) }));
199
+ const nl = source.includes('\r\n') ? '\r\n' : '\n';
200
+ const moved = pieces.filter((p) => moving.has(p.c)).map((p) => p.text.trimEnd() + nl).join('');
201
+ const typeAt = new Map(parsed.nodes.map((n) => [n.start, n.type]));
202
+ const stay = pieces.filter((p) => !moving.has(p.c));
203
+ const kept = stay.map((p, i) => {
204
+ const next = stay[i + 1];
205
+ if (!next || next.c === pieces[pieces.indexOf(p) + 1]?.c || typeAt.get(p.c) === 'text')
206
+ return p.text;
207
+ const text = p.text.trimEnd();
208
+ return typeAt.get(p.c) !== 'text' && typeAt.get(next.c) !== 'text' ? text + nl : text;
209
+ }).join('').trimEnd();
210
+ const close = last.type !== 'text' || source.slice(end, rawEnd).includes('\n') ? nl : '';
211
+ const fix = { start: first.start, end, text: `${moved}<fragment>${nl}${kept}${close}</fragment>` };
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);
213
+ },
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
+ },
89
225
  {
90
226
  name: 'unused-input',
91
227
  check({ parsed, reads, report }) {
@@ -108,6 +244,30 @@ export const lintRules = [
108
244
  }
109
245
  },
110
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
+ },
111
271
  {
112
272
  name: 'img-alt',
113
273
  check({ elements, report }) {
@@ -140,7 +300,7 @@ export const lintRules = [
140
300
  },
141
301
  },
142
302
  ];
143
- export function lint(source, file, config = {}, extra = []) {
303
+ export function lint(source, file, config = {}, extra = [], options = {}) {
144
304
  const parsed = parse(source, file);
145
305
  const corpus = [
146
306
  ...expressions(parsed.nodes),
@@ -163,22 +323,23 @@ export function lint(source, file, config = {}, extra = []) {
163
323
  parsed,
164
324
  elements: [...elements(parsed.nodes)],
165
325
  components: new Set(parsed.imports.map((i) => i.name)),
166
- 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(),
167
328
  };
168
329
  const out = [];
169
- const add = (rule, severity, start, message) => {
330
+ const add = (rule, severity, start, message, fix) => {
170
331
  const { line, column } = new ClarusError(message, file, source, start);
171
332
  const skip = ignored.get(line);
172
333
  if (skip === 'all' || skip?.has(rule))
173
334
  return;
174
- out.push({ rule, severity, message, file, line, column, start });
335
+ out.push({ rule, severity, message, file, line, column, start, ...(fix ? { fix } : {}) });
175
336
  };
176
337
  for (const rule of [...lintRules, ...extra]) {
177
- const level = config[rule.name] ?? 'warn';
338
+ const level = config[rule.name] ?? (rule.name === 'server-env-in-browser' ? 'error' : 'warn');
178
339
  if (level === 'off')
179
340
  continue;
180
341
  try {
181
- rule.check({ ...base, report: (start, message) => add(rule.name, level === 'error' ? 'error' : 'warning', start, message) });
342
+ rule.check({ ...base, report: (start, message, fix) => add(rule.name, level === 'error' ? 'error' : 'warning', start, message, fix) });
182
343
  }
183
344
  catch (err) {
184
345
  add(rule.name, 'error', 0, `the rule failed: ${err.message}`);
@@ -186,3 +347,11 @@ export function lint(source, file, config = {}, extra = []) {
186
347
  }
187
348
  return out.sort((a, b) => a.start - b.start);
188
349
  }
350
+ export function applyFixes(source, messages) {
351
+ const fixes = messages.flatMap((m) => (m.fix ? [m.fix] : [])).sort((a, b) => a.start - b.start);
352
+ const kept = [];
353
+ for (const f of fixes)
354
+ if (!kept.length || f.start >= kept.at(-1).end)
355
+ kept.push(f);
356
+ return kept.reduceRight((text, f) => text.slice(0, f.start) + f.text + text.slice(f.end), source);
357
+ }
@@ -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.
@@ -193,10 +208,33 @@ export type ParsedFile = {
193
208
  /** `@layout none` (#456): the page renders without its folder and config layouts. `layoutStart`: where it is. */
194
209
  layout?: 'none';
195
210
  layoutStart?: number;
211
+ /** `@extends button`: the native element this component stands for; it takes all of that element's attributes. */
212
+ extends?: {
213
+ tag: string;
214
+ start: number;
215
+ };
196
216
  nodes: TemplateNode[];
197
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
+ };
198
224
  /** The names a @for row has besides its item: $index, $count, $first, $last, $even, $odd. */
199
225
  export declare const FOR_IMPLICIT: string[];
226
+ /**
227
+ * A template's top-level nodes that render: no whitespace or comments, no <cl-head>, <script> or <style>. What one-root, @extends,
228
+ * fragment roots and check all look at.
229
+ * @internal
230
+ */
231
+ export declare function rootNodes(nodes: TemplateNode[]): TemplateNode[];
232
+ /**
233
+ * Whether a component's root is (or may be) a <fragment>: one at the top, or in a branch of a top-level @if. It
234
+ * renders no single element, so a parent's attributes and events have nowhere to land.
235
+ * @internal
236
+ */
237
+ export declare function fragmentRoot(nodes: TemplateNode[]): boolean;
200
238
  /**
201
239
  * Parse a `.tscl` file into its syntax tree, without compiling it: for tools (an editor, a linter, a docs
202
240
  * generator). Throws a located `ClarusError` for a syntax error.
@@ -211,3 +249,5 @@ export declare const FOR_IMPLICIT: string[];
211
249
  export declare function parse(source: string, file: string): ParsedFile;
212
250
  /** Local names an import clause binds: `{ a, b as c, type T }` → a, c; `x` → x. */
213
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;