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.

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