import { createClient, type SupabaseClient } from '@supabase/supabase-js' const supabaseUrl = import.meta.env['VITE_SUPABASE_URL'] ?? '' const supabaseAnonKey = import.meta.env['VITE_SUPABASE_ANON_KEY'] ?? '' const isLocalDev = supabaseUrl.includes('localhost') // supabase-js hardcodes /auth/v1 as the auth path prefix, but GoTrue // serves at the root when accessed directly (no API gateway). // This custom fetch strips the prefix for local dev. function localGoTrueFetch(input: RequestInfo | URL, init?: RequestInit): Promise { const url = input instanceof Request ? input.url : String(input) const rewritten = url.replace('/auth/v1/', '/') if (input instanceof Request) { return fetch(new Request(rewritten, input), init) } return fetch(rewritten, init) } function createSupabaseClient(): SupabaseClient { if (!supabaseUrl || !supabaseAnonKey) { return createClient('http://localhost:9999', 'stub-key') } return createClient(supabaseUrl, supabaseAnonKey, { auth: { autoRefreshToken: true, persistSession: true, }, ...(isLocalDev && { global: { fetch: localGoTrueFetch }, }), }) } export const supabase = createSupabaseClient()