Diffinery

homeflare/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

437 lines · 25.4 KBRaw History
1/** @jsxImportSource hono/jsx */
2/**
3 * The public docs at /docs, readable without signing in, plus the formats AI
4 * agents read: /docs/<page>.md (or any page with `Accept: text/markdown`),
5 * /llms.txt, /llms-full.txt, /llms-small.txt, each section's /docs/<section>/llms.txt and llms-full.txt,
6 * /docs/api/openapi.json and /docs/search.json.
7 * Also serves the CLI download at /-/cli/diffinery.mjs, and the scripts that install it:
8 * `curl -fsSL https://diffinery.com/install | bash` and `irm https://diffinery.com/install.ps1 | iex`;
9 * and the extension for VS Code, Cursor and other editors built on VS Code (apps/vscode) at
10 * /-/vscode/diffinery.vsix, with /-/vscode/version.json (which it updates itself from) and its
11 * install scripts at /install-editor and /install-editor.ps1; and the plugin for JetBrains IDEs (apps/jetbrains) at
12 * /-/jetbrains/diffinery-jetbrains.zip, with /-/jetbrains/updatePlugins.xml, the custom plugin repository the IDEs
13 * install and update it from; and the Claude Code plugins (claude-plugins/) at /-/claude/<name>.zip, which
14 * `diffinery setup` downloads (agent setup scripts included) and claude.ai's Upload plugin takes.
15 */
16import { raw } from "hono/html";
17import type { AppContext } from "../auth/principal.js";
18import type { Env } from "../env.js";
19import { imageProxy } from "../lib/camo.js";
20import { isValidLogin, isValidName } from "../lib/util.js";
21import { fenceLangs, renderMarkdown } from "../web/markdown.js";
22import { fenceHighlighter } from "../web/highlight.js";
23import { ICONS } from "../web/assets.js";
24import { render, StarButton, type WebApp } from "../web/ui.js";
25import { githubStars } from "../web/github-stars.js";
26import { pluginZipFor } from "./claude-plugins.js";
27import { AGENT_SETUP_SH, CLAUDE_PLUGINS, CLI_BUNDLE, CLI_INSTALL_PS1, CLI_INSTALL_SH, CLI_SHA256, CLI_VERSION, DOCS_IMAGES, EDITOR_EXTENSION_SHA256, EDITOR_EXTENSION_VERSION, EDITOR_EXTENSION_VSIX_B64, EDITOR_INSTALL_PS1, EDITOR_INSTALL_SH, JETBRAINS_PLUGIN_DESCRIPTION, JETBRAINS_PLUGIN_SHA256, JETBRAINS_PLUGIN_SINCE_BUILD, JETBRAINS_PLUGIN_VERSION, JETBRAINS_PLUGIN_ZIP_B64 } from "./content.generated.js";
28import { allPages, getPage, headings, llmsFullTxt, llmsSmallTxt, llmsTxt, markdownUrl, nav, pageMarkdown, pageUrl, searchIndex, sectionLlmsFullTxt, sectionLlmsTxt, SLUGS, type Page } from "./pages.js";
29import { docsJsonLd } from "../web/site.js";
30import { openApiDocument } from "./reference.js";
31
32const origin = (c: AppContext) => c.env.PUBLIC_URL.replace(/\/$/, "");
33
34/** Static per deploy; a short shared cache keeps them fresh after a deploy. */
35const PUBLIC = { "cache-control": "public, max-age=300", "access-control-allow-origin": "*", "x-content-type-options": "nosniff" };
36
37const htmlCache = new Map<string, string>();
38async function pageHtml(p: Page, origin: string, env: Env): Promise<string> {
39 const key = `${origin} ${p.slug}`;
40 let html = htmlCache.get(key);
41 if (html === undefined) {
42 html = renderMarkdown(p.markdown, { idPrefix: "", highlight: await fenceHighlighter(fenceLangs(p.markdown)), image: imageProxy(env) });
43 htmlCache.set(key, html);
44 }
45 return html;
46}
47
48/** Agents ask for Markdown with `Accept: text/markdown`; browsers never do. */
49const wantsMarkdown = (c: AppContext) => /\btext\/markdown\b/i.test(c.req.header("accept") ?? "");
50
51function markdownResponse(c: AppContext, body: string): Response {
52 return c.body(body, 200, { ...PUBLIC, "content-type": "text/markdown; charset=utf-8", vary: "Accept" });
53}
54
55const Sidebar = ({ current }: { current: string }) => (
56 <nav class="docs-nav" aria-label="Documentation">
57 <div class="docs-search">
58 <input type="search" placeholder="Search the docs" aria-label="Search the docs" autocomplete="off" spellcheck={false} data-docs-search="1" />
59 <ul class="docs-results" role="listbox" hidden></ul>
60 </div>
61 {nav().map((s) => (
62 <div class="docs-sec">
63 <h4>{s.title}</h4>
64 <ul>
65 {s.pages.map((p) => (
66 <li>
67 <a href={pageUrl(p.slug)} class={p.slug === current ? "on" : undefined} aria-current={p.slug === current ? "page" : undefined}>
68 {p.title}
69 </a>
70 </li>
71 ))}
72 </ul>
73 </div>
74 ))}
75 <div class="docs-sec">
76 <h4>For AI agents</h4>
77 <ul>
78 <li>
79 <a href="/llms.txt">llms.txt</a>
80 </li>
81 <li>
82 <a href="/llms-full.txt">llms-full.txt</a>
83 </li>
84 <li>
85 <a href="/llms-small.txt">llms-small.txt</a>
86 </li>
87 <li>
88 <a href="/docs/api/openapi.json">OpenAPI 3.1</a>
89 </li>
90 </ul>
91 </div>
92 </nav>
93);
94
95async function docsPage(c: AppContext, p: Page | null, status = 200): Promise<Response> {
96 const o = origin(c);
97 const html = p ? await pageHtml(p, o, c.env) : "";
98 const slug = p?.slug ?? "";
99 const i = SLUGS.indexOf(slug);
100 const prev = i > 0 ? getPage(SLUGS[i - 1]!, o) : null;
101 const next = i >= 0 && i < SLUGS.length - 1 ? getPage(SLUGS[i + 1]!, o) : null;
102 const toc = p ? headings(p.markdown).filter((h) => h.level === 2 || p.markdown.length < 60_000) : [];
103 const stars = await githubStars(c);
104 const body = (
105 <div class="docs">
106 <style>{raw(DOCS_CSS)}</style>
107 <details class="docs-mnav">
108 <summary>{p ? `${p.section}: ${p.title}` : "Documentation"}</summary>
109 <Sidebar current={slug} />
110 </details>
111 <aside class="docs-side">
112 <Sidebar current={slug} />
113 </aside>
114 <article class="docs-main">
115 {p ? (
116 <>
117 <div class="docs-crumbs">
118 <a href="/docs">Docs</a> <span class="faint">/</span> <span class="muted">{p.section}</span>
119 </div>
120 <h1>{p.title}</h1>
121 <p class="docs-lead">{p.description}</p>
122 <div class="docs-actions">
123 <a class="btn sm" href={markdownUrl(slug)} title="This page as plain Markdown">
124 {raw(ICONS.file)} View as Markdown
125 </a>
126 <button type="button" class="btn sm" data-copy-page={markdownUrl(slug)} title="Copy this page as Markdown, to paste into an AI assistant">
127 {raw(ICONS.copy)} <span>Copy page</span>
128 </button>
129 </div>
130 <div class="markdown docs-body">{raw(html)}</div>
131 <nav class="docs-pn" aria-label="Previous and next page">
132 {prev ? (
133 <a href={pageUrl(prev.slug)} class="prev">
134 <span class="faint small">Previous</span>
135 <span>{prev.title}</span>
136 </a>
137 ) : (
138 <span />
139 )}
140 {next ? (
141 <a href={pageUrl(next.slug)} class="next">
142 <span class="faint small">Next</span>
143 <span>{next.title}</span>
144 </a>
145 ) : (
146 <span />
147 )}
148 </nav>
149 </>
150 ) : (
151 <>
152 <h1>Page not found</h1>
153 <p class="docs-lead">There's no docs page at this address. Search the docs, or start from the overview.</p>
154 <p>
155 <a class="btn primary" href="/docs">
156 Go to the overview
157 </a>
158 </p>
159 </>
160 )}
161 </article>
162 <aside class="docs-toc" aria-label="On this page">
163 {toc.length ? (
164 <>
165 <h4>On this page</h4>
166 <ul>
167 {toc.map((h) => (
168 <li class={h.level === 3 ? "l3" : undefined}>
169 <a href={`#${h.id}`}>{h.text}</a>
170 </li>
171 ))}
172 </ul>
173 </>
174 ) : null}
175 <div class="docs-star">
176 <p>Diffinery is open source. A star on GitHub helps other people find it.</p>
177 <StarButton stars={stars} compact />
178 </div>
179 </aside>
180 </div>
181 );
182 if (p) {
183 c.header("link", `<${o}${markdownUrl(slug)}>; rel="alternate"; type="text/markdown", <${o}/llms.txt>; rel="describedby"; type="text/plain"`);
184 c.header("vary", "Accept");
185 }
186 return render(
187 c,
188 {
189 title: p ? (slug === "index" ? "Documentation" : `${p.title} · Docs`) : "Page not found · Docs",
190 description: p?.description,
191 status,
192 wide: true,
193 modified: p?.updated,
194 jsonLd: p ? docsJsonLd(o, { url: `${o}${pageUrl(slug)}`, title: p.title, description: p.description, section: p.section, markdown: p.markdown, updated: p.updated, home: slug === "index" }) : undefined,
195 head: p ? <link rel="alternate" type="text/markdown" href={markdownUrl(slug)} title={`${p.title} (Markdown)`} /> : null,
196 script: DOCS_JS,
197 },
198 body,
199 );
200}
201
202/** Pages that moved, old slug to new: links people and agents saved keep working. */
203const MOVED: Record<string, string> = {
204 "agents/claude-and-codex": "connect",
205};
206
207/** The custom plugin repository JetBrains IDEs read: one plugin, the version this deploy serves. */
208export function jetbrainsRepository(origin: string, fileName: string): string {
209 const description = JETBRAINS_PLUGIN_DESCRIPTION.replaceAll("https://diffinery.com", origin).replaceAll("]]>", "]]]]><![CDATA[>");
210 return `<?xml version="1.0" encoding="UTF-8"?>
211<plugins>
212 <plugin id="com.diffinery" url="${origin}/-/jetbrains/${fileName}" version="${JETBRAINS_PLUGIN_VERSION}">
213 <idea-version since-build="${JETBRAINS_PLUGIN_SINCE_BUILD}"/>
214 <name>Diffinery</name>
215 <vendor url="${origin}">Diffinery</vendor>
216 <description><![CDATA[${description}]]></description>
217 </plugin>
218</plugins>
219`;
220}
221
222export function registerDocs(web: WebApp): void {
223 web.get("/llms.txt", (c) => c.body(llmsTxt(origin(c)), 200, { ...PUBLIC, "content-type": "text/plain; charset=utf-8" }));
224 web.get("/llms-full.txt", (c) => c.body(llmsFullTxt(origin(c)), 200, { ...PUBLIC, "content-type": "text/plain; charset=utf-8" }));
225 web.get("/llms-small.txt", (c) => c.body(llmsSmallTxt(origin(c)), 200, { ...PUBLIC, "content-type": "text/plain; charset=utf-8" }));
226 web.get("/docs/llms.txt", (c) => c.redirect("/llms.txt", 301));
227 web.get("/docs/llms-full.txt", (c) => c.redirect("/llms-full.txt", 301));
228 // One docs section at a time (pages.ts SECTIONS), for assistants that only need, say, the Actions pages.
229 web.get("/docs/:section/llms.txt", (c) => {
230 const txt = sectionLlmsTxt(origin(c), c.req.param("section"));
231 return txt ? c.body(txt, 200, { ...PUBLIC, "content-type": "text/plain; charset=utf-8" }) : c.text(`No such docs section. See ${origin(c)}/llms.txt\n`, 404);
232 });
233 web.get("/docs/:section/llms-full.txt", (c) => {
234 const txt = sectionLlmsFullTxt(origin(c), c.req.param("section"));
235 return txt ? c.body(txt, 200, { ...PUBLIC, "content-type": "text/plain; charset=utf-8" }) : c.text(`No such docs section. See ${origin(c)}/llms.txt\n`, 404);
236 });
237 web.get("/docs/api/openapi.json", (c) => c.body(JSON.stringify(openApiDocument(origin(c), CLI_VERSION), null, 2), 200, { ...PUBLIC, "content-type": "application/json; charset=utf-8" }));
238 web.get("/docs/search.json", (c) => c.body(JSON.stringify(searchIndex(origin(c))), 200, { ...PUBLIC, "content-type": "application/json; charset=utf-8" }));
239 web.get("/-/cli/diffinery.mjs", (c) =>
240 c.body(CLI_BUNDLE, 200, {
241 ...PUBLIC,
242 "content-type": "text/javascript; charset=utf-8",
243 "content-disposition": 'inline; filename="diffinery.mjs"',
244 "x-diffinery-cli-version": CLI_VERSION,
245 }),
246 );
247
248 // The install scripts download the CLI from the server that served them (a self-hosted instance installs its own build).
249 const installScript = (c: AppContext, script: string) =>
250 c.body(script.replaceAll("__DIFFINERY_URL__", origin(c)), 200, { ...PUBLIC, "content-type": "text/plain; charset=utf-8", "x-diffinery-cli-version": CLI_VERSION });
251 web.get("/install", (c) => installScript(c, CLI_INSTALL_SH));
252 web.get("/install.sh", (c) => installScript(c, CLI_INSTALL_SH));
253 web.get("/install.ps1", (c) => installScript(c, CLI_INSTALL_PS1));
254 // Agent setup's script (lib/agent-setup.ts): the same for everyone, with the repository's name in it. It
255 // looks nothing up, so it says nothing about whether the repository exists, and it holds no secret.
256 web.get("/:owner/:repo/agent-setup.sh", (c) => {
257 const owner = c.req.param("owner");
258 const repo = c.req.param("repo");
259 if (!isValidLogin(owner) || !isValidName(repo)) return c.text("not a repository name\n", 404);
260 const script = AGENT_SETUP_SH.replaceAll("__DIFFINERY_URL__", origin(c)).replaceAll("__DIFFINERY_REPO__", `${owner}/${repo}`).replaceAll("__DIFFINERY_CLI_SHA256__", CLI_SHA256);
261 return c.body(script, 200, { ...PUBLIC, "content-type": "text/plain; charset=utf-8", "x-diffinery-cli-version": CLI_VERSION });
262 });
263
264 const vsixName = `diffinery-${EDITOR_EXTENSION_VERSION}.vsix`;
265 let vsix: Uint8Array<ArrayBuffer> | undefined;
266 const vsixBody = (c: AppContext) => {
267 vsix ??= Uint8Array.from(atob(EDITOR_EXTENSION_VSIX_B64), (ch) => ch.charCodeAt(0));
268 return c.body(vsix, 200, {
269 ...PUBLIC,
270 "content-type": "application/octet-stream",
271 "content-disposition": `attachment; filename="${vsixName}"`,
272 "x-diffinery-extension-version": EDITOR_EXTENSION_VERSION,
273 });
274 };
275 web.get("/-/vscode/diffinery.vsix", vsixBody);
276 web.get(`/-/vscode/${vsixName}`, vsixBody);
277 web.get("/-/vscode/version.json", (c) =>
278 c.json({ version: EDITOR_EXTENSION_VERSION, url: `/-/vscode/${vsixName}`, sha256: EDITOR_EXTENSION_SHA256 }, 200, PUBLIC),
279 );
280 web.get("/install-editor", (c) => installScript(c, EDITOR_INSTALL_SH));
281 web.get("/install-editor.sh", (c) => installScript(c, EDITOR_INSTALL_SH));
282 web.get("/install-editor.ps1", (c) => installScript(c, EDITOR_INSTALL_PS1));
283
284 // JetBrains IDEs install the plugin from a custom plugin repository: Settings → Plugins → ⚙ → Manage Plugin
285 // Repositories → this updatePlugins.xml. They check it for updates like the Marketplace.
286 const pluginName = `diffinery-jetbrains-${JETBRAINS_PLUGIN_VERSION}.zip`;
287 let pluginZip: Uint8Array<ArrayBuffer> | undefined;
288 const pluginBody = (c: AppContext) => {
289 pluginZip ??= Uint8Array.from(atob(JETBRAINS_PLUGIN_ZIP_B64), (ch) => ch.charCodeAt(0));
290 return c.body(pluginZip, 200, {
291 ...PUBLIC,
292 "content-type": "application/zip",
293 "content-disposition": `attachment; filename="${pluginName}"`,
294 "x-diffinery-plugin-version": JETBRAINS_PLUGIN_VERSION,
295 "x-diffinery-plugin-sha256": JETBRAINS_PLUGIN_SHA256,
296 });
297 };
298 web.get("/-/jetbrains/diffinery-jetbrains.zip", pluginBody);
299 web.get(`/-/jetbrains/${pluginName}`, pluginBody);
300 web.get("/-/jetbrains/updatePlugins.xml", (c) =>
301 c.body(jetbrainsRepository(origin(c), pluginName), 200, { ...PUBLIC, "content-type": "application/xml; charset=utf-8" }),
302 );
303
304 // The Claude Code plugins, for `diffinery setup` (which checks the SHA-256 header) and claude.ai's Upload
305 // plugin, neither of which can read the plugin repository. /-/claude/<name>.zip is always the current version; the versioned name stays the same bytes.
306 // A self-hosted instance's copies point the plugins at itself (claude-plugins.ts).
307 const claudeZips = new Map<string, Promise<{ bytes: Uint8Array; sha256: string }>>();
308 web.get("/-/claude/:file", async (c) => {
309 const file = c.req.param("file");
310 const m = /^([a-z][a-z0-9-]*?)(?:-(\d+\.\d+\.\d+))?\.zip$/.exec(file);
311 const plugin = m && Object.hasOwn(CLAUDE_PLUGINS, m[1]!) ? CLAUDE_PLUGINS[m[1]!]! : null;
312 if (!m || !plugin || (m[2] !== undefined && m[2] !== plugin.version)) return c.text("Not found", 404);
313 const key = `${origin(c)} ${m[1]}`;
314 let built = claudeZips.get(key);
315 if (!built) {
316 claudeZips.set(key, (built = pluginZipFor(origin(c), Uint8Array.from(atob(plugin.zip), (ch) => ch.charCodeAt(0)), plugin.sha256)));
317 built.catch(() => claudeZips.delete(key));
318 }
319 const { bytes, sha256 } = await built;
320 return c.body(bytes as Uint8Array<ArrayBuffer>, 200, {
321 ...PUBLIC,
322 "content-type": "application/zip",
323 "content-disposition": `attachment; filename="${m[1]}-${plugin.version}.zip"`,
324 "x-diffinery-plugin-version": plugin.version,
325 "x-diffinery-plugin-sha256": sha256,
326 });
327 });
328
329 // Pictures for the docs pages (docs/images/), decoded once per isolate.
330 const images = new Map<string, Uint8Array<ArrayBuffer>>();
331 web.get("/docs/images/:file", (c) => {
332 const name = c.req.param("file");
333 const img = Object.hasOwn(DOCS_IMAGES, name) ? DOCS_IMAGES[name]! : null;
334 if (!img) return c.text("Not found", 404);
335 let bytes = images.get(name);
336 if (!bytes) images.set(name, (bytes = Uint8Array.from(atob(img.data), (ch) => ch.charCodeAt(0))));
337 return c.body(bytes, 200, { ...PUBLIC, "cache-control": "public, max-age=86400", "content-type": img.type });
338 });
339
340 web.get("/docs", (c) => {
341 const p = getPage("index", origin(c))!;
342 return wantsMarkdown(c) ? markdownResponse(c, pageMarkdown(p, origin(c))) : docsPage(c, p);
343 });
344 web.get("/docs/:slug{.+}", (c) => {
345 let slug = c.req.param("slug").replace(/\/+$/, "");
346 if (c.req.path.endsWith("/") && slug) return c.redirect(pageUrl(slug), 301);
347 const md = slug.endsWith(".md");
348 if (md) slug = slug.slice(0, -3);
349 if (slug === "index" && !md) return c.redirect("/docs", 301);
350 if (Object.hasOwn(MOVED, slug)) return c.redirect(md ? markdownUrl(MOVED[slug]!) : pageUrl(MOVED[slug]!), 301);
351 const p = getPage(slug, origin(c));
352 if (!p) {
353 if (md) return c.body(`# Not found\n\nThere is no docs page "${slug}". See ${origin(c)}/llms.txt for every page.\n`, 404, { "content-type": "text/markdown; charset=utf-8" });
354 return docsPage(c, null, 404);
355 }
356 return md || wantsMarkdown(c) ? markdownResponse(c, pageMarkdown(p, origin(c))) : docsPage(c, p);
357 });
358}
359
360/** Every docs URL for the sitemap, with the date the page was last reviewed when its frontmatter says. */
361export const docsSitemapEntries = (): Array<{ path: string; updated?: string }> => SLUGS.map((slug) => ({ path: pageUrl(slug), updated: getPage(slug, "")?.updated }));
362export { allPages };
363
364const DOCS_CSS = `
365main.wrap:has(.docs){padding-top:0}
366.docs{display:grid;grid-template-columns:248px minmax(0,1fr) 220px;gap:40px;max-width:1240px;margin:0 auto}
367.docs-side,.docs-toc{position:sticky;top:52px;align-self:start;max-height:calc(100vh - 52px);overflow:auto;padding:20px 0 40px}
368.docs-nav h4,.docs-toc h4{font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--fg3);margin:18px 0 6px;font-weight:600}
369.docs-nav ul,.docs-toc ul{list-style:none;margin:0;padding:0}
370.docs-nav li a{display:block;padding:4px 10px;border-radius:6px;color:var(--fg2);font-size:13.5px}
371.docs-nav li a:hover{background:var(--bg-hover);color:var(--fg);text-decoration:none}
372.docs-nav li a.on{background:var(--accent-soft);color:var(--fg);font-weight:550}
373.docs-search{position:relative}
374.docs-results{position:absolute;z-index:30;left:0;right:-160px;top:calc(100% + 4px);background:var(--bg);border:1px solid var(--border);border-radius:var(--r);box-shadow:var(--shadow);list-style:none;margin:0;padding:4px;max-height:60vh;overflow:auto}
375.docs-results li a{display:block;padding:7px 10px;border-radius:6px;color:var(--fg)}
376.docs-results li a:hover,.docs-results li.sel a{background:var(--bg-hover);text-decoration:none}
377.docs-results .r-t{font-weight:550}.docs-results .r-s{display:block;font-size:12px;color:var(--fg2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
378.docs-results .r-none{padding:8px 10px;color:var(--fg2)}
379.docs-main{padding:28px 0 60px;min-width:0}
380.docs-main h1{font-size:30px;letter-spacing:-.02em;margin:6px 0 8px}
381.docs-crumbs{font-size:13px}
382.docs-lead{font-size:16px;color:var(--fg2);margin:0 0 14px}
383.docs-actions{display:flex;gap:8px;flex-wrap:wrap;margin:0 0 22px;padding-bottom:18px;border-bottom:1px solid var(--border2)}
384.docs-actions .st svg{width:14px;height:14px}
385.docs-body{font-size:15px;line-height:1.7}
386.docs-body h2{font-size:21px;margin-top:34px;scroll-margin-top:64px}.docs-body h3{font-size:16.5px;margin-top:26px;scroll-margin-top:64px}.docs-body h4{scroll-margin-top:64px}
387.docs-body pre{position:relative}.docs-body pre .cp{position:absolute;top:6px;right:6px;opacity:0;transition:opacity .15s}
388.docs-body pre:hover .cp,.docs-body pre .cp:focus{opacity:1}
389.docs-body blockquote{background:var(--bg2);border-left-color:var(--accent);border-radius:0 6px 6px 0;padding:10px 14px;color:var(--fg)}
390.docs-body blockquote p:last-child{margin:0}
391.docs-body table{font-size:13.5px}.docs-body td code{white-space:nowrap}
392.docs-body p>img{display:block;width:auto;max-width:100%;max-height:640px;margin:18px auto;border:1px solid var(--border);border-radius:10px;box-shadow:var(--shadow)}
393.docs-pn{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:40px;padding-top:20px;border-top:1px solid var(--border2)}
394.docs-pn a{display:flex;flex-direction:column;gap:2px;padding:12px 14px;border:1px solid var(--border);border-radius:var(--r);color:var(--fg)}
395.docs-pn a:hover{border-color:var(--accent);text-decoration:none}.docs-pn .next{text-align:right}
396.docs-toc li a{display:block;padding:3px 0 3px 10px;border-left:2px solid var(--border2);color:var(--fg2);font-size:12.5px;line-height:1.4}
397.docs-toc li.l3 a{padding-left:22px}
398.docs-toc li a:hover{color:var(--fg);text-decoration:none}.docs-toc li a.on{color:var(--fg);border-left-color:var(--accent)}
399.docs-star{margin-top:22px;padding-top:16px;border-top:1px solid var(--border2)}.docs-star p{margin:0 0 10px;font-size:12.5px;line-height:1.5;color:var(--fg2)}
400.docs-mnav{display:none}
401@media (max-width:1180px){.docs{grid-template-columns:232px minmax(0,1fr);gap:32px}.docs-toc{display:none}}
402@media (max-width:820px){.docs{grid-template-columns:minmax(0,1fr);gap:0}.docs-side{display:none}
403.docs-mnav{display:block;position:sticky;top:52px;z-index:15;background:var(--canvas);border-bottom:1px solid var(--border);margin:0 -12px;padding:0 12px}
404.docs-mnav summary{padding:10px 0;cursor:pointer;font-weight:550}.docs-mnav[open]{max-height:calc(100vh - 52px);overflow:auto}
405.docs-results{right:0}.docs-main{padding-top:16px}.docs-main h1{font-size:25px}}
406`;
407
408const DOCS_JS = `(()=>{
409const d=document,$=(s,r=d)=>r.querySelector(s),$$=(s,r=d)=>[...r.querySelectorAll(s)];
410// Copy buttons on code blocks.
411$$('.docs-body pre').forEach(pre=>{const b=d.createElement('button');b.type='button';b.className='btn sm cp';b.textContent='Copy';
412 b.addEventListener('click',()=>{const t=(pre.querySelector('code')||pre).innerText;navigator.clipboard.writeText(t).then(()=>{b.textContent='Copied';setTimeout(()=>{b.textContent='Copy'},1200)})});pre.appendChild(b)});
413// Copy the whole page as Markdown.
414$$('[data-copy-page]').forEach(b=>b.addEventListener('click',async()=>{const s=b.querySelector('span');
415 try{const r=await fetch(b.dataset.copyPage,{headers:{accept:'text/markdown'}});await navigator.clipboard.writeText(await r.text());s.textContent='Copied'}catch(_){s.textContent='Copy failed'}
416 setTimeout(()=>{s.textContent='Copy page'},1500)}));
417// Highlight the current section in "On this page".
418const toc=$$('.docs-toc a');if(toc.length&&'IntersectionObserver'in window){const map=new Map(toc.map(a=>[decodeURIComponent(a.hash.slice(1)),a]));
419 const io=new IntersectionObserver(es=>{es.forEach(e=>{if(e.isIntersecting){toc.forEach(a=>a.classList.remove('on'));const a=map.get(e.target.id);a&&a.classList.add('on')}})},{rootMargin:'-60px 0px -70% 0px'});
420 $$('.docs-body h2[id],.docs-body h3[id]').forEach(h=>io.observe(h))}
421// Search: a small index fetched on first use, ranked by title, heading and text matches.
422let idx=null,loading=null;const load=()=>loading||(loading=fetch('/docs/search.json').then(r=>r.json()).then(j=>{idx=j.map(p=>Object.assign(p,{tl:p.t.toLowerCase(),xl:p.x.toLowerCase(),hl:p.h.map(h=>h[1].toLowerCase())}))}));
423const esc=s=>s.replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
424function search(q){const terms=q.toLowerCase().split(/\\s+/).filter(Boolean);if(!terms.length||!idx)return[];const out=[];
425 for(const p of idx){let score=0,hit=null;for(const t of terms){let s=0;if(p.tl.includes(t))s+=10;p.hl.forEach((h,i)=>{if(h.includes(t)){s+=4;if(!hit)hit=p.h[i]}});if(p.xl.includes(t))s+=1;if(!s){score=0;break}score+=s}
426 if(score){const pos=p.xl.indexOf(terms[0]);out.push({p,score,hit,snip:pos>=0?p.x.slice(Math.max(0,pos-40),pos+90):p.d})}}
427 return out.sort((a,b)=>b.score-a.score).slice(0,12)}
428$$('[data-docs-search]').forEach(inp=>{const list=inp.parentElement.querySelector('.docs-results');let sel=-1;
429 const show=()=>{const q=inp.value.trim();if(!q){list.hidden=true;return}const rs=search(q);sel=-1;list.hidden=false;
430 list.innerHTML=rs.length?rs.map(r=>{const href=(r.p.u||(r.p.s==='index'?'/docs':'/docs/'+r.p.s))+(r.hit?'#'+r.hit[0]:'');
431 return '<li><a href="'+esc(href)+'"><span class="r-t">'+esc(r.p.t)+(r.hit?' › '+esc(r.hit[1]):'')+'</span><span class="r-s">'+esc(r.p.c+' · '+r.snip)+'</span></a></li>'}).join(''):'<li class="r-none">No results</li>'};
432 inp.addEventListener('focus',()=>{load().then(show)});inp.addEventListener('input',()=>{load().then(show)});
433 inp.addEventListener('keydown',e=>{const items=$$('li a',list);if(e.key==='ArrowDown'||e.key==='ArrowUp'){e.preventDefault();sel=(sel+(e.key==='ArrowDown'?1:-1)+items.length)%items.length;
434 $$('li',list).forEach((li,i)=>li.classList.toggle('sel',i===sel))}else if(e.key==='Enter'){const a=items[sel<0?0:sel];if(a){e.preventDefault();location.assign(a.href)}}else if(e.key==='Escape'){list.hidden=true;inp.blur()}});
435 d.addEventListener('click',e=>{if(!inp.parentElement.contains(e.target))list.hidden=true})});
436d.addEventListener('keydown',e=>{if(e.key==='/'&&!/input|textarea|select/i.test((e.target.tagName||''))&&!e.target.isContentEditable){const i=$$('[data-docs-search]').find(x=>x.offsetParent);if(i){e.preventDefault();i.focus()}}});
437})();`;