feat(site): ship the restyled docs to opencode.ai (#62466)

This commit is contained in:
Adam
2026-11-06 19:22:25 -06:00
committed by GitHub
Unverified
parent c045c7cfdc
commit a1dfa56c17
25 changed files with 33 additions and 2740 deletions
+1 -1
View File
@@ -37,7 +37,7 @@ await Bun.$`bun ./script/og.ts`.cwd(root).env(env)
await Bun.$`bun ./textjs/script/build.ts`.cwd(root).env(env)
await Bun.$`vite build`.cwd(root).env(env)
// The V2 docs at /docs: prerendered pages, Markdown twins and search (src/docs/script/build.ts).
await Bun.$`bun ./src/docs/script/build.ts --mode ${mode}`.cwd(root).env(env)
await Bun.$`bun ./src/docs/script/build.ts`.cwd(root).env(env)
await Bun.$`bun ./script/check-server-bundle.ts`.cwd(root).env(env)
await Bun.$`bun ./script/check-client-bundle.ts`.cwd(root).env(env)
await Bun.$`bun ./script/check-css-output.ts`.cwd(root).env(env)
+3 -8
View File
@@ -10,14 +10,9 @@
- Keep internal Markdown links docs-root-relative, for example `/config`; `remark-links.ts` adds `/docs`.
- Components used in MDX are registered in `document.tsx`. Named slots work as in Astro: `<div slot="go">` inside a component becomes that slot's content (`remark-slots.ts`, `components/Slot.tsx`).
## Restyle
- The docs are moving into the site's shell and David's docs components (the site's `DESIGN.md`, `component/site/docs-variants.css`). The build's mode picks the design, through `restyled` in `config.ts`: `--mode dev` (dev.opencode.ai and CI) and the development server render the restyle, and the production build (opencode.ai) still renders the old docs, whose code is in `legacy/` (its document, layout, components, rehype plugins, `client.ts` and `styles/global.css`). CI builds the dev mode (`.github/workflows/check-docs.yml`), and each deploy builds its own mode.
- Change the restyle, not `legacy/`; `legacy/` only takes fixes production needs before the flip.
- To ship the restyle to opencode.ai once David approves it: make `restyled` return `true`, then delete `legacy/`, the `restyle` option in `vite.ts`, `script/build.ts` and `render.tsx`, `restyle` in `virtual:docs-pages` (`modules.d.ts`), the switch itself, and this section, and build with both modes.
## Rendering
- The docs use the site's shell and David's docs components (the site's `DESIGN.md`, `component/site/docs-variants.css`), and every deploy builds the same docs.
- Pages are plain HTML in the site's docs layout (`layouts/DocsLayout.tsx`: the root attributes production renders, the logo and section lockup, the section nav, the article, search and Contents, and the site's footer). They render the site's own components on the server (`component/site/`: `DocsLockup`, `CodeFrame`, `FileTree`, `HeadingLink`, `OnThisPage`, `ContentsMenu`, the phone menu, the footer's parts) with the English strings, and never hydrate. Use those components instead of copying their markup; a component the docs need to drive from `client.ts` renders its state as attributes (`hidden`, `aria-expanded`, `data-state`, `data-code`).
- A page links its stylesheet, `styles/docs.css` (the site's stylesheets, `docs-variants.css` and the docs' own base rules, built with the site's production CSS plugins), and the one browser script, `client.ts`. They never load the site's built files, and the site's pages never load the docs'.
- Everything a page loads lives under `/docs` (the stylesheet, script and fonts are built to `/docs/_build`, images are in `public/docs/assets`), so the docs never depend on the site's files and never collide with them (the site's own build files are at `/_build`). The build fails otherwise.
@@ -28,8 +23,8 @@
## Build and serving
- `script/build.ts` runs after the site's `vite build` (from `script/build.ts` at the site root): it builds the docs' stylesheet and script, prerenders every page, every content page's Markdown twin (`/docs/config.md`; the intro's is `/docs/index.md`), `llms.txt` and the sitemap into `.output/public`, builds the Pagefind index, and checks every link, that nothing loads from outside `/docs` and that no page takes a reserved file name. `llms.txt` and the sitemap list opencode.ai's URLs in every mode, so dev never advertises its own.
- Pull requests that touch the site run the same build on its own (`.github/workflows/check-docs.yml`): `bun run generate`, then `bun src/docs/script/build.ts --mode dev --out <dir>`.
- `script/build.ts` runs after the site's `vite build` (from `script/build.ts` at the site root): it builds the docs' stylesheet and script, prerenders every page, every content page's Markdown twin (`/docs/config.md`; the intro's is `/docs/index.md`), `llms.txt` and the sitemap into `.output/public`, builds the Pagefind index, and checks every link, that nothing loads from outside `/docs` and that no page takes a reserved file name. `llms.txt` and the sitemap list opencode.ai's URLs on dev.opencode.ai too, so dev never advertises its own.
- Pull requests that touch the site run the same build on its own (`.github/workflows/check-docs.yml`): `bun run generate`, then `bun src/docs/script/build.ts --out <dir>`.
- The Worker never renders docs. `middleware.ts` serves the prerendered files: docs URLs reach it first (`runWorkerFirst` in `cloudflare.config.ts`), so a page's URL answers `Accept: text/markdown` with its twin. `vite dev` has no prerendered files, so the development server renders on request.
- `/docs` still receives the V1 docs' old links, which had more pages and other languages (`/docs/ja/...`). `middleware.ts` redirects any `/docs` path that isn't a page here (`virtual:docs-pages`, the same list the build prerenders) to the same path on the V1 docs with a 302, so adding a page here takes its URL over. The old `/v2` URLs redirect to `/docs` permanently (`src/lib/legacy.ts`).
-6
View File
@@ -7,9 +7,3 @@ export const base = "/docs/"
// one of these names (script/build.ts checks), the Worker serves them before the docs middleware
// (cloudflare.config.ts runWorkerFirst), and a missing one is a 404 rather than a V1 fallback.
export const files = ["_build", "assets", "pagefind", "favicon.svg", "llms.txt", "sitemap.xml", "openapi.json"]
// The restyle (the site's shell and David's docs components) builds for dev.opencode.ai first: the
// `--mode dev` build (dev.opencode.ai and CI) and the development server render it, while the
// production build keeps the docs as they were (legacy/) until David signs off. To ship it to
// opencode.ai, return true here, then delete legacy/ and this switch (AGENTS.md, "Restyle").
export const restyled = (mode: "dev" | "production") => mode === "dev"
-217
View File
@@ -1,217 +0,0 @@
// The docs pages' only script: search, copy buttons, tabs, the status link and the funnel. Pages are
// plain HTML (no hydration); everything here is delegated from the document, so it needs no
// per-element setup. The theme toggle is in the layout's head script, so it works before this loads.
import { Funnel } from "../../lib/funnel"
import { downloadOf, surfaceOf, targetOf } from "../../lib/funnel-config"
// The page reports to the Console's funnel like the site's (lib/funnel.ts). The docs are English, at the host's root
// like the site; their config is built in, as a chunk would bring Vite's preload helper with it.
Funnel.start(async () => ({ surfaceOf, targetOf, localeOf: () => "en", base: "", downloadOf }))
type PagefindResult = { url: string; excerpt: string; meta: { title: string } }
type Pagefind = { search(query: string): Promise<{ results: { data(): Promise<PagefindResult> }[] }> }
let pagefind: Promise<Pagefind> | undefined
// Pagefind is loaded from its built file on first search. Through `Function` because Vite would wrap
// a plain import() in its preload helper, a second script on every page for a file it can't preload.
const load = new Function("url", "return import(url)") as (url: string) => Promise<Pagefind>
const dialog = document.querySelector<HTMLDialogElement>("[data-search-dialog]")
const input = document.querySelector<HTMLInputElement>("[data-search-input]")
const results = document.querySelector<HTMLElement>("[data-search-results]")
// Whether a result was chosen since the search opened, so closing it then isn't a dismissal.
let chosen = false
function openSearch(via: "shortcut" | "button") {
if (dialog && !dialog.open)
Funnel.track({ name: "search.opened", action: "opened", target: via, properties: { kind: "docs" } })
chosen = false
dialog?.showModal()
input?.focus()
}
// How many results showed for how many characters; never what was typed.
const searched = () => ({
results: results?.querySelectorAll("a").length ?? 0,
query_len: input?.value.trim().length ?? 0,
})
dialog?.addEventListener("close", () => {
if (!chosen) Funnel.track({ name: "search.closed", action: "dismissed", target: "", properties: searched() })
})
// A chosen result, captured on the window so it's reported before the tracker's own report of the click sends what's
// waiting as the result's page loads.
window.addEventListener(
"click",
(event) => {
const result = event.target instanceof Element && event.target.closest<HTMLAnchorElement>("[data-search-results] a")
if (!result) return
chosen = true
const target = `link:${new URL(result.href).pathname}`.replace(/[^A-Za-z0-9/_.:+-]+/g, "-").slice(0, 96)
const rank = [...(results?.querySelectorAll("a") ?? [])].indexOf(result) + 1
Funnel.track({ name: "search.selected", action: "selected", target, properties: { rank, ...searched() } })
},
true,
)
document.addEventListener("keydown", (event) => {
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
event.preventDefault()
openSearch("shortcut")
}
})
input?.addEventListener("input", async () => {
if (!dialog || !results) return
const query = input.value.trim()
if (!query) {
results.innerHTML = "<p>Start typing to search the documentation.</p>"
return
}
const path = dialog.dataset.pagefindPath
if (!path) return
pagefind ??= load(path)
const search = await (await pagefind).search(query)
const pages = await Promise.all(search.results.slice(0, 8).map((result) => result.data()))
const base = dialog.dataset.baseUrl ?? "/"
results.replaceChildren(
...pages.map((page) => {
const link = document.createElement("a")
link.href = page.url.startsWith(base) ? page.url : `${base.replace(/\/$/, "")}${page.url}`
const title = document.createElement("strong")
title.textContent = page.meta.title
const excerpt = document.createElement("span")
excerpt.innerHTML = page.excerpt
link.append(title, excerpt)
return link
}),
)
if (!pages.length) results.innerHTML = "<p>No results found.</p>"
})
document.addEventListener("click", async (event) => {
if (!(event.target instanceof Element)) return
if (event.target.closest("[data-search-open]")) return openSearch("button")
const code = event.target.closest<HTMLButtonElement>("[data-copy-code]")
if (code) {
await navigator.clipboard.writeText(code.dataset.code ?? "")
code.textContent = "Copied"
window.setTimeout(() => (code.textContent = "Copy"), 1500)
return
}
const tab = event.target.closest<HTMLButtonElement>("[data-code-tab]")
if (tab) return selectCodeTab(tab)
const plan = event.target.closest<HTMLButtonElement>("[data-plan-tab]")
const plans = plan?.closest<HTMLElement>("[data-plan-tabs]")
if (plan?.dataset.planTab && plans) return selectSyncedPlan(plans, plan.dataset.planTab)
const markdown = event.target.closest<HTMLButtonElement>("[data-copy-markdown]")
if (markdown) {
markdown.dataset.copied = "true"
markdown.setAttribute("aria-label", "Copied")
window.setTimeout(() => {
delete markdown.dataset.copied
markdown.setAttribute("aria-label", "Copy page as Markdown")
}, 1500)
const response = await fetch(window.location.href, { headers: { Accept: "text/markdown" } })
if (!response.ok) return
await navigator.clipboard.writeText(await response.text())
}
})
// Arrow keys, Home and End move between tabs.
document.addEventListener("keydown", (event) => {
if (!(event.target instanceof HTMLButtonElement)) return
const tabs = event.target.closest<HTMLElement>("[data-code-tabs], [data-plan-tabs]")
if (!tabs || !event.target.matches("[data-code-tab], [data-plan-tab]")) return
const buttons = [...tabs.querySelectorAll<HTMLButtonElement>("[data-code-tab], [data-plan-tab]")]
const selected = buttons.indexOf(event.target)
const next =
event.key === "Home"
? buttons[0]
: event.key === "End"
? buttons.at(-1)
: event.key === "ArrowRight"
? buttons[(selected + 1) % buttons.length]
: event.key === "ArrowLeft"
? buttons[(selected - 1 + buttons.length) % buttons.length]
: undefined
if (!next) return
event.preventDefault()
if (next.dataset.planTab) selectSyncedPlan(tabs, next.dataset.planTab)
else selectCodeTab(next)
next.focus()
})
function selectCodeTab(button: HTMLButtonElement) {
const tabs = button.closest<HTMLElement>("[data-code-tabs]")
if (!tabs) return
const buttons = [...tabs.querySelectorAll<HTMLButtonElement>("[data-code-tab]")]
const selected = buttons.indexOf(button)
buttons.forEach((item, index) => {
item.setAttribute("aria-selected", String(index === selected))
item.tabIndex = index === selected ? 0 : -1
})
tabs.querySelectorAll<HTMLElement>("[data-code-panel]").forEach((panel, index) => (panel.hidden = index !== selected))
}
function selectPlan(tabs: HTMLElement, plan: string) {
tabs.querySelectorAll<HTMLButtonElement>("[data-plan-tab]").forEach((button) => {
const selected = button.dataset.planTab === plan
button.setAttribute("aria-selected", String(selected))
button.tabIndex = selected ? 0 : -1
})
tabs.querySelectorAll<HTMLElement>("[data-plan-panel]").forEach((panel) => {
panel.hidden = panel.dataset.planPanel !== plan
})
}
// Plan tabs with the same sync key switch together, and the choice is remembered.
function selectSyncedPlan(source: HTMLElement, plan: string) {
const syncKey = source.dataset.syncKey
if (!syncKey) return
document.querySelectorAll<HTMLElement>("[data-plan-tabs]").forEach((tabs) => {
if (tabs.dataset.syncKey === syncKey) selectPlan(tabs, plan)
})
localStorage.setItem(`docs-plan-tabs:${syncKey}`, plan)
}
document.querySelectorAll<HTMLElement>("[data-plan-tabs]").forEach((tabs) => {
const plan = tabs.dataset.syncKey && localStorage.getItem(`docs-plan-tabs:${tabs.dataset.syncKey}`)
if (plan) selectPlan(tabs, plan)
})
// The status page's summary. Each page is a full load, so the last answer is kept for a minute in
// sessionStorage: the next page shows it at once instead of fetching again.
const labels = {
operational: "All systems operational",
degraded: "Degraded performance",
outage: "Service disruption",
}
type Status = keyof typeof labels
function showStatus(status: Status) {
const link = document.querySelector<HTMLAnchorElement>(".system-status")
if (!link) return
link.dataset.status = status
link.textContent = labels[status]
}
const cached = (() => {
const value = JSON.parse(sessionStorage.getItem("docs-status") ?? "null") as { status: Status; at: number } | null
return value && value.status in labels ? value : undefined
})()
if (cached) showStatus(cached.status)
if (!cached || Date.now() - cached.at > 60_000)
fetch("/status/api/summary", { signal: AbortSignal.timeout(10_000) })
.then((response) => (response.ok ? response.json() : undefined))
.then((body: unknown) => {
const status = body && typeof body === "object" && "status" in body ? body.status : undefined
if (status !== "operational" && status !== "degraded" && status !== "outage") return
sessionStorage.setItem("docs-status", JSON.stringify({ status, at: Date.now() }))
showStatus(status)
})
.catch(() => undefined)
@@ -1,12 +0,0 @@
import type { JSX } from "solid-js"
export function Callout(props: { type?: "note" | "tip" | "warning"; title?: string; children?: JSX.Element }) {
const type = props.type ?? "note"
const title = props.title ?? (type === "tip" ? "Tip" : type === "warning" ? "Warning" : "Note")
return (
<aside class={`callout callout-${type}`} aria-label={title}>
<strong>{title}</strong>
<div>{props.children}</div>
</aside>
)
}
@@ -1,12 +0,0 @@
import type { JSX } from "solid-js"
import { base } from "../../config"
export function Card(props: { title: string; href: string; children?: JSX.Element }) {
const href = props.href.startsWith("/") ? `${base.slice(0, -1)}${props.href}` : props.href
return (
<a class="docs-card" href={href}>
<strong>{props.title}</strong>
<div>{props.children}</div>
</a>
)
}
@@ -1,9 +0,0 @@
import type { JSX } from "solid-js"
export function CardGroup(props: { cols?: number; children?: JSX.Element }) {
return (
<div class="docs-card-group" style={`--card-columns: ${props.cols ?? 2}`}>
{props.children}
</div>
)
}
@@ -1,13 +0,0 @@
// The copy button works through client.ts.
export function CodeBlock(props: { code: string }) {
return (
<div class="docs-code-block" data-funnel-copy="snippet">
<pre>
<code>{props.code}</code>
</pre>
<button type="button" data-copy-code data-code={props.code}>
Copy
</button>
</div>
)
}
@@ -1,41 +0,0 @@
import { For } from "solid-js"
import { CodeBlock } from "./CodeBlock"
// The tabs switch through client.ts.
export function CodeTabs(props: { id: string; label: string; tabs: { label: string; code: string }[] }) {
return (
<div class="docs-code-tabs" data-code-tabs>
<div class="docs-code-tabs-list" role="tablist" aria-label={props.label}>
<For each={props.tabs}>
{(tab, index) => (
<button
type="button"
role="tab"
id={`${props.id}-tab-${index()}`}
aria-controls={`${props.id}-panel-${index()}`}
aria-selected={index() === 0 ? "true" : "false"}
tabindex={index() === 0 ? 0 : -1}
data-code-tab
data-funnel={`code-tab:${tab.label}`}
>
{tab.label}
</button>
)}
</For>
</div>
<For each={props.tabs}>
{(tab, index) => (
<div
role="tabpanel"
id={`${props.id}-panel-${index()}`}
aria-labelledby={`${props.id}-tab-${index()}`}
hidden={index() !== 0}
data-code-panel
>
<CodeBlock code={tab.code} />
</div>
)}
</For>
</div>
)
}
@@ -1,12 +0,0 @@
// The status comes in through client.ts.
export function DocsFooter() {
return (
<footer class="site-footer">
<div class="footer-inner">
<a class="system-status" href="/status" data-status="unknown">
System status
</a>
</div>
</footer>
)
}
@@ -1,98 +0,0 @@
import { For, Show } from "solid-js"
import { base } from "../../config"
import { docsHref, docsSections, getDocsSection } from "../../lib/navigation"
// Search, the theme toggle and the ⌘K shortcut work through the layout's head script and client.ts.
export function DocsHeader(props: { currentSlug: string }) {
const currentSection = getDocsSection(props.currentSlug)
const searchEnabled = import.meta.env.PROD
return (
<>
<header class="site-header">
<div class="header-inner">
<a class="brand" href={docsHref("index")} aria-label="OpenCode docs home">
<img class="logo-dark" src={`${base}assets/logo-dark.svg`} alt="OpenCode" />
<img class="logo-light" src={`${base}assets/logo-light.svg`} alt="OpenCode" />
</a>
<nav aria-label="Documentation sections">
<For each={docsSections}>
{(section) => (
<a
href={docsHref(section.landingSlug)}
aria-current={currentSection.key === section.key ? "page" : undefined}
>
{section.title}
</a>
)}
</For>
{/* The V1 docs app, through the site's /v1/docs redirect (src/middleware.ts). */}
<a href="/v1/docs">V1</a>
</nav>
<div class="header-spacer"></div>
<Show when={searchEnabled}>
<button class="search-trigger" type="button" data-search-open aria-label="Search documentation">
<span>Search</span>
<kbd>⌘K</kbd>
</button>
</Show>
<button class="theme-toggle" type="button" data-theme-toggle aria-label="Toggle color theme">
<svg
class="theme-icon-light"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
aria-hidden="true"
>
<circle cx="12" cy="12" r="4" />
<path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" />
</svg>
<svg
class="theme-icon-dark"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
aria-hidden="true"
>
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79Z" />
</svg>
</button>
<a class="github-link" href="https://github.com/anomalyco/opencode" aria-label="OpenCode on GitHub">
GitHub
</a>
</div>
</header>
<Show when={searchEnabled}>
<dialog
class="search-dialog"
data-search-dialog
data-pagefind-path={`${base}pagefind/pagefind.js`}
data-base-url={base}
aria-label="Search documentation"
>
<form method="dialog" class="search-bar">
<span aria-hidden="true">&gt;</span>
<input
data-search-input
type="search"
placeholder="Search docs"
aria-label="Search docs"
autocomplete="off"
/>
<button type="submit" aria-label="Close search">
Esc
</button>
</form>
<div class="search-results" data-search-results>
<p>Start typing to search the documentation.</p>
</div>
</dialog>
</Show>
</>
)
}
@@ -1,29 +0,0 @@
import { For, Show } from "solid-js"
import { docsHref, type DocsNavGroup } from "../../lib/navigation"
export function DocsSidebar(props: { groups: DocsNavGroup[]; currentSlug: string }) {
return (
<nav class="docs-sidebar" aria-label="Documentation">
<For each={props.groups}>
{(group) => (
<section>
<Show when={group.title}>
<h2>{group.title}</h2>
</Show>
<ul>
<For each={group.items}>
{(item) => (
<li>
<a href={docsHref(item.slug)} aria-current={item.slug === props.currentSlug ? "page" : undefined}>
{item.title}
</a>
</li>
)}
</For>
</ul>
</section>
)}
</For>
</nav>
)
}
@@ -1,22 +0,0 @@
import { For, Show } from "solid-js"
import type { DocsHeading } from "../rehype-headings"
export function DocsTableOfContents(props: { headings: DocsHeading[] }) {
const headings = props.headings.filter((heading) => heading.depth === 2 || heading.depth === 3)
return (
<Show when={headings.length > 0}>
<nav class="docs-toc" aria-label="On this page">
<h2>On this page</h2>
<ul>
<For each={headings}>
{(heading) => (
<li class={heading.depth === 3 ? "nested" : undefined}>
<a href={`#${heading.slug}`}>{heading.text}</a>
</li>
)}
</For>
</ul>
</nav>
</Show>
)
}
@@ -1,224 +0,0 @@
import { For, Show } from "solid-js"
import openapi from "../../../../../../packages/protocol/openapi.json"
import { base } from "../../config"
import { openApiSchemaLabel, type OpenApiOperation, type OpenApiSchema } from "../../lib/openapi"
import { OpenApiSchemaView } from "./OpenApiSchema"
const methods = ["get", "post", "put", "patch", "delete", "options", "head"] as const
type Method = (typeof methods)[number]
const paths = openapi.paths as unknown as Record<string, Partial<Record<Method, OpenApiOperation>>>
const operations = Object.entries(paths).flatMap(([path, item]) =>
methods.flatMap((method) => {
const operation = item[method]
if (!operation) return []
return [
{ ...operation, path, method, id: operation.operationId ?? `${method}-${path}`.replace(/[^a-z0-9]+/gi, "-") },
]
}),
)
const groups = [...new Set(operations.map((operation) => operation.tags?.[0] ?? "other"))].map((tag) => ({
tag,
id: `tag-${tag.replace(/[^a-z0-9]+/gi, "-").toLowerCase()}`,
description: openapi.tags.find((item) => item.name === tag)?.description,
operations: operations.filter((operation) => (operation.tags?.[0] ?? "other") === tag),
}))
const schemas = Object.entries(openapi.components.schemas) as [string, OpenApiSchema][]
export function OpenApiReference() {
return (
<div class="api-reference">
<nav class="api-navigation" aria-label="API endpoints">
<strong>API reference</strong>
<a class="api-navigation-overview" href="#overview">
Overview
</a>
<For each={groups}>
{(group) => (
<details class="api-navigation-group">
<summary>
<span>{group.tag}</span>
<small>{group.operations.length}</small>
</summary>
<For each={group.operations}>
{(operation) => (
<a href={`#${operation.id}`}>
<span class={`api-navigation-method api-navigation-method-${operation.method}`}>
{operation.method}
</span>
<span>{operation.summary}</span>
</a>
)}
</For>
</details>
)}
</For>
<a class="api-navigation-overview" href="#schemas">
<span>Schemas</span>
<small>{schemas.length}</small>
</a>
</nav>
<article class="api-content" id="overview" data-pagefind-body data-pagefind-meta="title:API">
<header class="api-intro">
<p class="api-eyebrow">OpenAPI {openapi.openapi}</p>
<h1>HTTP API</h1>
<p>{openapi.info.description}</p>
<div class="api-meta">
<span>{operations.length} operations</span>
<span>{schemas.length} schemas</span>
<a href={`${base}openapi.json`}>OpenAPI JSON</a>
</div>
</header>
<For each={groups}>
{(group) => (
<section class="api-group" id={group.id}>
<header>
<p class="api-eyebrow">Resource</p>
<h2>{group.tag}</h2>
<Show when={group.description}>
<p>{group.description}</p>
</Show>
</header>
<div class="api-operations">
<For each={group.operations}>{(operation) => <Operation operation={operation} />}</For>
</div>
</section>
)}
</For>
<section class="api-group api-schemas" id="schemas">
<header>
<p class="api-eyebrow">Components</p>
<h2>Schemas</h2>
<p>Reusable data types referenced by API operations.</p>
</header>
<div class="api-operations">
<For each={schemas}>
{([name, schema]) => (
<details class="api-schema" id={`schema-${name}`}>
<summary>
<code>{name}</code>
<span>{openApiSchemaLabel(schema)}</span>
</summary>
<div class="api-schema-body">
<OpenApiSchemaView schema={schema} />
</div>
</details>
)}
</For>
</div>
</section>
</article>
</div>
)
}
function Operation(props: { operation: (typeof operations)[number] }) {
const operation = props.operation
return (
<details class="api-operation" id={operation.id}>
<summary>
<span class={`api-method api-method-${operation.method}`}>{operation.method}</span>
<code>{operation.path}</code>
<span>{operation.summary}</span>
</summary>
<div class="api-operation-body">
<Show when={operation.description}>
<p>{operation.description}</p>
</Show>
<p class="api-operation-id">
<span>Operation ID</span>
<code>{operation.operationId}</code>
</p>
<Show when={operation.parameters?.length}>
<section class="api-block">
<h3>Parameters</h3>
<div class="api-table-scroll">
<table>
<thead>
<tr>
<th>Name</th>
<th>Location</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<For each={operation.parameters}>
{(parameter) => (
<tr>
<td>
<code>{parameter.name}</code>
<Show when={parameter.required}>
<span class="api-required">required</span>
</Show>
</td>
<td>{parameter.in}</td>
<td>
<OpenApiSchemaView schema={parameter.schema} />
</td>
<td>{parameter.description ?? <span class="api-muted">No description</span>}</td>
</tr>
)}
</For>
</tbody>
</table>
</div>
</section>
</Show>
<Show when={operation.requestBody}>
{(body) => (
<section class="api-block">
<h3>
Request body{" "}
<Show when={body().required}>
<span class="api-required">required</span>
</Show>
</h3>
<Show when={body().description}>
<p>{body().description}</p>
</Show>
<div class="api-content-schemas">
<For each={Object.entries(body().content ?? {})}>
{([mediaType, content]) => (
<div>
<code class="api-media-type">{mediaType}</code>
<OpenApiSchemaView schema={content.schema} />
</div>
)}
</For>
</div>
</section>
)}
</Show>
<section class="api-block">
<h3>Responses</h3>
<div class="api-responses">
<For each={Object.entries(operation.responses ?? {})}>
{([status, response]) => (
<div class="api-response">
<div class="api-response-heading">
<code class={status.startsWith("2") ? "api-status api-status-success" : "api-status"}>
{status}
</code>
<span>{response.description ?? "Response"}</span>
</div>
<For each={Object.entries(response.content ?? {})}>
{([mediaType, content]) => (
<div class="api-response-schema">
<code class="api-media-type">{mediaType}</code>
<OpenApiSchemaView schema={content.schema} />
</div>
)}
</For>
</div>
)}
</For>
</div>
</section>
</div>
</details>
)
}
@@ -1,114 +0,0 @@
import { For, Show } from "solid-js"
import { formatOpenApiValue, openApiSchemaLabel, type OpenApiSchema } from "../../lib/openapi"
export function OpenApiSchemaView(props: { schema?: OpenApiSchema; required?: boolean }) {
const schema = props.schema
const reference = schema?.$ref?.split("/").at(-1)
const variants = schema?.anyOf ?? schema?.oneOf ?? schema?.allOf
const variantOperator = schema?.allOf ? "and" : "or"
const constraints = schema
? [
schema.pattern && `pattern ${schema.pattern}`,
schema.minimum !== undefined && `min ${schema.minimum}`,
schema.maximum !== undefined && `max ${schema.maximum}`,
schema.exclusiveMinimum !== undefined && `> ${schema.exclusiveMinimum}`,
schema.exclusiveMaximum !== undefined && `< ${schema.exclusiveMaximum}`,
schema.minLength !== undefined && `min length ${schema.minLength}`,
schema.maxLength !== undefined && `max length ${schema.maxLength}`,
schema.minItems !== undefined && `min items ${schema.minItems}`,
schema.maxItems !== undefined && `max items ${schema.maxItems}`,
].filter((value): value is string => typeof value === "string")
: []
if (reference)
return (
<a class="api-schema-link" href={`#schema-${reference}`}>
{reference}
</a>
)
return (
<div class="api-schema-node">
<div class="api-schema-heading">
<code>{openApiSchemaLabel(schema)}</code>
<Show when={props.required}>
<span class="api-required">required</span>
</Show>
<Show when={schema?.deprecated}>
<span class="api-deprecated">deprecated</span>
</Show>
</div>
<Show when={schema?.description}>
<p>{schema?.description}</p>
</Show>
<Show when={schema?.enum}>
{(values) => (
<div class="api-schema-values">
<span>Values</span>
<code>{values().map(formatOpenApiValue).join(" | ")}</code>
</div>
)}
</Show>
<Show when={schema?.const !== undefined}>
<div class="api-schema-values">
<span>Constant</span>
<code>{formatOpenApiValue(schema?.const)}</code>
</div>
</Show>
<Show when={schema?.default !== undefined}>
<div class="api-schema-values">
<span>Default</span>
<code>{formatOpenApiValue(schema?.default)}</code>
</div>
</Show>
<Show when={constraints.length > 0}>
<div class="api-schema-constraints">{constraints.join(", ")}</div>
</Show>
<Show when={variants}>
{(items) => (
<div class="api-schema-variants">
<For each={items()}>
{(variant, index) => (
<div>
<Show when={index() > 0}>
<span class="api-schema-operator">{variantOperator}</span>
</Show>
<OpenApiSchemaView schema={variant} />
</div>
)}
</For>
</div>
)}
</Show>
<Show when={schema?.type === "array" && schema.items}>
{(items) => (
<div class="api-schema-items">
<span>Items</span>
<OpenApiSchemaView schema={items()} />
</div>
)}
</Show>
<Show when={schema?.properties}>
{(properties) => (
<div class="api-schema-properties">
<For each={Object.entries(properties())}>
{([name, property]) => (
<div class="api-schema-property">
<code>{name}</code>
<OpenApiSchemaView schema={property} required={schema?.required?.includes(name)} />
</div>
)}
</For>
</div>
)}
</Show>
<Show when={typeof schema?.additionalProperties === "object" && schema.additionalProperties}>
{(additional) => (
<div class="api-schema-items">
<span>Additional properties</span>
<OpenApiSchemaView schema={additional() as OpenApiSchema} />
</div>
)}
</Show>
</div>
)
}
@@ -1,48 +0,0 @@
import { For, type JSX } from "solid-js"
import { SlotScope } from "../../components/Slot"
const plans = [
{ id: "go", label: "Go" },
{ id: "go-plus", label: "Go Plus" },
{ id: "go-teams", label: "Go Teams" },
] as const
// One panel per plan, from the `slot="go"`, `slot="go-plus"` and `slot="go-teams"` children. The tabs
// switch, and stay in step across every PlanTabs with the same syncKey, through client.ts.
export function PlanTabs(props: { id: string; label: string; syncKey: string; children?: JSX.Element }) {
return (
<div class="docs-plan-tabs" data-plan-tabs data-sync-key={props.syncKey}>
<div class="docs-plan-tabs-list" role="tablist" aria-label={props.label}>
<For each={plans}>
{(plan, index) => (
<button
type="button"
role="tab"
id={`${props.id}-tab-${plan.id}`}
aria-controls={`${props.id}-panel-${plan.id}`}
aria-selected={index() === 0 ? "true" : "false"}
tabindex={index() === 0 ? 0 : -1}
data-plan-tab={plan.id}
data-funnel={`plan-tab:${plan.id}`}
>
{plan.label}
</button>
)}
</For>
</div>
<For each={plans}>
{(plan, index) => (
<div
role="tabpanel"
id={`${props.id}-panel-${plan.id}`}
aria-labelledby={`${props.id}-tab-${plan.id}`}
hidden={index() !== 0}
data-plan-panel={plan.id}
>
<SlotScope name={plan.id}>{props.children}</SlotScope>
</div>
)}
</For>
</div>
)
}
@@ -1,54 +0,0 @@
import { NoHydration, ssr } from "solid-js/web"
import { Callout } from "./components/Callout"
import { Card } from "./components/Card"
import { CardGroup } from "./components/CardGroup"
import { CodeBlock } from "./components/CodeBlock"
import { CodeTabs } from "./components/CodeTabs"
import { OpenApiReference } from "./components/OpenApiReference"
import { PlanTabs } from "./components/PlanTabs"
import { Slot } from "../components/Slot"
import type { DocsModule } from "../content"
import { DocsLayout, type DocsAssets } from "./layouts/DocsLayout"
/** A docs page to render: a content page and its module, or the API reference (no module). */
export type DocsRender = { slug: string; module?: DocsModule; assets: DocsAssets }
const components = { Callout, Card, CardGroup, CodeBlock, CodeTabs, PlanTabs, Slot }
/**
* A whole docs page: plain HTML with the docs' own stylesheet and script, and no hydration
* (NoHydration), so it ships no framework code and none of the site's styles or scripts.
*/
export function DocsDocument(props: DocsRender) {
const module = props.module
return (
<NoHydration>
{ssr("<!DOCTYPE html>") as unknown as Element}
{module ? (
<DocsLayout
title={module.frontmatter.title}
description={module.frontmatter.description}
currentSlug={props.slug}
headings={module.headings}
showTableOfContents={module.frontmatter.tableOfContents !== false}
noindex={module.frontmatter.noindex}
assets={props.assets}
>
<module.default components={components} />
</DocsLayout>
) : (
<DocsLayout
title="API"
description="OpenCode HTTP API reference and OpenAPI specification."
currentSlug="api"
headings={[]}
showTableOfContents={false}
fullWidth
assets={props.assets}
>
<OpenApiReference />
</DocsLayout>
)}
</NoHydration>
)
}
@@ -1,145 +0,0 @@
import { Show, type JSX } from "solid-js"
import { base } from "../../config"
import { DocsFooter } from "../components/DocsFooter"
import { DocsHeader } from "../components/DocsHeader"
import { DocsSidebar } from "../components/DocsSidebar"
import { DocsTableOfContents } from "../components/DocsTableOfContents"
import { docsHref, getDocsSection } from "../../lib/navigation"
import type { DocsHeading } from "../rehype-headings"
/** The URLs of the docs' stylesheet (styles/global.css) and browser script (client.ts). */
export type DocsAssets = { stylesheet: string; script: string }
// Before first paint: the saved theme, else the system's, and the toggle. Inline so pages never flash.
const themeScript = `
const applyTheme = () => {
const theme =
localStorage.getItem("docs-theme") ?? (matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark")
document.documentElement.dataset.theme = theme
document.querySelector('meta[name="theme-color"]')?.setAttribute("content", theme === "light" ? "#ffffff" : "#000000")
}
applyTheme()
matchMedia("(prefers-color-scheme: light)").addEventListener("change", applyTheme)
document.addEventListener("click", (event) => {
if (!(event.target instanceof Element) || !event.target.closest("[data-theme-toggle]")) return
localStorage.setItem("docs-theme", document.documentElement.dataset.theme === "light" ? "dark" : "light")
applyTheme()
})
`
// Pages load as plain documents (no client router). The browser prerenders a docs link once the
// pointer rests on it, and global.css turns on cross-document view transitions, so a click shows the
// next page at once, without a blank frame.
const speculationRules = JSON.stringify({
prerender: [{ where: { href_matches: `${base}*` }, eagerness: "moderate" }],
})
export function DocsLayout(props: {
title: string
description?: string
currentSlug: string
headings: DocsHeading[]
showTableOfContents?: boolean
fullWidth?: boolean
noindex?: boolean
assets: DocsAssets
children: JSX.Element
}) {
const section = getDocsSection(props.currentSlug)
const description = props.description ?? `${props.title} documentation for OpenCode.`
const canonical = new URL(docsHref(props.currentSlug), "https://opencode.ai").href
return (
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content={description} />
<Show when={props.noindex}>
<meta name="robots" content="noindex" />
</Show>
<meta name="theme-color" content="#000000" />
<script innerHTML={themeScript} />
<script type="speculationrules" innerHTML={speculationRules} />
<link rel="canonical" href={canonical} />
<link rel="icon" type="image/svg+xml" href={`${base}favicon.svg`} />
<title>{`${props.title} | OpenCode`}</title>
<link rel="stylesheet" href={props.assets.stylesheet} />
</head>
<body>
<a class="skip-link" href="#docs-content">
Skip to content
</a>
<DocsHeader currentSlug={props.currentSlug} />
<Show
when={!props.fullWidth}
fallback={
<main id="docs-content" class="full-width-content">
{props.children}
</main>
}
>
<details class="mobile-navigation">
<summary>{section.title} navigation</summary>
<DocsSidebar groups={section.groups} currentSlug={props.currentSlug} />
</details>
<div class="docs-frame">
<aside class="sidebar-column">
<DocsSidebar groups={section.groups} currentSlug={props.currentSlug} />
</aside>
<main id="docs-content">
<article
class="prose"
data-pagefind-body={props.noindex ? undefined : ""}
data-pagefind-meta={`title:${props.title}`}
>
<h1>
{props.title}
<button
type="button"
aria-label="Copy page as Markdown"
data-copy-markdown
data-funnel-copy="page-markdown"
data-pagefind-ignore
>
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
aria-hidden="true"
>
<rect x="8" y="8" width="13" height="13" rx="2" />
<path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3" />
</svg>
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
aria-hidden="true"
>
<path d="m5 12 4 4L19 6" />
</svg>
</button>
</h1>
{props.children}
</article>
</main>
<aside class="toc-column">
<Show when={props.showTableOfContents !== false}>
<DocsTableOfContents headings={props.headings} />
</Show>
</aside>
</div>
</Show>
<DocsFooter />
<script type="module" src={props.assets.script} />
</body>
</html>
)
}
@@ -1,47 +0,0 @@
import type { Element, Root } from "hast"
import Slugger from "github-slugger"
import { visit } from "unist-util-visit"
import type { VFile } from "vfile"
export type DocsHeading = { depth: number; slug: string; text: string }
// Gives every heading a GitHub-style id (as Astro did, so existing anchors keep working), records
// them in `file.data.headings` for the table of contents, and appends a hover `#` link to h2 and h3.
// The link is ignored by Pagefind so search excerpts and sub-results read as before.
export default function rehypeHeadings() {
return (tree: Root, file: VFile) => {
const slugger = new Slugger()
const headings: DocsHeading[] = []
visit(tree, "element", (node: Element) => {
const depth = Number(/^h([1-6])$/.exec(node.tagName)?.[1])
if (!depth) return
const text = headingText(node)
if (typeof node.properties.id !== "string") node.properties.id = slugger.slug(text)
const slug = node.properties.id as string
headings.push({ depth, slug, text })
if (depth !== 2 && depth !== 3) return
node.children.push({
type: "element",
tagName: "a",
properties: {
className: ["heading-anchor"],
href: `#${slug}`,
ariaLabel: `Link to ${text}`,
dataPagefindIgnore: "",
},
children: [{ type: "text", value: "#" }],
})
})
file.data.headings = headings
}
}
// The heading's text, MDX expressions included as written.
function headingText(node: Element) {
let text = ""
visit(node, (child) => {
if (child.type === "text" || child.type === "raw" || child.type === "mdxTextExpression")
text += (child as { value: string }).value
})
return text
}
@@ -1,122 +0,0 @@
import type { Element, ElementContent, Root, RootContent } from "hast"
import { toText } from "hast-util-to-text"
import { bundledLanguages, createHighlighter, isSpecialLang, type ShikiTransformer } from "shiki"
// Highlights fenced code the way the docs' Astro build did, so global.css applies unchanged: a
// `pre.astro-code` with GitHub light colours inline and the dark ones as --shiki-dark variables,
// `data-language`, and `overflow-x: auto`. A `title="…"` in the fence's meta wraps it in a figure
// with a caption.
const themes = { light: "github-light", dark: "github-dark" }
const highlighter = createHighlighter({ langs: ["plaintext"], themes: Object.values(themes) })
export default function rehypeShiki() {
return async (tree: Root) => {
const blocks = findCodeBlocks(tree)
for (const block of blocks) block.parent.children[block.index] = await highlight(block.code)
}
}
async function highlight(code: Element): Promise<ElementContent> {
const shiki = await highlighter
const className = code.properties.className
const requested =
(Array.isArray(className) ? className : [])
.map((name) => /\blanguage-(\S+)/.exec(String(name))?.[1])
.find((name) => name !== undefined) ?? "plaintext"
// With the languages it embeds, so a Markdown block's YAML frontmatter or nested fences are
// highlighted whatever page loaded them first.
const grammar = await bundledLanguages[requested as keyof typeof bundledLanguages]?.()
const embedded = grammar?.default.flatMap((item) => item.embeddedLangsLazy ?? []) ?? []
const lang = await shiki
.loadLanguage(...([requested, ...embedded] as Parameters<typeof shiki.loadLanguage>))
.then(() => requested)
.catch(() => {
if (isSpecialLang(requested)) return requested
console.warn(`[Shiki] The language "${requested}" doesn't exist, falling back to "plaintext".`)
return "plaintext"
})
const meta = (code.data as { meta?: string } | undefined)?.meta
const root = shiki.codeToHast(toText(code, { whitespace: "pre" }).replace(/(?:\r\n|\r|\n)$/, ""), {
themes,
lang,
meta: meta ? { __raw: meta } : undefined,
transformers: [astroCode(lang), title],
})
return root.children[0] as ElementContent
}
function astroCode(lang: string): ShikiTransformer {
return {
pre(node) {
const join = (value: unknown) => (Array.isArray(value) ? value.join(" ") : value)
node.properties.class = String(join(node.properties.class) ?? "").replace(/shiki/g, "astro-code")
node.properties.dataLanguage = lang
// A copy of text selected in it is the funnel's `ui.copied` `snippet` (lib/funnel.ts).
node.properties.dataFunnelCopy = "snippet"
node.properties.dataFunnelMethod = lang
node.properties.style = `${join(node.properties.style) ?? ""}; overflow-x: auto;`
},
line(node) {
if (lang !== "diff") return
const span = node.children[0]
const text = span?.type === "element" ? span.children[0] : undefined
if (span?.type !== "element" || text?.type !== "text") return
const start = text.value[0]
if (start !== "+" && start !== "-") return
text.value = text.value.slice(1)
span.children.unshift({
type: "element",
tagName: "span",
properties: { style: "user-select: none;" },
children: [{ type: "text", value: start }],
})
},
}
}
const title: ShikiTransformer = {
name: "code-block-title",
root(root) {
const value = this.options.meta?.__raw?.match(/title="([^"]+)"/)?.[1]
const pre = root.children[0]
if (!value || pre?.type !== "element") return
root.children = [
{
type: "element",
tagName: "figure",
properties: { className: ["astro-code-figure"] },
children: [
{
type: "element",
tagName: "figcaption",
properties: { className: ["astro-code-title"] },
children: [{ type: "text", value }],
},
pre,
],
},
]
},
}
type Parent = { children: (RootContent | ElementContent)[] }
// A `pre` holding only a `code` (Markdown's fenced code), except math, anywhere in the tree (MDX
// component children included).
function findCodeBlocks(node: Parent): { parent: Parent; index: number; code: Element }[] {
return node.children.flatMap((child, index) => {
if (!("children" in child)) return []
const code = child.children[0]
if (
child.type === "element" &&
child.tagName === "pre" &&
child.children.length === 1 &&
code?.type === "element" &&
code.tagName === "code"
) {
const language = (Array.isArray(code.properties.className) ? code.properties.className : []).join(" ")
return /\blanguage-math\b/.test(language) ? [] : [{ parent: node, index, code }]
}
return findCodeBlocks(child as Parent)
})
}
File diff suppressed because it is too large Load Diff
+1 -3
View File
@@ -1,8 +1,6 @@
// The slug of every docs page (vite.ts), so the Worker knows them without loading any content, and
// whether this build renders the restyle (config.ts `restyled`).
// The slug of every docs page (vite.ts), so the Worker knows them without loading any content.
declare module "virtual:docs-pages" {
export const docsSlugs: string[]
export const restyle: boolean
}
// Solid's Babel preset ships no types; vite.ts passes it straight to Babel.
+2 -6
View File
@@ -1,16 +1,13 @@
import { renderToString } from "solid-js/web"
import { restyle } from "virtual:docs-pages"
import { docsContent } from "./content"
import { DocsDocument } from "./document"
import type { DocsAssets } from "./layouts/DocsLayout"
import { DocsDocument as LegacyDocsDocument } from "./legacy/document"
export { renderLlmsTxt } from "./lib/llms"
export { renderSitemap } from "./lib/sitemap"
// The docs' renderer: script/build.ts prerenders every page with it, and the development server
// renders on request (middleware.ts). The Worker never renders docs. The build's mode picks the
// restyle or the legacy pages (config.ts `restyled`).
// renders on request (middleware.ts). The Worker never renders docs.
/** Every docs page's slug: the content pages and the API reference. */
export const docsSlugs = [...docsContent.keys(), "api"].toSorted()
@@ -20,8 +17,7 @@ export async function renderDocsPage(slug: string, assets: DocsAssets) {
const load = docsContent.get(slug)
if (!load && slug !== "api") return
const module = await load?.()
const Document = restyle ? DocsDocument : LegacyDocsDocument
return renderToString(() => <Document slug={slug} module={module} assets={assets} />)
return renderToString(() => <DocsDocument slug={slug} module={module} assets={assets} />)
}
/** A content page's Markdown twin, or undefined when it has none. */
+18 -27
View File
@@ -5,10 +5,10 @@
// files (config.ts `files`).
//
// The pages render in a small server build of their own (render.tsx), outside the site's Worker
// bundle, which only serves the files (middleware.ts). The mode picks the restyle or the legacy pages
// (config.ts `restyled`). On its own (CI, after `bun run generate`):
// bundle, which only serves the files (middleware.ts). Every deploy builds the same docs. On its own
// (CI, after `bun run generate`):
//
// bun src/docs/script/build.ts [--mode dev|production] [--out <dir>]
// bun src/docs/script/build.ts [--out <dir>]
import { cp, mkdir, rm } from "node:fs/promises"
import path from "node:path"
import { parseArgs } from "node:util"
@@ -17,24 +17,19 @@ import solid from "vite-plugin-solid"
import { cssVariantsForProduction, devOnlyCss } from "../../../script/css-variants-plugin"
import { foldSettingsForProduction } from "../../../script/fold-settings"
import { config } from "../../config"
import { base, files, restyled } from "../config"
import { base, files } from "../config"
import { docsHref, docsMarkdownHref } from "../lib/navigation"
import type { docsSlugs, renderDocsMarkdown, renderDocsPage, renderLlmsTxt, renderSitemap } from "../render"
import { docs } from "../vite"
const args = parseArgs({ options: { mode: { type: "string", default: "production" }, out: { type: "string" } } })
const mode = args.values.mode
if (mode !== "dev" && mode !== "production") throw new Error(`Unknown --mode ${mode}; use dev or production`)
// check-docs.yml still passes `--mode dev`, which changes nothing; drop the option with it.
const args = parseArgs({ options: { mode: { type: "string" }, out: { type: "string" } } })
const root = path.resolve(import.meta.dir, "../../..")
const output = path.resolve(root, args.values.out ?? ".output/public")
const cache = path.join(root, "node_modules/.cache/docs")
const restyle = restyled(mode)
const alias = { "~": path.join(root, "src") }
// The restyle's stylesheet and script, or the legacy ones.
const inputs = restyle
? { stylesheet: "src/docs/styles/docs.css", script: "src/docs/client.ts" }
: { stylesheet: "src/docs/legacy/styles/global.css", script: "src/docs/legacy/client.ts" }
// llms.txt and the sitemap list opencode.ai's URLs in every mode, as the pages' canonical links do:
const inputs = { stylesheet: "src/docs/styles/docs.css", script: "src/docs/client.ts" }
// llms.txt and the sitemap list opencode.ai's URLs on dev.opencode.ai too, as the pages' canonical links do:
// search engines must not take dev.opencode.ai's for the real ones (src/lib/noindex.ts).
const site = new URL(config.baseUrl)
@@ -50,7 +45,7 @@ await build({
resolve: { alias },
// The site's production CSS: the stylesheets for development tools empty, and only the settings
// values production renders (the root's data-* attributes, DocsLayout.tsx).
plugins: restyle ? [devOnlyCss(), cssVariantsForProduction()] : [],
plugins: [devOnlyCss(), cssVariantsForProduction()],
build: {
outDir: path.join(cache, "client"),
assetsDir: "_build",
@@ -66,7 +61,7 @@ const assets = {
stylesheet: base + manifest[inputs.stylesheet].file,
script: base + manifest[inputs.script].file,
}
if (restyle) await checkBudget()
await checkBudget()
await build({
configFile: false,
@@ -78,7 +73,7 @@ await build({
resolve: { alias },
// Pages never hydrate, so no hydration markers. The site's components read their settings as
// production does (script/fold-settings.ts).
plugins: [foldSettingsForProduction(), docs({ restyle }), solid({ ssr: true, solid: { hydratable: false } })],
plugins: [foldSettingsForProduction(), docs(), solid({ ssr: true, solid: { hydratable: false } })],
build: {
ssr: "src/docs/render.tsx",
outDir: path.join(cache, "render"),
@@ -124,22 +119,18 @@ await Promise.all(
const pagefind = path.join(output, base)
await mkdir(pagefind, { recursive: true })
// The restyle's phone Contents bar repeats the page's headings, and code headers and screen reader
// text ("Copy", "Copied", "Opens in a new tab") aren't content, so they stay out of the index.
const exclude = restyle
? [
"--exclude-selectors",
"[data-component=contents-menu], [data-slot=code-head], [data-component=code-tabs] [data-slot=copy], [data-slot=sr-only]",
]
: []
await Bun.$`${path.join(root, "node_modules/.bin/pagefind")} --site ${pagefind} ${exclude}`.quiet()
// The phone Contents bar repeats the page's headings, and code headers and screen reader text
// ("Copy", "Copied", "Opens in a new tab") aren't content, so they stay out of the index.
const exclude =
"[data-component=contents-menu], [data-slot=code-head], [data-component=code-tabs] [data-slot=copy], [data-slot=sr-only]"
await Bun.$`${path.join(root, "node_modules/.bin/pagefind")} --site ${pagefind} --exclude-selectors ${exclude}`.quiet()
checkFileNames()
await checkAssetPrefix()
await Bun.$`bun ${path.join(import.meta.dir, "validate-links.ts")} ${output}`
console.log(`docs: built ${render.docsSlugs.length} pages (${mode}${restyle ? ", restyle" : ""})`)
console.log(`docs: built ${render.docsSlugs.length} pages`)
/**
* Fails when the restyle's first JavaScript or stylesheet outgrows its budget (gzipped): every docs
* Fails when the docs' first JavaScript or stylesheet outgrows its budget (gzipped): every docs
* page loads both, and nothing else is render-blocking.
*/
async function checkBudget() {
+8 -19
View File
@@ -12,8 +12,6 @@ import { base } from "./config"
import { frontmatterSchema } from "./frontmatter"
import { docsSlug } from "./lib/navigation"
import recmaSolid from "./recma-solid"
import legacyRehypeHeadings from "./legacy/rehype-headings"
import legacyRehypeShiki from "./legacy/rehype-shiki"
import rehypeHeadings from "./rehype-headings"
import rehypeShiki from "./rehype-shiki"
import rehypeTableScroll from "./rehype-table-scroll"
@@ -26,12 +24,9 @@ const pages = "virtual:docs-pages"
/**
* The docs in the site's Vite build: compiles content/*.mdx into server-only Solid modules (for
* script/build.ts and the development server) and provides `virtual:docs-pages`, the list of page
* slugs. The docs' stylesheet and script are built by script/build.ts, under /docs/_build. `restyle`
* picks the restyle's Markdown plugins or the legacy ones (config.ts `restyled`); the development
* server renders the restyle.
* slugs. The docs' stylesheet and script are built by script/build.ts, under /docs/_build.
*/
export function docs(options: { restyle?: boolean } = {}): Plugin {
const restyle = options.restyle ?? true
export function docs(): Plugin {
return {
name: "opencode-docs",
enforce: "pre",
@@ -41,14 +36,11 @@ export function docs(options: { restyle?: boolean } = {}): Plugin {
const slugs = readdirSync(content, { recursive: true, encoding: "utf8" })
.filter((file) => file.endsWith(".mdx"))
.map((file) => docsSlug(file.replaceAll("\\", "/")))
return [
`export const docsSlugs = ${JSON.stringify([...slugs, "api"].toSorted())}`,
`export const restyle = ${restyle}`,
].join("\n")
return `export const docsSlugs = ${JSON.stringify([...slugs, "api"].toSorted())}`
},
async transform(source, id) {
if (!id.endsWith(".mdx")) return
const code = await compileMdx(source, id, restyle)
const code = await compileMdx(source, id)
const result = await transformAsync(code, {
filename: id,
presets: [
@@ -64,10 +56,9 @@ export function docs(options: { restyle?: boolean } = {}): Plugin {
}
// MDX as Astro's MDX integration compiled it (GitHub-flavoured Markdown, smart punctuation, Shiki,
// heading ids), with the docs' own plugins: the restyle's wrap code in the site's CodeFrame and
// headings in HeadingLink, the legacy ones keep the Astro markup. The module also exports the page's frontmatter, its
// headings and its Markdown twin (`# Title` and the source, as the docs have always served it).
async function compileMdx(source: string, id: string, restyle: boolean) {
// heading ids), with the docs' own plugins, which wrap code in the site's CodeFrame and headings in
// HeadingLink. The module also exports the page's frontmatter, its headings and its Markdown twin (`# Title` and the source, as the docs have always served it).
async function compileMdx(source: string, id: string) {
const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(source)
const parsed = frontmatterSchema.safeParse(match ? parse(match[1]) : {})
if (!parsed.success) throw new Error(`${id}: invalid frontmatter\n${parsed.error.message}`)
@@ -80,9 +71,7 @@ async function compileMdx(source: string, id: string, restyle: boolean) {
elementAttributeNameCase: "html",
stylePropertyNameCase: "css",
remarkPlugins: [remarkGfm, remarkSmartypants, [remarkDocsLinks, { base }], remarkSlots],
rehypePlugins: restyle
? [rehypeShiki, rehypeTableScroll, rehypeHeadings]
: [legacyRehypeShiki, rehypeTableScroll, legacyRehypeHeadings],
rehypePlugins: [rehypeShiki, rehypeTableScroll, rehypeHeadings],
recmaPlugins: [recmaSolid],
})
return [