Compare commits
21 Commits
main
...
6e7ef894bf
| Author | SHA1 | Date | |
|---|---|---|---|
| 6e7ef894bf | |||
|
|
562d8294da | ||
| ca5bafff46 | |||
|
|
12dcf00d5f | ||
| 70d591f925 | |||
|
|
fda8751642 | ||
| bccadd18e2 | |||
|
|
41cfcc0260 | ||
| 71641f61bf | |||
|
|
1f1de2e04b | ||
| 9353fa8492 | |||
|
|
d2e1e5d4f0 | ||
| 957ff79033 | |||
|
|
2551ff8bb3 | ||
| ef06665fbc | |||
|
|
76306cc937 | ||
| 42263c2e7b | |||
|
|
152235dd14 | ||
| 0665521a7c | |||
|
|
6fddbbab68 | ||
|
|
3909fbc966 |
@@ -122,25 +122,17 @@ export const Route = createRootRouteWithContext<{
|
||||
context.queryClient,
|
||||
playerQueries.auth()
|
||||
);
|
||||
|
||||
console.log('__root beforeLoad auth data:', auth);
|
||||
|
||||
return { auth };
|
||||
} catch (error: any) {
|
||||
if (typeof window !== 'undefined') {
|
||||
const { doesSessionExist, attemptRefreshingSession } = await import('supertokens-web-js/recipe/session');
|
||||
if (error?.options?.to && error?.options?.statusCode) {
|
||||
console.log('__root beforeLoad: Re-throwing redirect', error.options);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const sessionExists = await doesSessionExist();
|
||||
if (sessionExists) {
|
||||
try {
|
||||
await attemptRefreshingSession();
|
||||
const auth = await ensureServerQueryData(
|
||||
context.queryClient,
|
||||
playerQueries.auth()
|
||||
);
|
||||
return { auth };
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
}
|
||||
console.error('__root beforeLoad error:', error);
|
||||
return {};
|
||||
}
|
||||
},
|
||||
|
||||
@@ -5,10 +5,14 @@ import { Flex, Loader } from "@mantine/core";
|
||||
|
||||
export const Route = createFileRoute("/_authed")({
|
||||
beforeLoad: ({ context }) => {
|
||||
console.log('_authed beforeLoad context:', context.auth);
|
||||
|
||||
if (!context.auth?.user) {
|
||||
console.log('_authed: No user in context, redirecting to login');
|
||||
throw redirect({ to: "/login" });
|
||||
}
|
||||
|
||||
console.log('_authed: User found, allowing access');
|
||||
return {
|
||||
auth: {
|
||||
...context.auth,
|
||||
|
||||
@@ -107,7 +107,6 @@ function RouteComponent() {
|
||||
tournamentId={tournament.id}
|
||||
hasKnockoutBracket={knockoutBracketPopulated}
|
||||
isRegional={tournament.regional}
|
||||
groupConfig={tournament.group_config}
|
||||
/>
|
||||
<Divider />
|
||||
<div>
|
||||
@@ -123,7 +122,6 @@ function RouteComponent() {
|
||||
tournamentId={tournament.id}
|
||||
hasKnockoutBracket={knockoutBracketPopulated}
|
||||
isRegional={tournament.regional}
|
||||
groupConfig={tournament.group_config}
|
||||
/>
|
||||
) : (
|
||||
<BracketView bracket={bracket} showControls groupConfig={tournament.group_config} />
|
||||
|
||||
@@ -40,7 +40,6 @@ function RouteComponent() {
|
||||
groups={tournament.groups || []}
|
||||
matches={tournament.matches || []}
|
||||
isRegional={tournament.regional}
|
||||
groupConfig={tournament.group_config}
|
||||
/>
|
||||
</Container>
|
||||
);
|
||||
|
||||
@@ -2,6 +2,7 @@ import LoginLayout from "@/features/login/components/layout";
|
||||
import LoginFlow from "@/features/login/components/login-flow";
|
||||
import { redirect, createFileRoute } from "@tanstack/react-router";
|
||||
import z from "zod";
|
||||
import { useEffect } from "react";
|
||||
|
||||
const loginSearchSchema = z.object({
|
||||
stage: z.enum(["code", "name"]).optional(),
|
||||
@@ -9,6 +10,36 @@ const loginSearchSchema = z.object({
|
||||
callback: z.string().optional(),
|
||||
});
|
||||
|
||||
function LoginComponent() {
|
||||
useEffect(() => {
|
||||
if (typeof window !== 'undefined') {
|
||||
const cookies = document.cookie.split(';');
|
||||
const accessTokenCookies = cookies.filter(c => c.trim().startsWith('sAccessToken='));
|
||||
|
||||
if (accessTokenCookies.length > 0) {
|
||||
console.log('[Login] Clearing old SuperTokens cookies');
|
||||
|
||||
const cookieNames = ['sAccessToken', 'sRefreshToken', 'sIdRefreshToken', 'sFrontToken'];
|
||||
const cookieDomain = (window as any).__COOKIE_DOMAIN__ || undefined;
|
||||
|
||||
cookieNames.forEach(name => {
|
||||
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
|
||||
|
||||
if (cookieDomain) {
|
||||
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=${cookieDomain}`;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<LoginLayout>
|
||||
<LoginFlow />
|
||||
</LoginLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export const Route = createFileRoute("/login")({
|
||||
validateSearch: loginSearchSchema,
|
||||
beforeLoad: async ({ context }) => {
|
||||
@@ -16,11 +47,5 @@ export const Route = createFileRoute("/login")({
|
||||
throw redirect({ to: "/" });
|
||||
}
|
||||
},
|
||||
component: () => {
|
||||
return (
|
||||
<LoginLayout>
|
||||
<LoginFlow />
|
||||
</LoginLayout>
|
||||
);
|
||||
},
|
||||
component: LoginComponent,
|
||||
});
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useEffect, useRef } from 'react'
|
||||
import FullScreenLoader from '@/components/full-screen-loader'
|
||||
import { attemptRefreshingSession } from 'supertokens-web-js/recipe/session'
|
||||
import { resetRefreshFlag, getOrCreateRefreshPromise } from '@/lib/supertokens/client'
|
||||
import { refreshManager } from '@/lib/supertokens/refresh-manager'
|
||||
import { logger } from '@/lib/supertokens'
|
||||
|
||||
export const Route = createFileRoute('/refresh-session')({
|
||||
@@ -20,9 +19,7 @@ function RouteComponent() {
|
||||
try {
|
||||
logger.info("Refresh session route: starting refresh");
|
||||
|
||||
const refreshed = await getOrCreateRefreshPromise(async () => {
|
||||
return await attemptRefreshingSession();
|
||||
});
|
||||
const refreshed = await refreshManager.refresh();
|
||||
|
||||
if (refreshed) {
|
||||
logger.info("Refresh session route: refresh successful");
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useNavigate } from '@tanstack/react-router';
|
||||
import { doesSessionExist } from 'supertokens-web-js/recipe/session';
|
||||
import { getOrCreateRefreshPromise } from '@/lib/supertokens/client';
|
||||
import { attemptRefreshingSession } from 'supertokens-web-js/recipe/session';
|
||||
import { refreshManager } from '@/lib/supertokens/refresh-manager';
|
||||
import { logger } from '@/lib/supertokens';
|
||||
import { ensureSuperTokensFrontend } from '@/lib/supertokens/client';
|
||||
|
||||
export function SessionMonitor() {
|
||||
const navigate = useNavigate();
|
||||
const lastRefreshTimeRef = useRef<number>(0);
|
||||
const REFRESH_COOLDOWN = 30 * 1000;
|
||||
const REFRESH_COOLDOWN = 5 * 1000;
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
@@ -22,23 +19,27 @@ export function SessionMonitor() {
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
if (now - lastRefreshTimeRef.current < REFRESH_COOLDOWN) {
|
||||
logger.info('Session monitor: skipping refresh (cooldown)');
|
||||
const timeSinceLastRefresh = now - lastRefreshTimeRef.current;
|
||||
|
||||
if (timeSinceLastRefresh < REFRESH_COOLDOWN) {
|
||||
logger.info(`Session monitor: skipping refresh (refreshed ${timeSinceLastRefresh}ms ago)`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
ensureSuperTokensFrontend();
|
||||
|
||||
const { doesSessionExist } = await import('supertokens-web-js/recipe/session');
|
||||
|
||||
const sessionExists = await doesSessionExist();
|
||||
if (!sessionExists) {
|
||||
logger.info('Session monitor: no session exists, skipping refresh');
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info('Session monitor: tab became visible, refreshing session');
|
||||
logger.info('Session monitor: tab became visible, checking session freshness');
|
||||
|
||||
const refreshed = await getOrCreateRefreshPromise(async () => {
|
||||
return await attemptRefreshingSession();
|
||||
});
|
||||
const refreshed = await refreshManager.refresh();
|
||||
|
||||
if (refreshed) {
|
||||
lastRefreshTimeRef.current = Date.now();
|
||||
@@ -46,19 +47,17 @@ export function SessionMonitor() {
|
||||
} else {
|
||||
logger.warn('Session monitor: refresh returned false');
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Session monitor: error refreshing session', error);
|
||||
} catch (error: any) {
|
||||
logger.error('Session monitor: error refreshing session', error?.message);
|
||||
}
|
||||
};
|
||||
|
||||
handleVisibilityChange();
|
||||
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
};
|
||||
}, [navigate]);
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ const BracketView: React.FC<BracketViewProps> = ({ bracket, showControls, groupC
|
||||
</Text>
|
||||
<Bracket rounds={bracket.winners} orders={orders} showControls={showControls} groupConfig={groupConfig} />
|
||||
</div>
|
||||
{bracket.losers && bracket.losers.length > 0 && bracket.losers.some(round => round.length > 0) && (
|
||||
{bracket.losers && (
|
||||
<div>
|
||||
<Text fw={600} size="md" m={16}>
|
||||
Losers Bracket
|
||||
|
||||
@@ -40,15 +40,6 @@ export const MatchCard: React.FC<MatchCardProps> = ({
|
||||
const numGroups = groupConfig.num_groups;
|
||||
const advancePerGroup = groupConfig.advance_per_group;
|
||||
|
||||
const totalQualifiedTeams = numGroups * advancePerGroup;
|
||||
const nextPowerOf2 = Math.pow(2, Math.ceil(Math.log2(totalQualifiedTeams)));
|
||||
const wildcardsNeeded = nextPowerOf2 - totalQualifiedTeams;
|
||||
|
||||
if (seed > totalQualifiedTeams && wildcardsNeeded > 0) {
|
||||
const wildcardNumber = seed - totalQualifiedTeams;
|
||||
return `Wildcard ${wildcardNumber}`;
|
||||
}
|
||||
|
||||
const pairIndex = Math.floor((seed - 1) / 2);
|
||||
const isFirstInPair = (seed - 1) % 2 === 0;
|
||||
|
||||
|
||||
@@ -270,120 +270,15 @@ async function populateKnockoutBracketInternal(tournamentId: string, groupConfig
|
||||
|
||||
const orderedTeamIds: string[] = [];
|
||||
const maxRank = groupConfig.advance_per_group;
|
||||
const numGroups = groupConfig.num_groups;
|
||||
|
||||
const teamsByGroup: string[][] = [];
|
||||
for (let g = 0; g < numGroups; g++) {
|
||||
teamsByGroup[g] = [];
|
||||
for (let rank = 1; rank <= maxRank; rank++) {
|
||||
const teamsAtRank = qualifiedTeams
|
||||
.filter(t => t.rank === rank)
|
||||
.sort((a, b) => a.groupOrder - b.groupOrder);
|
||||
orderedTeamIds.push(...teamsAtRank.map(t => t.teamId));
|
||||
}
|
||||
|
||||
for (const qualified of qualifiedTeams) {
|
||||
teamsByGroup[qualified.groupOrder][qualified.rank - 1] = qualified.teamId;
|
||||
}
|
||||
|
||||
const totalQualifiedTeams = numGroups * maxRank;
|
||||
for (let i = 0; i < totalQualifiedTeams / 2; i++) {
|
||||
const group1 = i % numGroups;
|
||||
const rankIndex1 = Math.floor(i / numGroups);
|
||||
|
||||
const group2 = (i + 1) % numGroups;
|
||||
const rankIndex2 = maxRank - 1 - rankIndex1;
|
||||
|
||||
const team1 = teamsByGroup[group1]?.[rankIndex1];
|
||||
const team2 = teamsByGroup[group2]?.[rankIndex2];
|
||||
|
||||
if (team1) orderedTeamIds.push(team1);
|
||||
if (team2) orderedTeamIds.push(team2);
|
||||
}
|
||||
|
||||
const knockoutTeamCount = orderedTeamIds.length;
|
||||
const nextPowerOf2 = Math.pow(2, Math.ceil(Math.log2(knockoutTeamCount)));
|
||||
const wildcardsNeeded = nextPowerOf2 - knockoutTeamCount;
|
||||
|
||||
if (wildcardsNeeded > 0) {
|
||||
logger.info('Wildcards needed', { knockoutTeamCount, nextPowerOf2, wildcardsNeeded });
|
||||
|
||||
const allNonQualifiedTeams: Array<{ teamId: string; wins: number; losses: number; cups_for: number; cups_against: number; cup_differential: number }> = [];
|
||||
const qualifiedTeamIds = new Set(qualifiedTeams.map(t => t.teamId));
|
||||
|
||||
for (const group of groups) {
|
||||
const groupMatches = await pbAdmin.getMatchesByGroup(group.id);
|
||||
const completedMatches = groupMatches.filter(m => m.status === "ended");
|
||||
|
||||
const standings = new Map<string, { teamId: string; wins: number; losses: number; cups_for: number; cups_against: number; cup_differential: number }>();
|
||||
|
||||
for (const team of group.teams || []) {
|
||||
const teamId = typeof team === 'string' ? team : team.id;
|
||||
|
||||
if (qualifiedTeamIds.has(teamId)) continue;
|
||||
|
||||
standings.set(teamId, {
|
||||
teamId,
|
||||
wins: 0,
|
||||
losses: 0,
|
||||
cups_for: 0,
|
||||
cups_against: 0,
|
||||
cup_differential: 0,
|
||||
});
|
||||
}
|
||||
|
||||
for (const match of completedMatches) {
|
||||
if (!match.home || !match.away) continue;
|
||||
|
||||
const homeStanding = standings.get(match.home.id);
|
||||
const awayStanding = standings.get(match.away.id);
|
||||
|
||||
if (homeStanding) {
|
||||
homeStanding.cups_for += match.home_cups;
|
||||
homeStanding.cups_against += match.away_cups;
|
||||
homeStanding.cup_differential = homeStanding.cups_for - homeStanding.cups_against;
|
||||
|
||||
if (match.home_cups > match.away_cups) {
|
||||
homeStanding.wins++;
|
||||
} else {
|
||||
homeStanding.losses++;
|
||||
}
|
||||
}
|
||||
|
||||
if (awayStanding) {
|
||||
awayStanding.cups_for += match.away_cups;
|
||||
awayStanding.cups_against += match.home_cups;
|
||||
awayStanding.cup_differential = awayStanding.cups_for - awayStanding.cups_against;
|
||||
|
||||
if (match.away_cups > match.home_cups) {
|
||||
awayStanding.wins++;
|
||||
} else {
|
||||
awayStanding.losses++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
allNonQualifiedTeams.push(...Array.from(standings.values()));
|
||||
}
|
||||
|
||||
allNonQualifiedTeams.sort((a, b) => {
|
||||
if (b.wins !== a.wins) return b.wins - a.wins;
|
||||
if (b.cup_differential !== a.cup_differential) return b.cup_differential - a.cup_differential;
|
||||
if (b.cups_for !== a.cups_for) return b.cups_for - a.cups_for;
|
||||
return a.teamId.localeCompare(b.teamId);
|
||||
});
|
||||
|
||||
const wildcardTeams = allNonQualifiedTeams.slice(0, wildcardsNeeded);
|
||||
const wildcardTeamIds = wildcardTeams.map(t => t.teamId);
|
||||
|
||||
orderedTeamIds.push(...wildcardTeamIds);
|
||||
|
||||
logger.info('Added wildcard teams', {
|
||||
wildcardTeams: wildcardTeams.map(t => ({
|
||||
teamId: t.teamId,
|
||||
wins: t.wins,
|
||||
cupDiff: t.cup_differential,
|
||||
cupsFor: t.cups_for
|
||||
}))
|
||||
});
|
||||
}
|
||||
|
||||
logger.info('Ordered team IDs (with wildcards)', { orderedTeamIds, totalTeams: orderedTeamIds.length });
|
||||
logger.info('Ordered team IDs', { orderedTeamIds });
|
||||
|
||||
const tournament = await pbAdmin.getTournament(tournamentId);
|
||||
const knockoutMatches = (tournament.matches || [])
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { useServerSuspenseQuery } from "@/lib/tanstack-query/hooks";
|
||||
import { listPlayers, getPlayer, getUnassociatedPlayers, fetchMe, getPlayerStats, getAllPlayerStats, getPlayerMatches, getUnenrolledPlayers, getPlayersActivity } from "./server";
|
||||
import { logger } from '@/lib/supertokens';
|
||||
|
||||
let queryRefreshRedirect: Promise<void> | null = null;
|
||||
|
||||
export const playerKeys = {
|
||||
auth: ['auth'],
|
||||
@@ -64,37 +61,7 @@ export const useMe = () => {
|
||||
staleTime: 30 * 1000,
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: true,
|
||||
retry: (failureCount, error: any) => {
|
||||
if (error?.response?.status === 401) {
|
||||
const errorData = error?.response?.data;
|
||||
if (errorData?.error === 'SESSION_REFRESH_REQUIRED') {
|
||||
logger.warn("Query detected SESSION_REFRESH_REQUIRED");
|
||||
|
||||
if (!queryRefreshRedirect) {
|
||||
const currentUrl = window.location.pathname + window.location.search;
|
||||
logger.info("Query initiating refresh redirect to:", currentUrl);
|
||||
|
||||
queryRefreshRedirect = new Promise<void>((resolve) => {
|
||||
setTimeout(() => {
|
||||
window.location.href = `/refresh-session?redirect=${encodeURIComponent(currentUrl)}`;
|
||||
resolve();
|
||||
}, 100);
|
||||
});
|
||||
|
||||
queryRefreshRedirect.finally(() => {
|
||||
setTimeout(() => {
|
||||
queryRefreshRedirect = null;
|
||||
}, 1000);
|
||||
});
|
||||
} else {
|
||||
logger.info("Query: refresh redirect already in progress");
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return failureCount < 3;
|
||||
},
|
||||
retry: 3,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -26,13 +26,25 @@ export const fetchMe = createServerFn()
|
||||
phone: context.phone
|
||||
};
|
||||
} catch (error: any) {
|
||||
// logger.info("FetchMe: Session error", error)
|
||||
if (error?.response?.status === 401) {
|
||||
const errorData = error?.response?.data;
|
||||
if (errorData?.error === "SESSION_REFRESH_REQUIRED") {
|
||||
logger.info("FetchMe: Error caught", {
|
||||
message: error?.message,
|
||||
isResponse: error instanceof Response,
|
||||
status: error instanceof Response ? error.status : error?.response?.status,
|
||||
hasOptions: !!error?.options,
|
||||
redirectTo: error?.options?.to
|
||||
});
|
||||
|
||||
if (error?.options?.to && error?.options?.statusCode) {
|
||||
logger.info("FetchMe: Redirect detected, re-throwing", error.options);
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (error?.message === "Unauthenticated") {
|
||||
logger.info("FetchMe: No authenticated user (expected when not logged in)");
|
||||
return { user: undefined, roles: [], metadata: {}, phone: undefined };
|
||||
}
|
||||
|
||||
logger.warn("FetchMe: Unexpected error, returning default", error);
|
||||
return { user: undefined, roles: [], metadata: {}, phone: undefined };
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import React, { useMemo, useState } from "react";
|
||||
import { Stack, Text, Card, Group as MantineGroup, Box, SimpleGrid, Tabs, Collapse, ActionIcon, Button, Alert, Badge } from "@mantine/core";
|
||||
import { Stack, Text, Card, Group as MantineGroup, Box, SimpleGrid, Tabs, Collapse, ActionIcon, Button, Alert } from "@mantine/core";
|
||||
import { CaretCircleDownIcon, CaretCircleUpIcon } from "@phosphor-icons/react";
|
||||
import { Match } from "@/features/matches/types";
|
||||
import { Group, GroupConfig } from "../types";
|
||||
import { Group } from "../types";
|
||||
import GroupMatchCard from "./group-match-card";
|
||||
import TeamAvatar from "@/components/team-avatar";
|
||||
import { useServerMutation } from "@/lib/tanstack-query/hooks/use-server-mutation";
|
||||
@@ -17,7 +17,6 @@ interface GroupStageViewProps {
|
||||
tournamentId?: string;
|
||||
hasKnockoutBracket?: boolean;
|
||||
isRegional?: boolean;
|
||||
groupConfig?: GroupConfig;
|
||||
}
|
||||
|
||||
interface TeamStanding {
|
||||
@@ -38,7 +37,6 @@ const GroupStageView: React.FC<GroupStageViewProps> = ({
|
||||
tournamentId,
|
||||
hasKnockoutBracket,
|
||||
isRegional,
|
||||
groupConfig,
|
||||
}) => {
|
||||
const queryClient = useQueryClient();
|
||||
const [expandedTeams, setExpandedTeams] = useState<Record<string, boolean>>({});
|
||||
@@ -241,57 +239,6 @@ const GroupStageView: React.FC<GroupStageViewProps> = ({
|
||||
});
|
||||
};
|
||||
|
||||
const allGroupStandings = useMemo(() => {
|
||||
return sortedGroups.map((group) => ({
|
||||
groupId: group.id,
|
||||
groupOrder: group.order,
|
||||
standings: getTeamStandings(group.id, group.teams || []),
|
||||
}));
|
||||
}, [sortedGroups, matchesByGroup]);
|
||||
|
||||
const advancingTeams = useMemo(() => {
|
||||
if (!groupConfig) return { qualifiedTeams: new Set<string>(), wildcardTeams: new Set<string>() };
|
||||
|
||||
const advancePerGroup = groupConfig.advance_per_group;
|
||||
const qualifiedTeams = new Set<string>();
|
||||
const wildcardTeams = new Set<string>();
|
||||
|
||||
allGroupStandings.forEach(({ standings }) => {
|
||||
standings.slice(0, advancePerGroup).forEach((standing) => {
|
||||
qualifiedTeams.add(standing.teamId);
|
||||
});
|
||||
});
|
||||
|
||||
const totalQualified = qualifiedTeams.size;
|
||||
const knockoutTeamCount = totalQualified;
|
||||
|
||||
const nextPowerOf2 = Math.pow(2, Math.ceil(Math.log2(knockoutTeamCount)));
|
||||
const wildcardsNeeded = nextPowerOf2 - knockoutTeamCount;
|
||||
|
||||
if (wildcardsNeeded > 0) {
|
||||
const allNonQualifiedTeams: TeamStanding[] = [];
|
||||
|
||||
allGroupStandings.forEach(({ standings }) => {
|
||||
standings.slice(advancePerGroup).forEach((standing) => {
|
||||
allNonQualifiedTeams.push(standing);
|
||||
});
|
||||
});
|
||||
|
||||
allNonQualifiedTeams.sort((a, b) => {
|
||||
if (b.wins !== a.wins) return b.wins - a.wins;
|
||||
if (b.cupDifference !== a.cupDifference) return b.cupDifference - a.cupDifference;
|
||||
if (b.cupsFor !== a.cupsFor) return b.cupsFor - a.cupsFor;
|
||||
return a.teamId.localeCompare(b.teamId);
|
||||
});
|
||||
|
||||
allNonQualifiedTeams.slice(0, wildcardsNeeded).forEach((standing) => {
|
||||
wildcardTeams.add(standing.teamId);
|
||||
});
|
||||
}
|
||||
|
||||
return { qualifiedTeams, wildcardTeams };
|
||||
}, [allGroupStandings, groupConfig]);
|
||||
|
||||
if (sortedGroups.length === 0) {
|
||||
return (
|
||||
<Box p="md">
|
||||
@@ -374,12 +321,7 @@ const GroupStageView: React.FC<GroupStageViewProps> = ({
|
||||
<Collapse in={expandedTeams[group.id]}>
|
||||
<Stack gap={0}>
|
||||
{standings.length > 0 ? (
|
||||
standings.map((standing, index) => {
|
||||
const isQualified = advancingTeams.qualifiedTeams.has(standing.teamId);
|
||||
const isWildcard = advancingTeams.wildcardTeams.has(standing.teamId);
|
||||
const isAdvancing = isQualified || isWildcard;
|
||||
|
||||
return (
|
||||
standings.map((standing, index) => (
|
||||
<MantineGroup
|
||||
key={standing.teamId}
|
||||
gap="sm"
|
||||
@@ -389,30 +331,16 @@ const GroupStageView: React.FC<GroupStageViewProps> = ({
|
||||
py="xs"
|
||||
style={{
|
||||
borderTop: index > 0 ? '1px solid var(--mantine-color-default-border)' : 'none',
|
||||
backgroundColor: isAdvancing ? 'var(--mantine-primary-color-light)' : undefined,
|
||||
borderLeft: isAdvancing ? '3px solid var(--mantine-primary-color-filled)' : '3px solid transparent',
|
||||
}}
|
||||
>
|
||||
<Text size="sm" fw={700} c="dimmed" w={24} ta="center">
|
||||
{index + 1}
|
||||
</Text>
|
||||
<TeamAvatar team={standing.team} size={28} radius="sm" isRegional={isRegional} />
|
||||
<Box style={{ flex: 1, minWidth: 0 }}>
|
||||
<Text size="sm" fw={500} lineClamp={1}>
|
||||
<Text size="sm" fw={500} style={{ flex: 1 }} lineClamp={1}>
|
||||
{standing.teamName}
|
||||
</Text>
|
||||
</Box>
|
||||
<MantineGroup gap="xs" wrap="nowrap">
|
||||
{isWildcard && (
|
||||
<Badge size="xs" color="yellow" variant="light">
|
||||
WC
|
||||
</Badge>
|
||||
)}
|
||||
{isQualified && (
|
||||
<Badge size="xs" variant="light">
|
||||
Q
|
||||
</Badge>
|
||||
)}
|
||||
<Text size="xs" c="dimmed" fw={500} miw={35} ta="center">
|
||||
{standing.wins}-{standing.losses}
|
||||
</Text>
|
||||
@@ -430,8 +358,7 @@ const GroupStageView: React.FC<GroupStageViewProps> = ({
|
||||
</Text>
|
||||
</MantineGroup>
|
||||
</MantineGroup>
|
||||
);
|
||||
})
|
||||
))
|
||||
) : (
|
||||
<Text size="sm" c="dimmed" ta="center" py="md">
|
||||
No teams assigned
|
||||
|
||||
@@ -80,16 +80,12 @@ const SetupGroupStage: React.FC<SetupGroupStageProps> = ({
|
||||
return null;
|
||||
}
|
||||
|
||||
const nextPowerOf2 = Math.pow(2, Math.ceil(Math.log2(knockoutTeamCount)));
|
||||
const bracketSize = nextPowerOf2;
|
||||
const wildcardsNeeded = bracketSize - knockoutTeamCount;
|
||||
|
||||
let bracketTemplate: any;
|
||||
if (Object.keys(brackets).includes(bracketSize.toString())) {
|
||||
bracketTemplate = brackets[bracketSize as keyof typeof brackets];
|
||||
if (Object.keys(brackets).includes(knockoutTeamCount.toString())) {
|
||||
bracketTemplate = brackets[knockoutTeamCount as keyof typeof brackets];
|
||||
} else {
|
||||
try {
|
||||
bracketTemplate = generateSingleEliminationBracket(bracketSize);
|
||||
bracketTemplate = generateSingleEliminationBracket(knockoutTeamCount);
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
@@ -117,10 +113,6 @@ const SetupGroupStage: React.FC<SetupGroupStageProps> = ({
|
||||
seedLabels[seedIndex++] = `${groupName2} ${rankSuffix2}`;
|
||||
}
|
||||
|
||||
for (let i = 0; i < wildcardsNeeded; i++) {
|
||||
seedLabels[seedIndex++] = `Wildcard ${i + 1}`;
|
||||
}
|
||||
|
||||
const ordersMap: Record<number, number> = {};
|
||||
bracketTemplate.winners.forEach((round: any[]) => {
|
||||
round.forEach((match: any) => {
|
||||
@@ -273,11 +265,10 @@ const SetupGroupStage: React.FC<SetupGroupStageProps> = ({
|
||||
<Box>
|
||||
<Divider mb="lg" />
|
||||
<Title order={3} ta="center" mb="md">
|
||||
Knockout Bracket Preview ({selectedConfig?.knockout_size} Teams)
|
||||
Knockout Bracket Preview ({knockoutTeamCount} Teams)
|
||||
</Title>
|
||||
<Text size="sm" c="dimmed" ta="center" mb="lg">
|
||||
Top {selectedConfig?.advance_per_group} team{selectedConfig?.advance_per_group !== 1 ? 's' : ''} from each group will advance
|
||||
{selectedConfig?.wildcards_needed ? ` + ${selectedConfig.wildcards_needed} wildcard${selectedConfig.wildcards_needed > 1 ? 's' : ''}` : ''}
|
||||
</Text>
|
||||
<Box
|
||||
style={{
|
||||
|
||||
@@ -6,6 +6,7 @@ import { logger } from ".";
|
||||
import { z } from "zod";
|
||||
import { toServerResult } from "@/lib/tanstack-query/utils/to-server-result";
|
||||
import { serverFnLoggingMiddleware } from "@/utils/activities";
|
||||
import { fa } from "zod/v4/locales";
|
||||
import brackets from "@/features/bracket/utils";
|
||||
import { MatchInput } from "@/features/matches/types";
|
||||
import { generateSingleEliminationBracket } from "./utils/bracket-generator";
|
||||
@@ -539,18 +540,10 @@ export const generateKnockoutBracket = createServerFn()
|
||||
}
|
||||
|
||||
const qualifiedTeams: { teamId: string; groupOrder: number; rank: number }[] = [];
|
||||
const allStandings: { standing: GroupStanding; groupOrder: number }[] = [];
|
||||
|
||||
for (const group of groups) {
|
||||
const standings = await calculateGroupStandings(group.id);
|
||||
|
||||
for (let i = 0; i < standings.length; i++) {
|
||||
allStandings.push({
|
||||
standing: standings[i],
|
||||
groupOrder: group.order,
|
||||
});
|
||||
}
|
||||
|
||||
const topTeams = standings.slice(0, tournament.group_config.advance_per_group);
|
||||
for (const standing of topTeams) {
|
||||
qualifiedTeams.push({
|
||||
@@ -589,42 +582,7 @@ export const generateKnockoutBracket = createServerFn()
|
||||
if (team2) orderedTeamIds.push(team2);
|
||||
}
|
||||
|
||||
let teamCount = orderedTeamIds.length;
|
||||
|
||||
const nextPowerOf2 = Math.pow(2, Math.ceil(Math.log2(teamCount)));
|
||||
const wildcardsNeeded = nextPowerOf2 - teamCount;
|
||||
|
||||
if (wildcardsNeeded > 0) {
|
||||
const qualifiedTeamIds = new Set(qualifiedTeams.map(t => t.teamId));
|
||||
const wildcardCandidates = allStandings
|
||||
.filter(s => !qualifiedTeamIds.has(s.standing.team.id))
|
||||
.map(s => s.standing);
|
||||
|
||||
wildcardCandidates.sort((a, b) => {
|
||||
if (b.wins !== a.wins) return b.wins - a.wins;
|
||||
if (b.cup_differential !== a.cup_differential) return b.cup_differential - a.cup_differential;
|
||||
if (b.cups_for !== a.cups_for) return b.cups_for - a.cups_for;
|
||||
return a.team.id.localeCompare(b.team.id);
|
||||
});
|
||||
|
||||
const wildcardTeams = wildcardCandidates.slice(0, wildcardsNeeded);
|
||||
const wildcardTeamIds = wildcardTeams.map(t => t.team.id);
|
||||
|
||||
orderedTeamIds.push(...wildcardTeamIds);
|
||||
teamCount = orderedTeamIds.length;
|
||||
|
||||
logger.info('Added wildcard teams to knockout bracket', {
|
||||
tournamentId: data.tournamentId,
|
||||
wildcardsNeeded,
|
||||
wildcardTeams: wildcardTeams.map(t => ({
|
||||
id: t.team.id,
|
||||
name: t.team.name,
|
||||
wins: t.wins,
|
||||
cupDiff: t.cup_differential,
|
||||
cupsFor: t.cups_for
|
||||
}))
|
||||
});
|
||||
}
|
||||
const teamCount = orderedTeamIds.length;
|
||||
|
||||
let bracketTemplate: any;
|
||||
if (Object.keys(brackets).includes(teamCount.toString())) {
|
||||
@@ -816,25 +774,14 @@ export const generateGroupStage = createServerFn()
|
||||
}
|
||||
|
||||
const knockoutTeamCount = data.groupConfig.num_groups * data.groupConfig.advance_per_group;
|
||||
|
||||
const nextPowerOf2 = Math.pow(2, Math.ceil(Math.log2(knockoutTeamCount)));
|
||||
const bracketSize = nextPowerOf2;
|
||||
|
||||
let bracketTemplate: any;
|
||||
|
||||
if (Object.keys(brackets).includes(bracketSize.toString())) {
|
||||
bracketTemplate = brackets[bracketSize as keyof typeof brackets];
|
||||
if (Object.keys(brackets).includes(knockoutTeamCount.toString())) {
|
||||
bracketTemplate = brackets[knockoutTeamCount as keyof typeof brackets];
|
||||
} else {
|
||||
bracketTemplate = generateSingleEliminationBracket(bracketSize);
|
||||
bracketTemplate = generateSingleEliminationBracket(knockoutTeamCount);
|
||||
}
|
||||
|
||||
logger.info('Creating knockout bracket template', {
|
||||
tournamentId: data.tournamentId,
|
||||
knockoutTeamCount,
|
||||
bracketSize,
|
||||
wildcardsNeeded: bracketSize - knockoutTeamCount
|
||||
});
|
||||
|
||||
const knockoutMatches: any[] = [];
|
||||
|
||||
bracketTemplate.winners.forEach((round: any[]) => {
|
||||
|
||||
@@ -26,25 +26,20 @@ export function calculateGroupConfigurations(teamCount: number): GroupConfigOpti
|
||||
const configs: GroupConfigOption[] = [];
|
||||
|
||||
for (let teamsPerGroup = 3; teamsPerGroup <= Math.min(6, teamCount); teamsPerGroup++) {
|
||||
const numGroupsFloor = Math.floor(teamCount / teamsPerGroup);
|
||||
const numGroupsCeil = Math.ceil(teamCount / teamsPerGroup);
|
||||
const numGroups = Math.floor(teamCount / teamsPerGroup);
|
||||
const remainder = teamCount % teamsPerGroup;
|
||||
|
||||
const groupOptions = new Set([numGroupsFloor, numGroupsCeil]);
|
||||
|
||||
for (const numGroups of groupOptions) {
|
||||
if (numGroups < 2) continue;
|
||||
|
||||
const baseTeamsPerGroup = Math.floor(teamCount / numGroups);
|
||||
const groupsWithExtra = teamCount % numGroups;
|
||||
if (remainder > numGroups) continue;
|
||||
|
||||
const minGroupSize = baseTeamsPerGroup;
|
||||
const maxGroupSize = baseTeamsPerGroup + (groupsWithExtra > 0 ? 1 : 0);
|
||||
|
||||
if (minGroupSize < 3 || maxGroupSize > 6) continue;
|
||||
const groupsWithExtra = remainder;
|
||||
|
||||
const groupsAtBaseSize = numGroups - groupsWithExtra;
|
||||
const minGroupSize = groupsAtBaseSize > 0 ? teamsPerGroup : teamsPerGroup + 1;
|
||||
const matchesGuaranteed = minGroupSize - 1;
|
||||
|
||||
for (let advancePerGroup = 1; advancePerGroup <= Math.min(3, minGroupSize - 1); advancePerGroup++) {
|
||||
for (let advancePerGroup = 1; advancePerGroup <= Math.min(3, teamsPerGroup - 1); advancePerGroup++) {
|
||||
const teamsAdvancing = numGroups * advancePerGroup;
|
||||
|
||||
if (teamsAdvancing < 4 || teamsAdvancing > 32) continue;
|
||||
@@ -56,13 +51,13 @@ export function calculateGroupConfigurations(teamCount: number): GroupConfigOpti
|
||||
|
||||
let totalGroupMatches = 0;
|
||||
for (let i = 0; i < numGroups; i++) {
|
||||
const groupSize = baseTeamsPerGroup + (i < groupsWithExtra ? 1 : 0);
|
||||
const groupSize = teamsPerGroup + (i < groupsWithExtra ? 1 : 0);
|
||||
totalGroupMatches += (groupSize * (groupSize - 1)) / 2;
|
||||
}
|
||||
|
||||
const description = generateDescription({
|
||||
num_groups: numGroups,
|
||||
teams_per_group: baseTeamsPerGroup,
|
||||
teams_per_group: teamsPerGroup,
|
||||
groups_with_extra: groupsWithExtra,
|
||||
advance_per_group: advancePerGroup,
|
||||
matches_guaranteed: matchesGuaranteed,
|
||||
@@ -72,7 +67,7 @@ export function calculateGroupConfigurations(teamCount: number): GroupConfigOpti
|
||||
|
||||
configs.push({
|
||||
num_groups: numGroups,
|
||||
teams_per_group: baseTeamsPerGroup,
|
||||
teams_per_group: teamsPerGroup,
|
||||
advance_per_group: advancePerGroup,
|
||||
matches_guaranteed: matchesGuaranteed,
|
||||
seeding_method: "random",
|
||||
@@ -84,7 +79,6 @@ export function calculateGroupConfigurations(teamCount: number): GroupConfigOpti
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const uniqueConfigs = new Map<string, GroupConfigOption>();
|
||||
|
||||
|
||||
@@ -4,34 +4,15 @@ import Passwordless from "supertokens-web-js/recipe/passwordless";
|
||||
import { appInfo } from "./config";
|
||||
import { logger } from "./";
|
||||
|
||||
let refreshPromise: Promise<boolean> | null = null;
|
||||
|
||||
export const resetRefreshFlag = () => {
|
||||
refreshPromise = null;
|
||||
logger.warn("resetRefreshFlag is deprecated. Use refreshManager.reset() instead.");
|
||||
};
|
||||
|
||||
|
||||
export const getOrCreateRefreshPromise = (refreshFn: () => Promise<boolean>): Promise<boolean> => {
|
||||
if (refreshPromise) {
|
||||
logger.info("Reusing existing refresh promise");
|
||||
return refreshPromise;
|
||||
}
|
||||
|
||||
logger.info("Creating new refresh promise");
|
||||
refreshPromise = refreshFn()
|
||||
.then((result) => {
|
||||
logger.info("Refresh completed successfully:", result);
|
||||
setTimeout(() => {
|
||||
refreshPromise = null;
|
||||
}, 500);
|
||||
return result;
|
||||
})
|
||||
.catch((error) => {
|
||||
logger.error("Refresh failed:", error);
|
||||
refreshPromise = null;
|
||||
throw error;
|
||||
});
|
||||
|
||||
return refreshPromise;
|
||||
logger.warn("getOrCreateRefreshPromise is deprecated. Use refreshManager.refresh() instead.");
|
||||
return refreshFn();
|
||||
};
|
||||
|
||||
export const frontendConfig = () => {
|
||||
|
||||
77
src/lib/supertokens/refresh-manager.ts
Normal file
77
src/lib/supertokens/refresh-manager.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { attemptRefreshingSession } from 'supertokens-web-js/recipe/session';
|
||||
import { logger } from './index';
|
||||
|
||||
class SessionRefreshManager {
|
||||
private refreshPromise: Promise<boolean> | null = null;
|
||||
private redirectPromise: Promise<void> | null = null;
|
||||
private lastRefreshTime: number = 0;
|
||||
private readonly MIN_REFRESH_INTERVAL = 1000;
|
||||
|
||||
async refresh(): Promise<boolean> {
|
||||
if (this.refreshPromise) {
|
||||
logger.info('RefreshManager: Reusing existing refresh promise');
|
||||
return this.refreshPromise;
|
||||
}
|
||||
|
||||
const timeSinceLastRefresh = Date.now() - this.lastRefreshTime;
|
||||
if (timeSinceLastRefresh < this.MIN_REFRESH_INTERVAL) {
|
||||
logger.info(`RefreshManager: Skipping refresh (last refresh ${timeSinceLastRefresh}ms ago)`);
|
||||
return true;
|
||||
}
|
||||
|
||||
logger.info('RefreshManager: Starting new session refresh');
|
||||
this.refreshPromise = attemptRefreshingSession()
|
||||
.then((result) => {
|
||||
logger.info('RefreshManager: Refresh completed successfully:', result);
|
||||
this.lastRefreshTime = Date.now();
|
||||
return result;
|
||||
})
|
||||
.catch((error) => {
|
||||
logger.error('RefreshManager: Refresh failed:', error);
|
||||
throw error;
|
||||
})
|
||||
.finally(() => {
|
||||
setTimeout(() => {
|
||||
this.refreshPromise = null;
|
||||
}, 500);
|
||||
});
|
||||
|
||||
return this.refreshPromise;
|
||||
}
|
||||
|
||||
async redirectToRefresh(currentPath: string): Promise<void> {
|
||||
if (this.redirectPromise) {
|
||||
logger.info('RefreshManager: Redirect already in progress, waiting...');
|
||||
return this.redirectPromise;
|
||||
}
|
||||
|
||||
logger.info('RefreshManager: Initiating refresh redirect to:', currentPath);
|
||||
this.redirectPromise = new Promise<void>((resolve) => {
|
||||
setTimeout(() => {
|
||||
window.location.href = `/refresh-session?redirect=${encodeURIComponent(currentPath)}`;
|
||||
resolve();
|
||||
}, 100);
|
||||
});
|
||||
|
||||
this.redirectPromise.finally(() => {
|
||||
setTimeout(() => {
|
||||
this.redirectPromise = null;
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
return this.redirectPromise;
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
logger.info('RefreshManager: Resetting state');
|
||||
this.refreshPromise = null;
|
||||
this.redirectPromise = null;
|
||||
this.lastRefreshTime = 0;
|
||||
}
|
||||
|
||||
getTimeSinceLastRefresh(): number {
|
||||
return Date.now() - this.lastRefreshTime;
|
||||
}
|
||||
}
|
||||
|
||||
export const refreshManager = new SessionRefreshManager();
|
||||
@@ -25,9 +25,29 @@ export const backendConfig = (): TypeInput => {
|
||||
cookieSameSite: "lax",
|
||||
cookieSecure: process.env.NODE_ENV === "production",
|
||||
cookieDomain: process.env.COOKIE_DOMAIN || undefined,
|
||||
olderCookieDomain: undefined,
|
||||
olderCookieDomain: process.env.COOKIE_DOMAIN || undefined,
|
||||
antiCsrf: process.env.NODE_ENV === "production" ? "VIA_TOKEN" : "NONE",
|
||||
|
||||
sessionExpiredStatusCode: 440,
|
||||
invalidClaimStatusCode: 403,
|
||||
|
||||
override: {
|
||||
functions: (originalImplementation) => ({
|
||||
...originalImplementation,
|
||||
refreshSession: async (input) => {
|
||||
logger.info('Backend: Refresh session attempt');
|
||||
try {
|
||||
const result = await originalImplementation.refreshSession(input);
|
||||
logger.info('Backend: Refresh session successful');
|
||||
return result;
|
||||
} catch (error) {
|
||||
logger.error('Backend: Refresh session failed:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
}),
|
||||
},
|
||||
|
||||
// Debug only
|
||||
exposeAccessTokenToFrontendInCookieBasedAuth: process.env.NODE_ENV !== "production",
|
||||
}),
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import { useMutation, UseMutationOptions } from "@tanstack/react-query";
|
||||
import { ServerResult } from "../types";
|
||||
import toast from '@/lib/sonner'
|
||||
import { logger } from '@/lib/supertokens'
|
||||
|
||||
|
||||
let sessionRefreshRedirect: Promise<void> | null = null;
|
||||
import { handleQueryError } from '../utils/global-error-handler';
|
||||
|
||||
export function useServerMutation<TData, TVariables = unknown>(
|
||||
options: Omit<UseMutationOptions<TData, Error, TVariables>, 'mutationFn'> & {
|
||||
@@ -39,41 +36,7 @@ export function useServerMutation<TData, TVariables = unknown>(
|
||||
|
||||
return result.data;
|
||||
} catch (error: any) {
|
||||
if (error?.response?.status === 401) {
|
||||
try {
|
||||
const errorData = typeof error.response.data === 'string'
|
||||
? JSON.parse(error.response.data)
|
||||
: error.response.data;
|
||||
|
||||
if (errorData?.error === "SESSION_REFRESH_REQUIRED") {
|
||||
logger.warn("Mutation detected SESSION_REFRESH_REQUIRED");
|
||||
|
||||
if (!sessionRefreshRedirect) {
|
||||
const currentUrl = window.location.pathname + window.location.search;
|
||||
logger.info("Mutation initiating refresh redirect to:", currentUrl);
|
||||
|
||||
sessionRefreshRedirect = new Promise<void>((resolve) => {
|
||||
setTimeout(() => {
|
||||
window.location.href = `/refresh-session?redirect=${encodeURIComponent(currentUrl)}`;
|
||||
resolve();
|
||||
}, 100);
|
||||
});
|
||||
|
||||
sessionRefreshRedirect.finally(() => {
|
||||
setTimeout(() => {
|
||||
sessionRefreshRedirect = null;
|
||||
}, 1000);
|
||||
});
|
||||
} else {
|
||||
logger.info("Mutation: refresh redirect already in progress, waiting...");
|
||||
await sessionRefreshRedirect;
|
||||
}
|
||||
|
||||
throw new Error("SESSION_REFRESH_REQUIRED");
|
||||
}
|
||||
} catch (parseError) {}
|
||||
}
|
||||
|
||||
await handleQueryError(error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { QueryKey, useQuery, UseQueryOptions } from "@tanstack/react-query";
|
||||
import { ServerResult } from "../types";
|
||||
import toast from '@/lib/sonner'
|
||||
import { handleQueryError } from '../utils/global-error-handler';
|
||||
|
||||
export function useServerQuery<TData>(
|
||||
options: {
|
||||
@@ -17,6 +18,7 @@ export function useServerQuery<TData>(
|
||||
...queryOptions,
|
||||
queryKey,
|
||||
queryFn: async () => {
|
||||
try {
|
||||
const result = await queryFn();
|
||||
|
||||
if (!result.success) {
|
||||
@@ -27,6 +29,10 @@ export function useServerQuery<TData>(
|
||||
}
|
||||
|
||||
return result.data;
|
||||
} catch (error: any) {
|
||||
await handleQueryError(error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { QueryKey, UseQueryOptions, useSuspenseQuery } from "@tanstack/react-query";
|
||||
import { ServerResult } from "../types";
|
||||
import toast from '@/lib/sonner'
|
||||
import { handleQueryError } from '../utils/global-error-handler';
|
||||
|
||||
export function useServerSuspenseQuery<TData>(
|
||||
options: {
|
||||
@@ -16,6 +17,7 @@ export function useServerSuspenseQuery<TData>(
|
||||
...queryOptions,
|
||||
queryKey,
|
||||
queryFn: async () => {
|
||||
try {
|
||||
const result = await queryFn();
|
||||
|
||||
if (!result.success) {
|
||||
@@ -26,6 +28,10 @@ export function useServerSuspenseQuery<TData>(
|
||||
}
|
||||
|
||||
return result.data;
|
||||
} catch (error: any) {
|
||||
await handleQueryError(error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ export async function ensureServerQueryData<TData>(
|
||||
return queryClient.ensureQueryData({
|
||||
queryKey: query.queryKey,
|
||||
queryFn: async () => {
|
||||
try {
|
||||
const result = await query.queryFn();
|
||||
|
||||
if (!result.success) {
|
||||
@@ -18,6 +19,12 @@ export async function ensureServerQueryData<TData>(
|
||||
}
|
||||
|
||||
return result.data;
|
||||
} catch (error: any) {
|
||||
if (error?.options?.to && error?.options?.statusCode) {
|
||||
throw error;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
65
src/lib/tanstack-query/utils/global-error-handler.ts
Normal file
65
src/lib/tanstack-query/utils/global-error-handler.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { refreshManager } from '@/lib/supertokens/refresh-manager';
|
||||
import { logger } from '@/lib/supertokens';
|
||||
|
||||
export async function handleQueryError(error: any): Promise<void> {
|
||||
if (typeof window === 'undefined') {
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (!error || typeof error !== 'object') {
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (error.options?.to && error.options?.statusCode) {
|
||||
logger.info('handleQueryError: Re-throwing TanStack Router redirect', error.options);
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (error instanceof Response) {
|
||||
const status = error.status;
|
||||
|
||||
if (status === 440) {
|
||||
try {
|
||||
const errorData = await error.json();
|
||||
|
||||
if (errorData?.error === 'SESSION_REFRESH_REQUIRED' && errorData?.shouldRetry === true) {
|
||||
logger.warn('Query detected SESSION_REFRESH_REQUIRED (Response), initiating redirect');
|
||||
|
||||
const currentUrl = window.location.pathname + window.location.search;
|
||||
await refreshManager.redirectToRefresh(currentUrl);
|
||||
|
||||
throw new Error('Redirecting to refresh session');
|
||||
}
|
||||
} catch (parseError) {
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const status = error?.response?.status;
|
||||
|
||||
if (status === 440) {
|
||||
try {
|
||||
let errorData = error?.response?.data;
|
||||
|
||||
if (typeof errorData === 'string') {
|
||||
try {
|
||||
errorData = JSON.parse(errorData);
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
|
||||
if (errorData?.error === 'SESSION_REFRESH_REQUIRED' && errorData?.shouldRetry === true) {
|
||||
logger.warn('Query detected SESSION_REFRESH_REQUIRED (legacy format), initiating redirect');
|
||||
|
||||
const currentUrl = window.location.pathname + window.location.search;
|
||||
await refreshManager.redirectToRefresh(currentUrl);
|
||||
|
||||
throw new Error('Redirecting to refresh session');
|
||||
}
|
||||
} catch (parseError) {
|
||||
}
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
@@ -26,6 +26,14 @@ export const toServerResult = async <T>(
|
||||
const data = await serverFn();
|
||||
return { success: true, data };
|
||||
} catch (error) {
|
||||
if (error && typeof error === 'object' && 'options' in error) {
|
||||
const redirectError = error as any;
|
||||
if (redirectError.options?.to && redirectError.options?.statusCode) {
|
||||
logger.info('toServerResult: Re-throwing TanStack Router redirect', redirectError.options);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
logger.error('Server Fn Error', error);
|
||||
|
||||
|
||||
@@ -57,6 +57,12 @@ export const getSessionContext = createServerOnlyFn(async (request: Request, opt
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
|
||||
if (url.pathname === '/refresh-session') {
|
||||
logger.warn("Already on refresh-session page but session needs refresh - treating as unauthenticated");
|
||||
throw new Error("Unauthenticated");
|
||||
}
|
||||
|
||||
const from = encodeURIComponent(url.pathname + url.search);
|
||||
throw redirect({
|
||||
to: "/refresh-session",
|
||||
@@ -110,11 +116,15 @@ export const superTokensFunctionMiddleware = createMiddleware({
|
||||
throw new Response(
|
||||
JSON.stringify({
|
||||
error: "SESSION_REFRESH_REQUIRED",
|
||||
message: "Session needs to be refreshed"
|
||||
message: "Session needs to be refreshed",
|
||||
shouldRetry: true
|
||||
}),
|
||||
{
|
||||
status: 401,
|
||||
headers: { "Content-Type": "application/json" }
|
||||
status: 440,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"X-Session-Expired": "true"
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -141,11 +151,15 @@ export const superTokensAdminFunctionMiddleware = createMiddleware({
|
||||
throw new Response(
|
||||
JSON.stringify({
|
||||
error: "SESSION_REFRESH_REQUIRED",
|
||||
message: "Session needs to be refreshed"
|
||||
message: "Session needs to be refreshed",
|
||||
shouldRetry: true
|
||||
}),
|
||||
{
|
||||
status: 401,
|
||||
headers: { "Content-Type": "application/json" }
|
||||
status: 440,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"X-Session-Expired": "true"
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user