1 /* eslint-disable no-console */
2 /**
3 * Uploads specs/ to Cloudflare R2.
4 *
5 * Every `openapi.full.yaml` is additionally uploaded as `openapi.full.json`.
6 * The JSON isn't committed to the repository, it only exists in R2.
7 *
8 * Usage:
9 * node ./scripts/upload-specs-to-r2.mjs
10 * Full upload of specs/ directory.
11 *
12 * node ./scripts/upload-specs-to-r2.mjs --upload specs/admin/paths/foo.yaml specs/store/paths/bar.yaml
13 * Upload only the listed files (paths relative to app root).
14 *
15 * node ./scripts/upload-specs-to-r2.mjs --remove specs/admin/paths/old.yaml
16 * Remove the listed keys from R2 (paths relative to app root).
17 *
18 * --upload and --remove can be combined in a single invocation.
19 *
20 * Required env vars:
21 * CLOUDFLARE_ACCOUNT_ID
22 * CLOUDFLARE_R2_ACCESS_KEY_ID
23 * CLOUDFLARE_R2_SECRET_ACCESS_KEY
24 * R2_BUCKET_NAME (default: docs-assets)
25 */
26
27 // Load .env if present; silently skip if not (e.g. CI injects vars directly)
28 try {
29 process.loadEnvFile()
30 } catch {
31 /* no .env file */
32 }
33
34 import {
35 S3Client,
36 PutObjectCommand,
37 DeleteObjectCommand,
38 } from "@aws-sdk/client-s3"
39 import { readFile, readdir } from "fs/promises"
40 import path from "path"
41 import { lookup as mimeLookup } from "mime-types"
42 import { parse as parseYaml } from "yaml"
43
44 const accountId = process.env.CLOUDFLARE_ACCOUNT_ID
45 const accessKeyId = process.env.CLOUDFLARE_R2_ACCESS_KEY_ID
46 const secretAccessKey = process.env.CLOUDFLARE_R2_SECRET_ACCESS_KEY
47 const bucket = process.env.R2_BUCKET_NAME || "docs-assets"
48
49 if (!accountId || !accessKeyId || !secretAccessKey) {
50 console.error(
51 "Missing required env vars: CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_R2_ACCESS_KEY_ID, CLOUDFLARE_R2_SECRET_ACCESS_KEY"
52 )
53 process.exit(1)
54 }
55
56 const client = new S3Client({
57 region: "auto",
58 endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
59 credentials: { accessKeyId, secretAccessKey },
60 })
61
62 // Parse --upload and --remove CLI flags
63 const args = process.argv.slice(2)
64 const filesToUpload = []
65 const filesToRemove = []
66 let mode = null
67
68 for (const arg of args) {
69 if (arg === "--upload") {
70 mode = "upload"
71 continue
72 }
73 if (arg === "--remove") {
74 mode = "remove"
75 continue
76 }
77 if (arg.startsWith("--")) {
78 mode = null
79 continue
80 }
81 if (mode === "upload") {
82 filesToUpload.push(arg)
83 }
84 if (mode === "remove") {
85 filesToRemove.push(arg)
86 }
87 }
88
89 const isSelective = filesToUpload.length > 0 || filesToRemove.length > 0
90
91 // Full OAS documents are also stored as JSON in R2 for consumers that can't
92 // parse YAML. The JSON isn't kept in the repository, so it's derived here.
93 const FULL_SPEC_FILE_NAME = "openapi.full.yaml"
94
95 function isFullSpec(fileOrKey) {
96 return path.basename(fileOrKey) === FULL_SPEC_FILE_NAME
97 }
98
99 function toJsonKey(r2Key) {
100 return r2Key.replace(/\.yaml$/, ".json")
101 }
102
103 async function putObject(r2Key, body, contentType) {
104 await client.send(
105 new PutObjectCommand({
106 Bucket: bucket,
107 Key: r2Key,
108 Body: body,
109 ContentType: contentType,
110 })
111 )
112 console.log(` uploaded: ${r2Key}`)
113 }
114
115 async function uploadFile(localPath, r2Key) {
116 const body = await readFile(localPath)
117 const contentType =
118 mimeLookup(path.basename(localPath)) || "application/octet-stream"
119 await putObject(r2Key, body, contentType)
120
121 if (isFullSpec(localPath)) {
122 const json = JSON.stringify(parseYaml(body.toString("utf-8")))
123 await putObject(toJsonKey(r2Key), json, "application/json")
124 }
125 }
126
127 async function removeFile(r2Key) {
128 await client.send(new DeleteObjectCommand({ Bucket: bucket, Key: r2Key }))
129 console.log(` removed: ${r2Key}`)
130
131 if (isFullSpec(r2Key)) {
132 const jsonKey = toJsonKey(r2Key)
133 await client.send(new DeleteObjectCommand({ Bucket: bucket, Key: jsonKey }))
134 console.log(` removed: ${jsonKey}`)
135 }
136 }
137
138 async function uploadDir(localDir, r2Prefix) {
139 const entries = await readdir(localDir, { withFileTypes: true })
140 for (const entry of entries) {
141 const localPath = path.join(localDir, entry.name)
142 const r2Key = `${r2Prefix}/${entry.name}`
143 if (entry.isDirectory()) {
144 await uploadDir(localPath, r2Key)
145 } else if (entry.isFile()) {
146 await uploadFile(localPath, r2Key)
147 }
148 }
149 }
150
151 if (isSelective) {
152 for (const relPath of filesToUpload) {
153 await uploadFile(
154 path.join(process.cwd(), relPath),
155 `api-reference/${relPath}`
156 )
157 }
158 for (const relPath of filesToRemove) {
159 await removeFile(`api-reference/${relPath}`)
160 }
161 } else {
162 const specsDir = path.join(process.cwd(), "specs")
163 console.log(`Uploading ${specsDir} → r2://${bucket}/api-reference/specs`)
164 await uploadDir(specsDir, "api-reference/specs")
165 }
166
167 console.log("Done.")