clarusjs 0.15.0 → 0.16.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.
@@ -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';
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,7 @@ 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;
53
65
  };
54
66
  /**
55
67
  * A lint rule: a name (used in levels and ignore comments) and a check over one file.
@@ -80,3 +92,15 @@ export declare const lintRules: LintRuleDef[];
80
92
  * @see https://clarusjs.com/reference/compiler#lint
81
93
  */
82
94
  export declare function lint(source: string, file: string, config?: LintConfig, extra?: LintRuleDef[]): LintMessage[];
95
+ /**
96
+ * The source with the findings' fixes applied. Overlapping fixes: the first one (by position) wins; run lint again for
97
+ * the rest.
98
+ * @example
99
+ * ```ts
100
+ * import { applyFixes, lint } from 'clarusjs/compiler'
101
+ * const fixed = applyFixes(source, lint(source, 'src/components/card.tscl'))
102
+ * ```
103
+ * @since 0.16.0
104
+ * @see https://clarusjs.com/reference/compiler#applyfixes
105
+ */
106
+ export declare function applyFixes(source: string, messages: readonly LintMessage[]): string;
@@ -1,5 +1,5 @@
1
1
  import { ClarusError } from './errors.js';
2
- import { awaitLists, importNames, parse } from './parse.js';
2
+ import { awaitLists, importNames, parse, rootNodes } from './parse.js';
3
3
  const FIELDS = new Set(['input', 'select', 'textarea', 'meter', 'output', 'progress']);
4
4
  const IGNORE_RE = /\{\{--\s*clarusjs-ignore\b([\w\s,-]*?)\s*--\}\}/g;
5
5
  function* elements(nodes) {
@@ -86,6 +86,58 @@ function named(nodes, components) {
86
86
  });
87
87
  }
88
88
  export const lintRules = [
89
+ {
90
+ name: 'one-root',
91
+ check({ file, source, parsed, report }) {
92
+ if (/(^|[\\/])(pages|layouts)[\\/]/.test(file))
93
+ return;
94
+ const top = rootNodes;
95
+ const nodes = top(parsed.nodes);
96
+ if (nodes.some((n) => n.type === 'element' && n.tag === 'html'))
97
+ return;
98
+ const element = (list) => list.length === 1 && list[0].type === 'element';
99
+ if (element(nodes))
100
+ return;
101
+ const one = (list) => element(list) && list[0].tag !== 'fragment';
102
+ const [first] = nodes;
103
+ if (nodes.length === 1 && first.type === 'if' && first.branches.at(-1).cond === null && first.branches.every((b) => one(top(b.children))))
104
+ return;
105
+ const at = nodes.length > 1 && (first.type === 'element') ? nodes[1] : first;
106
+ if (!at)
107
+ return;
108
+ const last = nodes.at(-1);
109
+ const blocks = [...parsed.styles.map((st) => st.tag), parsed.serverScript?.tag ?? -1, parsed.script ? source.lastIndexOf('<script', parsed.script.start) : -1];
110
+ const after = [...parsed.nodes.map((n) => n.start), ...blocks].filter((x) => x > last.start);
111
+ const rawEnd = after.length ? Math.min(...after) : source.length;
112
+ const end = source.slice(0, rawEnd).trimEnd().length;
113
+ const declared = Object.entries(parsed).flatMap(([key, value]) => {
114
+ if (['nodes', 'script', 'serverScript', 'styles'].includes(key))
115
+ return [];
116
+ if (typeof value === 'number')
117
+ return [value];
118
+ const items = Array.isArray(value) ? value : [value];
119
+ return items.flatMap((d) => (d && typeof d === 'object' && typeof d.start === 'number' ? [d.start] : []));
120
+ });
121
+ const inside = (x) => x > first.start && x < end;
122
+ const moving = new Set([...blocks, ...declared].filter(inside));
123
+ const cuts = [...new Set([first.start, ...parsed.nodes.map((n) => n.start).filter(inside), ...moving])].sort((a, b) => a - b);
124
+ const pieces = cuts.map((c, i) => ({ c, text: source.slice(c, cuts[i + 1] ?? end) }));
125
+ const nl = source.includes('\r\n') ? '\r\n' : '\n';
126
+ const moved = pieces.filter((p) => moving.has(p.c)).map((p) => p.text.trimEnd() + nl).join('');
127
+ const typeAt = new Map(parsed.nodes.map((n) => [n.start, n.type]));
128
+ const stay = pieces.filter((p) => !moving.has(p.c));
129
+ const kept = stay.map((p, i) => {
130
+ const next = stay[i + 1];
131
+ if (!next || next.c === pieces[pieces.indexOf(p) + 1]?.c || typeAt.get(p.c) === 'text')
132
+ return p.text;
133
+ const text = p.text.trimEnd();
134
+ return typeAt.get(p.c) !== 'text' && typeAt.get(next.c) !== 'text' ? text + nl : text;
135
+ }).join('').trimEnd();
136
+ const close = last.type !== 'text' || source.slice(end, rawEnd).includes('\n') ? nl : '';
137
+ const fix = { start: first.start, end, text: `${moved}<fragment>${nl}${kept}${close}</fragment>` };
138
+ 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
+ },
140
+ },
89
141
  {
90
142
  name: 'unused-input',
91
143
  check({ parsed, reads, report }) {
@@ -166,19 +218,19 @@ export function lint(source, file, config = {}, extra = []) {
166
218
  reads: (name) => new RegExp(`(?<![\\w$.])${name.replace(/\$/g, '\\$')}(?![\\w$])`).test(corpus),
167
219
  };
168
220
  const out = [];
169
- const add = (rule, severity, start, message) => {
221
+ const add = (rule, severity, start, message, fix) => {
170
222
  const { line, column } = new ClarusError(message, file, source, start);
171
223
  const skip = ignored.get(line);
172
224
  if (skip === 'all' || skip?.has(rule))
173
225
  return;
174
- out.push({ rule, severity, message, file, line, column, start });
226
+ out.push({ rule, severity, message, file, line, column, start, ...(fix ? { fix } : {}) });
175
227
  };
176
228
  for (const rule of [...lintRules, ...extra]) {
177
229
  const level = config[rule.name] ?? 'warn';
178
230
  if (level === 'off')
179
231
  continue;
180
232
  try {
181
- rule.check({ ...base, report: (start, message) => add(rule.name, level === 'error' ? 'error' : 'warning', start, message) });
233
+ rule.check({ ...base, report: (start, message, fix) => add(rule.name, level === 'error' ? 'error' : 'warning', start, message, fix) });
182
234
  }
183
235
  catch (err) {
184
236
  add(rule.name, 'error', 0, `the rule failed: ${err.message}`);
@@ -186,3 +238,11 @@ export function lint(source, file, config = {}, extra = []) {
186
238
  }
187
239
  return out.sort((a, b) => a.start - b.start);
188
240
  }
241
+ export function applyFixes(source, messages) {
242
+ const fixes = messages.flatMap((m) => (m.fix ? [m.fix] : [])).sort((a, b) => a.start - b.start);
243
+ const kept = [];
244
+ for (const f of fixes)
245
+ if (!kept.length || f.start >= kept.at(-1).end)
246
+ kept.push(f);
247
+ return kept.reduceRight((text, f) => text.slice(0, f.start) + f.text + text.slice(f.end), source);
248
+ }
@@ -193,10 +193,27 @@ export type ParsedFile = {
193
193
  /** `@layout none` (#456): the page renders without its folder and config layouts. `layoutStart`: where it is. */
194
194
  layout?: 'none';
195
195
  layoutStart?: number;
196
+ /** `@extends button`: the native element this component stands for; it takes all of that element's attributes. */
197
+ extends?: {
198
+ tag: string;
199
+ start: number;
200
+ };
196
201
  nodes: TemplateNode[];
197
202
  };
198
203
  /** The names a @for row has besides its item: $index, $count, $first, $last, $even, $odd. */
199
204
  export declare const FOR_IMPLICIT: string[];
205
+ /**
206
+ * A template's top-level nodes that render: no whitespace or comments, no <cl-head>, <script> or <style>. What one-root, @extends,
207
+ * fragment roots and check all look at.
208
+ * @internal
209
+ */
210
+ export declare function rootNodes(nodes: TemplateNode[]): TemplateNode[];
211
+ /**
212
+ * 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
213
+ * renders no single element, so a parent's attributes and events have nowhere to land.
214
+ * @internal
215
+ */
216
+ export declare function fragmentRoot(nodes: TemplateNode[]): boolean;
200
217
  /**
201
218
  * Parse a `.tscl` file into its syntax tree, without compiling it: for tools (an editor, a linter, a docs
202
219
  * generator). Throws a located `ClarusError` for a syntax error.
@@ -7,6 +7,14 @@ const IMPORT_TYPE_RE = /^@import\s+type\s+(\{[^}]*\}|[A-Za-z_$][\w$]*)\s+from\s+
7
7
  const IMPORT_RE = /^@import\s+([A-Za-z_$][\w-]*)\s+from\s+(['"])(.+?)\2\s*$/;
8
8
  const CSS_IMPORT_RE = /^@import\s+(['"])(.+?)\1\s*$/;
9
9
  const typeNames = (clause) => clause.startsWith('{') ? clause.slice(1, -1).split(',').map((p) => p.trim().replace(/^type\s+/, '').split(/\s+as\s+/).pop().trim()).filter(Boolean) : [clause.trim()];
10
+ export function rootNodes(nodes) {
11
+ return nodes.filter((n) => !(n.type === 'text' && !n.value.replace(/<!--[\s\S]*?-->/g, '').trim()) && !(n.type === 'element' && ['cl-head', 'script', 'style'].includes(n.tag)));
12
+ }
13
+ export function fragmentRoot(nodes) {
14
+ const top = rootNodes(nodes);
15
+ const frag = (list) => list.length === 1 && list[0].type === 'element' && list[0].tag === 'fragment';
16
+ return frag(top) || (top.length === 1 && top[0].type === 'if' && top[0].branches.some((b) => frag(rootNodes(b.children))));
17
+ }
10
18
  export function parse(source, file) {
11
19
  const out = { inputs: [], events: [], contexts: [], imports: [], typeImports: [], types: [], dataImports: [], styles: [], cssImports: [], nodes: [] };
12
20
  let i = 0;
@@ -48,6 +56,13 @@ export function parse(source, file) {
48
56
  const typeStart = d[2] ? lineStart + line.lastIndexOf(d[2]) : nameStart;
49
57
  out.events.push({ name: d[1], type: d[2] ?? 'void', start: i, nameStart, typeStart });
50
58
  }
59
+ else if ((m = /^@extends(?:\s+(\S+))?\s*$/.exec(line))) {
60
+ if (out.extends)
61
+ fail('a component has one @extends', i);
62
+ if (!m[1])
63
+ fail('@extends takes an element name: @extends button', i);
64
+ out.extends = { tag: m[1], start: i };
65
+ }
51
66
  else if ((m = /^@layout(?:\s+(\S+))?\s*$/.exec(line))) {
52
67
  if (m[1] !== 'none')
53
68
  fail('@layout only takes none: @layout none renders the page without its folder and config layouts', i);
@@ -35,4 +35,4 @@ export declare function spreadAttrs(obj: unknown, skip: readonly string[], tag?:
35
35
  * as an input. They land on its root element (a spread, so the root's own attributes win; style merges).
36
36
  * @internal Compiled components call this.
37
37
  */
38
- export declare function passed(props: Record<string, unknown>, inputs: readonly string[]): Record<string, unknown>;
38
+ export declare function passed(props: Record<string, unknown>, inputs: readonly string[], element?: readonly string[]): Record<string, unknown>;
@@ -7,13 +7,15 @@ const URL_ATTRS = new Set([
7
7
  // SVG animation values can set an href, but only on animation elements; elsewhere these are ordinary data.
8
8
  const ANIMATION_ATTRS = new Set(['to', 'from', 'values', 'by']);
9
9
  const ANIMATION_ELEMENTS = new Set(['animate', 'set', 'animatemotion', 'animatetransform']);
10
- // Attributes that load an image, where a raster data: URL is fine.
10
+ // Attributes that load an image, where a raster data: URL or an object URL (blob:, a preview of a picked file) is fine:
11
+ // an image can't run script. Attributes that load a page or a script (iframe, embed, object, script) are static only,
12
+ // so a bound value never reaches them; href keeps refusing blob: (a blob of HTML would open as this site's page).
11
13
  const IMAGE_ATTRS = new Set(['src', 'srcset', 'poster']);
12
14
  const SAFE_SCHEMES = new Set(['http', 'https', 'mailto', 'tel']);
13
15
  const RASTER_DATA = /^data:image\/(png|gif|jpe?g|webp|avif|bmp);/i;
14
16
  export const UNSAFE_URL = 'about:invalid#unsafe';
15
17
  /**
16
- * Allowlist: a relative URL, a safe scheme, or (for image attributes) a raster data: image.
18
+ * Allowlist: a relative URL, a safe scheme, or (for image attributes) a raster data: image or an object URL.
17
19
  * Browsers ignore control characters and whitespace around and inside the scheme, so the check does too.
18
20
  */
19
21
  function safeUrl(url, image) {
@@ -23,7 +25,7 @@ function safeUrl(url, image) {
23
25
  return true; // relative: /x, ../x, #x, ?x
24
26
  if (SAFE_SCHEMES.has(scheme))
25
27
  return true;
26
- return image && RASTER_DATA.test(compact);
28
+ return image && (scheme === 'blob' || RASTER_DATA.test(compact));
27
29
  }
28
30
  // false is a value here, not a missing attribute: enumerated attributes (removing one means its default), and the
29
31
  // ARIA states whose absence means "doesn't apply" (no aria-expanded: nothing expands). Other aria-* (aria-current:
@@ -136,11 +138,12 @@ const PASSED = /^(id|role|tabindex|hidden|lang|dir|style|(data|aria)-[\w:.-]+)$/
136
138
  * as an input. They land on its root element (a spread, so the root's own attributes win; style merges).
137
139
  * @internal Compiled components call this.
138
140
  */
139
- export function passed(props, inputs) {
141
+ export function passed(props, inputs, element = []) {
140
142
  const out = {};
141
143
  // Never clarusjs's own markers (data-cl-e, data-cl-u, data-cl-path…): passed data must not spoof the runtime's wiring.
144
+ // element: an @extends component's element attributes (button's disabled, form…), passed through as well.
142
145
  for (const k in props)
143
- if (PASSED.test(k) && !/^data-cl-/i.test(k) && !inputs.includes(k))
146
+ if ((PASSED.test(k) || element.includes(k.toLowerCase())) && !/^data-cl-/i.test(k) && !inputs.includes(k))
144
147
  out[k] = props[k];
145
148
  return out;
146
149
  }
@@ -121,12 +121,18 @@ export declare function emit(root: Element, name: string, value: unknown, info?:
121
121
  reason?: string;
122
122
  event?: Event;
123
123
  }): boolean;
124
- /** (name)="…" on a child island in region `index` (#442): its emit('name', …) arrives here, and goes no further. @internal */
124
+ /** A component's attach() records its @event names. @internal */
125
+ export declare function declare(root: Element, names: string[]): void;
126
+ /**
127
+ * (name)="…" on a component in region `index`. A child island's emit('name', …) arrives here and goes no further
128
+ * (#442); any other name is the DOM event, bubbling up from what the child renders (Vue's fallthrough), unless the
129
+ * child island declares it. @internal
130
+ */
125
131
  export declare function listen(ctx: Ctx, index: number, name: string, handler: (value: unknown, info: {
126
132
  reason?: string;
127
133
  event?: Event;
128
134
  cancel(): void;
129
- }) => void): void;
135
+ }) => void, bound?: string): void;
130
136
  /** [(name)]="…" on a child island in region `index`: the child's writes to its @model name arrive here. @internal */
131
137
  export declare function model(ctx: Ctx, index: number, name: string, set: (value: unknown) => void): void;
132
138
  export {};
@@ -518,15 +518,46 @@ export function modelInput(root, name, initial) {
518
518
  export function emit(root, name, value, info = {}) {
519
519
  return root.dispatchEvent(new CustomEvent('cl:event', { detail: { name, value, ...info }, bubbles: true, cancelable: true }));
520
520
  }
521
- /** (name)="…" on a child island in region `index` (#442): its emit('name', …) arrives here, and goes no further. @internal */
522
- export function listen(ctx, index, name, handler) {
521
+ // The @event names each child island declares (recorded when it attaches): those don't fall through as DOM events.
522
+ const declared = new WeakMap();
523
+ /** A component's attach() records its @event names. @internal */
524
+ export function declare(root, names) {
525
+ declared.set(root, names);
526
+ }
527
+ /**
528
+ * (name)="…" on a component in region `index`. A child island's emit('name', …) arrives here and goes no further
529
+ * (#442); any other name is the DOM event, bubbling up from what the child renders (Vue's fallthrough), unless the
530
+ * child island declares it. @internal
531
+ */
532
+ export function listen(ctx, index, name, handler, bound) {
533
+ // The bound component's island (by its c name): only its emit() is this listener's, and only its contract decides
534
+ // whether a DOM event is one it sends itself. A wrapper that declares nothing gets the DOM event.
535
+ const isBound = (el) => !bound || el.getAttribute('c') === bound;
523
536
  fromChild(ctx, index, 'cl:event', name, (event, detail) => {
524
537
  const { value, reason, event: cause } = detail;
525
538
  handler(value, { reason, event: cause, cancel: () => event.preventDefault() });
526
- });
539
+ }, (from) => isBound(from));
540
+ const r = scan(ctx).regions[index];
541
+ if (!r)
542
+ return;
543
+ const host = r.start.parentNode;
544
+ const dom = (event) => {
545
+ const from = event.target;
546
+ if (!(r.start.compareDocumentPosition(from) & 4) || !(r.end.compareDocumentPosition(from) & 2))
547
+ return;
548
+ // The bound island between the target and here: not attached yet, it replays the event once it is (its emit()
549
+ // decides then); declaring this name, it sends it as its own event.
550
+ for (let n = from; n && n !== host; n = n.parentNode) {
551
+ if (n.localName === 'cl-island' && isBound(n) && (!n.hasAttribute('data-cl-ready') || declared.get(n)?.includes(name)))
552
+ return;
553
+ }
554
+ handler(event, { event, cancel: () => event.preventDefault() });
555
+ };
556
+ host.addEventListener(name, dom);
557
+ onDispose(() => host.removeEventListener(name, dom));
527
558
  }
528
559
  /** Listen for `type` from the child island bound in region `index` only (not one nested in it), named `name`. */
529
- function fromChild(ctx, index, type, name, take) {
560
+ function fromChild(ctx, index, type, name, take, accept = () => true) {
530
561
  const r = scan(ctx).regions[index];
531
562
  if (!r)
532
563
  return;
@@ -538,7 +569,7 @@ function fromChild(ctx, index, type, name, take) {
538
569
  if (detail.name !== name || !(r.start.compareDocumentPosition(from) & 4) || !(r.end.compareDocumentPosition(from) & 2))
539
570
  return;
540
571
  // Only the child island this region binds: an island nested in it, which nobody bound, keeps its own.
541
- if (owner(from) !== rootOf(ctx))
572
+ if (owner(from) !== rootOf(ctx) || !accept(from))
542
573
  return;
543
574
  event.stopPropagation();
544
575
  take(event, detail);
@@ -1,5 +1,5 @@
1
1
  export { state, derived, shared, effect, scope, onDispose, untrack, batch, type Signal, type ReadSignal } from './signals.ts';
2
- export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput, emit, listen, use, provideOn, type Hole, type Block, type Ctx } from './dom.ts';
2
+ export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput, emit, listen, declare, use, provideOn, type Hole, type Block, type Ctx } from './dom.ts';
3
3
  export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './html.ts';
4
4
  export { parse as parseIslandData } from './serialize.ts';
5
5
  export { classValue, styleValue } from './attrs.ts';
@@ -1,6 +1,6 @@
1
1
  // Browser runtime used by compiled attach() functions.
2
2
  export { state, derived, shared, effect, scope, onDispose, untrack, batch } from './signals.js';
3
- export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput, emit, listen, use, provideOn } from './dom.js';
3
+ export { holes, blocks, text, on, attr, spread, block, awaited, forBlock, region, model, modelInput, emit, listen, declare, use, provideOn } from './dom.js';
4
4
  export { escape, attrHtml, spreadHtml, blockHtml, forHtml, regionHtml } from './html.js';
5
5
  export { parse as parseIslandData } from './serialize.js';
6
6
  export { classValue, styleValue } from './attrs.js';
@@ -35,6 +35,10 @@ function holds(inner, el) {
35
35
  const updates = new WeakMap();
36
36
  // Each attached island's disposer: everything its attach() wired (effects, listeners) is released by it.
37
37
  const attached = new Map();
38
+ // Each island root's attributes as the server last rendered them: a re-render's changes (the parent's passed
39
+ // attributes) are applied to the kept root; ones its own state drives render the same and are left to it.
40
+ const rendered = new WeakMap();
41
+ const rootAttrs = (island) => new Map([...(island.firstElementChild?.attributes ?? [])].filter((a) => !a.name.startsWith('data-cl-')).map((a) => [a.name, a.value]));
38
42
  let lastLoad = (src) => import(__rewriteRelativeImportExtension(/* @vite-ignore */ src));
39
43
  // Events recorded until an island attaches, then replayed. Clicks and submits are held back (no navigation, no
40
44
  // form post) so the island can handle them once it is ready.
@@ -95,7 +99,10 @@ function schedule(el, go) {
95
99
  go();
96
100
  }
97
101
  });
98
- io.observe(el);
102
+ // <cl-island> is display: contents (no box: it never intersects), so watch what it holds.
103
+ const targets = el.children.length ? [...el.children] : [el.parentElement ?? el];
104
+ for (const target of targets)
105
+ io.observe(target);
99
106
  }
100
107
  else if (mode === 'interaction') {
101
108
  const start = () => { for (const type of INTERACTION)
@@ -134,6 +141,7 @@ async function attachOne(el, load, recorded) {
134
141
  return;
135
142
  }
136
143
  try {
144
+ rendered.set(el, rootAttrs(el));
137
145
  attached.set(el, scope(() => {
138
146
  // An island with inputs returns how to update them: kept for a parent island that passes new props.
139
147
  const update = mod.attach(el, props, state);
@@ -233,6 +241,18 @@ globalThis.__clUpdate = (el, next) => {
233
241
  for (const { name, value } of [...next.attributes])
234
242
  if (name.startsWith('data-cl-path-'))
235
243
  el.setAttribute(name, value);
244
+ const root = el.firstElementChild;
245
+ const before = rendered.get(el);
246
+ const after = rootAttrs(next);
247
+ if (root && before) {
248
+ for (const [name, value] of after)
249
+ if (before.get(name) !== value)
250
+ root.setAttribute(name, value);
251
+ for (const name of before.keys())
252
+ if (!after.has(name))
253
+ root.removeAttribute(name);
254
+ }
255
+ rendered.set(el, after);
236
256
  update?.(parse(p));
237
257
  return true;
238
258
  };
@@ -1,4 +1,5 @@
1
1
  import { type Alias } from './aliases.ts';
2
+ import { type ComponentNames } from '../compiler/components.ts';
2
3
  /** Absolute paths of every component file under `srcDir` (`.tscl`, or any page source extension given). */
3
4
  export declare function findClarusFiles(srcDir: string, extensions?: string[]): string[];
4
5
  /**
@@ -25,8 +26,14 @@ export declare function prerender(serverEntry: string, outDir: string, manifestF
25
26
  /** The package a file belongs to, from its last node_modules segment (pnpm: node_modules/.pnpm/x@1/node_modules/x/…). @internal */
26
27
  export declare function packageOf(file: string): string | undefined;
27
28
  /**
28
- * Component files reachable from `start` through @import lines: relative paths, root-relative ('/src/…') and package
29
+ * Where a package specifier imported by `from` leads, as Node finds it: from the importing file first (a library's own
30
+ * dependencies live in its node_modules), then from the app. Undefined when neither finds it.
31
+ * @internal The build and the plugin's page graph share it.
32
+ */
33
+ export declare function resolvePackage(root: string, from: string, spec: string): string | undefined;
34
+ /**
35
+ * Component files reachable from `start` through @import lines (and tags `names` imports automatically): relative paths, root-relative ('/src/…') and package
29
36
  * specifiers ('@clarusjs/theme-docs/layout.tscl', resolved as Node would from the app). Real paths, so a workspace
30
37
  * package linked into node_modules is one file, not two.
31
38
  */
32
- export declare function reachableComponents(root: string, start: string[], read: (file: string) => string, extensions: string[], aliases?: Alias[]): string[];
39
+ export declare function reachableComponents(root: string, start: string[], read: (file: string) => string, extensions: string[], aliases?: Alias[], names?: ComponentNames): string[];
@@ -4,6 +4,7 @@ import { readdirSync, realpathSync } from 'node:fs';
4
4
  import { createRequire } from 'node:module';
5
5
  import { dirname, resolve } from 'node:path';
6
6
  import { parse } from '../compiler/parse.js';
7
+ import { autoImport } from '../compiler/components.js';
7
8
  export function findClarusFiles(srcDir, extensions = ['.tscl']) {
8
9
  let entries;
9
10
  try {
@@ -85,8 +86,16 @@ export async function prerender(serverEntry, outDir, manifestFile, only) {
85
86
  export function packageOf(file) {
86
87
  return /.*[\\/]node_modules[\\/]((?:@[^\\/]+[\\/])?[^\\/]+)[\\/]/.exec(file)?.[1].replace(/\\/g, '/');
87
88
  }
88
- export function reachableComponents(root, start, read, extensions, aliases = []) {
89
- const require = createRequire(resolve(root, 'package.json'));
89
+ export function resolvePackage(root, from, spec) {
90
+ for (const origin of [from, resolve(root, 'package.json')]) {
91
+ try {
92
+ return createRequire(origin).resolve(spec);
93
+ }
94
+ catch { }
95
+ }
96
+ return undefined;
97
+ }
98
+ export function reachableComponents(root, start, read, extensions, aliases = [], names) {
90
99
  const seen = new Set();
91
100
  const queue = start.map((f) => realpathSync(f));
92
101
  while (queue.length) {
@@ -96,7 +105,11 @@ export function reachableComponents(root, start, read, extensions, aliases = [])
96
105
  seen.add(file);
97
106
  let imports;
98
107
  try {
99
- imports = parse(read(file), file).imports;
108
+ const text = read(file);
109
+ const parsed = parse(text, file);
110
+ if (names)
111
+ autoImport(parsed, names, file, text);
112
+ imports = parsed.imports;
100
113
  }
101
114
  catch {
102
115
  continue;
@@ -107,8 +120,10 @@ export function reachableComponents(root, start, read, extensions, aliases = [])
107
120
  continue;
108
121
  let target;
109
122
  try {
110
- target = spec.startsWith('.') ? resolve(dirname(file), spec) : spec.startsWith('/') ? resolve(root, spec.slice(1)) : resolveAlias(spec, aliases) ?? require.resolve(spec);
111
- target = realpathSync(target);
123
+ const found = spec.startsWith('.') ? resolve(dirname(file), spec) : spec.startsWith('/') ? resolve(root, spec.slice(1)) : resolveAlias(spec, aliases) ?? resolvePackage(root, file, spec);
124
+ if (!found)
125
+ continue;
126
+ target = realpathSync(found);
112
127
  }
113
128
  catch {
114
129
  continue;
@@ -0,0 +1,32 @@
1
+ import { type ComponentNames, type Library } from '../compiler/components.ts';
2
+ /**
3
+ * A library the app uses: its package name, or the name with the tag prefix the app wants instead of the library's.
4
+ * @since 0.16.0
5
+ * @see https://clarusjs.com/guide/components#components-from-libraries
6
+ */
7
+ export type LibraryOption = string | {
8
+ from: string;
9
+ prefix?: string;
10
+ };
11
+ /** Each listed library, resolved: its components folder's `.tscl` files and its prefix. */
12
+ export declare function resolveLibraries(root: string, list: LibraryOption[]): Library[];
13
+ /**
14
+ * Every component name the app's templates may use without an @import: its own (`dirs`), then its libraries'. The
15
+ * folders and the libraries' names, none shadowed, go to .clarusjs/components.json for the editor, which lays the
16
+ * app's own (read live) over them; none when automatic imports are off. Undefined then.
17
+ */
18
+ export declare function componentNames(root: string, options?: {
19
+ dirs?: string[];
20
+ auto?: boolean;
21
+ libraries?: LibraryOption[];
22
+ }): ComponentNames | undefined;
23
+ /**
24
+ * The folders and libraries' names the plugin or `clarusjs check` last wrote for this app, if either has run. Written by a tool,
25
+ * but it may be stale or hand-edited: an entry that isn't a path (or several) is dropped, the rest kept.
26
+ */
27
+ export declare function readComponents(root: string): {
28
+ dirs?: string[];
29
+ names: ComponentNames;
30
+ } | undefined;
31
+ /** The libraries' names the plugin or `clarusjs check` last wrote for this app, if either has run. */
32
+ export declare function readComponentNames(root: string): ComponentNames | undefined;
@@ -0,0 +1,77 @@
1
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { dirname, relative, resolve, sep } from 'node:path';
4
+ import { COMPONENT_DIRS, componentIndex, libraryNames, withLibraries } from '../compiler/components.js';
5
+ import { findClarusFiles } from './build.js';
6
+ const posix = (path) => path.split(sep).join('/');
7
+ function packageDir(root, name) {
8
+ for (let dir = resolve(root);; dir = dirname(dir)) {
9
+ const candidate = resolve(dir, 'node_modules', name);
10
+ if (existsSync(resolve(candidate, 'package.json')))
11
+ return candidate;
12
+ if (dirname(dir) === dir)
13
+ return undefined;
14
+ }
15
+ }
16
+ export function resolveLibraries(root, list) {
17
+ return list.map((option) => {
18
+ const name = typeof option === 'string' ? option : option.from;
19
+ const dir = packageDir(root, name);
20
+ if (!dir)
21
+ throw new Error(`[clarusjs] the component library "${name}" isn't installed: add it to your dependencies, or remove it from components.libraries`);
22
+ const meta = JSON.parse(readFileSync(resolve(dir, 'package.json'), 'utf8')).clarusjs;
23
+ if (typeof meta?.components !== 'string') {
24
+ throw new Error(`[clarusjs] "${name}" doesn't describe its components: its package.json needs "clarusjs": { "components": "./src", "prefix": "ui" }`);
25
+ }
26
+ const base = resolve(dir, meta.components);
27
+ const files = findClarusFiles(base, ['.tscl']).map((f) => posix(relative(base, f))).sort();
28
+ const prefix = typeof option === 'object' && option.prefix !== undefined ? option.prefix : (meta.prefix ?? '');
29
+ if (prefix && !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(prefix))
30
+ throw new Error(`[clarusjs] the prefix "${prefix}" of "${name}" isn't kebab-case (lowercase letters, digits and hyphens): its tags couldn't be named`);
31
+ const require = createRequire(resolve(root, 'package.json'));
32
+ for (const file of files) {
33
+ const spec = `${name}/${file}`;
34
+ let found;
35
+ try {
36
+ found = realpathSync(require.resolve(spec));
37
+ }
38
+ catch { }
39
+ if (found !== realpathSync(resolve(base, file))) {
40
+ throw new Error(`[clarusjs] "${spec}" doesn't resolve to ${posix(relative(root, resolve(base, file)))}: the library's package.json exports must map its components with a plain path or a "default" condition, not "import" alone, for example "exports": { "./*": "${meta.components.replace(/\/?$/, '/')}*" }`);
41
+ }
42
+ }
43
+ return { name, prefix, files };
44
+ });
45
+ }
46
+ export function componentNames(root, options = {}) {
47
+ const dirs = options.auto === false ? [] : (options.dirs ?? COMPONENT_DIRS);
48
+ const own = componentIndex(findClarusFiles(resolve(root, 'src'), ['.tscl']).map((f) => posix(relative(root, f))), dirs).names;
49
+ const libraries = options.auto === false ? {} : libraryNames(resolveLibraries(root, options.libraries ?? []));
50
+ const file = resolve(root, '.clarusjs/components.json');
51
+ const text = `${JSON.stringify({ dirs, names: libraries }, null, 2)}\n`;
52
+ if (!existsSync(file) || readFileSync(file, 'utf8') !== text) {
53
+ mkdirSync(dirname(file), { recursive: true });
54
+ const temp = `${file}.${process.pid}.tmp`;
55
+ writeFileSync(temp, text);
56
+ renameSync(temp, file);
57
+ }
58
+ return options.auto === false ? undefined : withLibraries(own, libraries);
59
+ }
60
+ export function readComponents(root) {
61
+ let written;
62
+ try {
63
+ written = JSON.parse(readFileSync(resolve(root, '.clarusjs/components.json'), 'utf8'));
64
+ }
65
+ catch {
66
+ return undefined;
67
+ }
68
+ if (!written?.names || typeof written.names !== 'object')
69
+ return undefined;
70
+ const path = (v) => typeof v === 'string' || (Array.isArray(v) && v.length > 0 && v.every((p) => typeof p === 'string'));
71
+ const names = Object.fromEntries(Object.entries(written.names).filter(([, v]) => path(v)));
72
+ const dirs = Array.isArray(written.dirs) && written.dirs.every((d) => typeof d === 'string') ? written.dirs : undefined;
73
+ return dirs ? { dirs, names } : { names };
74
+ }
75
+ export function readComponentNames(root) {
76
+ return readComponents(root)?.names;
77
+ }
@@ -1,4 +1,5 @@
1
1
  import { type Plugin } from 'vite';
2
+ import { type LibraryOption } from './libraries.ts';
2
3
  import type { LintConfig, LintRuleDef } from '../compiler/lint.ts';
3
4
  export { packageOf } from './build.ts';
4
5
  /** Newest commit time (unix seconds) of every file under a folder, from one `git log` (themes use it for "last updated"). */
@@ -31,11 +32,14 @@ export type ClarusOptions = {
31
32
  /**
32
33
  * Automatic component imports (#458): a kebab-case file under these folders is used by its name, without @import
33
34
  * (`src/components/forms/text-field.tscl` → `<forms-text-field>`, or `<text-field>` when no other has that name).
34
- * Defaults: `{ dirs: ['src/components', 'src/layouts'], auto: true }`.
35
+ * Defaults: `{ dirs: ['src/components', 'src/layouts'], auto: true }`. `libraries`: installed component libraries whose
36
+ * components are used the same way (`libraries: ['@clarusjs/ui-primitives']` → `<ui-dialog>`), each described by its
37
+ * package.json; your own components win over theirs.
35
38
  */
36
39
  components?: {
37
40
  dirs?: string[];
38
41
  auto?: boolean;
42
+ libraries?: LibraryOption[];
39
43
  };
40
44
  /** Where server routes deploy. 'netlify': a Netlify Function (Frameworks API) next to the static files. */
41
45
  adapter?: 'netlify';