clarusjs 0.8.1 → 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 (61) hide show
  1. package/dist/check/generate.d.ts +20 -4
  2. package/dist/check/generate.js +157 -21
  3. package/dist/cli/check.d.ts +13 -0
  4. package/dist/cli/check.js +65 -18
  5. package/dist/cli/index.js +9 -3
  6. package/dist/cli/mapper.d.ts +25 -0
  7. package/dist/cli/mapper.js +65 -0
  8. package/dist/cli/project.d.ts +5 -0
  9. package/dist/cli/project.js +21 -0
  10. package/dist/compiler/emit-client.js +33 -9
  11. package/dist/compiler/emit-server.js +3 -2
  12. package/dist/compiler/errors.d.ts +14 -1
  13. package/dist/compiler/html-expr.d.ts +21 -0
  14. package/dist/compiler/html-expr.js +29 -3
  15. package/dist/compiler/index.d.ts +28 -3
  16. package/dist/compiler/index.js +36 -24
  17. package/dist/compiler/ir.d.ts +19 -1
  18. package/dist/compiler/ir.js +261 -11
  19. package/dist/compiler/parse.d.ts +52 -1
  20. package/dist/compiler/parse.js +145 -6
  21. package/dist/compiler/script.d.ts +22 -1
  22. package/dist/compiler/script.js +108 -5
  23. package/dist/fetch/index.d.ts +149 -0
  24. package/dist/fetch/index.js +312 -0
  25. package/dist/forms/index.d.ts +26 -0
  26. package/dist/forms/index.js +374 -0
  27. package/dist/forms/types.d.ts +111 -0
  28. package/dist/forms/types.js +1 -0
  29. package/dist/runtime/attrs.js +10 -2
  30. package/dist/runtime/dom.d.ts +26 -11
  31. package/dist/runtime/dom.js +102 -14
  32. package/dist/runtime/env.d.ts +14 -0
  33. package/dist/runtime/env.js +14 -0
  34. package/dist/runtime/html.d.ts +9 -7
  35. package/dist/runtime/html.js +12 -7
  36. package/dist/runtime/index.d.ts +3 -2
  37. package/dist/runtime/index.js +3 -2
  38. package/dist/runtime/loader.d.ts +1 -1
  39. package/dist/runtime/loader.js +36 -5
  40. package/dist/runtime/navigate.d.ts +5 -0
  41. package/dist/runtime/navigation.d.ts +85 -13
  42. package/dist/runtime/navigation.js +77 -11
  43. package/dist/runtime/router.js +10 -1
  44. package/dist/runtime/serialize.d.ts +1 -1
  45. package/dist/runtime/serialize.js +1 -1
  46. package/dist/runtime/server.d.ts +9 -2
  47. package/dist/runtime/server.js +23 -5
  48. package/dist/runtime/signals.d.ts +98 -3
  49. package/dist/runtime/signals.js +112 -6
  50. package/dist/server/handler.d.ts +14 -1
  51. package/dist/server/handler.js +2 -2
  52. package/dist/server/head.d.ts +4 -1
  53. package/dist/server/manifest.d.ts +14 -1
  54. package/dist/server/views.d.ts +64 -6
  55. package/dist/server/views.js +46 -0
  56. package/dist/vite/build.d.ts +1 -1
  57. package/dist/vite/manifest.d.ts +12 -0
  58. package/dist/vite/plugin.d.ts +30 -2
  59. package/dist/vite/plugin.js +17 -2
  60. package/dist/vite/sitemap.d.ts +1 -0
  61. package/package.json +19 -1
@@ -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;
@@ -1,5 +1,14 @@
1
- var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx, extraExtensions, ignoreCase) {
2
2
  if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ if (extraExtensions) {
4
+ for (var extension in extraExtensions) {
5
+ var suffix = path.slice(-extension.length);
6
+ if (suffix === extension || ignoreCase && suffix.toLowerCase() === extension.toLowerCase()) {
7
+ var output = extraExtensions[extension];
8
+ return output === extension ? path : path.slice(0, -extension.length) + output;
9
+ }
10
+ }
11
+ }
3
12
  return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
13
  return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
14
  });
@@ -186,6 +195,7 @@ export default function clarusjs(options = {}) {
186
195
  };
187
196
  return {
188
197
  name: 'clarusjs',
198
+ api: { sources },
189
199
  config(userConfig, env) {
190
200
  const projectRoot = resolve(userConfig.root ?? process.cwd());
191
201
  aliases = projectAliases(projectRoot, userConfig.resolve?.alias);
@@ -475,7 +485,12 @@ export default function clarusjs(options = {}) {
475
485
  }
476
486
  try {
477
487
  const renderImports = renderQuery && this.environment.config.consumer !== 'server';
478
- return { code: compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file) }).code, map: null, moduleType: 'js' };
488
+ const collapseWhitespace = command === 'build' && options.collapseWhitespace !== false;
489
+ const out = compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file), collapseWhitespace });
490
+ if (consumer === 'server' && !renderQuery)
491
+ for (const w of out.warnings)
492
+ this.warn(w.message);
493
+ return { code: out.code, map: null, moduleType: 'js' };
479
494
  }
480
495
  catch (err) {
481
496
  if (err instanceof ClarusError)
@@ -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. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clarusjs",
3
- "version": "0.8.1",
3
+ "version": "0.10.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": [
@@ -51,6 +51,14 @@
51
51
  "types": "./dist/runtime/navigation.d.ts",
52
52
  "default": "./dist/runtime/navigation.js"
53
53
  },
54
+ "./forms": {
55
+ "types": "./dist/forms/index.d.ts",
56
+ "default": "./dist/forms/index.js"
57
+ },
58
+ "./fetch": {
59
+ "types": "./dist/fetch/index.d.ts",
60
+ "default": "./dist/fetch/index.js"
61
+ },
54
62
  "./runtime/server": {
55
63
  "types": "./dist/runtime/server.d.ts",
56
64
  "default": "./dist/runtime/server.js"
@@ -96,12 +104,22 @@
96
104
  "happy-dom": "^21.0.4",
97
105
  "tailwindcss": "^4.3.5",
98
106
  "typescript": "^7.0.2",
107
+ "typescript-beta": "npm:typescript@7.1.0-beta",
99
108
  "vite": "^8.3.8",
100
109
  "vitest": "^5.1.1"
101
110
  },
102
111
  "publishConfig": {
103
112
  "access": "public"
104
113
  },
114
+ "typescript": {
115
+ "contentMapper": {
116
+ "exec": [
117
+ "node",
118
+ "./dist/cli/index.js",
119
+ "mapper"
120
+ ]
121
+ }
122
+ },
105
123
  "scripts": {
106
124
  "build": "node ../../scripts/build-package.mjs",
107
125
  "test": "vitest run",