/** * Short link client — talks to the BFF /share endpoints. * * Used by the text-selection toolbar (`buildShortHighlightUrl`) and the * `/share/[code]` page (`resolveShortLink`). */ import { bff, bffPost } from "@/lib/bff"; // Module-scoped cache: a single user shouldn't generate a fresh code every // time they re-click Share on the same selection. Keyed by the relative path // (including ?hl=…), this returns the same promise for repeat calls. const createCache = new Map>(); type CreateResponse = { code: string }; type ResolveResponse = { url: string }; /** * Create a short code for a same-site relative path (`/books/bg/18/66?hl=…`). * Returns `null` on any failure — caller should fall back to the long URL. */ export function createShortLink(longPath: string): Promise { const cached = createCache.get(longPath); if (cached) return cached; const promise = bffPost("/share", { url: longPath }) .then((r) => r.code) .catch(() => null); createCache.set(longPath, promise); // If the request fails, evict so the next click can retry instead of // returning the cached null forever. promise.then((code) => { if (code === null) createCache.delete(longPath); }); return promise; } /** * Resolve a short code to its full long path. Returns `null` when the code is * not found, expired, disabled, or the BFF is unreachable. */ export async function resolveShortLink(code: string): Promise { try { const r = await bff(`/share/${encodeURIComponent(code)}`, { revalidate: 0, }); return r?.url ?? null; } catch { return null; } }