clarusjs 0.13.0 → 0.15.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.d.ts +2 -5
- package/dist/check/generate.js +148 -13
- package/dist/cli/check.d.ts +4 -0
- package/dist/cli/check.js +3 -1
- package/dist/cli/mapper.js +19 -1
- package/dist/cli/project.d.ts +4 -0
- package/dist/cli/project.js +1 -1
- package/dist/compiler/class-style.d.ts +1 -1
- package/dist/compiler/class-style.js +6 -2
- package/dist/compiler/components.d.ts +32 -0
- package/dist/compiler/components.js +63 -0
- package/dist/compiler/emit-client.js +33 -4
- package/dist/compiler/emit-server.js +21 -11
- package/dist/compiler/html-expr.d.ts +11 -2
- package/dist/compiler/html-expr.js +38 -20
- package/dist/compiler/icon.d.ts +1 -1
- package/dist/compiler/icon.js +4 -0
- package/dist/compiler/index.d.ts +13 -1
- package/dist/compiler/index.js +64 -2
- package/dist/compiler/ir.d.ts +39 -0
- package/dist/compiler/ir.js +104 -11
- package/dist/compiler/lint.js +12 -1
- package/dist/compiler/parse.d.ts +44 -0
- package/dist/compiler/parse.js +93 -10
- package/dist/compiler/script.d.ts +21 -1
- package/dist/compiler/script.js +58 -3
- package/dist/compiler/shared.d.ts +6 -0
- package/dist/compiler/shared.js +14 -0
- package/dist/fetch/index.d.ts +157 -3
- package/dist/fetch/index.js +135 -14
- package/dist/forms/index.js +15 -3
- package/dist/runtime/attrs.d.ts +6 -0
- package/dist/runtime/attrs.js +16 -0
- package/dist/runtime/dom.d.ts +42 -1
- package/dist/runtime/dom.js +152 -23
- package/dist/runtime/html.d.ts +6 -0
- package/dist/runtime/html.js +12 -0
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/loader.js +32 -6
- package/dist/runtime/router.d.ts +6 -1
- package/dist/runtime/router.js +1 -1
- package/dist/runtime/server.d.ts +20 -2
- package/dist/runtime/server.js +48 -8
- package/dist/server/handler.d.ts +28 -1
- package/dist/server/handler.js +48 -2
- package/dist/server/modes.d.ts +2 -0
- package/dist/server/modes.js +5 -1
- package/dist/server/views.d.ts +1 -1
- package/dist/server/views.js +1 -1
- package/dist/vite/plugin.d.ts +19 -0
- package/dist/vite/plugin.js +61 -14
- package/package.json +1 -1
package/dist/check/generate.d.ts
CHANGED
|
@@ -1,17 +1,14 @@
|
|
|
1
|
+
import { type ComponentNames } from '../compiler/components.ts';
|
|
1
2
|
/**
|
|
2
3
|
* [virtual offset, length, source offset, exact, source length]. Exact spans are verbatim copies (offsets map one to
|
|
3
4
|
* one); other spans stand for a whole template construct (a component's tag, a binding's name): the source length
|
|
4
5
|
* says how much of the template that is.
|
|
5
6
|
*/
|
|
6
7
|
export type Mapping = [number, number, number, boolean, number?];
|
|
7
|
-
/**
|
|
8
|
-
* `loader`: the module specifier of the page's .load.ts when it exports load(); what it returns is checked against
|
|
9
|
-
* the page's inputs. `componentSuffix`: added to component imports ('.ts' for `clarusjs check`'s generated files; ''
|
|
10
|
-
* for the content mapper, where TypeScript resolves the .tscl file itself). `loaderSpan` is where that check sits in the generated code, so its errors can say so.
|
|
11
|
-
*/
|
|
12
8
|
export declare function generateTs(source: string, file: string, options?: {
|
|
13
9
|
loader?: string;
|
|
14
10
|
componentSuffix?: string;
|
|
11
|
+
components?: ComponentNames;
|
|
15
12
|
}): {
|
|
16
13
|
code: string;
|
|
17
14
|
mappings: Mapping[];
|
package/dist/check/generate.js
CHANGED
|
@@ -1,11 +1,38 @@
|
|
|
1
|
+
import { autoImport } from '../compiler/components.js';
|
|
2
|
+
import { parseExpressionAt } from 'acorn';
|
|
1
3
|
import { routeFromFile } from '../server/handler.js';
|
|
2
4
|
import { ClarusError } from '../compiler/errors.js';
|
|
3
5
|
import { FOR_IMPLICIT, parse } from '../compiler/parse.js';
|
|
4
|
-
import { referencesNames, splitImports, untypedParams } from '../compiler/script.js';
|
|
6
|
+
import { providesIn, referencesNames, splitImports, untypedParams } from '../compiler/script.js';
|
|
5
7
|
const ENUMERATED = new Set(['draggable', 'spellcheck', 'translate', 'autocorrect', 'contenteditable']);
|
|
6
8
|
const PROPERTY = { readonly: 'readOnly', novalidate: 'noValidate', formnovalidate: 'formNoValidate', allowfullscreen: 'allowFullscreen', playsinline: 'playsInline', nomodule: 'noModule', ismap: 'isMap' };
|
|
9
|
+
function patternNames(params) {
|
|
10
|
+
const names = [];
|
|
11
|
+
const walk = (p) => {
|
|
12
|
+
if (!p)
|
|
13
|
+
return;
|
|
14
|
+
if (p.type === 'Identifier')
|
|
15
|
+
names.push(p.name);
|
|
16
|
+
else if (p.type === 'ObjectPattern')
|
|
17
|
+
for (const prop of p.properties)
|
|
18
|
+
walk(prop.type === 'RestElement' ? prop.argument : prop.value);
|
|
19
|
+
else if (p.type === 'ArrayPattern')
|
|
20
|
+
p.elements.forEach(walk);
|
|
21
|
+
else if (p.type === 'AssignmentPattern')
|
|
22
|
+
walk(p.left);
|
|
23
|
+
else if (p.type === 'RestElement')
|
|
24
|
+
walk(p.argument);
|
|
25
|
+
};
|
|
26
|
+
try {
|
|
27
|
+
walk(parseExpressionAt(`(${params}) => 0`, 0, { ecmaVersion: 'latest' }).params[0]);
|
|
28
|
+
}
|
|
29
|
+
catch { }
|
|
30
|
+
return names;
|
|
31
|
+
}
|
|
7
32
|
export function generateTs(source, file, options = {}) {
|
|
8
33
|
const parsed = parse(source, file);
|
|
34
|
+
if (options.components)
|
|
35
|
+
autoImport(parsed, options.components, file, source);
|
|
9
36
|
const mappings = [];
|
|
10
37
|
let code = '';
|
|
11
38
|
const emit = (text) => { code += text; };
|
|
@@ -33,7 +60,7 @@ export function generateTs(source, file, options = {}) {
|
|
|
33
60
|
emit(` from ${JSON.stringify(t.from)}\n`);
|
|
34
61
|
}
|
|
35
62
|
for (const imp of parsed.imports)
|
|
36
|
-
emit(`import type { Inputs as ${alias(imp.name)}, Models as ${alias(imp.name)}_M } from ${JSON.stringify(`${imp.from}${options.componentSuffix ?? '.ts'}`)}\n`);
|
|
63
|
+
emit(`import type { Inputs as ${alias(imp.name)}, Models as ${alias(imp.name)}_M, Events as ${alias(imp.name)}_E } from ${JSON.stringify(`${imp.from}${options.componentSuffix ?? '.ts'}`)}\n`);
|
|
37
64
|
for (const d of parsed.dataImports) {
|
|
38
65
|
emit('import ');
|
|
39
66
|
copy(d.clause, d.clauseStart);
|
|
@@ -42,12 +69,20 @@ export function generateTs(source, file, options = {}) {
|
|
|
42
69
|
if (options.loader)
|
|
43
70
|
emit(`import { load as __cl_load } from ${JSON.stringify(options.loader)}\n`);
|
|
44
71
|
const script = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : null;
|
|
72
|
+
const provides = !!parsed.script && !!script && providesIn(script, file, source, parsed.script.start);
|
|
45
73
|
if (parsed.script && script) {
|
|
46
74
|
for (const imp of script.imports) {
|
|
47
75
|
copy(imp.text, parsed.script.start + imp.start);
|
|
48
76
|
emit('\n');
|
|
49
77
|
}
|
|
50
78
|
}
|
|
79
|
+
const serverScript = parsed.serverScript ? splitImports(parsed.serverScript.code, file, source, parsed.serverScript.start, true) : null;
|
|
80
|
+
if (parsed.serverScript && serverScript) {
|
|
81
|
+
for (const imp of serverScript.imports) {
|
|
82
|
+
copy(imp.text, parsed.serverScript.start + imp.start);
|
|
83
|
+
emit('\n');
|
|
84
|
+
}
|
|
85
|
+
}
|
|
51
86
|
for (const t of parsed.types) {
|
|
52
87
|
emit(t.kind === 'interface' ? `interface ${t.name}${t.params ?? ''} ` : `type ${t.name}${t.params ?? ''} = `);
|
|
53
88
|
copy(t.type, t.typeStart);
|
|
@@ -66,6 +101,20 @@ export function generateTs(source, file, options = {}) {
|
|
|
66
101
|
emit('}\n');
|
|
67
102
|
const models = parsed.inputs.filter((i) => i.model).map((i) => JSON.stringify(i.name));
|
|
68
103
|
emit(`export type Models = ${models.length ? models.join(' | ') : 'never'}\n`);
|
|
104
|
+
emit('export interface Events {\n');
|
|
105
|
+
for (const e of parsed.events) {
|
|
106
|
+
emit(` ${JSON.stringify(e.name)}: `);
|
|
107
|
+
if (e.type === 'void')
|
|
108
|
+
emit('void');
|
|
109
|
+
else
|
|
110
|
+
copy(e.type, e.typeStart);
|
|
111
|
+
emit('\n');
|
|
112
|
+
}
|
|
113
|
+
emit('}\n');
|
|
114
|
+
if (provides)
|
|
115
|
+
emit('declare function provide(key: string, value: unknown): void\n');
|
|
116
|
+
if (parsed.events.length)
|
|
117
|
+
emit('declare const emit: <K extends keyof Events>(name: K, ...args: Events[K] extends void ? [value?: undefined, info?: { reason?: string; event?: Event }] : [value: Events[K], info?: { reason?: string; event?: Event }]) => boolean\n');
|
|
69
118
|
let loaderSpan;
|
|
70
119
|
if (options.loader) {
|
|
71
120
|
emit('declare const __cl_loaded: Exclude<Awaited<ReturnType<typeof __cl_load>>, Response>\n');
|
|
@@ -76,7 +125,11 @@ export function generateTs(source, file, options = {}) {
|
|
|
76
125
|
emit('\n');
|
|
77
126
|
}
|
|
78
127
|
emit('export type __cl_Readonly<T> = T extends (...args: any[]) => unknown ? T : T extends object ? { readonly [K in keyof T]: __cl_Readonly<T[K]> } : T\n');
|
|
79
|
-
emit('
|
|
128
|
+
emit('export type __cl_Ev<T, K> = K extends keyof T ? T[K] : any\n');
|
|
129
|
+
emit('export type __cl_Use<E> = ((el: E) => unknown) | readonly ((el: E) => unknown)[]\n');
|
|
130
|
+
emit('export type __cl_Passed = { id?: string; role?: string; tabindex?: string | number; hidden?: boolean; lang?: string; dir?: string; style?: string; [k: `data-${string}`]: unknown; [k: `aria-${string}`]: unknown }\n');
|
|
131
|
+
const awaits = !!parsed.serverScript && /\bawait\b/.test(parsed.serverScript.code);
|
|
132
|
+
emit(`\nexport default ${awaits ? 'async ' : ''}function __cl_check(__cl_props: __cl_Readonly<Inputs>) {\n`);
|
|
80
133
|
for (const [keyword, list] of [['const', parsed.inputs.filter((x) => !x.model)], ['let', parsed.inputs.filter((x) => x.model)]]) {
|
|
81
134
|
if (!list.length)
|
|
82
135
|
continue;
|
|
@@ -93,23 +146,41 @@ export function generateTs(source, file, options = {}) {
|
|
|
93
146
|
emit(' } = __cl_props\n');
|
|
94
147
|
emit(` __cl_use([${list.map((x) => x.name).join(', ')}])\n`);
|
|
95
148
|
}
|
|
96
|
-
|
|
97
|
-
const
|
|
149
|
+
for (const c of parsed.contexts) {
|
|
150
|
+
emit(' const ');
|
|
151
|
+
copy(c.name, c.nameStart);
|
|
152
|
+
emit(': ');
|
|
153
|
+
copy(c.type, c.typeStart);
|
|
154
|
+
emit(' = ');
|
|
155
|
+
if (c.default !== undefined && c.defaultStart !== undefined)
|
|
156
|
+
copy(c.default, c.defaultStart);
|
|
157
|
+
else
|
|
158
|
+
emit('null!');
|
|
159
|
+
emit('\n');
|
|
160
|
+
}
|
|
161
|
+
if (parsed.contexts.length)
|
|
162
|
+
emit(` __cl_use([${parsed.contexts.map((c) => c.name).join(', ')}])\n`);
|
|
163
|
+
const copyScript = (from, split) => {
|
|
164
|
+
const body = split.body;
|
|
98
165
|
const cuts = [
|
|
99
|
-
...
|
|
100
|
-
...untypedParams(
|
|
166
|
+
...split.imports.map((imp) => ({ at: imp.start, end: imp.start + imp.text.length, text: body.slice(imp.start, imp.start + imp.text.length) })),
|
|
167
|
+
...untypedParams(from.code).map((e) => ({ ...e, end: e.at })),
|
|
101
168
|
].sort((a, b) => a.at - b.at);
|
|
102
169
|
let pos = 0;
|
|
103
170
|
for (const cut of cuts) {
|
|
104
171
|
if (cut.at > pos)
|
|
105
|
-
copy(body.slice(pos, cut.at),
|
|
172
|
+
copy(body.slice(pos, cut.at), from.start + pos);
|
|
106
173
|
emit(cut.text);
|
|
107
174
|
pos = Math.max(pos, cut.end);
|
|
108
175
|
}
|
|
109
176
|
if (body.length > pos)
|
|
110
|
-
copy(body.slice(pos),
|
|
177
|
+
copy(body.slice(pos), from.start + pos);
|
|
111
178
|
emit('\n;\n');
|
|
112
|
-
}
|
|
179
|
+
};
|
|
180
|
+
if (parsed.serverScript && serverScript)
|
|
181
|
+
copyScript(parsed.serverScript, serverScript);
|
|
182
|
+
if (parsed.script && script)
|
|
183
|
+
copyScript(parsed.script, script);
|
|
113
184
|
const use = (expr, start) => {
|
|
114
185
|
emit(' __cl_use((');
|
|
115
186
|
copy(expr, at(expr, start));
|
|
@@ -141,7 +212,13 @@ export function generateTs(source, file, options = {}) {
|
|
|
141
212
|
case 'expr':
|
|
142
213
|
return use(node.expr, node.start + 2);
|
|
143
214
|
case 'fill':
|
|
144
|
-
node.
|
|
215
|
+
if (node.params !== undefined) {
|
|
216
|
+
emit(` { const [${node.params}]: any = []; __cl_use([${patternNames(node.params).join(', ')}])\n`);
|
|
217
|
+
node.children.forEach(visit);
|
|
218
|
+
emit(' }\n');
|
|
219
|
+
}
|
|
220
|
+
else
|
|
221
|
+
node.children.forEach(visit);
|
|
145
222
|
return;
|
|
146
223
|
case 'if':
|
|
147
224
|
node.branches.forEach((b, i) => {
|
|
@@ -159,6 +236,28 @@ export function generateTs(source, file, options = {}) {
|
|
|
159
236
|
emit(' }\n');
|
|
160
237
|
});
|
|
161
238
|
return;
|
|
239
|
+
case 'await': {
|
|
240
|
+
emit(' { const __cl_aw = (');
|
|
241
|
+
copy(node.expr, at(node.expr, node.exprStart));
|
|
242
|
+
emit(');\n');
|
|
243
|
+
emit(' {\n');
|
|
244
|
+
node.pending.forEach(visit);
|
|
245
|
+
emit(' }\n');
|
|
246
|
+
for (const [b, type] of [[node.then, 'Awaited<typeof __cl_aw>'], [node.catch, 'any']]) {
|
|
247
|
+
if (!b)
|
|
248
|
+
continue;
|
|
249
|
+
emit(' { const ');
|
|
250
|
+
copy(b.name, b.nameStart);
|
|
251
|
+
emit(`: ${type} = null!; __cl_use(${b.name})\n`);
|
|
252
|
+
const outer = guards.splice(0);
|
|
253
|
+
guards.push(...outer.filter((g) => !referencesNames(g, new Set([b.name]))));
|
|
254
|
+
b.children.forEach(visit);
|
|
255
|
+
guards.splice(0, guards.length, ...outer);
|
|
256
|
+
emit(' }\n');
|
|
257
|
+
}
|
|
258
|
+
emit(' }\n');
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
162
261
|
case 'for': {
|
|
163
262
|
emit(' for (const ');
|
|
164
263
|
copy(node.item, node.itemStart);
|
|
@@ -184,7 +283,7 @@ export function generateTs(source, file, options = {}) {
|
|
|
184
283
|
if (component) {
|
|
185
284
|
emit(' { const ');
|
|
186
285
|
point('__cl_p', node.start, node.tag.length + 1);
|
|
187
|
-
emit(`: __cl_Readonly<${alias(node.tag)}> = { `);
|
|
286
|
+
emit(`: __cl_Readonly<${alias(node.tag)} & __cl_Passed> = { `);
|
|
188
287
|
for (const a of node.attrs) {
|
|
189
288
|
if (a.kind !== 'prop' || a.name !== '...')
|
|
190
289
|
continue;
|
|
@@ -193,9 +292,24 @@ export function generateTs(source, file, options = {}) {
|
|
|
193
292
|
emit('), ');
|
|
194
293
|
}
|
|
195
294
|
for (const a of node.attrs) {
|
|
295
|
+
if (a.kind === 'static' && a.name !== 'class' && a.name !== 'attach') {
|
|
296
|
+
const quoted = !/^[A-Za-z_$][\w$]*$/.test(a.name);
|
|
297
|
+
if (quoted)
|
|
298
|
+
emit('"');
|
|
299
|
+
copy(a.name, a.start);
|
|
300
|
+
if (quoted)
|
|
301
|
+
emit('"');
|
|
302
|
+
emit(`: ${a.value === true ? 'true' : JSON.stringify(a.value)}, `);
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
196
305
|
if ((a.kind !== 'prop' && a.kind !== 'model') || a.name === '...')
|
|
197
306
|
continue;
|
|
307
|
+
const quoted = !/^[A-Za-z_$][\w$]*$/.test(a.name);
|
|
308
|
+
if (quoted)
|
|
309
|
+
emit('"');
|
|
198
310
|
copy(a.name, a.start + (a.kind === 'model' ? 2 : 1));
|
|
311
|
+
if (quoted)
|
|
312
|
+
emit('"');
|
|
199
313
|
emit(': (');
|
|
200
314
|
copy(a.expr, at(a.expr, attrValueStart(a)));
|
|
201
315
|
emit('), ');
|
|
@@ -212,6 +326,19 @@ export function generateTs(source, file, options = {}) {
|
|
|
212
326
|
copy(a.expr, at(a.expr, attrValueStart(a)));
|
|
213
327
|
emit(` = (undefined as unknown as Exclude<${alias(node.tag)}[${JSON.stringify(a.name)}], undefined>) });\n`);
|
|
214
328
|
}
|
|
329
|
+
for (const a of node.attrs) {
|
|
330
|
+
if (a.kind !== 'event')
|
|
331
|
+
continue;
|
|
332
|
+
const name = JSON.stringify(a.name);
|
|
333
|
+
emit(' { const ');
|
|
334
|
+
point('__cl_ev', a.start, a.name.length + 2);
|
|
335
|
+
emit(`: keyof ${alias(node.tag)}_E = ${name}; __cl_use(__cl_ev) }\n`);
|
|
336
|
+
emit(` ;(($event: __cl_Ev<${alias(node.tag)}_E, ${name}>, $info: { reason?: string; event?: Event; cancel(): void }) => { `);
|
|
337
|
+
guarded();
|
|
338
|
+
emit('{ ');
|
|
339
|
+
copy(a.expr, at(a.expr, attrValueStart(a)));
|
|
340
|
+
emit(' } __cl_use($info) });\n');
|
|
341
|
+
}
|
|
215
342
|
node.children.forEach(visit);
|
|
216
343
|
return;
|
|
217
344
|
}
|
|
@@ -223,6 +350,14 @@ export function generateTs(source, file, options = {}) {
|
|
|
223
350
|
const radio = node.tag === 'input' && a.name === 'value' && type?.kind === 'static' && String(type.value).toLowerCase() === 'radio' && own?.kind === 'static';
|
|
224
351
|
writable(a, radio ? JSON.stringify(own.value === true ? '' : own.value) : undefined);
|
|
225
352
|
}
|
|
353
|
+
else if (a.kind === 'prop' && node.tag === 'slot') {
|
|
354
|
+
use(a.expr, attrValueStart(a));
|
|
355
|
+
}
|
|
356
|
+
else if (a.kind === 'prop' && a.name === 'use') {
|
|
357
|
+
emit(` ;((__cl_u: __cl_Use<__cl_El<${JSON.stringify(node.tag.toLowerCase())}>>) => __cl_use(__cl_u))((`);
|
|
358
|
+
copy(a.expr, at(a.expr, attrValueStart(a)));
|
|
359
|
+
emit('));\n');
|
|
360
|
+
}
|
|
226
361
|
else if (a.kind === 'prop' && a.name === 'engine') {
|
|
227
362
|
emit(` ;((__cl_f: import('clarusjs/forms').Form<any>) => __cl_use(__cl_f))((`);
|
|
228
363
|
copy(a.expr, at(a.expr, attrValueStart(a)));
|
|
@@ -313,7 +448,7 @@ export function viewsDeclaration(views) {
|
|
|
313
448
|
return lines.join('\n');
|
|
314
449
|
}
|
|
315
450
|
export function routesDeclaration(files) {
|
|
316
|
-
const pages = files.filter((f) => f.startsWith('src/pages/') && !/\.(m?[jt]s|css|json)$/.test(f) && !/(^|\/)_[^/]*$/.test(f));
|
|
451
|
+
const pages = files.filter((f) => f.startsWith('src/pages/') && !/\.(m?[jt]s|css|json)$/.test(f) && !/(^|\/)[_+][^/]*$/.test(f));
|
|
317
452
|
const routes = [...new Set(pages.map((f) => routeFromFile(`/${f}`)))].sort();
|
|
318
453
|
const entries = routes.map((route) => {
|
|
319
454
|
const keys = [...route.matchAll(/\[([^\]]+)\]/g)].map((m) => m[1]);
|
package/dist/cli/check.d.ts
CHANGED
package/dist/cli/check.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { COMPONENT_DIRS, componentIndex } from '../compiler/components.js';
|
|
1
2
|
import { spawnSync } from 'node:child_process';
|
|
2
3
|
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
4
|
import { createRequire } from 'node:module';
|
|
@@ -50,6 +51,7 @@ function typescriptDir(root, override) {
|
|
|
50
51
|
}
|
|
51
52
|
export function check(options) {
|
|
52
53
|
const root = resolve(options.root);
|
|
54
|
+
const names = options.components?.auto === false ? undefined : componentIndex(findClarusFiles(resolve(root, 'src'), ['.tscl']).map((f) => posix(relative(root, f))), options.components?.dirs ?? COMPONENT_DIRS).names;
|
|
53
55
|
const virtualRoot = resolve(root, VIRTUAL);
|
|
54
56
|
rmSync(virtualRoot, { recursive: true, force: true });
|
|
55
57
|
const diagnostics = [];
|
|
@@ -88,7 +90,7 @@ export function check(options) {
|
|
|
88
90
|
};
|
|
89
91
|
try {
|
|
90
92
|
const loader = loaderOf(path);
|
|
91
|
-
const { code, mappings, loaderSpan } = generateTs(source, file, loader ? { loader } : {});
|
|
93
|
+
const { code, mappings, loaderSpan } = generateTs(source, file, { ...(loader ? { loader } : {}), components: names });
|
|
92
94
|
const vpath = resolve(virtualRoot, `${file}.ts`);
|
|
93
95
|
mkdirSync(dirname(vpath), { recursive: true });
|
|
94
96
|
writeFileSync(vpath, code);
|
package/dist/cli/mapper.js
CHANGED
|
@@ -1,9 +1,27 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { dirname, relative, resolve, sep } from 'node:path';
|
|
1
3
|
import { generateTolerant } from '../check/generate.js';
|
|
4
|
+
import { COMPONENT_DIRS, componentIndex } from '../compiler/components.js';
|
|
5
|
+
import { findClarusFiles } from '../vite/build.js';
|
|
2
6
|
import { loaderOf } from './check.js';
|
|
7
|
+
function namesFor(fileName) {
|
|
8
|
+
let root = dirname(fileName);
|
|
9
|
+
while (!existsSync(resolve(root, 'package.json'))) {
|
|
10
|
+
if (dirname(root) === root)
|
|
11
|
+
return undefined;
|
|
12
|
+
root = dirname(root);
|
|
13
|
+
}
|
|
14
|
+
const files = findClarusFiles(resolve(root, 'src'), ['.tscl']).map((f) => relative(root, f).split(sep).join('/'));
|
|
15
|
+
const rel = (path) => { const r = relative(dirname(fileName), resolve(root, path.slice(1))).split(sep).join('/'); return r.startsWith('.') ? r : `./${r}`; };
|
|
16
|
+
const names = {};
|
|
17
|
+
for (const [name, path] of Object.entries(componentIndex(files, COMPONENT_DIRS).names))
|
|
18
|
+
names[name] = Array.isArray(path) ? path.map(rel) : rel(path);
|
|
19
|
+
return names;
|
|
20
|
+
}
|
|
3
21
|
export function transform(params) {
|
|
4
22
|
const { fileName, content } = params;
|
|
5
23
|
const loader = loaderOf(fileName);
|
|
6
|
-
const { result, errors } = generateTolerant(content, fileName, { componentSuffix: '', ...(loader ? { loader } : {}) });
|
|
24
|
+
const { result, errors } = generateTolerant(content, fileName, { componentSuffix: '', components: namesFor(fileName), ...(loader ? { loader } : {}) });
|
|
7
25
|
const diagnostics = errors.slice(0, 1).map((e) => ({ messageText: e.message, start: e.offset, length: Math.min(1, content.length - e.offset), code: 1 }));
|
|
8
26
|
if (!result)
|
|
9
27
|
return { text: 'export {}\n', extension: '.ts', mappings: [], diagnostics };
|
package/dist/cli/project.d.ts
CHANGED
package/dist/cli/project.js
CHANGED
|
@@ -18,5 +18,5 @@ export async function loadProject(root) {
|
|
|
18
18
|
if (!loaded)
|
|
19
19
|
return none;
|
|
20
20
|
const plugin = (await flatten(loaded.config.plugins)).find((p) => p.name === 'clarusjs');
|
|
21
|
-
return { sources: plugin?.api?.sources ?? [], viteAliases: loaded.config.resolve?.alias, lint: plugin?.api?.lint, lintRules: plugin?.api?.lintRules ?? [] };
|
|
21
|
+
return { sources: plugin?.api?.sources ?? [], viteAliases: loaded.config.resolve?.alias, lint: plugin?.api?.lint, lintRules: plugin?.api?.lintRules ?? [], components: plugin?.api?.components };
|
|
22
22
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type TemplateNode } from './parse.ts';
|
|
2
2
|
export declare function foldClass(nodes: TemplateNode[], components: Set<string>): void;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { awaitLists } from './parse.js';
|
|
1
2
|
const spreadOf = (node) => node.attrs.find((a) => a.kind === 'prop' && a.name === '...')?.expr;
|
|
2
3
|
const isSource = (a, name) => a.name === name && a.kind !== 'event';
|
|
3
4
|
function part(a) {
|
|
@@ -10,7 +11,7 @@ function part(a) {
|
|
|
10
11
|
function foldStyle(node) {
|
|
11
12
|
const props = node.attrs.filter((a) => a.kind === 'prop' && a.name.startsWith('style.'));
|
|
12
13
|
const sources = node.attrs.filter((a) => isSource(a, 'style'));
|
|
13
|
-
const spread = spreadOf(node);
|
|
14
|
+
const spread = spreadOf(node) === '__cl_attrs' ? undefined : spreadOf(node);
|
|
14
15
|
if (!spread && !props.length && !(sources.length > 1 && sources.some((a) => a.kind === 'prop')))
|
|
15
16
|
return;
|
|
16
17
|
const exprs = [...(spread ? [`((${spread}) || {}).style`] : []), ...sources.map(part), ...props.map((p) => `{ ${JSON.stringify(p.name.slice(6))}: (${p.expr}) }`)];
|
|
@@ -26,7 +27,7 @@ export function foldClass(nodes, components) {
|
|
|
26
27
|
const toggles = node.attrs.filter((a) => a.kind === 'prop' && a.name.startsWith('class.'));
|
|
27
28
|
const sources = node.attrs.filter((a) => isSource(a, 'class'));
|
|
28
29
|
const mixed = sources.length > 1 && sources.some((a) => a.kind === 'prop');
|
|
29
|
-
const spread = spreadOf(node);
|
|
30
|
+
const spread = spreadOf(node) === '__cl_attrs' ? undefined : spreadOf(node);
|
|
30
31
|
if (toggles.length || mixed || spread) {
|
|
31
32
|
const exprs = [...(spread ? [`((${spread}) || {}).class`] : []), ...sources.map(part), ...toggles.map((t) => `{ ${JSON.stringify(t.name.slice(6))}: (${t.expr}) }`)];
|
|
32
33
|
const start = (sources[0] ?? toggles[0] ?? node.attrs.find((a) => a.name === '...')).start;
|
|
@@ -45,5 +46,8 @@ export function foldClass(nodes, components) {
|
|
|
45
46
|
}
|
|
46
47
|
else if (node.type === 'fill')
|
|
47
48
|
foldClass(node.children, components);
|
|
49
|
+
else if (node.type === 'await')
|
|
50
|
+
for (const kids of awaitLists(node))
|
|
51
|
+
foldClass(kids, components);
|
|
48
52
|
}
|
|
49
53
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type ParsedFile } from './parse.ts';
|
|
2
|
+
/**
|
|
3
|
+
* Tag name → the component's root path ('/src/components/forms/text-field.tscl'), or every candidate when ambiguous.
|
|
4
|
+
* @see https://clarusjs.com/guide/components#automatic-imports
|
|
5
|
+
*/
|
|
6
|
+
export type ComponentNames = Record<string, string | string[]>;
|
|
7
|
+
/**
|
|
8
|
+
* Where automatic components live, by default (root-relative).
|
|
9
|
+
* @example
|
|
10
|
+
* componentIndex(files, COMPONENT_DIRS)
|
|
11
|
+
* @see https://clarusjs.com/guide/components#automatic-imports
|
|
12
|
+
*/
|
|
13
|
+
export declare const COMPONENT_DIRS: string[];
|
|
14
|
+
/**
|
|
15
|
+
* Name every `.tscl` file under `dirs` (root-relative, posix): its full name is its folders and file joined with
|
|
16
|
+
* hyphens (`forms/text-field.tscl` → `forms-text-field`), its short name the file alone (`text-field`) when no other
|
|
17
|
+
* component has that name; a full name wins over a short one. Only names with a hyphen count, like custom elements,
|
|
18
|
+
* so a component never takes an HTML element's name. `skipped`: files that aren't kebab-case (never named).
|
|
19
|
+
* @example
|
|
20
|
+
* componentIndex(['src/components/forms/text-field.tscl'], ['src/components']).names
|
|
21
|
+
* // { 'forms-text-field': '/src/components/forms/text-field.tscl', 'text-field': '/src/components/forms/text-field.tscl' }
|
|
22
|
+
* @see https://clarusjs.com/guide/components#automatic-imports
|
|
23
|
+
*/
|
|
24
|
+
export declare function componentIndex(files: string[], dirs: string[]): {
|
|
25
|
+
names: ComponentNames;
|
|
26
|
+
skipped: string[];
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Add an import for each component tag the template uses that `names` knows and the file doesn't import itself (only
|
|
30
|
+
* those). A tag that names two components is a located error. Other hyphenated tags stay HTML (web components).
|
|
31
|
+
*/
|
|
32
|
+
export declare function autoImport(parsed: ParsedFile, names: ComponentNames, file: string, source: string): void;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { ClarusError } from './errors.js';
|
|
2
|
+
import { awaitLists } from './parse.js';
|
|
3
|
+
export const COMPONENT_DIRS = ['src/components', 'src/layouts'];
|
|
4
|
+
const KEBAB = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
5
|
+
export function componentIndex(files, dirs) {
|
|
6
|
+
const full = new Map();
|
|
7
|
+
const short = new Map();
|
|
8
|
+
const skipped = [];
|
|
9
|
+
const add = (map, name, path) => map.set(name, [...(map.get(name) ?? []), path]);
|
|
10
|
+
for (const file of [...files].sort()) {
|
|
11
|
+
const dir = dirs.find((d) => file.startsWith(`${d.replace(/\/+$/, '')}/`));
|
|
12
|
+
if (!dir || !file.endsWith('.tscl'))
|
|
13
|
+
continue;
|
|
14
|
+
const segments = file.slice(dir.replace(/\/+$/, '').length + 1, -'.tscl'.length).split('/');
|
|
15
|
+
if (!segments.every((s) => KEBAB.test(s))) {
|
|
16
|
+
skipped.push(file);
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
add(full, segments.join('-'), `/${file}`);
|
|
20
|
+
if (segments.length > 1)
|
|
21
|
+
add(short, segments.at(-1), `/${file}`);
|
|
22
|
+
}
|
|
23
|
+
const names = {};
|
|
24
|
+
for (const [name, paths] of short)
|
|
25
|
+
if (name.includes('-') && !full.has(name))
|
|
26
|
+
names[name] = paths.length === 1 ? paths[0] : paths;
|
|
27
|
+
for (const [name, paths] of full)
|
|
28
|
+
if (name.includes('-'))
|
|
29
|
+
names[name] = paths.length === 1 ? paths[0] : paths;
|
|
30
|
+
return { names, skipped };
|
|
31
|
+
}
|
|
32
|
+
export function autoImport(parsed, names, file, source) {
|
|
33
|
+
const imported = new Set(parsed.imports.map((i) => i.name));
|
|
34
|
+
const walk = (nodes) => {
|
|
35
|
+
for (const node of nodes) {
|
|
36
|
+
if (node.type === 'element') {
|
|
37
|
+
const found = node.tag.includes('-') && !imported.has(node.tag) ? names[node.tag] : undefined;
|
|
38
|
+
if (Array.isArray(found)) {
|
|
39
|
+
throw new ClarusError(`<${node.tag}> could be ${found.join(' or ')}: use its full name, or @import the one you mean`, file, source, node.start);
|
|
40
|
+
}
|
|
41
|
+
if (found) {
|
|
42
|
+
parsed.imports.push({ name: node.tag, from: found, start: 0 });
|
|
43
|
+
imported.add(node.tag);
|
|
44
|
+
}
|
|
45
|
+
walk(node.children);
|
|
46
|
+
}
|
|
47
|
+
else if (node.type === 'if')
|
|
48
|
+
for (const b of node.branches)
|
|
49
|
+
walk(b.children);
|
|
50
|
+
else if (node.type === 'for') {
|
|
51
|
+
walk(node.children);
|
|
52
|
+
if (node.empty)
|
|
53
|
+
walk(node.empty);
|
|
54
|
+
}
|
|
55
|
+
else if (node.type === 'fill')
|
|
56
|
+
walk(node.children);
|
|
57
|
+
else if (node.type === 'await')
|
|
58
|
+
for (const kids of awaitLists(node))
|
|
59
|
+
walk(kids);
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
walk(parsed.nodes);
|
|
63
|
+
}
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import { FOR_IMPLICIT } from './parse.js';
|
|
2
2
|
import { attrValueExpr, componentCall, htmlExpr, tagArg, walk, whichExpr, rowNames, rowParams, rowDerived } from './html-expr.js';
|
|
3
3
|
import { formName, rewriteClient, rewriteClientExpr, wrapExpr } from './script.js';
|
|
4
|
-
import { indentScript, inputsLine, renderName } from './shared.js';
|
|
4
|
+
import { contextLines, indentScript, inputsLine, renderName } from './shared.js';
|
|
5
5
|
export function emitClient(ir, hot) {
|
|
6
6
|
if (!ir.stateful)
|
|
7
7
|
return 'export {}\n';
|
|
8
8
|
const kinds = new Set(ir.signals.values());
|
|
9
9
|
const all = walk(ir.nodes);
|
|
10
10
|
const hasHoles = all.some((n) => n.kind === 'hole' && n.reactive);
|
|
11
|
-
const hasBlocks = all.some((n) => n.kind === 'if' && n.block >= 0);
|
|
11
|
+
const hasBlocks = all.some((n) => (n.kind === 'if' || n.kind === 'await') && n.block >= 0);
|
|
12
12
|
const hasFors = all.some((n) => n.kind === 'for' && n.block >= 0);
|
|
13
13
|
const hasRegions = all.some((n) => n.kind === 'component' && n.region >= 0);
|
|
14
14
|
const rendersHtml = hasBlocks || hasFors || hasRegions;
|
|
@@ -22,15 +22,20 @@ export function emitClient(ir, hot) {
|
|
|
22
22
|
all.some((n) => n.kind === 'attr' && n.reactive && n.name !== '...') && 'attr as __cl_attr',
|
|
23
23
|
all.some((n) => n.kind === 'attr' && n.reactive && n.name === '...') && 'spread as __cl_spread',
|
|
24
24
|
hasBlocks && 'block as __cl_block',
|
|
25
|
+
all.some((n) => n.kind === 'await' && n.block >= 0) && 'awaited as __cl_awaited',
|
|
25
26
|
hasFors && 'forBlock as __cl_for',
|
|
26
27
|
all.some((n) => n.kind === 'for' && n.block >= 0 && rowNames(n, ir.events).some((x) => x !== '$count')) && 'derived as __cl_derived',
|
|
27
28
|
hasRegions && 'region as __cl_region',
|
|
28
29
|
all.some((n) => n.kind === 'component' && !!n.models?.length) && 'model as __cl_model',
|
|
30
|
+
all.some((n) => n.kind === 'component' && !!n.listens?.length) && 'listen as __cl_listen',
|
|
31
|
+
all.some((n) => n.kind === 'use') && 'use as __cl_useOn',
|
|
32
|
+
ir.sends && 'emit as __cl_emit',
|
|
33
|
+
ir.provides && 'provideOn as __cl_provideOn',
|
|
29
34
|
kinds.has('model') && 'modelInput as __cl_modelInput',
|
|
30
35
|
ir.inputs.some((i) => kinds.has('input') || i.model) && 'batch as __cl_batch',
|
|
31
36
|
rendersHtml && 'escape as __cl_escape',
|
|
32
37
|
rendersHtml && all.some((n) => n.kind === 'attr' && n.name !== '...') && 'attrHtml as __cl_attrHtml',
|
|
33
|
-
rendersHtml && all.some((n) => n.kind === 'attr' && n.name === '...') && 'spreadHtml as __cl_spreadHtml',
|
|
38
|
+
rendersHtml && all.some((n) => n.kind === 'attr' && n.name === '...' && !('expr' in n.value && n.value.expr === '__cl_attrs')) && 'spreadHtml as __cl_spreadHtml',
|
|
34
39
|
rendersHtml && hasBlocks && 'blockHtml as __cl_blockHtml',
|
|
35
40
|
rendersHtml && hasFors && 'forHtml as __cl_forHtml',
|
|
36
41
|
hasRegions && 'regionHtml as __cl_regionHtml',
|
|
@@ -53,6 +58,11 @@ export function emitClient(ir, hot) {
|
|
|
53
58
|
out += `${line}\n`;
|
|
54
59
|
out += `\nexport function attach(__cl_root, __cl_props = {}, __cl_state) {\n`;
|
|
55
60
|
out += ` const __cl_class = __cl_props.__cl_class ? " " + __cl_props.__cl_class : ""\n`;
|
|
61
|
+
if (ir.sends)
|
|
62
|
+
out += ` const emit = (name, value, info) => __cl_emit(__cl_root, name, value, info)\n`;
|
|
63
|
+
out += contextLines(ir, 'undefined');
|
|
64
|
+
if (ir.provides)
|
|
65
|
+
out += ` __cl_provideOn(__cl_root, __cl_cx)\n`;
|
|
56
66
|
const inputs = ir.inputs.filter((i) => ir.signals.get(i.name) === 'input' || ir.signals.get(i.name) === 'model');
|
|
57
67
|
const value = (i, from) => i.default === undefined ? `${from}.${i.name}` : `${from}.${i.name} === undefined ? (${rewriteClientExpr(i.default, ir.signals)}) : ${from}.${i.name}`;
|
|
58
68
|
for (const i of inputs) {
|
|
@@ -96,6 +106,8 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
|
|
|
96
106
|
lines.push(`__cl_attr(${ctx}, ${a.index}, ${JSON.stringify(a.name)}, () => ${attrValueExpr(a.value, rw.expr)}${tagArg(a)})`);
|
|
97
107
|
if (a.kind === 'connect')
|
|
98
108
|
lines.push(`__cl_connect(${ctx}, ${a.index}, () => ${wrapExpr(rw.expr(a.expr))})`);
|
|
109
|
+
if (a.kind === 'use')
|
|
110
|
+
lines.push(`__cl_useOn(${ctx}, ${a.index}, () => ${wrapExpr(rw.expr(a.expr))})`);
|
|
99
111
|
}
|
|
100
112
|
for (const e of ir.events.filter((ev) => ev.scope === scope)) {
|
|
101
113
|
const body = rewriteClient(e.handler, signals).trim();
|
|
@@ -106,14 +118,31 @@ function wiring(ir, nodes, scope, ctx, signals, depth) {
|
|
|
106
118
|
for (const n of nodes) {
|
|
107
119
|
if (n.kind === 'component' && n.region >= 0) {
|
|
108
120
|
const content = [...n.children, ...n.fills.flatMap((f) => f.nodes)];
|
|
109
|
-
lines.push(`__cl_region(${ctx}, ${n.region}, () => ${componentCall(n, rw)}, ${fn('', wiring(ir, content, `c${n.region}`, ctx, signals, depth))})`);
|
|
121
|
+
lines.push(`__cl_region(${ctx}, ${n.region}, (__cl_cx) => ${componentCall(n, rw)}, ${fn('', wiring(ir, content, `c${n.region}`, ctx, signals, depth))}, __cl_cx)`);
|
|
110
122
|
for (const m of n.models ?? [])
|
|
111
123
|
lines.push(`__cl_model(${ctx}, ${n.region}, ${JSON.stringify(m.name)}, (__cl_v) => { ${rewriteClient(m.set, signals).trim()} })`);
|
|
124
|
+
for (const l of n.listens ?? []) {
|
|
125
|
+
const body = rewriteClient(l.handler, signals).trim();
|
|
126
|
+
lines.push(`__cl_listen(${ctx}, ${n.region}, ${JSON.stringify(l.name)}, ($event, $info) => { ${body}${body.includes('//') ? '\n ' : ' '}})`);
|
|
127
|
+
}
|
|
112
128
|
}
|
|
113
129
|
if (n.kind === 'if' && n.block >= 0) {
|
|
114
130
|
const branches = n.branches.map((b, i) => ` { html: () => ${htmlExpr(b.nodes, rw)}, wire: ${fn('', wiring(ir, b.nodes, `${n.block}.${i}`, ctx, signals, depth))} },`);
|
|
115
131
|
lines.push(`__cl_block(${ctx}, ${n.block}, () => ${whichExpr(n, rw)}, [\n${branches.join('\n')}\n ])`);
|
|
116
132
|
}
|
|
133
|
+
if (n.kind === 'await' && n.block >= 0) {
|
|
134
|
+
const a = `__cl_a${n.block}`;
|
|
135
|
+
lines.push(`const ${a} = __cl_awaited(() => ${wrapExpr(rw.expr(n.expr))})`);
|
|
136
|
+
const named = (b, k) => {
|
|
137
|
+
if (!b)
|
|
138
|
+
return ` { html: () => "", wire: () => {} },`;
|
|
139
|
+
const plain = rw.without([b.name]);
|
|
140
|
+
const wire = wiring(ir, b.nodes, `${n.block}.${k}`, ctx, new Map([...signals].filter(([name]) => name !== b.name)), depth);
|
|
141
|
+
return ` { html: () => ((${b.name}) => ${htmlExpr(b.nodes, plain)})(${a}.v()), wire: ${fn('', wire.length ? [`const ${b.name} = ${a}.v()`, ...wire] : [])} },`;
|
|
142
|
+
};
|
|
143
|
+
const branches = [` { html: () => ${htmlExpr(n.pending, rw)}, wire: ${fn('', wiring(ir, n.pending, `${n.block}.0`, ctx, signals, depth))} },`, named(n.then, 1), named(n.catch, 2)];
|
|
144
|
+
lines.push(`__cl_block(${ctx}, ${n.block}, () => ${a}.k(), [\n${branches.join('\n')}\n ])`);
|
|
145
|
+
}
|
|
117
146
|
if (n.kind === 'for' && n.block >= 0) {
|
|
118
147
|
const rowCtx = `__cl_c${depth + 1}`;
|
|
119
148
|
const names = rowNames(n, ir.events);
|