@charmland/gem-vite 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
package/NOTICE ADDED
@@ -0,0 +1,13 @@
1
+ Copyright 2026 Charmbracelet, Inc.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,28 @@
1
- # Temporary Holding Version
1
+ # @charmland/gem-vite
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Build prerendered documentation sites from Markdown with Vite and Elm-backed rendering.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install --save-dev @charmland/gem-vite @charmland/gem vite
9
+ ```
10
+
11
+ The Vite integration requires Node `^22.22.2 || ^24.15.0 || >=26.0.0`, matching the prerenderer's jsdom engine floor.
12
+
13
+ The default integration uses `@charmland/gem`. It is an optional peer only for projects supplying both a fully custom entry and prerender theme.
14
+
15
+ ## Usage
16
+
17
+ ```ts
18
+ import { defineConfig } from "vite";
19
+ import { gem } from "@charmland/gem-vite";
20
+
21
+ export default defineConfig({
22
+ plugins: [gem()],
23
+ });
24
+ ```
25
+
26
+ Add `content/index.md`, then run `vite dev` or `vite build`. The package's public entrypoint is `@charmland/gem-vite`, which exports the `gem` plugin and `GemOptions`.
27
+
28
+ The default setup uses Gem's prebuilt theme and does not need the Elm compiler. Install and use Elm only when customizing and recompiling Gem's Elm sources. See the [Gem documentation](https://github.com/charmbracelet/gem#readme) for customization details.
package/dist/html.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import type { Page, SiteDocument } from "@charmland/gem-compiler/types";
2
+ export interface DocumentHtmlOptions {
3
+ site: SiteDocument;
4
+ page: Page | null;
5
+ body: string;
6
+ scripts: string[];
7
+ styles: string[];
8
+ client?: boolean;
9
+ origin?: string | null;
10
+ ogImage?: boolean;
11
+ }
12
+ export declare function routeFile(route: string): string;
13
+ export declare function documentHtml(options: DocumentHtmlOptions): string;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The Vite plugin: serves the compiled document and the generated client
3
+ * entry in dev, and writes one prerendered HTML file per route at build time.
4
+ */
5
+ import type { Plugin } from "vite";
6
+ export interface GemOptions {
7
+ root?: string;
8
+ configFile?: string;
9
+ /** Replaces the generated default entry. */
10
+ entry?: string;
11
+ /** Bundle used to prerender; without it routes are written unrendered. */
12
+ theme?: string;
13
+ /** Elm module to boot while prerendering, default `Gem.Main`. */
14
+ themeModule?: string;
15
+ prerender?: boolean;
16
+ }
17
+ export declare function gem(options?: GemOptions): Plugin;
package/dist/index.js ADDED
@@ -0,0 +1,689 @@
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";
5
+ import { CONFIG_NAMES, compileSite, loadConfig, parseFrontmatter } from "@charmland/gem-compiler";
6
+
7
+ // src/output.ts
8
+ function markdownFile(route) {
9
+ if (route === "/" || route === "")
10
+ return "index.md";
11
+ return `${route.replace(/^\/+|\/+$/g, "")}.md`;
12
+ }
13
+ function markdownRoute(route) {
14
+ return `/${markdownFile(route)}`;
15
+ }
16
+ function absoluteUrl(origin, route) {
17
+ if (!origin)
18
+ return null;
19
+ const path = route === "/" ? "/" : route;
20
+ return `${origin.replace(/\/$/, "")}${path}`;
21
+ }
22
+ function ogFile(route) {
23
+ if (route === "/" || route === "")
24
+ return "og/index.png";
25
+ return `og/${route.replace(/^\/+|\/+$/g, "")}.png`;
26
+ }
27
+ function ogRoute(route) {
28
+ return `/${ogFile(route)}`;
29
+ }
30
+ function sitemapXml(pages, origin) {
31
+ const entries = pages.map((page) => absoluteUrl(origin, page.route)).filter((url) => url !== null).map((url) => ` <url><loc>${escapeXml(url)}</loc></url>`).join(`
32
+ `);
33
+ return [
34
+ `<?xml version="1.0" encoding="UTF-8"?>`,
35
+ `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">`,
36
+ entries,
37
+ `</urlset>`,
38
+ ``
39
+ ].join(`
40
+ `);
41
+ }
42
+ function robotsTxt(origin) {
43
+ const lines = ["User-agent: *", "Allow: /"];
44
+ if (origin)
45
+ lines.push("", `Sitemap: ${origin.replace(/\/$/, "")}/sitemap.xml`);
46
+ return `${lines.join(`
47
+ `)}
48
+ `;
49
+ }
50
+ function llmsTxt(site, origin) {
51
+ const lines = [`# ${site.site.title}`, ""];
52
+ if (site.site.description)
53
+ lines.push(`> ${site.site.description}`, "");
54
+ for (const doc of site.docs) {
55
+ lines.push(`## ${doc.label}`, "");
56
+ for (const item of flatten(doc.nav)) {
57
+ const page = site.pages.find((candidate) => candidate.route === item.route);
58
+ const url = absoluteUrl(origin, item.route) ?? markdownRoute(item.route);
59
+ const summary = page?.summary ? `: ${page.summary}` : "";
60
+ lines.push(`- [${item.title}](${url})${summary}`);
61
+ }
62
+ lines.push("");
63
+ }
64
+ return `${lines.join(`
65
+ `)}
66
+ `;
67
+ }
68
+ function jsonLd(site, page, origin) {
69
+ const url = page ? absoluteUrl(origin, page.route) : origin;
70
+ const data = page ? {
71
+ "@context": "https://schema.org",
72
+ "@type": "TechArticle",
73
+ headline: page.title,
74
+ description: page.description || page.summary || site.site.description,
75
+ url: url ?? undefined,
76
+ isPartOf: { "@type": "WebSite", name: site.site.title }
77
+ } : {
78
+ "@context": "https://schema.org",
79
+ "@type": "WebSite",
80
+ name: site.site.title,
81
+ description: site.site.description,
82
+ url: url ?? undefined
83
+ };
84
+ return JSON.stringify(data).replace(/</g, "\\u003c");
85
+ }
86
+ function flatten(nav) {
87
+ const out = [];
88
+ for (const item of nav) {
89
+ if (item.kind === "page")
90
+ out.push({ route: item.route, title: item.title });
91
+ else
92
+ out.push(...flatten(item.items));
93
+ }
94
+ return out;
95
+ }
96
+ function escapeXml(value) {
97
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
98
+ }
99
+ function landingRedirect(route) {
100
+ const href = `.${route.replace(/\/$/, "")}/`;
101
+ return [
102
+ `<!doctype html>`,
103
+ `<html lang="en">`,
104
+ `<head>`,
105
+ `<meta charset="utf-8">`,
106
+ `<meta http-equiv="refresh" content="0; url=${href}">`,
107
+ `<link rel="canonical" href="${href}">`,
108
+ `<title>Redirecting…</title>`,
109
+ `</head>`,
110
+ `<body><a href="${href}">Continue</a></body>`,
111
+ `</html>`,
112
+ ``
113
+ ].join(`
114
+ `);
115
+ }
116
+
117
+ // src/html.ts
118
+ function routeFile(route) {
119
+ if (route === "/" || route === "")
120
+ return "index.html";
121
+ return `${route.replace(/^\/+|\/+$/g, "")}/index.html`;
122
+ }
123
+ function documentHtml(options) {
124
+ const {
125
+ site,
126
+ page,
127
+ body,
128
+ scripts,
129
+ styles,
130
+ client = false,
131
+ origin = null,
132
+ ogImage = false
133
+ } = options;
134
+ const meta = site.site;
135
+ const landing = site.docs[0]?.root ?? "/";
136
+ const title = page && page.route !== landing ? `${page.title} - ${meta.title}` : meta.title;
137
+ const description = page && page.description || meta.description || "";
138
+ const canonical = page ? absoluteUrl(origin, page.route) : origin;
139
+ const image = ogImage && page ? absoluteUrl(origin, ogRoute(page.route)) : null;
140
+ const keywords = page && page.tags.length ? page.tags.join(", ") : "";
141
+ const allowSystem = site.theme?.system ? "true" : "false";
142
+ 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>`;
143
+ return `<!doctype html>
144
+ <html lang="${escapeAttribute(meta.lang || "en")}">
145
+ <head>
146
+ <meta charset="utf-8" />
147
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
148
+ <title>${escapeHtml(title)}</title>
149
+ ${description ? `<meta name="description" content="${escapeAttribute(description)}" />` : ""}
150
+ ${keywords ? `<meta name="keywords" content="${escapeAttribute(keywords)}" />` : ""}
151
+ <meta name="robots" content="index, follow" />
152
+ ${canonical ? `<link rel="canonical" href="${escapeAttribute(canonical)}" />` : ""}
153
+ <meta property="og:type" content="article" />
154
+ <meta property="og:site_name" content="${escapeAttribute(meta.title)}" />
155
+ <meta property="og:title" content="${escapeAttribute(title)}" />
156
+ ${description ? `<meta property="og:description" content="${escapeAttribute(description)}" />` : ""}
157
+ ${canonical ? `<meta property="og:url" content="${escapeAttribute(canonical)}" />` : ""}
158
+ ${image ? `<meta property="og:image" content="${escapeAttribute(image)}" />` : ""}
159
+ <meta name="twitter:card" content="${image ? "summary_large_image" : "summary"}" />
160
+ <meta name="twitter:title" content="${escapeAttribute(title)}" />
161
+ ${description ? `<meta name="twitter:description" content="${escapeAttribute(description)}" />` : ""}
162
+ ${image ? `<meta name="twitter:image" content="${escapeAttribute(image)}" />` : ""}
163
+ <script type="application/ld+json">${jsonLd(site, page, origin)}</script>
164
+ ${modeScript}
165
+ ${styles.map((href) => `<link rel="stylesheet" href="${escapeAttribute(href)}" />`).join(`
166
+ `)}
167
+ ${client ? `<script type="module" src="/@vite/client"></script>` : ""}
168
+ </head>
169
+ <body>${body}</body>
170
+ ${scripts.map((src) => `<script type="module" src="${escapeAttribute(src)}"></script>`).join(`
171
+ `)}
172
+ </html>
173
+ `;
174
+ }
175
+ function escapeHtml(value) {
176
+ return String(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
177
+ }
178
+ function escapeAttribute(value) {
179
+ return escapeHtml(value).replace(/"/g, "&quot;");
180
+ }
181
+
182
+ // src/og.ts
183
+ import { readFileSync } from "node:fs";
184
+ import { createRequire } from "node:module";
185
+ import { join } from "node:path";
186
+ import { Resvg } from "@resvg/resvg-js";
187
+ import satori from "satori";
188
+ var WIDTH = 1200;
189
+ var HEIGHT = 630;
190
+ function require_(root) {
191
+ return createRequire(join(root, "package.json"));
192
+ }
193
+ var fontData = null;
194
+ var fontLoaded = false;
195
+ function loadFont(root) {
196
+ if (fontLoaded)
197
+ return fontData;
198
+ fontLoaded = true;
199
+ try {
200
+ const path = require_(root).resolve("@charmland/gem/fonts/PPFraktionSans-Variable.ttf");
201
+ fontData = readFileSync(path);
202
+ } catch {
203
+ fontData = null;
204
+ }
205
+ return fontData;
206
+ }
207
+ async function renderOgImage(site, page, root) {
208
+ const font = loadFont(root);
209
+ if (!font)
210
+ return null;
211
+ const accent = site.theme.accent || "#b8461f";
212
+ const title = page ? page.title : site.site.title;
213
+ const eyebrow = page ? site.site.title : site.site.description || site.site.title;
214
+ const node = {
215
+ type: "div",
216
+ props: {
217
+ style: {
218
+ width: "100%",
219
+ height: "100%",
220
+ display: "flex",
221
+ flexDirection: "column",
222
+ justifyContent: "space-between",
223
+ padding: "72px 80px",
224
+ background: "#141414",
225
+ color: "#f5f0e8",
226
+ fontFamily: "Fraktion"
227
+ },
228
+ children: [
229
+ {
230
+ type: "div",
231
+ props: {
232
+ style: {
233
+ display: "flex",
234
+ alignItems: "center",
235
+ gap: "20px",
236
+ fontSize: 30,
237
+ color: "#a8a29e"
238
+ },
239
+ children: [
240
+ {
241
+ type: "div",
242
+ props: {
243
+ style: { width: "52px", height: "10px", background: accent, borderRadius: "5px" }
244
+ }
245
+ },
246
+ { type: "div", props: { children: eyebrow } }
247
+ ]
248
+ }
249
+ },
250
+ {
251
+ type: "div",
252
+ props: {
253
+ style: {
254
+ display: "flex",
255
+ fontSize: title.length > 48 ? 62 : 76,
256
+ lineHeight: 1.1,
257
+ letterSpacing: "-0.02em"
258
+ },
259
+ children: title
260
+ }
261
+ },
262
+ {
263
+ type: "div",
264
+ props: {
265
+ style: { display: "flex", fontSize: 26, color: "#78716c" },
266
+ children: page ? page.route : "/"
267
+ }
268
+ }
269
+ ]
270
+ }
271
+ };
272
+ try {
273
+ const svg = await satori(node, {
274
+ width: WIDTH,
275
+ height: HEIGHT,
276
+ fonts: [{ name: "Fraktion", data: font, weight: 400, style: "normal" }]
277
+ });
278
+ const resvg = new Resvg(svg, { fitTo: { mode: "width", value: WIDTH } });
279
+ return resvg.render().asPng();
280
+ } catch {
281
+ return null;
282
+ }
283
+ }
284
+
285
+ // src/prerender.ts
286
+ import { existsSync, readFileSync as readFileSync2 } from "node:fs";
287
+ var cached = null;
288
+ function resolveModule(elm, path) {
289
+ return path.split(".").reduce((scope, part) => scope && typeof scope === "object" ? scope[part] : null, elm);
290
+ }
291
+ function loadThemeBundle(path) {
292
+ if (cached && cached.path === path)
293
+ return cached.source;
294
+ if (!existsSync(path))
295
+ return null;
296
+ const source = readFileSync2(path, "utf8");
297
+ cached = { path, source };
298
+ return source;
299
+ }
300
+ async function renderRoute(options) {
301
+ const { JSDOM, VirtualConsole } = await import("jsdom");
302
+ const { source, html, content, route, module: moduleName = "Gem.Main" } = options;
303
+ const virtualConsole = new VirtualConsole;
304
+ virtualConsole.on("jsdomError", (error) => {
305
+ if (!/Not implemented/.test(error.message))
306
+ console.warn(`[gem] ${error.message}`);
307
+ });
308
+ const dom = new JSDOM(html, {
309
+ runScripts: "dangerously",
310
+ pretendToBeVisual: true,
311
+ virtualConsole,
312
+ url: `${content.site.url || "https://gem.local"}${route}`
313
+ });
314
+ try {
315
+ dom.window.eval(source);
316
+ const elm = dom.window.Elm;
317
+ const theme = resolveModule(elm, moduleName);
318
+ if (!theme) {
319
+ throw new Error(`theme bundle did not expose Elm.${moduleName}`);
320
+ }
321
+ theme.init({ flags: content, node: dom.window.document.body });
322
+ await new Promise((resolve) => dom.window.requestAnimationFrame(() => resolve()));
323
+ return dom.window.document.body.innerHTML;
324
+ } finally {
325
+ dom.window.close();
326
+ }
327
+ }
328
+
329
+ // src/index.ts
330
+ var CONTENT = "virtual:gem/content";
331
+ var ENTRY = "virtual:gem/entry";
332
+ 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;
333
+ var GENERATED = /(^|[\\/])(node_modules|\.git|elm-stuff|\.cache)([\\/]|$)/;
334
+ function gem(options = {}) {
335
+ let root = process.cwd();
336
+ let site = null;
337
+ let scope = { content: [], config: [], theme: [] };
338
+ let revision = 0;
339
+ let pending = null;
340
+ let pendingRevision = -1;
341
+ let server = null;
342
+ let isBuild = false;
343
+ let base = "/";
344
+ let outDir = "";
345
+ let publicDir = "";
346
+ let logger = console;
347
+ const warnings = new Set;
348
+ const warn = (message) => {
349
+ if (warnings.has(message))
350
+ return;
351
+ warnings.add(message);
352
+ logger.warn(`[gem] ${message}`);
353
+ };
354
+ const readScope = () => {
355
+ const loaded = loadConfig(root, { file: options.configFile });
356
+ const config = loaded.config;
357
+ scope = {
358
+ content: config.docs.map((doc) => resolve(root, doc.dir)),
359
+ config: [...new Set([...CONFIG_NAMES.map((name) => join2(root, name)), loaded.file ?? ""])].filter((path) => path !== ""),
360
+ theme: [options.entry, config.theme.entry, config.theme.css].filter((path) => Boolean(path)).map((path) => resolve(root, path))
361
+ };
362
+ };
363
+ const watchScope = () => {
364
+ if (!server)
365
+ return;
366
+ for (const path of [...scope.content, ...scope.config, ...scope.theme])
367
+ server.watcher.add(path);
368
+ };
369
+ const generated = (file) => outDir !== "" && inDirectory(file, outDir) || GENERATED.test(file);
370
+ const compile = (force = false) => {
371
+ if (site && !force)
372
+ return Promise.resolve(site);
373
+ if (pending && pendingRevision === revision)
374
+ return pending;
375
+ const at = ++revision;
376
+ pendingRevision = at;
377
+ pending = compileSite({ root, configFile: options.configFile, onWarn: warn }).then((document) => {
378
+ if (at === revision)
379
+ site = document;
380
+ return document;
381
+ }).finally(() => {
382
+ if (pendingRevision === at)
383
+ pending = null;
384
+ });
385
+ return pending;
386
+ };
387
+ const invalidate = () => {
388
+ site = null;
389
+ revision++;
390
+ };
391
+ const reload = (environment, file) => {
392
+ logger.info(`[gem] page reload ${relative(root, file)}`, { clear: true, timestamp: true });
393
+ environment.hot.send({ type: "full-reload" });
394
+ };
395
+ return {
396
+ name: "gem",
397
+ enforce: "pre",
398
+ config(userConfig) {
399
+ if (options.root)
400
+ root = resolve(options.root);
401
+ if (userConfig.root)
402
+ root = resolve(userConfig.root);
403
+ if (existsSync2(join2(root, "index.html")))
404
+ return;
405
+ return {
406
+ appType: "custom",
407
+ build: { rollupOptions: { input: ENTRY } }
408
+ };
409
+ },
410
+ configResolved(resolved) {
411
+ root = resolved.root;
412
+ isBuild = resolved.command === "build";
413
+ base = resolved.base || "/";
414
+ outDir = resolve(root, resolved.build.outDir);
415
+ publicDir = resolved.publicDir;
416
+ logger = resolved.logger;
417
+ },
418
+ hotUpdate({ file, modules, timestamp }) {
419
+ if (this.environment.name !== "client")
420
+ return;
421
+ if (generated(file))
422
+ return [];
423
+ const changed = this.environment;
424
+ const isConfig = scope.config.includes(file);
425
+ const isContent = scope.content.some((dir) => inDirectory(file, dir));
426
+ if (isConfig || isContent) {
427
+ if (isConfig) {
428
+ readScope();
429
+ watchScope();
430
+ }
431
+ invalidate();
432
+ warnings.clear();
433
+ for (const id of [CONTENT, ENTRY]) {
434
+ const module = changed.moduleGraph.getModuleById(`\x00${id}`);
435
+ if (module)
436
+ changed.moduleGraph.invalidateModule(module, undefined, timestamp, true);
437
+ }
438
+ reload(changed, file);
439
+ return [];
440
+ }
441
+ if (modules.length > 0)
442
+ return;
443
+ const isPublic = publicDir !== "" && inDirectory(file, publicDir);
444
+ if (!isPublic && !PROJECT_ASSET.test(file))
445
+ return;
446
+ reload(changed, file);
447
+ return [];
448
+ },
449
+ resolveId(id) {
450
+ if (id === CONTENT || id === ENTRY)
451
+ return `\x00${id}`;
452
+ return null;
453
+ },
454
+ async load(id) {
455
+ if (id === `\x00${CONTENT}`) {
456
+ return `export default ${JSON.stringify(await compile())};`;
457
+ }
458
+ if (id === `\x00${ENTRY}`) {
459
+ return entrySource(await compile(), root, options.entry);
460
+ }
461
+ return null;
462
+ },
463
+ configureServer(devServer) {
464
+ server = devServer;
465
+ readScope();
466
+ watchScope();
467
+ server.middlewares.use((req, res, next) => {
468
+ if (req.method !== "GET" && req.method !== "HEAD")
469
+ return next();
470
+ const path = (req.url || "/").split("?")[0];
471
+ if (path.startsWith("/@") || path.startsWith("/node_modules"))
472
+ return next();
473
+ if (path.endsWith(".md")) {
474
+ compile().then((content) => {
475
+ const route = normalizeRoute(path.replace(/\.md$/, "").replace(/\/index$/, "") || "/");
476
+ const page = content.pages.find((item) => item.route === route);
477
+ if (!page) {
478
+ res.statusCode = 404;
479
+ res.end("not found");
480
+ return;
481
+ }
482
+ res.setHeader("Content-Type", "text/markdown; charset=utf-8");
483
+ res.end(parseFrontmatter(readFileSync3(join2(root, page.source), "utf8")).body);
484
+ });
485
+ return;
486
+ }
487
+ if (extname(path))
488
+ return next();
489
+ if (path.startsWith("/src") || path.startsWith("/public") || path.startsWith("/assets")) {
490
+ return next();
491
+ }
492
+ compile().then((content) => {
493
+ const route = normalizeRoute(path);
494
+ const landing = landingPage(content);
495
+ if (route === "/" && landing && landing !== "/") {
496
+ res.statusCode = 302;
497
+ res.setHeader("Location", landing);
498
+ res.end();
499
+ return;
500
+ }
501
+ const page = content.pages.find((item) => item.route === route) || null;
502
+ const host = req.headers.host;
503
+ const origin = host ? `${host.startsWith("localhost") || host.startsWith("127.") ? "http" : "https"}://${host}` : null;
504
+ res.statusCode = page ? 200 : 404;
505
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
506
+ res.end(documentHtml({
507
+ site: content,
508
+ page,
509
+ body: "",
510
+ scripts: [`/@id/${ENTRY}`],
511
+ styles: [],
512
+ client: true,
513
+ origin
514
+ }));
515
+ }, next);
516
+ });
517
+ },
518
+ async buildStart() {
519
+ await compile(true);
520
+ },
521
+ async generateBundle(_outputOptions, bundle) {
522
+ if (!isBuild)
523
+ return;
524
+ const content = await compile();
525
+ const scripts = [];
526
+ const styles = [];
527
+ for (const [file, asset] of Object.entries(bundle)) {
528
+ if (asset.type === "chunk" && asset.isEntry)
529
+ scripts.push(joinBase(base, file));
530
+ if (asset.type === "asset" && file.endsWith(".css"))
531
+ styles.push(joinBase(base, file));
532
+ }
533
+ const themePath = resolveTheme(root, options.theme);
534
+ const bundleSource = themePath ? loadThemeBundle(themePath) : null;
535
+ const origin = resolveOrigin(content.site.url);
536
+ if (!origin) {
537
+ warn("seo: no site.url and no deploy env; canonical, sitemap and og:url are skipped.");
538
+ }
539
+ if (!bundleSource && options.prerender !== false) {
540
+ warn("prerender skipped: no theme bundle. Set `theme` or build @charmland/gem first.");
541
+ }
542
+ this.emitFile({ type: "asset", fileName: "robots.txt", source: robotsTxt(origin) });
543
+ this.emitFile({ type: "asset", fileName: "llms.txt", source: llmsTxt(content, origin) });
544
+ if (origin) {
545
+ this.emitFile({
546
+ type: "asset",
547
+ fileName: "sitemap.xml",
548
+ source: sitemapXml(content.pages, origin)
549
+ });
550
+ }
551
+ const images = new Set;
552
+ for (const page of content.pages) {
553
+ const cover = await renderOgImage(content, page, root);
554
+ if (!cover)
555
+ continue;
556
+ images.add(page.route);
557
+ this.emitFile({ type: "asset", fileName: ogFile(page.route), source: cover });
558
+ }
559
+ for (const page of content.pages) {
560
+ const markdownSource = readFileSync3(join2(root, page.source), "utf8");
561
+ this.emitFile({
562
+ type: "asset",
563
+ fileName: markdownFile(page.route),
564
+ source: parseFrontmatter(markdownSource).body
565
+ });
566
+ const rendered = bundleSource && typeof bundleSource === "string" ? await renderRoute({
567
+ source: bundleSource,
568
+ html: documentHtml({
569
+ site: content,
570
+ page,
571
+ body: "",
572
+ scripts: [],
573
+ styles,
574
+ origin,
575
+ ogImage: images.has(page.route)
576
+ }),
577
+ content,
578
+ route: page.route,
579
+ module: options.themeModule || "Gem.Main"
580
+ }).catch((error) => {
581
+ warn(`prerender ${page.route}: ${errorMessage(error)}`);
582
+ return "";
583
+ }) : "";
584
+ this.emitFile({
585
+ type: "asset",
586
+ fileName: routeFile(page.route),
587
+ source: documentHtml({
588
+ site: content,
589
+ page,
590
+ body: rendered,
591
+ scripts,
592
+ styles,
593
+ origin,
594
+ ogImage: images.has(page.route)
595
+ })
596
+ });
597
+ }
598
+ const landing = landingPage(content);
599
+ if (landing && landing !== "/") {
600
+ this.emitFile({ type: "asset", fileName: "index.html", source: landingRedirect(landing) });
601
+ }
602
+ const notFoundHtml = documentHtml({
603
+ site: content,
604
+ page: null,
605
+ body: "",
606
+ scripts: [],
607
+ styles,
608
+ origin
609
+ });
610
+ const notFoundBody = bundleSource && typeof bundleSource === "string" ? await renderRoute({
611
+ source: bundleSource,
612
+ html: notFoundHtml,
613
+ content,
614
+ route: "/404",
615
+ module: options.themeModule || "Gem.Main"
616
+ }).catch(() => "") : "";
617
+ this.emitFile({
618
+ type: "asset",
619
+ fileName: "404.html",
620
+ source: documentHtml({
621
+ site: content,
622
+ page: null,
623
+ body: notFoundBody,
624
+ scripts,
625
+ styles,
626
+ origin
627
+ })
628
+ });
629
+ }
630
+ };
631
+ }
632
+ function landingPage(content) {
633
+ const root = content.docs[0]?.root;
634
+ if (!root)
635
+ return null;
636
+ return content.pages.some((page) => page.route === root) ? root : null;
637
+ }
638
+ function resolveOrigin(configured) {
639
+ const raw = configured || process.env.GEM_URL || process.env.VERCEL_URL || process.env.CF_PAGES_URL || process.env.URL || "";
640
+ if (!raw)
641
+ return null;
642
+ const value = raw.replace(/\/$/, "");
643
+ return /^https?:\/\//.test(value) ? value : `https://${value}`;
644
+ }
645
+ function entrySource(content, root, configuredEntry) {
646
+ const custom = configuredEntry || content.theme.entry;
647
+ const extra = content.theme.css ? `import ${JSON.stringify(resolve(root, content.theme.css))};` : "";
648
+ if (custom) {
649
+ return [`import ${JSON.stringify(resolve(root, custom))};`, extra].filter(Boolean).join(`
650
+ `);
651
+ }
652
+ return [
653
+ `import "@charmland/gem/theme.css";`,
654
+ extra,
655
+ `import { boot } from "@charmland/gem/boot";`,
656
+ `import content from ${JSON.stringify(CONTENT)};`,
657
+ `boot(content);`
658
+ ].filter(Boolean).join(`
659
+ `);
660
+ }
661
+ function resolveTheme(root, explicit) {
662
+ if (explicit)
663
+ return resolve(root, explicit);
664
+ try {
665
+ return createRequire2(join2(root, "package.json")).resolve("@charmland/gem/theme.js");
666
+ } catch {
667
+ return null;
668
+ }
669
+ }
670
+ function normalizeRoute(path) {
671
+ if (!path || path === "/")
672
+ return "/";
673
+ return path.replace(/\/+$/, "") || "/";
674
+ }
675
+ function inDirectory(file, directory) {
676
+ if (file === directory)
677
+ return true;
678
+ const base = directory.endsWith(sep) ? directory : directory + sep;
679
+ return file.startsWith(base);
680
+ }
681
+ function joinBase(base, file) {
682
+ return `${base.replace(/\/$/, "")}/${file.replace(/^\//, "")}`;
683
+ }
684
+ function errorMessage(error) {
685
+ return error instanceof Error ? error.message : String(error);
686
+ }
687
+ export {
688
+ gem
689
+ };
package/dist/og.d.ts ADDED
@@ -0,0 +1,2 @@
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>;
@@ -0,0 +1,20 @@
1
+ import type { Page, SiteDocument } from "@charmland/gem-compiler/types";
2
+ export interface OutputContext {
3
+ site: SiteDocument;
4
+ origin: string | null;
5
+ }
6
+ export declare function markdownFile(route: string): string;
7
+ export declare function markdownRoute(route: string): string;
8
+ export declare function absoluteUrl(origin: string | null, route: string): string | null;
9
+ export declare function ogFile(route: string): string;
10
+ export declare function ogRoute(route: string): string;
11
+ export declare function sitemapXml(pages: Page[], origin: string | null): string;
12
+ export declare function robotsTxt(origin: string | null): string;
13
+ export declare function llmsTxt(site: SiteDocument, origin: string | null): string;
14
+ export declare function jsonLd(site: SiteDocument, page: Page | null, origin: string | null): string;
15
+ /**
16
+ * A site whose landing page sits under its prefix still has to answer at the
17
+ * build root, both locally and under a mount. A relative redirect does that
18
+ * without duplicating the page or its canonical URL.
19
+ */
20
+ export declare function landingRedirect(route: string): string;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Renders a route by booting the compiled theme inside jsdom. Elm has no
3
+ * server renderer; this is what keeps one renderer for crawlers and browser.
4
+ */
5
+ import type { SiteDocument } from "@charmland/gem-compiler/types";
6
+ export interface RenderRouteOptions {
7
+ source: string;
8
+ html: string;
9
+ content: SiteDocument;
10
+ route: string;
11
+ module?: string;
12
+ }
13
+ export declare function loadThemeBundle(path: string): string | null;
14
+ export declare function renderRoute(options: RenderRouteOptions): Promise<string>;
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@charmland/gem-vite",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "The Vite plugin that turns a markdown directory into a prerendered docs site.",
5
+ "keywords": ["gem", "vite", "vite-plugin", "documentation", "prerender"],
6
+ "homepage": "https://github.com/charmbracelet/gem/tree/main/packages/vite",
7
+ "bugs": {
8
+ "url": "https://github.com/charmbracelet/gem/issues"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/charmbracelet/gem.git",
13
+ "directory": "packages/vite"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "license": "Apache-2.0",
19
+ "type": "module",
20
+ "sideEffects": false,
21
+ "engines": {
22
+ "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
23
+ },
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/index.js"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "LICENSE",
33
+ "NOTICE"
34
+ ],
35
+ "scripts": {
36
+ "clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
37
+ "build": "bun run clean && bun build src/index.ts --outdir dist --target node --format esm --packages external && bun run build:types",
38
+ "build:types": "tsc -p tsconfig.build.json",
39
+ "prepack": "bun run build"
40
+ },
41
+ "dependencies": {
42
+ "@charmland/gem-compiler": "0.1.0",
43
+ "@resvg/resvg-js": "^2.6.2",
44
+ "jsdom": "^30.1.3",
45
+ "satori": "^0.63.2"
46
+ },
47
+ "peerDependencies": {
48
+ "@charmland/gem": "^0.1.0",
49
+ "vite": ">=6"
50
+ },
51
+ "peerDependenciesMeta": {
52
+ "@charmland/gem": {
53
+ "optional": true
54
+ }
55
+ }
56
+ }