clarusjs 0.14.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.
Files changed (54) hide show
  1. package/dist/check/generate.d.ts +2 -5
  2. package/dist/check/generate.js +119 -5
  3. package/dist/cli/check.d.ts +10 -2
  4. package/dist/cli/check.js +38 -12
  5. package/dist/cli/index.js +4 -1
  6. package/dist/cli/mapper.js +24 -1
  7. package/dist/cli/project.d.ts +6 -0
  8. package/dist/cli/project.js +1 -1
  9. package/dist/compiler/class-style.js +2 -2
  10. package/dist/compiler/components.d.ts +61 -0
  11. package/dist/compiler/components.js +81 -0
  12. package/dist/compiler/element-attrs.d.ts +7 -0
  13. package/dist/compiler/element-attrs.js +32 -0
  14. package/dist/compiler/emit-client.js +23 -3
  15. package/dist/compiler/emit-server.js +11 -8
  16. package/dist/compiler/html-expr.d.ts +2 -1
  17. package/dist/compiler/html-expr.js +15 -9
  18. package/dist/compiler/index.d.ts +14 -2
  19. package/dist/compiler/index.js +143 -3
  20. package/dist/compiler/ir.d.ts +24 -0
  21. package/dist/compiler/ir.js +81 -11
  22. package/dist/compiler/lint.d.ts +26 -2
  23. package/dist/compiler/lint.js +64 -4
  24. package/dist/compiler/parse.d.ts +37 -0
  25. package/dist/compiler/parse.js +42 -10
  26. package/dist/compiler/script.d.ts +11 -0
  27. package/dist/compiler/script.js +41 -0
  28. package/dist/compiler/shared.d.ts +6 -0
  29. package/dist/compiler/shared.js +14 -0
  30. package/dist/forms/index.js +15 -3
  31. package/dist/runtime/attrs.d.ts +6 -0
  32. package/dist/runtime/attrs.js +22 -3
  33. package/dist/runtime/dom.d.ts +39 -1
  34. package/dist/runtime/dom.js +159 -23
  35. package/dist/runtime/html.d.ts +6 -0
  36. package/dist/runtime/html.js +12 -0
  37. package/dist/runtime/index.d.ts +1 -1
  38. package/dist/runtime/index.js +1 -1
  39. package/dist/runtime/loader.js +53 -7
  40. package/dist/runtime/router.d.ts +6 -1
  41. package/dist/runtime/router.js +1 -1
  42. package/dist/runtime/server.d.ts +8 -2
  43. package/dist/runtime/server.js +14 -7
  44. package/dist/server/handler.d.ts +28 -1
  45. package/dist/server/handler.js +44 -1
  46. package/dist/server/modes.d.ts +2 -0
  47. package/dist/server/modes.js +5 -1
  48. package/dist/vite/build.d.ts +9 -2
  49. package/dist/vite/build.js +20 -5
  50. package/dist/vite/libraries.d.ts +32 -0
  51. package/dist/vite/libraries.js +77 -0
  52. package/dist/vite/plugin.d.ts +23 -0
  53. package/dist/vite/plugin.js +52 -24
  54. package/package.json +1 -1
@@ -1,17 +1,14 @@
1
+ import { type ComponentNames } from '../compiler/components.ts';
1
2
  /**
2
3
  * [virtual offset, length, source offset, exact, source length]. Exact spans are verbatim copies (offsets map one to
3
4
  * one); other spans stand for a whole template construct (a component's tag, a binding's name): the source length
4
5
  * says how much of the template that is.
5
6
  */
6
7
  export type Mapping = [number, number, number, boolean, number?];
7
- /**
8
- * `loader`: the module specifier of the page's .load.ts when it exports load(); what it returns is checked against
9
- * the page's inputs. `componentSuffix`: added to component imports ('.ts' for `clarusjs check`'s generated files; ''
10
- * for the content mapper, where TypeScript resolves the .tscl file itself). `loaderSpan` is where that check sits in the generated code, so its errors can say so.
11
- */
12
8
  export declare function generateTs(source: string, file: string, options?: {
13
9
  loader?: string;
14
10
  componentSuffix?: string;
11
+ components?: ComponentNames;
15
12
  }): {
16
13
  code: string;
17
14
  mappings: Mapping[];
@@ -1,11 +1,40 @@
1
+ import { fragmentRoot } from '../compiler/parse.js';
2
+ import { ELEMENT_ATTRS, extendedAttrs } from '../compiler/element-attrs.js';
3
+ import { autoImport } from '../compiler/components.js';
4
+ import { parseExpressionAt } from 'acorn';
1
5
  import { routeFromFile } from '../server/handler.js';
2
6
  import { ClarusError } from '../compiler/errors.js';
3
7
  import { FOR_IMPLICIT, parse } from '../compiler/parse.js';
4
- import { referencesNames, splitImports, untypedParams } from '../compiler/script.js';
8
+ import { providesIn, referencesNames, splitImports, untypedParams } from '../compiler/script.js';
5
9
  const ENUMERATED = new Set(['draggable', 'spellcheck', 'translate', 'autocorrect', 'contenteditable']);
6
10
  const PROPERTY = { readonly: 'readOnly', novalidate: 'noValidate', formnovalidate: 'formNoValidate', allowfullscreen: 'allowFullscreen', playsinline: 'playsInline', nomodule: 'noModule', ismap: 'isMap' };
11
+ function patternNames(params) {
12
+ const names = [];
13
+ const walk = (p) => {
14
+ if (!p)
15
+ return;
16
+ if (p.type === 'Identifier')
17
+ names.push(p.name);
18
+ else if (p.type === 'ObjectPattern')
19
+ for (const prop of p.properties)
20
+ walk(prop.type === 'RestElement' ? prop.argument : prop.value);
21
+ else if (p.type === 'ArrayPattern')
22
+ p.elements.forEach(walk);
23
+ else if (p.type === 'AssignmentPattern')
24
+ walk(p.left);
25
+ else if (p.type === 'RestElement')
26
+ walk(p.argument);
27
+ };
28
+ try {
29
+ walk(parseExpressionAt(`(${params}) => 0`, 0, { ecmaVersion: 'latest' }).params[0]);
30
+ }
31
+ catch { }
32
+ return names;
33
+ }
7
34
  export function generateTs(source, file, options = {}) {
8
35
  const parsed = parse(source, file);
36
+ if (options.components)
37
+ autoImport(parsed, options.components, file, source);
9
38
  const mappings = [];
10
39
  let code = '';
11
40
  const emit = (text) => { code += text; };
@@ -33,7 +62,7 @@ export function generateTs(source, file, options = {}) {
33
62
  emit(` from ${JSON.stringify(t.from)}\n`);
34
63
  }
35
64
  for (const imp of parsed.imports)
36
- emit(`import type { Inputs as ${alias(imp.name)}, Models as ${alias(imp.name)}_M } from ${JSON.stringify(`${imp.from}${options.componentSuffix ?? '.ts'}`)}\n`);
65
+ emit(`import type { Inputs as ${alias(imp.name)}, Models as ${alias(imp.name)}_M, Events as ${alias(imp.name)}_E, Attrs as ${alias(imp.name)}_A, DomEvents as ${alias(imp.name)}_D } from ${JSON.stringify(`${imp.from}${options.componentSuffix ?? '.ts'}`)}\n`);
37
66
  for (const d of parsed.dataImports) {
38
67
  emit('import ');
39
68
  copy(d.clause, d.clauseStart);
@@ -42,6 +71,7 @@ export function generateTs(source, file, options = {}) {
42
71
  if (options.loader)
43
72
  emit(`import { load as __cl_load } from ${JSON.stringify(options.loader)}\n`);
44
73
  const script = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : null;
74
+ const provides = !!parsed.script && !!script && providesIn(script, file, source, parsed.script.start);
45
75
  if (parsed.script && script) {
46
76
  for (const imp of script.imports) {
47
77
  copy(imp.text, parsed.script.start + imp.start);
@@ -73,6 +103,25 @@ export function generateTs(source, file, options = {}) {
73
103
  emit('}\n');
74
104
  const models = parsed.inputs.filter((i) => i.model).map((i) => JSON.stringify(i.name));
75
105
  emit(`export type Models = ${models.length ? models.join(' | ') : 'never'}\n`);
106
+ const fragment = fragmentRoot(parsed.nodes);
107
+ const ext = parsed.extends && ELEMENT_ATTRS[parsed.extends.tag] ? extendedAttrs(parsed.extends.tag) : null;
108
+ const own = ext ? ` & Omit<{ ${Object.entries(ext).map(([k, t]) => `${JSON.stringify(k)}?: ${t}`).join('; ')} }, keyof Inputs>` : '';
109
+ emit(`export type Attrs = ${fragment ? '{ __cl_fragment_root_takes_no_attributes?: never }' : `__cl_Passed${own}`}\n`);
110
+ emit(`export type DomEvents = ${fragment ? 'never' : '__cl_Bubbling'}\n`);
111
+ emit('export interface Events {\n');
112
+ for (const e of parsed.events) {
113
+ emit(` ${JSON.stringify(e.name)}: `);
114
+ if (e.type === 'void')
115
+ emit('void');
116
+ else
117
+ copy(e.type, e.typeStart);
118
+ emit('\n');
119
+ }
120
+ emit('}\n');
121
+ if (provides)
122
+ emit('declare function provide(key: string, value: unknown): void\n');
123
+ if (parsed.events.length)
124
+ emit('declare const emit: <K extends keyof Events>(name: K, ...args: Events[K] extends void ? [value?: undefined, info?: { reason?: string; event?: Event }] : [value: Events[K], info?: { reason?: string; event?: Event }]) => boolean\n');
76
125
  let loaderSpan;
77
126
  if (options.loader) {
78
127
  emit('declare const __cl_loaded: Exclude<Awaited<ReturnType<typeof __cl_load>>, Response>\n');
@@ -83,6 +132,10 @@ export function generateTs(source, file, options = {}) {
83
132
  emit('\n');
84
133
  }
85
134
  emit('export type __cl_Readonly<T> = T extends (...args: any[]) => unknown ? T : T extends object ? { readonly [K in keyof T]: __cl_Readonly<T[K]> } : T\n');
135
+ emit("export type __cl_Bubbling = Exclude<keyof HTMLElementEventMap, 'focus' | 'blur' | 'mouseenter' | 'mouseleave' | 'pointerenter' | 'pointerleave' | 'load' | 'error' | 'scroll' | 'scrollend' | 'toggle' | 'beforetoggle' | 'loadstart' | 'loadeddata' | 'loadedmetadata' | 'play' | 'pause' | 'ended'>\n");
136
+ emit('export type __cl_Ev<T, K> = K extends keyof T ? T[K] : K extends keyof HTMLElementEventMap ? HTMLElementEventMap[K] : any\n');
137
+ emit('export type __cl_Use<E> = ((el: E) => unknown) | readonly ((el: E) => unknown)[]\n');
138
+ emit('export type __cl_Passed = { class?: unknown; id?: string; role?: string; tabindex?: string | number; hidden?: boolean; lang?: string; dir?: string; style?: string; [k: `data-${string}`]: unknown; [k: `aria-${string}`]: unknown }\n');
86
139
  const awaits = !!parsed.serverScript && /\bawait\b/.test(parsed.serverScript.code);
87
140
  emit(`\nexport default ${awaits ? 'async ' : ''}function __cl_check(__cl_props: __cl_Readonly<Inputs>) {\n`);
88
141
  for (const [keyword, list] of [['const', parsed.inputs.filter((x) => !x.model)], ['let', parsed.inputs.filter((x) => x.model)]]) {
@@ -101,6 +154,20 @@ export function generateTs(source, file, options = {}) {
101
154
  emit(' } = __cl_props\n');
102
155
  emit(` __cl_use([${list.map((x) => x.name).join(', ')}])\n`);
103
156
  }
157
+ for (const c of parsed.contexts) {
158
+ emit(' const ');
159
+ copy(c.name, c.nameStart);
160
+ emit(': ');
161
+ copy(c.type, c.typeStart);
162
+ emit(' = ');
163
+ if (c.default !== undefined && c.defaultStart !== undefined)
164
+ copy(c.default, c.defaultStart);
165
+ else
166
+ emit('null!');
167
+ emit('\n');
168
+ }
169
+ if (parsed.contexts.length)
170
+ emit(` __cl_use([${parsed.contexts.map((c) => c.name).join(', ')}])\n`);
104
171
  const copyScript = (from, split) => {
105
172
  const body = split.body;
106
173
  const cuts = [
@@ -153,7 +220,13 @@ export function generateTs(source, file, options = {}) {
153
220
  case 'expr':
154
221
  return use(node.expr, node.start + 2);
155
222
  case 'fill':
156
- node.children.forEach(visit);
223
+ if (node.params !== undefined) {
224
+ emit(` { const [${node.params}]: any = []; __cl_use([${patternNames(node.params).join(', ')}])\n`);
225
+ node.children.forEach(visit);
226
+ emit(' }\n');
227
+ }
228
+ else
229
+ node.children.forEach(visit);
157
230
  return;
158
231
  case 'if':
159
232
  node.branches.forEach((b, i) => {
@@ -218,7 +291,7 @@ export function generateTs(source, file, options = {}) {
218
291
  if (component) {
219
292
  emit(' { const ');
220
293
  point('__cl_p', node.start, node.tag.length + 1);
221
- emit(`: __cl_Readonly<${alias(node.tag)}> = { `);
294
+ emit(`: __cl_Readonly<${alias(node.tag)} & ${alias(node.tag)}_A> = { `);
222
295
  for (const a of node.attrs) {
223
296
  if (a.kind !== 'prop' || a.name !== '...')
224
297
  continue;
@@ -227,9 +300,29 @@ export function generateTs(source, file, options = {}) {
227
300
  emit('), ');
228
301
  }
229
302
  for (const a of node.attrs) {
303
+ if (a.name === 'class' && (a.kind === 'static' || a.kind === 'interp')) {
304
+ copy(a.name, a.start);
305
+ emit(': undefined, ');
306
+ continue;
307
+ }
308
+ if (a.kind === 'static' && a.name !== 'attach') {
309
+ const quoted = !/^[A-Za-z_$][\w$]*$/.test(a.name);
310
+ if (quoted)
311
+ emit('"');
312
+ copy(a.name, a.start);
313
+ if (quoted)
314
+ emit('"');
315
+ emit(`: ${a.value === true ? 'true' : JSON.stringify(a.value)}, `);
316
+ continue;
317
+ }
230
318
  if ((a.kind !== 'prop' && a.kind !== 'model') || a.name === '...')
231
319
  continue;
320
+ const quoted = !/^[A-Za-z_$][\w$]*$/.test(a.name);
321
+ if (quoted)
322
+ emit('"');
232
323
  copy(a.name, a.start + (a.kind === 'model' ? 2 : 1));
324
+ if (quoted)
325
+ emit('"');
233
326
  emit(': (');
234
327
  copy(a.expr, at(a.expr, attrValueStart(a)));
235
328
  emit('), ');
@@ -246,6 +339,19 @@ export function generateTs(source, file, options = {}) {
246
339
  copy(a.expr, at(a.expr, attrValueStart(a)));
247
340
  emit(` = (undefined as unknown as Exclude<${alias(node.tag)}[${JSON.stringify(a.name)}], undefined>) });\n`);
248
341
  }
342
+ for (const a of node.attrs) {
343
+ if (a.kind !== 'event')
344
+ continue;
345
+ const name = JSON.stringify(a.name);
346
+ emit(' { const ');
347
+ point('__cl_ev', a.start, a.name.length + 2);
348
+ emit(`: keyof ${alias(node.tag)}_E | ${alias(node.tag)}_D = ${name}; __cl_use(__cl_ev) }\n`);
349
+ emit(` ;(($event: __cl_Ev<${alias(node.tag)}_E, ${name}>, $info: { reason?: string; event?: Event; cancel(): void }) => { `);
350
+ guarded();
351
+ emit('{ ');
352
+ copy(a.expr, at(a.expr, attrValueStart(a)));
353
+ emit(' } __cl_use($info) });\n');
354
+ }
249
355
  node.children.forEach(visit);
250
356
  return;
251
357
  }
@@ -257,6 +363,14 @@ export function generateTs(source, file, options = {}) {
257
363
  const radio = node.tag === 'input' && a.name === 'value' && type?.kind === 'static' && String(type.value).toLowerCase() === 'radio' && own?.kind === 'static';
258
364
  writable(a, radio ? JSON.stringify(own.value === true ? '' : own.value) : undefined);
259
365
  }
366
+ else if (a.kind === 'prop' && node.tag === 'slot') {
367
+ use(a.expr, attrValueStart(a));
368
+ }
369
+ else if (a.kind === 'prop' && a.name === 'use') {
370
+ emit(` ;((__cl_u: __cl_Use<__cl_El<${JSON.stringify(node.tag.toLowerCase())}>>) => __cl_use(__cl_u))((`);
371
+ copy(a.expr, at(a.expr, attrValueStart(a)));
372
+ emit('));\n');
373
+ }
260
374
  else if (a.kind === 'prop' && a.name === 'engine') {
261
375
  emit(` ;((__cl_f: import('clarusjs/forms').Form<any>) => __cl_use(__cl_f))((`);
262
376
  copy(a.expr, at(a.expr, attrValueStart(a)));
@@ -347,7 +461,7 @@ export function viewsDeclaration(views) {
347
461
  return lines.join('\n');
348
462
  }
349
463
  export function routesDeclaration(files) {
350
- const pages = files.filter((f) => f.startsWith('src/pages/') && !/\.(m?[jt]s|css|json)$/.test(f) && !/(^|\/)_[^/]*$/.test(f));
464
+ const pages = files.filter((f) => f.startsWith('src/pages/') && !/\.(m?[jt]s|css|json)$/.test(f) && !/(^|\/)[_+][^/]*$/.test(f));
351
465
  const routes = [...new Set(pages.map((f) => routeFromFile(`/${f}`)))].sort();
352
466
  const entries = routes.map((route) => {
353
467
  const keys = [...route.matchAll(/\[([^\]]+)\]/g)].map((m) => m[1]);
@@ -1,3 +1,4 @@
1
+ import { type LibraryOption } from '../vite/libraries.ts';
1
2
  import { type LintConfig, type LintRuleDef } from '../compiler/lint.ts';
2
3
  /** A type error, a template error, or a lint finding (#304: `code` is the rule, usually a warning). */
3
4
  export type Diagnostic = {
@@ -12,7 +13,8 @@ export type CheckResult = {
12
13
  diagnostics: Diagnostic[];
13
14
  exitCode: 0 | 1;
14
15
  text: string;
15
- json: string;
16
+ json: string; /** With fix: the files it rewrote. */
17
+ fixed?: string[];
16
18
  };
17
19
  /** A page's .load.ts that exports load(), as an import specifier: what it returns is checked against the inputs. */
18
20
  export declare function loaderOf(path: string): string | undefined;
@@ -25,7 +27,7 @@ export type CheckSource = {
25
27
  addDependency(file: string): void;
26
28
  }): string;
27
29
  };
28
- /** `lint`: the plugin's rule levels; `lintRules`: the project's own rules; `strict`: warnings fail too. */
30
+ /** `lint`: the plugin's rule levels; `lintRules`: the project's own rules; `strict`: warnings fail too; `fix`: lint fixes are written to the .tscl files first. */
29
31
  export declare function check(options: {
30
32
  root: string;
31
33
  typescript?: string;
@@ -34,4 +36,10 @@ export declare function check(options: {
34
36
  lint?: LintConfig;
35
37
  lintRules?: LintRuleDef[];
36
38
  strict?: boolean;
39
+ fix?: boolean;
40
+ components?: {
41
+ dirs?: string[];
42
+ auto?: boolean;
43
+ libraries?: LibraryOption[];
44
+ };
37
45
  }): CheckResult;
package/dist/cli/check.js CHANGED
@@ -1,9 +1,10 @@
1
+ import { componentNames } from '../vite/libraries.js';
1
2
  import { spawnSync } from 'node:child_process';
2
3
  import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
3
4
  import { createRequire } from 'node:module';
4
5
  import { basename, dirname, relative, resolve, sep } from 'node:path';
5
6
  import { ClarusError } from '../compiler/errors.js';
6
- import { lint } from '../compiler/lint.js';
7
+ import { applyFixes, lint } from '../compiler/lint.js';
7
8
  import { checkIcons } from '../compiler/icon.js';
8
9
  import { parse } from '../compiler/parse.js';
9
10
  import { resolveIcon } from '../icons.js';
@@ -50,6 +51,7 @@ function typescriptDir(root, override) {
50
51
  }
51
52
  export function check(options) {
52
53
  const root = resolve(options.root);
54
+ const names = componentNames(root, options.components);
53
55
  const virtualRoot = resolve(root, VIRTUAL);
54
56
  rmSync(virtualRoot, { recursive: true, force: true });
55
57
  const diagnostics = [];
@@ -59,11 +61,29 @@ export function check(options) {
59
61
  const pageFiles = findClarusFiles(resolve(root, 'src'), ['.tscl', ...sources.map((x) => x.extension)])
60
62
  .filter((f) => f.endsWith('.tscl') || f.startsWith(resolve(root, 'src/pages') + sep));
61
63
  const views = [];
64
+ const fixed = [];
62
65
  for (const path of pageFiles) {
63
66
  const file = posix(relative(root, path));
64
67
  const original = readFileSync(path, 'utf8');
65
68
  const src = sources.find((x) => path.endsWith(x.extension));
66
69
  let source = original;
70
+ if (options.fix && path.endsWith('.tscl')) {
71
+ let next = original;
72
+ try {
73
+ next = applyFixes(original, lint(original, file, options.lint, options.lintRules));
74
+ }
75
+ catch { }
76
+ if (next !== original) {
77
+ try {
78
+ writeFileSync(path, next);
79
+ fixed.push(file);
80
+ source = next;
81
+ }
82
+ catch (err) {
83
+ diagnostics.push({ file, line: 1, column: 1, severity: 'error', code: 'fix', message: `--fix could not write ${file}: ${err.message}` });
84
+ }
85
+ }
86
+ }
67
87
  try {
68
88
  if (src)
69
89
  source = src.toTscl(original, path, { route: routeFromFile(`/${file}`), root, addDependency: () => { } });
@@ -88,7 +108,7 @@ export function check(options) {
88
108
  };
89
109
  try {
90
110
  const loader = loaderOf(path);
91
- const { code, mappings, loaderSpan } = generateTs(source, file, loader ? { loader } : {});
111
+ const { code, mappings, loaderSpan } = generateTs(source, file, { ...(loader ? { loader } : {}), components: names });
92
112
  const vpath = resolve(virtualRoot, `${file}.ts`);
93
113
  mkdirSync(dirname(vpath), { recursive: true });
94
114
  writeFileSync(vpath, code);
@@ -110,7 +130,7 @@ export function check(options) {
110
130
  const virtualOf = new Map();
111
131
  const converted = new Map(views.map((v) => [realpathSync(resolve(root, v.file)), v.source]));
112
132
  const textOf = (p) => converted.get(realpathSync(p)) ?? readFileSync(p, 'utf8');
113
- const components = reachableComponents(root, pageFiles, textOf, ['.tscl'], aliases);
133
+ const components = reachableComponents(root, pageFiles, textOf, ['.tscl'], aliases, names);
114
134
  for (const path of components.filter((p) => !p.startsWith(resolve(appRoot, 'src') + sep))) {
115
135
  const pkg = packageInfo(path);
116
136
  const vpath = resolve(virtualRoot, '_pkg', pkg.name, `${relative(pkg.dir, path)}.ts`);
@@ -128,17 +148,22 @@ export function check(options) {
128
148
  }
129
149
  }
130
150
  const require = createRequire(resolve(root, 'package.json'));
131
- for (const path of components) {
132
- for (const m of textOf(path).matchAll(/^@import\s+[A-Za-z_$][\w-]*\s+from\s+(['"])([^'"./][^'"]*\.tscl)\1/gm)) {
133
- try {
134
- const file = realpathSync(resolveAlias(m[2], aliases) ?? require.resolve(m[2]));
135
- const target = virtualOf.get(file) ?? (file.startsWith(appRoot + sep) ? resolve(virtualRoot, `${relative(appRoot, file)}.ts`) : undefined);
136
- if (target)
137
- paths[`${m[2]}.ts`] = [`./${posix(relative(resolve(root, '.clarusjs'), target))}`];
138
- }
139
- catch { }
151
+ const mapSpecifier = (spec) => {
152
+ try {
153
+ const file = realpathSync(resolveAlias(spec, aliases) ?? require.resolve(spec));
154
+ const target = virtualOf.get(file) ?? (file.startsWith(appRoot + sep) ? resolve(virtualRoot, `${relative(appRoot, file)}.ts`) : undefined);
155
+ if (target)
156
+ paths[`${spec}.ts`] = [`./${posix(relative(resolve(root, '.clarusjs'), target))}`];
140
157
  }
158
+ catch { }
159
+ };
160
+ for (const path of components) {
161
+ for (const m of textOf(path).matchAll(/^@import\s+[A-Za-z_$][\w-]*\s+from\s+(['"])([^'"./][^'"]*\.tscl)\1/gm))
162
+ mapSpecifier(m[2]);
141
163
  }
164
+ for (const spec of Object.values(names ?? {}).flat())
165
+ if (!spec.startsWith('/') && spec.endsWith('.tscl'))
166
+ mapSpecifier(spec);
142
167
  const fromCheck = (path) => { const rel = posix(relative(resolve(root, '.clarusjs'), path)); return rel.startsWith('.') ? rel : `./${rel}`; };
143
168
  paths['/*'] = ['../*', './virtual/*'];
144
169
  for (const alias of aliases) {
@@ -206,5 +231,6 @@ export function check(options) {
206
231
  exitCode: diagnostics.some((d) => d.severity === 'error' || options.strict) ? 1 : 0,
207
232
  text: diagnostics.map((d) => `${d.file}:${d.line}:${d.column} ${d.severity} ${d.code}: ${d.message}`).join('\n'),
208
233
  json: JSON.stringify(diagnostics, null, 2),
234
+ ...(options.fix ? { fixed } : {}),
209
235
  };
210
236
  }
package/dist/cli/index.js CHANGED
@@ -11,8 +11,11 @@ program
11
11
  .argument('[dir]', 'project folder', '.')
12
12
  .option('--json', 'print diagnostics as JSON')
13
13
  .option('--strict', 'fail on lint warnings too')
14
+ .option('--fix', 'apply lint fixes to the .tscl files (wrapping a component\'s several roots in <fragment>, …) before checking')
14
15
  .action(async (dir, options) => {
15
- const result = check({ root: dir, ...(await loadProject(dir)), strict: options.strict });
16
+ const result = check({ root: dir, ...(await loadProject(dir)), strict: options.strict, fix: options.fix });
17
+ for (const file of result.fixed ?? [])
18
+ (options.json ? console.error : console.log)(`fixed ${file}`);
16
19
  if (options.json)
17
20
  console.log(result.json);
18
21
  else if (result.diagnostics.length) {
@@ -1,9 +1,32 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { dirname, relative, resolve, sep } from 'node:path';
1
3
  import { generateTolerant } from '../check/generate.js';
4
+ import { COMPONENT_DIRS, componentIndex } from '../compiler/components.js';
5
+ import { readComponents } from '../vite/libraries.js';
6
+ import { findClarusFiles } from '../vite/build.js';
2
7
  import { loaderOf } from './check.js';
8
+ function namesFor(fileName) {
9
+ let root = dirname(fileName);
10
+ while (!existsSync(resolve(root, 'package.json'))) {
11
+ if (dirname(root) === root)
12
+ return undefined;
13
+ root = dirname(root);
14
+ }
15
+ const written = readComponents(root);
16
+ const files = findClarusFiles(resolve(root, 'src'), ['.tscl']).map((f) => relative(root, f).split(sep).join('/'));
17
+ const rel = (path) => { const r = relative(dirname(fileName), resolve(root, path.slice(1))).split(sep).join('/'); return r.startsWith('.') ? r : `./${r}`; };
18
+ const names = {};
19
+ for (const [name, path] of Object.entries(componentIndex(files, written?.dirs ?? COMPONENT_DIRS).names))
20
+ names[name] = Array.isArray(path) ? path.map(rel) : rel(path);
21
+ for (const [name, path] of Object.entries(written?.names ?? {}))
22
+ if (!(name in names) && ![path].flat().some((p) => p.startsWith('/')))
23
+ names[name] = path;
24
+ return names;
25
+ }
3
26
  export function transform(params) {
4
27
  const { fileName, content } = params;
5
28
  const loader = loaderOf(fileName);
6
- const { result, errors } = generateTolerant(content, fileName, { componentSuffix: '', ...(loader ? { loader } : {}) });
29
+ const { result, errors } = generateTolerant(content, fileName, { componentSuffix: '', components: namesFor(fileName), ...(loader ? { loader } : {}) });
7
30
  const diagnostics = errors.slice(0, 1).map((e) => ({ messageText: e.message, start: e.offset, length: Math.min(1, content.length - e.offset), code: 1 }));
8
31
  if (!result)
9
32
  return { text: 'export {}\n', extension: '.ts', mappings: [], diagnostics };
@@ -1,3 +1,4 @@
1
+ import type { LibraryOption } from '../vite/libraries.ts';
1
2
  import type { CheckSource } from './check.ts';
2
3
  import type { LintConfig, LintRuleDef } from '../compiler/lint.ts';
3
4
  type Project = {
@@ -5,6 +6,11 @@ type Project = {
5
6
  viteAliases: unknown;
6
7
  lint: LintConfig | undefined;
7
8
  lintRules: LintRuleDef[];
9
+ components?: {
10
+ dirs?: string[];
11
+ auto?: boolean;
12
+ libraries?: LibraryOption[];
13
+ };
8
14
  };
9
15
  export declare function loadProject(root: string): Promise<Project>;
10
16
  export {};
@@ -18,5 +18,5 @@ export async function loadProject(root) {
18
18
  if (!loaded)
19
19
  return none;
20
20
  const plugin = (await flatten(loaded.config.plugins)).find((p) => p.name === 'clarusjs');
21
- return { sources: plugin?.api?.sources ?? [], viteAliases: loaded.config.resolve?.alias, lint: plugin?.api?.lint, lintRules: plugin?.api?.lintRules ?? [] };
21
+ return { sources: plugin?.api?.sources ?? [], viteAliases: loaded.config.resolve?.alias, lint: plugin?.api?.lint, lintRules: plugin?.api?.lintRules ?? [], components: plugin?.api?.components };
22
22
  }
@@ -11,7 +11,7 @@ function part(a) {
11
11
  function foldStyle(node) {
12
12
  const props = node.attrs.filter((a) => a.kind === 'prop' && a.name.startsWith('style.'));
13
13
  const sources = node.attrs.filter((a) => isSource(a, 'style'));
14
- const spread = spreadOf(node);
14
+ const spread = spreadOf(node) === '__cl_attrs' ? undefined : spreadOf(node);
15
15
  if (!spread && !props.length && !(sources.length > 1 && sources.some((a) => a.kind === 'prop')))
16
16
  return;
17
17
  const exprs = [...(spread ? [`((${spread}) || {}).style`] : []), ...sources.map(part), ...props.map((p) => `{ ${JSON.stringify(p.name.slice(6))}: (${p.expr}) }`)];
@@ -27,7 +27,7 @@ export function foldClass(nodes, components) {
27
27
  const toggles = node.attrs.filter((a) => a.kind === 'prop' && a.name.startsWith('class.'));
28
28
  const sources = node.attrs.filter((a) => isSource(a, 'class'));
29
29
  const mixed = sources.length > 1 && sources.some((a) => a.kind === 'prop');
30
- const spread = spreadOf(node);
30
+ const spread = spreadOf(node) === '__cl_attrs' ? undefined : spreadOf(node);
31
31
  if (toggles.length || mixed || spread) {
32
32
  const exprs = [...(spread ? [`((${spread}) || {}).class`] : []), ...sources.map(part), ...toggles.map((t) => `{ ${JSON.stringify(t.name.slice(6))}: (${t.expr}) }`)];
33
33
  const start = (sources[0] ?? toggles[0] ?? node.attrs.find((a) => a.name === '...')).start;
@@ -0,0 +1,61 @@
1
+ import { type ParsedFile } from './parse.ts';
2
+ /**
3
+ * Tag name → the component's root path ('/src/components/forms/text-field.tscl'), or every candidate when ambiguous.
4
+ * @see https://clarusjs.com/guide/components#automatic-imports
5
+ */
6
+ export type ComponentNames = Record<string, string | string[]>;
7
+ /**
8
+ * Where automatic components live, by default (root-relative).
9
+ * @example
10
+ * componentIndex(files, COMPONENT_DIRS)
11
+ * @see https://clarusjs.com/guide/components#automatic-imports
12
+ */
13
+ export declare const COMPONENT_DIRS: string[];
14
+ /**
15
+ * Name every `.tscl` file under `dirs` (root-relative, posix): its full name is its folders and file joined with
16
+ * hyphens (`forms/text-field.tscl` → `forms-text-field`), its short name the file alone (`text-field`) when no other
17
+ * component has that name; a full name wins over a short one. Only names with a hyphen count, like custom elements,
18
+ * so a component never takes an HTML element's name. `skipped`: files that aren't kebab-case (never named).
19
+ * @example
20
+ * componentIndex(['src/components/forms/text-field.tscl'], ['src/components']).names
21
+ * // { 'forms-text-field': '/src/components/forms/text-field.tscl', 'text-field': '/src/components/forms/text-field.tscl' }
22
+ * @see https://clarusjs.com/guide/components#automatic-imports
23
+ */
24
+ export declare function componentIndex(files: string[], dirs: string[]): {
25
+ names: ComponentNames;
26
+ skipped: string[];
27
+ };
28
+ /**
29
+ * A component library an app uses, resolved: its package `name`, the `prefix` of its tags, and its `.tscl` files
30
+ * (posix, relative to the folder its package.json's `clarusjs.components` names).
31
+ * @since 0.16.0
32
+ * @see https://clarusjs.com/guide/components#components-from-libraries
33
+ */
34
+ export type Library = {
35
+ name: string;
36
+ prefix: string;
37
+ files: string[];
38
+ };
39
+ /**
40
+ * Name each library component: its prefix, folders and file joined with hyphens (`ui` + `dialog.tscl` → `ui-dialog`),
41
+ * imported as `<package>/<file>`. Only kebab-case names with a hyphen; a name two libraries share is ambiguous.
42
+ * @example
43
+ * libraryNames([{ name: '@clarusjs/ui-primitives', prefix: 'ui', files: ['dialog.tscl'] }])
44
+ * // { 'ui-dialog': '@clarusjs/ui-primitives/dialog.tscl' }
45
+ * @since 0.16.0
46
+ * @see https://clarusjs.com/guide/components#components-from-libraries
47
+ */
48
+ export declare function libraryNames(libraries: Library[]): ComponentNames;
49
+ /**
50
+ * The app's own component names with the libraries' added: a name the app's own components have stays theirs.
51
+ * @example
52
+ * withLibraries(componentIndex(files, COMPONENT_DIRS).names, libraryNames(libraries))
53
+ * @since 0.16.0
54
+ * @see https://clarusjs.com/guide/components#components-from-libraries
55
+ */
56
+ export declare function withLibraries(own: ComponentNames, libraries: ComponentNames): ComponentNames;
57
+ /**
58
+ * Add an import for each component tag the template uses that `names` knows and the file doesn't import itself (only
59
+ * those). A tag that names two components is a located error. Other hyphenated tags stay HTML (web components).
60
+ */
61
+ export declare function autoImport(parsed: ParsedFile, names: ComponentNames, file: string, source: string): void;
@@ -0,0 +1,81 @@
1
+ import { ClarusError } from './errors.js';
2
+ import { awaitLists } from './parse.js';
3
+ export const COMPONENT_DIRS = ['src/components', 'src/layouts'];
4
+ const KEBAB = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
5
+ export function componentIndex(files, dirs) {
6
+ const full = new Map();
7
+ const short = new Map();
8
+ const skipped = [];
9
+ const add = (map, name, path) => map.set(name, [...(map.get(name) ?? []), path]);
10
+ for (const file of [...files].sort()) {
11
+ const dir = dirs.find((d) => file.startsWith(`${d.replace(/\/+$/, '')}/`));
12
+ if (!dir || !file.endsWith('.tscl'))
13
+ continue;
14
+ const segments = file.slice(dir.replace(/\/+$/, '').length + 1, -'.tscl'.length).split('/');
15
+ if (!segments.every((s) => KEBAB.test(s))) {
16
+ skipped.push(file);
17
+ continue;
18
+ }
19
+ add(full, segments.join('-'), `/${file}`);
20
+ if (segments.length > 1)
21
+ add(short, segments.at(-1), `/${file}`);
22
+ }
23
+ const names = {};
24
+ for (const [name, paths] of short)
25
+ if (name.includes('-') && !full.has(name))
26
+ names[name] = paths.length === 1 ? paths[0] : paths;
27
+ for (const [name, paths] of full)
28
+ if (name.includes('-'))
29
+ names[name] = paths.length === 1 ? paths[0] : paths;
30
+ return { names, skipped };
31
+ }
32
+ export function libraryNames(libraries) {
33
+ const found = new Map();
34
+ for (const lib of libraries) {
35
+ for (const file of [...lib.files].sort()) {
36
+ if (!file.endsWith('.tscl'))
37
+ continue;
38
+ const segments = [...(lib.prefix ? [lib.prefix] : []), ...file.slice(0, -'.tscl'.length).split('/')];
39
+ const name = segments.join('-');
40
+ if (!segments.every((s) => KEBAB.test(s)) || !name.includes('-'))
41
+ continue;
42
+ found.set(name, [...(found.get(name) ?? []), `${lib.name}/${file}`]);
43
+ }
44
+ }
45
+ return Object.fromEntries([...found].map(([name, paths]) => [name, paths.length === 1 ? paths[0] : paths]));
46
+ }
47
+ export function withLibraries(own, libraries) {
48
+ return { ...libraries, ...own };
49
+ }
50
+ export function autoImport(parsed, names, file, source) {
51
+ const imported = new Set(parsed.imports.map((i) => i.name));
52
+ const walk = (nodes) => {
53
+ for (const node of nodes) {
54
+ if (node.type === 'element') {
55
+ const found = node.tag.includes('-') && !imported.has(node.tag) ? names[node.tag] : undefined;
56
+ if (Array.isArray(found)) {
57
+ throw new ClarusError(`<${node.tag}> could be ${found.join(' or ')}: use its full name, or @import the one you mean`, file, source, node.start);
58
+ }
59
+ if (found) {
60
+ parsed.imports.push({ name: node.tag, from: found, start: 0 });
61
+ imported.add(node.tag);
62
+ }
63
+ walk(node.children);
64
+ }
65
+ else if (node.type === 'if')
66
+ for (const b of node.branches)
67
+ walk(b.children);
68
+ else if (node.type === 'for') {
69
+ walk(node.children);
70
+ if (node.empty)
71
+ walk(node.empty);
72
+ }
73
+ else if (node.type === 'fill')
74
+ walk(node.children);
75
+ else if (node.type === 'await')
76
+ for (const kids of awaitLists(node))
77
+ walk(kids);
78
+ }
79
+ };
80
+ walk(parsed.nodes);
81
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Each supported element's own attributes (lowercase names) and their types.
3
+ * @internal The compiler and check read it.
4
+ */
5
+ export declare const ELEMENT_ATTRS: Record<string, Record<string, string>>;
6
+ /** The attributes `@extends tag` passes through: the element's and the global ones. */
7
+ export declare function extendedAttrs(tag: string): Record<string, string>;