clarusjs 0.7.0 → 0.8.1

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 (52) hide show
  1. package/dist/check/generate.d.ts +6 -0
  2. package/dist/check/generate.js +12 -22
  3. package/dist/cli/check.js +58 -15
  4. package/dist/cli/explain.js +0 -1
  5. package/dist/cli/index.js +0 -1
  6. package/dist/compiler/emit-client.js +1 -11
  7. package/dist/compiler/emit-server.js +1 -2
  8. package/dist/compiler/errors.js +0 -1
  9. package/dist/compiler/html-expr.js +2 -7
  10. package/dist/compiler/index.js +10 -8
  11. package/dist/compiler/ir.d.ts +1 -0
  12. package/dist/compiler/ir.js +9 -14
  13. package/dist/compiler/parse.d.ts +1 -0
  14. package/dist/compiler/parse.js +18 -19
  15. package/dist/compiler/script.js +2 -31
  16. package/dist/compiler/shared.js +0 -5
  17. package/dist/runtime/dom.js +4 -1
  18. package/dist/runtime/fragments.d.ts +1 -1
  19. package/dist/runtime/fragments.js +10 -30
  20. package/dist/runtime/html.d.ts +2 -0
  21. package/dist/runtime/html.js +4 -0
  22. package/dist/runtime/loader.js +41 -2
  23. package/dist/runtime/navigate.d.ts +38 -0
  24. package/dist/runtime/navigate.js +88 -0
  25. package/dist/runtime/navigation.d.ts +88 -0
  26. package/dist/runtime/navigation.js +165 -0
  27. package/dist/runtime/router.d.ts +8 -1
  28. package/dist/runtime/router.js +32 -42
  29. package/dist/runtime/server.d.ts +1 -1
  30. package/dist/runtime/server.js +1 -1
  31. package/dist/server/handler.d.ts +18 -0
  32. package/dist/server/handler.js +80 -53
  33. package/dist/server/head.d.ts +36 -0
  34. package/dist/server/head.js +129 -0
  35. package/dist/server/manifest.js +0 -3
  36. package/dist/server/modes.js +0 -5
  37. package/dist/server/views.js +0 -7
  38. package/dist/vite/aliases.d.ts +10 -0
  39. package/dist/vite/aliases.js +42 -0
  40. package/dist/vite/build.d.ts +9 -0
  41. package/dist/vite/build.js +43 -17
  42. package/dist/vite/links.d.ts +2 -0
  43. package/dist/vite/links.js +11 -10
  44. package/dist/vite/manifest.js +2 -10
  45. package/dist/vite/netlify.js +1 -7
  46. package/dist/vite/plugin.d.ts +35 -0
  47. package/dist/vite/plugin.js +162 -88
  48. package/dist/vite/redirects.d.ts +10 -0
  49. package/dist/vite/redirects.js +41 -0
  50. package/dist/vite/sitemap.d.ts +11 -0
  51. package/dist/vite/sitemap.js +31 -0
  52. package/package.json +18 -2
@@ -1,8 +1,9 @@
1
- // Build-time helpers for the Vite plugin: find components, and prerender every route to static HTML.
1
+ import { resolveAlias } from './aliases.js';
2
2
  import { spawnSync } from 'node:child_process';
3
- import { readdirSync } from 'node:fs';
4
- import { resolve } from 'node:path';
5
- /** Absolute paths of every component file under `srcDir` (`.tscl`, or any page source extension given). */
3
+ import { readdirSync, realpathSync } from 'node:fs';
4
+ import { createRequire } from 'node:module';
5
+ import { dirname, resolve } from 'node:path';
6
+ import { parse } from '../compiler/parse.js';
6
7
  export function findClarusFiles(srcDir, extensions = ['.tscl']) {
7
8
  let entries;
8
9
  try {
@@ -13,11 +14,6 @@ export function findClarusFiles(srcDir, extensions = ['.tscl']) {
13
14
  }
14
15
  return entries.filter((f) => extensions.some((ext) => f.endsWith(ext))).map((f) => resolve(srcDir, f)).sort();
15
16
  }
16
- /**
17
- * '/' → 'index.html', '/about/team' → 'about/team/index.html', '/users/a%20b' → 'users/a b/index.html'.
18
- * Segments are decoded because static hosts look files up by the decoded path. A decoded segment can't add a level:
19
- * entries() values never contain '/' (and a page file's own name has none).
20
- */
21
17
  export function routeToFile(route) {
22
18
  const path = route.replace(/^\/+|\/+$/g, '').split('/').map((seg) => {
23
19
  try {
@@ -25,21 +21,14 @@ export function routeToFile(route) {
25
21
  }
26
22
  catch {
27
23
  return seg;
28
- } // '100%' is a name, not an escape
24
+ }
29
25
  }).join('/');
30
- // A client page's data file is written as itself, next to the page's shell.
31
26
  if (path === '__data.json' || path.endsWith('/__data.json'))
32
27
  return path;
33
- // A page's fragment, likewise.
34
28
  if (path === 'index.frag.html' || path.endsWith('/index.frag.html'))
35
29
  return path;
36
30
  return path ? `${path}/index.html` : 'index.html';
37
31
  }
38
- /**
39
- * Call the built handler for every route (or only `only`) and write the HTML into `outDir`. Any failure fails the
40
- * build. Runs in a fresh Node process so a rebuilt server bundle is never served from a module cache. Returns the
41
- * routes rendered and those that read the route manifest (readManifest() from `manifestFile`).
42
- */
43
32
  export async function prerender(serverEntry, outDir, manifestFile, only) {
44
33
  const script = `
45
34
  import { mkdirSync, writeFileSync } from 'node:fs'
@@ -93,3 +82,40 @@ export async function prerender(serverEntry, outDir, manifestFile, only) {
93
82
  throw new Error(result.stderr.trim() || `prerender failed (exit ${result.status})`);
94
83
  return JSON.parse(result.stdout);
95
84
  }
85
+ export function packageOf(file) {
86
+ return /.*[\\/]node_modules[\\/]((?:@[^\\/]+[\\/])?[^\\/]+)[\\/]/.exec(file)?.[1].replace(/\\/g, '/');
87
+ }
88
+ export function reachableComponents(root, start, read, extensions, aliases = []) {
89
+ const require = createRequire(resolve(root, 'package.json'));
90
+ const seen = new Set();
91
+ const queue = start.map((f) => realpathSync(f));
92
+ while (queue.length) {
93
+ const file = queue.shift();
94
+ if (seen.has(file))
95
+ continue;
96
+ seen.add(file);
97
+ let imports;
98
+ try {
99
+ imports = parse(read(file), file).imports;
100
+ }
101
+ catch {
102
+ continue;
103
+ }
104
+ for (const { from } of imports) {
105
+ const spec = from.replace(/\?.*$/, '');
106
+ if (!extensions.some((e) => spec.endsWith(e)))
107
+ continue;
108
+ let target;
109
+ 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);
112
+ }
113
+ catch {
114
+ continue;
115
+ }
116
+ if (!seen.has(target))
117
+ queue.push(target);
118
+ }
119
+ }
120
+ return [...seen];
121
+ }
@@ -13,6 +13,8 @@ type Options = {
13
13
  /** Client routes render in the browser: their pages exist, but their anchors can't be checked at build. */
14
14
  clientRoutes: string[];
15
15
  base: string;
16
+ /** site.url: absolute links to the site itself are checked like internal ones. */
17
+ site?: string;
16
18
  };
17
19
  export declare function checkLinks(options: Options): LinkIssue[];
18
20
  export {};
@@ -1,9 +1,6 @@
1
- // Build-time link checking: once every page is built, links between pages and to #anchors are checked against
2
- // what was actually written. Reads dist/client only; reporting and failing are up to the caller.
3
1
  import { existsSync, readFileSync, statSync } from 'node:fs';
4
2
  import { resolve } from 'node:path';
5
3
  import { routeToFile } from './build.js';
6
- // A stray % is kept as written, as routeToFile does, instead of failing the build with a URIError.
7
4
  const decode = (s) => { try {
8
5
  return decodeURIComponent(s);
9
6
  }
@@ -17,7 +14,6 @@ catch {
17
14
  return false;
18
15
  } };
19
16
  const trim = (path) => (path.length > 1 ? path.replace(/\/+$/, '') : path);
20
- /** Edit distance, for "did you mean". */
21
17
  function distance(a, b) {
22
18
  const row = Array.from({ length: b.length + 1 }, (_, i) => i);
23
19
  for (let i = 1; i <= a.length; i++) {
@@ -31,7 +27,6 @@ function distance(a, b) {
31
27
  }
32
28
  return row[b.length];
33
29
  }
34
- /** The closest candidate, if it is close enough to be a likely typo. */
35
30
  function closest(target, candidates) {
36
31
  let best;
37
32
  let score = Infinity;
@@ -48,8 +43,8 @@ const ids = (html) => new Set([...html.matchAll(/\s(?:id|name)="([^"]+)"/g)].map
48
43
  const hrefs = (html) => [...html.replace(/<!--[\s\S]*?-->/g, '').matchAll(/<a\b[^>]*?\shref="([^"]*)"/g)].map((m) => m[1].replace(/&amp;/g, '&'));
49
44
  export function checkLinks(options) {
50
45
  const { outDir } = options;
51
- // An absolute base (https://cdn.example.com/docs/) is compared by its path.
52
46
  const base = /^https?:\/\//.test(options.base) ? new URL(options.base).pathname : options.base;
47
+ const siteRoot = options.site ? new URL(base, options.site.replace(/\/?$/, '/')) : undefined;
53
48
  const routes = new Set(options.routes.map(trim));
54
49
  const client = new Set(options.clientRoutes.map(trim));
55
50
  const serverPatterns = options.serverRoutes.map((r) => new RegExp(`^${r.split('/').map((seg) => (/^\[[^\]]+\]$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('/')}$`));
@@ -63,18 +58,24 @@ export function checkLinks(options) {
63
58
  };
64
59
  const issues = [];
65
60
  for (const page of [...routes].filter((r) => !client.has(r))) {
66
- for (const href of hrefs(read(page))) {
61
+ for (let href of hrefs(read(page))) {
62
+ if (siteRoot && /^https?:/i.test(href)) {
63
+ const u = new URL(href);
64
+ if (u.origin === siteRoot.origin && (u.pathname.startsWith(siteRoot.pathname) || `${u.pathname}/` === siteRoot.pathname)) {
65
+ href = base + u.pathname.slice(Math.min(u.pathname.length, siteRoot.pathname.length)) + u.search + u.hash;
66
+ }
67
+ }
67
68
  if (/^[a-z][\w+.-]*:|^\/\//i.test(href) || href === '')
68
- continue; // external, mailto:, tel:, …
69
+ continue;
69
70
  const url = new URL(href, `http://site${base}${page === '/' ? '' : page.slice(1) + '/'}`);
70
71
  if (!url.pathname.startsWith(base) && `${url.pathname}/` !== base)
71
- continue; // outside this site
72
+ continue;
72
73
  let path = trim(decode(url.pathname.slice(base.length - 1)) || '/');
73
74
  if (path.endsWith('/index.html'))
74
75
  path = trim(path.slice(0, -'index.html'.length));
75
76
  const anchor = decode(url.hash.slice(1));
76
77
  const isPage = routes.has(path);
77
- const exists = isPage || serverPatterns.some((re) => re.test(path)) || isFile(resolve(outDir, `.${path}`)); // a directory without a page is a 404
78
+ const exists = isPage || serverPatterns.some((re) => re.test(path)) || isFile(resolve(outDir, `.${path}`));
78
79
  if (!exists) {
79
80
  const guess = closest(path, routes);
80
81
  issues.push({ kind: 'pages', page, href, message: `no page at ${path}${guess ? ` (did you mean ${guess}?)` : ''}` });
@@ -1,5 +1,3 @@
1
- // The route manifest: after `vite build`, what each page ships, read back from its prerendered HTML.
2
- // dist/clarusjs-manifest.json is what `clarusjs explain` prints. Written outside dist/client, so it isn't served.
3
1
  import { readFileSync, writeFileSync } from 'node:fs';
4
2
  import { resolve } from 'node:path';
5
3
  import { gzipSync } from 'node:zlib';
@@ -11,12 +9,10 @@ const attrsOf = (tag) => {
11
9
  out[m[1]] = m[2].replace(/&amp;/g, '&');
12
10
  return out;
13
11
  };
14
- /** What one prerendered page ships. `size` returns a built file's gzip size. */
15
12
  export function describeRoute(route, html, opts) {
16
13
  const local = (url) => (url.startsWith(opts.base) ? url.slice(opts.base.length) : url.replace(/^\//, ''));
17
14
  const byFile = new Map(Object.values(opts.chunks).map((c) => [c.file, c]));
18
15
  const keyFile = new Map(Object.entries(opts.chunks).map(([k, c]) => [k, c.file]));
19
- // A chunk and everything it imports, in load order.
20
16
  const closure = (file, into) => {
21
17
  if (into.includes(file))
22
18
  return;
@@ -41,8 +37,7 @@ export function describeRoute(route, html, opts) {
41
37
  closure(local(m[1]), all);
42
38
  closure(local(m[1]), initial);
43
39
  }
44
- // A client route also loads its page's render module, named in the shell's route table.
45
- const table = /<script type="application\/json" id="cl-routes">(.*?)<\/script>/.exec(html)?.[1];
40
+ const table = /<script type="application\/json" id="cl-routes"[^>]*>(.*?)<\/script>/.exec(html)?.[1];
46
41
  const render = opts.client && table ? matchRoute(JSON.parse(table), route)?.r : undefined;
47
42
  if (render) {
48
43
  closure(local(render), all);
@@ -57,7 +52,6 @@ export function describeRoute(route, html, opts) {
57
52
  const css = [...html.matchAll(/<link\b[^>]*rel="stylesheet"[^>]*>/g)].map((m) => attrsOf(m[0]).href).filter(Boolean);
58
53
  return { mode: opts.client ? 'client' : 'static', html: routeToFile(route), loader: opts.loaded ? 'build' : null, islands, js: { files: all, gzip: sum(all), initialGzip: sum(initial) }, css };
59
54
  }
60
- /** Describe every prerendered route and write `<distDir>/clarusjs-manifest.json`. */
61
55
  export function writeManifest(distDir, routes, base, loaded = [], server = []) {
62
56
  const client = resolve(distDir, 'client');
63
57
  const chunks = JSON.parse(readFileSync(resolve(client, '.vite/manifest.json'), 'utf8'));
@@ -71,13 +65,11 @@ export function writeManifest(distDir, routes, base, loaded = [], server = []) {
71
65
  const dataFile = (route) => (route === '/' ? '/__data.json' : `${route}/__data.json`);
72
66
  for (const route of routes) {
73
67
  if (route.endsWith('/__data.json') || route.endsWith('/index.frag.html'))
74
- continue; // data and fragments, not pages
68
+ continue;
75
69
  const isClient = routes.includes(dataFile(route));
76
- // A client route's loader runs when its data file is written.
77
70
  const ran = loaded.includes(route) || (isClient && loaded.includes(dataFile(route)));
78
71
  manifest.routes[route] = describeRoute(route, readFileSync(resolve(client, routeToFile(route)), 'utf8'), { base, chunks, size, loaded: ran, client: isClient });
79
72
  }
80
- // Server routes have no HTML at build time: what they ship is decided per request.
81
73
  for (const { route, loader } of server) {
82
74
  manifest.routes[route] = { mode: 'server', html: null, loader: loader ? 'request' : null, islands: [], js: { files: [], gzip: 0, initialGzip: 0 }, css: [] };
83
75
  }
@@ -1,14 +1,10 @@
1
- // Netlify adapter: server routes run as one Netlify Function (Frameworks API) calling the same fetch handler.
2
- // Static routes stay files; preferStatic makes Netlify serve those first.
3
1
  import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
4
2
  import { dirname, relative, resolve, sep } from 'node:path';
5
3
  const FUNCTION = '.netlify/v1/functions/clarusjs-server.mjs';
6
- /** '/account/[id]' → ['/account/:id', '/account/:id/'] (Netlify paths use URLPattern syntax). */
7
4
  export function netlifyPaths(route, fragments = false) {
8
5
  const segments = route.split('/');
9
6
  const keyOf = (seg) => /^\[([A-Za-z_$][\w$]*)\]$/.exec(seg)?.[1];
10
7
  const valid = (key) => /^[A-Za-z_]\w*$/.test(key);
11
- // Names already valid in URLPattern are kept; others get p0, p1, … that aren't taken (URLPattern rejects duplicates).
12
8
  const taken = new Set(segments.map(keyOf).filter((k) => k !== undefined && valid(k)));
13
9
  let n = 0;
14
10
  const fresh = () => {
@@ -21,15 +17,13 @@ export function netlifyPaths(route, fragments = false) {
21
17
  const key = keyOf(seg);
22
18
  if (key !== undefined)
23
19
  return `:${valid(key) ? key : fresh()}`;
24
- return seg.replace(/[:*?+(){}\\]/g, '\\$&'); // literal text, not pattern syntax
20
+ return seg.replace(/[:*?+(){}\\]/g, '\\$&');
25
21
  }).join('/');
26
22
  const paths = path === '/' || path === '' ? ['/'] : [path, `${path}/`];
27
- // The page's fragment, for fragment navigation, comes from the same function.
28
23
  if (fragments)
29
24
  paths.push(path === '/' || path === '' ? '/index.frag.html' : `${path}/index.frag.html`);
30
25
  return paths;
31
26
  }
32
- /** Write (or, without server routes, remove) the function in `<root>/.netlify/v1/functions`. */
33
27
  export function writeNetlifyFunction(root, serverEntry, serverRoutes, fragments = false) {
34
28
  const file = resolve(root, FUNCTION);
35
29
  if (!serverRoutes.length) {
@@ -1,5 +1,9 @@
1
1
  import { type Plugin } from 'vite';
2
+ export { packageOf } from './build.ts';
3
+ /** Newest commit time (unix seconds) of every file under a folder, from one `git log` (themes use it for "last updated"). */
4
+ export { gitDates } from './sitemap.ts';
2
5
  import { type ModeTable } from '../server/modes.ts';
6
+ import type { HeadTag, SiteOptions } from '../server/head.ts';
3
7
  /** Dev URL of a component's client module: root-relative, or Vite's /@fs/ form for files outside the root. */
4
8
  export declare function clientUrlFor(root: string, file: string): string;
5
9
  export type ClarusOptions = {
@@ -20,7 +24,38 @@ export type ClarusOptions = {
20
24
  anchors?: LinkLevel;
21
25
  strict?: boolean;
22
26
  };
27
+ /**
28
+ * Paths that moved: `{ '/old': '/new' }` (a site path or a full URL). The build writes a page at each old path that
29
+ * sends visitors on, and `_redirects` lines (a real 301 on Netlify and Cloudflare Pages); dev answers 301.
30
+ * @see https://clarusjs.com/guide/routing
31
+ */
32
+ redirects?: Record<string, string>;
33
+ /**
34
+ * Every page's <head>: `titleTemplate` ('%s · Site') wraps the document title, `tags` are added unless the page has
35
+ * its own with the same key. Anything else: export `transformHead(head, page)` from src/head.ts.
36
+ */
37
+ head?: {
38
+ titleTemplate?: string;
39
+ tags?: HeadTag[];
40
+ jsonLd?: object | object[];
41
+ };
42
+ /**
43
+ * The site's public address. Every page gets a canonical URL and social cards (Open Graph, Twitter) from its title,
44
+ * description and an image (the page's og:image, or `image`); absolute links to the site are link-checked.
45
+ */
46
+ site?: SiteOptions;
47
+ /**
48
+ * With site.url, vite build writes sitemap.xml (static pages, dated from git). false: no sitemap. `exclude`: paths
49
+ * left out ('/legal', '/tags/*' one segment, '/drafts/**' any depth). A page opts out itself with
50
+ * <cl-head><meta name="sitemap" content="false"></cl-head> (removed from the built page) or noindex.
51
+ */
52
+ sitemap?: boolean | {
53
+ exclude?: string[];
54
+ };
55
+ /** With site.url, vite build writes robots.txt (allow all, and the sitemap), unless public/robots.txt exists. */
56
+ robots?: boolean;
23
57
  };
58
+ export type { HeadTag };
24
59
  export type LinkLevel = 'error' | 'warn' | 'off';
25
60
  /**
26
61
  * A page source: files with another extension (such as Markdown) turned into .tscl text, then compiled like any