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
@@ -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);
@@ -344,6 +359,95 @@ export function parse(source, file) {
344
359
  }
345
360
  return { type: 'await', expr, exprStart, pending, then, catch: caught, start };
346
361
  }
362
+ function transitionBlock() {
363
+ const start = i;
364
+ i += '@transition'.length;
365
+ while (/\s/.test(source[i] ?? ''))
366
+ i++;
367
+ let args = { name: null, nameStart: i, options: null, optionsStart: i };
368
+ if (source[i] === '(') {
369
+ const { condStart } = condition('@transition');
370
+ const raw = source.slice(condStart, i - 1);
371
+ const comma = topLevelComma(raw);
372
+ const part = (from, to) => {
373
+ const text = raw.slice(from, to);
374
+ const lead = text.length - text.trimStart().length;
375
+ return { text: text.trim() || null, at: condStart + from + lead };
376
+ };
377
+ const name = part(0, comma === -1 ? raw.length : comma);
378
+ const options = comma === -1 ? { text: null, at: condStart + raw.length } : part(comma + 1, raw.length);
379
+ args = { name: name.text, nameStart: name.at, options: options.text, optionsStart: options.at };
380
+ while (/\s/.test(source[i] ?? ''))
381
+ i++;
382
+ }
383
+ if (source[i] !== '{')
384
+ fail('expected { to open the block', i);
385
+ i++;
386
+ const kids = children({ tag: '@transition', start, block: true });
387
+ const wrapped = kids.filter((n) => !(n.type === 'text' && !n.value.trim()));
388
+ const only = wrapped[0];
389
+ const blockish = (n) => n.type === 'if' || n.type === 'for';
390
+ if (wrapped.length !== 1 || !blockish(only))
391
+ fail('@transition wraps one @if or @for', (wrapped.find((n) => !blockish(n)) ?? wrapped[1] ?? { start }).start);
392
+ const node = only;
393
+ node.transition = { ...args, start };
394
+ return node;
395
+ }
396
+ function topLevelComma(text) {
397
+ let depth = 0;
398
+ const template = (j) => {
399
+ for (j++; j < text.length; j++) {
400
+ if (text[j] === '\\')
401
+ j++;
402
+ else if (text[j] === '`')
403
+ return j;
404
+ else if (text[j] === '$' && text[j + 1] === '{') {
405
+ let inner = 1;
406
+ for (j += 2; j < text.length && inner; j++) {
407
+ const c = text[j];
408
+ if (c === '`')
409
+ j = template(j);
410
+ else if (c === '"' || c === "'") {
411
+ for (j++; j < text.length && text[j] !== c; j++)
412
+ if (text[j] === '\\')
413
+ j++;
414
+ }
415
+ else if (c === '{')
416
+ inner++;
417
+ else if (c === '}')
418
+ inner--;
419
+ }
420
+ j--;
421
+ }
422
+ }
423
+ return j;
424
+ };
425
+ for (let j = 0; j < text.length; j++) {
426
+ const c = text[j];
427
+ if (c === '"' || c === "'") {
428
+ for (j++; j < text.length && text[j] !== c; j++)
429
+ if (text[j] === '\\')
430
+ j++;
431
+ }
432
+ else if (c === '`')
433
+ j = template(j);
434
+ else if (c === '/' && text[j + 1] === '/') {
435
+ const nl = text.indexOf('\n', j);
436
+ j = nl === -1 ? text.length : nl;
437
+ }
438
+ else if (c === '/' && text[j + 1] === '*') {
439
+ const close = text.indexOf('*/', j + 2);
440
+ j = close === -1 ? text.length : close + 1;
441
+ }
442
+ else if (c === '(' || c === '[' || c === '{')
443
+ depth++;
444
+ else if (c === ')' || c === ']' || c === '}')
445
+ depth--;
446
+ else if (c === ',' && depth === 0)
447
+ return j;
448
+ }
449
+ return -1;
450
+ }
347
451
  function ifBlock() {
348
452
  const start = i;
349
453
  i += 3;
@@ -424,7 +528,30 @@ export function parse(source, file) {
424
528
  const listStart = at + first.start + m.indices[2][0];
425
529
  let track = null;
426
530
  let trackStart = -1;
531
+ const aliases = [];
427
532
  for (const clause of rest) {
533
+ if (/^let\s/.test(clause.text)) {
534
+ let from = at + clause.start + 4;
535
+ for (const part of clause.text.slice(4).split(',')) {
536
+ const lead = part.length - part.trimStart().length;
537
+ const a = /^([A-Za-z_$][\w$]*)\s*=\s*(\S+)$/.exec(part.trim());
538
+ const start = from + lead;
539
+ from += part.length + 1;
540
+ if (!a)
541
+ fail('let takes name = $index (or $count, $first, $last, $even, $odd), separated by commas', start);
542
+ const [, name, of] = a;
543
+ if (!FOR_IMPLICIT.includes(of))
544
+ fail(`let takes the row's $index, $count, $first, $last, $even or $odd: ${name} = ${of}`, start);
545
+ if (FOR_IMPLICIT.includes(name))
546
+ fail(`"${name}" is an implicit @for variable: name the alias something else`, start);
547
+ if (name === m[1].trim())
548
+ fail(`"${name}" is this @for's item: name the alias something else`, start);
549
+ if (aliases.some((x) => x.name === name))
550
+ fail(`"${name}" is named twice in this @for`, start);
551
+ aliases.push({ name: name, of: of, start });
552
+ }
553
+ continue;
554
+ }
428
555
  const t = /^track\s+([\s\S]+)$/d.exec(clause.text);
429
556
  if (!t)
430
557
  fail(`unknown @for clause "${clause.text}"`, headStart);
@@ -460,7 +587,7 @@ export function parse(source, file) {
460
587
  }
461
588
  else
462
589
  i = save;
463
- return { type: 'for', item: m[1], list: m[2].trim(), track, headStart, itemStart, listStart, trackStart, children: body, empty, start };
590
+ return { type: 'for', item: m[1], list: m[2].trim(), track, headStart, itemStart, listStart, trackStart, aliases, children: body, empty, start };
464
591
  }
465
592
  function fillBlock() {
466
593
  const start = i;
@@ -508,6 +635,11 @@ export function parse(source, file) {
508
635
  nodes.push(ifBlock());
509
636
  textStart = i;
510
637
  }
638
+ else if (/^@transition[\s({]/.test(source.slice(i, i + 12))) {
639
+ flush();
640
+ nodes.push(transitionBlock());
641
+ textStart = i;
642
+ }
511
643
  else if (/^@await[\s(]/.test(source.slice(i, i + 7))) {
512
644
  flush();
513
645
  nodes.push(awaitBlock());
@@ -662,6 +794,9 @@ export function parse(source, file) {
662
794
  return nodes;
663
795
  }
664
796
  out.nodes = children();
797
+ const kebab = new Map(out.imports.map((imp) => [kebabOf(imp.name), imp.name]).filter(([k, name]) => k !== name && k.includes('-')));
798
+ if (kebab.size)
799
+ renameTags(out.nodes, kebab);
665
800
  return out;
666
801
  }
667
802
  export function importNames(clause) {
@@ -670,3 +805,31 @@ export function importNames(clause) {
670
805
  return clause.slice(1, -1).split(',').map((p) => p.trim()).filter((p) => p && !p.startsWith('type '))
671
806
  .map((p) => p.split(/\s+as\s+/).pop().trim());
672
807
  }
808
+ function renameTags(nodes, names) {
809
+ for (const n of nodes) {
810
+ if (n.type === 'element') {
811
+ n.tag = names.get(n.tag) ?? n.tag;
812
+ renameTags(n.children, names);
813
+ }
814
+ else if (n.type === 'fill')
815
+ renameTags(n.children, names);
816
+ else if (n.type === 'if')
817
+ for (const b of n.branches)
818
+ renameTags(b.children, names);
819
+ else if (n.type === 'for') {
820
+ renameTags(n.children, names);
821
+ if (n.empty)
822
+ renameTags(n.empty, names);
823
+ }
824
+ else if (n.type === 'await') {
825
+ renameTags(n.pending, names);
826
+ if (n.then)
827
+ renameTags(n.then.children, names);
828
+ if (n.catch)
829
+ renameTags(n.catch.children, names);
830
+ }
831
+ }
832
+ }
833
+ export function kebabOf(name) {
834
+ return name.replace(/([a-z0-9])([A-Z])/g, '$1-$2').replace(/([A-Z])([A-Z][a-z])/g, '$1-$2').toLowerCase();
835
+ }
@@ -1,4 +1,6 @@
1
1
  export type Signals = Map<string, 'state' | 'derived' | 'shared' | 'input' | 'model'>;
2
+ /** Throw a located ClarusError for a script that isn't JavaScript (#432): what clarusjs check runs before reading it. */
3
+ export declare function checkScript(code: string, file: string, source: string, offset: number): void;
2
4
  /** Throw a located ClarusError unless `expr` is exactly one JS expression. */
3
5
  export declare function checkExpr(expr: string, file: string, source: string, offset: number): void;
4
6
  /** Throw a located ClarusError unless `code` parses as statements (event handlers may hold several). */
@@ -1,4 +1,4 @@
1
- import { parse as acornParse, parseExpressionAt } from 'acorn';
1
+ import { tokenizer, parse as acornParse, parseExpressionAt } from 'acorn';
2
2
  import { FOR_IMPLICIT } from './parse.js';
3
3
  import { ClarusError } from './errors.js';
4
4
  const OPTS = { ecmaVersion: 'latest', sourceType: 'module' };
@@ -51,15 +51,92 @@ function print(node, code, hook, parent = null, key = '') {
51
51
  }
52
52
  return out + code.slice(pos, node.end);
53
53
  }
54
+ const TS = 'TypeScript syntax in a <script> (scripts are JavaScript): ';
55
+ const TS_WHERE = '. Types come from @input, inference, and the .ts modules a script imports';
56
+ function typescriptAt(code, pos) {
57
+ const before = code.slice(0, pos).trimEnd();
58
+ const at = code.slice(pos);
59
+ if (/^as\s/.test(at) && /[\w$)\]]$/.test(before))
60
+ return 'an as cast';
61
+ if (/^satisfies\s/.test(at))
62
+ return 'a satisfies check';
63
+ if (/^!(?!=)/.test(at) && /[\w$)\]]$/.test(before))
64
+ return 'a non-null assertion (!)';
65
+ if (/^:/.test(at) && /[\w$)\]]$/.test(before))
66
+ return 'a type annotation';
67
+ if (/(^|[\n;{}])\s*(interface|enum)\s*$/.test(before) || /(^|[\n;{}])\s*(interface|enum|type\s+[\w$]+\s*[=<])/.test(code.slice(code.lastIndexOf('\n', pos - 1) + 1, pos + 40)))
68
+ return 'a type declaration';
69
+ if (/^</.test(at) && /\bfunction\s+[\w$]+$|[\w$]$/.test(before))
70
+ return 'type parameters (<T>)';
71
+ if (/<[^<>]*>\s*\(?$/.test(before))
72
+ return 'a type argument (<…>)';
73
+ return null;
74
+ }
75
+ const TYPE_TOKENS = new Set(['name', 'string', 'num', ',', '.', '[', ']', '{', '}', ':', '?', '|', '&', '=>', '(', ')', 'true', 'false', 'null', 'void', 'typeof', 'new', '...']);
76
+ function typeArgumentIn(code) {
77
+ let tokens;
78
+ try {
79
+ tokens = [...tokenizer(code, OPTS)];
80
+ }
81
+ catch {
82
+ return null;
83
+ }
84
+ for (let i = 1; i < tokens.length; i++) {
85
+ const lt = tokens[i];
86
+ const name = tokens[i - 1];
87
+ if (lt.value !== '<' || name.type.label !== 'name' || name.end !== lt.start)
88
+ continue;
89
+ let depth = 1;
90
+ let j = i + 1;
91
+ for (; j < tokens.length && depth > 0; j++) {
92
+ const t = tokens[j];
93
+ if (t.value === '<')
94
+ depth++;
95
+ else if (t.value === '>')
96
+ depth--;
97
+ else if (t.value === '>>')
98
+ depth -= 2;
99
+ else if (t.value === '>>>')
100
+ depth -= 3;
101
+ else if (!TYPE_TOKENS.has(t.type.label) && t.type.label !== 'keyof')
102
+ break;
103
+ if (depth < 0)
104
+ break;
105
+ }
106
+ if (depth !== 0 || tokens[j]?.type.label !== '(')
107
+ continue;
108
+ let k = i - 1;
109
+ while (k >= 2 && tokens[k - 1].type.label === '.' && tokens[k - 2].type.label === 'name')
110
+ k -= 2;
111
+ const what = tokens[k - 1]?.type.label === 'function' ? 'type parameters' : 'a type argument';
112
+ const between = code.slice(lt.end, tokens[j - 1].start).trim();
113
+ let p = j + 1;
114
+ for (let open = 1; p < tokens.length && open; p++)
115
+ open += tokens[p].type.label === '(' ? 1 : tokens[p].type.label === ')' ? -1 : 0;
116
+ const inside = code.slice(tokens[j].end, tokens[p - 1].start).trim();
117
+ const comparison = /^[\w$.]+$/.test(between) && tokens[j - 1].value === '>' ? `(${code.slice(tokens[k].start, lt.start)} < ${between}) > ${inside.includes(',') ? `(${inside})` : inside}` : '';
118
+ return { start: tokens[k].start, text: `${code.slice(tokens[k].start, tokens[j - 1].end)}(…)`, what, comparison };
119
+ }
120
+ return null;
121
+ }
54
122
  function parseScript(code, file = '<script>', source = code, offset = 0) {
123
+ const arg = typeArgumentIn(code);
124
+ if (arg)
125
+ throw new ClarusError(`${TS}${arg.what}, ${arg.text}${TS_WHERE}${arg.comparison ? ` (for a comparison, add parentheses: ${arg.comparison})` : ''}`, file, source, offset + arg.start);
55
126
  try {
56
127
  return acornParse(code, OPTS);
57
128
  }
58
129
  catch (e) {
59
130
  const pos = e.pos ?? 0;
131
+ const ts = typescriptAt(code, pos);
132
+ if (ts)
133
+ throw new ClarusError(TS + ts + TS_WHERE, file, source, offset + pos);
60
134
  throw new ClarusError(`script: ${e.message.replace(/ \(\d+:\d+\)$/, '')}`, file, source, offset + pos);
61
135
  }
62
136
  }
137
+ export function checkScript(code, file, source, offset) {
138
+ parseScript(code, file, source, offset);
139
+ }
63
140
  function parseExpr(expr) {
64
141
  const ast = parseExpressionAt(expr, 0, OPTS);
65
142
  const open = (expr.slice(0, ast.start).match(/\(/g) ?? []).length;
@@ -1,5 +1,5 @@
1
1
  import { effect, onDispose, state, untrack } from '../runtime/index.js';
2
- import { marked, openSlots, owner } from '../runtime/dom.js';
2
+ import { keepSlots, marked, openSlots, owner } from '../runtime/dom.js';
3
3
  import { browser } from '../runtime/env.js';
4
4
  const CONTAINERS = 'label, [data-cl-field], fieldset, cl-island';
5
5
  const FIELDS = 'input[data-cl-path],select[data-cl-path],textarea[data-cl-path]';
@@ -7,6 +7,9 @@ const FLAGS = ['valueMissing', 'typeMismatch', 'patternMismatch', 'tooLong', 'to
7
7
  let ids = 0;
8
8
  const read = (value, path) => path.split('.').reduce((v, k) => (v == null ? v : v[k]), value);
9
9
  const dotted = (path = []) => path.map((p) => String(typeof p === 'object' ? p.key : p)).join('.');
10
+ const same = (a, b) => a === b || (!!a && !!b && typeof a === 'object' && typeof b === 'object' && Array.isArray(a) === Array.isArray(b) &&
11
+ Object.keys(a).length === Object.keys(b).length && a.length === b.length &&
12
+ Object.keys(a).every((k) => same(a[k], b[k])));
10
13
  function pathOf(field, root) {
11
14
  const parts = [];
12
15
  let through = 0;
@@ -53,23 +56,26 @@ export function form(values, options = {}) {
53
56
  let server = {};
54
57
  let schemaIssues = {};
55
58
  let errorsNow = {};
59
+ let shownPaths = new Set();
60
+ let touchedPaths = new Set();
56
61
  const roots = new Map();
57
62
  let checkSeq = 0;
58
63
  let latest = Promise.resolve();
59
64
  let revision = 0;
60
65
  let failed = false;
61
66
  let timer;
67
+ let queued = false;
62
68
  let last = initial;
63
69
  const current = state('');
64
70
  const submitting = state(false);
65
71
  const passed = new Set();
66
72
  const now = () => untrack(() => current.get());
67
- const boxOf = (el, path, root) => {
73
+ const boxOf = (el, path, paths) => {
68
74
  for (let c = el.closest(CONTAINERS); c; c = c.parentElement?.closest(CONTAINERS) ?? null) {
69
75
  const box = c.querySelector('[data-cl-message]');
70
76
  if (!box)
71
77
  continue;
72
- return [...c.querySelectorAll(FIELDS)].every((x) => x === el || pathOf(x, root) === path) ? box : undefined;
78
+ return [...c.querySelectorAll(FIELDS)].every((x) => x === el || paths.get(x) === path) ? box : undefined;
73
79
  }
74
80
  };
75
81
  const eventField = (e) => {
@@ -78,10 +84,11 @@ export function form(values, options = {}) {
78
84
  };
79
85
  const fields = () => [...roots.keys()].flatMap((root) => [...root.querySelectorAll(FIELDS)].map((el) => ({ el: el, path: pathOf(el, root), root })));
80
86
  const shownField = (el, path) => shownAll.on || forced.has(path) || checked.has(el) || (show === 'input' ? touched.has(el) || dirty.has(el) : show === 'blur' && touched.has(el));
81
- const shown = (path) => shownAll.on || forced.has(path) || fields().some((f) => f.path === path && shownField(f.el, path));
87
+ const shown = (path) => shownAll.on || forced.has(path) || shownPaths.has(path);
82
88
  function refresh() {
83
89
  const next = {};
84
- for (const { el, path } of fields()) {
90
+ const list = keepSlots(fields);
91
+ for (const { el, path } of list) {
85
92
  el.setCustomValidity('');
86
93
  let native = '';
87
94
  if (!el.validity.valid) {
@@ -99,8 +106,11 @@ export function form(values, options = {}) {
99
106
  if (failed)
100
107
  next[''] ??= options.messages?.schema ?? "The form couldn't be checked. Try again.";
101
108
  errorsNow = next;
102
- for (const { el, path, root } of fields())
103
- paint(el, boxOf(el, path, root), shown(path) ? errorsNow[path] ?? '' : '');
109
+ shownPaths = new Set(list.filter((f) => shownField(f.el, f.path)).map((f) => f.path));
110
+ touchedPaths = new Set(list.filter((f) => touched.has(f.el)).map((f) => f.path));
111
+ const paths = new Map(list.map((f) => [f.el, f.path]));
112
+ for (const { el, path } of list)
113
+ paint(el, boxOf(el, path, paths), shown(path) ? errorsNow[path] ?? '' : '');
104
114
  version.set(untrack(() => version.get()) + 1);
105
115
  }
106
116
  function paint(el, box, message) {
@@ -191,6 +201,13 @@ export function form(values, options = {}) {
191
201
  step?.querySelector('input, select, textarea, button, [tabindex]')?.focus();
192
202
  };
193
203
  const errorsIn = (step) => new Set(fields().filter((f) => step.contains(f.el) && shown(f.path) && errorsNow[f.path]).map((f) => f.path)).size;
204
+ const refreshSoon = () => {
205
+ if (!queued) {
206
+ queued = true;
207
+ queueMicrotask(() => { queued = false; if (roots.size)
208
+ refresh(); });
209
+ }
210
+ };
194
211
  const checkSoon = () => {
195
212
  clearTimeout(timer);
196
213
  timer = setTimeout(check, 300);
@@ -203,10 +220,10 @@ export function form(values, options = {}) {
203
220
  delete server[path];
204
221
  last = value;
205
222
  revision++;
206
- if (roots.size) {
207
- refresh();
223
+ if (roots.size)
224
+ refreshSoon();
225
+ if (roots.size)
208
226
  checkSoon();
209
- }
210
227
  });
211
228
  });
212
229
  const onInput = (e) => {
@@ -215,7 +232,7 @@ export function form(values, options = {}) {
215
232
  return;
216
233
  dirty.add(field);
217
234
  revision++;
218
- refresh();
235
+ refreshSoon();
219
236
  checkSoon();
220
237
  };
221
238
  const onLeave = (e) => {
@@ -241,10 +258,11 @@ export function form(values, options = {}) {
241
258
  version.get();
242
259
  const out = [];
243
260
  const all = fields();
244
- for (const { el, path, root } of all) {
261
+ const paths = new Map(all.map((f) => [f.el, f.path]));
262
+ for (const { el, path } of all) {
245
263
  if (out.some((e) => e.path === path) || !shown(path) || !errorsNow[path])
246
264
  continue;
247
- out.push({ path, message: errorsNow[path], id: boxOf(el, path, root)?.id || el.id, step: el.closest('[data-cl-step]')?.id ?? null });
265
+ out.push({ path, message: errorsNow[path], id: boxOf(el, path, paths)?.id || el.id, step: el.closest('[data-cl-step]')?.id ?? null });
248
266
  }
249
267
  for (const [path, message] of Object.entries(errorsNow)) {
250
268
  if (!all.some((f) => f.path === path) && (shownAll.on || forced.has(path)))
@@ -252,8 +270,10 @@ export function form(values, options = {}) {
252
270
  }
253
271
  return out;
254
272
  },
255
- touched(path) { version.get(); return fields().some((f) => f.path === path && touched.has(f.el)); },
273
+ touched(path) { version.get(); return touchedPaths.has(path); },
256
274
  changed(path) { return read(signal.get(), path) !== read(initial, path); },
275
+ get dirty() { return !same(signal.get(), initial); },
276
+ shown(path) { version.get(); return shown(path); },
257
277
  get valid() { version.get(); return !Object.keys(errorsNow).length; },
258
278
  get pending() { return pending.get(); },
259
279
  setErrors(errors) { server = { ...errors }; for (const path of Object.keys(errors))
@@ -382,7 +402,7 @@ export function connect(ctx, index, get) {
382
402
  }
383
403
  function inert() {
384
404
  return {
385
- error: () => '', errors: [], touched: () => false, changed: () => false, valid: true, pending: false,
405
+ error: () => '', errors: [], touched: () => false, changed: () => false, dirty: false, shown: () => false, valid: true, pending: false,
386
406
  setErrors() { }, focus() { }, reset() { }, step: '', steps: [], next: async () => false, back() { }, go() { },
387
407
  submitting: false, submit: async () => false,
388
408
  };
@@ -71,6 +71,13 @@ export type Form<T> = {
71
71
  touched(path: Path<T>): boolean;
72
72
  /** Differs from the starting value. */
73
73
  changed(path: Path<T>): boolean;
74
+ /** Any value differs from the start (compared by value: typed into and back is clean). For "unsaved changes". */
75
+ readonly dirty: boolean;
76
+ /**
77
+ * Whether this field's error shows now, by the form's `show` rule (or after a step check or a submit): for a field
78
+ * that shows its own error, such as a component's.
79
+ */
80
+ shown(path: Path<T>): boolean;
74
81
  /** No errors at all (shown or not). */
75
82
  readonly valid: boolean;
76
83
  /** An async schema check is running. */
@@ -0,0 +1,26 @@
1
+ import { type IncomingMessage, type Server, type ServerResponse } from 'node:http';
2
+ /** @see https://clarusjs.com/guide/deploy#node */
3
+ export type ServeOptions = {
4
+ /** The project folder (the one with dist/). Default: the current folder. */
5
+ root?: string;
6
+ /** Default: $PORT, else 3000. 0 picks a free port. */
7
+ port?: number;
8
+ /** Default: $HOST, else 0.0.0.0 (every interface, as a container needs). */
9
+ host?: string;
10
+ };
11
+ /**
12
+ * The request listener for a built site, for your own `http.createServer()` (or a framework that takes one). Each
13
+ * request: a file under dist/client (a page at `<path>/index.html`), else a server route or endpoint, else 404.html.
14
+ * @example
15
+ * const site = await createListener('.')
16
+ * createServer((req, res) => (req.url === '/healthz' ? res.end('ok') : site(req, res))).listen(3000)
17
+ * @see https://clarusjs.com/guide/deploy#node
18
+ */
19
+ export declare function createListener(root?: string): Promise<(req: IncomingMessage, res: ServerResponse) => Promise<void>>;
20
+ /**
21
+ * Serves a built site. Resolves once it listens.
22
+ * @example
23
+ * const server = await serve({ root: '.', port: 8080 })
24
+ * @see https://clarusjs.com/guide/deploy#node
25
+ */
26
+ export declare function serve(options?: ServeOptions): Promise<Server>;
@@ -0,0 +1,150 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx, extraExtensions, ignoreCase) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ if (extraExtensions) {
4
+ for (var extension in extraExtensions) {
5
+ var suffix = path.slice(-extension.length);
6
+ if (suffix === extension || ignoreCase && suffix.toLowerCase() === extension.toLowerCase()) {
7
+ var output = extraExtensions[extension];
8
+ return output === extension ? path : path.slice(0, -extension.length) + output;
9
+ }
10
+ }
11
+ }
12
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
13
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
14
+ });
15
+ }
16
+ return path;
17
+ };
18
+ import { createReadStream, existsSync, statSync } from 'node:fs';
19
+ import { createServer } from 'node:http';
20
+ import { extname, resolve, sep } from 'node:path';
21
+ import { pathToFileURL } from 'node:url';
22
+ import { basePath } from '../server/head.js';
23
+ import { canonical, headersFor, readHeaders } from '../vite/headers.js';
24
+ import { acceptsEncoding, sendResponse, toRequest } from '../vite/node.js';
25
+ const TEXT = 'charset=utf-8';
26
+ const TYPES = {
27
+ '.html': `text/html; ${TEXT}`, '.js': `text/javascript; ${TEXT}`, '.mjs': `text/javascript; ${TEXT}`, '.css': `text/css; ${TEXT}`,
28
+ '.json': `application/json; ${TEXT}`, '.map': `application/json; ${TEXT}`, '.webmanifest': `application/manifest+json; ${TEXT}`,
29
+ '.txt': `text/plain; ${TEXT}`, '.md': `text/markdown; ${TEXT}`, '.xml': `application/xml; ${TEXT}`, '.svg': `image/svg+xml; ${TEXT}`,
30
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.avif': 'image/avif',
31
+ '.ico': 'image/x-icon', '.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf', '.otf': 'font/otf',
32
+ '.wasm': 'application/wasm', '.pdf': 'application/pdf', '.mp4': 'video/mp4', '.webm': 'video/webm', '.mp3': 'audio/mpeg',
33
+ };
34
+ const HIDDEN = new Set(['_headers', '_redirects', '_routes.json', '.assetsignore', '_worker.js']);
35
+ export async function createListener(root = '.') {
36
+ const client = resolve(root, 'dist/client');
37
+ const entry = resolve(root, 'dist/server/index.mjs');
38
+ if (!existsSync(client))
39
+ throw new Error(`clarusjs serve: no ${client}; run vite build first`);
40
+ const app = existsSync(entry) ? (await import(__rewriteRelativeImportExtension(pathToFileURL(entry).href))).default : undefined;
41
+ const base = basePath(app?.base ?? '/');
42
+ const rules = readHeaders(client);
43
+ const fileFor = (path) => {
44
+ for (const candidate of [path, `${path.replace(/\/?$/, '/')}index.html`]) {
45
+ const file = resolve(client, `.${candidate}`);
46
+ if (!file.startsWith(client + sep) || HIDDEN.has(file.slice(client.length + 1).split(sep)[0].toLowerCase()))
47
+ continue;
48
+ if (existsSync(file) && statSync(file).isFile())
49
+ return file;
50
+ }
51
+ return undefined;
52
+ };
53
+ const withRules = (res, pathname) => {
54
+ for (const [name, value] of headersFor(rules, pathname))
55
+ if (!res.hasHeader(name))
56
+ res.setHeader(name, value);
57
+ };
58
+ function sendFile(req, res, file, pathname, status = 200) {
59
+ const stat = statSync(file);
60
+ const etag = `W/"${stat.size.toString(36)}-${stat.mtimeMs.toString(36)}"`;
61
+ res.setHeader('content-type', TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream');
62
+ withRules(res, pathname);
63
+ if (!res.hasHeader('cache-control'))
64
+ res.setHeader('cache-control', 'no-cache');
65
+ if (status === 200) {
66
+ res.setHeader('etag', etag);
67
+ if (req.headers['if-none-match'] === etag) {
68
+ res.statusCode = 304;
69
+ return void res.end();
70
+ }
71
+ }
72
+ let body = file;
73
+ const copies = ['br', 'gzip'].filter((enc) => existsSync(file + (enc === 'br' ? '.br' : '.gz')));
74
+ if (copies.length) {
75
+ res.setHeader('vary', 'Accept-Encoding');
76
+ const pick = copies.find((enc) => acceptsEncoding(String(req.headers['accept-encoding'] ?? ''), enc));
77
+ if (pick) {
78
+ res.setHeader('content-encoding', pick);
79
+ body = file + (pick === 'br' ? '.br' : '.gz');
80
+ }
81
+ }
82
+ res.statusCode = status;
83
+ res.setHeader('content-length', statSync(body).size);
84
+ if (req.method === 'HEAD')
85
+ return void res.end();
86
+ const stream = createReadStream(body);
87
+ stream.on('error', (err) => {
88
+ if (res.headersSent)
89
+ return void res.destroy(err);
90
+ res.statusCode = 500;
91
+ res.removeHeader('content-length');
92
+ res.removeHeader('content-encoding');
93
+ res.end();
94
+ });
95
+ stream.once('open', () => stream.pipe(res));
96
+ res.once('close', () => stream.destroy());
97
+ }
98
+ return async (req, res) => {
99
+ const bad = () => {
100
+ res.statusCode = 400;
101
+ res.setHeader('content-type', `text/plain; ${TEXT}`);
102
+ res.end('Bad Request: malformed URL');
103
+ };
104
+ const [raw, query] = (req.url ?? '/').split(/\?(.*)/s);
105
+ let encoded;
106
+ let pathname;
107
+ try {
108
+ encoded = new URL(raw.startsWith('/') ? `http://x${raw}` : raw).pathname.replace(/\/{2,}/g, '/');
109
+ pathname = decodeURIComponent(encoded);
110
+ }
111
+ catch {
112
+ return bad();
113
+ }
114
+ if (canonical(pathname) !== pathname)
115
+ return bad();
116
+ const inBaseEncoded = encoded === base.slice(0, -1) ? '/' : encoded.startsWith(base) ? '/' + encoded.slice(base.length) : undefined;
117
+ const inBase = inBaseEncoded === undefined ? undefined : decodeURIComponent(inBaseEncoded);
118
+ const readable = req.method === 'GET' || req.method === 'HEAD';
119
+ const file = inBase !== undefined && readable ? fileFor(inBase) : undefined;
120
+ if (file)
121
+ return sendFile(req, res, file, pathname);
122
+ if (app && inBase !== undefined && app.isServerPath(inBase)) {
123
+ try {
124
+ req.url = inBaseEncoded + (query === undefined ? '' : `?${query}`);
125
+ const response = await app.fetch(toRequest(req));
126
+ withRules(res, pathname);
127
+ return await sendResponse(res, response);
128
+ }
129
+ catch (err) {
130
+ console.error(err);
131
+ res.statusCode = 500;
132
+ return void res.end();
133
+ }
134
+ }
135
+ const notFound = fileFor('/404.html');
136
+ if (notFound && readable)
137
+ return sendFile(req, res, notFound, pathname, 404);
138
+ res.statusCode = 404;
139
+ res.setHeader('content-type', `text/plain; ${TEXT}`);
140
+ res.end('Not Found');
141
+ };
142
+ }
143
+ export async function serve(options = {}) {
144
+ const listener = await createListener(options.root);
145
+ const server = createServer((req, res) => void listener(req, res));
146
+ const port = options.port ?? Number(process.env.PORT ?? 3000);
147
+ const host = options.host ?? process.env.HOST ?? '0.0.0.0';
148
+ await new Promise((done, fail) => server.once('error', fail).listen(port, host, done));
149
+ return server;
150
+ }
@@ -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>;