clarusjs 0.9.0 → 0.11.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.js +15 -8
  2. package/dist/cli/check.d.ts +7 -0
  3. package/dist/cli/check.js +14 -6
  4. package/dist/cli/explain.js +1 -1
  5. package/dist/cli/index.js +6 -3
  6. package/dist/cli/project.d.ts +7 -2
  7. package/dist/cli/project.js +4 -3
  8. package/dist/compiler/emit-client.d.ts +2 -1
  9. package/dist/compiler/emit-client.js +19 -7
  10. package/dist/compiler/emit-server.d.ts +1 -1
  11. package/dist/compiler/emit-server.js +4 -1
  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 +24 -1
  15. package/dist/compiler/index.d.ts +23 -2
  16. package/dist/compiler/index.js +5 -3
  17. package/dist/compiler/ir.d.ts +6 -1
  18. package/dist/compiler/ir.js +104 -4
  19. package/dist/compiler/lint.d.ts +82 -0
  20. package/dist/compiler/lint.js +177 -0
  21. package/dist/compiler/parse.d.ts +34 -0
  22. package/dist/compiler/parse.js +11 -0
  23. package/dist/compiler/script.js +27 -0
  24. package/dist/fetch/index.d.ts +149 -0
  25. package/dist/fetch/index.js +312 -0
  26. package/dist/forms/index.d.ts +21 -2
  27. package/dist/forms/types.d.ts +20 -3
  28. package/dist/runtime/attrs.js +10 -2
  29. package/dist/runtime/dom.d.ts +15 -7
  30. package/dist/runtime/dom.js +33 -13
  31. package/dist/runtime/env.d.ts +8 -1
  32. package/dist/runtime/env.js +8 -1
  33. package/dist/runtime/hot.d.ts +2 -0
  34. package/dist/runtime/hot.js +51 -0
  35. package/dist/runtime/html.d.ts +9 -7
  36. package/dist/runtime/html.js +12 -7
  37. package/dist/runtime/navigate.d.ts +5 -0
  38. package/dist/runtime/navigation.d.ts +85 -13
  39. package/dist/runtime/navigation.js +77 -11
  40. package/dist/runtime/serialize.d.ts +1 -1
  41. package/dist/runtime/serialize.js +1 -1
  42. package/dist/runtime/server.d.ts +18 -1
  43. package/dist/runtime/server.js +42 -4
  44. package/dist/runtime/signals.d.ts +97 -4
  45. package/dist/runtime/signals.js +88 -4
  46. package/dist/server/handler.d.ts +115 -5
  47. package/dist/server/handler.js +233 -10
  48. package/dist/server/head.d.ts +4 -1
  49. package/dist/server/manifest.d.ts +14 -1
  50. package/dist/server/views.d.ts +64 -6
  51. package/dist/server/views.js +46 -0
  52. package/dist/vite/aliases.js +3 -3
  53. package/dist/vite/build.d.ts +2 -1
  54. package/dist/vite/build.js +1 -1
  55. package/dist/vite/manifest.d.ts +15 -0
  56. package/dist/vite/manifest.js +2 -2
  57. package/dist/vite/node.js +4 -1
  58. package/dist/vite/plugin.d.ts +47 -3
  59. package/dist/vite/plugin.js +197 -106
  60. package/dist/vite/sitemap.d.ts +1 -0
  61. package/package.json +5 -1
@@ -10,19 +10,116 @@ type Params = Record<string, string>;
10
10
  */
11
11
  type DataModule = {
12
12
  entries?(): Params[] | Promise<Params[]>;
13
- load?(context: {
14
- params: Params;
15
- request: Request;
16
- }): object | Promise<object>;
13
+ load?(context: LoadContext): object | Promise<object>;
17
14
  };
15
+ /**
16
+ * Data a request carries from `handle()` (src/server.ts) to every `load()`, such as the signed-in user. Declare what
17
+ * it holds once, and every loader is checked against it:
18
+ * @example
19
+ * ```ts
20
+ * // src/server.ts
21
+ * declare module 'clarusjs/server' {
22
+ * interface Locals { user?: { id: string; name: string } }
23
+ * }
24
+ * ```
25
+ * @see https://clarusjs.com/reference/server#locals
26
+ */
27
+ export interface Locals {
28
+ }
29
+ /**
30
+ * Options for `cookies.set()`. Defaults: `path: '/'`, `httpOnly: true`, `sameSite: 'lax'`, and `secure: true` except
31
+ * in the Vite dev server (so development over plain http works everywhere).
32
+ * @see https://clarusjs.com/reference/server#cookies
33
+ */
34
+ export type CookieOptions = {
35
+ path?: string;
36
+ domain?: string;
37
+ maxAge?: number;
38
+ expires?: Date;
39
+ httpOnly?: boolean;
40
+ secure?: boolean;
41
+ sameSite?: 'lax' | 'strict' | 'none';
42
+ };
43
+ /**
44
+ * A request's cookies: read from its `Cookie` header; what's set or deleted goes on the answer as `Set-Cookie`.
45
+ * @example
46
+ * ```ts
47
+ * export function load({ cookies }: LoadContext) {
48
+ * cookies.set('visited', 'yes', { maxAge: 60 * 60 * 24 })
49
+ * return { theme: cookies.get('theme') ?? 'light' }
50
+ * }
51
+ * ```
52
+ * @see https://clarusjs.com/reference/server#cookies
53
+ */
54
+ export type Cookies = {
55
+ get(name: string): string | undefined;
56
+ getAll(): Record<string, string>;
57
+ set(name: string, value: string, options?: CookieOptions): void;
58
+ delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): void;
59
+ };
60
+ /**
61
+ * What a page's `load()` gets: its route params, the request, its cookies and the locals `handle()` filled.
62
+ * @see https://clarusjs.com/reference/server#loadcontext
63
+ */
64
+ export type LoadContext = {
65
+ params: Params;
66
+ request: Request;
67
+ cookies: Cookies;
68
+ locals: Locals;
69
+ };
70
+ /**
71
+ * `handle()` in src/server.ts: runs once per request before any page loads, to resolve the session into `locals`.
72
+ * Returning a Response (such as `redirect('/login')`) answers the request instead.
73
+ * @example
74
+ * ```ts
75
+ * // src/server.ts
76
+ * import type { Handle } from 'clarusjs/server'
77
+ * export const handle: Handle = async ({ cookies, locals }) => {
78
+ * const id = cookies.get('session')
79
+ * if (id) locals.user = await sessions.get(id)
80
+ * }
81
+ * ```
82
+ * @see https://clarusjs.com/reference/server#handle
83
+ */
84
+ export type Handle = (context: {
85
+ request: Request;
86
+ cookies: Cookies;
87
+ locals: Locals;
88
+ }) => void | Response | Promise<void | Response>;
89
+ /**
90
+ * An endpoint's handler (`export function GET(…)` in src/pages/api/items.ts): the request, its route params, cookies
91
+ * and locals; returns the Response.
92
+ * @example
93
+ * ```ts
94
+ * // src/pages/api/items.ts
95
+ * import type { RequestHandler } from 'clarusjs/server'
96
+ * export const GET: RequestHandler = ({ locals }) => Response.json(listItemsFor(locals.user))
97
+ * export const POST: RequestHandler = async ({ request }) => Response.json(await save(await request.json()), { status: 201 })
98
+ * ```
99
+ * @see https://clarusjs.com/reference/server#endpoints
100
+ */
101
+ export type RequestHandler = (context: LoadContext) => Response | Promise<Response>;
102
+ /** An endpoint module: one handler per HTTP method it answers. @internal */
103
+ export type EndpointModule = Partial<Record<'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS', RequestHandler>>;
18
104
  /** '/src/pages/index.tscl' → '/', '/src/pages/blog/index.tscl' → '/blog', '/src/pages/about.md' → '/about' (any page source) */
19
105
  /**
20
106
  * A redirect for a server page's `load()` to return: `return redirect('/login')`. 302 by default; 301 or 308 for
21
107
  * a page that moved for good, 303 after a form, 307 to keep the method.
22
- * @see https://clarusjs.com/guide/routing
108
+ * @example
109
+ * ```ts
110
+ * // src/pages/account.load.ts (a server route)
111
+ * export async function load({ request }: { request: Request }) {
112
+ * const user = await userFrom(request)
113
+ * if (!user) return redirect('/login')
114
+ * return { user }
115
+ * }
116
+ * ```
117
+ * @see https://clarusjs.com/reference/server#redirect
23
118
  */
24
119
  export declare function redirect(to: string, status?: 301 | 302 | 303 | 307 | 308): Response;
120
+ /** @internal clarusjs's own build and server code call this; apps don't. */
25
121
  export declare function routeFromFile(file: string): string;
122
+ /** @internal clarusjs's own build and server code call this; apps don't. */
26
123
  export declare function createHandler(pages: Record<string, () => Promise<PageModule>>, options?: {
27
124
  loaderUrl?: string;
28
125
  data?: Record<string, () => Promise<DataModule>>;
@@ -46,22 +143,35 @@ export declare function createHandler(pages: Record<string, () => Promise<PageMo
46
143
  site?: SiteOptions;
47
144
  /** Development: a failing page throws its error (the dev server shows it with its stack) instead of answering 500. */
48
145
  dev?: boolean;
146
+ /** src/server.ts: its `handle()` runs once per request, before any page loads. */
147
+ hooks?: {
148
+ handle?: Handle;
149
+ };
150
+ /** Component loaders (#97): each route's (as its file names it) loader files, by Vite path ('/src/x.load.ts'). */
151
+ componentLoaders?: Record<string, string[]>;
152
+ /** The component loader modules, by Vite path. */
153
+ componentData?: Record<string, () => Promise<DataModule>>;
154
+ /** Endpoints: .ts files under src/pages (not .load.ts) exporting GET, POST, … handlers. */
155
+ endpoints?: Record<string, () => Promise<EndpointModule>>;
49
156
  }): {
50
157
  fetch(request: Request): Promise<Response>;
51
158
  routes: string[];
52
159
  serverRoutes: string[];
53
160
  paths(): Promise<string[]>;
54
161
  hasLoader(route: string): Promise<boolean>;
162
+ readsCookies(route: string): Promise<boolean>;
55
163
  isServerPath(pathname: string): boolean;
56
164
  };
57
165
  /**
58
166
  * A page's fragment: its <title>, then the element marked data-cl-swap (the region fragment navigation replaces), or
59
167
  * its <body> when nothing is marked. Comments are ignored when looking; nested tags of the same name are balanced.
168
+ * @internal clarusjs's own build and server code call this; apps don't.
60
169
  */
61
170
  export declare function toFragment(html: string): string;
62
171
  /**
63
172
  * The 404 page is served at any depth (/a/b/c), so its relative links (href, src) are resolved from the site root:
64
173
  * 'guide' means <base>guide wherever the visitor is.
174
+ * @internal clarusjs's own build and server code call this; apps don't.
65
175
  */
66
176
  export declare function rootLinks(html: string, base: string): string;
67
177
  export {};
@@ -1,5 +1,5 @@
1
1
  import { modeFor } from './modes.js';
2
- import { stringify } from '../runtime/serialize.js';
2
+ import { toBrowser, withLoaded } 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';
@@ -28,6 +28,23 @@ export function createHandler(pages, options = {}) {
28
28
  const routes = Object.entries(pages)
29
29
  .map(([file, load]) => ({ path: routeFromFile(file), file: file.replace(/^\//, ''), load, ...compile(routeFromFile(file)) }))
30
30
  .sort((a, b) => a.keys.length - b.keys.length || b.path.split('/').length - a.path.split('/').length);
31
+ const endpointRoutes = Object.entries(options.endpoints ?? {})
32
+ .map(([file, load]) => ({ path: routeFromFile(file), file: file.replace(/^\//, ''), load, ...compile(routeFromFile(file)) }))
33
+ .sort((a, b) => a.keys.length - b.keys.length || b.path.split('/').length - a.path.split('/').length);
34
+ const matchEndpoint = (pathname) => {
35
+ for (const route of endpointRoutes) {
36
+ const m = route.regex.exec(pathname);
37
+ if (!m)
38
+ continue;
39
+ try {
40
+ return { route, params: Object.fromEntries(route.keys.map((k, i) => [k, decodeURIComponent(m[i + 1])])) };
41
+ }
42
+ catch {
43
+ return undefined;
44
+ }
45
+ }
46
+ return undefined;
47
+ };
31
48
  const data = options.data ?? {};
32
49
  const modes = options.modes ?? {};
33
50
  const loaderUrl = options.loaderUrl ?? '/cl-loader.js';
@@ -66,12 +83,18 @@ export function createHandler(pages, options = {}) {
66
83
  }
67
84
  const handler = {
68
85
  routes: routes.map((r) => r.path).sort(),
69
- serverRoutes: routes.filter((r) => modeFor(r.path, modes) === 'server').map((r) => r.path).sort(),
86
+ serverRoutes: [...routes.filter((r) => modeFor(r.path, modes) === 'server').map((r) => r.path), ...endpointRoutes.map((r) => r.path)].sort(),
70
87
  isServerPath(pathname) {
71
88
  const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
72
89
  const owner = options.fragments && pathname.endsWith(`/${FRAG}`) ? match(trim(pathname.slice(0, -FRAG.length - 1) || '/')) : null;
73
90
  const found = owner ?? match(trim(pathname));
74
- return Boolean(found && modeFor(found.route.path, modes) === 'server');
91
+ return Boolean(found ? modeFor(found.route.path, modes) === 'server' : matchEndpoint(trim(pathname)));
92
+ },
93
+ async readsCookies(route) {
94
+ const found = routes.find((r) => r.path === route);
95
+ const dataFile = found && `/${found.file.replace(/\.[^./]+$/, '.load.ts')}`;
96
+ const mod = dataFile && data[dataFile] ? await data[dataFile]() : undefined;
97
+ return !!mod?.load && /\bcookies\b/.test(String(mod.load));
75
98
  },
76
99
  async hasLoader(path) {
77
100
  const route = routes.find((r) => r.path === path);
@@ -115,6 +138,37 @@ export function createHandler(pages, options = {}) {
115
138
  return out.sort();
116
139
  },
117
140
  async fetch(request) {
141
+ const jar = cookieJar(request, options.dev === true);
142
+ const locals = {};
143
+ if (options.hooks?.handle) {
144
+ let early;
145
+ try {
146
+ early = await options.hooks.handle({ request, cookies: jar.cookies, locals });
147
+ }
148
+ catch (err) {
149
+ if (options.dev)
150
+ throw err;
151
+ console.error(`clarusjs: src/server.ts: handle() failed: ${err?.message ?? err}`);
152
+ return jar.apply(failure('src/server.ts: handle() failed'));
153
+ }
154
+ if (early instanceof Response)
155
+ return jar.apply(early);
156
+ }
157
+ return jar.apply(await answer(request, jar.cookies, locals));
158
+ },
159
+ };
160
+ async function answer(request, cookies, locals) {
161
+ if (endpointRoutes.length) {
162
+ const path = new URL(request.url).pathname;
163
+ const trimmed = path.length > 1 ? path.replace(/\/+$/, '') : path;
164
+ const found = !match(trimmed) && matchEndpoint(trimmed);
165
+ if (found) {
166
+ const response = await callEndpoint(found.route.file, await found.route.load(), { request, params: found.params, cookies, locals }, options);
167
+ if (response)
168
+ return response;
169
+ }
170
+ }
171
+ {
118
172
  if (request.method !== 'GET' && request.method !== 'HEAD')
119
173
  return new Response('Method Not Allowed', { status: 405 });
120
174
  const pathname = new URL(request.url).pathname;
@@ -167,6 +221,10 @@ export function createHandler(pages, options = {}) {
167
221
  return notFound();
168
222
  if (mode !== 'server' && found.route.keys.length && !(await listed(found.route, found.params)))
169
223
  return notFound();
224
+ const componentFiles = options.componentLoaders?.[found.route.path] ?? [];
225
+ if (mode === 'client' && componentFiles.length) {
226
+ return fail(`${found.route.file}: component loaders don't run in client routes yet (${componentFiles.map((f) => f.replace(/^\//, '')).join(', ')}); make the route 'static' or 'server'`);
227
+ }
170
228
  if (mode === 'client' && !wantsData) {
171
229
  const client = options.client ?? {};
172
230
  const prefix = (options.base ?? '/').replace(/\/$/, '');
@@ -192,7 +250,8 @@ export function createHandler(pages, options = {}) {
192
250
  if (mod?.load) {
193
251
  let loaded;
194
252
  try {
195
- loaded = await mod.load({ params: found.params, request });
253
+ const once = modeFor(found.route.path, modes) !== 'server';
254
+ loaded = await mod.load({ params: found.params, locals, ...(once ? builtOnce(found.route.path, request) : { request, cookies }) });
196
255
  }
197
256
  catch (err) {
198
257
  return fail(`${dataFile}: load() failed: ${err?.message ?? err}`, err);
@@ -207,11 +266,37 @@ export function createHandler(pages, options = {}) {
207
266
  props = { ...props, ...loaded };
208
267
  }
209
268
  if (wantsData) {
210
- return new Response(head ? null : safeJson(stringify(props)), { headers: { 'content-type': 'application/json; charset=utf-8' } });
269
+ return new Response(head ? null : safeJson(toBrowser(props)), { headers: { 'content-type': 'application/json; charset=utf-8' } });
270
+ }
271
+ let componentData = new Map();
272
+ if (componentFiles.length) {
273
+ const once = mode !== 'server';
274
+ const context = { params: found.params, locals, ...(once ? builtOnce(found.route.path, request) : { request, cookies }) };
275
+ try {
276
+ componentData = new Map(await Promise.all(componentFiles.map(async (file) => {
277
+ const name = file.replace(/^\//, '');
278
+ const mod = await options.componentData?.[file]?.();
279
+ let value;
280
+ try {
281
+ value = await mod?.load?.(context);
282
+ }
283
+ catch (err) {
284
+ throw Object.assign(new Error(`${name}: load() failed: ${err?.message ?? err}`), { cause: err });
285
+ }
286
+ if (value === null || typeof value !== 'object' || Array.isArray(value) || value instanceof Response) {
287
+ throw new Error(`${name}: load() must return an object of the component's inputs, got ${value instanceof Response ? 'a Response' : Array.isArray(value) ? 'an array' : value === null ? 'null' : typeof value}`);
288
+ }
289
+ return [name.replace(/\.load\.ts$/, '.tscl'), value];
290
+ })));
291
+ }
292
+ catch (err) {
293
+ return fail(err.message, err);
294
+ }
211
295
  }
212
296
  let html;
213
297
  try {
214
- html = (await found.route.load()).render(props);
298
+ const module = await found.route.load();
299
+ html = withLoaded(componentData, () => module.render(props));
215
300
  }
216
301
  catch (err) {
217
302
  return fail(`${found.route.file}: render failed: ${err?.message ?? err}`, err);
@@ -238,8 +323,8 @@ export function createHandler(pages, options = {}) {
238
323
  : hasIslands ? `<script type="module" src="${loaderUrl}"></script>` : '';
239
324
  const body = fullDocument(html, style, script);
240
325
  return new Response(head ? null : body, { headers: { 'content-type': 'text/html; charset=utf-8' } });
241
- },
242
- };
326
+ }
327
+ }
243
328
  return handler;
244
329
  }
245
330
  function pagePath(pathname, fragment) {
@@ -281,10 +366,12 @@ export function toFragment(html) {
281
366
  return titleHtml + html.slice(open.index, close) + '</body>';
282
367
  }
283
368
  function maskComments(html) {
284
- return html.replace(/<!--[\s\S]*?-->/g, (c) => ' '.repeat(c.length));
369
+ return html
370
+ .replace(/<!--[\s\S]*?-->/g, (c) => ' '.repeat(c.length))
371
+ .replace(/(<(script|style)\b[^>]*>)([\s\S]*?)(<\/\2\s*>)/gi, (_, open, _tag, body, close) => open + ' '.repeat(body.length) + close);
285
372
  }
286
373
  function fullDocument(html, style, script) {
287
- let out = /^\s*<!doctype/i.test(html) ? html : `<!doctype html>${html}`;
374
+ let out = /^\s*<!doctype/i.test(maskComments(html)) ? html : `<!doctype html>${html}`;
288
375
  if (style) {
289
376
  const head = maskComments(out).search(/<\/head>/i);
290
377
  out = head === -1 ? out + style : out.slice(0, head) + style + out.slice(head);
@@ -304,3 +391,139 @@ export function rootLinks(html, base) {
304
391
  return `${attr}${(resolved.pathname + resolved.search + resolved.hash).replace(/&/g, '&amp;')}"`;
305
392
  });
306
393
  }
394
+ const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
395
+ function cookieJar(request, dev) {
396
+ const incoming = new Map();
397
+ for (const part of (request.headers.get('cookie') ?? '').split(';')) {
398
+ const at = part.indexOf('=');
399
+ if (at < 1)
400
+ continue;
401
+ const name = part.slice(0, at).trim();
402
+ const raw = part.slice(at + 1).trim().replace(/^"(.*)"$/, '$1');
403
+ let value = raw;
404
+ try {
405
+ value = decodeURIComponent(raw);
406
+ }
407
+ catch { }
408
+ if (!incoming.has(name))
409
+ incoming.set(name, value);
410
+ }
411
+ const current = new Map(incoming);
412
+ const out = new Map();
413
+ const write = (name, value, o) => {
414
+ if (!TOKEN.test(name))
415
+ throw new Error(`cookies.set: ${JSON.stringify(name)} isn't a valid cookie name`);
416
+ const path = o.path ?? '/';
417
+ let header = `${name}=${encodeURIComponent(value)}; Path=${path}`;
418
+ if (o.domain)
419
+ header += `; Domain=${o.domain}`;
420
+ if (o.maxAge !== undefined)
421
+ header += `; Max-Age=${Math.floor(o.maxAge)}`;
422
+ if (o.expires)
423
+ header += `; Expires=${o.expires.toUTCString()}`;
424
+ if (o.httpOnly ?? true)
425
+ header += '; HttpOnly';
426
+ header += `; SameSite=${{ lax: 'Lax', strict: 'Strict', none: 'None' }[o.sameSite ?? 'lax']}`;
427
+ if (o.secure ?? !dev)
428
+ header += '; Secure';
429
+ out.set(`${name};${path};${o.domain ?? ''}`, header);
430
+ };
431
+ return {
432
+ cookies: {
433
+ get: (name) => current.get(name),
434
+ getAll: () => Object.fromEntries(current),
435
+ set(name, value, options = {}) {
436
+ write(name, value, options);
437
+ current.set(name, value);
438
+ },
439
+ delete(name, options = {}) {
440
+ write(name, '', { ...options, maxAge: undefined });
441
+ const key = `${name};${options.path ?? '/'};${options.domain ?? ''}`;
442
+ out.set(key, out.get(key) + '; Max-Age=0');
443
+ current.delete(name);
444
+ },
445
+ },
446
+ apply(response) {
447
+ if (!out.size)
448
+ return response;
449
+ const headers = new Headers(response.headers);
450
+ for (const header of out.values())
451
+ headers.append('set-cookie', header);
452
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
453
+ },
454
+ };
455
+ }
456
+ function builtOnce(route, request) {
457
+ const refuse = (what) => () => { throw new Error(`${route} reads ${what}, but static routes are built once for everyone: make it 'server' (routes in vite.config.ts)`); };
458
+ const cookies = { get: refuse('cookies'), getAll: refuse('cookies'), set: refuse('cookies'), delete: refuse('cookies') };
459
+ const headers = new Proxy(request.headers, { get: refuse("the request's headers") });
460
+ const proxied = new Proxy(request, {
461
+ get(target, key) {
462
+ if (key === 'headers')
463
+ return headers;
464
+ const value = Reflect.get(target, key, target);
465
+ return typeof value === 'function' ? value.bind(target) : value;
466
+ },
467
+ });
468
+ return { request: proxied, cookies };
469
+ }
470
+ const METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
471
+ const WRITES = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
472
+ async function callEndpoint(file, mod, context, options) {
473
+ const exported = METHODS.filter((m) => typeof mod[m] === 'function');
474
+ if (!exported.length)
475
+ return undefined;
476
+ const { request } = context;
477
+ const method = request.method.toUpperCase();
478
+ const fn = mod[method] ?? (method === 'HEAD' ? mod.GET : undefined);
479
+ if (!fn) {
480
+ const allow = [...new Set(exported.flatMap((m) => (m === 'GET' ? ['GET', 'HEAD'] : [m])))].sort();
481
+ return new Response('Method Not Allowed', { status: 405, headers: { allow: allow.join(', '), 'content-type': 'text/plain; charset=utf-8' } });
482
+ }
483
+ if (WRITES.has(method) && !sameOrigin(request, options.site?.url)) {
484
+ return new Response('Forbidden: cross-site request', { status: 403, headers: { 'content-type': 'text/plain; charset=utf-8' } });
485
+ }
486
+ let response;
487
+ try {
488
+ response = await fn(context);
489
+ }
490
+ catch (err) {
491
+ if (options.dev)
492
+ throw err;
493
+ console.error(`clarusjs: ${file}: ${method} failed: ${err?.message ?? err}`);
494
+ return failure(`${file}: ${method} failed`);
495
+ }
496
+ if (!(response instanceof Response)) {
497
+ const message = `${file}: ${method} must return a Response (got ${response === null ? 'null' : typeof response})`;
498
+ if (options.dev)
499
+ throw new Error(message);
500
+ console.error(`clarusjs: ${message}`);
501
+ return failure(message);
502
+ }
503
+ return method === 'HEAD' ? new Response(null, { status: response.status, statusText: response.statusText, headers: response.headers }) : response;
504
+ }
505
+ function sameOrigin(request, site) {
506
+ if (request.headers.get('sec-fetch-site') === 'cross-site')
507
+ return false;
508
+ let origin = request.headers.get('origin');
509
+ if (origin === 'null')
510
+ return false;
511
+ if (!origin) {
512
+ const referer = request.headers.get('referer');
513
+ try {
514
+ origin = referer ? new URL(referer).origin : null;
515
+ }
516
+ catch {
517
+ origin = null;
518
+ }
519
+ }
520
+ if (!origin)
521
+ return !request.headers.has('cookie');
522
+ const allowed = [new URL(request.url).origin];
523
+ if (site)
524
+ try {
525
+ allowed.push(new URL(site).origin);
526
+ }
527
+ catch { }
528
+ return allowed.includes(origin);
529
+ }
@@ -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
+ }
@@ -1,5 +1,5 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
- import { resolve } from 'node:path';
2
+ import { normalize, resolve } from 'node:path';
3
3
  function readJsonc(text) {
4
4
  const bare = text.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, str) => str ?? '');
5
5
  return JSON.parse(bare.replace(/,(\s*[}\]])/g, '$1'));
@@ -34,9 +34,9 @@ export function projectAliases(root, vite = []) {
34
34
  export function resolveAlias(spec, aliases) {
35
35
  for (const { find, replacement, exact } of aliases) {
36
36
  if (find.endsWith('/') ? spec.startsWith(find) : spec === find)
37
- return spec === find ? replacement : replacement + spec.slice(find.length);
37
+ return normalize(spec === find ? replacement : replacement + spec.slice(find.length));
38
38
  if (!exact && !find.endsWith('/') && spec.startsWith(find + '/'))
39
- return replacement + spec.slice(find.length);
39
+ return normalize(replacement + spec.slice(find.length));
40
40
  }
41
41
  return undefined;
42
42
  }