clarusjs 0.9.0 → 0.10.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 (44) hide show
  1. package/dist/check/generate.js +15 -8
  2. package/dist/compiler/emit-client.js +10 -5
  3. package/dist/compiler/errors.d.ts +14 -1
  4. package/dist/compiler/html-expr.d.ts +21 -0
  5. package/dist/compiler/html-expr.js +24 -1
  6. package/dist/compiler/index.d.ts +20 -2
  7. package/dist/compiler/index.js +2 -1
  8. package/dist/compiler/ir.d.ts +6 -1
  9. package/dist/compiler/ir.js +104 -4
  10. package/dist/compiler/parse.d.ts +34 -0
  11. package/dist/compiler/parse.js +11 -0
  12. package/dist/compiler/script.js +27 -0
  13. package/dist/fetch/index.d.ts +149 -0
  14. package/dist/fetch/index.js +312 -0
  15. package/dist/forms/index.d.ts +21 -2
  16. package/dist/forms/types.d.ts +20 -3
  17. package/dist/runtime/attrs.js +10 -2
  18. package/dist/runtime/dom.d.ts +15 -7
  19. package/dist/runtime/dom.js +33 -13
  20. package/dist/runtime/env.d.ts +8 -1
  21. package/dist/runtime/env.js +8 -1
  22. package/dist/runtime/html.d.ts +9 -7
  23. package/dist/runtime/html.js +12 -7
  24. package/dist/runtime/navigate.d.ts +5 -0
  25. package/dist/runtime/navigation.d.ts +85 -13
  26. package/dist/runtime/navigation.js +77 -11
  27. package/dist/runtime/serialize.d.ts +1 -1
  28. package/dist/runtime/serialize.js +1 -1
  29. package/dist/runtime/server.d.ts +8 -1
  30. package/dist/runtime/server.js +20 -4
  31. package/dist/runtime/signals.d.ts +97 -4
  32. package/dist/runtime/signals.js +88 -4
  33. package/dist/server/handler.d.ts +14 -1
  34. package/dist/server/handler.js +2 -2
  35. package/dist/server/head.d.ts +4 -1
  36. package/dist/server/manifest.d.ts +14 -1
  37. package/dist/server/views.d.ts +64 -6
  38. package/dist/server/views.js +46 -0
  39. package/dist/vite/build.d.ts +1 -1
  40. package/dist/vite/manifest.d.ts +12 -0
  41. package/dist/vite/plugin.d.ts +30 -2
  42. package/dist/vite/plugin.js +2 -1
  43. package/dist/vite/sitemap.d.ts +1 -0
  44. package/package.json +5 -1
@@ -1,17 +1,33 @@
1
1
  // Server-side helpers used by compiled render() functions. Runs at build time or per request, never in the browser.
2
- import { attrHtml, escape } from './html.js';
2
+ import { attrHtml, escape, HTML } from './html.js';
3
3
  import { stringify } from './serialize.js';
4
4
  export { escape, json, blockHtml, forHtml, regionHtml } from './html.js';
5
5
  /**
6
6
  * Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
7
7
  * component has state, the state values it rendered with (`s`), so the browser starts from the same values.
8
+ * @internal Compiled components call this; apps don't.
8
9
  */
9
10
  export function island(name, src, props, html, state, attach, paths) {
10
- const s = state === undefined ? '' : ` s="${escape(stringify(state))}"`;
11
+ const s = state === undefined ? '' : ` s="${escape(toBrowser(state))}"`;
11
12
  const a = attach && attach !== 'load' ? ` a="${escape(attach)}"` : ''; // when to attach: see runtime/loader.ts
12
13
  // A component bound two ways carries each binding's path for the forms engine (clarusjs/forms), given by its parent.
13
14
  const d = Object.entries(paths ?? {}).map(([model, path]) => ` data-cl-path-${escape(model)}="${escape(String(path))}"`).join('');
14
- return `<cl-island c="${escape(name)}" src="${escape(src)}" p="${escape(stringify(props))}"${s}${a}${d}>${html}</cl-island>`;
15
+ return `<cl-island c="${escape(name)}" src="${escape(src)}" p="${escape(toBrowser(props))}"${s}${a}${d}>${html}</cl-island>`;
15
16
  }
16
- /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. */
17
+ /** ` name="value"`, ` name` (true) or '' (false/null/undefined), escaped and URL-checked. @internal */
17
18
  export const attr = attrHtml;
19
+ /**
20
+ * Serialize data for the browser (an island's props and state, a client route's data), refusing h() output first: it's
21
+ * HTML for server-rendered pages, and serialized it would only be a confusing "it is a function" error.
22
+ * @internal clarusjs's own server code calls this; apps don't.
23
+ */
24
+ export function toBrowser(value, path = '', seen = new Set()) {
25
+ if (value && typeof value === 'object' && !seen.has(value)) {
26
+ if (value[HTML] === true)
27
+ throw new TypeError(`[clarusjs] cannot send ${path || 'the value'} to the browser: it is h() output (HTML for server-rendered pages); an island's props and a client route's data can only be data`);
28
+ seen.add(value);
29
+ for (const [key, item] of Object.entries(value))
30
+ toBrowser(item, path ? `${path}.${key}` : key, seen);
31
+ }
32
+ return path ? '' : stringify(value);
33
+ }
@@ -1,24 +1,117 @@
1
+ /**
2
+ * A value that can change, and the code that reads it runs again: `get()`, `set(value)`, and the value it started with.
3
+ * In an island's script you read and write a `state()` as a plain variable; in a `.ts` module, through these.
4
+ * @see https://clarusjs.com/reference/runtime#state
5
+ */
1
6
  export type Signal<T> = {
2
7
  get(): T;
3
8
  set(v: T): void;
4
9
  readonly initial: T;
5
10
  };
11
+ /**
12
+ * A value to read, not write: what `derived()` gives.
13
+ * @see https://clarusjs.com/reference/runtime#derived
14
+ */
6
15
  export type ReadSignal<T> = {
7
16
  get(): T;
8
17
  };
9
- /** Run `fn`; everything it creates (effects, onDispose cleanups, nested scopes) is undone by the returned dispose. */
18
+ /**
19
+ * Run `fn`; everything it creates (effects, onDispose cleanups, nested scopes) is undone by the returned dispose. An
20
+ * island's script already runs in one, disposed when the island leaves the page.
21
+ * @example
22
+ * ```ts
23
+ * const stop = scope(() => {
24
+ * effect(() => console.log(count.get()))
25
+ * })
26
+ * stop() // the effect stops
27
+ * ```
28
+ * @see https://clarusjs.com/reference/runtime#scope
29
+ */
10
30
  export declare function scope(fn: () => void): () => void;
11
- /** Register a cleanup with the enclosing scope (no-op outside one). */
31
+ /**
32
+ * Run `fn` when the enclosing scope is disposed (an island leaving the page, an @if branch or @for row going away).
33
+ * Outside a scope it does nothing.
34
+ * @example
35
+ * ```ts
36
+ * if (browser) {
37
+ * const onResize = () => (width = innerWidth)
38
+ * addEventListener('resize', onResize)
39
+ * onDispose(() => removeEventListener('resize', onResize))
40
+ * }
41
+ * ```
42
+ * @see https://clarusjs.com/reference/runtime#ondispose
43
+ */
12
44
  export declare function onDispose(fn: () => void): void;
13
- /** Read signals without subscribing the running effect to them. */
45
+ /**
46
+ * Read signals without making the running effect (or template expression) depend on them: it doesn't run again
47
+ * when they change.
48
+ * @example
49
+ * ```ts
50
+ * effect(() => {
51
+ * log(query.get(), untrack(() => page.get())) // runs again when query changes, not page
52
+ * })
53
+ * ```
54
+ * @see https://clarusjs.com/reference/runtime#untrack
55
+ */
14
56
  export declare function untrack<T>(fn: () => T): T;
15
- /** Run `fn`, then the effects its writes affect, once each: they never see some of its writes without the others. */
57
+ /**
58
+ * Run `fn`, then the effects its writes affect, once each: they never see some of its writes without the others.
59
+ * @example
60
+ * ```ts
61
+ * batch(() => {
62
+ * first.set('Ada')
63
+ * last.set('Lovelace')
64
+ * }) // an effect reading both runs once, with both names
65
+ * ```
66
+ * @see https://clarusjs.com/reference/runtime#batch
67
+ */
16
68
  export declare function batch(fn: () => void): void;
69
+ /**
70
+ * A reactive value: what reads it (the template, an effect, a derived value) updates when it changes. In an island's
71
+ * script, `let count = state(0)` is read and written as a plain variable (`count++`); in a `.ts` module (a store),
72
+ * through `get()` and `set()`.
73
+ * @example
74
+ * ```ts
75
+ * // stores/cart.ts
76
+ * export const items = state<string[]>([])
77
+ * export const add = (item: string) => items.set([...items.get(), item])
78
+ * ```
79
+ * @see https://clarusjs.com/reference/runtime#state
80
+ */
17
81
  export declare function state<T>(initial: T): Signal<T>;
82
+ /**
83
+ * Run `fn` now and again whenever a signal it read changes. Returns a function that stops it; in an island it stops
84
+ * when the island leaves the page.
85
+ * @example
86
+ * ```ts
87
+ * effect(() => {
88
+ * document.title = `${count.get()} new messages`
89
+ * })
90
+ * ```
91
+ * @see https://clarusjs.com/reference/runtime#effect
92
+ */
18
93
  export declare function effect(fn: () => void): () => void;
94
+ /**
95
+ * A value computed from other signals, kept up to date as they change. Read-only. In an island's script it reads as
96
+ * a plain variable.
97
+ * @example
98
+ * ```ts
99
+ * let price = state(20)
100
+ * let quantity = state(3)
101
+ * const total = derived(() => price * quantity) // 60, then follows both
102
+ * ```
103
+ * @see https://clarusjs.com/reference/runtime#derived
104
+ */
19
105
  export declare function derived<T>(fn: () => T): ReadSignal<T>;
20
106
  /**
21
107
  * Use a store (a module-level `state()`) in an island: `let items = shared(todos)` makes `items` read and write the
22
108
  * store, so every island using it stays in sync. On the server it renders the store's initial value.
109
+ * @example
110
+ * ```ts
111
+ * import { todos } from '../stores/todos.ts'
112
+ * let items = shared(todos)
113
+ * function add(text) { items = [...items, text] } // every island showing todos updates
114
+ * ```
115
+ * @see https://clarusjs.com/reference/runtime#shared
23
116
  */
24
117
  export declare function shared<T>(store: Signal<T>): Signal<T>;
@@ -2,7 +2,18 @@
2
2
  let current = null;
3
3
  // Cleanups registered while a scope() is running: effect stops, event listener removals, child scopes.
4
4
  let currentScope = null;
5
- /** Run `fn`; everything it creates (effects, onDispose cleanups, nested scopes) is undone by the returned dispose. */
5
+ /**
6
+ * Run `fn`; everything it creates (effects, onDispose cleanups, nested scopes) is undone by the returned dispose. An
7
+ * island's script already runs in one, disposed when the island leaves the page.
8
+ * @example
9
+ * ```ts
10
+ * const stop = scope(() => {
11
+ * effect(() => console.log(count.get()))
12
+ * })
13
+ * stop() // the effect stops
14
+ * ```
15
+ * @see https://clarusjs.com/reference/runtime#scope
16
+ */
6
17
  export function scope(fn) {
7
18
  const prev = currentScope;
8
19
  const cleanups = [];
@@ -18,11 +29,33 @@ export function scope(fn) {
18
29
  onDispose(dispose);
19
30
  return dispose;
20
31
  }
21
- /** Register a cleanup with the enclosing scope (no-op outside one). */
32
+ /**
33
+ * Run `fn` when the enclosing scope is disposed (an island leaving the page, an @if branch or @for row going away).
34
+ * Outside a scope it does nothing.
35
+ * @example
36
+ * ```ts
37
+ * if (browser) {
38
+ * const onResize = () => (width = innerWidth)
39
+ * addEventListener('resize', onResize)
40
+ * onDispose(() => removeEventListener('resize', onResize))
41
+ * }
42
+ * ```
43
+ * @see https://clarusjs.com/reference/runtime#ondispose
44
+ */
22
45
  export function onDispose(fn) {
23
46
  currentScope?.push(fn);
24
47
  }
25
- /** Read signals without subscribing the running effect to them. */
48
+ /**
49
+ * Read signals without making the running effect (or template expression) depend on them: it doesn't run again
50
+ * when they change.
51
+ * @example
52
+ * ```ts
53
+ * effect(() => {
54
+ * log(query.get(), untrack(() => page.get())) // runs again when query changes, not page
55
+ * })
56
+ * ```
57
+ * @see https://clarusjs.com/reference/runtime#untrack
58
+ */
26
59
  export function untrack(fn) {
27
60
  const prev = current;
28
61
  current = null;
@@ -35,7 +68,17 @@ export function untrack(fn) {
35
68
  }
36
69
  // Effects waiting for the current batch to end (null outside a batch).
37
70
  let queue = null;
38
- /** Run `fn`, then the effects its writes affect, once each: they never see some of its writes without the others. */
71
+ /**
72
+ * Run `fn`, then the effects its writes affect, once each: they never see some of its writes without the others.
73
+ * @example
74
+ * ```ts
75
+ * batch(() => {
76
+ * first.set('Ada')
77
+ * last.set('Lovelace')
78
+ * }) // an effect reading both runs once, with both names
79
+ * ```
80
+ * @see https://clarusjs.com/reference/runtime#batch
81
+ */
39
82
  export function batch(fn) {
40
83
  if (queue)
41
84
  return fn();
@@ -51,6 +94,18 @@ export function batch(fn) {
51
94
  e.run();
52
95
  }
53
96
  }
97
+ /**
98
+ * A reactive value: what reads it (the template, an effect, a derived value) updates when it changes. In an island's
99
+ * script, `let count = state(0)` is read and written as a plain variable (`count++`); in a `.ts` module (a store),
100
+ * through `get()` and `set()`.
101
+ * @example
102
+ * ```ts
103
+ * // stores/cart.ts
104
+ * export const items = state<string[]>([])
105
+ * export const add = (item: string) => items.set([...items.get(), item])
106
+ * ```
107
+ * @see https://clarusjs.com/reference/runtime#state
108
+ */
54
109
  export function state(initial) {
55
110
  let value = initial;
56
111
  const subs = new Set();
@@ -77,6 +132,17 @@ export function state(initial) {
77
132
  },
78
133
  };
79
134
  }
135
+ /**
136
+ * Run `fn` now and again whenever a signal it read changes. Returns a function that stops it; in an island it stops
137
+ * when the island leaves the page.
138
+ * @example
139
+ * ```ts
140
+ * effect(() => {
141
+ * document.title = `${count.get()} new messages`
142
+ * })
143
+ * ```
144
+ * @see https://clarusjs.com/reference/runtime#effect
145
+ */
80
146
  export function effect(fn) {
81
147
  const e = {
82
148
  deps: new Set(),
@@ -104,6 +170,17 @@ export function effect(fn) {
104
170
  return stop;
105
171
  }
106
172
  // ponytail: eager derived, may compute twice on diamond graphs; switch to push-pull (alien-signals style) when nested derived lands
173
+ /**
174
+ * A value computed from other signals, kept up to date as they change. Read-only. In an island's script it reads as
175
+ * a plain variable.
176
+ * @example
177
+ * ```ts
178
+ * let price = state(20)
179
+ * let quantity = state(3)
180
+ * const total = derived(() => price * quantity) // 60, then follows both
181
+ * ```
182
+ * @see https://clarusjs.com/reference/runtime#derived
183
+ */
107
184
  export function derived(fn) {
108
185
  const s = state(undefined);
109
186
  effect(() => s.set(fn()));
@@ -112,6 +189,13 @@ export function derived(fn) {
112
189
  /**
113
190
  * Use a store (a module-level `state()`) in an island: `let items = shared(todos)` makes `items` read and write the
114
191
  * store, so every island using it stays in sync. On the server it renders the store's initial value.
192
+ * @example
193
+ * ```ts
194
+ * import { todos } from '../stores/todos.ts'
195
+ * let items = shared(todos)
196
+ * function add(text) { items = [...items, text] } // every island showing todos updates
197
+ * ```
198
+ * @see https://clarusjs.com/reference/runtime#shared
115
199
  */
116
200
  export function shared(store) {
117
201
  return store;
@@ -19,10 +19,21 @@ type DataModule = {
19
19
  /**
20
20
  * A redirect for a server page's `load()` to return: `return redirect('/login')`. 302 by default; 301 or 308 for
21
21
  * a page that moved for good, 303 after a form, 307 to keep the method.
22
- * @see https://clarusjs.com/guide/routing
22
+ * @example
23
+ * ```ts
24
+ * // src/pages/account.load.ts (a server route)
25
+ * export async function load({ request }: { request: Request }) {
26
+ * const user = await userFrom(request)
27
+ * if (!user) return redirect('/login')
28
+ * return { user }
29
+ * }
30
+ * ```
31
+ * @see https://clarusjs.com/reference/server#redirect
23
32
  */
24
33
  export declare function redirect(to: string, status?: 301 | 302 | 303 | 307 | 308): Response;
34
+ /** @internal clarusjs's own build and server code call this; apps don't. */
25
35
  export declare function routeFromFile(file: string): string;
36
+ /** @internal clarusjs's own build and server code call this; apps don't. */
26
37
  export declare function createHandler(pages: Record<string, () => Promise<PageModule>>, options?: {
27
38
  loaderUrl?: string;
28
39
  data?: Record<string, () => Promise<DataModule>>;
@@ -57,11 +68,13 @@ export declare function createHandler(pages: Record<string, () => Promise<PageMo
57
68
  /**
58
69
  * A page's fragment: its <title>, then the element marked data-cl-swap (the region fragment navigation replaces), or
59
70
  * its <body> when nothing is marked. Comments are ignored when looking; nested tags of the same name are balanced.
71
+ * @internal clarusjs's own build and server code call this; apps don't.
60
72
  */
61
73
  export declare function toFragment(html: string): string;
62
74
  /**
63
75
  * The 404 page is served at any depth (/a/b/c), so its relative links (href, src) are resolved from the site root:
64
76
  * 'guide' means <base>guide wherever the visitor is.
77
+ * @internal clarusjs's own build and server code call this; apps don't.
65
78
  */
66
79
  export declare function rootLinks(html: string, base: string): string;
67
80
  export {};
@@ -1,5 +1,5 @@
1
1
  import { modeFor } from './modes.js';
2
- import { stringify } from '../runtime/serialize.js';
2
+ import { toBrowser } from '../runtime/server.js';
3
3
  import { completeHead } from './head.js';
4
4
  import { escape } from '../runtime/html.js';
5
5
  const DATA = '__data.json';
@@ -207,7 +207,7 @@ export function createHandler(pages, options = {}) {
207
207
  props = { ...props, ...loaded };
208
208
  }
209
209
  if (wantsData) {
210
- return new Response(head ? null : safeJson(stringify(props)), { headers: { 'content-type': 'application/json; charset=utf-8' } });
210
+ return new Response(head ? null : safeJson(toBrowser(props)), { headers: { 'content-type': 'application/json; charset=utf-8' } });
211
211
  }
212
212
  let html;
213
213
  try {
@@ -1,4 +1,7 @@
1
- /** A head tag as data: ['meta', { name: 'theme-color', content: '#fff' }], ['script', { src }, ''] */
1
+ /**
2
+ * A head tag as data: ['meta', { name: 'theme-color', content: '#fff' }], ['script', { src }, ''].
3
+ * @see https://clarusjs.com/reference/vite-plugin#head
4
+ */
2
5
  export type HeadTag = [tag: string, attrs: Record<string, string | true>, content?: string];
3
6
  export type HeadOptions = {
4
7
  /** '%s · Site': wraps the document's <title>. A <title> inside <cl-head> is used as written. */
@@ -1,4 +1,17 @@
1
1
  import type { Manifest } from '../vite/manifest.ts';
2
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. */
3
+ /**
4
+ * The built site's manifest, or null outside `vite build` (in dev) and on the first prerender pass. A page that
5
+ * calls it during `vite build` is rendered again once the manifest is written.
6
+ * @example
7
+ * ```ts
8
+ * // src/pages/size.load.ts
9
+ * import { readManifest } from 'clarusjs/manifest'
10
+ * export function load() {
11
+ * const home = readManifest()?.routes['/']
12
+ * return { js: home?.js.gzip ?? 0 }
13
+ * }
14
+ * ```
15
+ * @see https://clarusjs.com/reference/server#readmanifest
16
+ */
4
17
  export declare function readManifest(): Manifest | null;
@@ -1,17 +1,75 @@
1
+ import { HTML } from '../runtime/html.ts';
1
2
  type View = {
2
- render(props?: object): string;
3
+ render(props?: object, slots?: Record<string, string>): string;
3
4
  };
4
5
  type Registry = Record<string, () => Promise<View>>;
5
- /** View name → inputs. Filled in by the generated .clarusjs/views.d.ts (declaration merging). */
6
+ /**
7
+ * View name → inputs. Filled in by the generated .clarusjs/views.d.ts (declaration merging).
8
+ * @see https://clarusjs.com/reference/server#render
9
+ */
6
10
  export interface Views {
7
11
  }
8
- /** Without the generated registry any name is accepted; with it, only real views. */
12
+ /**
13
+ * Without the generated registry any name is accepted; with it, only real views.
14
+ * @see https://clarusjs.com/reference/server#render
15
+ */
9
16
  export type ViewName = [keyof Views] extends [never] ? string : Extract<keyof Views, string>;
17
+ /**
18
+ * A view's props: its inputs, from the generated registry.
19
+ * @see https://clarusjs.com/reference/server#render
20
+ */
10
21
  export type ViewProps<N> = N extends keyof Views ? Views[N] : Record<string, unknown>;
11
- /** '/src/components/pill.tscl' → 'components/pill' */
22
+ /** '/src/components/pill.tscl' → 'components/pill' @internal */
12
23
  export declare function viewName(file: string): string;
13
- /** Called by the server entry with import.meta.glob('/src/**\/*.tscl'). */
24
+ /** Called by the server entry with import.meta.glob('/src/**\/*.tscl'). @internal */
14
25
  export declare function registerViews(files: Registry): void;
15
- /** Render a view to HTML. Its props are checked against its inputs once `clarusjs check` has generated the registry. */
26
+ /**
27
+ * Render a view (any `.tscl` under src/, by its path without the extension) to HTML, from server code: a `load()`,
28
+ * an endpoint, a script importing the built server. Its props are checked against its inputs once `clarusjs check`
29
+ * has generated the registry.
30
+ * @example
31
+ * ```ts
32
+ * import { render } from 'clarusjs/views'
33
+ * const html = await render('components/pill', { text: 'new' })
34
+ * ```
35
+ * @see https://clarusjs.com/reference/server#render
36
+ */
16
37
  export declare function render<N extends ViewName>(name: N, props: ViewProps<N>): Promise<string>;
38
+ /**
39
+ * HTML that `h()` built: a template's `{{ }}` inserts it as it is (any other value is escaped). Only `h()` makes one,
40
+ * from escaped parts; data (JSON) can't. It's for server-rendered pages and components: it can't be sent to the
41
+ * browser (an island's props, a client route's data).
42
+ * @see https://clarusjs.com/reference/server#h
43
+ */
44
+ export type Html = {
45
+ readonly [HTML]: true;
46
+ readonly html: string;
47
+ toString(): string;
48
+ };
49
+ /**
50
+ * What `h()` takes as children: text (escaped), `h()` results, numbers, nothing (null, false), and lists of these.
51
+ * @see https://clarusjs.com/reference/server#h
52
+ */
53
+ export type Children = Html | string | number | boolean | null | undefined | Promise<Html> | Children[];
54
+ /**
55
+ * Build HTML in server code: an element (`'p'`, `'div'`), or a view (any `.tscl` under src/, by its path:
56
+ * `'components/card'`), with props or attributes and children. Text is escaped and attributes are URL-checked, as in
57
+ * templates; `h()` results nest. Put the result in a page through `load()`: `{{ }}` inserts it as HTML. Take view and
58
+ * tag names from your own list, never from request data or a database.
59
+ * @param name An element's tag, or a view's name (it has a `/`).
60
+ * @param props A view's inputs, or an element's attributes (`on*`, `srcdoc` refused).
61
+ * @param children The default slot's (or element's) content; for a view, an object fills named slots.
62
+ * @example
63
+ * ```ts
64
+ * // src/pages/index.load.ts
65
+ * import { h } from 'clarusjs/views'
66
+ * export async function load() {
67
+ * const picked = await getWidgets() // [{ view: 'components/chart', props: {…} }, …]
68
+ * return { widgets: await h('div', { class: 'grid' }, picked.map((w) => h(w.view, w.props))) }
69
+ * }
70
+ * // src/pages/index.tscl: @input widgets: any … <main>{{ widgets }}</main>
71
+ * ```
72
+ * @see https://clarusjs.com/reference/server#h
73
+ */
74
+ export declare function h<N extends ViewName>(name: N | (string & {}), props?: (N extends ViewName ? ViewProps<N> : never) | Record<string, unknown>, children?: Children | Record<string, Children>): Promise<Html>;
17
75
  export {};
@@ -1,3 +1,4 @@
1
+ import { attrHtml, escape, HTML } from '../runtime/html.js';
1
2
  export function viewName(file) {
2
3
  return file.replace(/^.*?\/src\//, '').replace(/\.[^./]+$/, '');
3
4
  }
@@ -14,3 +15,48 @@ export async function render(name, props) {
14
15
  throw new Error(`clarusjs: no view "${name}"; views: ${[...views.keys()].sort().join(', ')}`);
15
16
  return (await load()).render(props);
16
17
  }
18
+ const html = (s) => ({ [HTML]: true, html: s, toString: () => s });
19
+ const VOID = new Set(['area', 'br', 'col', 'hr', 'img', 'input', 'source', 'track', 'wbr']);
20
+ const REFUSED = new Set(['script', 'style', 'iframe', 'frame', 'object', 'embed', 'base', 'link', 'meta', 'template']);
21
+ async function childrenHtml(children) {
22
+ const c = await children;
23
+ if (c == null || typeof c === 'boolean')
24
+ return '';
25
+ if (Array.isArray(c))
26
+ return (await Promise.all(c.map(childrenHtml))).join('');
27
+ return escape(c);
28
+ }
29
+ export async function h(name, props = {}, children = []) {
30
+ if (name.includes('/')) {
31
+ const views = store.__clViews;
32
+ const load = views?.get(name);
33
+ if (!load)
34
+ throw new Error(`clarusjs: no view "${name}"${views ? `; views: ${[...views.keys()].sort().join(', ')}` : ' (h() runs in server code, after the server entry has loaded)'}`);
35
+ const named = children && typeof children === 'object' && !Array.isArray(children) && !children[HTML] && !(children instanceof Promise);
36
+ const slots = {};
37
+ const entries = Object.entries(named ? children : { default: children });
38
+ const filled = await Promise.all(entries.map(([, content]) => childrenHtml(content)));
39
+ entries.forEach(([slot], k) => { if (filled[k])
40
+ slots[slot] = filled[k]; });
41
+ return html((await load()).render(props, Object.keys(slots).length ? slots : undefined));
42
+ }
43
+ const tag = name.toLowerCase();
44
+ if (!/^[a-z][a-z0-9-]*$/.test(tag))
45
+ throw new Error(`h(): "${name}" isn't a tag or a view name (views have a /, such as "components/card")`);
46
+ if (REFUSED.has(tag) || tag.startsWith('cl-'))
47
+ throw new Error(`h(): <${tag}> loads or runs things: write it in a .tscl view, where the compiler checks it`);
48
+ if (children && typeof children === 'object' && !Array.isArray(children) && !children[HTML] && !(children instanceof Promise))
49
+ throw new Error(`h(): named slots are for views; <${tag}> takes a list of children`);
50
+ let attrs = '';
51
+ for (const [key, value] of Object.entries(props)) {
52
+ if (!/^[^\s"'>/=]+$/.test(key))
53
+ throw new Error(`h(): "${key}" isn't an attribute name`);
54
+ if (/^on/i.test(key) || key.toLowerCase() === 'srcdoc')
55
+ throw new Error(`h(): "${key}" can't be set from code (event handlers and srcdoc run code); use a .tscl view`);
56
+ attrs += attrHtml(key, value, tag);
57
+ }
58
+ const inner = await childrenHtml(children);
59
+ if (VOID.has(tag) && inner)
60
+ throw new Error(`h(): <${tag}> can't have children`);
61
+ return html(VOID.has(tag) ? `<${tag}${attrs}>` : `<${tag}${attrs}>${inner}</${tag}>`);
62
+ }
@@ -21,7 +21,7 @@ export declare function prerender(serverEntry: string, outDir: string, manifestF
21
21
  loader: boolean;
22
22
  }[];
23
23
  }>;
24
- /** The package a file belongs to, from its last node_modules segment (pnpm: node_modules/.pnpm/x@1/node_modules/x/…). */
24
+ /** The package a file belongs to, from its last node_modules segment (pnpm: node_modules/.pnpm/x@1/node_modules/x/…). @internal */
25
25
  export declare function packageOf(file: string): string | undefined;
26
26
  /**
27
27
  * Component files reachable from `start` through @import lines: relative paths, root-relative ('/src/…') and package
@@ -1,4 +1,8 @@
1
1
  export type Attach = 'load' | 'idle' | 'visible' | 'interaction';
2
+ /**
3
+ * An island on a page, in the manifest: its component, chunk, attach mode, how many, and its gzip size.
4
+ * @see https://clarusjs.com/reference/server#readmanifest
5
+ */
2
6
  export type IslandInfo = {
3
7
  component: string;
4
8
  src: string;
@@ -6,6 +10,10 @@ export type IslandInfo = {
6
10
  count: number;
7
11
  gzip: number;
8
12
  };
13
+ /**
14
+ * A route in the manifest: its mode, islands, JavaScript and CSS.
15
+ * @see https://clarusjs.com/reference/server#readmanifest
16
+ */
9
17
  export type RouteInfo = {
10
18
  /**
11
19
  * 'static': prerendered at build. 'server': rendered per request by dist/server/index.mjs (its key is the route as
@@ -25,6 +33,10 @@ export type RouteInfo = {
25
33
  };
26
34
  css: string[];
27
35
  };
36
+ /**
37
+ * The built site's route manifest (`dist/clarusjs-manifest.json`).
38
+ * @see https://clarusjs.com/reference/server#readmanifest
39
+ */
28
40
  export type Manifest = {
29
41
  version: 1;
30
42
  routes: Record<string, RouteInfo>;
@@ -4,8 +4,13 @@ export { packageOf } from './build.ts';
4
4
  export { gitDates } from './sitemap.ts';
5
5
  import { type ModeTable } from '../server/modes.ts';
6
6
  import type { HeadTag, SiteOptions } from '../server/head.ts';
7
- /** Dev URL of a component's client module: root-relative, or Vite's /@fs/ form for files outside the root. */
7
+ /** Dev URL of a component's client module: root-relative, or Vite's /@fs/ form for files outside the root. @internal */
8
8
  export declare function clientUrlFor(root: string, file: string): string;
9
+ /**
10
+ * The Vite plugin's options: when routes render, the deploy adapter, fragment navigation, link checks, head tags, the
11
+ * site's address, sitemap and robots, redirects, and page sources.
12
+ * @see https://clarusjs.com/reference/vite-plugin#clarusjs
13
+ */
9
14
  export type ClarusOptions = {
10
15
  /** When each route renders: { '/account/*': 'server' }. Routes default to 'static' (prerendered at build). */
11
16
  routes?: ModeTable;
@@ -54,21 +59,44 @@ export type ClarusOptions = {
54
59
  };
55
60
  /** With site.url, vite build writes robots.txt (allow all, and the sitemap), unless public/robots.txt exists. */
56
61
  robots?: boolean;
62
+ /** Collapse whitespace in template text at build (default true). */
63
+ collapseWhitespace?: boolean;
57
64
  };
58
65
  export type { HeadTag };
66
+ /**
67
+ * How a build reports a broken link: fail (`'error'`), print a warning, or skip the check.
68
+ * @see https://clarusjs.com/reference/vite-plugin#links
69
+ */
59
70
  export type LinkLevel = 'error' | 'warn' | 'off';
60
71
  /**
61
72
  * A page source: files with another extension (such as Markdown) turned into .tscl text, then compiled like any
62
73
  * page. `route` is the page's route when the file is under src/pages.
74
+ * @see https://clarusjs.com/reference/vite-plugin#page-sources
63
75
  */
64
76
  export type Source = {
65
77
  extension: string;
66
78
  toTscl(code: string, file: string, context: SourceContext): string;
67
79
  };
68
- /** `root`: the app root. `addDependency(file)`: another file the output depends on (rebuilt when it changes in dev). */
80
+ /** @see https://clarusjs.com/reference/vite-plugin#page-sources
81
+ * `root`: the app root. `addDependency(file)`: another file the output depends on (rebuilt when it changes in dev). */
69
82
  export type SourceContext = {
70
83
  route: string;
71
84
  root: string;
72
85
  addDependency(file: string): void;
73
86
  };
87
+ /**
88
+ * The clarusjs Vite plugin: compiles `.tscl` files, serves pages in development, and on `vite build` builds the
89
+ * browser code, the server and the prerendered pages.
90
+ * @example
91
+ * ```ts
92
+ * // vite.config.ts
93
+ * import { defineConfig } from 'vite'
94
+ * import clarusjs from 'clarusjs/vite'
95
+ *
96
+ * export default defineConfig({
97
+ * plugins: [clarusjs({ routes: { '/account/*': 'server' }, fragments: true })],
98
+ * })
99
+ * ```
100
+ * @see https://clarusjs.com/reference/vite-plugin#clarusjs
101
+ */
74
102
  export default function clarusjs(options?: ClarusOptions): Plugin;
@@ -485,7 +485,8 @@ export default function clarusjs(options = {}) {
485
485
  }
486
486
  try {
487
487
  const renderImports = renderQuery && this.environment.config.consumer !== 'server';
488
- const out = compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file) });
488
+ const collapseWhitespace = command === 'build' && options.collapseWhitespace !== false;
489
+ const out = compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file), collapseWhitespace });
489
490
  if (consumer === 'server' && !renderQuery)
490
491
  for (const w of out.warnings)
491
492
  this.warn(w.message);
@@ -2,6 +2,7 @@
2
2
  * Newest commit time (unix seconds) of every file under `dir` that git knows, by absolute path. One `git log` lists
3
3
  * commits newest first with the files each touched, so a file's first appearance is its last change. Not a git
4
4
  * repository (or no git): an empty map.
5
+ * @internal clarusjs's own build and server code call this; apps don't.
5
6
  */
6
7
  export declare function gitDates(root: string, dir: string): Map<string, number>;
7
8
  /** The sitemap: one <url> per page, under the site URL and base; lastmod (unix seconds) as a date when known. */