clarusjs 0.19.1 → 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 (63) hide show
  1. package/README.md +1 -1
  2. package/dist/check/generate.js +124 -25
  3. package/dist/cli/index.js +17 -0
  4. package/dist/cli/migrate-files.d.ts +5 -0
  5. package/dist/cli/migrate-files.js +22 -0
  6. package/dist/cli/migrate.d.ts +8 -0
  7. package/dist/cli/migrate.js +317 -0
  8. package/dist/compiler/emit-client.js +7 -4
  9. package/dist/compiler/emit-server.js +10 -3
  10. package/dist/compiler/factories.d.ts +38 -0
  11. package/dist/compiler/factories.js +273 -0
  12. package/dist/compiler/html-expr.d.ts +4 -0
  13. package/dist/compiler/html-expr.js +5 -1
  14. package/dist/compiler/index.js +8 -9
  15. package/dist/compiler/ir.d.ts +13 -0
  16. package/dist/compiler/ir.js +41 -12
  17. package/dist/compiler/jsdoc.d.ts +15 -0
  18. package/dist/compiler/jsdoc.js +81 -0
  19. package/dist/compiler/lint.js +9 -4
  20. package/dist/compiler/parse.d.ts +35 -9
  21. package/dist/compiler/parse.js +77 -8
  22. package/dist/compiler/script.d.ts +15 -5
  23. package/dist/compiler/script.js +112 -18
  24. package/dist/compiler/shared.d.ts +5 -0
  25. package/dist/compiler/shared.js +5 -3
  26. package/dist/compiler/strip-types.d.ts +20 -0
  27. package/dist/compiler/strip-types.js +148 -0
  28. package/dist/forms/index.js +26 -5
  29. package/dist/runtime/context.d.ts +39 -0
  30. package/dist/runtime/context.js +4 -0
  31. package/dist/runtime/fragments.js +6 -2
  32. package/dist/runtime/index.d.ts +1 -0
  33. package/dist/runtime/index.js +1 -0
  34. package/dist/runtime/navigate.js +2 -1
  35. package/dist/runtime/signals.d.ts +11 -6
  36. package/dist/runtime/signals.js +12 -3
  37. package/dist/vite/base-clash.d.ts +9 -0
  38. package/dist/vite/base-clash.js +54 -0
  39. package/dist/vite/build-app.d.ts +5 -0
  40. package/dist/vite/build-app.js +185 -0
  41. package/dist/vite/dev-server.d.ts +5 -0
  42. package/dist/vite/dev-server.js +67 -0
  43. package/dist/vite/graph.d.ts +45 -0
  44. package/dist/vite/graph.js +125 -0
  45. package/dist/vite/hmr.d.ts +19 -0
  46. package/dist/vite/hmr.js +53 -0
  47. package/dist/vite/links.d.ts +2 -0
  48. package/dist/vite/links.js +2 -0
  49. package/dist/vite/options.d.ts +147 -0
  50. package/dist/vite/options.js +1 -0
  51. package/dist/vite/output.d.ts +25 -0
  52. package/dist/vite/output.js +49 -0
  53. package/dist/vite/plugin.d.ts +4 -150
  54. package/dist/vite/plugin.js +68 -624
  55. package/dist/vite/preview.d.ts +3 -0
  56. package/dist/vite/preview.js +100 -0
  57. package/dist/vite/server-entry.d.ts +18 -0
  58. package/dist/vite/server-entry.js +83 -0
  59. package/dist/vite/shared.d.ts +34 -0
  60. package/dist/vite/shared.js +47 -0
  61. package/dist/vite/styles.d.ts +16 -0
  62. package/dist/vite/styles.js +56 -0
  63. package/package.json +6 -4
@@ -0,0 +1,273 @@
1
+ import { Parser } from 'acorn';
2
+ import { tsPlugin } from '@sveltejs/acorn-typescript';
3
+ import { StripError } from './strip-types.js';
4
+ const TS = Parser.extend(tsPlugin());
5
+ function identifiers(n) {
6
+ if (!n || typeof n !== 'object' || typeof n.type !== 'string')
7
+ return [];
8
+ if (['TSAsExpression', 'TSSatisfiesExpression', 'TSNonNullExpression', 'TSTypeAssertion'].includes(n.type))
9
+ return identifiers(n.expression);
10
+ if (n.type.startsWith('TS'))
11
+ return [];
12
+ if (n.type === 'Identifier')
13
+ return [n.name];
14
+ const out = [];
15
+ for (const [k, v] of Object.entries(n)) {
16
+ if (k === 'loc' || k === 'typeAnnotation' || k === 'typeArguments' || k === 'typeParameters' || k === 'returnType')
17
+ continue;
18
+ if (n.type === 'MemberExpression' && k === 'property' && !n.computed)
19
+ continue;
20
+ if (n.type === 'Property' && k === 'key' && !n.computed)
21
+ continue;
22
+ for (const c of Array.isArray(v) ? v : [v])
23
+ if (c && typeof c === 'object')
24
+ out.push(...identifiers(c));
25
+ }
26
+ return out;
27
+ }
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 = {}) {
63
+ const comments = [];
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) => {
68
+ let found;
69
+ for (const c of comments)
70
+ if (c.end <= start)
71
+ found = /\S/.test(code.slice(c.end, start)) ? undefined : c;
72
+ return found;
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`);
124
+ const out = { inputs: [], events: [], contexts: [], blank: [], refs: [] };
125
+ const body = ast.body;
126
+ let seenProps = false;
127
+ const imported = new Set(body.filter((s) => s.type === 'ImportDeclaration').flatMap((s) => s.specifiers.map((x) => x.local.name)));
128
+ const fail = (message, at) => { throw new StripError(message, at); };
129
+ const members = (t, what, at = 0) => {
130
+ if (!t)
131
+ return fail(options.js ? `${what}(): its type is the JSDoc ${howTo(what)}` : `${what}<T>() needs its type: ${howTo(what)}`, at);
132
+ if (t.type === 'TSTypeLiteral')
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
+ }
142
+ if (t.type === 'TSTypeReference' && t.typeName.type === 'Identifier') {
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);
144
+ if (t.typeArguments?.params?.length || t.typeParameters?.params?.length)
145
+ generic();
146
+ for (const s of body) {
147
+ const d = s.type === 'ExportNamedDeclaration' && s.declaration ? s.declaration : s;
148
+ if ((d.type === 'TSInterfaceDeclaration' || d.type === 'TSTypeAliasDeclaration') && d.id.name === t.typeName.name && d.typeParameters?.params?.length)
149
+ generic();
150
+ if (d.type === 'TSInterfaceDeclaration' && d.id.name === t.typeName.name) {
151
+ if (d.extends?.length)
152
+ fail(`${what}<${d.id.name}>(): an interface that extends another isn't read (write its members here)`, d.start);
153
+ return d.body.body;
154
+ }
155
+ if (d.type === 'TSTypeAliasDeclaration' && d.id.name === t.typeName.name && d.typeAnnotation.type === 'TSTypeLiteral')
156
+ return d.typeAnnotation.members;
157
+ }
158
+ }
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);
160
+ };
161
+ const typeText = (t) => (options.js ? code.slice(t.start, t.end).replace(/(\n[ \t]*)\*/g, '$1 ') : code.slice(t.start, t.end));
162
+ const named = (m, what) => {
163
+ if (m.type !== 'TSPropertySignature' || m.computed || !(m.key.type === 'Identifier' || (m.key.type === 'Literal' && typeof m.key.value === 'string')))
164
+ fail(`${what}: each member is a name and its type (name: Type)`, m.start);
165
+ const type = m.typeAnnotation?.typeAnnotation;
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 };
167
+ };
168
+ const returned = (fn, what) => {
169
+ if (!fn)
170
+ return undefined;
171
+ if (fn.type !== 'ArrowFunctionExpression' || fn.params.length || fn.body.type === 'BlockStatement')
172
+ fail(`${what}: the default is a function returning it, () => value`, fn.start);
173
+ return fn.body;
174
+ };
175
+ for (const stmt of body) {
176
+ if (stmt.type !== 'VariableDeclaration')
177
+ continue;
178
+ const d = stmt.declarations[0];
179
+ const call = d?.init;
180
+ if (!call || call.type !== 'CallExpression' || call.callee.type !== 'Identifier' || !['props', 'model', 'events', 'context'].includes(call.callee.name))
181
+ continue;
182
+ const kind = call.callee.name;
183
+ if (stmt.declarations.length > 1)
184
+ fail(`${kind}(): one declaration per statement`, stmt.start);
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]);
188
+ for (const arg of call.arguments)
189
+ out.refs.push(...identifiers(arg));
190
+ if (kind === 'props') {
191
+ const pattern = d.id.type === 'ObjectPattern' ? d.id : undefined;
192
+ if (d.id.type !== 'Identifier' && !pattern)
193
+ fail('props(): const props = props<Props>(…) and read props.name, or const { name } = props<Props>(…)', d.id.start);
194
+ if (seenProps)
195
+ fail('props(): one per component', stmt.start);
196
+ seenProps = true;
197
+ const defaults = returned(call.arguments[0], 'props()');
198
+ if (defaults && defaults.type !== 'ObjectExpression')
199
+ fail('props(): the defaults are an object, () => ({ name: value })', defaults.start);
200
+ const given = new Map();
201
+ for (const p of (defaults?.properties ?? [])) {
202
+ if (p.type !== 'Property' || p.computed || p.key.type !== 'Identifier')
203
+ fail('props(): each default is name: value', p.start);
204
+ given.set(p.key.name, p.value);
205
+ }
206
+ const bound = new Map();
207
+ for (const p of (pattern?.properties ?? [])) {
208
+ if (p.type === 'RestElement')
209
+ fail('props(): a ...rest element isn\'t supported: name each prop, or read props.name from const props = props<T>()', p.start);
210
+ const local = p.value.type === 'AssignmentPattern' ? p.value.left : p.value;
211
+ if (p.computed || p.key.type !== 'Identifier' || local.type !== 'Identifier' || local.name !== p.key.name)
212
+ fail(`props(): a prop is read by its own name; renaming it (${code.slice(p.start, p.end)}) isn't supported`, p.start);
213
+ if (p.value.type === 'AssignmentPattern' && given.has(p.key.name))
214
+ fail(`props(): "${p.key.name}" has a default twice (in the pattern and in the callback): keep one`, p.value.right.start);
215
+ bound.set(p.key.name, p.value.type === 'AssignmentPattern' ? p.value.right : undefined);
216
+ }
217
+ const order = [...bound.keys()];
218
+ const rank = (m) => { const i = order.indexOf(named(m, 'props').name); return i === -1 ? order.length : i; };
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));
226
+ const keys = new Set(list.map((m) => named(m, 'props').name));
227
+ for (const [name] of bound)
228
+ if (!keys.has(name))
229
+ fail(`props(): "${name}" isn't a prop`, pattern.properties.find((p) => p.key?.name === name).start);
230
+ for (const m of list) {
231
+ const decl = named(m, 'props');
232
+ const value = given.get(decl.name) ?? bound.get(decl.name);
233
+ if (value && !m.optional)
234
+ fail(`props(): "${decl.name}" is required, so it takes no default (make it optional: ${decl.name}?:)`, value.start);
235
+ given.delete(decl.name);
236
+ const doc = m.jsdoc ? m.doc : docBefore(m.start);
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 } : {}) });
238
+ }
239
+ for (const [name, value] of given)
240
+ fail(`props(): "${name}" isn't a prop`, value.start);
241
+ if (!pattern)
242
+ out.props = { name: d.id.name, keys: [...keys] };
243
+ }
244
+ else if (kind === 'model') {
245
+ if (stmt.kind !== 'let' || d.id.type !== 'Identifier')
246
+ fail('model(): let name = model<Type>(() => default); the variable is the model, written to update the parent', stmt.start);
247
+ const value = returned(call.arguments[0], 'model()');
248
+ const doc = docBefore(stmt.start);
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 } : {}) });
250
+ }
251
+ else if (kind === 'context') {
252
+ if (stmt.kind !== 'const' || d.id.type !== 'Identifier')
253
+ fail('context(): const name = context<Type>(() => fallback), or context(key, () => fallback)', stmt.start);
254
+ const [first, second] = call.arguments;
255
+ const keyed = first && (first.type === 'Identifier' || first.type === 'MemberExpression');
256
+ const root = (n) => (n.type !== 'MemberExpression' ? n : n.computed && !(n.property.type === 'Literal' && typeof n.property.value === 'string') ? undefined : root(n.object));
257
+ if (keyed && !imported.has(root(first)?.name))
258
+ fail(`context(${code.slice(first.start, first.end)}): the key is imported from a .ts module (it's read before this script runs), e.g. import { themeKey } from './context.ts'`, first.start);
259
+ if (!keyed)
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);
261
+ const value = returned(keyed ? second : first, 'context()');
262
+ const doc = docBefore(stmt.start);
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 } : {}) });
264
+ }
265
+ else {
266
+ if (d.id.type !== 'Identifier' || d.id.name !== 'emit')
267
+ fail('events(): const emit = events<{ name: Type }>(), then emit(\'name\', value)', d.id.start);
268
+ for (const m of members(t, 'events', stmt.start))
269
+ out.events.push({ ...named(m, 'events'), start: m.start });
270
+ }
271
+ }
272
+ return out;
273
+ }
@@ -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
  }
@@ -1,7 +1,7 @@
1
1
  import { emitClient } from './emit-client.js';
2
2
  import { ClarusError } from './errors.js';
3
3
  import { emitServer } from './emit-server.js';
4
- import { lower, SPREAD_REFUSED } from './ir.js';
4
+ import { isIsland, lower, SPREAD_REFUSED } from './ir.js';
5
5
  import { autoImport } from './components.js';
6
6
  import { ELEMENT_ATTRS } from './element-attrs.js';
7
7
  import { awaitLists, fragmentRoot, parse, rootNodes } from './parse.js';
@@ -13,7 +13,7 @@ export { checkIcons } from './icon.js';
13
13
  export { applyFixes, lint, lintRules } from './lint.js';
14
14
  export function compile(source, options) {
15
15
  const parsed = parse(source, options.file);
16
- if (options.layouts?.length && parsed.layout !== 'none' && (parsed.script || parsed.inputs.some((i) => i.model)))
16
+ if (options.layouts?.length && parsed.layout !== 'none' && isIsland(parsed, options.file, source))
17
17
  return compileIslandPage(parsed, source, options);
18
18
  return compileParsed(parsed, source, options);
19
19
  }
@@ -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 });
@@ -125,11 +125,18 @@ export type ComponentIR = {
125
125
  file: string;
126
126
  name: string;
127
127
  inputs: InputDecl[];
128
+ /** props<T>() in the script: the object it's read through (props.name) and its keys. */
129
+ props?: {
130
+ name: string;
131
+ keys: string[];
132
+ };
128
133
  /** `@extends tag`: the attribute names passed through to the root besides the usual ones. */
129
134
  extends?: string[];
130
135
  imports: ImportDecl[];
131
136
  script?: string;
132
137
  scriptImports: string[];
138
+ /** The script calls effect() without importing it. */
139
+ effect?: true;
133
140
  /** <script server> (#430): its hoisted imports, its body (run at the top of render), and whether it awaits. */
134
141
  server?: {
135
142
  imports: string[];
@@ -153,6 +160,12 @@ export type ComponentIR = {
153
160
  warnings: ClarusError[];
154
161
  };
155
162
  export declare const SPREAD_REFUSED: Set<string>;
163
+ /** A template that does something in the browser: an event or two-way binding, [use], [engine], or a transition. */
164
+ /**
165
+ * An island: a script with code (more than imports, and the types and props()/context() declarations that are spaces
166
+ * by now), events it sends, browser work in its template, or a @model input (which it writes, even from a handler alone).
167
+ */
168
+ export declare function isIsland(parsed: ParsedFile, file: string, source: string): boolean;
156
169
  export declare function lower(parsed: ParsedFile, file: string, source: string, options?: {
157
170
  collapseWhitespace?: boolean;
158
171
  icon?: IconResolver;
@@ -4,12 +4,37 @@ import { parseExpressionAt } from 'acorn';
4
4
  import { iconElement } from './icon.js';
5
5
  import { ClarusError } from './errors.js';
6
6
  import { outerIndexIn } from './loops.js';
7
- import { FOR_IMPLICIT, importNames } from './parse.js';
7
+ import { awaitLists, FOR_IMPLICIT, importNames } from './parse.js';
8
8
  import { baseUrl, isBaseAttr } from '../runtime/attrs.js';
9
- import { analyzeScript, 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']);
13
+ export function isIsland(parsed, file, source) {
14
+ const body = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start).body : '';
15
+ return (!!parsed.script && (hasStatements(body) || parsed.events.length > 0 || needsBrowser(parsed.nodes))) || parsed.inputs.some((i) => i.model);
16
+ }
17
+ function needsBrowser(nodes) {
18
+ return nodes.some((n) => {
19
+ const kids = [];
20
+ if ('transition' in n && n.transition)
21
+ return true;
22
+ if (n.type === 'element') {
23
+ if (n.attrs.some((a) => a.kind === 'event' || a.kind === 'model' || (a.kind === 'prop' && (a.name === 'use' || a.name === 'engine'))))
24
+ return true;
25
+ kids.push(n.children);
26
+ }
27
+ else if (n.type === 'if')
28
+ kids.push(...n.branches.map((b) => b.children));
29
+ else if (n.type === 'for')
30
+ kids.push(n.children, ...(n.empty ? [n.empty] : []));
31
+ else if (n.type === 'await')
32
+ kids.push(...awaitLists(n));
33
+ else if (n.type === 'fill')
34
+ kids.push(n.children);
35
+ return kids.some(needsBrowser);
36
+ });
37
+ }
13
38
  const iconBodies = new WeakMap();
14
39
  export function lower(parsed, file, source, options = {}) {
15
40
  const base = options.base && options.base !== '/' ? options.base : undefined;
@@ -17,11 +42,14 @@ export function lower(parsed, file, source, options = {}) {
17
42
  const outer = outerIndexIn(parsed.nodes);
18
43
  if (outer)
19
44
  fail(outer.message, outer.start);
20
- let stateful = !!parsed.script || parsed.inputs.some((i) => i.model);
45
+ const split = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : { imports: [], body: '' };
46
+ let stateful = isIsland(parsed, file, source);
21
47
  if (parsed.events.length && !parsed.script)
22
48
  fail('@event needs a <script> that sends it with emit(\'name\', value)', parsed.events[0].start);
23
- if (parsed.contexts.length && stateful)
24
- fail('@context is only for components without <script> or @model for now: an island has no context in the browser. Read it in a component without a script, or pass it in as a prop', parsed.contexts[0].start);
49
+ if (stateful)
50
+ for (const c of parsed.contexts)
51
+ if (!c.key)
52
+ fail(`context "${c.name}" is read in an island (a component with a <script> or @model), where its value is written into the page: read it through a typed key made public for that, contextKey<T>('${c.name}', { public: true }), or read it in a component without a script`, c.start);
25
53
  for (const c of parsed.contexts)
26
54
  if (parsed.inputs.some((i) => i.name === c.name))
27
55
  fail(`"${c.name}" is already an @input`, c.nameStart);
@@ -31,10 +59,12 @@ export function lower(parsed, file, source, options = {}) {
31
59
  fail('<script server> runs on the server only, and this component is an island (it has a <script> or a @model input): load the data in a parent, or in a page\'s <script server>, and pass it to the island as props', ss.tag);
32
60
  const server = ss ? serverScriptParts(ss.code, file, source, ss.start) : undefined;
33
61
  const modelNames = new Set(parsed.inputs.filter((i) => i.model).map((i) => i.name));
34
- const split = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : { imports: [], body: '' };
35
62
  const signals = parsed.script ? analyzeScript(split.body, file, source, parsed.script.start) : new Map();
36
- const provides = parsed.script ? providesIn(split, file, source, parsed.script.start) : false;
37
- const scriptScope = parsed.script ? new Set([...signals.keys(), ...scriptNames(parsed.script.code)]) : new Set();
63
+ const serverProvides = ss ? providesIn(splitImports(ss.code, file, source, ss.start, true), file, source, ss.start) : false;
64
+ if (server && serverProvides)
65
+ server.body = provideGetters(server.body);
66
+ const provides = (parsed.script ? providesIn(split, file, source, parsed.script.start) : false) || serverProvides;
67
+ const scriptScope = parsed.script ? new Set([...signals.keys(), ...scriptNames(parsed.script.code), ...(parsed.props ? [parsed.props.name] : [])]) : new Set();
38
68
  const inputNames = new Set(stateful ? parsed.inputs.filter((i) => !i.model).map((i) => i.name).filter((name) => !signals.has(name)) : []);
39
69
  for (const name of inputNames) {
40
70
  signals.set(name, 'input');
@@ -519,11 +549,8 @@ export function lower(parsed, file, source, options = {}) {
519
549
  checkExpr(e.expr, file, source, e.start);
520
550
  const reactive = stateful && exprs.some((e) => referencesNames(e.expr, scriptScope) || referencesNames(e.expr, loopNames));
521
551
  const written = a.kind === 'prop' ? { expr: a.expr } : { parts: a.parts.map((p) => (typeof p === 'string' ? p : { expr: p.expr })) };
522
- const value = base && isBaseAttr(a.name)
523
- ? { 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('')`})` }
524
- : written;
525
552
  const content = node.tag === 'textarea' && a.name === 'value';
526
- 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 } : {}) };
527
554
  if (content)
528
555
  textareaValue = a.kind === 'prop' ? a.expr : `[${a.parts.map((p) => (typeof p === 'string' ? JSON.stringify(p) : `(${p.expr})`)).join(', ')}].join('')`;
529
556
  if (reactive)
@@ -576,10 +603,12 @@ export function lower(parsed, file, source, options = {}) {
576
603
  file,
577
604
  name: file.split('/').pop().replace(/\.tscl$/, ''),
578
605
  inputs: parsed.inputs,
606
+ ...(parsed.props ? { props: parsed.props } : {}),
579
607
  ...(parsed.extends ? { extends: Object.keys(extendedAttrs(parsed.extends.tag)) } : {}),
580
608
  imports: parsed.imports,
581
609
  script: parsed.script ? split.body : undefined,
582
610
  scriptImports: split.imports.map((imp) => imp.text),
611
+ ...(parsed.script && usesRuntime(split.body, split.imports.map((imp) => imp.text), 'effect') ? { effect: true } : {}),
583
612
  ...(server ? { server } : {}),
584
613
  dataImports: parsed.dataImports,
585
614
  signals,
@@ -0,0 +1,15 @@
1
+ /** A JSDoc type as TypeScript (`*`, `?T`, `Array.<T>`). ponytail: Closure's `function(a): b` and `!T` stay as written. */
2
+ export declare function tsType(type: string): string;
3
+ type Tag = {
4
+ tag: string;
5
+ type?: string;
6
+ name?: string;
7
+ optional?: boolean;
8
+ };
9
+ /** A doc comment's tags: {type}, then a name (`[name]`: optional). */
10
+ export declare function tags(comment: string): Tag[];
11
+ /** `@typedef` (with `@property`) → `type Name = …;`. */
12
+ export declare function typedefs(comment: string): string;
13
+ /** `@import { A } from './x'` → `import type { A } from "./x"`, for the file's top (generics keep their parameters). */
14
+ export declare function jsdocImports(comment: string): string[];
15
+ export {};
@@ -0,0 +1,81 @@
1
+ function braced(text, from) {
2
+ const open = text.indexOf('{', from);
3
+ if (open === -1 || /\S/.test(text.slice(from, open)))
4
+ return undefined;
5
+ let depth = 0;
6
+ for (let i = open; i < text.length; i++) {
7
+ const q = text[i];
8
+ if (q === "'" || q === '"' || q === '`') {
9
+ const close = text.indexOf(q, i + 1);
10
+ if (close !== -1) {
11
+ i = close;
12
+ continue;
13
+ }
14
+ }
15
+ if (text[i] === '{')
16
+ depth++;
17
+ else if (text[i] === '}' && --depth === 0)
18
+ return { type: text.slice(open + 1, i).replace(/^\s*\*\s?/gm, ' ').trim(), end: i + 1 };
19
+ }
20
+ return undefined;
21
+ }
22
+ export function tsType(type) {
23
+ let t = type.trim();
24
+ if (t === '*' || t === '?')
25
+ return 'any';
26
+ if (t.startsWith('?'))
27
+ return `(${tsType(t.slice(1))}) | null`;
28
+ t = t.replace(/\bArray\.</g, 'Array<').replace(/\bObject\.</g, 'Record<');
29
+ return t;
30
+ }
31
+ export function tags(comment) {
32
+ const out = [];
33
+ for (const m of comment.matchAll(/@([a-zA-Z]+)/g)) {
34
+ const tag = { tag: m[1] };
35
+ let at = m.index + m[0].length;
36
+ const b = braced(comment, at);
37
+ if (b) {
38
+ tag.type = tsType(b.type);
39
+ at = b.end;
40
+ }
41
+ const name = /^\s+(\[\s*([\w$.]+)(?:\s*=[^\]]*)?\]|[\w$.]+)/.exec(comment.slice(at));
42
+ if (name) {
43
+ tag.optional = name[1].startsWith('[');
44
+ tag.name = name[2] ?? name[1];
45
+ }
46
+ out.push(tag);
47
+ }
48
+ return out;
49
+ }
50
+ export function typedefs(comment) {
51
+ const all = tags(comment);
52
+ return all.map((t, i) => {
53
+ if (t.tag !== 'typedef' || !t.name)
54
+ return '';
55
+ let type = t.type ?? 'any';
56
+ const root = { type, members: new Map() };
57
+ for (const p of all.slice(i + 1)) {
58
+ if (p.tag === 'typedef')
59
+ break;
60
+ if ((p.tag !== 'property' && p.tag !== 'prop') || !p.name || !p.type)
61
+ continue;
62
+ let at = root;
63
+ const path = p.name.split('.');
64
+ for (const [k, key] of path.entries()) {
65
+ if (!at.members.has(key))
66
+ at.members.set(key, { type: 'Object', members: new Map() });
67
+ at = at.members.get(key);
68
+ if (k === path.length - 1)
69
+ Object.assign(at, { type: p.type, optional: p.optional });
70
+ }
71
+ }
72
+ const print = (m) => (m.members.size && /^(Object|object)$/.test(m.type)
73
+ ? `{ ${[...m.members].map(([k, v]) => `${k}${v.optional ? '?' : ''}: ${print(v)}`).join('; ')} }`
74
+ : m.type);
75
+ type = print(root);
76
+ return `type ${t.name} = ${type};`;
77
+ }).join(' ');
78
+ }
79
+ export function jsdocImports(comment) {
80
+ return [...comment.matchAll(/@import\s+(\{[^}]*\}|\*\s+as\s+[\w$]+|[\w$]+)\s+from\s+(['"])(.+?)\2/g)].map((m) => `import type ${m[1].trim()} from ${JSON.stringify(m[3])}`);
81
+ }
@@ -224,10 +224,15 @@ export const lintRules = [
224
224
  },
225
225
  {
226
226
  name: 'unused-input',
227
- check({ parsed, reads, report }) {
228
- for (const i of parsed.inputs)
229
- if (!reads(i.name))
230
- report(i.start, `@${i.model ? 'model' : 'input'} ${i.name} is never used`);
227
+ check({ parsed, source, reads, report }) {
228
+ const via = parsed.props;
229
+ const whole = via && new RegExp(`\\b${via.name}\\b(?!\\s*\\??\\.)`).test(source.replace(/\b(const|let|var)\s+\w+\s*=\s*props\s*</, ''));
230
+ const viaProps = (name) => !!via && via.keys.includes(name) && (whole || new RegExp(`\\b${via.name}\\s*\\??\\.\\s*${name}\\b`).test(source));
231
+ for (const i of parsed.inputs) {
232
+ if (reads(i.name) || viaProps(i.name))
233
+ continue;
234
+ report(i.start, `${i.model ? '@model' : via?.keys.includes(i.name) ? 'prop' : '@input'} ${i.name} is never used`);
235
+ }
231
236
  },
232
237
  },
233
238
  {