|
| 1 | +// cloudflare worker to building warning if the docs are ahead of the latest release |
| 2 | +// see https://developers.cloudflare.com/pages/functions/advanced-mode/ |
| 3 | + |
| 4 | +export default { |
| 5 | + async fetch(request, env) { |
| 6 | + const url = new URL(request.url) |
| 7 | + if (url.pathname === '/version-warning.html') { |
| 8 | + try { |
| 9 | + const html = await versionWarning(request, env) |
| 10 | + return new Response(html, { headers: {'Content-Type': 'text/html', 'Cache-Control': 'max-age=1800'} }) |
| 11 | + } catch (e) { |
| 12 | + console.error(e) |
| 13 | + return new Response( |
| 14 | + `Error getting ahead HTML: ${e}`, |
| 15 | + { status: 500, headers: {'Content-Type': 'text/plain'} } |
| 16 | + ) |
| 17 | + } |
| 18 | + } else { |
| 19 | + return env.ASSETS.fetch(request) |
| 20 | + } |
| 21 | + }, |
| 22 | +} |
| 23 | + |
| 24 | +// env looks like |
| 25 | +// {"CF_PAGES":"1","CF_PAGES_BRANCH":"ahead-warning","CF_PAGES_COMMIT_SHA":"...","CF_PAGES_URL":"https://..."} |
| 26 | +async function versionWarning(request, env) { |
| 27 | + const headers = new Headers({ |
| 28 | + 'User-Agent': request.headers.get('User-Agent') || 'pydantic-ai-docs', |
| 29 | + 'Accept': 'application/vnd.github.v3+json', |
| 30 | + }) |
| 31 | + const r1 = await fetch('https://api.github.com/repos/pydantic/pydantic-ai/releases/latest', {headers}) |
| 32 | + if (!r1.ok) { |
| 33 | + const text = await r1.text() |
| 34 | + throw new Error(`Failed to fetch latest release, response status ${r1.status}:\n${text}`) |
| 35 | + } |
| 36 | + const {html_url, name, tag_name} = await r1.json() |
| 37 | + const r2 = await fetch( |
| 38 | + `https://api.github.com/repos/pydantic/pydantic-ai/compare/${tag_name}...${env.CF_PAGES_COMMIT_SHA}`, |
| 39 | + {headers} |
| 40 | + ) |
| 41 | + if (!r2.ok) { |
| 42 | + const text = await r2.text() |
| 43 | + throw new Error(`Failed to fetch compare, response status ${r2.status}:\n${text}`) |
| 44 | + } |
| 45 | + const {ahead_by} = await r2.json() |
| 46 | + |
| 47 | + if (ahead_by === 0) { |
| 48 | + return `<div class="admonition success" style="margin: 0"> |
| 49 | + <p class="admonition-title">Version</p> |
| 50 | + <p>Showing documentation for the latest release <a href="${html_url}">${name}</a>.</p> |
| 51 | +</div>` |
| 52 | + } |
| 53 | + |
| 54 | + return `<div class="admonition info" style="margin: 0"> |
| 55 | + <p class="admonition-title">Version Notice</p> |
| 56 | + <p> |
| 57 | + ${env.CF_PAGES_BRANCH === 'main' ? '' : `(<b>${env.CF_PAGES_BRANCH}</b> preview)`} |
| 58 | + This documentation is ahead of the latest release by <b>${ahead_by}</b> commit${ahead_by === 1 ? '' : 's'}. |
| 59 | + You may see documentation for features not yet supported in the latest release <a href="${html_url}">${name}</a>. |
| 60 | + </p> |
| 61 | +</div>` |
| 62 | +} |
0 commit comments