clarusjs 0.2.0 → 0.4.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 (47) hide show
  1. package/README.md +5 -15
  2. package/dist/check/generate.d.ts +11 -0
  3. package/dist/check/generate.js +164 -0
  4. package/dist/cli/check.d.ts +17 -0
  5. package/dist/cli/check.js +91 -0
  6. package/dist/cli/explain.d.ts +9 -0
  7. package/dist/cli/explain.js +46 -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 +90 -17
  11. package/dist/compiler/emit-server.js +32 -24
  12. package/dist/compiler/errors.d.ts +1 -1
  13. package/dist/compiler/errors.js +1 -1
  14. package/dist/compiler/html-expr.d.ts +29 -0
  15. package/dist/compiler/html-expr.js +85 -0
  16. package/dist/compiler/ir.d.ts +40 -1
  17. package/dist/compiler/ir.js +155 -33
  18. package/dist/compiler/parse.d.ts +56 -0
  19. package/dist/compiler/parse.js +244 -11
  20. package/dist/compiler/script.d.ts +21 -2
  21. package/dist/compiler/script.js +67 -6
  22. package/dist/runtime/attrs.d.ts +5 -0
  23. package/dist/runtime/attrs.js +56 -0
  24. package/dist/runtime/dom.d.ts +61 -5
  25. package/dist/runtime/dom.js +257 -17
  26. package/dist/runtime/html.d.ts +10 -0
  27. package/dist/runtime/html.js +30 -0
  28. package/dist/runtime/index.d.ts +4 -2
  29. package/dist/runtime/index.js +4 -2
  30. package/dist/runtime/loader.d.ts +7 -2
  31. package/dist/runtime/loader.js +125 -28
  32. package/dist/runtime/serialize.d.ts +8 -0
  33. package/dist/runtime/serialize.js +93 -0
  34. package/dist/runtime/server.d.ts +9 -4
  35. package/dist/runtime/server.js +13 -24
  36. package/dist/runtime/signals.d.ts +12 -0
  37. package/dist/runtime/signals.js +44 -1
  38. package/dist/server/handler.d.ts +1 -1
  39. package/dist/server/handler.js +2 -2
  40. package/dist/server/manifest.d.ts +4 -0
  41. package/dist/server/manifest.js +17 -0
  42. package/dist/vite/build.d.ts +8 -4
  43. package/dist/vite/build.js +16 -9
  44. package/dist/vite/manifest.d.ts +38 -0
  45. package/dist/vite/manifest.js +69 -0
  46. package/dist/vite/plugin.js +49 -10
  47. package/package.json +10 -2
@@ -1,4 +1,9 @@
1
- /** Escape a value for HTML text or a double-quoted attribute. null/undefined render as ''. */
2
- export declare function escape(value: unknown): string;
3
- /** Wrap a stateful component's HTML in its island boundary: name, client chunk URL, serialized props. */
4
- export declare function island(name: string, src: string, props: Record<string, unknown>, html: string): string;
1
+ import { attrHtml } from './html.ts';
2
+ export { escape, blockHtml, forHtml, regionHtml } from './html.ts';
3
+ /**
4
+ * Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
5
+ * component has state, the state values it rendered with (`s`), so the browser starts from the same values.
6
+ */
7
+ export declare function island(name: string, src: string, props: Record<string, unknown>, html: string, state?: Record<string, unknown>, attach?: string): string;
8
+ /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. */
9
+ export declare const attr: typeof attrHtml;
@@ -1,26 +1,15 @@
1
1
  // Server-side helpers used by compiled render() functions. Runs at build time or per request, never in the browser.
2
- const ENTITIES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
3
- /** Escape a value for HTML text or a double-quoted attribute. null/undefined render as ''. */
4
- export function escape(value) {
5
- if (value == null)
6
- return '';
7
- return String(value).replace(/[&<>"']/g, (ch) => ENTITIES[ch]);
8
- }
9
- function assertSerializable(value, path) {
10
- const t = typeof value;
11
- if (t === 'function' || t === 'symbol' || t === 'bigint') {
12
- throw new TypeError(`[clarusjs] island prop "${path}" is a ${t}; island props must be JSON-serializable`);
13
- }
14
- if (t === 'number' && !Number.isFinite(value)) {
15
- throw new TypeError(`[clarusjs] island prop "${path}" is ${value}; island props must be JSON-serializable`);
16
- }
17
- if (value && t === 'object') {
18
- for (const [k, v] of Object.entries(value))
19
- assertSerializable(v, path ? `${path}.${k}` : k);
20
- }
21
- }
22
- /** Wrap a stateful component's HTML in its island boundary: name, client chunk URL, serialized props. */
23
- export function island(name, src, props, html) {
24
- assertSerializable(props, '');
25
- return `<cl-island c="${escape(name)}" src="${escape(src)}" p="${escape(JSON.stringify(props))}">${html}</cl-island>`;
2
+ import { attrHtml, escape } from './html.js';
3
+ import { stringify } from './serialize.js';
4
+ export { escape, blockHtml, forHtml, regionHtml } from './html.js';
5
+ /**
6
+ * Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
7
+ * component has state, the state values it rendered with (`s`), so the browser starts from the same values.
8
+ */
9
+ export function island(name, src, props, html, state, attach) {
10
+ const s = state === undefined ? '' : ` s="${escape(stringify(state))}"`;
11
+ const a = attach && attach !== 'load' ? ` a="${escape(attach)}"` : ''; // when to attach: see runtime/loader.ts
12
+ return `<cl-island c="${escape(name)}" src="${escape(src)}" p="${escape(stringify(props))}"${s}${a}>${html}</cl-island>`;
26
13
  }
14
+ /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. */
15
+ export const attr = attrHtml;
@@ -1,10 +1,22 @@
1
1
  export type Signal<T> = {
2
2
  get(): T;
3
3
  set(v: T): void;
4
+ readonly initial: T;
4
5
  };
5
6
  export type ReadSignal<T> = {
6
7
  get(): T;
7
8
  };
9
+ /** Run `fn`; everything it creates (effects, onDispose cleanups, nested scopes) is undone by the returned dispose. */
10
+ export declare function scope(fn: () => void): () => void;
11
+ /** Register a cleanup with the enclosing scope (no-op outside one). */
12
+ export declare function onDispose(fn: () => void): void;
13
+ /** Read signals without subscribing the running effect to them. */
14
+ export declare function untrack<T>(fn: () => T): T;
8
15
  export declare function state<T>(initial: T): Signal<T>;
9
16
  export declare function effect(fn: () => void): () => void;
10
17
  export declare function derived<T>(fn: () => T): ReadSignal<T>;
18
+ /**
19
+ * Use a store (a module-level `state()`) in an island: `let items = shared(todos)` makes `items` read and write the
20
+ * store, so every island using it stays in sync. On the server it renders the store's initial value.
21
+ */
22
+ export declare function shared<T>(store: Signal<T>): Signal<T>;
@@ -1,9 +1,43 @@
1
1
  // Fine-grained reactivity used by compiled attach() functions. Browser only.
2
2
  let current = null;
3
+ // Cleanups registered while a scope() is running: effect stops, event listener removals, child scopes.
4
+ let currentScope = null;
5
+ /** Run `fn`; everything it creates (effects, onDispose cleanups, nested scopes) is undone by the returned dispose. */
6
+ export function scope(fn) {
7
+ const prev = currentScope;
8
+ const cleanups = [];
9
+ currentScope = cleanups;
10
+ try {
11
+ fn();
12
+ }
13
+ finally {
14
+ currentScope = prev;
15
+ }
16
+ const dispose = () => { for (const c of cleanups.splice(0).reverse())
17
+ c(); };
18
+ onDispose(dispose);
19
+ return dispose;
20
+ }
21
+ /** Register a cleanup with the enclosing scope (no-op outside one). */
22
+ export function onDispose(fn) {
23
+ currentScope?.push(fn);
24
+ }
25
+ /** Read signals without subscribing the running effect to them. */
26
+ export function untrack(fn) {
27
+ const prev = current;
28
+ current = null;
29
+ try {
30
+ return fn();
31
+ }
32
+ finally {
33
+ current = prev;
34
+ }
35
+ }
3
36
  export function state(initial) {
4
37
  let value = initial;
5
38
  const subs = new Set();
6
39
  return {
40
+ initial, // what the server renders for a shared store: never a value another request set
7
41
  get() {
8
42
  if (current?.active) {
9
43
  subs.add(current);
@@ -42,8 +76,10 @@ export function effect(fn) {
42
76
  },
43
77
  };
44
78
  e.run();
45
- return () => { e.active = false; for (const subs of e.deps)
79
+ const stop = () => { e.active = false; for (const subs of e.deps)
46
80
  subs.delete(e); e.deps.clear(); };
81
+ onDispose(stop);
82
+ return stop;
47
83
  }
48
84
  // ponytail: eager derived, may compute twice on diamond graphs; switch to push-pull (alien-signals style) when nested derived lands
49
85
  export function derived(fn) {
@@ -51,3 +87,10 @@ export function derived(fn) {
51
87
  effect(() => s.set(fn()));
52
88
  return { get: s.get };
53
89
  }
90
+ /**
91
+ * Use a store (a module-level `state()`) in an island: `let items = shared(todos)` makes `items` read and write the
92
+ * store, so every island using it stays in sync. On the server it renders the store's initial value.
93
+ */
94
+ export function shared(store) {
95
+ return store;
96
+ }
@@ -1,7 +1,7 @@
1
1
  type PageModule = {
2
2
  render(props?: object): string;
3
3
  };
4
- /** '/src/pages/index.clarus' → '/', '/src/pages/blog/index.clarus' → '/blog', '/src/pages/about.clarus' → '/about' */
4
+ /** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.tscl' → '/about' */
5
5
  export declare function routeFromFile(file: string): string;
6
6
  export declare function createHandler(pages: Record<string, () => Promise<PageModule>>, options?: {
7
7
  loaderUrl?: string;
@@ -1,7 +1,7 @@
1
1
  // The fetch handler: Request → Response. Same function for dev, per-request SSR and (later) build-time prerender.
2
- /** '/src/pages/index.clarus' → '/', '/src/pages/blog/index.clarus' → '/blog', '/src/pages/about.clarus' → '/about' */
2
+ /** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.tscl' → '/about' */
3
3
  export function routeFromFile(file) {
4
- const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.clarus$/, '').replace(/\/index$/, '');
4
+ const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.tscl$/, '').replace(/\/index$/, '');
5
5
  return path || '/';
6
6
  }
7
7
  export function createHandler(pages, options = {}) {
@@ -0,0 +1,4 @@
1
+ import type { Manifest } from '../vite/manifest.ts';
2
+ export type { Manifest, RouteInfo, IslandInfo } from '../vite/manifest.ts';
3
+ /** The built site's manifest, or null outside `vite build` (in dev) and on the first prerender pass. */
4
+ export declare function readManifest(): Manifest | null;
@@ -0,0 +1,17 @@
1
+ // Read the route manifest while pages are prerendered. Server only (Node): a page that calls readManifest() during
2
+ // `vite build` is rendered again once the manifest is written, so it can show what the built site ships.
3
+ import { readFileSync } from 'node:fs';
4
+ /** The built site's manifest, or null outside `vite build` (in dev) and on the first prerender pass. */
5
+ export function readManifest() {
6
+ ;
7
+ globalThis.__clManifestRead = true;
8
+ const file = process.env.CLARUS_MANIFEST;
9
+ if (!file)
10
+ return null;
11
+ try {
12
+ return JSON.parse(readFileSync(file, 'utf8'));
13
+ }
14
+ catch {
15
+ return null;
16
+ }
17
+ }
@@ -1,9 +1,13 @@
1
- /** Absolute paths of every `.clarus` file under `srcDir` (empty if it doesn't exist). */
1
+ /** Absolute paths of every `.tscl` file under `srcDir` (empty if it doesn't exist). */
2
2
  export declare function findClarusFiles(srcDir: string): string[];
3
3
  /** '/' → 'index.html', '/about/team' → 'about/team/index.html' */
4
4
  export declare function routeToFile(route: string): string;
5
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.
6
+ * Call the built handler for every route (or only `only`) and write the HTML into `outDir`. Any failure fails the
7
+ * build. Runs in a fresh Node process so a rebuilt server bundle is never served from a module cache. Returns the
8
+ * routes rendered and those that read the route manifest (readManifest() from `manifestFile`).
8
9
  */
9
- export declare function prerender(serverEntry: string, outDir: string): Promise<string[]>;
10
+ export declare function prerender(serverEntry: string, outDir: string, manifestFile: string, only?: string[]): Promise<{
11
+ routes: string[];
12
+ readers: string[];
13
+ }>;
@@ -2,7 +2,7 @@
2
2
  import { spawnSync } from 'node:child_process';
3
3
  import { readdirSync } from 'node:fs';
4
4
  import { resolve } from 'node:path';
5
- /** Absolute paths of every `.clarus` file under `srcDir` (empty if it doesn't exist). */
5
+ /** Absolute paths of every `.tscl` file under `srcDir` (empty if it doesn't exist). */
6
6
  export function findClarusFiles(srcDir) {
7
7
  let entries;
8
8
  try {
@@ -11,7 +11,7 @@ export function findClarusFiles(srcDir) {
11
11
  catch {
12
12
  return [];
13
13
  }
14
- return entries.filter((f) => f.endsWith('.clarus')).map((f) => resolve(srcDir, f)).sort();
14
+ return entries.filter((f) => f.endsWith('.tscl')).map((f) => resolve(srcDir, f)).sort();
15
15
  }
16
16
  /** '/' → 'index.html', '/about/team' → 'about/team/index.html' */
17
17
  export function routeToFile(route) {
@@ -19,18 +19,22 @@ export function routeToFile(route) {
19
19
  return path ? `${path}/index.html` : 'index.html';
20
20
  }
21
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.
22
+ * Call the built handler for every route (or only `only`) and write the HTML into `outDir`. Any failure fails the
23
+ * build. Runs in a fresh Node process so a rebuilt server bundle is never served from a module cache. Returns the
24
+ * routes rendered and those that read the route manifest (readManifest() from `manifestFile`).
24
25
  */
25
- export async function prerender(serverEntry, outDir) {
26
+ export async function prerender(serverEntry, outDir, manifestFile, only) {
26
27
  const script = `
27
28
  import { mkdirSync, writeFileSync } from 'node:fs'
28
29
  import { dirname, resolve } from 'node:path'
29
30
  import { pathToFileURL } from 'node:url'
30
31
  const routeToFile = ${routeToFile.toString()}
31
- const [entry, outDir] = process.argv.slice(1)
32
+ const [entry, outDir, only] = process.argv.slice(1)
32
33
  const { default: handler } = await import(pathToFileURL(entry).href)
33
- for (const route of handler.routes) {
34
+ const routes = only ? JSON.parse(only) : handler.routes
35
+ const readers = []
36
+ for (const route of routes) {
37
+ globalThis.__clManifestRead = false
34
38
  let response
35
39
  try {
36
40
  response = await handler.fetch(new Request('http://localhost' + route))
@@ -45,10 +49,13 @@ export async function prerender(serverEntry, outDir) {
45
49
  const file = resolve(outDir, routeToFile(route))
46
50
  mkdirSync(dirname(file), { recursive: true })
47
51
  writeFileSync(file, await response.text())
52
+ if (globalThis.__clManifestRead) readers.push(route)
48
53
  }
49
- process.stdout.write(JSON.stringify(handler.routes))
54
+ process.stdout.write(JSON.stringify({ routes, readers }))
50
55
  `;
51
- const result = spawnSync(process.execPath, ['--input-type=module', '-e', script, serverEntry, outDir], { encoding: 'utf8' });
56
+ const args = ['--input-type=module', '-e', script, serverEntry, outDir, ...(only ? [JSON.stringify(only)] : [])];
57
+ const env = { ...process.env, CLARUS_MANIFEST: manifestFile };
58
+ const result = spawnSync(process.execPath, args, { encoding: 'utf8', env });
52
59
  if (result.status !== 0)
53
60
  throw new Error(result.stderr.trim() || `prerender failed (exit ${result.status})`);
54
61
  return JSON.parse(result.stdout);
@@ -0,0 +1,38 @@
1
+ export type Attach = 'load' | 'idle' | 'visible' | 'interaction';
2
+ export type IslandInfo = {
3
+ component: string;
4
+ src: string;
5
+ attach: Attach;
6
+ count: number;
7
+ gzip: number;
8
+ };
9
+ export type RouteInfo = {
10
+ mode: 'static';
11
+ html: string;
12
+ loader: null;
13
+ islands: IslandInfo[];
14
+ /** Files relative to dist/client; gzip sizes in bytes. initialGzip is what loads with the page (attach="load"). */
15
+ js: {
16
+ files: string[];
17
+ gzip: number;
18
+ initialGzip: number;
19
+ };
20
+ css: string[];
21
+ };
22
+ export type Manifest = {
23
+ version: 1;
24
+ routes: Record<string, RouteInfo>;
25
+ };
26
+ /** Vite's client manifest (dist/client/.vite/manifest.json). */
27
+ export type ChunkGraph = Record<string, {
28
+ file: string;
29
+ imports?: string[];
30
+ }>;
31
+ /** What one prerendered page ships. `size` returns a built file's gzip size. */
32
+ export declare function describeRoute(route: string, html: string, opts: {
33
+ base: string;
34
+ chunks: ChunkGraph;
35
+ size(file: string): number;
36
+ }): RouteInfo;
37
+ /** Describe every prerendered route and write `<distDir>/clarusjs-manifest.json`. */
38
+ export declare function writeManifest(distDir: string, routes: string[], base: string): Manifest;
@@ -0,0 +1,69 @@
1
+ // The route manifest: after `vite build`, what each page ships, read back from its prerendered HTML.
2
+ // dist/clarusjs-manifest.json is what `clarusjs explain` prints. Written outside dist/client, so it isn't served.
3
+ import { readFileSync, writeFileSync } from 'node:fs';
4
+ import { resolve } from 'node:path';
5
+ import { gzipSync } from 'node:zlib';
6
+ import { routeToFile } from './build.js';
7
+ const attrsOf = (tag) => {
8
+ const out = {};
9
+ for (const m of tag.matchAll(/([\w-]+)="([^"]*)"/g))
10
+ out[m[1]] = m[2].replace(/&amp;/g, '&');
11
+ return out;
12
+ };
13
+ /** What one prerendered page ships. `size` returns a built file's gzip size. */
14
+ export function describeRoute(route, html, opts) {
15
+ const local = (url) => (url.startsWith(opts.base) ? url.slice(opts.base.length) : url.replace(/^\//, ''));
16
+ const byFile = new Map(Object.values(opts.chunks).map((c) => [c.file, c]));
17
+ const keyFile = new Map(Object.entries(opts.chunks).map(([k, c]) => [k, c.file]));
18
+ // A chunk and everything it imports, in load order.
19
+ const closure = (file, into) => {
20
+ if (into.includes(file))
21
+ return;
22
+ into.push(file);
23
+ for (const imp of byFile.get(file)?.imports ?? [])
24
+ closure(keyFile.get(imp) ?? imp, into);
25
+ };
26
+ const islands = [];
27
+ for (const m of html.matchAll(/<cl-island\b([^>]*)>/g)) {
28
+ const a = attrsOf(m[1]);
29
+ const attach = (a.a ?? 'load');
30
+ const src = local(a.src ?? '');
31
+ const same = islands.find((i) => i.component === a.c && i.attach === attach);
32
+ if (same)
33
+ same.count++;
34
+ else
35
+ islands.push({ component: a.c ?? '', src, attach, count: 1, gzip: opts.size(src) });
36
+ }
37
+ const all = [];
38
+ const initial = [];
39
+ for (const m of html.matchAll(/<script type="module" src="([^"]+)"><\/script>/g)) {
40
+ closure(local(m[1]), all);
41
+ closure(local(m[1]), initial);
42
+ }
43
+ for (const island of islands) {
44
+ closure(island.src, all);
45
+ if (island.attach === 'load')
46
+ closure(island.src, initial);
47
+ }
48
+ const sum = (files) => files.reduce((n, f) => n + opts.size(f), 0);
49
+ const css = [...html.matchAll(/<link\b[^>]*rel="stylesheet"[^>]*>/g)].map((m) => attrsOf(m[0]).href).filter(Boolean);
50
+ // ponytail: every route is prerendered with no data loader; mode and loader become real with routing (#28).
51
+ return { mode: 'static', html: routeToFile(route), loader: null, islands, js: { files: all, gzip: sum(all), initialGzip: sum(initial) }, css };
52
+ }
53
+ /** Describe every prerendered route and write `<distDir>/clarusjs-manifest.json`. */
54
+ export function writeManifest(distDir, routes, base) {
55
+ const client = resolve(distDir, 'client');
56
+ const chunks = JSON.parse(readFileSync(resolve(client, '.vite/manifest.json'), 'utf8'));
57
+ const sizes = new Map();
58
+ const size = (file) => {
59
+ if (!sizes.has(file))
60
+ sizes.set(file, gzipSync(readFileSync(resolve(client, file)), { level: 9 }).length);
61
+ return sizes.get(file);
62
+ };
63
+ const manifest = { version: 1, routes: {} };
64
+ for (const route of routes) {
65
+ manifest.routes[route] = describeRoute(route, readFileSync(resolve(client, routeToFile(route)), 'utf8'), { base, chunks, size });
66
+ }
67
+ writeFileSync(resolve(distDir, 'clarusjs-manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
68
+ return manifest;
69
+ }
@@ -1,11 +1,12 @@
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 { existsSync, readFileSync } from 'node:fs';
4
- import { isAbsolute, relative, resolve } from 'node:path';
3
+ import { existsSync, readFileSync, rmSync } from 'node:fs';
4
+ import { dirname, isAbsolute, relative, resolve } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { isRunnableDevEnvironment } from 'vite';
7
7
  import { compile, ClarusError } from '../compiler/index.js';
8
8
  import { findClarusFiles, prerender } from './build.js';
9
+ import { writeManifest } from './manifest.js';
9
10
  import { sendResponse, toRequest } from './node.js';
10
11
  // From src/ (workspace, tests) our siblings are .ts files; from the published dist/ they are .js.
11
12
  const ext = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
@@ -18,8 +19,10 @@ export function clientUrlFor(root, file) {
18
19
  }
19
20
  const LOADER_ENTRY = 'cl-loader';
20
21
  const CLIENT_OUT = 'dist/client';
22
+ // Placeholder for a nested island's chunk URL in the client build, replaced once the bundle's file names are known.
23
+ const CHUNK_TOKEN = '__CLARUS_CHUNK__';
21
24
  const SERVER_OUT = 'dist/server';
22
- const entryName = (root, file) => relative(root, file).replace(/\.clarus$/, '');
25
+ const entryName = (root, file) => relative(root, file).replace(/\.tscl$/, '');
23
26
  export default function clarusjs() {
24
27
  let root = process.cwd();
25
28
  let command = 'serve';
@@ -82,6 +85,25 @@ export default function clarusjs() {
82
85
  },
83
86
  // Each build re-reads the client manifest: a builder can run buildApp() more than once.
84
87
  buildStart() { built = undefined; },
88
+ // Client build: nested islands rendered in the browser get their chunk's real URL.
89
+ generateBundle(_options, bundle) {
90
+ if (this.environment.config.consumer !== 'client' || command !== 'build')
91
+ return;
92
+ const byName = new Map();
93
+ for (const out of Object.values(bundle))
94
+ if (out.type === 'chunk' && out.isEntry)
95
+ byName.set(out.name, base + out.fileName);
96
+ for (const out of Object.values(bundle)) {
97
+ if (out.type !== 'chunk' || !out.code.includes(CHUNK_TOKEN))
98
+ continue;
99
+ out.code = out.code.replace(/__CLARUS_CHUNK__\[(.+?)\]__/g, (_, name) => {
100
+ const url = byName.get(name);
101
+ if (!url)
102
+ this.error(`clarusjs: no client chunk for ${name}.tscl (stateful components must be under src/)`);
103
+ return url;
104
+ });
105
+ }
106
+ },
85
107
  configResolved(config) {
86
108
  root = config.root;
87
109
  command = config.command;
@@ -94,7 +116,18 @@ export default function clarusjs() {
94
116
  return;
95
117
  await builder.build(client);
96
118
  await builder.build(ssr);
97
- await prerender(resolve(builder.config.root, SERVER_OUT, 'index.mjs'), resolve(builder.config.root, CLIENT_OUT));
119
+ const entry = resolve(builder.config.root, SERVER_OUT, 'index.mjs');
120
+ const out = resolve(builder.config.root, CLIENT_OUT);
121
+ const dist = dirname(out);
122
+ const manifestFile = resolve(dist, 'clarusjs-manifest.json');
123
+ rmSync(manifestFile, { force: true }); // a page reading the manifest must never see the previous build's
124
+ const { routes, readers } = await prerender(entry, out, manifestFile);
125
+ writeManifest(dist, routes, builder.config.base);
126
+ // Pages that read the manifest saw none on the first pass: render them again now that it exists.
127
+ if (readers.length) {
128
+ await prerender(entry, out, manifestFile, readers);
129
+ writeManifest(dist, routes, builder.config.base);
130
+ }
98
131
  },
99
132
  resolveId(id) {
100
133
  if (id === '/cl-loader.js')
@@ -107,16 +140,22 @@ export default function clarusjs() {
107
140
  return;
108
141
  const loaderUrl = builtUrls()?.get(LOADER_ENTRY) ?? '/cl-loader.js';
109
142
  return `import { createHandler } from ${JSON.stringify(here('../server/handler'))}\n` +
110
- `export default createHandler(import.meta.glob('/src/pages/**/*.clarus'), { loaderUrl: ${JSON.stringify(loaderUrl)} })\n`;
143
+ `export default createHandler(import.meta.glob('/src/pages/**/*.tscl'), { loaderUrl: ${JSON.stringify(loaderUrl)} })\n`;
111
144
  },
112
145
  transform: {
113
- filter: { id: /\.clarus(\?|$)/ },
146
+ filter: { id: /\.tscl(\?|$)/ },
114
147
  handler(code, id) {
115
148
  const file = id.replace(/\?.*$/, '');
116
- const target = this.environment.config.consumer === 'server' ? 'server' : 'client';
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)
118
- const urls = target === 'server' ? builtUrls() : undefined;
119
- const clientUrl = urls ? urls.get(entryName(root, file)) : clientUrlFor(root, file);
149
+ // ?render: a component's server render function, used in the browser to render children of islands.
150
+ const target = this.environment.config.consumer === 'server' || /[?&]render\b/.test(id) ? 'server' : 'client';
151
+ // ponytail: ?import makes Vite's dev transform middleware serve .tscl as JS for the loader's dynamic import; build output uses hashed chunk URLs from the client manifest (stage 3)
152
+ const consumer = this.environment.config.consumer;
153
+ // Server build: chunk URLs come from the client manifest. Client build (a ?render child): the chunk doesn't
154
+ // exist yet, so write a placeholder that generateBundle swaps for the real file name. Dev: the source URL.
155
+ const urls = consumer === 'server' ? builtUrls() : undefined;
156
+ const clientUrl = urls
157
+ ? urls.get(entryName(root, file))
158
+ : command === 'build' ? `${CHUNK_TOKEN}[${entryName(root, file)}]__` : clientUrlFor(root, file);
120
159
  if (urls && !clientUrl && compile(code, { file, target: 'client' }).stateful) {
121
160
  this.error(`${file}: stateful component is not under src/, so it has no client chunk`);
122
161
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clarusjs",
3
- "version": "0.2.0",
3
+ "version": "0.4.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": [
@@ -48,8 +48,15 @@
48
48
  "./vite": {
49
49
  "types": "./dist/vite/plugin.d.ts",
50
50
  "default": "./dist/vite/plugin.js"
51
+ },
52
+ "./manifest": {
53
+ "types": "./dist/server/manifest.d.ts",
54
+ "default": "./dist/server/manifest.js"
51
55
  }
52
56
  },
57
+ "bin": {
58
+ "clarusjs": "./dist/cli/index.js"
59
+ },
53
60
  "files": [
54
61
  "dist",
55
62
  "LICENSE",
@@ -59,7 +66,8 @@
59
66
  "node": "^22.12.0 || ^24.0.0 || >=26.0.0"
60
67
  },
61
68
  "dependencies": {
62
- "acorn": "^8.19.0"
69
+ "acorn": "^8.19.0",
70
+ "commander": "^15.1.0"
63
71
  },
64
72
  "peerDependencies": {
65
73
  "vite": "^8.0.0"