clarusjs 0.14.0 → 0.16.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 (54) hide show
  1. package/dist/check/generate.d.ts +2 -5
  2. package/dist/check/generate.js +119 -5
  3. package/dist/cli/check.d.ts +10 -2
  4. package/dist/cli/check.js +38 -12
  5. package/dist/cli/index.js +4 -1
  6. package/dist/cli/mapper.js +24 -1
  7. package/dist/cli/project.d.ts +6 -0
  8. package/dist/cli/project.js +1 -1
  9. package/dist/compiler/class-style.js +2 -2
  10. package/dist/compiler/components.d.ts +61 -0
  11. package/dist/compiler/components.js +81 -0
  12. package/dist/compiler/element-attrs.d.ts +7 -0
  13. package/dist/compiler/element-attrs.js +32 -0
  14. package/dist/compiler/emit-client.js +23 -3
  15. package/dist/compiler/emit-server.js +11 -8
  16. package/dist/compiler/html-expr.d.ts +2 -1
  17. package/dist/compiler/html-expr.js +15 -9
  18. package/dist/compiler/index.d.ts +14 -2
  19. package/dist/compiler/index.js +143 -3
  20. package/dist/compiler/ir.d.ts +24 -0
  21. package/dist/compiler/ir.js +81 -11
  22. package/dist/compiler/lint.d.ts +26 -2
  23. package/dist/compiler/lint.js +64 -4
  24. package/dist/compiler/parse.d.ts +37 -0
  25. package/dist/compiler/parse.js +42 -10
  26. package/dist/compiler/script.d.ts +11 -0
  27. package/dist/compiler/script.js +41 -0
  28. package/dist/compiler/shared.d.ts +6 -0
  29. package/dist/compiler/shared.js +14 -0
  30. package/dist/forms/index.js +15 -3
  31. package/dist/runtime/attrs.d.ts +6 -0
  32. package/dist/runtime/attrs.js +22 -3
  33. package/dist/runtime/dom.d.ts +39 -1
  34. package/dist/runtime/dom.js +159 -23
  35. package/dist/runtime/html.d.ts +6 -0
  36. package/dist/runtime/html.js +12 -0
  37. package/dist/runtime/index.d.ts +1 -1
  38. package/dist/runtime/index.js +1 -1
  39. package/dist/runtime/loader.js +53 -7
  40. package/dist/runtime/router.d.ts +6 -1
  41. package/dist/runtime/router.js +1 -1
  42. package/dist/runtime/server.d.ts +8 -2
  43. package/dist/runtime/server.js +14 -7
  44. package/dist/server/handler.d.ts +28 -1
  45. package/dist/server/handler.js +44 -1
  46. package/dist/server/modes.d.ts +2 -0
  47. package/dist/server/modes.js +5 -1
  48. package/dist/vite/build.d.ts +9 -2
  49. package/dist/vite/build.js +20 -5
  50. package/dist/vite/libraries.d.ts +32 -0
  51. package/dist/vite/libraries.js +77 -0
  52. package/dist/vite/plugin.d.ts +23 -0
  53. package/dist/vite/plugin.js +52 -24
  54. package/package.json +1 -1
@@ -1,14 +1,12 @@
1
1
  // Server-side helpers used by compiled render() functions. Runs at build time or per request, never in the browser.
2
2
  import { attrHtml, escape, HTML } from './html.js';
3
3
  import { stringify } from './serialize.js';
4
- export { escape, json, blockHtml, forHtml, regionHtml, spreadHtml } from './html.js';
5
- export { classValue, styleValue } from './attrs.js';
6
- /**
7
- * Wrap a stateful component's HTML in its island boundary: name, client chunk URL, props (`p`) and, when the
8
- * component has state, the state values it rendered with (`s`), so the browser starts from the same values.
9
- * @internal Compiled components call this; apps don't.
10
- */
4
+ export { escape, json, blockHtml, forHtml, regionHtml, spreadHtml, passedHtml } from './html.js';
5
+ export { classValue, styleValue, passed } from './attrs.js';
11
6
  export function island(name, src, props, html, state, attach, paths) {
7
+ // Slot content that awaits (#430) makes the island's HTML a promise: wrap it once it's there.
8
+ if (html instanceof Promise)
9
+ return html.then((h) => island(name, src, props, h, state, attach, paths));
12
10
  const s = state === undefined ? '' : ` s="${escape(toBrowser(state))}"`;
13
11
  const a = attach && attach !== 'load' ? ` a="${escape(attach)}"` : ''; // when to attach: see runtime/loader.ts
14
12
  // A component bound two ways carries each binding's path for the forms engine (clarusjs/forms), given by its parent.
@@ -38,6 +36,15 @@ export async function awaitHtml(promise, then, caught) {
38
36
  }
39
37
  return then ? then(value) : '';
40
38
  }
39
+ /**
40
+ * A slot's HTML (#455): its fill, a function called with what the slot passes and the context at the slot (#465), or
41
+ * the fallback when nothing fills it. A string fill (hand-built slots) is used as is. @internal
42
+ */
43
+ export function slot(fill, data, fallback, cx) {
44
+ if (fill === undefined || fill === null)
45
+ return fallback();
46
+ return typeof fill === 'function' ? fill(data ?? {}, cx) : fill;
47
+ }
41
48
  /** A child component's HTML inside an island: a promise (it awaits) is an error naming both. @internal */
42
49
  export function sync(html, child, island) {
43
50
  if (typeof html === 'string')
@@ -1,7 +1,12 @@
1
1
  import { type ModeTable } from './modes.ts';
2
2
  import { type HeadOptions, type SiteOptions } from './head.ts';
3
3
  type PageModule = {
4
- render(props?: object): string | Promise<string>;
4
+ render(props?: object, slots?: undefined, opts?: {
5
+ route: {
6
+ path: string;
7
+ params: Record<string, string>;
8
+ };
9
+ }): string | Promise<string>;
5
10
  };
6
11
  type Params = Record<string, string>;
7
12
  /**
@@ -67,6 +72,24 @@ export type LoadContext = {
67
72
  cookies: Cookies;
68
73
  locals: Locals;
69
74
  };
75
+ /**
76
+ * What a folder's `+guard.ts` gets (#457): the page's load() context plus the URL. Return a `Response` (such as
77
+ * `redirect()`) to answer instead of the page, or nothing to go on; it may set `locals` for what runs after it.
78
+ *
79
+ * ```ts
80
+ * // src/pages/admin/+guard.ts
81
+ * export function guard({ locals, url }: GuardContext) {
82
+ * if (!locals.user) return redirect('/sign-in?next=' + encodeURIComponent(url.pathname))
83
+ * }
84
+ * ```
85
+ * @see https://clarusjs.com/guide/auth
86
+ */
87
+ export type GuardContext = LoadContext & {
88
+ url: URL;
89
+ };
90
+ type GuardModule = {
91
+ guard?(context: GuardContext): Response | void | undefined | Promise<Response | void | undefined>;
92
+ };
70
93
  /**
71
94
  * `handle()` in src/server.ts: runs once per request before any page loads, to resolve the session into `locals`.
72
95
  * Returning a Response (such as `redirect('/login')`) answers the request instead.
@@ -118,11 +141,15 @@ export type EndpointModule = Partial<Record<'GET' | 'HEAD' | 'POST' | 'PUT' | 'P
118
141
  */
119
142
  export declare function redirect(to: string, status?: 301 | 302 | 303 | 307 | 308): Response;
120
143
  /** @internal clarusjs's own build and server code call this; apps don't. */
144
+ export declare function isPageFile(file: string): boolean;
145
+ /** @internal clarusjs's own build and server code call this; apps don't. */
121
146
  export declare function routeFromFile(file: string): string;
122
147
  /** @internal clarusjs's own build and server code call this; apps don't. */
123
148
  export declare function createHandler(pages: Record<string, () => Promise<PageModule>>, options?: {
124
149
  loaderUrl?: string;
125
150
  data?: Record<string, () => Promise<DataModule>>;
151
+ /** Folder guards (#457): each src/pages folder's +guard.ts → its module. */
152
+ guards?: Record<string, () => Promise<GuardModule>>;
126
153
  modes?: ModeTable;
127
154
  /** Client routes (as their files name them) → URL of the page's browser render module. */
128
155
  client?: Record<string, string>;
@@ -23,15 +23,20 @@ function compile(path) {
23
23
  export function redirect(to, status = 302) {
24
24
  return new Response(null, { status, headers: { location: to } });
25
25
  }
26
+ export function isPageFile(file) {
27
+ return !/\/\+[^/]*$/.test(file);
28
+ }
26
29
  export function routeFromFile(file) {
27
30
  const path = file.replace(/^.*?\/src\/pages/, '').replace(/\.[^./]+$/, '').replace(/\/index$/, '');
28
31
  return path || '/';
29
32
  }
30
33
  export function createHandler(pages, options = {}) {
31
34
  const routes = Object.entries(pages)
35
+ .filter(([file]) => isPageFile(file))
32
36
  .map(([file, load]) => ({ path: routeFromFile(file), file: file.replace(/^\//, ''), load, ...compile(routeFromFile(file)) }))
33
37
  .sort((a, b) => a.keys.length - b.keys.length || b.path.split('/').length - a.path.split('/').length);
34
38
  const endpointRoutes = Object.entries(options.endpoints ?? {})
39
+ .filter(([file]) => isPageFile(file))
35
40
  .map(([file, load]) => ({ path: routeFromFile(file), file: file.replace(/^\//, ''), load, ...compile(routeFromFile(file)) }))
36
41
  .sort((a, b) => a.keys.length - b.keys.length || b.path.split('/').length - a.path.split('/').length);
37
42
  const matchEndpoint = (pathname) => {
@@ -49,6 +54,26 @@ export function createHandler(pages, options = {}) {
49
54
  return undefined;
50
55
  };
51
56
  const data = options.data ?? {};
57
+ const guards = options.guards ?? {};
58
+ async function guarded(file, once, context) {
59
+ const folders = file.replace(/^\/?src\/pages\//, '').split('/').slice(0, -1);
60
+ for (let i = 0; i <= folders.length; i++) {
61
+ const key = `/src/pages/${[...folders.slice(0, i), '+guard.ts'].join('/')}`;
62
+ if (!guards[key])
63
+ continue;
64
+ try {
65
+ const mod = await guards[key]();
66
+ const route = routeFromFile(`/${file.replace(/^\//, '')}`);
67
+ const answer = await mod.guard?.({ ...context, url: new URL(context.request.url), ...(once ? builtOnce(route, context.request) : {}) });
68
+ if (answer instanceof Response)
69
+ return answer;
70
+ }
71
+ catch (err) {
72
+ throw new Error(`${key.slice(1)}: guard() failed: ${err?.message ?? err}`, { cause: err });
73
+ }
74
+ }
75
+ return undefined;
76
+ }
52
77
  const modes = options.modes ?? {};
53
78
  const loaderUrl = options.loaderUrl ?? '/cl-loader.js';
54
79
  function match(pathname) {
@@ -166,6 +191,16 @@ export function createHandler(pages, options = {}) {
166
191
  const trimmed = path.length > 1 ? path.replace(/\/+$/, '') : path;
167
192
  const found = !match(trimmed) && matchEndpoint(trimmed);
168
193
  if (found) {
194
+ try {
195
+ const stop = await guarded(found.route.file, false, { request, params: found.params, cookies, locals });
196
+ if (stop)
197
+ return stop;
198
+ }
199
+ catch (err) {
200
+ if (options.dev)
201
+ throw err;
202
+ return failure(err.message);
203
+ }
169
204
  const response = await callEndpoint(found.route.file, await found.route.load(), { request, params: found.params, cookies, locals }, options);
170
205
  if (response)
171
206
  return response;
@@ -247,6 +282,14 @@ export function createHandler(pages, options = {}) {
247
282
  }
248
283
  return new Response(head ? null : page, { headers: { 'content-type': 'text/html; charset=utf-8' } });
249
284
  }
285
+ try {
286
+ const stop = await guarded(found.route.file, modeFor(found.route.path, modes) !== 'server', { params: found.params, locals, request, cookies });
287
+ if (stop)
288
+ return stop;
289
+ }
290
+ catch (err) {
291
+ return fail(err.message, err);
292
+ }
250
293
  let props = found.route.path === '/500' ? { status: 500, ...found.params } : found.params;
251
294
  const dataFile = found.route.file.replace(/\.[^./]+$/, '.load.ts');
252
295
  const mod = data[`/${dataFile}`] ? await data[`/${dataFile}`]() : undefined;
@@ -299,7 +342,7 @@ export function createHandler(pages, options = {}) {
299
342
  let html;
300
343
  try {
301
344
  const module = await found.route.load();
302
- html = await loadedStore.run(componentData, () => module.render(props));
345
+ html = await loadedStore.run(componentData, () => module.render(props, undefined, { route: { path: pathname, params: found.params } }));
303
346
  }
304
347
  catch (err) {
305
348
  return fail(`${found.route.file}: render failed: ${err?.message ?? err}`, err);
@@ -2,5 +2,7 @@ export type Mode = 'static' | 'server' | 'client';
2
2
  export type ModeTable = Record<string, string>;
3
3
  /** Throws on an unknown mode or a malformed pattern, naming it. */
4
4
  export declare function checkModes(table: ModeTable): void;
5
+ /** A route pattern: '/about' is that route; '/docs/*' is /docs and every route under it ('/*': all). */
6
+ export declare function routeMatches(route: string, pattern: string): boolean;
5
7
  /** The mode of a route (as its file names it, e.g. '/account/[id]'): the most specific matching pattern wins. */
6
8
  export declare function modeFor(route: string, table: ModeTable): Mode;
@@ -10,11 +10,15 @@ export function checkModes(table) {
10
10
  throw new Error(`clarusjs: routes['${pattern}'] is "${mode}"; use 'static', 'server' or 'client'`);
11
11
  }
12
12
  }
13
+ export function routeMatches(route, pattern) {
14
+ const folder = pattern.endsWith('/*') ? pattern.slice(0, -2) : undefined;
15
+ return folder !== undefined ? route === (folder || '/') || route.startsWith(`${folder}/`) : route === pattern;
16
+ }
13
17
  export function modeFor(route, table) {
14
18
  let best;
15
19
  for (const [pattern, mode] of Object.entries(table)) {
16
20
  const folder = pattern.endsWith('/*') ? pattern.slice(0, -2) : undefined;
17
- const hit = folder !== undefined ? route === (folder || '/') || route.startsWith(`${folder}/`) : route === pattern;
21
+ const hit = routeMatches(route, pattern);
18
22
  const length = folder !== undefined ? folder.length : pattern.length + 0.5;
19
23
  if (hit && (!best || length > best.length))
20
24
  best = { length, mode: mode };
@@ -1,4 +1,5 @@
1
1
  import { type Alias } from './aliases.ts';
2
+ import { type ComponentNames } from '../compiler/components.ts';
2
3
  /** Absolute paths of every component file under `srcDir` (`.tscl`, or any page source extension given). */
3
4
  export declare function findClarusFiles(srcDir: string, extensions?: string[]): string[];
4
5
  /**
@@ -25,8 +26,14 @@ export declare function prerender(serverEntry: string, outDir: string, manifestF
25
26
  /** The package a file belongs to, from its last node_modules segment (pnpm: node_modules/.pnpm/x@1/node_modules/x/…). @internal */
26
27
  export declare function packageOf(file: string): string | undefined;
27
28
  /**
28
- * Component files reachable from `start` through @import lines: relative paths, root-relative ('/src/…') and package
29
+ * Where a package specifier imported by `from` leads, as Node finds it: from the importing file first (a library's own
30
+ * dependencies live in its node_modules), then from the app. Undefined when neither finds it.
31
+ * @internal The build and the plugin's page graph share it.
32
+ */
33
+ export declare function resolvePackage(root: string, from: string, spec: string): string | undefined;
34
+ /**
35
+ * Component files reachable from `start` through @import lines (and tags `names` imports automatically): relative paths, root-relative ('/src/…') and package
29
36
  * specifiers ('@clarusjs/theme-docs/layout.tscl', resolved as Node would from the app). Real paths, so a workspace
30
37
  * package linked into node_modules is one file, not two.
31
38
  */
32
- export declare function reachableComponents(root: string, start: string[], read: (file: string) => string, extensions: string[], aliases?: Alias[]): string[];
39
+ export declare function reachableComponents(root: string, start: string[], read: (file: string) => string, extensions: string[], aliases?: Alias[], names?: ComponentNames): string[];
@@ -4,6 +4,7 @@ import { readdirSync, realpathSync } from 'node:fs';
4
4
  import { createRequire } from 'node:module';
5
5
  import { dirname, resolve } from 'node:path';
6
6
  import { parse } from '../compiler/parse.js';
7
+ import { autoImport } from '../compiler/components.js';
7
8
  export function findClarusFiles(srcDir, extensions = ['.tscl']) {
8
9
  let entries;
9
10
  try {
@@ -85,8 +86,16 @@ export async function prerender(serverEntry, outDir, manifestFile, only) {
85
86
  export function packageOf(file) {
86
87
  return /.*[\\/]node_modules[\\/]((?:@[^\\/]+[\\/])?[^\\/]+)[\\/]/.exec(file)?.[1].replace(/\\/g, '/');
87
88
  }
88
- export function reachableComponents(root, start, read, extensions, aliases = []) {
89
- const require = createRequire(resolve(root, 'package.json'));
89
+ export function resolvePackage(root, from, spec) {
90
+ for (const origin of [from, resolve(root, 'package.json')]) {
91
+ try {
92
+ return createRequire(origin).resolve(spec);
93
+ }
94
+ catch { }
95
+ }
96
+ return undefined;
97
+ }
98
+ export function reachableComponents(root, start, read, extensions, aliases = [], names) {
90
99
  const seen = new Set();
91
100
  const queue = start.map((f) => realpathSync(f));
92
101
  while (queue.length) {
@@ -96,7 +105,11 @@ export function reachableComponents(root, start, read, extensions, aliases = [])
96
105
  seen.add(file);
97
106
  let imports;
98
107
  try {
99
- imports = parse(read(file), file).imports;
108
+ const text = read(file);
109
+ const parsed = parse(text, file);
110
+ if (names)
111
+ autoImport(parsed, names, file, text);
112
+ imports = parsed.imports;
100
113
  }
101
114
  catch {
102
115
  continue;
@@ -107,8 +120,10 @@ export function reachableComponents(root, start, read, extensions, aliases = [])
107
120
  continue;
108
121
  let target;
109
122
  try {
110
- target = spec.startsWith('.') ? resolve(dirname(file), spec) : spec.startsWith('/') ? resolve(root, spec.slice(1)) : resolveAlias(spec, aliases) ?? require.resolve(spec);
111
- target = realpathSync(target);
123
+ const found = spec.startsWith('.') ? resolve(dirname(file), spec) : spec.startsWith('/') ? resolve(root, spec.slice(1)) : resolveAlias(spec, aliases) ?? resolvePackage(root, file, spec);
124
+ if (!found)
125
+ continue;
126
+ target = realpathSync(found);
112
127
  }
113
128
  catch {
114
129
  continue;
@@ -0,0 +1,32 @@
1
+ import { type ComponentNames, type Library } from '../compiler/components.ts';
2
+ /**
3
+ * A library the app uses: its package name, or the name with the tag prefix the app wants instead of the library's.
4
+ * @since 0.16.0
5
+ * @see https://clarusjs.com/guide/components#components-from-libraries
6
+ */
7
+ export type LibraryOption = string | {
8
+ from: string;
9
+ prefix?: string;
10
+ };
11
+ /** Each listed library, resolved: its components folder's `.tscl` files and its prefix. */
12
+ export declare function resolveLibraries(root: string, list: LibraryOption[]): Library[];
13
+ /**
14
+ * Every component name the app's templates may use without an @import: its own (`dirs`), then its libraries'. The
15
+ * folders and the libraries' names, none shadowed, go to .clarusjs/components.json for the editor, which lays the
16
+ * app's own (read live) over them; none when automatic imports are off. Undefined then.
17
+ */
18
+ export declare function componentNames(root: string, options?: {
19
+ dirs?: string[];
20
+ auto?: boolean;
21
+ libraries?: LibraryOption[];
22
+ }): ComponentNames | undefined;
23
+ /**
24
+ * The folders and libraries' names the plugin or `clarusjs check` last wrote for this app, if either has run. Written by a tool,
25
+ * but it may be stale or hand-edited: an entry that isn't a path (or several) is dropped, the rest kept.
26
+ */
27
+ export declare function readComponents(root: string): {
28
+ dirs?: string[];
29
+ names: ComponentNames;
30
+ } | undefined;
31
+ /** The libraries' names the plugin or `clarusjs check` last wrote for this app, if either has run. */
32
+ export declare function readComponentNames(root: string): ComponentNames | undefined;
@@ -0,0 +1,77 @@
1
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { dirname, relative, resolve, sep } from 'node:path';
4
+ import { COMPONENT_DIRS, componentIndex, libraryNames, withLibraries } from '../compiler/components.js';
5
+ import { findClarusFiles } from './build.js';
6
+ const posix = (path) => path.split(sep).join('/');
7
+ function packageDir(root, name) {
8
+ for (let dir = resolve(root);; dir = dirname(dir)) {
9
+ const candidate = resolve(dir, 'node_modules', name);
10
+ if (existsSync(resolve(candidate, 'package.json')))
11
+ return candidate;
12
+ if (dirname(dir) === dir)
13
+ return undefined;
14
+ }
15
+ }
16
+ export function resolveLibraries(root, list) {
17
+ return list.map((option) => {
18
+ const name = typeof option === 'string' ? option : option.from;
19
+ const dir = packageDir(root, name);
20
+ if (!dir)
21
+ throw new Error(`[clarusjs] the component library "${name}" isn't installed: add it to your dependencies, or remove it from components.libraries`);
22
+ const meta = JSON.parse(readFileSync(resolve(dir, 'package.json'), 'utf8')).clarusjs;
23
+ if (typeof meta?.components !== 'string') {
24
+ throw new Error(`[clarusjs] "${name}" doesn't describe its components: its package.json needs "clarusjs": { "components": "./src", "prefix": "ui" }`);
25
+ }
26
+ const base = resolve(dir, meta.components);
27
+ const files = findClarusFiles(base, ['.tscl']).map((f) => posix(relative(base, f))).sort();
28
+ const prefix = typeof option === 'object' && option.prefix !== undefined ? option.prefix : (meta.prefix ?? '');
29
+ if (prefix && !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(prefix))
30
+ throw new Error(`[clarusjs] the prefix "${prefix}" of "${name}" isn't kebab-case (lowercase letters, digits and hyphens): its tags couldn't be named`);
31
+ const require = createRequire(resolve(root, 'package.json'));
32
+ for (const file of files) {
33
+ const spec = `${name}/${file}`;
34
+ let found;
35
+ try {
36
+ found = realpathSync(require.resolve(spec));
37
+ }
38
+ catch { }
39
+ if (found !== realpathSync(resolve(base, file))) {
40
+ throw new Error(`[clarusjs] "${spec}" doesn't resolve to ${posix(relative(root, resolve(base, file)))}: the library's package.json exports must map its components with a plain path or a "default" condition, not "import" alone, for example "exports": { "./*": "${meta.components.replace(/\/?$/, '/')}*" }`);
41
+ }
42
+ }
43
+ return { name, prefix, files };
44
+ });
45
+ }
46
+ export function componentNames(root, options = {}) {
47
+ const dirs = options.auto === false ? [] : (options.dirs ?? COMPONENT_DIRS);
48
+ const own = componentIndex(findClarusFiles(resolve(root, 'src'), ['.tscl']).map((f) => posix(relative(root, f))), dirs).names;
49
+ const libraries = options.auto === false ? {} : libraryNames(resolveLibraries(root, options.libraries ?? []));
50
+ const file = resolve(root, '.clarusjs/components.json');
51
+ const text = `${JSON.stringify({ dirs, names: libraries }, null, 2)}\n`;
52
+ if (!existsSync(file) || readFileSync(file, 'utf8') !== text) {
53
+ mkdirSync(dirname(file), { recursive: true });
54
+ const temp = `${file}.${process.pid}.tmp`;
55
+ writeFileSync(temp, text);
56
+ renameSync(temp, file);
57
+ }
58
+ return options.auto === false ? undefined : withLibraries(own, libraries);
59
+ }
60
+ export function readComponents(root) {
61
+ let written;
62
+ try {
63
+ written = JSON.parse(readFileSync(resolve(root, '.clarusjs/components.json'), 'utf8'));
64
+ }
65
+ catch {
66
+ return undefined;
67
+ }
68
+ if (!written?.names || typeof written.names !== 'object')
69
+ return undefined;
70
+ const path = (v) => typeof v === 'string' || (Array.isArray(v) && v.length > 0 && v.every((p) => typeof p === 'string'));
71
+ const names = Object.fromEntries(Object.entries(written.names).filter(([, v]) => path(v)));
72
+ const dirs = Array.isArray(written.dirs) && written.dirs.every((d) => typeof d === 'string') ? written.dirs : undefined;
73
+ return dirs ? { dirs, names } : { names };
74
+ }
75
+ export function readComponentNames(root) {
76
+ return readComponents(root)?.names;
77
+ }
@@ -1,4 +1,5 @@
1
1
  import { type Plugin } from 'vite';
2
+ import { type LibraryOption } from './libraries.ts';
2
3
  import type { LintConfig, LintRuleDef } from '../compiler/lint.ts';
3
4
  export { packageOf } from './build.ts';
4
5
  /** Newest commit time (unix seconds) of every file under a folder, from one `git log` (themes use it for "last updated"). */
@@ -18,6 +19,28 @@ export declare function clientUrlFor(root: string, file: string, path?: Pick<typ
18
19
  export type ClarusOptions = {
19
20
  /** When each route renders: { '/account/*': 'server' }. Routes default to 'static' (prerendered at build). */
20
21
  routes?: ModeTable;
22
+ /**
23
+ * Layouts by route (#456), outermost first, around the folder layouts (`+layout.tscl`): `{ layout: '/src/layouts/site.tscl',
24
+ * include: ['/*'], exclude: ['/embed/*'] }` (patterns as in `routes`; include defaults to every route). A page with
25
+ * `@layout none` gets none.
26
+ */
27
+ layouts?: {
28
+ layout: string;
29
+ include?: string[];
30
+ exclude?: string[];
31
+ }[];
32
+ /**
33
+ * Automatic component imports (#458): a kebab-case file under these folders is used by its name, without @import
34
+ * (`src/components/forms/text-field.tscl` → `<forms-text-field>`, or `<text-field>` when no other has that name).
35
+ * Defaults: `{ dirs: ['src/components', 'src/layouts'], auto: true }`. `libraries`: installed component libraries whose
36
+ * components are used the same way (`libraries: ['@clarusjs/ui-primitives']` → `<ui-dialog>`), each described by its
37
+ * package.json; your own components win over theirs.
38
+ */
39
+ components?: {
40
+ dirs?: string[];
41
+ auto?: boolean;
42
+ libraries?: LibraryOption[];
43
+ };
21
44
  /** Where server routes deploy. 'netlify': a Netlify Function (Frameworks API) next to the static files. */
22
45
  adapter?: 'netlify';
23
46
  /** Fragment navigation: each static and server page also answers at <path>/index.frag.html. */
@@ -17,13 +17,14 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
17
17
  };
18
18
  import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, watch as watchFs, writeFileSync } from 'node:fs';
19
19
  import { brotliCompressSync, constants as zlibConstants, gzipSync } from 'node:zlib';
20
- import { createRequire } from 'node:module';
21
20
  import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
22
21
  import { fileURLToPath, pathToFileURL } from 'node:url';
23
22
  import { isRunnableDevEnvironment, normalizePath } from 'vite';
24
23
  import { compile, scopeId, ClarusError } from '../compiler/index.js';
25
24
  import { parse } from '../compiler/parse.js';
26
- import { findClarusFiles, packageOf as packageOfFile, prerender, reachableComponents, routeToFile } from './build.js';
25
+ import { autoImport, COMPONENT_DIRS, componentIndex } from '../compiler/components.js';
26
+ import { componentNames } from './libraries.js';
27
+ import { findClarusFiles, packageOf as packageOfFile, prerender, reachableComponents, resolvePackage, routeToFile } from './build.js';
27
28
  export { packageOf } from './build.js';
28
29
  export { gitDates } from './sitemap.js';
29
30
  import { writeManifest } from './manifest.js';
@@ -32,8 +33,8 @@ import { checkLinks } from './links.js';
32
33
  import { checkRedirects, redirectFor, writeRedirects } from './redirects.js';
33
34
  import { projectAliases, resolveAlias } from './aliases.js';
34
35
  import { gitDates, sitemapFiles } from './sitemap.js';
35
- import { checkModes, modeFor } from '../server/modes.js';
36
- import { rootLinks, routeFromFile } from '../server/handler.js';
36
+ import { checkModes, modeFor, routeMatches } from '../server/modes.js';
37
+ import { isPageFile, rootLinks, routeFromFile } from '../server/handler.js';
37
38
  import { basePath } from '../server/head.js';
38
39
  import { acceptsEncoding, sendResponse, toRequest } from './node.js';
39
40
  import { resolveIcon } from '../icons.js';
@@ -64,18 +65,15 @@ const STYLES_FILE = '.clarusjs/styles.css';
64
65
  const scopeFor = (root, file) => scopeId(relative(root, file).split(sep).join('/'));
65
66
  function pageGraph(root, files, aliases = []) {
66
67
  const deps = new Map();
67
- const require = createRequire(resolve(root, 'package.json'));
68
- const packageFile = (spec) => { try {
69
- return realpathSync(require.resolve(spec.replace(/\?.*$/, '')));
70
- }
71
- catch {
72
- return undefined;
73
- } };
68
+ const names = files.names(root);
74
69
  const read = (file) => {
75
70
  if (!deps.has(file)) {
76
71
  let parsed;
77
72
  try {
78
- parsed = parse(files.read(file, root), file);
73
+ const text = files.read(file, root);
74
+ parsed = parse(text, file);
75
+ if (names)
76
+ autoImport(parsed, names, file, text);
79
77
  }
80
78
  catch {
81
79
  parsed = null;
@@ -84,7 +82,8 @@ function pageGraph(root, files, aliases = []) {
84
82
  const path = from.replace(/\?.*$/, '');
85
83
  return path.startsWith('/') ? resolve(root, `.${path}`) : resolve(dirname(file), path);
86
84
  };
87
- const bare = (from) => resolveAlias(from.replace(/\?.*$/, ''), aliases) ?? packageFile(from);
85
+ const packageFile = (spec) => { const found = resolvePackage(root, file, spec); return found && realpathSync(found); };
86
+ const bare = (from) => resolveAlias(from.replace(/\?.*$/, ''), aliases) ?? packageFile(from.replace(/\?.*$/, ''));
88
87
  deps.set(file, {
89
88
  css: parsed?.cssImports.map((c) => (/^[./]/.test(c.from) ? near(c.from) : bare(c.from))).filter((f) => !!f) ?? [],
90
89
  components: parsed?.imports.map((imp) => (/^[./]/.test(imp.from) ? near(imp.from) : bare(imp.from))).filter((f) => !!f) ?? [],
@@ -105,7 +104,7 @@ function pageGraph(root, files, aliases = []) {
105
104
  out.push(sheet);
106
105
  };
107
106
  const pages = new Map();
108
- for (const file of files.find(resolve(root, 'src/pages'))) {
107
+ for (const file of files.pages(root)) {
109
108
  const css = [];
110
109
  const seen = new Set();
111
110
  collect(file, css, seen);
@@ -114,6 +113,23 @@ function pageGraph(root, files, aliases = []) {
114
113
  }
115
114
  return pages;
116
115
  }
116
+ function layoutsFor(root, file, config) {
117
+ const pages = resolve(root, 'src/pages');
118
+ const rel = relative(pages, file);
119
+ if (rel.startsWith('..') || isAbsolute(rel) || !isPageFile(file.split(sep).join('/')))
120
+ return undefined;
121
+ const route = routeFromFile(`/src/pages/${rel.split(sep).join('/')}`);
122
+ const out = config
123
+ .filter((l) => (l.include ?? ['/*']).some((p) => routeMatches(route, p)) && !(l.exclude ?? []).some((p) => routeMatches(route, p)))
124
+ .map((l) => l.layout);
125
+ const folders = dirname(rel) === '.' ? [] : dirname(rel).split(sep);
126
+ for (let i = 0; i <= folders.length; i++) {
127
+ const layout = resolve(pages, ...folders.slice(0, i), '+layout.tscl');
128
+ if (existsSync(layout))
129
+ out.push(`/${relative(root, layout).split(sep).join('/')}`);
130
+ }
131
+ return out;
132
+ }
117
133
  function componentLoaderOf(root, file) {
118
134
  if (!file.endsWith('.tscl') || real(file).startsWith(real(resolve(root, 'src/pages')) + sep))
119
135
  return undefined;
@@ -126,7 +142,7 @@ function writeStyles(root, files) {
126
142
  const outDir = resolve(root, '.clarusjs');
127
143
  for (const file of files.components(root)) {
128
144
  try {
129
- let out = compile(files.read(file, root), { file, target: 'client', scope: scopeFor(root, file), icon: iconsFor(file) }).css;
145
+ let out = compile(files.read(file, root), { file, target: 'client', scope: scopeFor(root, file), icon: iconsFor(file), layouts: files.layouts(file, root), components: files.names(root) }).css;
130
146
  out = out.replace(/^(?:[ \t]*@(?:reference|import)\b[^;{]*;[ \t]*\n?)+/, (statements) => {
131
147
  for (const statement of statements.split(';').map((x) => x.trim()).filter(Boolean)) {
132
148
  head.add(statement.replace(/(["'])(\.{1,2}\/[^"']*)\1/, (_, q, spec) => {
@@ -153,7 +169,7 @@ const SERVER_OUT = 'dist/server';
153
169
  const entryName = (root, file) => relative(root, file).split(sep).join('/').replace(/\.[^./\\]+$/, '').replace(/^(\.\.\/)+/, (ups) => '_/'.repeat(ups.length / 3));
154
170
  function clientPages(appRoot, modes, files) {
155
171
  const pages = new Map();
156
- for (const file of files.find(resolve(appRoot, 'src/pages'))) {
172
+ for (const file of files.pages(appRoot)) {
157
173
  const route = routeFromFile(`/${relative(appRoot, file).split(sep).join('/')}`);
158
174
  if (modeFor(route, modes) === 'client')
159
175
  pages.set(route, file);
@@ -195,7 +211,10 @@ export default function clarusjs(options = {}) {
195
211
  let extra = () => [];
196
212
  const files = {
197
213
  find: (dir) => findClarusFiles(dir, extensions).filter((f) => f.endsWith('.tscl') || f.includes(`${sep}src${sep}pages${sep}`)),
198
- components: (appRoot) => reachableComponents(appRoot, [...files.find(resolve(appRoot, 'src')), ...extra(appRoot).filter((f) => existsSync(f))], (file) => files.read(file, appRoot), extensions, aliases),
214
+ pages: (root) => files.find(resolve(root, 'src/pages')).filter((f) => isPageFile(f.split(sep).join('/'))),
215
+ layouts: (file, root) => layoutsFor(root, file, options.layouts ?? []),
216
+ names: (root) => componentNames(root, options.components),
217
+ components: (appRoot) => reachableComponents(appRoot, [...files.find(resolve(appRoot, 'src')), ...extra(appRoot).filter((f) => existsSync(f))], (file) => files.read(file, appRoot), extensions, aliases, files.names(appRoot)),
199
218
  read: (file, appRoot) => {
200
219
  const code = readFileSync(file, 'utf8');
201
220
  const src = sources.find((x) => file.endsWith(x.extension));
@@ -238,7 +257,7 @@ export default function clarusjs(options = {}) {
238
257
  };
239
258
  return {
240
259
  name: 'clarusjs',
241
- api: { sources, lint: options.lint, lintRules: options.lintRules },
260
+ api: { sources, lint: options.lint, lintRules: options.lintRules, components: options.components },
242
261
  config(userConfig, env) {
243
262
  extra = (appRoot) => pluginsOf(userConfig.plugins).flatMap((p) => p.api?.clarusComponents?.(appRoot) ?? []);
244
263
  const projectRoot = resolve(userConfig.root ?? process.cwd());
@@ -276,7 +295,7 @@ export default function clarusjs(options = {}) {
276
295
  const input = { [LOADER_ENTRY]: here('../runtime/loader') };
277
296
  const components = files.components(appRoot);
278
297
  for (const file of components) {
279
- if (compile(files.read(file, appRoot), { file, target: 'client', icon: iconsFor(file) }).stateful)
298
+ if (compile(files.read(file, appRoot), { file, target: 'client', icon: iconsFor(file), layouts: files.layouts(file, appRoot), components: files.names(appRoot) }).stateful)
280
299
  input[entryName(appRoot, file)] = file;
281
300
  }
282
301
  const client = clientPages(appRoot, modes, files);
@@ -327,6 +346,13 @@ export default function clarusjs(options = {}) {
327
346
  root = config.root;
328
347
  command = config.command;
329
348
  base = config.base;
349
+ if (options.components?.auto !== false) {
350
+ const found = findClarusFiles(resolve(root, 'src'), ['.tscl']).map((f) => relative(root, f).split(sep).join('/'));
351
+ for (const file of componentIndex(found, options.components?.dirs ?? COMPONENT_DIRS).skipped) {
352
+ config.logger.warn(`clarusjs: ${file} isn't imported automatically: its name isn't kebab-case (rename it, or @import it)`);
353
+ }
354
+ }
355
+ componentNames(root, options.components);
330
356
  },
331
357
  async buildApp(builder) {
332
358
  const { client, ssr } = builder.environments;
@@ -336,7 +362,7 @@ export default function clarusjs(options = {}) {
336
362
  if (watching)
337
363
  client.config.build.watch = ssr.config.build.watch = null;
338
364
  const once = async () => {
339
- checkRedirects(options.redirects ?? {}, files.find(resolve(builder.config.root, 'src/pages')).map((f) => routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`)));
365
+ checkRedirects(options.redirects ?? {}, files.pages(builder.config.root).map((f) => routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`)));
340
366
  await builder.build(client);
341
367
  await builder.build(ssr);
342
368
  const entry = resolve(builder.config.root, SERVER_OUT, 'index.mjs');
@@ -399,7 +425,7 @@ export default function clarusjs(options = {}) {
399
425
  site: options.site?.url,
400
426
  });
401
427
  const levels = { pages: options.links?.pages ?? 'error', anchors: options.links?.anchors ?? 'warn' };
402
- const sourceOf = new Map(files.find(resolve(builder.config.root, 'src/pages')).map((f) => [routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`), f]));
428
+ const sourceOf = new Map(files.pages(builder.config.root).map((f) => [routeFromFile(`/${relative(builder.config.root, f).split(sep).join('/')}`), f]));
403
429
  const pattern = (route) => new RegExp(`^${route.split('/').map((seg) => (/^\[[^\]]+\]$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('/')}$`);
404
430
  const fileOf = (page) => sourceOf.get(page) ?? [...sourceOf].find(([route]) => pattern(route).test(page))?.[1];
405
431
  const locate = (page, href) => {
@@ -543,7 +569,8 @@ export default function clarusjs(options = {}) {
543
569
  ` data: import.meta.glob('/src/pages/**/*.load.ts'),\n` +
544
570
  ` componentLoaders: ${JSON.stringify(componentLoaders)},\n` +
545
571
  ` componentData: import.meta.glob(['/src/**/*.load.ts', '!/src/pages/**']),\n` +
546
- ` endpoints: import.meta.glob(['/src/pages/**/*.ts', '!/src/pages/**/*.load.ts', '!/src/pages/**/*.d.ts']),\n` +
572
+ ` guards: import.meta.glob('/src/pages/**/+guard.ts'),\n` +
573
+ ` endpoints: import.meta.glob(['/src/pages/**/*.ts', '!/src/pages/**/*.load.ts', '!/src/pages/**/*.d.ts', '!/src/pages/**/+*']),\n` +
547
574
  ` modes: ${JSON.stringify(modes)},\n` +
548
575
  ` routerUrl: ${JSON.stringify(routerUrl)},\n` +
549
576
  ` client: ${JSON.stringify(client)},\n` +
@@ -578,7 +605,7 @@ export default function clarusjs(options = {}) {
578
605
  const clientUrl = urls
579
606
  ? urls.get(entryName(root, file)) ?? urls.get(relative(root, file).split(sep).join('/')) ?? urls.get(real(file))
580
607
  : command === 'build' ? `${CHUNK_TOKEN}[${entryName(root, file)}]__` : clientUrlFor(root, file);
581
- if (urls && !clientUrl && compile(code, { file, target: 'client', icon: iconsFor(file) }).stateful) {
608
+ if (urls && !clientUrl && compile(code, { file, target: 'client', icon: iconsFor(file), layouts: files.layouts(file, root), components: files.names(root) }).stateful) {
582
609
  this.error(`${file}: stateful component is not under src/, so it has no client chunk`);
583
610
  }
584
611
  let parsed;
@@ -602,7 +629,8 @@ export default function clarusjs(options = {}) {
602
629
  const collapseWhitespace = command === 'build' && options.collapseWhitespace !== false;
603
630
  const loader = componentLoaderOf(root, file) ? relative(root, file).split(sep).join('/') : undefined;
604
631
  const hot = command === 'serve' && target === 'client' ? '/cl-hot.js' : undefined;
605
- const out = compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file), collapseWhitespace, loader, hot, icon: iconsFor(file) });
632
+ const layouts = files.layouts(file, root);
633
+ const out = compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file), collapseWhitespace, loader, hot, icon: iconsFor(file), layouts, components: files.names(root) });
606
634
  if (consumer === 'server' && !renderQuery)
607
635
  for (const w of out.warnings)
608
636
  this.warn(w.message);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clarusjs",
3
- "version": "0.14.0",
3
+ "version": "0.16.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": [