clarusjs 0.20.0 → 0.21.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 (49) hide show
  1. package/README.md +1 -1
  2. package/dist/check/generate.js +10 -4
  3. package/dist/cli/migrate.js +33 -9
  4. package/dist/compiler/emit-client.js +4 -3
  5. package/dist/compiler/emit-server.js +3 -1
  6. package/dist/compiler/factories.d.ts +4 -2
  7. package/dist/compiler/factories.js +116 -15
  8. package/dist/compiler/html-expr.d.ts +4 -0
  9. package/dist/compiler/html-expr.js +5 -1
  10. package/dist/compiler/index.js +6 -7
  11. package/dist/compiler/ir.d.ts +2 -0
  12. package/dist/compiler/ir.js +3 -5
  13. package/dist/compiler/parse.js +33 -13
  14. package/dist/compiler/script.d.ts +5 -0
  15. package/dist/compiler/script.js +14 -2
  16. package/dist/forms/index.js +26 -5
  17. package/dist/runtime/context.d.ts +16 -8
  18. package/dist/runtime/fragments.js +6 -2
  19. package/dist/runtime/index.d.ts +1 -1
  20. package/dist/runtime/navigate.js +2 -1
  21. package/dist/runtime/signals.d.ts +11 -6
  22. package/dist/runtime/signals.js +12 -3
  23. package/dist/vite/base-clash.d.ts +9 -0
  24. package/dist/vite/base-clash.js +54 -0
  25. package/dist/vite/build-app.d.ts +5 -0
  26. package/dist/vite/build-app.js +185 -0
  27. package/dist/vite/dev-server.d.ts +5 -0
  28. package/dist/vite/dev-server.js +67 -0
  29. package/dist/vite/graph.d.ts +45 -0
  30. package/dist/vite/graph.js +125 -0
  31. package/dist/vite/hmr.d.ts +19 -0
  32. package/dist/vite/hmr.js +53 -0
  33. package/dist/vite/links.d.ts +2 -0
  34. package/dist/vite/links.js +2 -0
  35. package/dist/vite/options.d.ts +147 -0
  36. package/dist/vite/options.js +1 -0
  37. package/dist/vite/output.d.ts +25 -0
  38. package/dist/vite/output.js +49 -0
  39. package/dist/vite/plugin.d.ts +4 -150
  40. package/dist/vite/plugin.js +45 -624
  41. package/dist/vite/preview.d.ts +3 -0
  42. package/dist/vite/preview.js +100 -0
  43. package/dist/vite/server-entry.d.ts +18 -0
  44. package/dist/vite/server-entry.js +83 -0
  45. package/dist/vite/shared.d.ts +34 -0
  46. package/dist/vite/shared.js +47 -0
  47. package/dist/vite/styles.d.ts +16 -0
  48. package/dist/vite/styles.js +56 -0
  49. package/package.json +1 -1
package/README.md CHANGED
@@ -14,7 +14,7 @@ Write components in a familiar template language. clarusjs compiles them to plai
14
14
  only for the parts that are interactive. Static sites, server rendering and client apps share one component model,
15
15
  and you can always see where each line runs.
16
16
 
17
- > Status: early (`0.x`). The API will change between minor versions.
17
+ > Status: **0.x, with stable syntax.** The template syntax and the script form (`props()`, `model()`, `events()`, `context()`) are stable: changes to them are additive, or come with `clarusjs migrate` and a deprecation that lasts at least one minor version, marked **Breaking** in the changelog. Other APIs (the Vite plugin's options, runtime internals, the HTML contract) can still change between minor versions.
18
18
 
19
19
  ## Install
20
20
 
@@ -7,7 +7,7 @@ import { ClarusError } from '../compiler/errors.js';
7
7
  import { modifierError, splitEvent } from '../compiler/events.js';
8
8
  import { outerIndexIn } from '../compiler/loops.js';
9
9
  import { FOR_IMPLICIT, parse } from '../compiler/parse.js';
10
- import { checkScript, providesIn, referencesNames, scriptAnnotations, scriptTypeImports, splitImports } from '../compiler/script.js';
10
+ import { checkScript, providesIn, referencesNames, scriptAnnotations, scriptTypeImports, splitImports, usesRuntime } from '../compiler/script.js';
11
11
  const ENUMERATED = new Set(['draggable', 'spellcheck', 'translate', 'autocorrect', 'contenteditable']);
12
12
  const PROPERTY = { readonly: 'readOnly', novalidate: 'noValidate', formnovalidate: 'formNoValidate', allowfullscreen: 'allowFullscreen', playsinline: 'playsInline', nomodule: 'noModule', ismap: 'isMap' };
13
13
  function patternNames(params) {
@@ -67,6 +67,8 @@ export function generateTs(source, file, options = {}) {
67
67
  emit('declare function state<T>(value: T): T extends never[] ? any[] : T\n');
68
68
  emit('declare function derived<T>(fn: () => T): T\n');
69
69
  emit('declare function shared<T>(store: { get(): T }): T\n');
70
+ if (parsed.script && usesRuntime(parsed.script.code, [], 'effect'))
71
+ emit('declare function effect(fn: () => void | (() => void)): () => void\n');
70
72
  emit('declare function __cl_use(value: unknown): void\n');
71
73
  emit('declare const __cl_bool: boolean\n');
72
74
  const transitions = (nodes) => nodes.some((n) => {
@@ -85,8 +87,12 @@ export function generateTs(source, file, options = {}) {
85
87
  emit(`export type __cl_Style = ${text} | __cl_Style[] | { [property: string]: ${text} }\n`);
86
88
  emit(`type __cl_AttrOf<T extends string, P extends string> = P extends '...' ? { [name: string]: unknown } | null | undefined : P extends 'class' ? __cl_Class : P extends \`class.\${string}\` ? unknown : P extends 'style' ? __cl_Style : T extends keyof HTMLElementTagNameMap ? P extends keyof HTMLElementTagNameMap[T] ? (HTMLElementTagNameMap[T][P] extends boolean ? boolean | null | undefined : ${text}) : ${text} : ${text}\n`);
87
89
  emit('declare function __cl_attr<T extends string, P extends string>(value: __cl_AttrOf<T, P>): void\n');
90
+ const eventType = (type, tag) => {
91
+ const k = JSON.stringify(type), t = JSON.stringify(tag);
92
+ const el = `T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : T extends keyof SVGElementTagNameMap ? SVGElementTagNameMap[T] : HTMLElement`;
93
+ return `{ [K in ${k}]: { [T in ${t}]: (K extends keyof HTMLElementEventMap ? HTMLElementEventMap[K] : CustomEvent) & { target: any; currentTarget: ${el} } }[${t}] }[${k}]`;
94
+ };
88
95
  emit('export type __cl_El<T extends string> = T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : T extends keyof SVGElementTagNameMap ? SVGElementTagNameMap[T] : HTMLElement\n');
89
- emit('export type __cl_Event<K extends string, E = HTMLElement> = (K extends keyof HTMLElementEventMap ? HTMLElementEventMap[K] : CustomEvent) & { target: any; currentTarget: E }\n');
90
96
  for (const t of parsed.typeImports) {
91
97
  emit('import type ');
92
98
  copy(t.clause, t.clauseStart);
@@ -254,7 +260,7 @@ export function generateTs(source, file, options = {}) {
254
260
  let body = split.body;
255
261
  const moved = from.ts ? [...(from.typeImports ?? []), ...(from.typeDecls ?? [])].filter((t) => from.ts.startsWith(t.text, t.start)) : [];
256
262
  for (const [s, e] of from.factories ?? [])
257
- moved.push({ text: from.ts.slice(s, e), start: s });
263
+ moved.push({ text: (from.ts ?? from.code).slice(s, e), start: s });
258
264
  if (from.ts)
259
265
  body = body.split('').map((c, i) => (c === from.code[i] ? from.ts[i] : c)).join('');
260
266
  const cuts = [
@@ -527,7 +533,7 @@ export function generateTs(source, file, options = {}) {
527
533
  const wrong = modifierError(type, mods);
528
534
  if (wrong)
529
535
  throw new ClarusError(wrong, file, source, a.start);
530
- emit(` ;(($event: __cl_Event<${JSON.stringify(type)}, __cl_El<${JSON.stringify(node.tag.toLowerCase())}>>, $values: Record<string, any>) => { `);
536
+ emit(` ;(($event: ${eventType(type, node.tag.toLowerCase())}, $values: Record<string, any>) => { `);
531
537
  guarded();
532
538
  emit('{ ');
533
539
  copy(a.expr, at(a.expr, attrValueStart(a)));
@@ -244,6 +244,15 @@ export function migrate(source, file) {
244
244
  if (island)
245
245
  for (const d of parsed.dataImports)
246
246
  notes.push(`${file}: @import ${d.clause} from '${d.from}' kept (an island: as a script import it would ship to the browser)`);
247
+ const scriptTag = parsed.script ? source.lastIndexOf('<script', parsed.script.start) : -1;
248
+ const jsScript = !!parsed.script && !/\blang=/.test(source.slice(scriptTag, parsed.script.start)) && !parsed.types.length && !parsed.typeImports.length;
249
+ const closes = [...inputs, ...models, ...parsed.events].some((d) => d.type.includes('*/'));
250
+ if (jsScript && closes)
251
+ notes.push(`${file}: a type contains */, which would end a JSDoc comment: its <script> becomes TypeScript instead`);
252
+ const js = jsScript && !closes;
253
+ const scriptCode = parsed.script?.code ?? '';
254
+ const propsType = ['Props', 'ComponentProps', 'InputProps'].find((n) => !new RegExp(`\\b${n}\\b`).test(scriptCode)) ?? `Props${scriptCode.length}`;
255
+ const proseOf = (doc) => doc?.replace(/^\/\*\*|\*\/$/g, '').split('\n').map((l) => l.replace(/^\s*\*?\s?/, '').trim()).filter(Boolean).join(' ');
247
256
  const decl = [];
248
257
  for (const d of dataImports)
249
258
  decl.push(`import ${d.clause} from '${d.from}'`);
@@ -251,15 +260,30 @@ export function migrate(source, file) {
251
260
  decl.push(`import type ${t.clause} from '${t.from}'`);
252
261
  for (const t of parsed.types)
253
262
  decl.push(...(t.doc ? [indentDoc(t.doc, ' ')] : []), t.kind === 'interface' ? `interface ${t.name}${t.params ?? ''} ${t.type}` : `type ${t.name}${t.params ?? ''} = ${t.type}`);
254
- if (inputs.length) {
255
- const members = inputs.map((i) => `${i.doc ? ` ${indentDoc(i.doc, ' ')}\n` : ''} ${i.name}${i.default !== undefined ? '?' : ''}: ${i.type}`);
256
- const defaults = inputs.filter((i) => i.default !== undefined);
257
- decl.push(`const props = props<{\n${members.join('\n')}\n }>(${defaults.length ? `() => ({ ${defaults.map((i) => `${i.name}: ${i.default}`).join(', ')} })` : ''})`);
263
+ const defaultsOf = (list) => { const d = list.filter((i) => i.default !== undefined); return d.length ? `() => ({ ${d.map((i) => `${i.name}: ${i.default}`).join(', ')} })` : ''; };
264
+ const modelDefault = (m) => (m.default !== undefined ? `() => ${/^\{/.test(m.default) ? `(${m.default})` : m.default}` : '');
265
+ if (js) {
266
+ if (inputs.length) {
267
+ const lines = inputs.map((i) => { const d = proseOf(i.doc); return ` * @property {${i.type}} ${i.default !== undefined ? `[${i.name}]` : i.name}${d ? ` - ${d}` : ''}`; });
268
+ decl.push(`/**\n * @typedef {object} ${propsType}\n${lines.join('\n')}\n */`, `/** @type {${propsType}} */`, `const props = props(${defaultsOf(inputs)})`);
269
+ }
270
+ for (const m of models) {
271
+ const d = proseOf(m.doc);
272
+ decl.push(d ? `/**\n * ${d}\n * @type {${m.type}}\n */` : `/** @type {${m.type}} */`, `let ${m.name} = model(${modelDefault(m)})`);
273
+ }
274
+ if (parsed.events.length)
275
+ decl.push(`/** @type {{ ${parsed.events.map((e) => `${e.name}: ${e.type}`).join(', ')} }} */`, 'const emit = events()');
276
+ }
277
+ else {
278
+ if (inputs.length) {
279
+ const members = inputs.map((i) => `${i.doc ? ` ${indentDoc(i.doc, ' ')}\n` : ''} ${i.name}${i.default !== undefined ? '?' : ''}: ${i.type}`);
280
+ decl.push(`const props = props<{\n${members.join('\n')}\n }>(${defaultsOf(inputs)})`);
281
+ }
282
+ for (const m of models)
283
+ decl.push(...(m.doc ? [indentDoc(m.doc, ' ')] : []), `let ${m.name} = model<${m.type}>(${modelDefault(m)})`);
284
+ if (parsed.events.length)
285
+ decl.push(`const emit = events<{ ${parsed.events.map((e) => `${e.name}: ${e.type}`).join('; ')} }>()`);
258
286
  }
259
- for (const m of models)
260
- decl.push(...(m.doc ? [indentDoc(m.doc, ' ')] : []), `let ${m.name} = model<${m.type}>(${m.default !== undefined ? `() => ${/^\{/.test(m.default) ? `(${m.default})` : m.default}` : ''})`);
261
- if (parsed.events.length)
262
- decl.push(`const emit = events<{ ${parsed.events.map((e) => `${e.name}: ${e.type}`).join('; ')} }>()`);
263
287
  const block = decl.map((l) => ` ${l}`).join('\n');
264
288
  const names = new Set(inputs.map((i) => i.name));
265
289
  if (names.size) {
@@ -273,7 +297,7 @@ export function migrate(source, file) {
273
297
  if (parsed.script) {
274
298
  const s = parsed.script;
275
299
  const tag = source.lastIndexOf('<script', s.start);
276
- if (!/\blang=/.test(source.slice(tag, s.start))) {
300
+ if (!js && !/\blang=/.test(source.slice(tag, s.start))) {
277
301
  edits.push({ start: tag + '<script'.length, end: tag + '<script'.length, text: ' lang="ts"' });
278
302
  notes.push(`${file}: its <script> is now TypeScript: give its untyped function parameters types (clarusjs check lists them)`);
279
303
  }
@@ -1,6 +1,6 @@
1
1
  import { guardCode } from './events.js';
2
2
  import { FOR_IMPLICIT } from './parse.js';
3
- import { attrValueExpr, componentCall, htmlExpr, tagArg, walk, whichExpr, rowNames, rowParams, rowDerived } from './html-expr.js';
3
+ import { attrValue, attrValueExpr, componentCall, htmlExpr, tagArg, walk, whichExpr, rowNames, rowParams, rowDerived } from './html-expr.js';
4
4
  import { formName, rewriteClient, rewriteClientExpr, wrapExpr } from './script.js';
5
5
  import { contextLines, indentScript, inputsLine, renderName } from './shared.js';
6
6
  export function emitClient(ir, hot) {
@@ -17,6 +17,7 @@ export function emitClient(ir, hot) {
17
17
  (kinds.has('state') || kinds.has('input')) && 'state',
18
18
  kinds.has('derived') && 'derived',
19
19
  kinds.has('shared') && 'shared',
20
+ ir.effect && 'effect',
20
21
  hasHoles && 'holes as __cl_holes',
21
22
  hasHoles && 'text as __cl_text',
22
23
  ir.events.length > 0 && 'on as __cl_on',
@@ -44,7 +45,7 @@ export function emitClient(ir, hot) {
44
45
  rendersHtml && hasFors && 'forHtml as __cl_forHtml',
45
46
  hasRegions && 'regionHtml as __cl_regionHtml',
46
47
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_classValue(')) && 'classValue as __cl_classValue',
47
- all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_baseUrl(')) && 'baseUrl as __cl_baseUrl',
48
+ all.some((n) => n.kind === 'attr' && n.name !== '...' && !!n.base) && 'baseUrl as __cl_baseUrl',
48
49
  all.some((n) => n.kind === 'attr' && n.name === '...' && !!n.base) && 'baseAttrs as __cl_baseAttrs',
49
50
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_styleValue(')) && 'styleValue as __cl_styleValue',
50
51
  ].filter(Boolean);
@@ -119,7 +120,7 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
119
120
  if (a.kind === 'attr' && a.reactive && a.name === '...')
120
121
  lines.push(`__cl_spread(${ctx}, ${a.index}, () => ${a.base ? `__cl_baseAttrs(${JSON.stringify(a.base)}, ${attrValueExpr(a.value, rw.expr)})` : attrValueExpr(a.value, rw.expr)}, ${JSON.stringify(a.skip ?? [])}, ${JSON.stringify(a.tag)})`);
121
122
  else if (a.kind === 'attr' && a.reactive)
122
- lines.push(`__cl_attr(${ctx}, ${a.index}, ${JSON.stringify(a.name)}, () => ${attrValueExpr(a.value, rw.expr)}${tagArg(a)})`);
123
+ lines.push(`__cl_attr(${ctx}, ${a.index}, ${JSON.stringify(a.name)}, () => ${attrValue(a, rw.expr)}${tagArg(a)})`);
123
124
  if (a.kind === 'connect')
124
125
  lines.push(`__cl_connect(${ctx}, ${a.index}, () => ${wrapExpr(rw.expr(a.expr))})`);
125
126
  if (a.kind === 'use')
@@ -12,7 +12,7 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
12
12
  html.includes('__cl_spreadHtml(') && 'spreadHtml as __cl_spreadHtml',
13
13
  html.includes('__cl_passedHtml(') && 'passedHtml as __cl_passedHtml',
14
14
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_classValue(')) && 'classValue as __cl_classValue',
15
- all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_baseUrl(')) && 'baseUrl as __cl_baseUrl',
15
+ all.some((n) => n.kind === 'attr' && n.name !== '...' && !!n.base) && 'baseUrl as __cl_baseUrl',
16
16
  all.some((n) => n.kind === 'attr' && n.name === '...' && !!n.base) && 'baseAttrs as __cl_baseAttrs',
17
17
  all.some((n) => n.kind === 'attr' && JSON.stringify(n.value).includes('__cl_styleValue(')) && 'styleValue as __cl_styleValue',
18
18
  all.some((n) => (n.kind === 'if' || n.kind === 'await') && n.block >= 0) && 'blockHtml as __cl_blockHtml',
@@ -32,6 +32,8 @@ export function emitServer(ir, clientUrl, renderImports = false, loader) {
32
32
  out += `import ${d.clause} from '${d.from}'\n`;
33
33
  for (const line of ir.scriptImports)
34
34
  out += `${line}\n`;
35
+ if (ir.effect)
36
+ out += `import { effect } from 'clarusjs/runtime'\n`;
35
37
  for (const line of ir.server?.imports ?? [])
36
38
  out += `${line}\n`;
37
39
  const notPublic = (c) => `(() => { throw new Error("[clarusjs] <${ir.name}> is an island and reads context \\"" + ${contextName(c)} + "\\", which isn't public: its value would be written into the page. The key it's read with and the key it's provided with must both be contextKey(name, { public: true })") })()`;
@@ -32,5 +32,7 @@ export type Factories = {
32
32
  blank: [number, number][]; /** The names their arguments use at runtime (a key, a default's import): not type members. */
33
33
  refs: string[];
34
34
  };
35
- /** The factories in `code` (TypeScript, as written). */
36
- export declare function factories(code: string, js?: string): Factories;
35
+ /** The factories in `code` (TypeScript, as written; or JavaScript with JSDoc types, with `js: true`). */
36
+ export declare function factories(code: string, js?: string, options?: {
37
+ js?: boolean;
38
+ }): Factories;
@@ -25,27 +25,120 @@ function identifiers(n) {
25
25
  }
26
26
  return out;
27
27
  }
28
- export function factories(code, js = code) {
28
+ function typeAt(text, at) {
29
+ const clean = text.replace(/(\n[ \t]*)\*/g, '$1 ');
30
+ const lead = 'let _: ';
31
+ try {
32
+ const ast = TS.parse(' '.repeat(at - lead.length) + lead + clean, { ecmaVersion: 'latest', sourceType: 'module' });
33
+ return ast.body[0].declarations[0].id.typeAnnotation.typeAnnotation;
34
+ }
35
+ catch (e) {
36
+ const err = e;
37
+ throw new StripError(`this JSDoc type doesn't parse: ${err.message.replace(/\s*\(\d+:\d+\)$/, '')}`, err.pos ?? at);
38
+ }
39
+ }
40
+ function braced(text, open) {
41
+ let depth = 0;
42
+ for (let i = open; i < text.length; i++) {
43
+ if (text[i] === "'" || text[i] === '"' || text[i] === '`') {
44
+ const q = text[i];
45
+ for (i++; i < text.length && text[i] !== q; i++)
46
+ if (text[i] === '\\')
47
+ i++;
48
+ continue;
49
+ }
50
+ if (text[i] === '{')
51
+ depth++;
52
+ else if (text[i] === '}' && --depth === 0)
53
+ return text.slice(open + 1, i);
54
+ }
55
+ return undefined;
56
+ }
57
+ function prose(comment) {
58
+ const lines = comment.replace(/^\/\*\*|\*\/$/g, '').split('\n').map((l) => l.replace(/^\s*\*?\s?/, '').trim());
59
+ const text = lines.slice(0, lines.findIndex((l) => l.startsWith('@')) === -1 ? lines.length : lines.findIndex((l) => l.startsWith('@'))).filter(Boolean).join(' ');
60
+ return text ? `/** ${text} */` : undefined;
61
+ }
62
+ export function factories(code, js = code, options = {}) {
29
63
  const comments = [];
30
- const ast = TS.parse(code, { ecmaVersion: 'latest', sourceType: 'module', locations: true, onComment: (block, text, _s, end) => { if (block && text.startsWith('*'))
31
- comments.push({ text: `/*${text}*/`, end }); } });
32
- const docBefore = (start) => {
64
+ const onComment = (block, text, start, end) => { if (block && text.startsWith('*'))
65
+ comments.push({ text: `/*${text}*/`, start, end }); };
66
+ const ast = (options.js ? Parser : TS).parse(code, { ecmaVersion: 'latest', sourceType: 'module', locations: true, onComment });
67
+ const commentBefore = (start) => {
33
68
  let found;
34
69
  for (const c of comments)
35
70
  if (c.end <= start)
36
- found = /\S/.test(code.slice(c.end, start)) ? undefined : c.text;
71
+ found = /\S/.test(code.slice(c.end, start)) ? undefined : c;
37
72
  return found;
38
73
  };
74
+ const docBefore = (start) => {
75
+ const c = commentBefore(start);
76
+ return c && (options.js ? prose(c.text) : c.text);
77
+ };
78
+ const jsdocType = (stmtStart) => {
79
+ const c = commentBefore(stmtStart);
80
+ const at = c ? c.text.search(/@type\s*\{/) : -1;
81
+ if (!c || at === -1)
82
+ return undefined;
83
+ const open = c.text.indexOf('{', at);
84
+ const text = braced(c.text, open);
85
+ return text === undefined ? undefined : typeAt(text, c.start + open + 1);
86
+ };
87
+ const typedefs = new Map();
88
+ if (options.js) {
89
+ for (const c of comments) {
90
+ const at = c.text.search(/@typedef\s*\{/);
91
+ if (at === -1)
92
+ continue;
93
+ const open = c.text.indexOf('{', at);
94
+ const text = braced(c.text, open);
95
+ if (text === undefined)
96
+ continue;
97
+ const name = /^\}\s*([A-Za-z_$][\w$]*)/.exec(c.text.slice(open + text.length + 1))?.[1];
98
+ if (!name)
99
+ continue;
100
+ if (typedefs.has(name))
101
+ throw new StripError(`@typedef ${name} is declared twice in this script: give one another name`, c.start + at);
102
+ if (!/^\s*(object|Object)\s*$/.test(text)) {
103
+ typedefs.set(name, typeAt(text, c.start + open + 1));
104
+ continue;
105
+ }
106
+ const list = [];
107
+ for (const m of c.text.matchAll(/@property\s*\{/g)) {
108
+ const pOpen = c.text.indexOf('{', m.index);
109
+ const pType = braced(c.text, pOpen);
110
+ if (pType === undefined)
111
+ continue;
112
+ const after = c.text.slice(pOpen + pType.length + 2);
113
+ const p = /^(\s*)(\[)?\s*([A-Za-z_$][\w$]*)(?:\s*=[^\]]*)?\s*\]?[ \t]*(?:-\s*)?([^\n@]*)/.exec(after);
114
+ if (!p)
115
+ continue;
116
+ const keyStart = c.start + pOpen + pType.length + 2 + p[1].length + (p[2] ? after.slice(p[1].length).indexOf(p[3]) : 0);
117
+ const desc = p[4].replace(/\*\/\s*$/, '').trim();
118
+ list.push({ type: 'TSPropertySignature', start: keyStart, end: keyStart + p[3].length, key: { type: 'Identifier', name: p[3], start: keyStart, end: keyStart + p[3].length }, optional: !!p[2], computed: false, typeAnnotation: { typeAnnotation: typeAt(pType, c.start + pOpen + 1) }, doc: desc ? `/** ${desc} */` : undefined, jsdoc: true });
119
+ }
120
+ typedefs.set(name, list);
121
+ }
122
+ }
123
+ const howTo = (what) => (options.js ? `/** @type {{ name: Type }} */ above it (or the name of a @typedef in this script)` : `${what}<{ … }>(), or the name of an interface in this script`);
39
124
  const out = { inputs: [], events: [], contexts: [], blank: [], refs: [] };
40
125
  const body = ast.body;
41
126
  let seenProps = false;
42
127
  const imported = new Set(body.filter((s) => s.type === 'ImportDeclaration').flatMap((s) => s.specifiers.map((x) => x.local.name)));
43
128
  const fail = (message, at) => { throw new StripError(message, at); };
44
- const members = (t, what) => {
129
+ const members = (t, what, at = 0) => {
45
130
  if (!t)
46
- return fail(`${what}<T>() needs its type: ${what}<{ … }>(), or the name of an interface in this script`, 0);
131
+ return fail(options.js ? `${what}(): its type is the JSDoc ${howTo(what)}` : `${what}<T>() needs its type: ${howTo(what)}`, at);
47
132
  if (t.type === 'TSTypeLiteral')
48
133
  return t.members;
134
+ if (options.js && t.type === 'TSTypeReference' && t.typeName.type === 'Identifier') {
135
+ const def = typedefs.get(t.typeName.name);
136
+ if (Array.isArray(def))
137
+ return def;
138
+ if (def?.type === 'TSTypeLiteral')
139
+ return def.members;
140
+ return fail(`${what}(): the compiler reads the type's members, so ${t.typeName.name} is an object type written in the @type, or a @typedef in this script ({{ … }}, or {object} with @property lines), not imported`, t.start);
141
+ }
49
142
  if (t.type === 'TSTypeReference' && t.typeName.type === 'Identifier') {
50
143
  const generic = () => fail(`${what}<${t.typeName.name}<…>>(): a generic type isn't read (its members would name its parameters); write the members here, or declare a non-generic interface`, t.start);
51
144
  if (t.typeArguments?.params?.length || t.typeParameters?.params?.length)
@@ -65,11 +158,12 @@ export function factories(code, js = code) {
65
158
  }
66
159
  return fail(`${what}<T>(): the compiler reads T's members, so T is written here (${what}<{ … }>()) or declared in this script as an interface or object type, not imported`, t.start);
67
160
  };
161
+ const typeText = (t) => (options.js ? code.slice(t.start, t.end).replace(/(\n[ \t]*)\*/g, '$1 ') : code.slice(t.start, t.end));
68
162
  const named = (m, what) => {
69
163
  if (m.type !== 'TSPropertySignature' || m.computed || !(m.key.type === 'Identifier' || (m.key.type === 'Literal' && typeof m.key.value === 'string')))
70
164
  fail(`${what}: each member is a name and its type (name: Type)`, m.start);
71
165
  const type = m.typeAnnotation?.typeAnnotation;
72
- return { name: String(m.key.name ?? m.key.value), nameStart: m.key.start, type: type ? code.slice(type.start, type.end) : 'any', typeStart: type?.start ?? m.key.start };
166
+ return { name: String(m.key.name ?? m.key.value), nameStart: m.key.start, type: type ? typeText(type) : 'any', typeStart: type?.start ?? m.key.start };
73
167
  };
74
168
  const returned = (fn, what) => {
75
169
  if (!fn)
@@ -88,8 +182,9 @@ export function factories(code, js = code) {
88
182
  const kind = call.callee.name;
89
183
  if (stmt.declarations.length > 1)
90
184
  fail(`${kind}(): one declaration per statement`, stmt.start);
91
- const t = (call.typeArguments ?? call.typeParameters)?.params?.[0];
92
- out.blank.push([stmt.start, stmt.end]);
185
+ const t = options.js ? jsdocType(stmt.start) : (call.typeArguments ?? call.typeParameters)?.params?.[0];
186
+ const own = options.js ? commentBefore(stmt.start) : undefined;
187
+ out.blank.push([own ? own.start : stmt.start, stmt.end]);
93
188
  for (const arg of call.arguments)
94
189
  out.refs.push(...identifiers(arg));
95
190
  if (kind === 'props') {
@@ -121,7 +216,13 @@ export function factories(code, js = code) {
121
216
  }
122
217
  const order = [...bound.keys()];
123
218
  const rank = (m) => { const i = order.indexOf(named(m, 'props').name); return i === -1 ? order.length : i; };
124
- const list = [...members(t, 'props')].sort((a, b) => rank(a) - rank(b));
219
+ const untyped = options.js && !t && pattern ? [...bound].map(([name, value]) => {
220
+ const p = pattern.properties.find((x) => x.key?.name === name);
221
+ return { type: 'TSPropertySignature', start: p.start, end: p.end, key: p.key, optional: !!value || given.has(name), computed: false, jsdoc: true };
222
+ }) : undefined;
223
+ if (options.js && !t && !pattern)
224
+ fail(`props(): its type is the JSDoc ${howTo('props')}; or destructure it, const { name } = props(), and the pattern names the props`, stmt.start);
225
+ const list = [...(untyped ?? members(t, 'props', stmt.start))].sort((a, b) => rank(a) - rank(b));
125
226
  const keys = new Set(list.map((m) => named(m, 'props').name));
126
227
  for (const [name] of bound)
127
228
  if (!keys.has(name))
@@ -132,7 +233,7 @@ export function factories(code, js = code) {
132
233
  if (value && !m.optional)
133
234
  fail(`props(): "${decl.name}" is required, so it takes no default (make it optional: ${decl.name}?:)`, value.start);
134
235
  given.delete(decl.name);
135
- const doc = docBefore(m.start);
236
+ const doc = m.jsdoc ? m.doc : docBefore(m.start);
136
237
  out.inputs.push({ ...decl, start: m.start, ...(value ? { default: js.slice(value.start, value.end).trim(), defaultTs: code.slice(value.start, value.end), defaultStart: value.start } : m.optional ? { optional: true } : {}), ...(doc ? { doc } : {}) });
137
238
  }
138
239
  for (const [name, value] of given)
@@ -145,7 +246,7 @@ export function factories(code, js = code) {
145
246
  fail('model(): let name = model<Type>(() => default); the variable is the model, written to update the parent', stmt.start);
146
247
  const value = returned(call.arguments[0], 'model()');
147
248
  const doc = docBefore(stmt.start);
148
- out.inputs.push({ name: d.id.name, nameStart: d.id.start, type: t ? code.slice(t.start, t.end) : 'any', typeStart: t?.start ?? d.id.start, start: stmt.start, model: true, ...(value ? { default: js.slice(value.start, value.end).trim(), defaultTs: code.slice(value.start, value.end), defaultStart: value.start } : {}), ...(doc ? { doc } : {}) });
249
+ out.inputs.push({ name: d.id.name, nameStart: d.id.start, type: t ? typeText(t) : 'any', typeStart: t?.start ?? d.id.start, start: stmt.start, model: true, ...(value ? { default: js.slice(value.start, value.end).trim(), defaultTs: code.slice(value.start, value.end), defaultStart: value.start } : {}), ...(doc ? { doc } : {}) });
149
250
  }
150
251
  else if (kind === 'context') {
151
252
  if (stmt.kind !== 'const' || d.id.type !== 'Identifier')
@@ -159,12 +260,12 @@ export function factories(code, js = code) {
159
260
  fail("context() reads through a typed key: context(themeKey, () => fallback), with themeKey = contextKey<T>('theme', { public: true }) in a .ts module (an island's context is written into the page, so the key says it may be)", call.start);
160
261
  const value = returned(keyed ? second : first, 'context()');
161
262
  const doc = docBefore(stmt.start);
162
- out.contexts.push({ name: d.id.name, nameStart: d.id.start, type: keyed ? `__cl_ContextOf<typeof ${code.slice(first.start, first.end)}>` : t ? code.slice(t.start, t.end) : 'any', typeStart: keyed ? first.start : t?.start ?? d.id.start, start: stmt.start, ...(keyed ? { key: code.slice(first.start, first.end) } : {}), ...(value ? { default: js.slice(value.start, value.end).trim(), defaultTs: code.slice(value.start, value.end), defaultStart: value.start } : {}), ...(doc ? { doc } : {}) });
263
+ out.contexts.push({ name: d.id.name, nameStart: d.id.start, type: keyed ? `__cl_ContextOf<typeof ${code.slice(first.start, first.end)}>` : t ? typeText(t) : 'any', typeStart: keyed ? first.start : t?.start ?? d.id.start, start: stmt.start, ...(keyed ? { key: code.slice(first.start, first.end) } : {}), ...(value ? { default: js.slice(value.start, value.end).trim(), defaultTs: code.slice(value.start, value.end), defaultStart: value.start } : {}), ...(doc ? { doc } : {}) });
163
264
  }
164
265
  else {
165
266
  if (d.id.type !== 'Identifier' || d.id.name !== 'emit')
166
267
  fail('events(): const emit = events<{ name: Type }>(), then emit(\'name\', value)', d.id.start);
167
- for (const m of members(t, 'events'))
268
+ for (const m of members(t, 'events', stmt.start))
168
269
  out.events.push({ ...named(m, 'events'), start: m.start });
169
270
  }
170
271
  }
@@ -30,6 +30,10 @@ export declare function whichExpr(n: Extract<IRNode, {
30
30
  export declare function attrValueExpr(value: Extract<IRNode, {
31
31
  kind: 'attr';
32
32
  }>['value'], rewrite: (e: string) => string): string;
33
+ /** An attribute's value, through baseUrl() when it's a URL attribute under a base. */
34
+ export declare function attrValue(n: Extract<IRNode, {
35
+ kind: 'attr';
36
+ }>, rewrite: (e: string) => string): string;
33
37
  /** The element's tag, passed only for attributes whose meaning depends on it (SVG animation values). */
34
38
  export declare function tagArg(n: Extract<IRNode, {
35
39
  kind: 'attr';
@@ -22,7 +22,7 @@ export function htmlExpr(nodes, rw = asWritten, top) {
22
22
  if (n.kind === 'attr' && n.content)
23
23
  return '""';
24
24
  if (n.kind === 'attr')
25
- return `__cl_attrHtml(${JSON.stringify(n.name)}, ${attrValueExpr(n.value, rw.expr)}${tagArg(n)})`;
25
+ return `__cl_attrHtml(${JSON.stringify(n.name)}, ${attrValue(n, rw.expr)}${tagArg(n)})`;
26
26
  if (n.kind === 'if') {
27
27
  if (n.block === -1) {
28
28
  const last = n.branches[n.branches.length - 1];
@@ -91,6 +91,10 @@ export function attrValueExpr(value, rewrite) {
91
91
  return `(${rewrite(value.expr)})`;
92
92
  return `[${value.parts.map((p) => (typeof p === 'string' ? JSON.stringify(p) : `(${rewrite(p.expr)})`)).join(', ')}].join("")`;
93
93
  }
94
+ export function attrValue(n, rewrite) {
95
+ const value = attrValueExpr(n.value, rewrite);
96
+ return n.base ? `__cl_baseUrl(${JSON.stringify(n.base)}, ${JSON.stringify(n.name)}, ${value})` : value;
97
+ }
94
98
  export function tagArg(n) {
95
99
  return ['to', 'from', 'values', 'by'].includes(n.name.toLowerCase()) ? `, ${JSON.stringify(n.tag)}` : '';
96
100
  }
@@ -27,7 +27,7 @@ function compileParsed(parsed, source, options) {
27
27
  const warnings = [];
28
28
  const id = options.scope ?? scopeId(options.file);
29
29
  if (!fragmentRoot)
30
- fallThrough(parsed);
30
+ fallThrough(parsed, isIsland(parsed, options.file, source));
31
31
  foldClass(parsed.nodes, new Set(parsed.imports.map((imp) => imp.name)));
32
32
  markRoots(parsed.nodes, `cl-c-${id}`, new Set(parsed.imports.map((imp) => imp.name)), parsed.styles.some((st) => st.mode === 'scoped'));
33
33
  let css = '';
@@ -161,7 +161,7 @@ function unwrapFragments(parsed, file, source) {
161
161
  parsed.nodes = flat(parsed.nodes);
162
162
  return root;
163
163
  }
164
- function fallThrough(parsed) {
164
+ function fallThrough(parsed, island) {
165
165
  const meaningfulOf = (nodes) => nodes.filter((n) => !(n.type === 'text' && !n.value.replace(/<!--[\s\S]*?-->/g, '').trim()) && !(n.type === 'element' && UNMARKED.has(n.tag)));
166
166
  const meaningful = meaningfulOf(parsed.nodes);
167
167
  if (meaningful.length !== 1)
@@ -169,21 +169,20 @@ function fallThrough(parsed) {
169
169
  const top = meaningful[0];
170
170
  if (top.type === 'if') {
171
171
  const roots = top.branches.map((b) => meaningfulOf(b.children));
172
- if (parsed.script || parsed.inputs.some((i) => i.model) || top.branches.at(-1).cond !== null || roots.some((r) => r.length !== 1 || r[0].type !== 'element'))
172
+ if (island || top.branches.at(-1).cond !== null || roots.some((r) => r.length !== 1 || r[0].type !== 'element'))
173
173
  return;
174
174
  for (const [r] of roots)
175
- fallOnto(parsed, r);
175
+ fallOnto(parsed, r, island);
176
176
  return;
177
177
  }
178
178
  if (top.type === 'element')
179
- fallOnto(parsed, top);
179
+ fallOnto(parsed, top, island);
180
180
  }
181
- function fallOnto(parsed, root) {
181
+ function fallOnto(parsed, root, island) {
182
182
  if (SPREAD_REFUSED.has(root.tag.toLowerCase()))
183
183
  return;
184
184
  if (root.attrs.some((a) => a.kind === 'prop' && a.name === '...'))
185
185
  return;
186
- const island = !!parsed.script || parsed.inputs.some((i) => i.model);
187
186
  if (island && parsed.imports.some((i) => i.name === root.tag))
188
187
  return;
189
188
  root.attrs.push({ kind: 'prop', name: '...', expr: '__cl_attrs', start: root.start });
@@ -135,6 +135,8 @@ export type ComponentIR = {
135
135
  imports: ImportDecl[];
136
136
  script?: string;
137
137
  scriptImports: string[];
138
+ /** The script calls effect() without importing it. */
139
+ effect?: true;
138
140
  /** <script server> (#430): its hoisted imports, its body (run at the top of render), and whether it awaits. */
139
141
  server?: {
140
142
  imports: string[];
@@ -6,7 +6,7 @@ import { ClarusError } from './errors.js';
6
6
  import { outerIndexIn } from './loops.js';
7
7
  import { awaitLists, FOR_IMPLICIT, importNames } from './parse.js';
8
8
  import { baseUrl, isBaseAttr } from '../runtime/attrs.js';
9
- import { analyzeScript, hasStatements, provideGetters, providesIn, mutationsOf, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, serverScriptParts, splitImports } from './script.js';
9
+ import { analyzeScript, hasStatements, provideGetters, providesIn, mutationsOf, writesTo, checkExpr, checkHandler, referencesNames, scriptNames, serverScriptParts, splitImports, usesRuntime } from './script.js';
10
10
  const ATTACH_MODES = ['load', 'idle', 'visible', 'interaction'];
11
11
  export const SPREAD_REFUSED = new Set(['iframe', 'frame', 'embed', 'object', 'base', 'link', 'script', 'meta']);
12
12
  const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
@@ -549,11 +549,8 @@ export function lower(parsed, file, source, options = {}) {
549
549
  checkExpr(e.expr, file, source, e.start);
550
550
  const reactive = stateful && exprs.some((e) => referencesNames(e.expr, scriptScope) || referencesNames(e.expr, loopNames));
551
551
  const written = a.kind === 'prop' ? { expr: a.expr } : { parts: a.parts.map((p) => (typeof p === 'string' ? p : { expr: p.expr })) };
552
- const value = base && isBaseAttr(a.name)
553
- ? { expr: `__cl_baseUrl(${JSON.stringify(base)}, ${JSON.stringify(a.name)}, ${a.kind === 'prop' ? `(${a.expr})` : `[${a.parts.map((p) => (typeof p === 'string' ? JSON.stringify(p) : `(${p.expr})`)).join(', ')}].join('')`})` }
554
- : written;
555
552
  const content = node.tag === 'textarea' && a.name === 'value';
556
- const node_ = { kind: 'attr', name: a.name, value, reactive, index: -1, tag: node.tag, ...(content ? { content: true } : {}) };
553
+ const node_ = { kind: 'attr', name: a.name, value: written, reactive, index: -1, tag: node.tag, ...(content ? { content: true } : {}), ...(base && isBaseAttr(a.name) ? { base } : {}) };
557
554
  if (content)
558
555
  textareaValue = a.kind === 'prop' ? a.expr : `[${a.parts.map((p) => (typeof p === 'string' ? JSON.stringify(p) : `(${p.expr})`)).join(', ')}].join('')`;
559
556
  if (reactive)
@@ -611,6 +608,7 @@ export function lower(parsed, file, source, options = {}) {
611
608
  imports: parsed.imports,
612
609
  script: parsed.script ? split.body : undefined,
613
610
  scriptImports: split.imports.map((imp) => imp.text),
611
+ ...(parsed.script && usesRuntime(split.body, split.imports.map((imp) => imp.text), 'effect') ? { effect: true } : {}),
614
612
  ...(server ? { server } : {}),
615
613
  dataImports: parsed.dataImports,
616
614
  signals,
@@ -32,26 +32,46 @@ export function parse(source, file) {
32
32
  const next = /^\s*@(input|model|context|type|interface|import)\s/.exec(source.slice(close + 2));
33
33
  return next && /\n/.test(next[0]) ? { text: source.slice(at, close + 2), end: close + 2 } : undefined;
34
34
  };
35
+ const declare = (made, start) => {
36
+ for (const i of made.inputs)
37
+ out.inputs.push({ ...i, start: start + i.start, nameStart: start + i.nameStart, typeStart: start + i.typeStart, ...(i.defaultStart !== undefined ? { defaultStart: start + i.defaultStart } : {}) });
38
+ for (const c of made.contexts)
39
+ out.contexts.push({ ...c, start: start + c.start, nameStart: start + c.nameStart, typeStart: start + c.typeStart, ...(c.defaultStart !== undefined ? { defaultStart: start + c.defaultStart } : {}) });
40
+ for (const e of made.events)
41
+ out.events.push({ ...e, start: start + e.start, nameStart: start + e.nameStart, typeStart: start + e.typeStart });
42
+ if (made.props)
43
+ out.props = made.props;
44
+ };
45
+ const blanked = (code, made) => {
46
+ for (const [from, to] of made.blank)
47
+ code = code.slice(0, from) + code.slice(from, to).replace(/[^\n]/g, ' ') + code.slice(to);
48
+ return code;
49
+ };
35
50
  const script = (code, start, attrs) => {
36
51
  const lang = attrs.find((a) => a.name === 'lang');
37
- if (!lang)
38
- return { code, start };
52
+ if (!lang) {
53
+ if (!/\b(props|model|events|context)\b/.test(code))
54
+ return { code, start };
55
+ try {
56
+ const made = factories(code, code, { js: true });
57
+ if (!made.blank.length)
58
+ return { code, start };
59
+ declare(made, start);
60
+ return { code: blanked(code, made), start, factories: made.blank, factoryRefs: made.refs };
61
+ }
62
+ catch (e) {
63
+ if (e instanceof StripError)
64
+ fail(e.message, start + e.pos);
65
+ return { code, start };
66
+ }
67
+ }
39
68
  if (lang.kind !== 'static' || !['ts', 'typescript'].includes(String(lang.value)))
40
69
  fail('<script lang> takes "ts"', lang.start);
41
70
  try {
42
71
  const js = stripTypes(code);
43
72
  const made = factories(code, js.code);
44
- let jsCode = js.code;
45
- for (const [from, to] of made.blank)
46
- jsCode = jsCode.slice(0, from) + jsCode.slice(from, to).replace(/[^\n]/g, ' ') + jsCode.slice(to);
47
- for (const i of made.inputs)
48
- out.inputs.push({ ...i, start: start + i.start, nameStart: start + i.nameStart, typeStart: start + i.typeStart, ...(i.defaultStart !== undefined ? { defaultStart: start + i.defaultStart } : {}) });
49
- for (const c of made.contexts)
50
- out.contexts.push({ ...c, start: start + c.start, nameStart: start + c.nameStart, typeStart: start + c.typeStart, ...(c.defaultStart !== undefined ? { defaultStart: start + c.defaultStart } : {}) });
51
- for (const e of made.events)
52
- out.events.push({ ...e, start: start + e.start, nameStart: start + e.nameStart, typeStart: start + e.typeStart });
53
- if (made.props)
54
- out.props = made.props;
73
+ const jsCode = blanked(js.code, made);
74
+ declare(made, start);
55
75
  return { code: jsCode, start, ts: code, typeImports: js.typeImports, typeDecls: js.typeDecls, ...(js.stayingExports.length ? { stayingExports: js.stayingExports } : {}), ...(made.blank.length ? { factories: made.blank, factoryRefs: made.refs } : {}) };
56
76
  }
57
77
  catch (e) {
@@ -9,6 +9,11 @@ export declare function checkHandler(code: string, file: string, source: string,
9
9
  export declare function templateRanges(code: string): [number, number][];
10
10
  /** Parenthesize expressions whose meaning changes when inlined as an argument or arrow body (`a, b`, `{ … }`). */
11
11
  export declare function wrapExpr(expr: string): string;
12
+ /**
13
+ * Whether a script calls a runtime function it didn't import or declare at its top level: effect(), which (like
14
+ * state() and derived()) a script uses without importing. `imports` are the script's import statements.
15
+ */
16
+ export declare function usesRuntime(code: string, imports: readonly string[], name: string): boolean;
12
17
  /** Names declared at the top level of <script>: variables, functions, classes. */
13
18
  export declare function scriptNames(code: string): Set<string>;
14
19
  /**