@ninjainfosys/site-kit 0.0.0-stage → 0.2.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 (48) hide show
  1. package/README.md +99 -2
  2. package/bin/site-kit.mjs +24 -0
  3. package/package.json +40 -4
  4. package/src/components/blog/Pager.astro +60 -0
  5. package/src/components/blog/PostCard.astro +53 -0
  6. package/src/components/blog/PostList.astro +21 -0
  7. package/src/components/blog/Story.astro +63 -0
  8. package/src/components/blog/Topics.astro +23 -0
  9. package/src/components/seo/Seo.astro +46 -0
  10. package/src/components/site/CtaBand.astro +21 -0
  11. package/src/components/site/DashainPopup.astro +324 -0
  12. package/src/components/site/Faq.astro +37 -0
  13. package/src/components/site/Footer.astro +66 -0
  14. package/src/components/site/Header.astro +311 -0
  15. package/src/components/site/Related.astro +44 -0
  16. package/src/config.ts +56 -0
  17. package/src/contract.ts +181 -0
  18. package/src/integration.d.mts +4 -0
  19. package/src/integration.mjs +96 -0
  20. package/src/layouts/Base.astro +65 -0
  21. package/src/lib/blog-schema.ts +60 -0
  22. package/src/lib/blog.ts +64 -0
  23. package/src/lib/glossary-types.ts +25 -0
  24. package/src/lib/glossary.ts +21 -0
  25. package/src/lib/posts.ts +22 -0
  26. package/src/lib/rehype-figures.mjs +25 -0
  27. package/src/lib/seo.ts +176 -0
  28. package/src/pages/blog/[slug].astro +274 -0
  29. package/src/pages/blog/index.astro +111 -0
  30. package/src/pages/blog/page/[page].astro +32 -0
  31. package/src/pages/blog/tag/[tag].astro +38 -0
  32. package/src/pages/glossary/[slug].astro +125 -0
  33. package/src/pages/glossary/index.astro +51 -0
  34. package/src/pages/llms.txt.ts +25 -0
  35. package/src/pages/og/[...slug].png.ts +61 -0
  36. package/src/pages/rss.xml.ts +23 -0
  37. package/src/scripts/a11y.mjs +38 -0
  38. package/src/scripts/check-credits.mjs +31 -0
  39. package/src/scripts/check-site.mjs +198 -0
  40. package/src/scripts/commons.mjs +106 -0
  41. package/src/scripts/config.mjs +19 -0
  42. package/src/scripts/indexnow.mjs +25 -0
  43. package/src/scripts/redirects.mjs +55 -0
  44. package/src/scripts/sitemap.mjs +173 -0
  45. package/src/styles/base.css +164 -0
  46. package/src/styles/blog-serif.css +2 -0
  47. package/src/styles/motion.css +20 -0
  48. package/src/virtual.d.ts +4 -0
@@ -0,0 +1,96 @@
1
+ // The Astro integration every site adds: `integrations: [siteKit()]`. Plain
2
+ // JavaScript so Node can load it from node_modules when astro.config runs.
3
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { join } from 'node:path';
6
+ import { rehypeFigures } from './lib/rehype-figures.mjs';
7
+
8
+ const PACKAGE = '@ninjainfosys/site-kit';
9
+ const BLOG_IMAGES = 'virtual:site-kit/blog-images';
10
+ const IMAGE = /\.(jpe?g|png|webp|avif)$/i;
11
+
12
+ /**
13
+ * The images of the posts that will be published, as one module. A glob over
14
+ * src/assets/blog would also emit the images of draft posts (and of folders
15
+ * with no post yet) into dist; this lists only posts that ship. The dev server
16
+ * lists every post so drafts can be reviewed.
17
+ */
18
+ function blogImages(root, dev) {
19
+ const posts = join(root, 'src/content/blog');
20
+ const assets = join(root, 'src/assets/blog');
21
+ const ids = [];
22
+ if (existsSync(posts) && existsSync(assets)) {
23
+ for (const f of readdirSync(posts).filter((x) => x.endsWith('.md'))) {
24
+ const fm = readFileSync(join(posts, f), 'utf8').match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1] ?? '';
25
+ if (!dev && /^draft:\s*true\s*$/m.test(fm)) continue;
26
+ const slug = f.replace(/\.md$/, '');
27
+ const dir = join(assets, slug);
28
+ if (existsSync(dir)) for (const img of readdirSync(dir).filter((x) => IMAGE.test(x)).sort()) ids.push(`/src/assets/blog/${slug}/${img}`);
29
+ }
30
+ }
31
+ const imports = ids.map((id, i) => `import m${i} from ${JSON.stringify(id)};`).join('\n');
32
+ const entries = ids.map((id, i) => `${JSON.stringify(id)}: { default: m${i} }`).join(', ');
33
+ return `${imports}\nexport default { ${entries} };\n`;
34
+ }
35
+
36
+ // Pages that are the same on every site. The site turns one off with
37
+ // `siteKit({ pages: { glossary: false } })` and supplies its own.
38
+ /** @type {Record<import('./contract').PageName, { pattern: string; entrypoint: string }[]>} */
39
+ const PAGES = {
40
+ blog: [
41
+ { pattern: '/blog', entrypoint: 'blog/index.astro' },
42
+ { pattern: '/blog/[slug]', entrypoint: 'blog/[slug].astro' },
43
+ { pattern: '/blog/page/[page]', entrypoint: 'blog/page/[page].astro' },
44
+ { pattern: '/blog/tag/[tag]', entrypoint: 'blog/tag/[tag].astro' },
45
+ ],
46
+ glossary: [
47
+ { pattern: '/glossary', entrypoint: 'glossary/index.astro' },
48
+ { pattern: '/glossary/[slug]', entrypoint: 'glossary/[slug].astro' },
49
+ ],
50
+ og: [{ pattern: '/og/[...slug].png', entrypoint: 'og/[...slug].png.ts' }],
51
+ rss: [{ pattern: '/rss.xml', entrypoint: 'rss.xml.ts' }],
52
+ llms: [{ pattern: '/llms.txt', entrypoint: 'llms.txt.ts' }],
53
+ };
54
+
55
+ /**
56
+ * @param {import('./contract').SiteKitOptions} [options]
57
+ * @returns {import('astro').AstroIntegration}
58
+ */
59
+ export default function siteKit(options = {}) {
60
+ return {
61
+ name: PACKAGE,
62
+ hooks: {
63
+ 'astro:config:setup': ({ config, command, updateConfig, injectRoute }) => {
64
+ const root = fileURLToPath(config.root);
65
+ updateConfig({
66
+ markdown: { rehypePlugins: [rehypeFigures] },
67
+ vite: {
68
+ plugins: [
69
+ {
70
+ name: 'site-kit-blog-images',
71
+ resolveId: (id) => (id === BLOG_IMAGES ? `\0${BLOG_IMAGES}` : null),
72
+ load: (id) => (id === `\0${BLOG_IMAGES}` ? blogImages(root, command === 'dev') : null),
73
+ },
74
+ ],
75
+ resolve: {
76
+ // Kit code imports the site's own modules as '@site/...'.
77
+ alias: { '@site': join(root, 'src') },
78
+ // One copy of Astro and its runtime, whichever package a file lives in.
79
+ dedupe: ['astro'],
80
+ },
81
+ // The kit ships .astro and .ts source for Vite to compile. resvg is a
82
+ // native module used only at build time for share images; Vite must
83
+ // load it from node_modules instead of trying to bundle the .node file.
84
+ ssr: { noExternal: [PACKAGE], external: ['@resvg/resvg-js'] },
85
+ optimizeDeps: { exclude: ['@resvg/resvg-js'] },
86
+ build: { rollupOptions: { external: [/\.node$/] } },
87
+ },
88
+ });
89
+ for (const [name, routes] of Object.entries(PAGES)) {
90
+ if (options.pages?.[name] === false) continue;
91
+ for (const r of routes) injectRoute({ pattern: r.pattern, entrypoint: `${PACKAGE}/pages/${r.entrypoint}` });
92
+ }
93
+ },
94
+ },
95
+ };
96
+ }
@@ -0,0 +1,65 @@
1
+ ---
2
+ import DashainPopup from '../components/site/DashainPopup.astro';
3
+ // The site's stylesheet pulls in the kit's base.css and motion.css.
4
+ import '@site/styles/site.css';
5
+ import Seo from '../components/seo/Seo.astro';
6
+ import Header from '../components/site/Header.astro';
7
+ import Footer from '../components/site/Footer.astro';
8
+ import { kit } from '../config';
9
+
10
+ export interface Props {
11
+ title?: string;
12
+ description: string;
13
+ path: string;
14
+ image?: string;
15
+ imageAlt?: string;
16
+ type?: 'website' | 'article';
17
+ noindex?: boolean;
18
+ jsonLd?: object[];
19
+ published?: Date;
20
+ modified?: Date;
21
+ }
22
+
23
+ const props = Astro.props;
24
+ // Dashain popup kept for next season; `kit.dashain.enabled` shows it again.
25
+ const SHOW_DASHAIN_POPUP = kit.dashain?.enabled ?? false;
26
+ ---
27
+ <!doctype html>
28
+ <html lang="en">
29
+ <head>
30
+ <meta charset="utf-8" />
31
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
32
+ <meta name="theme-color" content="#FFFFFF" />
33
+ <meta name="color-scheme" content="light" />
34
+ {kit.head.preloadFonts.map((href) => <link rel="preload" href={href} as="font" type="font/woff2" crossorigin />)}
35
+ {kit.head.icons.map((i) => <link rel={i.rel} href={i.href} type={i.type} sizes={i.sizes} />)}
36
+ {kit.head.manifest && <link rel="manifest" href={kit.head.manifest} />}
37
+ <link rel="alternate" type="application/rss+xml" title={kit.blog.name} href="/rss.xml" />
38
+ <Seo {...props} />
39
+ <slot name="head" /><slot name="head-end" />
40
+ </head>
41
+ <body>
42
+ <a class="skip-link" href="#main">Skip to content</a>
43
+ <Header />
44
+ <main id="main">
45
+ <slot />
46
+ </main>
47
+ <Footer />
48
+ <slot name="scripts" />
49
+ <script>
50
+ // Fade sections in as they enter the viewport. Content is visible
51
+ // without this; it only runs when motion is allowed.
52
+ if (!matchMedia('(prefers-reduced-motion: reduce)').matches && 'IntersectionObserver' in window) {
53
+ const els = document.querySelectorAll('[data-reveal]');
54
+ const io = new IntersectionObserver((entries) => {
55
+ for (const e of entries) if (e.isIntersecting) { e.target.classList.add('is-in'); io.unobserve(e.target); }
56
+ }, { rootMargin: '0px', threshold: 0 });
57
+ const vh = innerHeight;
58
+ els.forEach((el) => { if (el.getBoundingClientRect().top > vh) io.observe(el); else el.classList.add('is-in'); });
59
+ document.documentElement.classList.add('reveal-ready');
60
+ }
61
+ </script>
62
+ {SHOW_DASHAIN_POPUP && <DashainPopup />}
63
+ <slot name="body-end" />
64
+ </body>
65
+ </html>
@@ -0,0 +1,60 @@
1
+ import { z } from 'astro/zod';
2
+
3
+ /**
4
+ * Licences a blog image may carry. All allow commercial use and changes
5
+ * (covers are cropped), so NC and ND licences are not accepted.
6
+ */
7
+ export const LICENCES = {
8
+ 'CC0 1.0': 'https://creativecommons.org/publicdomain/zero/1.0/',
9
+ 'Public domain': 'https://creativecommons.org/publicdomain/mark/1.0/',
10
+ 'CC BY 2.0': 'https://creativecommons.org/licenses/by/2.0/',
11
+ 'CC BY 2.5': 'https://creativecommons.org/licenses/by/2.5/',
12
+ 'CC BY 3.0': 'https://creativecommons.org/licenses/by/3.0/',
13
+ 'CC BY 4.0': 'https://creativecommons.org/licenses/by/4.0/',
14
+ 'CC BY-SA 2.0': 'https://creativecommons.org/licenses/by-sa/2.0/',
15
+ 'CC BY-SA 2.5': 'https://creativecommons.org/licenses/by-sa/2.5/',
16
+ 'CC BY-SA 3.0': 'https://creativecommons.org/licenses/by-sa/3.0/',
17
+ 'CC BY-SA 4.0': 'https://creativecommons.org/licenses/by-sa/4.0/',
18
+ 'Unsplash License': 'https://unsplash.com/license',
19
+ 'Pexels License': 'https://www.pexels.com/license/',
20
+ } as const;
21
+ export type Licence = keyof typeof LICENCES;
22
+
23
+ /**
24
+ * Credit for one image file in src/assets/blog/<slug>/. Third-party images
25
+ * carry title, author, source and licence (TASL) plus any changes made, as CC
26
+ * BY and BY-SA require. Our own diagrams set `own: true`.
27
+ * `pnpm check` fails when an image file has no credit.
28
+ */
29
+ export const creditSchema = z.union([
30
+ z.object({ file: z.string(), own: z.literal(true) }),
31
+ z.object({
32
+ file: z.string(),
33
+ title: z.string().min(2),
34
+ author: z.string().min(2),
35
+ authorUrl: z.string().url().optional(),
36
+ source: z.string().url(),
37
+ licence: z.enum(Object.keys(LICENCES) as [Licence, ...Licence[]]),
38
+ changes: z.string().optional(),
39
+ }),
40
+ ]);
41
+ export type Credit = z.infer<typeof creditSchema>;
42
+
43
+ export const postSchema = z.object({
44
+ title: z.string().min(10).max(90),
45
+ description: z.string().min(120).max(160),
46
+ date: z.coerce.date(),
47
+ updated: z.coerce.date().optional(),
48
+ tags: z.array(z.string().regex(/^[a-z0-9-]+$/)).min(1),
49
+ draft: z.boolean().default(false),
50
+ pillar: z.boolean().default(false),
51
+ image: z.string().optional(),
52
+ imageAlt: z.string().optional(),
53
+ coverAlt: z.string().optional(),
54
+ /** Three to five one-line points shown in a box under the cover. */
55
+ takeaways: z.array(z.string().min(10)).max(6).default([]),
56
+ /** Credits for every image file the post uses, cover included. */
57
+ credits: z.array(creditSchema).default([]),
58
+ /** Questions answered at the end of the post; also sent as FAQPage data. */
59
+ faq: z.array(z.object({ q: z.string().min(5), a: z.string().min(20) })).default([]),
60
+ });
@@ -0,0 +1,64 @@
1
+ // Only the constants module is read here, so this file stays light for tests.
2
+ import * as constants from '@site/config/site';
3
+
4
+ const TAG_ACRONYMS = ((constants as Record<string, unknown>)['TAG_ACRONYMS'] as readonly string[] | undefined) ?? [];
5
+
6
+ export const PAGE_SIZE = 10;
7
+
8
+ export interface PostLike {
9
+ id: string;
10
+ data: { title: string; date: Date; updated?: Date; tags: string[]; draft: boolean; pillar?: boolean };
11
+ }
12
+
13
+ /** Published posts, newest first. Drafts never reach pages, sitemap or RSS. */
14
+ export function published<T extends PostLike>(posts: T[]): T[] {
15
+ return posts.filter((p) => !p.data.draft).sort((a, b) => b.data.date.getTime() - a.data.date.getTime());
16
+ }
17
+
18
+ export function byTag<T extends PostLike>(posts: T[], tag: string): T[] {
19
+ return published(posts).filter((p) => p.data.tags.includes(tag));
20
+ }
21
+
22
+ export function allTags<T extends PostLike>(posts: T[]): string[] {
23
+ return [...new Set(published(posts).flatMap((p) => p.data.tags))].sort();
24
+ }
25
+
26
+ /** Page 1 is /blog; later pages are /blog/page/N. */
27
+ export const pagePath = (n: number) => (n <= 1 ? '/blog' : `/blog/page/${n}`);
28
+
29
+ /**
30
+ * Page numbers to show: first, last, and a window around the current page,
31
+ * with null where pages are skipped (rendered as an ellipsis).
32
+ */
33
+ export function pageWindow(current: number, last: number, around = 1): (number | null)[] {
34
+ const keep = new Set([1, last]);
35
+ for (let i = current - around; i <= current + around; i++) if (i >= 1 && i <= last) keep.add(i);
36
+ const sorted = [...keep].sort((a, b) => a - b);
37
+ const out: (number | null)[] = [];
38
+ sorted.forEach((n, i) => {
39
+ if (i > 0) {
40
+ const gap = n - sorted[i - 1];
41
+ if (gap === 2) out.push(n - 1);
42
+ else if (gap > 2) out.push(null);
43
+ }
44
+ out.push(n);
45
+ });
46
+ return out;
47
+ }
48
+
49
+ const acronyms = new RegExp(`\\b(${TAG_ACRONYMS.join('|')})\\b`, 'gi');
50
+ export const tagLabel = (tag: string) => {
51
+ const label = tag.replace(/-/g, ' ').replace(/^./, (c) => c.toUpperCase());
52
+ return TAG_ACRONYMS.length ? label.replace(acronyms, (w) => w.toUpperCase()) : label;
53
+ };
54
+
55
+ /** Posts sharing the most tags with `post`, excluding itself. */
56
+ export function related<T extends PostLike>(posts: T[], post: T, n = 3): T[] {
57
+ return published(posts)
58
+ .filter((p) => p.id !== post.id)
59
+ .map((p) => ({ p, score: p.data.tags.filter((t) => post.data.tags.includes(t)).length }))
60
+ .filter((x) => x.score > 0)
61
+ .sort((a, b) => b.score - a.score || b.p.data.date.getTime() - a.p.data.date.getTime())
62
+ .slice(0, n)
63
+ .map((x) => x.p);
64
+ }
@@ -0,0 +1,25 @@
1
+ export interface Term {
2
+ slug: string;
3
+ term: string;
4
+ /** Full name, when the term is an abbreviation. */
5
+ full?: string;
6
+ short: string;
7
+ body: string[];
8
+ related: string[];
9
+ /** Product page this term leads to. */
10
+ product?: string;
11
+ /** Other names people search for, marked up as alternate names. */
12
+ aka?: string[];
13
+ /** Day the term goes live (YYYY-MM-DD). Builds before this day leave it out; no date means always live. */
14
+ published?: string;
15
+ /** Date the long-form content was last revised (YYYY-MM-DD). */
16
+ updated?: string;
17
+ /** Search title, when the default "meaning and how it works" undersells the page. */
18
+ title?: string;
19
+ /** Meta description, when `short` is not the best search snippet. */
20
+ description?: string;
21
+ /** Long-form sections under their own headings, for terms people search in depth. */
22
+ sections?: { id: string; h: string; p: string[]; list?: string[] }[];
23
+ /** Questions people ask about the term, shown on the page and marked up as FAQ. */
24
+ faq?: { q: string; a: string }[];
25
+ }
@@ -0,0 +1,21 @@
1
+ // Glossary terms, one page each under /glossary. `short` is the
2
+ // one-or-two sentence definition that search engines and AI tools quote, so
3
+ // it must stand on its own. `body` explains it plainly for a business owner.
4
+ // One file per term in ./terms, picked up automatically; sorted by name.
5
+ export type { Term } from './glossary-types';
6
+ import type { Term } from './glossary-types';
7
+
8
+ const files = import.meta.glob<{ default: Term }>('@site/data/glossary/terms/*.ts', { eager: true });
9
+
10
+ // A term with a future `published` date stays out of the build until a rebuild
11
+ // on or after that day. SHOW_SCHEDULED=1 shows every term (local preview).
12
+ const today = new Date().toISOString().slice(0, 10);
13
+ const showAll = typeof process !== 'undefined' && process.env.SHOW_SCHEDULED === '1';
14
+ export const isLive = (t: Term) => showAll || !t.published || t.published <= today;
15
+
16
+ export const glossary: Term[] = Object.values(files)
17
+ .map((m) => m.default)
18
+ .filter(isLive)
19
+ .sort((a, b) => a.term.localeCompare(b.term));
20
+
21
+ export const termBySlug = (slug: string) => glossary.find((t) => t.slug === slug);
@@ -0,0 +1,22 @@
1
+ import { getCollection, type CollectionEntry } from 'astro:content';
2
+ import { published } from './blog';
3
+
4
+ export type Post = CollectionEntry<'blog'>;
5
+
6
+ /**
7
+ * Posts for pages. Drafts show on the dev server (marked) so the owner can
8
+ * review them; the production build leaves them out everywhere.
9
+ */
10
+ export async function posts(): Promise<Post[]> {
11
+ const all = await getCollection('blog');
12
+ if (import.meta.env.DEV) return all.sort((a, b) => b.data.date.getTime() - a.data.date.getTime());
13
+ return published(all);
14
+ }
15
+
16
+ export const fmtDate = (d: Date) => d.toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });
17
+
18
+ /** Minutes to read at 220 words a minute, never less than one. */
19
+ export const readMinutes = (p: Post) => Math.max(1, Math.round((p.body ?? '').split(/\s+/).filter(Boolean).length / 220));
20
+
21
+ /** The cover: the post's own image, else its generated share card. */
22
+ export const coverFor = (p: Post) => p.data.image ?? `/og/blog/${p.id}.png`;
@@ -0,0 +1,25 @@
1
+ // Markdown `![alt](img "caption")` alone in a paragraph becomes
2
+ // <figure><img><figcaption>caption</figcaption></figure>, so in-post photos
3
+ // carry a visible caption (and their short credit) under them.
4
+ export function rehypeFigures() {
5
+ const walk = (node) => {
6
+ if (!node.children) return;
7
+ node.children = node.children.map((child) => {
8
+ const kids = (child.children ?? []).filter((k) => !(k.type === 'text' && !k.value.trim()));
9
+ if (child.type === 'element' && child.tagName === 'p' && kids.length === 1 && kids[0].tagName === 'img' && kids[0].properties?.title) {
10
+ const img = kids[0];
11
+ const caption = String(img.properties.title);
12
+ delete img.properties.title;
13
+ return {
14
+ type: 'element',
15
+ tagName: 'figure',
16
+ properties: {},
17
+ children: [img, { type: 'element', tagName: 'figcaption', properties: {}, children: [{ type: 'text', value: caption }] }],
18
+ };
19
+ }
20
+ walk(child);
21
+ return child;
22
+ });
23
+ };
24
+ return (tree) => walk(tree);
25
+ }
package/src/lib/seo.ts ADDED
@@ -0,0 +1,176 @@
1
+ import { COMPANY, CONTACT_EMAIL, CONTACT_PHONE_JSONLD, LEGAL_ADDRESS, PARENT_COMPANY_ID, PARENT_COMPANY_NAME, PARENT_COMPANY_URL, SITE_NAME, SITE_URL, SOCIAL_PROFILES, kit } from '../config';
2
+
3
+ /** The one URL a page is known by: lowercase, no query, no .html, no trailing slash except root. */
4
+ export function canonicalFor(path: string): string {
5
+ let p = (path || '/').split(/[?#]/)[0].toLowerCase();
6
+ p = p.replace(/\.html$/, '').replace(/\/index$/, '/');
7
+ if (p !== '/') p = p.replace(/\/+$/, '');
8
+ if (!p.startsWith('/')) p = `/${p}`;
9
+ return p === '/' ? `${SITE_URL}/` : `${SITE_URL}${p}`;
10
+ }
11
+
12
+ export const abs = (path: string) => (path.startsWith('http') ? path : `${SITE_URL}${path.startsWith('/') ? '' : '/'}${path}`);
13
+
14
+ export function titleFor(page?: string): string {
15
+ if (!page || page === SITE_NAME) return SITE_NAME;
16
+ return `${page} · ${SITE_NAME}`;
17
+ }
18
+
19
+ export const ORG_ID = `${SITE_URL}/#organization`;
20
+
21
+ export function orgJsonLd() {
22
+ return {
23
+ '@context': 'https://schema.org',
24
+ '@type': 'Organization',
25
+ '@id': ORG_ID,
26
+ name: SITE_NAME,
27
+ ...(COMPANY ? { legalName: COMPANY } : {}),
28
+ url: `${SITE_URL}/`,
29
+ logo: abs(kit.seo.logo),
30
+ ...(SOCIAL_PROFILES ? { sameAs: [...SOCIAL_PROFILES] } : {}),
31
+ ...(PARENT_COMPANY_ID ? { parentOrganization: { '@type': 'Organization', '@id': PARENT_COMPANY_ID, name: PARENT_COMPANY_NAME, url: PARENT_COMPANY_URL } } : {}),
32
+ ...(CONTACT_EMAIL ? { email: CONTACT_EMAIL } : {}),
33
+ ...(CONTACT_PHONE_JSONLD ? { telephone: CONTACT_PHONE_JSONLD } : {}),
34
+ ...(LEGAL_ADDRESS
35
+ ? {
36
+ address: {
37
+ '@type': 'PostalAddress',
38
+ streetAddress: LEGAL_ADDRESS.street,
39
+ addressLocality: LEGAL_ADDRESS.locality,
40
+ addressRegion: LEGAL_ADDRESS.region,
41
+ postalCode: LEGAL_ADDRESS.postal,
42
+ addressCountry: LEGAL_ADDRESS.country,
43
+ },
44
+ }
45
+ : {}),
46
+ ...(kit.seo.contactPoint
47
+ ? {
48
+ contactPoint: {
49
+ '@type': 'ContactPoint',
50
+ contactType: kit.seo.contactPoint.contactType,
51
+ ...(CONTACT_PHONE_JSONLD ? { telephone: CONTACT_PHONE_JSONLD } : {}),
52
+ ...(CONTACT_EMAIL ? { email: CONTACT_EMAIL } : {}),
53
+ areaServed: kit.seo.contactPoint.areaServed,
54
+ availableLanguage: kit.seo.contactPoint.availableLanguage,
55
+ },
56
+ }
57
+ : {}),
58
+ };
59
+ }
60
+
61
+ export function websiteJsonLd() {
62
+ return {
63
+ '@context': 'https://schema.org',
64
+ '@type': 'WebSite',
65
+ '@id': `${SITE_URL}/#website`,
66
+ name: SITE_NAME,
67
+ url: `${SITE_URL}/`,
68
+ inLanguage: 'en',
69
+ publisher: { '@id': ORG_ID },
70
+ };
71
+ }
72
+
73
+ export function breadcrumbJsonLd(items: { name: string; path: string }[]) {
74
+ const all = [{ name: 'Home', path: '/' }, ...items];
75
+ return {
76
+ '@context': 'https://schema.org',
77
+ '@type': 'BreadcrumbList',
78
+ itemListElement: all.map((it, i) => ({
79
+ '@type': 'ListItem',
80
+ position: i + 1,
81
+ name: it.name,
82
+ item: canonicalFor(it.path),
83
+ })),
84
+ };
85
+ }
86
+
87
+ /** FAQ markup for questions shown on the page (never for hidden text). */
88
+ export function faqJsonLd(items: { q: string; a: string }[]) {
89
+ return {
90
+ '@context': 'https://schema.org',
91
+ '@type': 'FAQPage',
92
+ mainEntity: items.map((f) => ({ '@type': 'Question', name: f.q, acceptedAnswer: { '@type': 'Answer', text: f.a } })),
93
+ };
94
+ }
95
+
96
+ const ymd = (d: Date) => d.toISOString().slice(0, 10);
97
+
98
+ export function articleJsonLd(post: {
99
+ slug: string;
100
+ title: string;
101
+ description: string;
102
+ date: Date;
103
+ updated?: Date;
104
+ image: string;
105
+ tags?: string[];
106
+ words?: number;
107
+ }) {
108
+ return {
109
+ '@context': 'https://schema.org',
110
+ '@type': 'BlogPosting',
111
+ headline: post.title,
112
+ description: post.description,
113
+ datePublished: ymd(post.date),
114
+ dateModified: ymd(post.updated ?? post.date),
115
+ image: abs(post.image),
116
+ url: canonicalFor(`/blog/${post.slug}`),
117
+ mainEntityOfPage: canonicalFor(`/blog/${post.slug}`),
118
+ author: { '@type': 'Organization', '@id': ORG_ID, name: SITE_NAME },
119
+ publisher: { '@id': ORG_ID },
120
+ inLanguage: 'en',
121
+ ...(post.tags?.length ? { keywords: post.tags.map((t) => t.replace(/-/g, ' ')).join(', '), articleSection: post.tags[0].replace(/-/g, ' ') } : {}),
122
+ ...(post.words ? { wordCount: post.words } : {}),
123
+ about: { '@type': 'Thing', name: kit.blog.about },
124
+ };
125
+ }
126
+
127
+ /** The glossary as a set of defined terms. */
128
+ export function definedTermSetJsonLd(terms: { slug: string; term: string; short: string }[]) {
129
+ return {
130
+ '@context': 'https://schema.org',
131
+ '@type': 'DefinedTermSet',
132
+ '@id': `${SITE_URL}/glossary#set`,
133
+ name: kit.glossary.name,
134
+ url: canonicalFor('/glossary'),
135
+ hasDefinedTerm: terms.map((t) => ({ '@type': 'DefinedTerm', name: t.term, description: t.short, url: canonicalFor(`/glossary/${t.slug}`) })),
136
+ };
137
+ }
138
+
139
+ /** One glossary term. */
140
+ export function definedTermJsonLd(t: { slug: string; term: string; full?: string; aka?: string[]; short: string }) {
141
+ const alt = [...(t.full ? [t.full] : []), ...(t.aka ?? [])];
142
+ return {
143
+ '@context': 'https://schema.org',
144
+ '@type': 'DefinedTerm',
145
+ '@id': `${canonicalFor(`/glossary/${t.slug}`)}#term`,
146
+ name: t.term,
147
+ ...(alt.length ? { alternateName: alt.length === 1 ? alt[0] : alt } : {}),
148
+ description: t.short,
149
+ url: canonicalFor(`/glossary/${t.slug}`),
150
+ inDefinedTermSet: { '@type': 'DefinedTermSet', '@id': `${SITE_URL}/glossary#set`, name: kit.glossary.name, url: canonicalFor('/glossary') },
151
+ };
152
+ }
153
+
154
+ /** A long-form glossary page as an article about its term, for terms with sections. */
155
+ export function termArticleJsonLd(t: { slug: string; term: string; title: string; description: string; published: string; updated: string; sections: { id: string; h: string }[]; words: number }) {
156
+ const url = canonicalFor(`/glossary/${t.slug}`);
157
+ return {
158
+ '@context': 'https://schema.org',
159
+ '@type': 'TechArticle',
160
+ headline: t.title,
161
+ description: t.description,
162
+ url,
163
+ mainEntityOfPage: url,
164
+ image: abs(`/og/glossary/${t.slug}.png`),
165
+ datePublished: t.published,
166
+ dateModified: t.updated,
167
+ author: { '@type': 'Organization', '@id': ORG_ID, name: SITE_NAME },
168
+ publisher: { '@id': ORG_ID },
169
+ inLanguage: 'en',
170
+ about: { '@id': `${url}#term` },
171
+ articleSection: 'Glossary',
172
+ wordCount: t.words,
173
+ hasPart: t.sections.map((s) => ({ '@type': 'WebPageElement', name: s.h, url: `${url}#${s.id}` })),
174
+ };
175
+ }
176
+