@charmland/gem-vite 0.1.1 → 0.2.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.
package/dist/html.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Page, SiteDocument } from "@charmland/gem-compiler/types";
2
+ import type { ImageSize } from "./output.js";
2
3
  export interface DocumentHtmlOptions {
3
4
  site: SiteDocument;
4
5
  page: Page | null;
@@ -8,6 +9,8 @@ export interface DocumentHtmlOptions {
8
9
  client?: boolean;
9
10
  origin?: string | null;
10
11
  ogImage?: boolean;
12
+ /** Sniffed dimensions of a static `[site] og_image`, when local. */
13
+ staticImageSize?: ImageSize | null;
11
14
  /** The deployment mount path (`"/"` or `"/sub/"`); prefixes head URLs. */
12
15
  basePath?: string;
13
16
  }
package/dist/index.js CHANGED
@@ -1,11 +1,13 @@
1
1
  // src/index.ts
2
- import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
3
- import { createRequire as createRequire2 } from "node:module";
4
- import { extname, join as join2, relative, resolve, sep } from "node:path";
2
+ import { existsSync as existsSync4, readFileSync as readFileSync5 } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { extname as extname2, join as join3, relative as relative2, resolve as resolve4, sep as sep2 } from "node:path";
5
5
  import { performance } from "node:perf_hooks";
6
6
  import { CONFIG_NAMES, compileSite, loadConfig, normalizeBase, parseFrontmatter } from "@charmland/gem-compiler";
7
7
 
8
8
  // src/output.ts
9
+ import { existsSync, readFileSync } from "node:fs";
10
+ import { resolve } from "node:path";
9
11
  function markdownFile(route) {
10
12
  if (route === "/" || route === "")
11
13
  return "index.md";
@@ -37,6 +39,115 @@ function absoluteUrl(origin, route, base = "/") {
37
39
  return null;
38
40
  return `${origin.replace(/\/$/, "")}${withBase(base, route)}`;
39
41
  }
42
+ function assetUrl(origin, path, base = "/") {
43
+ if (/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(path))
44
+ return path;
45
+ const route = path.startsWith("/") ? path : `/${path}`;
46
+ return absoluteUrl(origin, route, base) ?? withBase(base, route);
47
+ }
48
+ function isRemote(value) {
49
+ return /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(value);
50
+ }
51
+ function publicAsset(publicDir, value) {
52
+ if (isRemote(value))
53
+ return null;
54
+ const relative = value.replace(/^\/+/, "").split(/[?#]/, 1)[0] ?? "";
55
+ if (!publicDir || !relative)
56
+ return null;
57
+ const candidate = resolve(publicDir, relative);
58
+ return existsSync(candidate) ? candidate : null;
59
+ }
60
+ function localAssetExists(publicDir, value) {
61
+ if (isRemote(value))
62
+ return true;
63
+ if (!publicDir)
64
+ return true;
65
+ return publicAsset(publicDir, value) !== null;
66
+ }
67
+ function readLocalAsset(publicDir, value) {
68
+ const path = publicAsset(publicDir, value);
69
+ if (!path)
70
+ return null;
71
+ try {
72
+ return readFileSync(path);
73
+ } catch {
74
+ return null;
75
+ }
76
+ }
77
+ function warnOnce(warn) {
78
+ const seen = new Set;
79
+ return (message) => {
80
+ if (seen.has(message))
81
+ return;
82
+ seen.add(message);
83
+ warn(message);
84
+ };
85
+ }
86
+ function imageSize(data) {
87
+ if (data.length >= 24 && data.readUInt32BE(0) === 2303741511) {
88
+ return { width: data.readUInt32BE(16), height: data.readUInt32BE(20) };
89
+ }
90
+ if (data.length >= 10 && data.subarray(0, 4).toString("ascii") === "GIF8") {
91
+ return { width: data.readUInt16LE(6), height: data.readUInt16LE(8) };
92
+ }
93
+ if (data.length >= 30 && data.subarray(0, 4).toString("ascii") === "RIFF" && data.subarray(8, 12).toString("ascii") === "WEBP") {
94
+ return webpSize(data);
95
+ }
96
+ if (data.length >= 4 && data[0] === 255 && data[1] === 216) {
97
+ return jpegSize(data);
98
+ }
99
+ return null;
100
+ }
101
+ function jpegSize(data) {
102
+ let offset = 2;
103
+ while (offset + 9 <= data.length) {
104
+ if (data[offset] !== 255) {
105
+ offset += 1;
106
+ continue;
107
+ }
108
+ const marker = data[offset + 1];
109
+ if (marker === undefined)
110
+ return null;
111
+ if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {
112
+ offset += 2;
113
+ continue;
114
+ }
115
+ const length = data.readUInt16BE(offset + 2);
116
+ const isSof = marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204;
117
+ if (isSof) {
118
+ return {
119
+ height: data.readUInt16BE(offset + 5),
120
+ width: data.readUInt16BE(offset + 7)
121
+ };
122
+ }
123
+ offset += 2 + length;
124
+ }
125
+ return null;
126
+ }
127
+ function webpSize(data) {
128
+ const chunk = data.subarray(12, 16).toString("ascii");
129
+ if (chunk === "VP8X") {
130
+ return {
131
+ width: 1 + data.readUIntLE(24, 3),
132
+ height: 1 + data.readUIntLE(27, 3)
133
+ };
134
+ }
135
+ if (chunk === "VP8 ") {
136
+ return {
137
+ width: data.readUInt16LE(26) & 16383,
138
+ height: data.readUInt16LE(28) & 16383
139
+ };
140
+ }
141
+ if (chunk === "VP8L") {
142
+ if (data[20] !== 47)
143
+ return null;
144
+ return {
145
+ width: 1 + ((data[22] & 63) << 8 | data[21]),
146
+ height: 1 + ((data[24] & 15) << 10 | data[23] << 2 | (data[22] & 192) >> 6)
147
+ };
148
+ }
149
+ return null;
150
+ }
40
151
  function ogFile(route) {
41
152
  if (route === "/" || route === "")
42
153
  return "og/index.png";
@@ -80,25 +191,77 @@ function llmsTxt(site, origin, base = "/") {
80
191
  }
81
192
  lines.push("");
82
193
  }
194
+ const full = absoluteUrl(origin, "/llms-full.txt", base) ?? withBase(base, "/llms-full.txt");
195
+ lines.push(`## Full text`, "", `- [Every page inlined](${full})`, "");
83
196
  return `${lines.join(`
84
197
  `)}
85
198
  `;
86
199
  }
87
- function jsonLd(site, page, origin, base = "/") {
200
+ function llmsFullTxt(site, bodies, origin, base = "/") {
201
+ const lines = [`# ${site.site.title}`, ""];
202
+ if (site.site.description)
203
+ lines.push(`> ${site.site.description}`, "");
204
+ const collections = [];
205
+ for (const doc of site.docs) {
206
+ const sections = [];
207
+ for (const item of flatten(doc.nav)) {
208
+ const body = bodies.get(item.route)?.trim();
209
+ if (!body)
210
+ continue;
211
+ const url = absoluteUrl(origin, item.route, base) ?? withBase(base, markdownRoute(item.route));
212
+ sections.push(`### [${item.title}](${url})
213
+
214
+ ${body}`);
215
+ }
216
+ if (sections.length > 0)
217
+ collections.push(`## ${doc.label}
218
+
219
+ ${sections.join(`
220
+
221
+ ---
222
+
223
+ `)}`);
224
+ }
225
+ if (collections.length > 0)
226
+ lines.push(collections.join(`
227
+
228
+ ---
229
+
230
+ `), "");
231
+ return `${lines.join(`
232
+ `).trimEnd()}
233
+ `;
234
+ }
235
+ function jsonLd(site, page, origin, base = "/", image = null) {
88
236
  const url = page ? absoluteUrl(origin, page.route, base) : base && base !== "/" ? absoluteUrl(origin, "/", base) : origin;
89
- const data = page ? {
237
+ const home = absoluteUrl(origin, "/", base) ?? origin;
238
+ const language = site.seo.locale ? site.seo.locale.replace(/_/g, "-") : site.site.lang || undefined;
239
+ const publisher = {
240
+ "@type": "Organization",
241
+ name: site.seo.publisher || site.site.title,
242
+ ...home ? { url: home } : {}
243
+ };
244
+ const isHome = !page || page.isIndex || page.route === (site.docs[0]?.root ?? "/");
245
+ const data = isHome ? {
90
246
  "@context": "https://schema.org",
91
- "@type": "TechArticle",
92
- headline: page.title,
93
- description: page.description || page.summary || site.site.description,
247
+ "@type": "WebSite",
248
+ name: page ? page.title : site.site.title,
249
+ description: page && (page.description || page.summary) || site.site.description,
94
250
  url: url ?? undefined,
95
- isPartOf: { "@type": "WebSite", name: site.site.title }
251
+ inLanguage: language,
252
+ image: image ?? undefined,
253
+ publisher
96
254
  } : {
97
255
  "@context": "https://schema.org",
98
- "@type": "WebSite",
99
- name: site.site.title,
100
- description: site.site.description,
101
- url: url ?? undefined
256
+ "@type": "TechArticle",
257
+ headline: page?.title,
258
+ description: page && (page.description || page.summary) || site.site.description,
259
+ url: url ?? undefined,
260
+ isPartOf: { "@type": "WebSite", name: site.site.title },
261
+ mainEntityOfPage: url ? { "@type": "WebPage", "@id": url } : undefined,
262
+ inLanguage: language,
263
+ image: image ?? undefined,
264
+ publisher
102
265
  };
103
266
  return JSON.stringify(data).replace(/</g, "\\u003c");
104
267
  }
@@ -133,6 +296,34 @@ function landingRedirect(route) {
133
296
  `);
134
297
  }
135
298
 
299
+ // src/theme.ts
300
+ import { relative, resolve as resolve2, sep } from "node:path";
301
+
302
+ // src/paths.ts
303
+ function joinBase(base, file) {
304
+ return `${base.replace(/\/$/, "")}/${file.replace(/^\//, "")}`;
305
+ }
306
+
307
+ // src/theme.ts
308
+ var THEME_JS = "@charmland/gem/theme.js";
309
+ var THEME_CSS = "@charmland/gem/theme.css";
310
+ var FONT_ORIGIN = "https://stuff.charm.land";
311
+ var FONT_CSS = `${FONT_ORIGIN}/fonts/charmform/charmform.css`;
312
+ function devStyles(content, root, configuredEntry) {
313
+ const styles = [];
314
+ if (content.theme.css)
315
+ styles.push(joinBase(content.base, cssUrl(root, content.theme.css)));
316
+ if (!configuredEntry && !content.theme.entry) {
317
+ styles.push(joinBase(content.base, `@id/${THEME_CSS}`));
318
+ }
319
+ return styles;
320
+ }
321
+ function cssUrl(root, css) {
322
+ const file = resolve2(root, css);
323
+ const path = relative(root, file).split(sep).join("/");
324
+ return path.startsWith("..") ? `@fs${file.split(sep).join("/")}` : path;
325
+ }
326
+
136
327
  // src/html.ts
137
328
  function routeFile(route) {
138
329
  if (route === "/" || route === "")
@@ -149,15 +340,32 @@ function documentHtml(options) {
149
340
  client = false,
150
341
  origin = null,
151
342
  ogImage = false,
343
+ staticImageSize = null,
152
344
  basePath = "/"
153
345
  } = options;
154
346
  const meta = site.site;
347
+ const seo = site.seo;
155
348
  const landing = site.docs[0]?.root ?? "/";
156
349
  const title = page && page.route !== landing ? `${page.title} - ${meta.title}` : meta.title;
157
350
  const description = page && page.description || meta.description || "";
158
351
  const canonical = page ? absoluteUrl(origin, page.route, basePath) : basePath && basePath !== "/" ? absoluteUrl(origin, "/", basePath) : origin;
159
- const image = ogImage && page ? absoluteUrl(origin, ogRoute(page.route), basePath) : null;
352
+ const generatedImage = !meta.ogImage && ogImage && page !== null;
353
+ const image = meta.ogImage ? assetUrl(origin, meta.ogImage, basePath) : generatedImage && page ? absoluteUrl(origin, ogRoute(page.route), basePath) : null;
354
+ const imageType = generatedImage ? "image/png" : image ? imageTypeOf(image) : null;
355
+ const imageWidth = image ? generatedImage ? site.og.width : seo.imageWidth ?? staticImageSize?.width ?? null : null;
356
+ const imageHeight = image ? generatedImage ? site.og.height : seo.imageHeight ?? staticImageSize?.height ?? null : null;
357
+ const imageAlt = image ? imageAltOf(seo.imageAlt, page, meta.title) : null;
358
+ const locale = (seo.locale ?? localeFromLang(meta.lang))?.replace("-", "_") ?? null;
359
+ const favicon = meta.favicon ? assetUrl(origin, meta.favicon, basePath) : null;
360
+ const ogType = !page || page.isIndex || page.route === landing ? "website" : "article";
361
+ const twitterCard = seo.twitterCard ?? (image ? "summary_large_image" : "summary");
160
362
  const keywords = page && page.tags.length ? page.tags.join(", ") : "";
363
+ const extraMeta = seo.meta.map((tag) => {
364
+ const key = tag.property ? "property" : "name";
365
+ const value = tag.property ?? tag.name ?? "";
366
+ return `<meta ${key}="${escapeAttribute(value)}" content="${escapeAttribute(tag.content)}" />`;
367
+ }).join(`
368
+ `);
161
369
  const allowSystem = site.theme?.system ? "true" : "false";
162
370
  const modeScript = `<script>(function(){try{` + `var p=localStorage.getItem("gem-theme"),s=${allowSystem};` + `if(p!=="light"&&p!=="dark"&&p!=="system")p="system";` + `var t=p==="system"?(!window.matchMedia||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"):p;` + `var r=document.documentElement;r.setAttribute("data-theme",t);r.style.colorScheme=t` + `}catch(e){}})()</script>`;
163
371
  return `<!doctype html>
@@ -168,22 +376,38 @@ function documentHtml(options) {
168
376
  <title>${escapeHtml(title)}</title>
169
377
  ${description ? `<meta name="description" content="${escapeAttribute(description)}" />` : ""}
170
378
  ${keywords ? `<meta name="keywords" content="${escapeAttribute(keywords)}" />` : ""}
171
- <meta name="robots" content="index, follow" />
379
+ <meta name="robots" content="${escapeAttribute(seo.robots)}" />
380
+ ${seo.themeColor ? `<meta name="theme-color" content="${escapeAttribute(seo.themeColor)}" />` : ""}
172
381
  ${canonical ? `<link rel="canonical" href="${escapeAttribute(canonical)}" />` : ""}
173
- <meta property="og:type" content="article" />
382
+ ${favicon ? `<link rel="icon" href="${escapeAttribute(favicon)}" />` : ""}
383
+ ${extraMeta}
384
+ <meta property="og:type" content="${ogType}" />
174
385
  <meta property="og:site_name" content="${escapeAttribute(meta.title)}" />
175
386
  <meta property="og:title" content="${escapeAttribute(title)}" />
176
387
  ${description ? `<meta property="og:description" content="${escapeAttribute(description)}" />` : ""}
177
388
  ${canonical ? `<meta property="og:url" content="${escapeAttribute(canonical)}" />` : ""}
389
+ ${locale ? `<meta property="og:locale" content="${escapeAttribute(locale)}" />` : ""}
390
+ ${seo.localeAlternates.map((alternate) => `<meta property="og:locale:alternate" content="${escapeAttribute(alternate)}" />`).join(`
391
+ `)}
178
392
  ${image ? `<meta property="og:image" content="${escapeAttribute(image)}" />` : ""}
179
- <meta name="twitter:card" content="${image ? "summary_large_image" : "summary"}" />
393
+ ${imageAlt ? `<meta property="og:image:alt" content="${escapeAttribute(imageAlt)}" />` : ""}
394
+ ${imageType ? `<meta property="og:image:type" content="${escapeAttribute(imageType)}" />` : ""}
395
+ ${imageWidth ? `<meta property="og:image:width" content="${String(imageWidth)}" />` : ""}
396
+ ${imageHeight ? `<meta property="og:image:height" content="${String(imageHeight)}" />` : ""}
397
+ <meta name="twitter:card" content="${escapeAttribute(twitterCard)}" />
180
398
  <meta name="twitter:title" content="${escapeAttribute(title)}" />
181
399
  ${description ? `<meta name="twitter:description" content="${escapeAttribute(description)}" />` : ""}
400
+ ${seo.twitterSite ? `<meta name="twitter:site" content="${escapeAttribute(seo.twitterSite)}" />` : ""}
401
+ ${seo.twitterCreator ? `<meta name="twitter:creator" content="${escapeAttribute(seo.twitterCreator)}" />` : ""}
182
402
  ${image ? `<meta name="twitter:image" content="${escapeAttribute(image)}" />` : ""}
183
- <script type="application/ld+json">${jsonLd(site, page, origin, basePath)}</script>
403
+ ${imageAlt ? `<meta name="twitter:image:alt" content="${escapeAttribute(imageAlt)}" />` : ""}
404
+ <script type="application/ld+json">${jsonLd(site, page, origin, basePath, image)}</script>
184
405
  ${modeScript}
185
406
  ${styles.map((href) => `<link rel="stylesheet" href="${escapeAttribute(href)}" />`).join(`
186
407
  `)}
408
+ <link rel="preconnect" href="${FONT_ORIGIN}" crossorigin />
409
+ <link rel="stylesheet" href="${FONT_CSS}" media="print" onload="this.media='all'" />
410
+ <noscript><link rel="stylesheet" href="${FONT_CSS}" /></noscript>
187
411
  ${client ? `<script type="module" src="${escapeAttribute(clientScript(basePath))}"></script>` : ""}
188
412
  </head>
189
413
  <body>${body}</body>
@@ -192,6 +416,26 @@ function documentHtml(options) {
192
416
  </html>
193
417
  `;
194
418
  }
419
+ function localeFromLang(lang) {
420
+ return /^[a-z]{2}[-_][a-z]{2}$/i.test(lang) ? lang.replace("-", "_") : null;
421
+ }
422
+ function imageAltOf(configured, page, siteTitle) {
423
+ const pageTitle = page ? page.title : siteTitle;
424
+ return (configured ?? "{title}").replace(/\{title\}/g, () => pageTitle).replace(/\{site\}/g, () => siteTitle);
425
+ }
426
+ var IMAGE_TYPES = {
427
+ png: "image/png",
428
+ jpg: "image/jpeg",
429
+ jpeg: "image/jpeg",
430
+ webp: "image/webp",
431
+ gif: "image/gif",
432
+ avif: "image/avif",
433
+ svg: "image/svg+xml"
434
+ };
435
+ function imageTypeOf(src) {
436
+ const match = /\.([a-z0-9]+)(?:[?#]|$)/i.exec(src);
437
+ return match ? IMAGE_TYPES[match[1].toLowerCase()] ?? null : null;
438
+ }
195
439
  function escapeHtml(value) {
196
440
  return String(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
197
441
  }
@@ -204,62 +448,231 @@ function clientScript(basePath) {
204
448
  }
205
449
 
206
450
  // src/og.ts
207
- import { readFileSync } from "node:fs";
208
- import { createRequire } from "node:module";
209
- import { join } from "node:path";
210
- var WIDTH = 1200;
211
- var HEIGHT = 630;
212
- var FONT_FAMILY = "Fraktion";
213
- function require_(root) {
214
- return createRequire(join(root, "package.json"));
215
- }
216
- var fontData = null;
217
- var fontLoaded = false;
218
- function loadFont(root) {
219
- if (fontLoaded)
220
- return fontData;
221
- fontLoaded = true;
451
+ import { readFileSync as readFileSync2, statSync } from "node:fs";
452
+ import { join, resolve as resolve3 } from "node:path";
453
+ var DEFAULT_FONT_FAMILY = "Charmform Web";
454
+ var CUSTOM_FONT_FAMILY = "GemCover";
455
+ var REMOTE_TIMEOUT_MS = 1e4;
456
+ var fonts = new Map;
457
+ function readFont(path) {
222
458
  try {
223
- const path = require_(root).resolve("@charmland/gem/fonts/PPFraktionSans-Variable.ttf");
224
- fontData = readFileSync(path);
459
+ const mtime = statSync(path).mtimeMs;
460
+ const key = `${path}:${mtime}`;
461
+ const cached = fonts.get(key);
462
+ if (cached)
463
+ return cached;
464
+ const data = readFileSync2(path);
465
+ const entry = { data, mtime };
466
+ fonts.set(key, entry);
467
+ return entry;
225
468
  } catch {
226
- fontData = null;
469
+ return null;
470
+ }
471
+ }
472
+ var remoteFont = null;
473
+ async function fetchOk(url) {
474
+ const response = await fetch(url, { signal: AbortSignal.timeout(REMOTE_TIMEOUT_MS) });
475
+ if (!response.ok)
476
+ throw new Error(`${response.status} ${response.statusText}`);
477
+ return response;
478
+ }
479
+ async function remoteDefaultFont(warn) {
480
+ try {
481
+ const css = await (await fetchOk(FONT_CSS)).text();
482
+ const match = /url\(\s*["']?([^"')]+)["']?\s*\)/.exec(css);
483
+ if (!match?.[1])
484
+ throw new Error("the stylesheet names no font file");
485
+ const src = new URL(match[1], FONT_CSS).href;
486
+ const data = Buffer.from(await (await fetchOk(src)).arrayBuffer());
487
+ return { path: src, data, mtime: 0, name: DEFAULT_FONT_FAMILY, weight: null, style: null };
488
+ } catch (error) {
489
+ const reason = error instanceof Error ? error.message : String(error);
490
+ warn(`og: default cover font unavailable (${reason}); covers use the fallback face`);
491
+ return null;
492
+ }
493
+ }
494
+ var defaultFont = (warn) => {
495
+ remoteFont ??= remoteDefaultFont(warn);
496
+ return remoteFont;
497
+ };
498
+ async function resolveFonts(root, site, warn, loadDefault) {
499
+ const og = site.og;
500
+ const declared = og.fonts.length ? og.fonts.map((font) => ({
501
+ src: font.src,
502
+ name: font.name ?? og.fontName ?? CUSTOM_FONT_FAMILY,
503
+ weight: font.weight,
504
+ style: font.style
505
+ })) : og.font ? [
506
+ {
507
+ src: og.font,
508
+ name: og.fontName ?? CUSTOM_FONT_FAMILY,
509
+ weight: null,
510
+ style: null
511
+ }
512
+ ] : [];
513
+ const loaded = [];
514
+ for (const font of declared) {
515
+ const path = resolve3(root, font.src);
516
+ const entry = readFont(path);
517
+ if (!entry) {
518
+ warn(`og: font "${font.src}" not found; skipping it`);
519
+ continue;
520
+ }
521
+ loaded.push({
522
+ path,
523
+ data: entry.data,
524
+ mtime: entry.mtime,
525
+ name: font.name,
526
+ weight: font.weight,
527
+ style: font.style
528
+ });
227
529
  }
228
- return fontData;
530
+ if (loaded.length > 0)
531
+ return loaded;
532
+ const fallback = await loadDefault(warn);
533
+ return fallback ? [fallback] : [];
229
534
  }
230
- var renderer = null;
231
- function loadRenderer(font) {
232
- renderer ??= (async () => {
535
+ var renderers = new Map;
536
+ function loadRenderer(fonts) {
537
+ const key = fonts.map((font) => `${font.path}:${font.mtime}:${font.name}:${font.weight ?? ""}:${font.style ?? ""}`).join("|");
538
+ const existing = renderers.get(key);
539
+ if (existing)
540
+ return existing;
541
+ const pending = (async () => {
233
542
  const { Renderer } = await import("@takumi-rs/core");
234
543
  const instance = new Renderer;
235
- await instance.registerFont({ name: FONT_FAMILY, data: font });
544
+ for (const font of fonts) {
545
+ await instance.registerFont({
546
+ name: font.name,
547
+ data: font.data,
548
+ ...font.weight !== null ? { weight: font.weight } : {},
549
+ ...font.style !== null ? { style: font.style } : {}
550
+ });
551
+ }
236
552
  return instance;
237
553
  })().catch((error) => {
238
- renderer = null;
554
+ renderers.delete(key);
239
555
  throw error;
240
556
  });
241
- return renderer;
557
+ renderers.set(key, pending);
558
+ return pending;
242
559
  }
243
- async function renderOgImage(site, page, root) {
244
- const font = loadFont(root);
245
- if (!font)
246
- return null;
247
- const accent = site.theme.accent || "#b8461f";
560
+ function textFor(node, site, page) {
561
+ switch (node.field) {
562
+ case "title":
563
+ return page ? page.title : site.site.title;
564
+ case "site":
565
+ return site.site.title;
566
+ case "description":
567
+ return page && (page.description || page.summary) || site.site.description;
568
+ case "route":
569
+ return page ? page.route : "/";
570
+ case "category":
571
+ return page?.category ?? "";
572
+ case "literal":
573
+ return node.text ?? "";
574
+ }
575
+ }
576
+ async function coverNode(site, page, options) {
577
+ const og = site.og;
578
+ const warn = options.warn ?? (() => {});
579
+ const custom = og.text.length > 0 || og.images.length > 0;
580
+ if (!custom)
581
+ return builtinNode(site, page, options.family);
582
+ const children = [];
583
+ for (const image of og.images) {
584
+ const src = image.src.replace(/\{logo_image\}/g, () => site.site.logoImage ?? "");
585
+ if (!src) {
586
+ warn(`og: image "${image.src}" has no value for {logo_image}`);
587
+ continue;
588
+ }
589
+ const data = await options.loadImage(src);
590
+ if (!data)
591
+ continue;
592
+ children.push(imageNode(image, data));
593
+ }
594
+ for (const text of og.text) {
595
+ const value = textFor(text, site, page);
596
+ if (!value)
597
+ continue;
598
+ children.push(textNode(text, value, options.family));
599
+ }
600
+ return {
601
+ type: "container",
602
+ style: {
603
+ position: "relative",
604
+ width: og.width,
605
+ height: og.height,
606
+ boxSizing: "border-box",
607
+ backgroundColor: og.background,
608
+ color: "#f5f0e8",
609
+ fontFamily: options.family
610
+ },
611
+ children
612
+ };
613
+ }
614
+ function textNode(text, value, family) {
615
+ return {
616
+ type: "text",
617
+ text: value,
618
+ style: {
619
+ position: "absolute",
620
+ left: text.x,
621
+ top: text.y,
622
+ width: text.width ?? undefined,
623
+ height: text.height ?? undefined,
624
+ overflow: text.height !== null ? "hidden" : undefined,
625
+ fontFamily: family,
626
+ fontSize: text.fontSize ?? 32,
627
+ fontWeight: text.fontWeight ?? undefined,
628
+ lineHeight: text.lineHeight ?? undefined,
629
+ letterSpacing: text.letterSpacing ?? undefined,
630
+ color: text.color ?? "#f5f0e8",
631
+ textAlign: text.align,
632
+ opacity: text.opacity ?? undefined,
633
+ fontStyle: text.fontStyle ?? undefined,
634
+ ...text.family ? { fontFamily: text.family } : {}
635
+ }
636
+ };
637
+ }
638
+ function imageNode(image, src) {
639
+ return {
640
+ type: "image",
641
+ src,
642
+ width: image.width,
643
+ height: image.height,
644
+ style: {
645
+ position: "absolute",
646
+ left: image.x,
647
+ top: image.y,
648
+ width: image.width,
649
+ height: image.height,
650
+ objectFit: image.fit,
651
+ borderRadius: image.radius ?? undefined,
652
+ opacity: image.opacity ?? undefined
653
+ }
654
+ };
655
+ }
656
+ function builtinNode(site, page, family) {
657
+ const og = site.og;
658
+ const accent = og.accent || site.theme.accent || "#b8461f";
248
659
  const title = page ? page.title : site.site.title;
249
660
  const eyebrow = page ? site.site.title : site.site.description || site.site.title;
250
- const node = {
661
+ const scale = Math.max(0.4, Math.min(og.width / 1200, og.height / 630));
662
+ const size = (value) => Math.round(value * scale);
663
+ return {
251
664
  type: "container",
252
665
  style: {
253
- width: WIDTH,
254
- height: HEIGHT,
666
+ width: og.width,
667
+ height: og.height,
255
668
  display: "flex",
256
669
  flexDirection: "column",
257
670
  justifyContent: "space-between",
258
671
  boxSizing: "border-box",
259
- padding: "72px 80px",
260
- backgroundColor: "#141414",
672
+ padding: `${size(72)}px ${size(80)}px`,
673
+ backgroundColor: og.background,
261
674
  color: "#f5f0e8",
262
- fontFamily: FONT_FAMILY
675
+ fontFamily: family
263
676
  },
264
677
  children: [
265
678
  {
@@ -267,8 +680,8 @@ async function renderOgImage(site, page, root) {
267
680
  style: {
268
681
  display: "flex",
269
682
  alignItems: "center",
270
- gap: "20px",
271
- fontSize: 30,
683
+ gap: `${size(20)}px`,
684
+ fontSize: size(30),
272
685
  color: "#a8a29e"
273
686
  },
274
687
  children: [
@@ -276,10 +689,10 @@ async function renderOgImage(site, page, root) {
276
689
  type: "container",
277
690
  style: {
278
691
  display: "flex",
279
- width: "52px",
280
- height: "10px",
692
+ width: `${size(52)}px`,
693
+ height: `${size(10)}px`,
281
694
  backgroundColor: accent,
282
- borderRadius: "5px"
695
+ borderRadius: `${size(5)}px`
283
696
  }
284
697
  },
285
698
  { type: "text", text: eyebrow }
@@ -289,7 +702,7 @@ async function renderOgImage(site, page, root) {
289
702
  type: "container",
290
703
  style: {
291
704
  display: "flex",
292
- fontSize: title.length > 48 ? 62 : 76,
705
+ fontSize: size(title.length > 48 ? 62 : 76),
293
706
  lineHeight: 1.1,
294
707
  letterSpacing: "-0.02em"
295
708
  },
@@ -297,21 +710,115 @@ async function renderOgImage(site, page, root) {
297
710
  },
298
711
  {
299
712
  type: "container",
300
- style: { display: "flex", fontSize: 26, color: "#78716c" },
713
+ style: { display: "flex", fontSize: size(26), color: "#78716c" },
301
714
  children: [{ type: "text", text: page ? page.route : "/" }]
302
715
  }
303
716
  ]
304
717
  };
718
+ }
719
+ function coverImageLoader(root, warn, publicDir = join(root, "public")) {
720
+ const cache = new Map;
721
+ const load = async (src) => {
722
+ if (/^data:/i.test(src)) {
723
+ const match = /^data:([^;,]*)(;base64)?,([\s\S]*)$/i.exec(src);
724
+ if (!match) {
725
+ warn("og: malformed data: image URL");
726
+ return null;
727
+ }
728
+ const payload = match[3] ?? "";
729
+ if (match[2] && !/^[a-z0-9+/=\s]+$/i.test(payload)) {
730
+ warn("og: malformed data: image URL");
731
+ return null;
732
+ }
733
+ try {
734
+ const bytes = new Uint8Array(Buffer.from(match[2] ? payload : decodeURIComponent(payload), match[2] ? "base64" : "utf8"));
735
+ if (bytes.length === 0) {
736
+ warn("og: malformed data: image URL");
737
+ return null;
738
+ }
739
+ return bytes;
740
+ } catch {
741
+ warn("og: malformed data: image URL");
742
+ return null;
743
+ }
744
+ }
745
+ if (/^https?:/i.test(src)) {
746
+ try {
747
+ const response = await fetch(src, {
748
+ signal: AbortSignal.timeout(REMOTE_TIMEOUT_MS)
749
+ });
750
+ if (!response.ok)
751
+ throw new Error(`HTTP ${response.status}`);
752
+ return new Uint8Array(await response.arrayBuffer());
753
+ } catch (error) {
754
+ const message = error instanceof Error ? error.message : String(error);
755
+ warn(`og: could not fetch "${src}": ${message}`);
756
+ return null;
757
+ }
758
+ }
759
+ const relative = src.replace(/^\/+/, "").split(/[?#]/, 1)[0] ?? "";
760
+ const bases = publicDir ? [publicDir, root] : [root];
761
+ for (const base of bases) {
762
+ try {
763
+ return readFileSync2(resolve3(base, relative));
764
+ } catch {}
765
+ }
766
+ warn(`og: image "${src}" not found`);
767
+ return null;
768
+ };
769
+ return async (src) => {
770
+ if (cache.has(src))
771
+ return cache.get(src) ?? null;
772
+ const value = await load(src);
773
+ cache.set(src, value);
774
+ return value;
775
+ };
776
+ }
777
+ async function renderOgImage(site, page, root, onWarn, loadImage, loadDefaultFont = defaultFont) {
778
+ const warn = onWarn ?? (() => {});
779
+ const og = site.og;
780
+ const fonts = await resolveFonts(root, site, warn, loadDefaultFont);
781
+ const node = await coverNode(site, page, {
782
+ family: fonts[0]?.name ?? DEFAULT_FONT_FAMILY,
783
+ loadImage: loadImage ?? coverImageLoader(root, warn),
784
+ warn
785
+ });
305
786
  try {
306
- const takumi = await loadRenderer(font);
307
- return await takumi.render(node, { width: WIDTH, height: HEIGHT, format: "png" });
308
- } catch {
787
+ const takumi = await loadRenderer(fonts);
788
+ return await takumi.render(node, {
789
+ width: og.width,
790
+ height: og.height,
791
+ format: "png"
792
+ });
793
+ } catch (error) {
794
+ warn(`og: cover render failed: ${error instanceof Error ? error.message : String(error)}`);
309
795
  return null;
310
796
  }
311
797
  }
312
798
 
799
+ // src/preview.ts
800
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
801
+ import { extname, join as join2 } from "node:path";
802
+ function previewHtml(outDir) {
803
+ return (req, res, next) => {
804
+ if (req.method !== "GET" && req.method !== "HEAD")
805
+ return next();
806
+ const path = (req.url || "/").split("?")[0] ?? "/";
807
+ if (extname(path) || path.includes(".."))
808
+ return next();
809
+ const route = join2(outDir, routeFile(path));
810
+ const notFound = join2(outDir, "404.html");
811
+ const file = existsSync2(route) ? route : existsSync2(notFound) ? notFound : null;
812
+ if (!file)
813
+ return next();
814
+ res.statusCode = file === route ? 200 : 404;
815
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
816
+ res.end(req.method === "HEAD" ? undefined : readFileSync3(file));
817
+ };
818
+ }
819
+
313
820
  // src/prerender.ts
314
- import { existsSync, readFileSync as readFileSync2 } from "node:fs";
821
+ import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
315
822
  var cached = null;
316
823
  function resolveModule(elm, path) {
317
824
  return path.split(".").reduce((scope, part) => scope && typeof scope === "object" ? scope[part] : null, elm);
@@ -319,9 +826,9 @@ function resolveModule(elm, path) {
319
826
  function loadThemeBundle(path) {
320
827
  if (cached && cached.path === path)
321
828
  return cached.source;
322
- if (!existsSync(path))
829
+ if (!existsSync3(path))
323
830
  return null;
324
- const source = readFileSync2(path, "utf8");
831
+ const source = readFileSync4(path, "utf8");
325
832
  cached = { path, source };
326
833
  return source;
327
834
  }
@@ -347,7 +854,11 @@ async function renderRoute(options) {
347
854
  if (!theme) {
348
855
  throw new Error(`theme bundle did not expose Elm.${moduleName}`);
349
856
  }
350
- theme.init({ flags: content, node: dom.window.document.body });
857
+ const flags = {
858
+ ...content,
859
+ theme: { ...content.theme, mode: content.theme.mode ?? "system" }
860
+ };
861
+ theme.init({ flags, node: dom.window.document.body });
351
862
  await new Promise((resolve) => dom.window.requestAnimationFrame(() => resolve()));
352
863
  return dom.window.document.body.innerHTML;
353
864
  } finally {
@@ -358,17 +869,20 @@ async function renderRoute(options) {
358
869
  // src/index.ts
359
870
  var CONTENT = "virtual:gem/content";
360
871
  var ENTRY = "virtual:gem/entry";
872
+ var MACHINE_FILES = new Set(["/robots.txt", "/sitemap.xml", "/llms.txt", "/llms-full.txt"]);
361
873
  var PROJECT_ASSET = /\.(elm|ts|tsx|js|jsx|mjs|mts|css|scss|sass|html|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|otf|txt|xml|webmanifest|pdf)$/i;
362
874
  var GENERATED = /(^|[\\/])(node_modules|\.git|elm-stuff|\.cache)([\\/]|$)/;
363
875
  function gem(options = {}) {
364
876
  let root = process.cwd();
365
877
  let site = null;
878
+ let devImageSize = null;
366
879
  let scope = { content: [], config: [], theme: [] };
367
880
  let revision = 0;
368
881
  let pending = null;
369
882
  let pendingRevision = -1;
370
883
  let server = null;
371
884
  let isBuild = false;
885
+ let servesHtml = false;
372
886
  let base = "/";
373
887
  let basePath = "/";
374
888
  let outDir = "";
@@ -385,9 +899,9 @@ function gem(options = {}) {
385
899
  const loaded = loadConfig(root, { file: options.configFile });
386
900
  const config = loaded.config;
387
901
  scope = {
388
- content: config.docs.map((doc) => resolve(root, doc.dir)),
389
- config: [...new Set([...CONFIG_NAMES.map((name) => join2(root, name)), loaded.file ?? ""])].filter((path) => path !== ""),
390
- theme: [options.entry, config.theme.entry, config.theme.css].filter((path) => Boolean(path)).map((path) => resolve(root, path))
902
+ content: config.docs.map((doc) => resolve4(root, doc.dir)),
903
+ config: [...new Set([...CONFIG_NAMES.map((name) => join3(root, name)), loaded.file ?? ""])].filter((path) => path !== ""),
904
+ theme: [options.entry, config.theme.entry, config.theme.css].filter((path) => Boolean(path)).map((path) => resolve4(root, path))
391
905
  };
392
906
  };
393
907
  const watchScope = () => {
@@ -407,6 +921,7 @@ function gem(options = {}) {
407
921
  pending = compileSite({ root, configFile: options.configFile, base: basePath, onWarn: warn }).then((document) => {
408
922
  if (at === revision)
409
923
  site = document;
924
+ devImageSize = document.site.ogImage ? imageSize(readLocalAsset(publicDir, document.site.ogImage) ?? Buffer.alloc(0)) : null;
410
925
  return document;
411
926
  }).finally(() => {
412
927
  if (pendingRevision === at)
@@ -419,7 +934,7 @@ function gem(options = {}) {
419
934
  revision++;
420
935
  };
421
936
  const reload = (environment, file) => {
422
- logger.info(`[gem] page reload ${relative(root, file)}`, { clear: true, timestamp: true });
937
+ logger.info(`[gem] page reload ${relative2(root, file)}`, { clear: true, timestamp: true });
423
938
  environment.hot.send({ type: "full-reload" });
424
939
  };
425
940
  return {
@@ -427,11 +942,12 @@ function gem(options = {}) {
427
942
  enforce: "pre",
428
943
  config(userConfig) {
429
944
  if (options.root)
430
- root = resolve(options.root);
945
+ root = resolve4(options.root);
431
946
  if (userConfig.root)
432
- root = resolve(userConfig.root);
433
- if (existsSync2(join2(root, "index.html")))
947
+ root = resolve4(userConfig.root);
948
+ if (existsSync4(join3(root, "index.html")))
434
949
  return;
950
+ servesHtml = true;
435
951
  return {
436
952
  appType: "custom",
437
953
  build: { rollupOptions: { input: ENTRY } }
@@ -442,7 +958,7 @@ function gem(options = {}) {
442
958
  isBuild = resolved.command === "build";
443
959
  base = resolved.base || "/";
444
960
  basePath = normalizeBase(base);
445
- outDir = resolve(root, resolved.build.outDir);
961
+ outDir = resolve4(root, resolved.build.outDir);
446
962
  publicDir = resolved.publicDir;
447
963
  logger = resolved.logger;
448
964
  },
@@ -487,7 +1003,7 @@ function gem(options = {}) {
487
1003
  return `export default ${JSON.stringify(await compile())};`;
488
1004
  }
489
1005
  if (id === `\x00${ENTRY}`) {
490
- return entrySource(await compile(), root, options.entry);
1006
+ return entrySource(await compile(), root, options.entry, isBuild);
491
1007
  }
492
1008
  return null;
493
1009
  },
@@ -517,11 +1033,24 @@ function gem(options = {}) {
517
1033
  return;
518
1034
  }
519
1035
  res.setHeader("Content-Type", "text/markdown; charset=utf-8");
520
- res.end(parseFrontmatter(readFileSync3(join2(root, page.source), "utf8")).body);
1036
+ res.end(parseFrontmatter(readFileSync5(join3(root, page.source), "utf8")).body);
1037
+ });
1038
+ return;
1039
+ }
1040
+ if (MACHINE_FILES.has(path)) {
1041
+ compile().then((content) => {
1042
+ const file = machineFile(content, path, devOrigin(req.headers.host), root);
1043
+ if (!file) {
1044
+ res.statusCode = 404;
1045
+ res.end("not found");
1046
+ return;
1047
+ }
1048
+ res.setHeader("Content-Type", file.type);
1049
+ res.end(file.body);
521
1050
  });
522
1051
  return;
523
1052
  }
524
- if (extname(path))
1053
+ if (extname2(path))
525
1054
  return next();
526
1055
  if (path.startsWith("/src") || path.startsWith("/public") || path.startsWith("/assets")) {
527
1056
  return next();
@@ -537,8 +1066,7 @@ function gem(options = {}) {
537
1066
  return;
538
1067
  }
539
1068
  const page = content.pages.find((item) => item.route === route) || null;
540
- const host = req.headers.host;
541
- const origin = host ? `${host.startsWith("localhost") || host.startsWith("127.") ? "http" : "https"}://${host}` : null;
1069
+ const origin = devOrigin(req.headers.host);
542
1070
  res.statusCode = page ? 200 : 404;
543
1071
  res.setHeader("Content-Type", "text/html; charset=utf-8");
544
1072
  res.end(documentHtml({
@@ -546,14 +1074,22 @@ function gem(options = {}) {
546
1074
  page,
547
1075
  body: "",
548
1076
  scripts: [joinBase(documentBase, `@id/${ENTRY}`)],
549
- styles: [],
1077
+ styles: devStyles(content, root, options.entry),
550
1078
  client: true,
551
1079
  basePath: documentBase,
552
- origin
1080
+ origin,
1081
+ staticImageSize: devImageSize
553
1082
  }));
554
1083
  }, next);
555
1084
  });
556
1085
  },
1086
+ configurePreviewServer(preview) {
1087
+ if (!servesHtml)
1088
+ return;
1089
+ return () => {
1090
+ preview.middlewares.use(previewHtml(outDir));
1091
+ };
1092
+ },
557
1093
  async buildStart() {
558
1094
  await compile(true);
559
1095
  },
@@ -582,6 +1118,17 @@ function gem(options = {}) {
582
1118
  if (!bundleSource && options.prerender !== false) {
583
1119
  warn("prerender skipped: no theme bundle. Set `theme` or build @charmland/gem first.");
584
1120
  }
1121
+ const ogWarn = warnOnce(warn);
1122
+ for (const [name, value] of [
1123
+ ["favicon", content.site.favicon],
1124
+ ["og_image", content.site.ogImage]
1125
+ ]) {
1126
+ if (value && !localAssetExists(publicDir, value)) {
1127
+ warn(`seo: ${name} "${value}" was not found in the Vite public dir.`);
1128
+ }
1129
+ }
1130
+ const configuredImageSize = content.site.ogImage ? imageSize(readLocalAsset(publicDir, content.site.ogImage) ?? Buffer.alloc(0)) : null;
1131
+ const coverImage = coverImageLoader(root, ogWarn, publicDir);
585
1132
  this.emitFile({ type: "asset", fileName: "robots.txt", source: robotsTxt(origin, documentBase) });
586
1133
  this.emitFile({
587
1134
  type: "asset",
@@ -600,24 +1147,25 @@ function gem(options = {}) {
600
1147
  const canRender = bundleText !== "";
601
1148
  const startedAt = performance.now();
602
1149
  const timing = { covers: 0, renders: 0, notFound: 0 };
603
- const coversStarted = performance.now();
604
1150
  const images = new Set;
605
- for (const page of pages) {
606
- const cover = await renderOgImage(content, page, root);
607
- if (!cover)
608
- continue;
609
- images.add(page.route);
610
- this.emitFile({ type: "asset", fileName: ogFile(page.route), source: cover });
1151
+ if (!content.site.ogImage) {
1152
+ const coversStarted = performance.now();
1153
+ for (const page of pages) {
1154
+ const cover = await renderOgImage(content, page, root, ogWarn, coverImage);
1155
+ if (!cover)
1156
+ continue;
1157
+ images.add(page.route);
1158
+ this.emitFile({ type: "asset", fileName: ogFile(page.route), source: cover });
1159
+ }
1160
+ timing.covers += performance.now() - coversStarted;
611
1161
  }
612
- timing.covers += performance.now() - coversStarted;
613
1162
  const rendersStarted = performance.now();
1163
+ const bodies = new Map;
614
1164
  for (const page of pages) {
615
- const markdownSource = readFileSync3(join2(root, page.source), "utf8");
616
- this.emitFile({
617
- type: "asset",
618
- fileName: markdownFile(page.route),
619
- source: parseFrontmatter(markdownSource).body
620
- });
1165
+ const markdownSource = readFileSync5(join3(root, page.source), "utf8");
1166
+ const body = parseFrontmatter(markdownSource).body;
1167
+ bodies.set(page.route, body);
1168
+ this.emitFile({ type: "asset", fileName: markdownFile(page.route), source: body });
621
1169
  const rendered = canRender ? await renderRoute({
622
1170
  source: bundleText,
623
1171
  html: documentHtml({
@@ -628,7 +1176,8 @@ function gem(options = {}) {
628
1176
  styles,
629
1177
  basePath: documentBase,
630
1178
  origin,
631
- ogImage: images.has(page.route)
1179
+ ogImage: images.has(page.route),
1180
+ staticImageSize: configuredImageSize
632
1181
  }),
633
1182
  content,
634
1183
  route: page.route,
@@ -648,11 +1197,17 @@ function gem(options = {}) {
648
1197
  styles,
649
1198
  basePath: documentBase,
650
1199
  origin,
651
- ogImage: images.has(page.route)
1200
+ ogImage: images.has(page.route),
1201
+ staticImageSize: configuredImageSize
652
1202
  })
653
1203
  });
654
1204
  }
655
1205
  timing.renders += performance.now() - rendersStarted;
1206
+ this.emitFile({
1207
+ type: "asset",
1208
+ fileName: "llms-full.txt",
1209
+ source: llmsFullTxt(content, bodies, origin, documentBase)
1210
+ });
656
1211
  const landing = landingPage(content);
657
1212
  if (landing && landing !== "/") {
658
1213
  this.emitFile({ type: "asset", fileName: "index.html", source: landingRedirect(landing) });
@@ -665,7 +1220,8 @@ function gem(options = {}) {
665
1220
  scripts: [],
666
1221
  styles,
667
1222
  basePath: documentBase,
668
- origin
1223
+ origin,
1224
+ staticImageSize: configuredImageSize
669
1225
  });
670
1226
  const notFoundBody = canRender ? await renderRoute({
671
1227
  source: bundleText,
@@ -699,6 +1255,34 @@ function landingPage(content) {
699
1255
  return null;
700
1256
  return content.pages.some((page) => page.route === root) ? root : null;
701
1257
  }
1258
+ function devOrigin(host) {
1259
+ if (!host)
1260
+ return null;
1261
+ return `${host.startsWith("localhost") || host.startsWith("127.") ? "http" : "https"}://${host}`;
1262
+ }
1263
+ function machineFile(content, path, origin, root) {
1264
+ const base = content.base;
1265
+ if (path === "/robots.txt") {
1266
+ return { body: robotsTxt(origin, base), type: "text/plain; charset=utf-8" };
1267
+ }
1268
+ if (path === "/sitemap.xml") {
1269
+ if (!origin)
1270
+ return null;
1271
+ return { body: sitemapXml(content.pages, origin, base), type: "application/xml; charset=utf-8" };
1272
+ }
1273
+ if (path === "/llms.txt") {
1274
+ return { body: llmsTxt(content, origin, base), type: "text/plain; charset=utf-8" };
1275
+ }
1276
+ if (path === "/llms-full.txt") {
1277
+ const bodies = new Map;
1278
+ for (const page of content.pages) {
1279
+ const source = readFileSync5(join3(root, page.source), "utf8");
1280
+ bodies.set(page.route, parseFrontmatter(source).body);
1281
+ }
1282
+ return { body: llmsFullTxt(content, bodies, origin, base), type: "text/plain; charset=utf-8" };
1283
+ }
1284
+ return null;
1285
+ }
702
1286
  function resolveOrigin(configured) {
703
1287
  const raw = configured || process.env.GEM_URL || process.env.VERCEL_URL || process.env.CF_PAGES_URL || process.env.URL || "";
704
1288
  if (!raw.trim())
@@ -713,15 +1297,15 @@ function resolveOrigin(configured) {
713
1297
  return { origin: originOnly(value), ignoredPath: null };
714
1298
  }
715
1299
  }
716
- function entrySource(content, root, configuredEntry) {
1300
+ function entrySource(content, root, configuredEntry, includeCss) {
717
1301
  const custom = configuredEntry || content.theme.entry;
718
- const extra = content.theme.css ? `import ${JSON.stringify(resolve(root, content.theme.css))};` : "";
1302
+ const extra = includeCss && content.theme.css ? `import ${JSON.stringify(resolve4(root, content.theme.css))};` : "";
719
1303
  if (custom) {
720
- return [`import ${JSON.stringify(resolve(root, custom))};`, extra].filter(Boolean).join(`
1304
+ return [`import ${JSON.stringify(resolve4(root, custom))};`, extra].filter(Boolean).join(`
721
1305
  `);
722
1306
  }
723
1307
  return [
724
- `import "@charmland/gem/theme.css";`,
1308
+ includeCss ? `import ${JSON.stringify(THEME_CSS)};` : "",
725
1309
  extra,
726
1310
  `import { boot } from "@charmland/gem/boot";`,
727
1311
  `import content from ${JSON.stringify(CONTENT)};`,
@@ -731,9 +1315,9 @@ function entrySource(content, root, configuredEntry) {
731
1315
  }
732
1316
  function resolveTheme(root, explicit) {
733
1317
  if (explicit)
734
- return resolve(root, explicit);
1318
+ return resolve4(root, explicit);
735
1319
  try {
736
- return createRequire2(join2(root, "package.json")).resolve("@charmland/gem/theme.js");
1320
+ return createRequire(join3(root, "package.json")).resolve(THEME_JS);
737
1321
  } catch {
738
1322
  return null;
739
1323
  }
@@ -746,12 +1330,9 @@ function normalizeRoute(path) {
746
1330
  function inDirectory(file, directory) {
747
1331
  if (file === directory)
748
1332
  return true;
749
- const base = directory.endsWith(sep) ? directory : directory + sep;
1333
+ const base = directory.endsWith(sep2) ? directory : directory + sep2;
750
1334
  return file.startsWith(base);
751
1335
  }
752
- function joinBase(base, file) {
753
- return `${base.replace(/\/$/, "")}/${file.replace(/^\//, "")}`;
754
- }
755
1336
  function stripBasePath(basePath, path) {
756
1337
  if (basePath === "/")
757
1338
  return path;
package/dist/og.d.ts CHANGED
@@ -1,2 +1,33 @@
1
1
  import type { Page, SiteDocument } from "@charmland/gem-compiler/types";
2
- export declare function renderOgImage(site: SiteDocument, page: Page | null, root: string): Promise<Buffer | null>;
2
+ import type { ContainerNode } from "@takumi-rs/core";
3
+ type Warn = (message: string) => void;
4
+ interface ResolvedFont {
5
+ path: string;
6
+ data: Buffer;
7
+ mtime: number;
8
+ name: string;
9
+ weight: number | null;
10
+ style: "normal" | "italic" | null;
11
+ }
12
+ type DefaultFont = (warn: Warn) => Promise<ResolvedFont | null>;
13
+ export type CoverImage = string | Uint8Array;
14
+ export interface CoverNodeOptions {
15
+ /** The family the registered fonts answer to. */
16
+ family: string;
17
+ /** Resolve one image node source; `null` skips the node. */
18
+ loadImage: (src: string) => Promise<CoverImage | null>;
19
+ warn?: Warn;
20
+ }
21
+ /**
22
+ * Build the cover node tree. Pure apart from image resolution, so tests can
23
+ * assert the layout with a stub loader and never touch the network.
24
+ */
25
+ export declare function coverNode(site: SiteDocument, page: Page | null, options: CoverNodeOptions): Promise<ContainerNode>;
26
+ /**
27
+ * Resolve image bytes once per source. Local paths are project-relative with
28
+ * the Vite public dir as a fallback root; remote URLs are fetched with a
29
+ * timeout so a flaky host cannot hang the build.
30
+ */
31
+ export declare function coverImageLoader(root: string, warn: Warn, publicDir?: string): (src: string) => Promise<CoverImage | null>;
32
+ export declare function renderOgImage(site: SiteDocument, page: Page | null, root: string, onWarn?: Warn, loadImage?: (src: string) => Promise<CoverImage | null>, loadDefaultFont?: DefaultFont): Promise<Buffer | null>;
33
+ export {};
package/dist/output.d.ts CHANGED
@@ -17,12 +17,37 @@ export declare function withBase(base: string, route: string): string;
17
17
  */
18
18
  export declare function originOnly(raw: string): string | null;
19
19
  export declare function absoluteUrl(origin: string | null, route: string, base?: string): string | null;
20
+ /**
21
+ * Resolve a configured asset (favicon, share image). External and
22
+ * protocol-relative URLs pass through; any local path is root-absolute and
23
+ * base-free like a route ID, so it takes the deployment base and, when known,
24
+ * the origin.
25
+ */
26
+ export declare function assetUrl(origin: string | null, path: string, base?: string): string;
27
+ /** Whether a configured deployed asset exists. Unknown when the public dir is off. */
28
+ export declare function localAssetExists(publicDir: string, value: string): boolean;
29
+ /** Bytes of a deployed asset, for sniffing its dimensions. */
30
+ export declare function readLocalAsset(publicDir: string, value: string): Buffer | null;
31
+ export interface ImageSize {
32
+ width: number;
33
+ height: number;
34
+ }
35
+ /** Wrap a warning sink so one message reaches it once per build. */
36
+ export declare function warnOnce(warn: (message: string) => void): (message: string) => void;
37
+ /** PNG, GIF, JPEG and WebP dimensions from the file header. */
38
+ export declare function imageSize(data: Buffer): ImageSize | null;
20
39
  export declare function ogFile(route: string): string;
21
40
  export declare function ogRoute(route: string): string;
22
41
  export declare function sitemapXml(pages: Page[], origin: string | null, base?: string): string;
23
42
  export declare function robotsTxt(origin: string | null, base?: string): string;
24
43
  export declare function llmsTxt(site: SiteDocument, origin: string | null, base?: string): string;
25
- export declare function jsonLd(site: SiteDocument, page: Page | null, origin: string | null, base?: string): string;
44
+ /**
45
+ * `llms-full.txt`: the same nav order as `llms.txt`, but with each page's
46
+ * markdown body inlined. `bodies` is keyed by route; a route without one is
47
+ * skipped so the file never carries an empty heading.
48
+ */
49
+ export declare function llmsFullTxt(site: SiteDocument, bodies: Map<string, string>, origin: string | null, base?: string): string;
50
+ export declare function jsonLd(site: SiteDocument, page: Page | null, origin: string | null, base?: string, image?: string | null): string;
26
51
  /**
27
52
  * A site whose landing page sits under its prefix still has to answer at the
28
53
  * build root, both locally and under a mount. A relative redirect does that
@@ -0,0 +1 @@
1
+ export declare function joinBase(base: string, file: string): string;
@@ -0,0 +1,8 @@
1
+ import type { Connect } from "vite";
2
+ /**
3
+ * The HTML a preview request answers with: the emitted file for its route, or
4
+ * the build's `404.html`. Mounted after Vite's static and base middlewares, so
5
+ * assets are already served and `req.url` no longer carries the deployment
6
+ * base. `routeFile` is the same naming the build wrote, so they cannot drift.
7
+ */
8
+ export declare function previewHtml(outDir: string): Connect.NextHandleFunction;
@@ -0,0 +1,6 @@
1
+ import type { SiteDocument } from "@charmland/gem-compiler/types";
2
+ export declare const THEME_JS = "@charmland/gem/theme.js";
3
+ export declare const THEME_CSS = "@charmland/gem/theme.css";
4
+ export declare const FONT_ORIGIN = "https://stuff.charm.land";
5
+ export declare const FONT_CSS = "https://stuff.charm.land/fonts/charmform/charmform.css";
6
+ export declare function devStyles(content: SiteDocument, root: string, configuredEntry?: string): string[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@charmland/gem-vite",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
4
  "description": "The Vite plugin that turns a markdown directory into a prerendered docs site.",
5
5
  "keywords": ["gem", "vite", "vite-plugin", "documentation", "prerender"],
6
6
  "homepage": "https://github.com/charmbracelet/gem/tree/main/packages/vite",
@@ -39,12 +39,12 @@
39
39
  "prepack": "bun run build"
40
40
  },
41
41
  "dependencies": {
42
- "@charmland/gem-compiler": "0.1.1",
42
+ "@charmland/gem-compiler": "0.2.1",
43
43
  "@takumi-rs/core": "^2.20.0",
44
44
  "jsdom": "^30.1.3"
45
45
  },
46
46
  "peerDependencies": {
47
- "@charmland/gem": "^0.1.1",
47
+ "@charmland/gem": "^0.2.1",
48
48
  "vite": ">=6"
49
49
  },
50
50
  "peerDependenciesMeta": {