-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
253 lines (210 loc) · 6.83 KB
/
Copy pathmiddleware.ts
File metadata and controls
253 lines (210 loc) · 6.83 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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import { next } from "@vercel/edge";
export const config = {
matcher: ["/", "/festivals/:path*", "/editions/:path*"],
};
const BOT_USER_AGENT_RE =
/facebookexternalhit|Facebot|Twitterbot|Slackbot|LinkedInBot|WhatsApp|TelegramBot|Discordbot|SkypeUriPreview|iMessageLinkPreview|Applebot|redditbot|Pinterest|vkShare|W3C_Validator|Googlebot|bot|crawler|spider|preview|unfurl|opengraph|embed|scraper|validator/i;
const SET_PATH_RE = /^\/festivals\/([^/]+)\/editions\/([^/]+)\/sets\/([^/]+)/;
const EDITION_PATH_RE = /^\/festivals\/([^/]+)\/editions\/([^/]+)/;
const FESTIVAL_PATH_RE = /^\/festivals\/([^/]+)\/?$/;
const SUBDOMAIN_SET_PATH_RE = /^\/editions\/([^/]+)\/sets\/([^/]+)/;
const SUBDOMAIN_EDITION_PATH_RE = /^\/editions\/([^/]+)/;
interface SocialMeta {
title: string;
description: string;
}
export default async function middleware(request: Request) {
const userAgent = request.headers.get("user-agent") ?? "";
if (!BOT_USER_AGENT_RE.test(userAgent)) {
return next();
}
const url = new URL(request.url);
const meta = await resolveSocialMeta(url);
if (!meta) {
return next();
}
const indexUrl = new URL("/index.html", url.origin);
const indexResponse = await fetch(indexUrl);
if (!indexResponse.ok) {
return next();
}
const html = applySocialMeta(await indexResponse.text(), meta);
return new Response(html, {
headers: { "content-type": "text/html; charset=utf-8" },
});
}
// Production festival pages are served from a subdomain (own-spirit.getupline.com),
// with the path carrying only the edition/set segments (no /festivals prefix).
function getFestivalSlugFromHost(hostname: string): string | null {
if (!hostname.endsWith("getupline.com")) return null;
const parts = hostname.split(".");
if (parts.length < 3) return null;
const [subdomain] = parts;
return subdomain === "www" ? null : subdomain;
}
async function resolveSocialMeta(url: URL): Promise<SocialMeta | null> {
const pathname = url.pathname;
const hostFestivalSlug = getFestivalSlugFromHost(url.hostname);
if (hostFestivalSlug) {
const setMatch = pathname.match(SUBDOMAIN_SET_PATH_RE);
if (setMatch) {
return resolveSetMeta(hostFestivalSlug, setMatch[1], setMatch[2]);
}
const editionMatch = pathname.match(SUBDOMAIN_EDITION_PATH_RE);
if (editionMatch) {
return resolveEditionMeta(hostFestivalSlug, editionMatch[1]);
}
if (pathname === "/") {
return resolveFestivalMeta(hostFestivalSlug);
}
return null;
}
const setMatch = pathname.match(SET_PATH_RE);
if (setMatch) {
return resolveSetMeta(setMatch[1], setMatch[2], setMatch[3]);
}
const editionMatch = pathname.match(EDITION_PATH_RE);
if (editionMatch) {
return resolveEditionMeta(editionMatch[1], editionMatch[2]);
}
const festivalMatch = pathname.match(FESTIVAL_PATH_RE);
if (festivalMatch) {
return resolveFestivalMeta(festivalMatch[1]);
}
return null;
}
async function resolveFestivalMeta(
festivalSlug: string,
): Promise<SocialMeta | null> {
const festival = await fetchFestivalBySlug(festivalSlug);
if (!festival) return null;
return {
title: festival.name,
description: festival.description || "UpLine - Your Festival companion",
};
}
async function resolveEditionMeta(
festivalSlug: string,
editionSlug: string,
): Promise<SocialMeta | null> {
const festival = await fetchFestivalBySlug(festivalSlug);
if (!festival) return null;
const edition = await fetchEditionBySlug(festival.id, editionSlug);
if (!edition) return null;
return {
title: `${festival.name} - ${edition.name}`,
description:
edition.description ||
festival.description ||
"UpLine - Your Festival companion",
};
}
async function resolveSetMeta(
festivalSlug: string,
editionSlug: string,
setSlug: string,
): Promise<SocialMeta | null> {
const festival = await fetchFestivalBySlug(festivalSlug);
if (!festival) return null;
const edition = await fetchEditionBySlug(festival.id, editionSlug);
if (!edition) return null;
const set = await fetchSetBySlug(edition.id, setSlug);
if (!set) return null;
return {
title: `${set.name} - ${festival.name}`,
description:
set.description || `${set.name} at ${festival.name} ${edition.name}`,
};
}
interface FestivalRecord {
id: string;
name: string;
description: string | null;
}
interface EditionRecord {
id: string;
name: string;
description: string | null;
}
interface SetRecord {
name: string;
description: string | null;
}
async function fetchFestivalBySlug(
slug: string,
): Promise<FestivalRecord | null> {
const rows = await supabaseSelect<FestivalRecord>("festivals", {
select: "id,name,description",
slug: `eq.${slug}`,
archived: "eq.false",
});
return rows[0] ?? null;
}
async function fetchEditionBySlug(
festivalId: string,
slug: string,
): Promise<EditionRecord | null> {
const rows = await supabaseSelect<EditionRecord>("festival_editions", {
select: "id,name,description",
festival_id: `eq.${festivalId}`,
slug: `eq.${slug}`,
archived: "eq.false",
});
return rows[0] ?? null;
}
async function fetchSetBySlug(
editionId: string,
slug: string,
): Promise<SetRecord | null> {
const rows = await supabaseSelect<SetRecord>("sets", {
select: "name,description",
festival_edition_id: `eq.${editionId}`,
slug: `eq.${slug}`,
archived: "eq.false",
});
return rows[0] ?? null;
}
async function supabaseSelect<T>(
table: string,
params: Record<string, string>,
): Promise<T[]> {
const supabaseUrl = process.env.VITE_SUPABASE_URL;
const supabaseKey = process.env.VITE_SUPABASE_PUBLISHABLE_KEY;
if (!supabaseUrl || !supabaseKey) return [];
const url = new URL(`${supabaseUrl}/rest/v1/${table}`);
for (const [key, value] of Object.entries(params)) {
url.searchParams.set(key, value);
}
const response = await fetch(url, {
headers: {
apikey: supabaseKey,
authorization: `Bearer ${supabaseKey}`,
},
});
if (!response.ok) return [];
return response.json() as Promise<T[]>;
}
function applySocialMeta(html: string, meta: SocialMeta): string {
const fullTitle = `${meta.title} - UpLine`;
return html
.replace(/<title>.*?<\/title>/, `<title>${escapeHtml(fullTitle)}</title>`)
.replace(
/<meta name="description" content=".*?"\s*\/>/,
`<meta name="description" content="${escapeHtml(meta.description)}" />`,
)
.replace(
/<meta property="og:title" content=".*?"\s*\/>/,
`<meta property="og:title" content="${escapeHtml(fullTitle)}" />`,
)
.replace(
/<meta\s+property="og:description"\s+content=".*?"\s*\/>/,
`<meta property="og:description" content="${escapeHtml(meta.description)}" />`,
);
}
function escapeHtml(value: string): string {
return value
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
}