1 import { NextResponse } from "next/server"
2 import { throwErrorResponse, withRouteErrorHandling } from "docs-utils"
3 import { globalConfig } from "docs-utils/global-config"
4 import {
5 getCachedSpecVersions,
6 specVersionExists,
7 } from "@/utils/get-spec-versions"
8
9 const DEFAULT_LIMIT = 15
10 const MAX_LIMIT = 100
11
12 const cacheHeaders = {
13 "Cache-Control": "public, max-age=3600, must-revalidate",
14 }
15
16 type VersionSpecs = {
17 version: string
18 admin_url: string
19 store_url: string
20 }
21
22 function clampNumber(
23 value: string | null,
24 fallback: number,
25 min: number,
26 max: number
27 ): number {
28 const parsed = parseInt(value || "", 10)
29
30 return Number.isNaN(parsed) ? fallback : Math.min(Math.max(parsed, min), max)
31 }
32
33 /**
34 * The latest version isn't archived under `specs/versions`, so it's derived
35 * from the docs' global config, which is updated on every release. The release
36 * URL is used since it holds the full version, unlike `version.number`.
37 */
38 function getLatestVersion(): string {
39 const { number, releaseUrl } = globalConfig.version
40
41 return releaseUrl.match(/\/tag\/v?([^/]+)\/?$/)?.[1] || number
42 }
43
44 export const GET = withRouteErrorHandling(async (request: Request) => {
45 const r2Base = process.env.SPECS_R2_BASE_URL
46 // Outside of Cloudflare the specs aren't in R2, so the download route, which
47 // reads them from the file system, is linked to instead.
48 const requestUrl = new URL(request.url)
49 const downloadBaseUrl = `${requestUrl.origin}${requestUrl.pathname.replace(
50 /\/versions\/?$/,
51 ""
52 )}/download`
53
54 const getSpecUrl = (area: "admin" | "store", version?: string): string => {
55 if (!r2Base) {
56 return `${downloadBaseUrl}/${area}${
57 version ? `?version=${encodeURIComponent(version)}` : ""
58 }`
59 }
60
61 const segments = ["specs"]
62 if (version) {
63 segments.push("versions", version)
64 }
65 segments.push(area, "openapi.full.json")
66
67 return `${r2Base}/${segments.join("/")}`
68 }
69
70 const toVersionSpecs = (
71 version: string,
72 archivedVersion?: string
73 ): VersionSpecs => ({
74 version,
75 admin_url: getSpecUrl("admin", archivedVersion),
76 store_url: getSpecUrl("store", archivedVersion),
77 })
78
79 const latestVersion = getLatestVersion()
80 const versionFilter = requestUrl.searchParams.get("version")
81
82 // A single version is looked up on its own, so the full listing is never
83 // retrieved when it's filtered down to one version anyway.
84 if (versionFilter) {
85 const isLatest = versionFilter === latestVersion
86
87 if (!isLatest && !(await specVersionExists(versionFilter))) {
88 throwErrorResponse(
89 404,
90 `No OpenAPI specs found for version "${versionFilter}"`
91 )
92 }
93
94 return NextResponse.json(
95 {
96 versions: [
97 toVersionSpecs(versionFilter, isLatest ? undefined : versionFilter),
98 ],
99 count: 1,
100 limit: 1,
101 offset: 0,
102 },
103 { headers: cacheHeaders }
104 )
105 }
106
107 const archivedVersions = (await getCachedSpecVersions()).filter(
108 (version) => version !== latestVersion
109 )
110
111 const count = archivedVersions.length + 1
112 const limit = clampNumber(
113 requestUrl.searchParams.get("limit"),
114 DEFAULT_LIMIT,
115 1,
116 MAX_LIMIT
117 )
118 const offset = clampNumber(requestUrl.searchParams.get("offset"), 0, 0, count)
119
120 // The latest version heads the list, so it shifts the archived versions by
121 // one and only an offset of `0` includes it.
122 const versions: VersionSpecs[] = [
123 ...(offset === 0 ? [toVersionSpecs(latestVersion)] : []),
124 ...archivedVersions
125 .slice(Math.max(offset - 1, 0), offset + limit - 1)
126 .map((version) => toVersionSpecs(version, version)),
127 ]
128
129 return NextResponse.json(
130 {
131 versions,
132 count,
133 limit,
134 offset,
135 },
136 { headers: cacheHeaders }
137 )
138 })