clarusjs 0.19.1 → 0.20.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.
- package/dist/check/generate.js +116 -23
- package/dist/cli/index.js +17 -0
- package/dist/cli/migrate-files.d.ts +5 -0
- package/dist/cli/migrate-files.js +22 -0
- package/dist/cli/migrate.d.ts +8 -0
- package/dist/cli/migrate.js +293 -0
- package/dist/compiler/emit-client.js +3 -1
- package/dist/compiler/emit-server.js +7 -2
- package/dist/compiler/factories.d.ts +36 -0
- package/dist/compiler/factories.js +172 -0
- package/dist/compiler/index.js +2 -2
- package/dist/compiler/ir.d.ts +11 -0
- package/dist/compiler/ir.js +39 -8
- package/dist/compiler/jsdoc.d.ts +15 -0
- package/dist/compiler/jsdoc.js +81 -0
- package/dist/compiler/lint.js +9 -4
- package/dist/compiler/parse.d.ts +35 -9
- package/dist/compiler/parse.js +57 -8
- package/dist/compiler/script.d.ts +10 -5
- package/dist/compiler/script.js +98 -16
- package/dist/compiler/shared.d.ts +5 -0
- package/dist/compiler/shared.js +5 -3
- package/dist/compiler/strip-types.d.ts +20 -0
- package/dist/compiler/strip-types.js +148 -0
- package/dist/runtime/context.d.ts +31 -0
- package/dist/runtime/context.js +4 -0
- package/dist/runtime/index.d.ts +1 -0
- package/dist/runtime/index.js +1 -0
- package/dist/vite/plugin.js +28 -5
- package/package.json +6 -4
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export type FactoryInput = {
|
|
2
|
+
name: string;
|
|
3
|
+
type: string;
|
|
4
|
+
nameStart: number;
|
|
5
|
+
typeStart: number;
|
|
6
|
+
default?: string; /** The default as written (TypeScript), for type checking. */
|
|
7
|
+
defaultTs?: string;
|
|
8
|
+
defaultStart?: number;
|
|
9
|
+
model?: true;
|
|
10
|
+
optional?: true;
|
|
11
|
+
doc?: string;
|
|
12
|
+
start: number;
|
|
13
|
+
};
|
|
14
|
+
export type FactoryEvent = {
|
|
15
|
+
name: string;
|
|
16
|
+
type: string;
|
|
17
|
+
nameStart: number;
|
|
18
|
+
typeStart: number;
|
|
19
|
+
start: number;
|
|
20
|
+
};
|
|
21
|
+
export type FactoryContext = Omit<FactoryInput, 'model'> & {
|
|
22
|
+
key?: string;
|
|
23
|
+
};
|
|
24
|
+
export type Factories = {
|
|
25
|
+
inputs: FactoryInput[];
|
|
26
|
+
events: FactoryEvent[];
|
|
27
|
+
contexts: FactoryContext[];
|
|
28
|
+
props?: {
|
|
29
|
+
name: string;
|
|
30
|
+
keys: string[];
|
|
31
|
+
};
|
|
32
|
+
blank: [number, number][]; /** The names their arguments use at runtime (a key, a default's import): not type members. */
|
|
33
|
+
refs: string[];
|
|
34
|
+
};
|
|
35
|
+
/** The factories in `code` (TypeScript, as written). */
|
|
36
|
+
export declare function factories(code: string, js?: string): Factories;
|
|
@@ -0,0 +1,172 @@
|
|
|
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
|
+
export function factories(code, js = code) {
|
|
29
|
+
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) => {
|
|
33
|
+
let found;
|
|
34
|
+
for (const c of comments)
|
|
35
|
+
if (c.end <= start)
|
|
36
|
+
found = /\S/.test(code.slice(c.end, start)) ? undefined : c.text;
|
|
37
|
+
return found;
|
|
38
|
+
};
|
|
39
|
+
const out = { inputs: [], events: [], contexts: [], blank: [], refs: [] };
|
|
40
|
+
const body = ast.body;
|
|
41
|
+
let seenProps = false;
|
|
42
|
+
const imported = new Set(body.filter((s) => s.type === 'ImportDeclaration').flatMap((s) => s.specifiers.map((x) => x.local.name)));
|
|
43
|
+
const fail = (message, at) => { throw new StripError(message, at); };
|
|
44
|
+
const members = (t, what) => {
|
|
45
|
+
if (!t)
|
|
46
|
+
return fail(`${what}<T>() needs its type: ${what}<{ … }>(), or the name of an interface in this script`, 0);
|
|
47
|
+
if (t.type === 'TSTypeLiteral')
|
|
48
|
+
return t.members;
|
|
49
|
+
if (t.type === 'TSTypeReference' && t.typeName.type === 'Identifier') {
|
|
50
|
+
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
|
+
if (t.typeArguments?.params?.length || t.typeParameters?.params?.length)
|
|
52
|
+
generic();
|
|
53
|
+
for (const s of body) {
|
|
54
|
+
const d = s.type === 'ExportNamedDeclaration' && s.declaration ? s.declaration : s;
|
|
55
|
+
if ((d.type === 'TSInterfaceDeclaration' || d.type === 'TSTypeAliasDeclaration') && d.id.name === t.typeName.name && d.typeParameters?.params?.length)
|
|
56
|
+
generic();
|
|
57
|
+
if (d.type === 'TSInterfaceDeclaration' && d.id.name === t.typeName.name) {
|
|
58
|
+
if (d.extends?.length)
|
|
59
|
+
fail(`${what}<${d.id.name}>(): an interface that extends another isn't read (write its members here)`, d.start);
|
|
60
|
+
return d.body.body;
|
|
61
|
+
}
|
|
62
|
+
if (d.type === 'TSTypeAliasDeclaration' && d.id.name === t.typeName.name && d.typeAnnotation.type === 'TSTypeLiteral')
|
|
63
|
+
return d.typeAnnotation.members;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
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
|
+
};
|
|
68
|
+
const named = (m, what) => {
|
|
69
|
+
if (m.type !== 'TSPropertySignature' || m.computed || !(m.key.type === 'Identifier' || (m.key.type === 'Literal' && typeof m.key.value === 'string')))
|
|
70
|
+
fail(`${what}: each member is a name and its type (name: Type)`, m.start);
|
|
71
|
+
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 };
|
|
73
|
+
};
|
|
74
|
+
const returned = (fn, what) => {
|
|
75
|
+
if (!fn)
|
|
76
|
+
return undefined;
|
|
77
|
+
if (fn.type !== 'ArrowFunctionExpression' || fn.params.length || fn.body.type === 'BlockStatement')
|
|
78
|
+
fail(`${what}: the default is a function returning it, () => value`, fn.start);
|
|
79
|
+
return fn.body;
|
|
80
|
+
};
|
|
81
|
+
for (const stmt of body) {
|
|
82
|
+
if (stmt.type !== 'VariableDeclaration')
|
|
83
|
+
continue;
|
|
84
|
+
const d = stmt.declarations[0];
|
|
85
|
+
const call = d?.init;
|
|
86
|
+
if (!call || call.type !== 'CallExpression' || call.callee.type !== 'Identifier' || !['props', 'model', 'events', 'context'].includes(call.callee.name))
|
|
87
|
+
continue;
|
|
88
|
+
const kind = call.callee.name;
|
|
89
|
+
if (stmt.declarations.length > 1)
|
|
90
|
+
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]);
|
|
93
|
+
for (const arg of call.arguments)
|
|
94
|
+
out.refs.push(...identifiers(arg));
|
|
95
|
+
if (kind === 'props') {
|
|
96
|
+
const pattern = d.id.type === 'ObjectPattern' ? d.id : undefined;
|
|
97
|
+
if (d.id.type !== 'Identifier' && !pattern)
|
|
98
|
+
fail('props(): const props = props<Props>(…) and read props.name, or const { name } = props<Props>(…)', d.id.start);
|
|
99
|
+
if (seenProps)
|
|
100
|
+
fail('props(): one per component', stmt.start);
|
|
101
|
+
seenProps = true;
|
|
102
|
+
const defaults = returned(call.arguments[0], 'props()');
|
|
103
|
+
if (defaults && defaults.type !== 'ObjectExpression')
|
|
104
|
+
fail('props(): the defaults are an object, () => ({ name: value })', defaults.start);
|
|
105
|
+
const given = new Map();
|
|
106
|
+
for (const p of (defaults?.properties ?? [])) {
|
|
107
|
+
if (p.type !== 'Property' || p.computed || p.key.type !== 'Identifier')
|
|
108
|
+
fail('props(): each default is name: value', p.start);
|
|
109
|
+
given.set(p.key.name, p.value);
|
|
110
|
+
}
|
|
111
|
+
const bound = new Map();
|
|
112
|
+
for (const p of (pattern?.properties ?? [])) {
|
|
113
|
+
if (p.type === 'RestElement')
|
|
114
|
+
fail('props(): a ...rest element isn\'t supported: name each prop, or read props.name from const props = props<T>()', p.start);
|
|
115
|
+
const local = p.value.type === 'AssignmentPattern' ? p.value.left : p.value;
|
|
116
|
+
if (p.computed || p.key.type !== 'Identifier' || local.type !== 'Identifier' || local.name !== p.key.name)
|
|
117
|
+
fail(`props(): a prop is read by its own name; renaming it (${code.slice(p.start, p.end)}) isn't supported`, p.start);
|
|
118
|
+
if (p.value.type === 'AssignmentPattern' && given.has(p.key.name))
|
|
119
|
+
fail(`props(): "${p.key.name}" has a default twice (in the pattern and in the callback): keep one`, p.value.right.start);
|
|
120
|
+
bound.set(p.key.name, p.value.type === 'AssignmentPattern' ? p.value.right : undefined);
|
|
121
|
+
}
|
|
122
|
+
const order = [...bound.keys()];
|
|
123
|
+
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));
|
|
125
|
+
const keys = new Set(list.map((m) => named(m, 'props').name));
|
|
126
|
+
for (const [name] of bound)
|
|
127
|
+
if (!keys.has(name))
|
|
128
|
+
fail(`props(): "${name}" isn't a prop`, pattern.properties.find((p) => p.key?.name === name).start);
|
|
129
|
+
for (const m of list) {
|
|
130
|
+
const decl = named(m, 'props');
|
|
131
|
+
const value = given.get(decl.name) ?? bound.get(decl.name);
|
|
132
|
+
if (value && !m.optional)
|
|
133
|
+
fail(`props(): "${decl.name}" is required, so it takes no default (make it optional: ${decl.name}?:)`, value.start);
|
|
134
|
+
given.delete(decl.name);
|
|
135
|
+
const doc = docBefore(m.start);
|
|
136
|
+
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
|
+
}
|
|
138
|
+
for (const [name, value] of given)
|
|
139
|
+
fail(`props(): "${name}" isn't a prop`, value.start);
|
|
140
|
+
if (!pattern)
|
|
141
|
+
out.props = { name: d.id.name, keys: [...keys] };
|
|
142
|
+
}
|
|
143
|
+
else if (kind === 'model') {
|
|
144
|
+
if (stmt.kind !== 'let' || d.id.type !== 'Identifier')
|
|
145
|
+
fail('model(): let name = model<Type>(() => default); the variable is the model, written to update the parent', stmt.start);
|
|
146
|
+
const value = returned(call.arguments[0], 'model()');
|
|
147
|
+
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 } : {}) });
|
|
149
|
+
}
|
|
150
|
+
else if (kind === 'context') {
|
|
151
|
+
if (stmt.kind !== 'const' || d.id.type !== 'Identifier')
|
|
152
|
+
fail('context(): const name = context<Type>(() => fallback), or context(key, () => fallback)', stmt.start);
|
|
153
|
+
const [first, second] = call.arguments;
|
|
154
|
+
const keyed = first && (first.type === 'Identifier' || first.type === 'MemberExpression');
|
|
155
|
+
const root = (n) => (n.type !== 'MemberExpression' ? n : n.computed && !(n.property.type === 'Literal' && typeof n.property.value === 'string') ? undefined : root(n.object));
|
|
156
|
+
if (keyed && !imported.has(root(first)?.name))
|
|
157
|
+
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);
|
|
158
|
+
if (!keyed)
|
|
159
|
+
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
|
+
const value = returned(keyed ? second : first, 'context()');
|
|
161
|
+
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 } : {}) });
|
|
163
|
+
}
|
|
164
|
+
else {
|
|
165
|
+
if (d.id.type !== 'Identifier' || d.id.name !== 'emit')
|
|
166
|
+
fail('events(): const emit = events<{ name: Type }>(), then emit(\'name\', value)', d.id.start);
|
|
167
|
+
for (const m of members(t, 'events'))
|
|
168
|
+
out.events.push({ ...named(m, 'events'), start: m.start });
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return out;
|
|
172
|
+
}
|
package/dist/compiler/index.js
CHANGED
|
@@ -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
|
|
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
|
}
|
package/dist/compiler/ir.d.ts
CHANGED
|
@@ -125,6 +125,11 @@ 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[];
|
|
@@ -153,6 +158,12 @@ export type ComponentIR = {
|
|
|
153
158
|
warnings: ClarusError[];
|
|
154
159
|
};
|
|
155
160
|
export declare const SPREAD_REFUSED: Set<string>;
|
|
161
|
+
/** A template that does something in the browser: an event or two-way binding, [use], [engine], or a transition. */
|
|
162
|
+
/**
|
|
163
|
+
* An island: a script with code (more than imports, and the types and props()/context() declarations that are spaces
|
|
164
|
+
* by now), events it sends, browser work in its template, or a @model input (which it writes, even from a handler alone).
|
|
165
|
+
*/
|
|
166
|
+
export declare function isIsland(parsed: ParsedFile, file: string, source: string): boolean;
|
|
156
167
|
export declare function lower(parsed: ParsedFile, file: string, source: string, options?: {
|
|
157
168
|
collapseWhitespace?: boolean;
|
|
158
169
|
icon?: IconResolver;
|
package/dist/compiler/ir.js
CHANGED
|
@@ -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 } 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
|
-
|
|
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 (
|
|
24
|
-
|
|
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
|
|
37
|
-
|
|
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');
|
|
@@ -576,6 +606,7 @@ export function lower(parsed, file, source, options = {}) {
|
|
|
576
606
|
file,
|
|
577
607
|
name: file.split('/').pop().replace(/\.tscl$/, ''),
|
|
578
608
|
inputs: parsed.inputs,
|
|
609
|
+
...(parsed.props ? { props: parsed.props } : {}),
|
|
579
610
|
...(parsed.extends ? { extends: Object.keys(extendedAttrs(parsed.extends.tag)) } : {}),
|
|
580
611
|
imports: parsed.imports,
|
|
581
612
|
script: parsed.script ? split.body : undefined,
|
|
@@ -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
|
+
}
|
package/dist/compiler/lint.js
CHANGED
|
@@ -224,10 +224,15 @@ export const lintRules = [
|
|
|
224
224
|
},
|
|
225
225
|
{
|
|
226
226
|
name: 'unused-input',
|
|
227
|
-
check({ parsed, reads, report }) {
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
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
|
{
|
package/dist/compiler/parse.d.ts
CHANGED
|
@@ -116,6 +116,27 @@ export type TemplateNode = {
|
|
|
116
116
|
start: number;
|
|
117
117
|
transition?: Transition;
|
|
118
118
|
};
|
|
119
|
+
/**
|
|
120
|
+
* A component's script. `code` is JavaScript; with `lang="ts"` it's the TypeScript with its types turned to spaces
|
|
121
|
+
* (every position the same), `ts` is the TypeScript as written and `typeImports` its type-only imports (type checking
|
|
122
|
+
* reads those).
|
|
123
|
+
*/
|
|
124
|
+
export type Script = {
|
|
125
|
+
code: string;
|
|
126
|
+
start: number;
|
|
127
|
+
ts?: string;
|
|
128
|
+
typeImports?: {
|
|
129
|
+
text: string;
|
|
130
|
+
start: number;
|
|
131
|
+
}[];
|
|
132
|
+
typeDecls?: {
|
|
133
|
+
text: string;
|
|
134
|
+
start: number;
|
|
135
|
+
}[]; /** props()/model()/events() statements: what they declare is in inputs and events. */
|
|
136
|
+
factories?: [number, number][]; /** The names those statements' arguments use (for linters: they're spaces in `code`). */
|
|
137
|
+
factoryRefs?: string[]; /** Where `export` starts on a type that stays in the script (type checking drops the keyword). */
|
|
138
|
+
stayingExports?: number[];
|
|
139
|
+
};
|
|
119
140
|
/**
|
|
120
141
|
* An `@input` (or `@model`) declaration: its name, type text, default, and offsets.
|
|
121
142
|
* @see https://clarusjs.com/reference/compiler#parse
|
|
@@ -128,7 +149,11 @@ export type InputDecl = {
|
|
|
128
149
|
nameStart: number;
|
|
129
150
|
typeStart: number;
|
|
130
151
|
defaultStart?: number;
|
|
131
|
-
model?: true;
|
|
152
|
+
model?: true; /** The `/** … *\/` right before it, as written: what editors show for it. */
|
|
153
|
+
doc?: string; /** A context read with a typed key: the key's expression (context(tabsKey)). */
|
|
154
|
+
key?: string; /** props<{ a?: T }>() without a default: optional all the same. */
|
|
155
|
+
optional?: true; /** A factory default as written, TypeScript (`default` is it stripped, for the compiler). */
|
|
156
|
+
defaultTs?: string;
|
|
132
157
|
};
|
|
133
158
|
export type TypeImport = {
|
|
134
159
|
clause: string;
|
|
@@ -169,7 +194,8 @@ export type TypeDecl = {
|
|
|
169
194
|
type: string;
|
|
170
195
|
start: number;
|
|
171
196
|
nameStart: number;
|
|
172
|
-
typeStart: number;
|
|
197
|
+
typeStart: number; /** The `/** … *\/` right before it, as written. */
|
|
198
|
+
doc?: string;
|
|
173
199
|
};
|
|
174
200
|
/**
|
|
175
201
|
* A `.tscl` file's syntax tree, as `parse()` gives it: inputs, imports, the script, styles and template nodes.
|
|
@@ -185,16 +211,16 @@ export type ParsedFile = {
|
|
|
185
211
|
typeImports: TypeImport[];
|
|
186
212
|
types: TypeDecl[];
|
|
187
213
|
dataImports: DataImport[];
|
|
188
|
-
script?:
|
|
189
|
-
code: string;
|
|
190
|
-
start: number;
|
|
191
|
-
};
|
|
214
|
+
script?: Script;
|
|
192
215
|
/** <script server> (#430): runs at render on the server only. `tag` = offset of `<script`. */
|
|
193
|
-
serverScript?: {
|
|
194
|
-
code: string;
|
|
195
|
-
start: number;
|
|
216
|
+
serverScript?: Script & {
|
|
196
217
|
tag: number;
|
|
197
218
|
};
|
|
219
|
+
/** props<T>() in the script: the variable it's read through (props.name), and the props it holds. */
|
|
220
|
+
props?: {
|
|
221
|
+
name: string;
|
|
222
|
+
keys: string[];
|
|
223
|
+
};
|
|
198
224
|
styles: {
|
|
199
225
|
css: string;
|
|
200
226
|
mode: 'scoped' | 'global' | 'plain';
|