#!/usr/bin/env node /** * Documentation Generator for Apicity Providers * * Generates README.md files with a collapsible API Reference section * sourced from the endpoint walker + endpoint-docs.tsv. * * node scripts/doc-gen.mjs # regenerate every provider README * node scripts/doc-gen.mjs # regenerate one provider README * node scripts/doc-gen.mjs --check # exit 1 if any README is stale * * Also refreshes docs/frontier.md from the checked-in frontier snapshots. * That file is never downloaded. * * Every mode exits 1 before rendering anything when an `ENDPOINT_NOTES` key * matches no generated endpoint. */ import { spawnSync } from "node:child_process"; import fs from "node:fs/promises"; import fsSync from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { loadProject, walkAllEndpoints, METHOD_KEYS, STREAM_KEYS, PROVIDERS, TSV_ONLY_PROVIDERS, } from "./lib/endpoint-walk.mjs"; import { displayDotPath, resolveEndpointLabels, } from "./lib/endpoint-labels.mjs"; import { syncFrontierDoc } from "./lib/frontier-models.mjs"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const REPO_ROOT = path.resolve(__dirname, ".."); const TSV_PATH = path.join(__dirname, "endpoint-docs.tsv"); const COST_TIERS_TSV_PATH = path.join(__dirname, "endpoint-cost-tiers.tsv"); function loadCostTierMap() { const map = new Map(); if (!fsSync.existsSync(COST_TIERS_TSV_PATH)) return map; const text = fsSync.readFileSync(COST_TIERS_TSV_PATH, "utf8"); const lines = text.split("\n").filter(Boolean); for (let i = 1; i < lines.length; i++) { const [provider, dotPath, method, tier] = lines[i].split("\t"); map.set(`${provider}\t${dotPath}\t${method}`, tier); } return map; } // Canonical per-endpoint cost tier (from @apicity/cost via the generated // scripts/endpoint-cost-tiers.tsv). Surfaced in each endpoint's docs. const COST_TIER_MAP = loadCostTierMap(); function loadEndpointDocsRows() { const rows = []; if (!fsSync.existsSync(TSV_PATH)) return rows; const text = fsSync.readFileSync(TSV_PATH, "utf8"); const lines = text.split("\n").filter(Boolean); for (let i = 1; i < lines.length; i++) { const [provider, dotPath, method, fullUrl, docsUrl] = lines[i].split("\t"); rows.push({ provider, dotPath, method, fullUrl, docsUrl: docsUrl ?? "", }); } return rows; } function loadDocsTsv() { const byKey = new Map(); const byDotPath = new Map(); for (const row of loadEndpointDocsRows()) { byKey.set(`${row.provider}\t${row.dotPath}\t${row.method}`, row); const dotPathKey = `${row.provider}\t${row.dotPath}`; const rows = byDotPath.get(dotPathKey) ?? []; rows.push(row); byDotPath.set(dotPathKey, rows); } return { byKey, byDotPath }; } function cleanTsvValue(value) { return value && value !== "?" ? value : null; } /** * The logical dot path of a leaf literally named `stream`, `ws` or `run`, with * that leaf kept: `logicalDotPath` drops those names wherever they sit, but * fal's `v1.serverless.logs.stream` and simplefunctions' * `api.dashboard2.marketWatch.panels.run` are tsv rows under the full name. * Null for any other leaf, so no other block's lookup changes. * * @param {string} providerName * @param {{ fullDotPath?: string }} ep * @returns {string | null} */ function leafDotPath(providerName, ep) { const segs = String(ep.fullDotPath ?? "") .split(".") .filter(Boolean); const leaf = segs[segs.length - 1]; if (!leaf || !STREAM_KEYS.has(leaf.toLowerCase())) return null; const kept = segs .slice(0, -1) .filter((seg) => !isCollapsedSegment(seg, providerName)); return [...kept, leaf].join("."); } /** * The `scripts/endpoint-docs.tsv` row that documents one rendered block. * * `label` is the heading the block renders under (from `resolveEndpointLabels`) * and is tried first: a row naming the rendered label describes exactly that * block. `displayDotPath` stays in the list as the *fallback* that keeps a * relabelled stream sibling on its canonical sibling's row while no row names * the label itself. */ function resolveEndpointDocRow(docs, ep, providerName, label) { const displayPath = displayDotPath(providerName, ep); const dotPaths = [ ...new Set( [label, displayPath, ep.dotPath, leafDotPath(providerName, ep)].filter( Boolean ) ), ]; const method = ep.method ?? "?"; for (const dotPath of dotPaths) { const row = docs.byKey.get(`${ep.provider}\t${dotPath}\t${method}`); if (row) return row; } for (const dotPath of dotPaths) { const rows = docs.byDotPath.get(`${ep.provider}\t${dotPath}`) ?? []; const concreteRows = rows.filter( (row) => cleanTsvValue(row.method) || cleanTsvValue(row.fullUrl) ); if (concreteRows.length === 1) return concreteRows[0]; } return null; } export async function collectEndpointsByProvider() { const project = loadProject(); const byProvider = new Map(); for await (const ep of walkAllEndpoints(project)) { const list = byProvider.get(ep.provider) ?? []; list.push(ep); byProvider.set(ep.provider, list); } for (const provider of TSV_ONLY_PROVIDERS) { const endpoints = loadEndpointDocsRows() .filter((row) => row.provider === provider) .map((row) => ({ ...row, file: `packages/provider/${provider}/src/${provider}.ts`, factory: resolveFactory(provider), fullDotPath: row.dotPath, path: row.fullUrl, })); byProvider.set(provider, endpoints); } return byProvider; } function sectionKey(dotPath) { if (!dotPath) return "general"; const segments = dotPath.split("."); for (const seg of segments) { if (/^v\d+$/i.test(seg)) continue; if (seg === "api") continue; return seg; } return "general"; } /** * Whether one parameter is the cancellation slot every endpoint takes, * `signal?: AbortSignal`. The rule is `isSignalParam`'s in * `scripts/gen-call-shapes.mjs`: the declared type must be exactly the signal, * because several overloaded endpoints declare a union that merely includes it * (`modelIdOrSignal?: string | AbortSignal`), and those are real inputs. */ function isSignalParam(param) { const typeText = (param.getTypeNode()?.getText() ?? "").trim(); if (typeText === "AbortSignal" || typeText === "AbortSignal | undefined") { return true; } return param.getName() === "signal" && typeText === ""; } /** * Whether a walked leaf takes no argument: its function declares no parameter * but an optional `AbortSignal`, so its usage snippet is a bare `()` call. The * generic request placeholder would land in the signal slot, where it does not * type-check. A helper-built leaf (`jsonBody(...)` and its siblings) always * takes a request, and a TSV-only endpoint has no leaf, so both keep the * placeholder. * * @param {{leafNode?: import("ts-morph").Node}} ep * @returns {boolean} */ export function takesNoArgument(ep) { const leaf = ep.leafNode; if (typeof leaf?.getParameters !== "function") return false; return leaf .getParameters() .every( (param) => isSignalParam(param) && (param.hasQuestionToken() || param.hasInitializer()) ); } // The provider's name as a variable in README code: a hyphenated name // (free-media-upload) is not a valid identifier, so it is camelCased. function providerVariable(providerName) { return providerName.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase()); } function formatUsageSnippet( providerName, dotPath, callPath = dotPath, noArgument = false ) { // `dotPath` is the collapsed display label. Special cases match that label. // `callPath` is the copy-pasteable path, which may put back a verb or leaf // the label dropped (ac-kqdzn9). const variable = providerVariable(providerName); const call = callPath ? `${variable}.${callPath}` : variable; if ( providerName === "google" && dotPath === "v1.publishers.google.models.countTokens" ) { return [ `const res = await ${call}(`, ' "gemini-2.5-flash",', " {", ' contents: [{ role: "user", parts: [{ text: "How does AI work?" }] }],', " }", ");", ].join("\n"); } if ( providerName === "google" && dotPath === "v1.publishers.google.models.generateContent" ) { return [ `const res = await ${call}(`, ' "gemini-2.5-flash",', " {", ' contents: [{ role: "user", parts: [{ text: "How does AI work?" }] }],', " }", ");", ].join("\n"); } if ( providerName === "google" && dotPath === "v1.projects.locations.global.publishers.google.models.generateContent" ) { return [ `const res = await ${call}(`, ' "your-project-id",', ' "gemini-nano-banana-2.1",', " {", ' contents: [{ role: "user", parts: [{ text: "A red origami crane" }] }],', " generationConfig: {", ' responseModalities: ["IMAGE"],', ' imageConfig: { aspectRatio: "1:1", imageSize: "1K" },', " },", " }", ");", ].join("\n"); } if (providerName === "openligadb" && dotPath === "getavailablesports") { return `const sports = await ${call}();`; } if (providerName === "endless" && dotPath === "social.tiktokTrends.public") { return `const trends = await ${call}({ region: "thailand" });`; } if (providerName === "endless" && dotPath === "social.trends.public") { return `const trends = await ${call}({ region: "worldwide" });`; } if ( providerName === "tiktok-creative-center" && dotPath === "ads.creativeOne.report.getTopContentsOverview" ) { return `const overview = await ${call}();`; } if ( providerName === "tiktok-creative-center" && dotPath === "ads.creativeOne.report.creativeCenterGetTopContentsList" ) { return [ `const top = await ${call}({`, ' countryCode: "TH",', " periodDimension: 3,", " periodEndTimestamp: 1792886400,", " orderByMetric: 1,", "});", ].join("\n"); } if (providerName === "omkar" && dotPath === "feed.trending") { return `const feed = await ${call}({ country: "TH" });`; } if (providerName === "omkar" && dotPath === "feed.explore") { return `const feed = await ${call}({ country: "TH", category: "all" });`; } if (providerName === "omkar" && dotPath === "feed.explore.categories") { return `const categories = await ${call}();`; } if (providerName === "wavespeed" && dotPath === "api.v3.predictions.result") { return `const prediction = await ${call}("prediction_id");`; } if (providerName === "openf1" && dotPath === "token") { return [ `const token = await ${call}({`, ' username: "driver@example.com",', ' password: "placeholder-password",', "});", ].join("\n"); } if (providerName === "openligadb" && dotPath === "getavailableleagues") { return `const leagues = await ${call}();`; } if ( providerName === "openligadb" && dotPath === "getavailableleagues.bySeason" ) { return `const leagues = await ${call}({ season: 2024 });`; } if (providerName === "openligadb" && dotPath === "getavailablegroups") { return `const groups = await ${call}({ leagueShortcut: "bl1", leagueSeason: 2024 });`; } if (providerName === "openligadb" && dotPath === "getcurrentgroup") { return `const group = await ${call}({ leagueShortcut: "bl1" });`; } if (providerName === "openligadb" && dotPath === "getlastchangedate") { return [ `const changedAt = await ${call}({`, ' leagueShortcut: "bl1",', " leagueSeason: 2024,", " groupOrderId: 1,", "});", ].join("\n"); } if (providerName === "openligadb" && dotPath === "getresultinfos") { return `const resultInfo = await ${call}({ leagueId: 4500 });`; } if (providerName === "openligadb" && dotPath === "getavailableteams") { return `const teams = await ${call}({ leagueShortcut: "bl1", leagueSeason: 2024 });`; } if ( providerName === "openligadb" && (dotPath === "getnextmatchbyleagueteam" || dotPath === "getlastmatchbyleagueteam") ) { return [ `const match = await ${call}({`, " leagueId: 4500,", " teamId: 40,", "});", ].join("\n"); } if ( providerName === "openligadb" && (dotPath === "getnextmatchbyleagueshortcut" || dotPath === "getlastmatchbyleagueshortcut") ) { return `const match = await ${call}({ leagueShortcut: "bl1" });`; } if (providerName === "openligadb" && dotPath === "getmatchesbyteam") { return [ `const matches = await ${call}({`, ' teamFilterstring: "Bayern",', " weekCountPast: 4,", " weekCountFuture: 2,", "});", ].join("\n"); } if (providerName === "openligadb" && dotPath === "getmatchesbyteamid") { return [ `const matches = await ${call}({`, " teamId: 40,", " weekCountPast: 4,", " weekCountFuture: 2,", "});", ].join("\n"); } if (providerName === "elevenlabs" && dotPath === "v1.textToSpeech") { return `const res = await ${call}("voice_id", { /* ... */ });`; } if (providerName === "elevenlabs" && dotPath === "v1.voices") { return `const res = await ${call}("voice_id", { /* ... */ });`; } if (providerName === "elevenlabs" && dotPath === "v1.voices.settings") { return `const res = await ${call}("voice_id");`; } if (providerName === "elevenlabs" && dotPath === "v1.voices.pvc.captcha") { return [ "declare const recording: Blob;", "", `const res = await ${call}("voice_id", { recording });`, ].join("\n"); } if ( providerName === "elevenlabs" && dotPath === "v1.voices.pvc.captcha.get" ) { return `const res = await ${call}("voice_id");`; } if (providerName === "elevenlabs" && dotPath === "v1.voices.pvc.samples") { return `const res = await ${call}("voice_id", "sample_id", { /* ... */ });`; } if ( providerName === "elevenlabs" && (dotPath === "v1.voices.pvc.samples.delete" || dotPath === "v1.voices.pvc.samples.separateSpeakers" || dotPath === "v1.voices.pvc.samples.waveform") ) { return `const res = await ${call}("voice_id", "sample_id");`; } if ( providerName === "elevenlabs" && dotPath === "v1.voices.pvc.samples.speakers.audio" ) { return `const res = await ${call}("voice_id", "sample_id", "speaker_id");`; } if ( providerName === "elevenlabs" && (dotPath === "v1.voices.pvc.train" || dotPath === "v1.voices.pvc.verification") ) { return `const res = await ${call}("voice_id", { /* ... */ });`; } if ( providerName === "openligadb" && (dotPath === "getbltable" || dotPath === "getgrouptable") ) { return [ `const res = await ${call}({`, ' leagueShortcut: "bl1",', " leagueSeason: 2024,", "});", ].join("\n"); } if (providerName === "openligadb" && dotPath === "getgoalgetters") { return [ `const res = await ${call}({`, ' leagueShortcut: "bl1",', " leagueSeason: 2024,", "});", ].join("\n"); } if (providerName === "simplefunctions" && dotPath === "api.public.query") { return [ `const res = await ${call}({`, ' q: "Fed rate cut",', ' sources: ["kalshi", "polymarket"],', " limit: 3,", "});", ].join("\n"); } if (providerName === "simplefunctions" && dotPath === "data.v1.markets") { return [ `const res = await ${call}({`, ' q: "newsom",', ' venue: "kalshi",', "});", ].join("\n"); } if ( providerName === "simplefunctions" && dotPath === "data.v1.markets.featured" ) { return `const res = await ${call}({ n: 50 });`; } if ( providerName === "simplefunctions" && dotPath === "data.v1.markets.retrieve" ) { return `const res = await ${call}("KXPRESNOMD-28-GN");`; } if (providerName === "simplefunctions" && dotPath === "data.v1.search") { return [ `const res = await ${call}({`, ' q: "rate cut",', " limit: 10,", ' venue: "kalshi",', "});", ].join("\n"); } if (providerName === "simplefunctions" && dotPath === "data.v1.movers") { return [ `const res = await ${call}({`, ' window: "1h",', " n: 50,", " minVol: 1000,", ' dir: "both",', "});", ].join("\n"); } if (providerName === "simplefunctions" && dotPath === "data.v1.orderbook") { return `const res = await ${call}("KXPRESNOMD-28-GN");`; } if (providerName === "simplefunctions" && dotPath === "data.v1.candles") { return [ `const res = await ${call}("KXPRESNOMD-28-GN", {`, ' tf: "1h",', " limit: 500,", "});", ].join("\n"); } if (providerName === "simplefunctions" && dotPath === "data.v1.trades") { return `const res = await ${call}("KXPRESNOMD-28-GN", { limit: 50 });`; } if (providerName === "openligadb" && dotPath === "getmatchdata.byId") { return `const res = await ${call}({ matchId: 68720 });`; } if ( providerName === "openligadb" && dotPath === "getmatchdata.byLeagueSeason" ) { return [ `const res = await ${call}({`, ' leagueShortcut: "bl1",', " leagueSeason: 2024,", "});", ].join("\n"); } if ( providerName === "openligadb" && dotPath === "getmatchdata.byLeagueSeasonGroup" ) { return [ `const res = await ${call}({`, ' leagueShortcut: "bl1",', " leagueSeason: 2024,", " groupOrderId: 1,", "});", ].join("\n"); } if ( providerName === "openligadb" && dotPath === "getmatchdata.byLeagueSeasonTeam" ) { return [ `const res = await ${call}({`, ' leagueShortcut: "bl1",', " leagueSeason: 2024,", ' teamFilterstring: "Bayern",', "});", ].join("\n"); } if (providerName === "openligadb" && dotPath === "getmatchdata.byTeams") { return `const res = await ${call}({ teamId1: 16, teamId2: 40 });`; } if (providerName === "simplefunctions" && dotPath === "api.public.market") { return [ `const res = await ${call}({`, ' ticker: "KXRATECUT-26DEC31",', " depth: true,", "});", ].join("\n"); } if ( providerName === "simplefunctions" && dotPath === "api.public.market.history" ) { return [ `const res = await ${call}({`, ' ticker: "KXRATECUT-26DEC31",', "});", ].join("\n"); } if ( providerName === "simplefunctions" && dotPath === "api.public.market.candles" ) { return [ `const res = await ${call}({`, ' ticker: "KXRATECUT-26DEC31",', ' venue: "kalshi",', ' timeframe: "1m",', " limit: 500,", "});", ].join("\n"); } if (noArgument) return `const res = await ${call}();`; return `const res = await ${call}({ /* ... */ });`; } const KIE_GEMINI_HTTP_200_ERROR_NOTE = [ "> **HTTP 200 error bodies:** this method rejects with `KieError` when an", "HTTP 200 JSON body has no `candidates` array and carries either KIE's", "numeric `code` envelope (`{ code, msg }`, any `code` other than 200) or a", "top-level `error` object (such as KIE docs' `{ error: { message, type } }`", "or Google's `{ error: { code, message, status } }`).", ].join(" "); /** * README note for a Fireworks audio endpoint, deprecated upstream on 2026-06-10 * and kept callable because part of the family still answers (ac-8l1x3z). * `state` is what that endpoint's host did with a valid key on 2026-11-05. */ function fireworksDeprecatedAudioNote(state) { return [ "> **Deprecated:** Fireworks deprecated audio inference on 2026-06-10, gave", "no shutdown date, and no longer publishes a rate for it, so a cost", `estimate fails closed. On 2026-11-05 ${state}`, "This method still sends requests unchanged, but Fireworks may stop", "answering them without notice.", ].join(" "); } const FIREWORKS_AUDIO_HOSTS_STATE = [ "`audio-prod` answered 401 to a valid key on real and made-up paths alike,", "and `audio-turbo` answered 503 with no healthy upstream.", ].join(" "); const FIREWORKS_AUDIO_BATCH_STATE = [ "`audio-batch` answered `submitted` to an empty request with", "`endpoint_id=audio-prod` or `audio-turbo`, and the status endpoint answered", "404 for the ids it issued. Whether a real submission runs is unproven.", ].join(" "); /** * README notes for single endpoints, keyed `providerlabelmethod`: * the dot path the endpoint's README heading prints and the method its block * renders (`endpointNoteKey`). A key that names no rendered block fails the * run (`assertEndpointNotesMatch`) instead of dropping its note. */ export const ENDPOINT_NOTES = new Map([ [ "google\tv1.projects.locations.global.publishers.google.models.generateContent\tPOST", [ "Project-scoped global Vertex AI route, required by global-only models", "such as `gemini-nano-banana-2.1` (express mode routes to `europe-west1`", "and returns 404). Nano Banana 2.1 supports 1K/2K/4K image outputs across", "14 aspect ratios and up to 14 input images, and bills $1.50/1M input", "tokens ($0.15 cached), $7.50/1M text/reasoning output tokens, and $30/1M", "image output tokens (`usageMetadata`).", ].join(" "), ], [ "openai\tv1.images.generations\tPOST", [ "Serves `gpt-image-2.6-sunburst`, `gpt-image-2.6-flare`,", "`gpt-image-2.5-sunburst`, `gpt-image-2.5-flare`, `gpt-image-2` and", "`gpt-image-1.5`. The 2.6 models accept `complexity` (`low`, `medium` or", "`high`, default `high`, no extra fee) and `output_format` `gif` or", "`svg` (`svg` requires `n: 1`). `@apicity/cost` prices 2.6 raster", "images from the guide's calculator at $30/1M image output tokens", "(applying the `4.2` low and `3.3` medium multipliers) with a floor", "warning for unbilled input tokens; `auto`, `gif` and `svg` fail", "closed.", ].join(" "), ], [ "openai\tv1.images.edits\tPOST", [ "Serves `gpt-image-2.6-sunburst`, `gpt-image-2.6-flare`,", "`gpt-image-2.5-sunburst`, `gpt-image-2.5-flare` and `gpt-image-2`.", "Accepts `complexity` (`low`, `medium` or `high`), a visual `markup`", 'overlay alongside `image`, `WIDTHxHEIGHT` custom sizes and `"gif"`', "output (edits do not support `svg`). `@apicity/cost` prices 2.6", "raster outputs at $30/1M image output tokens as a floor.", ].join(" "), ], [ "nunchux\tv2.openai.images.generations\tPOST", [ "> **Board setting:** Artificial Analysis ranks GPT Image 2.6 Sunburst", "and Flare at quality max. Nunchux does not offer OpenAI's `xhigh` or", "`max` (re-read 2026-11-19,", "[GPT Image](https://docs.nunchux.ai/partner-models/gpt-image)), so that", "setting cannot be reproduced. The highest quality on this route is", "`high`, and `auto` renders at `high`. `quality` of `xhigh` or `max`", "is rejected. Both `gpt-image-2.6-sunburst` and `gpt-image-2.6-flare`", "bill $5 / $8 / $30 per 1M text-input / image-input / image-output", "tokens ([pricing](https://nunchux.ai/pricing)). The call is", "synchronous and returns base64. A generation body must not send", "`images`, `mask`, `markup`, `stream` or `partial_images`.", ].join(" "), ], [ "nunchux\tv2.openai.images.edits\tPOST", [ "> **Board setting:** Artificial Analysis ranks GPT Image 2.6 Sunburst", "and Flare at quality max. Nunchux does not offer OpenAI's `xhigh` or", "`max` (re-read 2026-11-19,", "[GPT Image](https://docs.nunchux.ai/partner-models/gpt-image)), so that", "setting cannot be reproduced. The highest quality on this route is", "`high`, and `auto` renders at `high`. Both `gpt-image-2.6-sunburst`", "and `gpt-image-2.6-flare` bill $5 / $8 / $30 per 1M text-input /", "image-input / image-output tokens", "([pricing](https://nunchux.ai/pricing)). Input images, the mask and", "the markup count as image input. The call is synchronous and returns", "base64. `images` is required, 1 to 16 `image_url` values, each an", "https URL or a `data:image` URI. Send `mask` or `markup`, not both.", "`stream` and `partial_images` are not offered.", ].join(" "), ], [ "fireworks\tinference.v1.audio.transcriptions\tPOST", fireworksDeprecatedAudioNote(FIREWORKS_AUDIO_HOSTS_STATE), ], [ "fireworks\tinference.v1.audio.translations\tPOST", fireworksDeprecatedAudioNote(FIREWORKS_AUDIO_HOSTS_STATE), ], [ "fireworks\tinference.v1.audio.batch.transcriptions\tPOST", fireworksDeprecatedAudioNote(FIREWORKS_AUDIO_BATCH_STATE), ], [ "fireworks\tinference.v1.audio.batch.translations\tPOST", fireworksDeprecatedAudioNote(FIREWORKS_AUDIO_BATCH_STATE), ], [ "fireworks\tinference.v1.audio.batch\tGET", fireworksDeprecatedAudioNote(FIREWORKS_AUDIO_BATCH_STATE), ], [ "polymarket\tclob.markets\tGET", [ "> **Legacy compatibility:** current public market discovery is documented", "on the Gamma `/markets` pages. The CLOB `/markets` compatibility path", "is retained for existing callers and is documented by the CLOB OpenAPI", "spec.", ].join(" "), ], [ "polymarket\tgamma.events\tGET", [ "> **Deprecated upstream:** the replay fixture for the list form", "`GET /events?...` returned `Deprecation: true`,", "`Sunset: Fri, 01 May 2026 00:00:00 GMT`, and", '`Warning: 299 - "use /events/keyset"`. This compatibility method', "remains for existing bare-array `/events` callers; prefer", "`polymarket.gamma.events.keyset()` for new paginated event lists.", ].join(" "), ], [ "kie\tgemini.post.v1.models.gemini36Flash.streamGenerateContent\tPOST", KIE_GEMINI_HTTP_200_ERROR_NOTE, ], [ "kie\tgemini.post.v1.models.gemini37Flash.streamGenerateContent\tPOST", KIE_GEMINI_HTTP_200_ERROR_NOTE, ], [ "kie\tgemini.post.v1.models.gemini38Flash.streamGenerateContent\tPOST", KIE_GEMINI_HTTP_200_ERROR_NOTE, ], [ "kie\tpost.anthropic.v1.messages\tPOST", [ "> **Latency:** this method uses the `createKie` `timeout`, which", "defaults to 30 s (30000 ms). KIE's agent proxy has answered it more", "slowly than that: the slowest successful call observed took 108 s", "(2026-09-30). Pass a larger `timeout` in milliseconds to", "`createKie`, for example `createKie({ apiKey, timeout: 300_000 })`.", "The option applies to every method of that client.", ].join(" "), ], [ "machgen\tapi.v0.upscale.quote\tPOST", [ "> **Undocumented upstream:** MachGen's REST docs do not list this", "endpoint (read 2026-10-26), so MachGen may change or remove it without", "notice. MachGen's web app prices an upscale with it before submitting,", "and the MCP server's `quote_video_upscale` tool", "([docs](https://www.machgen.ai/docs/mcp#tools)) is the documented form", "of the same check. The quote is free, creates no task and answers", "`{ cost_micros }`, the micro-USD the upscale of a source you own would", "bill; a recorded Topaz upscale billed exactly its quote. On 2026-10-26 a", "2160p Topaz Video Generative Fast upscale of a 4 s 480p task quoted", "596000 micros (recording", "`machgen/topaz-video-generative-fast-upscale-quote`).", "`resolveMachGenUpscaleEstimate` in `@apicity/cost` turns a quote into", "an estimate.", ].join(" "), ], [ "machgen\tapi.v0.adapters.create\tPOST", [ "> **Write capability:** the reserve answers a one-time `upload_url`", "that takes the `.safetensors` weights by `PUT` for 7 days, and anyone", "holding it can write the file, so keep it out of logs and recordings.", "apicity's recording of this call keeps only `https://storage.googleapis.com/***`.", "Reserving bills nothing, and `MiniMax-H3` is the only model with custom", "LoRAs (read 2026-11-11). `model` goes in the `?model=` query and the", "rest in the JSON body. Send the file to the latest `upload_url`, then", "commit it (`POST /api/v0/adapters/{adapter_id}/commit`). Reserving the", "same file and configs again returns the same `adapter` id and a fresh", "`upload_url`, which retires the previous one.", ].join(" "), ], [ "machgen\tapi.v0.adapters.commit\tPOST", [ "> **Send the file first:** `PUT` the `.safetensors` bytes to the", "reserve's `upload_url` with `Content-Type: application/octet-stream`.", "That URL belongs to Google Cloud Storage, not MachGen, so apicity has", "no method for it. Commit then checks the file's size, MD5 and", 'safetensors header and answers the upload with `status: "ready"`', "(without `expires_at`, `chunk_size` or `upload_url`, read 2026-11-11).", "It bills nothing and is safe to repeat. A 409 means the file has not", "arrived or a newer reserve replaced its URL: reserve again and resend.", ].join(" "), ], ]); const PROVIDER_NOTES = new Map([ [ "nunchux", "Nunchux account credits and plan limits. `v1.credits()` is free and " + "takes no job slot, but counts toward the request rate limit. " + "Authentication uses `Authorization: Bearer`. `NunchuxError` preserves " + "the HTTP status, error code and body across standard and partner errors.", ], [ "omkar", [ "Omkar Cloud's TikTok Scraper scrapes TikTok live on every call, so a", "feed call returns a fresh batch each time. The key goes in the", "`API-Key` header. The free plan allows 1,000 successful (HTTP 200)", "requests a month; errors are not charged, and", "`GET https://tiktok-scraper.omkar.cloud/account/usage` reports usage", "without spending a request. Every gateway error is JSON with a stable", "`code` (`missing_api_key`, `invalid_api_key`, `quota_exceeded`,", "`rate_limited`, ...), which rejects with `OmkarError` (`code`).", "Media and subtitle links are signed TikTok CDN URLs that expire.", ].join(" "), ], [ "wavespeed", [ "WaveSpeed runs one endpoint per model id: a model call answers at once", "with a prediction id in `data.id`, and `api.v3.predictions.result`", "reads that prediction until `data.status` is `completed`, when", "`data.outputs` holds the results, or `failed`, `cancelled`, `timeout`", "or `deleted`. Poll at least 2 s apart, and never resubmit a model call", "automatically: a submit whose answer was lost may still have created,", "and billed, a task. The key goes in `Authorization: Bearer`. API", "errors answer `{ code, message }` and reject with `WaveSpeedError`,", "whose `code` is that envelope code (404 for an unknown prediction).", "Output URLs are temporary.", ].join(" "), ], [ "tiktok-creative-center", [ "These are unofficial, undocumented endpoints behind TikTok Creative", "Center's Trending videos page", "(https://ads.tiktok.com/creative/creativeCenter/trends/video), and", "TikTok can change or remove them without notice. They need no key.", "Without a TikTok One session every list holds the top 4 rows of", "page 1, whatever `page` and `limit` ask, and the client does not", "support a session cookie. TikTok sends item, author and creator ids as", "JSON numbers above 2^53, so `itemID`, `authorID` and `creatorID` come", "back as strings with every digit. Creative Center reports a failure as", "HTTP 200 with a nonzero `BaseResp.StatusCode`, which rejects with", "`TiktokCreativeCenterError` (`statusCode`). The overview reports the", "latest daily, weekly and monthly period ends, the values a list's", "`periodEndTimestamp` takes. A row's video page is", "`https://www.tiktok.com/@/video/`; `videoURL`", "is a signed CDN link that expires.", ].join(" "), ], [ "endless", [ "Endless's public social endpoints need no key; its authenticated API", "is not covered. `region` is a slug from", "`EndlessTikTokTrendsRegionSchema.options` for TikTok trends or", "`EndlessTrendsRegionSchema.options` for X trends, and any other value", "is a 404 whose `EndlessError.code` is `invalid_path_parameter`. Every", "call sends `Endless-Api-Version: 1` unless `apiVersion` names another", "major.", ].join(" "), ], [ "openai", [ "Realtime voice over WebRTC: `openai.post.v1.realtime.calls({ sdp,", "session })` sends the browser's SDP offer and resolves to the SDP", "answer plus the `callId` (from the `Location` header). The", "`@apicity/openai/realtime` subpath exports `connectOpenAiRealtime`, which", "opens a server-side WebSocket to that call (`callId`) or to a new", "session (`model`): `send()` client events such as `session.update`, and", "receive server events through `onEvent`.", "`openai.post.v1.realtime.calls.hangup(callId)` ends the call.", ].join(" "), ], [ "binance", [ "Binance coverage is focused on public REST market-data reads across", "Spot, USD-M Futures, COIN-M Futures, and Options.", "The COIN-M Old Trades Lookup endpoint (`GET /dapi/v1/historicalTrades`) is intentionally not exposed because Binance requires an API key for it.", "USD-M Old Trades Lookup (`GET /fapi/v1/historicalTrades`), signed trade, account, and user endpoints are out of scope.", ].join(" "), ], [ "simplefunctions", [ "SimpleFunctions exposes two REST surfaces here: analytical Query API", "calls use `https://simplefunctions.dev`, while real-time market-data", "calls under `simplefunctions.data.v1.*` use the separate", "`https://data.simplefunctions.dev/v1` data API base URL.", "Authenticated dashboard, thesis, portfolio, alerting, tool, and runtime", "routes also live under `simplefunctions.api.*` on the analytical host.", "`simplefunctions.api.public.market({ ticker })` mirrors", "`sf inspect --json`; pass `depth: true` for the public", "orderbook view used by `sf book --json`.", "The current public WebSocket endpoint is `wss://app.simplefunctions.dev/ws`;", "do not model `wss://data.simplefunctions.dev/v1/ws` as active until", "upstream routing changes.", ].join(" "), ], [ "openligadb", [ "OpenLigaDB is a public read-only API. `createOpenLigaDB()` does not", "take credentials, and the provider does not send auth headers.", ].join(" "), ], // Return types stay generic by design (GF-S4..S10); the typed path is the // exported response schemas (ac-j3d6ki.7). [ "googleflow", [ "Every method resolves to the generic `GoogleFlowResponse` and never", "validates the response body. For typed access, parse the result with", "the response schema the package exports for that endpoint; each schema", "has a same-name `z.output` type. For example,", "`GoogleFlowImagesResponseSchema.parse(await flow.v1.images(req))` types", "`media[].image.generatedImage.fifeUrl`. The schemas follow useapi.net's", "documented response models and are not yet verified against live", "responses, so parsing reports any drift instead of trusting it.", ].join(" "), ], [ "machgen", [ "Image generation uses the same `api.v0.generate` method: set", "`task_type` to `T2I` or `I2I` and supply `image_config` with `height`", "and optional `width`/`aspect_ratio`. For automatic sizing on GPT Image, send", '`image_config: { size_mode: "auto" }` and omit `height`, `width` and `aspect_ratio`.', "Automatic sizing has no upfront cost estimate. The frontier image IDs are", "`GPT-Image-2`, `GPT-Image-2.5-Sunburst`, `GPT-Image-2.5-Flare`,", "`GPT-Image-2.6-Sunburst`, `GPT-Image-2.6-Flare`, `Nano-Banana-2` and `Nano-Banana-2.1`. Edits take public HTTP(S)", "`src_image_urls`, up to 16 on the GPT Image models and 14 on the Nano", "Banana models (`MACHGEN_I2I_MAX_IMAGES`), or previous image", "`src_task_ids`. GPT Image edits accept `src_mask_url`. Versions 2.5 and 2.6 also accept `src_markup_url`.", "An edit can include either a mask or markup. On 2.6, `continuation_task_id` alone can supply the source for a continued edit.", "GPT Image accepts a `safety_identifier` of up to 128 characters.", "`Seedream-5.5` is registered for T2I and I2I. It is private on this account; the docs page was re-read 2026-11-20.", "An edit takes up to 10 public HTTP(S) source images. Output is PNG or JPEG.", "Backgrounds are auto, opaque or transparent, and transparent needs PNG.", "Automatic sizing may set `resolution` to `1K`, `1.5K` or `2K` and has no upfront estimate.", "Square presets are 1024, 1536 and 2048. A custom size is 921,600 to 4,624,220 pixels.", "`image_output.layers` extracts extra images: omit `background`, and `max_images` is the priced output count. `watermark` passes through.", "`safety_identifier` is at most 64 ASCII characters.", "The docs price is 0.008 USD per input image plus 0.020 USD per output through 2,601,123 pixels, or 0.035 USD through 4,624,220.", "The public pricebook the same day lists one flat 0.020 USD per image and no input surcharge.", "Use `MACHGEN_IMAGE_SURFACES[model][task_type]` to look up supported settings.", "In `image_output`, set `quality`, `background`, `output_format`, JPEG/WebP `output_compression` or raster `partial_images`.", "GPT Image 2.6 adds `complexity` and GIF controls (`frame_count`, `frame_duration_ms`) for both tasks. T2I also supports SVG author settings (`svg.model`, `svg.reasoning.effort`).", "Unregistered image model aliases follow the field types and bounds and may pass additional output settings.", "Poll `api.v0.tasks` for `task_output.image`. GPT", "Image 2 defaults to high quality;", '`optimization_level: "EXPRESS"` selects low quality. The recorded', "1280×544 EXPRESS request billed $0.001385 before Generation Credit.", "For GPT Image 2.6, the requested dimensions and `image_output.quality` determine the output-token count.", "With auto or omitted quality, MachGen reserves the maximum price and bills the quality it returns.", "Each source image in an edit adds 7,024 tokens. The discounted rate is $0.000021 per token.", "Sunburst and Flare bill the same. At low quality, the recorded 1280×720 generations billed $0.009345 each.", "The recorded 720×1280 edits with one source image billed $0.156849 each.", "Send `Alibaba-Wan-3.0` requests with MachGen's documented", '`video_config`: `aspect_ratio: "adaptive"`, `fps: 30` and `audio: true`.', "On 2026-10-22, seven Wan 3.0 tasks that omitted `aspect_ratio` and", "`fps` and sent `audio: false` were accepted, then failed upstream with", "`Request Rejected` at zero charge. With the documented config, 2-second", "480p T2V, I2V and R2V requests completed. Which of the three fields", "MachGen requires has not been isolated.", "`Gemini-Omni-1.2-Flash` is on this account's model list (read", "2026-11-19) and absent from the public docs. T2V and I2V take 360,", "720, 1080 or 2160, 16:9 or 9:16, and 3-15 s. R2V also takes adaptive", "and a smart duration, up to 6 images and 3 videos, and reference,", "edit or extend. The public pricebook bills 0.023172 USD/s at 360p", "with no Generation Credit. A recorded 360p 3 s clip billed 0.073664", "USD against that quote of 0.069516 USD.", ].join(" "), ], ]); function renderBinancePublicDataGuide() { return [ "## Public Market Data", "", "`createBinance()` works without credentials for the public market-data", "surface. Pass `apiKey` only when you intentionally call a Binance", "endpoint that is documented as API-key or `MARKET_DATA`; signed trade,", "account, and user-data-stream endpoints are not exposed by this package.", "", "| Surface | Namespace | Default host | Auth |", "|---------|-----------|--------------|------|", "| Spot REST | `binance.api.v3.*` | `https://api.binance.com` | No key for public market data; optional `apiKey` header when supplied |", "| Spot market-data-only REST | `binance.api.v3.*` with `spotBaseURL` | `https://data-api.binance.vision` | No key |", "| USD-M Futures | `binance.fapi.v1.*`, `binance.fapi.v2.*`, `binance.futures.data.*` | `https://fapi.binance.com` | No key for exposed endpoints |", "| COIN-M Futures | `binance.dapi.v1.*`, `binance.coinMFutures.data.*` | `https://dapi.binance.com` | No key for exposed endpoints |", "| Options | `binance.eapi.v1.*` | `https://eapi.binance.com` | No key for exposed endpoints |", "", "To send existing Spot public calls to Binance's market-data-only host,", "override the Spot base URL. This keeps the same `api.v3` method paths", "while changing the host:", "", "```typescript", "const binance = createBinance({", ' spotBaseURL: "https://data-api.binance.vision",', "});", "", "const exchangeInfo = await binance.api.v3.exchangeInfo({", ' symbol: "BTCUSDT",', " showPermissionSets: false,", "});", "```", "", "You can also configure every public host explicitly:", "", "```typescript", "const binance = createBinance({", " publicBaseURLs: {", ' spot: "https://data-api.binance.vision",', ' spotData: "https://data-api.binance.vision",', ' fapi: "https://fapi.binance.com",', ' dapi: "https://dapi.binance.com",', ' eapi: "https://eapi.binance.com",', " },", "});", "```", "", "`binance.public.*` contains explicit no-auth smoke aliases for each", "public surface, and `binance.public.coinMFutures.*` mirrors the COIN-M", "public REST tree. Use the top-level namespaces above for the full", "implemented market-data surface.", "", "The `https://data.binance.vision` static archive serves public ZIP and", "checksum files for historical Spot, USD-M, and COIN-M datasets. It is", "intentionally outside this JSON REST provider; archive downloads need", "separate binary/checksum handling and tests.", "", ].join("\n"); } function renderSimpleFunctionsPublicMarketGuide() { return [ "## Public Market APIs", "", "`simplefunctions.api.public.*` mirrors the hosted `/api/public/*`", "surface on `https://simplefunctions.dev`. Most basic reads work without", "an API key. Passing `createSimpleFunctions({ apiKey })` adds the", "`Authorization: Bearer ...` header and may unlock higher rate limits,", "higher model tiers, or user-specific overlays on routes that support", "them.", "", "Most public routes are CDN cached with `Cache-Control: public,", "s-maxage=N`; route TTLs vary. Common TTLs are: markets, scan, and", "screen at 60 seconds; query, query-gov, and query-econ at 5-10 minutes", "in memory plus 5 minute CDN stale-while-revalidate; index and regime at", "30 seconds; legislation and congress members at 1 hour ISR.", "", "| Group | Methods | Purpose |", "|-------|---------|---------|", "| Markets | `markets`, `newmarkets`, `scan`, `screen`, `screenByTickers`, `search`, `market`, `market.history`, `marketMicrostructureHistory`, `liveTickers`, `market.candles` | Market universe, recently listed markets, keyword/series/market scans, indicator screens, explicit ticker screens, search, detail, history, spread/depth/flow history, live-priced tickers, and OHLCV candles. |", "| Cross-venue | `crossVenue.pairs`, `crossVenue.stats` | Kalshi to Polymarket pairs, pair counts, and confidence distribution. |", "| Regime and index | `regime.scan`, `index`, `index.history`, `calibration` | Current regime labels, SimpleFunctions Index v2 gauges, index history, and calibration. |", "| Probability index | `odds`, `oddsMd` | Liquidity-weighted YES probability snapshot for the `/odds` page, refreshed every 15 minutes; `oddsMd` is the Markdown variant for agents, capped at 500 slugs upstream. |", "| Calendar and milestones | `calendar`, `yieldCurves`, `yieldCurves.event` | Upcoming resolutions and event yield curves. |", "| Liquidity and contagion | `liquidityByTheme`, `contagion` | Liquidity grouped by theme and lagging related markets. |", "| Government data | `queryGov`, `legislation`, `legislation.byBillId`, `congress.members`, `congress.member` | Congress-mirror-backed bill, member, and treaty search plus bill/member detail. |", "| Economic data | `queryEcon`, `fred`, `databento`, `tradMarkets` | FRED-mirror-backed series search, FRED details, Databento traditional markets, and traditional market anchors. |", "| Content | `query`, `topic`, `answer`, `glossary`, `glossary.entry`, `guide`, `highlights`, `briefing`, `diff`, `discuss` | Headline cross-venue search, topic and stable answer data, glossary, agent guide, editorial highlights, briefing, daily diff, and discussion topics. |", "| Skills | `skills`, `skill` | Public skill catalog and one skill by slug. |", "| Theses and opinions | `theses`, `thesis`, `opinions`, `opinions.entry` | Public theses and editorial opinions. |", "| Technicals | `technicals`, `technicals.entry` | Technical guides and one guide by slug. |", "| Ideas | `ideas`, `ideas.byId` | Trade ideas and one idea by id. |", "| Context | `context` | Global market context without thesis payloads. |", "", "### Market candles", "", "`simplefunctions.api.public.market.candles` is the hosted API mapping for", "the strict `market.candles` SDK/Agent contract. The Vercel API route", "proxies to the terminal/Fly candle service and normalizes the response", "for SDK consumers.", "", "```typescript", "const candles = await simplefunctions.api.public.market.candles({", ' ticker: "KXRATECUT-26DEC31",', ' venue: "kalshi",', ' timeframe: "1m",', " limit: 500,", "});", "```", "", "| Parameter | Values | Notes |", "|-----------|--------|-------|", "| `venue` | `kalshi`, `polymarket` | Optional. Use it when the ticker or id is ambiguous. |", "| `timeframe` / `tf` | `1m`, `5m`, `15m`, `1h`, `1d` | Default is `1m`. |", "| `limit` | number | Default is 500, max is 2000 upstream. |", "", "The probability index routes accept `category`, `band`, and `limit`.", "`band` can be `mid` for probabilities near 50% or `moving` for recently", "shifted questions.", "", "`GET /api/public/regime/history` is deprecated and returns `410 Gone`.", "Use `regime.scan` for current regime labels and", "`marketMicrostructureHistory` for spread/depth history.", "", ].join("\n"); } function renderTheSportsDBAuthGuide() { return [ "## V2 Authentication", "", "V1 calls default to TheSportsDB's free `123` key in the URL path when", "`apiKey` is omitted. V2 is premium-only and sends the same `apiKey` in", "the `X-API-KEY` header; V2 methods throw locally if no key is configured.", "", "```typescript", "const thesportsdb = createTheSportsDB({", " apiKey: process.env.THESPORTSDB_API_KEY!,", "});", "", "const teams = await thesportsdb.v2.search.team({", ' teamName: "Manchester United",', "});", "```", "", "For V1 premium calls, the same `apiKey` option is encoded into the", "path segment instead of a header:", "", "```typescript", "const premiumV1 = createTheSportsDB({", " apiKey: process.env.THESPORTSDB_API_KEY!,", "});", "", "const broadcasts = await premiumV1.v1.eventstv({", ' channel: "Peacock_Premium",', "});", "```", "", ].join("\n"); } function renderTheSportsDBOperationalNotes() { return [ "## Operational Notes", "", "All implemented TheSportsDB endpoints are read-only `GET` calls. The", "provider does not expose mutating endpoints.", "", "The implemented API surface has no pagination parameters. Upstream", "responses use endpoint-specific wrapper arrays and documented result", "limits; empty and no-result wrappers remain representable as `null` or", "empty arrays.", "", "Non-2xx responses throw `TheSportsDBError` with `status` and parsed", "`body` where possible. Rate-limit responses keep their upstream `429`", "status and body. V2 methods throw a local `401` before fetch when no", "`apiKey` is configured for `X-API-KEY` authentication.", "", ].join("\n"); } function renderSimpleFunctionsAuthenticatedGuide() { return [ "## Authenticated APIs", "", "Passing `createSimpleFunctions({ apiKey })` adds", "`Authorization: Bearer ...` to authenticated dashboard, thesis,", "portfolio, alerting, tool, and runtime routes. The CLI-auth and", "session-oriented Market Watch routes can also be called with a custom", "`fetch` implementation that supplies browser/session cookies instead of", "a local API key.", "", "| Group | Methods | Purpose |", "|-------|---------|---------|", "| API keys and auth | `api.keys`, `api.keys.create`, `api.keys.delete`, `api.auth.cli.*`, `api.signup` | API-key lifecycle, CLI login handshakes, and signup. |", "| Account | `api.feed`, `api.dashboard.usage` | Authenticated feed and usage telemetry. |", "| Theses | `api.thesis.*` | Create, retrieve, update, fork, evaluate, augment, publish, and attach positions, strategies, videos, or context to private theses. |", "| Portfolio | `api.portfolio.*` | Portfolio state, config, ticks, trades, ledger imports, fills, positions, activity, attribution, risk, views, strategy, secrets, and triggers. |", "| Execution | `api.intents.*`, `api.runtime.exec.*` | Execution-intent lifecycle and runtime execution triggers. |", "| Watch and alerts | `api.watch.*`, `api.alertRules.*`, `api.webhookEndpoints.*`, `api.alertDeliveries.*` | Watch objects, alert rules, webhook endpoints, delivery history, and test/refresh actions. |", "| Tools | `api.contracts.tools`, `api.tools`, `api.skills`, `api.prompt`, `api.mcp.*`, `api.proxy.*` | Tool catalogs, prompt payloads, MCP transport, and raw speech proxy responses. |", "| Market Watch | `api.dashboard2.marketWatchV2`, `api.dashboard2.marketWatch.panels.*` | Session-backed Market Watch dashboard reads and panel CRUD. |", "", ].join("\n"); } /** * Segments `logicalDotPath` drops. `s3` has no verb namespace, so a leading * `get` there is a real key and must stay. * * @param {string} segment * @param {string} providerName * @returns {boolean} */ function isCollapsedSegment(segment, providerName) { const lower = segment.toLowerCase(); if (providerName !== "s3" && METHOD_KEYS.has(lower)) return true; return STREAM_KEYS.has(lower); } /** * The copy-pasteable call path for one rendered block. * * The display label drops HTTP-verb segments and `run` / `stream` / `ws` * wherever they sit. That is not always a path on the factory: * * - Some factories expose only verb namespaces. `createOpenAI` returns * `post` / `get` / `delete`, so `openai.v1.audio.speech` does not * resolve and `openai.post.v1.audio.speech` does (ac-kqdzn9). A verb * is not a universal alias. * - `run` / `stream` / `ws` are real namespaces. `FalProvider` has no * top-level `alibaba`, so the collapsed label rendered * `fal.alibaba.wan3p0.textToVideo(...)`, which does not compile * (ac-5xsd5z). * - A trailing or interior leaf (`delete`, `get`, `stream`) is the * function. The collapsed label stops on the namespace object: * `fireworks.inference.v1.accounts.apiKeys` is not callable, * `.delete` is. * * `fullDotPath` is the access path the walker found. When the label is that * path with only the collapsed segments removed, put those segments back. * A label that already contains `fullDotPath` — including one with a * disambiguating prefix `fullDotPath` does not have, such as kie `suno.` — * is kept. Rebuilding every snippet from `fullDotPath` alone would drop * that prefix. * * @param {{fullDotPath?: string}} ep * @param {string} dotPath - the collapsed display label * @param {string} providerName * @returns {string} */ function callableDotPath(ep, dotPath, providerName) { if (!ep.fullDotPath) return dotPath; const full = ep.fullDotPath.split("."); const label = dotPath.split(".").filter((segment) => segment.length > 0); const fullText = full.join("."); const labelText = label.join("."); if (labelText === fullText || labelText.endsWith(`.${fullText}`)) { return dotPath; } const logical = full.filter( (segment) => !isCollapsedSegment(segment, providerName) ); const logicalText = logical.join("."); if (logicalText.length > 0 && labelText === logicalText) return fullText; if ( logicalText.length > 0 && labelText.endsWith(`.${logicalText}`) && label.length > logical.length ) { const prefix = label.slice(0, label.length - logical.length); return [...prefix, ...full].join("."); } // The label is already a distinct path (a sibling labelled with its own // fullDotPath, or a label that retained `stream`). Do not prepend. return dotPath; } /** * The `ENDPOINT_NOTES` key of one rendered block: its provider, its display * label (the dot path its heading prints) and the method the block renders. * `renderEndpointDetails` looks notes up by it, and `endpointNoteKeys` lists * every key a provider's README can look up. */ function endpointNoteKey(providerName, label, method) { return `${providerName}\t${label}\t${method ?? ""}`; } function renderEndpointDetails(ep, providerName, docsUrl, tier, dotPath) { const method = ep.method ?? ""; const headerCode = method ? `${method} ` : ""; const summary = `${headerCode}${providerName}${dotPath ? "." + dotPath : ""}`; const urlLine = ep.fullUrl ? `${method ? method + " " : ""}${ep.fullUrl}` : ""; const tierLine = tier ? `Cost tier: ${tier}` : ""; const docsLine = docsUrl && docsUrl.length > 0 ? `[Upstream docs ↗](${docsUrl})` : ""; const noteLine = ENDPOINT_NOTES.get(endpointNoteKey(providerName, dotPath, method)) ?? ""; // The snippet is copy-pasteable source, so it must name a callable on the // factory. The heading keeps the collapsed label. See // `callableDotPath` for which segments are put back (ac-kqdzn9). A leaf // that takes nothing but an optional AbortSignal is a bare `()` call. const usage = formatUsageSnippet( providerName, dotPath, callableDotPath(ep, dotPath, providerName), takesNoArgument(ep) ); const relSrc = ep.file.replace( new RegExp(`^packages/provider/${providerName}/`), "" ); const sourceLine = `Source: [\`${ep.file}\`](${relSrc})`; const lines = ["
", `${summary}`, ""]; if (urlLine) lines.push(urlLine, ""); if (tierLine) lines.push(tierLine, ""); if (docsLine) lines.push(docsLine, ""); if (noteLine) lines.push(noteLine, ""); lines.push("```typescript", usage, "```", ""); lines.push(sourceLine, "", "
", ""); return lines.join("\n"); } function groupEndpoints(endpoints) { const groups = new Map(); for (const ep of endpoints) { const key = sectionKey(ep.dotPath); const list = groups.get(key) ?? []; list.push(ep); groups.set(key, list); } for (const list of groups.values()) { list.sort((a, b) => { const aPath = a.fullDotPath ?? a.dotPath ?? ""; const bPath = b.fullDotPath ?? b.dotPath ?? ""; if (aPath !== bPath) return aPath < bPath ? -1 : 1; return (a.method ?? "").localeCompare(b.method ?? ""); }); } return new Map([...groups.entries()].sort(([a], [b]) => a.localeCompare(b))); } /** * One rendered block's endpoint-docs.tsv row, and the endpoint with the * method and URL that row fills in. `renderApiReference` renders the enriched * endpoint and `endpointNoteKeys` keys on it, so a note key names exactly the * block a README prints. */ function enrichEndpoint(docs, ep, providerName, label) { const docRow = resolveEndpointDocRow(docs, ep, providerName, label); const endpoint = docRow ? { ...ep, method: ep.method ?? cleanTsvValue(docRow.method), fullUrl: ep.fullUrl ?? cleanTsvValue(docRow.fullUrl), } : ep; return { docRow, endpoint }; } export function renderApiReference(providerName, endpoints) { const sections = ["## API Reference", ""]; // Verb aliases of one path collapse to a single block; genuinely distinct // siblings (stream variants) keep a block each under a distinct label. const { labels, rendered } = resolveEndpointLabels(providerName, endpoints); if (rendered.length === 0) { sections.push("_No endpoints discovered for this provider yet._", ""); return { text: sections.join("\n"), renderedCount: 0 }; } const groups = groupEndpoints(rendered); sections.push( `${rendered.length} endpoint${rendered.length === 1 ? "" : "s"} across ${groups.size} group${groups.size === 1 ? "" : "s"}. Each method mirrors an upstream URL path.`, "" ); const docs = loadDocsTsv(); for (const [group, list] of groups) { sections.push(`### ${group}`, ""); for (const ep of list) { const label = labels.get(ep); const { docRow, endpoint: enrichedEndpoint } = enrichEndpoint( docs, ep, providerName, label ); const tierKey = `${providerName}\t${ docRow?.dotPath ?? enrichedEndpoint.fullDotPath ?? enrichedEndpoint.dotPath }\t${docRow?.method ?? enrichedEndpoint.method ?? ""}`; const tier = COST_TIER_MAP.get(tierKey) ?? "prohibitive"; sections.push( renderEndpointDetails( enrichedEndpoint, providerName, docRow?.docsUrl ?? "", tier, label ) ); } } return { text: sections.join("\n"), renderedCount: rendered.length }; } /** * Every `ENDPOINT_NOTES` key that `providerName`'s README can look up: one per * block `renderApiReference` renders for `endpoints`. */ function endpointNoteKeys(providerName, endpoints, docs) { const { labels, rendered } = resolveEndpointLabels(providerName, endpoints); return new Set( rendered.map((ep) => { const label = labels.get(ep); const { endpoint } = enrichEndpoint(docs, ep, providerName, label); return endpointNoteKey(providerName, label, endpoint.method); }) ); } /** * Throws unless every `notes` key names a block its provider's README renders. * A key that matches nothing drops its note silently, and the README * regenerated without the note still passes `--check` (ac-shq7sd: one renamed * gemini key left the kie README with four of its five notes). * * Each key is checked against its own provider's endpoints, whichever * providers a run renders, so a single-provider run (`doc-gen:fal`) checks the * kie and polymarket keys too and never fails a valid one. * * @param {Map} endpointsByProvider - every provider's * endpoints, as `collectEndpointsByProvider` returns them * @param {Map} [notes] */ export function assertEndpointNotesMatch( endpointsByProvider, notes = ENDPOINT_NOTES ) { const docs = loadDocsTsv(); const keysByProvider = new Map(); const unmatched = []; for (const key of notes.keys()) { const [provider] = key.split("\t"); if (!keysByProvider.has(provider)) { const endpoints = endpointsByProvider.get(provider) ?? []; keysByProvider.set(provider, endpointNoteKeys(provider, endpoints, docs)); } if (!keysByProvider.get(provider).has(key)) { unmatched.push(` provider ${provider}: ${JSON.stringify(key)}`); } } if (unmatched.length === 0) return; const count = unmatched.length; const summary = count === 1 ? "1 ENDPOINT_NOTES key matches no generated endpoint, so its note " + "never renders:" : `${count} ENDPOINT_NOTES keys match no generated endpoint, so their ` + "notes never render:"; throw new Error( [ summary, ...unmatched, 'Each key is "\\t