Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
fix(docs): restore API reference pages dropped by undeclared tags (#3973)
Alberto Schiabel3335bb30134f
diff --git a/.github/workflows/docs-check-links.yml b/.github/workflows/docs-check-links.ymlindex 4177f2cfa..26e889354 100644--- a/.github/workflows/docs-check-links.yml+++ b/.github/workflows/docs-check-links.yml@@ -8,6 +8,11 @@ on:- '.github/workflows/docs-check-links.yml'- 'mise.toml'- 'mise.lock'+ schedule:+ # Nightly external-link sweep. HEAD/GET-checking every external URL is+ # slow and depends on third-party uptime, so it never runs on the PR path.+ - cron: '30 2 * * *'+ workflow_dispatch:concurrency:group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}@@ -22,6 +27,9 @@ jobs:defaults:run:working-directory: ./docs+ permissions:+ contents: read+ issues: writesteps:- name: Checkout repository@@ -41,5 +49,50 @@ jobs:- name: Install dependenciesrun: bun install- - name: Validate links+ - name: Validate internal links+ if: github.event_name == 'pull_request'run: bun run lint:links++ - name: Validate internal and external links+ if: github.event_name != 'pull_request'+ run: bun run lint:links:external++ # A red scheduled run is invisible unless someone watches the Actions+ # tab. File one tracking issue and leave it open until the cause is+ # fixed; PR runs skip this because their failures are already visible.+ - name: Open tracking issue on failure+ if: failure() && github.event_name != 'pull_request'+ continue-on-error: true+ # Override the job-level `./docs` default: that path only exists after+ # checkout, and a pre-checkout failure would otherwise leave the runner+ # unable to start this shell, silently losing the alert.+ working-directory: ${{ github.workspace }}+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ GH_REPO: ${{ github.repository }}+ LABEL: docs-external-links-failure+ RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}+ EVENT_NAME: ${{ github.event_name }}+ run: |+ gh label create "$LABEL" \+ --color B60205 \+ --description "Nightly docs external-link check is failing" 2>/dev/null || true++ existing=$(gh issue list --label "$LABEL" --state open --limit 1 --json number --jq '.[0].number // empty')+ if [ -n "$existing" ]; then+ echo "Issue #$existing is already open for this failure; not filing a duplicate."+ exit 0+ fi++ gh issue create \+ --title "Nightly docs external-link check is failing" \+ --label "$LABEL" \+ --body "The scheduled \`Docs - Check Links\` external sweep failed.++ - Run: $RUN_URL+ - Trigger: \`$EVENT_NAME\`++ The failing URLs are listed in the run log. External links only fail on+ evidence they are dead (404/410, or repeated network errors), so this+ usually means a linked page moved or was taken down — fix or remove the+ link in \`docs/content\`."diff --git a/docs/content/docs/migration-guide/new-sdk.mdx b/docs/content/docs/migration-guide/new-sdk.mdxindex 056f5d260..ccbe291ed 100644--- a/docs/content/docs/migration-guide/new-sdk.mdx+++ b/docs/content/docs/migration-guide/new-sdk.mdx@@ -1124,7 +1124,7 @@ export default async function webhookHandler(req: NextApiRequest, res: NextApiRe### Local tools-Previously, the Python SDK included *[local tools](https://github.com/ComposioHQ/composio/tree/master/python/composio/tools/local)*. These were tools defined within the SDK and consisted of local shell and code-related tools such as "clipboard", "sqltool", and "shelltool".+Previously, the Python SDK included *[local tools](https://github.com/ComposioHQ/composio/tree/0.5.0%2Bpost.1/python/composio/tools/local)*. These were tools defined within the SDK and consisted of local shell and code-related tools such as "clipboard", "sqltool", and "shelltool".This feature is currently in development for both Python and TypeScript SDKs, with newly created tools built for improved agent accuracy.diff --git a/docs/content/docs/providers/anthropic.mdx b/docs/content/docs/providers/anthropic.mdxindex 6b4e96ae4..b44587cd4 100644--- a/docs/content/docs/providers/anthropic.mdx+++ b/docs/content/docs/providers/anthropic.mdx@@ -7,7 +7,7 @@ keywords: [claude, messages api, claude agent sdk, agents sdk]The Anthropic provider formats Composio tools for Claude and executes the tool calls Claude returns. It works two ways:- The [Claude Messages API](https://docs.anthropic.com/en/api/messages), where you run the tool-call loop yourself.-- The [Claude Agent SDK](https://docs.anthropic.com/en/docs/agents-and-tools/claude-agent-sdk), where the SDK runs the loop and Composio tools are exposed as an in-process MCP server.+- The [Claude Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview), where the SDK runs the loop and Composio tools are exposed as an in-process MCP server.Pick the tab that matches your integration.diff --git a/docs/content/examples/general-agent-with-pi.mdx b/docs/content/examples/general-agent-with-pi.mdxindex a7391a565..0e73db1c4 100644--- a/docs/content/examples/general-agent-with-pi.mdx+++ b/docs/content/examples/general-agent-with-pi.mdx@@ -100,8 +100,6 @@ The two files above are the spine. The real project rounds them out with grouped<RepoBrowser />-The complete project lives on GitHub: [composio-slack-bot](https://github.com/ComposioHQ/composio-slack-bot).-## Run itRun `bun install.ts` once to set up the bot, start the server with `bun bot.ts`, then `@mention` the bot in any channel. It opens a session as you, finds the tool it needs, runs it against your connections, and replies in thread as the workspace bot, usually within a few seconds. Ask it to do something in an app you haven't connected yet and it DMs you a link first, then continues once you approve.diff --git a/docs/content/examples/local-sandbox-pr-reviewer.mdx b/docs/content/examples/local-sandbox-pr-reviewer.mdxindex ef237fd3e..d99225571 100644--- a/docs/content/examples/local-sandbox-pr-reviewer.mdx+++ b/docs/content/examples/local-sandbox-pr-reviewer.mdx@@ -90,8 +90,6 @@ The file above is the spine. The real project rounds it out with a CLI, a smoke/<RepoBrowser source="local-workbench" />-The complete project lives on GitHub: [local-pr-reviewer](https://github.com/ComposioHQ/local-pr-reviewer).-## Run itDry-run first to validate your input with no credentials, network calls, or sandbox startup, then run it for real:diff --git a/docs/content/reference/errors.mdx b/docs/content/reference/errors.mdxindex 1a479e18a..8c020592f 100644--- a/docs/content/reference/errors.mdx+++ b/docs/content/reference/errors.mdx@@ -52,7 +52,7 @@ Composio uses two types of API keys:| Error | Cause ||-------|-------|-| Invalid API key | The API key is incorrect or revoked. Verify in [Settings](https://dashboard.composio.dev/settings). |+| Invalid API key | The API key is incorrect or revoked. Verify in [Settings](https://dashboard.composio.dev/~/project/settings/api-keys). || No authentication provided | The request is missing the `x-api-key` or `x-org-api-key` header. || Invalid organization key | The organization API key is incorrect or revoked. Verify in Organization Settings. || Insufficient permissions | The API key doesn't have access to this resource. |diff --git a/docs/content/reference/v3/errors.mdx b/docs/content/reference/v3/errors.mdxindex b8b90de3b..b794551ae 100644--- a/docs/content/reference/v3/errors.mdx+++ b/docs/content/reference/v3/errors.mdx@@ -52,7 +52,7 @@ Composio uses two types of API keys:| Error | Cause ||-------|-------|-| Invalid API key | The API key is incorrect or revoked. Verify in [Settings](https://dashboard.composio.dev/settings). |+| Invalid API key | The API key is incorrect or revoked. Verify in [Settings](https://dashboard.composio.dev/~/project/settings/api-keys). || No authentication provided | The request is missing the `x-api-key` or `x-org-api-key` header. || Invalid organization key | The organization API key is incorrect or revoked. Verify in Organization Settings. || Insufficient permissions | The API key doesn't have access to this resource. |diff --git a/docs/lib/openapi-tags.ts b/docs/lib/openapi-tags.tsnew file mode 100644index 000000000..571c331cf--- /dev/null+++ b/docs/lib/openapi-tags.ts@@ -0,0 +1,46 @@+export type OpenAPIOperation = {+ security?: Record<string, string[]>[];+ tags?: string[];+};++export type OpenAPIDocument = {+ tags?: { name: string }[];+ paths?: Record<string, Record<string, OpenAPIOperation | undefined>>;+ webhooks?: Record<string, Record<string, OpenAPIOperation | undefined>>;+};++/**+ * fumadocs-openapi's tag grouping only generates pages for operations whose+ * tags are declared in the document's top-level `tags` array; operations with+ * undeclared tags are silently skipped. The backend generator omits some tags+ * (e.g. Projects) from that array, so declare every tag used by an operation.+ *+ * Applied both when syncing specs (scripts/fetch-openapi.mjs) so the committed+ * documents are complete, and again at load time (lib/openapi.ts) as a safety+ * net for snapshots that predate the sync-time normalization.+ */+export function declareOperationTags<T extends OpenAPIDocument>(document: T): T {+ const declared = new Set((document.tags ?? []).map((tag) => tag.name));+ const undeclared: string[] = [];+ for (const group of [document.paths, document.webhooks]) {+ for (const pathItem of Object.values(group ?? {})) {+ for (const operation of Object.values(pathItem ?? {})) {+ if (!operation || typeof operation !== 'object') continue;+ for (const tag of operation.tags ?? []) {+ if (declared.has(tag)) continue;+ declared.add(tag);+ undeclared.push(tag);+ }+ }+ }+ }++ if (undeclared.length > 0) {+ document.tags = [+ ...(document.tags ?? []),+ ...undeclared.map((name) => ({ name })),+ ];+ }++ return document;+}diff --git a/docs/lib/openapi.ts b/docs/lib/openapi.tsindex 6a03128d3..d324b44be 100644--- a/docs/lib/openapi.ts+++ b/docs/lib/openapi.ts@@ -1,6 +1,9 @@import { readFile } from 'node:fs/promises';import { join } from 'path';import { createOpenAPI } from 'fumadocs-openapi/server';+import { declareOperationTags, type OpenAPIDocument } from './openapi-tags';++export { declareOperationTags } from './openapi-tags';const openapiPath = join(process.cwd(), 'public/openapi.json');const openapiWebhooksPath = join(@@ -9,13 +12,6 @@ const openapiWebhooksPath = join();const openapiV3Path = join(process.cwd(), 'public/openapi-v3.json');-type OpenAPIDocument = {- paths?: Record<- string,- Record<string, { security?: Record<string, string[]>[] } | undefined>- >;-};-// v3.1 (latest) — clean operationIds, default API reference.// The webhook-events spec (openapi-webhooks.json) is a separate OpenAPI 3.1// document whose top-level `webhooks` block documents the payloads Composio@@ -38,7 +34,7 @@ export const openapiV3 = createOpenAPI({async function loadOpenAPISchema(path: string) {const document = JSON.parse(await readFile(path, 'utf8')) as OpenAPIDocument;- return normalizeNoAuthSecurity(document);+ return declareOperationTags(normalizeNoAuthSecurity(document));}export function normalizeNoAuthSecurity<T extends OpenAPIDocument>(document: T): T {diff --git a/docs/lib/repo-browser-markdown.ts b/docs/lib/repo-browser-markdown.tsnew file mode 100644index 000000000..d00b80780--- /dev/null+++ b/docs/lib/repo-browser-markdown.ts@@ -0,0 +1,22 @@+const REPO_BROWSER_PATTERN = /<RepoBrowser\b([^>]*)\/>/g;++const REPO_BROWSER_NOTICES: Record<string, string> = {+ 'slack-bot':+ 'The Slack bot browser is a documentation snapshot; a public repository is not available.',+ 'local-workbench':+ 'The local PR reviewer browser is a documentation snapshot; a public repository is not available.',+ standup:+ 'The standup bot browser is a documentation snapshot; a public repository is not available.',+ imessage:+ 'The iMessage implementation is maintained in [platform-imessage](https://github.com/ComposioHQ/platform-imessage).',+};++export function replaceRepoBrowserMarkdown(markdown: string): string {+ return markdown.replace(REPO_BROWSER_PATTERN, (_, props: string) => {+ const source = props.match(/\bsource="([^"]+)"/)?.[1] ?? 'slack-bot';+ const notice =+ REPO_BROWSER_NOTICES[source] ??+ 'This code browser is a documentation snapshot; a public repository is not available.';+ return `\n> ${notice}\n`;+ });+}diff --git a/docs/lib/source.ts b/docs/lib/source.tsindex 0f57e2a55..65d4386e9 100644--- a/docs/lib/source.ts+++ b/docs/lib/source.ts@@ -6,6 +6,7 @@ import { openapiSource, openapiPlugin } from 'fumadocs-openapi/server';import { getGuardrails } from './llm-guardrails';import { HIDDEN_API_TAGS } from './filter-api-version';import { FILE_BUILDS } from './file-builds';+import { replaceRepoBrowserMarkdown } from './repo-browser-markdown';import { deprecatedApiSidebarTransformer } from './deprecated-api-sidebar';/**@@ -297,18 +298,7 @@ export function mdxToCleanMarkdown(content: string): string {});- // RepoBrowser is an interactive file tree. The iMessage page intentionally- // shows a source slice while its public runnable fixture is still pending.- result = result.replace(- /<RepoBrowser\b(?=[^>]*\bsource="imessage")[^>]*\/>/g,- '\n> The iMessage code browser is an implementation slice, not a standalone fixture. The complete runnable project will be published in the Composio examples repo.\n'- );-- // Point the existing Slack browser at its real repository.- result = result.replace(- /<RepoBrowser\b[^>]*\/>/g,- '\n> The complete project is on GitHub: [composio-slack-bot](https://github.com/ComposioHQ/composio-slack-bot).\n'- );+ result = replaceRepoBrowserMarkdown(result);result = result.replace(/<\/?(ProviderGrid|Tabs|Frame|div|QuickstartFlow|IntegrationTabs|Accordions|ToolTypeFlow|ToolkitsLanding|TemplateGrid|Glossary|ConnectFlow|ConnectClientOption)[^>]*>/g, '');diff --git a/docs/package.json b/docs/package.jsonindex d28f7b600..3b6fc509d 100644--- a/docs/package.json+++ b/docs/package.json@@ -16,6 +16,7 @@"postinstall": "fumadocs-mdx","lint": "oxlint .","lint:links": "bun scripts/validate-links.ts",+ "lint:links:external": "bun scripts/validate-links.ts --external","sync:search": "bun scripts/sync-algolia-search.ts","test:search": "bun scripts/test-algolia-search.ts","eval:agent": "eve eval docs-agent --skip-report",diff --git a/docs/public/openapi-v3.json b/docs/public/openapi-v3.jsonindex 663ba8296..6e22a864e 100644--- a/docs/public/openapi-v3.json+++ b/docs/public/openapi-v3.json@@ -104,6 +104,12 @@{"name": "Tool Router","description": "(Labs) Tool router endpoints"+ },+ {+ "name": "Organization Management"+ },+ {+ "name": "Projects"}],"components": {diff --git a/docs/public/openapi.json b/docs/public/openapi.jsonindex 36cca228e..a282c7463 100644--- a/docs/public/openapi.json+++ b/docs/public/openapi.json@@ -104,6 +104,15 @@{"name": "Tool Router","description": "(Labs) Tool router endpoints"+ },+ {+ "name": "Invite Codes"+ },+ {+ "name": "Projects"+ },+ {+ "name": "Organization Management"}],"components": {diff --git a/docs/scripts/fetch-openapi.mjs b/docs/scripts/fetch-openapi.mjsindex 6749a0a90..5feb17c1a 100644--- a/docs/scripts/fetch-openapi.mjs+++ b/docs/scripts/fetch-openapi.mjs@@ -23,6 +23,7 @@ import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';import { z } from 'zod';import { fetchWithRetry } from './fetch-with-retry';+import { declareOperationTags } from '../lib/openapi-tags';import {PRODUCTION_BASE_URL,PRODUCTION_API_V3_URL,@@ -180,7 +181,7 @@ function forEachOperation(paths, callback) {}/**- * Filter paths: remove ignored/internal tags, keep first tag only.+ * Filter paths: remove ignored/internal tags, keep the first public tag only.*/function filterPaths(paths) {const filteredPaths = {};@@ -195,13 +196,14 @@ function filterPaths(paths) {const tags = operation.tags ?? [];const isInternal = operation['x-internal'] === true || tags.includes('x-internal');- const hasOnlyIgnoredTags = tags.length > 0 && tags.every(tag => IGNORED_TAGS.has(tag));+ const publicTags = tags.filter(tag => !IGNORED_TAGS.has(tag));+ const hasOnlyIgnoredTags = tags.length > 0 && publicTags.length === 0;if (isInternal || hasOnlyIgnoredTags) {delete filteredPathItem[method];removedCount++;- } else if (tags.length > 1) {- filteredPathItem[method] = { ...operation, tags: [tags[0]] };+ } else if (publicTags.length > 0) {+ filteredPathItem[method] = { ...operation, tags: [publicTags[0]] };}}@@ -340,6 +342,18 @@ function postProcessSpec(spec) {if (spec.tags) {spec.tags = spec.tags.filter(tag => !IGNORED_TAGS.has(tag.name));}+ // fumadocs-openapi only generates pages for operations whose tags are+ // declared top-level; the backend generator omits some (e.g. Projects).+ const declaredUpstream = new Set((spec.tags ?? []).map(tag => tag.name));+ declareOperationTags(spec);+ const addedTags = (spec.tags ?? []).filter(tag => !declaredUpstream.has(tag.name));+ if (addedTags.length > 0) {+ console.warn(+ `WARN: upstream spec uses tags missing from its top-level tags array: ${addedTags+ .map(tag => tag.name)+ .join(', ')}. Declared them automatically; the backend generator should emit them.`+ );+ }removeCookieAuthentication(spec);normalizeLargeObjectUnions(spec);diff --git a/docs/scripts/validate-links.ts b/docs/scripts/validate-links.tsindex f06ca9cdd..86700ff48 100644--- a/docs/scripts/validate-links.ts+++ b/docs/scripts/validate-links.ts@@ -15,6 +15,13 @@ import {toolkitsSource,} from '../lib/source';+/**+ * `--external` additionally HEAD/GET-checks every external URL. Slow and+ * dependent on third-party uptime, so it runs on a schedule (nightly CI),+ * never on the PR path.+ */+const checkExternalLinks = process.argv.includes('--external');+type AnySource =| typeof source| Awaited<ReturnType<typeof getReferenceSource>>@@ -90,6 +97,67 @@ async function getDynamicToolkitEntries() {return toolkits.map((t) => ({ value: { slug: [t.slug] }, hashes: [] as string[] }));}+const EXTERNAL_FETCH_HEADERS = {+ // Some hosts reject requests without a browser-like UA (bot filters).+ 'user-agent':+ 'Mozilla/5.0 (compatible; composio-docs-link-check; +https://docs.composio.dev)',+ accept: 'text/html,application/xhtml+xml;q=0.9,*/*;q=0.8',+};++async function fetchStatus(url: URL, method: 'HEAD' | 'GET'): Promise<number> {+ const response = await fetch(url, {+ method,+ headers: EXTERNAL_FETCH_HEADERS,+ redirect: 'follow',+ signal: AbortSignal.timeout(15_000),+ });+ await response.body?.cancel();+ return response.status;+}++const externalResultCache = new Map<+ string,+ Promise<{ success: true } | { success: false; message?: string }>+>();++/**+ * Replaces next-validate-link's default external validator (bare HEAD, no+ * timeout, no UA, no retry). This one only fails on evidence the link is dead+ * — 404/410, or a network error after a retry. Auth walls, rate limits, and+ * transient 5xx count as reachable: the nightly job hunts dead links, not+ * third-party uptime.+ */+function validateExternalUrl(url: URL) {+ if (url.hostname === 'localhost' || url.hostname === '127.0.0.1') {+ return Promise.resolve({ success: true as const });+ }+ const cached = externalResultCache.get(url.href);+ if (cached) return cached;++ const result = (async () => {+ for (let attempt = 0; attempt < 2; attempt++) {+ try {+ let status = await fetchStatus(url, 'HEAD');+ // Many servers reject HEAD (405, bot filters); confirm with GET.+ if (status >= 400) status = await fetchStatus(url, 'GET');+ if (status === 404 || status === 410) {+ return { success: false as const, message: `responded status ${status}` };+ }+ return { success: true as const };+ } catch (error) {+ if (attempt === 0) continue;+ return {+ success: false as const,+ message: error instanceof Error ? error.message : 'fetch failed',+ };+ }+ }+ return { success: false as const };+ })();+ externalResultCache.set(url.href, result);+ return result;+}+async function checkLinks() {const referenceSource = await getReferenceSource();const [docsEntries, refEntries, exampleEntries, toolkitEntries, dynamicToolkitEntries] = await Promise.all([@@ -119,6 +187,7 @@ async function checkLinks() {},},checkRelativePaths: 'as-url',+ checkExternal: checkExternalLinks ? { validate: validateExternalUrl } : false,});// Filter out API route URLs (these are valid but not detected as pages)diff --git a/docs/tests/static/api-reference-routes.test.ts b/docs/tests/static/api-reference-routes.test.tsnew file mode 100644index 000000000..4a94e0e9e--- /dev/null+++ b/docs/tests/static/api-reference-routes.test.ts@@ -0,0 +1,281 @@+/**+ * API reference route guards.+ *+ * fumadocs-openapi's tag grouping silently drops any operation whose tag is+ * not declared in the document's top-level `tags` array (preset-auto:+ * `builder.fromTagName(tag)` returns undefined -> `continue`, no warning).+ * The v10 -> v11 upgrade shipped exactly that: 16 operation pages vanished+ * from the site, sitemap, and search while the checked-in tag landing pages+ * kept rendering quick links that 404ed. Nothing else can catch this class:+ * validate-links only sees markdown links (ApiEndpointsTable hrefs live in a+ * JSX prop), and the integration suite samples fixed routes.+ *+ * Two guards, both derived from the shipped specs rather than snapshots so+ * routine spec syncs (docs-update-data) never churn them:+ * 1. Completeness — every operation/webhook a spec implies maps 1:1 to a page+ * the production loader path actually generates, regardless of the drop+ * mechanism.+ * 2. Quick links — every href serialized into an ApiEndpointsTable in+ * content/reference resolves to a generated page.+ */+import { describe, expect, test } from 'bun:test';+import { readFileSync, readdirSync } from 'node:fs';+import { join, relative } from 'node:path';+import { loader, multiple } from 'fumadocs-core/source';+import { createOpenAPI, openapiSource } from 'fumadocs-openapi/server';++import { openapi, openapiV3 } from '../../lib/openapi';+import { HIDDEN_API_TAGS } from '../../lib/filter-api-version';++const DOCS_DIR = join(import.meta.dir, '../..');++const HTTP_METHODS = [+ 'get',+ 'put',+ 'post',+ 'delete',+ 'options',+ 'head',+ 'patch',+ 'trace',+] as const;++interface SpecOperation {+ operationId?: string;+ tags?: string[];+}++interface SpecDocument {+ paths?: Record<string, Record<string, unknown>>;+ webhooks?: Record<string, Record<string, unknown>>;+}++/** Mirrors the default slugify in fumadocs-openapi's auto preset. */+function slugifyTag(tag: string): string {+ return tag.replace(/\s+/g, '-').toLowerCase();+}++/** Mirrors the hidden-tag URL filter applied in lib/source.ts. */+function isHiddenReferenceUrl(url: string): boolean {+ for (const tag of HIDDEN_API_TAGS) {+ if (+ url.startsWith(`/reference/api-reference/${tag}/`) ||+ url.startsWith(`/reference/v3/api-reference/${tag}/`)+ ) {+ return true;+ }+ }+ return false;+}++function* specOperations(document: SpecDocument): Generator<{+ location: string;+ operation: SpecOperation;+}> {+ for (const group of [document.paths, document.webhooks]) {+ for (const [key, pathItem] of Object.entries(group ?? {})) {+ for (const method of HTTP_METHODS) {+ const operation = pathItem?.[method];+ if (!operation || typeof operation !== 'object') continue;+ yield { location: `${method.toUpperCase()} ${key}`, operation };+ }+ }+ }+}++/**+ * URLs the spec implies: one page per visible (operation, tag) pair, named by+ * operationId — the scheme both fumadocs-openapi (groupBy: 'tag', name+ * algorithm v2) and generate-api-index.ts encode.+ */+function expectedReferenceUrls(document: SpecDocument, baseDir: string): Set<string> {+ const urls = new Set<string>();+ for (const { operation } of specOperations(document)) {+ for (const tag of operation.tags ?? []) {+ const tagSlug = slugifyTag(tag);+ if (HIDDEN_API_TAGS.has(tagSlug)) continue;+ urls.add(`/reference/${baseDir}/${tagSlug}/${operation.operationId}`);+ }+ }+ return urls;+}++function loadSpec(fileName: string): SpecDocument {+ return JSON.parse(readFileSync(join(DOCS_DIR, 'public', fileName), 'utf-8'));+}++/**+ * The reference URLs production actually serves, built through the same+ * pipeline as lib/source.ts getReferenceSource (minus the checked-in MDX+ * collection, which bun test cannot load and which contributes no operation+ * pages).+ */+async function generatedReferenceUrls(): Promise<Set<string>> {+ const [latest, v3] = await Promise.all([+ openapiSource(openapi, { groupBy: 'tag', baseDir: 'api-reference' }),+ openapiSource(openapiV3, { groupBy: 'tag', baseDir: 'v3/api-reference' }),+ ]);+ const referenceLoader = loader({+ baseUrl: '/reference',+ source: multiple({ openapi: latest, 'openapi-v3': v3 }),+ });+ return new Set(+ referenceLoader+ .getPages()+ .map((page) => page.url)+ .filter((url) => !isHiddenReferenceUrl(url)),+ );+}++const generatedUrlsPromise = generatedReferenceUrls();++describe('API reference route completeness', () => {+ test('every visible operation declares a tag and an operationId', () => {+ const violations: string[] = [];+ for (const fileName of ['openapi.json', 'openapi-v3.json', 'openapi-webhooks.json']) {+ for (const { location, operation } of specOperations(loadSpec(fileName))) {+ const visibleTags = (operation.tags ?? []).filter(+ (tag) => !HIDDEN_API_TAGS.has(slugifyTag(tag)),+ );+ // Untagged operations fall into fumadocs' synthetic "unknown" tag,+ // which is never declared — the page silently vanishes.+ if ((operation.tags ?? []).length === 0) {+ violations.push(`${fileName}: ${location} has no tags`);+ }+ // Without an operationId, fumadocs falls back to a path-derived file+ // name while generate-api-index derives the href from the summary —+ // the quick link is guaranteed to 404.+ if (visibleTags.length > 0 && !operation.operationId) {+ violations.push(`${fileName}: ${location} has no operationId`);+ }+ }+ }++ expect(violations, violations.join('\n')).toEqual([]);+ });++ test('every spec operation and webhook yields exactly one generated page', async () => {+ const expected = new Set<string>([+ ...expectedReferenceUrls(loadSpec('openapi.json'), 'api-reference'),+ ...expectedReferenceUrls(loadSpec('openapi-webhooks.json'), 'api-reference'),+ ...expectedReferenceUrls(loadSpec('openapi-v3.json'), 'v3/api-reference'),+ ]);+ const generated = await generatedUrlsPromise;++ const missing = [...expected].filter((url) => !generated.has(url)).sort();+ const extra = [...generated].filter((url) => !expected.has(url)).sort();++ expect(expected.size).toBeGreaterThan(0);+ expect(+ missing,+ `pages implied by the OpenAPI specs but not generated (silently dropped):\n${missing.join('\n')}`,+ ).toEqual([]);+ expect(+ extra,+ `generated pages not implied by the OpenAPI specs:\n${extra.join('\n')}`,+ ).toEqual([]);+ });++ test('the completeness diff flags operations whose tag is undeclared', async () => {+ // The exact v10 -> v11 regression, in miniature: "Projects" is used by an+ // operation but missing from the top-level tags array, and lib/openapi's+ // declareOperationTags normalization is deliberately not applied.+ const document = {+ openapi: '3.0.0',+ info: { title: 'Guard fixture', version: '1' },+ tags: [{ name: 'Auth' }],+ paths: {+ '/v3.1/project/usage/summary': {+ post: {+ tags: ['Projects'],+ operationId: 'postProjectUsageSummary',+ summary: 'Usage summary',+ responses: { '200': { description: 'ok' } },+ },+ },+ '/v3.1/auth/session': {+ get: {+ tags: ['Auth'],+ operationId: 'getSession',+ summary: 'Session',+ responses: { '200': { description: 'ok' } },+ },+ },+ },+ };++ const server = createOpenAPI({ input: { 'guard-fixture.json': document } });+ const source = await openapiSource(server, { groupBy: 'tag', baseDir: 'api-reference' });+ const generated = new Set(+ loader({ baseUrl: '/reference', source }).getPages().map((page) => page.url),+ );+ const missing = [...expectedReferenceUrls(document, 'api-reference')].filter(+ (url) => !generated.has(url),+ );++ // fumadocs-openapi still silently drops the undeclared tag...+ expect(generated.has('/reference/api-reference/auth/getSession')).toBe(true);+ // ...and the completeness diff is what surfaces the loss. If this ever+ // fails with `missing` empty, upstream fixed the silent drop and the+ // declareOperationTags workaround in lib/openapi.ts can be retired.+ expect(missing).toEqual([+ '/reference/api-reference/projects/postProjectUsageSummary',+ ]);+ });+});++describe('API reference quick links', () => {+ function mdxFiles(dir: string): string[] {+ const files: string[] = [];+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const fullPath = join(dir, entry.name);+ if (entry.isDirectory()) files.push(...mdxFiles(fullPath));+ else if (entry.name.endsWith('.mdx')) files.push(fullPath);+ }+ return files;+ }++ /** Parses the serialized endpoints of every ApiEndpointsTable in a file. */+ function parseEndpointHrefs(content: string, file: string): string[] {+ const hrefs: string[] = [];+ const prefix = /<ApiEndpointsTable endpoints=\{/g;+ let match: RegExpExecArray | null;+ while ((match = prefix.exec(content)) !== null) {+ const start = match.index + match[0].length;+ const end = content.indexOf('} />', start);+ expect(end, `${file}: unterminated ApiEndpointsTable`).toBeGreaterThan(start);+ const endpoints: { href: string }[] = JSON.parse(content.slice(start, end));+ hrefs.push(...endpoints.map((endpoint) => endpoint.href));+ }+ // A file mentioning the component but yielding no parsed table means the+ // generator's serialization drifted from this extractor — fail loudly+ // instead of silently checking nothing.+ if (content.includes('<ApiEndpointsTable')) {+ expect(hrefs.length, `${file}: found ApiEndpointsTable but extracted no hrefs`).toBeGreaterThan(0);+ }+ return hrefs;+ }++ test('every ApiEndpointsTable href resolves to a generated reference page', async () => {+ const generated = await generatedUrlsPromise;+ const dead: string[] = [];+ let totalHrefs = 0;++ for (const file of mdxFiles(join(DOCS_DIR, 'content/reference'))) {+ const content = readFileSync(file, 'utf-8');+ for (const href of parseEndpointHrefs(content, relative(DOCS_DIR, file))) {+ totalHrefs++;+ if (!generated.has(href)) {+ dead.push(`${relative(DOCS_DIR, file)}: ${href}`);+ }+ }+ }++ // Sanity: the extractor must have found the generated landing pages.+ expect(totalHrefs).toBeGreaterThan(0);+ expect(+ dead,+ `quick links pointing at reference pages that are never generated (would 404):\n${dead.join('\n')}`,+ ).toEqual([]);+ });+});diff --git a/docs/tests/static/openapi-tags.test.ts b/docs/tests/static/openapi-tags.test.tsnew file mode 100644index 000000000..b5bfc4f17--- /dev/null+++ b/docs/tests/static/openapi-tags.test.ts@@ -0,0 +1,89 @@+import { describe, expect, test } from 'bun:test';++import { declareOperationTags } from '../../lib/openapi';++describe('declareOperationTags', () => {+ test('declares operation tags missing from the top-level tags array', () => {+ const document = {+ tags: [{ name: 'Auth', description: 'Auth endpoints' }],+ paths: {+ '/project/usage/summary': {+ post: { tags: ['Projects'] },+ },+ '/auth/session': {+ get: { tags: ['Auth'] },+ },+ '/org/members': {+ get: { tags: ['Organization Management', 'Projects'] },+ },+ },+ };++ declareOperationTags(document);++ expect(document.tags).toEqual([+ { name: 'Auth', description: 'Auth endpoints' },+ { name: 'Projects' },+ { name: 'Organization Management' },+ ]);+ });++ test('covers webhook operations and documents without a tags array', () => {+ const document: {+ tags?: { name: string }[];+ webhooks: Record<string, Record<string, { tags?: string[] }>>;+ } = {+ webhooks: {+ 'trigger.fired': {+ post: { tags: ['Webhook Events'] },+ },+ },+ };++ declareOperationTags(document);++ expect(document.tags).toEqual([{ name: 'Webhook Events' }]);+ });++ test('leaves a fully declared document unchanged', () => {+ const tags = [{ name: 'Auth' }];+ const document = {+ tags,+ paths: {+ '/auth/session': {+ get: { tags: ['Auth'] },+ },+ },+ };++ declareOperationTags(document);++ expect(document.tags).toBe(tags);+ });++ test('every shipped spec declares all operation tags', async () => {+ for (const specPath of [+ 'public/openapi.json',+ 'public/openapi-v3.json',+ 'public/openapi-webhooks.json',+ ]) {+ const document = JSON.parse(+ await Bun.file(new URL(`../../${specPath}`, import.meta.url)).text(),+ );+ const declared = new Set(+ (document.tags ?? []).map((tag: { name: string }) => tag.name),+ );+ for (const group of [document.paths, document.webhooks]) {+ for (const pathItem of Object.values(group ?? {})) {+ for (const operation of Object.values(+ pathItem as Record<string, { tags?: string[] } | undefined>,+ )) {+ for (const tag of operation?.tags ?? []) {+ expect(declared.has(tag)).toBe(true);+ }+ }+ }+ }+ }+ });+});diff --git a/docs/tests/static/source.test.ts b/docs/tests/static/source.test.tsnew file mode 100644index 000000000..5de6d332f--- /dev/null+++ b/docs/tests/static/source.test.ts@@ -0,0 +1,26 @@+import { describe, expect, test } from 'bun:test';++import { replaceRepoBrowserMarkdown } from '../../lib/repo-browser-markdown';++describe('replaceRepoBrowserMarkdown', () => {+ test('emits source-aware RepoBrowser availability notices', () => {+ const markdown = replaceRepoBrowserMarkdown(`+<RepoBrowser />+<RepoBrowser source="local-workbench" />+<RepoBrowser source="standup" />+<RepoBrowser source="imessage" />+<RepoBrowser source="unknown" />+`);++ expect(markdown).toContain('The Slack bot browser is a documentation snapshot');+ expect(markdown).toContain('The local PR reviewer browser is a documentation snapshot');+ expect(markdown).toContain('The standup bot browser is a documentation snapshot');+ expect(markdown).toContain(+ '[platform-imessage](https://github.com/ComposioHQ/platform-imessage)',+ );+ expect(markdown).toContain(+ 'This code browser is a documentation snapshot; a public repository is not available.',+ );+ expect(markdown).not.toContain('composio-slack-bot');+ });+});diff --git a/docs/tests/static/webhook-openapi.test.ts b/docs/tests/static/webhook-openapi.test.tsindex 56b3cad99..eba84bfa4 100644--- a/docs/tests/static/webhook-openapi.test.ts+++ b/docs/tests/static/webhook-openapi.test.ts@@ -135,4 +135,35 @@ describe('REST OpenAPI processing', () => {]);expect(payload.paths['/visible'].get.operationId).toBe('getV3_1Visible');});++ test('declares operation tags missing from the top-level tags array', () => {+ const payload = createApiSpec();+ (payload.paths as Record<string, unknown>)['/project/usage/summary'] = {+ post: {+ tags: ['Projects'],+ operationId: 'postProjectUsageSummary',+ },+ };++ const { spec } = prepareApiSpec(payload, '3.1');++ expect(spec.tags).toEqual([{ name: 'Public' }, { name: 'Projects' }]);+ });++ test('keeps the first non-ignored tag from mixed-tag operations', () => {+ const payload = createApiSpec();+ payload.tags.push({ name: 'Admin' });+ (payload.paths as Record<string, unknown>)['/projects'] = {+ get: {+ tags: ['Admin', 'Projects'],+ operationId: 'getProjects',+ },+ };++ const { spec } = prepareApiSpec(payload, '3.1');++ expect(spec.paths['/projects'].get.tags).toEqual(['Projects']);+ expect(spec.tags).toContainEqual({ name: 'Projects' });+ expect(spec.tags).not.toContainEqual({ name: 'Admin' });+ });});