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,9 +1,13 @@
1
+ import { fragmentRoot } from '../compiler/parse.js';
2
+ import { ELEMENT_ATTRS, extendedAttrs } from '../compiler/element-attrs.js';
1
3
  import { autoImport } from '../compiler/components.js';
2
4
  import { parseExpressionAt } from 'acorn';
3
5
  import { routeFromFile } from '../server/handler.js';
4
6
  import { ClarusError } from '../compiler/errors.js';
7
+ import { modifierError, splitEvent } from '../compiler/events.js';
8
+ import { outerIndexIn } from '../compiler/loops.js';
5
9
  import { FOR_IMPLICIT, parse } from '../compiler/parse.js';
6
- import { providesIn, referencesNames, splitImports, untypedParams } from '../compiler/script.js';
10
+ import { checkScript, providesIn, referencesNames, splitImports, untypedParams } from '../compiler/script.js';
7
11
  const ENUMERATED = new Set(['draggable', 'spellcheck', 'translate', 'autocorrect', 'contenteditable']);
8
12
  const PROPERTY = { readonly: 'readOnly', novalidate: 'noValidate', formnovalidate: 'formNoValidate', allowfullscreen: 'allowFullscreen', playsinline: 'playsInline', nomodule: 'noModule', ismap: 'isMap' };
9
13
  function patternNames(params) {
@@ -29,8 +33,26 @@ function patternNames(params) {
29
33
  catch { }
30
34
  return names;
31
35
  }
36
+ function defaultedKeys(params) {
37
+ try {
38
+ const p = parseExpressionAt(`(${params}) => 0`, 0, { ecmaVersion: 'latest' }).params[0];
39
+ if (p.type !== 'ObjectPattern')
40
+ return [];
41
+ return p.properties.flatMap((x) => x.type === 'Property' && !x.computed && x.value?.type === 'AssignmentPattern'
42
+ ? [String(x.key.type === 'Identifier' ? x.key.name : x.key.value)] : []);
43
+ }
44
+ catch {
45
+ return [];
46
+ }
47
+ }
32
48
  export function generateTs(source, file, options = {}) {
33
49
  const parsed = parse(source, file);
50
+ const outer = outerIndexIn(parsed.nodes);
51
+ if (outer)
52
+ throw new ClarusError(outer.message, file, source, outer.start);
53
+ for (const s of [parsed.script, parsed.serverScript])
54
+ if (s)
55
+ checkScript(s.code, file, source, s.start);
34
56
  if (options.components)
35
57
  autoImport(parsed, options.components, file, source);
36
58
  const mappings = [];
@@ -47,6 +69,17 @@ export function generateTs(source, file, options = {}) {
47
69
  emit('declare function shared<T>(store: { get(): T }): T\n');
48
70
  emit('declare function __cl_use(value: unknown): void\n');
49
71
  emit('declare const __cl_bool: boolean\n');
72
+ const transitions = (nodes) => nodes.some((n) => {
73
+ if (n.type === 'if')
74
+ return !!n.transition || n.branches.some((b) => transitions(b.children));
75
+ if (n.type === 'for')
76
+ return !!n.transition || transitions(n.children) || (!!n.empty && transitions(n.empty));
77
+ if (n.type === 'await')
78
+ return transitions(n.pending) || (!!n.then && transitions(n.then.children)) || (!!n.catch && transitions(n.catch.children));
79
+ return 'children' in n && Array.isArray(n.children) && transitions(n.children);
80
+ });
81
+ if (transitions(parsed.nodes))
82
+ emit("declare function __cl_transition(name: string, options?: import('clarusjs/motion').TransitionOptions): void\n");
50
83
  const text = 'string | number | boolean | null | undefined';
51
84
  emit(`export type __cl_Class = ${text} | readonly __cl_Class[] | { [name: string]: unknown }\n`);
52
85
  emit(`export type __cl_Style = ${text} | __cl_Style[] | { [property: string]: ${text} }\n`);
@@ -60,7 +93,7 @@ export function generateTs(source, file, options = {}) {
60
93
  emit(` from ${JSON.stringify(t.from)}\n`);
61
94
  }
62
95
  for (const imp of parsed.imports)
63
- emit(`import type { Inputs as ${alias(imp.name)}, Models as ${alias(imp.name)}_M, Events as ${alias(imp.name)}_E } from ${JSON.stringify(`${imp.from}${options.componentSuffix ?? '.ts'}`)}\n`);
96
+ 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, Slots as ${alias(imp.name)}_S } from ${JSON.stringify(`${imp.from}${options.componentSuffix ?? '.ts'}`)}\n`);
64
97
  for (const d of parsed.dataImports) {
65
98
  emit('import ');
66
99
  copy(d.clause, d.clauseStart);
@@ -101,6 +134,11 @@ export function generateTs(source, file, options = {}) {
101
134
  emit('}\n');
102
135
  const models = parsed.inputs.filter((i) => i.model).map((i) => JSON.stringify(i.name));
103
136
  emit(`export type Models = ${models.length ? models.join(' | ') : 'never'}\n`);
137
+ const fragment = fragmentRoot(parsed.nodes);
138
+ const ext = parsed.extends && ELEMENT_ATTRS[parsed.extends.tag] ? extendedAttrs(parsed.extends.tag) : null;
139
+ const own = ext ? ` & Omit<{ ${Object.entries(ext).map(([k, t]) => `${JSON.stringify(k)}?: ${t}`).join('; ')} }, keyof Inputs>` : '';
140
+ emit(`export type Attrs = ${fragment ? '{ __cl_fragment_root_takes_no_attributes?: never }' : `__cl_Passed${own}`}\n`);
141
+ emit(`export type DomEvents = ${fragment ? 'never' : '__cl_Bubbling'}\n`);
104
142
  emit('export interface Events {\n');
105
143
  for (const e of parsed.events) {
106
144
  emit(` ${JSON.stringify(e.name)}: `);
@@ -125,9 +163,11 @@ export function generateTs(source, file, options = {}) {
125
163
  emit('\n');
126
164
  }
127
165
  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');
128
- emit('export type __cl_Ev<T, K> = K extends keyof T ? T[K] : any\n');
166
+ 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");
167
+ emit('export type __cl_Ev<T, K> = K extends keyof T ? T[K] : K extends keyof HTMLElementEventMap ? HTMLElementEventMap[K] : any\n');
168
+ emit('export type __cl_SlotOf<S, K extends string> = K extends keyof S ? S[K] : any\n');
129
169
  emit('export type __cl_Use<E> = ((el: E) => unknown) | readonly ((el: E) => unknown)[]\n');
130
- emit('export type __cl_Passed = { id?: string; role?: string; tabindex?: string | number; hidden?: boolean; lang?: string; dir?: string; style?: string; [k: `data-${string}`]: unknown; [k: `aria-${string}`]: unknown }\n');
170
+ 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');
131
171
  const awaits = !!parsed.serverScript && /\bawait\b/.test(parsed.serverScript.code);
132
172
  emit(`\nexport default ${awaits ? 'async ' : ''}function __cl_check(__cl_props: __cl_Readonly<Inputs>) {\n`);
133
173
  for (const [keyword, list] of [['const', parsed.inputs.filter((x) => !x.model)], ['let', parsed.inputs.filter((x) => x.model)]]) {
@@ -204,6 +244,22 @@ export function generateTs(source, file, options = {}) {
204
244
  emit(value);
205
245
  emit(') });\n');
206
246
  };
247
+ let owner;
248
+ const slotVars = [];
249
+ const transitionCall = (tr) => {
250
+ if (!tr)
251
+ return;
252
+ emit(' __cl_transition(');
253
+ if (tr.name !== null)
254
+ copy(tr.name, tr.nameStart);
255
+ else
256
+ emit("'cl'");
257
+ if (tr.options !== null) {
258
+ emit(', ');
259
+ copy(tr.options, tr.optionsStart);
260
+ }
261
+ emit(')\n');
262
+ };
207
263
  function visit(node) {
208
264
  switch (node.type) {
209
265
  case 'text':
@@ -211,16 +267,26 @@ export function generateTs(source, file, options = {}) {
211
267
  return;
212
268
  case 'expr':
213
269
  return use(node.expr, node.start + 2);
214
- case 'fill':
270
+ case 'fill': {
271
+ const of = owner;
272
+ owner = undefined;
215
273
  if (node.params !== undefined) {
216
- emit(` { const [${node.params}]: any = []; __cl_use([${patternNames(node.params).join(', ')}])\n`);
274
+ const slot = of ? `__cl_SlotOf<${alias(of)}_S, ${JSON.stringify(node.name)}>` : 'any';
275
+ const own = defaultedKeys(node.params).map((k) => `${JSON.stringify(k)}?: any`);
276
+ const data = own.length && of ? `${slot} & Omit<{ ${own.join('; ')} }, keyof ${slot}>` : slot;
277
+ emit(' { const [');
278
+ copy(node.params, node.paramsStart);
279
+ emit(`]: [${data}, ...any[]] = null!; __cl_use([${patternNames(node.params).join(', ')}])\n`);
217
280
  node.children.forEach(visit);
218
281
  emit(' }\n');
219
282
  }
220
283
  else
221
284
  node.children.forEach(visit);
285
+ owner = of;
222
286
  return;
287
+ }
223
288
  case 'if':
289
+ transitionCall(node.transition);
224
290
  node.branches.forEach((b, i) => {
225
291
  if (b.cond === null)
226
292
  emit(' else {\n');
@@ -259,15 +325,18 @@ export function generateTs(source, file, options = {}) {
259
325
  return;
260
326
  }
261
327
  case 'for': {
328
+ transitionCall(node.transition);
262
329
  emit(' for (const ');
263
330
  copy(node.item, node.itemStart);
264
331
  emit(' of ');
265
332
  copy(node.list, node.listStart);
266
333
  emit(') {\n const $index: number = 0, $count: number = 0, $first = __cl_bool, $last = __cl_bool, $even = __cl_bool, $odd = __cl_bool; __cl_use([$index, $count, $first, $last, $even, $odd])\n');
334
+ for (const a of node.aliases)
335
+ emit(` const ${a.name} = ${a.of}; __cl_use(${a.name})\n`);
267
336
  if (node.track !== null)
268
337
  use(node.track, node.trackStart);
269
338
  const outer = guards.splice(0);
270
- guards.push(...outer.filter((g) => !referencesNames(g, new Set([node.item, ...FOR_IMPLICIT]))));
339
+ guards.push(...outer.filter((g) => !referencesNames(g, new Set([node.item, ...FOR_IMPLICIT, ...node.aliases.map((a) => a.name)]))));
271
340
  node.children.forEach(visit);
272
341
  guards.splice(0, guards.length, ...outer);
273
342
  emit(' }\n');
@@ -283,7 +352,7 @@ export function generateTs(source, file, options = {}) {
283
352
  if (component) {
284
353
  emit(' { const ');
285
354
  point('__cl_p', node.start, node.tag.length + 1);
286
- emit(`: __cl_Readonly<${alias(node.tag)} & __cl_Passed> = { `);
355
+ emit(`: __cl_Readonly<${alias(node.tag)} & ${alias(node.tag)}_A> = { `);
287
356
  for (const a of node.attrs) {
288
357
  if (a.kind !== 'prop' || a.name !== '...')
289
358
  continue;
@@ -292,7 +361,12 @@ export function generateTs(source, file, options = {}) {
292
361
  emit('), ');
293
362
  }
294
363
  for (const a of node.attrs) {
295
- if (a.kind === 'static' && a.name !== 'class' && a.name !== 'attach') {
364
+ if (a.name === 'class' && (a.kind === 'static' || a.kind === 'interp')) {
365
+ copy(a.name, a.start);
366
+ emit(': undefined, ');
367
+ continue;
368
+ }
369
+ if (a.kind === 'static' && a.name !== 'attach') {
296
370
  const quoted = !/^[A-Za-z_$][\w$]*$/.test(a.name);
297
371
  if (quoted)
298
372
  emit('"');
@@ -332,16 +406,34 @@ export function generateTs(source, file, options = {}) {
332
406
  const name = JSON.stringify(a.name);
333
407
  emit(' { const ');
334
408
  point('__cl_ev', a.start, a.name.length + 2);
335
- emit(`: keyof ${alias(node.tag)}_E = ${name}; __cl_use(__cl_ev) }\n`);
409
+ emit(`: keyof ${alias(node.tag)}_E | ${alias(node.tag)}_D = ${name}; __cl_use(__cl_ev) }\n`);
336
410
  emit(` ;(($event: __cl_Ev<${alias(node.tag)}_E, ${name}>, $info: { reason?: string; event?: Event; cancel(): void }) => { `);
337
411
  guarded();
338
412
  emit('{ ');
339
413
  copy(a.expr, at(a.expr, attrValueStart(a)));
340
414
  emit(' } __cl_use($info) });\n');
341
415
  }
416
+ const outer = owner;
417
+ owner = node.tag;
342
418
  node.children.forEach(visit);
419
+ owner = outer;
343
420
  return;
344
421
  }
422
+ if (node.tag === 'slot') {
423
+ const name = node.attrs.find((a) => a.kind === 'static' && a.name === 'name');
424
+ const key = name?.kind === 'static' && typeof name.value === 'string' ? name.value : 'default';
425
+ const v = `__cl_slot_${slotVars.length}`;
426
+ slotVars.push([key, v]);
427
+ emit(` var ${v} = { `);
428
+ for (const a of node.attrs) {
429
+ if (a.kind !== 'prop')
430
+ continue;
431
+ emit(`${JSON.stringify(a.name)}: (`);
432
+ copy(a.expr, at(a.expr, attrValueStart(a)));
433
+ emit('), ');
434
+ }
435
+ emit('};\n');
436
+ }
345
437
  for (const a of node.attrs) {
346
438
  if (a.kind === 'model') {
347
439
  use(a.expr, attrValueStart(a));
@@ -351,7 +443,7 @@ export function generateTs(source, file, options = {}) {
351
443
  writable(a, radio ? JSON.stringify(own.value === true ? '' : own.value) : undefined);
352
444
  }
353
445
  else if (a.kind === 'prop' && node.tag === 'slot') {
354
- use(a.expr, attrValueStart(a));
446
+ continue;
355
447
  }
356
448
  else if (a.kind === 'prop' && a.name === 'use') {
357
449
  emit(` ;((__cl_u: __cl_Use<__cl_El<${JSON.stringify(node.tag.toLowerCase())}>>) => __cl_use(__cl_u))((`);
@@ -374,7 +466,11 @@ export function generateTs(source, file, options = {}) {
374
466
  use(p.expr, p.start + 2);
375
467
  }
376
468
  else if (a.kind === 'event') {
377
- emit(` ;(($event: __cl_Event<${JSON.stringify(a.name)}, __cl_El<${JSON.stringify(node.tag.toLowerCase())}>>) => { `);
469
+ const { type, mods } = splitEvent(a.name);
470
+ const wrong = modifierError(type, mods);
471
+ if (wrong)
472
+ throw new ClarusError(wrong, file, source, a.start);
473
+ emit(` ;(($event: __cl_Event<${JSON.stringify(type)}, __cl_El<${JSON.stringify(node.tag.toLowerCase())}>>, $values: Record<string, any>) => { `);
378
474
  guarded();
379
475
  emit('{ ');
380
476
  copy(a.expr, at(a.expr, attrValueStart(a)));
@@ -387,7 +483,12 @@ export function generateTs(source, file, options = {}) {
387
483
  }
388
484
  }
389
485
  parsed.nodes.forEach(visit);
486
+ const byName = new Map();
487
+ for (const [key, v] of slotVars)
488
+ byName.set(key, [...(byName.get(key) ?? []), `typeof ${v}`]);
489
+ emit(` return { __cl_slots: null! as { ${[...byName].map(([k, t]) => `${JSON.stringify(k)}: ${t.join(' | ')}`).join('; ')} } }\n`);
390
490
  emit('}\n');
491
+ emit('export type Slots = Awaited<ReturnType<typeof __cl_check>>[\'__cl_slots\']\n');
391
492
  return { code, mappings, loaderSpan };
392
493
  }
393
494
  export function toSourceOffset(mappings, virtualOffset) {
@@ -490,7 +591,8 @@ export function generateTolerant(source, file, options = {}) {
490
591
  text += closer;
491
592
  continue;
492
593
  }
493
- const from = /@|block|\( after|\(\s*$/.test(message) && text.lastIndexOf('@', offset) !== -1 ? text.lastIndexOf('@', offset) : offset;
594
+ const directive = !/^(script:|TypeScript syntax)/.test(message) && /@|block|\( after|\(\s*$/.test(message);
595
+ const from = directive && text.lastIndexOf('@', offset) !== -1 ? text.lastIndexOf('@', offset) : offset;
494
596
  const lineStart = text.lastIndexOf('\n', from - 1) + 1;
495
597
  const lineEnd = text.indexOf('\n', from) === -1 ? text.length : text.indexOf('\n', from);
496
598
  const blank = (from) => text.slice(0, from) + text.slice(from, lineEnd).replace(/[^\n]/g, ' ') + text.slice(lineEnd);
@@ -1,4 +1,6 @@
1
+ import { type LibraryOption } from '../vite/libraries.ts';
1
2
  import { type LintConfig, type LintRuleDef } from '../compiler/lint.ts';
3
+ import { type ModeTable } from '../server/modes.ts';
2
4
  /** A type error, a template error, or a lint finding (#304: `code` is the rule, usually a warning). */
3
5
  export type Diagnostic = {
4
6
  file: string;
@@ -12,7 +14,8 @@ export type CheckResult = {
12
14
  diagnostics: Diagnostic[];
13
15
  exitCode: 0 | 1;
14
16
  text: string;
15
- json: string;
17
+ json: string; /** With fix: the files it rewrote. */
18
+ fixed?: string[];
16
19
  };
17
20
  /** A page's .load.ts that exports load(), as an import specifier: what it returns is checked against the inputs. */
18
21
  export declare function loaderOf(path: string): string | undefined;
@@ -25,7 +28,7 @@ export type CheckSource = {
25
28
  addDependency(file: string): void;
26
29
  }): string;
27
30
  };
28
- /** `lint`: the plugin's rule levels; `lintRules`: the project's own rules; `strict`: warnings fail too. */
31
+ /** `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
32
  export declare function check(options: {
30
33
  root: string;
31
34
  typescript?: string;
@@ -34,8 +37,12 @@ export declare function check(options: {
34
37
  lint?: LintConfig;
35
38
  lintRules?: LintRuleDef[];
36
39
  strict?: boolean;
40
+ fix?: boolean;
37
41
  components?: {
38
42
  dirs?: string[];
39
43
  auto?: boolean;
44
+ libraries?: LibraryOption[];
40
45
  };
46
+ envPrefix?: string | string[];
47
+ routes?: ModeTable;
41
48
  }): CheckResult;
package/dist/cli/check.js CHANGED
@@ -1,10 +1,11 @@
1
- import { COMPONENT_DIRS, componentIndex } from '../compiler/components.js';
1
+ import { componentNames } from '../vite/libraries.js';
2
2
  import { spawnSync } from 'node:child_process';
3
3
  import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
4
4
  import { createRequire } from 'node:module';
5
5
  import { basename, dirname, relative, resolve, sep } from 'node:path';
6
6
  import { ClarusError } from '../compiler/errors.js';
7
- import { lint } from '../compiler/lint.js';
7
+ import { compile } from '../compiler/index.js';
8
+ import { applyFixes, lint } from '../compiler/lint.js';
8
9
  import { checkIcons } from '../compiler/icon.js';
9
10
  import { parse } from '../compiler/parse.js';
10
11
  import { resolveIcon } from '../icons.js';
@@ -12,6 +13,7 @@ import { generateTs, routesDeclaration, toSourceOffset, viewsDeclaration } from
12
13
  import { findClarusFiles, reachableComponents } from '../vite/build.js';
13
14
  import { projectAliases, resolveAlias } from '../vite/aliases.js';
14
15
  import { routeFromFile } from '../server/handler.js';
16
+ import { modeFor } from '../server/modes.js';
15
17
  const VIRTUAL = '.clarusjs/virtual';
16
18
  const posix = (path) => path.split(sep).join('/');
17
19
  function packageInfo(file) {
@@ -51,21 +53,74 @@ function typescriptDir(root, override) {
51
53
  }
52
54
  export function check(options) {
53
55
  const root = resolve(options.root);
54
- const names = options.components?.auto === false ? undefined : componentIndex(findClarusFiles(resolve(root, 'src'), ['.tscl']).map((f) => posix(relative(root, f))), options.components?.dirs ?? COMPONENT_DIRS).names;
56
+ const names = componentNames(root, options.components);
55
57
  const virtualRoot = resolve(root, VIRTUAL);
56
58
  rmSync(virtualRoot, { recursive: true, force: true });
57
59
  const diagnostics = [];
60
+ const compilerOnly = [];
58
61
  const generated = new Map();
59
62
  const sources = options.sources ?? [];
60
63
  const aliases = projectAliases(root, options.viteAliases);
61
64
  const pageFiles = findClarusFiles(resolve(root, 'src'), ['.tscl', ...sources.map((x) => x.extension)])
62
65
  .filter((f) => f.endsWith('.tscl') || f.startsWith(resolve(root, 'src/pages') + sep));
63
66
  const views = [];
67
+ const fixed = [];
68
+ const readRaw = (p) => readFileSync(p, 'utf8');
69
+ const islands = pageFiles.filter((p) => {
70
+ if (!p.endsWith('.tscl'))
71
+ return false;
72
+ try {
73
+ const parsed = parse(readRaw(p), p);
74
+ return !!parsed.script || parsed.inputs.some((i) => i.model);
75
+ }
76
+ catch {
77
+ return false;
78
+ }
79
+ });
80
+ const inIslands = new Set();
81
+ for (const island of islands) {
82
+ const self = realpathSync(island);
83
+ try {
84
+ for (const f of reachableComponents(root, [island], readRaw, ['.tscl'], aliases, names))
85
+ if (f !== self)
86
+ inIslands.add(f);
87
+ }
88
+ catch { }
89
+ }
90
+ const pagesDir = resolve(root, 'src/pages') + sep;
91
+ for (const page of pageFiles) {
92
+ if (!page.endsWith('.tscl') || !page.startsWith(pagesDir))
93
+ continue;
94
+ if (modeFor(routeFromFile(`/${posix(relative(root, page))}`), options.routes ?? {}) !== 'client')
95
+ continue;
96
+ try {
97
+ for (const f of reachableComponents(root, [page], readRaw, ['.tscl'], aliases, names))
98
+ inIslands.add(f);
99
+ }
100
+ catch { }
101
+ }
64
102
  for (const path of pageFiles) {
65
103
  const file = posix(relative(root, path));
66
104
  const original = readFileSync(path, 'utf8');
67
105
  const src = sources.find((x) => path.endsWith(x.extension));
68
106
  let source = original;
107
+ if (options.fix && path.endsWith('.tscl')) {
108
+ let next = original;
109
+ try {
110
+ next = applyFixes(original, lint(original, file, options.lint, options.lintRules, { envPrefix: options.envPrefix }));
111
+ }
112
+ catch { }
113
+ if (next !== original) {
114
+ try {
115
+ writeFileSync(path, next);
116
+ fixed.push(file);
117
+ source = next;
118
+ }
119
+ catch (err) {
120
+ diagnostics.push({ file, line: 1, column: 1, severity: 'error', code: 'fix', message: `--fix could not write ${file}: ${err.message}` });
121
+ }
122
+ }
123
+ }
69
124
  try {
70
125
  if (src)
71
126
  source = src.toTscl(original, path, { route: routeFromFile(`/${file}`), root, addDependency: () => { } });
@@ -77,7 +132,7 @@ export function check(options) {
77
132
  views.push({ file, source });
78
133
  if (!src) {
79
134
  try {
80
- for (const m of lint(source, file, options.lint, options.lintRules))
135
+ for (const m of lint(source, file, options.lint, options.lintRules, { envPrefix: options.envPrefix }))
81
136
  diagnostics.push({ file, line: m.line, column: m.column, severity: m.severity, code: m.rule, message: m.message });
82
137
  }
83
138
  catch { }
@@ -88,6 +143,7 @@ export function check(options) {
88
143
  const at = src ? inSource(original, source, lines.slice(0, err.line - 1).reduce((n, l) => n + l.length + 1, 0) + err.column - 1) : null;
89
144
  diagnostics.push({ file, ...(src ? (at === null ? { line: 1, column: 1 } : position(original, at)) : { line: err.line, column: err.column }), severity: 'error', code: 'clarus', message });
90
145
  };
146
+ let generatedOk = true;
91
147
  try {
92
148
  const loader = loaderOf(path);
93
149
  const { code, mappings, loaderSpan } = generateTs(source, file, { ...(loader ? { loader } : {}), components: names });
@@ -100,7 +156,19 @@ export function check(options) {
100
156
  if (!(err instanceof ClarusError))
101
157
  throw err;
102
158
  located(err);
159
+ generatedOk = false;
103
160
  }
161
+ if (generatedOk)
162
+ try {
163
+ compile(source, { file, target: 'client', components: names, icon: (name) => resolveIcon(name, path), renderImports: inIslands.has(realpathSync(path)) });
164
+ }
165
+ catch (err) {
166
+ if (!(err instanceof ClarusError))
167
+ throw err;
168
+ const before = diagnostics.length;
169
+ located(err);
170
+ compilerOnly.push(...diagnostics.splice(before));
171
+ }
104
172
  try {
105
173
  for (const err of checkIcons(parse(source, file), file, source, (name) => resolveIcon(name, path)))
106
174
  located(err);
@@ -112,7 +180,7 @@ export function check(options) {
112
180
  const virtualOf = new Map();
113
181
  const converted = new Map(views.map((v) => [realpathSync(resolve(root, v.file)), v.source]));
114
182
  const textOf = (p) => converted.get(realpathSync(p)) ?? readFileSync(p, 'utf8');
115
- const components = reachableComponents(root, pageFiles, textOf, ['.tscl'], aliases);
183
+ const components = reachableComponents(root, pageFiles, textOf, ['.tscl'], aliases, names);
116
184
  for (const path of components.filter((p) => !p.startsWith(resolve(appRoot, 'src') + sep))) {
117
185
  const pkg = packageInfo(path);
118
186
  const vpath = resolve(virtualRoot, '_pkg', pkg.name, `${relative(pkg.dir, path)}.ts`);
@@ -130,17 +198,22 @@ export function check(options) {
130
198
  }
131
199
  }
132
200
  const require = createRequire(resolve(root, 'package.json'));
133
- for (const path of components) {
134
- for (const m of textOf(path).matchAll(/^@import\s+[A-Za-z_$][\w-]*\s+from\s+(['"])([^'"./][^'"]*\.tscl)\1/gm)) {
135
- try {
136
- const file = realpathSync(resolveAlias(m[2], aliases) ?? require.resolve(m[2]));
137
- const target = virtualOf.get(file) ?? (file.startsWith(appRoot + sep) ? resolve(virtualRoot, `${relative(appRoot, file)}.ts`) : undefined);
138
- if (target)
139
- paths[`${m[2]}.ts`] = [`./${posix(relative(resolve(root, '.clarusjs'), target))}`];
140
- }
141
- catch { }
201
+ const mapSpecifier = (spec) => {
202
+ try {
203
+ const file = realpathSync(resolveAlias(spec, aliases) ?? require.resolve(spec));
204
+ const target = virtualOf.get(file) ?? (file.startsWith(appRoot + sep) ? resolve(virtualRoot, `${relative(appRoot, file)}.ts`) : undefined);
205
+ if (target)
206
+ paths[`${spec}.ts`] = [`./${posix(relative(resolve(root, '.clarusjs'), target))}`];
142
207
  }
208
+ catch { }
209
+ };
210
+ for (const path of components) {
211
+ for (const m of textOf(path).matchAll(/^@import\s+[A-Za-z_$][\w-]*\s+from\s+(['"])([^'"./][^'"]*\.tscl)\1/gm))
212
+ mapSpecifier(m[2]);
143
213
  }
214
+ for (const spec of Object.values(names ?? {}).flat())
215
+ if (!spec.startsWith('/') && spec.endsWith('.tscl'))
216
+ mapSpecifier(spec);
144
217
  const fromCheck = (path) => { const rel = posix(relative(resolve(root, '.clarusjs'), path)); return rel.startsWith('.') ? rel : `./${rel}`; };
145
218
  paths['/*'] = ['../*', './virtual/*'];
146
219
  for (const alias of aliases) {
@@ -171,7 +244,7 @@ export function check(options) {
171
244
  rootDirs: ['..', './virtual'],
172
245
  paths,
173
246
  },
174
- include: ['../src', './virtual', './views.d.ts', './routes.d.ts'],
247
+ include: ['../src', './virtual', './views.d.ts', './routes.d.ts', './env.d.ts'],
175
248
  };
176
249
  const configPath = resolve(root, '.clarusjs/tsconfig.check.json');
177
250
  mkdirSync(dirname(configPath), { recursive: true });
@@ -202,11 +275,14 @@ export function check(options) {
202
275
  const message = fromLoader ? `load() returns a value that doesn't fit this page's inputs: ${m[5]}` : source === null ? `${m[5]} (in generated code)` : m[5];
203
276
  diagnostics.push({ file: g.file, ...at, severity: 'error', code: m[4], message });
204
277
  }
278
+ const errorLines = new Set(diagnostics.filter((d) => d.severity === 'error').map((d) => `${d.file}:${d.line}`));
279
+ diagnostics.push(...compilerOnly.filter((d) => !errorLines.has(`${d.file}:${d.line}`)));
205
280
  diagnostics.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column);
206
281
  return {
207
282
  diagnostics,
208
283
  exitCode: diagnostics.some((d) => d.severity === 'error' || options.strict) ? 1 : 0,
209
284
  text: diagnostics.map((d) => `${d.file}:${d.line}:${d.column} ${d.severity} ${d.code}: ${d.message}`).join('\n'),
210
285
  json: JSON.stringify(diagnostics, null, 2),
286
+ ...(options.fix ? { fixed } : {}),
211
287
  };
212
288
  }
@@ -9,12 +9,14 @@ const WHEN = {
9
9
  const kb = (bytes) => (bytes ? `${(bytes / 1024).toFixed(1)} KB` : '0 KB');
10
10
  const row = (label, lines) => lines.map((l, i) => ` ${(i ? '' : label).padEnd(12)}${l}`);
11
11
  function describe(path, r) {
12
+ const parts = [...(r.layouts?.length ? row('Layouts', r.layouts) : []), ...(r.guards?.length ? row('Guards', r.guards) : [])];
12
13
  if (r.mode === 'server') {
13
14
  return [
14
15
  path,
15
16
  ...row('Rendered', ['on every request, by dist/server/index.mjs']),
16
17
  ...row('Data', [r.loader === 'request' ? `load() runs on every request${r.cookies ? ', and reads cookies' : ''}` : 'no loader']),
17
18
  ...row('Islands', ['decided per request']),
19
+ ...parts,
18
20
  ].join('\n');
19
21
  }
20
22
  const islands = r.islands.map((i) => `${i.component}${i.count > 1 ? ` ×${i.count}` : ''} (${kb(i.gzip)}, ${WHEN[i.attach]})`);
@@ -25,6 +27,7 @@ function describe(path, r) {
25
27
  ...row('Islands', islands.length ? islands : ['none']),
26
28
  ...row('JavaScript', [r.js.files.length ? `${kb(r.js.initialGzip)} on page load, ${kb(r.js.gzip)} in all (gzip, ${r.js.files.length} files)` : 'none']),
27
29
  ...row('CSS', [r.css.length ? r.css.join(', ') : 'none']),
30
+ ...parts,
28
31
  ].join('\n');
29
32
  }
30
33
  function table(routes) {
package/dist/cli/index.js CHANGED
@@ -3,7 +3,9 @@ import { Command } from 'commander';
3
3
  import { check } from './check.js';
4
4
  import { loadProject } from './project.js';
5
5
  import { explain } from './explain.js';
6
- import { serve } from './mapper.js';
6
+ import { serve as mapper } from './mapper.js';
7
+ import { serve } from '../node/serve.js';
8
+ import { writeEnvTypes } from '../vite/env.js';
7
9
  const program = new Command('clarusjs').description('clarusjs: clear, compiled views');
8
10
  program
9
11
  .command('check')
@@ -11,8 +13,14 @@ program
11
13
  .argument('[dir]', 'project folder', '.')
12
14
  .option('--json', 'print diagnostics as JSON')
13
15
  .option('--strict', 'fail on lint warnings too')
16
+ .option('--fix', 'apply lint fixes to the .tscl files (wrapping a component\'s several roots in <fragment>, …) before checking')
14
17
  .action(async (dir, options) => {
15
- const result = check({ root: dir, ...(await loadProject(dir)), strict: options.strict });
18
+ const project = await loadProject(dir);
19
+ if (project.env)
20
+ writeEnvTypes(dir, project.env);
21
+ const result = check({ root: dir, ...project, strict: options.strict, fix: options.fix });
22
+ for (const file of result.fixed ?? [])
23
+ (options.json ? console.error : console.log)(`fixed ${file}`);
16
24
  if (options.json)
17
25
  console.log(result.json);
18
26
  else if (result.diagnostics.length) {
@@ -42,5 +50,18 @@ program
42
50
  program
43
51
  .command('mapper')
44
52
  .description('the TypeScript 7.1 content mapper for .tscl files (TypeScript starts it; see https://clarusjs.com/guide/editor)')
45
- .action(() => serve());
53
+ .action(() => mapper());
54
+ program
55
+ .command('serve')
56
+ .description('serve a built site (vite build first) on Node: its files, server routes and _headers; for any Node host or a container')
57
+ .argument('[dir]', 'project folder', '.')
58
+ .option('--port <port>', 'port (default: $PORT, else 3000)')
59
+ .option('--host <host>', 'interface (default: $HOST, else 0.0.0.0)')
60
+ .action(async (dir, options) => {
61
+ const server = await serve({ root: dir, port: options.port === undefined ? undefined : Number(options.port), host: options.host });
62
+ const address = server.address();
63
+ console.log(`clarusjs: serving ${dir} at http://${typeof address === 'object' && address ? `${address.address === '0.0.0.0' ? 'localhost' : address.address}:${address.port}` : address}/`);
64
+ for (const signal of ['SIGTERM', 'SIGINT'])
65
+ process.once(signal, () => server.close(() => process.exit(0)));
66
+ });
46
67
  program.parse();
@@ -2,6 +2,7 @@ import { existsSync } from 'node:fs';
2
2
  import { dirname, relative, resolve, sep } from 'node:path';
3
3
  import { generateTolerant } from '../check/generate.js';
4
4
  import { COMPONENT_DIRS, componentIndex } from '../compiler/components.js';
5
+ import { readComponents } from '../vite/libraries.js';
5
6
  import { findClarusFiles } from '../vite/build.js';
6
7
  import { loaderOf } from './check.js';
7
8
  function namesFor(fileName) {
@@ -11,11 +12,15 @@ function namesFor(fileName) {
11
12
  return undefined;
12
13
  root = dirname(root);
13
14
  }
15
+ const written = readComponents(root);
14
16
  const files = findClarusFiles(resolve(root, 'src'), ['.tscl']).map((f) => relative(root, f).split(sep).join('/'));
15
17
  const rel = (path) => { const r = relative(dirname(fileName), resolve(root, path.slice(1))).split(sep).join('/'); return r.startsWith('.') ? r : `./${r}`; };
16
18
  const names = {};
17
- for (const [name, path] of Object.entries(componentIndex(files, COMPONENT_DIRS).names))
19
+ for (const [name, path] of Object.entries(componentIndex(files, written?.dirs ?? COMPONENT_DIRS).names))
18
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;
19
24
  return names;
20
25
  }
21
26
  export function transform(params) {
@@ -1,3 +1,6 @@
1
+ import type { LibraryOption } from '../vite/libraries.ts';
2
+ import type { EnvOption } from '../vite/env.ts';
3
+ import type { ModeTable } from '../server/modes.ts';
1
4
  import type { CheckSource } from './check.ts';
2
5
  import type { LintConfig, LintRuleDef } from '../compiler/lint.ts';
3
6
  type Project = {
@@ -8,7 +11,11 @@ type Project = {
8
11
  components?: {
9
12
  dirs?: string[];
10
13
  auto?: boolean;
14
+ libraries?: LibraryOption[];
11
15
  };
16
+ env?: EnvOption;
17
+ envPrefix?: string | string[];
18
+ routes?: ModeTable;
12
19
  };
13
20
  export declare function loadProject(root: string): Promise<Project>;
14
21
  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 ?? [], components: plugin?.api?.components };
21
+ return { sources: plugin?.api?.sources ?? [], viteAliases: loaded.config.resolve?.alias, lint: plugin?.api?.lint, lintRules: plugin?.api?.lintRules ?? [], components: plugin?.api?.components, env: plugin?.api?.env, envPrefix: loaded.config.envPrefix, routes: plugin?.api?.routes };
22
22
  }