clarusjs 0.1.0 → 0.2.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/README.md +71 -0
- package/dist/compiler/emit-server.js +25 -12
- package/dist/compiler/ir.d.ts +3 -0
- package/dist/compiler/ir.js +24 -6
- package/dist/server/handler.d.ts +4 -1
- package/dist/server/handler.js +30 -5
- package/dist/vite/build.d.ts +9 -0
- package/dist/vite/build.js +55 -0
- package/dist/vite/plugin.js +102 -13
- package/package.json +3 -2
package/README.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
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">
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
<h1 align="center">clarusjs</h1>
|
|
6
|
+
|
|
7
|
+
<p align="center"><strong>Clear, compiled views.</strong></p>
|
|
8
|
+
|
|
9
|
+
Write components in a familiar template language. clarusjs compiles them to plain server HTML and ships JavaScript
|
|
10
|
+
only for the parts that are interactive. Static sites, server rendering and client apps share one component model,
|
|
11
|
+
and you can always see where each line runs.
|
|
12
|
+
|
|
13
|
+
> Status: early (`0.x`). The API will change between minor versions.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
pnpm add clarusjs
|
|
19
|
+
pnpm add -D vite
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Use
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
// vite.config.ts
|
|
26
|
+
import { defineConfig } from 'vite'
|
|
27
|
+
import clarusjs from 'clarusjs/vite'
|
|
28
|
+
|
|
29
|
+
export default defineConfig({ plugins: [clarusjs()] })
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
```clarus
|
|
33
|
+
{{-- src/components/counter.clarus --}}
|
|
34
|
+
@input start: number = 0
|
|
35
|
+
|
|
36
|
+
<script>
|
|
37
|
+
let count = state(start)
|
|
38
|
+
function add() { count++ }
|
|
39
|
+
</script>
|
|
40
|
+
|
|
41
|
+
<button (click)="add()">Clicked {{ count }} times</button>
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
```clarus
|
|
45
|
+
{{-- src/pages/index.clarus --}}
|
|
46
|
+
@import counter from '../components/counter.clarus'
|
|
47
|
+
|
|
48
|
+
<h1>Hello</h1>
|
|
49
|
+
<counter [start]="1" />
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
- `vite` serves `src/pages/**/*.clarus` as routes, rendered on the server.
|
|
53
|
+
- `vite build` writes a static site to `dist/client/`: one HTML file per page, plus JavaScript only for components
|
|
54
|
+
with a `<script>` (the counter above). The `<h1>` ships no JavaScript at all.
|
|
55
|
+
|
|
56
|
+
## Exports
|
|
57
|
+
|
|
58
|
+
| Import | What |
|
|
59
|
+
|---|---|
|
|
60
|
+
| `clarusjs/vite` | the Vite plugin |
|
|
61
|
+
| `clarusjs/compiler` | `compile()`, for tools |
|
|
62
|
+
| `clarusjs/runtime` | browser runtime used by compiled components (signals, attach) |
|
|
63
|
+
| `clarusjs/runtime/server` | server helpers used by compiled components |
|
|
64
|
+
| `clarusjs/server` | `createHandler()`, the `fetch(Request)` handler |
|
|
65
|
+
|
|
66
|
+
## Links
|
|
67
|
+
|
|
68
|
+
- Repository and design: [github.com/forinda/clarusjs](https://github.com/forinda/clarusjs)
|
|
69
|
+
- Contributing: [CONTRIBUTING.md](https://github.com/forinda/clarusjs/blob/main/CONTRIBUTING.md)
|
|
70
|
+
- Security: [SECURITY.md](https://github.com/forinda/clarusjs/blob/main/SECURITY.md)
|
|
71
|
+
- License: MIT
|
|
@@ -5,19 +5,13 @@ export function emitServer(ir, clientUrl) {
|
|
|
5
5
|
let out = `import { ${runtime} } from 'clarusjs/runtime/server'\n`;
|
|
6
6
|
for (const imp of ir.imports)
|
|
7
7
|
out += `import { render as ${renderName(imp.name)} } from '${imp.from}'\n`;
|
|
8
|
-
const
|
|
9
|
-
if (n.kind === 'static')
|
|
10
|
-
return JSON.stringify(n.html);
|
|
11
|
-
if (n.kind === 'component') {
|
|
12
|
-
const props = n.props.map((p) => `${p.name}: ${wrapExpr(p.expr)}`).join(', ');
|
|
13
|
-
return `${renderName(n.name)}({ ${props} })`;
|
|
14
|
-
}
|
|
15
|
-
const value = `__cl_escape(${wrapExpr(n.expr)})`;
|
|
16
|
-
return n.reactive ? `"<!--[${n.index}-->" + ${value} + "<!--]-->"` : value;
|
|
17
|
-
});
|
|
18
|
-
const html = parts.length ? parts.join(' + ') : '""';
|
|
8
|
+
const html = htmlExpr(ir.nodes);
|
|
19
9
|
const props = `{ ${ir.inputs.map((i) => i.name).join(', ')} }`.replace('{ }', '{}');
|
|
20
|
-
out += `\nexport function render(__cl_props = {}) {\n`;
|
|
10
|
+
out += `\nexport function render(__cl_props = {}, __cl_slot) {\n`;
|
|
11
|
+
if (ir.stateful)
|
|
12
|
+
out += ` if (__cl_slot !== undefined) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> does not accept children yet`)})\n`;
|
|
13
|
+
else if (!hasSlot(ir.nodes))
|
|
14
|
+
out += ` if (__cl_slot !== undefined) throw new Error(${JSON.stringify(`[clarusjs] <${ir.name}> has no <slot /> for the content passed to it`)})\n`;
|
|
21
15
|
out += inputsLine(ir);
|
|
22
16
|
if (ir.script)
|
|
23
17
|
out += indentScript(rewriteServer(ir.script));
|
|
@@ -26,3 +20,22 @@ export function emitServer(ir, clientUrl) {
|
|
|
26
20
|
: ` return ${html}\n`;
|
|
27
21
|
return out + '}\n';
|
|
28
22
|
}
|
|
23
|
+
/** One JS string expression for a list of IR nodes. Component children become the child's slot argument. */
|
|
24
|
+
function htmlExpr(nodes) {
|
|
25
|
+
const parts = nodes.map((n) => {
|
|
26
|
+
if (n.kind === 'static')
|
|
27
|
+
return JSON.stringify(n.html);
|
|
28
|
+
if (n.kind === 'slot')
|
|
29
|
+
return '(__cl_slot ?? "")';
|
|
30
|
+
if (n.kind === 'component') {
|
|
31
|
+
const props = n.props.map((p) => `${p.name}: ${wrapExpr(p.expr)}`).join(', ');
|
|
32
|
+
return n.children.length ? `${renderName(n.name)}({ ${props} }, ${htmlExpr(n.children)})` : `${renderName(n.name)}({ ${props} })`;
|
|
33
|
+
}
|
|
34
|
+
const value = `__cl_escape(${wrapExpr(n.expr)})`;
|
|
35
|
+
return n.reactive ? `"<!--[${n.index}-->" + ${value} + "<!--]-->"` : value;
|
|
36
|
+
});
|
|
37
|
+
return parts.length ? parts.join(' + ') : '""';
|
|
38
|
+
}
|
|
39
|
+
function hasSlot(nodes) {
|
|
40
|
+
return nodes.some((n) => n.kind === 'slot' || (n.kind === 'component' && hasSlot(n.children)));
|
|
41
|
+
}
|
package/dist/compiler/ir.d.ts
CHANGED
package/dist/compiler/ir.js
CHANGED
|
@@ -11,15 +11,17 @@ export function lower(parsed, file, source) {
|
|
|
11
11
|
const scriptScope = parsed.script ? new Set([...signals.keys(), ...scriptNames(parsed.script.code)]) : new Set();
|
|
12
12
|
const components = new Set(parsed.imports.map((i) => i.name));
|
|
13
13
|
const nodes = [];
|
|
14
|
+
let out = nodes; // where lowering writes; switched while lowering a component's children
|
|
15
|
+
let slotCount = 0;
|
|
14
16
|
const events = [];
|
|
15
17
|
let holeCount = 0;
|
|
16
18
|
let eventElementCount = 0;
|
|
17
19
|
const emitStatic = (html) => {
|
|
18
|
-
const last =
|
|
20
|
+
const last = out[out.length - 1];
|
|
19
21
|
if (last?.kind === 'static')
|
|
20
22
|
last.html += html;
|
|
21
23
|
else
|
|
22
|
-
|
|
24
|
+
out.push({ kind: 'static', html });
|
|
23
25
|
};
|
|
24
26
|
for (const input of parsed.inputs)
|
|
25
27
|
if (input.default !== undefined)
|
|
@@ -34,14 +36,12 @@ export function lower(parsed, file, source) {
|
|
|
34
36
|
const reactive = referencesNames(node.expr, scriptScope);
|
|
35
37
|
if (reactive && rawText)
|
|
36
38
|
fail(`reactive {{ }} inside <${rawText}> is not supported yet (it cannot hold update markers)`, node.start);
|
|
37
|
-
|
|
39
|
+
out.push({ kind: 'hole', expr: node.expr, reactive, index: reactive ? holeCount++ : -1 });
|
|
38
40
|
return;
|
|
39
41
|
}
|
|
40
42
|
if (components.has(node.tag)) {
|
|
41
43
|
if (stateful)
|
|
42
44
|
fail('components inside a stateful component are not supported yet', node.start);
|
|
43
|
-
if (node.children.length)
|
|
44
|
-
fail('slots are not supported yet', node.start);
|
|
45
45
|
const props = [];
|
|
46
46
|
for (const a of node.attrs) {
|
|
47
47
|
if (a.kind === 'prop') {
|
|
@@ -51,7 +51,25 @@ export function lower(parsed, file, source) {
|
|
|
51
51
|
else
|
|
52
52
|
fail(`component <${node.tag}> only takes [prop] bindings`, a.start);
|
|
53
53
|
}
|
|
54
|
-
|
|
54
|
+
// The wrapped content is rendered here, in this component's scope, and handed to the child as its slot.
|
|
55
|
+
const children = [];
|
|
56
|
+
const parent = out;
|
|
57
|
+
out = children;
|
|
58
|
+
node.children.forEach((child) => visit(child, rawText));
|
|
59
|
+
out = parent;
|
|
60
|
+
out.push({ kind: 'component', name: node.tag, props, children });
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (node.tag === 'slot') {
|
|
64
|
+
if (stateful)
|
|
65
|
+
fail('<slot /> is only supported in components without <script>', node.start);
|
|
66
|
+
if (node.attrs.some((a) => a.name === 'name'))
|
|
67
|
+
fail('named slots are not supported yet', node.start);
|
|
68
|
+
if (node.children.length)
|
|
69
|
+
fail('<slot /> takes no children', node.start);
|
|
70
|
+
if (slotCount++)
|
|
71
|
+
fail('only one <slot /> per component', node.start);
|
|
72
|
+
out.push({ kind: 'slot' });
|
|
55
73
|
return;
|
|
56
74
|
}
|
|
57
75
|
let open = `<${node.tag}`;
|
package/dist/server/handler.d.ts
CHANGED
|
@@ -3,7 +3,10 @@ type PageModule = {
|
|
|
3
3
|
};
|
|
4
4
|
/** '/src/pages/index.clarus' → '/', '/src/pages/blog/index.clarus' → '/blog', '/src/pages/about.clarus' → '/about' */
|
|
5
5
|
export declare function routeFromFile(file: string): string;
|
|
6
|
-
export declare function createHandler(pages: Record<string, () => Promise<PageModule
|
|
6
|
+
export declare function createHandler(pages: Record<string, () => Promise<PageModule>>, options?: {
|
|
7
|
+
loaderUrl?: string;
|
|
8
|
+
}): {
|
|
7
9
|
fetch(request: Request): Promise<Response>;
|
|
10
|
+
routes: string[];
|
|
8
11
|
};
|
|
9
12
|
export {};
|
package/dist/server/handler.js
CHANGED
|
@@ -4,23 +4,48 @@ export function routeFromFile(file) {
|
|
|
4
4
|
const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.clarus$/, '').replace(/\/index$/, '');
|
|
5
5
|
return path || '/';
|
|
6
6
|
}
|
|
7
|
-
export function createHandler(pages) {
|
|
7
|
+
export function createHandler(pages, options = {}) {
|
|
8
8
|
const routes = new Map(Object.entries(pages).map(([file, load]) => [routeFromFile(file), load]));
|
|
9
|
+
const loaderUrl = options.loaderUrl ?? '/cl-loader.js';
|
|
9
10
|
return {
|
|
11
|
+
routes: [...routes.keys()].sort(),
|
|
10
12
|
async fetch(request) {
|
|
11
13
|
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
12
14
|
return new Response('Method Not Allowed', { status: 405 });
|
|
13
|
-
const
|
|
15
|
+
const pathname = new URL(request.url).pathname;
|
|
16
|
+
// '/guide/x/' is the same page as '/guide/x', in dev as on a static host.
|
|
17
|
+
const load = routes.get(pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname);
|
|
14
18
|
const head = request.method === 'HEAD';
|
|
15
19
|
if (!load)
|
|
16
20
|
return new Response(head ? null : 'Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } });
|
|
17
21
|
const html = (await load()).render({});
|
|
22
|
+
const visible = maskComments(html);
|
|
23
|
+
const hasIslands = visible.includes('<cl-island ');
|
|
18
24
|
// Only pages with islands get a script, and only the loader; it fetches each island's own chunk.
|
|
19
|
-
const hasIslands = html.replace(/<!--[\s\S]*?-->/g, '').includes('<cl-island ');
|
|
20
|
-
const scripts = hasIslands ? '<script type="module" src="/cl-loader.js"></script>' : '';
|
|
21
25
|
const style = hasIslands ? '<style>cl-island{display:contents}</style>' : ''; // islands never affect layout
|
|
22
|
-
const
|
|
26
|
+
const script = hasIslands ? `<script type="module" src="${loaderUrl}"></script>` : '';
|
|
27
|
+
const body = /<html[\s>]/i.test(visible)
|
|
28
|
+
? fullDocument(html, style, script)
|
|
29
|
+
: `<!doctype html><html><head><meta charset="utf-8"><title>clarusjs</title>${style}</head><body>${html}${script}</body></html>`;
|
|
23
30
|
return new Response(head ? null : body, { headers: { 'content-type': 'text/html; charset=utf-8' } });
|
|
24
31
|
},
|
|
25
32
|
};
|
|
26
33
|
}
|
|
34
|
+
/** Same length as `html`, with every HTML comment blanked out, so positions found in it are valid in `html`. */
|
|
35
|
+
function maskComments(html) {
|
|
36
|
+
return html.replace(/<!--[\s\S]*?-->/g, (c) => ' '.repeat(c.length));
|
|
37
|
+
}
|
|
38
|
+
/** A page whose layout renders the whole document: add the doctype if missing, and put style/script in place. */
|
|
39
|
+
function fullDocument(html, style, script) {
|
|
40
|
+
let out = /^\s*<!doctype/i.test(html) ? html : `<!doctype html>${html}`;
|
|
41
|
+
if (style) {
|
|
42
|
+
const head = maskComments(out).search(/<\/head>/i);
|
|
43
|
+
out = head === -1 ? out + style : out.slice(0, head) + style + out.slice(head);
|
|
44
|
+
}
|
|
45
|
+
if (script) {
|
|
46
|
+
const bodies = [...maskComments(out).matchAll(/<\/body>/gi)];
|
|
47
|
+
const body = bodies.length ? bodies[bodies.length - 1].index : -1;
|
|
48
|
+
out = body === -1 ? out + script : out.slice(0, body) + script + out.slice(body);
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Absolute paths of every `.clarus` file under `srcDir` (empty if it doesn't exist). */
|
|
2
|
+
export declare function findClarusFiles(srcDir: string): string[];
|
|
3
|
+
/** '/' → 'index.html', '/about/team' → 'about/team/index.html' */
|
|
4
|
+
export declare function routeToFile(route: string): string;
|
|
5
|
+
/**
|
|
6
|
+
* Call the built handler for every route and write the HTML into `outDir`. Any failure fails the build.
|
|
7
|
+
* Runs in a fresh Node process so a rebuilt server bundle is never served from a module cache.
|
|
8
|
+
*/
|
|
9
|
+
export declare function prerender(serverEntry: string, outDir: string): Promise<string[]>;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Build-time helpers for the Vite plugin: find components, and prerender every route to static HTML.
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { readdirSync } from 'node:fs';
|
|
4
|
+
import { resolve } from 'node:path';
|
|
5
|
+
/** Absolute paths of every `.clarus` file under `srcDir` (empty if it doesn't exist). */
|
|
6
|
+
export function findClarusFiles(srcDir) {
|
|
7
|
+
let entries;
|
|
8
|
+
try {
|
|
9
|
+
entries = readdirSync(srcDir, { recursive: true });
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return [];
|
|
13
|
+
}
|
|
14
|
+
return entries.filter((f) => f.endsWith('.clarus')).map((f) => resolve(srcDir, f)).sort();
|
|
15
|
+
}
|
|
16
|
+
/** '/' → 'index.html', '/about/team' → 'about/team/index.html' */
|
|
17
|
+
export function routeToFile(route) {
|
|
18
|
+
const path = route.replace(/^\/+|\/+$/g, '');
|
|
19
|
+
return path ? `${path}/index.html` : 'index.html';
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Call the built handler for every route and write the HTML into `outDir`. Any failure fails the build.
|
|
23
|
+
* Runs in a fresh Node process so a rebuilt server bundle is never served from a module cache.
|
|
24
|
+
*/
|
|
25
|
+
export async function prerender(serverEntry, outDir) {
|
|
26
|
+
const script = `
|
|
27
|
+
import { mkdirSync, writeFileSync } from 'node:fs'
|
|
28
|
+
import { dirname, resolve } from 'node:path'
|
|
29
|
+
import { pathToFileURL } from 'node:url'
|
|
30
|
+
const routeToFile = ${routeToFile.toString()}
|
|
31
|
+
const [entry, outDir] = process.argv.slice(1)
|
|
32
|
+
const { default: handler } = await import(pathToFileURL(entry).href)
|
|
33
|
+
for (const route of handler.routes) {
|
|
34
|
+
let response
|
|
35
|
+
try {
|
|
36
|
+
response = await handler.fetch(new Request('http://localhost' + route))
|
|
37
|
+
} catch (err) {
|
|
38
|
+
process.stderr.write('prerender ' + route + ': ' + (err && err.message || err))
|
|
39
|
+
process.exit(1)
|
|
40
|
+
}
|
|
41
|
+
if (response.status !== 200) {
|
|
42
|
+
process.stderr.write('prerender ' + route + ': status ' + response.status)
|
|
43
|
+
process.exit(1)
|
|
44
|
+
}
|
|
45
|
+
const file = resolve(outDir, routeToFile(route))
|
|
46
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
47
|
+
writeFileSync(file, await response.text())
|
|
48
|
+
}
|
|
49
|
+
process.stdout.write(JSON.stringify(handler.routes))
|
|
50
|
+
`;
|
|
51
|
+
const result = spawnSync(process.execPath, ['--input-type=module', '-e', script, serverEntry, outDir], { encoding: 'utf8' });
|
|
52
|
+
if (result.status !== 0)
|
|
53
|
+
throw new Error(result.stderr.trim() || `prerender failed (exit ${result.status})`);
|
|
54
|
+
return JSON.parse(result.stdout);
|
|
55
|
+
}
|
package/dist/vite/plugin.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
// The clarusjs Vite plugin: a thin adapter around the compiler.
|
|
2
2
|
// Server environment gets render(), client environment gets attach(). Dev requests go through the fetch handler.
|
|
3
|
-
import {
|
|
3
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { isAbsolute, relative, resolve } from 'node:path';
|
|
4
5
|
import { fileURLToPath } from 'node:url';
|
|
5
6
|
import { isRunnableDevEnvironment } from 'vite';
|
|
6
7
|
import { compile, ClarusError } from '../compiler/index.js';
|
|
8
|
+
import { findClarusFiles, prerender } from './build.js';
|
|
7
9
|
import { sendResponse, toRequest } from './node.js';
|
|
8
10
|
// From src/ (workspace, tests) our siblings are .ts files; from the published dist/ they are .js.
|
|
9
11
|
const ext = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
|
|
@@ -14,20 +16,86 @@ export function clientUrlFor(root, file) {
|
|
|
14
16
|
const rel = relative(root, file);
|
|
15
17
|
return rel.startsWith('..') || isAbsolute(rel) ? `/@fs${file}?import` : `/${rel}?import`;
|
|
16
18
|
}
|
|
19
|
+
const LOADER_ENTRY = 'cl-loader';
|
|
20
|
+
const CLIENT_OUT = 'dist/client';
|
|
21
|
+
const SERVER_OUT = 'dist/server';
|
|
22
|
+
const entryName = (root, file) => relative(root, file).replace(/\.clarus$/, '');
|
|
17
23
|
export default function clarusjs() {
|
|
18
24
|
let root = process.cwd();
|
|
25
|
+
let command = 'serve';
|
|
26
|
+
let base = '/';
|
|
27
|
+
// `vite build` only: client entry name (see entryName) → public URL of its hashed chunk.
|
|
28
|
+
// Read from the client manifest on disk, because Vite resolves config (and so creates a new plugin instance) per
|
|
29
|
+
// environment: the server build cannot see state set during the client build.
|
|
30
|
+
let built;
|
|
31
|
+
const builtUrls = () => {
|
|
32
|
+
if (command !== 'build')
|
|
33
|
+
return undefined;
|
|
34
|
+
if (built)
|
|
35
|
+
return built;
|
|
36
|
+
const manifestFile = resolve(root, CLIENT_OUT, '.vite/manifest.json');
|
|
37
|
+
if (!existsSync(manifestFile)) {
|
|
38
|
+
throw new Error(`clarusjs: client manifest not found at ${manifestFile}; the server build must run after the client build`);
|
|
39
|
+
}
|
|
40
|
+
const manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
|
|
41
|
+
built = new Map();
|
|
42
|
+
for (const chunk of Object.values(manifest))
|
|
43
|
+
if (chunk.isEntry && chunk.name)
|
|
44
|
+
built.set(chunk.name, base + chunk.file);
|
|
45
|
+
return built;
|
|
46
|
+
};
|
|
19
47
|
return {
|
|
20
48
|
name: 'clarusjs',
|
|
21
|
-
config
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
49
|
+
config(userConfig, env) {
|
|
50
|
+
const config = {
|
|
51
|
+
appType: 'custom',
|
|
52
|
+
resolve: {
|
|
53
|
+
alias: [
|
|
54
|
+
{ find: 'clarusjs/runtime/server', replacement: here('../runtime/server') },
|
|
55
|
+
{ find: 'clarusjs/runtime', replacement: here('../runtime/index') },
|
|
56
|
+
],
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
if (env.isPreview)
|
|
60
|
+
config.build = { outDir: CLIENT_OUT }; // preview serves the static site
|
|
61
|
+
if (env.command !== 'build')
|
|
62
|
+
return config;
|
|
63
|
+
if (userConfig.base !== undefined && !userConfig.base.startsWith('/') && !/^https?:\/\//.test(userConfig.base)) {
|
|
64
|
+
// Pages live at different depths and islands are imported from the loader, so URLs must not be relative.
|
|
65
|
+
throw new Error(`clarusjs: relative base "${userConfig.base}" is not supported; use an absolute base such as "/" or "/docs/"`);
|
|
66
|
+
}
|
|
67
|
+
// Client entries: the island loader plus every stateful component. Stateless components never reach the client.
|
|
68
|
+
const appRoot = resolve(userConfig.root ?? process.cwd());
|
|
69
|
+
const input = { [LOADER_ENTRY]: here('../runtime/loader') };
|
|
70
|
+
for (const file of findClarusFiles(resolve(appRoot, 'src'))) {
|
|
71
|
+
if (compile(readFileSync(file, 'utf8'), { file, target: 'client' }).stateful)
|
|
72
|
+
input[entryName(appRoot, file)] = file;
|
|
73
|
+
}
|
|
74
|
+
config.builder = {};
|
|
75
|
+
config.environments = {
|
|
76
|
+
// Island chunks are loaded with import() and must keep their `attach` export.
|
|
77
|
+
client: { build: { outDir: CLIENT_OUT, manifest: true, rolldownOptions: { input, preserveEntrySignatures: 'exports-only' } } },
|
|
78
|
+
// Always .mjs, so Node loads it as ESM whatever the app's package.json says.
|
|
79
|
+
ssr: { build: { outDir: SERVER_OUT, rolldownOptions: { input: { index: ENTRY }, output: { entryFileNames: '[name].mjs' } } } },
|
|
80
|
+
};
|
|
81
|
+
return config;
|
|
82
|
+
},
|
|
83
|
+
// Each build re-reads the client manifest: a builder can run buildApp() more than once.
|
|
84
|
+
buildStart() { built = undefined; },
|
|
85
|
+
configResolved(config) {
|
|
86
|
+
root = config.root;
|
|
87
|
+
command = config.command;
|
|
88
|
+
base = config.base;
|
|
89
|
+
},
|
|
90
|
+
// Order matters: the server build needs the client's hashed URLs, and prerendering needs the server build.
|
|
91
|
+
async buildApp(builder) {
|
|
92
|
+
const { client, ssr } = builder.environments;
|
|
93
|
+
if (!client || !ssr)
|
|
94
|
+
return;
|
|
95
|
+
await builder.build(client);
|
|
96
|
+
await builder.build(ssr);
|
|
97
|
+
await prerender(resolve(builder.config.root, SERVER_OUT, 'index.mjs'), resolve(builder.config.root, CLIENT_OUT));
|
|
98
|
+
},
|
|
31
99
|
resolveId(id) {
|
|
32
100
|
if (id === '/cl-loader.js')
|
|
33
101
|
return here('../runtime/loader');
|
|
@@ -37,8 +105,9 @@ export default function clarusjs() {
|
|
|
37
105
|
load(id) {
|
|
38
106
|
if (id !== '\0' + ENTRY)
|
|
39
107
|
return;
|
|
108
|
+
const loaderUrl = builtUrls()?.get(LOADER_ENTRY) ?? '/cl-loader.js';
|
|
40
109
|
return `import { createHandler } from ${JSON.stringify(here('../server/handler'))}\n` +
|
|
41
|
-
`export default createHandler(import.meta.glob('/src/pages/**/*.clarus'))\n`;
|
|
110
|
+
`export default createHandler(import.meta.glob('/src/pages/**/*.clarus'), { loaderUrl: ${JSON.stringify(loaderUrl)} })\n`;
|
|
42
111
|
},
|
|
43
112
|
transform: {
|
|
44
113
|
filter: { id: /\.clarus(\?|$)/ },
|
|
@@ -46,7 +115,11 @@ export default function clarusjs() {
|
|
|
46
115
|
const file = id.replace(/\?.*$/, '');
|
|
47
116
|
const target = this.environment.config.consumer === 'server' ? 'server' : 'client';
|
|
48
117
|
// ponytail: ?import makes Vite's dev transform middleware serve .clarus as JS for the loader's dynamic import; build output uses hashed chunk URLs from the client manifest (stage 3)
|
|
49
|
-
const
|
|
118
|
+
const urls = target === 'server' ? builtUrls() : undefined;
|
|
119
|
+
const clientUrl = urls ? urls.get(entryName(root, file)) : clientUrlFor(root, file);
|
|
120
|
+
if (urls && !clientUrl && compile(code, { file, target: 'client' }).stateful) {
|
|
121
|
+
this.error(`${file}: stateful component is not under src/, so it has no client chunk`);
|
|
122
|
+
}
|
|
50
123
|
try {
|
|
51
124
|
return { code: compile(code, { file, target, clientUrl }).code, map: null };
|
|
52
125
|
}
|
|
@@ -57,6 +130,22 @@ export default function clarusjs() {
|
|
|
57
130
|
}
|
|
58
131
|
},
|
|
59
132
|
},
|
|
133
|
+
// The built site is static files: /guide/x is guide/x/index.html. appType 'custom' turns off Vite's own lookup.
|
|
134
|
+
configurePreviewServer(server) {
|
|
135
|
+
const outDir = resolve(server.config.root, server.config.build.outDir);
|
|
136
|
+
const base = server.config.base; // e.g. '/' or '/docs/'; Vite strips it after this middleware
|
|
137
|
+
server.middlewares.use((req, _res, next) => {
|
|
138
|
+
const url = decodeURIComponent((req.url ?? '/').split('?')[0]);
|
|
139
|
+
const inBase = url === base.slice(0, -1) ? '/' : url.startsWith(base) ? '/' + url.slice(base.length) : undefined;
|
|
140
|
+
if (inBase !== undefined) {
|
|
141
|
+
// A built page wins; anything else (assets, /x.css) falls through to Vite's static files.
|
|
142
|
+
const file = resolve(outDir, `.${inBase.replace(/\/?$/, '/')}index.html`);
|
|
143
|
+
if (file.startsWith(outDir) && existsSync(file))
|
|
144
|
+
req.url = base + file.slice(outDir.length + 1).replace(/\\/g, '/');
|
|
145
|
+
}
|
|
146
|
+
next();
|
|
147
|
+
});
|
|
148
|
+
},
|
|
60
149
|
configureServer(server) {
|
|
61
150
|
return () => {
|
|
62
151
|
server.middlewares.use(async (req, res, next) => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clarusjs",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Clear, compiled views: templates compiled to server HTML, with JavaScript only for interactive islands. SSR, SSG and CSR from one component model, built on Vite.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"keywords": [
|
|
@@ -52,7 +52,8 @@
|
|
|
52
52
|
},
|
|
53
53
|
"files": [
|
|
54
54
|
"dist",
|
|
55
|
-
"LICENSE"
|
|
55
|
+
"LICENSE",
|
|
56
|
+
"README.md"
|
|
56
57
|
],
|
|
57
58
|
"engines": {
|
|
58
59
|
"node": "^22.12.0 || ^24.0.0 || >=26.0.0"
|