-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathproxy.ts
More file actions
155 lines (132 loc) · 5.32 KB
/
Copy pathproxy.ts
File metadata and controls
155 lines (132 loc) · 5.32 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
import { createServerClient } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'
import { getCanonicalSkillSlug } from '@/lib/skill-slug-aliases'
const MARKET_LOCALE_CODES = new Set(['zh', 'ja', 'ko', 'es', 'de', 'fr', 'id'])
const DOCUMENT_LANG_BY_LOCALE: Record<string, string> = {
zh: 'zh-CN',
ja: 'ja',
ko: 'ko',
es: 'es',
de: 'de',
fr: 'fr',
id: 'id',
}
const LEGACY_LOCALIZED_NAVIGATION_PATHS = new Set([
'/',
'/resolve',
'/skills',
'/tasks',
'/skill-packs',
'/compare',
'/api-docs',
'/agent-skill',
'/agent-skills-registry',
'/docs',
'/submit',
])
const LOCALIZED_DEEP_ROUTE_ROOTS = new Set(['/skill-packs', '/collections'])
const SESSION_REFRESH_PATH_PREFIXES = ['/profile', '/api/claims', '/api/points']
function getLocalizedDeepPath(pathname: string, locale: string) {
const segments = pathname.split('/').filter(Boolean)
const [root, ...rest] = segments
const baseRoot = `/${root || ''}`
if (!LOCALIZED_DEEP_ROUTE_ROOTS.has(baseRoot) || rest.length === 0) return null
return `/${locale}/${[root, ...rest].join('/')}`
}
function getLocaleFromPath(pathname: string) {
const segment = pathname.split('/').filter(Boolean)[0]
return segment && MARKET_LOCALE_CODES.has(segment) ? segment : null
}
function getCanonicalSkillPath(pathname: string) {
const match = pathname.match(/^\/skills\/([^/]+)(\/(?:audit|evals))?$/)
if (!match) return null
const [, requestedSlug, suffix = ''] = match
const canonicalSlug = getCanonicalSkillSlug(requestedSlug)
if (requestedSlug === canonicalSlug) return null
return `/skills/${canonicalSlug}${suffix}`
}
function createNextResponse(locale: string | null, noindex = false) {
const response = NextResponse.next()
if (locale) response.headers.set('Content-Language', DOCUMENT_LANG_BY_LOCALE[locale] || locale)
if (noindex) response.headers.set('X-Robots-Tag', 'noindex, follow')
return response
}
function isSkillDetailVariant(pathname: string, searchParams: URLSearchParams) {
return /^\/skills\/[^/]+$/.test(pathname) && Array.from(searchParams.keys()).length > 0
}
function needsSessionRefresh(pathname: string) {
return SESSION_REFRESH_PATH_PREFIXES.some(
(prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`)
)
}
// Fallback to hardcoded values if env vars are not set (same as public.ts)
const SUPABASE_URL =
process.env.NEXT_PUBLIC_SUPABASE_URL ||
process.env.SUPABASE_URL ||
'https://rtuodkczrlkxwwtaxwrr.supabase.co'
const SUPABASE_ANON_KEY =
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||
process.env.SUPABASE_ANON_KEY ||
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJ0dW9ka2N6cmxreHd3dGF4d3JyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzE1OTc0ODAsImV4cCI6MjA4NzE3MzQ4MH0.KlJ70ysYG78x1hwOTmePW53t_IEeLqC_PzGiBozh2Ug'
export async function proxy(request: NextRequest) {
const { pathname, searchParams } = request.nextUrl
const queryLocale = searchParams.get('lang')
const pathLocale = getLocaleFromPath(pathname)
const locale = pathLocale || (queryLocale && MARKET_LOCALE_CODES.has(queryLocale) ? queryLocale : null)
const noindex = isSkillDetailVariant(pathname, searchParams)
// Static skill pages can be served straight from the cache, so normalize
// aliases here instead of relying on a page-level redirect.
const canonicalSkillPath = getCanonicalSkillPath(pathname)
if (canonicalSkillPath) {
const url = request.nextUrl.clone()
url.pathname = canonicalSkillPath
return NextResponse.redirect(url, 308)
}
// Canonicalize query-based locale links before rendering. Core navigation
// routes and curated deep pages both have stable locale paths, so the first
// server render, metadata, and client navigation all share one language.
if (queryLocale && MARKET_LOCALE_CODES.has(queryLocale)) {
const localizedDeepPath = getLocalizedDeepPath(pathname, queryLocale)
if (LEGACY_LOCALIZED_NAVIGATION_PATHS.has(pathname) || localizedDeepPath) {
const url = request.nextUrl.clone()
url.pathname = localizedDeepPath || (pathname === '/' ? `/${queryLocale}` : `/${queryLocale}${pathname}`)
url.searchParams.delete('lang')
return NextResponse.redirect(url, 308)
}
}
const initialResponse = createNextResponse(locale, noindex)
// Public discovery pages do not need an auth lookup on every navigation.
// Keeping this proxy lightweight makes language changes and deep links fast.
if (!needsSessionRefresh(pathname)) {
return initialResponse
}
let supabaseResponse = initialResponse
const supabase = createServerClient(
SUPABASE_URL,
SUPABASE_ANON_KEY,
{
cookies: {
getAll() {
return request.cookies.getAll()
},
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value))
supabaseResponse = createNextResponse(locale, noindex)
cookiesToSet.forEach(({ name, value, options }) =>
supabaseResponse.cookies.set(name, value, options),
)
},
},
},
)
// Refresh session — do NOT add code between createServerClient and getUser
await supabase.auth.getUser()
return supabaseResponse
}
export const config = {
matcher: [
'/((?!api(?:/|$)|_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml|sitemaps/).*)',
'/api/claims/:path*',
'/api/points/:path*',
],
}