clarusjs 0.8.0 → 0.9.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 +26 -4
- package/dist/check/generate.js +160 -21
- package/dist/cli/check.d.ts +13 -0
- package/dist/cli/check.js +76 -19
- package/dist/cli/index.js +9 -3
- package/dist/cli/mapper.d.ts +25 -0
- package/dist/cli/mapper.js +65 -0
- package/dist/cli/project.d.ts +5 -0
- package/dist/cli/project.js +21 -0
- package/dist/compiler/emit-client.js +23 -4
- package/dist/compiler/emit-server.js +3 -2
- package/dist/compiler/html-expr.js +5 -2
- package/dist/compiler/index.d.ts +8 -1
- package/dist/compiler/index.js +34 -23
- package/dist/compiler/ir.d.ts +13 -0
- package/dist/compiler/ir.js +157 -7
- package/dist/compiler/parse.d.ts +18 -1
- package/dist/compiler/parse.js +134 -6
- package/dist/compiler/script.d.ts +22 -1
- package/dist/compiler/script.js +81 -5
- package/dist/forms/index.d.ts +7 -0
- package/dist/forms/index.js +374 -0
- package/dist/forms/types.d.ts +94 -0
- package/dist/forms/types.js +1 -0
- package/dist/runtime/dom.d.ts +12 -5
- package/dist/runtime/dom.js +76 -5
- package/dist/runtime/env.d.ts +7 -0
- package/dist/runtime/env.js +7 -0
- package/dist/runtime/fragments.d.ts +1 -1
- package/dist/runtime/fragments.js +10 -35
- package/dist/runtime/index.d.ts +3 -2
- package/dist/runtime/index.js +3 -2
- package/dist/runtime/loader.d.ts +1 -1
- package/dist/runtime/loader.js +38 -5
- package/dist/runtime/navigate.d.ts +38 -0
- package/dist/runtime/navigate.js +88 -0
- package/dist/runtime/navigation.d.ts +88 -0
- package/dist/runtime/navigation.js +165 -0
- package/dist/runtime/router.d.ts +8 -1
- package/dist/runtime/router.js +38 -40
- package/dist/runtime/server.d.ts +1 -1
- package/dist/runtime/server.js +4 -2
- package/dist/runtime/signals.d.ts +2 -0
- package/dist/runtime/signals.js +25 -3
- package/dist/server/handler.d.ts +8 -0
- package/dist/server/handler.js +36 -9
- package/dist/vite/aliases.d.ts +10 -0
- package/dist/vite/aliases.js +42 -0
- package/dist/vite/build.d.ts +2 -1
- package/dist/vite/build.js +3 -2
- package/dist/vite/plugin.d.ts +6 -0
- package/dist/vite/plugin.js +82 -20
- package/dist/vite/redirects.d.ts +10 -0
- package/dist/vite/redirects.js +41 -0
- package/package.json +29 -1
package/dist/check/generate.d.ts
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* [virtual offset, length, source offset, exact]. Exact spans are verbatim copies (offsets map one to
|
|
3
|
-
* spans stand for a whole template construct
|
|
2
|
+
* [virtual offset, length, source offset, exact, source length]. Exact spans are verbatim copies (offsets map one to
|
|
3
|
+
* one); other spans stand for a whole template construct (a component's tag, a binding's name): the source length
|
|
4
|
+
* says how much of the template that is.
|
|
4
5
|
*/
|
|
5
|
-
export type Mapping = [number, number, number, boolean];
|
|
6
|
+
export type Mapping = [number, number, number, boolean, number?];
|
|
6
7
|
/**
|
|
7
8
|
* `loader`: the module specifier of the page's .load.ts when it exports load(); what it returns is checked against
|
|
8
|
-
* the page's inputs. `
|
|
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.
|
|
9
11
|
*/
|
|
10
12
|
export declare function generateTs(source: string, file: string, options?: {
|
|
11
13
|
loader?: string;
|
|
14
|
+
componentSuffix?: string;
|
|
12
15
|
}): {
|
|
13
16
|
code: string;
|
|
14
17
|
mappings: Mapping[];
|
|
@@ -25,3 +28,22 @@ export declare function viewsDeclaration(views: {
|
|
|
25
28
|
file: string;
|
|
26
29
|
source: string;
|
|
27
30
|
}[]): string;
|
|
31
|
+
/**
|
|
32
|
+
* .clarusjs/routes.d.ts: every page's route → its params, for href() from clarusjs/navigation. A page is any file
|
|
33
|
+
* under src/pages but scripts (.ts/.js, so .load.ts too), styles and data, and _-prefixed files (partials). Markdown
|
|
34
|
+
* and other page sources count, though check only type-checks .tscl pages (#142).
|
|
35
|
+
*/
|
|
36
|
+
export declare function routesDeclaration(files: string[]): string;
|
|
37
|
+
/**
|
|
38
|
+
* generateTs for a template that may not parse, as an editor has it while someone types: each error is collected and
|
|
39
|
+
* the text repaired (what's open at the end is closed; any other error blanks its line, from the error on, then whole)
|
|
40
|
+
* until it parses, so TypeScript still covers the rest. Repairs only append or replace with spaces, so every offset
|
|
41
|
+
* in `source` stays where it was. `result` is null if it still doesn't parse after a few repairs.
|
|
42
|
+
*/
|
|
43
|
+
export declare function generateTolerant(source: string, file: string, options?: Parameters<typeof generateTs>[2]): {
|
|
44
|
+
result: ReturnType<typeof generateTs> | null;
|
|
45
|
+
errors: {
|
|
46
|
+
message: string;
|
|
47
|
+
offset: number;
|
|
48
|
+
}[];
|
|
49
|
+
};
|
package/dist/check/generate.js
CHANGED
|
@@ -1,28 +1,36 @@
|
|
|
1
|
+
import { routeFromFile } from '../server/handler.js';
|
|
2
|
+
import { ClarusError } from '../compiler/errors.js';
|
|
1
3
|
import { parse } from '../compiler/parse.js';
|
|
2
|
-
import { splitImports } from '../compiler/script.js';
|
|
4
|
+
import { referencesNames, splitImports, untypedParams } from '../compiler/script.js';
|
|
5
|
+
const ENUMERATED = new Set(['draggable', 'spellcheck', 'translate', 'autocorrect', 'contenteditable']);
|
|
6
|
+
const PROPERTY = { readonly: 'readOnly', novalidate: 'noValidate', formnovalidate: 'formNoValidate', allowfullscreen: 'allowFullscreen', playsinline: 'playsInline', nomodule: 'noModule', ismap: 'isMap' };
|
|
3
7
|
export function generateTs(source, file, options = {}) {
|
|
4
8
|
const parsed = parse(source, file);
|
|
5
9
|
const mappings = [];
|
|
6
10
|
let code = '';
|
|
7
11
|
const emit = (text) => { code += text; };
|
|
8
12
|
const copy = (text, sourceStart) => { mappings.push([code.length, text.length, sourceStart, true]); code += text; };
|
|
9
|
-
const point = (text, sourceStart) => { mappings.push([code.length, text.length, sourceStart, false]); code += text; };
|
|
13
|
+
const point = (text, sourceStart, sourceLength = 1) => { mappings.push([code.length, text.length, sourceStart, false, sourceLength]); code += text; };
|
|
10
14
|
const at = (text, from) => source.indexOf(text, from);
|
|
11
15
|
const components = new Map(parsed.imports.map((imp) => [imp.name, imp]));
|
|
12
16
|
const alias = (name) => `__cl_I_${name.replace(/-/g, '$')}`;
|
|
13
17
|
emit('// Generated by clarusjs for type checking. It never runs.\n');
|
|
14
|
-
emit('declare function state<T>(value: T): T\n');
|
|
18
|
+
emit('declare function state<T>(value: T): T extends never[] ? any[] : T\n');
|
|
15
19
|
emit('declare function derived<T>(fn: () => T): T\n');
|
|
16
20
|
emit('declare function shared<T>(store: { get(): T }): T\n');
|
|
17
21
|
emit('declare function __cl_use(value: unknown): void\n');
|
|
18
|
-
|
|
22
|
+
const text = 'string | number | boolean | null | undefined';
|
|
23
|
+
emit(`type __cl_AttrOf<T extends string, P extends string> = T extends keyof HTMLElementTagNameMap ? P extends keyof HTMLElementTagNameMap[T] ? (HTMLElementTagNameMap[T][P] extends boolean ? boolean | null | undefined : ${text}) : ${text} : ${text}\n`);
|
|
24
|
+
emit('declare function __cl_attr<T extends string, P extends string>(value: __cl_AttrOf<T, P>): void\n');
|
|
25
|
+
emit('export type __cl_El<T extends string> = T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : T extends keyof SVGElementTagNameMap ? SVGElementTagNameMap[T] : HTMLElement\n');
|
|
26
|
+
emit('export type __cl_Event<K extends string, E = HTMLElement> = (K extends keyof HTMLElementEventMap ? HTMLElementEventMap[K] : CustomEvent) & { target: any; currentTarget: E }\n');
|
|
19
27
|
for (const t of parsed.typeImports) {
|
|
20
28
|
emit('import type ');
|
|
21
29
|
copy(t.clause, t.clauseStart);
|
|
22
30
|
emit(` from ${JSON.stringify(t.from)}\n`);
|
|
23
31
|
}
|
|
24
32
|
for (const imp of parsed.imports)
|
|
25
|
-
emit(`import type { Inputs as ${alias(imp.name)} } from ${JSON.stringify(`${imp.from}.ts`)}\n`);
|
|
33
|
+
emit(`import type { Inputs as ${alias(imp.name)}, Models as ${alias(imp.name)}_M } from ${JSON.stringify(`${imp.from}${options.componentSuffix ?? '.ts'}`)}\n`);
|
|
26
34
|
for (const d of parsed.dataImports) {
|
|
27
35
|
emit('import ');
|
|
28
36
|
copy(d.clause, d.clauseStart);
|
|
@@ -37,7 +45,14 @@ export function generateTs(source, file, options = {}) {
|
|
|
37
45
|
emit('\n');
|
|
38
46
|
}
|
|
39
47
|
}
|
|
48
|
+
for (const t of parsed.types) {
|
|
49
|
+
emit(t.kind === 'interface' ? `interface ${t.name}${t.params ?? ''} ` : `type ${t.name}${t.params ?? ''} = `);
|
|
50
|
+
copy(t.type, t.typeStart);
|
|
51
|
+
emit('\n');
|
|
52
|
+
}
|
|
40
53
|
emit('\nexport interface Inputs {\n');
|
|
54
|
+
if (!parsed.inputs.length)
|
|
55
|
+
emit(' __cl_none?: never\n');
|
|
41
56
|
for (const input of parsed.inputs) {
|
|
42
57
|
emit(' ');
|
|
43
58
|
copy(input.name, input.nameStart);
|
|
@@ -46,18 +61,24 @@ export function generateTs(source, file, options = {}) {
|
|
|
46
61
|
emit('\n');
|
|
47
62
|
}
|
|
48
63
|
emit('}\n');
|
|
64
|
+
const models = parsed.inputs.filter((i) => i.model).map((i) => JSON.stringify(i.name));
|
|
65
|
+
emit(`export type Models = ${models.length ? models.join(' | ') : 'never'}\n`);
|
|
49
66
|
let loaderSpan;
|
|
50
67
|
if (options.loader) {
|
|
51
|
-
emit('declare const __cl_loaded: Awaited<ReturnType<typeof __cl_load
|
|
68
|
+
emit('declare const __cl_loaded: Exclude<Awaited<ReturnType<typeof __cl_load>>, Response>\n');
|
|
52
69
|
const start = code.length;
|
|
53
70
|
point('const __cl_from_load: Partial<Inputs> = __cl_loaded', 0);
|
|
54
71
|
loaderSpan = [start, code.length];
|
|
72
|
+
emit('; __cl_use(__cl_from_load)');
|
|
55
73
|
emit('\n');
|
|
56
74
|
}
|
|
57
|
-
emit('
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
75
|
+
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');
|
|
76
|
+
emit('\nexport default function __cl_check(__cl_props: __cl_Readonly<Inputs>) {\n');
|
|
77
|
+
for (const [keyword, list] of [['const', parsed.inputs.filter((x) => !x.model)], ['let', parsed.inputs.filter((x) => x.model)]]) {
|
|
78
|
+
if (!list.length)
|
|
79
|
+
continue;
|
|
80
|
+
emit(` ${keyword} { `);
|
|
81
|
+
list.forEach((input, i) => {
|
|
61
82
|
if (i)
|
|
62
83
|
emit(', ');
|
|
63
84
|
copy(input.name, input.nameStart);
|
|
@@ -67,9 +88,23 @@ export function generateTs(source, file, options = {}) {
|
|
|
67
88
|
}
|
|
68
89
|
});
|
|
69
90
|
emit(' } = __cl_props\n');
|
|
91
|
+
emit(` __cl_use([${list.map((x) => x.name).join(', ')}])\n`);
|
|
70
92
|
}
|
|
71
93
|
if (parsed.script && script) {
|
|
72
|
-
|
|
94
|
+
const body = script.body;
|
|
95
|
+
const cuts = [
|
|
96
|
+
...script.imports.map((imp) => ({ at: imp.start, end: imp.start + imp.text.length, text: body.slice(imp.start, imp.start + imp.text.length) })),
|
|
97
|
+
...untypedParams(parsed.script.code).map((e) => ({ ...e, end: e.at })),
|
|
98
|
+
].sort((a, b) => a.at - b.at);
|
|
99
|
+
let pos = 0;
|
|
100
|
+
for (const cut of cuts) {
|
|
101
|
+
if (cut.at > pos)
|
|
102
|
+
copy(body.slice(pos, cut.at), parsed.script.start + pos);
|
|
103
|
+
emit(cut.text);
|
|
104
|
+
pos = Math.max(pos, cut.end);
|
|
105
|
+
}
|
|
106
|
+
if (body.length > pos)
|
|
107
|
+
copy(body.slice(pos), parsed.script.start + pos);
|
|
73
108
|
emit('\n;\n');
|
|
74
109
|
}
|
|
75
110
|
const use = (expr, start) => {
|
|
@@ -77,7 +112,21 @@ export function generateTs(source, file, options = {}) {
|
|
|
77
112
|
copy(expr, at(expr, start));
|
|
78
113
|
emit('));\n');
|
|
79
114
|
};
|
|
80
|
-
const attrValueStart = (a) => a.start + a.name.length + (a.kind === 'static' || a.kind === 'interp' ? 2 : 4);
|
|
115
|
+
const attrValueStart = (a) => a.start + a.name.length + (a.kind === 'static' || a.kind === 'interp' ? 2 : a.kind === 'model' ? 6 : 4);
|
|
116
|
+
const guards = [];
|
|
117
|
+
const guarded = () => {
|
|
118
|
+
if (guards.length)
|
|
119
|
+
emit(`\n // @ts-ignore\n if (${guards.join(' && ')})\n `);
|
|
120
|
+
};
|
|
121
|
+
const writable = (a) => {
|
|
122
|
+
emit(' ;(() => { ');
|
|
123
|
+
guarded();
|
|
124
|
+
emit('(');
|
|
125
|
+
copy(a.expr, at(a.expr, attrValueStart(a)));
|
|
126
|
+
emit(') = (');
|
|
127
|
+
copy(a.expr, at(a.expr, attrValueStart(a)));
|
|
128
|
+
emit(') });\n');
|
|
129
|
+
};
|
|
81
130
|
function visit(node) {
|
|
82
131
|
switch (node.type) {
|
|
83
132
|
case 'text':
|
|
@@ -97,7 +146,10 @@ export function generateTs(source, file, options = {}) {
|
|
|
97
146
|
copy(b.cond, at(b.cond, b.condStart));
|
|
98
147
|
emit(')) {\n');
|
|
99
148
|
}
|
|
149
|
+
const earlier = node.branches.slice(0, i).map((x) => `!(${x.cond})`);
|
|
150
|
+
guards.push([...earlier, ...(b.cond === null ? [] : [`(${b.cond})`])].join(' && ') || 'true');
|
|
100
151
|
b.children.forEach(visit);
|
|
152
|
+
guards.pop();
|
|
101
153
|
emit(' }\n');
|
|
102
154
|
});
|
|
103
155
|
return;
|
|
@@ -106,10 +158,13 @@ export function generateTs(source, file, options = {}) {
|
|
|
106
158
|
copy(node.item, node.itemStart);
|
|
107
159
|
emit(' of ');
|
|
108
160
|
copy(node.list, node.listStart);
|
|
109
|
-
emit(') {\n const $index: number = 0\n');
|
|
161
|
+
emit(') {\n const $index: number = 0; __cl_use($index)\n');
|
|
110
162
|
if (node.track !== null)
|
|
111
163
|
use(node.track, node.trackStart);
|
|
164
|
+
const outer = guards.splice(0);
|
|
165
|
+
guards.push(...outer.filter((g) => !referencesNames(g, new Set([node.item, '$index']))));
|
|
112
166
|
node.children.forEach(visit);
|
|
167
|
+
guards.splice(0, guards.length, ...outer);
|
|
113
168
|
emit(' }\n');
|
|
114
169
|
if (node.empty) {
|
|
115
170
|
emit(' {\n');
|
|
@@ -122,32 +177,57 @@ export function generateTs(source, file, options = {}) {
|
|
|
122
177
|
const component = components.get(node.tag);
|
|
123
178
|
if (component) {
|
|
124
179
|
emit(' { const ');
|
|
125
|
-
point('__cl_p', node.start);
|
|
126
|
-
emit(`:
|
|
180
|
+
point('__cl_p', node.start, node.tag.length + 1);
|
|
181
|
+
emit(`: __cl_Readonly<${alias(node.tag)}> = { `);
|
|
127
182
|
for (const a of node.attrs) {
|
|
128
|
-
if (a.kind !== 'prop')
|
|
183
|
+
if (a.kind !== 'prop' && a.kind !== 'model')
|
|
129
184
|
continue;
|
|
130
|
-
copy(a.name, a.start + 1);
|
|
185
|
+
copy(a.name, a.start + (a.kind === 'model' ? 2 : 1));
|
|
131
186
|
emit(': (');
|
|
132
187
|
copy(a.expr, at(a.expr, attrValueStart(a)));
|
|
133
188
|
emit('), ');
|
|
134
189
|
}
|
|
135
190
|
emit('}; __cl_use(__cl_p) }\n');
|
|
191
|
+
for (const a of node.attrs) {
|
|
192
|
+
if (a.kind !== 'model')
|
|
193
|
+
continue;
|
|
194
|
+
emit(' { const ');
|
|
195
|
+
point('__cl_m', a.start, a.name.length + 4);
|
|
196
|
+
emit(`: ${alias(node.tag)}_M = ${JSON.stringify(a.name)}; __cl_use(__cl_m) }\n`);
|
|
197
|
+
emit(' ;(() => { ');
|
|
198
|
+
guarded();
|
|
199
|
+
copy(a.expr, at(a.expr, attrValueStart(a)));
|
|
200
|
+
emit(` = (undefined as unknown as Exclude<${alias(node.tag)}[${JSON.stringify(a.name)}], undefined>) });\n`);
|
|
201
|
+
}
|
|
136
202
|
node.children.forEach(visit);
|
|
137
203
|
return;
|
|
138
204
|
}
|
|
139
205
|
for (const a of node.attrs) {
|
|
140
|
-
if (a.kind === '
|
|
206
|
+
if (a.kind === 'model') {
|
|
141
207
|
use(a.expr, attrValueStart(a));
|
|
208
|
+
writable(a);
|
|
209
|
+
}
|
|
210
|
+
else if (a.kind === 'prop' && a.name === 'engine') {
|
|
211
|
+
emit(` ;((__cl_f: import('clarusjs/forms').Form<any>) => __cl_use(__cl_f))((`);
|
|
212
|
+
copy(a.expr, at(a.expr, attrValueStart(a)));
|
|
213
|
+
emit('));\n');
|
|
214
|
+
}
|
|
215
|
+
else if (a.kind === 'prop') {
|
|
216
|
+
emit(` __cl_attr<${JSON.stringify(node.tag.toLowerCase())}, ${JSON.stringify(ENUMERATED.has(a.name.toLowerCase()) ? '' : PROPERTY[a.name.toLowerCase()] ?? a.name.toLowerCase())}>((`);
|
|
217
|
+
copy(a.expr, at(a.expr, attrValueStart(a)));
|
|
218
|
+
emit('));\n');
|
|
219
|
+
}
|
|
142
220
|
else if (a.kind === 'interp') {
|
|
143
221
|
for (const p of a.parts)
|
|
144
222
|
if (typeof p !== 'string')
|
|
145
223
|
use(p.expr, p.start + 2);
|
|
146
224
|
}
|
|
147
225
|
else if (a.kind === 'event') {
|
|
148
|
-
emit(` ;(($event: __cl_Event<${JSON.stringify(a.name)}
|
|
226
|
+
emit(` ;(($event: __cl_Event<${JSON.stringify(a.name)}, __cl_El<${JSON.stringify(node.tag.toLowerCase())}>>) => { `);
|
|
227
|
+
guarded();
|
|
228
|
+
emit('{ ');
|
|
149
229
|
copy(a.expr, at(a.expr, attrValueStart(a)));
|
|
150
|
-
emit(' });\n');
|
|
230
|
+
emit(' } });\n');
|
|
151
231
|
}
|
|
152
232
|
}
|
|
153
233
|
node.children.forEach(visit);
|
|
@@ -202,13 +282,72 @@ export function viewsDeclaration(views) {
|
|
|
202
282
|
body.push(` type ${clause} = import(${JSON.stringify(from)}).default`);
|
|
203
283
|
}
|
|
204
284
|
}
|
|
285
|
+
for (const t of parsed.types)
|
|
286
|
+
body.push(t.kind === 'interface' ? ` interface ${t.name}${t.params ?? ''} ${t.type}` : ` type ${t.name}${t.params ?? ''} = ${t.type}`);
|
|
205
287
|
body.push(` interface Inputs {`);
|
|
288
|
+
if (!parsed.inputs.length)
|
|
289
|
+
body.push(' __cl_none?: never');
|
|
206
290
|
for (const input of parsed.inputs)
|
|
207
291
|
body.push(` ${input.name}${input.default !== undefined ? '?' : ''}: ${input.type}`);
|
|
208
292
|
body.push(' }');
|
|
209
293
|
lines.push(`declare namespace ${ns} {`, ...body, '}');
|
|
210
|
-
entries.push(` ${JSON.stringify(file.replace(/^src\//, '').replace(/\.
|
|
294
|
+
entries.push(` ${JSON.stringify(file.replace(/^src\//, '').replace(/\.[^./]+$/, ''))}: ${ns}.Inputs`);
|
|
211
295
|
});
|
|
212
296
|
lines.push("declare module 'clarusjs/views' {", ' interface Views {', ...entries, ' }', '}', 'export {}', '');
|
|
213
297
|
return lines.join('\n');
|
|
214
298
|
}
|
|
299
|
+
export function routesDeclaration(files) {
|
|
300
|
+
const pages = files.filter((f) => f.startsWith('src/pages/') && !/\.(m?[jt]s|css|json)$/.test(f) && !/(^|\/)_[^/]*$/.test(f));
|
|
301
|
+
const routes = [...new Set(pages.map((f) => routeFromFile(`/${f}`)))].sort();
|
|
302
|
+
const entries = routes.map((route) => {
|
|
303
|
+
const keys = [...route.matchAll(/\[([^\]]+)\]/g)].map((m) => m[1]);
|
|
304
|
+
return ` ${JSON.stringify(route)}: ${keys.length ? `{ ${keys.map((k) => `${k}: string`).join('; ')} }` : '{}'}`;
|
|
305
|
+
});
|
|
306
|
+
return ['// Generated by clarusjs check: every page route → its params, for href() from clarusjs/navigation.', "declare module 'clarusjs/navigation' {", ' interface Routes {', ...entries, ' }', '}', 'export {}', ''].join('\n');
|
|
307
|
+
}
|
|
308
|
+
function located(err, source) {
|
|
309
|
+
const lines = source.split('\n');
|
|
310
|
+
const offset = Math.min(source.length, lines.slice(0, err.line - 1).reduce((n, l) => n + l.length + 1, 0) + err.column - 1);
|
|
311
|
+
return { text: err.message.slice(`${err.file}:${err.line}:${err.column} `.length), offset };
|
|
312
|
+
}
|
|
313
|
+
const CLOSERS = [
|
|
314
|
+
[/^unclosed \{\{--/, () => ' --}}'],
|
|
315
|
+
[/^unclosed <!--/, () => ' -->'],
|
|
316
|
+
[/^unclosed \{\{$/, () => ' }}'],
|
|
317
|
+
[/^unclosed <\/([\w:-]+)>$/, () => '>'],
|
|
318
|
+
[/^unclosed <(script|style)\b/, (m) => `</${m[1]}>`],
|
|
319
|
+
[/^unclosed <([\w:-]+)(?: verbatim)?>$/, (m) => `</${m[1]}>`],
|
|
320
|
+
[/^unclosed @?[\w-]+ block$/, () => '\n}'],
|
|
321
|
+
];
|
|
322
|
+
export function generateTolerant(source, file, options = {}) {
|
|
323
|
+
const errors = [];
|
|
324
|
+
let text = source;
|
|
325
|
+
for (let tries = 0; tries < 20; tries++) {
|
|
326
|
+
try {
|
|
327
|
+
const result = generateTs(text, file, options);
|
|
328
|
+
result.mappings = result.mappings.filter(([, , s]) => s < source.length).map((m) => (m[2] + m[1] > source.length && m[3] ? [m[0], m[1], m[2], false, source.length - m[2]] : m));
|
|
329
|
+
return { result, errors };
|
|
330
|
+
}
|
|
331
|
+
catch (err) {
|
|
332
|
+
if (!(err instanceof ClarusError))
|
|
333
|
+
throw err;
|
|
334
|
+
const { text: message, offset } = located(err, text);
|
|
335
|
+
if (!errors.some((e) => e.message === message && e.offset === offset))
|
|
336
|
+
errors.push({ message, offset: Math.min(offset, source.length) });
|
|
337
|
+
const closer = CLOSERS.map(([re, close]) => { const m = re.exec(message); return m && close(m); }).find((c) => c);
|
|
338
|
+
if (closer && text.slice(offset).indexOf('\n', 1) === -1 || closer && /^unclosed (<[\w:-]+|@?[\w-]+ block)/.test(message)) {
|
|
339
|
+
text += closer;
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
const from = /@|block|\( after|\(\s*$/.test(message) && text.lastIndexOf('@', offset) !== -1 ? text.lastIndexOf('@', offset) : offset;
|
|
343
|
+
const lineStart = text.lastIndexOf('\n', from - 1) + 1;
|
|
344
|
+
const lineEnd = text.indexOf('\n', from) === -1 ? text.length : text.indexOf('\n', from);
|
|
345
|
+
const blank = (from) => text.slice(0, from) + text.slice(from, lineEnd).replace(/[^\n]/g, ' ') + text.slice(lineEnd);
|
|
346
|
+
const next = blank(from) !== text ? blank(from) : blank(lineStart);
|
|
347
|
+
if (next === text)
|
|
348
|
+
break;
|
|
349
|
+
text = next;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
return { result: null, errors };
|
|
353
|
+
}
|
package/dist/cli/check.d.ts
CHANGED
|
@@ -11,7 +11,20 @@ export type CheckResult = {
|
|
|
11
11
|
text: string;
|
|
12
12
|
json: string;
|
|
13
13
|
};
|
|
14
|
+
/** A page's .load.ts that exports load(), as an import specifier: what it returns is checked against the inputs. */
|
|
15
|
+
export declare function loaderOf(path: string): string | undefined;
|
|
16
|
+
/** A page source, as the Vite plugin's `sources` option takes it (Markdown from @clarusjs/content, …). */
|
|
17
|
+
export type CheckSource = {
|
|
18
|
+
extension: string;
|
|
19
|
+
toTscl(code: string, file: string, context: {
|
|
20
|
+
route: string;
|
|
21
|
+
root: string;
|
|
22
|
+
addDependency(file: string): void;
|
|
23
|
+
}): string;
|
|
24
|
+
};
|
|
14
25
|
export declare function check(options: {
|
|
15
26
|
root: string;
|
|
16
27
|
typescript?: string;
|
|
28
|
+
sources?: CheckSource[];
|
|
29
|
+
viteAliases?: unknown;
|
|
17
30
|
}): CheckResult;
|
package/dist/cli/check.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { spawnSync } from 'node:child_process';
|
|
2
|
-
import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
3
|
import { createRequire } from 'node:module';
|
|
4
4
|
import { basename, dirname, relative, resolve, sep } from 'node:path';
|
|
5
5
|
import { ClarusError } from '../compiler/errors.js';
|
|
6
|
-
import { generateTs, toSourceOffset, viewsDeclaration } from '../check/generate.js';
|
|
6
|
+
import { generateTs, routesDeclaration, toSourceOffset, viewsDeclaration } from '../check/generate.js';
|
|
7
7
|
import { findClarusFiles, reachableComponents } from '../vite/build.js';
|
|
8
|
+
import { projectAliases, resolveAlias } from '../vite/aliases.js';
|
|
9
|
+
import { routeFromFile } from '../server/handler.js';
|
|
8
10
|
const VIRTUAL = '.clarusjs/virtual';
|
|
9
11
|
const posix = (path) => path.split(sep).join('/');
|
|
10
12
|
function packageInfo(file) {
|
|
@@ -19,6 +21,24 @@ function position(text, offset) {
|
|
|
19
21
|
const before = text.slice(0, offset);
|
|
20
22
|
return { line: before.split('\n').length, column: offset - before.lastIndexOf('\n') };
|
|
21
23
|
}
|
|
24
|
+
function inSource(original, converted, offset) {
|
|
25
|
+
const tag = [converted.lastIndexOf('<', offset), converted.indexOf('>', offset) + 1];
|
|
26
|
+
const line = [converted.lastIndexOf('\n', offset - 1) + 1, converted.indexOf('\n', offset) === -1 ? converted.length : converted.indexOf('\n', offset)];
|
|
27
|
+
for (const [a, b] of [tag, line]) {
|
|
28
|
+
if (a < 0 || b <= offset || b - a < 3)
|
|
29
|
+
continue;
|
|
30
|
+
const snippet = converted.slice(a, b);
|
|
31
|
+
const at = original.indexOf(snippet);
|
|
32
|
+
if (at !== -1 && original.indexOf(snippet, at + 1) === -1)
|
|
33
|
+
return at + (offset - a);
|
|
34
|
+
}
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
export function loaderOf(path) {
|
|
38
|
+
const loaderPath = path.replace(/\.[^./]+$/, '.load.ts');
|
|
39
|
+
const hasLoad = existsSync(loaderPath) && /export\s+(async\s+)?function\s+load\b|export\s+(const|let)\s+load\b/.test(readFileSync(loaderPath, 'utf8'));
|
|
40
|
+
return hasLoad ? `./${basename(loaderPath)}` : undefined;
|
|
41
|
+
}
|
|
22
42
|
function typescriptDir(root, override) {
|
|
23
43
|
if (override)
|
|
24
44
|
return override;
|
|
@@ -30,29 +50,48 @@ export function check(options) {
|
|
|
30
50
|
rmSync(virtualRoot, { recursive: true, force: true });
|
|
31
51
|
const diagnostics = [];
|
|
32
52
|
const generated = new Map();
|
|
33
|
-
|
|
53
|
+
const sources = options.sources ?? [];
|
|
54
|
+
const aliases = projectAliases(root, options.viteAliases);
|
|
55
|
+
const pageFiles = findClarusFiles(resolve(root, 'src'), ['.tscl', ...sources.map((x) => x.extension)])
|
|
56
|
+
.filter((f) => f.endsWith('.tscl') || f.startsWith(resolve(root, 'src/pages') + sep));
|
|
57
|
+
const views = [];
|
|
58
|
+
for (const path of pageFiles) {
|
|
34
59
|
const file = posix(relative(root, path));
|
|
35
|
-
const
|
|
60
|
+
const original = readFileSync(path, 'utf8');
|
|
61
|
+
const src = sources.find((x) => path.endsWith(x.extension));
|
|
62
|
+
let source = original;
|
|
36
63
|
try {
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
64
|
+
if (src)
|
|
65
|
+
source = src.toTscl(original, path, { route: routeFromFile(`/${file}`), root, addDependency: () => { } });
|
|
66
|
+
}
|
|
67
|
+
catch (err) {
|
|
68
|
+
diagnostics.push({ file, line: 1, column: 1, code: 'clarus', message: err.message });
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
views.push({ file, source });
|
|
72
|
+
try {
|
|
73
|
+
const loader = loaderOf(path);
|
|
74
|
+
const { code, mappings, loaderSpan } = generateTs(source, file, loader ? { loader } : {});
|
|
40
75
|
const vpath = resolve(virtualRoot, `${file}.ts`);
|
|
41
76
|
mkdirSync(dirname(vpath), { recursive: true });
|
|
42
77
|
writeFileSync(vpath, code);
|
|
43
|
-
generated.set(vpath, { file, source, code, mappings, loaderSpan });
|
|
78
|
+
generated.set(vpath, { file, source, code, mappings, loaderSpan, ...(src ? { original } : {}) });
|
|
44
79
|
}
|
|
45
80
|
catch (err) {
|
|
46
81
|
if (!(err instanceof ClarusError))
|
|
47
82
|
throw err;
|
|
48
83
|
const message = err.message.slice(`${err.file}:${err.line}:${err.column} `.length);
|
|
49
|
-
|
|
84
|
+
const lines = source.split('\n');
|
|
85
|
+
const at = src ? inSource(original, source, lines.slice(0, err.line - 1).reduce((n, l) => n + l.length + 1, 0) + err.column - 1) : null;
|
|
86
|
+
diagnostics.push({ file, ...(src ? (at === null ? { line: 1, column: 1 } : position(original, at)) : { line: err.line, column: err.column }), code: 'clarus', message });
|
|
50
87
|
}
|
|
51
88
|
}
|
|
52
89
|
const appRoot = realpathSync(root);
|
|
53
90
|
const paths = {};
|
|
54
91
|
const virtualOf = new Map();
|
|
55
|
-
const
|
|
92
|
+
const converted = new Map(views.map((v) => [realpathSync(resolve(root, v.file)), v.source]));
|
|
93
|
+
const textOf = (p) => converted.get(realpathSync(p)) ?? readFileSync(p, 'utf8');
|
|
94
|
+
const components = reachableComponents(root, pageFiles, textOf, ['.tscl'], aliases);
|
|
56
95
|
for (const path of components.filter((p) => !p.startsWith(resolve(appRoot, 'src') + sep))) {
|
|
57
96
|
const pkg = packageInfo(path);
|
|
58
97
|
const vpath = resolve(virtualRoot, '_pkg', pkg.name, `${relative(pkg.dir, path)}.ts`);
|
|
@@ -71,21 +110,37 @@ export function check(options) {
|
|
|
71
110
|
}
|
|
72
111
|
const require = createRequire(resolve(root, 'package.json'));
|
|
73
112
|
for (const path of components) {
|
|
74
|
-
for (const m of
|
|
113
|
+
for (const m of textOf(path).matchAll(/^@import\s+[A-Za-z_$][\w-]*\s+from\s+(['"])([^'"./][^'"]*\.tscl)\1/gm)) {
|
|
75
114
|
try {
|
|
76
|
-
const
|
|
115
|
+
const file = realpathSync(resolveAlias(m[2], aliases) ?? require.resolve(m[2]));
|
|
116
|
+
const target = virtualOf.get(file) ?? (file.startsWith(appRoot + sep) ? resolve(virtualRoot, `${relative(appRoot, file)}.ts`) : undefined);
|
|
77
117
|
if (target)
|
|
78
118
|
paths[`${m[2]}.ts`] = [`./${posix(relative(resolve(root, '.clarusjs'), target))}`];
|
|
79
119
|
}
|
|
80
120
|
catch { }
|
|
81
121
|
}
|
|
82
122
|
}
|
|
123
|
+
const fromCheck = (path) => { const rel = posix(relative(resolve(root, '.clarusjs'), path)); return rel.startsWith('.') ? rel : `./${rel}`; };
|
|
124
|
+
paths['/*'] = ['../*', './virtual/*'];
|
|
125
|
+
for (const alias of aliases) {
|
|
126
|
+
const mirror = resolve(virtualRoot, relative(root, alias.replacement));
|
|
127
|
+
const targets = (tail) => [fromCheck(alias.replacement) + tail, fromCheck(mirror) + tail].map((p) => p.replace(/\/\/\*$/, '/*'));
|
|
128
|
+
if (alias.find.endsWith('/'))
|
|
129
|
+
paths[`${alias.find}*`] = targets('/*');
|
|
130
|
+
else {
|
|
131
|
+
paths[alias.find] = targets('');
|
|
132
|
+
if (!alias.exact)
|
|
133
|
+
paths[`${alias.find}/*`] = targets('/*');
|
|
134
|
+
}
|
|
135
|
+
}
|
|
83
136
|
mkdirSync(resolve(root, '.clarusjs'), { recursive: true });
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
137
|
+
writeFileSync(resolve(root, '.clarusjs/views.d.ts'), viewsDeclaration(views));
|
|
138
|
+
const walk = (dir) => (existsSync(dir) ? readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(resolve(dir, e.name)) : [resolve(dir, e.name)])) : []);
|
|
139
|
+
writeFileSync(resolve(root, '.clarusjs/routes.d.ts'), routesDeclaration(walk(resolve(root, 'src/pages')).map((path) => posix(relative(root, path)))));
|
|
140
|
+
const own = ['tsconfig.json', 'jsconfig.json'].find((name) => existsSync(resolve(root, name)));
|
|
141
|
+
const hasConfig = own !== undefined;
|
|
87
142
|
const config = {
|
|
88
|
-
...(hasConfig ? { extends:
|
|
143
|
+
...(hasConfig ? { extends: `../${own}` } : {}),
|
|
89
144
|
compilerOptions: {
|
|
90
145
|
...(hasConfig ? {} : { strict: true, target: 'ES2023', module: 'ESNext', moduleResolution: 'Bundler', lib: ['ES2023', 'DOM', 'DOM.Iterable'] }),
|
|
91
146
|
noEmit: true,
|
|
@@ -95,7 +150,7 @@ export function check(options) {
|
|
|
95
150
|
rootDirs: ['..', './virtual'],
|
|
96
151
|
paths,
|
|
97
152
|
},
|
|
98
|
-
include: ['../src', './virtual', './views.d.ts'],
|
|
153
|
+
include: ['../src', './virtual', './views.d.ts', './routes.d.ts'],
|
|
99
154
|
};
|
|
100
155
|
const configPath = resolve(root, '.clarusjs/tsconfig.check.json');
|
|
101
156
|
mkdirSync(dirname(configPath), { recursive: true });
|
|
@@ -118,8 +173,10 @@ export function check(options) {
|
|
|
118
173
|
}
|
|
119
174
|
const lines = g.code.split('\n');
|
|
120
175
|
const offset = lines.slice(0, Number(m[2]) - 1).reduce((n, l) => n + l.length + 1, 0) + Number(m[3]) - 1;
|
|
121
|
-
|
|
122
|
-
|
|
176
|
+
let source = toSourceOffset(g.mappings, offset);
|
|
177
|
+
if (source !== null && g.original !== undefined)
|
|
178
|
+
source = inSource(g.original, g.source, source);
|
|
179
|
+
const at = source === null ? { line: 1, column: 1 } : position(g.original ?? g.source, source);
|
|
123
180
|
const fromLoader = g.loaderSpan && offset >= g.loaderSpan[0] && offset < g.loaderSpan[1];
|
|
124
181
|
const message = fromLoader ? `load() returns a value that doesn't fit this page's inputs: ${m[5]}` : source === null ? `${m[5]} (in generated code)` : m[5];
|
|
125
182
|
diagnostics.push({ file: g.file, ...at, code: m[4], message });
|
package/dist/cli/index.js
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { Command } from 'commander';
|
|
3
3
|
import { check } from './check.js';
|
|
4
|
+
import { loadProject } from './project.js';
|
|
4
5
|
import { explain } from './explain.js';
|
|
6
|
+
import { serve } from './mapper.js';
|
|
5
7
|
const program = new Command('clarusjs').description('clarusjs: clear, compiled views');
|
|
6
8
|
program
|
|
7
9
|
.command('check')
|
|
8
|
-
.description('type-check every .tscl file under src/ and
|
|
10
|
+
.description('type-check every .tscl file under src/ and every page (Markdown pages too), reporting errors where they are written')
|
|
9
11
|
.argument('[dir]', 'project folder', '.')
|
|
10
12
|
.option('--json', 'print diagnostics as JSON')
|
|
11
|
-
.action((dir, options) => {
|
|
12
|
-
const result = check({ root: dir });
|
|
13
|
+
.action(async (dir, options) => {
|
|
14
|
+
const result = check({ root: dir, ...(await loadProject(dir)) });
|
|
13
15
|
if (options.json)
|
|
14
16
|
console.log(result.json);
|
|
15
17
|
else if (result.diagnostics.length) {
|
|
@@ -34,4 +36,8 @@ program
|
|
|
34
36
|
console.log(options.json ? result.json : result.text);
|
|
35
37
|
process.exitCode = result.exitCode;
|
|
36
38
|
});
|
|
39
|
+
program
|
|
40
|
+
.command('mapper')
|
|
41
|
+
.description('the TypeScript 7.1 content mapper for .tscl files (TypeScript starts it; see https://clarusjs.com/guide/editor)')
|
|
42
|
+
.action(() => serve());
|
|
37
43
|
program.parse();
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* [virtual start, virtual length, original start, original length, kind, features?]: kind 0 = verbatim, 1 = atom (a
|
|
3
|
+
* whole span). Features (a bitmask of language-service operations; all when absent) are none for atoms: they are
|
|
4
|
+
* generated stand-ins (`__cl_p` for a component's props), so only their errors belong in the template, not hover,
|
|
5
|
+
* completion or rename. Diagnostics can't be switched off per span.
|
|
6
|
+
*/
|
|
7
|
+
type Span = [number, number, number, number, 0 | 1] | [number, number, number, number, 1, number];
|
|
8
|
+
type Diagnostic = {
|
|
9
|
+
messageText: string;
|
|
10
|
+
start: number;
|
|
11
|
+
length: number;
|
|
12
|
+
code: number;
|
|
13
|
+
};
|
|
14
|
+
export declare function transform(params: {
|
|
15
|
+
fileName: string;
|
|
16
|
+
content: string;
|
|
17
|
+
}): {
|
|
18
|
+
text: string;
|
|
19
|
+
extension: '.ts';
|
|
20
|
+
mappings: Span[];
|
|
21
|
+
diagnostics: Diagnostic[];
|
|
22
|
+
};
|
|
23
|
+
/** Serve the protocol on stdin/stdout until stdin ends. */
|
|
24
|
+
export declare function serve(): void;
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { generateTolerant } from '../check/generate.js';
|
|
2
|
+
import { loaderOf } from './check.js';
|
|
3
|
+
export function transform(params) {
|
|
4
|
+
const { fileName, content } = params;
|
|
5
|
+
const loader = loaderOf(fileName);
|
|
6
|
+
const { result, errors } = generateTolerant(content, fileName, { componentSuffix: '', ...(loader ? { loader } : {}) });
|
|
7
|
+
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
|
+
if (!result)
|
|
9
|
+
return { text: 'export {}\n', extension: '.ts', mappings: [], diagnostics };
|
|
10
|
+
const { code, mappings } = result;
|
|
11
|
+
const spans = mappings.map(([v, length, s, exact, sourceLength]) => {
|
|
12
|
+
if (exact && code.slice(v, v + length) === content.slice(s, s + length))
|
|
13
|
+
return [v, length, s, length, 0];
|
|
14
|
+
if (exact)
|
|
15
|
+
return [v, length, s, Math.min(length, content.length - s), 1];
|
|
16
|
+
return [v, length, s, Math.min(sourceLength ?? 1, content.length - s), 1, 0];
|
|
17
|
+
});
|
|
18
|
+
return { text: code, extension: '.ts', mappings: spans, diagnostics };
|
|
19
|
+
}
|
|
20
|
+
function handle(request) {
|
|
21
|
+
if (request.id === undefined)
|
|
22
|
+
return;
|
|
23
|
+
switch (request.method) {
|
|
24
|
+
case 'initialize': return { id: request.id, result: { positionEncoding: 'utf-16', diagnosticSource: 'clarus' } };
|
|
25
|
+
case 'openProject': return { id: request.id, result: {} };
|
|
26
|
+
case 'closeProject': return { id: request.id, result: null };
|
|
27
|
+
case 'transform': return { id: request.id, result: transform(request.params) };
|
|
28
|
+
default: return { id: request.id, error: { code: -32601, message: `Unknown method: ${request.method}` } };
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export function serve() {
|
|
32
|
+
const send = (message) => {
|
|
33
|
+
const body = Buffer.from(JSON.stringify({ jsonrpc: '2.0', ...message }));
|
|
34
|
+
process.stdout.write(`Content-Length: ${body.length}\r\n\r\n`);
|
|
35
|
+
process.stdout.write(body);
|
|
36
|
+
};
|
|
37
|
+
let pending = Buffer.alloc(0);
|
|
38
|
+
process.stdin.on('data', (chunk) => {
|
|
39
|
+
pending = Buffer.concat([pending, chunk]);
|
|
40
|
+
for (;;) {
|
|
41
|
+
const headerEnd = pending.indexOf('\r\n\r\n');
|
|
42
|
+
if (headerEnd === -1)
|
|
43
|
+
return;
|
|
44
|
+
const match = /Content-Length:\s*(\d+)/i.exec(pending.subarray(0, headerEnd).toString());
|
|
45
|
+
if (!match)
|
|
46
|
+
throw new Error('clarusjs mapper: a message without Content-Length');
|
|
47
|
+
const start = headerEnd + 4;
|
|
48
|
+
const end = start + Number(match[1]);
|
|
49
|
+
if (pending.length < end)
|
|
50
|
+
return;
|
|
51
|
+
const request = JSON.parse(pending.subarray(start, end).toString());
|
|
52
|
+
pending = pending.subarray(end);
|
|
53
|
+
let response;
|
|
54
|
+
try {
|
|
55
|
+
response = handle(request);
|
|
56
|
+
}
|
|
57
|
+
catch (err) {
|
|
58
|
+
response = { id: request.id, error: { code: -32603, message: err.message } };
|
|
59
|
+
}
|
|
60
|
+
if (response)
|
|
61
|
+
send(response);
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
process.stdin.on('end', () => process.exit(0));
|
|
65
|
+
}
|