clarusjs 0.11.0 → 0.13.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.
@@ -31,11 +31,13 @@ import { writeNetlifyFunction } from './netlify.js';
31
31
  import { checkLinks } from './links.js';
32
32
  import { checkRedirects, redirectFor, writeRedirects } from './redirects.js';
33
33
  import { projectAliases, resolveAlias } from './aliases.js';
34
- import { gitDates, sitemapXml } from './sitemap.js';
34
+ import { gitDates, sitemapFiles } from './sitemap.js';
35
35
  import { checkModes, modeFor } from '../server/modes.js';
36
36
  import { rootLinks, routeFromFile } from '../server/handler.js';
37
37
  import { basePath } from '../server/head.js';
38
- import { sendResponse, toRequest } from './node.js';
38
+ import { acceptsEncoding, sendResponse, toRequest } from './node.js';
39
+ import { resolveIcon } from '../icons.js';
40
+ const iconsFor = (file) => (name) => resolveIcon(name, file);
39
41
  const ext = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
40
42
  const here = (path) => fileURLToPath(new URL(path + ext, import.meta.url));
41
43
  const ENTRY = 'virtual:clarusjs/server-entry';
@@ -124,7 +126,7 @@ function writeStyles(root, files) {
124
126
  const outDir = resolve(root, '.clarusjs');
125
127
  for (const file of files.components(root)) {
126
128
  try {
127
- let out = compile(files.read(file, root), { file, target: 'client', scope: scopeFor(root, file) }).css;
129
+ let out = compile(files.read(file, root), { file, target: 'client', scope: scopeFor(root, file), icon: iconsFor(file) }).css;
128
130
  out = out.replace(/^(?:[ \t]*@(?:reference|import)\b[^;{]*;[ \t]*\n?)+/, (statements) => {
129
131
  for (const statement of statements.split(';').map((x) => x.trim()).filter(Boolean)) {
130
132
  head.add(statement.replace(/(["'])(\.{1,2}\/[^"']*)\1/, (_, q, spec) => {
@@ -158,6 +160,24 @@ function clientPages(appRoot, modes, files) {
158
160
  }
159
161
  return pages;
160
162
  }
163
+ function metaAttr(tag, name) {
164
+ return new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(tag)?.slice(1).find((v) => v !== undefined);
165
+ }
166
+ function lastmodTime(value) {
167
+ const m = /^(\d{4})-(\d{2})-(\d{2})(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?$/.exec(value);
168
+ if (!m)
169
+ return NaN;
170
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
171
+ const day = new Date(Date.UTC(y, mo - 1, d));
172
+ if (day.getUTCFullYear() !== y || day.getUTCMonth() !== mo - 1 || day.getUTCDate() !== d)
173
+ return NaN;
174
+ return Date.parse(m[4] ? value : `${value}T00:00:00Z`);
175
+ }
176
+ function pluginsOf(list) {
177
+ if (Array.isArray(list))
178
+ return list.flatMap(pluginsOf);
179
+ return list && typeof list === 'object' && !(list instanceof Promise) ? [list] : [];
180
+ }
161
181
  export default function clarusjs(options = {}) {
162
182
  const modes = options.routes ?? {};
163
183
  checkModes(modes);
@@ -172,9 +192,10 @@ export default function clarusjs(options = {}) {
172
192
  }
173
193
  const extensions = ['.tscl', ...sources.map((src) => src.extension)];
174
194
  let aliases = [];
195
+ let extra = () => [];
175
196
  const files = {
176
197
  find: (dir) => findClarusFiles(dir, extensions).filter((f) => f.endsWith('.tscl') || f.includes(`${sep}src${sep}pages${sep}`)),
177
- components: (appRoot) => reachableComponents(appRoot, files.find(resolve(appRoot, 'src')), (file) => files.read(file, appRoot), extensions, aliases),
198
+ components: (appRoot) => reachableComponents(appRoot, [...files.find(resolve(appRoot, 'src')), ...extra(appRoot).filter((f) => existsSync(f))], (file) => files.read(file, appRoot), extensions, aliases),
178
199
  read: (file, appRoot) => {
179
200
  const code = readFileSync(file, 'utf8');
180
201
  const src = sources.find((x) => file.endsWith(x.extension));
@@ -219,6 +240,7 @@ export default function clarusjs(options = {}) {
219
240
  name: 'clarusjs',
220
241
  api: { sources, lint: options.lint, lintRules: options.lintRules },
221
242
  config(userConfig, env) {
243
+ extra = (appRoot) => pluginsOf(userConfig.plugins).flatMap((p) => p.api?.clarusComponents?.(appRoot) ?? []);
222
244
  const projectRoot = resolve(userConfig.root ?? process.cwd());
223
245
  aliases = projectAliases(projectRoot, userConfig.resolve?.alias);
224
246
  const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
@@ -254,7 +276,7 @@ export default function clarusjs(options = {}) {
254
276
  const input = { [LOADER_ENTRY]: here('../runtime/loader') };
255
277
  const components = files.components(appRoot);
256
278
  for (const file of components) {
257
- if (compile(files.read(file, appRoot), { file, target: 'client' }).stateful)
279
+ if (compile(files.read(file, appRoot), { file, target: 'client', icon: iconsFor(file) }).stateful)
258
280
  input[entryName(appRoot, file)] = file;
259
281
  }
260
282
  const client = clientPages(appRoot, modes, files);
@@ -330,6 +352,28 @@ export default function clarusjs(options = {}) {
330
352
  }
331
353
  const pageRoutes = routes.filter((r) => !/\/(__data\.json|index\.frag\.html)$/.test(r));
332
354
  const clientRoutes = pageRoutes.filter((r) => routes.includes(r === '/' ? '/__data.json' : `${r}/__data.json`));
355
+ const markers = new Map();
356
+ for (const page of pageRoutes) {
357
+ const file = resolve(out, routeToFile(page));
358
+ let html = readFileSync(file, 'utf8');
359
+ const tags = [...html.matchAll(/<meta\b[^>]*>/gi)].map(([tag]) => tag);
360
+ const optOut = tags.find((tag) => metaAttr(tag, 'name')?.toLowerCase() === 'sitemap' && metaAttr(tag, 'content') === 'false');
361
+ const dated = tags.find((tag) => metaAttr(tag, 'name')?.toLowerCase() === 'sitemap:lastmod');
362
+ let lastmod;
363
+ if (dated) {
364
+ const value = metaAttr(dated, 'content') ?? '';
365
+ const time = lastmodTime(value);
366
+ if (Number.isNaN(time))
367
+ throw new Error(`clarusjs: ${page}: sitemap:lastmod '${value}' isn't a date (YYYY-MM-DD)`);
368
+ lastmod = time / 1000;
369
+ }
370
+ for (const marker of [optOut, dated])
371
+ if (marker)
372
+ html = html.replace(marker, '');
373
+ if (optOut || dated)
374
+ writeFileSync(file, html);
375
+ markers.set(page, { out: !!optOut, ...(lastmod === undefined ? {} : { lastmod }) });
376
+ }
333
377
  if (pageRoutes.includes('/404') && !clientRoutes.includes('/404')) {
334
378
  const html = rootLinks(readFileSync(resolve(out, routeToFile('/404')), 'utf8'), basePath(builder.config.base));
335
379
  writeFileSync(resolve(out, routeToFile('/404')), html);
@@ -384,19 +428,41 @@ export default function clarusjs(options = {}) {
384
428
  const epoch = process.env.SOURCE_DATE_EPOCH ? Number(process.env.SOURCE_DATE_EPOCH) : undefined;
385
429
  const exclude = (typeof options.sitemap === 'object' ? options.sitemap.exclude ?? [] : [])
386
430
  .map((p) => new RegExp(`^${p.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*\*|\*/g, (s) => (s === '**' ? '.*' : '[^/]+'))}$`));
387
- const optedOut = (page) => {
431
+ const images = typeof options.sitemap !== 'object' || options.sitemap.images !== false;
432
+ const sitemapMeta = (page) => {
388
433
  const file = resolve(out, routeToFile(page));
389
434
  const html = readFileSync(file, 'utf8');
390
435
  const tags = [...html.matchAll(/<meta\b[^>]*>/gi)].map(([tag]) => tag);
391
- const attr = (tag, name) => new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(tag)?.slice(1).find((v) => v !== undefined);
392
- const marker = tags.find((tag) => attr(tag, 'name')?.toLowerCase() === 'sitemap' && attr(tag, 'content') === 'false');
393
- if (marker)
394
- writeFileSync(file, html.replace(marker, ''));
395
- return !!marker || tags.some((tag) => attr(tag, 'name')?.toLowerCase() === 'robots' && /\bnoindex\b/i.test(attr(tag, 'content') ?? ''));
436
+ const attr = metaAttr;
437
+ const { out: optOut, lastmod } = markers.get(page) ?? { out: false };
438
+ const decode = (v) => v.replace(/&(amp|quot|#39|lt|gt);/g, (_, e) => ({ amp: '&', quot: '"', '#39': "'", lt: '<', gt: '>' })[e]);
439
+ const pics = images ? [...new Set([...html.matchAll(/<img\b[^>]*>/gi)].map(([tag]) => tag)
440
+ .filter((tag) => attr(tag, 'alt') !== '')
441
+ .map((tag) => decode(attr(tag, 'src') ?? ''))
442
+ .filter((src) => src && !/^data:/i.test(src)))].slice(0, 1000) : [];
443
+ const alternates = [...html.matchAll(/<link\b[^>]*>/gi)].map(([tag]) => tag)
444
+ .filter((tag) => /(^|\s)alternate(\s|$)/i.test(attr(tag, 'rel') ?? '') && attr(tag, 'hreflang') && attr(tag, 'href'))
445
+ .map((tag) => ({ hreflang: attr(tag, 'hreflang'), href: decode(attr(tag, 'href')) }));
446
+ return { out: optOut || tags.some((tag) => attr(tag, 'name')?.toLowerCase() === 'robots' && /\bnoindex\b/i.test(attr(tag, 'content') ?? '')), ...(lastmod === undefined ? {} : { lastmod }), images: pics, alternates };
396
447
  };
397
- const pages = pageRoutes.filter((page) => page !== '/404' && page !== '/500' && !clientRoutes.includes(page) && !optedOut(page) && !exclude.some((re) => re.test(page)))
398
- .map((path) => ({ path, lastmod: dates.get(fileOf(path) ?? '') ?? epoch }));
399
- writeFileSync(resolve(out, 'sitemap.xml'), sitemapXml(options.site.url, builder.config.base, pages));
448
+ const pages = pageRoutes.filter((page) => page !== '/404' && page !== '/500' && !clientRoutes.includes(page))
449
+ .map((path) => ({ path, meta: sitemapMeta(path) }));
450
+ const keptOut = new Set(pages.filter(({ path, meta }) => meta.out || exclude.some((re) => re.test(path))).map((p) => p.path));
451
+ const listedPages = pages.filter(({ path }) => !keptOut.has(path));
452
+ const entries = listedPages.map(({ path, meta }) => ({ path, lastmod: meta.lastmod ?? dates.get(fileOf(path) ?? '') ?? epoch, images: meta.images, alternates: meta.alternates }));
453
+ const include = typeof options.sitemap === 'object' ? options.sitemap.include : undefined;
454
+ const extra = typeof include === 'function' ? await include() : include ?? [];
455
+ const listed = new Set(entries.map((p) => p.path));
456
+ for (const path of extra) {
457
+ if (typeof path !== 'string' || !path.startsWith('/'))
458
+ throw new Error(`clarusjs: sitemap.include: '${String(path)}' isn't a path (start it with /)`);
459
+ if (listed.has(path) || keptOut.has(path) || exclude.some((re) => re.test(path)))
460
+ continue;
461
+ entries.push({ path, lastmod: undefined, images: [], alternates: [] });
462
+ listed.add(path);
463
+ }
464
+ for (const { file, xml } of sitemapFiles(options.site.url, builder.config.base, entries))
465
+ writeFileSync(resolve(out, file), xml);
400
466
  }
401
467
  if (options.site && options.robots !== false && !existsSync(resolve(out, 'robots.txt'))) {
402
468
  const sitemap = options.sitemap !== false ? `\nSitemap: ${new URL('sitemap.xml', new URL(builder.config.base, options.site.url.replace(/\/?$/, '/'))).href}\n` : '';
@@ -510,7 +576,7 @@ export default function clarusjs(options = {}) {
510
576
  const clientUrl = urls
511
577
  ? urls.get(entryName(root, file)) ?? urls.get(relative(root, file).split(sep).join('/')) ?? urls.get(real(file))
512
578
  : command === 'build' ? `${CHUNK_TOKEN}[${entryName(root, file)}]__` : clientUrlFor(root, file);
513
- if (urls && !clientUrl && compile(code, { file, target: 'client' }).stateful) {
579
+ if (urls && !clientUrl && compile(code, { file, target: 'client', icon: iconsFor(file) }).stateful) {
514
580
  this.error(`${file}: stateful component is not under src/, so it has no client chunk`);
515
581
  }
516
582
  let parsed;
@@ -534,7 +600,7 @@ export default function clarusjs(options = {}) {
534
600
  const collapseWhitespace = command === 'build' && options.collapseWhitespace !== false;
535
601
  const loader = componentLoaderOf(root, file) ? relative(root, file).split(sep).join('/') : undefined;
536
602
  const hot = command === 'serve' && target === 'client' ? '/cl-hot.js' : undefined;
537
- const out = compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file), collapseWhitespace, loader, hot });
603
+ const out = compile(code, { file, target, clientUrl, renderImports, scope: scopeFor(root, file), collapseWhitespace, loader, hot, icon: iconsFor(file) });
538
604
  if (consumer === 'server' && !renderQuery)
539
605
  for (const w of out.warnings)
540
606
  this.warn(w.message);
@@ -565,6 +631,7 @@ export default function clarusjs(options = {}) {
565
631
  const file = resolve(outDir, `.${inBase.replace(/\/?$/, '/')}index.html`);
566
632
  if (file.startsWith(outDir + sep) && existsSync(file))
567
633
  req.url = base + file.slice(outDir.length + 1).replace(/\\/g, '/');
634
+ precompressed(req, res, outDir, base);
568
635
  }
569
636
  next();
570
637
  });
@@ -636,6 +703,30 @@ export default function clarusjs(options = {}) {
636
703
  },
637
704
  };
638
705
  }
706
+ function precompressed(req, res, outDir, base) {
707
+ if ((req.method !== 'GET' && req.method !== 'HEAD') || req.headers.range)
708
+ return;
709
+ const [path, query] = (req.url ?? '/').split('?');
710
+ if (!path.startsWith(base))
711
+ return;
712
+ let file;
713
+ try {
714
+ file = resolve(outDir, decodeURIComponent(path.slice(base.length)));
715
+ }
716
+ catch {
717
+ return;
718
+ }
719
+ if (!file.startsWith(outDir + sep) || !existsSync(file))
720
+ return;
721
+ const copies = ['br', 'gzip'].filter((enc) => existsSync(file + (enc === 'br' ? '.br' : '.gz')));
722
+ if (!copies.length)
723
+ return;
724
+ res.setHeader('Vary', 'Accept-Encoding');
725
+ const accept = String(req.headers['accept-encoding'] ?? '');
726
+ const pick = copies.find((enc) => acceptsEncoding(accept, enc));
727
+ if (pick)
728
+ req.url = `${path}${pick === 'br' ? '.br' : '.gz'}${query === undefined ? '' : `?${query}`}`;
729
+ }
639
730
  function precompress(dir) {
640
731
  for (const name of readdirSync(dir, { recursive: true })) {
641
732
  if (!/\.(html|js|css|svg|json|xml)$/.test(name))
@@ -5,8 +5,27 @@
5
5
  * @internal clarusjs's own build and server code call this; apps don't.
6
6
  */
7
7
  export declare function gitDates(root: string, dir: string): Map<string, number>;
8
- /** The sitemap: one <url> per page, under the site URL and base; lastmod (unix seconds) as a date when known. */
8
+ /**
9
+ * The sitemap: one <url> per page, under the site URL and base; lastmod (unix seconds) as a date when known; images
10
+ * (src as written, resolved against the page's URL) with Google's image extension; translations (hreflang alternates,
11
+ * href resolved the same way) as xhtml:link.
12
+ */
9
13
  export declare function sitemapXml(siteUrl: string, base: string, pages: {
10
14
  path: string;
11
15
  lastmod: number | undefined;
16
+ images?: string[];
17
+ alternates?: {
18
+ hreflang: string;
19
+ href: string;
20
+ }[];
12
21
  }[]): string;
22
+ /**
23
+ * The sitemap files to write: one sitemap.xml within the protocol's limits (50,000 URLs and 52,428,800 bytes
24
+ * uncompressed a file); past either, sitemap-1.xml, sitemap-2.xml… each within both, and sitemap.xml as their index,
25
+ * so robots.txt and search consoles keep one address. (A single page past the byte limit still gets a file alone.)
26
+ * @internal the build writes these; apps don't call it.
27
+ */
28
+ export declare function sitemapFiles(siteUrl: string, base: string, pages: Parameters<typeof sitemapXml>[2], max?: number, maxBytes?: number): {
29
+ file: string;
30
+ xml: string;
31
+ }[];
@@ -22,10 +22,34 @@ export function gitDates(root, dir) {
22
22
  }
23
23
  export function sitemapXml(siteUrl, base, pages) {
24
24
  const root = new URL(/^https?:\/\//i.test(base) ? new URL(base).pathname : base, siteUrl.replace(/\/?$/, '/'));
25
- const urls = pages.map(({ path, lastmod }) => {
25
+ const urls = pages.map(({ path, lastmod, images = [], alternates = [] }) => {
26
26
  const loc = new URL(`./${path.slice(1)}`, root).href;
27
27
  const date = lastmod === undefined ? '' : `<lastmod>${new Date(lastmod * 1000).toISOString().slice(0, 10)}</lastmod>`;
28
- return `<url><loc>${xml(loc)}</loc>${date}</url>\n`;
28
+ const pics = images.map((src) => `<image:image><image:loc>${xml(new URL(src, loc).href)}</image:loc></image:image>`).join('');
29
+ const alts = alternates.map((a) => `<xhtml:link rel="alternate" hreflang="${xml(a.hreflang)}" href="${xml(new URL(a.href, loc).href)}"/>`).join('');
30
+ return `<url><loc>${xml(loc)}</loc>${date}${alts}${pics}</url>\n`;
29
31
  });
30
- return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls.join('')}</urlset>\n`;
32
+ const ns = (pages.some((p) => p.alternates?.length) ? ' xmlns:xhtml="http://www.w3.org/1999/xhtml"' : '') + (pages.some((p) => p.images?.length) ? ' xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"' : '');
33
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"${ns}>\n${urls.join('')}</urlset>\n`;
34
+ }
35
+ export function sitemapFiles(siteUrl, base, pages, max = 50_000, maxBytes = 52_428_800) {
36
+ const envelope = Buffer.byteLength(sitemapXml(siteUrl, base, [])) + 200;
37
+ const chunks = [[]];
38
+ let bytes = envelope;
39
+ for (const page of pages) {
40
+ const size = Buffer.byteLength(sitemapXml(siteUrl, base, [page])) - envelope + 200;
41
+ const chunk = chunks.at(-1);
42
+ if (chunk.length && (chunk.length >= max || bytes + size > maxBytes)) {
43
+ chunks.push([]);
44
+ bytes = envelope;
45
+ }
46
+ chunks.at(-1).push(page);
47
+ bytes += size;
48
+ }
49
+ if (chunks.length === 1)
50
+ return [{ file: 'sitemap.xml', xml: sitemapXml(siteUrl, base, pages) }];
51
+ const parts = chunks.map((chunk, i) => ({ file: `sitemap-${i + 1}.xml`, xml: sitemapXml(siteUrl, base, chunk) }));
52
+ const root = new URL(/^https?:\/\//i.test(base) ? new URL(base).pathname : base, siteUrl.replace(/\/?$/, '/'));
53
+ const entries = parts.map((p) => `<sitemap><loc>${xml(new URL(p.file, root).href)}</loc></sitemap>\n`).join('');
54
+ return [...parts, { file: 'sitemap.xml', xml: `<?xml version="1.0" encoding="UTF-8"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${entries}</sitemapindex>\n` }];
31
55
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clarusjs",
3
- "version": "0.11.0",
3
+ "version": "0.13.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": [
@@ -43,6 +43,10 @@
43
43
  "types": "./dist/compiler/index.d.ts",
44
44
  "default": "./dist/compiler/index.js"
45
45
  },
46
+ "./icons": {
47
+ "types": "./dist/icons.d.ts",
48
+ "default": "./dist/icons.js"
49
+ },
46
50
  "./runtime": {
47
51
  "types": "./dist/runtime/index.d.ts",
48
52
  "default": "./dist/runtime/index.js"