diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eb8c80db..921809a8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -48,6 +48,10 @@ jobs: run: pnpm --filter @coder/docs-site csp:check - name: No zod in first-load JavaScript (apps/docs) run: pnpm --filter @coder/docs-site first-load:check + - name: No API playground code (apps/offlinedocs) + run: pnpm --filter @coder/offlinedocs playground:check + - name: No API playground code (apps/docs) + run: pnpm --filter @coder/docs-site playground:check - name: URL and anchor parity (apps/docs) run: pnpm --filter @coder/docs-site parity:urls @@ -205,6 +209,46 @@ jobs: shellcheck --version actionlint -color + # Every API code sample must already be what its language's formatter writes. + code-samples-format: + name: code samples format + runs-on: ubuntu-latest + timeout-minutes: 15 + env: + RUFF_VERSION: 0.17.2 + SHFMT_VERSION: 3.14.1 + SHFMT_SHA256: 76e77641faa025814b77f153b29796b8e6fa2fca03e0c76a691608b86c7ea7bf + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: ./.github/actions/setup + - uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0 + with: + go-version: 1.25.x + cache: false + - name: Install ruff + run: pipx install "ruff==${RUFF_VERSION}" + - name: Install shfmt + run: | + set -euo pipefail + binary="shfmt_v${SHFMT_VERSION}_linux_amd64" + mkdir -p "$RUNNER_TEMP/shfmt-bin" + cd "$RUNNER_TEMP/shfmt-bin" + curl -fsSL -o "$binary" "https://github.com/mvdan/sh/releases/download/v${SHFMT_VERSION}/$binary" + echo "$SHFMT_SHA256 $binary" | sha256sum -c - + mv "$binary" shfmt + chmod +x shfmt + echo "$RUNNER_TEMP/shfmt-bin" >> "$GITHUB_PATH" + - name: Build the packages + run: pnpm turbo run build --filter='./packages/*' + - name: Check the samples + run: | + set -euo pipefail + go version + ruff --version + shfmt --version + shellcheck --version + pnpm --filter @coder/docs-site samples:format + # The CLI smoke-builds the kit from the packed files alone before packing it. dist-dry-run: name: public release dry run @@ -311,6 +355,7 @@ jobs: test-matrix-guard, actionlint, dist-dry-run, + code-samples-format, code-server-pin, ] runs-on: ubuntu-latest diff --git a/.github/workflows/docs-pr-preview.yml b/.github/workflows/docs-pr-preview.yml index e734a692..3186d8aa 100644 --- a/.github/workflows/docs-pr-preview.yml +++ b/.github/workflows/docs-pr-preview.yml @@ -188,7 +188,10 @@ jobs: repository: ${{ inputs.content_repository }} ref: ${{ inputs.content_ref }} path: content - sparse-checkout: docs + # coderd/apidoc holds the Swagger document the API reference is built from. + sparse-checkout: | + docs + coderd/apidoc sparse-checkout-cone-mode: true persist-credentials: false diff --git a/.github/workflows/historical-sync.yml b/.github/workflows/historical-sync.yml index 4b48d8f3..45944f65 100644 --- a/.github/workflows/historical-sync.yml +++ b/.github/workflows/historical-sync.yml @@ -86,7 +86,7 @@ jobs: run: | set -euo pipefail git clone --quiet --depth 1 --branch "$TAG" --filter=blob:none --sparse https://github.com/coder/coder.git "$RUNNER_TEMP/coder" - git -C "$RUNNER_TEMP/coder" sparse-checkout set docs + git -C "$RUNNER_TEMP/coder" sparse-checkout set docs coderd/apidoc - name: Sync it with the default historical pipeline env: TAG: ${{ steps.ref.outputs.tag }} diff --git a/.github/workflows/publish-version.yml b/.github/workflows/publish-version.yml index 2d211edc..74ba1775 100644 --- a/.github/workflows/publish-version.yml +++ b/.github/workflows/publish-version.yml @@ -376,7 +376,10 @@ jobs: repository: ${{ env.CONTENT_REPOSITORY }} ref: ${{ steps.resolve.outputs.sha }} path: content - sparse-checkout: docs + # coderd/apidoc holds the Swagger document the API reference is built from. + sparse-checkout: | + docs + coderd/apidoc sparse-checkout-cone-mode: true # Full history, without blobs: the sitemap dates pages from git log. fetch-depth: 0 diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index e6d5d37c..e0cf4c5d 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -37,8 +37,8 @@ docs-ui ────► docs-config docs-theme (no dependencies) - `@coder/docs-config` is the root contract package and depends on no other workspace package. - `@coder/docs-sources` depends on `docs-config`. - `@coder/docs-transforms` depends on `docs-config` (for the `Manifest` and `DocSource` contracts its pure transforms consume, and the `StaticDocsRenderContext` a static compile resolves the `premium` condition against). -- `@coder/docs-build` depends on `docs-config` and `docs-transforms`. -- `@coder/docs-next` depends on `docs-config`, `docs-ui`, and the dependency-free `version-segment` subpath of `docs-manifest`. +- `@coder/docs-build` depends on `docs-config`, `docs-transforms`, and the `version-segment` subpath of `docs-manifest` (for `isLineAtLeast`, which picks the versions that render the generated REST API reference); its external base for that reference is `swagger2openapi` and `oas-validator`. +- `@coder/docs-next` depends on `docs-config`, `docs-ui`, and the dependency-free `version-segment` subpath of `docs-manifest`; its `openapi` subpath renders the REST API reference with `fumadocs-openapi`. - `@coder/docs-ui` depends on the zod-free `client` subpath of `docs-config` for the `DocsRenderContext` its runtime `Premium`/`Experimental` annotation components read (loading the zod parser only when a fetched context arrives), and on the `version-segment` subpath of `docs-manifest` for the runtime version switcher's links; its external base is `fumadocs-ui`. - `@coder/docs-theme` depends on nothing; it ships plain CSS. - `@coder/docs-manifest` depends on `docs-config` only. @@ -133,6 +133,7 @@ Keeping every subword piece and the first 5,000 or more vocabulary rows as well One version of the docs flows through four stages: 1. **Provider.** A `VersionsProvider` from `@coder/docs-sources` loads the version into a `DocSource`: raw `.md` files, the `manifest.json` sidebar model, resolved images, and optional redirects. + For a version that renders the generated REST API reference, the sync scripts then rewrite that `DocSource` before syncing it (refer to "The REST API reference" below). 2. **Sync.** `syncDocSource` (`@coder/docs-build`) validates the source (dead links, broken images, route collisions, stale manifest entries) and writes a Fumadocs content tree: `.md` files with injected frontmatter, rewritten links and image paths, per-directory `meta.json`, and copied images. Only pages named by the manifest are emitted. 3. **Compile.** `fumadocs-mdx` compiles the synced tree using `createCoderMdxOptions({ renderContext, linkPrefix })` (`@coder/docs-transforms/mdx-config`), of which `coderMdxOptions` is the default instance (no static context, no link prefix — the in-product runtime pipeline): the Coder remark stack (GitHub callouts, Coder tabs, `
` accordions, steps), then `rehype-raw` to reparse the corpus's raw HTML, then the sanitizer, then Shiki highlighting with a fallback language for unbundled fences. @@ -144,6 +145,27 @@ This design rests on a `.md`-only precondition: the sync emits only `.md` files, Emitting `.mdx` would let corpus content execute at compile time and bypass the sanitizer entirely. Refer to "Security: the corpus is untrusted" in the `@coder/docs-transforms` README for the full invariant. +### The REST API reference + +From 2.24 on, and on `main`, the REST API reference is built from coder/coder's Swagger 2.0 document rather than from the Markdown pages its generator writes. +`rendersOpenApi` (`@coder/docs-build`) picks those versions; `OPENAPI_MIN_LINE` is the oldest line, since older documents repeat operation ids. +`DOCS_OPENAPI` set to `0`, `false`, `off` or `no` keeps the Markdown reference for every version, and is the rollback; any value that is not an off or on spelling fails the sync. + +The Swagger document is read from the checkout the docs come from, never fetched. +Both `@coder/docs-sources` providers, given `apiDocument: SWAGGER_PATH`, read `coderd/apidoc/swagger.json` onto the version's `DocSource` as `apiDocument`. +The local tree provider reads it beside the `docs/` tree, so every checkout a sync runs on, the publisher's and the preview's sparse ones included, has to hold `coderd/apidoc` as well as `docs`; the git provider reads it from the worktree it loads the version's docs from, so both come from one commit resolution. +A version with no Swagger document keeps its Markdown reference with a warning, except when `DOCS_PUBLISH=1`, where the sync fails, so a publish never ships the old reference for a version that should have the new one. + +`withOpenApiReference` rewrites the version's `DocSource` before `syncDocSource` sees it: `applyOpenApiReference` converts the document to OpenAPI 3, adds one Markdown stub page per operation under its tag, turns each tag page and the schemas page into lists of links, and adds the setup section to the landing page. +Each stub carries `_openapi: { method }` in its frontmatter; the sync validates that shape and keeps it, and fumadocs-openapi's loader plugin reads it to draw the sidebar's method badge. +It also writes the version's reference data, the converted document plus the route of every operation page, the old anchors, the landing cards and the schema rows, to `.generated/openapi/.json` (`docs.json` in the single-version offline export), which the app reads at render time so the document stays out of the server bundle. +A generated page whose path or route another page already has fails the sync. + +The page route factories take a `renderBody` hook, which may replace a page's compiled Markdown body, add after it, widen it, or extend its table of contents. +`createOpenApiRenderBody` (`@coder/docs-next/openapi`) is that hook for the reference: an operation page renders through fumadocs-openapi from the document pruned to that operation and what it reaches, with code samples built on the server; the tag and schemas pages add a client redirect from the old single-page anchors; the landing page adds its cards. +fumadocs-openapi's API playground never ships: `withoutOpenApiPlayground` (`@coder/docs-next/next-config`) wraps the Next config of `apps/docs` and `apps/offlinedocs` and replaces the playground, its OAuth flows and fetcher, and the server proxy with inert stubs in every bundle, and `playground:check` fails a build whose JavaScript still holds that code. +Every `$ref` must be in-document (`#/...`) at three points, the Swagger document, the converted document, and the renderer's input, because fumadocs-openapi's bundler fetches or reads any other reference. + ## Design decisions These seams are decided and recorded, but not all are implemented yet. diff --git a/apps/dist-release/src/smoke.mjs b/apps/dist-release/src/smoke.mjs index 5fe63e4f..81072613 100644 --- a/apps/dist-release/src/smoke.mjs +++ b/apps/dist-release/src/smoke.mjs @@ -81,6 +81,15 @@ export async function smokeTestKit({ kitDir, assetsDir, version }) { if (!new JSDOM(html).window.document.title.trim()) { throw new Error("the kit's out/index.html has an empty "); } + // Imported here, once the packages it reads are built. + const { findPlaygroundCode } = + await import("../../offlinedocs/scripts/playground-check-helpers.mjs"); + const playground = await findPlaygroundCode(path.join(built, "out")); + if (playground.length > 0) { + throw new Error( + `the kit's export ships API playground code: ${playground.map((hit) => hit.file).join(", ")}`, + ); + } await checkFinalizedLockfile(kitDir, path.join(work, "finalized")); } finally { diff --git a/apps/docs/README.md b/apps/docs/README.md index b61ae7f9..18ce94a6 100644 --- a/apps/docs/README.md +++ b/apps/docs/README.md @@ -161,6 +161,7 @@ This is the mode the public site is built in: the per-version publisher uses it | `DOCS_SITE_URL` | `https://coder.com/docs` | Optional; the public origin plus base path, for `og:url` and the canonical link. | | `DOCS_HOME_URL` | `https://coder.com/` | Optional; the main site the sidebar footer links back to. | | `DOCS_ANALYTICS` | `1` | Optional; loads coder.com's consent manager and tag manager; see "Analytics". | +| `DOCS_OPENAPI` | `0` | Optional; `0`, `false`, `off` or `no` keeps the Markdown REST API reference. | A local single-version build, against a real coder/coder clone: @@ -175,6 +176,8 @@ Every task the publisher's `pnpm turbo run build --filter=@coder/docs-site` touc The build task declares the two social-card variables for the same reason: stripped, they take the preview image off every published page with nothing failing. `DOCS_HOME_URL` is declared there too; stripped, the published pages would lose their link back to the main site the same silent way. `DOCS_ANALYTICS` is declared for the same reason. +`DOCS_OPENAPI`, the switch that rolls the REST API reference back to Markdown, is declared on `sync`, the only task that reads it; stripped, the rollback would do nothing. +Any value other than the off and on spellings (`1`, `true`, `on`, `yes` or empty) fails the sync, so a mistyped rollback never ships the new reference silently. ### The corpus guard diff --git a/apps/docs/app/[[...slug]]/page.tsx b/apps/docs/app/[[...slug]]/page.tsx index fa2c1239..500c5bc4 100644 --- a/apps/docs/app/[[...slug]]/page.tsx +++ b/apps/docs/app/[[...slug]]/page.tsx @@ -6,6 +6,7 @@ import { withSeoMetadata, } from "@coder/docs-next"; import type { Metadata } from "next"; +import { renderApiReference } from "@/lib/openapi"; import { productMetadata } from "@/lib/products"; import { sourceFor } from "@/lib/sources"; import { versions } from "@/lib/versions"; @@ -39,6 +40,7 @@ const { // Root-relative image URLs get the same base path Next applies to routes. assetBasePath: basePath, openGraph, + renderBody: renderApiReference, }); // Every version serves the same page at the same slug, so the canonical is the diff --git a/apps/docs/app/global.css b/apps/docs/app/global.css index 4a4911ee..f9f031fc 100644 --- a/apps/docs/app/global.css +++ b/apps/docs/app/global.css @@ -1,6 +1,7 @@ @import "tailwindcss"; @import "fumadocs-ui/css/neutral.css"; @import "fumadocs-ui/css/preset.css"; +@import "fumadocs-openapi/css/preset.css"; @import "@coder/docs-theme"; @import "@fontsource-variable/geist"; @@ -16,6 +17,7 @@ * pre-generated CSS only for its own layouts). */ @source "../node_modules/@coder/docs-ui/dist/*.js"; @source "../node_modules/@coder/docs-next/dist/*.js"; +@source "../node_modules/@coder/docs-next/dist/openapi/*.js"; @source "../node_modules/fumadocs-ui/dist/components/ui/popover.js"; /* coder.com's consent manager, present only when DOCS_ANALYTICS is on. The diff --git a/apps/docs/fixtures/docs/manifest.json b/apps/docs/fixtures/docs/manifest.json index 8b8abb17..b3be67ea 100644 --- a/apps/docs/fixtures/docs/manifest.json +++ b/apps/docs/fixtures/docs/manifest.json @@ -33,6 +33,15 @@ "state": ["early access", "beta"] } ] + }, + { + "title": "REST API", + "path": "./reference/api/index.md", + "children": [ + { "title": "Users", "path": "./reference/api/users.md" }, + { "title": "Workspaces", "path": "./reference/api/workspaces.md" }, + { "title": "Schemas", "path": "./reference/api/schemas.md" } + ] } ] } diff --git a/apps/docs/fixtures/docs/reference/api/index.md b/apps/docs/fixtures/docs/reference/api/index.md new file mode 100644 index 00000000..fe13f0a8 --- /dev/null +++ b/apps/docs/fixtures/docs/reference/api/index.md @@ -0,0 +1,16 @@ +--- +title: REST API +description: "Reference for the Coder REST API, including endpoints, authentication, and schemas." +--- + +Get started with the Coder API. + +## Quickstart + +List your workspaces: + +```sh +coder tokens create +``` + +Send the token in the `Coder-Session-Token` header of each request. diff --git a/apps/docs/fixtures/docs/reference/api/schemas.md b/apps/docs/fixtures/docs/reference/api/schemas.md new file mode 100644 index 00000000..49eff907 --- /dev/null +++ b/apps/docs/fixtures/docs/reference/api/schemas.md @@ -0,0 +1,16 @@ +--- +title: Schemas +--- + +## codersdk.User + +| Name | Type | Required | Restrictions | Description | +|------------|--------|----------|--------------|-------------| +| `id` | string | false | | | +| `username` | string | false | | | + +## codersdk.WorkspacesResponse + +| Name | Type | Required | Restrictions | Description | +|---------|---------|----------|--------------|-------------| +| `count` | integer | false | | | diff --git a/apps/docs/fixtures/docs/reference/api/users.md b/apps/docs/fixtures/docs/reference/api/users.md new file mode 100644 index 00000000..483a26b4 --- /dev/null +++ b/apps/docs/fixtures/docs/reference/api/users.md @@ -0,0 +1,23 @@ +--- +title: Users +--- + +## Create new user + +`POST /api/v2/users` + +### Responses + +| Status | Meaning | Description | Schema | +|--------|--------------------------------------------------------------|-------------|------------------------------------------| +| 201 | [Created](https://tools.ietf.org/html/rfc7231#section-6.3.2) | Created | [codersdk.User](schemas.md#codersdkuser) | + +## Get user by name + +`GET /api/v2/users/{user}` + +### Responses + +| Status | Meaning | Description | Schema | +|--------|---------------------------------------------------------|-------------|------------------------------------------| +| 200 | [OK](https://tools.ietf.org/html/rfc7231#section-6.3.1) | OK | [codersdk.User](schemas.md#codersdkuser) | diff --git a/apps/docs/fixtures/docs/reference/api/workspaces.md b/apps/docs/fixtures/docs/reference/api/workspaces.md new file mode 100644 index 00000000..934d6c81 --- /dev/null +++ b/apps/docs/fixtures/docs/reference/api/workspaces.md @@ -0,0 +1,15 @@ +--- +title: Workspaces +--- + +## List workspaces + +`GET /api/v2/workspaces` + +Returns the workspaces the caller can read, filtered by the search query. + +### Responses + +| Status | Meaning | Description | Schema | +|--------|---------------------------------------------------------|-------------|----------------------------------------------------------------------| +| 200 | [OK](https://tools.ietf.org/html/rfc7231#section-6.3.1) | OK | [codersdk.WorkspacesResponse](schemas.md#codersdkworkspacesresponse) | diff --git a/apps/docs/fixtures/openapi/swagger.json b/apps/docs/fixtures/openapi/swagger.json new file mode 100644 index 00000000..8d404808 --- /dev/null +++ b/apps/docs/fixtures/openapi/swagger.json @@ -0,0 +1,134 @@ +{ + "swagger": "2.0", + "info": { "title": "Coder API", "version": "2.0" }, + "basePath": "/", + "tags": [{ "name": "Workspaces", "description": "Create, list, and manage workspaces." }], + "paths": { + "/api/v2/workspaces": { + "get": { + "security": [{ "CoderSessionToken": [] }], + "produces": ["application/json"], + "tags": ["Workspaces"], + "summary": "List workspaces", + "operationId": "list-workspaces", + "description": "Returns the workspaces the caller can read, filtered by the search query.", + "parameters": [ + { + "type": "string", + "description": "Search query, such as `owner:me`", + "name": "q", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { "$ref": "#/definitions/codersdk.WorkspacesResponse" } + } + } + } + }, + "/api/v2/users": { + "post": { + "security": [{ "CoderSessionToken": [] }], + "consumes": ["application/json"], + "produces": ["application/json"], + "tags": ["Users"], + "summary": "Create new user", + "operationId": "create-new-user", + "parameters": [ + { + "description": "Create user request", + "name": "request", + "in": "body", + "required": true, + "schema": { "$ref": "#/definitions/codersdk.CreateUserRequest" } + } + ], + "responses": { + "201": { "description": "Created", "schema": { "$ref": "#/definitions/codersdk.User" } }, + "409": { "description": "A user with that username or email already exists" } + } + } + }, + "/api/v2/users/{user}": { + "get": { + "security": [{ "CoderSessionToken": [] }], + "produces": ["application/json"], + "tags": ["Users"], + "summary": "Get user by name", + "operationId": "get-user-by-name", + "parameters": [ + { + "type": "string", + "description": "User ID, username, or me", + "name": "user", + "in": "path", + "required": true + } + ], + "responses": { + "200": { "description": "OK", "schema": { "$ref": "#/definitions/codersdk.User" } } + } + } + }, + "/api/v2/debug/pprof": { + "get": { + "security": [{ "CoderSessionToken": [] }], + "tags": ["Debug"], + "summary": "Debug pprof index", + "operationId": "debug-pprof-index", + "responses": { "200": { "description": "OK" } }, + "x-apidocgen": { "skip": true } + } + } + }, + "definitions": { + "Response": { + "type": "object", + "properties": { "message": { "type": "string" } } + }, + "agentsdk.Manifest": { + "type": "object", + "properties": { "agent_id": { "type": "string" } } + }, + "codersdk.CreateUserRequest": { + "type": "object", + "required": ["email", "username"], + "properties": { + "email": { "type": "string", "format": "email" }, + "username": { "type": "string" } + } + }, + "codersdk.User": { + "type": "object", + "properties": { + "id": { "type": "string", "format": "uuid" }, + "username": { "type": "string" }, + "status": { + "enum": ["active", "suspended"], + "allOf": [{ "$ref": "#/definitions/codersdk.UserStatus" }] + } + } + }, + "codersdk.UserStatus": { "type": "string", "enum": ["active", "suspended"] }, + "codersdk.Workspace": { + "type": "object", + "properties": { + "id": { "type": "string", "format": "uuid" }, + "name": { "type": "string" }, + "owner_name": { "type": "string" } + } + }, + "codersdk.WorkspacesResponse": { + "type": "object", + "properties": { + "count": { "type": "integer" }, + "workspaces": { "type": "array", "items": { "$ref": "#/definitions/codersdk.Workspace" } } + } + } + }, + "securityDefinitions": { + "CoderSessionToken": { "type": "apiKey", "name": "Coder-Session-Token", "in": "header" } + } +} diff --git a/apps/docs/fixtures/url-parity-approved.json b/apps/docs/fixtures/url-parity-approved.json index fe51488c..ff4ebfd3 100644 --- a/apps/docs/fixtures/url-parity-approved.json +++ b/apps/docs/fixtures/url-parity-approved.json @@ -1 +1,98 @@ -[] +[ + { + "kind": "anchor-missing", + "url": "/docs/reference/api/users", + "anchor": "create-new-user", + "reason": "operation moved to its own page; the tag page redirects the anchor" + }, + { + "kind": "anchor-missing", + "url": "/docs/reference/api/users", + "anchor": "get-user-by-name", + "reason": "operation moved to its own page; the tag page redirects the anchor" + }, + { + "kind": "anchor-missing", + "url": "/docs/reference/api/users", + "anchor": "responses", + "reason": "per-operation subsection, now on the operation page" + }, + { + "kind": "anchor-missing", + "url": "/docs/reference/api/users", + "anchor": "responses-1", + "reason": "per-operation subsection, now on the operation page" + }, + { + "kind": "anchor-missing", + "url": "/docs/reference/api/workspaces", + "anchor": "list-workspaces", + "reason": "operation moved to its own page; the tag page redirects the anchor" + }, + { + "kind": "anchor-missing", + "url": "/docs/reference/api/workspaces", + "anchor": "responses", + "reason": "per-operation subsection, now on the operation page" + }, + { + "kind": "anchor-missing", + "url": "/docs/reference/api/schemas", + "anchor": "codersdkuser", + "reason": "schemas render on the operation pages; the schemas page redirects the anchor" + }, + { + "kind": "anchor-missing", + "url": "/docs/reference/api/schemas", + "anchor": "codersdkworkspacesresponse", + "reason": "schemas render on the operation pages; the schemas page redirects the anchor" + }, + { + "kind": "anchor-missing", + "url": "/docs/@main/reference/api/users", + "anchor": "create-new-user", + "reason": "main renders the per-operation reference; the tag page's anchor redirect sends it to the operation page" + }, + { + "kind": "anchor-missing", + "url": "/docs/@main/reference/api/users", + "anchor": "get-user-by-name", + "reason": "main renders the per-operation reference; the tag page's anchor redirect sends it to the operation page" + }, + { + "kind": "anchor-missing", + "url": "/docs/@main/reference/api/users", + "anchor": "responses", + "reason": "per-operation subsection, now on the operation page; not redirected, so the link lands at the top of the tag page" + }, + { + "kind": "anchor-missing", + "url": "/docs/@main/reference/api/users", + "anchor": "responses-1", + "reason": "per-operation subsection, now on the operation page; not redirected, so the link lands at the top of the tag page" + }, + { + "kind": "anchor-missing", + "url": "/docs/@main/reference/api/workspaces", + "anchor": "list-workspaces", + "reason": "main renders the per-operation reference; the tag page's anchor redirect sends it to the operation page" + }, + { + "kind": "anchor-missing", + "url": "/docs/@main/reference/api/workspaces", + "anchor": "responses", + "reason": "per-operation subsection, now on the operation page; not redirected, so the link lands at the top of the tag page" + }, + { + "kind": "anchor-missing", + "url": "/docs/@main/reference/api/schemas", + "anchor": "codersdkuser", + "reason": "main renders the per-operation reference; the schemas page's anchor redirect sends it to the operation page that shows the schema" + }, + { + "kind": "anchor-missing", + "url": "/docs/@main/reference/api/schemas", + "anchor": "codersdkworkspacesresponse", + "reason": "main renders the per-operation reference; the schemas page's anchor redirect sends it to the operation page that shows the schema" + } +] diff --git a/apps/docs/lib/openapi.ts b/apps/docs/lib/openapi.ts new file mode 100644 index 00000000..c1462f26 --- /dev/null +++ b/apps/docs/lib/openapi.ts @@ -0,0 +1,5 @@ +import { createOpenApiDataLoader, createOpenApiRenderBody } from "@coder/docs-next/openapi"; + +export const renderApiReference = createOpenApiRenderBody( + createOpenApiDataLoader(process.cwd(), (versionId) => versionId), +); diff --git a/apps/docs/lib/sources.ts b/apps/docs/lib/sources.ts index 3176995d..4e21e66d 100644 --- a/apps/docs/lib/sources.ts +++ b/apps/docs/lib/sources.ts @@ -7,6 +7,7 @@ import { versionBaseUrl, } from "@coder/docs-next"; import { loader } from "fumadocs-core/source"; +import { openapiPlugin } from "fumadocs-openapi/server"; // The generated content collections stay below the package imports. This // module is the one place the seven route handlers (api/search and the llms @@ -23,8 +24,9 @@ import { versions } from "./versions"; // One Fumadocs source per version, each loaded with the version's URL prefix // so page URLs and relative links carry it (mainline `latest` sits at "/"), -// and with the plugins that put a page's manifest state pills on its sidebar -// item and make the code-server folder, where a version has one, a root folder. +// and with the plugins that put a page's manifest state pills, or an API +// operation's method badge, on its sidebar item and make the code-server +// folder, where a version has one, a root folder. const collections = [docsV0, docsV1, docsV2, docsV3, docsV4, docsV5]; const byId = new Map<string, DocsSource>( @@ -36,7 +38,12 @@ const byId = new Map<string, DocsSource>( loader({ baseUrl: versionBaseUrl(version), source: collection.toFumadocsSource(), - plugins: [navTitlePlugin(), stateBadgesPlugin(), productRootsPlugin(ROUTED_PRODUCTS)], + plugins: [ + navTitlePlugin(), + stateBadgesPlugin(), + openapiPlugin(), + productRootsPlugin(ROUTED_PRODUCTS), + ], }), ]; }), diff --git a/apps/docs/lib/versioned-shell.tsx b/apps/docs/lib/versioned-shell.tsx index 891b513a..c1d144f0 100644 --- a/apps/docs/lib/versioned-shell.tsx +++ b/apps/docs/lib/versioned-shell.tsx @@ -1,9 +1,11 @@ import { latestSource, sourceFor, versionHasSlug } from "@/lib/sources"; import { versions } from "@/lib/versions"; import { + API_REFERENCE_DIR, CODE_SERVER_PRODUCT, CODER_PRODUCT, analyticsEnabled, + isApiReferenceSlug, stripCodeTitle, } from "@coder/docs-config"; import { @@ -11,8 +13,10 @@ import { resolveSlug, rootProductOf, sourceHasProduct, + versionHref, versionSwitcherOptions, } from "@coder/docs-next"; +import { collapseFoldersUnder } from "@coder/docs-next/openapi"; import { BetaBanner, CookiePreferencesButton, RuntimeVersionSwitcher } from "@coder/docs-ui"; import type { ReactNode } from "react"; import { @@ -89,6 +93,14 @@ export function VersionedShell({ slug, children }: { slug?: string[]; children: // two share one fetch). Where there is no router, a preview or a raw // deployment URL, the fetch fails and the build-time options stand. const versionsUrl = `${basePath}/versions.json`; + // Operation pages are listed in the sidebar only while reading the API reference. + const inApiReference = resolved !== undefined && isApiReferenceSlug(resolved.slug); + const apiReference = resolved + ? versionHref(resolved.version, API_REFERENCE_DIR.split("/")) + : `/${API_REFERENCE_DIR}`; + const tree = inApiReference + ? undefined + : collapseFoldersUnder(source.pageTree, `${apiReference}/`); // A product other than Coder is not versioned with Coder, so its pages carry // neither the version switcher nor the beta banner. const page = resolved && source.getPage(resolved.slug); @@ -96,6 +108,7 @@ export function VersionedShell({ slug, children }: { slug?: string[]; children: return ( <DocsShell source={source} + tree={tree} primaryProduct={CODER_PRODUCT} sidebarBanner={ ownProduct ? undefined : ( diff --git a/apps/docs/next.config.mjs b/apps/docs/next.config.mjs index d338fd4d..94278370 100644 --- a/apps/docs/next.config.mjs +++ b/apps/docs/next.config.mjs @@ -1,4 +1,5 @@ import { fileURLToPath } from "node:url"; +import { withoutOpenApiPlayground } from "@coder/docs-next/next-config"; import { withSentryConfig } from "@sentry/nextjs/config"; import { createMDX } from "fumadocs-mdx/next"; import { keyMdxLoaders, mdxPipelineDigest } from "./scripts/mdx-cache-key.mjs"; @@ -66,7 +67,7 @@ const config = keyMdxLoaders( // Outermost, so its Turbopack rules for the instrumentation file land in the keyed config. // Source maps stay off: uploading needs a token the untrusted-content build must not hold. -export default withSentryConfig(config, { +export default withSentryConfig(withoutOpenApiPlayground(config), { org: "coder-3d", project: "docs-engine", silent: !process.env.CI, diff --git a/apps/docs/package.json b/apps/docs/package.json index 3e4bd07b..bcf44d83 100644 --- a/apps/docs/package.json +++ b/apps/docs/package.json @@ -13,6 +13,7 @@ "build": "node --import tsx scripts/build-versions.mjs", "archive:layout": "node scripts/archive-layout.mjs", "csp:check": "node ../offlinedocs/scripts/csp-check.mjs .", + "playground:check": "node ../offlinedocs/scripts/playground-check.mjs out", "first-load:check": "node scripts/first-load-js.mjs", "pretypecheck": "[ -n \"$TURBO_HASH\" ] || pnpm run sync", "typecheck": "tsc -p tsconfig.json --noEmit", @@ -26,6 +27,7 @@ "perf:probe": "node scripts/perf-probe.mjs", "a11y:axe": "node scripts/a11y-axe.mjs", "a11y:keyboard": "node scripts/a11y-keyboard.mjs", + "samples:format": "node scripts/code-samples-format.mjs", "a11y:live": "node scripts/a11y-live.mjs", "parity:urls": "node --import tsx scripts/url-parity.mjs --out out", "parity:urls:live": "node --import tsx scripts/url-parity.mjs --live https://coder.com/beta-docs", @@ -57,6 +59,7 @@ "@vercel/blob": "catalog:", "fumadocs-core": "catalog:", "fumadocs-mdx": "catalog:", + "fumadocs-openapi": "12.6.1", "fumadocs-ui": "catalog:", "next": "catalog:", "react": "catalog:", diff --git a/apps/docs/scripts/a11y-axe-helpers.mjs b/apps/docs/scripts/a11y-axe-helpers.mjs index 081ad6f0..5027fba8 100644 --- a/apps/docs/scripts/a11y-axe-helpers.mjs +++ b/apps/docs/scripts/a11y-axe-helpers.mjs @@ -21,11 +21,21 @@ export const DEFAULT_PAGES = [ "/authoring/callouts", "/authoring/cards", "/authoring/states", + "/reference/api", + "/reference/api/schemas", + "/reference/api/users", + "/reference/api/users/create-new-user", + "/reference/api/workspaces/list-workspaces", // The code-server fixture, built by the a11y job with DOCS_CODE_SERVER_ROOT set. "/code-server", "/code-server/install", ]; -export const DEFAULT_MOBILE_PAGES = ["/", "/authoring/tables", "/code-server"]; +export const DEFAULT_MOBILE_PAGES = [ + "/", + "/authoring/tables", + "/reference/api/users/create-new-user", + "/code-server", +]; // The search dialog is scanned open on this page, with a query the fixture corpus matches. export const SEARCH_PAGE = "/"; export const SEARCH_QUERY = "code"; diff --git a/apps/docs/scripts/a11y-keyboard-helpers.mjs b/apps/docs/scripts/a11y-keyboard-helpers.mjs index 14ff6611..39fd8bf2 100644 --- a/apps/docs/scripts/a11y-keyboard-helpers.mjs +++ b/apps/docs/scripts/a11y-keyboard-helpers.mjs @@ -1,4 +1,6 @@ export const DEFAULT_PAGE = "/admin/users"; +// An API operation page with a request body, whose code-sample tabs are checked with the pointer. +export const DEFAULT_API_PAGE = "/reference/api/users/create-new-user"; /** Callouts and tables set smaller text than the body, so their inline code is the tightest fit. */ export const INLINE_CODE_PAGES = ["/authoring/callouts", "/authoring/tables"]; export const BROWSERS = ["chromium", "firefox"]; @@ -11,7 +13,12 @@ export const SCHEMES = ["light", "dark"]; export const MIN_BORDER_CONTRAST = 3; export function parseArgs(argv) { - const options = { out: undefined, page: DEFAULT_PAGE, browsers: BROWSERS }; + const options = { + out: undefined, + page: DEFAULT_PAGE, + apiPage: DEFAULT_API_PAGE, + browsers: BROWSERS, + }; for (let i = 0; i < argv.length; i++) { const flag = argv[i]; const next = () => { @@ -21,6 +28,7 @@ export function parseArgs(argv) { }; if (flag === "--out") options.out = next(); else if (flag === "--page") options.page = next(); + else if (flag === "--api-page") options.apiPage = next(); else if (flag === "--browsers") { options.browsers = next().split(",").filter(Boolean); const unknown = options.browsers.filter((b) => !BROWSERS.includes(b)); diff --git a/apps/docs/scripts/a11y-keyboard.mjs b/apps/docs/scripts/a11y-keyboard.mjs index 69bc1a1e..4c035365 100644 --- a/apps/docs/scripts/a11y-keyboard.mjs +++ b/apps/docs/scripts/a11y-keyboard.mjs @@ -1,7 +1,8 @@ // Keyboard, focus and pointer checks axe cannot make: button cursors, the skip // link's Tab order and focus hand-off, the heading # links, the version switcher's More -// contrast outline in the mobile drawer, and inline code that fits its line. Runs in -// Chromium and Firefox, at desktop and phone widths. +// contrast outline in the mobile drawer, inline code that fits its line, and that each +// API code-sample tab takes a pointer click. Runs in Chromium and Firefox, at desktop +// and phone widths. import path from "node:path"; import { fileURLToPath } from "node:url"; import { loadPlaywright, serve } from "./a11y-browser.mjs"; @@ -248,6 +249,27 @@ async function checkDrawerSwitcher(page, fail) { return `More switcher outline ${ratio.toFixed(2)}:1`; } +// Each code-sample tab takes a pointer click, after the tallest sample has been shown, so no panel covers the tab list. +async function checkSampleTabs(page, fail) { + const tabs = page.locator(".coder-sample-tabs > [role=tablist] [role=tab]"); + const labels = await tabs.allTextContents(); + if (labels.length < 2) { + fail(`expected the code-sample tabs, found ${labels.length}`); + return "no sample tabs"; + } + for (const label of [...labels.slice(1), labels[0]]) { + const tab = tabs.filter({ hasText: new RegExp(`^${label}$`) }); + try { + await tab.click({ timeout: 5000 }); + } catch (error) { + fail(`the ${label} sample tab cannot be clicked: ${String(error.message).split("\n")[0]}`); + continue; + } + if ((await tab.getAttribute("aria-selected")) !== "true") fail(`${label} is not selected`); + } + return `${labels.length} sample tabs clickable`; +} + async function checkButtonCursor(page, fail) { const buttons = await page.evaluate(() => [...document.querySelectorAll('button, [role="button"]')].map((el) => ({ @@ -294,7 +316,7 @@ async function checkInlineCodeFit(page, base, fail) { return `${boxes} inline code boxes`; } -async function check({ browsers, base, pagePath, run }) { +async function check({ browsers, base, pagePath, apiPage, run }) { const failures = []; const fail = (message, at = pagePath) => failures.push(`FAIL ${runName(run)} ${at}: ${message}`); const mobile = run.viewport === "mobile"; @@ -320,6 +342,9 @@ async function check({ browsers, base, pagePath, run }) { notes.push(await checkHeadingAnchor(page, run.browser, fail)); } notes.push(await checkInlineCodeFit(page, base, fail)); + const api = await page.goto(base + apiPage, { waitUntil: "networkidle" }); + if (!api?.ok()) throw new Error(`${apiPage} answered ${api?.status()}`); + notes.push(await checkSampleTabs(page, fail)); } finally { await context.close(); } @@ -341,6 +366,7 @@ async function main() { browsers, base: `http://127.0.0.1:${port}`, pagePath: options.page, + apiPage: options.apiPage, run, }); failures.push(...result.failures); @@ -354,7 +380,9 @@ async function main() { server.close(); } for (const failure of failures) console.log(failure); - console.log(`\n${runs.length} runs on ${options.page}: ${failures.length} failures.`); + console.log( + `\n${runs.length} runs on ${options.page} and ${options.apiPage}: ${failures.length} failures.`, + ); if (failures.length > 0) process.exitCode = 1; } diff --git a/apps/docs/scripts/a11y-keyboard.test.mjs b/apps/docs/scripts/a11y-keyboard.test.mjs index 03bc6c2a..e92d5cd2 100644 --- a/apps/docs/scripts/a11y-keyboard.test.mjs +++ b/apps/docs/scripts/a11y-keyboard.test.mjs @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { BROWSERS, + DEFAULT_API_PAGE, DEFAULT_PAGE, composite, contrastRatio, @@ -11,12 +12,25 @@ import { } from "./a11y-keyboard-helpers.mjs"; test("parseArgs defaults to both browsers and reads the flags", () => { - assert.deepEqual(parseArgs([]), { out: undefined, page: DEFAULT_PAGE, browsers: BROWSERS }); - assert.deepEqual(parseArgs(["--out", "o", "--page", "/install", "--browsers", "firefox"]), { - out: "o", - page: "/install", - browsers: ["firefox"], + assert.deepEqual(parseArgs([]), { + out: undefined, + page: DEFAULT_PAGE, + apiPage: DEFAULT_API_PAGE, + browsers: BROWSERS, }); + assert.deepEqual( + parseArgs([ + "--out", + "o", + "--page", + "/install", + "--api-page", + "/api/x", + "--browsers", + "firefox", + ]), + { out: "o", page: "/install", apiPage: "/api/x", browsers: ["firefox"] }, + ); assert.throws(() => parseArgs(["--browsers", "webkit"]), /Unknown browser webkit/); assert.throws(() => parseArgs(["--bogus"]), /Unknown flag/); assert.throws(() => parseArgs(["--page"]), /needs a value/); diff --git a/apps/docs/scripts/code-samples-format.mjs b/apps/docs/scripts/code-samples-format.mjs new file mode 100644 index 00000000..17627119 --- /dev/null +++ b/apps/docs/scripts/code-samples-format.mjs @@ -0,0 +1,105 @@ +// Checks that every generated API code sample is already formatted the way +// its language's formatter formats it, and still parses: gofmt for Go, ruff +// format (Black's style) for Python, shfmt for the shell, and oxfmt with +// Prettier's defaults for JavaScript, plus shellcheck, sh -n, node --check and +// py_compile. The docs build never runs these tools; this proves the text it +// writes is what they would write. Defaults to the fixture document; pass +// --swagger <coder/coder's coderd/apidoc/swagger.json> to check a real one. +import { execFile } from "node:child_process"; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { convertSwagger } from "@coder/docs-build"; +import { HTTP_METHODS } from "@coder/docs-config"; +import { codeSamples } from "@coder/docs-next/openapi/code-samples"; + +const run = promisify(execFile); +const appDir = path.dirname(path.dirname(fileURLToPath(import.meta.url))); +const oxfmt = path.join(appDir, "..", "..", "node_modules", ".bin", "oxfmt"); +const EXTENSIONS = { curl: "sh", javascript: "mjs", python: "py", go: "go" }; + +function parseArgs(argv) { + const options = { swagger: path.join(appDir, "fixtures", "openapi", "swagger.json") }; + for (let i = 0; i < argv.length; i++) { + if (argv[i] === "--swagger" && argv[i + 1]) options.swagger = argv[++i]; + else throw new Error(`Unknown flag ${argv[i]}`); + } + return options; +} + +async function writeSamples(swagger, dir) { + const { document } = await convertSwagger(swagger); + let count = 0; + for (const [route, item] of Object.entries(document.paths ?? {})) { + for (const method of HTTP_METHODS) { + if (!item?.[method]) continue; + const name = `${method}${route.replace(/[^\w]+/g, "_")}`; + for (const sample of codeSamples(document, route, method)) { + const folder = sample.id === "go" ? path.join(dir, "go", name) : path.join(dir, sample.id); + await mkdir(folder, { recursive: true }); + const file = sample.id === "go" ? "main.go" : `${name}.${EXTENSIONS[sample.id]}`; + await writeFile(path.join(folder, file), `${sample.source}\n`); + } + count++; + } + } + return count; +} + +const filesIn = async (dir) => (await readdir(dir)).map((file) => path.join(dir, file)); + +// A check fails when its command exits non-zero or prints anything for a clean run. +async function check(name, command, args, { quietWhenClean = false } = {}) { + try { + const { stdout } = await run(command, args, { maxBuffer: 64 * 1024 * 1024 }); + if (quietWhenClean && stdout.trim()) return `${name}:\n${stdout.trim()}`; + return undefined; + } catch (error) { + if (error.code === "ENOENT") return `${name}: ${command} is not installed`; + return `${name}:\n${`${error.stdout ?? ""}${error.stderr ?? ""}`.trim() || error.message}`; + } +} + +async function main() { + const options = parseArgs(process.argv.slice(2)); + const swagger = JSON.parse(await readFile(options.swagger, "utf8")); + const dir = await mkdtemp(path.join(tmpdir(), "code-samples-")); + try { + const count = await writeSamples(swagger, dir); + const config = path.join(dir, "prettier-defaults.json"); + await writeFile(config, "{}\n"); + const shell = await filesIn(path.join(dir, "curl")); + const python = await filesIn(path.join(dir, "python")); + const javascript = await filesIn(path.join(dir, "javascript")); + const failures = ( + await Promise.all([ + check("gofmt", "gofmt", ["-l", path.join(dir, "go")], { quietWhenClean: true }), + check("ruff format", "ruff", [ + "format", + "--check", + "--diff", + "--isolated", + "--no-cache", + ...python, + ]), + check("shfmt", "shfmt", ["-d", ...shell]), + check("oxfmt (Prettier defaults)", oxfmt, ["-c", config, "--check", ...javascript]), + check("shellcheck", "shellcheck", ["-s", "sh", ...shell]), + ...shell.map((file) => check(`sh -n ${path.basename(file)}`, "sh", ["-n", file])), + ...javascript.map((file) => + check(`node --check ${path.basename(file)}`, process.execPath, ["--check", file]), + ), + check("py_compile", "python3", ["-m", "py_compile", ...python]), + ]) + ).filter(Boolean); + for (const failure of failures) console.log(`FAIL ${failure}`); + console.log(`${count} operations, ${count * 4} samples: ${failures.length} failing checks.`); + if (failures.length > 0) process.exitCode = 1; + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +await main(); diff --git a/apps/docs/scripts/mdx-cache-key.test.mjs b/apps/docs/scripts/mdx-cache-key.test.mjs index 5fd0dfd2..49d36c6c 100644 --- a/apps/docs/scripts/mdx-cache-key.test.mjs +++ b/apps/docs/scripts/mdx-cache-key.test.mjs @@ -12,7 +12,7 @@ process.env._FUMADOCS_MDX = "1"; const fumadocsLoaders = (config) => Object.values(config.turbopack.rules) .flatMap((rule) => rule.loaders) - .filter((loader) => loader.loader.startsWith("fumadocs-mdx/")); + .filter((loader) => typeof loader === "object" && loader.loader.startsWith("fumadocs-mdx/")); async function fakeRepo() { const root = await mkdtemp(path.join(tmpdir(), "mdx-cache-key-")); diff --git a/apps/docs/scripts/sync-docs.mjs b/apps/docs/scripts/sync-docs.mjs index e7d728b0..8a4c19dd 100644 --- a/apps/docs/scripts/sync-docs.mjs +++ b/apps/docs/scripts/sync-docs.mjs @@ -13,10 +13,17 @@ import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; -import { syncDocSource, writeReleaseSchedule } from "@coder/docs-build"; +import { + OPENAPI_MIN_LINE, + clearOpenApi, + rendersOpenApi, + syncDocSource, + withOpenApiReference, + writeReleaseSchedule, +} from "@coder/docs-build"; import { parseReleaseSchedule, resolveVersionPipeline } from "@coder/docs-config"; import { versionBaseUrl } from "@coder/docs-next/version-routing"; -import { createGitRefsProvider, createLocalTreeProvider } from "@coder/docs-sources"; +import { SWAGGER_PATH, createGitRefsProvider, createLocalTreeProvider } from "@coder/docs-sources"; import { versions } from "../lib/versions.ts"; import { CODE_SERVER_ROUTE, @@ -44,6 +51,7 @@ import { readVersionRedirects } from "./version-redirects.mjs"; const execFileAsync = promisify(execFile); const appDir = path.dirname(path.dirname(fileURLToPath(import.meta.url))); const cacheDir = path.join(appDir, ".cache", "docs-clone"); +const FIXTURE_OPENAPI_MIN_LINE = "0.2"; async function git(cwd, args, env) { await execFileAsync("git", args, { cwd, ...(env ? { env: { ...process.env, ...env } } : {}) }); @@ -70,6 +78,11 @@ async function ensureFixtureRepo() { path.join(repo, "docs", "README.md"), `# About\n\nFixture corpus at **${marker}**.\n\nRefer to [administration](./admin/index.md), and see the ![logo](./images/logo.svg).\n`, ); + await mkdir(path.join(repo, "coderd", "apidoc"), { recursive: true }); + await cp( + path.join(appDir, "fixtures", "openapi", "swagger.json"), + path.join(repo, "coderd", "apidoc", "swagger.json"), + ); await git(repo, ["add", "-A"]); await git(repo, ["commit", "-m", `docs at ${marker}`, "--allow-empty"], { GIT_AUTHOR_DATE: date, @@ -97,15 +110,29 @@ if (single) { } // Fail before the build, not after it, when this commit's redirects are invalid. await readVersionRedirects(docsRoot); - provider = createLocalTreeProvider({ docsRoot, version: single, lastModified: true }); + provider = createLocalTreeProvider({ + docsRoot, + version: single, + lastModified: true, + apiDocument: SWAGGER_PATH, + }); console.log(`[sync] corpus: local tree at ${docsRoot} as version ${single.id} (${single.ref})`); } else { const repo = process.env.DOCS_REPO ?? (await ensureFixtureRepo()); console.log( `[sync] corpus: git ${redactRepoUrl(repo)} (${versions.map((v) => v.ref).join(", ")})`, ); - provider = createGitRefsProvider({ repo, versions, cacheDir, lastModified: true }); + provider = createGitRefsProvider({ + repo, + versions, + cacheDir, + lastModified: true, + apiDocument: SWAGGER_PATH, + }); } +// The fixture's 0.2 renders the generated reference and its 0.1 keeps Markdown, as 2.24 and 2.23 do. +const usesFixture = !single && !process.env.DOCS_REPO; +const openApiMinLine = usesFixture ? FIXTURE_OPENAPI_MIN_LINE : OPENAPI_MIN_LINE; // Start from an empty content/ so switching between the fixture and a real // corpus never leaves a stale version directory behind. Clear the slug @@ -116,6 +143,7 @@ await rm(slugManifestPath(appDir), { force: true }); await rm(imageSizesPath(appDir), { force: true }); await rm(lastModifiedPath(appDir), { force: true }); await rm(releaseSchedulePath(appDir), { force: true }); +await clearOpenApi(appDir); // Latest syncs last. Each version's images are copied under its own URL // prefix in public/ (refer to syncDocSource's baseUrl), so no version's @@ -136,7 +164,12 @@ for (const version of latestLastSyncOrder(versions)) { let result; let codeServerResult; try { - const source = await provider.loadVersion(version); + let source = await provider.loadVersion(version); + if (rendersOpenApi(version, process.env, openApiMinLine)) { + source = await withOpenApiReference(appDir, version, source, source.apiDocument, { + required: process.env.DOCS_PUBLISH === "1", + }); + } result = await syncDocSource(source, { contentDir: path.join(appDir, "content", version.id), publicDir: path.join(appDir, "public"), diff --git a/apps/offlinedocs/app/[[...slug]]/page.tsx b/apps/offlinedocs/app/[[...slug]]/page.tsx index 1bce0aeb..43dac20c 100644 --- a/apps/offlinedocs/app/[[...slug]]/page.tsx +++ b/apps/offlinedocs/app/[[...slug]]/page.tsx @@ -1,4 +1,5 @@ import { createDocsPage } from "@coder/docs-next"; +import { renderApiReference } from "@/lib/openapi"; import { source } from "@/lib/source"; const { Page, generateStaticParams, generateMetadata } = createDocsPage(source, { @@ -7,6 +8,7 @@ const { Page, generateStaticParams, generateMetadata } = createDocsPage(source, // link, whose every link is to a service on the public internet. pageActions: { viewOptions: false }, editLink: false, + renderBody: renderApiReference, }); export default Page; diff --git a/apps/offlinedocs/app/global.css b/apps/offlinedocs/app/global.css index a14036a7..2f9d040a 100644 --- a/apps/offlinedocs/app/global.css +++ b/apps/offlinedocs/app/global.css @@ -1,6 +1,7 @@ @import "tailwindcss"; @import "fumadocs-ui/css/neutral.css"; @import "fumadocs-ui/css/preset.css"; +@import "fumadocs-openapi/css/preset.css"; @import "@coder/docs-theme"; @import "@fontsource-variable/geist"; @@ -13,4 +14,5 @@ * pre-generated CSS only for its own layouts). */ @source "../node_modules/@coder/docs-ui/dist/*.js"; @source "../node_modules/@coder/docs-next/dist/*.js"; +@source "../node_modules/@coder/docs-next/dist/openapi/*.js"; @source "../node_modules/fumadocs-ui/dist/components/ui/popover.js"; diff --git a/apps/offlinedocs/lib/openapi.ts b/apps/offlinedocs/lib/openapi.ts new file mode 100644 index 00000000..5a157a13 --- /dev/null +++ b/apps/offlinedocs/lib/openapi.ts @@ -0,0 +1,6 @@ +import { createOpenApiDataLoader, createOpenApiRenderBody } from "@coder/docs-next/openapi"; +import { OPENAPI_DATA_ID } from "../scripts/sync-helpers.mjs"; + +export const renderApiReference = createOpenApiRenderBody( + createOpenApiDataLoader(process.cwd(), () => OPENAPI_DATA_ID), +); diff --git a/apps/offlinedocs/lib/source.ts b/apps/offlinedocs/lib/source.ts index 3c376176..37243ee7 100644 --- a/apps/offlinedocs/lib/source.ts +++ b/apps/offlinedocs/lib/source.ts @@ -1,5 +1,6 @@ import { navTitlePlugin, stateBadgesPlugin } from "@coder/docs-next"; import { loader } from "fumadocs-core/source"; +import { openapiPlugin } from "fumadocs-openapi/server"; // The generated collection stays below the package imports, as in // apps/docs/lib/sources.ts: the order Turbopack meets these imports in decides @@ -11,5 +12,5 @@ import { docs } from "@/.source/server"; export const source = loader({ baseUrl: "/", source: docs.toFumadocsSource(), - plugins: [navTitlePlugin(), stateBadgesPlugin()], + plugins: [navTitlePlugin(), stateBadgesPlugin(), openapiPlugin()], }); diff --git a/apps/offlinedocs/next.config.mjs b/apps/offlinedocs/next.config.mjs index 0751a748..252b0215 100644 --- a/apps/offlinedocs/next.config.mjs +++ b/apps/offlinedocs/next.config.mjs @@ -1,3 +1,4 @@ +import { withoutOpenApiPlayground } from "@coder/docs-next/next-config"; import { createMDX } from "fumadocs-mdx/next"; // Vercel's build image sets NEXT_DEPLOYMENT_ID. When it is present, Next 16 @@ -15,11 +16,13 @@ delete process.env.NEXT_DEPLOYMENT_ID; const withMDX = createMDX(); -export default withMDX({ - // A static, serverless bundle: no live search route, no ISR. `next build` - // sets NODE_ENV=production, so builds always export; `next dev` stays a - // normal dev server. - output: process.env.NODE_ENV === "production" ? "export" : undefined, - trailingSlash: true, - images: { unoptimized: true }, -}); +export default withoutOpenApiPlayground( + withMDX({ + // A static, serverless bundle: no live search route, no ISR. `next build` + // sets NODE_ENV=production, so builds always export; `next dev` stays a + // normal dev server. + output: process.env.NODE_ENV === "production" ? "export" : undefined, + trailingSlash: true, + images: { unoptimized: true }, + }), +); diff --git a/apps/offlinedocs/package.json b/apps/offlinedocs/package.json index 77397f8f..452c6002 100644 --- a/apps/offlinedocs/package.json +++ b/apps/offlinedocs/package.json @@ -13,6 +13,7 @@ "build": "next build && node ../docs/scripts/relocate-twins.mjs out && node ../docs/scripts/semantic-index.mjs out", "build:output": "node scripts/build-output.mjs", "csp:check": "node scripts/csp-check.mjs", + "playground:check": "node scripts/playground-check.mjs out", "analytics:check": "node scripts/analytics-check.mjs", "annotations:check": "node scripts/annotations-check.mjs", "pretypecheck": "[ -n \"$TURBO_HASH\" ] || pnpm run sync", @@ -32,6 +33,7 @@ "@fontsource-variable/geist-mono": "5.3.0", "fumadocs-core": "catalog:", "fumadocs-mdx": "catalog:", + "fumadocs-openapi": "12.6.1", "fumadocs-ui": "catalog:", "next": "catalog:", "react": "catalog:", diff --git a/apps/offlinedocs/scripts/playground-check-helpers.mjs b/apps/offlinedocs/scripts/playground-check-helpers.mjs new file mode 100644 index 00000000..230d596b --- /dev/null +++ b/apps/offlinedocs/scripts/playground-check-helpers.mjs @@ -0,0 +1,30 @@ +import { readFile, readdir } from "node:fs/promises"; +import path from "node:path"; +import { OPENAPI_PLAYGROUND_MARKERS } from "@coder/docs-next/next-config"; + +/** + * Every JavaScript file under a static export that holds fumadocs-openapi + * playground code, with the markers it holds. Throws when the directory is + * missing or has no JavaScript, so a broken build never passes as clean. + * @param {string} exportDir + * @returns {Promise<{ file: string, markers: string[] }[]>} + */ +export async function findPlaygroundCode(exportDir) { + const entries = await readdir(exportDir, { recursive: true, withFileTypes: true }).catch( + (error) => { + throw new Error(`playground-check: ${exportDir} is missing; build first (${error.message})`); + }, + ); + const files = entries + .filter((entry) => entry.isFile() && /\.[cm]?js$/.test(entry.name)) + .map((entry) => path.join(entry.parentPath, entry.name)) + .toSorted(); + if (files.length === 0) throw new Error(`playground-check: no JavaScript under ${exportDir}`); + const found = []; + for (const file of files) { + const text = await readFile(file, "utf8"); + const markers = OPENAPI_PLAYGROUND_MARKERS.filter((marker) => text.includes(marker)); + if (markers.length > 0) found.push({ file: path.relative(exportDir, file), markers }); + } + return found; +} diff --git a/apps/offlinedocs/scripts/playground-check.mjs b/apps/offlinedocs/scripts/playground-check.mjs new file mode 100644 index 00000000..b759c7ea --- /dev/null +++ b/apps/offlinedocs/scripts/playground-check.mjs @@ -0,0 +1,16 @@ +// Fails when a static export ships fumadocs-openapi playground code: `node playground-check.mjs <exportDir>`. +import path from "node:path"; +import { findPlaygroundCode } from "./playground-check-helpers.mjs"; + +if (!process.argv[2]) { + console.error("usage: node playground-check.mjs <exportDir>"); + process.exit(2); +} +const exportDir = path.resolve(process.cwd(), process.argv[2]); +const found = await findPlaygroundCode(exportDir); +if (found.length > 0) { + console.error(`[playground-check] API playground code in ${found.length} file(s):`); + for (const { file, markers } of found) console.error(` - ${file}: ${markers.join(", ")}`); + process.exit(1); +} +console.log(`[playground-check] ${exportDir}: no API playground code`); diff --git a/apps/offlinedocs/scripts/playground-check.test.mjs b/apps/offlinedocs/scripts/playground-check.test.mjs new file mode 100644 index 00000000..4bceb168 --- /dev/null +++ b/apps/offlinedocs/scripts/playground-check.test.mjs @@ -0,0 +1,46 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { OPENAPI_PLAYGROUND_MARKERS } from "@coder/docs-next/next-config"; +import { findPlaygroundCode } from "./playground-check-helpers.mjs"; + +async function exportWith(files) { + const dir = await mkdtemp(path.join(tmpdir(), "playground-check-")); + for (const [rel, text] of Object.entries(files)) { + await mkdir(path.dirname(path.join(dir, rel)), { recursive: true }); + await writeFile(path.join(dir, rel), text); + } + return dir; +} + +test("finds each marker in the export's JavaScript", async (t) => { + for (const marker of OPENAPI_PLAYGROUND_MARKERS) { + const dir = await exportWith({ + "_next/static/chunks/a.js": "console.log(1)", + "_next/static/chunks/b.js": `sessionStorage.getItem(${JSON.stringify(marker)})`, + }); + t.after(() => rm(dir, { recursive: true, force: true })); + assert.deepEqual(await findPlaygroundCode(dir), [ + { file: path.join("_next", "static", "chunks", "b.js"), markers: [marker] }, + ]); + } +}); + +test("passes an export without playground code, and ignores page data", async (t) => { + const dir = await exportWith({ + "_next/static/chunks/a.js": "console.log(1)", + "reference/api/index.html": "<p>grant_type</p>", + "reference/api/index.txt": "device_code", + }); + t.after(() => rm(dir, { recursive: true, force: true })); + assert.deepEqual(await findPlaygroundCode(dir), []); +}); + +test("fails closed on a missing export or one with no JavaScript", async (t) => { + const dir = await exportWith({ "index.html": "<p></p>" }); + t.after(() => rm(dir, { recursive: true, force: true })); + await assert.rejects(findPlaygroundCode(dir), /no JavaScript/); + await assert.rejects(findPlaygroundCode(path.join(dir, "missing")), /is missing/); +}); diff --git a/apps/offlinedocs/scripts/sync-docs.mjs b/apps/offlinedocs/scripts/sync-docs.mjs index b7f7eff9..f33a3ac9 100644 --- a/apps/offlinedocs/scripts/sync-docs.mjs +++ b/apps/offlinedocs/scripts/sync-docs.mjs @@ -14,11 +14,18 @@ import { cp, mkdir, readFile, writeFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { syncDocSource, writeReleaseSchedule } from "@coder/docs-build"; +import { + clearOpenApi, + rendersOpenApi, + syncDocSource, + withOpenApiReference, + writeReleaseSchedule, +} from "@coder/docs-build"; import { parseReleaseSchedule } from "@coder/docs-config"; -import { createGitRefsProvider, createLocalTreeProvider } from "@coder/docs-sources"; +import { SWAGGER_PATH, createGitRefsProvider, createLocalTreeProvider } from "@coder/docs-sources"; import { assertDeployHasCorpus, + OPENAPI_DATA_ID, exportVersionFromEnv, githubBlobSourceLink, redactRepoUrl, @@ -34,13 +41,18 @@ const version = exportVersionFromEnv(process.env); let provider; let sourceLink; if (process.env.DOCS_ROOT) { - provider = createLocalTreeProvider({ docsRoot: process.env.DOCS_ROOT, version }); + provider = createLocalTreeProvider({ + docsRoot: process.env.DOCS_ROOT, + version, + apiDocument: SWAGGER_PATH, + }); console.log(`[sync] corpus: local tree at ${process.env.DOCS_ROOT}`); } else if (process.env.DOCS_REPO) { provider = createGitRefsProvider({ repo: process.env.DOCS_REPO, versions: [version], cacheDir: path.join(appDir, ".cache", "docs-clone"), + apiDocument: SWAGGER_PATH, }); sourceLink = githubBlobSourceLink(process.env.DOCS_REPO, version.ref); console.log(`[sync] corpus: git ${redactRepoUrl(process.env.DOCS_REPO)} @ ${version.ref}`); @@ -52,7 +64,14 @@ if (process.env.DOCS_ROOT) { console.log("[sync] corpus: committed fixture (set DOCS_ROOT or DOCS_REPO for the real corpus)"); } -const source = await provider.loadVersion(version); +await clearOpenApi(appDir); +let source = await provider.loadVersion(version); +if ((process.env.DOCS_ROOT || process.env.DOCS_REPO) && rendersOpenApi(version)) { + source = await withOpenApiReference(appDir, version, source, source.apiDocument, { + required: process.env.DOCS_PUBLISH === "1", + dataId: OPENAPI_DATA_ID, + }); +} const result = await syncDocSource(source, { contentDir: path.join(appDir, "content", "docs"), publicDir: path.join(appDir, "public"), diff --git a/apps/offlinedocs/scripts/sync-helpers.mjs b/apps/offlinedocs/scripts/sync-helpers.mjs index 434d736f..6e94d725 100644 --- a/apps/offlinedocs/scripts/sync-helpers.mjs +++ b/apps/offlinedocs/scripts/sync-helpers.mjs @@ -78,3 +78,6 @@ export function exportVersionFromEnv(env) { ); return { id: match[1], label: `v${match[1]}`, ref, latest: true }; } + +/** The API reference data's file name: fixed, not the version id, so any DOCS_VERSION finds it. */ +export const OPENAPI_DATA_ID = "docs"; diff --git a/apps/offlinedocs/scripts/sync-helpers.test.mjs b/apps/offlinedocs/scripts/sync-helpers.test.mjs index e204c110..22e86632 100644 --- a/apps/offlinedocs/scripts/sync-helpers.test.mjs +++ b/apps/offlinedocs/scripts/sync-helpers.test.mjs @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; -import { readFile } from "node:fs/promises"; +import { mkdtemp, readFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; import path from "node:path"; import { test } from "node:test"; import { fileURLToPath } from "node:url"; @@ -8,8 +9,11 @@ import { compileVercelHeaders, headersForPath, } from "../../docs/scripts/vercel-headers.mjs"; +import { withOpenApiReference } from "@coder/docs-build"; +import { openApiDataFile } from "@coder/docs-config"; import { buildOutputConfig } from "./build-output-helpers.mjs"; import { + OPENAPI_DATA_ID, assertDeployHasCorpus, exportVersionFromEnv, githubBlobSourceLink, @@ -202,3 +206,43 @@ test("a DOCS_VERSION that isn't a version or main fails the sync", () => { assert.throws(() => exportVersionFromEnv({ DOCS_VERSION: value }), /DOCS_VERSION/, value); } }); + +const swagger = JSON.parse( + await readFile(new URL("../../docs/fixtures/openapi/swagger.json", import.meta.url), "utf8"), +); + +const source = { + files: [ + { path: "reference/api/index.md", content: "# REST API\n" }, + { path: "reference/api/users.md", content: "# Users\n" }, + { path: "reference/api/workspaces.md", content: "# Workspaces\n" }, + { path: "reference/api/schemas.md", content: "# Schemas\n" }, + ], + images: [], + manifest: { + versions: ["main"], + routes: [ + { + title: "REST API", + path: "./reference/api/index.md", + children: [ + { title: "Users", path: "./reference/api/users.md" }, + { title: "Workspaces", path: "./reference/api/workspaces.md" }, + { title: "Schemas", path: "./reference/api/schemas.md" }, + ], + }, + ], + }, +}; + +test("the reference data of a release export is where lib/openapi.ts reads it", async () => { + const exportDir = await mkdtemp(path.join(tmpdir(), "offline-openapi-")); + const version = exportVersionFromEnv({ DOCS_VERSION: "v2.38.1" }); + assert.equal(version.id, "2.38.1"); + await withOpenApiReference(exportDir, version, source, swagger, { + logger: { log() {}, warn() {} }, + dataId: OPENAPI_DATA_ID, + }); + const data = JSON.parse(await readFile(openApiDataFile(exportDir, OPENAPI_DATA_ID), "utf8")); + assert.ok(data.operations["reference/api/users/create-new-user"]); +}); diff --git a/packages/docs-build/package.json b/packages/docs-build/package.json index 421cf918..cc96e39a 100644 --- a/packages/docs-build/package.json +++ b/packages/docs-build/package.json @@ -24,8 +24,12 @@ }, "dependencies": { "@coder/docs-config": "workspace:*", + "@coder/docs-manifest": "workspace:*", "@coder/docs-transforms": "workspace:*", - "@fumari/image-size": "0.1.1" + "@fumari/image-size": "0.1.1", + "github-slugger": "2.0.0", + "oas-validator": "5.0.8", + "swagger2openapi": "7.0.8" }, "devDependencies": { "@mdx-js/mdx": "3.1.1", diff --git a/packages/docs-build/src/index.ts b/packages/docs-build/src/index.ts index 98517ef5..3f997287 100644 --- a/packages/docs-build/src/index.ts +++ b/packages/docs-build/src/index.ts @@ -9,3 +9,12 @@ export { reservedAssetReason, reservedRouteReason, } from "./reserved-routes.js"; +export { applyOpenApiReference, convertSwagger, tagSlug } from "./openapi-reference.js"; +export { + OPENAPI_MIN_LINE, + clearOpenApi, + rendersOpenApi, + withOpenApiReference, +} from "./openapi-output.js"; +export type { ApplyOpenApiReferenceOptions, OpenApiReference } from "./openapi-reference.js"; +export type { WithOpenApiReferenceOptions } from "./openapi-output.js"; diff --git a/packages/docs-build/src/openapi-output.test.ts b/packages/docs-build/src/openapi-output.test.ts new file mode 100644 index 00000000..e4548bc8 --- /dev/null +++ b/packages/docs-build/src/openapi-output.test.ts @@ -0,0 +1,140 @@ +import assert from "node:assert/strict"; +import { mkdtemp, readFile, stat } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { test } from "node:test"; +import { type DocSource, openApiDataDir } from "@coder/docs-config"; +import { + OPENAPI_MIN_LINE, + clearOpenApi, + rendersOpenApi, + withOpenApiReference, +} from "./openapi-output.js"; + +const swagger = JSON.parse( + await readFile( + new URL("../../../apps/docs/fixtures/openapi/swagger.json", import.meta.url), + "utf8", + ), +); + +const source: DocSource = { + files: [ + { path: "reference/api/index.md", content: "# REST API\n" }, + { path: "reference/api/users.md", content: "# Users\n" }, + { path: "reference/api/workspaces.md", content: "# Workspaces\n" }, + { path: "reference/api/schemas.md", content: "# Schemas\n" }, + ], + images: [], + manifest: { + versions: ["main"], + routes: [ + { + title: "REST API", + path: "./reference/api/index.md", + children: [ + { title: "Users", path: "./reference/api/users.md" }, + { title: "Workspaces", path: "./reference/api/workspaces.md" }, + { title: "Schemas", path: "./reference/api/schemas.md" }, + ], + }, + ], + }, +}; + +const quiet = { log() {}, warn() {} }; + +test(`main and every line or tag from ${OPENAPI_MIN_LINE} render the reference; older ones keep Markdown`, () => { + assert.equal(OPENAPI_MIN_LINE, "2.24"); + for (const id of ["main", "2.38", "2.24", "2.24.1", "2.39"]) + assert.equal(rendersOpenApi({ id }, {}), true, id); + for (const id of ["2.23", "2.23.9", "2.9"]) assert.equal(rendersOpenApi({ id }, {}), false, id); +}); + +test("DOCS_OPENAPI=0, false, off or no, in any case, keeps Markdown for every version", () => { + for (const value of ["0", "false", "off", "no", "FALSE", "Off", " no "]) + for (const id of ["main", "2.38"]) + assert.equal(rendersOpenApi({ id }, { DOCS_OPENAPI: value }), false, value); +}); + +test("DOCS_OPENAPI unset, empty, 1, true, on or yes renders the reference", () => { + assert.equal(rendersOpenApi({ id: "main" }, {}), true); + for (const value of ["", "1", "true", "on", "yes", "TRUE"]) + assert.equal(rendersOpenApi({ id: "main" }, { DOCS_OPENAPI: value }), true, value); +}); + +test("an unrecognised DOCS_OPENAPI fails the sync rather than being ignored", () => { + for (const value of ["disabled", "nope", "2"]) + assert.throws(() => rendersOpenApi({ id: "main" }, { DOCS_OPENAPI: value }), /DOCS_OPENAPI/); +}); + +test("a corpus with its own versions, such as the fixture, can set its own floor line", () => { + assert.equal(rendersOpenApi({ id: "0.2" }, {}, "0.2"), true); + assert.equal(rendersOpenApi({ id: "0.1" }, {}, "0.2"), false); +}); + +test("the version's reference data is written where the page renderer reads it", async () => { + const appDir = await mkdtemp(path.join(tmpdir(), "openapi-output-")); + const next = await withOpenApiReference(appDir, { id: "2.38" }, source, swagger, { + logger: quiet, + }); + assert.ok(next.files.some((file) => file.path === "reference/api/users/create-new-user.md")); + const data = JSON.parse(await readFile(path.join(openApiDataDir(appDir), "2.38.json"), "utf8")); + assert.deepEqual(Object.keys(data).sort(), [ + "anchors", + "document", + "landing", + "operations", + "schemas", + ]); + assert.equal(data.landing.route, "reference/api"); + await clearOpenApi(appDir); + await assert.rejects(stat(openApiDataDir(appDir)), { code: "ENOENT" }); +}); + +test("an API landing page nested past the Markdown cap is rejected before it is parsed", async () => { + const appDir = await mkdtemp(path.join(tmpdir(), "openapi-output-")); + const deep: DocSource = { + ...source, + files: source.files.map((file) => + file.path === "reference/api/index.md" + ? { ...file, content: `# REST API\n\n${">".repeat(101)} deep\n` } + : file, + ), + }; + await assert.rejects( + withOpenApiReference(appDir, { id: "2.38" }, deep, swagger, { logger: quiet }), + /nested 101 levels/, + ); +}); + +test("a version without a Swagger document keeps its Markdown reference and writes nothing", async () => { + const appDir = await mkdtemp(path.join(tmpdir(), "openapi-output-")); + const next = await withOpenApiReference(appDir, { id: "2.10" }, source, undefined, { + logger: quiet, + }); + assert.equal(next, source); + await assert.rejects(stat(openApiDataDir(appDir)), { code: "ENOENT" }); +}); + +test("a publish fails rather than ship a selected version without its Swagger document", async () => { + const appDir = await mkdtemp(path.join(tmpdir(), "openapi-output-")); + await assert.rejects( + withOpenApiReference(appDir, { id: "2.38" }, source, undefined, { + logger: quiet, + required: true, + }), + /2\.38: no Swagger document \(coderd\/apidoc\/swagger\.json\)/, + ); + await assert.rejects(stat(openApiDataDir(appDir)), { code: "ENOENT" }); +}); + +test("a caller can name the data file, as the single-version offline export does", async () => { + const appDir = await mkdtemp(path.join(tmpdir(), "openapi-output-")); + await withOpenApiReference(appDir, { id: "2.38.1" }, source, swagger, { + logger: quiet, + dataId: "docs", + }); + const data = JSON.parse(await readFile(path.join(openApiDataDir(appDir), "docs.json"), "utf8")); + assert.equal(data.landing.route, "reference/api"); +}); diff --git a/packages/docs-build/src/openapi-output.ts b/packages/docs-build/src/openapi-output.ts new file mode 100644 index 00000000..db86144d --- /dev/null +++ b/packages/docs-build/src/openapi-output.ts @@ -0,0 +1,83 @@ +import { mkdir, rm, writeFile } from "node:fs/promises"; +import { + type DocSource, + type OpenApiPagesData, + openApiDataDir, + openApiDataFile, +} from "@coder/docs-config"; +import { isLineAtLeast } from "@coder/docs-manifest/version-segment"; +import { applyOpenApiReference } from "./openapi-reference.js"; + +export interface WithOpenApiReferenceOptions { + logger?: Pick<Console, "log" | "warn">; + /** Throw instead of keeping the Markdown reference when there is no Swagger document: set for a publish. */ + required?: boolean; + /** The data file's name, without `.json`; defaults to the version id. */ + dataId?: string; +} + +/** The oldest line whose Swagger document converts cleanly; older lines repeat operation ids. */ +export const OPENAPI_MIN_LINE = "2.24"; + +const OPENAPI_OFF = new Set(["0", "false", "off", "no"]); +const OPENAPI_ON = new Set(["", "1", "true", "on", "yes"]); + +/** Whether a version renders the generated reference: main and every line or tag from `minLine`, unless DOCS_OPENAPI turns it off. */ +export function rendersOpenApi( + version: { id: string }, + env: Record<string, string | undefined> = process.env, + minLine: string = OPENAPI_MIN_LINE, +): boolean { + const value = (env.DOCS_OPENAPI ?? "").trim().toLowerCase(); + if (OPENAPI_OFF.has(value)) return false; + if (!OPENAPI_ON.has(value)) { + throw new Error( + `DOCS_OPENAPI must be 0, false, off or no to keep the Markdown reference, or 1, true, on, yes or unset to render it; got ${JSON.stringify(env.DOCS_OPENAPI)}`, + ); + } + return isLineAtLeast(version.id, minLine); +} + +export async function clearOpenApi(appDir: string): Promise<void> { + await rm(openApiDataDir(appDir), { recursive: true, force: true }); +} + +/** + * Swaps the version's Markdown API reference for one page per operation and + * writes the data the renderer needs. Returns the source unchanged when there + * is no Swagger document. + */ +export async function withOpenApiReference( + appDir: string, + version: { id: string }, + source: DocSource, + swagger: unknown, + options: WithOpenApiReferenceOptions = {}, +): Promise<DocSource> { + const { logger = console, required = false, dataId = version.id } = options; + if (swagger === undefined) { + const message = `${version.id}: no Swagger document (coderd/apidoc/swagger.json)`; + if (required) throw new Error(`${message}, so a publish would ship the Markdown API reference`); + logger.warn(`[sync] ${message}; keeping the Markdown API reference`); + return source; + } + const started = Date.now(); + const { source: next, reference } = await applyOpenApiReference(source, swagger); + await mkdir(openApiDataDir(appDir), { recursive: true }); + await writeFile( + openApiDataFile(appDir, dataId), + JSON.stringify({ + document: reference.document, + operations: reference.operations, + anchors: reference.anchors, + landing: reference.landing, + schemas: reference.schemas, + } satisfies OpenApiPagesData), + ); + logger.log( + `[sync] ${version.id}: API reference, ${Object.keys(reference.operations).length} operation pages in ${Date.now() - started} ms`, + ); + for (const warning of reference.warnings) + logger.warn(`[sync] ${version.id}: openapi: ${warning}`); + return next; +} diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts new file mode 100644 index 00000000..4132bbca --- /dev/null +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -0,0 +1,378 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { test } from "node:test"; +import type { DocSource } from "@coder/docs-config"; +import { createProcessor } from "@mdx-js/mdx"; +import { applyOpenApiReference, assertConvertedDocument } from "./openapi-reference.js"; + +const swagger = JSON.parse( + await readFile( + new URL("../../../apps/docs/fixtures/openapi/swagger.json", import.meta.url), + "utf8", + ), +); + +const source: DocSource = { + files: [ + { path: "reference/api/index.md", content: "# REST API\n" }, + { path: "reference/api/users.md", content: "# Users\n\n## Create new user\n" }, + { path: "reference/api/workspaces.md", content: "# Workspaces\n\n## List workspaces\n" }, + { path: "reference/api/schemas.md", content: "# Schemas\n\n## codersdk.User\n" }, + ], + images: [], + manifest: { + versions: ["main"], + routes: [ + { + title: "REST API", + path: "./reference/api/index.md", + children: [ + { title: "Users", path: "./reference/api/users.md" }, + { title: "Workspaces", path: "./reference/api/workspaces.md" }, + { title: "Schemas", path: "./reference/api/schemas.md" }, + ], + }, + ], + }, +}; + +test("each documented operation gets a page under its tag, named by the old anchor", async () => { + const { source: out, reference } = await applyOpenApiReference(source, swagger); + assert.deepEqual(reference.operations, { + "reference/api/workspaces/list-workspaces": { method: "get", path: "/api/v2/workspaces" }, + "reference/api/users/create-new-user": { method: "post", path: "/api/v2/users" }, + "reference/api/users/get-user-by-name": { method: "get", path: "/api/v2/users/{user}" }, + }); + const paths = out.files.map((file) => file.path).sort(); + assert.ok(paths.includes("reference/api/users/create-new-user.md")); + assert.ok(!paths.some((p) => p.includes("pprof")), "x-apidocgen skip is honoured"); + const users = out.manifest.routes[0]?.children?.find((c) => c.title === "Users"); + assert.deepEqual( + users?.children?.map((c) => c.path), + ["./reference/api/users/create-new-user.md", "./reference/api/users/get-user-by-name.md"], + ); +}); + +test("each operation page records its method for the sidebar's method badge", async () => { + const { source: out } = await applyOpenApiReference(source, swagger); + const page = out.files.find((file) => file.path === "reference/api/users/create-new-user.md"); + assert.match( + page?.content ?? "", + /^---\ntitle: "Create new user"\n_openapi:\n {2}method: post\n---\n/, + ); +}); + +test("old tag and schema anchors redirect to the operation pages", async () => { + const { reference } = await applyOpenApiReference(source, swagger); + assert.equal( + reference.anchors["reference/api/users"]?.["get-user-by-name"], + "reference/api/users/get-user-by-name", + ); + assert.equal( + reference.anchors["reference/api/schemas"]?.["codersdkworkspace"], + "reference/api/workspaces/list-workspaces", + ); +}); + +test("the try-it server is the reader's deployment, not the docs site", async () => { + const { reference } = await applyOpenApiReference(source, swagger); + assert.deepEqual(reference.document.servers, [ + { + url: "{deployment}", + variables: { + deployment: { + default: "https://coder.example.com", + description: "The URL of your Coder deployment", + }, + }, + }, + ]); +}); + +test("a Swagger document with an external $ref is rejected before conversion", async () => { + for (const ref of ["https://example.com/schema.json", "../x.json"]) { + const hostile = structuredClone(swagger); + hostile.definitions["codersdk.User"].properties.id = { $ref: ref }; + await assert.rejects( + applyOpenApiReference(source, hostile), + /\$ref at \/definitions\/codersdk\.User\/properties\/id\/\$ref is not an in-document reference/, + ); + } +}); + +test("a converted document with an external $ref is rejected before it can reach the renderer", async () => { + const { reference } = await applyOpenApiReference(source, swagger); + await assertConvertedDocument(reference.document); + for (const ref of ["https://example.com/schema.json", "/etc/passwd", "../x.json"]) { + const hostile = structuredClone(reference.document); + const schemas = (hostile.components as { schemas: Record<string, unknown> }).schemas; + schemas["codersdk.User"] = { $ref: ref }; + await assert.rejects( + assertConvertedDocument(hostile), + /the converted OpenAPI document: \$ref at \/components\/schemas\/codersdk\.User\/\$ref is not an in-document reference/, + ); + } +}); + +test("summaries are escaped where the tag and schemas pages put them in Markdown", async () => { + const tricky = structuredClone(swagger); + tricky.paths["/api/v2/workspaces"].get.summary = "List [all] a|b \\ *workspaces*"; + const { source: out } = await applyOpenApiReference(source, tricky); + const tagPage = out.files.find((file) => file.path === "reference/api/workspaces.md")?.content; + assert.match(tagPage ?? "", /- \[List \\\[all\\\] a\\\|b \\\\ \\\*workspaces\\\*\]\(/); +}); + +test("a schema name with a pipe or a backtick stays inside its table cell", async () => { + const tricky = structuredClone(swagger); + tricky.definitions["a|b`c"] = { type: "object" }; + const { source: out } = await applyOpenApiReference(source, tricky); + const page = out.files.find((file) => file.path === "reference/api/schemas.md")?.content ?? ""; + const row = page.split("\n").find((line) => line.includes("a_b_c")); + assert.equal(row, "| `a_b_c` | Not used by a documented endpoint |"); +}); + +test("the undeclared CoderProvisionerKey scheme is defined as the header coderd reads", async () => { + const doc = structuredClone(swagger); + doc.paths["/api/v2/users/{user}"].get.security = [{ CoderProvisionerKey: [] }]; + doc.paths["/api/v2/users"].post.security = [{ Undeclared: [] }]; + const { reference } = await applyOpenApiReference(source, doc); + const { document: converted, warnings } = reference; + const components = converted.components as { securitySchemes: Record<string, unknown> }; + assert.deepEqual(components.securitySchemes.CoderProvisionerKey, { + type: "apiKey", + in: "header", + name: "Coder-Provisioner-Daemon-Key", + }); + const paths = converted.paths as Record<string, Record<string, { security?: unknown }>>; + assert.deepEqual(paths["/api/v2/users/{user}"]?.get?.security, [{ CoderProvisionerKey: [] }]); + assert.deepEqual(paths["/api/v2/users"]?.post?.security, []); + assert.ok(warnings.some((warning) => warning.includes("Undeclared is not defined"))); + assert.ok(!warnings.some((warning) => warning.includes("CoderProvisionerKey"))); +}); + +function retagged(changes: { tag?: string; summary?: string }[]) { + const doc = structuredClone(swagger); + const ops = [ + doc.paths["/api/v2/workspaces"].get, + doc.paths["/api/v2/users"].post, + doc.paths["/api/v2/users/{user}"].get, + ]; + changes.forEach((change, index) => { + if (change.tag !== undefined) ops[index].tags = [change.tag]; + if (change.summary !== undefined) ops[index].summary = change.summary; + }); + return doc; +} + +test("two tags that differ only in case or punctuation fail instead of overwriting each other", async () => { + await assert.rejects( + applyOpenApiReference(source, retagged([{ tag: "Templates" }, { tag: "templates" }])), + /reference\/api\/templates\.md is generated twice/, + ); +}); + +test("a tag named Schemas or Index fails instead of replacing the schemas or landing page", async () => { + await assert.rejects( + applyOpenApiReference(source, retagged([{ tag: "Schemas" }])), + /reference\/api\/schemas\.md is generated twice/, + ); + await assert.rejects( + applyOpenApiReference(source, retagged([{ tag: "Index" }])), + /reference\/api\/index\.md is generated twice/, + ); +}); + +test("an operation summarised as Index fails instead of taking its tag page's route", async () => { + await assert.rejects( + applyOpenApiReference(source, retagged([{}, { summary: "Index" }])), + /reference\/api\/users\/index\.md and reference\/api\/users\.md share the route reference\/api\/users/, + ); +}); + +test("a tag or summary with nothing to slug fails instead of writing a nameless page", async () => { + await assert.rejects( + applyOpenApiReference(source, retagged([{ tag: "!!!" }])), + /tag "!!!" has no characters to name its page by/, + ); + await assert.rejects( + applyOpenApiReference(source, retagged([{ summary: "!!!" }])), + /summary "!!!" has no characters to name its page by/, + ); +}); + +function inlineCode(markdown: string): string[] { + const values: string[] = []; + const visit = (node: { type: string; value?: string; children?: unknown[] }) => { + if (node.type === "inlineCode" && node.value !== undefined) values.push(node.value); + for (const child of node.children ?? []) visit(child as typeof node); + }; + visit(createProcessor({ format: "md" }).parse(markdown.replace(/^---\n[\s\S]*?\n---\n/, ""))); + return values; +} + +test("a path with a backtick stays one code span on its tag page and its own page", async () => { + const odd = structuredClone(swagger); + odd.paths["/api/v2/a`b``c"] = odd.paths["/api/v2/workspaces"]; + delete odd.paths["/api/v2/workspaces"]; + const { source: out } = await applyOpenApiReference(source, odd); + const page = (path: string) => out.files.find((file) => file.path === path)?.content ?? ""; + for (const path of ["reference/api/workspaces.md", "reference/api/workspaces/list-workspaces.md"]) + assert.deepEqual(inlineCode(page(path)), ["GET /api/v2/a`b``c"], path); +}); + +const withLanding = (content: string): DocSource => ({ + ...source, + files: source.files.map((file) => + file.path === "reference/api/index.md" ? { ...file, content } : file, + ), +}); + +const landingPage = (out: DocSource): string => + out.files.find((file) => file.path === "reference/api/index.md")?.content ?? ""; + +test("the landing page gets the environment setup section before its first section", async () => { + const { source: out, reference } = await applyOpenApiReference( + withLanding( + "# REST API\n\nIntro.\n\n```md\n## Not a heading\n```\n\n## Quickstart\n\nSteps.\n", + ), + swagger, + ); + const page = landingPage(out); + const setup = page.indexOf("## Set up your environment"); + assert.ok(setup > page.indexOf("## Not a heading"), "a heading in a code fence is not a section"); + assert.ok(setup < page.indexOf("## Quickstart")); + assert.match(page, /export CODER_URL="\$\(coder whoami -o json \| jq -r '\.\[0\]\.url'\)"/); + assert.match(page, /export CODER_SESSION_TOKEN="\$\(coder login token\)"/); + assert.match(page, /coder tokens create --name/); + assert.equal(reference.landing.setupId, "set-up-your-environment"); +}); + +test("the setup section is appended to a landing page with no sections", async () => { + const { source: out } = await applyOpenApiReference(source, swagger); + assert.match(landingPage(out), /^# REST API\n\n## Set up your environment\n/); +}); + +test("the landing sections follow the sidebar's tag order, one card per operation", async () => { + const { reference } = await applyOpenApiReference(source, swagger); + assert.equal(reference.landing.route, "reference/api"); + assert.deepEqual(reference.landing.sections, [ + { + title: "Users", + id: "users", + operations: [ + { route: "reference/api/users/create-new-user", title: "Create new user", method: "post" }, + { route: "reference/api/users/get-user-by-name", title: "Get user by name", method: "get" }, + ], + }, + { + title: "Workspaces", + id: "workspaces", + operations: [ + { + route: "reference/api/workspaces/list-workspaces", + title: "List workspaces", + method: "get", + description: "Returns the workspaces the caller can read, filtered by the search query.", + }, + ], + }, + ]); +}); + +test("a card's description is the first sentence of the operation's, as plain text", async () => { + const long = structuredClone(swagger); + long.paths["/api/v2/workspaces"].get.description = + "Lists [workspaces](https://example.com) with `q`.\nMore detail.\n\nSecond paragraph."; + const { reference } = await applyOpenApiReference(source, long); + const op = reference.landing.sections[1]?.operations[0]; + assert.equal(op?.description, "Lists workspaces with q."); +}); + +test("a description that opens with a long run of [ takes no longer than an ordinary one", async () => { + const hostile = structuredClone(swagger); + hostile.paths["/api/v2/workspaces"].get.description = "[".repeat(100_000); + const started = performance.now(); + const { reference } = await applyOpenApiReference(source, hostile); + assert.ok(performance.now() - started < 1000, `took ${performance.now() - started} ms`); + assert.ok((reference.landing.sections[1]?.operations[0]?.description?.length ?? 0) <= 201); +}); + +test("section ids never repeat a heading the landing page already has", async () => { + const { reference } = await applyOpenApiReference( + withLanding("# REST API\n\n## Users\n\n## Set up your environment\n"), + swagger, + ); + assert.equal(reference.landing.setupId, "set-up-your-environment"); + assert.equal(reference.landing.sections[0]?.id, "users-1"); + assert.equal(reference.landing.sections[1]?.id, "workspaces"); +}); + +test("a tag named for a Next.js bootstrap global gets a protected section id, and two tags cannot collide on it", async () => { + const { reference } = await applyOpenApiReference( + source, + retagged([{ tag: "__next_f" }, { tag: "user-content-__next_f" }, { tag: "__NEXT_DATA__" }]), + ); + const idOf = (title: string) => + reference.landing.sections.find((section) => section.title === title)?.id; + assert.equal(idOf("__next_f"), "user-content-__next_f"); + assert.equal(idOf("user-content-__next_f"), "user-content-__next_f-1"); + assert.equal(idOf("__NEXT_DATA__"), "user-content-__next_data__"); +}); + +test("the appended setup section follows the page's text, not its trailing blank lines", async () => { + const { source: out } = await applyOpenApiReference( + withLanding(`# REST API\n\nIntro.\n\n\n \n`), + swagger, + ); + assert.match(landingPage(out), /Intro\.\n\n## Set up your environment\n/); +}); + +test("an older document's basePath is folded into its paths, as newer documents write them", async () => { + const old = structuredClone(swagger); + old.basePath = "/api/v2"; + old.paths = Object.fromEntries( + Object.entries(old.paths).map(([route, item]) => [route.replace(/^\/api\/v2/, ""), item]), + ); + const { reference } = await applyOpenApiReference(source, old); + assert.deepEqual(reference.operations["reference/api/users/get-user-by-name"], { + method: "get", + path: "/api/v2/users/{user}", + }); + assert.ok(Object.keys(reference.document.paths as object).every((p) => p.startsWith("/api/v2/"))); +}); + +test("the schemas page's rows name each schema and the operation page that shows it", async () => { + const { reference } = await applyOpenApiReference(source, swagger); + assert.equal(reference.schemas.route, "reference/api/schemas"); + const byName = new Map(reference.schemas.rows.map((row) => [row.name, row])); + assert.deepEqual(byName.get("codersdk.Workspace"), { + name: "codersdk.Workspace", + operation: { title: "List workspaces", route: "reference/api/workspaces/list-workspaces" }, + }); + assert.equal(reference.schemas.rows.length, Object.keys(swagger.definitions).length); +}); + +test("a basePath's trailing slashes are dropped, and a root basePath adds nothing", async () => { + for (const [basePath, expected] of [ + ["/api/v2//", "/api/v2/users/{user}"], + ["/", "/users/{user}"], + ] as const) { + const old = structuredClone(swagger); + old.basePath = basePath; + old.paths = Object.fromEntries( + Object.entries(old.paths).map(([route, item]) => [route.replace(/^\/api\/v2/, ""), item]), + ); + const { reference } = await applyOpenApiReference(source, old); + assert.equal(reference.operations["reference/api/users/get-user-by-name"]?.path, expected); + } +}); + +test("section ids follow the ids the landing page renders, not its heading source", async () => { + const { reference } = await applyOpenApiReference( + withLanding("# REST API\n\n### _Users_\n\n ## <kbd>Workspaces</kbd>\n"), + swagger, + ); + assert.equal(reference.landing.setupId, "set-up-your-environment"); + assert.equal(reference.landing.sections[0]?.id, "users-1"); + assert.equal(reference.landing.sections[1]?.id, "workspaces-1"); +}); diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts new file mode 100644 index 00000000..067a1161 --- /dev/null +++ b/packages/docs-build/src/openapi-reference.ts @@ -0,0 +1,506 @@ +import { + API_REFERENCE_DIR, + assertInDocumentRefs, + collectRefs, + DEPLOYMENT_URL_ENV, + type DocFile, + type DocSource, + HTTP_METHODS, + type HttpMethod, + isObject, + type JsonObject, + type ManifestNode, + type OpenApiLandingSection, + type OpenApiOperationRef, + type OpenApiPagesData, + SESSION_TOKEN_ENV, +} from "@coder/docs-config"; +import { + buildDirRoutes, + extractTitle, + headingIds, + mapMdPath, + parseFrontmatter, + safeHeadingId, +} from "@coder/docs-transforms"; +import GithubSlugger, { slug as slugify } from "github-slugger"; +import { validate } from "oas-validator"; +import { convertObj } from "swagger2openapi"; + +/** + * The REST API reference built from coder/coder's Swagger 2.0 document: the + * data the page renderer reads, and what the conversion warned about. + */ +export interface OpenApiReference extends OpenApiPagesData { + warnings: string[]; +} + +export interface ApplyOpenApiReferenceOptions { + /** The docs-relative directory of the generated reference; defaults to `reference/api`. */ + dir?: string; + /** The server URL template of the document, which an operation page shows with its path. */ + server?: { url: string; variables?: Record<string, { default: string; description?: string }> }; +} + +const UNNAMEABLE = "has no characters to name its page by"; + +export const tagSlug = (tag: string): string => tag.toLowerCase().replace(/[^a-z0-9]/g, ""); + +// Summaries are plain text: escape what Markdown would read as link, table, or emphasis syntax. +const linkText = (text: string): string => + text + .replace(/[\\`*_[\]<>|]/g, (char) => `\\${char}`) + .replace(/\s+/g, " ") + .trim(); + +/** `text` as one Markdown code span, fenced by a backtick run longer than any inside it. */ +function codeSpan(text: string): string { + const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length)); + const fence = "`".repeat(longest + 1); + const pad = /^[`\s]|[`\s]$/.test(text) ? " " : ""; + return `${fence}${pad}${text}${pad}${fence}`; +} + +const cell = (markdown: string): string => markdown.replace(/\|/g, "\\|"); + +const frontmatter = (title: string, method?: string): string => + `---\ntitle: ${JSON.stringify(title)}\n${method ? `_openapi:\n method: ${method}\n` : ""}---\n\n`; + +const SCHEMA_REF = "#/components/schemas/"; + +/** Each schema an operation reaches, with how many `$ref` hops away it is. */ +function schemaDepths(roots: unknown, schemas: JsonObject): Map<string, number> { + const depths = new Map<string, number>(); + let frontier = new Set<string>(); + collectRefs(roots, frontier); + for (let depth = 0; frontier.size > 0; depth++) { + const next = new Set<string>(); + for (const ref of frontier) { + if (!ref.startsWith(SCHEMA_REF)) continue; + const name = ref.slice(SCHEMA_REF.length); + if (depths.has(name)) continue; + depths.set(name, depth); + collectRefs(schemas[name], next); + } + frontier = next; + } + return depths; +} + +/** Older coder/coder documents give `/api/v2` as `basePath`; the samples and pages need it in each path. */ +function withBasePathInPaths(swagger: unknown): unknown { + if (!isObject(swagger) || typeof swagger.basePath !== "string" || !isObject(swagger.paths)) { + return swagger; + } + let base = swagger.basePath; + while (base.endsWith("/")) base = base.slice(0, -1); + const { basePath: _, ...rest } = swagger; + return { + ...rest, + paths: Object.fromEntries( + Object.entries(swagger.paths).map(([route, item]) => [`${base}${route}`, item]), + ), + }; +} + +/** Schemes coderd authenticates with but its Swagger document never declares, as `httpmw` reads them. */ +const UNDECLARED_SCHEMES: Record<string, JsonObject> = { + CoderProvisionerKey: { type: "apiKey", in: "header", name: "Coder-Provisioner-Daemon-Key" }, +}; + +/** Converts Swagger 2.0 to OpenAPI 3, repairs the defects that make it invalid, and validates it. */ +export async function convertSwagger( + swagger: unknown, +): Promise<{ document: JsonObject; warnings: string[] }> { + const warnings: string[] = []; + assertInDocumentRefs(swagger, "swagger.json"); + const converted = await convertObj(withBasePathInPaths(swagger), { + patch: true, + warnOnly: true, + resolve: false, + resolveInternal: false, + }); + const document = converted.openapi; + if (converted.patches) warnings.push(`swagger2openapi patched ${converted.patches} defect(s)`); + for (const warning of converted.warnings ?? []) + warnings.push(`swagger2openapi: ${JSON.stringify(warning)}`); + + if (!isObject(document.components)) document.components = {}; + const components = document.components as JsonObject; + if (!isObject(components.securitySchemes)) components.securitySchemes = {}; + const schemes = components.securitySchemes as JsonObject; + for (const [route, item] of Object.entries(isObject(document.paths) ? document.paths : {})) { + if (!isObject(item)) continue; + for (const method of HTTP_METHODS) { + const operation = item[method]; + if (!isObject(operation)) continue; + if (Array.isArray(operation.security)) { + operation.security = operation.security.filter((requirement) => { + const unknown = Object.keys(isObject(requirement) ? requirement : {}).filter((name) => { + if (Object.hasOwn(schemes, name)) return false; + if (!Object.hasOwn(UNDECLARED_SCHEMES, name)) return true; + schemes[name] = UNDECLARED_SCHEMES[name]; + return false; + }); + for (const name of unknown) { + warnings.push( + `${method.toUpperCase()} ${route}: security scheme ${name} is not defined; dropped`, + ); + } + return unknown.length === 0; + }); + } + if (Array.isArray(operation.parameters)) { + operation.parameters = operation.parameters.filter((parameter) => { + if (!isObject(parameter) || parameter.in !== "path") return true; + if (route.includes(`{${String(parameter.name)}}`)) return true; + warnings.push( + `${method.toUpperCase()} ${route}: path parameter ${String(parameter.name)} is not in the path; dropped`, + ); + return false; + }); + } + } + } + + await assertConvertedDocument(document); + return { document, warnings }; +} + +/** Throws when a converted document holds a `$ref` the renderer's bundler would fetch or read, or is not valid OpenAPI. */ +export async function assertConvertedDocument(spec: JsonObject): Promise<void> { + assertInDocumentRefs(spec, "the converted OpenAPI document"); + const result = await validate(spec, { + lint: false, + prettify: false, + warnOnly: true, + resolve: false, + }); + if (!result.valid) throw new Error("the converted OpenAPI document is not valid"); +} + +/** + * Replaces the generated single-page-per-tag API reference in a version's + * `DocSource` with one page per operation, grouped by tag, rendered from the + * version's Swagger document. `reference/api/index.md` is kept. Each tag page + * becomes a list of its endpoints and the schemas page a list of schemas with + * the endpoint that uses each, so links to either still land; the old anchors + * are returned for a client-side redirect. + */ +export async function applyOpenApiReference( + source: DocSource, + swagger: unknown, + options: ApplyOpenApiReferenceOptions = {}, +): Promise<{ source: DocSource; reference: OpenApiReference }> { + const dir = options.dir ?? API_REFERENCE_DIR; + const { document, warnings } = await convertSwagger(swagger); + document.servers = [ + options.server ?? { + url: "{deployment}", + variables: { + deployment: { + default: "https://coder.example.com", + description: "The URL of your Coder deployment", + }, + }, + }, + ]; + + const paths = isObject(document.paths) ? document.paths : {}; + const components = isObject(document.components) ? document.components : {}; + const schemas = isObject(components.schemas) ? components.schemas : {}; + const tagInfo = new Map<string, string | undefined>(); + for (const tag of Array.isArray(document.tags) ? document.tags : []) { + if (isObject(tag) && typeof tag.name === "string") { + tagInfo.set(tag.name, typeof tag.description === "string" ? tag.description : undefined); + } + } + + interface Op { + method: HttpMethod; + path: string; + summary: string; + description?: string; + deprecated: boolean; + file: string; + depths: Map<string, number>; + } + const byTag = new Map<string, { slugger: GithubSlugger; ops: Op[] }>(); + for (const [route, item] of Object.entries(paths)) { + if (!isObject(item)) continue; + for (const method of HTTP_METHODS) { + const operation = item[method]; + if (!isObject(operation)) continue; + const apidocgen = operation["x-apidocgen"]; + if (isObject(apidocgen) && apidocgen.skip === true) continue; + const tag = + Array.isArray(operation.tags) && typeof operation.tags[0] === "string" + ? operation.tags[0] + : "General"; + if (!tagSlug(tag)) throw new Error(`tag ${JSON.stringify(tag)} ${UNNAMEABLE}`); + let group = byTag.get(tag); + if (!group) byTag.set(tag, (group = { slugger: new GithubSlugger(), ops: [] })); + const summary = + typeof operation.summary === "string" + ? operation.summary + : `${method.toUpperCase()} ${route}`; + const slug = group.slugger.slug(summary); + if (!slug) throw new Error(`summary ${JSON.stringify(summary)} ${UNNAMEABLE}`); + group.ops.push({ + method, + path: route, + summary, + description: typeof operation.description === "string" ? operation.description : undefined, + deprecated: operation.deprecated === true, + file: `${dir}/${tagSlug(tag)}/${slug}.md`, + depths: schemaDepths([operation, item.parameters], schemas), + }); + } + } + + const generated = new Map<string, string>(); + const put = (path: string, content: string) => { + if (generated.has(path)) throw new Error(`${path} is generated twice`); + generated.set(path, content); + }; + const tagFile = (tag: string) => `${dir}/${tagSlug(tag)}.md`; + for (const [tag, { ops }] of byTag) { + const items = ops.map( + (op) => + `- [${linkText(op.summary)}](./${op.file.slice(dir.length + 1)}): ${codeSpan(`${op.method.toUpperCase()} ${op.path}`)}`, + ); + const description = tagInfo.get(tag); + put( + tagFile(tag), + `${frontmatter(tag)}${description ? `${description}\n\n` : ""}${items.join("\n")}\n`, + ); + for (const op of ops) { + const lines = [codeSpan(`${op.method.toUpperCase()} ${op.path}`)]; + if (op.deprecated) lines.push("This endpoint is deprecated."); + if (op.description) lines.push(op.description); + put(op.file, `${frontmatter(op.summary, op.method)}${lines.join("\n\n")}\n`); + } + } + + const allOps = [...byTag.values()].flatMap((group) => group.ops); + const schemaRows: string[] = []; + const schemaTargets = new Map<string, Op>(); + const schemaSlugger = new GithubSlugger(); + const schemaAnchors: Record<string, string> = {}; + const schemaList: { name: string; op?: Op }[] = []; + for (const name of Object.keys(schemas)) { + let best: Op | undefined; + let bestDepth = Number.POSITIVE_INFINITY; + for (const op of allOps) { + const depth = op.depths.get(name); + if (depth !== undefined && depth < bestDepth) { + best = op; + bestDepth = depth; + } + } + const anchor = schemaSlugger.slug(name); + schemaList.push(best ? { name, op: best } : { name }); + if (best) { + schemaTargets.set(anchor, best); + schemaRows.push( + `| ${cell(codeSpan(name))} | [${linkText(best.summary)}](./${best.file.slice(dir.length + 1)}) |`, + ); + } else { + schemaRows.push(`| ${cell(codeSpan(name))} | Not used by a documented endpoint |`); + } + } + const schemasFile = `${dir}/schemas.md`; + put( + schemasFile, + `${frontmatter("Schemas")}Each endpoint's page documents the request and response schemas it uses. This table names, for each schema, the endpoint page that shows it most directly.\n\n| Schema | Shown on |\n| --- | --- |\n${schemaRows.join("\n")}\n`, + ); + + const landingFile = `${dir}/index.md`; + const landingSource = source.files.find((file) => file.path === landingFile); + if (!landingSource) throw new Error(`the source has no ${landingFile}`); + const landing = withSetupSection(landingSource.content); + put(landingFile, landing.content); + + const files: DocFile[] = [ + ...source.files.filter((file) => !generated.has(file.path)), + ...[...generated].map(([path, content]) => ({ path, content })), + ]; + + const manifestPath = (file: string) => `./${file}`; + const routes = structuredClone(source.manifest.routes); + const findNode = (nodes: ManifestNode[]): ManifestNode | undefined => { + for (const node of nodes) { + if (node.path === manifestPath(`${dir}/index.md`)) return node; + const found = node.children && findNode(node.children); + if (found) return found; + } + return undefined; + }; + const apiNode = findNode(routes); + if (!apiNode) throw new Error(`the manifest has no ${dir}/index.md node`); + const children = apiNode.children ?? []; + for (const [tag, { ops }] of byTag) { + const opChildren = ops.map((op) => ({ title: op.summary, path: manifestPath(op.file) })); + const existing = children.find((child) => child.path === manifestPath(tagFile(tag))); + if (existing) existing.children = opChildren; + else { + warnings.push(`tag ${tag} has no manifest entry; appended`); + children.push({ title: tag, path: manifestPath(tagFile(tag)), children: opChildren }); + } + } + apiNode.children = children; + + const mdPaths = files.map((file) => file.path).filter((path) => path.endsWith(".md")); + const dirRoutes = buildDirRoutes(mdPaths); + const routeOf = (file: string) => mapMdPath(file, dirRoutes).route; + const fileByRoute = new Map<string, string>(); + for (const path of mdPaths) { + const route = routeOf(path); + const other = fileByRoute.get(route); + if (other !== undefined && (generated.has(path) || generated.has(other))) { + throw new Error(`${path} and ${other} share the route ${route}`); + } + fileByRoute.set(route, path); + } + const operations: Record<string, OpenApiOperationRef> = {}; + const anchors: Record<string, Record<string, string>> = {}; + for (const [tag, { ops }] of byTag) { + const tagAnchors: Record<string, string> = {}; + for (const op of ops) { + const route = routeOf(op.file); + operations[route] = { method: op.method, path: op.path }; + tagAnchors[route.slice(route.lastIndexOf("/") + 1)] = route; + } + anchors[routeOf(tagFile(tag))] = tagAnchors; + } + for (const [anchor, op] of schemaTargets) schemaAnchors[anchor] = routeOf(op.file); + anchors[routeOf(schemasFile)] = schemaAnchors; + + const tagByFile = new Map([...byTag.keys()].map((tag) => [manifestPath(tagFile(tag)), tag])); + const sections: OpenApiLandingSection[] = []; + for (const child of children) { + const tag = child.path === undefined ? undefined : tagByFile.get(child.path); + const group = tag === undefined ? undefined : byTag.get(tag); + if (tag === undefined || !group) continue; + sections.push({ + title: tag, + id: landing.slugger.slug(safeHeadingId(slugify(tag))), + operations: group.ops.map((op) => { + const description = firstSentence(op.description); + return { + route: routeOf(op.file), + title: op.summary, + method: op.method, + ...(description ? { description } : {}), + }; + }), + }); + } + + return { + source: { ...source, files, manifest: { ...source.manifest, routes } }, + reference: { + document, + operations, + anchors, + landing: { route: routeOf(landingFile), setupId: landing.setupId, sections }, + schemas: { + route: routeOf(schemasFile), + rows: schemaList.map(({ name, op }) => + op ? { name, operation: { title: op.summary, route: routeOf(op.file) } } : { name }, + ), + }, + warnings, + }, + }; +} + +const SETUP_HEADING = "Set up your environment"; + +const SETUP_SECTION = `## ${SETUP_HEADING} + +The code samples on each endpoint's page read your deployment URL and a session token from two environment variables, \`${DEPLOYMENT_URL_ENV}\` and \`${SESSION_TOKEN_ENV}\`, the same ones the Coder CLI reads. + +If you are logged in with the Coder CLI v2.31.1 or later and have \`jq\` installed, set both from your login: + +\`\`\`sh +export ${DEPLOYMENT_URL_ENV}="$(coder whoami -o json | jq -r '.[0].url')" +export ${SESSION_TOKEN_ENV}="$(coder login token)" +\`\`\` + +For scripts and CI, create a long-lived token instead, with \`coder tokens create\` or under **Settings** > **Tokens** in the dashboard: + +\`\`\`sh +coder tokens create --name ci --lifetime 30d +\`\`\` + +Store the token in your secret store, and set the variables from it where the script runs: + +\`\`\`sh +export ${DEPLOYMENT_URL_ENV}="https://coder.example.com" +export ${SESSION_TOKEN_ENV}="$(cat /run/secrets/coder-token)" +\`\`\` + +Keep the token out of your shell history and out of committed files. +`; + +/** The ids the page renders for a landing source's headings, by 0-based line; the sync drops the H1, so it takes none. */ +function landingHeadingIds(content: string): Map<number, { depth: number; id: string }> { + const { endLine } = parseFrontmatter(content); + const { h1Line } = extractTitle(content, API_REFERENCE_DIR); + const body = content + .split("\n") + .map((line, index) => (index === h1Line ? "" : line)) + .slice(endLine) + .join("\n"); + return new Map( + headingIds(body).map(({ line, depth, id }) => [line + endLine, { depth, id }] as const), + ); +} + +/** + * The landing page with the environment setup section before its first + * section, and a slugger that has seen every id the rendered page will have, + * so the setup and card section ids match the page's own. + */ +function withSetupSection(content: string): { + content: string; + setupId: string; + slugger: GithubSlugger; +} { + const at = [...landingHeadingIds(content)].find(([, heading]) => heading.depth === 2)?.[0]; + const lines = content.split("\n"); + const next = + at === undefined + ? `${content.trimEnd()}\n\n${SETUP_SECTION}` + : [...lines.slice(0, at), SETUP_SECTION, ...lines.slice(at)].join("\n"); + const ids = landingHeadingIds(next); + const setupId = ids.get(at ?? `${content.trimEnd()}\n`.split("\n").length)?.id; + if (setupId === undefined) throw new Error("the landing page's setup heading has no id"); + const slugger = new GithubSlugger(); + for (const { id } of ids.values()) slugger.slug(id); + return { content: next, setupId, slugger }; +} + +/** Inline Markdown as plain text: links and images by their text, without code or emphasis markers. */ +const inlineMarkdownText = (markdown: string): string => + markdown + .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1") + .replace(/[`*]/g, "") + .replace(/\s+/g, " ") + .trim(); + +/** The first sentence of an operation's Markdown description, as plain text for its card. */ +function firstSentence(markdown: string | undefined): string | undefined { + // The link pattern below is quadratic, and only the first 200 characters are kept. + const paragraph = markdown + ?.trim() + .slice(0, 2000) + .split(/\n\s*\n/)[0]; + if (!paragraph) return undefined; + const text = inlineMarkdownText(paragraph); + const sentence = /^.*?[.!?](?=\s|$)/.exec(text)?.[0] ?? text; + if (sentence.length <= 200) return sentence || undefined; + const space = sentence.lastIndexOf(" ", 199); + return `${sentence.slice(0, space > 0 ? space : 199)}…`; +} diff --git a/packages/docs-build/src/sync.test.ts b/packages/docs-build/src/sync.test.ts index 7562cc99..4589bb24 100644 --- a/packages/docs-build/src/sync.test.ts +++ b/packages/docs-build/src/sync.test.ts @@ -1121,6 +1121,43 @@ for (const [label, value] of [ }); } +test("sync passes an operation page's _openapi method through for the sidebar badge", async () => { + const src = fixtureSource( + { + "index.md": "---\ntitle: List users\n_openapi:\n method: GET\n---\n\nBody\n", + "plain.md": "# Plain\n\nBody\n", + }, + { experiments: [] }, + ); + await syncDocSource(src, { contentDir, publicDir }); + assert.match(await read("index.md"), /^_openapi: \{"method":"get"\}$/m); + assert.doesNotMatch(await read("plain.md"), /_openapi/); +}); + +for (const [label, value] of [ + ["an unknown method", '{ method: "fetch" }'], + ["a method that is not a string", "{ method: 1 }"], + ["a key other than method", '{ method: "get", webhook: true }'], + ["not a mapping", '"get"'], +] as const) { + test(`sync rejects an _openapi that is ${label}, naming the file`, async () => { + const src = fixtureSource( + { "index.md": `---\ntitle: Home\n_openapi: ${value}\n---\n\nBody\n` }, + { experiments: [] }, + ); + await assert.rejects( + () => syncDocSource(src, { contentDir, publicDir }), + (err: unknown) => { + assert.ok(err instanceof DocSyncError); + assert.equal(err.issues.invalidOpenApi.length, 1); + assert.equal(err.issues.invalidOpenApi[0]?.source, "index.md"); + assert.match(err.message, /index\.md.*_openapi|_openapi.*index\.md/s); + return true; + }, + ); + }); +} + // The manifest is the only source of a page's state: the fixture puts it on // the manifest node, and the sync writes it as a JSON array (a valid YAML flow // sequence) so the page schema reads back exactly the manifest's list. diff --git a/packages/docs-build/src/sync.ts b/packages/docs-build/src/sync.ts index 009d7aba..bc3eb4b2 100644 --- a/packages/docs-build/src/sync.ts +++ b/packages/docs-build/src/sync.ts @@ -1,6 +1,14 @@ import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; import path from "node:path"; -import { DOC_STATE_IDS, experimentDisplayName, isCodeTitle, isDocState } from "@coder/docs-config"; +import { + DOC_STATE_IDS, + experimentDisplayName, + HTTP_METHODS, + isCodeTitle, + isDocState, + isHttpMethod, + isObject, +} from "@coder/docs-config"; import type { DocImage, DocSource, ManifestIssue } from "@coder/docs-config"; import { FrontmatterError, @@ -26,6 +34,7 @@ import { rewriteLegacyReleaseCalendar, scanHtmlContent, scanMarkdownNesting, + MAX_MARKDOWN_NESTING_DEPTH, selfCloseVoidElements, stripBadgeLines, stripDoctoc, @@ -44,14 +53,6 @@ import { reservedAssetReason, reservedRouteReason } from "./reserved-routes.js"; */ const MAX_HTML_NESTING_DEPTH = 100; -/** - * Maximum blockquote and list nesting depth allowed in one page. The real - * corpus nests a few levels; the Markdown parser takes minutes on a thousand - * and the compile overflows the stack, so deeper nesting fails here, before - * anything parses the page. - */ -const MAX_MARKDOWN_NESTING_DEPTH = 100; - /** * Maximum length of a `premium_callout` frontmatter value. It renders as a * short note above a gated section, not a place for a whole page of prose. @@ -305,6 +306,11 @@ export interface SyncIssues { * colour to render as a pill. */ invalidState: { source: string; value: string }[]; + /** + * Pages whose `_openapi` frontmatter is not `{ method }` with an HTTP + * method, the only shape the sidebar's method badge reads. + */ + invalidOpenApi: { source: string; reason: string }[]; } /** Summary returned by a successful `syncDocSource`. */ @@ -383,6 +389,7 @@ function emptyIssues(): SyncIssues { invalidPremiumCallout: [], invalidTocDepth: [], invalidState: [], + invalidOpenApi: [], }; } @@ -408,7 +415,8 @@ function hasIssues(i: SyncIssues): boolean { i.unknownExperiments.length > 0 || i.invalidPremiumCallout.length > 0 || i.invalidTocDepth.length > 0 || - i.invalidState.length > 0 + i.invalidState.length > 0 || + i.invalidOpenApi.length > 0 ); } @@ -561,6 +569,13 @@ function formatIssues(i: SyncIssues): string { .join("\n")}`, ); } + if (i.invalidOpenApi.length > 0) { + parts.push( + `${i.invalidOpenApi.length} page(s) with an invalid _openapi:\n${i.invalidOpenApi + .map((u) => ` ${u.source}: ${u.reason}`) + .join("\n")}`, + ); + } return `docs sync found ${parts.length} blocking issue group(s):\n${parts.join("\n\n")}`; } @@ -814,6 +829,7 @@ export async function syncDocSource( description: fmDescription, premiumCalloutRaw, tocDepthRaw, + openapiRaw, } = extracted; const title = route === "" && options.rootTitle !== undefined ? options.rootTitle : extractedTitle; @@ -948,6 +964,23 @@ export async function syncDocSource( } } + let openapiMethod: string | null = null; + if (openapiRaw !== undefined) { + const method = + isObject(openapiRaw) && Object.keys(openapiRaw).length === 1 + ? openapiRaw.method + : undefined; + const lower = typeof method === "string" ? method.toLowerCase() : undefined; + if (isHttpMethod(lower)) { + openapiMethod = lower; + } else { + issues.invalidOpenApi.push({ + source: rel, + reason: `_openapi must be { method } with one of ${HTTP_METHODS.join(", ")}`, + }); + } + } + // The manifest's state list, deduped in manifest order; an unknown value // is reported and (in lenient mode) dropped, so the page schema never // sees a value it cannot render. @@ -1027,6 +1060,7 @@ export async function syncDocSource( if (states.length > 0) fm.push(`state: ${JSON.stringify(states)}`); if (navTitle !== undefined) fm.push(`nav_title: ${yamlString(navTitle)}`); if (tocDepth !== null) fm.push(`toc_depth: ${tocDepth}`); + if (openapiMethod !== null) fm.push(`_openapi: ${JSON.stringify({ method: openapiMethod })}`); if (Object.keys(experimentNames).length > 0) fm.push(`experiments: ${JSON.stringify(experimentNames)}`); const out = `---\n${fm.join("\n")}\n---\n\n${body.replace(/^\n+/, "")}`; diff --git a/packages/docs-build/src/vendor.d.ts b/packages/docs-build/src/vendor.d.ts new file mode 100644 index 00000000..f2ffc6ae --- /dev/null +++ b/packages/docs-build/src/vendor.d.ts @@ -0,0 +1,13 @@ +declare module "swagger2openapi" { + export function convertObj( + swagger: unknown, + options: Record<string, unknown>, + ): Promise<{ openapi: Record<string, unknown>; patches?: number; warnings?: unknown[] }>; +} + +declare module "oas-validator" { + export function validate( + openapi: unknown, + options: Record<string, unknown>, + ): Promise<{ valid: boolean; warnings?: unknown[] }>; +} diff --git a/packages/docs-config/src/client-entry.test.ts b/packages/docs-config/src/client-entry.test.ts index 69a5c70b..07157d31 100644 --- a/packages/docs-config/src/client-entry.test.ts +++ b/packages/docs-config/src/client-entry.test.ts @@ -36,3 +36,9 @@ test("the client entry imports no package, so it never bundles zod", () => { test("the import-graph walk sees zod behind the package root", () => { assert.ok(importGraph("index.ts").packages.includes("zod")); }); + +test("the package root imports no node: module, so a webpack build of client code can read it", () => { + const { files, packages } = importGraph("index.ts"); + const builtins = packages.filter((name) => name.startsWith("node:")); + assert.deepEqual(builtins, [], `index.ts reaches ${builtins.join(", ")} via ${files.join(", ")}`); +}); diff --git a/packages/docs-config/src/client.ts b/packages/docs-config/src/client.ts index 373862ca..dc40c325 100644 --- a/packages/docs-config/src/client.ts +++ b/packages/docs-config/src/client.ts @@ -41,3 +41,25 @@ export { CODE_SERVER_PRODUCT, CODER_PRODUCT, productForUrl, ROUTED_PRODUCTS } fr export type { DocsProduct, RoutedDocsProduct } from "./products.js"; export { MDX_COMPONENT_NAMES } from "./mdx-components.js"; export type { MdxComponentName } from "./mdx-components.js"; + +export { + API_REFERENCE_DIR, + collectRefs, + DEPLOYMENT_URL_ENV, + HTTP_METHODS, + isApiReferenceSlug, + isHttpMethod, + SESSION_TOKEN_ENV, + SESSION_TOKEN_HEADER, +} from "./openapi.js"; +export type { + HttpMethod, + OpenApiLanding, + OpenApiLandingOperation, + OpenApiLandingSection, + OpenApiOperationRef, + OpenApiPagesData, + OpenApiSchemaRow, + OpenApiSchemas, +} from "./openapi.js"; +export { isObject, type JsonObject } from "./json.js"; diff --git a/packages/docs-config/src/content.ts b/packages/docs-config/src/content.ts index b53f9411..52eeceac 100644 --- a/packages/docs-config/src/content.ts +++ b/packages/docs-config/src/content.ts @@ -121,4 +121,10 @@ export interface DocSource { * when the provider was not asked for dates or has no history. */ lastModified?: ReadonlyMap<string, string>; + /** + * The version's API document (coder/coder's Swagger document), parsed, read + * from the same checkout as the docs. Absent when the provider was not asked + * for one or the version has none. + */ + apiDocument?: unknown; } diff --git a/packages/docs-config/src/index.ts b/packages/docs-config/src/index.ts index d0975bc6..e2bcb454 100644 --- a/packages/docs-config/src/index.ts +++ b/packages/docs-config/src/index.ts @@ -106,6 +106,9 @@ export { } from "./analytics.js"; export { USER_CONTENT_PREFIX } from "./user-content.js"; +export * from "./openapi.js"; +export { openApiDataDir, openApiDataFile } from "./openapi-data.js"; +export { isObject, type JsonObject } from "./json.js"; export { CODE_SERVER_PRODUCT, CODER_PRODUCT, productForUrl, ROUTED_PRODUCTS } from "./products.js"; export type { DocsProduct, RoutedDocsProduct } from "./products.js"; diff --git a/packages/docs-config/src/json.ts b/packages/docs-config/src/json.ts new file mode 100644 index 00000000..d68593a1 --- /dev/null +++ b/packages/docs-config/src/json.ts @@ -0,0 +1,6 @@ +/** A parsed JSON object. */ +export type JsonObject = Record<string, unknown>; + +/** Whether `value` is a plain object: not `null`, not an array. */ +export const isObject = (value: unknown): value is JsonObject => + typeof value === "object" && value !== null && !Array.isArray(value); diff --git a/packages/docs-config/src/openapi-data.test.ts b/packages/docs-config/src/openapi-data.test.ts new file mode 100644 index 00000000..ff9abc2d --- /dev/null +++ b/packages/docs-config/src/openapi-data.test.ts @@ -0,0 +1,16 @@ +import assert from "node:assert/strict"; +import path from "node:path"; +import { test } from "node:test"; +import { openApiDataDir, openApiDataFile } from "./openapi-data.js"; + +test("a version's data file sits in the app's generated openapi directory", () => { + const app = path.join("/srv", "app"); + assert.equal(openApiDataDir(app), path.join(app, ".generated", "openapi")); + assert.equal(openApiDataFile(app, "2.38"), path.join(app, ".generated", "openapi", "2.38.json")); +}); + +test("an id that would leave the directory is refused", () => { + for (const id of ["", "../x", "a/b", "a\\b", "."]) { + assert.throws(() => openApiDataFile("/srv/app", id), /data id/); + } +}); diff --git a/packages/docs-config/src/openapi-data.ts b/packages/docs-config/src/openapi-data.ts new file mode 100644 index 00000000..e40cbe48 --- /dev/null +++ b/packages/docs-config/src/openapi-data.ts @@ -0,0 +1,10 @@ +/** Where a sync leaves each version's REST API reference data, which the page renderer reads. */ +export const openApiDataDir = (appDir: string): string => `${appDir}/.generated/openapi`; + +const DATA_ID = /^[\w-][\w.-]*$/; + +/** The data file of one version, named by `id`: the version id, or a fixed name for a single-version export. */ +export function openApiDataFile(appDir: string, id: string): string { + if (!DATA_ID.test(id)) throw new Error(`not an API reference data id: ${JSON.stringify(id)}`); + return `${openApiDataDir(appDir)}/${id}.json`; +} diff --git a/packages/docs-config/src/openapi.test.ts b/packages/docs-config/src/openapi.test.ts new file mode 100644 index 00000000..13b4f9f5 --- /dev/null +++ b/packages/docs-config/src/openapi.test.ts @@ -0,0 +1,61 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + API_REFERENCE_DIR, + HTTP_METHODS, + assertInDocumentRefs, + collectRefs, + findExternalRef, + isApiReferenceSlug, + isHttpMethod, +} from "./openapi.js"; +import { isObject } from "./json.js"; + +test("in-document references pass", () => { + assert.equal( + findExternalRef({ a: { $ref: "#/definitions/x" }, b: [{ $ref: "#/c" }] }), + undefined, + ); +}); + +test("a URL or file reference is found by its JSON pointer", () => { + assert.equal( + findExternalRef({ + paths: { "/a/b": { get: { schema: { $ref: "https://example.com/x.json" } } } }, + }), + "/paths/~1a~1b/get/schema/$ref", + ); + assert.equal(findExternalRef({ list: [{}, { $ref: "../x.json" }] }), "/list/1/$ref"); + assert.throws( + () => assertInDocumentRefs({ $ref: "../x.json" }, "swagger.json"), + /\$ref at \/\$ref/, + ); +}); + +test("isObject accepts plain objects only", () => { + assert.equal(isObject({}), true); + assert.equal(isObject({ a: 1 }), true); + for (const value of [null, undefined, [], "x", 1, true]) assert.equal(isObject(value), false); +}); + +test("collectRefs gathers every string $ref, however deep", () => { + const refs = new Set<string>(); + collectRefs({ a: { $ref: "#/x" }, b: [{ c: { $ref: "#/y" } }, { $ref: 3 }], $ref: "#/z" }, refs); + assert.deepEqual([...refs].toSorted(), ["#/x", "#/y", "#/z"]); +}); + +test("isHttpMethod recognises an operation key", () => { + for (const method of HTTP_METHODS) assert.equal(isHttpMethod(method), true); + for (const value of ["GET", "parameters", "summary", 1, undefined]) { + assert.equal(isHttpMethod(value), false); + } +}); + +test("isApiReferenceSlug matches the reference and every page under it", () => { + assert.equal(API_REFERENCE_DIR, "reference/api"); + assert.equal(isApiReferenceSlug(["reference", "api"]), true); + assert.equal(isApiReferenceSlug(["reference", "api", "users", "get-user"]), true); + assert.equal(isApiReferenceSlug(["reference", "cli"]), false); + assert.equal(isApiReferenceSlug(["reference"]), false); + assert.equal(isApiReferenceSlug(["api", "reference"]), false); +}); diff --git a/packages/docs-config/src/openapi.ts b/packages/docs-config/src/openapi.ts new file mode 100644 index 00000000..6d259ec1 --- /dev/null +++ b/packages/docs-config/src/openapi.ts @@ -0,0 +1,133 @@ +import { isObject, type JsonObject } from "./json.js"; + +/** Adds every string `$ref` under `value` to `into`. */ +export function collectRefs(value: unknown, into: Set<string>): void { + if (Array.isArray(value)) { + for (const item of value) collectRefs(item, into); + } else if (isObject(value)) { + for (const [key, child] of Object.entries(value)) { + if (key === "$ref" && typeof child === "string") into.add(child); + else collectRefs(child, into); + } + } +} + +/** The operation keys of an OpenAPI path item, in the order the reference lists them. */ +export const HTTP_METHODS = [ + "get", + "put", + "post", + "delete", + "options", + "head", + "patch", + "trace", +] as const; + +export type HttpMethod = (typeof HTTP_METHODS)[number]; + +const HTTP_METHOD_SET: ReadonlySet<unknown> = new Set(HTTP_METHODS); + +export const isHttpMethod = (value: unknown): value is HttpMethod => HTTP_METHOD_SET.has(value); + +/** The docs-relative directory of the generated REST API reference. */ +export const API_REFERENCE_DIR = "reference/api"; + +const API_REFERENCE_SLUGS = API_REFERENCE_DIR.split("/"); + +/** Whether a page slug is the API reference's landing page or a page under it. */ +export const isApiReferenceSlug = (slugs: readonly string[]): boolean => + API_REFERENCE_SLUGS.every((segment, index) => slugs[index] === segment); + +/** The variable the code samples and the setup section read the deployment URL from. */ +export const DEPLOYMENT_URL_ENV = "CODER_URL"; +/** The variable the code samples and the setup section read the session token from. */ +export const SESSION_TOKEN_ENV = "CODER_SESSION_TOKEN"; +/** The header coderd reads a session token from. */ +export const SESSION_TOKEN_HEADER = "Coder-Session-Token"; + +/** The OpenAPI path item and method an operation page renders. */ +export interface OpenApiOperationRef { + method: HttpMethod; + path: string; +} + +/** An operation's card on the landing page. */ +export interface OpenApiLandingOperation { + route: string; + title: string; + method: HttpMethod; + description?: string; +} + +/** A tag's cards, under a heading of their own, in sidebar order. */ +export interface OpenApiLandingSection { + title: string; + id: string; + operations: OpenApiLandingOperation[]; +} + +/** The landing page: its route, its setup section's id, and its card sections. */ +export interface OpenApiLanding { + route: string; + setupId: string; + sections: OpenApiLandingSection[]; +} + +/** One row of the schemas page: a schema and the operation page that shows it most directly, if any does. */ +export interface OpenApiSchemaRow { + name: string; + operation?: { title: string; route: string }; +} + +/** The schemas page: its route and its rows. */ +export interface OpenApiSchemas { + route: string; + rows: OpenApiSchemaRow[]; +} + +/** + * One version's REST API reference data, as the sync writes it and the page + * renderer reads it: the OpenAPI 3 document, each operation page's route, the + * old single-page anchors, and the landing and schemas pages. + */ +export interface OpenApiPagesData { + document: JsonObject; + operations: Record<string, OpenApiOperationRef>; + anchors: Record<string, Record<string, string>>; + landing: OpenApiLanding; + schemas: OpenApiSchemas; +} + +const escapePointer = (key: string) => key.replace(/~/g, "~0").replace(/\//g, "~1"); + +/** + * The JSON pointer of the first `$ref` that is not an in-document reference + * (`#/...`), or `undefined` when there is none. An OpenAPI bundler fetches or + * reads any other reference at build time, so an API document has to be + * rejected before it reaches one. + */ +export function findExternalRef(value: unknown, pointer = ""): string | undefined { + if (Array.isArray(value)) { + for (const [index, item] of value.entries()) { + const found = findExternalRef(item, `${pointer}/${index}`); + if (found !== undefined) return found; + } + } else if (isObject(value)) { + for (const [key, child] of Object.entries(value)) { + const at = `${pointer}/${escapePointer(key)}`; + if (key === "$ref" && (typeof child !== "string" || !child.startsWith("#/"))) return at; + const found = findExternalRef(child, at); + if (found !== undefined) return found; + } + } + return undefined; +} + +/** Throws, naming the JSON pointer, when the document holds a `$ref` that is not `#/...`. */ +export function assertInDocumentRefs(document: unknown, label: string): void { + const pointer = findExternalRef(document); + if (pointer !== undefined) { + throw new Error(`${label}: $ref at ${pointer || "/"} is not an in-document reference (#/...)`); + } +} diff --git a/packages/docs-manifest/src/version-segment.test.ts b/packages/docs-manifest/src/version-segment.test.ts index 1e2580cc..78a96c9a 100644 --- a/packages/docs-manifest/src/version-segment.test.ts +++ b/packages/docs-manifest/src/version-segment.test.ts @@ -5,6 +5,7 @@ import { parseManifestItems } from "./items.js"; import { CANONICAL_LAYOUT, compareVersionIdsDesc, + isLineAtLeast, isSupportStatus, isVersionShapedSegment, oldFormsServed, @@ -163,3 +164,21 @@ test("a segment that only resembles a version parses to null", () => { assert.equal(parseVersionSegment(segment, manifest), null, JSON.stringify(segment)); } }); + +test("isLineAtLeast compares a line or tag's minor line with a floor line, and main is newest", () => { + assert.equal(isLineAtLeast("2.24", "2.24"), true); + assert.equal(isLineAtLeast("2.38", "2.24"), true); + assert.equal(isLineAtLeast("2.39", "2.24"), true); + assert.equal(isLineAtLeast("2.24.3", "2.24"), true); + assert.equal(isLineAtLeast("2.23", "2.24"), false); + assert.equal(isLineAtLeast("2.23.9", "2.24"), false); + assert.equal(isLineAtLeast("2.9", "2.24"), false, "minors compare as numbers, not text"); + assert.equal(isLineAtLeast("3.0", "2.24"), true); + assert.equal(isLineAtLeast("main", "2.24"), true); + assert.equal(isLineAtLeast("10.0", "2.24"), true); + assert.equal(isLineAtLeast("2.100.1", "2.24"), true); + assert.equal(isLineAtLeast("0.1", "0.2"), false); + assert.equal(isLineAtLeast("0.2", "0.2"), true); + assert.throws(() => isLineAtLeast("2.24", "main"), /not a line id/); + assert.throws(() => isLineAtLeast("v2.24", "2.24"), /not a version id/); +}); diff --git a/packages/docs-manifest/src/version-segment.ts b/packages/docs-manifest/src/version-segment.ts index acfe8a37..c5e1672d 100644 --- a/packages/docs-manifest/src/version-segment.ts +++ b/packages/docs-manifest/src/version-segment.ts @@ -85,6 +85,13 @@ export function versionKind(id: string): VersionKind { throw new Error(`not a version id: ${JSON.stringify(id)}`); } +/** Whether a version is on the `floor` line or a newer one: a line or tag by its minor line, and main as the newest. */ +export function isLineAtLeast(id: string, floor: string): boolean { + if (!LINE_ID_PATTERN.test(floor)) throw new Error(`not a line id: ${JSON.stringify(floor)}`); + if (versionKind(id) === "dev") return true; + return compareVersionIdsDesc(id.split(".").slice(0, 2).join("."), floor) <= 0; +} + /** The canonical first segment: `v2.38` for a line, `@v2.38.1` for a tag, `@main` for main. */ export function versionSegment(id: string): string { const kind = versionKind(id); diff --git a/packages/docs-next/package.json b/packages/docs-next/package.json index 97bc34df..cec8f1ab 100644 --- a/packages/docs-next/package.json +++ b/packages/docs-next/package.json @@ -19,6 +19,18 @@ "./semantic-search": { "types": "./dist/semantic-search.d.ts", "default": "./dist/semantic-search.js" + }, + "./openapi": { + "types": "./dist/openapi/index.d.ts", + "default": "./dist/openapi/index.js" + }, + "./openapi/code-samples": { + "types": "./dist/openapi/code-samples.d.ts", + "default": "./dist/openapi/code-samples.js" + }, + "./next-config": { + "types": "./dist/next-config.d.ts", + "default": "./dist/next-config.js" } }, "files": [ @@ -34,9 +46,14 @@ "@coder/docs-config": "workspace:*", "@coder/docs-manifest": "workspace:*", "@coder/docs-ui": "workspace:*", + "@fumadocs/json-schema": "0.3.5", + "@scalar/json-magic": "0.18.0", + "es-module-lexer": "1.7.0", "fumadocs-core": "catalog:", + "fumadocs-openapi": "12.6.1", "fumadocs-ui": "catalog:", - "lucide-react": "1.46.0" + "lucide-react": "1.73.0", + "shiki": "4.6.0" }, "peerDependencies": { "next": ">=16", @@ -48,10 +65,10 @@ "@mdx-js/mdx": "3.1.1", "@radix-ui/react-tabs": "catalog:", "@types/mdx": "2.0.14", - "fumadocs-mdx": "catalog:", "@types/node": "^24", "@types/react": "catalog:", "@types/react-dom": "catalog:", + "fumadocs-mdx": "catalog:", "jsdom": "25.0.1", "next": "catalog:", "react": "catalog:", diff --git a/packages/docs-next/src/index.ts b/packages/docs-next/src/index.ts index 29a091a4..546233f9 100644 --- a/packages/docs-next/src/index.ts +++ b/packages/docs-next/src/index.ts @@ -99,7 +99,7 @@ export type { PageTocOptions } from "./toc.js"; export { coderFaviconIcons, coderFaviconIconsFor } from "./favicons.js"; export { screenshotBackdropStyle } from "./screenshot-backdrop.js"; export type { ScreenshotBackdropStyle } from "./screenshot-backdrop.js"; -export type { DocsSource } from "./types.js"; +export type { DocsSource, RenderBody, RenderBodyContext } from "./types.js"; export { createVersionedDocs } from "./versioned.js"; export type { DocsRenderMode, VersionedDocsOptions } from "./versioned.js"; export { diff --git a/packages/docs-next/src/llms.ts b/packages/docs-next/src/llms.ts index f8b1ff40..a2a07b9c 100644 --- a/packages/docs-next/src/llms.ts +++ b/packages/docs-next/src/llms.ts @@ -13,7 +13,7 @@ * untrusted, so nothing may render them as HTML; refer to the "Security: the * corpus is untrusted" section of `packages/docs-transforms/README.md`. */ -import { normalizeBasePath } from "./version-routing.js"; +import { normalizeBasePath, pageHref } from "./version-routing.js"; /** * The staging directory the twin routes generate into. A Next route segment @@ -149,16 +149,6 @@ function linkText(text: string): string { return oneLine(text).replace(/\\/g, "\\\\").replace(/]/g, "\\]"); } -/** - * A page's link as the export actually serves it. Both exports are built - * `trailingSlash: true` and the router redirects a bare page path, so the - * loader's own URL would cost every reader of this file one 308 per line. - */ -function pageHref(base: string, url: string): string { - const href = `${base}${url}`; - return href.endsWith("/") ? href : `${href}/`; -} - /** * A version's `llms.txt`, in the llmstxt.org shape: the version's heading, a * one-line description, and a `## Pages` list of every page with its diff --git a/packages/docs-next/src/next-config.test.ts b/packages/docs-next/src/next-config.test.ts new file mode 100644 index 00000000..2557a841 --- /dev/null +++ b/packages/docs-next/src/next-config.test.ts @@ -0,0 +1,54 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import type { NextConfig } from "next"; +import { withoutOpenApiPlayground } from "./next-config.js"; +import { OPENAPI_PLAYGROUND_MODULE } from "./openapi/playground-stubs.js"; + +const LOADER = /[\\/]openapi[\\/]playground-stub-loader\.js$/; + +test("adds a Turbopack rule that runs the stub loader on the playground modules", () => { + const rules = withoutOpenApiPlayground({}).turbopack?.rules ?? {}; + assert.deepEqual(Object.keys(rules), ["*.js"]); + const rule = rules["*.js"]; + assert.ok(rule && !Array.isArray(rule)); + assert.deepEqual(rule.condition, { path: OPENAPI_PLAYGROUND_MODULE }); + assert.equal(rule.loaders?.length, 1); + assert.match(String(rule.loaders?.[0]), LOADER); +}); + +test("keeps the config's own Turbopack rules and options", () => { + const mdx = { loaders: ["mdx-loader"], as: "*.js" }; + const own = { condition: { path: /own/ }, loaders: ["own-loader"] }; + const config: NextConfig = { + trailingSlash: true, + turbopack: { resolveAlias: { a: "b" }, rules: { "*.mdx": mdx, "*.js": own } }, + }; + const out = withoutOpenApiPlayground(config); + assert.equal(out.trailingSlash, true); + assert.deepEqual(out.turbopack?.resolveAlias, { a: "b" }); + assert.equal(out.turbopack?.rules?.["*.mdx"], mdx); + const js = out.turbopack?.rules?.["*.js"]; + assert.ok(Array.isArray(js)); + assert.equal(js[0], own); + assert.equal(js.length, 2); +}); + +test("adds the same loader to webpack after the config's own webpack function", () => { + const calls: string[] = []; + const out = withoutOpenApiPlayground({ + webpack: (config: { module: { rules: unknown[] } }) => { + calls.push("own"); + config.module.rules.push("own-rule"); + return config; + }, + }); + const webpackConfig = { module: { rules: [] as unknown[] } }; + const result = out.webpack?.(webpackConfig, Object.create(null)); + assert.deepEqual(calls, ["own"]); + assert.equal(result, webpackConfig); + assert.equal(webpackConfig.module.rules[0], "own-rule"); + const added = webpackConfig.module.rules[1]; + assert.ok(added && typeof added === "object" && "test" in added && "use" in added); + assert.equal(added.test, OPENAPI_PLAYGROUND_MODULE); + assert.match(JSON.stringify(added.use), /playground-stub-loader\.js/); +}); diff --git a/packages/docs-next/src/next-config.ts b/packages/docs-next/src/next-config.ts new file mode 100644 index 00000000..8c1725e0 --- /dev/null +++ b/packages/docs-next/src/next-config.ts @@ -0,0 +1,33 @@ +import { fileURLToPath } from "node:url"; +import type { NextConfig } from "next"; +import { OPENAPI_PLAYGROUND_MODULE } from "./openapi/playground-stubs.js"; + +export { OPENAPI_PLAYGROUND_MARKERS } from "./openapi/playground-stubs.js"; + +const LOADER = fileURLToPath(new URL("./openapi/playground-stub-loader.js", import.meta.url)); + +interface WebpackConfig { + module: { rules: unknown[] }; +} + +/** + * `config` with fumadocs-openapi's API playground, OAuth flows, fetcher and + * proxy replaced by inert stubs in every Turbopack and webpack bundle, so none + * of their code is in the build. An app opts in by wrapping its config. + */ +export function withoutOpenApiPlayground(config: NextConfig): NextConfig { + const rule = { condition: { path: OPENAPI_PLAYGROUND_MODULE }, loaders: [LOADER] }; + const rules = { ...config.turbopack?.rules }; + const own = rules["*.js"]; + rules["*.js"] = own === undefined ? rule : [...(Array.isArray(own) ? own : [own]), rule]; + const ownWebpack = config.webpack; + return { + ...config, + turbopack: { ...config.turbopack, rules }, + webpack(webpackConfig: WebpackConfig, context) { + const out: WebpackConfig = ownWebpack ? ownWebpack(webpackConfig, context) : webpackConfig; + out.module.rules.push({ test: OPENAPI_PLAYGROUND_MODULE, use: [{ loader: LOADER }] }); + return out; + }, + }; +} diff --git a/packages/docs-next/src/open-graph.ts b/packages/docs-next/src/open-graph.ts index 1aef7536..87329588 100644 --- a/packages/docs-next/src/open-graph.ts +++ b/packages/docs-next/src/open-graph.ts @@ -14,6 +14,7 @@ */ import { stripCodeTitle } from "@coder/docs-config"; import type { Metadata } from "next"; +import { pageHref } from "./version-routing.js"; /** * The header line the generator prints above the title. @@ -213,7 +214,5 @@ function pageUrl( siteUrl: string | undefined, segments: readonly string[] = [], ): string | undefined { - if (!siteUrl) return undefined; - const href = `${siteUrl}/${segments.join("/")}`; - return href.endsWith("/") ? href : `${href}/`; + return siteUrl ? pageHref(siteUrl, `/${segments.join("/")}`) : undefined; } diff --git a/packages/docs-next/src/openapi/anchor-redirect.test.tsx b/packages/docs-next/src/openapi/anchor-redirect.test.tsx new file mode 100644 index 00000000..5f2feade --- /dev/null +++ b/packages/docs-next/src/openapi/anchor-redirect.test.tsx @@ -0,0 +1,67 @@ +import assert from "node:assert/strict"; +import test, { type TestContext } from "node:test"; +import type { ReactNode } from "react"; +import { mountClient, typeInto } from "../../test/dom.js"; +import { AnchorRedirect } from "./anchor-redirect.js"; +import { SchemaTables } from "./schemas.js"; + +const PAGE = "/reference/api/schemas/"; +// A same-page target, so jsdom follows the redirect as a fragment navigation. +const TARGET = `${PAGE}#redirected`; +const targets = { codersdkuser: TARGET }; + +function mount(t: TestContext, url: string, node: ReactNode): Promise<HTMLElement> { + window.history.replaceState(null, "", url); + return mountClient(t, node); +} + +// jsdom reports a navigation away from the document, which it doesn't implement, through console.error. +function navigationsAway(t: TestContext) { + const error = t.mock.method(console, "error", () => {}); + return () => + error.mock.calls.filter((call) => String(call.arguments[0]).includes("navigation")).length; +} + +test("a hash that arrives after the page loaded, with a filter typed, still redirects", async (t) => { + const container = await mount( + t, + PAGE, + <> + <SchemaTables + rows={[{ name: "codersdk.User" }, { name: "agentsdk.Manifest" }]} + hrefFor={() => undefined} + /> + <AnchorRedirect targets={targets} /> + </>, + ); + const input = container.querySelector("input"); + assert.ok(input); + await typeInto(input, "user"); + assert.equal(container.querySelector('[aria-live="polite"]')?.textContent, "1 of 2 schemas"); + assert.equal(window.location.hash, ""); + window.location.hash = "codersdkuser"; + window.dispatchEvent(new HashChangeEvent("hashchange")); + assert.equal(window.location.hash, "#redirected"); +}); + +test("a malformed hash such as #% is ignored instead of taking the page down", async (t) => { + const container = await mount( + t, + `${PAGE}#%`, + <> + <p data-still-here>Schemas</p> + <AnchorRedirect targets={targets} /> + </>, + ); + assert.ok(container.querySelector("[data-still-here]")); + assert.equal(window.location.hash, "#%"); +}); + +test("an inherited key such as #constructor is not a target", async (t) => { + const navigations = navigationsAway(t); + await mount(t, `${PAGE}#constructor`, <AnchorRedirect targets={targets} />); + window.location.hash = "toString"; + window.dispatchEvent(new HashChangeEvent("hashchange")); + assert.equal(navigations(), 0); + assert.equal(window.location.pathname, PAGE); +}); diff --git a/packages/docs-next/src/openapi/anchor-redirect.tsx b/packages/docs-next/src/openapi/anchor-redirect.tsx new file mode 100644 index 00000000..2aa005bd --- /dev/null +++ b/packages/docs-next/src/openapi/anchor-redirect.tsx @@ -0,0 +1,23 @@ +"use client"; + +import { useEffect } from "react"; + +/** Sends a link to an anchor of the old single-page reference on to the page that replaced it, on load or when the hash changes. */ +export function AnchorRedirect({ targets }: { targets: Record<string, string> }) { + useEffect(() => { + const follow = () => { + let anchor: string; + try { + anchor = decodeURIComponent(window.location.hash.slice(1)); + } catch { + return; + } + const target = Object.hasOwn(targets, anchor) ? targets[anchor] : undefined; + if (target) window.location.replace(target); + }; + follow(); + window.addEventListener("hashchange", follow); + return () => window.removeEventListener("hashchange", follow); + }, [targets]); + return null; +} diff --git a/packages/docs-next/src/openapi/api-page-lazy.tsx b/packages/docs-next/src/openapi/api-page-lazy.tsx new file mode 100644 index 00000000..02d3b29b --- /dev/null +++ b/packages/docs-next/src/openapi/api-page-lazy.tsx @@ -0,0 +1,6 @@ +"use client"; + +import dynamic from "next/dynamic"; + +// Its own chunk, so only the pages that render an operation load fumadocs-openapi. +export const ApiPage = dynamic(() => import("./api-page.js").then((module) => module.ApiPage)); diff --git a/packages/docs-next/src/openapi/api-page.test.tsx b/packages/docs-next/src/openapi/api-page.test.tsx new file mode 100644 index 00000000..ae1d88f0 --- /dev/null +++ b/packages/docs-next/src/openapi/api-page.test.tsx @@ -0,0 +1,134 @@ +import assert from "node:assert/strict"; +import test, { type TestContext } from "node:test"; +import { FrameworkProvider } from "fumadocs-core/framework"; +import type { Document } from "fumadocs-openapi"; +import { act } from "react"; +import { mountClient } from "../../test/dom.js"; +import { ApiPage } from "./api-page.js"; +import { withCodeSamples } from "./code-samples.js"; + +const STORED_SERVER = "coder-api-server-url"; + +const document_ = withCodeSamples( + { + openapi: "3.0.3", + info: { title: "Coder API", version: "2.0" }, + servers: [ + { + url: "{deployment}", + variables: { deployment: { default: "https://coder.example.com" } }, + }, + ], + paths: { + "/api/v2/buildinfo": { + get: { summary: "Build info", responses: { "200": { description: "OK" } } }, + }, + }, + components: {}, + }, + "/api/v2/buildinfo", + "get", +); + +async function renderPage( + t: TestContext, + bundled: Record<string, unknown> = document_, + path = "/api/v2/buildinfo", + method: "get" | "post" = "get", +): Promise<HTMLElement> { + const container = await mountClient( + t, + <FrameworkProvider + usePathname={() => "/"} + useParams={() => ({})} + useRouter={() => ({ push() {}, refresh() {} })} + > + <ApiPage + document="coder" + showTitle={false} + operations={[{ path, method }]} + payload={{ bundled: bundled as Document }} + /> + </FrameworkProvider>, + ); + await act(async () => new Promise((resolve) => setTimeout(resolve, 50))); + return container; +} + +for (const [label, deployment] of [ + ["a leading space and a trailing dot", " http://localhost:3142."], + ["not a URL at all", "not a url"], +] as const) { + test(`a stored server URL that is ${label} still renders the samples`, async (t) => { + localStorage.setItem( + STORED_SERVER, + JSON.stringify({ url: "{deployment}", variables: { deployment } }), + ); + const errors: unknown[] = []; + const onError = (event: ErrorEvent) => errors.push(event.error); + window.addEventListener("error", onError); + try { + const container = await renderPage(t); + assert.deepEqual(errors, []); + const tabs = [...container.querySelectorAll('[role="tab"]')].map((tab) => tab.textContent); + for (const name of ["cURL", "JavaScript", "Python", "Go"]) + assert.ok(tabs.includes(name), name); + assert.match(container.textContent ?? "", / -X GET \\\n\t"\$CODER_URL\/api\/v2\/buildinfo"/); + } finally { + window.removeEventListener("error", onError); + localStorage.clear(); + } + }); +} + +const json = (examples: Record<string, unknown>) => ({ + "application/json": { + examples: Object.fromEntries( + Object.entries(examples).map(([name, value]) => [name, { summary: name, value }]), + ), + }, +}); + +const choices = withCodeSamples( + { + openapi: "3.0.3", + info: { title: "Coder API", version: "2.0" }, + paths: { + "/api/v2/templates": { + post: { + summary: "Create template", + requestBody: { + content: json({ Minimal: { name: "a" }, Full: { name: "a", icon: "b" } }), + }, + responses: { + "201": { description: "Created", content: json({ New: { id: 1 }, Copied: { id: 2 } }) }, + "409": { description: "Conflict", content: json({ Taken: { message: "taken" } }) }, + }, + }, + }, + }, + components: {}, + }, + "/api/v2/templates", + "post", +); + +test("every select in the example column has a name, and each code region is named by its tab", async (t) => { + const container = await renderPage(t, choices, "/api/v2/templates", "post"); + const selects = [...container.querySelectorAll('[role="combobox"]')]; + // Each name against the value its select shows, so a reshuffled DOM can't swap two names unnoticed. + assert.deepEqual( + selects.map((select) => [select.getAttribute("aria-label"), select.textContent]), + [ + ["Example request", "Minimal"], + ["Response status", "201"], + ["Example", "New"], + ], + ); + const regions = [...container.querySelectorAll('.coder-sample-tabs [role="region"]')]; + assert.deepEqual( + regions.map((region) => region.getAttribute("aria-label")), + ["cURL sample", "JavaScript sample", "Python sample", "Go sample"].slice(0, regions.length), + ); + assert.ok(regions.length > 0); +}); diff --git a/packages/docs-next/src/openapi/api-page.tsx b/packages/docs-next/src/openapi/api-page.tsx new file mode 100644 index 00000000..d50f0b93 --- /dev/null +++ b/packages/docs-next/src/openapi/api-page.tsx @@ -0,0 +1,136 @@ +"use client"; + +import { createShikiFactory } from "fumadocs-core/highlight/shiki"; +import type { CodeBlockProps } from "fumadocs-openapi"; +import { useOperation } from "fumadocs-openapi/operation"; +import { createCodeUsageGeneratorRegistry } from "fumadocs-openapi/requests/generators"; +import { createOpenAPIPageBase } from "fumadocs-openapi/ui/base"; +import { DynamicCodeBlock } from "fumadocs-ui/components/dynamic-codeblock.core"; +import { Tab, Tabs } from "fumadocs-ui/components/tabs"; +import type { ComponentProps } from "react"; +import { SamplesNote } from "./samples-note.js"; + +// Only the grammars and themes an API page uses (JSON, the code samples, TypeScript definitions), on the JavaScript regex engine (no WASM, no eval). +const shiki = createShikiFactory({ + async init() { + const [{ createHighlighterCore }, { createJavaScriptRegexEngine }] = await Promise.all([ + import("shiki/core"), + import("shiki/engine/javascript"), + ]); + return createHighlighterCore({ + engine: createJavaScriptRegexEngine(), + langs: [ + import("shiki/langs/json.mjs"), + import("shiki/langs/shellscript.mjs"), + import("shiki/langs/typescript.mjs"), + import("shiki/langs/javascript.mjs"), + import("shiki/langs/python.mjs"), + import("shiki/langs/go.mjs"), + ], + themes: [ + import("shiki/themes/github-light-high-contrast.mjs"), + import("shiki/themes/github-dark-default.mjs"), + ], + }); + }, +}); + +const shikiOptions = { + themes: { light: "github-light-high-contrast", dark: "github-dark-default" }, +} as const; + +// fumadocs-openapi's default code block leaves its scroll region unnamed, so every block on a page is the same landmark. +function CodeBlock({ name, ...props }: CodeBlockProps & { name?: string }) { + return ( + <DynamicCodeBlock + highlighter={() => shiki.getOrInit()} + options={shikiOptions} + {...props} + codeblock={{ + ...props.codeblock, + viewportProps: { + ...props.codeblock?.viewportProps, + "aria-label": name ?? `${props.lang} code`, + }, + }} + /> + ); +} + +// One tab per language, where fumadocs-openapi's default is a select in the code block's header. +// The samples are the server-built text as is, never run through fumadocs-openapi's generators, which resolve the reader's stored server URL. +function SampleTabs() { + const samples = (useOperation().operation["x-codeSamples"] ?? []).flatMap((sample) => + typeof sample.source === "string" + ? [ + { + id: sample.id ?? sample.lang, + lang: sample.lang, + label: sample.label ?? sample.lang, + source: sample.source, + }, + ] + : [], + ); + if (samples.length === 0) return null; + return ( + <Tabs + groupId="coder-api-sample" + items={samples.map((sample) => sample.label)} + className="coder-sample-tabs mb-4" + > + {samples.map((sample) => ( + <Tab key={sample.id} value={sample.label}> + <CodeBlock lang={sample.lang} code={sample.source} name={`${sample.label} sample`} /> + </Tab> + ))} + </Tabs> + ); +} + +const STORAGE_KEY_PREFIX = "coder-api-"; + +const OpenApiPage = createOpenAPIPageBase({ + shiki, + shikiOptions, + components: { CodeBlock }, + // Never rendered; withoutOpenApiPlayground in each app's Next config also keeps its code out of the build. + playground: { enabled: false }, + // Empty, or fumadocs-openapi adds its own generators beside the operation's x-codeSamples. + codeUsages: createCodeUsageGeneratorRegistry(), + storageKeyPrefix: STORAGE_KEY_PREFIX, + content: { + renderAPIExampleUsageTabs: () => <SampleTabs />, + // fumadocs-openapi 12.5.4's operation layout (ui/operation/index.js), with the example column half the width, between 400px and 640px, instead of a fixed 400px. + renderOperationLayout: (slots) => ( + <div className="flex flex-col gap-x-6 gap-y-4 @4xl:flex-row @4xl:items-start"> + <div className="min-w-0 flex-1"> + {slots.header} + {slots.apiPlayground} + {slots.description} + {slots.authSchemes} + {slots.parameters} + {slots.body} + {slots.responses} + {slots.callbacks} + </div> + <div className="@4xl:sticky @4xl:top-[calc(var(--fd-docs-row-3,0px)+1rem)] @4xl:flex @4xl:max-h-[calc(var(--fd-docs-height,100dvh)-var(--fd-docs-row-3,0px)-2rem)] @4xl:w-[clamp(400px,50%,640px)] @4xl:shrink-0 @4xl:flex-col"> + {slots.apiExample} + </div> + </div> + ), + renderAPIExampleLayout: ({ selector, usageTabs, responseTabs }) => ( + <div className="flex min-h-0 flex-col prose-no-margin"> + {selector} + <SamplesNote /> + {usageTabs} + {responseTabs} + </div> + ), + }, +}); + +/** One REST API operation, rendered by fumadocs-openapi from the document its page was given, with the server-built code samples. */ +export function ApiPage(props: ComponentProps<typeof OpenApiPage>) { + return <OpenApiPage {...props} />; +} diff --git a/packages/docs-next/src/openapi/code-samples.test.ts b/packages/docs-next/src/openapi/code-samples.test.ts new file mode 100644 index 00000000..3b0acab6 --- /dev/null +++ b/packages/docs-next/src/openapi/code-samples.test.ts @@ -0,0 +1,704 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import test from "node:test"; +import { SAMPLE_LINE_WIDTH, codeSamples, withCodeSamples } from "./code-samples.js"; + +const document = { + openapi: "3.0.3", + info: { title: "Coder API", version: "2.0" }, + paths: { + "/api/v2/users/{user}": { + get: { + security: [{ CoderSessionToken: [] }], + parameters: [ + { name: "user", in: "path", required: true, schema: { type: "string" } }, + { name: "q", in: "query", required: false, schema: { type: "string" } }, + { name: "limit", in: "query", required: true, schema: { type: "integer" } }, + ], + responses: { "200": { description: "OK" } }, + }, + }, + "/api/v2/users": { + post: { + security: [{ CoderSessionToken: [] }], + requestBody: { + required: true, + content: { + "application/json": { schema: { $ref: "#/components/schemas/CreateUser" } }, + }, + }, + responses: { "201": { description: "Created" } }, + }, + }, + "/api/v2/buildinfo": { + get: { responses: { "200": { description: "OK" } } }, + }, + "/scim/v2/Users": { + get: { security: [{ Authorization: [] }], responses: { "200": { description: "OK" } } }, + }, + }, + components: { + securitySchemes: { + CoderSessionToken: { type: "apiKey", name: "Coder-Session-Token", in: "header" }, + Authorization: { type: "apiKey", name: "Authorization", in: "header" }, + }, + schemas: { + CreateUser: { + type: "object", + required: ["email", "username"], + properties: { + email: { type: "string", format: "email" }, + username: { type: "string" }, + name: { type: "string" }, + note: { type: "string", default: "it's" }, + }, + }, + }, + }, +}; + +const sample = (doc: Record<string, unknown>, path: string, method: string, id: string): string => { + const found = codeSamples(doc, path, method).find((item) => item.id === id); + if (!found) throw new Error(`no ${id} sample`); + return found.source; +}; + +const ENV = { CODER_URL: "https://coder.test", CODER_SESSION_TOKEN: "s3cret" }; + +/** The arguments the shell passes to curl when it runs the sample. */ +function curlArgs(source: string): string[] { + const stub = `curl() { for arg; do printf '%s\\0' "$arg"; done; }\n`; + const out = execFileSync("sh", ["-c", stub + source], { + env: { ...process.env, ...ENV }, + encoding: "utf8", + }); + return out.split("\0").slice(0, -1); +} + +interface FetchCall { + url: string; + init: { method: string; headers?: Record<string, string>; body?: unknown }; +} + +/** The `fetch` call the JavaScript sample makes, with the environment set. */ +async function fetchCall(source: string): Promise<FetchCall> { + const calls: FetchCall[] = []; + const fakeFetch = async (url: string, init: FetchCall["init"]) => { + calls.push({ url, init }); + return { status: 200, text: async () => "" }; + }; + const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor; + await new AsyncFunction("fetch", "process", "console", source)( + fakeFetch, + { env: ENV }, + { log() {} }, + ); + assert.equal(calls.length, 1); + return calls[0] as FetchCall; +} + +const tricky = { + ...document, + paths: { + "/api/v2/users": { + post: { + security: [{ CoderSessionToken: [] }], + requestBody: { + content: { + "application/json": { + example: { note: 'it\'s "q" `tick` $HOME ${x} \\ back\nline' }, + }, + }, + }, + responses: { "201": { description: "Created" } }, + }, + }, + }, +}; +const trickyNote = 'it\'s "q" `tick` $HOME ${x} \\ back\nline'; + +test("there is one sample per language, in tab order", () => { + assert.deepEqual( + codeSamples(document, "/api/v2/buildinfo", "get").map(({ id, lang, label }) => ({ + id, + lang, + label, + })), + [ + { id: "curl", lang: "bash", label: "cURL" }, + { id: "javascript", lang: "javascript", label: "JavaScript" }, + { id: "python", lang: "python", label: "Python" }, + { id: "go", lang: "go", label: "Go" }, + ], + ); +}); + +test("no sample logs in or exports anything: they read CODER_URL and CODER_SESSION_TOKEN", () => { + for (const { source } of codeSamples(document, "/api/v2/users/{user}", "get")) { + assert.doesNotMatch(source, /coder (login|whoami)|export /); + assert.match(source, /CODER_URL/); + assert.match(source, /CODER_SESSION_TOKEN/); + } +}); + +test("curl: path params stay placeholders and only required query params are added", () => { + assert.equal( + sample(document, "/api/v2/users/{user}", "get", "curl"), + [ + `curl -X GET \\`, + `\t"$CODER_URL/api/v2/users/{user}?limit={limit}" \\`, + `\t-H "Coder-Session-Token: $CODER_SESSION_TOKEN"`, + ].join("\n"), + ); +}); + +test("curl: a JSON body is a sample of the schema's required fields", () => { + assert.equal( + sample(document, "/api/v2/users", "post", "curl"), + [ + `curl -X POST \\`, + `\t"$CODER_URL/api/v2/users" \\`, + `\t-H "Coder-Session-Token: $CODER_SESSION_TOKEN" \\`, + `\t-H "Content-Type: application/json" \\`, + `\t-d '{`, + ` "email": "user@example.com",`, + ` "username": "string"`, + `}'`, + ].join("\n"), + ); +}); + +test("curl: an operation without security sends no token", () => { + assert.equal( + sample(document, "/api/v2/buildinfo", "get", "curl"), + [`curl -X GET \\`, `\t"$CODER_URL/api/v2/buildinfo"`].join("\n"), + ); +}); + +test("curl: another auth scheme gets a placeholder, never the session token", () => { + assert.equal( + sample(document, "/scim/v2/Users", "get", "curl"), + [ + `curl -X GET \\`, + `\t"$CODER_URL/scim/v2/Users" \\`, + `\t-H "Authorization: {Authorization}"`, + ].join("\n"), + ); +}); + +test("curl: the shell passes the body, URL and token through exactly", () => { + const args = curlArgs(sample(tricky, "/api/v2/users", "post", "curl")); + assert.equal(args[2], "https://coder.test/api/v2/users"); + assert.ok(args.includes("Coder-Session-Token: s3cret")); + assert.deepEqual(JSON.parse(args.at(-1) ?? ""), { note: trickyNote }); +}); + +test("curl: a path with shell syntax in it reaches curl unexpanded", () => { + const odd = { + ...document, + paths: { '/api/v2/$x/`y`/"z"': { get: { responses: { "200": { description: "OK" } } } } }, + }; + const args = curlArgs(sample(odd, '/api/v2/$x/`y`/"z"', "get", "curl")); + assert.equal(args[2], 'https://coder.test/api/v2/$x/`y`/"z"'); +}); + +test("curl: a body of only optional fields shows the first three instead of {}", () => { + const optional = { + ...document, + paths: { + "/api/v2/templates/{template}": { + patch: { + parameters: [{ name: "template", in: "path", required: true }], + requestBody: { + content: { + "application/json": { + schema: { + type: "object", + properties: { + a: { type: "boolean" }, + b: { type: "integer" }, + c: { type: "string" }, + d: { type: "string" }, + }, + }, + }, + }, + }, + responses: { "200": { description: "OK" } }, + }, + }, + }, + }; + assert.match( + sample(optional, "/api/v2/templates/{template}", "patch", "curl"), + /-d '\{\n {2}"a": true,\n {2}"b": 0,\n {2}"c": "string"\n\}'$/, + ); +}); + +const upload = { + ...document, + paths: { + "/api/v2/files": { + post: { + security: [{ CoderSessionToken: [] }], + parameters: [{ name: "Content-Type", in: "header", required: true }], + requestBody: { + content: { "application/x-tar": { schema: { type: "string", format: "binary" } } }, + }, + responses: { "201": { description: "Created" } }, + }, + }, + }, +}; + +test("curl: a Content-Type header parameter replaces the declared media type", () => { + assert.equal( + sample(upload, "/api/v2/files", "post", "curl"), + [ + `curl -X POST \\`, + `\t"$CODER_URL/api/v2/files" \\`, + `\t-H "Coder-Session-Token: $CODER_SESSION_TOKEN" \\`, + `\t-H "Content-Type: {Content-Type}" \\`, + `\t--data-binary "@{file}"`, + ].join("\n"), + ); +}); + +const form = { + ...document, + paths: { + "/api/v2/form": { + post: { + requestBody: { + content: { + "multipart/form-data": { + schema: { + type: "object", + required: ["name"], + properties: { name: { type: "string" }, other: { type: "string" } }, + }, + }, + }, + }, + responses: { "200": { description: "OK" } }, + }, + }, + }, +}; + +test("curl: a multipart body sends its required fields as literal strings", () => { + assert.equal( + sample(form, "/api/v2/form", "post", "curl"), + [`curl -X POST \\`, `\t"$CODER_URL/api/v2/form" \\`, `\t--form-string "name={name}"`].join( + "\n", + ), + ); +}); + +test("curl: a field name curl would split at its = is left out, so it can't name a local file", () => { + const hostile = structuredClone(form); + hostile.paths["/api/v2/form"].post.requestBody.content["multipart/form-data"].schema.required = [ + "name", + "f=@/etc/passwd;x", + ]; + const curl = sample(hostile, "/api/v2/form", "post", "curl"); + assert.equal( + curl, + [`curl -X POST \\`, `\t"$CODER_URL/api/v2/form" \\`, `\t--form-string "name={name}"`].join( + "\n", + ), + ); +}); + +test("a field name with an = is left out of all four samples, so they send the same fields", () => { + const hostile = structuredClone(form); + hostile.paths["/api/v2/form"].post.requestBody.content["multipart/form-data"].schema.required = [ + "name", + "f=@/etc/passwd;x", + ]; + for (const id of ["curl", "javascript", "python", "go"]) { + const source = sample(hostile, "/api/v2/form", "post", id); + assert.ok(source.includes("{name}"), `${id} sends name`); + assert.ok(!source.includes("passwd"), `${id} leaves the = field out`); + } +}); + +test("JavaScript: fetch with the URL and token from the environment", () => { + assert.equal( + sample(document, "/api/v2/users", "post", "javascript"), + [ + `const { CODER_URL, CODER_SESSION_TOKEN } = process.env;`, + "const url = `${CODER_URL}/api/v2/users`;", + `const response = await fetch(url, {`, + ` method: "POST",`, + ` headers: {`, + ` "Coder-Session-Token": CODER_SESSION_TOKEN,`, + ` "Content-Type": "application/json",`, + ` },`, + ` body: JSON.stringify({`, + ` email: "user@example.com",`, + ` username: "string",`, + ` }),`, + `});`, + `console.log(response.status, await response.text());`, + ].join("\n"), + ); +}); + +test("JavaScript: no auth means no headers", () => { + assert.equal( + sample(document, "/api/v2/buildinfo", "get", "javascript"), + [ + `const { CODER_URL } = process.env;`, + "const url = `${CODER_URL}/api/v2/buildinfo`;", + `const response = await fetch(url, {`, + ` method: "GET",`, + `});`, + `console.log(response.status, await response.text());`, + ].join("\n"), + ); +}); + +test("JavaScript: the sample runs and sends the body, URL and token exactly", async () => { + const call = await fetchCall(sample(tricky, "/api/v2/users", "post", "javascript")); + assert.equal(call.url, "https://coder.test/api/v2/users"); + assert.equal(call.init.method, "POST"); + assert.equal(call.init.headers?.["Coder-Session-Token"], "s3cret"); + assert.deepEqual(JSON.parse(String(call.init.body)), { note: trickyNote }); +}); + +test("JavaScript: path and query placeholders and other auth schemes", async () => { + const get = await fetchCall(sample(document, "/api/v2/users/{user}", "get", "javascript")); + assert.equal(get.url, "https://coder.test/api/v2/users/{user}?limit={limit}"); + const scim = await fetchCall(sample(document, "/scim/v2/Users", "get", "javascript")); + assert.deepEqual(scim.init.headers, { Authorization: "{Authorization}" }); +}); + +test("JavaScript: a multipart body is FormData and a binary body is read from a file", async () => { + const multipart = await fetchCall(sample(form, "/api/v2/form", "post", "javascript")); + assert.ok(multipart.init.body instanceof FormData); + assert.equal(multipart.init.body.get("name"), "{name}"); + assert.equal(multipart.init.headers, undefined); + assert.match(sample(upload, "/api/v2/files", "post", "javascript"), /readFile\("\{file\}"\)/); +}); + +test("Python: requests with the URL and token from the environment", () => { + assert.equal( + sample(document, "/api/v2/users", "post", "python"), + [ + `import os`, + ``, + `import requests`, + ``, + `url = os.environ["CODER_URL"] + "/api/v2/users"`, + `token = os.environ["CODER_SESSION_TOKEN"]`, + `response = requests.post(`, + ` url,`, + ` headers={`, + ` "Coder-Session-Token": token,`, + ` },`, + ` json={`, + ` "email": "user@example.com",`, + ` "username": "string",`, + ` },`, + `)`, + `print(response.status_code, response.text)`, + ].join("\n"), + ); +}); + +test("Python: no auth and no body", () => { + assert.equal( + sample(document, "/api/v2/users/{user}", "get", "python").split("\n").slice(4).join("\n"), + [ + `url = os.environ["CODER_URL"] + "/api/v2/users/{user}?limit={limit}"`, + `token = os.environ["CODER_SESSION_TOKEN"]`, + `response = requests.get(`, + ` url,`, + ` headers={`, + ` "Coder-Session-Token": token,`, + ` },`, + `)`, + `print(response.status_code, response.text)`, + ].join("\n"), + ); + assert.match( + sample(document, "/api/v2/buildinfo", "get", "python"), + /^url = os\.environ\["CODER_URL"\] \+ "\/api\/v2\/buildinfo"\nresponse = requests\.get\(\n {4}url,\n\)$/m, + ); +}); + +test("Python: a body is a Python literal with True, False, None and escaped strings", () => { + const values = { + ...document, + paths: { + "/api/v2/users": { + post: { + requestBody: { + content: { + "application/json": { + example: { + a: true, + b: false, + c: null, + d: [1, "x"], + e: {}, + f: [], + note: trickyNote, + }, + }, + }, + }, + responses: { "201": { description: "Created" } }, + }, + }, + }, + }; + assert.match( + sample(values, "/api/v2/users", "post", "python"), + new RegExp( + [ + ` json=\\{`, + ` "a": True,`, + ` "b": False,`, + ` "c": None,`, + ` "d": \\[`, + ` 1,`, + ` "x",`, + ` \\],`, + ` "e": \\{\\},`, + ` "f": \\[\\],`, + ` "note": 'it\\\\'s "q" \`tick\` \\$HOME \\$\\{x\\} \\\\\\\\ back\\\\nline',`, + ` \\},`, + ].join("\n"), + ), + ); +}); + +test("Go: net/http with the URL and token from the environment", () => { + assert.equal( + sample(document, "/api/v2/users", "post", "go"), + [ + `package main`, + ``, + `import (`, + `\t"fmt"`, + `\t"io"`, + `\t"net/http"`, + `\t"os"`, + `\t"strings"`, + `)`, + ``, + `func main() {`, + `\tbody := strings.NewReader(\`{`, + ` "email": "user@example.com",`, + ` "username": "string"`, + `}\`)`, + `\turl := os.Getenv("CODER_URL") + "/api/v2/users"`, + `\ttoken := os.Getenv("CODER_SESSION_TOKEN")`, + `\treq, err := http.NewRequest(http.MethodPost, url, body)`, + `\tif err != nil {`, + `\t\tpanic(err)`, + `\t}`, + `\treq.Header.Set("Coder-Session-Token", token)`, + `\treq.Header.Set("Content-Type", "application/json")`, + `\tresp, err := http.DefaultClient.Do(req)`, + `\tif err != nil {`, + `\t\tpanic(err)`, + `\t}`, + `\tdefer resp.Body.Close()`, + `\tout, err := io.ReadAll(resp.Body)`, + `\tif err != nil {`, + `\t\tpanic(err)`, + `\t}`, + `\tfmt.Println(resp.Status, string(out))`, + `}`, + ].join("\n"), + ); +}); + +test("Go: no body is nil and leaves strings unimported; no auth sets no header", () => { + const source = sample(document, "/api/v2/buildinfo", "get", "go"); + assert.match( + source, + /url := os\.Getenv\("CODER_URL"\) \+ "\/api\/v2\/buildinfo"\n\treq, err := http\.NewRequest\(http\.MethodGet, url, nil\)/, + ); + assert.doesNotMatch(source, /"strings"|Header\.Set|token/); +}); + +test("Go: a body with a backtick is an interpreted string literal", () => { + const source = sample(tricky, "/api/v2/users", "post", "go"); + const literal = JSON.stringify(JSON.stringify({ note: trickyNote }, null, 2)); + assert.ok(source.includes(`body := strings.NewReader(${literal})`)); + assert.ok(literal.startsWith(String.raw`"{\n \"note\": \"it's \\\"q\\\" `)); +}); + +test("Go: a lone surrogate stays a JSON escape, never a Go \\u escape Go would reject", () => { + const lone = structuredClone(tricky); + lone.paths["/api/v2/users"].post.requestBody.content["application/json"].example.note = "\ud800`"; + assert.ok(sample(lone, "/api/v2/users", "post", "go").includes(String.raw`\"\\ud800`)); +}); + +test("the samples become the operation's only code samples without changing the input", () => { + const before = JSON.stringify(document); + const out = withCodeSamples(document, "/api/v2/buildinfo", "get"); + assert.equal(JSON.stringify(document), before); + const samples = JSON.parse(JSON.stringify(out)).paths["/api/v2/buildinfo"].get["x-codeSamples"]; + assert.deepEqual(samples, codeSamples(document, "/api/v2/buildinfo", "get")); +}); + +const longPath = "/api/v2/organizations/{organization}/members/{user}/workspaces"; +const long = { + ...document, + paths: { + ...document.paths, + [longPath]: { + post: { + security: [{ CoderSessionToken: [] }], + parameters: [ + { name: "organization", in: "path", required: true }, + { name: "user", in: "path", required: true }, + ], + requestBody: { + content: { + "application/json": { example: { template_id: "string", name: "string" } }, + }, + }, + responses: { "201": { description: "Created" } }, + }, + }, + }, +}; + +// Prettier's 80, Black's 88, and the 64 columns the shell and Go samples aim for. +const WIDTH_BY_LABEL: Record<string, number> = { cURL: 64, JavaScript: 80, Python: 88, Go: 64 }; +// What each language puts around a URL line of its own: indent, quotes, `$CODER_URL`, `const url =`. +const URL_LINE_WRAPPER: Record<string, number> = { cURL: 18, JavaScript: 27, Python: 8, Go: 10 }; + +test("sample lines stay within each language's width, except a URL line whose path is too long to break", () => { + const operations: [string, string][] = [ + ["/api/v2/users/{user}", "get"], + ["/api/v2/users", "post"], + ["/api/v2/buildinfo", "get"], + ["/scim/v2/Users", "get"], + [longPath, "post"], + ]; + for (const [path, method] of operations) { + for (const { label, source } of codeSamples(long, path, method)) { + const limit = WIDTH_BY_LABEL[label] ?? 0; + const wrapper = URL_LINE_WRAPPER[label] ?? 0; + for (const line of source.split("\n")) { + const width = line.replace(/\t/g, " ").length; + const urlLineOnly = line.includes(path) && width - path.length <= wrapper; + if (urlLineOnly && path.length + wrapper > limit) continue; + assert.ok(width <= limit, `${label} ${method} ${path}: ${width} > ${limit}: ${line}`); + } + } + } +}); + +test("the samples' widths are the formatters' own", () => { + assert.deepEqual(SAMPLE_LINE_WIDTH, { curl: 64, javascript: 80, python: 88, go: 64 }); +}); + +test("a long URL is split where each language's formatter splits it", async () => { + const [shell, js, python, go] = codeSamples(long, longPath, "post").map((s) => s.source); + assert.ok(shell?.includes(` -X POST \\\n\t"$CODER_URL${longPath}" \\`)); + // Prettier never breaks a template literal. + assert.ok(js?.includes(`const url = \`\${CODER_URL}${longPath}\`;`)); + assert.ok(python?.includes(`url = (\n os.environ["CODER_URL"]\n + "${longPath}"\n)`)); + assert.ok(go?.includes(`\turl := os.Getenv("CODER_URL") +\n\t\t"${longPath}"`)); + const call = await fetchCall(js ?? ""); + assert.equal(call.url, `https://coder.test${longPath}`); +}); + +test("Python: a URL that fits Black's 88 columns inside parentheses stays on one line there", () => { + const path = "/api/v2/workspaceagents/{workspaceagent}/listening-ports"; + const doc = { + ...document, + paths: { [path]: { get: { responses: { "200": { description: "OK" } } } } }, + }; + assert.ok( + sample(doc, path, "get", "python").includes( + `url = (\n os.environ["CODER_URL"] + "${path}"\n)`, + ), + ); +}); + +const bodyOf = (example: unknown) => ({ + ...document, + paths: { + "/api/v2/users": { + post: { + requestBody: { content: { "application/json": { example } } }, + responses: { "201": { description: "Created" } }, + }, + }, + }, +}); + +test("JavaScript: the body is the literal Prettier prints, with keys unquoted where they can be", () => { + const source = sample( + bodyOf({ + "a-b": 1, + list: ["x", "y"], + objs: [{ id: "string", type: "*" }], + quoted: 'it\'s "q"', + plain: "it's", + e: {}, + f: [], + }), + "/api/v2/users", + "post", + "javascript", + ); + assert.ok( + source.includes( + [ + ` body: JSON.stringify({`, + ` "a-b": 1,`, + ` list: ["x", "y"],`, + ` objs: [`, + ` {`, + ` id: "string",`, + ` type: "*",`, + ` },`, + ` ],`, + ` quoted: 'it\\'s "q"',`, + ` plain: "it's",`, + ` e: {},`, + ` f: [],`, + ` }),`, + ].join("\n"), + ), + source, + ); +}); + +test("JavaScript: an array too long for one line puts one value per line", () => { + const items = Array.from({ length: 8 }, (_, index) => `value-number-${index}`); + const source = sample(bodyOf({ items }), "/api/v2/users", "post", "javascript"); + assert.ok(source.includes(` items: [\n "value-number-0",\n`), source); + assert.ok(source.includes(` "value-number-7",\n ],`), source); +}); + +test("Python: a string takes single quotes only when that needs fewer escapes, as Black does", () => { + const source = sample( + bodyOf({ a: 'it\'s "q"', b: "it's", c: 'say "hi"' }), + "/api/v2/users", + "post", + "python", + ); + assert.ok(source.includes(` "a": 'it\\'s "q"',`), source); + assert.ok(source.includes(` "b": "it's",`), source); + assert.ok(source.includes(` "c": 'say "hi"',`), source); +}); + +test("JavaScript: a path with template-literal syntax in it reaches fetch as written", async () => { + const odd = { + ...document, + paths: { "/api/v2/`a`/${b}/\\c": { get: { responses: { "200": { description: "OK" } } } } }, + }; + const call = await fetchCall(sample(odd, "/api/v2/`a`/${b}/\\c", "get", "javascript")); + assert.equal(call.url, "https://coder.test/api/v2/`a`/${b}/\\c"); +}); diff --git a/packages/docs-next/src/openapi/code-samples.ts b/packages/docs-next/src/openapi/code-samples.ts new file mode 100644 index 00000000..ca771acf --- /dev/null +++ b/packages/docs-next/src/openapi/code-samples.ts @@ -0,0 +1,514 @@ +import { type JsonSchema, dereference, sample } from "@fumadocs/json-schema"; +import { createMagicProxy, getRaw } from "@scalar/json-magic/magic-proxy"; +import { + DEPLOYMENT_URL_ENV, + isObject, + type JsonObject, + SESSION_TOKEN_ENV, + SESSION_TOKEN_HEADER, +} from "@coder/docs-config/client"; + +const resolve = (node: unknown): JsonObject | undefined => { + const value = dereference(node); + return isObject(value) ? value : undefined; +}; + +const placeholder = (name: string): string => `{${name}}`; + +interface Parameter { + name: string; + in: string; + required?: boolean; +} + +function parametersOf(pathItem: JsonObject, operation: JsonObject): Parameter[] { + const byKey = new Map<string, Parameter>(); + for (const list of [pathItem.parameters, operation.parameters]) { + if (!Array.isArray(list)) continue; + for (const item of list) { + const param = resolve(item); + if (typeof param?.name !== "string" || typeof param.in !== "string") continue; + byKey.set(`${param.in}:${param.name}`, { + name: param.name, + in: param.in, + required: param.required === true, + }); + } + } + return [...byKey.values()]; +} + +/** A header whose value is either literal text or the session token from the environment. */ +type Header = { name: string; value: string } | { name: string; token: true }; + +type Body = + | { kind: "json"; contentType: string; value: unknown } + | { kind: "form"; fields: string[] } + | { kind: "binary"; contentType: string }; + +/** One operation's example request, which each language writes out in its own syntax. */ +export interface ExampleRequest { + method: string; + /** The path and required query string, with `{name}` placeholders, appended to the deployment URL. */ + url: string; + headers: Header[]; + body?: Body; +} + +/** The auth headers of the first security alternative, preferring the session token; none when auth is optional. */ +function authHeaders(document: JsonObject, operation: JsonObject): Header[] { + const requirements = (operation.security ?? document.security) as JsonObject[] | undefined; + if (!Array.isArray(requirements) || requirements.length === 0) return []; + if (requirements.some((item) => isObject(item) && Object.keys(item).length === 0)) return []; + const schemes = resolve(resolve(document.components)?.securitySchemes) ?? {}; + const header = (key: string): Header | undefined => { + const scheme = resolve(schemes[key]); + if (scheme?.type === "apiKey" && scheme.in === "header" && typeof scheme.name === "string") { + return scheme.name === SESSION_TOKEN_HEADER + ? { name: scheme.name, token: true } + : { name: scheme.name, value: placeholder(key) }; + } + if (scheme?.type === "http" && String(scheme.scheme).toLowerCase() === "bearer") { + return { name: "Authorization", value: `Bearer ${placeholder(key)}` }; + } + return undefined; + }; + const chosen = + requirements.find((item) => + Object.keys(item).some((key) => resolve(schemes[key])?.name === SESSION_TOKEN_HEADER), + ) ?? requirements[0]; + return Object.keys(chosen ?? {}) + .map(header) + .filter((item): item is Header => item !== undefined); +} + +const isJson = (mediaType: string): boolean => + /^application\/(?:[\w.+-]+\+)?json\b/.test(mediaType); + +const isEmptyObject = (value: unknown): boolean => + isObject(value) && Object.keys(value).length === 0; + +function jsonSample(schema: JsonSchema, method: string): unknown { + const options = { skipReadOnly: method !== "get", skipWriteOnly: method === "get" }; + const required = sample(schema, { ...options, skipNonRequired: true }); + if (!isEmptyObject(required)) return required; + // A body of only optional fields, such as a PATCH, shows its first few instead of {}. + const full = sample(schema, options); + return isObject(full) ? Object.fromEntries(Object.entries(full).slice(0, 3)) : full; +} + +/** `contentType` replaces the declared media type when the operation takes it as a header parameter. */ +function bodyOf(operation: JsonObject, method: string, contentType?: string): Body | undefined { + const body = resolve(operation.requestBody); + const content = resolve(body?.content); + if (!content) return undefined; + const types = Object.keys(content); + const type = types.find(isJson) ?? types[0]; + if (type === undefined) return undefined; + const media = resolve(content[type]) ?? {}; + if (isJson(type)) { + const examples = resolve(media.examples); + const firstExample = examples ? resolve(Object.values(examples)[0]) : undefined; + const value = + media.example !== undefined + ? getRaw(media.example) + : firstExample?.value !== undefined + ? getRaw(firstExample.value) + : jsonSample((media.schema ?? {}) as JsonSchema, method); + return { kind: "json", contentType: contentType ?? type, value }; + } + if (type === "multipart/form-data") { + const schema = resolve(media.schema); + const required = Array.isArray(schema?.required) ? (schema.required as string[]) : []; + // curl splits a field at its first =, so such a name can't be written there; every sample leaves it out. + return { kind: "form", fields: required.filter((field) => !field.includes("=")) }; + } + return { kind: "binary", contentType: contentType ?? type }; +} + +/** + * The example request for one operation. Path and required query and header + * parameters stay `{name}` placeholders for the reader to fill in; a JSON body + * is the schema's example, or a sample of its required fields. + */ +export function exampleRequest(bundled: JsonObject, path: string, method: string): ExampleRequest { + const document = createMagicProxy(bundled) as JsonObject; + const pathItem = resolve(resolve(document.paths)?.[path]); + const operation = resolve(pathItem?.[method]); + if (!pathItem || !operation) throw new Error(`no ${method} ${path} in the API document`); + const params = parametersOf(pathItem, operation).filter((param) => param.required); + const isContentType = (param: Parameter) => + param.in === "header" && param.name.toLowerCase() === "content-type"; + const contentTypeParam = params.find(isContentType); + const query = params + .filter((param) => param.in === "query") + .map((param) => `${encodeURIComponent(param.name)}=${placeholder(param.name)}`) + .join("&"); + const body = bodyOf(operation, method, contentTypeParam && placeholder(contentTypeParam.name)); + const headers: Header[] = [ + ...authHeaders(document, operation), + ...params + .filter((param) => param.in === "header" && !isContentType(param)) + .map((param) => ({ name: param.name, value: placeholder(param.name) })), + ]; + if (body && body.kind !== "form") headers.push({ name: "Content-Type", value: body.contentType }); + return { + method: method.toUpperCase(), + url: `${path}${query ? `?${query}` : ""}`, + headers, + ...(body ? { body } : {}), + }; +} + +const jsonText = (value: unknown, indent = 2): string => JSON.stringify(value, null, indent); + +/** Text inside double quotes, where the shell would otherwise expand `$`, backticks and backslashes. */ +const shellDoubleQuoted = (text: string): string => `"${text.replace(/["$`\\]/g, "\\$&")}"`; + +const shellSingleQuoted = (text: string): string => `'${text.replace(/'/g, `'\\''`)}'`; + +export function curlSample(request: ExampleRequest): string { + const { body } = request; + const lines = [ + `curl -X ${request.method}`, + `"$${DEPLOYMENT_URL_ENV}${shellDoubleQuoted(request.url).slice(1)}`, + ...request.headers.map((header) => + "token" in header + ? `-H "${header.name}: $${SESSION_TOKEN_ENV}"` + : `-H ${shellDoubleQuoted(`${header.name}: ${header.value}`)}`, + ), + ]; + if (body?.kind === "json") lines.push(`-d ${shellSingleQuoted(jsonText(body.value))}`); + if (body?.kind === "form") { + for (const name of body.fields) + lines.push(`--form-string ${shellDoubleQuoted(`${name}=${placeholder(name)}`)}`); + } + if (body?.kind === "binary") + lines.push(`--data-binary ${shellDoubleQuoted("@".concat(placeholder("file")))}`); + // shfmt indents a continued line with a tab. + return lines.join(" \\\n\t"); +} + +/** + * The width each sample's lines are broken to: the formatter's own line width + * where it has one (Prettier 80, Black and ruff 88), and the column width the + * samples aim for in shell and Go, whose formatters have none. A path too long + * to break can exceed it. + */ +export const SAMPLE_LINE_WIDTH = { curl: 64, javascript: 80, python: 88, go: 64 } as const; + +const width = (line: string): number => line.replace(/\t/g, " ").length; + +/** The one-line form of a statement when it fits the width, else its broken form. */ +const fitOrBreak = (limit: number, oneLine: string[], broken: string[]): string[] => + oneLine.every((line) => width(line) <= limit) ? oneLine : broken; + +/** The body of a JSON string literal, escaped for single quotes instead: ' escaped, " unescaped. */ +const singleQuotedBody = (jsonBody: string): string => + jsonBody.replace(/\\(.)|(')/gs, (match, escaped?: string) => + escaped === undefined ? "\\'" : escaped === '"' ? '"' : match, + ); + +/** A JavaScript string literal as Prettier writes it: double quotes unless the text holds more of them than single quotes. */ +function jsString(text: string): string { + const doubles = text.split('"').length - 1; + const singles = text.split("'").length - 1; + const inner = JSON.stringify(text).slice(1, -1); + if (doubles <= singles) return `"${inner}"`; + return `'${singleQuotedBody(inner)}'`; +} + +const IDENTIFIER = /^[A-Za-z_$][\w$]*$/; + +const isEmptyCollection = (value: unknown): boolean => + (Array.isArray(value) && value.length === 0) || isEmptyObject(value); + +/** + * A JSON value as the JavaScript literal Prettier prints with its defaults: an + * object keeps one property per line and drops the quotes a key doesn't need, + * and an array of plain values goes on one line when it fits the 80 columns. + * `before` and `after` are the text on the value's first and last lines. + */ +function jsLiteral(value: unknown, indent: string, before: number, after: number): string { + const inner = `${indent} `; + if (Array.isArray(value)) { + if (value.length === 0) return "[]"; + const flat = + value.every((item) => !isObject(item) && !Array.isArray(item)) || + value.every((item) => isEmptyCollection(item) || (!isObject(item) && !Array.isArray(item))); + if (flat) { + const oneLine = `[${value.map((item) => jsLiteral(item, inner, 0, 0)).join(", ")}]`; + if (before + oneLine.length + after <= SAMPLE_LINE_WIDTH.javascript) return oneLine; + } + const items = value.map((item) => `${inner}${jsLiteral(item, inner, inner.length, 1)},`); + return `[\n${items.join("\n")}\n${indent}]`; + } + if (isObject(value)) { + const entries = Object.entries(value); + if (entries.length === 0) return "{}"; + const items = entries.map(([key, item]) => { + const name = IDENTIFIER.test(key) ? key : jsString(key); + const head = `${inner}${name}: `; + return `${head}${jsLiteral(item, inner, head.length, 1)},`; + }); + return `{\n${items.join("\n")}\n${indent}}`; + } + if (typeof value === "string") return jsString(value); + return JSON.stringify(value) ?? "null"; +} + +/** A Python string literal as Black writes it: double quotes, unless single quotes need fewer escapes. */ +function pythonString(text: string): string { + const inner = JSON.stringify(text).slice(1, -1); + const single = singleQuotedBody(inner); + const escapes = (body: string) => body.split("\\").length - 1; + return escapes(single) < escapes(inner) ? `'${single}'` : `"${inner}"`; +} + +/** Text inside a JavaScript template literal, where a backtick, a backslash or `${` would end or change it. */ +const templateText = (text: string): string => text.replace(/[\\`]|\$\{/g, "\\$&"); + +export function javascriptSample(request: ExampleRequest): string { + const { body } = request; + const lines: string[] = []; + if (body?.kind === "binary") lines.push(`import { readFile } from "node:fs/promises";`, ``); + if (body?.kind === "form") { + lines.push(`const form = new FormData();`); + for (const name of body.fields) { + lines.push(`form.append(${jsString(name)}, ${jsString(placeholder(name))});`); + } + lines.push(``); + } + const usesToken = request.headers.some((header) => "token" in header); + const env = usesToken ? `${DEPLOYMENT_URL_ENV}, ${SESSION_TOKEN_ENV}` : DEPLOYMENT_URL_ENV; + const url = `\`\${${DEPLOYMENT_URL_ENV}}${templateText(request.url)}\`;`; + lines.push( + `const { ${env} } = process.env;`, + // Prettier never breaks a template literal, however long. + `const url = ${url}`, + `const response = await fetch(url, {`, + ` method: ${jsString(request.method)},`, + ); + if (request.headers.length > 0) { + lines.push(` headers: {`); + for (const header of request.headers) { + const value = "token" in header ? SESSION_TOKEN_ENV : jsString(header.value); + const key = IDENTIFIER.test(header.name) ? header.name : jsString(header.name); + lines.push(` ${key}: ${value},`); + } + lines.push(` },`); + } + if (body?.kind === "json") { + const head = " body: JSON.stringify("; + lines.push(`${head}${jsLiteral(body.value, " ", head.length, 2)}),`); + } + if (body?.kind === "form") lines.push(` body: form,`); + if (body?.kind === "binary") { + lines.push(` body: await readFile(${jsString(placeholder("file"))}),`); + } + lines.push(`});`, `console.log(response.status, await response.text());`); + return lines.join("\n"); +} + +/** A JSON value as a Python literal; a JSON string literal is also a valid Python one. */ +function pythonLiteral(value: unknown, indent: string): string { + const inner = `${indent} `; + if (value === null || value === undefined) return "None"; + if (value === true) return "True"; + if (value === false) return "False"; + if (Array.isArray(value)) { + if (value.length === 0) return "[]"; + return `[\n${value.map((item) => `${inner}${pythonLiteral(item, inner)},`).join("\n")}\n${indent}]`; + } + if (isObject(value)) { + const entries = Object.entries(value); + if (entries.length === 0) return "{}"; + return `{\n${entries.map(([key, item]) => `${inner}${pythonString(key)}: ${pythonLiteral(item, inner)},`).join("\n")}\n${indent}}`; + } + if (typeof value === "string") return pythonString(value); + return JSON.stringify(value); +} + +const PYTHON_METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]); + +export function pythonSample(request: ExampleRequest): string { + const { body } = request; + const call = PYTHON_METHODS.has(request.method) + ? `requests.${request.method.toLowerCase()}(` + : `requests.request(\n ${pythonString(request.method)},`; + const lines = [ + `import os`, + ``, + `import requests`, + ``, + ...fitOrBreak( + SAMPLE_LINE_WIDTH.python, + [`url = os.environ["${DEPLOYMENT_URL_ENV}"] + ${pythonString(request.url)}`], + fitOrBreak( + SAMPLE_LINE_WIDTH.python, + [`url = (`, ` os.environ["${DEPLOYMENT_URL_ENV}"] + ${pythonString(request.url)}`, `)`], + [ + `url = (`, + ` os.environ["${DEPLOYMENT_URL_ENV}"]`, + ` + ${pythonString(request.url)}`, + `)`, + ], + ), + ), + ...(request.headers.some((header) => "token" in header) + ? [`token = os.environ["${SESSION_TOKEN_ENV}"]`] + : []), + `response = ${call}`, + ` url,`, + ]; + // requests sets this one itself for `json=`. + const headers = request.headers.filter( + (header) => + !(body?.kind === "json" && "value" in header && header.value === "application/json"), + ); + if (headers.length > 0) { + lines.push(` headers={`); + for (const header of headers) { + const value = "token" in header ? "token" : pythonString(header.value); + lines.push(` ${pythonString(header.name)}: ${value},`); + } + lines.push(` },`); + } + if (body?.kind === "json") lines.push(` json=${pythonLiteral(body.value, " ")},`); + if (body?.kind === "form") { + lines.push(` files={`); + for (const name of body.fields) { + lines.push(` ${pythonString(name)}: (None, ${pythonString(placeholder(name))}),`); + } + lines.push(` },`); + } + if (body?.kind === "binary") { + lines.push(` data=open(${pythonString(placeholder("file"))}, "rb"),`); + } + lines.push(`)`, `print(response.status_code, response.text)`); + return lines.join("\n"); +} + +const GO_METHODS: Record<string, string> = { + GET: "http.MethodGet", + POST: "http.MethodPost", + PUT: "http.MethodPut", + PATCH: "http.MethodPatch", + DELETE: "http.MethodDelete", + HEAD: "http.MethodHead", + OPTIONS: "http.MethodOptions", +}; + +/** A Go string literal for JSON text: raw when it can be, else interpreted, whose escapes JSON's match. */ +const goString = (json: string): string => + json.includes("`") ? JSON.stringify(json) : `\`${json}\``; + +const goCheck = [`\tif err != nil {`, `\t\tpanic(err)`, `\t}`]; + +export function goSample(request: ExampleRequest): string { + const { body } = request; + const imports = new Set(["fmt", "io", "net/http", "os"]); + const setup: string[] = []; + let reader = "nil"; + if (body?.kind === "json") { + imports.add("strings"); + setup.push(`\tbody := strings.NewReader(${goString(jsonText(body.value))})`); + reader = "body"; + } + if (body?.kind === "form") { + imports.add("bytes"); + imports.add("mime/multipart"); + setup.push(`\tvar body bytes.Buffer`, `\tform := multipart.NewWriter(&body)`); + for (const name of body.fields) { + setup.push( + `\tif err := form.WriteField(${JSON.stringify(name)}, ${JSON.stringify(placeholder(name))}); err != nil {`, + `\t\tpanic(err)`, + `\t}`, + ); + } + setup.push(`\tif err := form.Close(); err != nil {`, `\t\tpanic(err)`, `\t}`); + reader = "&body"; + } + if (body?.kind === "binary") { + setup.push(`\tbody, err := os.Open(${JSON.stringify(placeholder("file"))})`, ...goCheck); + setup.push(`\tdefer body.Close()`); + reader = "body"; + } + const method = GO_METHODS[request.method] ?? JSON.stringify(request.method); + const headers = request.headers.map((header) => + "token" in header + ? `\treq.Header.Set(${JSON.stringify(header.name)}, token)` + : `\treq.Header.Set(${JSON.stringify(header.name)}, ${JSON.stringify(header.value)})`, + ); + const token = request.headers.some((header) => "token" in header) + ? [`\ttoken := os.Getenv("${SESSION_TOKEN_ENV}")`] + : []; + if (body?.kind === "form") + headers.push(`\treq.Header.Set("Content-Type", form.FormDataContentType())`); + return [ + `package main`, + ``, + `import (`, + ...[...imports].sort().map((name) => `\t"${name}"`), + `)`, + ``, + `func main() {`, + ...setup, + ...fitOrBreak( + SAMPLE_LINE_WIDTH.go, + [`\turl := os.Getenv("${DEPLOYMENT_URL_ENV}") + ${JSON.stringify(request.url)}`], + [`\turl := os.Getenv("${DEPLOYMENT_URL_ENV}") +`, `\t\t${JSON.stringify(request.url)}`], + ), + ...token, + `\treq, err := http.NewRequest(${method}, url, ${reader})`, + ...goCheck, + ...headers, + `\tresp, err := http.DefaultClient.Do(req)`, + ...goCheck, + `\tdefer resp.Body.Close()`, + `\tout, err := io.ReadAll(resp.Body)`, + ...goCheck, + `\tfmt.Println(resp.Status, string(out))`, + `}`, + ].join("\n"); +} + +export interface CodeSample { + id: string; + lang: string; + label: string; + source: string; +} + +/** The operation's example request in each language the reference shows, in tab order. */ +export function codeSamples(bundled: JsonObject, path: string, method: string): CodeSample[] { + const request = exampleRequest(bundled, path, method); + return [ + { id: "curl", lang: "bash", label: "cURL", source: curlSample(request) }, + { + id: "javascript", + lang: "javascript", + label: "JavaScript", + source: javascriptSample(request), + }, + { id: "python", lang: "python", label: "Python", source: pythonSample(request) }, + { id: "go", lang: "go", label: "Go", source: goSample(request) }, + ]; +} + +/** The document with the operation's code samples as its only ones, leaving the input untouched. */ +export function withCodeSamples(bundled: JsonObject, path: string, method: string): JsonObject { + const samples = codeSamples(bundled, path, method); + const paths = bundled.paths as Record<string, JsonObject>; + const pathItem = paths[path] as JsonObject; + return { + ...bundled, + paths: { + ...paths, + [path]: { + ...pathItem, + [method]: { ...(pathItem[method] as JsonObject), "x-codeSamples": samples }, + }, + }, + }; +} diff --git a/packages/docs-next/src/openapi/data.test.ts b/packages/docs-next/src/openapi/data.test.ts new file mode 100644 index 00000000..b142158e --- /dev/null +++ b/packages/docs-next/src/openapi/data.test.ts @@ -0,0 +1,42 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { openApiDataFile } from "@coder/docs-config"; +import { createOpenApiDataLoader } from "./data.js"; + +async function appWith(files: Record<string, string>): Promise<string> { + const app = await mkdtemp(path.join(tmpdir(), "openapi-data-")); + for (const [id, text] of Object.entries(files)) { + const file = openApiDataFile(app, id); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, text); + } + return app; +} + +test("reads a version's data, once, and gives undefined for a version without any", async (t) => { + const app = await appWith({ "2.38": '{"operations":{}}' }); + t.after(() => rm(app, { recursive: true, force: true })); + const load = createOpenApiDataLoader(app, (versionId) => versionId); + const first = load("2.38"); + assert.equal(load("2.38"), first); + assert.deepEqual(await first, { operations: {} }); + assert.equal(await load("2.37"), undefined); + assert.equal(await load(undefined), undefined); +}); + +test("maps every version to one file when told to", async (t) => { + const app = await appWith({ docs: '{"operations":{"a":{}}}' }); + t.after(() => rm(app, { recursive: true, force: true })); + const load = createOpenApiDataLoader(app, () => "docs"); + assert.deepEqual(await load("2.38"), { operations: { a: {} } }); + assert.equal(load(undefined), load("2.38")); +}); + +test("a file that is not JSON fails rather than reading as no data", async (t) => { + const app = await appWith({ main: "not json" }); + t.after(() => rm(app, { recursive: true, force: true })); + await assert.rejects(createOpenApiDataLoader(app, () => "main")(undefined), SyntaxError); +}); diff --git a/packages/docs-next/src/openapi/data.ts b/packages/docs-next/src/openapi/data.ts new file mode 100644 index 00000000..49176480 --- /dev/null +++ b/packages/docs-next/src/openapi/data.ts @@ -0,0 +1,31 @@ +import { readFile } from "node:fs/promises"; +import { type OpenApiPagesData, openApiDataFile } from "@coder/docs-config"; + +/** + * Reads the REST API reference data a sync wrote under `appDir`, at render + * time rather than as an import, so the document stays out of the server + * bundle. `idFor` names a version's data file; a version with no file has no + * generated reference, nor does one `idFor` maps to undefined. Each file is read once. + */ +export function createOpenApiDataLoader( + appDir: string, + idFor: (versionId: string | undefined) => string | undefined, +): (versionId: string | undefined) => Promise<OpenApiPagesData | undefined> { + const cache = new Map<string, Promise<OpenApiPagesData | undefined>>(); + return (versionId) => { + const id = idFor(versionId); + if (id === undefined) return Promise.resolve(undefined); + let cached = cache.get(id); + if (!cached) { + cached = readFile(openApiDataFile(appDir, id), "utf8").then( + (text): OpenApiPagesData => JSON.parse(text), + (error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return undefined; + throw error; + }, + ); + cache.set(id, cached); + } + return cached; + }; +} diff --git a/packages/docs-next/src/openapi/index.test.tsx b/packages/docs-next/src/openapi/index.test.tsx new file mode 100644 index 00000000..17dadbb1 --- /dev/null +++ b/packages/docs-next/src/openapi/index.test.tsx @@ -0,0 +1,144 @@ +import assert from "node:assert/strict"; +import { mkdtemp, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import type { OpenApiPagesData } from "@coder/docs-config"; +import { createOpenApiRenderBody, pruneDocument } from "./index.js"; + +const ROUTE = "reference/api/secrets/get-secret"; + +function pagesData(spec: Record<string, unknown>): OpenApiPagesData { + return { + document: spec, + operations: { [ROUTE]: { method: "get", path: "/api/v2/secret" } }, + anchors: {}, + landing: { route: "reference/api", setupId: "set-up-your-environment", sections: [] }, + schemas: { route: "reference/api/schemas", rows: [] }, + }; +} + +const withSchema = (schema: Record<string, unknown>) => ({ + openapi: "3.0.3", + info: { title: "Coder API", version: "2.0" }, + paths: { + "/api/v2/secret": { + get: { + summary: "Get secret", + responses: { + "200": { + description: "OK", + content: { "application/json": { schema: { $ref: "#/components/schemas/Secret" } } }, + }, + }, + }, + }, + }, + components: { schemas: { Secret: schema } }, +}); + +test("an API document with an external $ref is rejected before the bundler can read it", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "openapi-ref-")); + const secret = path.join(dir, "secret.json"); + await writeFile(secret, JSON.stringify({ type: "string", description: "do-not-leak" })); + for (const target of [secret, `file://${secret}`, "https://example.com/schema.json"]) { + const renderBody = createOpenApiRenderBody(async () => pagesData(withSchema({ $ref: target }))); + await assert.rejects( + renderBody({ versionId: undefined, slugs: ROUTE.split("/"), hrefFor: (r) => `/${r}/` }), + (error: Error) => { + assert.match( + error.message, + /\$ref at \/components\/schemas\/Secret\/\$ref is not an in-document reference/, + ); + assert.doesNotMatch(error.message, /do-not-leak/); + return true; + }, + target, + ); + } +}); + +const ref = (kind: string, name: string) => ({ $ref: `#/components/${kind}/${name}` }); + +const api = { + openapi: "3.0.3", + info: { title: "Coder API", version: "2.0", description: "Not carried." }, + servers: [{ url: "{deployment}" }], + paths: { + "/api/v2/a/{id}": { + parameters: [ref("parameters", "Id")], + get: { + responses: { + "200": { + description: "OK", + content: { "application/json": { schema: ref("schemas", "A") } }, + }, + }, + }, + }, + "/api/v2/d": { + get: { + responses: { + "200": { + description: "OK", + content: { "application/json": { schema: ref("schemas", "D") } }, + }, + }, + }, + }, + }, + components: { + securitySchemes: { + CoderSessionToken: { type: "apiKey", in: "header", name: "Coder-Session-Token" }, + }, + parameters: { Id: { name: "id", in: "path", required: true, schema: ref("schemas", "Id") } }, + schemas: { + A: { type: "object", properties: { b: ref("schemas", "B") } }, + B: { type: "array", items: ref("schemas", "C") }, + C: { type: "object", properties: { back: ref("schemas", "A"), self: ref("schemas", "C") } }, + D: { type: "string" }, + Id: { type: "string", format: "uuid" }, + }, + }, +}; + +test("a pruned page keeps its operation, its path's parameters and every schema they reach, and nothing else", () => { + const pruned = pruneDocument(api, "/api/v2/a/{id}", "get"); + assert.deepEqual(Object.keys(pruned.paths as object), ["/api/v2/a/{id}"]); + const item = (pruned.paths as Record<string, Record<string, unknown>>)["/api/v2/a/{id}"]; + assert.deepEqual(item?.parameters, [ref("parameters", "Id")]); + assert.deepEqual(Object.keys(item ?? {}).sort(), ["get", "parameters"]); + const components = pruned.components as Record<string, Record<string, unknown>>; + assert.deepEqual(Object.keys(components.schemas ?? {}).sort(), ["A", "B", "C", "Id"]); + assert.deepEqual(components.parameters, api.components.parameters); + assert.deepEqual(components.securitySchemes, api.components.securitySchemes); + assert.deepEqual(pruned.info, { title: "Coder API", version: "2.0" }); + assert.deepEqual(pruned.servers, api.servers); +}); + +test("a component whose name holds / or ~ is kept when its reference escapes them", () => { + const document = { + openapi: "3.0.3", + info: { title: "T", version: "1" }, + paths: { + "/x": { + get: { + responses: { + "200": { + description: "OK", + content: { "application/json": { schema: { $ref: "#/components/schemas/a~1b~0c" } } }, + }, + }, + }, + }, + }, + components: { schemas: { "a/b~c": { type: "string" } } }, + }; + const pruned = pruneDocument(document, "/x", "get"); + const components = pruned.components as Record<string, Record<string, unknown>>; + assert.deepEqual(Object.keys(components.schemas ?? {}), ["a/b~c"]); +}); + +test("pruning a page whose operation isn't in the document fails", () => { + assert.throws(() => pruneDocument(api, "/api/v2/a/{id}", "post"), /no post \/api\/v2\/a\/\{id\}/); +}); diff --git a/packages/docs-next/src/openapi/index.tsx b/packages/docs-next/src/openapi/index.tsx new file mode 100644 index 00000000..636d5e53 --- /dev/null +++ b/packages/docs-next/src/openapi/index.tsx @@ -0,0 +1,151 @@ +import { + assertInDocumentRefs, + collectRefs, + type HttpMethod, + isObject, + type JsonObject, + type OpenApiPagesData, +} from "@coder/docs-config"; +import type { Document } from "fumadocs-openapi"; +import { createOpenAPI } from "fumadocs-openapi/server"; +import type { RenderBody } from "../types.js"; +import { AnchorRedirect } from "./anchor-redirect.js"; +import { ApiPage } from "./api-page-lazy.js"; +import { withCodeSamples } from "./code-samples.js"; +import { ApiLanding } from "./landing.js"; +import { SetupHrefProvider } from "./samples-note.js"; +import { SchemaTables } from "./schemas.js"; + +const unescapePointer = (segment: string): string => + segment.replace(/~1/g, "/").replace(/~0/g, "~"); + +/** + * The document cut down to one operation and the components it reaches, so a + * page's props carry only what that page renders, not the whole API. + */ +export function pruneDocument(document: JsonObject, path: string, method: HttpMethod): JsonObject { + const paths = document.paths as Record<string, JsonObject>; + const item = paths[path]; + if (!item || !isObject(item[method])) throw new Error(`no ${method} ${path} in the API document`); + const components = (document.components ?? {}) as Record<string, JsonObject>; + const kept: Record<string, JsonObject> = { securitySchemes: components.securitySchemes ?? {} }; + const pathItem: JsonObject = { [method]: item[method] }; + if (item.parameters) pathItem.parameters = item.parameters; + const seen = new Set<string>(); + let frontier = new Set<string>(); + collectRefs(pathItem, frontier); + while (frontier.size > 0) { + const next = new Set<string>(); + for (const ref of frontier) { + if (seen.has(ref) || !ref.startsWith("#/components/")) continue; + seen.add(ref); + const [kind, name] = ref.slice("#/components/".length).split("/").map(unescapePointer) as [ + string, + string, + ]; + const value = components[kind]?.[name]; + if (value === undefined) continue; + (kept[kind] ??= {})[name] = value; + collectRefs(value, next); + } + frontier = next; + } + const info = (document.info ?? {}) as JsonObject; + return { + openapi: document.openapi, + info: { title: info.title, version: info.version }, + servers: document.servers, + ...(document.security ? { security: document.security } : {}), + paths: { [path]: pathItem }, + components: kept, + }; +} + +/** + * The page-body hook that renders a version's REST API reference: each + * operation page through fumadocs-openapi, and the old anchor redirect on the + * tag and schemas pages. `load` returns a version's data, or `undefined` for + * a version that keeps its Markdown reference. + */ +export function createOpenApiRenderBody( + load: (versionId: string | undefined) => Promise<OpenApiPagesData | undefined>, +): RenderBody { + const bundled = new Map<string | undefined, Promise<JsonObject>>(); + const bundle = (versionId: string | undefined, document: JsonObject): Promise<JsonObject> => { + let cached = bundled.get(versionId); + if (!cached) { + // The bundler fetches or reads any other reference, so only in-document ones may reach it. + assertInDocumentRefs(document, "the API document"); + const server = createOpenAPI({ input: { coder: () => document as Document } }); + cached = server.getSchema("coder").then((schema) => schema.bundled as JsonObject); + bundled.set(versionId, cached); + } + return cached; + }; + + return async ({ versionId, slugs, hrefFor }) => { + const data = await load(versionId); + if (!data) return undefined; + const route = slugs.join("/"); + const { landing } = data; + if (route === landing.route) { + return { + after: <ApiLanding sections={landing.sections} hrefFor={hrefFor} />, + toc: landing.sections.map((section) => ({ + title: section.title, + url: `#${section.id}`, + depth: 2, + })), + }; + } + const operation = data.operations[route]; + if (operation) { + const landingHref = hrefFor(landing.route); + const document = withCodeSamples( + pruneDocument(await bundle(versionId, data.document), operation.path, operation.method), + operation.path, + operation.method, + ); + return { + full: true, + replace: ( + <div className="coder-api-page"> + <SetupHrefProvider href={landingHref && `${landingHref}#${landing.setupId}`}> + <ApiPage + document="coder" + showTitle={false} + showDescription + operations={[{ path: operation.path, method: operation.method }]} + payload={{ bundled: document as Document }} + /> + </SetupHrefProvider> + </div> + ), + }; + } + const anchors = data.anchors[route]; + if (!anchors) return undefined; + const targets: Record<string, string> = {}; + for (const [anchor, target] of Object.entries(anchors)) { + const href = hrefFor(target); + if (href) targets[anchor] = href; + } + const redirect = <AnchorRedirect targets={targets} />; + if (route !== data.schemas.route) return { after: redirect }; + return { + replace: ( + <> + <p> + Each endpoint's page documents the request and response schemas it uses. These + tables name, for each schema, the endpoint page that shows it most directly. + </p> + <SchemaTables rows={data.schemas.rows} hrefFor={hrefFor} /> + </> + ), + after: redirect, + }; + }; +} + +export { createOpenApiDataLoader } from "./data.js"; +export { collapseFoldersUnder } from "./tree.js"; diff --git a/packages/docs-next/src/openapi/landing.test.tsx b/packages/docs-next/src/openapi/landing.test.tsx new file mode 100644 index 00000000..0456f16d --- /dev/null +++ b/packages/docs-next/src/openapi/landing.test.tsx @@ -0,0 +1,133 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { renderToFragment } from "../../test/dom.js"; +import { createOpenApiRenderBody } from "./index.js"; +import type { OpenApiLanding } from "@coder/docs-config/client"; +import { ApiLanding } from "./landing.js"; + +const landing: OpenApiLanding = { + route: "reference/api", + setupId: "set-up-your-environment", + sections: [ + { + title: "Users", + id: "users", + operations: [ + { route: "reference/api/users/create-new-user", title: "Create new user", method: "post" }, + { + route: "reference/api/users/get-user-by-name", + title: "Get user by name", + method: "get", + description: "Returns one user.", + }, + ], + }, + { + title: "Workspaces", + id: "workspaces", + operations: [ + { route: "reference/api/workspaces/delete", title: "Delete workspace", method: "delete" }, + ], + }, + ], +}; + +const hrefFor = (route: string) => `/beta-docs/${route}/`; + +const CARDS = ".coder-api-cards > [data-card]"; + +test("each tag is a section heading with a card per operation, in order", () => { + const page = renderToFragment(<ApiLanding sections={landing.sections} hrefFor={hrefFor} />); + assert.deepEqual( + [...page.querySelectorAll("h2")].map((h2) => [h2.id, h2.querySelector("a")?.textContent]), + [ + ["users", "Users"], + ["workspaces", "Workspaces"], + ], + ); + const cards = [...page.querySelectorAll(CARDS)]; + assert.deepEqual( + cards.map((card) => { + const link = card.querySelector("h3 a"); + return { + href: link?.getAttribute("href"), + name: link?.textContent, + badge: link?.querySelector("span.font-mono")?.textContent, + description: card.querySelector("p")?.textContent ?? null, + }; + }), + [ + { + href: "/beta-docs/reference/api/users/create-new-user/", + name: "Create new user POST", + badge: "POST", + description: null, + }, + { + href: "/beta-docs/reference/api/users/get-user-by-name/", + name: "Get user by name GET", + badge: "GET", + description: "Returns one user.", + }, + { + href: "/beta-docs/reference/api/workspaces/delete/", + name: "Delete workspace DELETE", + badge: "DELETE", + description: null, + }, + ], + ); +}); + +test("an operation without a page gets no card rather than a dead link", () => { + const page = renderToFragment( + <ApiLanding + sections={landing.sections} + hrefFor={(route) => (route.endsWith("delete") ? undefined : hrefFor(route))} + />, + ); + assert.equal(page.querySelectorAll(CARDS).length, 2); + assert.equal(page.querySelectorAll("a:not([href])").length, 0); +}); + +test("the landing route gets the cards after its body and their headings in its TOC", async () => { + const renderBody = createOpenApiRenderBody(async () => ({ + document: {}, + operations: {}, + anchors: {}, + schemas: { route: "reference/api/schemas", rows: [] }, + landing, + })); + const result = await renderBody({ versionId: undefined, slugs: ["reference", "api"], hrefFor }); + assert.equal(result?.replace, undefined, "the page's own Markdown stays"); + assert.deepEqual(result?.toc, [ + { title: "Users", url: "#users", depth: 2 }, + { title: "Workspaces", url: "#workspaces", depth: 2 }, + ]); + const after = renderToFragment(result?.after); + assert.equal(after.querySelectorAll(CARDS).length, 3); +}); + +test("a protected section id is the heading id and the TOC link, unchanged", async () => { + const reserved: OpenApiLanding = { + ...landing, + sections: [{ title: "__next_f", id: "user-content-__next_f", operations: [] }], + }; + const renderBody = createOpenApiRenderBody(async () => ({ + document: {}, + operations: {}, + anchors: {}, + schemas: { route: "reference/api/schemas", rows: [] }, + landing: reserved, + })); + const result = await renderBody({ versionId: undefined, slugs: ["reference", "api"], hrefFor }); + assert.deepEqual( + result?.toc?.map((entry) => entry.url), + ["#user-content-__next_f"], + ); + const after = renderToFragment(result?.after); + assert.deepEqual( + [...after.querySelectorAll("h2")].map((h2) => h2.id), + ["user-content-__next_f"], + ); +}); diff --git a/packages/docs-next/src/openapi/landing.tsx b/packages/docs-next/src/openapi/landing.tsx new file mode 100644 index 00000000..94b2e800 --- /dev/null +++ b/packages/docs-next/src/openapi/landing.tsx @@ -0,0 +1,44 @@ +import type { OpenApiLanding } from "@coder/docs-config/client"; +import { Card, Cards } from "fumadocs-ui/components/card"; +import { Heading } from "fumadocs-ui/components/heading"; +import { Fragment } from "react"; +import { MethodBadge } from "./method-badge.js"; + +/** + * A card for every operation, under a heading per tag in sidebar order. The + * cards are server-rendered plain links (no client `Link`, so no prefetch), + * each stretched over its card by `.coder-api-cards` in the theme. + */ +export function ApiLanding({ + sections, + hrefFor, +}: { + sections: OpenApiLanding["sections"]; + hrefFor: (route: string) => string | undefined; +}) { + return sections.map((section) => ( + <Fragment key={section.id}> + {/* Prose zeroes the margin of whatever follows an h2, as the first section does after bare text. */} + <Heading as="h2" id={section.id} className="mt-12"> + {section.title} + </Heading> + <Cards className="coder-api-cards"> + {section.operations.map((operation) => { + const href = hrefFor(operation.route); + if (href === undefined) return null; + return ( + <Card + key={operation.route} + title={ + <a href={href}> + {operation.title} <MethodBadge method={operation.method} /> + </a> + } + description={operation.description} + /> + ); + })} + </Cards> + </Fragment> + )); +} diff --git a/packages/docs-next/src/openapi/method-badge.test.tsx b/packages/docs-next/src/openapi/method-badge.test.tsx new file mode 100644 index 00000000..3e471914 --- /dev/null +++ b/packages/docs-next/src/openapi/method-badge.test.tsx @@ -0,0 +1,32 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { flattenTree } from "fumadocs-core/page-tree"; +import { type PageData, type VirtualFile, loader } from "fumadocs-core/source"; +import { openapiPlugin } from "fumadocs-openapi/server"; +import { renderToFragment } from "../../test/dom.js"; +import { MethodBadge } from "./method-badge.js"; + +type Files = VirtualFile<{ pageData: PageData & { _openapi?: unknown }; metaData: never }>[]; + +/** The badge fumadocs-openapi's loader plugin puts on the sidebar item of a page with the sync's `_openapi` frontmatter. */ +function sidebarBadge(method: string): Element | null { + const files: Files = [ + { type: "page", path: "api/op.md", data: { title: "Op", _openapi: { method } } }, + ]; + const docs = loader({ baseUrl: "/", source: { files }, plugins: [openapiPlugin()] }); + const item = flattenTree(docs.pageTree.children).find((node) => node.url === "/api/op"); + return renderToFragment(item?.name).querySelector("span"); +} + +for (const method of ["get", "post", "put", "patch", "delete"]) { + test(`the ${method.toUpperCase()} badge looks like the sidebar's, so the theme's contrast overrides cover both`, () => { + const sidebar = sidebarBadge(method); + const badge = renderToFragment(<MethodBadge method={method} />).querySelector("span"); + assert.equal(sidebar?.textContent, method.toUpperCase()); + assert.equal(badge?.textContent, method.toUpperCase()); + const colors = (el: Element | null | undefined) => + [...(el?.classList ?? [])].filter((name) => /^(dark:)?text-[a-z]+-\d+$/.test(name)).sort(); + assert.deepEqual(colors(badge), colors(sidebar)); + assert.ok(colors(badge).length === 2); + }); +} diff --git a/packages/docs-next/src/openapi/method-badge.tsx b/packages/docs-next/src/openapi/method-badge.tsx new file mode 100644 index 00000000..db08f938 --- /dev/null +++ b/packages/docs-next/src/openapi/method-badge.tsx @@ -0,0 +1,19 @@ +// Mirrors MethodLabel in fumadocs-openapi 12.5.4 (ui/components/method-label), which the sidebar uses but the package does not export. +const COLORS: Record<string, string> = { + PUT: "text-yellow-600 dark:text-yellow-400", + PATCH: "text-orange-600 dark:text-orange-400", + POST: "text-blue-600 dark:text-blue-400", + DELETE: "text-red-600 dark:text-red-400", +}; + +/** An HTTP method as the coloured badge the API reference's sidebar shows beside each operation. */ +export function MethodBadge({ method }: { method: string }) { + const label = method.toUpperCase(); + return ( + <span + className={`font-mono font-medium text-xs text-nowrap ${COLORS[label] ?? "text-green-600 dark:text-green-400"}`} + > + {label} + </span> + ); +} diff --git a/packages/docs-next/src/openapi/playground-stub-loader.ts b/packages/docs-next/src/openapi/playground-stub-loader.ts new file mode 100644 index 00000000..52d66d95 --- /dev/null +++ b/packages/docs-next/src/openapi/playground-stub-loader.ts @@ -0,0 +1,15 @@ +import { playgroundStub } from "./playground-stubs.js"; + +interface LoaderContext { + resourcePath: string; + async(): (error: Error | null, result?: string) => void; +} + +/** A webpack and Turbopack loader that replaces a fumadocs-openapi playground module with its inert stub. */ +export default function playgroundStubLoader(this: LoaderContext, source: string): void { + const callback = this.async(); + playgroundStub(this.resourcePath, source).then( + (stub) => callback(null, stub), + (error: Error) => callback(error), + ); +} diff --git a/packages/docs-next/src/openapi/playground-stubs.test.ts b/packages/docs-next/src/openapi/playground-stubs.test.ts new file mode 100644 index 00000000..af28f180 --- /dev/null +++ b/packages/docs-next/src/openapi/playground-stubs.test.ts @@ -0,0 +1,118 @@ +import assert from "node:assert/strict"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { init, parse } from "es-module-lexer"; +import { + OPENAPI_PLAYGROUND_MARKERS, + OPENAPI_PLAYGROUND_MODULE, + OPENAPI_PLAYGROUND_STUBBED, + playgroundStub, +} from "./playground-stubs.js"; + +const dist = path.dirname( + path.dirname(fileURLToPath(import.meta.resolve("fumadocs-openapi/ui/base"))), +); +const read = (rel: string) => readFileSync(path.join(dist, rel), "utf8"); +const markersIn = (source: string) => OPENAPI_PLAYGROUND_MARKERS.filter((m) => source.includes(m)); + +// The fumadocs-openapi modules the engine imports, as package.json's exports map them. +const ENTRIES = [ + "index.js", + "index.browser.js", + "operation.js", + "requests/generators/index.js", + "server/index.js", + "ui/base.js", +]; + +/** Every module reached from the entries over relative imports, each stubbed module replaced by its stub. */ +async function reachable(stubbed: boolean): Promise<Map<string, string>> { + await init; + const sources = new Map<string, string>(); + const queue = [...ENTRIES]; + while (queue.length > 0) { + const rel = queue.pop(); + if (rel === undefined || sources.has(rel)) continue; + const file = path.join(dist, rel); + const source = + stubbed && OPENAPI_PLAYGROUND_MODULE.test(file) + ? await playgroundStub(file, read(rel)) + : read(rel); + sources.set(rel, source); + for (const { n } of parse(source, rel)[0]) { + if (n?.startsWith(".")) queue.push(path.posix.join(path.posix.dirname(rel), n)); + } + } + return sources; +} + +test("every stubbed module exists in the installed fumadocs-openapi", () => { + for (const rel of OPENAPI_PLAYGROUND_STUBBED) { + assert.ok(existsSync(path.join(dist, rel)), rel); + assert.match(path.join(dist, rel), OPENAPI_PLAYGROUND_MODULE); + } +}); + +test("each stub keeps its module's exports and holds none of the playground's code", async () => { + await init; + for (const rel of OPENAPI_PLAYGROUND_STUBBED) { + const source = read(rel); + const stub = await playgroundStub(path.join(dist, rel), source); + const names = (text: string) => + parse(text, rel)[1] + .map((e) => e.n) + .toSorted(); + assert.deepEqual(names(stub), names(source), rel); + assert.deepEqual(markersIn(stub), [], rel); + assert.equal(/\bfetch\(|sessionStorage|localStorage/.test(stub), false, rel); + } +}); + +test("every marker is in the code the stubs replace", () => { + const replaced = OPENAPI_PLAYGROUND_STUBBED.map(read).join("\n"); + for (const marker of OPENAPI_PLAYGROUND_MARKERS) assert.ok(replaced.includes(marker), marker); +}); + +test("the stubs cut every path from the engine's entries to playground code", async () => { + const unstubbed = [...(await reachable(false))].filter(([, s]) => markersIn(s).length > 0); + assert.ok(unstubbed.length > 0, "the entries reach no playground code even without the stubs"); + const stubbed = [...(await reachable(true))].filter(([, s]) => markersIn(s).length > 0); + assert.deepEqual( + stubbed.map(([rel]) => rel), + [], + ); +}); + +test("every export of the auth stub throws instead of running an auth flow", async () => { + const stub = await playgroundStub( + path.join(dist, "playground/auth.js"), + read("playground/auth.js"), + ); + const url = `data:text/javascript,${encodeURIComponent(stub.replace('"use client";', ""))}`; + const auth = (await import(url)) as Record<string, () => unknown>; + const names = Object.keys(auth); + assert.ok(names.length > 0, "the stub exports something"); + for (const name of names) assert.throws(() => auth[name]?.(), /not included in this build/, name); +}); + +test("a matched module with no stub, or with other exports, fails the build", async () => { + await assert.rejects( + playgroundStub(path.join(dist, "playground/index.js"), read("playground/index.js")), + /no inert stub/, + ); + await assert.rejects( + playgroundStub( + path.join(dist, "playground/fetcher.js"), + `${read("playground/fetcher.js")}\nexport const added = 1;`, + ), + /exports/, + ); +}); + +test("modules outside the playground are not matched", () => { + for (const rel of ["ui/operation/index.js", "utils/create-page.js", "server/index.js"]) { + assert.equal(OPENAPI_PLAYGROUND_MODULE.test(path.join(dist, rel)), false, rel); + } +}); diff --git a/packages/docs-next/src/openapi/playground-stubs.ts b/packages/docs-next/src/openapi/playground-stubs.ts new file mode 100644 index 00000000..181da8c7 --- /dev/null +++ b/packages/docs-next/src/openapi/playground-stubs.ts @@ -0,0 +1,86 @@ +import { init, parse } from "es-module-lexer"; + +/** fumadocs-openapi's modules that send requests or run auth flows: the API playground, its OAuth flows and fetcher, and the server's proxy and OAuth redirect handler. */ +export const OPENAPI_PLAYGROUND_MODULE = + /[\\/]fumadocs-openapi[\\/]dist[\\/]((?:ui[\\/])?playground[\\/][^\\/]+\.js|server[\\/](?:proxy|oauth)\.js)$/; + +/** Strings found only in those modules: JavaScript that holds one ships playground code. */ +export const OPENAPI_PLAYGROUND_MARKERS = [ + "fumadocs-openapi-flow", + "fumadocs-openapi-oauth", + "grant_type", + "device_code", + "proxyForwardCookie", + "is required for proxy url", +]; + +const unavailable = `function unavailable() { + throw new Error("fumadocs-openapi's API playground is not included in this build"); +}`; + +const STUBS: Record<string, string> = { + "playground/auth.js": `"use client"; +${unavailable} +export { + unavailable as finishOAuthFlow, + unavailable as requestOAuthToken, + unavailable as useAuthFields, + unavailable as useAuthRedirect, + unavailable as useOpenIdConnectFlows, + unavailable as usePlaygroundAuth, +}; +`, + "playground/fetcher.js": `${unavailable} +export { unavailable as createBrowserFetcher, unavailable as proxied }; +`, + "playground/use-playground.js": `"use client"; +${unavailable} +export { unavailable as usePlayground }; +`, + "ui/playground/client.js": `"use client"; +${unavailable} +export default function PlaygroundClient() { + return null; +} +export function DefaultResultDisplay() { + return null; +} +export const Custom = { useController: unavailable }; +`, + "server/proxy.js": `${unavailable} +export { unavailable as createProxy }; +`, + "server/oauth.js": `${unavailable} +export { unavailable as createOAuthHandler }; +`, +}; + +/** The modules that have a stub, relative to fumadocs-openapi's `dist/`. */ +export const OPENAPI_PLAYGROUND_STUBBED = Object.keys(STUBS); + +const exportNames = (source: string, file: string): string[] => + parse(source, file)[1] + .map((entry) => entry.n) + .toSorted(); + +/** + * The inert stand-in for the fumadocs-openapi module at `file`, whose own code + * is `source`. Rejects when the module has no stub or the stub's exports + * differ from the module's, so an upgrade that changes either fails the build. + */ +export async function playgroundStub(file: string, source: string): Promise<string> { + await init; + const rel = OPENAPI_PLAYGROUND_MODULE.exec(file)?.[1]?.replaceAll("\\", "/"); + const stub = rel === undefined ? undefined : STUBS[rel]; + if (rel === undefined || stub === undefined) { + throw new Error(`no inert stub for ${file}; stub it in @coder/docs-next before using it`); + } + const want = exportNames(source, file); + const have = exportNames(stub, `${rel} stub`); + if (want.join() !== have.join()) { + throw new Error( + `fumadocs-openapi's ${rel} exports ${want.join(", ")}, but its stub exports ${have.join(", ")}`, + ); + } + return stub; +} diff --git a/packages/docs-next/src/openapi/samples-note.test.tsx b/packages/docs-next/src/openapi/samples-note.test.tsx new file mode 100644 index 00000000..6b00b478 --- /dev/null +++ b/packages/docs-next/src/openapi/samples-note.test.tsx @@ -0,0 +1,27 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { renderToFragment } from "../../test/dom.js"; +import { SamplesNote, SetupHrefProvider } from "./samples-note.js"; + +test("the note names both variables and links to the setup section it is given", () => { + const note = renderToFragment( + <SetupHrefProvider href="/beta-docs/reference/api/#set-up-your-environment"> + <SamplesNote /> + </SetupHrefProvider>, + ); + assert.deepEqual( + [...note.querySelectorAll("code")].map((code) => code.textContent), + ["CODER_URL", "CODER_SESSION_TOKEN"], + ); + assert.equal( + note.querySelector("a")?.getAttribute("href"), + "/beta-docs/reference/api/#set-up-your-environment", + ); + assert.doesNotMatch(note.textContent ?? "", /coder login|v2\.31/); +}); + +test("without a setup link the note has no link", () => { + const note = renderToFragment(<SamplesNote />); + assert.equal(note.querySelector("a"), null); + assert.match(note.textContent ?? "", /CODER_SESSION_TOKEN\.$/); +}); diff --git a/packages/docs-next/src/openapi/samples-note.tsx b/packages/docs-next/src/openapi/samples-note.tsx new file mode 100644 index 00000000..2684c721 --- /dev/null +++ b/packages/docs-next/src/openapi/samples-note.tsx @@ -0,0 +1,28 @@ +"use client"; + +import { DEPLOYMENT_URL_ENV, SESSION_TOKEN_ENV } from "@coder/docs-config/client"; +import { type ReactNode, createContext, useContext } from "react"; + +const SetupHref = createContext<string | undefined>(undefined); + +/** Gives the operation page's samples note the base-path-aware link to the landing page's setup section. */ +export function SetupHrefProvider({ href, children }: { href?: string; children: ReactNode }) { + return <SetupHref value={href}>{children}</SetupHref>; +} + +/** The line above the code samples naming the environment variables they read. */ +export function SamplesNote() { + const href = useContext(SetupHref); + return ( + <p className="mb-2 text-sm text-fd-muted-foreground"> + The samples read <code>{DEPLOYMENT_URL_ENV}</code> and <code>{SESSION_TOKEN_ENV}</code> + {href ? ( + <> + : <a href={href}>set up your environment</a>. + </> + ) : ( + "." + )} + </p> + ); +} diff --git a/packages/docs-next/src/openapi/schema-filter.tsx b/packages/docs-next/src/openapi/schema-filter.tsx new file mode 100644 index 00000000..64452ec5 --- /dev/null +++ b/packages/docs-next/src/openapi/schema-filter.tsx @@ -0,0 +1,65 @@ +"use client"; + +import { useEffect, useId, useRef, useState } from "react"; + +/** + * Narrows the server-rendered schema tables around it by name. The tables + * stay complete without JavaScript; this only hides rows, and opens the + * groups that match while a filter is set. + */ +export function SchemaFilter({ total }: { total: number }) { + const id = useId(); + const ref = useRef<HTMLDivElement>(null); + const [query, setQuery] = useState(""); + const [matches, setMatches] = useState(total); + const openBeforeFilter = useRef<Map<HTMLDetailsElement, boolean> | undefined>(undefined); + + useEffect(() => { + const container = ref.current?.closest("[data-schemas]"); + if (!container) return; + const needle = query.trim().toLowerCase(); + const groups = [ + ...container.querySelectorAll<HTMLDetailsElement>("details[data-schema-group]"), + ]; + if (needle && !openBeforeFilter.current) { + openBeforeFilter.current = new Map(groups.map((group) => [group, group.open])); + } + let count = 0; + for (const group of groups) { + let groupMatches = 0; + for (const row of group.querySelectorAll<HTMLTableRowElement>("tr[data-schema-name]")) { + const match = row.dataset.schemaName?.includes(needle) ?? false; + row.hidden = !match; + if (match) groupMatches++; + } + count += groupMatches; + if (needle) { + group.hidden = groupMatches === 0; + group.open = groupMatches > 0; + } else { + group.hidden = false; + group.open = openBeforeFilter.current?.get(group) ?? group.open; + } + } + if (!needle) openBeforeFilter.current = undefined; + setMatches(count); + }, [query]); + + return ( + <div ref={ref} className="coder-schema-filter not-prose"> + <label htmlFor={id}>Filter schemas by name</label> + <input + id={id} + type="search" + autoComplete="off" + spellCheck={false} + value={query} + onChange={(event) => setQuery(event.target.value)} + /> + <p aria-live="polite">{`${matches} of ${total} schemas`}</p> + <p data-schema-empty hidden={matches !== 0}> + {`No schema name contains “${query.trim()}”.`} + </p> + </div> + ); +} diff --git a/packages/docs-next/src/openapi/schemas.test.tsx b/packages/docs-next/src/openapi/schemas.test.tsx new file mode 100644 index 00000000..5bc8f4b8 --- /dev/null +++ b/packages/docs-next/src/openapi/schemas.test.tsx @@ -0,0 +1,133 @@ +import assert from "node:assert/strict"; +import test, { type TestContext } from "node:test"; +import type { OpenApiSchemaRow } from "@coder/docs-config/client"; +import { mountClient, renderToFragment, typeInto } from "../../test/dom.js"; +import { createOpenApiRenderBody } from "./index.js"; +import { SchemaTables } from "./schemas.js"; + +const rows: OpenApiSchemaRow[] = [ + { + name: "codersdk.User", + operation: { title: "Get user", route: "reference/api/users/get-user" }, + }, + { name: "codersdk.UserStatus" }, + { name: "codersdk.Workspace", operation: { title: "List workspaces", route: "reference/api/w" } }, + { name: "agentsdk.Manifest", operation: { title: "Get manifest", route: "reference/api/m" } }, + { name: "wsproxysdk.RegisterRequest" }, + { name: "Response" }, +]; + +const hrefFor = (route: string) => `/beta-docs/${route}/`; +const page = () => <SchemaTables rows={rows} hrefFor={hrefFor} />; + +test("the server HTML holds every row, in closed package groups, with Other last", () => { + const html = renderToFragment(page()); + assert.deepEqual( + [...html.querySelectorAll("tbody tr td:first-child")].map((td) => td.textContent), + [ + "agentsdk.Manifest", + "codersdk.User", + "codersdk.UserStatus", + "codersdk.Workspace", + "wsproxysdk.RegisterRequest", + "Response", + ], + ); + const groups = [...html.querySelectorAll("details")]; + assert.deepEqual( + groups.map((details) => details.querySelector("summary")?.textContent), + ["agentsdk (1)", "codersdk (3)", "wsproxysdk (1)", "Other (1)"], + ); + assert.ok(groups.every((details) => !details.open)); + assert.equal( + html.querySelector('a[href="/beta-docs/reference/api/users/get-user/"]')?.textContent, + "Get user", + ); + const input = html.querySelector("input"); + assert.equal(input?.getAttribute("type"), "search"); + assert.equal( + html.querySelector(`label[for="${input?.id}"]`)?.textContent, + "Filter schemas by name", + ); + const count = html.querySelector('[aria-live="polite"]'); + assert.equal(count?.textContent, "6 of 6 schemas"); +}); + +async function mount(t: TestContext) { + const container = await mountClient(t, page(), { hydrate: true }); + const input = container.querySelector("input"); + assert.ok(input); + const type = (text: string) => typeInto(input, text); + const visibleRows = () => + [...container.querySelectorAll("tbody tr")] + .filter((tr) => !(tr as HTMLElement).hidden) + .map((tr) => tr.querySelector("td")?.textContent); + const groups = () => + [...container.querySelectorAll("details")].map((details) => ({ + name: details.querySelector("summary")?.textContent, + open: details.open, + hidden: details.hidden, + })); + const count = () => container.querySelector('[aria-live="polite"]')?.textContent; + const empty = () => container.querySelector("[data-schema-empty]") as HTMLElement | null; + return { type, visibleRows, groups, count, empty }; +} + +test("typing narrows the rows by name, case-insensitively, and updates the count", async (t) => { + const view = await mount(t); + await view.type("USER"); + assert.deepEqual(view.visibleRows(), ["codersdk.User", "codersdk.UserStatus"]); + assert.equal(view.count(), "2 of 6 schemas"); + assert.equal(view.empty()?.hidden, true); +}); + +test("a filter opens the groups with a match and hides the rest; clearing it restores them", async (t) => { + const view = await mount(t); + await view.type("request"); + assert.deepEqual(view.groups(), [ + { name: "agentsdk (1)", open: false, hidden: true }, + { name: "codersdk (3)", open: false, hidden: true }, + { name: "wsproxysdk (1)", open: true, hidden: false }, + { name: "Other (1)", open: false, hidden: true }, + ]); + await view.type(""); + assert.ok(view.groups().every((group) => !group.open && !group.hidden)); + assert.equal(view.visibleRows().length, 6); + assert.equal(view.count(), "6 of 6 schemas"); +}); + +test("no match shows the empty state and a zero count", async (t) => { + const view = await mount(t); + await view.type("nothing-like-this"); + assert.equal(view.count(), "0 of 6 schemas"); + assert.equal(view.empty()?.hidden, false); + assert.match(view.empty()?.textContent ?? "", /No schema name contains “nothing-like-this”/); +}); + +test("a group a reader opened stays open after a filter is cleared", async (t) => { + const view = await mount(t); + const details = document.querySelectorAll("details")[0] as HTMLDetailsElement; + details.open = true; + await view.type("user"); + await view.type(""); + assert.equal(view.groups()[0]?.open, true); + assert.equal(view.groups()[1]?.open, false); +}); + +test("the schemas route renders the grouped tables in place of its Markdown table, and keeps the redirect", async () => { + const renderBody = createOpenApiRenderBody(async () => ({ + document: {}, + operations: {}, + anchors: { "reference/api/schemas": { codersdkuser: "reference/api/users/get-user" } }, + landing: { route: "reference/api", setupId: "set-up-your-environment", sections: [] }, + schemas: { route: "reference/api/schemas", rows }, + })); + const result = await renderBody({ + versionId: undefined, + slugs: ["reference", "api", "schemas"], + hrefFor, + }); + const body = renderToFragment(result?.replace); + assert.equal(body.querySelectorAll("tbody tr").length, rows.length); + assert.ok(result?.after, "the old-anchor redirect still renders"); +}); diff --git a/packages/docs-next/src/openapi/schemas.tsx b/packages/docs-next/src/openapi/schemas.tsx new file mode 100644 index 00000000..46acdaf3 --- /dev/null +++ b/packages/docs-next/src/openapi/schemas.tsx @@ -0,0 +1,71 @@ +import type { OpenApiSchemaRow } from "@coder/docs-config/client"; +import { SchemaFilter } from "./schema-filter.js"; + +const OTHER = "Other"; + +function groupsOf(rows: OpenApiSchemaRow[]): { name: string; rows: OpenApiSchemaRow[] }[] { + const byPackage = new Map<string, OpenApiSchemaRow[]>(); + for (const row of rows) { + const dot = row.name.indexOf("."); + const name = dot > 0 ? row.name.slice(0, dot) : OTHER; + let group = byPackage.get(name); + if (!group) byPackage.set(name, (group = [])); + group.push(row); + } + const names = [...byPackage.keys()] + .filter((name) => name !== OTHER) + .sort((a, b) => a.localeCompare(b)); + if (byPackage.has(OTHER)) names.push(OTHER); + return names.map((name) => ({ name, rows: byPackage.get(name) ?? [] })); +} + +/** + * The schemas page's table, one collapsed `<details>` per package prefix, with + * a filter above it. Every row is in the server HTML, so the page works the + * same without JavaScript. + */ +export function SchemaTables({ + rows, + hrefFor, +}: { + rows: OpenApiSchemaRow[]; + hrefFor: (route: string) => string | undefined; +}) { + return ( + <div data-schemas className="coder-schemas"> + <SchemaFilter total={rows.length} /> + {groupsOf(rows).map((group) => ( + <details key={group.name} data-schema-group className="coder-schema-group"> + <summary>{`${group.name} (${group.rows.length})`}</summary> + <table> + <thead> + <tr> + <th scope="col">Schema</th> + <th scope="col">Shown on</th> + </tr> + </thead> + <tbody> + {group.rows.map((row) => { + const href = row.operation && hrefFor(row.operation.route); + return ( + <tr key={row.name} data-schema-name={row.name.toLowerCase()}> + <td> + <code>{row.name}</code> + </td> + <td> + {row.operation && href ? ( + <a href={href}>{row.operation.title}</a> + ) : ( + "Not used by a documented endpoint" + )} + </td> + </tr> + ); + })} + </tbody> + </table> + </details> + ))} + </div> + ); +} diff --git a/packages/docs-next/src/openapi/tree.ts b/packages/docs-next/src/openapi/tree.ts new file mode 100644 index 00000000..02d3d8db --- /dev/null +++ b/packages/docs-next/src/openapi/tree.ts @@ -0,0 +1,25 @@ +import type * as PageTree from "fumadocs-core/page-tree"; + +// The same tree object for every render, so the flight payload dedupes it like the uncollapsed one. +const collapsed = new WeakMap<PageTree.Root, Map<string, PageTree.Root>>(); + +/** + * The page tree with each folder under `urlPrefix` reduced to its index page, + * so pages outside the API reference don't carry hundreds of operation links + * in their sidebar payload. Folders without an index page are left as they are. + */ +export function collapseFoldersUnder(tree: PageTree.Root, urlPrefix: string): PageTree.Root { + let byPrefix = collapsed.get(tree); + if (!byPrefix) collapsed.set(tree, (byPrefix = new Map())); + const cached = byPrefix.get(urlPrefix); + if (cached) return cached; + const visit = (nodes: PageTree.Node[]): PageTree.Node[] => + nodes.map((node) => { + if (node.type !== "folder") return node; + if (node.index && node.index.url.startsWith(urlPrefix)) return node.index; + return { ...node, children: visit(node.children) }; + }); + const result = { ...tree, children: visit(tree.children) }; + byPrefix.set(urlPrefix, result); + return result; +} diff --git a/packages/docs-next/src/page.tsx b/packages/docs-next/src/page.tsx index 9bc94115..83c44f1f 100644 --- a/packages/docs-next/src/page.tsx +++ b/packages/docs-next/src/page.tsx @@ -8,7 +8,8 @@ import { markdownTwinUrl } from "./llms.js"; import { type OpenGraphOptions, openGraphMetadata, sectionBadge } from "./open-graph.js"; import type { PageActionsOption } from "./page-actions.js"; import { pageNeighbours } from "./slim-tree.js"; -import type { DocsSource } from "./types.js"; +import { resolveBody } from "./render-body.js"; +import type { DocsSource, RenderBody } from "./types.js"; // The route renders an optional catch-all (`[[...slug]]`), so `slug` is // `undefined` at the index and a path-segment array elsewhere. A Next app reads @@ -46,6 +47,8 @@ export interface DocsPageOptions { * what an export whose readers cannot reach the image generator wants. */ openGraph?: OpenGraphOptions; + /** Replaces or extends a page's rendered body; refer to `RenderBody`. */ + renderBody?: RenderBody; } export function createDocsPage(source: DocsSource, options: DocsPageOptions = {}) { @@ -55,10 +58,27 @@ export function createDocsPage(source: DocsSource, options: DocsPageOptions = {} if (!page) notFound(); const MDX = page.data.body; + const { body, data } = await resolveBody( + options.renderBody, + source, + undefined, + page.slugs, + options.assetBasePath, + <MDX + components={getMDXComponents( + { + // Resolve relative inter-doc links against the current page. + a: createRelativeLink(source, page), + }, + { assetBasePath: options.assetBasePath }, + )} + />, + page.data, + ); return ( <DocsArticle - page={page.data} + page={data} markdownUrl={markdownTwinUrl([], page.slugs, options.assetBasePath)} pageActions={options.pageActions} versionBase="" @@ -66,15 +86,7 @@ export function createDocsPage(source: DocsSource, options: DocsPageOptions = {} editLink={options.editLink} neighbours={pageNeighbours(source.pageTree, page.url)} > - <MDX - components={getMDXComponents( - { - // Resolve relative inter-doc links against the current page. - a: createRelativeLink(source, page), - }, - { assetBasePath: options.assetBasePath }, - )} - /> + {body} </DocsArticle> ); } diff --git a/packages/docs-next/src/render-body.test.tsx b/packages/docs-next/src/render-body.test.tsx new file mode 100644 index 00000000..d65ddc51 --- /dev/null +++ b/packages/docs-next/src/render-body.test.tsx @@ -0,0 +1,46 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { renderToFragment } from "../test/dom.js"; +import { docsSource, pageFile } from "../test/source.js"; +import { resolveBody } from "./render-body.js"; + +const source = docsSource([pageFile("reference/api/index.md"), pageFile("reference/api/users.md")]); +const data: { toc: { title: string; url: string; depth: number }[]; full?: boolean } = { + toc: [{ title: "Quickstart", url: "#quickstart", depth: 2 }], +}; + +test("headings a hook renders after the body join the end of the page's TOC", async () => { + const { body, data: out } = await resolveBody( + async ({ hrefFor }) => ({ + after: <h2 id="users">{hrefFor("reference/api/users")}</h2>, + toc: [{ title: "Users", url: "#users", depth: 2 }], + }), + source, + undefined, + ["reference", "api"], + "/beta-docs", + <p>markdown</p>, + data, + ); + assert.deepEqual( + out.toc.map((item) => item.url), + ["#quickstart", "#users"], + ); + assert.equal(out.full, undefined); + const page = renderToFragment(body); + assert.equal(page.querySelector("p")?.textContent, "markdown"); + assert.equal(page.querySelector("h2")?.textContent, "/beta-docs/reference/api/users/"); +}); + +test("a page no hook touches keeps its own data", async () => { + const result = await resolveBody( + async () => undefined, + source, + undefined, + ["reference", "api"], + undefined, + <p>markdown</p>, + data, + ); + assert.equal(result.data, data); +}); diff --git a/packages/docs-next/src/render-body.tsx b/packages/docs-next/src/render-body.tsx new file mode 100644 index 00000000..93b17042 --- /dev/null +++ b/packages/docs-next/src/render-body.tsx @@ -0,0 +1,38 @@ +import type { TableOfContents } from "fumadocs-core/toc"; +import type { ReactNode } from "react"; +import type { DocsSource, RenderBody } from "./types.js"; +import { normalizeBasePath, pageHref } from "./version-routing.js"; + +/** The page body after an optional `renderBody` hook has had its say, with the page data it changes. */ +export async function resolveBody<Data extends { toc: TableOfContents; full?: boolean }>( + renderBody: RenderBody | undefined, + source: DocsSource, + versionId: string | undefined, + slugs: string[], + assetBasePath: string | undefined, + markdown: ReactNode, + data: Data, +): Promise<{ body: ReactNode; data: Data }> { + const custom = await renderBody?.({ + versionId, + slugs, + hrefFor: (route) => { + const url = source.getPage(route.split("/"))?.url; + return url === undefined ? undefined : pageHref(normalizeBasePath(assetBasePath), url); + }, + }); + if (!custom) return { body: markdown, data }; + return { + body: ( + <> + {custom.replace ?? markdown} + {custom.after} + </> + ), + data: { + ...data, + ...(custom.full ? { full: true } : {}), + ...(custom.toc ? { toc: [...data.toc, ...custom.toc] } : {}), + }, + }; +} diff --git a/packages/docs-next/src/search.ts b/packages/docs-next/src/search.ts index 3545142e..21bd71bc 100644 --- a/packages/docs-next/src/search.ts +++ b/packages/docs-next/src/search.ts @@ -1,4 +1,4 @@ -import { stripCodeTitle } from "@coder/docs-config"; +import { API_REFERENCE_DIR, isApiReferenceSlug, stripCodeTitle } from "@coder/docs-config"; import type { StructuredData } from "fumadocs-core/mdx-plugins"; import { findPath } from "fumadocs-core/page-tree"; import { createFromSource } from "fumadocs-core/search/server"; @@ -189,9 +189,9 @@ async function loadToc(data: IndexablePageData): Promise<TableOfContents> { throw new Error("Cannot find the table of contents of an API reference page."); } -/** The generated REST API reference pages under `reference/api/`, not its hand-written index. */ +/** The generated REST API reference pages, not its hand-written index. */ function isApiReferencePage(slugs: readonly string[]): boolean { - return slugs.length > 2 && slugs[0] === "reference" && slugs[1] === "api"; + return isApiReferenceSlug(slugs) && slugs.join("/") !== API_REFERENCE_DIR; } const API_ROUTE = /^`?(?:GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) \/\S*`?$/; diff --git a/packages/docs-next/src/shell.tsx b/packages/docs-next/src/shell.tsx index 20038f64..f5edefbb 100644 --- a/packages/docs-next/src/shell.tsx +++ b/packages/docs-next/src/shell.tsx @@ -1,4 +1,5 @@ import type { DocsProduct } from "@coder/docs-config/client"; +import type * as PageTree from "fumadocs-core/page-tree"; import { Copyright, type DocsContextSource } from "@coder/docs-ui"; import { DocsLayout } from "fumadocs-ui/layouts/docs"; import type { BaseLayoutProps } from "fumadocs-ui/layouts/shared"; @@ -55,8 +56,11 @@ export function DocsShell({ sidebarFooter, context, providerOptions, + tree, }: { source: DocsSource; + /** The sidebar tree, when it differs from the source's own page tree. */ + tree?: PageTree.Root; children: ReactNode; options?: Partial<BaseLayoutProps>; /** @@ -149,7 +153,7 @@ export function DocsShell({ <div data-top-banner="">{topBanner}</div> <SidebarLandmarks /> <DocsLayout - tree={slimPageTree(source.pageTree)} + tree={slimPageTree(tree ?? source.pageTree)} tabs={false} sidebar={{ banner, diff --git a/packages/docs-next/src/types.ts b/packages/docs-next/src/types.ts index 6f1b56f8..25bae6c9 100644 --- a/packages/docs-next/src/types.ts +++ b/packages/docs-next/src/types.ts @@ -1,4 +1,5 @@ import type { LoaderOutput, Meta, Page, PageData } from "fumadocs-core/source"; +import type { ReactNode } from "react"; import type { TableOfContents } from "fumadocs-core/toc"; import type { MDXContent } from "mdx/types"; @@ -96,3 +97,25 @@ export type DocsSource = Omit< // oxlint-disable-next-line typescript/no-explicit-any -- deliberate; see the docstring. resolveHref: (href: string, parent?: any) => string; }; + +/** What a page-body hook is told about the page it may render. */ +export interface RenderBodyContext { + /** The version being rendered; `undefined` under the single-version factory. */ + versionId: string | undefined; + /** The page's slugs within its version. */ + slugs: string[]; + /** The href of another page of the same version, base path included. */ + hrefFor: (route: string) => string | undefined; +} + +/** + * Replaces a page's rendered Markdown body (`replace`) or adds after it + * (`after`); `full` widens the page and drops its table of contents, and + * `toc` adds the headings `after` renders to it. `undefined` leaves the page + * as it is. + */ +export type RenderBody = ( + context: RenderBodyContext, +) => Promise< + { replace?: ReactNode; after?: ReactNode; full?: boolean; toc?: TableOfContents } | undefined +>; diff --git a/packages/docs-next/src/version-routing.test.ts b/packages/docs-next/src/version-routing.test.ts index 78ffa4c9..873d275d 100644 --- a/packages/docs-next/src/version-routing.test.ts +++ b/packages/docs-next/src/version-routing.test.ts @@ -3,6 +3,7 @@ import test from "node:test"; import type { DocVersion } from "@coder/docs-config"; import { normalizeBasePath, + pageHref, resolveSlug, switchHref, versionBaseUrl, @@ -220,3 +221,9 @@ test("versionSwitcherOptions excludes hidden versions and flags the current one" assert.equal(options.find((o) => o.id === "2.19")?.href, "/v2.19/admin"); assert.equal(options.find((o) => o.id === "nick/preview")?.href, "/@nick/preview"); }); + +test("pageHref joins the base and the page URL with the trailing slash the exports serve", () => { + assert.equal(pageHref("", "/install"), "/install/"); + assert.equal(pageHref("/beta-docs", "/install/"), "/beta-docs/install/"); + assert.equal(pageHref("https://coder.com/docs", "/"), "https://coder.com/docs/"); +}); diff --git a/packages/docs-next/src/version-routing.ts b/packages/docs-next/src/version-routing.ts index 10e896c6..20f6dea4 100644 --- a/packages/docs-next/src/version-routing.ts +++ b/packages/docs-next/src/version-routing.ts @@ -233,3 +233,13 @@ export function versionSwitcherOptions( return option; }); } + +/** + * A page's link as the exports serve it: `base` and the loader's URL, with + * the trailing slash both exports are built with (`trailingSlash: true`), so + * the link costs no 308. + */ +export function pageHref(base: string, url: string): string { + const href = `${base}${url}`; + return href.endsWith("/") ? href : `${href}/`; +} diff --git a/packages/docs-next/src/versioned.tsx b/packages/docs-next/src/versioned.tsx index 92ae7da1..5c9e1618 100644 --- a/packages/docs-next/src/versioned.tsx +++ b/packages/docs-next/src/versioned.tsx @@ -9,7 +9,8 @@ import { markdownTwinUrl } from "./llms.js"; import { type OpenGraphOptions, openGraphMetadata, sectionBadge } from "./open-graph.js"; import type { PageActionsOption } from "./page-actions.js"; import { pageNeighbours } from "./slim-tree.js"; -import type { DocsSource } from "./types.js"; +import { resolveBody } from "./render-body.js"; +import type { DocsSource, RenderBody } from "./types.js"; import { resolveSlug, versionBaseUrl, @@ -62,6 +63,8 @@ export interface VersionedDocsOptions { source: (versionId: string) => DocsSource | undefined; /** Render mode; defaults to `static`. */ mode?: DocsRenderMode; + /** Replaces or extends a page's rendered body; refer to `RenderBody`. */ + renderBody?: RenderBody; } /** @@ -80,6 +83,7 @@ export function createVersionedDocs(options: VersionedDocsOptions) { pageActions, editLink, openGraph, + renderBody, } = options; function pick(slug: string[] | undefined) { @@ -97,9 +101,23 @@ export function createVersionedDocs(options: VersionedDocsOptions) { if (!found) notFound(); const MDX = found.page.data.body; + const { body, data } = await resolveBody( + renderBody, + found.source, + found.version.id, + found.page.slugs, + assetBasePath, + <MDX + components={getMDXComponents( + { a: createRelativeLink(found.source, found.page) }, + { assetBasePath }, + )} + />, + found.page.data, + ); return ( <DocsArticle - page={found.page.data} + page={data} markdownUrl={markdownTwinUrl(versionPrefix(found.version), found.page.slugs, assetBasePath)} pageActions={pageActions} versionBase={versionBaseUrl(found.version)} @@ -107,12 +125,7 @@ export function createVersionedDocs(options: VersionedDocsOptions) { editLink={editLink} neighbours={pageNeighbours(found.source.pageTree, found.page.url)} > - <MDX - components={getMDXComponents( - { a: createRelativeLink(found.source, found.page) }, - { assetBasePath }, - )} - /> + {body} </DocsArticle> ); } diff --git a/packages/docs-next/test/dom.ts b/packages/docs-next/test/dom.ts index 78158e82..1f9aabcb 100644 --- a/packages/docs-next/test/dom.ts +++ b/packages/docs-next/test/dom.ts @@ -1,5 +1,7 @@ -import type { ReactNode } from "react"; -import { renderToStaticMarkup } from "react-dom/server"; +import type { TestContext } from "node:test"; +import { act, type ReactNode } from "react"; +import { createRoot, hydrateRoot, type Root } from "react-dom/client"; +import { renderToStaticMarkup, renderToString } from "react-dom/server"; // Parsed by the jsdom that test/jsdom-setup.mjs installs, so tests query the DOM instead of matching markup as text. export function renderToFragment(node: ReactNode): DocumentFragment { @@ -7,3 +9,39 @@ export function renderToFragment(node: ReactNode): DocumentFragment { template.innerHTML = renderToStaticMarkup(node); return template.content; } + +/** + * Mounts `node` in a container in the document, rendered on the client or, + * with `hydrate`, server-rendered and then hydrated as a page would be. + * Unmounted and removed when the test ends. + */ +export async function mountClient( + t: TestContext, + node: ReactNode, + { hydrate = false }: { hydrate?: boolean } = {}, +): Promise<HTMLElement> { + const container = document.body.appendChild(document.createElement("div")); + let root: Root | undefined; + if (hydrate) { + container.innerHTML = renderToString(node); + await act(async () => { + root = hydrateRoot(container, node); + }); + } else { + root = createRoot(container); + await act(async () => root?.render(node)); + } + t.after(async () => { + await act(async () => root?.unmount()); + container.remove(); + }); + return container; +} + +/** Types `text` into a controlled input the way a reader does: React sees the value change. */ +export async function typeInto(input: HTMLInputElement, text: string): Promise<void> { + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, text); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); +} diff --git a/packages/docs-sources/src/api-document.test.ts b/packages/docs-sources/src/api-document.test.ts new file mode 100644 index 00000000..a2262de1 --- /dev/null +++ b/packages/docs-sources/src/api-document.test.ts @@ -0,0 +1,42 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { test } from "node:test"; +import { SWAGGER_PATH, readApiDocument } from "./api-document.js"; + +async function checkout() { + const root = await mkdtemp(path.join(tmpdir(), "openapi-source-")); + await mkdir(path.join(root, "docs")); + await mkdir(path.join(root, "coderd", "apidoc"), { recursive: true }); + return root; +} + +test("reads and parses the API document, and nothing when there is none", async () => { + const root = await checkout(); + assert.equal(await readApiDocument(root, SWAGGER_PATH), undefined); + await writeFile(path.join(root, SWAGGER_PATH), '{"swagger":"2.0"}'); + assert.deepEqual(await readApiDocument(root, SWAGGER_PATH), { swagger: "2.0" }); +}); + +test("a symlinked API document is rejected and its target never surfaces", async () => { + const root = await checkout(); + const outside = await mkdtemp(path.join(tmpdir(), "openapi-source-secret-")); + await writeFile(path.join(outside, "secret.json"), '{"secret":"do-not-leak"}'); + await symlink(path.join(outside, "secret.json"), path.join(root, SWAGGER_PATH)); + await assert.rejects(readApiDocument(root, SWAGGER_PATH), (error: Error) => { + assert.match(error.message, /symbolic link/); + assert.doesNotMatch(error.message, /do-not-leak/); + return true; + }); +}); + +test("invalid JSON is reported without the file's content", async () => { + const root = await checkout(); + await writeFile(path.join(root, SWAGGER_PATH), "not json do-not-leak"); + await assert.rejects(readApiDocument(root, SWAGGER_PATH), (error: Error) => { + assert.match(error.message, /is not valid JSON/); + assert.doesNotMatch(error.message, /do-not-leak/); + return true; + }); +}); diff --git a/packages/docs-sources/src/api-document.ts b/packages/docs-sources/src/api-document.ts new file mode 100644 index 00000000..9e0f6ab6 --- /dev/null +++ b/packages/docs-sources/src/api-document.ts @@ -0,0 +1,24 @@ +import { readContainedFile } from "./contained-file.js"; +import { DEFAULT_MAX_FILE_BYTES } from "./read-tree.js"; + +/** Where coder/coder keeps the Swagger 2.0 document the REST API reference is built from. */ +export const SWAGGER_PATH = "coderd/apidoc/swagger.json"; + +/** + * The JSON document at `relPath` in a checkout, or undefined when there is + * none. Read with the docs tree's own guarantees: no symbolic links, a + * regular file under the per-file cap, inside the checkout. + */ +export async function readApiDocument( + checkout: string, + relPath: string, + maxBytes: number = DEFAULT_MAX_FILE_BYTES, +): Promise<unknown> { + const text = await readContainedFile(checkout, relPath, maxBytes); + if (text === undefined) return undefined; + try { + return JSON.parse(text); + } catch { + throw new Error(`@coder/docs-sources: ${relPath} is not valid JSON`); + } +} diff --git a/packages/docs-sources/src/contained-file.test.ts b/packages/docs-sources/src/contained-file.test.ts new file mode 100644 index 00000000..9408a0f3 --- /dev/null +++ b/packages/docs-sources/src/contained-file.test.ts @@ -0,0 +1,50 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { test } from "node:test"; +import { readContainedFile } from "./contained-file.js"; + +async function checkout() { + const root = await mkdtemp(path.join(tmpdir(), "contained-file-")); + await mkdir(path.join(root, "coderd", "apidoc"), { recursive: true }); + return root; +} + +test("reads a regular file inside the checkout", async () => { + const root = await checkout(); + await writeFile(path.join(root, "coderd", "apidoc", "swagger.json"), "{}"); + assert.equal(await readContainedFile(root, "coderd/apidoc/swagger.json"), "{}"); +}); + +test("a missing file is undefined", async () => { + const root = await checkout(); + assert.equal(await readContainedFile(root, "coderd/apidoc/swagger.json"), undefined); +}); + +test("rejects a symlinked file without reading the target", async () => { + const root = await checkout(); + const outside = await mkdtemp(path.join(tmpdir(), "contained-file-secret-")); + await writeFile(path.join(outside, "secret"), "top secret"); + await symlink(path.join(outside, "secret"), path.join(root, "coderd", "apidoc", "swagger.json")); + await assert.rejects(readContainedFile(root, "coderd/apidoc/swagger.json"), (error: Error) => { + assert.match(error.message, /symbolic link/); + assert.doesNotMatch(error.message, /top secret/); + return true; + }); +}); + +test("rejects a symlinked directory on the way", async () => { + const root = await checkout(); + const outside = await mkdtemp(path.join(tmpdir(), "contained-file-dir-")); + await writeFile(path.join(outside, "swagger.json"), "{}"); + await symlink(outside, path.join(root, "coderd", "linked")); + await assert.rejects(readContainedFile(root, "coderd/linked/swagger.json"), /symbolic link/); +}); + +test("rejects an oversized file and a path that climbs out", async () => { + const root = await checkout(); + await writeFile(path.join(root, "coderd", "apidoc", "swagger.json"), "x".repeat(20)); + await assert.rejects(readContainedFile(root, "coderd/apidoc/swagger.json", 10), /per-file limit/); + await assert.rejects(readContainedFile(root, "../etc/passwd"), /inside the checkout/); +}); diff --git a/packages/docs-sources/src/contained-file.ts b/packages/docs-sources/src/contained-file.ts new file mode 100644 index 00000000..75bfb40b --- /dev/null +++ b/packages/docs-sources/src/contained-file.ts @@ -0,0 +1,54 @@ +import { lstat, readFile, realpath } from "node:fs/promises"; +import path from "node:path"; +import { DEFAULT_MAX_FILE_BYTES } from "./read-tree.js"; + +/** + * Reads one file of a checkout by its path relative to the checkout root, + * with the same guarantees the tree walk gives the docs tree: no symbolic + * link anywhere from the root down, a regular file, under the per-file size + * cap, and still inside the root once resolved. Returns `undefined` when the + * file does not exist. Errors name the path, never the content. + */ +export async function readContainedFile( + root: string, + relPath: string, + maxBytes: number = DEFAULT_MAX_FILE_BYTES, +): Promise<string | undefined> { + if (path.isAbsolute(relPath) || relPath.split(/[\\/]/).includes("..")) { + throw new Error(`@coder/docs-sources: ${relPath} must be a path inside the checkout`); + } + const rootStat = await lstat(root); + if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) { + throw new Error(`@coder/docs-sources: ${root} is not a real directory`); + } + let current = root; + const segments = relPath.split(/[\\/]/).filter(Boolean); + for (const [index, segment] of segments.entries()) { + current = path.join(current, segment); + let info; + try { + info = await lstat(current); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; + throw error; + } + if (info.isSymbolicLink()) { + throw new Error(`@coder/docs-sources: ${relPath} passes through a symbolic link`); + } + const last = index === segments.length - 1; + if (last ? !info.isFile() : !info.isDirectory()) { + throw new Error(`@coder/docs-sources: ${relPath} is not a regular file`); + } + if (last && info.size > maxBytes) { + throw new Error( + `@coder/docs-sources: ${relPath} is ${info.size} bytes, over the ${maxBytes}-byte per-file limit`, + ); + } + } + const realRoot = await realpath(root); + const realFile = await realpath(current); + if (!realFile.startsWith(`${realRoot}${path.sep}`)) { + throw new Error(`@coder/docs-sources: ${relPath} resolves outside the checkout`); + } + return readFile(realFile, "utf8"); +} diff --git a/packages/docs-sources/src/git-refs.test.ts b/packages/docs-sources/src/git-refs.test.ts index 7f5d7c73..c212b5ca 100644 --- a/packages/docs-sources/src/git-refs.test.ts +++ b/packages/docs-sources/src/git-refs.test.ts @@ -300,6 +300,49 @@ test("createGitRefsProvider applies each version's manifest policy", async () => await assert.rejects(() => provider.loadVersion(living), /invalid manifest\.json/); }); +test("createGitRefsProvider reads the API document from each version's own commit", async () => { + await git(repo, ["checkout", "-q", "preview"]); + await mkdir(path.join(repo, "coderd", "apidoc"), { recursive: true }); + await writeFile(path.join(repo, "coderd", "apidoc", "swagger.json"), '{"swagger":"2.0"}'); + await git(repo, ["add", "-A"]); + await git(repo, ["commit", "-m", "swagger"]); + await git(repo, ["checkout", "-q", "main"]); + const provider = createGitRefsProvider({ + repo, + versions, + cacheDir, + apiDocument: "coderd/apidoc/swagger.json", + }); + assert.deepEqual((await provider.loadVersion(versions[1] as DocVersion)).apiDocument, { + swagger: "2.0", + }); + const tagged = await provider.loadVersion(versions[0] as DocVersion); + assert.equal("apiDocument" in tagged, false); + const unasked = createGitRefsProvider({ repo, versions, cacheDir }); + assert.equal("apiDocument" in (await unasked.loadVersion(versions[1] as DocVersion)), false); +}); + +test("createGitRefsProvider refuses a committed symlink as the API document", async () => { + const secret = path.join(tmp, "secret.json"); + await writeFile(secret, '{"secret":"do-not-leak"}'); + await mkdir(path.join(repo, "coderd", "apidoc"), { recursive: true }); + await symlink(secret, path.join(repo, "coderd", "apidoc", "swagger.json")); + await git(repo, ["add", "-A"]); + await git(repo, ["commit", "-m", "symlinked swagger"]); + const main: DocVersion = { id: "main", label: "main", ref: "main" }; + const provider = createGitRefsProvider({ + repo, + versions: [main], + cacheDir, + apiDocument: "coderd/apidoc/swagger.json", + }); + await assert.rejects(provider.loadVersion(main), (error: Error) => { + assert.match(error.message, /symbolic link/); + assert.doesNotMatch(error.message, /do-not-leak/); + return true; + }); +}); + test("createGitRefsProvider rejects an unresolvable ref", async () => { const provider = createGitRefsProvider({ repo, versions, cacheDir }); await assert.rejects(() => provider.loadVersion({ id: "x", label: "X", ref: "does-not-exist" })); diff --git a/packages/docs-sources/src/git-refs.ts b/packages/docs-sources/src/git-refs.ts index 408fcb3b..6fb7a623 100644 --- a/packages/docs-sources/src/git-refs.ts +++ b/packages/docs-sources/src/git-refs.ts @@ -4,6 +4,7 @@ import type { Dirent } from "node:fs"; import { cp, lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; +import { readApiDocument } from "./api-document.js"; import { type DocImage, type DocSource, @@ -62,6 +63,8 @@ export interface GitRefsProviderOptions extends Omit<ReadDocTreeOptions, "manife cacheDir: string; /** Subdirectory within the repo that holds the docs. Defaults to `docs`. */ docsPath?: string; + /** Repo-relative path of a JSON API document to read from each version's checkout onto its source as `apiDocument`. */ + apiDocument?: string; } /** @@ -153,7 +156,13 @@ interface GitCore { * worktree-based `loadVersion`. */ function createGitCore(options: Omit<GitRefsProviderOptions, "versions">): GitCore { - const { repo, cacheDir, docsPath = "docs", ...readOptions } = options; + const { + repo, + cacheDir, + docsPath = "docs", + apiDocument: apiDocumentPath, + ...readOptions + } = options; const worktreeRoot = path.join(cacheDir, STATE_DIR, "worktrees"); const imagesRoot = path.join(cacheDir, STATE_DIR, "images"); const maxFileBytes = readOptions.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES; @@ -208,7 +217,11 @@ function createGitCore(options: Omit<GitRefsProviderOptions, "versions">): GitCo maxFileBytes, maxTotalBytes, }); - return { ...source, images }; + const apiDocument = + apiDocumentPath === undefined + ? undefined + : await readApiDocument(worktree, apiDocumentPath, maxFileBytes); + return { ...source, images, ...(apiDocument === undefined ? {} : { apiDocument }) }; } finally { await runGit(["-C", cacheDir, "worktree", "remove", "--force", worktree]).catch( () => undefined, diff --git a/packages/docs-sources/src/index.ts b/packages/docs-sources/src/index.ts index 89bf6055..181f10e2 100644 --- a/packages/docs-sources/src/index.ts +++ b/packages/docs-sources/src/index.ts @@ -21,3 +21,5 @@ export { redactRepoUrl, } from "./git-refs.js"; export { readGitLastModified } from "./last-modified.js"; +export { readContainedFile } from "./contained-file.js"; +export { SWAGGER_PATH, readApiDocument } from "./api-document.js"; diff --git a/packages/docs-sources/src/local-tree.test.ts b/packages/docs-sources/src/local-tree.test.ts index 41733482..26d1e768 100644 --- a/packages/docs-sources/src/local-tree.test.ts +++ b/packages/docs-sources/src/local-tree.test.ts @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, test } from "node:test"; @@ -82,3 +82,24 @@ test("createLocalTreeProvider honours a per-version manifest override", async () ); assert.equal(source.manifestIssues?.length, 1); }); + +test("createLocalTreeProvider reads the API document from the checkout around the docs tree", async () => { + const checkout = await mkdtemp(path.join(os.tmpdir(), "docs-sources-checkout-")); + try { + const docsRoot = path.join(checkout, "docs"); + await mkdir(docsRoot); + await writeFile( + path.join(docsRoot, "manifest.json"), + JSON.stringify({ versions: ["main"], routes: [{ title: "Home", path: "./index.md" }] }), + ); + await writeFile(path.join(docsRoot, "index.md"), "# Home\n"); + const apiDocument = "coderd/apidoc/swagger.json"; + const provider = createLocalTreeProvider({ docsRoot, version, apiDocument }); + assert.equal("apiDocument" in (await provider.loadVersion(version)), false); + await mkdir(path.join(checkout, "coderd", "apidoc"), { recursive: true }); + await writeFile(path.join(checkout, apiDocument), '{"swagger":"2.0"}'); + assert.deepEqual((await provider.loadVersion(version)).apiDocument, { swagger: "2.0" }); + } finally { + await rm(checkout, { recursive: true, force: true }); + } +}); diff --git a/packages/docs-sources/src/local-tree.ts b/packages/docs-sources/src/local-tree.ts index a9c078cc..5babb7d0 100644 --- a/packages/docs-sources/src/local-tree.ts +++ b/packages/docs-sources/src/local-tree.ts @@ -4,6 +4,8 @@ import { type VersionsProvider, resolveVersionPipeline, } from "@coder/docs-config"; +import path from "node:path"; +import { readApiDocument } from "./api-document.js"; import { type ReadDocTreeOptions, readDocTree } from "./read-tree.js"; export interface LocalTreeProviderOptions extends Omit<ReadDocTreeOptions, "manifestMode"> { @@ -16,6 +18,8 @@ export interface LocalTreeProviderOptions extends Omit<ReadDocTreeOptions, "mani * of whatever `strict` value a caller passes to `syncDocSource`. */ version: DocVersion; + /** Path, relative to the directory holding `docsRoot`, of a JSON API document to read onto the source as `apiDocument`. */ + apiDocument?: string; } /** @@ -25,13 +29,22 @@ export interface LocalTreeProviderOptions extends Omit<ReadDocTreeOptions, "mani * so `loadVersion` ignores which version it is handed. */ export function createLocalTreeProvider(options: LocalTreeProviderOptions): VersionsProvider { - const { docsRoot, version, ...readOptions } = options; + const { docsRoot, version, apiDocument: apiDocumentPath, ...readOptions } = options; return { listVersions: async (): Promise<DocVersion[]> => [version], - loadVersion: async (): Promise<DocSource> => - readDocTree(docsRoot, { + loadVersion: async (): Promise<DocSource> => { + const source = await readDocTree(docsRoot, { ...readOptions, manifestMode: resolveVersionPipeline(version).manifest, - }), + }); + if (apiDocumentPath === undefined) return source; + const checkout = path.dirname(path.resolve(docsRoot)); + const apiDocument = await readApiDocument( + checkout, + apiDocumentPath, + readOptions.maxFileBytes, + ); + return apiDocument === undefined ? source : { ...source, apiDocument }; + }, }; } diff --git a/packages/docs-theme/scripts/brand.test.mjs b/packages/docs-theme/scripts/brand.test.mjs new file mode 100644 index 00000000..6b0603c5 --- /dev/null +++ b/packages/docs-theme/scripts/brand.test.mjs @@ -0,0 +1,32 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { test } from "node:test"; +import postcss from "postcss"; + +const brand = postcss.parse(await readFile(new URL("../src/brand.css", import.meta.url), "utf8")); + +const normalize = (selector) => selector.replace(/\s+/g, " "); + +test("an API page's example figures are dark code windows like every other code block", () => { + const backgrounds = []; + brand.walkRules((rule) => { + const selectors = rule.selectors.map(normalize); + if ( + !selectors.includes( + ".coder-api-page figure.shiki.bg-transparent:not(.not-fumadocs-codeblock *)", + ) + ) { + return; + } + rule.walkDecls("background-color", (decl) => backgrounds.push(decl.value)); + }); + assert.deepEqual(backgrounds, ["var(--docs-code-bg)"]); +}); + +test("the theme asks for no weight above Medium", () => { + const heavy = []; + brand.walkDecls("font-weight", (decl) => { + if (Number(decl.value) > 500) heavy.push(`${decl.parent.selector}: ${decl.value}`); + }); + assert.deepEqual(heavy, []); +}); diff --git a/packages/docs-theme/src/brand.css b/packages/docs-theme/src/brand.css index 773b37b5..cfa3a494 100644 --- a/packages/docs-theme/src/brand.css +++ b/packages/docs-theme/src/brand.css @@ -913,7 +913,7 @@ figure.shiki:not(.not-fumadocs-codeblock *) pre { min-width: 1.5rem; min-height: 1.5rem; border-radius: 0.375rem; - font-weight: 600; + font-weight: 500; color: var(--color-fd-muted-foreground); text-decoration: none; opacity: 0; @@ -945,6 +945,185 @@ figure.shiki:not(.not-fumadocs-codeblock *) pre { opacity: 1; } +/* fumadocs-openapi draws its example figure transparent on a light card, so the dark token colours need the dark window behind them. */ +.coder-api-page figure.shiki.bg-transparent:not(.not-fumadocs-codeblock *) { + background-color: var(--docs-code-bg); +} + +/* fumadocs-openapi's method badges (on API pages, the landing cards, the sidebar and the page footer) and links are -600/-400 shades that fall short of 4.5:1 (7:1 for More contrast). */ +:root:not(.dark) + :is(.coder-api-page, .coder-api-cards, #nd-sidebar, #nd-sidebar-mobile, #nd-page > footer) { + --color-green-600: oklch(45% 0.13 150); + --color-blue-600: oklch(48% 0.2 262); + --color-orange-600: oklch(50% 0.15 50); + --color-yellow-600: oklch(48% 0.11 85); + --color-red-600: oklch(50% 0.2 27); +} + +:root[data-contrast="more"]:not(.dark) + :is(.coder-api-page, .coder-api-cards, #nd-sidebar, #nd-sidebar-mobile, #nd-page > footer) { + --color-green-600: oklch(38% 0.1 150); + --color-blue-600: oklch(40% 0.18 262); + --color-orange-600: oklch(42% 0.13 50); + --color-yellow-600: oklch(40% 0.09 85); + --color-red-600: oklch(42% 0.17 27); +} + +:root[data-contrast="more"].dark + :is(.coder-api-page, .coder-api-cards, #nd-sidebar, #nd-sidebar-mobile, #nd-page > footer) { + --color-green-400: oklch(88% 0.15 150); + --color-blue-400: oklch(85% 0.1 262); + --color-orange-400: oklch(86% 0.1 60); + --color-yellow-400: oklch(90% 0.13 95); + --color-red-400: oklch(85% 0.1 25); +} + +@media (prefers-contrast: more) { + :root:not([data-contrast="standard"]):not(.dark) + :is(.coder-api-page, .coder-api-cards, #nd-sidebar, #nd-sidebar-mobile, #nd-page > footer) { + --color-green-600: oklch(38% 0.1 150); + --color-blue-600: oklch(40% 0.18 262); + --color-orange-600: oklch(42% 0.13 50); + --color-yellow-600: oklch(40% 0.09 85); + --color-red-600: oklch(42% 0.17 27); + } + + :root:not([data-contrast="standard"]).dark + :is(.coder-api-page, .coder-api-cards, #nd-sidebar, #nd-sidebar-mobile, #nd-page > footer) { + --color-green-400: oklch(88% 0.15 150); + --color-blue-400: oklch(85% 0.1 262); + --color-orange-400: oklch(86% 0.1 60); + --color-yellow-400: oklch(90% 0.13 95); + --color-red-400: oklch(85% 0.1 25); + } +} + +:root[data-contrast="more"].dark .coder-api-page .text-fd-primary { + color: hsl(213 94% 82%); +} + +@media (prefers-contrast: more) { + :root:not([data-contrast="standard"]).dark .coder-api-page .text-fd-primary { + color: hsl(213 94% 82%); + } +} + +/* The API landing page's cards are server-rendered, so each card's link is stretched over it. */ +.coder-api-cards > [data-card] { + position: relative; +} + +.coder-api-cards > [data-card]:hover { + background-color: color-mix(in oklab, var(--color-fd-accent) 80%, transparent); +} + +.coder-api-cards > [data-card] a { + color: inherit; + text-decoration: none; +} + +.coder-api-cards > [data-card] a::after { + content: ""; + position: absolute; + inset: 0; + border-radius: inherit; +} + +.coder-api-cards > [data-card] a:focus-visible { + outline: none; +} + +.coder-api-cards > [data-card]:has(a:focus-visible) { + outline: 2px solid var(--color-fd-ring); + outline-offset: 2px; +} + +.coder-schema-filter { + display: grid; + gap: 0.375rem; + margin-block: 1.5rem 1rem; +} + +.coder-schema-filter label { + font-weight: 500; +} + +.coder-schema-filter input { + min-height: 2.5rem; + max-width: 28rem; + padding-inline: 0.75rem; + border: 1px solid var(--docs-control-border); + border-radius: 0.5rem; + background-color: var(--color-fd-background); + color: var(--color-fd-foreground); +} + +.coder-schema-filter p { + margin: 0; + font-size: 0.875rem; + color: var(--color-fd-muted-foreground); +} + +.coder-schema-group > summary { + display: flex; + align-items: center; + min-height: 2.5rem; + cursor: pointer; + font-weight: 500; + list-style: none; +} + +.coder-schema-group > summary::-webkit-details-marker { + display: none; +} + +.coder-schema-group > summary::before { + content: ""; + flex-shrink: 0; + width: 0.5rem; + height: 0.5rem; + margin-inline: 0.25rem 0.75rem; + border-block-end: 2px solid currentColor; + border-inline-end: 2px solid currentColor; + transform: rotate(-45deg); +} + +.coder-schema-group[open] > summary::before { + transform: rotate(45deg); +} + +.coder-schema-group > table { + margin-top: 0.25rem; +} + +@media (pointer: coarse) { + .coder-schema-filter input, + .coder-schema-group > summary { + min-height: 2.75rem; + } +} + +/* The example column has a max height: the tab list keeps its size and the sample scrolls. */ +.coder-sample-tabs > [role="tablist"] { + flex-shrink: 0; +} + +.coder-sample-tabs > [role="tabpanel"][data-state="active"], +.coder-sample-tabs > [role="tabpanel"][data-state="active"] > figure { + display: flex; + flex-direction: column; + min-height: 0; +} + +.coder-sample-tabs > [role="tabpanel"] > figure > [role="region"] { + min-height: 0; +} + +/* gofmt and shfmt indent with tabs; four columns keeps the samples within the example column. */ +.coder-sample-tabs pre { + tab-size: 4; +} + [data-heading-anchor]:hover { color: var(--color-fd-foreground); } diff --git a/packages/docs-transforms/src/index.ts b/packages/docs-transforms/src/index.ts index 48599f56..77b8642a 100644 --- a/packages/docs-transforms/src/index.ts +++ b/packages/docs-transforms/src/index.ts @@ -22,10 +22,12 @@ export { selfCloseVoidElements, scanHtmlContent, scanMarkdownNesting, + MAX_MARKDOWN_NESTING_DEPTH, findIncludeDirectives, parseFrontmatter, FrontmatterError, extractTitle, + headingIds, rewriteTarget, rewriteContent, } from "./transform.js"; @@ -60,6 +62,8 @@ export { trimSlashes, trimTrailingSlashes } from "./slashes.js"; export { MAX_SEO_TITLE_CHARS, isSeoTitle } from "./seo-title.js"; +export { safeHeadingId } from "./mdx-plugins/remark-safe-heading-ids.js"; + export { isHtml } from "./mdx-plugins/mdast.js"; export type { MdastNode } from "./mdx-plugins/mdast.js"; diff --git a/packages/docs-transforms/src/transform.test.ts b/packages/docs-transforms/src/transform.test.ts index e09c09e9..f5a90322 100644 --- a/packages/docs-transforms/src/transform.test.ts +++ b/packages/docs-transforms/src/transform.test.ts @@ -7,6 +7,8 @@ import { escapeCurlyBraces, extractTitle, findIncludeDirectives, + headingIds, + MAX_MARKDOWN_NESTING_DEPTH, isIndexFile, lastSeg, normalizeAngleBrackets, @@ -1455,3 +1457,44 @@ test("scanMarkdownNesting stays linear on a long line of container markers", () assert.ok(elapsed(() => scanMarkdownNesting(md)) < LINEAR_BUDGET_MS, md.slice(0, 6)); } }); + +test("headingIds refuses a body nested past the cap instead of parsing it", () => { + const nested = (depth: number) => `${">".repeat(depth)} deep\n\n## Heading\n`; + assert.equal(headingIds(nested(MAX_MARKDOWN_NESTING_DEPTH)).length, 1); + assert.throws(() => headingIds(nested(MAX_MARKDOWN_NESTING_DEPTH + 1)), /nested 101 levels/); +}); + +test("headingIds gives each heading the id the synced page renders with", () => { + assert.deepEqual( + headingIds( + [ + "```md", + "## In a fence", + "```", + "", + "<div>", + "## In an HTML block", + "</div>", + "", + "## Use `coder` with [links](./x.md) ##", + "### An _emphasis_ heading", + " ## Indented", + "## Use <kbd>Ctrl</kbd> keys", + "## Step 1: Install", + "## Intro", + "## Intro", + "## __next data", + ].join("\n"), + ), + [ + { line: 8, depth: 2, id: "use-coder-with-links" }, + { line: 9, depth: 3, id: "an-emphasis-heading" }, + { line: 10, depth: 2, id: "indented" }, + { line: 11, depth: 2, id: "use-ctrl-keys" }, + { line: 12, depth: 2, id: "step-1-install" }, + { line: 13, depth: 2, id: "intro" }, + { line: 14, depth: 2, id: "intro-1" }, + { line: 15, depth: 2, id: "user-content-__next-data" }, + ], + ); +}); diff --git a/packages/docs-transforms/src/transform.ts b/packages/docs-transforms/src/transform.ts index 1cc0736b..0182f9b7 100644 --- a/packages/docs-transforms/src/transform.ts +++ b/packages/docs-transforms/src/transform.ts @@ -11,7 +11,13 @@ import { tagTerminator, } from "./mdx-plugins/html-delimiters.js"; import type { MdastNode } from "./mdx-plugins/mdast.js"; -import { classicHeadingText } from "./mdx-plugins/remark-classic-heading-ids.js"; +import { + classicHeadingId, + classicHeadingText, + remarkClassicHeadingIds, + visitHeadings, +} from "./mdx-plugins/remark-classic-heading-ids.js"; +import { safeHeadingId } from "./mdx-plugins/remark-safe-heading-ids.js"; import { trimSlashes, trimTrailingSlashes } from "./slashes.js"; // The asset-extension set (images and videos) comes from the shared @@ -1042,6 +1048,14 @@ function containerDepth(line: string): number { return lists > 0 ? depth + Math.floor(indent / 2) : depth; } +/** + * Maximum blockquote and list nesting depth allowed in one page. The real + * corpus nests a few levels; the Markdown parser takes minutes on a thousand + * and the compile overflows the stack, so deeper nesting fails before + * anything parses the page. + */ +export const MAX_MARKDOWN_NESTING_DEPTH = 100; + // Measure blockquote and list nesting line by line, outside fenced code and // raw HTML blocks, without parsing. A deeply nested container recurses in // every later stage (the Markdown parser takes minutes on it, then the @@ -1106,6 +1120,8 @@ export function parseFrontmatter(content: string): { * anything else against the file. */ tocDepthRaw?: unknown; + /** The raw `_openapi` frontmatter value, on the same terms; the sync validates it. */ + openapiRaw?: unknown; endLine: number; } { const none = { title: null, description: null, premiumCallout: null, endLine: 0 }; @@ -1141,6 +1157,7 @@ export function parseFrontmatter(content: string): { endLine, ...(obj.premium_callout !== undefined ? { premiumCalloutRaw: obj.premium_callout } : {}), ...(obj.toc_depth !== undefined ? { tocDepthRaw: obj.toc_depth } : {}), + ...(obj._openapi !== undefined ? { openapiRaw: obj._openapi } : {}), }; } @@ -1161,6 +1178,8 @@ export function extractTitle( premiumCalloutRaw?: unknown; /** See `parseFrontmatter`'s `tocDepthRaw`; threaded through unchanged. */ tocDepthRaw?: unknown; + /** See `parseFrontmatter`'s `openapiRaw`; threaded through unchanged. */ + openapiRaw?: unknown; } { const fm = parseFrontmatter(content); const body = fm.endLine > 0 ? content.split("\n").slice(fm.endLine).join("\n") : content; @@ -1194,9 +1213,36 @@ export function extractTitle( premiumCallout: fm.premiumCallout, ...(fm.premiumCalloutRaw !== undefined ? { premiumCalloutRaw: fm.premiumCalloutRaw } : {}), ...(fm.tocDepthRaw !== undefined ? { tocDepthRaw: fm.tocDepthRaw } : {}), + ...(fm.openapiRaw !== undefined ? { openapiRaw: fm.openapiRaw } : {}), }; } +/** + * The id each heading of a page body renders with, from the passes the sync + * and the MDX pipeline run: `normalizeStepHeadings`, `remarkClassicHeadingIds` + * and `safeHeadingId`. `line` is the heading's 0-based line in `body`. + */ +export function headingIds(body: string): { line: number; depth: number; id: string }[] { + const content = stripHtmlComments(normalizeStepHeadings(body)).content; + const nesting = scanMarkdownNesting(content); + if (nesting.maxDepth > MAX_MARKDOWN_NESTING_DEPTH) { + throw new Error( + `blockquotes or lists nested ${nesting.maxDepth} levels at line ${nesting.line}, past the ${MAX_MARKDOWN_NESTING_DEPTH} allowed`, + ); + } + const tree = fromMarkdown(content) as MdastNode; + remarkClassicHeadingIds()(tree); + const headings: { line: number; depth: number; id: string }[] = []; + visitHeadings(tree, (heading) => { + const id = classicHeadingId(heading); + const line = heading.position?.start?.line; + if (id !== undefined && line !== undefined && heading.depth !== undefined) { + headings.push({ line: line - 1, depth: heading.depth, id: safeHeadingId(id) }); + } + }); + return headings; +} + // Context supplied to rewriteTarget/rewriteContent: image handling and the // resolvers that turn a docs-relative link into an output href. export interface RewriteContext { diff --git a/packages/docs-ui/src/runtime-version-switcher.tsx b/packages/docs-ui/src/runtime-version-switcher.tsx index 041a1b5a..d051e1cc 100644 --- a/packages/docs-ui/src/runtime-version-switcher.tsx +++ b/packages/docs-ui/src/runtime-version-switcher.tsx @@ -1,5 +1,6 @@ "use client"; +import { isObject } from "@coder/docs-config/client"; import { DEV_ID, LINE_ID_PATTERN, @@ -41,13 +42,9 @@ interface VersionsDocumentTag { label?: string; } -function isRecord(value: unknown): value is Record<string, unknown> { - return typeof value === "object" && value !== null; -} - function isLine(value: unknown): value is VersionsDocumentLine { return ( - isRecord(value) && + isObject(value) && typeof value.id === "string" && LINE_ID_PATTERN.test(value.id) && typeof value.label === "string" && @@ -57,12 +54,12 @@ function isLine(value: unknown): value is VersionsDocumentLine { } function isDevelopment(value: unknown): value is VersionsDocumentDevelopment { - return isRecord(value) && value.id === DEV_ID && typeof value.label === "string"; + return isObject(value) && value.id === DEV_ID && typeof value.label === "string"; } function isTag(value: unknown): value is VersionsDocumentTag { return ( - isRecord(value) && + isObject(value) && typeof value.id === "string" && TAG_ID_PATTERN.test(value.id) && typeof value.line === "string" && diff --git a/packages/docs-ui/src/versions-document-client.ts b/packages/docs-ui/src/versions-document-client.ts index c6fa0dd1..dbeacbb4 100644 --- a/packages/docs-ui/src/versions-document-client.ts +++ b/packages/docs-ui/src/versions-document-client.ts @@ -1,5 +1,6 @@ "use client"; +import { isObject } from "@coder/docs-config/client"; import { useEffect, useRef, useState } from "react"; /** @@ -28,12 +29,8 @@ export type VersionsDocumentState = | { status: "ready"; document: VersionsDocumentShape } | { status: "error"; document: null }; -function isRecord(value: unknown): value is Record<string, unknown> { - return typeof value === "object" && value !== null; -} - function isBanner(value: unknown): value is VersionsDocumentBanner { - if (!isRecord(value)) return false; + if (!isObject(value)) return false; return ( typeof value.enabled === "boolean" && typeof value.legacyBase === "string" && @@ -43,7 +40,7 @@ function isBanner(value: unknown): value is VersionsDocumentBanner { } function asDocument(value: unknown): VersionsDocumentShape | null { - if (!isRecord(value) || value.schemaVersion !== 1 || !Array.isArray(value.lines)) return null; + if (!isObject(value) || value.schemaVersion !== 1 || !Array.isArray(value.lines)) return null; const banner = value.banner === undefined || value.banner === null ? null : value.banner; if (banner !== null && !isBanner(banner)) return null; return { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 961b10f1..14278985 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -122,6 +122,9 @@ importers: fumadocs-mdx: specifier: 'catalog:' version: 15.6.0(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7) + fumadocs-openapi: + specifier: 12.6.1 + version: 12.6.1(83fbde21deb18050b9b10d0b4220f1cf) fumadocs-ui: specifier: 'catalog:' version: 16.19.0(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) @@ -225,6 +228,9 @@ importers: fumadocs-mdx: specifier: 'catalog:' version: 15.6.0(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7) + fumadocs-openapi: + specifier: 12.6.1 + version: 12.6.1(83fbde21deb18050b9b10d0b4220f1cf) fumadocs-ui: specifier: 'catalog:' version: 16.19.0(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) @@ -320,12 +326,24 @@ importers: '@coder/docs-config': specifier: workspace:* version: link:../docs-config + '@coder/docs-manifest': + specifier: workspace:* + version: link:../docs-manifest '@coder/docs-transforms': specifier: workspace:* version: link:../docs-transforms '@fumari/image-size': specifier: 0.1.1 version: 0.1.1 + github-slugger: + specifier: 2.0.0 + version: 2.0.0 + oas-validator: + specifier: 5.0.8 + version: 5.0.8 + swagger2openapi: + specifier: 7.0.8 + version: 7.0.8 devDependencies: '@mdx-js/mdx': specifier: 3.1.1 @@ -392,15 +410,30 @@ importers: '@coder/docs-ui': specifier: workspace:* version: link:../docs-ui + '@fumadocs/json-schema': + specifier: 0.3.5 + version: 0.3.5(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@scalar/json-magic': + specifier: 0.18.0 + version: 0.18.0 + es-module-lexer: + specifier: 1.7.0 + version: 1.7.0 fumadocs-core: specifier: 'catalog:' - version: 16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7) + version: 16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7) + fumadocs-openapi: + specifier: 12.6.1 + version: 12.6.1(83fbde21deb18050b9b10d0b4220f1cf) fumadocs-ui: specifier: 'catalog:' - version: 16.19.0(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) + version: 16.19.0(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) lucide-react: - specifier: 1.46.0 - version: 1.46.0(react@19.2.7) + specifier: 1.73.0 + version: 1.73.0(@types/react@19.2.17)(react@19.2.7) + shiki: + specifier: 4.6.0 + version: 4.6.0 devDependencies: '@coder/docs-transforms': specifier: workspace:* @@ -425,7 +458,7 @@ importers: version: 19.2.3(@types/react@19.2.17) fumadocs-mdx: specifier: 'catalog:' - version: 15.6.0(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7) + version: 15.6.0(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7) jsdom: specifier: 25.0.1 version: 25.0.1 @@ -612,6 +645,36 @@ packages: resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} engines: {node: '>=6.9.0'} + '@babel/runtime@8.1.2': + resolution: {integrity: sha512-Ay6HdEKZJAeGs6KKJ/ezCK5ssjFmkvUiR0TEGv/B1abyjLWrQ2RU+M507Ppk0NikhvVFhlEFC1/rHfCiYqSUcw==} + + '@base-ui/react@1.9.0': + resolution: {integrity: sha512-S8CSYosASBKtpL8SWUfS78rFElfLijiCgA7oHOK22jCJ95FULsYyKwBNFOgudt0RA+/7yNc7F81bOvQnRgbBiQ==} + engines: {node: '>=14.0.0'} + peerDependencies: + '@date-fns/tz': ^1.2.0 + '@types/react': ^17 || ^18 || ^19 + date-fns: ^4.0.0 + react: ^17 || ^18 || ^19 + react-dom: ^17 || ^18 || ^19 + peerDependenciesMeta: + '@date-fns/tz': + optional: true + '@types/react': + optional: true + date-fns: + optional: true + + '@base-ui/utils@0.5.0': + resolution: {integrity: sha512-dYGGcEttjkYiMoa5nHm8vLaJ2UcuTWxo3BFAwOYXeRg/q7UVVvA6cacEIXEs3FgBfK1CGtW1ptElqs7wsx+t9A==} + peerDependencies: + '@types/react': ^17 || ^18 || ^19 + react: ^17 || ^18 || ^19 + react-dom: ^17 || ^18 || ^19 + peerDependenciesMeta: + '@types/react': + optional: true + '@bytecodealliance/preview2-shim@0.17.6': resolution: {integrity: sha512-n3cM88gTen5980UOBAD6xDcNNL3ocTK8keab21bpx1ONdA+ARj7uD1qoFxOWCyKlkpSi195FH+GeAut7Oc6zZw==} @@ -1034,6 +1097,9 @@ packages: cpu: [x64] os: [win32] + '@exodus/schemasafe@1.3.0': + resolution: {integrity: sha512-5Aap/GaRupgNx/feGBwLLTVv8OQFfv3pq2lPRzPg9R+IOBnDgghTGW7l7EuVXOvg5cc/xSAlRW8rBrjIC3Nvqw==} + '@fastify/busboy@2.1.1': resolution: {integrity: sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==} engines: {node: '>=14'} @@ -1069,6 +1135,17 @@ packages: '@types/react': optional: true + '@fumadocs/json-schema@0.3.5': + resolution: {integrity: sha512-BhFhYtVufkLY0cZfWuMFJm0Rq7oBaIDMzONrsHovhY6on7GiPiuTSuJv4ZlOgmyBaPL3HW+s1wkevjhvRUUlFg==} + peerDependencies: + json-schema-typed: '*' + react: ^19.2.0 + peerDependenciesMeta: + json-schema-typed: + optional: true + react: + optional: true + '@fumadocs/tailwind@0.1.5': resolution: {integrity: sha512-ohzmuLTfNNRvP6B/Xx31lWJ58xu40NcmI+6mc/jivYeOoofnmdxBKu5gCErTgOE/mUqyVv4GvYeqd9FhoLHphg==} peerDependencies: @@ -1080,6 +1157,24 @@ packages: '@fumari/image-size@0.1.1': resolution: {integrity: sha512-iaiV2wyzJ4mW358NX4CX3yGit+WjKYzpaQ+rldK9BjL/5jFpeV6ruWnZVq7MEyMn3Gd0DLi8g/79NZAAQaGscw==} + '@fumari/json-schema-ts@1.0.2': + resolution: {integrity: sha512-1NHGl8Oqg50mhpWMvbhqnwFRLBugkGCRubLSH/TrAzTAS99x4z0xFgOVcbJne+yfaZv94ZNdmRWobDvUiZswPg==} + peerDependencies: + json-schema-typed: '*' + peerDependenciesMeta: + json-schema-typed: + optional: true + + '@fumari/stf@1.1.2': + resolution: {integrity: sha512-8PuvETmnMRJjof6BJLFNJBKq9at6Ar1oJWRkedSJ0K/GJ73QPHVSZqTkgXh3hb6uXkQhbbWkv+5WD0Fh50YUGA==} + peerDependencies: + '@types/react': '*' + react: ^19.2.0 + react-dom: ^19.2.0 + peerDependenciesMeta: + '@types/react': + optional: true + '@img/colour@1.1.0': resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} engines: {node: '>=18'} @@ -2785,6 +2880,34 @@ packages: cpu: [x64] os: [win32] + '@scalar/helpers@0.16.4': + resolution: {integrity: sha512-9eILWzUcAkHEuYMMvijpSIy69t+Vkq+NudLB/7lgARFTWqXfQpIxW1L3VH7ogKyRie5+E4CNZ3PSvlw6IIfLGw==} + engines: {node: '>=22'} + + '@scalar/helpers@0.17.0': + resolution: {integrity: sha512-/XzBJDB/nr/Nzkx/a8ow0WdWb5LIb6KsWrjv7TsQYolkCxOM6ZT+iEJ635QssQG33wEzAK0os5Xbiub6RUU+Ng==} + engines: {node: '>=22'} + + '@scalar/helpers@0.18.1': + resolution: {integrity: sha512-5/FsnE/4bCbr+h0OOgT1Zlnl4G7MKgPsZlzDN4KiBjpVCCZNHn7Px9gLOqtQSfsSqM/JFwUW+voZNVTODiL2BA==} + engines: {node: '>=22'} + + '@scalar/json-magic@0.16.1': + resolution: {integrity: sha512-yWQJUrkufUsShizF+rGKO4BoZ/ijMpnrgwRjtCA2cYqjxkQOYaQCd+WVF+b3ihmXE7amr768pLItFCx5UV/ObQ==} + engines: {node: '>=22'} + + '@scalar/json-magic@0.18.0': + resolution: {integrity: sha512-mz/H7H9gP2jZvViQS2cyOmqrBvLQwN5UdJ+5k77yBxV25D/6jh0BfGubQyxNwAqA62TP8JnEiIQ4gzbsMZvESw==} + engines: {node: '>=22.19.0'} + + '@scalar/openapi-types@0.9.10': + resolution: {integrity: sha512-rQVlvSLXvP3ljCY7BqKeJ07EjqtzJyaj1OTMVRVRBftmNmxupmmx1xNTnuLnaJIfGnrNEFLW7kyJofzH43wUPg==} + engines: {node: '>=22'} + + '@scalar/openapi-upgrader@0.4.11': + resolution: {integrity: sha512-Kpd6O0fx1QqrM8evUGeTh5b4NBDET3TnwWeeQkDvV9NSOiQ/asM58sLCnqRzwRid1JN+0xJRG2fX4dgIoX4m8g==} + engines: {node: '>=22'} + '@sentry/browser-utils@11.9.0': resolution: {integrity: sha512-HwEa+BYxNJ+9msyzKSL2w5+eQwWRGk13StZoMinRmkq+tK34pmIOeDRq/ARlofyYzffvY6R9Xggh9peLjYn2Rg==} engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} @@ -3558,6 +3681,9 @@ packages: resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} engines: {node: '>= 0.4'} + call-me-maybe@1.0.2: + resolution: {integrity: sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==} + callsites@3.1.0: resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} engines: {node: '>=6'} @@ -3601,6 +3727,10 @@ packages: client-only@0.0.1: resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==} + cliui@8.0.1: + resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==} + engines: {node: '>=12'} + clsx@2.1.1: resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} engines: {node: '>=6'} @@ -3800,6 +3930,9 @@ packages: resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==} engines: {node: '>= 0.4'} + es6-promise@3.3.1: + resolution: {integrity: sha512-SOp9Phqvqn7jtEUxPWdWfWoLmyt2VaJ6MpvP9Comy1MceMXqE6bxvaTu4iaxpYYPzhny28Lc+M87/c2cPK6lDg==} + esast-util-from-estree@2.0.0: resolution: {integrity: sha512-4CyanoAudUSBAn5K13H4JhsMH6L9ZP7XbLVe/dKybkxMO7eDyLsT8UHl9TRNrU2Gr9nz+FovfSIjuXWJ81uVwQ==} @@ -3816,6 +3949,10 @@ packages: engines: {node: '>=18'} hasBin: true + escalade@3.2.0: + resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} + engines: {node: '>=6'} + escape-string-regexp@5.0.0: resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==} engines: {node: '>=12'} @@ -3881,6 +4018,9 @@ packages: fast-json-stable-stringify@2.1.0: resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} + fast-safe-stringify@2.1.1: + resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==} + fast-uri@3.1.8: resolution: {integrity: sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==} @@ -4058,6 +4198,24 @@ packages: vite: optional: true + fumadocs-openapi@12.6.1: + resolution: {integrity: sha512-ZaBinW7tr1oadHNqjOhho3gFbNCNC2OWwP4HHwRXxLU6irJjfOxRI7XlnsKqJ6UNrqhjsCcTJz8Ov2vT5IzlIQ==} + peerDependencies: + '@scalar/api-client-react': ^2.0.20 + '@types/react': '*' + fumadocs-core: ^16.17.11 + fumadocs-ui: ^16.17.8 + json-schema-typed: '*' + react: ^19.2.0 + react-dom: ^19.2.0 + peerDependenciesMeta: + '@scalar/api-client-react': + optional: true + '@types/react': + optional: true + json-schema-typed: + optional: true + fumadocs-ui@16.19.0: resolution: {integrity: sha512-/enoAAdsJe9By/mTkc49EG9GiHsNG7GOcBfj9w46kg7sYcuLJcClIA51Gr7OsJ77rUbQ16VZ5YPC+3mHmRIsUA==} peerDependencies: @@ -4085,6 +4243,10 @@ packages: resolution: {integrity: sha512-H7cUpwCQSiJmAHM4c/aFu6fUfrhWXW1ncyh8ftxEPMu6AiYkHw9K8br720TGPZJbk5eOH2bynjZD1yPvdDAmag==} engines: {node: '>= 4'} + get-caller-file@2.0.5: + resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} + engines: {node: 6.* || 8.* || >= 10.*} + get-east-asian-width@1.7.0: resolution: {integrity: sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==} engines: {node: '>=18'} @@ -4240,6 +4402,9 @@ packages: resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==} engines: {node: '>= 14'} + http2-client@1.3.5: + resolution: {integrity: sha512-EC2utToWl4RKfs5zd36Mxq7nzHHBuomZboI0yYL6Y0RmBgT7Sgkq4rQ0ezFTYoIsSs7Tm9SJe+o2FcAg6GBhGA==} + https-proxy-agent@7.0.6: resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==} engines: {node: '>= 14'} @@ -4506,11 +4671,6 @@ packages: resolution: {integrity: sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==} engines: {node: '>=10'} - lucide-react@1.46.0: - resolution: {integrity: sha512-Bv+FZXgZPrxc/NCl1e7JJVQFLdiCxYgxNVhqoV7X0p6I8ADJo8DxBnK1auH0fZz4AmqOJ3jgneL4f1i8LJQRAA==} - peerDependencies: - react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0 - lucide-react@1.73.0: resolution: {integrity: sha512-fVOzGviL9mTfHenG1PbCfIceavyGlnpYNSYr+aGZHLRymAJ7DTP6KHuqt0uBkCKAoenr1UVkwSbDIYt2xIesEQ==} peerDependencies: @@ -4836,6 +4996,10 @@ packages: sass: optional: true + node-fetch-h2@2.3.0: + resolution: {integrity: sha512-ofRW94Ab0T4AOh5Fk8t0h8OBWrmjb0SSB20xh1H8YnPV9EJ+f5AMoYSUQ2zgJ4Iq2HAK0I2l5/Nequ8YzFS3Hg==} + engines: {node: 4.x || >=6.0.0} + node-fetch@2.6.7: resolution: {integrity: sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==} engines: {node: 4.x || >=6.0.0} @@ -4867,6 +5031,9 @@ packages: resolution: {integrity: sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==} hasBin: true + node-readfiles@0.2.0: + resolution: {integrity: sha512-SU00ZarexNlE4Rjdm83vglt5Y9yiQ+XI1XpflWlb7q7UTN1JUItm69xMeiQCTxtTfnzt+83T8Cx+vI2ED++VDA==} + nopt@8.1.0: resolution: {integrity: sha512-ieGu42u/Qsa4TFktmaKEwM6MQH0pOWnaB3htzh0JRtx84+Mebc0cbZYN5bC+6WTZ4+77xrL9Pn5m7CV6VIkV7A==} engines: {node: ^18.17.0 || >=20.5.0} @@ -4887,6 +5054,22 @@ packages: nwsapi@2.2.24: resolution: {integrity: sha512-7YRhZ3jS45LwmSCT4b2sVFHt/WuovaktDU07QrtOBY2PXskss5a9jfmR9jptyumwXST+rFjrmppMY1KT/yn35A==} + oas-kit-common@1.0.8: + resolution: {integrity: sha512-pJTS2+T0oGIwgjGpw7sIRU8RQMcUoKCDWFLdBqKB2BNmGpbBMH2sdqAaOXUg8OzonZHU0L7vfJu1mJFEiYDWOQ==} + + oas-linter@3.2.2: + resolution: {integrity: sha512-KEGjPDVoU5K6swgo9hJVA/qYGlwfbFx+Kg2QB/kd7rzV5N8N5Mg6PlsoCMohVnQmo+pzJap/F610qTodKzecGQ==} + + oas-resolver@2.5.6: + resolution: {integrity: sha512-Yx5PWQNZomfEhPPOphFbZKi9W93CocQj18NlD2Pa4GWZzdZpSJvYwoiuurRI7m3SpcChrnO08hkuQDL3FGsVFQ==} + hasBin: true + + oas-schema-walker@1.1.5: + resolution: {integrity: sha512-2yucenq1a9YPmeNExoUa9Qwrt9RFkjqaMAA1X+U7sbb0AqBeTIdMHky9SQQ6iN94bO5NW0W4TRYXerG+BdAvAQ==} + + oas-validator@5.0.8: + resolution: {integrity: sha512-cu20/HE5N5HKqVygs3dt94eYJfBi0TsZvPVXDhbXQHiEityDN+RROTleefoKRKKJ9dFAF2JBkDHgvWj0sjKGmw==} + once@1.4.0: resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} @@ -4991,6 +5174,9 @@ packages: path-to-regexp@8.4.2: resolution: {integrity: sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==} + pathe@2.0.3: + resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + pend@1.2.0: resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==} @@ -5125,6 +5311,9 @@ packages: recma-stringify@1.0.0: resolution: {integrity: sha512-cjwII1MdIIVloKvC9ErQ+OgAtwHBmcZ0Bg4ciz78FtbT8In39aAYbaA7zvxQ61xVMSPE8WxhLwLbhif4Js2C+g==} + reftools@1.1.9: + resolution: {integrity: sha512-OVede/NQE13xBQ+ob5CKd5KyeJYU2YInb1bmV4nRoOfquZPkAkxuOXicSe1PvqIuZZ4kD13sPKBbR7UFDmli6w==} + regex-recursion@6.0.2: resolution: {integrity: sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==} @@ -5161,10 +5350,17 @@ packages: remark@15.0.1: resolution: {integrity: sha512-Eht5w30ruCXgFmxVUSlNWQ9iiimq07URKeFS3hNc8cUWy1llX4KDWfyEDZRycMc+znsN9Ux5/tJ/BFdgdOwA3A==} + require-directory@2.1.1: + resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} + engines: {node: '>=0.10.0'} + require-from-string@2.0.2: resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} engines: {node: '>=0.10.0'} + reselect@5.3.0: + resolution: {integrity: sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg==} + resolve-from@4.0.0: resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} engines: {node: '>=4'} @@ -5267,6 +5463,24 @@ packages: resolution: {integrity: sha512-imjLsVHgPuWhvpU3P+zOekvMYqnel7QmKsFC4Sn0fCuAvaaalBsxwKEsrU8Ko5BdFnZA6Go/8a0RzahS634UgA==} engines: {node: '>=20'} + should-equal@2.0.0: + resolution: {integrity: sha512-ZP36TMrK9euEuWQYBig9W55WPC7uo37qzAEmbjHz4gfyuXrEUgF8cUvQVO+w+d3OMfPvSRQJ22lSm8MQJ43LTA==} + + should-format@3.0.3: + resolution: {integrity: sha512-hZ58adtulAk0gKtua7QxevgUaXTTXxIi8t41L3zo9AHvjXO1/7sdLECuHeIN2SRtYXpNkmhoUP2pdeWgricQ+Q==} + + should-type-adaptors@1.1.0: + resolution: {integrity: sha512-JA4hdoLnN+kebEp2Vs8eBe9g7uy0zbRo+RMcU0EsNy+R+k049Ki+N5tT5Jagst2g7EAja+euFuoXFCa8vIklfA==} + + should-type@1.4.0: + resolution: {integrity: sha512-MdAsTu3n25yDbIe1NeN69G4n6mUnJGtSJHygX3+oN0ZbO3DTiATnf7XnYJdGT42JCXurTb1JI0qOBR65shvhPQ==} + + should-util@1.0.1: + resolution: {integrity: sha512-oXF8tfxx5cDk8r2kYqlkUJzZpDBqVY/II2WhvU0n9Y3XYvAYRmeaf1PvvIvTgPnv4KJ+ES5M0PyDq5Jp+Ygy2g==} + + should@13.2.3: + resolution: {integrity: sha512-ggLesLtu2xp+ZxI+ysJTmNjh2U0TsC+rQ/pfED9bUZZ4DKefP27D+7YJVVTvKsmjLpIi9jAa7itwDGkDDmt1GQ==} + signal-exit@3.0.7: resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} @@ -5388,6 +5602,10 @@ packages: svg-tags@1.0.0: resolution: {integrity: sha512-ovssysQTa+luh7A5Weu3Rta6FJlFBBbInjOh722LIt6klpU2/HtdUbszju/G4devcvk8PGt7FCLv5wftu3THUA==} + swagger2openapi@7.0.8: + resolution: {integrity: sha512-upi/0ZGkYgEcLeGieoz8gT74oWHA0E7JivX7aN9mAf+Tc7BQoRBvnIGHoPDw+f9TXTW4s6kGYCZJtauP6OYp7g==} + hasBin: true + symbol-tree@3.2.4: resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==} @@ -5532,6 +5750,14 @@ packages: resolution: {integrity: sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==} engines: {node: '>=20.18.1'} + undici@8.12.3: + resolution: {integrity: sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==} + engines: {node: '>=22.19.0'} + + undici@8.12.4: + resolution: {integrity: sha512-8Mx+uNKKER2bA4AdtedkqRbwUCIJFr2nJckXRe5yrDqzePqwLP7VNcctN8/XdmDSbF7mS+jJKIszlL+vbam1VA==} + engines: {node: '>=22.19.0'} + unicorn-magic@0.4.1: resolution: {integrity: sha512-lzlXPoVB0Uy/FvTaUgX39RbixYiSKoc3JSoSf01+0c2B6FR3qdYIPN7Qjo/AV7n6sqLCk0509cT3LRj1oSZ1+A==} engines: {node: '>=20'} @@ -5591,6 +5817,11 @@ packages: '@types/react': optional: true + use-sync-external-store@1.7.0: + resolution: {integrity: sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==} + peerDependencies: + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + util-deprecate@1.0.2: resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} @@ -5657,6 +5888,10 @@ packages: engines: {node: '>= 8'} hasBin: true + wrap-ansi@7.0.0: + resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} + engines: {node: '>=10'} + wrappy@1.0.2: resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} @@ -5695,6 +5930,10 @@ packages: xmlchars@2.2.0: resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} + y18n@5.0.8: + resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} + engines: {node: '>=10'} + yallist@4.0.0: resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==} @@ -5702,11 +5941,23 @@ packages: resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==} engines: {node: '>=18'} + yaml@1.10.3: + resolution: {integrity: sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==} + engines: {node: '>= 6'} + yaml@2.9.1: resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} engines: {node: '>= 14.6'} hasBin: true + yargs-parser@21.1.1: + resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} + engines: {node: '>=12'} + + yargs@17.7.3: + resolution: {integrity: sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==} + engines: {node: '>=12'} + yauzl-clone@1.0.4: resolution: {integrity: sha512-igM2RRCf3k8TvZoxR2oguuw4z1xasOnA31joCqHIyLkeWrvAc2Jgay5ISQ2ZplinkoGaJ6orCz56Ey456c5ESA==} engines: {node: '>=6'} @@ -5769,6 +6020,31 @@ snapshots: '@babel/helper-validator-identifier@7.29.7': {} + '@babel/runtime@8.1.2': {} + + '@base-ui/react@1.9.0(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)': + dependencies: + '@babel/runtime': 8.1.2 + '@base-ui/utils': 0.5.0(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@floating-ui/react-dom': 2.1.9(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@floating-ui/utils': 0.2.12 + react: 19.2.7 + react-dom: 19.2.7(react@19.2.7) + use-sync-external-store: 1.7.0(react@19.2.7) + optionalDependencies: + '@types/react': 19.2.17 + + '@base-ui/utils@0.5.0(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)': + dependencies: + '@babel/runtime': 8.1.2 + '@floating-ui/utils': 0.2.12 + react: 19.2.7 + react-dom: 19.2.7(react@19.2.7) + reselect: 5.3.0 + use-sync-external-store: 1.7.0(react@19.2.7) + optionalDependencies: + '@types/react': 19.2.17 + '@bytecodealliance/preview2-shim@0.17.6': {} '@cacheable/memory@2.2.0': @@ -6015,6 +6291,8 @@ snapshots: '@esbuild/win32-x64@0.28.2': optional: true + '@exodus/schemasafe@1.3.0': {} + '@fastify/busboy@2.1.1': {} '@floating-ui/core@1.8.0': @@ -6045,12 +6323,31 @@ snapshots: optionalDependencies: '@types/react': 19.2.17 + '@fumadocs/json-schema@0.3.5(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)': + dependencies: + '@fuma-translate/react': 1.0.2(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@scalar/json-magic': 0.16.1 + optionalDependencies: + react: 19.2.7 + transitivePeerDependencies: + - '@types/react' + - react-dom + '@fumadocs/tailwind@0.1.5(tailwindcss@4.3.3)': optionalDependencies: tailwindcss: 4.3.3 '@fumari/image-size@0.1.1': {} + '@fumari/json-schema-ts@1.0.2': {} + + '@fumari/stf@1.1.2(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)': + dependencies: + react: 19.2.7 + react-dom: 19.2.7(react@19.2.7) + optionalDependencies: + '@types/react': 19.2.17 + '@img/colour@1.1.0': optional: true @@ -7208,6 +7505,33 @@ snapshots: '@rollup/rollup-win32-x64-msvc@4.65.1': optional: true + '@scalar/helpers@0.16.4': {} + + '@scalar/helpers@0.17.0': {} + + '@scalar/helpers@0.18.1': {} + + '@scalar/json-magic@0.16.1': + dependencies: + '@scalar/helpers': 0.16.4 + pathe: 2.0.3 + undici: 7.30.1 + yaml: 2.9.1 + + '@scalar/json-magic@0.18.0': + dependencies: + '@scalar/helpers': 0.17.0 + pathe: 2.0.3 + undici: 8.12.3 + yaml: 2.9.1 + + '@scalar/openapi-types@0.9.10': {} + + '@scalar/openapi-upgrader@0.4.11': + dependencies: + '@scalar/helpers': 0.18.1 + '@scalar/openapi-types': 0.9.10 + '@sentry/browser-utils@11.9.0': dependencies: '@sentry/conventions': 0.27.0 @@ -8184,6 +8508,8 @@ snapshots: es-errors: 1.3.0 function-bind: 1.1.2 + call-me-maybe@1.0.2: {} + callsites@3.1.0: {} caniuse-lite@1.0.30001810: {} @@ -8216,6 +8542,12 @@ snapshots: client-only@0.0.1: {} + cliui@8.0.1: + dependencies: + string-width: 4.2.3 + strip-ansi: 6.0.1 + wrap-ansi: 7.0.0 + clsx@2.1.1: {} cn@0.5.2: {} @@ -8376,6 +8708,8 @@ snapshots: has-tostringtag: 1.0.2 hasown: 2.0.4 + es6-promise@3.3.1: {} + esast-util-from-estree@2.0.0: dependencies: '@types/estree-jsx': 1.0.5 @@ -8448,6 +8782,8 @@ snapshots: '@esbuild/win32-ia32': 0.28.2 '@esbuild/win32-x64': 0.28.2 + escalade@3.2.0: {} + escape-string-regexp@5.0.0: {} estree-util-attach-comments@3.0.0: @@ -8541,6 +8877,8 @@ snapshots: fast-json-stable-stringify@2.1.0: optional: true + fast-safe-stringify@2.1.1: {} + fast-uri@3.1.8: {} fastest-levenshtein@1.0.16: {} @@ -8607,43 +8945,6 @@ snapshots: fsevents@2.3.3: optional: true - fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7): - dependencies: - '@fumari/image-size': 0.1.1 - acorn: 8.19.0 - acorn-jsx: 5.3.2(acorn@8.19.0) - estree-util-value-to-estree: 3.5.0 - github-slugger: 2.0.0 - hast-util-from-dom: 5.0.1 - hast-util-to-estree: 3.1.3 - mdast-util-mdx: 3.0.0 - micromark: 4.0.3 - micromark-extension-gfm-table: 2.1.2 - npm-to-yarn: 3.2.0 - remark: 15.0.1 - remark-gfm: 4.0.1 - remark-rehype: 11.1.2 - scroll-into-view-if-needed: 3.1.0 - shiki: 4.6.0 - tinyglobby: 0.2.17 - unified: 11.0.5 - vfile: 6.0.3 - yaml: 2.9.1 - zbsearch: 4.0.4 - optionalDependencies: - '@mdx-js/mdx': 3.1.1 - '@types/estree-jsx': 1.0.5 - '@types/hast': 3.0.5 - '@types/mdast': 4.0.4 - '@types/react': 19.2.17 - lucide-react: 1.46.0(react@19.2.7) - next: 16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - react: 19.2.7 - react-dom: 19.2.7(react@19.2.7) - zod: 4.6.7 - transitivePeerDependencies: - - supports-color - fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6): dependencies: '@fumari/image-size': 0.1.1 @@ -8718,40 +9019,6 @@ snapshots: transitivePeerDependencies: - supports-color - fumadocs-mdx@15.6.0(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7): - dependencies: - '@mdx-js/mdx': 3.1.1 - '@standard-schema/spec': 1.1.0 - acorn: 8.19.0 - acorn-jsx: 5.3.2(acorn@8.19.0) - chokidar: 6.0.0 - esbuild: 0.28.2 - estree-util-value-to-estree: 3.5.0 - fumadocs-core: 16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7) - github-slugger: 2.0.0 - magic-string: 1.4.5 - mdast-util-from-markdown: 2.1.0 - mdast-util-mdx: 3.0.0 - micromark-extension-mdxjs-esm: 3.0.0 - picocolors: 1.1.1 - picomatch: 4.0.7 - tinyexec: 1.3.1 - tinyglobby: 0.2.17 - unified: 11.0.5 - unist-util-remove-position: 5.0.0 - vfile: 6.0.3 - yaml: 2.9.1 - yuku-analyzer: 0.19.0 - zod: 4.6.7 - optionalDependencies: - '@types/mdast': 4.0.4 - '@types/mdx': 2.0.14 - '@types/react': 19.2.17 - next: 16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - react: 19.2.7 - transitivePeerDependencies: - - supports-color - fumadocs-mdx@15.6.0(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7): dependencies: '@mdx-js/mdx': 3.1.1 @@ -8820,39 +9087,35 @@ snapshots: transitivePeerDependencies: - supports-color - fumadocs-ui@16.19.0(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3): + fumadocs-openapi@12.6.1(83fbde21deb18050b9b10d0b4220f1cf): dependencies: + '@base-ui/react': 1.9.0(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) '@fuma-translate/react': 1.0.2(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@fumadocs/tailwind': 0.1.5(tailwindcss@4.3.3) - '@radix-ui/react-accordion': 1.3.1(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@radix-ui/react-collapsible': 1.2.1(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@radix-ui/react-dialog': 1.3.1(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@radix-ui/react-direction': 1.2.0(@types/react@19.2.17)(react@19.2.7) - '@radix-ui/react-navigation-menu': 1.4.1(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@radix-ui/react-popover': 1.3.1(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@radix-ui/react-presence': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@radix-ui/react-scroll-area': 1.4.0(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@radix-ui/react-slot': 1.5.0(@types/react@19.2.17)(react@19.2.7) - '@radix-ui/react-tabs': 1.2.1(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@fumadocs/json-schema': 0.3.5(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@fumari/json-schema-ts': 1.0.2 + '@fumari/stf': 1.1.2(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@scalar/json-magic': 0.18.0 + '@scalar/openapi-upgrader': 0.4.11 + chokidar: 6.0.0 class-variance-authority: 0.7.1 cn: 0.5.2 - fumadocs-core: 16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7) + fumadocs-core: 16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7) + fumadocs-ui: 16.19.0(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) + github-slugger: 2.0.0 lucide-react: 1.73.0(@types/react@19.2.17)(react@19.2.7) - motion: 14.14.0(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - next-themes: 0.4.6(react-dom@19.2.7(react@19.2.7))(react@19.2.7) react: 19.2.7 react-dom: 19.2.7(react@19.2.7) - react-remove-scroll: 2.7.2(@types/react@19.2.17)(react@19.2.7) - scroll-into-view-if-needed: 3.1.0 + remark: 15.0.1 + remark-rehype: 11.1.2 shiki: 4.6.0 + undici: 8.12.4 + yaml: 2.9.1 optionalDependencies: - '@types/mdx': 2.0.14 '@types/react': 19.2.17 - next: 16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) transitivePeerDependencies: - - '@types/react-dom' - - remix - - tailwindcss + - '@date-fns/tz' + - date-fns + - supports-color fumadocs-ui@16.19.0(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3): dependencies: @@ -8892,6 +9155,8 @@ snapshots: generic-pool@3.4.2: {} + get-caller-file@2.0.5: {} + get-east-asian-width@1.7.0: {} get-intrinsic@1.3.0: @@ -9151,6 +9416,8 @@ snapshots: transitivePeerDependencies: - supports-color + http2-client@1.3.5: {} + https-proxy-agent@7.0.6: dependencies: agent-base: 7.1.4 @@ -9393,10 +9660,6 @@ snapshots: dependencies: yallist: 4.0.0 - lucide-react@1.46.0(react@19.2.7): - dependencies: - react: 19.2.7 - lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7): dependencies: react: 19.2.7 @@ -10006,6 +10269,10 @@ snapshots: - '@types/node' - babel-plugin-macros + node-fetch-h2@2.3.0: + dependencies: + http2-client: 1.3.5 + node-fetch@2.6.7: dependencies: whatwg-url: 5.0.0 @@ -10020,6 +10287,10 @@ snapshots: node-gyp-build@4.8.4: {} + node-readfiles@0.2.0: + dependencies: + es6-promise: 3.3.1 + nopt@8.1.0: dependencies: abbrev: 3.0.1 @@ -10034,6 +10305,37 @@ snapshots: nwsapi@2.2.24: {} + oas-kit-common@1.0.8: + dependencies: + fast-safe-stringify: 2.1.1 + + oas-linter@3.2.2: + dependencies: + '@exodus/schemasafe': 1.3.0 + should: 13.2.3 + yaml: 1.10.3 + + oas-resolver@2.5.6: + dependencies: + node-fetch-h2: 2.3.0 + oas-kit-common: 1.0.8 + reftools: 1.1.9 + yaml: 1.10.3 + yargs: 17.7.3 + + oas-schema-walker@1.1.5: {} + + oas-validator@5.0.8: + dependencies: + call-me-maybe: 1.0.2 + oas-kit-common: 1.0.8 + oas-linter: 3.2.2 + oas-resolver: 2.5.6 + oas-schema-walker: 1.1.5 + reftools: 1.1.9 + should: 13.2.3 + yaml: 1.10.3 + once@1.4.0: dependencies: wrappy: 1.0.2 @@ -10228,6 +10530,8 @@ snapshots: path-to-regexp@8.4.2: {} + pathe@2.0.3: {} + pend@1.2.0: {} picocolors@1.0.0: {} @@ -10360,6 +10664,8 @@ snapshots: unified: 11.0.5 vfile: 6.0.3 + reftools@1.1.9: {} + regex-recursion@6.0.2: dependencies: regex-utilities: 2.3.0 @@ -10442,8 +10748,12 @@ snapshots: transitivePeerDependencies: - supports-color + require-directory@2.1.1: {} + require-from-string@2.0.2: {} + reselect@5.3.0: {} + resolve-from@4.0.0: {} resolve-from@5.0.0: {} @@ -10607,6 +10917,32 @@ snapshots: '@shikijs/vscode-textmate': 10.1.0 '@types/hast': 3.0.5 + should-equal@2.0.0: + dependencies: + should-type: 1.4.0 + + should-format@3.0.3: + dependencies: + should-type: 1.4.0 + should-type-adaptors: 1.1.0 + + should-type-adaptors@1.1.0: + dependencies: + should-type: 1.4.0 + should-util: 1.0.1 + + should-type@1.4.0: {} + + should-util@1.0.1: {} + + should@13.2.3: + dependencies: + should-equal: 2.0.0 + should-format: 3.0.3 + should-type: 1.4.0 + should-type-adaptors: 1.1.0 + should-util: 1.0.1 + signal-exit@3.0.7: {} signal-exit@4.0.2: {} @@ -10745,6 +11081,22 @@ snapshots: svg-tags@1.0.0: {} + swagger2openapi@7.0.8: + dependencies: + call-me-maybe: 1.0.2 + node-fetch: 2.7.0 + node-fetch-h2: 2.3.0 + node-readfiles: 0.2.0 + oas-kit-common: 1.0.8 + oas-resolver: 2.5.6 + oas-schema-walker: 1.1.5 + oas-validator: 5.0.8 + reftools: 1.1.9 + yaml: 1.10.3 + yargs: 17.7.3 + transitivePeerDependencies: + - encoding + symbol-tree@3.2.4: {} table@6.9.0: @@ -10888,6 +11240,10 @@ snapshots: undici@7.30.1: {} + undici@8.12.3: {} + + undici@8.12.4: {} + unicorn-magic@0.4.1: {} unified@11.0.5: @@ -10955,6 +11311,10 @@ snapshots: optionalDependencies: '@types/react': 19.2.17 + use-sync-external-store@1.7.0(react@19.2.7): + dependencies: + react: 19.2.7 + util-deprecate@1.0.2: {} uuid@14.0.1: {} @@ -11072,6 +11432,12 @@ snapshots: dependencies: isexe: 2.0.0 + wrap-ansi@7.0.0: + dependencies: + ansi-styles: 4.3.0 + string-width: 4.2.3 + strip-ansi: 6.0.1 + wrappy@1.0.2: {} write-file-atomic@7.0.1: @@ -11097,12 +11463,28 @@ snapshots: xmlchars@2.2.0: {} + y18n@5.0.8: {} + yallist@4.0.0: {} yallist@5.0.0: {} + yaml@1.10.3: {} + yaml@2.9.1: {} + yargs-parser@21.1.1: {} + + yargs@17.7.3: + dependencies: + cliui: 8.0.1 + escalade: 3.2.0 + get-caller-file: 2.0.5 + require-directory: 2.1.1 + string-width: 4.2.3 + y18n: 5.0.8 + yargs-parser: 21.1.1 + yauzl-clone@1.0.4: dependencies: events-intercept: 2.0.0 diff --git a/turbo.json b/turbo.json index 45649825..828d709f 100644 --- a/turbo.json +++ b/turbo.json @@ -33,6 +33,7 @@ "DOCS_PUBLISH", "DOCS_GITHUB_TOKEN", "DOCS_RELEASE_SCHEDULE_FILE", + "DOCS_OPENAPI", "DOCS_CODE_SERVER_ROOT", "DOCS_CODE_SERVER_REF", "DOCS_CODE_SERVER_REPO"