Raw
1 /* eslint-disable no-console */
2 import OpenAPIParser from "@readme/openapi-parser"
3 import algoliasearch from "algoliasearch"
4 import { JSDOM } from "jsdom"
5 import path from "path"
6 import { fileURLToPath } from "url"
7 import {
8 apiRefIntroSections,
9 apiRefPaths,
10 } from "../generated/api-ref-paths.mjs"
11
12 const __dirname = path.dirname(fileURLToPath(import.meta.url))
13 const appDir = path.resolve(__dirname, "..")
14
15 const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || ""
16 const basePath = process.env.NEXT_PUBLIC_BASE_PATH || "/api"
17
18 // The app now uses real page paths (no hash anchors), e.g.
19 // `/api/store/carts/get-a-cart`. Slugs/paths are read from the generated
20 // `api-ref-paths.mjs` (the single source of truth) rather than recomputed.
21 function getAreaUrl(area) {
22 return `${baseUrl}${basePath}/${area}`
23 }
24
25 function getPageUrl(pagePath) {
26 return `${baseUrl}${basePath}${pagePath}`
27 }
28
29 function capitalize(str) {
30 return str.charAt(0).toUpperCase() + str.slice(1)
31 }
32
33 function getObjectId(area, objectName) {
34 return `${area}_${objectName}`
35 }
36
37 function getHierarchy(area, levels) {
38 const hierarchy = { lvl0: `${capitalize(area)} API Reference` }
39 levels.forEach((level, i) => {
40 hierarchy[`lvl${i + 1}`] = level
41 })
42 return hierarchy
43 }
44
45 // Build a `title` -> intro section slug lookup for the scraped MDX headers.
46 function getIntroSlugByTitle(area) {
47 const map = new Map()
48 ;(apiRefIntroSections[area] || []).forEach((section) => {
49 map.set(section.title.trim().toLowerCase(), section.slug)
50 })
51 return map
52 }
53
54 // Build an `operationId` -> generated operation entry (path/oldHash/title/...)
55 // lookup across all of an area's tags.
56 function getOperationsById(area) {
57 const map = new Map()
58 const tags = apiRefPaths[area]?.tags || {}
59 Object.entries(tags).forEach(([tagSlug, tag]) => {
60 Object.entries(tag.operations || {}).forEach(([operationId, operation]) => {
61 map.set(operationId, { ...operation, tagSlug })
62 })
63 })
64 return map
65 }
66
67 // Build a tag `name` -> generated tag entry (path/schemaPath/...) lookup.
68 function getTagsByName(area) {
69 const map = new Map()
70 const tags = apiRefPaths[area]?.tags || {}
71 Object.entries(tags).forEach(([tagSlug, tag]) => {
72 map.set(tag.name.trim().toLowerCase(), { ...tag, tagSlug })
73 })
74 return map
75 }
76
77 async function main() {
78 const algoliaClient = algoliasearch(
79 process.env.NEXT_PUBLIC_ALGOLIA_APP_ID || "",
80 process.env.ALGOLIA_WRITE_API_KEY || ""
81 )
82 const index = algoliaClient.initIndex(
83 process.env.NEXT_PUBLIC_API_ALGOLIA_INDEX_NAME || ""
84 )
85
86 /**
87 * @type {Record<string, any>[]}
88 */
89 const indices = []
90
91 for (const area of ["store", "admin"]) {
92 const defaultIndexData = {
93 version: ["current"],
94 lang: "en",
95 _tags: ["api", `${area}-v2`],
96 }
97
98 const introSlugByTitle = getIntroSlugByTitle(area)
99 const operationsById = getOperationsById(area)
100 const tagsByName = getTagsByName(area)
101 const introPaths = apiRefPaths[area]?.intro || {}
102
103 // Index static MDX section headers from the live page. Each `h2` maps to an
104 // intro section that now has its own page path (`/api/{area}/{slug}`).
105 const pageUrl = getAreaUrl(area)
106 console.log(`Scraping page headers from ${pageUrl}...`)
107 try {
108 const dom = await JSDOM.fromURL(pageUrl)
109 const headers = dom.window.document.querySelectorAll("h2")
110 headers.forEach((header) => {
111 if (!header.textContent || !header.nextSibling?.textContent) {
112 return
113 }
114 const normalizedHeaderContent = header.textContent.replaceAll("#", "")
115 const description = header.nextSibling?.textContent
116 const slug = introSlugByTitle.get(
117 normalizedHeaderContent.trim().toLowerCase()
118 )
119 if (!slug) {
120 console.warn(
121 `No intro section slug found for header "${normalizedHeaderContent.trim()}" in ${area}; skipping.`
122 )
123 return
124 }
125 const url = getPageUrl(introPaths[slug] || `/${area}/${slug}`)
126 indices.push({
127 objectID: getObjectId(area, `${slug}-mdx-section`),
128 hierarchy: getHierarchy(area, [normalizedHeaderContent]),
129 type: "content",
130 content: description || "",
131 url,
132 url_without_variables: url,
133 url_without_anchor: url,
134 ...defaultIndexData,
135 })
136 })
137 } catch (e) {
138 console.warn(`Failed to scrape ${pageUrl}: ${e.message}`)
139 }
140
141 // Parse OpenAPI spec for tag/operation descriptions, joining each to its
142 // generated page path (and stable objectID) via name/operationId.
143 const specPath = path.join(appDir, `specs/${area}/openapi.full.yaml`)
144 console.log(`Parsing spec at ${specPath}...`)
145 const baseSpecs = await OpenAPIParser.parse(specPath)
146
147 baseSpecs.tags?.forEach((tag) => {
148 const tagEntry = tagsByName.get(tag.name.trim().toLowerCase())
149 if (!tagEntry) {
150 console.warn(
151 `No generated path for tag "${tag.name}" in ${area}; skipping.`
152 )
153 return
154 }
155 const url = getPageUrl(tagEntry.path)
156 indices.push({
157 objectID: getObjectId(area, tagEntry.tagSlug),
158 hierarchy: getHierarchy(area, [tag.name]),
159 type: "lvl1",
160 content: null,
161 description: tag.description,
162 url,
163 url_without_variables: url,
164 url_without_anchor: url,
165 ...defaultIndexData,
166 })
167 })
168
169 Object.values(baseSpecs.paths).forEach((pathItem) => {
170 Object.values(pathItem).forEach((operation) => {
171 if (!operation?.operationId) {
172 return
173 }
174 const operationEntry = operationsById.get(operation.operationId)
175 if (!operationEntry) {
176 console.warn(
177 `No generated path for operation "${operation.operationId}" in ${area}; skipping.`
178 )
179 return
180 }
181 const url = getPageUrl(operationEntry.path)
182
183 indices.push({
184 objectID: getObjectId(area, operationEntry.oldHash),
185 hierarchy: getHierarchy(area, [operation.summary]),
186 type: "content",
187 content: operation.summary,
188 content_camel: operation.summary,
189 url,
190 url_without_variables: url,
191 url_without_anchor: url,
192 ...defaultIndexData,
193 })
194
195 if (operation.description) {
196 indices.push({
197 objectID: getObjectId(
198 area,
199 `${operationEntry.oldHash}-description`
200 ),
201 hierarchy: getHierarchy(area, [
202 operation.summary,
203 operation.description,
204 ]),
205 type: "content",
206 content: operation.description,
207 content_camel: operation.description,
208 url,
209 url_without_variables: url,
210 url_without_anchor: url,
211 ...defaultIndexData,
212 })
213 }
214 })
215 })
216 }
217
218 console.log(`Saving ${indices.length} records to Algolia...`)
219 if (indices.length) {
220 await index.saveObjects(indices, { autoGenerateObjectIDIfNotExist: true })
221 }
222 console.log("Done.")
223 }
224
225 main().catch((err) => {
226 console.error(err)
227 process.exit(1)
228 })