clarusjs 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +5 -5
  2. package/dist/check/generate.d.ts +27 -0
  3. package/dist/check/generate.js +234 -0
  4. package/dist/cli/check.d.ts +17 -0
  5. package/dist/cli/check.js +101 -0
  6. package/dist/cli/explain.d.ts +9 -0
  7. package/dist/cli/explain.js +56 -0
  8. package/dist/cli/index.d.ts +2 -0
  9. package/dist/cli/index.js +38 -0
  10. package/dist/compiler/emit-client.js +2 -0
  11. package/dist/compiler/emit-server.d.ts +1 -1
  12. package/dist/compiler/emit-server.js +4 -2
  13. package/dist/compiler/errors.d.ts +1 -1
  14. package/dist/compiler/errors.js +1 -1
  15. package/dist/compiler/index.d.ts +5 -0
  16. package/dist/compiler/index.js +1 -1
  17. package/dist/compiler/ir.d.ts +2 -1
  18. package/dist/compiler/ir.js +14 -4
  19. package/dist/compiler/parse.d.ts +22 -0
  20. package/dist/compiler/parse.js +52 -14
  21. package/dist/compiler/script.d.ts +5 -1
  22. package/dist/compiler/script.js +2 -1
  23. package/dist/runtime/router.d.ts +15 -0
  24. package/dist/runtime/router.js +101 -0
  25. package/dist/server/handler.d.ts +25 -1
  26. package/dist/server/handler.js +170 -9
  27. package/dist/server/manifest.d.ts +4 -0
  28. package/dist/server/manifest.js +17 -0
  29. package/dist/server/modes.d.ts +6 -0
  30. package/dist/server/modes.js +28 -0
  31. package/dist/server/views.d.ts +17 -0
  32. package/dist/server/views.js +23 -0
  33. package/dist/vite/build.d.ts +18 -5
  34. package/dist/vite/build.js +49 -12
  35. package/dist/vite/manifest.d.ts +49 -0
  36. package/dist/vite/manifest.js +86 -0
  37. package/dist/vite/netlify.d.ts +4 -0
  38. package/dist/vite/netlify.js +46 -0
  39. package/dist/vite/plugin.d.ts +8 -1
  40. package/dist/vite/plugin.js +134 -20
  41. package/package.json +14 -2
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  <p align="center">
2
- <img src="https://raw.githubusercontent.com/forinda/clarusjs/main/docs/assets/logo.svg" width="96" height="96" alt="clarusjs logo: a clear cut crystal with one bright facet">
2
+ <img src="https://raw.githubusercontent.com/forinda/clarusjs/main/docs/assets/logo.svg" width="96" height="96" alt="clarusjs logo">
3
3
  </p>
4
4
 
5
5
  <h1 align="center">clarusjs</h1>
@@ -30,7 +30,7 @@ export default defineConfig({ plugins: [clarusjs()] })
30
30
  ```
31
31
 
32
32
  ```clarus
33
- {{-- src/components/counter.clarus --}}
33
+ {{-- src/components/counter.tscl --}}
34
34
  @input start: number = 0
35
35
 
36
36
  <script>
@@ -42,14 +42,14 @@ export default defineConfig({ plugins: [clarusjs()] })
42
42
  ```
43
43
 
44
44
  ```clarus
45
- {{-- src/pages/index.clarus --}}
46
- @import counter from '../components/counter.clarus'
45
+ {{-- src/pages/index.tscl --}}
46
+ @import counter from '../components/counter.tscl'
47
47
 
48
48
  <h1>Hello</h1>
49
49
  <counter [start]="1" />
50
50
  ```
51
51
 
52
- - `vite` serves `src/pages/**/*.clarus` as routes, rendered on the server.
52
+ - `vite` serves `src/pages/**/*.tscl` as routes, rendered on the server.
53
53
  - `vite build` writes a static site to `dist/client/`: one HTML file per page, plus JavaScript only for components
54
54
  with a `<script>` (the counter above). The `<h1>` ships no JavaScript at all.
55
55
 
@@ -0,0 +1,27 @@
1
+ /**
2
+ * [virtual offset, length, source offset, exact]. Exact spans are verbatim copies (offsets map one to one); other
3
+ * spans stand for a whole template construct and map to its start.
4
+ */
5
+ export type Mapping = [number, number, number, boolean];
6
+ /**
7
+ * `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. `loaderSpan` is where that check sits in the generated code, so its errors can say so.
9
+ */
10
+ export declare function generateTs(source: string, file: string, options?: {
11
+ loader?: string;
12
+ }): {
13
+ code: string;
14
+ mappings: Mapping[];
15
+ loaderSpan?: [number, number];
16
+ };
17
+ /** The template offset for an offset in the virtual file, or null when it falls in generated scaffolding. */
18
+ export declare function toSourceOffset(mappings: Mapping[], virtualOffset: number): number | null;
19
+ /**
20
+ * .clarusjs/views.d.ts: view name → inputs, as declarations only, so an app's own tsconfig can include it. Each view's
21
+ * inputs are written inline in a namespace; its `@import type`s become import() types with paths relative to
22
+ * .clarusjs/ (where this file lives). Views that don't parse are left out (check reports them).
23
+ */
24
+ export declare function viewsDeclaration(views: {
25
+ file: string;
26
+ source: string;
27
+ }[]): string;
@@ -0,0 +1,234 @@
1
+ // .tscl → virtual TypeScript for type checking (it never runs). Template expressions are copied verbatim inside
2
+ // TypeScript that has the same meaning (@if → if, @for → for…of, a component → an object typed as its Inputs), and
3
+ // every copied span is recorded so tsc's errors can be mapped back to the template. Pure: string in, string out.
4
+ import { parse } from '../compiler/parse.js';
5
+ import { splitImports } from '../compiler/script.js';
6
+ /**
7
+ * `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. `loaderSpan` is where that check sits in the generated code, so its errors can say so.
9
+ */
10
+ export function generateTs(source, file, options = {}) {
11
+ const parsed = parse(source, file);
12
+ const mappings = [];
13
+ let code = '';
14
+ const emit = (text) => { code += text; };
15
+ const copy = (text, sourceStart) => { mappings.push([code.length, text.length, sourceStart, true]); code += text; };
16
+ const point = (text, sourceStart) => { mappings.push([code.length, text.length, sourceStart, false]); code += text; };
17
+ // Where a trimmed expression starts in the source, searching from `from`.
18
+ const at = (text, from) => source.indexOf(text, from);
19
+ const components = new Map(parsed.imports.map((imp) => [imp.name, imp]));
20
+ const alias = (name) => `__cl_I_${name.replace(/-/g, '$')}`;
21
+ emit('// Generated by clarusjs for type checking. It never runs.\n');
22
+ emit('declare function state<T>(value: T): T\n');
23
+ emit('declare function derived<T>(fn: () => T): T\n');
24
+ emit('declare function shared<T>(store: { get(): T }): T\n');
25
+ emit('declare function __cl_use(value: unknown): void\n');
26
+ emit('type __cl_Event<K extends string> = (K extends keyof HTMLElementEventMap ? HTMLElementEventMap[K] : Event) & { target: any; currentTarget: any }\n');
27
+ for (const t of parsed.typeImports) {
28
+ emit('import type ');
29
+ copy(t.clause, t.clauseStart);
30
+ emit(` from ${JSON.stringify(t.from)}\n`);
31
+ }
32
+ for (const imp of parsed.imports)
33
+ emit(`import type { Inputs as ${alias(imp.name)} } from ${JSON.stringify(`${imp.from}.ts`)}\n`);
34
+ for (const d of parsed.dataImports) {
35
+ emit('import ');
36
+ copy(d.clause, d.clauseStart);
37
+ emit(` from ${JSON.stringify(d.from)}\n`);
38
+ }
39
+ if (options.loader)
40
+ emit(`import { load as __cl_load } from ${JSON.stringify(options.loader)}\n`);
41
+ const script = parsed.script ? splitImports(parsed.script.code, file, source, parsed.script.start) : null;
42
+ if (parsed.script && script) {
43
+ for (const imp of script.imports) {
44
+ copy(imp.text, parsed.script.start + imp.start);
45
+ emit('\n');
46
+ }
47
+ }
48
+ emit('\nexport interface Inputs {\n');
49
+ for (const input of parsed.inputs) {
50
+ emit(' ');
51
+ copy(input.name, input.nameStart);
52
+ emit(input.default !== undefined ? '?: ' : ': ');
53
+ copy(input.type, input.typeStart);
54
+ emit('\n');
55
+ }
56
+ emit('}\n');
57
+ let loaderSpan;
58
+ if (options.loader) {
59
+ // Params and defaults fill the rest, so load() may return any subset of the inputs, each with the right type.
60
+ emit('declare const __cl_loaded: Awaited<ReturnType<typeof __cl_load>>\n');
61
+ const start = code.length;
62
+ point('const __cl_from_load: Partial<Inputs> = __cl_loaded', 0);
63
+ loaderSpan = [start, code.length];
64
+ emit('\n');
65
+ }
66
+ emit('\nexport default function __cl_check(__cl_props: Inputs) {\n');
67
+ if (parsed.inputs.length) {
68
+ emit(' const { ');
69
+ parsed.inputs.forEach((input, i) => {
70
+ if (i)
71
+ emit(', ');
72
+ copy(input.name, input.nameStart);
73
+ if (input.default !== undefined && input.defaultStart !== undefined) {
74
+ emit(' = ');
75
+ copy(input.default, input.defaultStart);
76
+ }
77
+ });
78
+ emit(' } = __cl_props\n');
79
+ }
80
+ if (parsed.script && script) {
81
+ copy(script.body, parsed.script.start);
82
+ emit('\n;\n'); // the script may end without a semicolon; what follows must not continue its last statement
83
+ }
84
+ const use = (expr, start) => {
85
+ emit(' __cl_use((');
86
+ copy(expr, at(expr, start));
87
+ emit('));\n');
88
+ };
89
+ const attrValueStart = (a) => a.start + a.name.length + (a.kind === 'static' || a.kind === 'interp' ? 2 : 4);
90
+ function visit(node) {
91
+ switch (node.type) {
92
+ case 'text':
93
+ case 'raw':
94
+ return;
95
+ case 'expr':
96
+ return use(node.expr, node.start + 2);
97
+ case 'fill':
98
+ node.children.forEach(visit);
99
+ return;
100
+ case 'if':
101
+ node.branches.forEach((b, i) => {
102
+ if (b.cond === null)
103
+ emit(' else {\n');
104
+ else {
105
+ emit(i === 0 ? ' if ((' : ' else if ((');
106
+ copy(b.cond, at(b.cond, b.condStart));
107
+ emit(')) {\n');
108
+ }
109
+ b.children.forEach(visit);
110
+ emit(' }\n');
111
+ });
112
+ return;
113
+ case 'for': {
114
+ emit(' for (const ');
115
+ copy(node.item, node.itemStart);
116
+ emit(' of ');
117
+ copy(node.list, node.listStart);
118
+ emit(') {\n const $index: number = 0\n');
119
+ if (node.track !== null)
120
+ use(node.track, node.trackStart);
121
+ node.children.forEach(visit);
122
+ emit(' }\n');
123
+ if (node.empty) {
124
+ emit(' {\n');
125
+ node.empty.forEach(visit);
126
+ emit(' }\n');
127
+ }
128
+ return;
129
+ }
130
+ case 'element': {
131
+ const component = components.get(node.tag);
132
+ if (component) {
133
+ // An object literal typed as the child's Inputs: unknown props are excess properties, missing ones are
134
+ // reported on the variable, which maps to the tag.
135
+ emit(' { const ');
136
+ point('__cl_p', node.start);
137
+ emit(`: ${alias(node.tag)} = { `);
138
+ for (const a of node.attrs) {
139
+ if (a.kind !== 'prop')
140
+ continue;
141
+ copy(a.name, a.start + 1);
142
+ emit(': (');
143
+ copy(a.expr, at(a.expr, attrValueStart(a)));
144
+ emit('), ');
145
+ }
146
+ emit('}; __cl_use(__cl_p) }\n');
147
+ node.children.forEach(visit);
148
+ return;
149
+ }
150
+ for (const a of node.attrs) {
151
+ if (a.kind === 'prop')
152
+ use(a.expr, attrValueStart(a));
153
+ else if (a.kind === 'interp') {
154
+ for (const p of a.parts)
155
+ if (typeof p !== 'string')
156
+ use(p.expr, p.start + 2);
157
+ }
158
+ else if (a.kind === 'event') {
159
+ emit(` ;(($event: __cl_Event<${JSON.stringify(a.name)}>) => { `);
160
+ copy(a.expr, at(a.expr, attrValueStart(a)));
161
+ emit(' });\n');
162
+ }
163
+ }
164
+ node.children.forEach(visit);
165
+ return;
166
+ }
167
+ }
168
+ }
169
+ parsed.nodes.forEach(visit);
170
+ emit('}\n');
171
+ return { code, mappings, loaderSpan };
172
+ }
173
+ /** The template offset for an offset in the virtual file, or null when it falls in generated scaffolding. */
174
+ export function toSourceOffset(mappings, virtualOffset) {
175
+ for (const [v, length, s, exact] of mappings) {
176
+ if (virtualOffset >= v && virtualOffset < v + Math.max(length, 1))
177
+ return exact ? s + (virtualOffset - v) : s;
178
+ }
179
+ return null;
180
+ }
181
+ /** 'src/components' + '../domain/user' → 'src/domain/user' (POSIX, no fs). */
182
+ function joinPath(dir, rel) {
183
+ const out = dir.split('/').filter(Boolean);
184
+ for (const part of rel.split('/')) {
185
+ if (part === '..')
186
+ out.pop();
187
+ else if (part !== '.' && part !== '')
188
+ out.push(part);
189
+ }
190
+ return out.join('/');
191
+ }
192
+ /**
193
+ * .clarusjs/views.d.ts: view name → inputs, as declarations only, so an app's own tsconfig can include it. Each view's
194
+ * inputs are written inline in a namespace; its `@import type`s become import() types with paths relative to
195
+ * .clarusjs/ (where this file lives). Views that don't parse are left out (check reports them).
196
+ */
197
+ export function viewsDeclaration(views) {
198
+ const lines = ['// Generated by clarusjs check: view name → inputs, for render() from clarusjs/views. Declarations only.'];
199
+ const entries = [];
200
+ views.forEach(({ file, source }, i) => {
201
+ let parsed;
202
+ try {
203
+ parsed = parse(source, file);
204
+ }
205
+ catch {
206
+ return;
207
+ }
208
+ const ns = `__cl_v${i}`;
209
+ const body = [];
210
+ for (const t of parsed.typeImports) {
211
+ // Relative paths are written from .clarusjs/, one level below the project root.
212
+ const from = t.from.startsWith('.') ? `../${joinPath(file.split('/').slice(0, -1).join('/'), t.from)}` : t.from;
213
+ const clause = t.clause.trim();
214
+ if (clause.startsWith('{')) {
215
+ for (const part of clause.slice(1, -1).split(',').map((p) => p.trim().replace(/^type\s+/, '')).filter(Boolean)) {
216
+ const [name, local = name] = part.split(/\s+as\s+/).map((x) => x.trim());
217
+ body.push(` type ${local} = import(${JSON.stringify(from)}).${name}`);
218
+ }
219
+ }
220
+ else if (!clause.startsWith('*')) {
221
+ // ponytail: `* as N` type imports aren't carried into the registry; use named type imports for inputs.
222
+ body.push(` type ${clause} = import(${JSON.stringify(from)}).default`);
223
+ }
224
+ }
225
+ body.push(` interface Inputs {`);
226
+ for (const input of parsed.inputs)
227
+ body.push(` ${input.name}${input.default !== undefined ? '?' : ''}: ${input.type}`);
228
+ body.push(' }');
229
+ lines.push(`declare namespace ${ns} {`, ...body, '}');
230
+ entries.push(` ${JSON.stringify(file.replace(/^src\//, '').replace(/\.tscl$/, ''))}: ${ns}.Inputs`);
231
+ });
232
+ lines.push("declare module 'clarusjs/views' {", ' interface Views {', ...entries, ' }', '}', 'export {}', '');
233
+ return lines.join('\n');
234
+ }
@@ -0,0 +1,17 @@
1
+ export type Diagnostic = {
2
+ file: string;
3
+ line: number;
4
+ column: number;
5
+ code: string;
6
+ message: string;
7
+ };
8
+ export type CheckResult = {
9
+ diagnostics: Diagnostic[];
10
+ exitCode: 0 | 1;
11
+ text: string;
12
+ json: string;
13
+ };
14
+ export declare function check(options: {
15
+ root: string;
16
+ typescript?: string;
17
+ }): CheckResult;
@@ -0,0 +1,101 @@
1
+ // `clarusjs check`: type-check every .tscl file in a project (and the .ts it uses) with the project's TypeScript,
2
+ // reporting each error at file.tscl:line:col.
3
+ import { spawnSync } from 'node:child_process';
4
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { createRequire } from 'node:module';
6
+ import { basename, dirname, relative, resolve, sep } from 'node:path';
7
+ import { ClarusError } from '../compiler/errors.js';
8
+ import { generateTs, toSourceOffset, viewsDeclaration } from '../check/generate.js';
9
+ import { findClarusFiles } from '../vite/build.js';
10
+ const VIRTUAL = '.clarusjs/virtual';
11
+ const posix = (path) => path.split(sep).join('/');
12
+ /** Line and column (1-based) of an offset in `text`. */
13
+ function position(text, offset) {
14
+ const before = text.slice(0, offset);
15
+ return { line: before.split('\n').length, column: offset - before.lastIndexOf('\n') };
16
+ }
17
+ /** Where the project's TypeScript lives (overridable for tests and monorepos). */
18
+ function typescriptDir(root, override) {
19
+ if (override)
20
+ return override;
21
+ return dirname(createRequire(resolve(root, 'package.json')).resolve('typescript/package.json'));
22
+ }
23
+ export function check(options) {
24
+ const root = resolve(options.root);
25
+ const virtualRoot = resolve(root, VIRTUAL);
26
+ rmSync(virtualRoot, { recursive: true, force: true });
27
+ const diagnostics = [];
28
+ const generated = new Map();
29
+ for (const path of findClarusFiles(resolve(root, 'src'))) {
30
+ const file = posix(relative(root, path));
31
+ const source = readFileSync(path, 'utf8');
32
+ try {
33
+ // A page's .load.ts that exports load(): what it returns is checked against the page's inputs.
34
+ const loaderPath = path.replace(/\.tscl$/, '.load.ts');
35
+ const hasLoad = existsSync(loaderPath) && /export\s+(async\s+)?function\s+load\b|export\s+(const|let)\s+load\b/.test(readFileSync(loaderPath, 'utf8'));
36
+ const { code, mappings, loaderSpan } = generateTs(source, file, hasLoad ? { loader: `./${basename(loaderPath)}` } : {});
37
+ const vpath = resolve(virtualRoot, `${file}.ts`);
38
+ mkdirSync(dirname(vpath), { recursive: true });
39
+ writeFileSync(vpath, code);
40
+ generated.set(vpath, { file, source, code, mappings, loaderSpan });
41
+ }
42
+ catch (err) {
43
+ if (!(err instanceof ClarusError))
44
+ throw err;
45
+ const message = err.message.slice(`${err.file}:${err.line}:${err.column} `.length);
46
+ diagnostics.push({ file, line: err.line, column: err.column, code: 'clarus', message });
47
+ }
48
+ }
49
+ // The view registry: every view's name → its inputs, so render(name, props) is checked. Declarations only, so apps
50
+ // can add .clarusjs/views.d.ts to their own tsconfig's include and get the same types in their editor.
51
+ mkdirSync(resolve(root, '.clarusjs'), { recursive: true });
52
+ const sources = findClarusFiles(resolve(root, 'src')).map((path) => ({ file: posix(relative(root, path)), source: readFileSync(path, 'utf8') }));
53
+ writeFileSync(resolve(root, '.clarusjs/views.d.ts'), viewsDeclaration(sources));
54
+ // The project's own settings, plus what checking templates needs. Scripts are JavaScript, so untyped parameters
55
+ // are expected (noImplicitAny off). rootDirs lets virtual files and real sources import each other.
56
+ const hasConfig = existsSync(resolve(root, 'tsconfig.json'));
57
+ const config = {
58
+ ...(hasConfig ? { extends: '../tsconfig.json' } : {}),
59
+ compilerOptions: {
60
+ ...(hasConfig ? {} : { strict: true, target: 'ES2023', module: 'ESNext', moduleResolution: 'Bundler', lib: ['ES2023', 'DOM', 'DOM.Iterable'] }),
61
+ noEmit: true,
62
+ allowImportingTsExtensions: true,
63
+ noImplicitAny: false,
64
+ skipLibCheck: true,
65
+ rootDirs: ['..', './virtual'],
66
+ },
67
+ include: ['../src', './virtual', './views.d.ts'],
68
+ };
69
+ const configPath = resolve(root, '.clarusjs/tsconfig.check.json');
70
+ mkdirSync(dirname(configPath), { recursive: true });
71
+ writeFileSync(configPath, JSON.stringify(config, null, 2));
72
+ const tsDir = typescriptDir(root, options.typescript);
73
+ const bin = JSON.parse(readFileSync(resolve(tsDir, 'package.json'), 'utf8')).bin;
74
+ const tsc = resolve(tsDir, typeof bin === 'string' ? bin : bin.tsc);
75
+ const run = spawnSync(process.execPath, [tsc, '-p', configPath, '--pretty', 'false'], { cwd: root, encoding: 'utf8' });
76
+ for (const line of `${run.stdout}\n${run.stderr}`.split('\n')) {
77
+ const m = /^(.+?)\((\d+),(\d+)\): error (TS\d+): (.*)$/.exec(line.trim());
78
+ if (!m)
79
+ continue;
80
+ const path = resolve(root, m[1]);
81
+ const g = generated.get(path);
82
+ if (!g) {
83
+ diagnostics.push({ file: posix(relative(root, path)), line: Number(m[2]), column: Number(m[3]), code: m[4], message: m[5] });
84
+ continue;
85
+ }
86
+ const lines = g.code.split('\n');
87
+ const offset = lines.slice(0, Number(m[2]) - 1).reduce((n, l) => n + l.length + 1, 0) + Number(m[3]) - 1;
88
+ const source = toSourceOffset(g.mappings, offset);
89
+ const at = source === null ? { line: 1, column: 1 } : position(g.source, source);
90
+ const fromLoader = g.loaderSpan && offset >= g.loaderSpan[0] && offset < g.loaderSpan[1];
91
+ 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];
92
+ diagnostics.push({ file: g.file, ...at, code: m[4], message });
93
+ }
94
+ diagnostics.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column);
95
+ return {
96
+ diagnostics,
97
+ exitCode: diagnostics.length ? 1 : 0,
98
+ text: diagnostics.map((d) => `${d.file}:${d.line}:${d.column} error ${d.code}: ${d.message}`).join('\n'),
99
+ json: JSON.stringify(diagnostics, null, 2),
100
+ };
101
+ }
@@ -0,0 +1,9 @@
1
+ export type ExplainResult = {
2
+ exitCode: 0 | 1;
3
+ text: string;
4
+ json: string;
5
+ };
6
+ export declare function explain(options: {
7
+ root: string;
8
+ route?: string;
9
+ }): ExplainResult;
@@ -0,0 +1,56 @@
1
+ // `clarusjs explain [route]`: where each part of a built route runs, in plain words, from dist/clarusjs-manifest.json.
2
+ import { readFileSync } from 'node:fs';
3
+ import { resolve } from 'node:path';
4
+ const WHEN = {
5
+ load: 'on page load',
6
+ idle: 'when the browser is idle',
7
+ visible: 'when scrolled into view',
8
+ interaction: 'on first interaction',
9
+ };
10
+ const kb = (bytes) => (bytes ? `${(bytes / 1024).toFixed(1)} KB` : '0 KB');
11
+ const row = (label, lines) => lines.map((l, i) => ` ${(i ? '' : label).padEnd(12)}${l}`);
12
+ function describe(path, r) {
13
+ if (r.mode === 'server') {
14
+ return [
15
+ path,
16
+ ...row('Rendered', ['on every request, by dist/server/index.mjs']),
17
+ ...row('Data', [r.loader === 'request' ? 'load() runs on every request' : 'no loader']),
18
+ ...row('Islands', ['decided per request']),
19
+ ].join('\n');
20
+ }
21
+ const islands = r.islands.map((i) => `${i.component}${i.count > 1 ? ` ×${i.count}` : ''} (${kb(i.gzip)}, ${WHEN[i.attach]})`);
22
+ return [
23
+ path,
24
+ ...row('Rendered', [r.mode === 'client' ? `in the browser, by the router (shell: dist/client/${r.html})` : `at build time, to dist/client/${r.html}`]),
25
+ ...row('Data', [r.loader === 'build' ? (r.mode === 'client' ? 'load() ran once, at build time; fetched as __data.json' : 'load() ran once, at build time') : 'no loader']),
26
+ ...row('Islands', islands.length ? islands : ['none']),
27
+ ...row('JavaScript', [r.js.files.length ? `${kb(r.js.initialGzip)} on page load, ${kb(r.js.gzip)} in all (gzip, ${r.js.files.length} files)` : 'none']),
28
+ ...row('CSS', [r.css.length ? r.css.join(', ') : 'none']),
29
+ ].join('\n');
30
+ }
31
+ function table(routes) {
32
+ const width = Math.max(5, ...Object.keys(routes).map((r) => r.length)) + 2;
33
+ const line = (cells) => cells[0].padEnd(width) + cells[1].padEnd(9) + cells[2].padEnd(12) + cells[3];
34
+ return [
35
+ line(['Route', 'Islands', 'JS on load', 'JS in all']),
36
+ ...Object.entries(routes).map(([path, r]) => r.mode === 'server'
37
+ ? line([path, '-', 'per request', ''])
38
+ : line([path, String(r.islands.reduce((n, i) => n + i.count, 0)), kb(r.js.initialGzip), kb(r.js.gzip)])),
39
+ ].join('\n');
40
+ }
41
+ export function explain(options) {
42
+ let manifest;
43
+ try {
44
+ manifest = JSON.parse(readFileSync(resolve(options.root, 'dist/clarusjs-manifest.json'), 'utf8'));
45
+ }
46
+ catch {
47
+ return { exitCode: 1, text: 'No dist/clarusjs-manifest.json: run vite build first, then explain the built site.', json: '{}' };
48
+ }
49
+ if (options.route === undefined)
50
+ return { exitCode: 0, text: table(manifest.routes), json: JSON.stringify(manifest.routes, null, 2) };
51
+ const path = options.route.replace(/(.)\/+$/, '$1');
52
+ const route = manifest.routes[path];
53
+ if (!route)
54
+ return { exitCode: 1, text: `No route ${path}. Routes: ${Object.keys(manifest.routes).join(', ')}`, json: '{}' };
55
+ return { exitCode: 0, text: describe(path, route), json: JSON.stringify({ route: path, ...route }, null, 2) };
56
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ // The clarusjs command line. Node only: nothing here is reachable from a browser bundle.
3
+ import { Command } from 'commander';
4
+ import { check } from './check.js';
5
+ import { explain } from './explain.js';
6
+ const program = new Command('clarusjs').description('clarusjs: clear, compiled views');
7
+ program
8
+ .command('check')
9
+ .description('type-check every .tscl file under src/ and report errors at file.tscl:line:col')
10
+ .argument('[dir]', 'project folder', '.')
11
+ .option('--json', 'print diagnostics as JSON')
12
+ .action((dir, options) => {
13
+ const result = check({ root: dir });
14
+ if (options.json)
15
+ console.log(result.json);
16
+ else if (result.diagnostics.length) {
17
+ console.log(result.text);
18
+ console.log(`\n${result.diagnostics.length} error${result.diagnostics.length === 1 ? '' : 's'}`);
19
+ }
20
+ else
21
+ console.log('No errors.');
22
+ process.exitCode = result.exitCode;
23
+ });
24
+ program
25
+ .command('explain')
26
+ .description('explain where each part of a built route runs: rendering, data, islands, JavaScript and CSS')
27
+ .argument('[route]', 'a route such as /guide/intro; without one, every route is listed')
28
+ .option('--root <dir>', 'project folder', '.')
29
+ .option('--json', 'print the route manifest entry as JSON')
30
+ .action((route, options) => {
31
+ const result = explain({ root: options.root, route });
32
+ if (result.exitCode)
33
+ console.error(result.text);
34
+ else
35
+ console.log(options.json ? result.json : result.text);
36
+ process.exitCode = result.exitCode;
37
+ });
38
+ program.parse();
@@ -37,6 +37,8 @@ export function emitClient(ir) {
37
37
  if (usedComponents.has(imp.name))
38
38
  out += `import { render as ${renderName(imp.name)} } from '${imp.from}?render'\n`;
39
39
  }
40
+ for (const d of ir.dataImports)
41
+ out += `import ${d.clause} from '${d.from}'\n`;
40
42
  for (const line of ir.scriptImports)
41
43
  out += `${line}\n`;
42
44
  out += `\nexport function attach(__cl_root, __cl_props = {}, __cl_state) {\n`;
@@ -1,2 +1,2 @@
1
1
  import type { ComponentIR } from './ir.ts';
2
- export declare function emitServer(ir: ComponentIR, clientUrl: string): string;
2
+ export declare function emitServer(ir: ComponentIR, clientUrl: string, renderImports?: boolean): string;
@@ -1,7 +1,7 @@
1
1
  import { htmlExpr, walk } from './html-expr.js';
2
2
  import { rewriteServer } from './script.js';
3
3
  import { indentScript, inputsLine, renderName } from './shared.js';
4
- export function emitServer(ir, clientUrl) {
4
+ export function emitServer(ir, clientUrl, renderImports = false) {
5
5
  const all = walk(ir.nodes);
6
6
  const runtime = [
7
7
  'escape as __cl_escape',
@@ -13,7 +13,9 @@ export function emitServer(ir, clientUrl) {
13
13
  ].filter(Boolean).join(', ');
14
14
  let out = `import { ${runtime} } from 'clarusjs/runtime/server'\n`;
15
15
  for (const imp of ir.imports)
16
- out += `import { render as ${renderName(imp.name)} } from '${imp.from}'\n`;
16
+ out += `import { render as ${renderName(imp.name)} } from '${imp.from}${renderImports ? '?render' : ''}'\n`;
17
+ for (const d of ir.dataImports)
18
+ out += `import ${d.clause} from '${d.from}'\n`;
17
19
  for (const line of ir.scriptImports)
18
20
  out += `${line}\n`;
19
21
  const html = htmlExpr(ir.nodes);
@@ -1,4 +1,4 @@
1
- /** A compile error pointing at a place in a .clarus file. Message format: `file:line:column text` (1-based). */
1
+ /** A compile error pointing at a place in a .tscl file. Message format: `file:line:column text` (1-based). */
2
2
  export declare class ClarusError extends Error {
3
3
  file: string;
4
4
  line: number;
@@ -1,4 +1,4 @@
1
- /** A compile error pointing at a place in a .clarus file. Message format: `file:line:column text` (1-based). */
1
+ /** A compile error pointing at a place in a .tscl file. Message format: `file:line:column text` (1-based). */
2
2
  export class ClarusError extends Error {
3
3
  file;
4
4
  line;
@@ -1,8 +1,13 @@
1
1
  export { ClarusError } from './errors.ts';
2
+ /**
3
+ * `renderImports`: import child components' render functions with `?render`, for a render module that runs in the
4
+ * browser (a client route's page, or a component re-rendered inside an island).
5
+ */
2
6
  export type CompileOptions = {
3
7
  file: string;
4
8
  target: 'server' | 'client';
5
9
  clientUrl?: string;
10
+ renderImports?: boolean;
6
11
  };
7
12
  export type CompileResult = {
8
13
  code: string;
@@ -10,5 +10,5 @@ export function compile(source, options) {
10
10
  return { code: emitClient(ir), stateful: ir.stateful };
11
11
  if (ir.stateful && !options.clientUrl)
12
12
  throw new Error(`[clarusjs] ${options.file}: clientUrl is required to compile a stateful component for the server`);
13
- return { code: emitServer(ir, options.clientUrl ?? ''), stateful: ir.stateful };
13
+ return { code: emitServer(ir, options.clientUrl ?? '', options.renderImports), stateful: ir.stateful };
14
14
  }
@@ -1,4 +1,4 @@
1
- import type { ImportDecl, InputDecl, ParsedFile } from './parse.ts';
1
+ import { type DataImport, type ImportDecl, type InputDecl, type ParsedFile } from './parse.ts';
2
2
  import { type Signals } from './script.ts';
3
3
  export type IRNode = {
4
4
  kind: 'static';
@@ -68,6 +68,7 @@ export type ComponentIR = {
68
68
  imports: ImportDecl[];
69
69
  script?: string;
70
70
  scriptImports: string[];
71
+ dataImports: DataImport[];
71
72
  signals: Signals;
72
73
  stateful: boolean;
73
74
  nodes: IRNode[];