-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathproxy-api-docs.js
More file actions
185 lines (159 loc) · 5.61 KB
/
proxy-api-docs.js
File metadata and controls
185 lines (159 loc) · 5.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
import { DOMParser } from "https://deno.land/x/deno_dom@v0.1.56/deno-dom-wasm.ts";
export default async (request, context) => {
const url = new URL(request.url);
const originalOrigin = url.origin;
// Redirects from old API paths to new ones
const redirects = {
"/api/doc": "/api",
"/api/admin-api": "/api/doc/admin/",
"/api/http-proxy-api": "/api/doc/http-proxy/",
"/api/schema-registry-api": "/api/doc/schema-registry/",
"/api/cloud-controlplane-api": "/api/doc/cloud-controlplane/",
"/api/cloud-dataplane-api": "/api/doc/cloud-dataplane/",
"/api/cloud-api": "/api/doc/cloud-controlplane/",
};
const normalizedPath = url.pathname.endsWith("/")
? url.pathname.slice(0, -1)
: url.pathname;
if (redirects[normalizedPath]) {
return Response.redirect(`${url.origin}${redirects[normalizedPath]}`, 301);
}
// Map paths to header background colors
const headerColors = {
"/api/doc/admin": "#107569",
"/api/doc/cloud-controlplane": "#014F86",
"/api/doc/cloud-dataplane": "#014F86",
};
const matchedPath = Object.keys(headerColors).find((path) =>
normalizedPath.startsWith(path)
);
const headerColor = headerColors[matchedPath] || "#d73d23";
// Build the proxied Bump.sh URL
const bumpUrl = new URL(request.url);
bumpUrl.host = "bump.sh";
bumpUrl.pathname = `/redpanda/hub/redpanda${bumpUrl.pathname.replace("/api", "")}`;
const secret = Netlify.env.get("BUMP_PROXY_SECRET");
// Validate secret exists
if (!secret) {
console.error("❌ BUMP_PROXY_SECRET environment variable not set");
return new Response("Service temporarily unavailable", { status: 503 });
}
try {
const bumpRes = await fetchWithRetry(bumpUrl, {
headers: {
"X-BUMP-SH-PROXY": secret,
"X-BUMP-SH-EMBED": "true",
"User-Agent": "Redpanda-Docs-Proxy/1.0",
},
});
// Handle non-successful responses
if (!bumpRes.ok) {
console.error(`❌ Bump.sh returned ${bumpRes.status}: ${bumpRes.statusText}`);
throw new Error(`Bump.sh API error: ${bumpRes.status}`);
}
const contentType = bumpRes.headers.get("content-type") || "";
if (!contentType.includes("text/html")) {
return bumpRes;
}
// Load Bump.sh page and widgets
const [
originalHtml,
headScript,
headerWidget,
footerWidget,
] = await Promise.all([
bumpRes.text(),
fetchWidget(`${originalOrigin}/assets/widgets/head-bump.html`, "head-bump"),
fetchWidget(`${originalOrigin}/assets/widgets/header.html`, "header"),
fetchWidget(`${originalOrigin}/assets/widgets/footer.html`, "footer"),
]);
const document = new DOMParser().parseFromString(originalHtml, "text/html");
if (!document) {
console.error("❌ Failed to parse Bump.sh HTML.");
return new Response(originalHtml, {
status: 200,
headers: { "content-type": "text/html; charset=utf-8" },
});
}
// Inject head script
const head = document.querySelector("head");
if (head && headScript) {
const temp = document.createElement("div");
temp.innerHTML = headScript;
for (const node of temp.childNodes) {
head.appendChild(node);
}
}
// Inject header with dynamic background color
const topBody = document.querySelector("#embed-top-body");
if (topBody && headerWidget) {
const coloredHeader = headerWidget.replace(
/(<nav[^>]*style="[^"]*background-color:\s*)#[^";]+/,
`$1${headerColor}`
);
const wrapper = document.createElement("div");
wrapper.innerHTML = coloredHeader;
while (wrapper.firstChild) {
topBody.appendChild(wrapper.firstChild);
}
}
// Inject footer
const bottomBody = document.querySelector("#embed-bottom-body");
if (bottomBody && footerWidget) {
const wrapper = document.createElement("div");
wrapper.innerHTML = footerWidget;
while (wrapper.firstChild) {
bottomBody.appendChild(wrapper.firstChild);
}
}
return new Response(document.documentElement.outerHTML, {
status: 200,
headers: {
"content-type": "text/html; charset=utf-8",
"cache-control": "public, max-age=300", // Cache for 5 minutes
},
});
} catch (error) {
console.error("❌ Failed to fetch from Bump.sh after retries:", error);
// Return a graceful fallback response
return new Response(
`<html><head><title>API Documentation Temporarily Unavailable</title></head><body><h1>API Documentation Temporarily Unavailable</h1><p>Please try again later.</p></body></html>`,
{
status: 503,
headers: { "content-type": "text/html; charset=utf-8" }
}
);
}
};
// Fetch with retry logic and exponential backoff
async function fetchWithRetry(url, options, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch(url, {
...options,
signal: AbortSignal.timeout(10000), // 10 second timeout
});
return response;
} catch (error) {
console.warn(`Attempt ${attempt} failed for ${url}:`, error.message);
if (attempt === maxRetries) {
throw error;
}
// Exponential backoff: wait 2^attempt seconds
const delay = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
// Helper function to fetch widget content with fallback
async function fetchWidget(url, label) {
try {
const res = await fetchWithRetry(url, {}, 2); // 2 retries for widgets
if (res.ok) return await res.text();
console.warn(`⚠️ Failed to load ${label} widget from ${url}`);
return "";
} catch (err) {
console.error(`❌ Error fetching ${label} widget:`, err);
return "";
}
}