Files
descrybe/apps/web/src/lib/public-api-base.ts
T

197 lines
6.0 KiB
TypeScript
Raw Normal View History

import { PUBLIC_API_URL } from "$env/static/public";
/**
* Empty PUBLIC_API_URL = same-origin (`/api` via Vite proxy or reverse proxy).
* When set, OpenAPI is fetched from that API origin (must be in CSP connect-src).
*/
const API_BASE = (PUBLIC_API_URL ?? "").replace(/\/$/, "");
/** Public production API base from OpenAPI servers[0] (Descrybe-hosted; not customer self-host). */
export const PUBLIC_DOCS_API_SERVER = "https://descrybe.io/api/v1";
/** Public OpenAPI document URL for links and fetches. */
export const OPENAPI_SPEC_URL = `${API_BASE}/api/v1/openapi.yaml`;
/**
* Absolute base for RapiDoc Try-it.
* Dev/local: PUBLIC_API_URL when set (npm run dev forces http://localhost:28471),
* else current origin so Vite proxies /api → :28471.
* Production same-origin deploy resolves to https://descrybe.io/api/v1.
* OpenAPI servers[0] stays PUBLIC_DOCS_API_SERVER for the public YAML narrative.
*/
export function docsTryItServerURL(
origin = typeof window !== "undefined" ? window.location.origin : ""
): string {
if (API_BASE) {
return `${API_BASE}/api/v1`;
}
if (origin) {
return `${origin}/api/v1`;
}
return PUBLIC_DOCS_API_SERVER;
}
export type RapiDocTryItHost = {
setAttribute: (name: string, value: string) => void;
selectedServer?: { url: string; computedUrl: string };
requestUpdate?: () => void;
};
/**
* Point RapiDoc Try-it at the local/dev API.
* RapiDoc only selects `server-url` when it equals `default-api-server`;
* otherwise Try-it uses OpenAPI servers[0] (production) even if server-url is set.
*/
export function applyRapiDocTryItServer(
el: RapiDocTryItHost,
origin = typeof window !== "undefined" ? window.location.origin : ""
): string {
const url = docsTryItServerURL(origin);
el.setAttribute("server-url", url);
el.setAttribute("default-api-server", url);
return url;
}
/** Re-assert Try-it base after loadSpec (afterSpecParsed may race attributes). */
export function lockRapiDocTryItServer(el: RapiDocTryItHost, tryItUrl: string): void {
const url = tryItUrl.replace(/\/$/, "");
if (!url) return;
el.setAttribute("server-url", url);
el.setAttribute("default-api-server", url);
el.selectedServer = { url, computedUrl: url };
el.requestUpdate?.();
}
const CACHE_KEY = "descrybe:openapi-yaml:v1";
/** Align with Go `max-age=300`; client soft-TTL for memory/session reuse. */
export const OPENAPI_CACHE_TTL_MS = 5 * 60 * 1000;
/** Hard cap so a dead Vite→API proxy cannot leave the docs viewer loading forever. */
export const OPENAPI_FETCH_TIMEOUT_MS = 12_000;
type CacheEntry = { yaml: string; fetchedAt: number };
let memoryCache: CacheEntry | null = null;
/** Shared in-flight fetch so early prefetch + docs mount hit one network request. */
let inflight: Promise<string> | null = null;
function readSessionCache(): CacheEntry | null {
if (typeof sessionStorage === "undefined") return null;
try {
const raw = sessionStorage.getItem(CACHE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as CacheEntry;
if (typeof parsed?.yaml !== "string" || typeof parsed?.fetchedAt !== "number") {
return null;
}
if (!parsed.yaml.trim().startsWith("openapi:")) return null;
return parsed;
} catch {
return null;
}
}
function writeSessionCache(entry: CacheEntry): void {
if (typeof sessionStorage === "undefined") return;
try {
sessionStorage.setItem(CACHE_KEY, JSON.stringify(entry));
} catch {
/* quota / private mode — memory cache still applies */
}
}
function isFresh(entry: CacheEntry, now = Date.now()): boolean {
return now - entry.fetchedAt < OPENAPI_CACHE_TTL_MS;
}
/**
* Kick off OpenAPI fetch as early as the docs module loads (browser).
* Prefer this over `<link rel="preload" as="fetch">` — custom Accept / cache
* hits left that preload unused and triggered Chrome warnings.
*/
export function prefetchOpenApiSpec(): Promise<string> {
return loadOpenApiSpec();
}
function isAbortError(err: unknown): boolean {
return (
(err instanceof DOMException && err.name === "AbortError") ||
(err instanceof Error && err.name === "AbortError")
);
}
/**
* Load the public OpenAPI YAML with timeout, memory + sessionStorage cache,
* shared in-flight dedupe, and stale-while-revalidate on network failure.
*/
export async function loadOpenApiSpec(opts?: {
force?: boolean;
signal?: AbortSignal;
timeoutMs?: number;
}): Promise<string> {
const now = Date.now();
if (!opts?.force && memoryCache && isFresh(memoryCache, now)) {
return memoryCache.yaml;
}
const session = readSessionCache();
if (!opts?.force && session && isFresh(session, now)) {
memoryCache = session;
return session.yaml;
}
if (!opts?.force && inflight) {
return inflight;
}
const timeoutMs = opts?.timeoutMs ?? OPENAPI_FETCH_TIMEOUT_MS;
const run = (async (): Promise<string> => {
const ac = new AbortController();
const timer = setTimeout(() => ac.abort(), timeoutMs);
const onOuterAbort = () => ac.abort();
opts?.signal?.addEventListener("abort", onOuterAbort);
try {
const res = await fetch(OPENAPI_SPEC_URL, {
method: "GET",
signal: ac.signal,
credentials: "omit",
cache: "no-store"
});
if (!res.ok) {
throw new Error(`OpenAPI fetch failed (HTTP ${res.status}).`);
}
const yaml = await res.text();
if (!yaml.trim().startsWith("openapi:")) {
throw new Error("OpenAPI document looks invalid.");
}
const entry: CacheEntry = { yaml, fetchedAt: Date.now() };
memoryCache = entry;
writeSessionCache(entry);
return yaml;
} catch (err) {
const stale = memoryCache ?? session;
if (stale?.yaml) {
memoryCache = stale;
return stale.yaml;
}
if (isAbortError(err)) {
throw new Error(
"Timed out loading the OpenAPI document. Is the API running on the configured host?"
);
}
throw err;
} finally {
clearTimeout(timer);
opts?.signal?.removeEventListener("abort", onOuterAbort);
}
})();
if (!opts?.force) {
const tracked = run.finally(() => {
if (inflight === tracked) inflight = null;
});
inflight = tracked;
return tracked;
}
return run;
}