1 import { readdirSync, readFileSync, statSync, writeFileSync } from "fs"
2 import getSlugs from "../utils/get-slugs.mjs"
3 import path from "path"
4
5 const monoRepoPath = path.resolve("..", "..", "..")
6 const baseReferencePath = path.resolve("references")
7
8 /**
9 * Reference pages bake their final slug into the JSON doc-model. Emit a
10 * slug-change entry for each page whose slug differs from its file location, so
11 * the broken-link checker can resolve slug-overridden reference links (e.g.
12 * `/references/api-key/revoke`).
13 *
14 * @param {string} [dir]
15 * @returns {import("types").SlugChange[]}
16 */
17 function getReferenceSlugs(dir = baseReferencePath) {
18 /** @type {import("types").SlugChange[]} */
19 const slugs = []
20 let files
21 try {
22 files = readdirSync(dir)
23 } catch {
24 return slugs
25 }
26
27 for (const file of files) {
28 const filePath = path.join(dir, file)
29 if (path.basename(file) !== "page.json") {
30 if (statSync(filePath).isDirectory()) {
31 slugs.push(...getReferenceSlugs(filePath))
32 }
33 continue
34 }
35
36 // file location relative to the resources root, e.g. /references/api_key/...
37 const origSlug = filePath
38 .replace(path.resolve(), "")
39 .replace(`/${path.basename(file)}`, "")
40
41 let newSlug
42 try {
43 newSlug = JSON.parse(readFileSync(filePath, "utf-8")).slug
44 } catch {
45 continue
46 }
47
48 if (newSlug && newSlug !== origSlug) {
49 slugs.push({
50 origSlug,
51 newSlug,
52 filePath: filePath.replace(monoRepoPath, ""),
53 })
54 }
55 }
56
57 return slugs
58 }
59
60 export async function main() {
61 const slugs = await getSlugs()
62 slugs.push(...getReferenceSlugs())
63
64 // write generated slugs
65 writeFileSync(
66 path.resolve("generated", "slug-changes.mjs"),
67 `export const slugChanges = ${JSON.stringify(slugs, null, 2)}`
68 )
69 }