Compare commits

...
10 Commits
46 changed files with 9728 additions and 478 deletions

No files matched your search

+2
View File
@@ -26,6 +26,8 @@ website/LICENSE
*.md
!README.md
!AGENTS.md
!docs/specs/internal-match-game-analysis.md
!docs/plans/internal-match-game-analysis-p0-p1.md
!agents/**/*.md
!skills/**/*.md
/tmp/
+6 -1
View File
@@ -14,20 +14,23 @@ FROM pnpm-base AS deps
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY apps/api/package.json apps/api/package.json
COPY apps/web/package.json apps/web/package.json
COPY packages/contracts/package.json packages/contracts/package.json
RUN pnpm install --frozen-lockfile --filter api... --filter lolympus-tournament-support
FROM deps AS build
COPY packages/contracts packages/contracts
COPY apps/api apps/api
RUN pnpm --filter api build
RUN pnpm --filter api... build
FROM pnpm-base AS prod-deps
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY apps/api/package.json apps/api/package.json
COPY apps/web/package.json apps/web/package.json
COPY packages/contracts/package.json packages/contracts/package.json
RUN pnpm install --prod --frozen-lockfile --filter api... --filter lolympus-tournament-support
@@ -41,6 +44,8 @@ COPY --from=prod-deps --chown=nonroot:nonroot /app/package.json ./package.json
COPY --from=prod-deps --chown=nonroot:nonroot /app/node_modules ./node_modules
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/package.json ./apps/api/package.json
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/node_modules ./apps/api/node_modules
COPY --from=build --chown=nonroot:nonroot /app/packages/contracts/package.json ./packages/contracts/package.json
COPY --from=build --chown=nonroot:nonroot /app/packages/contracts/dist ./packages/contracts/dist
COPY --chown=nonroot:nonroot apps/api/newrelic.cjs ./apps/api/newrelic.cjs
COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist
COPY --chown=nonroot:nonroot apps/project.env ./project.env
@@ -83,7 +83,7 @@ function record(matchId: mongoose.Types.ObjectId): InternalRecord {
}
describe('CommunityStatsService', () => {
it('ignores stale detail cache entries missing timeline build fields', async () => {
it('ignores detail caches missing unified events or containing invalid checkpoints', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match: InternalMatchCardView = {
@@ -97,6 +97,20 @@ describe('CommunityStatsService', () => {
seriesResults: [],
};
const participant = record(matchId);
Object.assign(participant, {
participantId: 1,
checkpoints: {
at10: {
timestamp: 590,
gold: 5_200,
cs: 90,
xp: 4_200,
kills: 1,
deaths: 1,
assists: 1,
},
},
});
const gameDetail: InternalGameDetail = {
gameNumber: 1,
riotMatchId: 'KR_1',
@@ -125,38 +139,81 @@ describe('CommunityStatsService', () => {
},
],
};
const staleCache = {
match,
games: [
Object.assign(gameDetail, {
timelineEvents: [
{
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
teams: [
timestamp: 300,
side: 'blue',
type: 'championKill',
killerParticipantId: 1,
victimParticipantId: 2,
assistingParticipantIds: [],
},
],
});
const otherwiseCompleteCachedGame = {
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
timeline: [],
objectiveEvents: [],
teams: [
{
teamIndex: 1,
side: 'blue' as const,
win: true,
objectives: objectives(),
bans: [],
participants: [
{
teamIndex: 1,
side: 'blue',
win: true,
objectives: { tower: 1, dragon: 0, baron: 0 },
participants: [
{
summonerName: 'Player',
perks: {
primaryStyle: 8000,
subStyle: 8400,
keystone: 8010,
},
},
],
summonerName: 'Cached Player',
tagLine: 'KR1',
itemBuild: [],
skillBuild: [],
},
],
},
],
};
const missingTimelineEventsCache = {
match,
games: [otherwiseCompleteCachedGame],
} as unknown as InternalMatchDetailResponse;
const invalidCheckpointCache = {
match,
games: [
{
...otherwiseCompleteCachedGame,
timelineEvents: [],
teams: otherwiseCompleteCachedGame.teams.map((team) => ({
...team,
participants: team.participants.map((cachedParticipant) => ({
...cachedParticipant,
participantId: 1,
checkpoints: {
at10: {
timestamp: '590',
gold: 5_200,
cs: 90,
xp: 4_200,
kills: 1,
deaths: 1,
assists: 1,
},
},
})),
})),
},
],
} as unknown as InternalMatchDetailResponse;
const setDetail = jest.fn().mockResolvedValue(undefined);
const cacheService = {
get: jest.fn().mockResolvedValue(staleCache),
setDetail: jest.fn().mockResolvedValue(undefined),
get: jest
.fn()
.mockResolvedValueOnce(missingTimelineEventsCache)
.mockResolvedValueOnce(invalidCheckpointCache),
setDetail,
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const matchStatsService = {
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
@@ -180,22 +237,245 @@ describe('CommunityStatsService', () => {
detailsByMatchId: new Map([[matchId.toString(), [gameDetail]]]),
});
const response = await service.getMatchDetail({ communityId, matchId });
const missingEventsResponse = await service.getMatchDetail({
communityId,
matchId,
});
const invalidCheckpointResponse = await service.getMatchDetail({
communityId,
matchId,
});
expect(response.games[0].timeline).toHaveLength(1);
expect(response.games[0].teams[0].participants[0].itemBuild).toHaveLength(
1,
);
expect(response.games[0].teams[0].participants[0].perks).toMatchObject({
selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451],
expect(missingEventsResponse.games[0].timeline).toHaveLength(1);
expect(invalidCheckpointResponse.games[0].timeline).toHaveLength(1);
expect(invalidCheckpointResponse.games[0]).toMatchObject({
timelineEvents: [
{
timestamp: 300,
side: 'blue',
type: 'championKill',
},
],
});
expect(
invalidCheckpointResponse.games[0].teams[0].participants[0],
).toMatchObject({
participantId: 1,
checkpoints: {
at10: {
timestamp: 590,
gold: 5_200,
cs: 90,
xp: 4_200,
kills: 1,
deaths: 1,
assists: 1,
},
},
itemBuild: [{ timestamp: 10, itemId: 1054, type: 'purchased' }],
perks: {
selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451],
},
});
expect(matchStatsService.buildAndUpsert).not.toHaveBeenCalled();
expect(cacheService.setDetail).toHaveBeenCalledWith(
expect.stringContaining(':r3:'),
response,
expect(setDetail).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenNthCalledWith(
2,
expect.stringContaining(':r4:'),
invalidCheckpointResponse,
);
});
it('backs off failed timeline hydration and retries after the short cache expires', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match: InternalMatchCardView = {
matchId: matchId.toString(),
title: '내전',
scheduledAt: '2026-06-18T12:00:00.000Z',
status: 'finished',
gameCount: 1,
games: [],
teams: [],
seriesResults: [],
};
const participant = record(matchId);
const gameDetail: InternalGameDetail = {
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
winnerSide: 'blue',
timelineLoaded: false,
timeline: [],
objectiveEvents: [],
timelineEvents: [],
teams: [
{
teamIndex: 1,
side: 'blue',
win: true,
objectives: objectives(),
bans: [],
participants: [participant],
},
],
};
const dataset = (timelineLoaded: boolean) => ({
season: {
id: 'all',
label: '전체',
startTime: null,
endTime: null,
},
matches: [match],
records: [participant],
detailsByMatchId: new Map([
[matchId.toString(), [{ ...gameDetail, timelineLoaded }]],
]),
});
let cachedResponse: InternalMatchDetailResponse | null = null;
const set = jest
.fn()
.mockImplementation(
(_key: string, value: InternalMatchDetailResponse) => {
cachedResponse = value;
return Promise.resolve();
},
);
const setDetail = jest
.fn()
.mockImplementation(
(_key: string, value: InternalMatchDetailResponse) => {
cachedResponse = value;
return Promise.resolve();
},
);
const cacheService = {
get: jest.fn().mockImplementation(() => Promise.resolve(cachedResponse)),
set,
setDetail,
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const service = new CommunityStatsService(
{} as ConnectionService,
cacheService,
{} as MatchStatsRepository,
{ buildAndUpsert } as unknown as MatchStatsService,
);
(service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset =
jest
.fn()
.mockResolvedValueOnce(dataset(false))
.mockResolvedValueOnce(dataset(false))
.mockResolvedValueOnce(dataset(false))
.mockResolvedValueOnce(dataset(true));
const fallback = await service.getMatchDetail({ communityId, matchId });
const backedOff = await service.getMatchDetail({ communityId, matchId });
expect(backedOff).toBe(fallback);
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
expect(set).toHaveBeenCalledWith(
expect.stringContaining(':r4:'),
fallback,
60,
);
expect(setDetail).not.toHaveBeenCalled();
cachedResponse = null;
const recovered = await service.getMatchDetail({ communityId, matchId });
expect(buildAndUpsert).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenCalledTimes(1);
expect(setDetail).toHaveBeenCalledWith(
expect.stringContaining(':r4:'),
recovered,
);
});
it('coalesces concurrent internal match detail cache misses', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match: InternalMatchCardView = {
matchId: matchId.toString(),
title: '내전',
scheduledAt: '2026-06-18T12:00:00.000Z',
status: 'finished',
gameCount: 1,
games: [],
teams: [],
seriesResults: [],
};
const participant = record(matchId);
const dataset = {
season: {
id: 'all',
label: '전체',
startTime: null,
endTime: null,
},
matches: [match],
records: [participant],
detailsByMatchId: new Map([
[
matchId.toString(),
[
{
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
winnerSide: 'blue' as const,
timelineLoaded: true,
timeline: [],
objectiveEvents: [],
timelineEvents: [],
teams: [
{
teamIndex: 1,
side: 'blue' as const,
win: true,
objectives: objectives(),
bans: [],
participants: [participant],
},
],
},
],
],
]),
};
let resolveDataset: ((value: typeof dataset) => void) | undefined;
const datasetPromise = new Promise<typeof dataset>((resolve) => {
resolveDataset = resolve;
});
const setDetail = jest.fn().mockResolvedValue(undefined);
const cacheService = {
get: jest.fn().mockResolvedValue(null),
setDetail,
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const service = new CommunityStatsService(
{} as ConnectionService,
cacheService,
{} as MatchStatsRepository,
{} as MatchStatsService,
);
const buildBaseDataset = jest.fn().mockReturnValue(datasetPromise);
(service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset =
buildBaseDataset;
const first = service.getMatchDetail({ communityId, matchId });
const second = service.getMatchDetail({ communityId, matchId });
await Promise.resolve();
resolveDataset?.(dataset);
const [firstResponse, secondResponse] = await Promise.all([first, second]);
expect(firstResponse).toBe(secondResponse);
expect(buildBaseDataset).toHaveBeenCalledTimes(1);
expect(setDetail).toHaveBeenCalledTimes(1);
});
it('includes internal match route fields in user internal history matches', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
@@ -40,7 +40,8 @@ const DEFAULT_LIST_LIMIT = 20;
const MAX_LIST_LIMIT = 50;
const MAX_MATCH_SCAN = 300;
const MIN_HIGHLIGHT_GAMES = 5;
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 3;
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 4;
const INCOMPLETE_MATCH_DETAIL_TTL_SECONDS = 60;
interface CommunityStatsContext {
community: CommunityDocument;
@@ -59,6 +60,10 @@ interface BaseDataset {
@Injectable()
export class CommunityStatsService {
private readonly logger = new Logger(CommunityStatsService.name);
private readonly matchDetailInFlight = new Map<
string,
Promise<InternalMatchDetailResponse>
>();
private readonly userInternalHistoryInFlight = new Map<
string,
Promise<UserInternalHistoryResponse>
@@ -219,6 +224,27 @@ export class CommunityStatsService {
await this.cacheService.get<InternalMatchDetailResponse>(key);
if (cached && isCompleteMatchDetailResponse(cached)) return cached;
const inFlight = this.matchDetailInFlight.get(key);
if (inFlight) return inFlight;
const promise = this.buildMatchDetailResponse(params, key);
this.matchDetailInFlight.set(key, promise);
try {
return await promise;
} finally {
if (this.matchDetailInFlight.get(key) === promise) {
this.matchDetailInFlight.delete(key);
}
}
}
private async buildMatchDetailResponse(
params: {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
},
key: string,
): Promise<InternalMatchDetailResponse> {
const dataset = await this.buildBaseDataset(params.communityId, {
seasonId: 'all',
});
@@ -246,6 +272,7 @@ export class CommunityStatsService {
gameVersion: game.gameVersion,
timeline: game.timeline ?? [],
objectiveEvents: game.objectiveEvents ?? [],
timelineEvents: game.timelineEvents ?? game.objectiveEvents ?? [],
teams: game.teams.map((team) => ({
teamIndex: team.teamIndex,
side: team.side,
@@ -253,6 +280,8 @@ export class CommunityStatsService {
objectives: team.objectives,
bans: team.bans ?? [],
participants: team.participants.map((record) => ({
participantId: record.participantId,
checkpoints: record.checkpoints,
userId: record.userId,
summonerName: record.summonerName,
tagLine: record.tagLine,
@@ -289,7 +318,15 @@ export class CommunityStatsService {
})),
})),
};
await this.cacheService.setDetail(key, response);
if (gameDetails.every((game) => game.timelineLoaded === true)) {
await this.cacheService.setDetail(key, response);
} else {
await this.cacheService.set(
key,
response,
INCOMPLETE_MATCH_DETAIL_TTL_SECONDS,
);
}
return response;
}
@@ -1160,6 +1197,7 @@ function isCompleteMatchDetailResponse(
(game) =>
Array.isArray(game.timeline) &&
Array.isArray(game.objectiveEvents) &&
Array.isArray(game.timelineEvents) &&
game.teams.every(
(team) =>
Array.isArray(team.bans) &&
@@ -1167,8 +1205,41 @@ function isCompleteMatchDetailResponse(
(participant) =>
typeof participant.tagLine === 'string' &&
Array.isArray(participant.itemBuild) &&
Array.isArray(participant.skillBuild),
Array.isArray(participant.skillBuild) &&
isOptionalFiniteNumber(participant.participantId) &&
isCompleteParticipantCheckpoints(participant.checkpoints),
),
),
);
}
function isCompleteParticipantCheckpoints(value: unknown): boolean {
if (value === undefined) return true;
if (!isRecord(value)) return false;
return ['at10', 'at15'].every((key) => {
const checkpoint = value[key];
if (checkpoint === undefined) return true;
if (!isRecord(checkpoint)) return false;
return [
'timestamp',
'gold',
'cs',
'xp',
'kills',
'deaths',
'assists',
].every((field) => isFiniteNumber(checkpoint[field]));
});
}
function isOptionalFiniteNumber(value: unknown): boolean {
return value === undefined || isFiniteNumber(value);
}
function isFiniteNumber(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
@@ -1,7 +1,9 @@
import type {
MatchStatsParticipantCheckpoints,
MatchStatsItemBuildEvent,
MatchStatsRunePerks,
MatchStatsSkillBuildEvent,
MatchStatsTimelineEvent,
RiotLane,
TeamSide,
} from '../global/database/schema';
@@ -128,6 +130,7 @@ export interface InternalMatchDetailResponse {
type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub';
monsterSubType?: string;
}>;
timelineEvents: MatchStatsTimelineEvent[];
teams: Array<{
teamIndex: number;
side: TeamSide;
@@ -143,6 +146,8 @@ export interface InternalMatchDetailResponse {
};
bans: Array<{ championId: number; pickTurn: number }>;
participants: Array<{
participantId?: number;
checkpoints?: MatchStatsParticipantCheckpoints;
userId: string | null;
summonerName: string;
tagLine: string;
@@ -100,6 +100,24 @@ describe('MatchStatsFragmentBuilder', () => {
it('builds rich set detail from raw Riot match data', () => {
const builder = new MatchStatsFragmentBuilder();
const match = makeMatch();
const redUserId = new mongoose.Types.ObjectId();
match.participants.push({
userId: redUserId,
puuid: 'puuid-2',
gameName: 'Opponent',
profileIconId: 8,
});
match.teams[1].members.push({ userId: redUserId, assignedPosition: 'TOP' });
match.result?.games[0].participants.push({
userId: redUserId,
teamIndex: 2,
side: 'red',
championId: 24,
kills: 1,
deaths: 3,
assists: 0,
win: false,
});
const raw = {
metadata: {
dataVersion: '2',
@@ -206,6 +224,51 @@ describe('MatchStatsFragmentBuilder', () => {
],
},
};
raw.info.participants.push(
{
...raw.info.participants[0],
assists: 0,
championId: 24,
championName: 'Jax',
deaths: 3,
kills: 1,
participantId: 2,
puuid: 'puuid-2',
riotIdGameName: 'Opponent',
summonerId: 'summoner-2',
summonerName: 'Opponent',
teamId: 200,
win: false,
},
{
...raw.info.participants[0],
assists: 2,
championId: 64,
championName: 'LeeSin',
deaths: 0,
kills: 1,
participantId: 3,
puuid: 'puuid-3',
riotIdGameName: 'Jungler',
summonerId: 'summoner-3',
summonerName: 'Jungler',
teamId: 100,
},
);
raw.info.teams.push({
bans: [],
objectives: {
baron: { first: false, kills: 0 },
champion: { first: false, kills: 3 },
dragon: { first: false, kills: 0 },
horde: { first: false, kills: 0 },
inhibitor: { first: false, kills: 0 },
riftHerald: { first: false, kills: 0 },
tower: { first: false, kills: 0 },
},
teamId: 200,
win: false,
});
const timeline = {
metadata: {
dataVersion: '2',
@@ -218,7 +281,20 @@ describe('MatchStatsFragmentBuilder', () => {
{
timestamp: 0,
participantFrames: {
'1': { participantId: 1, totalGold: 500, xp: 0 },
'1': {
participantId: 1,
totalGold: 500,
xp: 0,
minionsKilled: 0,
jungleMinionsKilled: 0,
},
'2': {
participantId: 2,
totalGold: 500,
xp: 0,
minionsKilled: 0,
jungleMinionsKilled: 0,
},
},
},
{
@@ -291,7 +367,137 @@ describe('MatchStatsFragmentBuilder', () => {
},
],
participantFrames: {
'1': { participantId: 1, totalGold: 1_150, xp: 550 },
'1': {
participantId: 1,
totalGold: 1_150,
xp: 550,
minionsKilled: 5,
jungleMinionsKilled: 1,
},
'2': {
participantId: 2,
totalGold: 1_050,
xp: 500,
minionsKilled: 4,
jungleMinionsKilled: 0,
},
},
},
{
timestamp: 540_000,
events: [
{
type: 'CHAMPION_KILL',
timestamp: 300_000,
killerId: 1,
victimId: 2,
assistingParticipantIds: [3],
},
{
type: 'CHAMPION_KILL',
timestamp: 400_000,
killerId: 0,
victimId: 1,
},
{
type: 'BUILDING_KILL',
timestamp: 450_000,
killerId: 0,
teamId: 200,
buildingType: 'TOWER_BUILDING',
towerType: 'OUTER_TURRET',
},
{
type: 'BUILDING_KILL',
timestamp: 450_000,
killerId: 1,
teamId: 200,
buildingType: 'INHIBITOR_BUILDING',
},
{
type: 'CHAMPION_KILL',
timestamp: 500_000,
killerId: 3,
victimId: 2,
assistingParticipantIds: [1],
},
],
participantFrames: {
'1': {
participantId: 1,
totalGold: 4_900,
xp: 3_900,
minionsKilled: 72,
jungleMinionsKilled: 8,
},
'2': {
participantId: 2,
totalGold: 4_300,
xp: 3_500,
minionsKilled: 68,
jungleMinionsKilled: 2,
},
},
},
{
timestamp: 590_000,
events: [],
participantFrames: {
'1': {
participantId: 1,
totalGold: 5_200,
xp: 4_200,
minionsKilled: 80,
jungleMinionsKilled: 10,
},
},
},
{
timestamp: 900_000,
events: [
{
type: 'CHAMPION_KILL',
timestamp: 900_000,
killerId: 1,
victimId: 2,
assistingParticipantIds: [3],
},
],
participantFrames: {
'1': {
participantId: 1,
totalGold: 8_100,
xp: 7_300,
minionsKilled: 130,
jungleMinionsKilled: 15,
},
'2': {
participantId: 2,
totalGold: 6_700,
xp: 6_100,
minionsKilled: 115,
jungleMinionsKilled: 5,
},
},
},
{
timestamp: 1_800_000,
events: [],
participantFrames: {
'1': {
participantId: 1,
totalGold: 12_500,
xp: 14_000,
minionsKilled: 205,
jungleMinionsKilled: 23,
},
'2': {
participantId: 2,
totalGold: 10_200,
xp: 12_700,
minionsKilled: 190,
jungleMinionsKilled: 10,
},
},
},
],
@@ -329,19 +535,105 @@ describe('MatchStatsFragmentBuilder', () => {
{
timestamp: 0,
blue: { gold: 500, xp: 0 },
red: { gold: 0, xp: 0 },
goldDiff: 500,
red: { gold: 500, xp: 0 },
goldDiff: 0,
xpDiff: 0,
},
{
timestamp: 60,
blue: { gold: 1_150, xp: 550 },
red: { gold: 1_050, xp: 500 },
goldDiff: 100,
xpDiff: 50,
},
{
timestamp: 540,
blue: { gold: 4_900, xp: 3_900 },
red: { gold: 4_300, xp: 3_500 },
goldDiff: 600,
xpDiff: 400,
},
{
timestamp: 590,
blue: { gold: 5_200, xp: 4_200 },
red: { gold: 0, xp: 0 },
goldDiff: 1_150,
xpDiff: 550,
goldDiff: 5_200,
xpDiff: 4_200,
},
{
timestamp: 900,
blue: { gold: 8_100, xp: 7_300 },
red: { gold: 6_700, xp: 6_100 },
goldDiff: 1_400,
xpDiff: 1_200,
},
{
timestamp: 1_800,
blue: { gold: 12_500, xp: 14_000 },
red: { gold: 10_200, xp: 12_700 },
goldDiff: 2_300,
xpDiff: 1_300,
},
],
});
expect(fragment.gameDetails[0].timelineEvents).toEqual([
{
timestamp: 20,
side: 'blue',
type: 'dragon',
monsterSubType: 'FIRE_DRAGON',
},
{
timestamp: 30,
side: 'blue',
type: 'elderDragon',
monsterSubType: 'ELDER_DRAGON',
},
{ timestamp: 40, side: 'blue', type: 'voidGrub' },
{ timestamp: 50, side: 'blue', type: 'baron' },
{ timestamp: 55, side: 'blue', type: 'riftHerald' },
{
timestamp: 300,
side: 'blue',
type: 'championKill',
killerParticipantId: 1,
victimParticipantId: 2,
assistingParticipantIds: [3],
},
{
timestamp: 400,
type: 'championKill',
victimParticipantId: 1,
},
{
timestamp: 450,
side: 'blue',
type: 'tower',
towerType: 'OUTER_TURRET',
},
{
timestamp: 450,
side: 'blue',
type: 'inhibitor',
killerParticipantId: 1,
},
{
timestamp: 500,
side: 'blue',
type: 'championKill',
killerParticipantId: 3,
victimParticipantId: 2,
assistingParticipantIds: [1],
},
{
timestamp: 900,
side: 'blue',
type: 'championKill',
killerParticipantId: 1,
victimParticipantId: 2,
assistingParticipantIds: [3],
},
]);
expect(fragment.gameDetails[0].teams[0].bans).toEqual([
{ championId: 14, pickTurn: 1 },
{ championId: 43, pickTurn: 2 },
@@ -356,6 +648,27 @@ describe('MatchStatsFragmentBuilder', () => {
voidGrub: 1,
});
expect(fragment.records[0]).toMatchObject({
participantId: 1,
checkpoints: {
at10: {
timestamp: 590,
gold: 5_200,
cs: 90,
xp: 4_200,
kills: 1,
deaths: 1,
assists: 1,
},
at15: {
timestamp: 900,
gold: 8_100,
cs: 145,
xp: 7_300,
kills: 2,
deaths: 1,
assists: 1,
},
},
championLevel: 15,
cs: 228,
damageDealtToChampions: 18_765,
@@ -392,5 +705,118 @@ describe('MatchStatsFragmentBuilder', () => {
{ timestamp: 45, skillSlot: 3, level: 2, levelUpType: 'NORMAL' },
],
});
expect(fragment.records[1]).toMatchObject({
participantId: 2,
checkpoints: {
at15: {
timestamp: 900,
gold: 6_700,
cs: 120,
xp: 6_100,
kills: 0,
deaths: 3,
assists: 0,
},
},
});
expect(fragment.records[1].checkpoints).not.toHaveProperty('at10');
const timelineWithoutEvents = {
...timeline,
info: {
...timeline.info,
frames: timeline.info.frames.map((frame) => ({
...frame,
events: [],
})),
},
} as RiotMatchTimelineDto;
const objectiveFallback = builder.buildFragment({
match,
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
timelineByRiotMatchId: new Map([['KR_1', timelineWithoutEvents]]),
});
expect(objectiveFallback.gameDetails[0].teams[0].objectives).toMatchObject({
baron: 1,
dragon: 2,
elderDragon: 0,
riftHerald: 0,
voidGrub: 3,
});
const dragonOnlyTimeline = {
...timeline,
info: {
...timeline.info,
frames: timeline.info.frames.map((frame) => ({
...frame,
events: (frame.events ?? []).filter(
(event) =>
event.type !== 'ELITE_MONSTER_KILL' ||
event.monsterType === 'DRAGON',
),
})),
},
} as RiotMatchTimelineDto;
const partialObjectiveFallback = builder.buildFragment({
match,
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
timelineByRiotMatchId: new Map([['KR_1', dragonOnlyTimeline]]),
});
expect(
partialObjectiveFallback.gameDetails[0].teams[0].objectives,
).toMatchObject({
baron: 1,
dragon: 1,
elderDragon: 1,
riftHerald: 0,
voidGrub: 3,
});
const shortMatch = {
...match,
result: {
...match.result!,
games: match.result!.games.map((game) => ({
...game,
gameDuration: 599,
})),
},
} as MatchDocument;
const shortFragment = builder.buildFragment({
match: shortMatch,
rawByRiotMatchId: new Map([
[
'KR_1',
{
...raw,
info: { ...raw.info, gameDuration: 599 },
} as RiotMatchDto,
],
]),
timelineByRiotMatchId: new Map([
['KR_1', timeline as RiotMatchTimelineDto],
]),
});
expect(
shortFragment.records.every((record) => record.checkpoints === undefined),
).toBe(true);
const invalidIntervalTimeline = {
...timeline,
info: { ...timeline.info, frameInterval: Number.NaN },
} as RiotMatchTimelineDto;
const invalidIntervalFragment = builder.buildFragment({
match,
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
timelineByRiotMatchId: new Map([['KR_1', invalidIntervalTimeline]]),
});
expect(invalidIntervalFragment.gameDetails[0].timelineLoaded).toBe(false);
expect(invalidIntervalFragment.gameDetails[0].timeline).toEqual([]);
expect(
invalidIntervalFragment.records.every(
(record) => record.checkpoints === undefined,
),
).toBe(true);
});
});
@@ -3,10 +3,13 @@ import mongoose from 'mongoose';
import type {
MatchDocument,
MatchGameResultParticipant,
MatchStatsCheckpoint,
MatchStatsItemBuildEvent,
MatchStatsObjectiveEvent,
MatchStatsObjectiveSummary,
MatchStatsParticipantCheckpoints,
MatchStatsSkillBuildEvent,
MatchStatsTimelineEvent,
MatchStatsTimelinePoint,
TeamSide,
} from '../global/database/schema';
@@ -27,13 +30,17 @@ interface ParticipantBuildEvents {
skills: MatchStatsSkillBuildEvent[];
}
interface TimelineProjection {
objectiveEvents: MatchStatsObjectiveEvent[];
timelineEvents: MatchStatsTimelineEvent[];
}
@Injectable()
export class MatchStatsFragmentBuilder {
public buildFragment(params: {
match: MatchDocument;
rawByRiotMatchId: Map<string, RiotMatchDto>;
timelineByRiotMatchId?: Map<string, RiotMatchTimelineDto>;
timelineLoadAttempted?: boolean;
}): MatchStatsFragment {
const games = [...(params.match.result?.games ?? [])].sort(
(left, right) => left.gameNumber - right.gameNumber,
@@ -43,13 +50,7 @@ export class MatchStatsFragmentBuilder {
const raw = params.rawByRiotMatchId.get(game.riotMatchId);
const timeline = params.timelineByRiotMatchId?.get(game.riotMatchId);
return raw
? this.toGameDetail(
params.match,
game,
raw,
timeline,
params.timelineLoadAttempted === true,
)
? this.toGameDetail(params.match, game, raw, timeline)
: this.toFallbackGameDetail(params.match, game);
});
const records = gameDetails.flatMap((detail) =>
@@ -130,8 +131,10 @@ export class MatchStatsFragmentBuilder {
game: NonNullable<MatchDocument['result']>['games'][number],
raw: RiotMatchDto,
timeline?: RiotMatchTimelineDto,
timelineLoadAttempted = false,
): InternalGameDetail {
const usableTimeline = isUsableTimeline(timeline, raw.info.gameDuration)
? timeline
: undefined;
const puuidByUserId = new Map(
match.participants
.filter((participant) => participant.puuid)
@@ -158,14 +161,18 @@ export class MatchStatsFragmentBuilder {
raw,
rawTeamIdBySide,
);
const objectiveEvents = this.toObjectiveEvents(
timeline,
const { objectiveEvents, timelineEvents } = this.toTimelineEvents(
usableTimeline,
rawTeamIdBySide,
sideByParticipantId,
);
const timelineObjectives = this.toTimelineObjectives(objectiveEvents);
const buildEventsByParticipantId =
this.toBuildEventsByParticipantId(timeline);
this.toBuildEventsByParticipantId(usableTimeline);
const checkpointsByParticipantId = this.toCheckpointsByParticipantId(
usableTimeline,
raw.info.gameDuration,
);
return {
gameNumber: game.gameNumber,
@@ -174,9 +181,10 @@ export class MatchStatsFragmentBuilder {
gameDuration: game.gameDuration,
gameVersion: raw.info.gameVersion,
winnerSide: game.winnerSide,
timeline: this.toTimeline(raw, rawTeamIdBySide, timeline),
timelineLoaded: timelineLoadAttempted || Boolean(timeline),
timeline: this.toTimeline(raw, rawTeamIdBySide, usableTimeline),
timelineLoaded: Boolean(usableTimeline),
objectiveEvents,
timelineEvents,
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
const teamIndex =
side === 'blue' ? game.blueTeamIndex : game.redTeamIndex;
@@ -202,7 +210,6 @@ export class MatchStatsFragmentBuilder {
objectives: this.toObjectiveSummary(
rawTeam,
timelineObjectives.get(side),
Boolean(timeline),
),
bans: (rawTeam?.bans ?? []).map((ban) => ({
championId: ban.championId,
@@ -224,6 +231,9 @@ export class MatchStatsFragmentBuilder {
rawParticipant.participantId,
)
: undefined,
checkpoints: rawParticipant
? checkpointsByParticipantId.get(rawParticipant.participantId)
: undefined,
teamKills,
teamDamage,
});
@@ -246,6 +256,7 @@ export class MatchStatsFragmentBuilder {
timeline: [],
timelineLoaded: false,
objectiveEvents: [],
timelineEvents: [],
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
side,
@@ -273,6 +284,7 @@ export class MatchStatsFragmentBuilder {
participant: MatchGameResultParticipant;
rawParticipant?: RiotMatchParticipantDto;
buildEvents?: ParticipantBuildEvents;
checkpoints?: MatchStatsParticipantCheckpoints;
teamKills: number;
teamDamage: number;
}): InternalRecord {
@@ -282,6 +294,7 @@ export class MatchStatsFragmentBuilder {
participant,
rawParticipant,
buildEvents,
checkpoints,
teamKills,
teamDamage,
} = params;
@@ -319,6 +332,8 @@ export class MatchStatsFragmentBuilder {
riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
participantId: rawParticipant?.participantId,
checkpoints,
userId: participant.userId.toString(),
summonerName:
snapshot?.gameName ??
@@ -455,6 +470,107 @@ export class MatchStatsFragmentBuilder {
return buildEventsByParticipantId;
}
private toCheckpointsByParticipantId(
timeline: RiotMatchTimelineDto | undefined,
gameDurationSeconds: number,
): Map<number, MatchStatsParticipantCheckpoints> {
const checkpointsByParticipantId = new Map<
number,
MatchStatsParticipantCheckpoints
>();
if (
!timeline?.info.frames.length ||
!Number.isFinite(timeline.info.frameInterval) ||
timeline.info.frameInterval <= 0
) {
return checkpointsByParticipantId;
}
const participantIds = new Set<number>();
const championKillEvents = timeline.info.frames.flatMap((frame) =>
(frame.events ?? []).filter((event) => event.type === 'CHAMPION_KILL'),
);
for (const frame of timeline.info.frames) {
for (const participantFrame of Object.values(frame.participantFrames)) {
participantIds.add(participantFrame.participantId);
}
}
const targets = [
['at10', 600_000],
['at15', 900_000],
] as const;
for (const participantId of participantIds) {
const checkpoints: MatchStatsParticipantCheckpoints = {};
for (const [key, targetTimestamp] of targets) {
if (gameDurationSeconds * 1_000 < targetTimestamp) continue;
const selectedFrame = timeline.info.frames.reduce<
RiotMatchTimelineDto['info']['frames'][number] | undefined
>((latest, frame) => {
if (
frame.timestamp > targetTimestamp ||
!Object.values(frame.participantFrames).some(
(participantFrame) =>
participantFrame.participantId === participantId,
)
) {
return latest;
}
return !latest || frame.timestamp > latest.timestamp ? frame : latest;
}, undefined);
if (
!selectedFrame ||
targetTimestamp - selectedFrame.timestamp >=
timeline.info.frameInterval
) {
continue;
}
const participantFrame = Object.values(
selectedFrame.participantFrames,
).find((frame) => frame.participantId === participantId);
if (
!participantFrame ||
typeof participantFrame.minionsKilled !== 'number' ||
!Number.isFinite(participantFrame.minionsKilled) ||
typeof participantFrame.jungleMinionsKilled !== 'number' ||
!Number.isFinite(participantFrame.jungleMinionsKilled)
) {
continue;
}
const checkpoint: MatchStatsCheckpoint = {
timestamp: Math.max(0, Math.round(selectedFrame.timestamp / 1_000)),
gold: participantFrame.totalGold,
cs:
participantFrame.minionsKilled +
participantFrame.jungleMinionsKilled,
xp: participantFrame.xp,
kills: 0,
deaths: 0,
assists: 0,
};
for (const event of championKillEvents) {
if (event.timestamp > selectedFrame.timestamp) continue;
if (event.killerId === participantId && event.killerId > 0) {
checkpoint.kills += 1;
}
if (event.victimId === participantId) checkpoint.deaths += 1;
if (event.assistingParticipantIds?.includes(participantId)) {
checkpoint.assists += 1;
}
}
checkpoints[key] = checkpoint;
}
if (checkpoints.at10 || checkpoints.at15) {
checkpointsByParticipantId.set(participantId, checkpoints);
}
}
return checkpointsByParticipantId;
}
private toTimeline(
raw: RiotMatchDto,
rawTeamIdBySide: Map<TeamSide, number>,
@@ -511,65 +627,124 @@ export class MatchStatsFragmentBuilder {
return sideByParticipantId;
}
private toObjectiveEvents(
private toTimelineEvents(
timeline: RiotMatchTimelineDto | undefined,
rawTeamIdBySide: Map<TeamSide, number>,
sideByParticipantId: Map<number, TeamSide>,
): MatchStatsObjectiveEvent[] {
if (!timeline?.info.frames.length) return [];
): TimelineProjection {
if (!timeline?.info.frames.length) {
return { objectiveEvents: [], timelineEvents: [] };
}
const sideByTeamId = new Map<number, TeamSide>();
for (const [side, teamId] of rawTeamIdBySide.entries()) {
sideByTeamId.set(teamId, side);
}
const objectiveEvents: MatchStatsObjectiveEvent[] = [];
const projected: Array<{
sourceSequence: number;
event: MatchStatsTimelineEvent;
}> = [];
let sourceSequence = 0;
for (const frame of timeline.info.frames) {
for (const event of frame.events ?? []) {
if (event.type !== 'ELITE_MONSTER_KILL') continue;
const side =
(typeof event.killerTeamId === 'number'
? sideByTeamId.get(event.killerTeamId)
: undefined) ??
(typeof event.killerId === 'number'
? sideByParticipantId.get(event.killerId)
: undefined);
if (!side) continue;
const currentSequence = sourceSequence;
sourceSequence += 1;
const timestamp = Math.max(0, Math.round(event.timestamp / 1000));
switch (event.monsterType) {
case 'BARON_NASHOR':
objectiveEvents.push({ timestamp, side, type: 'baron' });
break;
case 'RIFTHERALD':
objectiveEvents.push({ timestamp, side, type: 'riftHerald' });
break;
case 'HORDE':
objectiveEvents.push({ timestamp, side, type: 'voidGrub' });
break;
case 'DRAGON':
if (event.monsterSubType === 'ELDER_DRAGON') {
objectiveEvents.push({
timestamp,
side,
type: 'elderDragon',
monsterSubType: event.monsterSubType,
});
} else {
objectiveEvents.push({
timestamp,
side,
type: 'dragon',
monsterSubType: event.monsterSubType,
});
}
break;
default:
break;
if (event.type === 'ELITE_MONSTER_KILL') {
const side =
(typeof event.killerTeamId === 'number'
? sideByTeamId.get(event.killerTeamId)
: undefined) ??
(typeof event.killerId === 'number'
? sideByParticipantId.get(event.killerId)
: undefined);
if (!side) continue;
const objectiveEvent = toObjectiveTimelineEvent({
timestamp,
side,
monsterType: event.monsterType,
monsterSubType: event.monsterSubType,
});
if (objectiveEvent) {
projected.push({
sourceSequence: currentSequence,
event: objectiveEvent,
});
}
continue;
}
if (event.type === 'CHAMPION_KILL') {
const side =
typeof event.killerId === 'number' && event.killerId > 0
? sideByParticipantId.get(event.killerId)
: undefined;
projected.push({
sourceSequence: currentSequence,
event: {
timestamp,
type: 'championKill',
...(side ? { side } : {}),
...(typeof event.killerId === 'number' && event.killerId > 0
? { killerParticipantId: event.killerId }
: {}),
...(typeof event.victimId === 'number' && event.victimId > 0
? { victimParticipantId: event.victimId }
: {}),
...(event.assistingParticipantIds
? { assistingParticipantIds: event.assistingParticipantIds }
: {}),
},
});
continue;
}
if (event.type !== 'BUILDING_KILL') continue;
const destroyedSide =
typeof event.teamId === 'number'
? sideByTeamId.get(event.teamId)
: undefined;
const side =
(typeof event.killerId === 'number' && event.killerId > 0
? sideByParticipantId.get(event.killerId)
: undefined) ??
(destroyedSide ? oppositeSide(destroyedSide) : undefined);
const type =
event.buildingType === 'TOWER_BUILDING'
? 'tower'
: event.buildingType === 'INHIBITOR_BUILDING'
? 'inhibitor'
: undefined;
if (!side || !type) continue;
projected.push({
sourceSequence: currentSequence,
event: {
timestamp,
side,
type,
...(typeof event.killerId === 'number' && event.killerId > 0
? { killerParticipantId: event.killerId }
: {}),
...(type === 'tower' && event.towerType
? { towerType: event.towerType }
: {}),
},
});
}
}
return objectiveEvents.sort((left, right) => left.timestamp - right.timestamp);
const timelineEvents = projected
.sort(
(left, right) =>
left.event.timestamp - right.event.timestamp ||
left.sourceSequence - right.sourceSequence,
)
.map(({ event }) => event);
return {
timelineEvents,
objectiveEvents: timelineEvents.filter(isObjectiveTimelineEvent),
};
}
private toTimelineObjectives(
@@ -608,29 +783,29 @@ export class MatchStatsFragmentBuilder {
}
private toObjectiveSummary(
rawTeam:
| RiotMatchDto['info']['teams'][number]
| undefined,
rawTeam: RiotMatchDto['info']['teams'][number] | undefined,
timelineObjectives: MatchStatsObjectiveSummary | undefined,
hasTimeline: boolean,
): MatchStatsObjectiveSummary {
const rawObjectives = rawTeam?.objectives;
const timelineDragon = timelineObjectives?.dragon ?? 0;
const timelineElder = timelineObjectives?.elderDragon ?? 0;
const hasProjectedDragon = timelineDragon + timelineElder > 0;
return {
tower: rawObjectives?.tower?.kills ?? 0,
dragon: hasTimeline
? (timelineObjectives?.dragon ?? 0)
dragon: hasProjectedDragon
? timelineDragon
: (rawObjectives?.dragon?.kills ?? 0),
inhibitor: rawObjectives?.inhibitor?.kills ?? 0,
baron: hasTimeline
baron: (timelineObjectives?.baron ?? 0) > 0
? (timelineObjectives?.baron ?? 0)
: (rawObjectives?.baron?.kills ?? 0),
riftHerald: hasTimeline
riftHerald: (timelineObjectives?.riftHerald ?? 0) > 0
? (timelineObjectives?.riftHerald ?? 0)
: (rawObjectives?.riftHerald?.kills ?? 0),
voidGrub: hasTimeline
voidGrub: (timelineObjectives?.voidGrub ?? 0) > 0
? (timelineObjectives?.voidGrub ?? 0)
: (rawObjectives?.horde?.kills ?? 0),
elderDragon: timelineObjectives?.elderDragon ?? 0,
elderDragon: hasProjectedDragon ? timelineElder : 0,
};
}
@@ -687,6 +862,79 @@ function toItemBuildType(
}
}
function toObjectiveTimelineEvent(params: {
timestamp: number;
side: TeamSide;
monsterType?: string;
monsterSubType?: string;
}): MatchStatsObjectiveEvent | null {
switch (params.monsterType) {
case 'BARON_NASHOR':
return { timestamp: params.timestamp, side: params.side, type: 'baron' };
case 'RIFTHERALD':
return {
timestamp: params.timestamp,
side: params.side,
type: 'riftHerald',
};
case 'HORDE':
return {
timestamp: params.timestamp,
side: params.side,
type: 'voidGrub',
};
case 'DRAGON':
return {
timestamp: params.timestamp,
side: params.side,
type:
params.monsterSubType === 'ELDER_DRAGON' ? 'elderDragon' : 'dragon',
monsterSubType: params.monsterSubType,
};
default:
return null;
}
}
function isObjectiveTimelineEvent(
event: MatchStatsTimelineEvent,
): event is MatchStatsObjectiveEvent {
return (
event.type === 'dragon' ||
event.type === 'elderDragon' ||
event.type === 'baron' ||
event.type === 'riftHerald' ||
event.type === 'voidGrub'
);
}
function oppositeSide(side: TeamSide): TeamSide {
return side === 'blue' ? 'red' : 'blue';
}
function isUsableTimeline(
timeline: RiotMatchTimelineDto | undefined,
gameDurationSeconds: number,
): timeline is RiotMatchTimelineDto {
if (
!timeline ||
!Number.isFinite(timeline.info.frameInterval) ||
timeline.info.frameInterval <= 0 ||
!Array.isArray(timeline.info.frames) ||
timeline.info.frames.length === 0
) {
return false;
}
const finalTimestamp = Math.max(
...timeline.info.frames.map((frame) => frame.timestamp),
);
return (
Number.isFinite(finalTimestamp) &&
Math.abs(gameDurationSeconds * 1_000 - finalTimestamp) <
timeline.info.frameInterval
);
}
function round(value: number): number {
return Math.round(value * 10) / 10;
}
@@ -3,6 +3,7 @@ import { ConnectionService } from '../global/database/connection.service';
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types';
describe('MatchStatsService', () => {
it('deletes an existing fragment when the match is no longer eligible', async () => {
@@ -158,8 +159,10 @@ describe('MatchStatsService', () => {
match,
rawByRiotMatchId: expect.any(Map),
timelineByRiotMatchId: expect.any(Map),
timelineLoadAttempted: false,
});
expect(
builder.buildFragment.mock.calls[0][0].timelineByRiotMatchId,
).toHaveProperty('size', 0);
expect(repository.upsert).toHaveBeenCalledWith(
expect.objectContaining({
matchId,
@@ -167,11 +170,169 @@ describe('MatchStatsService', () => {
scheduledAt,
gameCreationMin: 1_000,
gameCreationMax: 2_000,
builderVersion: 9,
builderVersion: MATCH_STATS_BUILDER_VERSION,
}),
);
});
it('retries unusable timeline caches and stores a later usable fetch', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
scheduledAt: new Date('2026-05-03T00:00:00.000Z'),
status: 'finished',
result: { games: [{ riotMatchId: 'KR_1' }] },
};
const emptyTimeline = {
info: { frameInterval: 60_000, frames: [] },
};
const partialTimeline = {
info: {
frameInterval: 60_000,
frames: [{ timestamp: 0, events: [] }],
},
};
const nonPositiveTimeline = {
info: {
frameInterval: 0,
frames: [timelineFrame(120_000)],
},
};
const truncatedTimeline = {
info: {
frameInterval: 60_000,
frames: [timelineFrame()],
},
};
const usableTimeline = {
metadata: {
dataVersion: '2',
matchId: 'KR_1',
participants: ['puuid-1'],
},
info: {
frameInterval: 60_000,
frames: [timelineFrame(120_000)],
},
};
const cachedTimelines = [
emptyTimeline,
partialTimeline,
nonPositiveTimeline,
truncatedTimeline,
];
let buildIndex = 0;
const riotFind = jest.fn().mockImplementation(() => ({
lean: () => ({
exec: jest.fn().mockResolvedValue([
{
matchId: 'KR_1',
raw: { info: { gameDuration: 120 } },
timeline: cachedTimelines[Math.min(buildIndex++, 3)],
},
]),
}),
}));
const updateExec = jest.fn().mockResolvedValue(undefined);
let storedUpdate:
| {
filter: unknown;
update: { $set: { timeline: unknown; timelineFetchedAt: Date } };
}
| undefined;
const updateOne = jest.fn(
(
filter: unknown,
update: { $set: { timeline: unknown; timelineFetchedAt: Date } },
) => {
storedUpdate = { filter, update };
return { exec: updateExec };
},
);
const connectionService = {
getModel: jest.fn().mockImplementation((name: string) => {
if (name === 'match') {
return Promise.resolve({ findById: () => queryResult(match, false) });
}
if (name === 'competition') {
return Promise.resolve({ findOne: () => queryResult(null) });
}
if (name === 'riotMatch') {
return Promise.resolve({ find: riotFind, updateOne });
}
if (name === 'community') {
return Promise.resolve({
findById: () => ({
select: () => queryResult({ riotRegion: 'asia' }),
}),
});
}
return Promise.reject(new Error(`Unexpected model: ${name}`));
}),
} as unknown as ConnectionService;
const repository = {
upsert: jest.fn().mockResolvedValue(undefined),
deleteByMatch: jest.fn(),
deleteLegacyByMatch: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
type BuildParams = Parameters<
MatchStatsFragmentBuilder['buildFragment']
>[0];
const buildCalls: BuildParams[] = [];
const builtFragment = {
matchCard: { matchId: matchId.toString() },
records: [],
gameDetails: [],
userIds: [],
championIds: [],
gameCreationMin: 1_000,
gameCreationMax: 2_000,
} as ReturnType<MatchStatsFragmentBuilder['buildFragment']>;
const buildFragment = jest.fn((params: BuildParams) => {
buildCalls.push(params);
return builtFragment;
});
const builder = {
buildFragment,
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const getMatchTimeline = jest
.fn()
.mockRejectedValueOnce(new Error('temporary Riot failure'))
.mockRejectedValueOnce(new Error('temporary Riot failure'))
.mockRejectedValueOnce(new Error('temporary Riot failure'))
.mockResolvedValueOnce(usableTimeline);
const service = new MatchStatsService(
connectionService,
repository,
builder,
{ getMatchTimeline } as never,
);
await service.buildAndUpsert(matchId, { includeTimeline: true });
await service.buildAndUpsert(matchId, { includeTimeline: true });
await service.buildAndUpsert(matchId, { includeTimeline: true });
await service.buildAndUpsert(matchId, { includeTimeline: true });
expect(getMatchTimeline).toHaveBeenCalledTimes(4);
expect(buildFragment).toHaveBeenCalledTimes(4);
expect(buildCalls[0].timelineByRiotMatchId).toHaveProperty('size', 0);
expect(buildCalls[1].timelineByRiotMatchId).toHaveProperty('size', 0);
expect(buildCalls[2].timelineByRiotMatchId?.get('KR_1')).toBeUndefined();
expect(buildCalls[3].timelineByRiotMatchId?.get('KR_1')).toBe(
usableTimeline,
);
for (const call of buildCalls) {
expect(call).not.toHaveProperty('timelineLoadAttempted');
}
expect(updateOne).toHaveBeenCalledTimes(1);
expect(storedUpdate?.filter).toEqual({ matchId: 'KR_1' });
expect(storedUpdate?.update.$set.timeline).toBe(usableTimeline);
expect(storedUpdate?.update.$set.timelineFetchedAt).toBeInstanceOf(Date);
expect(updateExec).toHaveBeenCalledTimes(1);
});
it('builds from the Competition projection and records its source revision', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
@@ -451,3 +612,19 @@ function queryResult<T>(value: T, lean = true) {
query.lean.mockReturnValue(query);
return lean ? query : { exec: query.exec };
}
function timelineFrame(timestamp = 0) {
return {
timestamp,
events: [],
participantFrames: {
'1': {
participantId: 1,
totalGold: 500,
xp: 0,
minionsKilled: 0,
jungleMinionsKilled: 0,
},
},
};
}
@@ -77,7 +77,7 @@ export class MatchStatsService {
);
const timelineByRiotMatchId = new Map<string, RiotMatchTimelineDto>();
for (const doc of riotDocs) {
if (isRiotMatchTimelineDto(doc.timeline)) {
if (isUsableRiotMatchTimeline(doc.timeline, doc.raw)) {
timelineByRiotMatchId.set(doc.matchId, doc.timeline);
}
}
@@ -94,6 +94,12 @@ export class MatchStatsService {
doc.matchId,
{ region },
);
if (!isUsableRiotMatchTimeline(timeline, doc.raw)) {
this.logger.warn(
`Ignored unusable match timeline for ${doc.matchId}.`,
);
continue;
}
await RiotMatchModel.updateOne(
{ matchId: doc.matchId },
{
@@ -118,7 +124,6 @@ export class MatchStatsService {
match: sourceMatch,
rawByRiotMatchId,
timelineByRiotMatchId,
timelineLoadAttempted: options.includeTimeline === true,
});
await this.repository.upsert({
@@ -253,9 +258,65 @@ export class MatchStatsService {
}
}
function isRiotMatchTimelineDto(value: unknown): value is RiotMatchTimelineDto {
if (!isRecord(value) || !isRecord(value.info)) return false;
return Array.isArray(value.info.frames);
function isUsableRiotMatchTimeline(
value: unknown,
rawMatch: unknown,
): value is RiotMatchTimelineDto {
if (
!isRecord(value) ||
!isRecord(value.info) ||
!isRecord(rawMatch) ||
!isRecord(rawMatch.info)
) {
return false;
}
const frameInterval = finiteNumber(value.info.frameInterval);
const gameDuration = finiteNumber(rawMatch.info.gameDuration);
const frames = value.info.frames;
if (
frameInterval === undefined ||
frameInterval <= 0 ||
gameDuration === undefined ||
gameDuration < 0 ||
!Array.isArray(frames) ||
frames.length === 0 ||
!frames.every(isUsableTimelineFrame)
) {
return false;
}
const lastTimestamp = Math.max(
...frames.map((frame) => (frame as { timestamp: number }).timestamp),
);
return Math.abs(gameDuration * 1_000 - lastTimestamp) < frameInterval;
}
function isUsableTimelineFrame(value: unknown): boolean {
if (
!isRecord(value) ||
finiteNumber(value.timestamp) === undefined ||
!Array.isArray(value.events) ||
!value.events.every(
(event) =>
isRecord(event) &&
typeof event.type === 'string' &&
finiteNumber(event.timestamp) !== undefined,
) ||
!isRecord(value.participantFrames)
) {
return false;
}
const participantFrames = Object.values(value.participantFrames);
return (
participantFrames.length > 0 &&
participantFrames.every(
(participantFrame) =>
isRecord(participantFrame) &&
finiteNumber(participantFrame.participantId) !== undefined &&
finiteNumber(participantFrame.totalGold) !== undefined &&
finiteNumber(participantFrame.xp) !== undefined,
)
);
}
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -4,7 +4,7 @@ import type {
} from '../global/database/schema';
import type { InternalMatchCardView } from './community-stats.types';
export const MATCH_STATS_BUILDER_VERSION = 9;
export const MATCH_STATS_BUILDER_VERSION = 10;
export type InternalRecord = MatchStatsRecord;
export type InternalGameDetail = MatchStatsGameDetail;
@@ -1,5 +1,18 @@
import { generateSeriesGraph } from './series-graph';
type GraphInput = Parameters<typeof generateSeriesGraph>[0];
type ExplicitRoundRobinPairing = {
roundNumber: number;
matchNumber: number;
teamAId: string;
teamBId: string;
};
type ExplicitRoundRobinGraphInput = Omit<GraphInput, 'format'> & {
format: Extract<GraphInput['format'], { type: 'round-robin' }> & {
pairings: readonly ExplicitRoundRobinPairing[];
};
};
describe('generateSeriesGraph', () => {
it('generates a deterministic graph with stable opaque ids', () => {
const input = {
@@ -112,8 +125,254 @@ describe('generateSeriesGraph', () => {
expect(error).toMatchObject({ code: 'INVALID_FIRST_TO_RULE' });
}
});
it('reproduces an explicit persisted round-robin schedule by TeamId and pairing position', () => {
const input: ExplicitRoundRobinGraphInput = {
competitionId: 'competition-persisted-round-robin',
teams: Array.from({ length: 8 }, (_, index) => ({
teamId: `team-${index + 1}`,
displayOrder: 8 - index,
seedNumber: index + 1,
})),
format: {
type: 'round-robin',
rule: fixedGames(1),
maxRounds: 3,
tieBreakers: ['series-wins', 'game-diff', 'head-to-head'],
// Persisted schedules need not arrive in display order. Their explicit
// round/match positions, rather than array position, define identity.
pairings: [
pairing(3, 4, 'team-6', 'team-7'),
pairing(1, 2, 'team-3', 'team-4'),
pairing(2, 1, 'team-1', 'team-3'),
pairing(1, 4, 'team-7', 'team-8'),
pairing(3, 1, 'team-1', 'team-4'),
pairing(2, 3, 'team-5', 'team-7'),
pairing(1, 1, 'team-1', 'team-2'),
pairing(3, 3, 'team-5', 'team-8'),
pairing(2, 4, 'team-6', 'team-8'),
pairing(1, 3, 'team-5', 'team-6'),
pairing(3, 2, 'team-2', 'team-3'),
pairing(2, 2, 'team-2', 'team-4'),
],
},
};
const first = generateSeriesGraph(input);
const second = generateSeriesGraph({
...input,
format: {
...input.format,
pairings: [...input.format.pairings].reverse(),
},
});
expect(second).toEqual(first);
expect(
first.map((series) => ({
code: series.code,
roundNumber: series.stage.roundNumber,
displayOrder: series.stage.displayOrder,
sources: series.slots.map((slot) => slot.source),
})),
).toEqual([
roundRobinSeries('RR_R1_M1', 1, 1, 'team-1', 'team-2'),
roundRobinSeries('RR_R1_M2', 1, 2, 'team-3', 'team-4'),
roundRobinSeries('RR_R1_M3', 1, 3, 'team-5', 'team-6'),
roundRobinSeries('RR_R1_M4', 1, 4, 'team-7', 'team-8'),
roundRobinSeries('RR_R2_M1', 2, 5, 'team-1', 'team-3'),
roundRobinSeries('RR_R2_M2', 2, 6, 'team-2', 'team-4'),
roundRobinSeries('RR_R2_M3', 2, 7, 'team-5', 'team-7'),
roundRobinSeries('RR_R2_M4', 2, 8, 'team-6', 'team-8'),
roundRobinSeries('RR_R3_M1', 3, 9, 'team-1', 'team-4'),
roundRobinSeries('RR_R3_M2', 3, 10, 'team-2', 'team-3'),
roundRobinSeries('RR_R3_M3', 3, 11, 'team-5', 'team-8'),
roundRobinSeries('RR_R3_M4', 3, 12, 'team-6', 'team-7'),
]);
});
it.each([
{
name: 'a TeamId that is absent from the Competition',
replacement: pairing(1, 1, 'team-1', 'team-9'),
},
{
name: 'the same TeamId in both slots',
replacement: pairing(1, 1, 'team-1', 'team-1'),
},
{
name: 'a non-positive round number',
replacement: pairing(0, 1, 'team-1', 'team-2'),
},
{
name: 'a non-positive match number',
replacement: pairing(1, 0, 'team-1', 'team-2'),
},
])(
'rejects an explicit round-robin pairing with $name',
({ replacement }) => {
const input = explicitRoundRobinInput([
replacement,
pairing(1, 2, 'team-3', 'team-4'),
]);
expectGraphError(input, 'INVALID_ROUND_ROBIN_PAIRING');
},
);
it.each([
{
name: 'round and match position',
pairings: [
pairing(1, 1, 'team-1', 'team-2'),
pairing(1, 1, 'team-3', 'team-4'),
],
code: 'DUPLICATE_ROUND_ROBIN_PAIRING_POSITION',
},
{
name: 'opponents with reversed slots',
pairings: [
pairing(1, 1, 'team-1', 'team-2'),
pairing(2, 1, 'team-2', 'team-1'),
],
code: 'DUPLICATE_ROUND_ROBIN_OPPONENTS',
},
])('rejects a duplicate explicit $name', ({ pairings, code }) => {
expectGraphError(explicitRoundRobinInput(pairings), code);
});
it('keeps distinct opponent pairs when opaque TeamIds contain delimiters', () => {
const input = explicitRoundRobinInput([
pairing(1, 1, 'a', 'b:c'),
pairing(1, 2, 'a:b', 'c'),
]);
input.format.maxRounds = 1;
input.teams = ['a', 'b:c', 'a:b', 'c'].map((teamId, index) => ({
teamId,
displayOrder: index + 1,
seedNumber: index + 1,
}));
expect(generateSeriesGraph(input)).toHaveLength(2);
});
it('validates complete odd-team rounds and clamps maxRounds to the full schedule', () => {
const pairings = [
pairing(1, 1, 'team-2', 'team-5'),
pairing(1, 2, 'team-3', 'team-4'),
pairing(2, 1, 'team-1', 'team-5'),
pairing(2, 2, 'team-2', 'team-3'),
pairing(3, 1, 'team-1', 'team-4'),
pairing(3, 2, 'team-3', 'team-5'),
pairing(4, 1, 'team-1', 'team-3'),
pairing(4, 2, 'team-2', 'team-4'),
pairing(5, 1, 'team-1', 'team-2'),
pairing(5, 2, 'team-4', 'team-5'),
];
const input = explicitRoundRobinInput(pairings);
input.teams = Array.from({ length: 5 }, (_, index) => ({
teamId: `team-${index + 1}`,
displayOrder: index + 1,
seedNumber: index + 1,
}));
input.format.maxRounds = 10;
expect(generateSeriesGraph(input)).toHaveLength(10);
});
it.each([
{
name: 'an expected round',
pairings: [
pairing(1, 1, 'team-1', 'team-2'),
pairing(1, 2, 'team-3', 'team-4'),
],
},
{
name: 'a match from an expected round',
pairings: [
pairing(1, 1, 'team-1', 'team-2'),
pairing(1, 2, 'team-3', 'team-4'),
pairing(2, 1, 'team-1', 'team-3'),
],
},
])('rejects explicit pairings missing $name', ({ pairings }) => {
expectGraphError(
explicitRoundRobinInput(pairings),
'INCOMPLETE_ROUND_ROBIN_PAIRINGS',
);
});
});
function firstTo(winsRequired: number, maxGames: number) {
return { type: 'first-to' as const, winsRequired, maxGames };
}
function expectGraphError(input: GraphInput, code: string): void {
try {
generateSeriesGraph(input);
throw new Error(`Expected graph error ${code}.`);
} catch (error) {
expect(error).toMatchObject({ code });
}
}
function fixedGames(gameCount: number) {
return {
type: 'fixed-games' as const,
gameCount,
drawPolicy: 'allow' as const,
};
}
function pairing(
roundNumber: number,
matchNumber: number,
teamAId: string,
teamBId: string,
): ExplicitRoundRobinPairing {
return {
roundNumber,
matchNumber,
teamAId,
teamBId,
};
}
function explicitRoundRobinInput(
pairings: readonly ExplicitRoundRobinPairing[],
): ExplicitRoundRobinGraphInput {
return {
competitionId: 'competition-explicit-round-robin-validation',
teams: Array.from({ length: 4 }, (_, index) => ({
teamId: `team-${index + 1}`,
displayOrder: index + 1,
seedNumber: index + 1,
})),
format: {
type: 'round-robin',
rule: fixedGames(1),
maxRounds: 2,
tieBreakers: ['series-wins', 'game-diff', 'head-to-head'],
pairings,
},
};
}
function roundRobinSeries(
code: string,
roundNumber: number,
displayOrder: number,
teamAId: string,
teamBId: string,
) {
return {
code,
roundNumber,
displayOrder,
sources: [
{ type: 'team', teamId: teamAId },
{ type: 'team', teamId: teamBId },
],
};
}
@@ -68,6 +68,13 @@ export interface CompetitionGraphTeam {
seedNumber?: number;
}
export interface RoundRobinPairing {
roundNumber: number;
matchNumber: number;
teamAId: string;
teamBId: string;
}
export type CompetitionGraphFormat =
| {
type: 'paired-series';
@@ -77,6 +84,7 @@ export type CompetitionGraphFormat =
type: 'round-robin';
rule: FixedGamesSeriesRule;
maxRounds?: number;
pairings?: readonly RoundRobinPairing[];
tieBreakers: readonly ['series-wins', 'game-diff', 'head-to-head'];
}
| {
@@ -116,7 +124,7 @@ type TemplateParticipantSource =
}
| { type: 'series-slot'; seriesCode: string; slot: SeriesSlot };
interface RoundRobinPairing {
interface CanonicalRoundRobinPairing {
roundNumber: number;
teamAIndex: number;
teamBIndex: number;
@@ -143,12 +151,7 @@ export function generateSeriesGraph(
);
break;
case 'round-robin':
graph = generateRoundRobinGraph(
input.competitionId,
teams,
input.format.rule,
input.format.maxRounds,
);
graph = generateRoundRobinGraph(input.competitionId, teams, input.format);
break;
case 'double-elimination':
graph = generateDoubleEliminationGraph(
@@ -200,10 +203,9 @@ function generatePairedSeriesGraph(
function generateRoundRobinGraph(
competitionId: string,
teams: CompetitionGraphTeam[],
rule: FixedGamesSeriesRule,
maxRounds?: number,
format: Extract<CompetitionGraphFormat, { type: 'round-robin' }>,
): SeriesDefinition[] {
assertFixedGamesRule(rule);
assertFixedGamesRule(format.rule);
if (teams.length < 2) {
throw graphError(
'INVALID_ROUND_ROBIN_TEAM_COUNT',
@@ -211,13 +213,16 @@ function generateRoundRobinGraph(
);
}
const pairings = roundRobinPairings(teams.length, maxRounds);
const matchNumberByRound = new Map<number, number>();
const pairings = format.pairings
? validateExplicitRoundRobinPairings(
teams,
format.pairings,
format.maxRounds,
)
: canonicalRoundRobinPairings(teams, format.maxRounds);
return pairings.map((pairing, index) => {
const matchNumber = (matchNumberByRound.get(pairing.roundNumber) ?? 0) + 1;
matchNumberByRound.set(pairing.roundNumber, matchNumber);
const code = `RR_R${pairing.roundNumber}_M${matchNumber}`;
const code = `RR_R${pairing.roundNumber}_M${pairing.matchNumber}`;
return createSeriesDefinition({
competitionId,
code,
@@ -225,14 +230,139 @@ function generateRoundRobinGraph(
roundNumber: pairing.roundNumber,
displayOrder: index + 1,
sources: [
{ type: 'team', teamId: teams[pairing.teamAIndex].teamId },
{ type: 'team', teamId: teams[pairing.teamBIndex].teamId },
{ type: 'team', teamId: pairing.teamAId },
{ type: 'team', teamId: pairing.teamBId },
],
rule,
rule: format.rule,
});
});
}
function canonicalRoundRobinPairings(
teams: CompetitionGraphTeam[],
maxRounds?: number,
): RoundRobinPairing[] {
const matchNumberByRound = new Map<number, number>();
return roundRobinPairings(teams.length, maxRounds).map((pairing) => {
const matchNumber = (matchNumberByRound.get(pairing.roundNumber) ?? 0) + 1;
matchNumberByRound.set(pairing.roundNumber, matchNumber);
return {
roundNumber: pairing.roundNumber,
matchNumber,
teamAId: teams[pairing.teamAIndex].teamId,
teamBId: teams[pairing.teamBIndex].teamId,
};
});
}
function validateExplicitRoundRobinPairings(
teams: CompetitionGraphTeam[],
pairings: readonly RoundRobinPairing[],
maxRounds?: number,
): RoundRobinPairing[] {
if (pairings.length === 0) {
throw graphError(
'INVALID_ROUND_ROBIN_PAIRING',
'Explicit round-robin pairings cannot be empty.',
);
}
const teamIds = new Set(teams.map(({ teamId }) => teamId));
const positions = new Set<string>();
const opponentPairs = new Set<string>();
const teamsByRound = new Map<number, Set<string>>();
const sorted = pairings
.map((pairing) => ({ ...pairing }))
.sort(
(left, right) =>
left.roundNumber - right.roundNumber ||
left.matchNumber - right.matchNumber,
);
for (const pairing of sorted) {
if (
!Number.isInteger(pairing.roundNumber) ||
pairing.roundNumber < 1 ||
!Number.isInteger(pairing.matchNumber) ||
pairing.matchNumber < 1 ||
(maxRounds !== undefined && pairing.roundNumber > maxRounds) ||
!teamIds.has(pairing.teamAId) ||
!teamIds.has(pairing.teamBId) ||
pairing.teamAId === pairing.teamBId
) {
throw graphError(
'INVALID_ROUND_ROBIN_PAIRING',
'Every explicit round-robin pairing needs a valid position and two known, distinct teams.',
);
}
const position = `${pairing.roundNumber}:${pairing.matchNumber}`;
if (positions.has(position)) {
throw graphError(
'DUPLICATE_ROUND_ROBIN_PAIRING_POSITION',
`Round-robin pairing position ${position} occurs more than once.`,
);
}
positions.add(position);
const opponents = JSON.stringify([pairing.teamAId, pairing.teamBId].sort());
if (opponentPairs.has(opponents)) {
throw graphError(
'DUPLICATE_ROUND_ROBIN_OPPONENTS',
'A round-robin opponent pair occurs more than once.',
);
}
opponentPairs.add(opponents);
const roundTeams = teamsByRound.get(pairing.roundNumber) ?? new Set();
if (roundTeams.has(pairing.teamAId) || roundTeams.has(pairing.teamBId)) {
throw graphError(
'INVALID_ROUND_ROBIN_PAIRING',
'A team cannot appear in multiple Series in the same round.',
);
}
roundTeams.add(pairing.teamAId);
roundTeams.add(pairing.teamBId);
teamsByRound.set(pairing.roundNumber, roundTeams);
}
for (const roundNumber of new Set(
sorted.map((pairing) => pairing.roundNumber),
)) {
const matches = sorted.filter(
(pairing) => pairing.roundNumber === roundNumber,
);
if (matches.some((pairing, index) => pairing.matchNumber !== index + 1)) {
throw graphError(
'INVALID_ROUND_ROBIN_PAIRING',
`Round ${roundNumber} match numbers must be contiguous from one.`,
);
}
}
const expectedRoundCount = roundRobinRoundCount(teams.length, maxRounds);
const expectedMatchesPerRound = Math.floor(teams.length / 2);
for (
let roundNumber = 1;
roundNumber <= expectedRoundCount;
roundNumber += 1
) {
const matchCount = (teamsByRound.get(roundNumber)?.size ?? 0) / 2;
if (matchCount !== expectedMatchesPerRound) {
throw graphError(
'INCOMPLETE_ROUND_ROBIN_PAIRINGS',
`Round ${roundNumber} must contain ${expectedMatchesPerRound} Series.`,
);
}
}
if (teamsByRound.size !== expectedRoundCount) {
throw graphError(
'INCOMPLETE_ROUND_ROBIN_PAIRINGS',
`Explicit round-robin pairings must contain rounds 1 through ${expectedRoundCount}.`,
);
}
return sorted;
}
function generateDoubleEliminationGraph(
competitionId: string,
teams: CompetitionGraphTeam[],
@@ -436,20 +566,13 @@ function ruleForStage(
function roundRobinPairings(
teamCount: number,
maxRounds?: number,
): RoundRobinPairing[] {
): CanonicalRoundRobinPairing[] {
const bye = -1;
const rotating = Array.from({ length: teamCount }, (_, index) => index);
if (rotating.length % 2 === 1) rotating.push(bye);
const fullRoundCount = rotating.length - 1;
const requestedRounds =
maxRounds === undefined
? fullRoundCount
: Number.isFinite(maxRounds)
? Math.floor(maxRounds)
: fullRoundCount;
const roundCount = Math.max(0, Math.min(fullRoundCount, requestedRounds));
const pairings: RoundRobinPairing[] = [];
const roundCount = roundRobinRoundCount(teamCount, maxRounds);
const pairings: CanonicalRoundRobinPairing[] = [];
for (let roundIndex = 0; roundIndex < roundCount; roundIndex += 1) {
for (let index = 0; index < rotating.length / 2; index += 1) {
@@ -472,6 +595,17 @@ function roundRobinPairings(
return pairings;
}
function roundRobinRoundCount(teamCount: number, maxRounds?: number): number {
const fullRoundCount = teamCount % 2 === 0 ? teamCount - 1 : teamCount;
const requestedRounds =
maxRounds === undefined
? fullRoundCount
: Number.isFinite(maxRounds)
? Math.floor(maxRounds)
: fullRoundCount;
return Math.max(0, Math.min(fullRoundCount, requestedRounds));
}
function normalizeTeams(
teams: readonly CompetitionGraphTeam[],
): CompetitionGraphTeam[] {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -33,12 +33,73 @@ describe('migrateCompetitionDomain', () => {
factCount: 1,
assignmentCount: 1,
});
if (result.matches[0].status !== 'ready') {
throw new Error('Expected a ready dry-run result.');
}
expect(result.matches[0].planHash).toMatch(/^sha256:[a-f0-9]{64}$/);
const repeated = await migrateCompetitionDomain(db);
expect(repeated.matches[0]).toMatchObject({ status: 'ready' });
if (repeated.matches[0].status !== 'ready') {
throw new Error('Expected a repeated ready dry-run result.');
}
expect(repeated.matches[0].planHash).toBe(result.matches[0].planHash);
expect(startSession).not.toHaveBeenCalled();
expect(db.writeCount).toBe(0);
expect(db.docs('competition')).toHaveLength(0);
expect(db.createdIndexes).toHaveLength(0);
});
it('reports apply-time global identity conflicts during dry-run without writes', async () => {
const riotMatchId = 'KR_DRY_RUN_GLOBAL_CONFLICT';
const match = readyMatch(riotMatchId);
const conflictingFactId = objectId();
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [riotArchive(riotMatchId)],
tournamentCode: [usedTournamentCode(match, riotMatchId)],
competition_fact: [
{
_id: conflictingFactId,
competitionId: objectId(),
type: 'game-accepted',
evidence: { type: 'riot', riotMatchId },
},
],
});
const dryRun = await migrateCompetitionDomain(db);
expect(dryRun.summary).toMatchObject({
scanned: 1,
ready: 0,
applied: 0,
quarantined: 1,
failed: 0,
});
expect(dryRun.matches[0]).toMatchObject({ status: 'quarantined' });
if (dryRun.matches[0].status !== 'quarantined') {
throw new Error('Expected a quarantined dry-run result.');
}
const conflict = dryRun.matches[0].reasons.find(
({ code }) => code === 'GLOBAL_UNIQUE_INDEX_CONFLICT',
);
expect(conflict?.details?.collection).toBe('competition_fact');
expect(conflict?.details?.indexName).toBe('evidence.riotMatchId_1');
expect(conflict?.details?.conflictingDocumentId).toBe(
conflictingFactId.toHexString(),
);
expect(db.writeCount).toBe(0);
expect(db.createdIndexes).toHaveLength(0);
const applied = await migrateCompetitionDomain(db, {
dryRun: false,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(applied.summary).toMatchObject({ applied: 0, quarantined: 1 });
expect(applied.matches[0]).toEqual(dryRun.matches[0]);
});
it.each([
['absent', (match: AnyDoc) => delete match.gameMode],
['null', (match: AnyDoc) => (match.gameMode = null)],
@@ -157,6 +218,188 @@ describe('migrateCompetitionDomain', () => {
expect(sessions[1]).toMatchObject({ committed: 1, aborted: 0, ended: 1 });
});
it('persists the source voidedAt timestamp without synthesizing it from usedAt', async () => {
const match = readyMatch('KR_VOIDED_TIMESTAMP');
const code = usedTournamentCode(match, 'KR_VOIDED_TIMESTAMP');
code.state = 'voided';
code.voidedAt = new Date('2026-07-03T00:00:00.000Z');
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [riotArchive('KR_VOIDED_TIMESTAMP')],
tournamentCode: [code],
});
const result = await migrateCompetitionDomain(db, {
dryRun: false,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(result.summary).toMatchObject({ applied: 1, failed: 0 });
expect(db.docs('tournament_code_assignment')).toContainEqual(
expect.objectContaining({
state: 'voided',
voidedAt: new Date('2026-07-03T00:00:00.000Z'),
updatedAt: new Date('2026-07-03T00:00:00.000Z'),
}),
);
});
it('hydrates Riot occurrence evidence and persists the normalized used transition idempotently', async () => {
const riotMatchId = 'KR_LEGACY_USED_TRANSITION';
const match = readyMatch(riotMatchId);
match.updatedAt = new Date('2026-07-03T00:06:00.000Z');
const legacyOccurrenceAt = new Date(1_782_864_000_000 + 1800 * 1000);
const code = usedTournamentCode(match, riotMatchId);
code.reservedAt = new Date('2026-07-03T00:00:00.000Z');
code.usedAt = legacyOccurrenceAt;
code.updatedAt = new Date('2026-07-03T00:05:00.000Z');
const originalCode = canonical(code);
const archive = riotArchive(riotMatchId);
archive.raw = {
info: {
gameCreation: 1_782_864_000_000,
gameEndTimestamp: legacyOccurrenceAt.getTime(),
},
};
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [archive],
tournamentCode: [code],
});
const dryRun = await migrateCompetitionDomain(db);
expect(dryRun.summary).toMatchObject({
ready: 1,
quarantined: 0,
warnings: 1,
});
const warning = dryRun.matches[0].warnings.find(
({ code: warningCode }) =>
warningCode === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED',
);
expect(warning?.details).toMatchObject({
originalReservedAt: '2026-07-03T00:00:00.000Z',
originalUsedAt: legacyOccurrenceAt.toISOString(),
sourceUpdatedAt: '2026-07-03T00:05:00.000Z',
normalizedUsedAt: '2026-07-03T00:05:00.000Z',
legacyOccurrenceSource: 'riot-archive-gameEndTimestamp',
riotMatchId,
strategy: 'use-persisted-transition-time',
});
expect(db.writeCount).toBe(0);
const firstApply = await migrateCompetitionDomain(db, {
dryRun: false,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(firstApply.summary).toMatchObject({ applied: 1, failed: 0 });
expect(db.docs('tournament_code_assignment')).toContainEqual(
expect.objectContaining({
state: 'used',
reservedAt: new Date('2026-07-03T00:00:00.000Z'),
usedAt: new Date('2026-07-03T00:05:00.000Z'),
createdAt: new Date('2026-07-03T00:00:00.000Z'),
updatedAt: new Date('2026-07-03T00:05:00.000Z'),
}),
);
expect(canonical(db.docs('tournamentCode')[0])).toBe(originalCode);
const replay = await migrateCompetitionDomain(db, {
dryRun: false,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(replay.summary).toMatchObject({
applied: 0,
alreadyApplied: 1,
failed: 0,
});
});
it.each([
[
'raw.info.gameCreation',
{ raw: { info: { gameCreation: 1_782_864_000_000 } } },
],
[
'top-level gameCreation',
{
gameCreation: 1_782_864_000_000,
raw: { metadata: { matchId: 'KR_GAME_CREATION_FALLBACK' } },
},
],
])(
'hydrates the %s Riot occurrence fallback',
async (_label, archiveFields) => {
const riotMatchId = 'KR_GAME_CREATION_FALLBACK';
const match = readyMatch(riotMatchId);
const code = usedTournamentCode(match, riotMatchId);
code.reservedAt = new Date('2026-07-01T00:10:00.000Z');
code.usedAt = new Date('2026-07-01T00:00:00.000Z');
code.updatedAt = new Date('2026-07-01T00:20:00.000Z');
const archive = Object.assign(riotArchive(riotMatchId), archiveFields);
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [archive],
tournamentCode: [code],
});
const result = await migrateCompetitionDomain(db);
expect(result.summary).toMatchObject({ ready: 1, quarantined: 0 });
const warning = result.matches[0].warnings.find(
({ code: warningCode }) =>
warningCode === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED',
);
expect(warning?.details).toMatchObject({
originalUsedAt: '2026-07-01T00:00:00.000Z',
normalizedUsedAt: '2026-07-01T00:20:00.000Z',
legacyOccurrenceSource: 'riot-archive-gameCreation',
});
},
);
it.each([
['null', null],
['blank', ''],
['invalid', 'not-a-date'],
])(
'falls back to archive gameCreation when gameEndTimestamp is %s',
async (_label, invalidGameEnd) => {
const riotMatchId = 'KR_INVALID_ARCHIVE_GAME_END';
const match = readyMatch(riotMatchId);
const code = usedTournamentCode(match, riotMatchId);
code.reservedAt = new Date('2026-07-01T00:10:00.000Z');
code.usedAt = new Date('2026-07-01T00:00:00.000Z');
code.updatedAt = new Date('2026-07-01T00:20:00.000Z');
const archive = riotArchive(riotMatchId);
archive.raw = {
info: {
gameEndTimestamp: invalidGameEnd,
gameCreation: 1_782_864_000_000,
},
};
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [archive],
tournamentCode: [code],
});
const result = await migrateCompetitionDomain(db);
expect(result.summary).toMatchObject({ ready: 1, quarantined: 0 });
const warning = result.matches[0].warnings.find(
({ code: warningCode }) =>
warningCode === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED',
);
expect(warning?.details).toMatchObject({
legacyOccurrenceSource: 'riot-archive-gameCreation',
});
},
);
it('quarantines an ambiguous Match without changing any legacy Match field', async () => {
const match = ambiguousMatch();
const before = canonical(match);
@@ -364,6 +607,46 @@ describe('migrateCompetitionDomain', () => {
expect(db.docs('competition_migration_quarantine')).toHaveLength(1);
});
it('detects the same global identity collision between dry-run plans as sequential apply', async () => {
const riotMatchId = 'KR_SHARED_DRY_RUN_MIGRATION';
const firstMatch = readyMatch(riotMatchId);
const secondMatch = readyMatch(riotMatchId);
const db = new MemoryMigrationDb({
match: [firstMatch, secondMatch],
riotMatch: [riotArchive(riotMatchId)],
tournamentCode: [
usedTournamentCode(firstMatch, riotMatchId),
usedTournamentCode(secondMatch, riotMatchId),
],
});
const dryRun = await migrateCompetitionDomain(db);
expect(dryRun.summary).toMatchObject({ ready: 1, quarantined: 1 });
expect(dryRun.matches.map(({ status }) => status)).toEqual([
'ready',
'quarantined',
]);
expect(dryRun.matches[1]).toMatchObject({ status: 'quarantined' });
if (dryRun.matches[1].status !== 'quarantined') {
throw new Error('Expected the second dry-run result to be quarantined.');
}
expect(
dryRun.matches[1].reasons.some(
({ code }) => code === 'GLOBAL_UNIQUE_INDEX_CONFLICT',
),
).toBe(true);
expect(db.writeCount).toBe(0);
const applied = await migrateCompetitionDomain(db, {
dryRun: false,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(applied.summary).toMatchObject({ applied: 1, quarantined: 1 });
expect(applied.matches[1]).toEqual(dryRun.matches[1]);
});
it('resumes repeated limited apply runs after the durable Match checkpoint', async () => {
const firstMatch = readyMatch('KR_BATCH_1');
const secondMatch = readyMatch('KR_BATCH_2');
@@ -98,6 +98,7 @@ export type CompetitionDomainMigrationMatchResult =
status: 'ready' | 'applied';
factCount: number;
assignmentCount: number;
planHash: string;
})
| (CompetitionDomainMigrationMatchBase & {
status: 'already-applied';
@@ -206,11 +207,17 @@ export async function migrateCompetitionDomain(
resumeStart.startedAfterMatchId,
);
const matches: CompetitionDomainMigrationMatchResult[] = [];
const dryRunUniquenessClaims = new Map<string, ClaimedUniqueIdentity>();
let checkpointAfterMatchId = resumeStart.startedAfterMatchId;
let haltedOnFailure = false;
for (const [index, scannedMatch] of scan.matches.entries()) {
const result = dryRun
? await inspectMatch(db, scannedMatch, migrationRunId)
? await inspectMatch(
db,
scannedMatch,
migrationRunId,
dryRunUniquenessClaims,
)
: await applyMatch(db, scannedMatch, migrationRunId, options);
matches.push(result);
options.onProgress?.({
@@ -433,6 +440,7 @@ async function inspectMatch(
db: CompetitionDomainMigrationDb,
scannedMatch: AnyDocument,
migrationRunId: string,
uniquenessClaims: Map<string, ClaimedUniqueIdentity>,
): Promise<CompetitionDomainMigrationMatchResult> {
const matchId = idString(scannedMatch._id);
try {
@@ -450,6 +458,21 @@ async function inspectMatch(
const legacy = await hydrateLegacyMatch(db, scannedMatch);
const plan = planCompetitionMigration(legacy, { migrationRunId });
if (plan.status === 'ready') {
const uniquenessConflicts = await findReadyPlanUniquenessConflicts(
db,
plan,
{ claims: uniquenessClaims },
);
if (uniquenessConflicts.length > 0) {
return {
status: 'quarantined',
matchId,
warnings: plan.warnings,
reasons: uniquenessConflicts,
};
}
}
return planResult(matchId, plan);
} catch (error) {
return failedResult(matchId, error);
@@ -521,7 +544,7 @@ async function applyMatch(
const uniquenessConflicts = await findReadyPlanUniquenessConflicts(
db,
plan,
session,
{ session },
);
if (uniquenessConflicts.length > 0) {
await persistQuarantine(
@@ -577,6 +600,7 @@ async function applyMatch(
competitionId,
factCount: plan.facts.length,
assignmentCount: plan.assignments.length,
planHash: readyPlanHash(plan),
warnings: plan.warnings,
};
} catch (error) {
@@ -592,12 +616,21 @@ interface UniqueIdentityCheck {
indexName: string;
filter: Record<string, unknown>;
expectedDocumentId: string;
expectedCompetitionId?: string;
}
interface ClaimedUniqueIdentity {
documentId: string;
competitionId?: string;
}
async function findReadyPlanUniquenessConflicts(
db: CompetitionDomainMigrationDb,
plan: ReadyCompetitionMigrationPlan,
session: CompetitionDomainMigrationSession,
options: {
session?: CompetitionDomainMigrationSession;
claims?: Map<string, ClaimedUniqueIdentity>;
} = {},
): Promise<CompetitionMigrationIssue[]> {
const checks: UniqueIdentityCheck[] = [
{
@@ -619,6 +652,7 @@ async function findReadyPlanUniquenessConflicts(
ordinalWithinRevision: fact.ordinalWithinRevision,
},
expectedDocumentId: fact.id,
expectedCompetitionId: fact.competitionId,
},
{
collection: 'competition_fact',
@@ -629,6 +663,7 @@ async function findReadyPlanUniquenessConflicts(
ordinalWithinRevision: fact.ordinalWithinRevision,
},
expectedDocumentId: fact.id,
expectedCompetitionId: fact.competitionId,
},
);
if (fact.type === 'game-accepted' && fact.evidence.type === 'riot') {
@@ -640,6 +675,7 @@ async function findReadyPlanUniquenessConflicts(
'evidence.riotMatchId': fact.evidence.riotMatchId,
},
expectedDocumentId: fact.id,
expectedCompetitionId: fact.competitionId,
});
}
}
@@ -655,6 +691,7 @@ async function findReadyPlanUniquenessConflicts(
state: { $in: ['reserved', 'used'] },
},
expectedDocumentId: assignment.id,
expectedCompetitionId: assignment.competitionId,
},
{
collection: 'tournament_code_assignment',
@@ -664,6 +701,7 @@ async function findReadyPlanUniquenessConflicts(
state: { $in: ['reserved', 'used'] },
},
expectedDocumentId: assignment.id,
expectedCompetitionId: assignment.competitionId,
},
);
}
@@ -673,6 +711,7 @@ async function findReadyPlanUniquenessConflicts(
indexName: 'riotMatchId_1',
filter: { riotMatchId: assignment.riotMatchId },
expectedDocumentId: assignment.id,
expectedCompetitionId: assignment.competitionId,
});
}
}
@@ -680,30 +719,66 @@ async function findReadyPlanUniquenessConflicts(
const conflicts: CompetitionMigrationIssue[] = [];
// Mongo sessions do not support parallel operations inside one transaction.
for (const check of checks) {
const claim = options.claims?.get(uniqueIdentityKey(check));
if (claim && claim.documentId !== check.expectedDocumentId) {
conflicts.push(
uniqueIdentityConflict(check, {
_id: persistenceId(claim.documentId),
...(claim.competitionId
? { competitionId: persistenceId(claim.competitionId) }
: {}),
}),
);
continue;
}
const existing = await db
.collection(check.collection)
.findOne(check.filter, { session });
.findOne(
check.filter,
options.session ? { session: options.session } : undefined,
);
if (!existing || idString(existing._id) === check.expectedDocumentId) {
continue;
}
conflicts.push({
code: 'GLOBAL_UNIQUE_INDEX_CONFLICT',
message: `Migration input conflicts with ${check.collection}.${check.indexName}.`,
details: {
collection: check.collection,
indexName: check.indexName,
key: canonicalValue(check.filter) as Record<string, unknown>,
expectedDocumentId: check.expectedDocumentId,
conflictingDocumentId: idString(existing._id),
...(existing.competitionId
? { conflictingCompetitionId: idString(existing.competitionId) }
conflicts.push(uniqueIdentityConflict(check, existing));
}
if (conflicts.length === 0 && options.claims) {
for (const check of checks) {
options.claims.set(uniqueIdentityKey(check), {
documentId: check.expectedDocumentId,
...(check.expectedCompetitionId
? { competitionId: check.expectedCompetitionId }
: {}),
},
});
});
}
}
return conflicts;
}
function uniqueIdentityKey(check: UniqueIdentityCheck): string {
return `${check.collection}:${check.indexName}:${canonicalJson(check.filter)}`;
}
function uniqueIdentityConflict(
check: UniqueIdentityCheck,
existing: AnyDocument,
): CompetitionMigrationIssue {
return {
code: 'GLOBAL_UNIQUE_INDEX_CONFLICT',
message: `Migration input conflicts with ${check.collection}.${check.indexName}.`,
details: {
collection: check.collection,
indexName: check.indexName,
key: canonicalValue(check.filter) as Record<string, unknown>,
expectedDocumentId: check.expectedDocumentId,
conflictingDocumentId: idString(existing._id),
...(existing.competitionId
? { conflictingCompetitionId: idString(existing.competitionId) }
: {}),
},
};
}
async function hydrateLegacyMatch(
db: CompetitionDomainMigrationDb,
match: AnyDocument,
@@ -781,15 +856,67 @@ function hydrateLegacyGameEvidence(
typeof game.payloadHash === 'string' && game.payloadHash.trim().length > 0
? game.payloadHash
: undefined;
const archiveRaw = isRecord(archive.raw) ? archive.raw : undefined;
const archiveInfo = isRecord(archiveRaw?.info) ? archiveRaw.info : undefined;
const riotGameEndEvidence = resolveRiotGameEndEvidence(
archiveInfo,
archive.gameCreation,
);
return {
...game,
riotArchivePresent: true,
...(riotGameEndEvidence === undefined
? {}
: {
riotGameEndedAt: riotGameEndEvidence.value,
riotGameEndedAtSource: riotGameEndEvidence.source,
}),
payloadHash:
existingPayloadHash ??
`sha256:${createNodeHash(canonicalJson(archive.raw ?? archive))}`,
};
}
function resolveRiotGameEndEvidence(
archiveInfo: Record<string, unknown> | undefined,
archiveGameCreation: unknown,
):
| {
value: unknown;
source: 'gameEndTimestamp' | 'gameCreation';
}
| undefined {
const candidates = [
{
value: archiveInfo?.gameEndTimestamp,
source: 'gameEndTimestamp' as const,
},
{
value: archiveInfo?.gameCreation,
source: 'gameCreation' as const,
},
{ value: archiveGameCreation, source: 'gameCreation' as const },
];
return candidates.find(({ value }) => isValidRiotTimestamp(value));
}
function isValidRiotTimestamp(value: unknown): boolean {
if (value === undefined || value === null || value === '') return false;
if (typeof value === 'string' && value.trim() === '') return false;
if (typeof value === 'number' && !Number.isFinite(value)) return false;
const normalized =
typeof value === 'number' && value < 10_000_000_000 ? value * 1000 : value;
try {
const date =
normalized instanceof Date
? normalized
: new Date(normalized as string | number);
return !Number.isNaN(date.getTime());
} catch {
return false;
}
}
async function upsertReadyPlan(
db: CompetitionDomainMigrationDb,
plan: ReadyCompetitionMigrationPlan,
@@ -1085,12 +1212,18 @@ function assignmentForPersistence(
): AnyDocument {
const reservedAt = new Date(assignment.reservedAt);
const updatedAt = new Date(
assignment.releasedAt ?? assignment.usedAt ?? assignment.reservedAt,
assignment.voidedAt ??
assignment.releasedAt ??
assignment.usedAt ??
assignment.reservedAt,
);
const voidedAt =
assignment.state === 'voided'
? new Date(
assignment.releasedAt ?? assignment.usedAt ?? assignment.reservedAt,
assignment.voidedAt ??
assignment.releasedAt ??
assignment.usedAt ??
assignment.reservedAt,
)
: undefined;
return {
@@ -1138,10 +1271,23 @@ function planResult(
competitionId: plan.competition.id,
factCount: plan.facts.length,
assignmentCount: plan.assignments.length,
planHash: readyPlanHash(plan),
warnings: plan.warnings,
};
}
function readyPlanHash(plan: ReadyCompetitionMigrationPlan): string {
return `sha256:${createHash('sha256')
.update(
canonicalJson({
competition: plan.competition,
facts: plan.facts,
assignments: plan.assignments,
}),
)
.digest('hex')}`;
}
function failedResult(
matchId: string,
error: unknown,
@@ -940,6 +940,21 @@ export interface MatchStatsSkillBuildEvent {
levelUpType?: string;
}
export interface MatchStatsCheckpoint {
timestamp: number;
gold: number;
cs: number;
xp: number;
kills: number;
deaths: number;
assists: number;
}
export interface MatchStatsParticipantCheckpoints {
at10?: MatchStatsCheckpoint;
at15?: MatchStatsCheckpoint;
}
export interface MatchStatsRecord {
matchId: string;
title: string;
@@ -948,6 +963,8 @@ export interface MatchStatsRecord {
riotMatchId: string;
gameCreation: number;
gameDuration: number;
participantId?: number;
checkpoints?: MatchStatsParticipantCheckpoints;
userId: string;
summonerName: string;
tagLine: string;
@@ -994,6 +1011,7 @@ export interface MatchStatsGameDetail {
timeline: MatchStatsTimelinePoint[];
timelineLoaded?: boolean;
objectiveEvents: MatchStatsObjectiveEvent[];
timelineEvents?: MatchStatsTimelineEvent[];
teams: Array<{
teamIndex: number;
side: TeamSide;
@@ -1021,6 +1039,28 @@ export interface MatchStatsObjectiveEvent {
monsterSubType?: string;
}
export interface MatchStatsChampionKillEvent {
timestamp: number;
side?: TeamSide;
type: 'championKill';
killerParticipantId?: number;
victimParticipantId?: number;
assistingParticipantIds?: number[];
}
export interface MatchStatsBuildingEvent {
timestamp: number;
side: TeamSide;
type: 'tower' | 'inhibitor';
killerParticipantId?: number;
towerType?: string;
}
export type MatchStatsTimelineEvent =
| MatchStatsObjectiveEvent
| MatchStatsChampionKillEvent
| MatchStatsBuildingEvent;
export interface MatchStatsTimelinePoint {
timestamp: number;
blue: { gold: number; xp: number };
@@ -214,4 +214,52 @@ describe('RiotMatchService', () => {
levelUpType: 'NORMAL',
});
});
it('rejects non-numeric champion kill victim ids', async () => {
const payload = {
metadata: {
dataVersion: '2',
matchId: 'KR_8188913502',
participants: ['puuid-1'],
},
info: {
frameInterval: 60_000,
frames: [
{
timestamp: 60_000,
events: [
{
type: 'CHAMPION_KILL',
timestamp: 30_000,
killerId: 1,
victimId: '2',
},
],
participantFrames: {
'1': {
participantId: 1,
totalGold: 1_150,
xp: 550,
},
},
},
],
},
};
const riotClientService = {
get: jest.fn(
<T>(_path: string, _options: unknown, parser?: RiotResponseParser<T>) =>
Promise.resolve().then(() =>
parser ? parser(payload) : (payload as T),
),
),
} as unknown as RiotClientService;
const service = new RiotMatchService(riotClientService);
await expect(
service.getMatchTimeline('KR_8188913502', { region: 'asia' }),
).rejects.toThrow(
'timeline.info.frames[0].events[0].victimId must be a finite number when present.',
);
});
});
@@ -415,6 +415,10 @@ function parseTimelineEvent(
value.type,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].type`,
),
victimId: optionalNumber(
value.victimId,
`timeline.info.frames[${frameIndex}].events[${eventIndex}].victimId`,
),
};
}
+1
View File
@@ -291,6 +291,7 @@ export interface RiotMatchTimelineEventDto extends Record<string, unknown> {
skillSlot?: number;
teamId?: number;
towerType?: string;
victimId?: number;
}
export interface RiotMatchTimelineParticipantFrameDto
+39
View File
@@ -701,6 +701,24 @@ export interface ApiInternalMatchDetailResponse {
type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub';
monsterSubType?: string;
}>;
timelineEvents?: Array<{
timestamp: number;
side?: TeamSide;
type:
| 'dragon'
| 'elderDragon'
| 'baron'
| 'riftHerald'
| 'voidGrub'
| 'championKill'
| 'tower'
| 'inhibitor';
monsterSubType?: string;
killerParticipantId?: number;
victimParticipantId?: number;
assistingParticipantIds?: number[];
towerType?: string;
}>;
teams: Array<{
teamIndex: number;
side: TeamSide;
@@ -716,6 +734,27 @@ export interface ApiInternalMatchDetailResponse {
};
bans: Array<{ championId: number; pickTurn: number }>;
participants: Array<{
participantId?: number;
checkpoints?: {
at10?: {
timestamp: number;
gold: number;
cs: number;
xp: number;
kills: number;
deaths: number;
assists: number;
};
at15?: {
timestamp: number;
gold: number;
cs: number;
xp: number;
kills: number;
deaths: number;
assists: number;
};
};
userId: string | null;
summonerName: string;
tagLine: string;
@@ -6,6 +6,14 @@ import {
} from "../lib/ddragon";
import { teamIndexLabel } from "../lib/league";
import { LANE_LABELS } from "../lib/riot-history";
import {
DEFAULT_LANE_CHECKPOINT,
pairLaneParticipants,
resolveCheckpointComparison,
type LaneCheckpointKey,
type LaneParticipantLike,
type NormalizedLanePosition,
} from "../lib/internal-game-matchups";
import { ItemIcon, RuneIcon, RuneStyleIcon } from "./ItemTooltip";
export type InternalGameDetailTab = "scoreboard" | "matchup" | "build";
@@ -13,6 +21,7 @@ export type InternalGameDetailTab = "scoreboard" | "matchup" | "build";
type InternalGameDetail = ApiInternalMatchDetailResponse["games"][number];
type InternalGameTeam = InternalGameDetail["teams"][number];
type InternalGameParticipant = InternalGameTeam["participants"][number];
type CheckpointParticipant = InternalGameParticipant & LaneParticipantLike;
type DdragonManifestData = DdragonManifest | null | undefined;
type RuneStyleEntry = DdragonManifest["runesReforged"][number];
@@ -44,8 +53,6 @@ const STAT_PERK_LABELS: Record<number, string> = {
5011: "체력",
};
const LANE_SORT_ORDER = ["TOP", "JUNGLE", "MIDDLE", "BOTTOM", "UTILITY"];
function formatDuration(seconds: number) {
const minutes = Math.floor(seconds / 60);
const rest = seconds % 60;
@@ -56,6 +63,11 @@ function formatNumber(value: number) {
return new Intl.NumberFormat("ko-KR").format(value);
}
function formatSignedNumber(value: number) {
if (value === 0) return "0";
return `${value > 0 ? "+" : "-"}${formatNumber(Math.abs(value))}`;
}
function sideTone(side: TeamSide) {
return side === "blue"
? {
@@ -111,11 +123,6 @@ function runeStyleSelection(
return participant.perks.styles?.find((style) => style.styleId === styleId);
}
function laneSortValue(position: string) {
const index = LANE_SORT_ORDER.indexOf(position);
return index === -1 ? 99 : index;
}
function ChampionCell({
participant,
manifest,
@@ -648,12 +655,14 @@ function SkillBuildPanel({
function MatchupMetricRow({
label,
difference,
blueLead,
redLead,
blueText,
redText,
}: {
label: string;
difference?: string;
blueLead: boolean;
redLead: boolean;
blueText: string;
@@ -668,8 +677,13 @@ function MatchupMetricRow({
>
{blueText}
</span>
<span className="text-[10px] font-bold uppercase tracking-wider text-base-content/30">
{label}
<span className="min-w-16 text-center text-[10px] font-bold uppercase tracking-wider text-base-content/30">
<span className="block">{label}</span>
{difference ? (
<span className="mt-0.5 block normal-case text-base-content/50">
{difference}
</span>
) : null}
</span>
<span
className={`tabular-nums ${
@@ -682,101 +696,172 @@ function MatchupMetricRow({
);
}
function LaneMatchupCard({
blue,
red,
detail,
function checkpointKda(kills: number, deaths: number, assists: number) {
return deaths === 0 ? kills + assists : (kills + assists) / deaths;
}
function LaneParticipantIdentity({
participant,
manifest,
align,
ambiguous,
}: {
blue: InternalGameParticipant;
red: InternalGameParticipant;
detail: ApiInternalMatchDetailResponse;
participant: CheckpointParticipant | null;
manifest: DdragonManifestData;
align: "left" | "right";
ambiguous: boolean;
}) {
const laneLabel =
LANE_LABELS[blue.teamPosition] ??
LANE_LABELS[red.teamPosition] ??
blue.teamPosition ??
"-";
if (!participant) {
return (
<div
className={`min-w-0 text-[11px] font-bold text-base-content/30 ${
align === "right" ? "text-right" : "text-left"
}`}
>
{ambiguous ? "포지션 중복" : "선수 없음"}
</div>
);
}
const metrics = [
{
key: "kda",
label: "KDA",
blueValue:
blue.deaths === 0
? blue.kills + blue.assists
: (blue.kills + blue.assists) / blue.deaths,
redValue:
red.deaths === 0
? red.kills + red.assists
: (red.kills + red.assists) / red.deaths,
blueText: `${blue.kills}/${blue.deaths}/${blue.assists}`,
redText: `${red.kills}/${red.deaths}/${red.assists}`,
},
{
key: "gold",
label: "골드",
blueValue: blue.gold,
redValue: red.gold,
blueText: formatNumber(blue.gold),
redText: formatNumber(red.gold),
},
{
key: "cs",
label: "CS",
blueValue: blue.cs,
redValue: red.cs,
blueText: `${blue.cs} (${blue.csPerMin}/m)`,
redText: `${red.cs} (${red.csPerMin}/m)`,
},
];
const championName = (participant: InternalGameParticipant) =>
const championName =
championDisplayName(manifest, participant.championId) ??
String(participant.championId);
const details = (
<div className={`min-w-0 ${align === "right" ? "text-right" : ""}`}>
<div className="truncate text-xs font-bold text-base-content">
{participant.summonerName}
</div>
<div className="truncate text-[11px] text-base-content/40">
{championName}
</div>
</div>
);
return (
<div
className={`flex min-w-0 items-center gap-2 ${
align === "right" ? "justify-end" : ""
}`}
>
{align === "right" ? details : null}
<ChampionAvatar participant={participant} manifest={manifest} />
{align === "left" ? details : null}
</div>
);
}
function LaneMatchupCard({
position,
blue,
red,
ambiguousBlue,
ambiguousRed,
checkpointKey,
manifest,
}: {
position: NormalizedLanePosition;
blue: CheckpointParticipant | null;
red: CheckpointParticipant | null;
ambiguousBlue: boolean;
ambiguousRed: boolean;
checkpointKey: LaneCheckpointKey;
manifest: DdragonManifestData;
}) {
const laneLabel = LANE_LABELS[position] ?? position;
const comparison = resolveCheckpointComparison(blue, red, checkpointKey);
const metrics = comparison
? [
{
key: "gold",
label: "골드",
difference: `GD ${formatSignedNumber(comparison.goldDiff)}`,
blueValue: comparison.blue.gold,
redValue: comparison.red.gold,
blueText: formatNumber(comparison.blue.gold),
redText: formatNumber(comparison.red.gold),
},
{
key: "cs",
label: "CS",
difference: `CSD ${formatSignedNumber(comparison.csDiff)}`,
blueValue: comparison.blue.cs,
redValue: comparison.red.cs,
blueText: formatNumber(comparison.blue.cs),
redText: formatNumber(comparison.red.cs),
},
{
key: "xp",
label: "경험치",
difference: `XPD ${formatSignedNumber(comparison.xpDiff)}`,
blueValue: comparison.blue.xp,
redValue: comparison.red.xp,
blueText: formatNumber(comparison.blue.xp),
redText: formatNumber(comparison.red.xp),
},
{
key: "kda",
label: "K / D / A",
blueValue: checkpointKda(
comparison.blue.kills,
comparison.blue.deaths,
comparison.blue.assists,
),
redValue: checkpointKda(
comparison.red.kills,
comparison.red.deaths,
comparison.red.assists,
),
blueText: `${comparison.blue.kills}/${comparison.blue.deaths}/${comparison.blue.assists}`,
redText: `${comparison.red.kills}/${comparison.red.deaths}/${comparison.red.assists}`,
},
]
: [];
return (
<div className="overflow-hidden border border-base-content/10 bg-base-100">
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-2 border-b border-base-content/8 bg-base-content/[0.015] px-3 py-2">
<div className="flex min-w-0 items-center justify-end gap-2">
<div className="min-w-0 text-right">
<div className="truncate text-xs font-bold text-base-content">
{blue.summonerName}
</div>
<div className="truncate text-[11px] text-base-content/40">
{championName(blue)}
</div>
</div>
<ChampionAvatar participant={blue} manifest={manifest} />
</div>
<LaneParticipantIdentity
participant={blue}
manifest={manifest}
align="right"
ambiguous={ambiguousBlue}
/>
<span className="border border-base-content/10 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider text-base-content/45">
{laneLabel}
</span>
<div className="flex min-w-0 items-center gap-2">
<ChampionAvatar participant={red} manifest={manifest} />
<div className="min-w-0">
<div className="truncate text-xs font-bold text-base-content">
{red.summonerName}
</div>
<div className="truncate text-[11px] text-base-content/40">
{championName(red)}
</div>
<LaneParticipantIdentity
participant={red}
manifest={manifest}
align="left"
ambiguous={ambiguousRed}
/>
</div>
{comparison ? (
<>
<div className="divide-y divide-base-content/5">
{metrics.map((metric) => (
<MatchupMetricRow
key={`${position}-${checkpointKey}-${metric.key}`}
label={metric.label}
difference={metric.difference}
blueLead={metric.blueValue > metric.redValue}
redLead={metric.redValue > metric.blueValue}
blueText={metric.blueText}
redText={metric.redText}
/>
))}
</div>
<div className="border-t border-base-content/5 px-3 py-1.5 text-center text-[10px] font-bold text-base-content/30">
실제 기준 {formatDuration(comparison.blue.timestamp)} · {formatDuration(comparison.red.timestamp)}
</div>
</>
) : (
<div className="px-3 py-7 text-center text-xs font-bold text-base-content/35">
{ambiguousBlue || ambiguousRed
? "포지션이 중복되어 상대를 확정할 수 없습니다"
: "선택한 시점의 라인전 데이터가 없습니다"}
</div>
</div>
<div className="divide-y divide-base-content/5">
{metrics.map((metric) => (
<MatchupMetricRow
key={`${detail.match.matchId}-${blue.teamPosition}-${metric.key}`}
label={metric.label}
blueLead={metric.blueValue > metric.redValue}
redLead={metric.redValue > metric.blueValue}
blueText={metric.blueText}
redText={metric.redText}
/>
))}
</div>
)}
</div>
);
}
@@ -790,6 +875,8 @@ function LaneMatchupPanel({
detail: ApiInternalMatchDetailResponse;
manifest: DdragonManifestData;
}) {
const [checkpointKey, setCheckpointKey] =
useState<LaneCheckpointKey>(DEFAULT_LANE_CHECKPOINT);
const blueTeam = selectedGame.teams.find((team) => team.side === "blue");
const redTeam = selectedGame.teams.find((team) => team.side === "red");
@@ -801,40 +888,64 @@ function LaneMatchupPanel({
);
}
const blueSorted = [...blueTeam.participants].sort(
(left, right) =>
laneSortValue(left.teamPosition) - laneSortValue(right.teamPosition),
);
const redSorted = [...redTeam.participants].sort(
(left, right) =>
laneSortValue(left.teamPosition) - laneSortValue(right.teamPosition),
const matchups = pairLaneParticipants(
blueTeam.participants as CheckpointParticipant[],
redTeam.participants as CheckpointParticipant[],
);
const blueTeamName = getTeamName(detail, blueTeam.teamIndex);
const redTeamName = getTeamName(detail, redTeam.teamIndex);
return (
<section className="overflow-hidden border border-base-content/10 bg-base-100">
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-3 border-b border-base-content/8 px-4 py-3 text-xs font-bold">
<span className="truncate text-right text-blue-400">
{blueTeamName}
</span>
<span className="text-base-content/20">VS</span>
<span className="truncate text-red-400">{redTeamName}</span>
<div className="border-b border-base-content/8 px-4 py-3">
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-3 text-xs font-bold">
<span className="truncate text-right text-blue-400">
{blueTeamName}
</span>
<span className="text-base-content/20">VS</span>
<span className="truncate text-red-400">{redTeamName}</span>
</div>
<div
className="mx-auto mt-3 flex w-fit border border-base-content/10"
role="group"
aria-label="라인전 비교 시점"
>
{(["at10", "at15"] as const).map((key) => (
<button
key={key}
type="button"
aria-pressed={checkpointKey === key}
onClick={() => setCheckpointKey(key)}
className={`border-r border-base-content/8 px-4 py-1.5 text-xs font-black transition-colors last:border-r-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary ${
checkpointKey === key
? "bg-primary text-primary-content"
: "text-base-content/45 hover:bg-base-content/[0.03] hover:text-base-content"
}`}
>
{key === "at10" ? "10분" : "15분"}
</button>
))}
</div>
</div>
<div className="grid gap-3 p-4 lg:grid-cols-2">
{blueSorted.map((blue, index) => {
const red = redSorted[index];
if (!red) return null;
return (
{matchups.length > 0 ? (
matchups.map((matchup) => (
<LaneMatchupCard
key={`matchup-${blue.teamPosition}-${blue.summonerName}`}
blue={blue}
red={red}
detail={detail}
key={`matchup-${matchup.position}`}
position={matchup.position}
blue={matchup.blue}
red={matchup.red}
ambiguousBlue={matchup.ambiguousBlue}
ambiguousRed={matchup.ambiguousRed}
checkpointKey={checkpointKey}
manifest={manifest}
/>
);
})}
))
) : (
<div className="py-10 text-center text-sm font-bold text-base-content/35 lg:col-span-2">
비교 가능한 포지션 정보가 없습니다
</div>
)}
</div>
</section>
);
@@ -5,6 +5,9 @@ import type {
TeamId,
} from "@lolympus/contracts";
import { Link } from "react-router";
import { DoubleEliminationBracket } from "./DoubleEliminationBracket";
import { createCompetitionBracketLayout } from "./competition-display-layout";
import { bracketRoundLabel } from "./double-elimination-bracket-layout";
import { RoundRobinTable } from "./RoundRobinTable";
import { SeriesScoreCard } from "./SeriesScoreCard";
@@ -20,6 +23,7 @@ export function CompetitionResults({
const seriesById = new Map(
projection.series.map((series) => [series.seriesId, series]),
);
const doubleEliminationLayout = createCompetitionBracketLayout(competition);
return (
<section className="mb-6 space-y-4" aria-labelledby="competition-heading">
@@ -54,18 +58,20 @@ export function CompetitionResults({
)}
{projection.rounds.length > 0 ? (
<div className="overflow-x-auto pb-2">
<div className="grid min-w-max auto-cols-[17rem] grid-flow-col gap-4">
{projection.rounds.map((round) => (
<RoundColumn
key={`${round.stage}:${round.roundNumber ?? 0}`}
round={round}
seriesById={seriesById}
teamById={teamById}
/>
))}
</div>
</div>
projection.formatType === "double-elimination" &&
doubleEliminationLayout ? (
<DoubleEliminationBracket
projection={projection}
layout={doubleEliminationLayout}
teamById={teamById}
/>
) : (
<GenericRoundGrid
rounds={projection.rounds}
seriesById={seriesById}
teamById={teamById}
/>
)
) : (
<p
className="border border-dashed border-base-content/15 px-4 py-5 text-sm text-base-content/45"
@@ -101,6 +107,34 @@ export function CompetitionResults({
);
}
function GenericRoundGrid({
rounds,
seriesById,
teamById,
}: {
rounds: BracketRoundView[];
seriesById: Map<
string,
CompetitionDetailResponse["projection"]["series"][number]
>;
teamById: Map<TeamId, CompetitionDetailResponse["teams"][number]>;
}) {
return (
<div className="overflow-x-auto pb-2">
<div className="grid min-w-max auto-cols-[17rem] grid-flow-col gap-4">
{rounds.map((round) => (
<RoundColumn
key={`${round.stage}:${round.roundNumber ?? 0}`}
round={round}
seriesById={seriesById}
teamById={teamById}
/>
))}
</div>
</div>
);
}
function RoundColumn({
round,
seriesById,
@@ -116,7 +150,7 @@ function RoundColumn({
return (
<section aria-label={round.label} className="space-y-2">
<h3 className="px-1 text-xs font-bold text-base-content/45">
{stageLabel(round.stage, round.roundNumber)}
{bracketRoundLabel(round.stage, round.roundNumber)}
</h3>
<div className="space-y-3">
{round.seriesIds.map((seriesId) => {
@@ -166,20 +200,3 @@ function OutcomeSummary({
</p>
);
}
function stageLabel(stage: BracketRoundView["stage"], round?: number) {
switch (stage) {
case "pair":
return "대진";
case "round-robin":
return `${round ?? 1}라운드`;
case "upper":
return `승자조 ${round ?? 1}라운드`;
case "lower":
return `패자조 ${round ?? 1}라운드`;
case "grand-final":
return "그랜드 파이널";
case "reset-final":
return "리셋 파이널";
}
}
@@ -0,0 +1,282 @@
import type {
CompetitionTeamView,
DoubleEliminationCompetitionProjection,
TeamId,
} from "@lolympus/contracts";
import type {
BracketConnectorKind,
DoubleEliminationBracketLayout,
} from "./double-elimination-bracket-layout";
import { DOUBLE_ELIMINATION_BRACKET_GEOMETRY } from "./double-elimination-bracket-layout";
import { DoubleEliminationMobileBracket } from "./DoubleEliminationMobileBracket";
import { SeriesScoreCard } from "./SeriesScoreCard";
export function DoubleEliminationBracket({
projection,
layout,
teamById,
}: {
projection: DoubleEliminationCompetitionProjection;
layout: DoubleEliminationBracketLayout;
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
}) {
return (
<>
<DesktopBracket
projection={projection}
layout={layout}
teamById={teamById}
/>
<DoubleEliminationMobileBracket
projection={projection}
layout={layout}
teamById={teamById}
/>
</>
);
}
function DesktopBracket({
projection,
layout,
teamById,
}: {
projection: DoubleEliminationCompetitionProjection;
layout: DoubleEliminationBracketLayout;
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
}) {
const seriesById = new Map(
projection.series.map((series) => [series.seriesId, series]),
);
const nodeById = new Map(layout.nodes.map((node) => [node.seriesId, node]));
const finalNodes = layout.nodes.filter(({ lane }) => lane === "final");
const hasResetRoute = layout.connectors.some(({ kind }) => kind === "reset");
const finalZoneLeft = Math.max(
0,
Math.min(...finalNodes.map(({ x }) => x), layout.width) - 16,
);
return (
<div className="hidden xl:block">
<div className="mb-2 flex flex-wrap items-center justify-between gap-3 text-xs text-content-muted">
<p>
승자조와 패자조는 같은 시간축을 공유하며 오른쪽 결승에서 합류합니다.
<span className="ml-2 text-content-subtle">
화면에 모두 보이지 않으면 가로로 스크롤하세요.
</span>
</p>
<ConnectorLegend showReset={hasResetRoute} />
</div>
<div
className="overflow-x-auto border-y border-base-content/10 bg-base-100 pb-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary"
role="region"
aria-label="더블 엘리미네이션 대진표"
tabIndex={0}
>
<div
className="relative"
style={{ width: layout.width, height: layout.height }}
>
<LaneBand
label="승자조"
description="패배 시 패자조 이동"
top={layout.upperLane.top}
height={layout.upperLane.height}
width={layout.width}
/>
<LaneBand
label="패자조"
description="패배 시 탈락"
top={layout.lowerLane.top}
height={layout.lowerLane.height}
width={layout.width}
/>
{finalNodes.length > 0 && (
<div
className="absolute border-l border-primary/15 bg-primary/[0.025]"
style={{
left: finalZoneLeft,
top: 0,
width: layout.width - finalZoneLeft,
height: layout.height,
}}
aria-hidden="true"
/>
)}
<svg
className="pointer-events-none absolute inset-0 z-[1]"
width={layout.width}
height={layout.height}
viewBox={`0 0 ${layout.width} ${layout.height}`}
aria-hidden="true"
focusable="false"
>
{layout.connectors.map((connector) => (
<g
key={`${connector.fromSeriesId}:${connector.select}:${connector.toSeriesId}:${connector.toSlot}`}
className={connectorClass(connector.kind)}
>
<path
d={connector.path}
fill="none"
stroke="var(--color-base-100)"
strokeWidth="4"
strokeLinecap="round"
strokeLinejoin="round"
vectorEffect="non-scaling-stroke"
/>
<path
d={connector.path}
fill="none"
stroke="currentColor"
strokeWidth="1.25"
strokeDasharray={connectorDash(connector.kind)}
strokeLinecap="round"
strokeLinejoin="round"
vectorEffect="non-scaling-stroke"
/>
<circle
cx={connector.targetX}
cy={connector.targetY}
r="2.25"
fill="currentColor"
/>
</g>
))}
</svg>
{layout.rounds.map((round) => (
<section
key={`${round.stage}:${round.roundNumber}`}
aria-labelledby={`competition-round-${round.stage}-${round.roundNumber}`}
>
<h3
id={`competition-round-${round.stage}-${round.roundNumber}`}
className="absolute z-[2] truncate px-1 text-xs font-bold text-content-muted"
style={{
left: round.x,
top: round.labelY,
width: DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnWidth,
}}
>
{round.label}
</h3>
{round.seriesIds.map((seriesId) => {
const node = nodeById.get(seriesId);
const series = seriesById.get(seriesId);
if (!node || !series) return null;
const routes = layout.connectors.filter(
(connector) => connector.fromSeriesId === node.seriesId,
);
return (
<div
key={node.seriesId}
className="absolute z-[3]"
style={{
left: node.x,
top: node.y,
width: node.width,
minHeight: node.height,
}}
>
<SeriesScoreCard
series={series}
displayLabel={node.label}
teamById={teamById}
variant="bracket"
/>
{routes.length > 0 && (
<span className="sr-only">
{routes.map(({ label }) => label).join(". ")}
</span>
)}
</div>
);
})}
</section>
))}
</div>
</div>
</div>
);
}
function LaneBand({
label,
description,
top,
height,
width,
}: {
label: string;
description: string;
top: number;
height: number;
width: number;
}) {
return (
<>
<div
className="absolute border-y border-base-content/8 bg-base-content/[0.018]"
style={{ top: top - 6, width, height: height + 12 }}
aria-hidden="true"
/>
<p
className="absolute z-[2] flex items-center gap-2 text-[11px] font-bold uppercase tracking-wider text-content-muted"
style={{ left: 12, top: top - 57 }}
>
<span>{label}</span>
<span className="font-normal normal-case tracking-normal text-content-subtle">
{description}
</span>
</p>
</>
);
}
function ConnectorLegend({ showReset }: { showReset: boolean }) {
return (
<div className="flex flex-wrap items-center gap-4" aria-label="연결선 범례">
<LegendItem label="승자 진출" kind="winner" />
<LegendItem label="패자조 이동" kind="loser" />
{showReset && <LegendItem label="리셋 대진 유지" kind="reset" />}
</div>
);
}
function LegendItem({
label,
kind,
}: {
label: string;
kind: BracketConnectorKind;
}) {
return (
<span className="inline-flex items-center gap-1.5">
<svg width="24" height="6" aria-hidden="true">
<path
d="M 0 3 H 24"
fill="none"
stroke="currentColor"
strokeWidth="1.25"
strokeDasharray={connectorDash(kind)}
className={connectorClass(kind)}
/>
</svg>
{label}
</span>
);
}
function connectorClass(kind: BracketConnectorKind): string {
if (kind === "loser") return "text-warning/65";
if (kind === "reset") return "text-primary/55";
return "text-base-content/30";
}
function connectorDash(kind: BracketConnectorKind): string | undefined {
if (kind === "loser") return "6 5";
if (kind === "reset") return "2 5";
return undefined;
}
@@ -0,0 +1,121 @@
import type {
CompetitionTeamView,
DoubleEliminationCompetitionProjection,
SeriesId,
TeamId,
} from "@lolympus/contracts";
import type { DoubleEliminationBracketLayout } from "./double-elimination-bracket-layout";
import { SeriesScoreCard } from "./SeriesScoreCard";
export function DoubleEliminationMobileBracket({
projection,
layout,
teamById,
}: {
projection: DoubleEliminationCompetitionProjection;
layout: DoubleEliminationBracketLayout;
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
}) {
const seriesById = new Map(
projection.series.map((series) => [series.seriesId, series]),
);
const nodeById = new Map(layout.nodes.map((node) => [node.seriesId, node]));
const sections = [
{
key: "upper",
title: "승자조",
description: "승리하면 승자조에 남고, 패배하면 패자조로 이동합니다.",
stages: new Set(["upper"]),
},
{
key: "lower",
title: "패자조",
description: "승리하면 다음 라운드로 진출하고, 패배하면 탈락합니다.",
stages: new Set(["lower"]),
},
{
key: "final",
title: "결승",
description: "승자조 우승 팀과 패자조 우승 팀이 최종 우승을 결정합니다.",
stages: new Set(["grand-final", "reset-final"]),
},
];
return (
<div
className="space-y-7 xl:hidden"
role="region"
aria-label="더블 엘리미네이션 대진표"
>
{sections.map((section) => {
const groups = layout.mobileGroups.filter((group) =>
section.stages.has(group.stage),
);
if (groups.length === 0) return null;
return (
<section key={section.key} aria-labelledby={`bracket-${section.key}`}>
<div className="mb-3 border-b border-base-content/10 pb-2">
<h3 id={`bracket-${section.key}`} className="text-sm font-bold">
{section.title}
</h3>
<p className="mt-0.5 text-xs text-content-muted">
{section.description}
</p>
</div>
<div className="space-y-5">
{groups.map((group) => (
<section
key={`${group.stage}:${group.roundNumber}`}
aria-label={group.label}
>
<h4 className="mb-2 text-xs font-bold text-content-muted">
{group.label}
</h4>
<div className="space-y-3">
{group.seriesIds.map((seriesId) => {
const series = seriesById.get(seriesId);
if (!series) return null;
return (
<div key={seriesId}>
<SeriesScoreCard
series={series}
displayLabel={nodeById.get(seriesId)?.label}
teamById={teamById}
variant="bracket"
/>
<MobileRoutes layout={layout} seriesId={seriesId} />
</div>
);
})}
</div>
</section>
))}
</div>
</section>
);
})}
</div>
);
}
function MobileRoutes({
layout,
seriesId,
}: {
layout: DoubleEliminationBracketLayout;
seriesId: SeriesId;
}) {
const routes = layout.connectors.filter(
(connector) => connector.fromSeriesId === seriesId,
);
if (routes.length === 0) return null;
return (
<ul className="mt-1.5 space-y-0.5 border-l border-base-content/10 pl-2 text-[11px] text-content-muted">
{routes.map((route) => (
<li key={`${route.select}:${route.toSeriesId}:${route.toSlot}`}>
{route.label}
</li>
))}
</ul>
);
}
@@ -3,6 +3,8 @@ import type {
SeriesProjection,
TeamId,
} from "@lolympus/contracts";
import { SERIES_SCORE_CARD_GEOMETRY } from "./series-score-card-geometry";
import { isSeriesEntryWinner } from "./series-score-card-model";
const STATUS_LABEL: Record<SeriesProjection["status"], string> = {
inactive: "비활성",
@@ -14,24 +16,41 @@ const STATUS_LABEL: Record<SeriesProjection["status"], string> = {
export function SeriesScoreCard({
series,
displayLabel,
teamById,
variant = "default",
}: {
series: SeriesProjection;
displayLabel?: string;
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
variant?: "default" | "bracket";
}) {
const winnerTeamId =
series.status === "completed" && series.outcome.type !== "draw"
? series.outcome.winnerTeamId
: null;
const isBracket = variant === "bracket";
const seriesLabel = series.code ?? displayLabel;
return (
<article
className="border border-base-content/10 bg-base-100"
aria-label={`${series.code ?? "경기"} ${STATUS_LABEL[series.status]}`}
aria-label={`${seriesLabel ?? "경기"} ${STATUS_LABEL[series.status]}`}
style={
isBracket ? { height: SERIES_SCORE_CARD_GEOMETRY.height } : undefined
}
>
<header className="flex items-center justify-between gap-3 border-b border-base-content/8 px-3 py-2">
<span className="truncate text-xs font-bold text-base-content/65">
{series.code ?? "Series"}
<header
className={`flex items-center justify-between gap-3 border-b border-base-content/8 ${
isBracket ? "px-2" : "px-3 py-2"
}`}
style={
isBracket
? { height: SERIES_SCORE_CARD_GEOMETRY.headerHeight }
: undefined
}
>
<span
className="truncate text-xs font-bold text-base-content/65"
title={seriesLabel ?? "Series"}
>
{seriesLabel ?? "Series"}
</span>
<span className="shrink-0 text-[11px] text-base-content/40">
{STATUS_LABEL[series.status]}
@@ -40,36 +59,96 @@ export function SeriesScoreCard({
<div className="divide-y divide-base-content/8">
{series.entries.map((entry) => {
const team = entry.teamId ? teamById.get(entry.teamId) : undefined;
const isWinner = entry.teamId === winnerTeamId;
return (
<div
const isWinner = isSeriesEntryWinner(series, entry.teamId);
const teamName =
team?.name ?? (entry.teamId ? "알 수 없는 팀" : "대기 중");
return isBracket ? (
<BracketEntryRow
key={entry.slot}
className="grid grid-cols-[1.5rem_minmax(0,1fr)_2rem] items-center gap-2 px-3 py-2.5"
>
<span className="text-[10px] font-bold text-base-content/30">
{entry.slot}
</span>
<span
className={`truncate text-sm ${
isWinner
? "font-bold text-base-content"
: "text-base-content/60"
}`}
>
{team?.name ?? (entry.teamId ? "알 수 없는 팀" : "대기 중")}
{isWinner && (
<span className="ml-2 text-[10px] font-bold text-success">
승리
</span>
)}
</span>
<span className="text-right font-mono text-base font-bold tabular-nums text-base-content/75">
{entry.gameWins}
</span>
</div>
entry={entry}
isWinner={isWinner}
teamName={teamName}
/>
) : (
<DefaultEntryRow
key={entry.slot}
entry={entry}
isWinner={isWinner}
teamName={teamName}
/>
);
})}
</div>
</article>
);
}
function DefaultEntryRow({
entry,
isWinner,
teamName,
}: {
entry: SeriesProjection["entries"][number];
isWinner: boolean;
teamName: string;
}) {
return (
<div className="grid grid-cols-[1.5rem_minmax(0,1fr)_2rem] items-center gap-2 px-3 py-2.5">
<span className="text-[10px] font-bold text-base-content/30">
{entry.slot}
</span>
<span
className={`truncate text-sm ${
isWinner ? "font-bold text-base-content" : "text-base-content/60"
}`}
>
{teamName}
{isWinner && (
<span className="ml-2 text-[10px] font-bold text-success">승리</span>
)}
</span>
<Score gameWins={entry.gameWins} />
</div>
);
}
function BracketEntryRow({
entry,
isWinner,
teamName,
}: {
entry: SeriesProjection["entries"][number];
isWinner: boolean;
teamName: string;
}) {
return (
<div
className="grid grid-cols-[0.75rem_minmax(0,1fr)_1.5rem_1.25rem] items-center gap-1 px-2"
style={{ height: SERIES_SCORE_CARD_GEOMETRY.entryHeight }}
>
<span className="text-[9px] font-bold text-base-content/30">
{entry.slot}
</span>
<span
className={`line-clamp-2 break-words text-[13px] leading-4 ${
isWinner ? "font-bold text-base-content" : "text-base-content/60"
}`}
title={teamName}
>
{teamName}
</span>
<span className="text-center text-[10px] font-bold text-success">
{isWinner ? "승리" : null}
</span>
<Score gameWins={entry.gameWins} />
</div>
);
}
function Score({ gameWins }: { gameWins: number }) {
return (
<span className="text-right font-mono text-base font-bold tabular-nums text-base-content/75">
{gameWins}
</span>
);
}
@@ -0,0 +1,32 @@
import type {
CompetitionDetailResponse,
MatchGameMode,
} from "@lolympus/contracts";
import { createDoubleEliminationBracketLayout } from "./double-elimination-bracket-layout.ts";
export function matchPageMaxWidthClass(gameMode: MatchGameMode): string {
return gameMode === "double-elimination" ? "max-w-[1600px]" : "max-w-5xl";
}
export function createCompetitionBracketLayout(
competition: CompetitionDetailResponse,
) {
const { format, projection, teams } = competition;
if (
format.type !== "double-elimination" ||
projection.formatType !== "double-elimination" ||
format.teamCount !== teams.length
) {
return null;
}
const hasResetFinal = projection.series.some(
({ stage }) => stage.type === "reset-final",
);
if (format.resetFinalEnabled !== hasResetFinal) return null;
return createDoubleEliminationBracketLayout(projection, {
teamCount: format.teamCount,
resetFinalEnabled: format.resetFinalEnabled,
});
}
@@ -0,0 +1,170 @@
import type {
CompetitionGameView,
CompetitionProjection,
IsoDateTime,
SeriesProjection,
} from "@lolympus/contracts";
export type CompetitionSeriesHistorySeries = Extract<
SeriesProjection,
{ status: "in-progress" | "completed" }
>;
export interface CompetitionSeriesHistoryRow {
series: CompetitionSeriesHistorySeries;
games: CompetitionGameView[];
occurredAt: IsoDateTime;
timestampSource: "game-start" | "decision";
}
export interface CompetitionSeriesHistoryDay {
dateKey: string;
rows: CompetitionSeriesHistoryRow[];
}
type HistoryProjection = Pick<CompetitionProjection, "series" | "games">;
export function createCompetitionSeriesHistory(
projection: HistoryProjection,
timeZone = "Asia/Seoul",
): CompetitionSeriesHistoryDay[] {
const gamesBySeriesId = new Map<string, CompetitionGameView[]>();
for (const game of projection.games) {
const seriesGames = gamesBySeriesId.get(game.seriesId) ?? [];
seriesGames.push(game);
gamesBySeriesId.set(game.seriesId, seriesGames);
}
const rows: CompetitionSeriesHistoryRow[] = [];
for (const series of projection.series) {
const games = [...(gamesBySeriesId.get(series.seriesId) ?? [])].sort(
compareGames,
);
if (series.status === "in-progress") {
const occurredAt = earliestStartedAt(games);
if (!occurredAt) continue;
rows.push({
series,
games,
occurredAt,
timestampSource: "game-start",
});
continue;
}
if (series.status !== "completed") continue;
const gameStartedAt = earliestStartedAt(games);
rows.push({
series,
games,
occurredAt: gameStartedAt ?? series.outcome.completedAt,
timestampSource: gameStartedAt ? "game-start" : "decision",
});
}
rows.sort(compareRows);
const days: CompetitionSeriesHistoryDay[] = [];
for (const row of rows) {
const dateKey = dateKeyInTimeZone(row.occurredAt, timeZone);
const currentDay = days.at(-1);
if (currentDay?.dateKey === dateKey) {
currentDay.rows.push(row);
} else {
days.push({ dateKey, rows: [row] });
}
}
return days;
}
export function getSeriesHistoryStatusLabel(
series: CompetitionSeriesHistorySeries,
): string {
if (series.status === "in-progress") return "진행 중";
switch (series.outcome.type) {
case "played":
return "종료";
case "draw":
return "무승부";
case "walkover":
return "부전승";
case "forfeit":
return "기권승";
case "administrative":
return "판정";
}
}
export function formatSeriesGameDuration(
durationSeconds: number,
): string | null {
if (!Number.isFinite(durationSeconds) || durationSeconds <= 0) return null;
const totalSeconds = Math.floor(durationSeconds);
const hours = Math.floor(totalSeconds / 3_600);
const minutes = Math.floor((totalSeconds % 3_600) / 60);
const seconds = totalSeconds % 60;
if (hours > 0) {
return `${hours}:${padNumber(minutes)}:${padNumber(seconds)}`;
}
return `${minutes}:${padNumber(seconds)}`;
}
function compareGames(
left: CompetitionGameView,
right: CompetitionGameView,
): number {
return (
left.ordinal - right.ordinal ||
timestampValue(left.startedAt) - timestampValue(right.startedAt) ||
left.id.localeCompare(right.id)
);
}
function compareRows(
left: CompetitionSeriesHistoryRow,
right: CompetitionSeriesHistoryRow,
): number {
return (
timestampValue(left.occurredAt) - timestampValue(right.occurredAt) ||
left.series.stage.displayOrder - right.series.stage.displayOrder ||
left.series.seriesId.localeCompare(right.series.seriesId)
);
}
function earliestStartedAt(games: CompetitionGameView[]): IsoDateTime | null {
let earliest: { value: number; startedAt: IsoDateTime } | null = null;
for (const game of games) {
const value = timestampValue(game.startedAt);
if (!Number.isFinite(value)) continue;
if (!earliest || value < earliest.value) {
earliest = { value, startedAt: game.startedAt };
}
}
return earliest?.startedAt ?? null;
}
function dateKeyInTimeZone(value: IsoDateTime, timeZone: string): string {
const date = new Date(value);
if (Number.isNaN(date.getTime())) return "unknown";
const parts = new Intl.DateTimeFormat("en-US", {
timeZone,
year: "numeric",
month: "2-digit",
day: "2-digit",
}).formatToParts(date);
const part = (type: Intl.DateTimeFormatPartTypes) =>
parts.find((entry) => entry.type === type)?.value;
const year = part("year");
const month = part("month");
const day = part("day");
return year && month && day ? `${year}-${month}-${day}` : "unknown";
}
function timestampValue(value: IsoDateTime): number {
const timestamp = Date.parse(value);
return Number.isNaN(timestamp) ? Number.POSITIVE_INFINITY : timestamp;
}
function padNumber(value: number): string {
return value.toString().padStart(2, "0");
}
@@ -0,0 +1,822 @@
import type {
BracketRoundView,
DoubleEliminationCompetitionProjection,
SeriesConnectorView,
SeriesId,
SeriesSlot,
SeriesStageType,
} from "@lolympus/contracts";
import { SERIES_SCORE_CARD_GEOMETRY } from "./series-score-card-geometry.ts";
type BracketStage = "upper" | "lower" | "grand-final" | "reset-final";
export type BracketLane = "upper" | "lower" | "final";
export type BracketConnectorKind = "winner" | "loser" | "reset";
export const DOUBLE_ELIMINATION_BRACKET_GEOMETRY = {
boardPadding: 12,
columnWidth: 228,
columnGap: 32,
cardBorderWidth: SERIES_SCORE_CARD_GEOMETRY.borderWidth,
cardHeight: SERIES_SCORE_CARD_GEOMETRY.height,
cardHeaderHeight: SERIES_SCORE_CARD_GEOMETRY.headerHeight,
cardEntryHeight: SERIES_SCORE_CARD_GEOMETRY.entryHeight,
cardGap: 20,
upperTop: 64,
laneGap: 152,
} as const;
export interface BracketNodeLayout {
seriesId: SeriesId;
label: string;
stage: BracketStage;
roundNumber: number;
lane: BracketLane;
column: number;
x: number;
y: number;
width: number;
height: number;
}
export interface BracketConnectorLayout {
fromSeriesId: SeriesId;
select: SeriesConnectorView["from"]["select"];
toSeriesId: SeriesId;
toSlot: SeriesSlot;
kind: BracketConnectorKind;
sourceX: number;
sourceY: number;
verticalX: number;
targetX: number;
targetY: number;
path: string;
label: string;
}
export interface DoubleEliminationBracketConfiguration {
teamCount: 4 | 8;
resetFinalEnabled: boolean;
}
export interface BracketRoundLayout {
stage: BracketStage;
roundNumber: number;
label: string;
lane: BracketLane;
column: number;
x: number;
labelY: number;
seriesIds: SeriesId[];
}
export interface MobileBracketGroup {
stage: BracketStage;
roundNumber: number;
label: string;
seriesIds: SeriesId[];
}
export interface DoubleEliminationBracketLayout {
width: number;
height: number;
columnCount: number;
upperLane: { top: number; height: number };
lowerLane: { top: number; height: number };
finalCenterY: number;
nodes: BracketNodeLayout[];
rounds: BracketRoundLayout[];
connectors: BracketConnectorLayout[];
mobileGroups: MobileBracketGroup[];
}
interface ValidatedGraph {
seriesById: Map<SeriesId, DoubleEliminationCompetitionProjection["series"][number]>;
roundBySeriesId: Map<SeriesId, NormalizedRound>;
rounds: NormalizedRound[];
rankBySeriesId: Map<SeriesId, number>;
}
interface NormalizedRound {
stage: BracketStage;
roundNumber: number;
label: string;
seriesIds: SeriesId[];
}
const STAGE_ORDER: Record<BracketStage, number> = {
upper: 0,
lower: 1,
"grand-final": 2,
"reset-final": 3,
};
const CONNECTOR_SELECTION_ORDER: Record<
SeriesConnectorView["from"]["select"],
number
> = {
winner: 0,
loser: 1,
"slot-a": 2,
"slot-b": 3,
};
export function createDoubleEliminationBracketLayout(
projection: DoubleEliminationCompetitionProjection,
configuration: DoubleEliminationBracketConfiguration,
): DoubleEliminationBracketLayout | null {
const graph = validateGraph(projection, configuration);
if (!graph) return null;
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
const upperRounds = graph.rounds.filter(({ stage }) => stage === "upper");
const lowerRounds = graph.rounds.filter(({ stage }) => stage === "lower");
const upperHeight = laneHeight(upperRounds);
const lowerHeight = laneHeight(lowerRounds);
const upperLane = { top: geometry.upperTop, height: upperHeight };
const lowerLane = {
top: upperLane.top + upperLane.height + geometry.laneGap,
height: lowerHeight,
};
const finalCenterY = upperLane.top + upperLane.height + geometry.laneGap / 2;
const columnCount =
Math.max(...graph.rankBySeriesId.values(), 0) + 1;
const width =
geometry.boardPadding * 2 +
columnCount * geometry.columnWidth +
Math.max(0, columnCount - 1) * geometry.columnGap;
const height = lowerLane.top + lowerLane.height + geometry.boardPadding;
const nodes = buildNodes(graph, upperLane, lowerLane, finalCenterY);
const nodeById = new Map(nodes.map((node) => [node.seriesId, node]));
const connectors = buildConnectors(projection, graph, nodeById);
if (!connectors) return null;
return {
width,
height,
columnCount,
upperLane,
lowerLane,
finalCenterY,
nodes,
rounds: buildRoundLayouts(graph, nodeById, upperLane, lowerLane),
connectors,
mobileGroups: graph.rounds.map((round) => ({ ...round })),
};
}
export function bracketRoundLabel(
stage: SeriesStageType,
roundNumber?: number,
): string {
switch (stage) {
case "upper":
return `승자조 ${roundNumber ?? 1}라운드`;
case "lower":
return `패자조 ${roundNumber ?? 1}라운드`;
case "grand-final":
return "그랜드 파이널";
case "reset-final":
return "리셋 파이널";
case "pair":
return "대진";
case "round-robin":
return `${roundNumber ?? 1}라운드`;
}
}
function validateGraph(
projection: DoubleEliminationCompetitionProjection,
configuration: DoubleEliminationBracketConfiguration,
): ValidatedGraph | null {
if (projection.formatType !== "double-elimination") return null;
if (projection.series.length === 0) return null;
if (configuration.teamCount !== 4 && configuration.teamCount !== 8) {
return null;
}
const seriesById = new Map<
SeriesId,
DoubleEliminationCompetitionProjection["series"][number]
>();
const displayOrders = new Set<number>();
for (const series of projection.series) {
if (seriesById.has(series.seriesId)) return null;
if (!isBracketStage(series.stage.type)) return null;
if (!isRoundNumber(series.stage.roundNumber)) return null;
if (
!Number.isInteger(series.stage.displayOrder) ||
series.stage.displayOrder <= 0 ||
displayOrders.has(series.stage.displayOrder)
) {
return null;
}
displayOrders.add(series.stage.displayOrder);
seriesById.set(series.seriesId, series);
}
const normalizedRounds = normalizeRounds(projection.rounds, seriesById);
if (!normalizedRounds) return null;
const roundBySeriesId = new Map<SeriesId, NormalizedRound>();
for (const round of normalizedRounds) {
for (const seriesId of round.seriesIds) {
if (roundBySeriesId.has(seriesId)) return null;
roundBySeriesId.set(seriesId, round);
}
}
if (roundBySeriesId.size !== seriesById.size) return null;
const grandFinals = projection.series.filter(
({ stage }) => stage.type === "grand-final",
);
const resetFinals = projection.series.filter(
({ stage }) => stage.type === "reset-final",
);
if (
!matchesCanonicalShape(
projection,
normalizedRounds,
configuration,
grandFinals.length,
resetFinals.length,
)
) {
return null;
}
if (!hasContiguousRounds(normalizedRounds, "upper")) return null;
if (!hasContiguousRounds(normalizedRounds, "lower")) return null;
if (!connectorsHaveSupportedDiscriminators(projection.connectors)) return null;
const rankBySeriesId = rankConnectorDag(
projection.series.map(({ seriesId }) => seriesId),
projection.connectors,
seriesById,
);
if (!rankBySeriesId) return null;
if (!validateTopology(projection, seriesById, configuration)) {
return null;
}
for (const round of normalizedRounds) {
const ranks = new Set(
round.seriesIds.map((seriesId) => rankBySeriesId.get(seriesId)),
);
if (ranks.size !== 1 || ranks.has(undefined)) return null;
}
return {
seriesById,
roundBySeriesId,
rounds: normalizedRounds,
rankBySeriesId,
};
}
function normalizeRounds(
rounds: readonly BracketRoundView[],
seriesById: ValidatedGraph["seriesById"],
): NormalizedRound[] | null {
const keys = new Set<string>();
const result: NormalizedRound[] = [];
for (const round of rounds) {
if (!isBracketStage(round.stage) || !isRoundNumber(round.roundNumber)) {
return null;
}
const key = `${round.stage}:${round.roundNumber}`;
if (keys.has(key) || round.seriesIds.length === 0) return null;
keys.add(key);
const ids = [...round.seriesIds].sort((left, right) => {
const leftSeries = seriesById.get(left);
const rightSeries = seriesById.get(right);
return (
(leftSeries?.stage.displayOrder ?? 0) -
(rightSeries?.stage.displayOrder ?? 0)
);
});
for (const seriesId of ids) {
const series = seriesById.get(seriesId);
if (
!series ||
series.stage.type !== round.stage ||
series.stage.roundNumber !== round.roundNumber
) {
return null;
}
}
result.push({
stage: round.stage,
roundNumber: round.roundNumber,
label: bracketRoundLabel(round.stage, round.roundNumber),
seriesIds: ids,
});
}
return result.sort(
(left, right) =>
STAGE_ORDER[left.stage] - STAGE_ORDER[right.stage] ||
left.roundNumber - right.roundNumber,
);
}
function rankConnectorDag(
seriesIds: readonly SeriesId[],
connectors: readonly SeriesConnectorView[],
seriesById: ValidatedGraph["seriesById"],
): Map<SeriesId, number> | null {
const indegree = new Map(seriesIds.map((seriesId) => [seriesId, 0]));
const outgoing = new Map(seriesIds.map((seriesId) => [seriesId, [] as SeriesId[]]));
const targetedSlots = new Set<string>();
for (const connector of connectors) {
const source = seriesById.get(connector.from.seriesId);
const target = seriesById.get(connector.to.seriesId);
if (!source || !target || source.seriesId === target.seriesId) return null;
const targetSlotKey = `${target.seriesId}:${connector.to.slot}`;
if (targetedSlots.has(targetSlotKey)) return null;
targetedSlots.add(targetSlotKey);
indegree.set(target.seriesId, (indegree.get(target.seriesId) ?? 0) + 1);
outgoing.get(source.seriesId)?.push(target.seriesId);
}
const rank = new Map(seriesIds.map((seriesId) => [seriesId, 0]));
const queue = seriesIds
.filter((seriesId) => indegree.get(seriesId) === 0)
.sort((left, right) =>
compareSeriesDisplayOrder(seriesById.get(left), seriesById.get(right)),
);
let processed = 0;
while (queue.length > 0) {
const sourceId = queue.shift();
if (!sourceId) break;
processed += 1;
for (const targetId of outgoing.get(sourceId) ?? []) {
rank.set(
targetId,
Math.max(rank.get(targetId) ?? 0, (rank.get(sourceId) ?? 0) + 1),
);
const remaining = (indegree.get(targetId) ?? 0) - 1;
indegree.set(targetId, remaining);
if (remaining === 0) {
queue.push(targetId);
queue.sort((left, right) =>
compareSeriesDisplayOrder(seriesById.get(left), seriesById.get(right)),
);
}
}
}
return processed === seriesIds.length ? rank : null;
}
function validateTopology(
projection: DoubleEliminationCompetitionProjection,
seriesById: ValidatedGraph["seriesById"],
configuration: DoubleEliminationBracketConfiguration,
): boolean {
const incoming = new Map<SeriesId, SeriesConnectorView[]>();
const sourceSelections = new Set<string>();
for (const connector of projection.connectors) {
const source = seriesById.get(connector.from.seriesId);
const target = seriesById.get(connector.to.seriesId);
if (
!source ||
!target ||
!isBracketStage(source.stage.type) ||
!isBracketStage(target.stage.type) ||
!isRoundNumber(source.stage.roundNumber) ||
!isRoundNumber(target.stage.roundNumber)
) {
return false;
}
const sourceSelectionKey = `${source.seriesId}:${connector.from.select}`;
if (sourceSelections.has(sourceSelectionKey)) return false;
sourceSelections.add(sourceSelectionKey);
if (
!isCanonicalTransition(
source.stage.type,
source.stage.roundNumber,
target.stage.type,
target.stage.roundNumber,
connector.from.select,
configuration,
)
) {
return false;
}
const list = incoming.get(connector.to.seriesId) ?? [];
list.push(connector);
incoming.set(connector.to.seriesId, list);
if (
connector.from.select === "slot-a" ||
connector.from.select === "slot-b"
) {
const expectedSlot = connector.from.select === "slot-a" ? "A" : "B";
if (connector.to.slot !== expectedSlot) return false;
}
}
for (const series of projection.series) {
const edges = incoming.get(series.seriesId) ?? [];
const isRoot = series.stage.type === "upper" && series.stage.roundNumber === 1;
if (isRoot) {
if (edges.length !== 0) return false;
continue;
}
if (
edges.length !== 2 ||
!edges.some(({ to }) => to.slot === "A") ||
!edges.some(({ to }) => to.slot === "B")
) {
return false;
}
}
return true;
}
function buildNodes(
graph: ValidatedGraph,
upperLane: DoubleEliminationBracketLayout["upperLane"],
lowerLane: DoubleEliminationBracketLayout["lowerLane"],
finalCenterY: number,
): BracketNodeLayout[] {
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
const result: BracketNodeLayout[] = [];
for (const round of graph.rounds) {
const lane = laneForStage(round.stage);
const laneGeometry = lane === "upper" ? upperLane : lowerLane;
round.seriesIds.forEach((seriesId, index) => {
const column = graph.rankBySeriesId.get(seriesId) ?? 0;
const centerY =
lane === "final"
? finalCenterY
: laneGeometry.top +
(laneGeometry.height * (index + 0.5)) / round.seriesIds.length;
result.push({
seriesId,
label: seriesName(graph.seriesById.get(seriesId), round),
stage: round.stage,
roundNumber: round.roundNumber,
lane,
column,
x:
geometry.boardPadding +
column * (geometry.columnWidth + geometry.columnGap),
y: centerY - geometry.cardHeight / 2,
width: geometry.columnWidth,
height: geometry.cardHeight,
});
});
}
return result;
}
function buildRoundLayouts(
graph: ValidatedGraph,
nodeById: Map<SeriesId, BracketNodeLayout>,
upperLane: DoubleEliminationBracketLayout["upperLane"],
lowerLane: DoubleEliminationBracketLayout["lowerLane"],
): BracketRoundLayout[] {
return graph.rounds.map((round) => {
const node = nodeById.get(round.seriesIds[0]);
const lane = laneForStage(round.stage);
const labelY =
lane === "upper"
? upperLane.top - 28
: lane === "lower"
? lowerLane.top - 28
: (node?.y ?? 0) - 28;
return {
...round,
lane,
column: node?.column ?? 0,
x: node?.x ?? 0,
labelY,
};
});
}
function buildConnectors(
projection: DoubleEliminationCompetitionProjection,
graph: ValidatedGraph,
nodeById: Map<SeriesId, BracketNodeLayout>,
): BracketConnectorLayout[] | null {
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
const connectorsByTargetColumn = new Map<
number,
Array<{
connector: SeriesConnectorView;
source: BracketNodeLayout;
target: BracketNodeLayout;
}>
>();
for (const connector of projection.connectors) {
const source = nodeById.get(connector.from.seriesId);
const target = nodeById.get(connector.to.seriesId);
if (!source || !target || target.column <= source.column) return null;
const routes = connectorsByTargetColumn.get(target.column) ?? [];
routes.push({ connector, source, target });
connectorsByTargetColumn.set(target.column, routes);
}
const verticalXByConnector = new Map<string, number>();
for (const routes of connectorsByTargetColumn.values()) {
routes.sort(
(left, right) =>
connectorAnchorY(right.source, right.connector.from.select) -
connectorAnchorY(left.source, left.connector.from.select) ||
targetSlotY(right.target, right.connector.to.slot) -
targetSlotY(left.target, left.connector.to.slot) ||
connectorKey(left.connector).localeCompare(connectorKey(right.connector)),
);
routes.forEach(({ connector, target }, index) => {
verticalXByConnector.set(
connectorKey(connector),
target.x -
geometry.columnGap +
(geometry.columnGap * (index + 1)) / (routes.length + 1),
);
});
}
const result: BracketConnectorLayout[] = [];
for (const connector of projection.connectors) {
const source = nodeById.get(connector.from.seriesId);
const target = nodeById.get(connector.to.seriesId);
if (!source || !target || target.column <= source.column) return null;
const sourceX = source.x + source.width;
const targetX = target.x;
const sourceY = connectorAnchorY(source, connector.from.select);
const targetY = targetSlotY(target, connector.to.slot);
const verticalX = verticalXByConnector.get(connectorKey(connector));
if (verticalX === undefined) return null;
const kind = connectorKind(connector.from.select);
result.push({
fromSeriesId: connector.from.seriesId,
select: connector.from.select,
toSeriesId: connector.to.seriesId,
toSlot: connector.to.slot,
kind,
sourceX,
sourceY,
verticalX,
targetX,
targetY,
path: `M ${number(sourceX)} ${number(sourceY)} H ${number(verticalX)} V ${number(targetY)} H ${number(targetX)}`,
label: connectorLabel(connector, graph),
});
}
return result.sort(
(left, right) =>
compareSeriesDisplayOrder(
graph.seriesById.get(left.fromSeriesId),
graph.seriesById.get(right.fromSeriesId),
) ||
CONNECTOR_SELECTION_ORDER[left.select] -
CONNECTOR_SELECTION_ORDER[right.select] ||
compareSeriesDisplayOrder(
graph.seriesById.get(left.toSeriesId),
graph.seriesById.get(right.toSeriesId),
) ||
left.toSlot.localeCompare(right.toSlot),
);
}
function connectorLabel(
connector: SeriesConnectorView,
graph: ValidatedGraph,
): string {
const source = graph.seriesById.get(connector.from.seriesId);
const target = graph.seriesById.get(connector.to.seriesId);
const sourceRound = graph.roundBySeriesId.get(connector.from.seriesId);
const targetRound = graph.roundBySeriesId.get(connector.to.seriesId);
const sourceName = seriesName(source, sourceRound);
const targetName = seriesName(target, targetRound);
const selection =
connector.from.select === "winner"
? "승자"
: connector.from.select === "loser"
? "패자"
: connector.from.select === "slot-a"
? "A팀"
: "B팀";
return `${sourceName} ${selection} → ${targetName} ${connector.to.slot} 슬롯`;
}
function seriesName(
series: DoubleEliminationCompetitionProjection["series"][number] | undefined,
round: NormalizedRound | undefined,
): string {
if (series?.code) return series.code;
if (!series || !round) return "알 수 없는 경기";
const index = round.seriesIds.indexOf(series.seriesId);
return round.seriesIds.length > 1
? `${round.label} ${index + 1}경기`
: round.label;
}
function connectorAnchorY(
node: BracketNodeLayout,
select: SeriesConnectorView["from"]["select"],
): number {
const center = node.y + node.height / 2;
switch (select) {
case "winner":
return center - 7;
case "loser":
return center + 7;
case "slot-a":
return targetSlotY(node, "A");
case "slot-b":
return targetSlotY(node, "B");
}
}
function targetSlotY(node: BracketNodeLayout, slot: SeriesSlot): number {
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
const rowIndex = slot === "A" ? 0 : 1;
return (
node.y +
geometry.cardBorderWidth +
geometry.cardHeaderHeight +
geometry.cardEntryHeight * (rowIndex + 0.5)
);
}
function connectorKind(
select: SeriesConnectorView["from"]["select"],
): BracketConnectorKind {
if (select === "winner") return "winner";
if (select === "loser") return "loser";
return "reset";
}
function connectorKey(connector: SeriesConnectorView): string {
return `${connector.from.seriesId}:${connector.from.select}:${connector.to.seriesId}:${connector.to.slot}`;
}
function matchesCanonicalShape(
projection: DoubleEliminationCompetitionProjection,
rounds: readonly NormalizedRound[],
configuration: DoubleEliminationBracketConfiguration,
grandFinalCount: number,
resetFinalCount: number,
): boolean {
const expectedUpper =
configuration.teamCount === 4 ? [2, 1] : [4, 2, 1];
const expectedLower =
configuration.teamCount === 4 ? [1, 1] : [2, 2, 1, 1];
const resetCount = configuration.resetFinalEnabled ? 1 : 0;
const expectedSeriesCount = configuration.teamCount * 2 - 2 + resetCount;
const expectedConnectorCount =
configuration.teamCount * 3 - 4 + resetCount * 2;
return (
projection.series.length === expectedSeriesCount &&
projection.connectors.length === expectedConnectorCount &&
grandFinalCount === 1 &&
resetFinalCount === resetCount &&
roundSizes(rounds, "upper").every(
(size, index) => size === expectedUpper[index],
) &&
roundSizes(rounds, "upper").length === expectedUpper.length &&
roundSizes(rounds, "lower").every(
(size, index) => size === expectedLower[index],
) &&
roundSizes(rounds, "lower").length === expectedLower.length &&
rounds.filter(({ stage }) => stage === "grand-final").length === 1 &&
rounds
.filter(({ stage }) => stage === "grand-final")
.every(({ roundNumber, seriesIds }) => roundNumber === 1 && seriesIds.length === 1) &&
rounds.filter(({ stage }) => stage === "reset-final").length === resetCount &&
rounds
.filter(({ stage }) => stage === "reset-final")
.every(({ roundNumber, seriesIds }) => roundNumber === 1 && seriesIds.length === 1)
);
}
function roundSizes(
rounds: readonly NormalizedRound[],
stage: "upper" | "lower",
): number[] {
return rounds
.filter((round) => round.stage === stage)
.sort((left, right) => left.roundNumber - right.roundNumber)
.map(({ seriesIds }) => seriesIds.length);
}
function connectorsHaveSupportedDiscriminators(
connectors: readonly SeriesConnectorView[],
): boolean {
return connectors.every(
(connector) =>
isConnectorSelection(connector.from.select) &&
isSeriesSlot(connector.to.slot),
);
}
function isCanonicalTransition(
sourceStage: BracketStage,
sourceRound: number,
targetStage: BracketStage,
targetRound: number,
select: SeriesConnectorView["from"]["select"],
configuration: DoubleEliminationBracketConfiguration,
): boolean {
const upperFinalRound = configuration.teamCount === 4 ? 2 : 3;
const lowerFinalRound = configuration.teamCount === 4 ? 2 : 4;
if (select === "winner") {
if (sourceStage === "upper") {
return sourceRound < upperFinalRound
? targetStage === "upper" && targetRound === sourceRound + 1
: sourceRound === upperFinalRound && targetStage === "grand-final";
}
if (sourceStage === "lower") {
return sourceRound < lowerFinalRound
? targetStage === "lower" && targetRound === sourceRound + 1
: sourceRound === lowerFinalRound && targetStage === "grand-final";
}
return false;
}
if (select === "loser") {
return (
sourceStage === "upper" &&
targetStage === "lower" &&
targetRound ===
(sourceRound === upperFinalRound ? lowerFinalRound : sourceRound)
);
}
return sourceStage === "grand-final" && targetStage === "reset-final";
}
function laneHeight(rounds: readonly NormalizedRound[]): number {
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
const maxSeries = Math.max(...rounds.map(({ seriesIds }) => seriesIds.length), 1);
return maxSeries * (geometry.cardHeight + geometry.cardGap);
}
function laneForStage(stage: BracketStage): BracketLane {
if (stage === "upper") return "upper";
if (stage === "lower") return "lower";
return "final";
}
function hasContiguousRounds(
rounds: readonly NormalizedRound[],
stage: "upper" | "lower",
): boolean {
const numbers = rounds
.filter((round) => round.stage === stage)
.map(({ roundNumber }) => roundNumber)
.sort((left, right) => left - right);
return (
numbers.length > 0 && numbers.every((roundNumber, index) => roundNumber === index + 1)
);
}
function isBracketStage(stage: SeriesStageType): stage is BracketStage {
return (
stage === "upper" ||
stage === "lower" ||
stage === "grand-final" ||
stage === "reset-final"
);
}
function isRoundNumber(value: number | undefined): value is number {
return Number.isInteger(value) && (value ?? 0) > 0;
}
function isConnectorSelection(
value: unknown,
): value is SeriesConnectorView["from"]["select"] {
return (
value === "winner" ||
value === "loser" ||
value === "slot-a" ||
value === "slot-b"
);
}
function isSeriesSlot(value: unknown): value is SeriesSlot {
return value === "A" || value === "B";
}
function compareSeriesDisplayOrder(
left: DoubleEliminationCompetitionProjection["series"][number] | undefined,
right: DoubleEliminationCompetitionProjection["series"][number] | undefined,
): number {
return (left?.stage.displayOrder ?? 0) - (right?.stage.displayOrder ?? 0);
}
function number(value: number): string {
return Number.isInteger(value) ? String(value) : value.toFixed(1);
}
@@ -0,0 +1,6 @@
export const SERIES_SCORE_CARD_GEOMETRY = {
borderWidth: 1,
height: 116,
headerHeight: 32,
entryHeight: 41,
} as const;
@@ -0,0 +1,13 @@
import type { SeriesProjection, TeamId } from "@lolympus/contracts";
export function isSeriesEntryWinner(
series: SeriesProjection,
teamId: TeamId | null,
): boolean {
return (
teamId !== null &&
series.status === "completed" &&
series.outcome.type !== "draw" &&
series.outcome.winnerTeamId === teamId
);
}
+127
View File
@@ -0,0 +1,127 @@
export type LaneCheckpointKey = "at10" | "at15";
export const DEFAULT_LANE_CHECKPOINT: LaneCheckpointKey = "at15";
export type NormalizedLanePosition =
| "TOP"
| "JUNGLE"
| "MIDDLE"
| "BOTTOM"
| "UTILITY";
export interface LaneCheckpoint {
timestamp: number;
gold: number;
cs: number;
xp: number;
kills: number;
deaths: number;
assists: number;
}
export interface LaneParticipantLike {
teamPosition: string;
checkpoints?: Partial<Record<LaneCheckpointKey, LaneCheckpoint>>;
}
export interface LanePair<TParticipant extends LaneParticipantLike> {
position: NormalizedLanePosition;
blue: TParticipant | null;
red: TParticipant | null;
ambiguousBlue: boolean;
ambiguousRed: boolean;
}
export interface LaneCheckpointComparison {
blue: LaneCheckpoint;
red: LaneCheckpoint;
goldDiff: number;
csDiff: number;
xpDiff: number;
}
const LANE_ORDER: readonly NormalizedLanePosition[] = [
"TOP",
"JUNGLE",
"MIDDLE",
"BOTTOM",
"UTILITY",
];
const LANE_ALIASES: Readonly<Record<string, NormalizedLanePosition>> = {
TOP: "TOP",
JUNGLE: "JUNGLE",
JGL: "JUNGLE",
MIDDLE: "MIDDLE",
MID: "MIDDLE",
BOTTOM: "BOTTOM",
ADC: "BOTTOM",
UTILITY: "UTILITY",
SUPPORT: "UTILITY",
SUP: "UTILITY",
};
export function normalizeLanePosition(
value: string | undefined,
): NormalizedLanePosition | null {
if (!value) return null;
return LANE_ALIASES[value.toUpperCase()] ?? null;
}
export function pairLaneParticipants<TParticipant extends LaneParticipantLike>(
blueParticipants: readonly TParticipant[],
redParticipants: readonly TParticipant[],
): Array<LanePair<TParticipant>> {
const blueByPosition = groupByPosition(blueParticipants);
const redByPosition = groupByPosition(redParticipants);
return LANE_ORDER.flatMap((position) => {
const blue = blueByPosition.get(position) ?? [];
const red = redByPosition.get(position) ?? [];
if (blue.length === 0 && red.length === 0) return [];
return [
{
position,
blue: blue.length === 1 ? blue[0] : null,
red: red.length === 1 ? red[0] : null,
ambiguousBlue: blue.length > 1,
ambiguousRed: red.length > 1,
},
];
});
}
export function resolveCheckpointComparison<
TParticipant extends LaneParticipantLike,
>(
blueParticipant: TParticipant | null,
redParticipant: TParticipant | null,
checkpointKey: LaneCheckpointKey,
): LaneCheckpointComparison | null {
const blue = blueParticipant?.checkpoints?.[checkpointKey];
const red = redParticipant?.checkpoints?.[checkpointKey];
if (!blue || !red) return null;
return {
blue,
red,
goldDiff: blue.gold - red.gold,
csDiff: blue.cs - red.cs,
xpDiff: blue.xp - red.xp,
};
}
function groupByPosition<TParticipant extends LaneParticipantLike>(
participants: readonly TParticipant[],
) {
const grouped = new Map<NormalizedLanePosition, TParticipant[]>();
for (const participant of participants) {
const position = normalizeLanePosition(participant.teamPosition);
if (!position) continue;
const values = grouped.get(position) ?? [];
values.push(participant);
grouped.set(position, values);
}
return grouped;
}
+218
View File
@@ -0,0 +1,218 @@
export type InternalMatchTeamSide = "blue" | "red";
export type InternalMatchObjectiveType =
| "dragon"
| "elderDragon"
| "baron"
| "riftHerald"
| "voidGrub";
export type InternalMatchTimelineEventType =
| InternalMatchObjectiveType
| "championKill"
| "tower"
| "inhibitor";
export type TimelineEventCategory = "objective" | "kill" | "structure";
export type TimelineEventFilter = "all" | TimelineEventCategory;
export interface InternalMatchTimelineEvent {
timestamp: number;
side?: InternalMatchTeamSide;
type: InternalMatchTimelineEventType;
killerParticipantId?: number;
victimParticipantId?: number;
assistingParticipantIds?: number[];
monsterSubType?: string;
towerType?: string;
}
export interface InternalMatchObjectiveEvent {
timestamp: number;
side: InternalMatchTeamSide;
type: InternalMatchObjectiveType;
monsterSubType?: string;
}
export interface NormalizedObjectiveEvent extends InternalMatchObjectiveEvent {
label: string;
markerLabel: string;
}
export interface NormalizedTimelineEvent extends InternalMatchTimelineEvent {
category: TimelineEventCategory;
label: string;
markerLabel: string;
}
const DRAGON_TYPE_LABELS: Readonly<Record<string, string>> = {
AIR_DRAGON: "바람",
EARTH_DRAGON: "대지",
WATER_DRAGON: "바다",
FIRE_DRAGON: "화염",
HEXTECH_DRAGON: "마법공학",
CHEMTECH_DRAGON: "화학공학",
ELDER_DRAGON: "장로",
};
const OBJECTIVE_LABELS: Readonly<
Record<Exclude<InternalMatchObjectiveType, "dragon">, string>
> = {
elderDragon: "장로 드래곤",
baron: "바론",
riftHerald: "협곡의 전령",
voidGrub: "공허 유충",
};
const OBJECTIVE_MARKER_LABELS: Readonly<
Record<Exclude<InternalMatchObjectiveType, "dragon">, string>
> = {
elderDragon: "장로",
baron: "바론",
riftHerald: "전령",
voidGrub: "유충",
};
export function dragonTypeLabel(
monsterSubType: string | undefined,
): string | null {
if (!monsterSubType) return null;
return DRAGON_TYPE_LABELS[monsterSubType] ?? null;
}
export function normalizeObjectiveEvents(
events: readonly InternalMatchObjectiveEvent[],
): NormalizedObjectiveEvent[] {
return events
.map((event) => {
if (event.type === "dragon") {
const dragonLabel = dragonTypeLabel(event.monsterSubType);
return {
...event,
label: dragonLabel ? `${dragonLabel} 드래곤` : "드래곤",
markerLabel: dragonLabel ?? "용",
};
}
return {
...event,
label: OBJECTIVE_LABELS[event.type],
markerLabel: OBJECTIVE_MARKER_LABELS[event.type],
};
})
.sort((left, right) => left.timestamp - right.timestamp);
}
export function normalizeTimelineEvents(
events: readonly InternalMatchTimelineEvent[],
): NormalizedTimelineEvent[] {
return events
.map((event): NormalizedTimelineEvent => {
if (event.type === "championKill") {
return {
...event,
category: "kill",
label: "챔피언 처치",
markerLabel: "킬",
};
}
if (event.type === "tower") {
return {
...event,
category: "structure",
label: "포탑 파괴",
markerLabel: "포탑",
};
}
if (event.type === "inhibitor") {
return {
...event,
category: "structure",
label: "억제기 파괴",
markerLabel: "억제기",
};
}
if (event.type === "dragon") {
const dragonLabel = dragonTypeLabel(event.monsterSubType);
return {
...event,
category: "objective",
label: dragonLabel ? `${dragonLabel} 드래곤` : "드래곤",
markerLabel: dragonLabel ?? "용",
};
}
return {
...event,
category: "objective",
label: OBJECTIVE_LABELS[event.type],
markerLabel: OBJECTIVE_MARKER_LABELS[event.type],
};
})
.sort((left, right) => left.timestamp - right.timestamp);
}
export function selectTimelineEventSource<
TTimeline extends InternalMatchTimelineEvent,
TObjective extends InternalMatchObjectiveEvent,
>(
timelineEvents: readonly TTimeline[] | undefined,
objectiveEvents: readonly TObjective[],
): readonly (TTimeline | TObjective)[] {
return timelineEvents && timelineEvents.length > 0
? timelineEvents
: objectiveEvents;
}
export function filterTimelineEvents<TEvent extends NormalizedTimelineEvent>(
events: readonly TEvent[],
filter: TimelineEventFilter,
): TEvent[] {
return filter === "all"
? [...events]
: events.filter((event) => event.category === filter);
}
export function summarizeDragonTypes(
events: readonly NormalizedObjectiveEvent[],
side: InternalMatchTeamSide,
): Array<{ label: string; count: number }> {
const counts = new Map<string, number>();
for (const event of events) {
if (event.side !== side || event.type !== "dragon") continue;
const label = dragonTypeLabel(event.monsterSubType);
if (!label) continue;
counts.set(label, (counts.get(label) ?? 0) + 1);
}
return [...counts.entries()].map(([label, count]) => ({ label, count }));
}
export function projectObjectiveMarkers<
TEvent extends NormalizedObjectiveEvent,
>(
events: readonly TEvent[],
points: readonly { timestamp: number; value: number }[],
): Array<TEvent & { value: number }> {
return projectTimelineEventMarkers(events, points);
}
export function projectTimelineEventMarkers<TEvent extends { timestamp: number }>(
events: readonly TEvent[],
points: readonly { timestamp: number; value: number }[],
): Array<TEvent & { value: number }> {
if (points.length === 0) return [];
const orderedPoints = [...points].sort(
(left, right) => left.timestamp - right.timestamp,
);
return events.map((event) => {
let selected = orderedPoints[0];
for (const point of orderedPoints) {
if (point.timestamp > event.timestamp) break;
selected = point;
}
return { ...event, value: selected.value };
});
}
+6 -1
View File
@@ -28,6 +28,7 @@ import {
import { RankBadge } from "../components/RankBadge";
import { CompetitionAdminControls } from "../components/competition/CompetitionAdminControls";
import { CompetitionResults } from "../components/competition/CompetitionResults";
import { matchPageMaxWidthClass } from "../components/competition/competition-display-layout";
import { DEFAULT_COMMUNITY_ID, useAuthUserId } from "../config";
import { apiFetch, ApiError } from "../lib/api";
import { profileIconUrl } from "../lib/ddragon";
@@ -1792,7 +1793,11 @@ export default function MatchDetailPage() {
hasValidAuctionTimerSettings;
return (
<main className="max-w-5xl mx-auto px-4 sm:px-6 py-6">
<main
className={`mx-auto px-4 py-6 sm:px-6 ${
matchPageMaxWidthClass(matchQuery.data.gameMode)
}`}
>
<Link
to="/"
className="inline-flex items-center gap-1 text-xs text-base-content/40 hover:text-base-content transition-colors mb-5"
+424 -10
View File
@@ -5,6 +5,7 @@ import {
AreaChart,
CartesianGrid,
Line,
ReferenceDot,
ReferenceLine,
ResponsiveContainer,
Tooltip,
@@ -28,6 +29,16 @@ import {
internalMatchGamePath,
} from "../lib/internal-match-routes";
import { LANE_LABELS } from "../lib/riot-history";
import {
filterTimelineEvents,
normalizeObjectiveEvents,
normalizeTimelineEvents,
projectTimelineEventMarkers,
selectTimelineEventSource,
summarizeDragonTypes,
type NormalizedTimelineEvent,
type TimelineEventFilter,
} from "../lib/internal-match-timeline";
import {
InternalGameAnalysisPanel,
InternalGameDetailTabBar,
@@ -58,6 +69,16 @@ const TIMELINE_METRICS: Array<{ id: TimelineMetric; label: string }> = [
{ id: "xp", label: "경험치" },
];
const TIMELINE_EVENT_FILTERS: Array<{
id: TimelineEventFilter;
label: string;
}> = [
{ id: "all", label: "전체" },
{ id: "objective", label: "오브젝트" },
{ id: "kill", label: "킬" },
{ id: "structure", label: "구조물" },
];
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
@@ -142,6 +163,16 @@ function formatPercent(value: number) {
return `${value}%`;
}
function formatDragonTypeSummary(
values: Array<{ label: string; count: number }>,
total: number,
) {
if (values.length === 0) return total > 0 ? "유형 정보 없음" : "-";
return values
.map(({ label, count }) => (count > 1 ? `${label}×${count}` : label))
.join(" · ");
}
function barWidth(value: number, max: number) {
return `${Math.max(0, Math.min(100, max > 0 ? (value / max) * 100 : 0))}%`;
}
@@ -411,13 +442,13 @@ function PlayerRow({
{participant.assists}
</div>
<div className="text-xs font-bold tabular-nums text-base-content/40">
{formatKda(
KDA {formatKda(
participant.kills,
participant.deaths,
participant.assists,
)}
<span className="ml-1 text-base-content/35">
({participant.killParticipation}%)
· KP {participant.killParticipation}%
</span>
</div>
</td>
@@ -451,6 +482,12 @@ function PlayerRow({
<span className="block text-base-content/35">
{participant.csPerMin}/m
</span>
<span className="mt-1 block font-bold text-base-content/55">
{formatCompactNumber(participant.gold)}
<span className="ml-1 font-normal text-base-content/30">
{formatNumber(participant.gpm)} GPM
</span>
</span>
</td>
<td className="px-3 py-2.5">
<ItemStrip participant={participant} manifest={manifest} />
@@ -486,13 +523,13 @@ function PlayerCard({
{participant.assists}
</div>
<div className="text-[11px] font-bold tabular-nums text-base-content/40">
{formatKda(
KDA {formatKda(
participant.kills,
participant.deaths,
participant.assists,
)}
<span className="ml-1 text-base-content/35">
({participant.killParticipation}%)
· KP {participant.killParticipation}%
</span>
</div>
</div>
@@ -527,13 +564,19 @@ function PlayerCard({
</div>
<div className="border border-base-content/8 px-2 py-1.5">
<div className="text-[10px] font-bold uppercase tracking-wider text-base-content/30">
CS
CS · 경제
</div>
<div className="mt-0.5 font-black text-base-content/70">
{participant.cs}
<span className="ml-1 font-bold text-base-content/35">
{participant.csPerMin}/m
</span>
<span className="mt-1 block text-base-content/60">
{formatCompactNumber(participant.gold)}
<span className="ml-1 font-bold text-base-content/35">
{formatNumber(participant.gpm)} GPM
</span>
</span>
</div>
</div>
<div className="border border-base-content/8 px-2 py-1.5">
@@ -701,11 +744,125 @@ function PostgameBreakdown({
);
})}
</div>
<ObjectiveComparisonStrip selectedGame={selectedGame} />
<GoldComparisonStrip selectedGame={selectedGame} detail={detail} />
</section>
);
}
function ObjectiveComparisonStrip({
selectedGame,
}: {
selectedGame: MatchGameDetail;
}) {
const blueTeam = selectedGame.teams.find((team) => team.side === "blue");
const redTeam = selectedGame.teams.find((team) => team.side === "red");
if (!blueTeam || !redTeam) return null;
const events = normalizeObjectiveEvents(selectedGame.objectiveEvents ?? []);
const blueDragonTypes = formatDragonTypeSummary(
summarizeDragonTypes(events, "blue"),
blueTeam.objectives.dragon,
);
const redDragonTypes = formatDragonTypeSummary(
summarizeDragonTypes(events, "red"),
redTeam.objectives.dragon,
);
const objectives = [
{
key: "tower",
label: "포탑",
blue: blueTeam.objectives.tower,
red: redTeam.objectives.tower,
},
{
key: "dragon",
label: "드래곤",
blue: blueTeam.objectives.dragon,
red: redTeam.objectives.dragon,
blueDetail: blueDragonTypes,
redDetail: redDragonTypes,
},
{
key: "inhibitor",
label: "억제기",
blue: blueTeam.objectives.inhibitor,
red: redTeam.objectives.inhibitor,
},
{
key: "baron",
label: "바론",
blue: blueTeam.objectives.baron,
red: redTeam.objectives.baron,
},
{
key: "riftHerald",
label: "전령",
blue: blueTeam.objectives.riftHerald,
red: redTeam.objectives.riftHerald,
},
{
key: "voidGrub",
label: "공허 유충",
blue: blueTeam.objectives.voidGrub,
red: redTeam.objectives.voidGrub,
},
{
key: "elderDragon",
label: "장로",
blue: blueTeam.objectives.elderDragon,
red: redTeam.objectives.elderDragon,
},
];
return (
<div className="border-t border-base-content/8 bg-base-content/[0.01]">
<h3 className="sr-only">오브젝트 비교</h3>
<div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7">
{objectives.map((objective) => (
<div
key={objective.key}
className="border-b border-r border-base-content/8 px-3 py-2.5 last:border-r-0 lg:border-b-0"
aria-label={`${objective.label}: 블루 ${objective.blue}, 레드 ${objective.red}`}
>
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-2 text-xs tabular-nums">
<span
className={`text-right font-black ${
objective.blue > objective.red
? "text-blue-400"
: "text-base-content/50"
}`}
>
{objective.blue}
</span>
<span className="text-[10px] font-bold text-base-content/35">
{objective.label}
</span>
<span
className={`font-black ${
objective.red > objective.blue
? "text-red-400"
: "text-base-content/50"
}`}
>
{objective.red}
</span>
</div>
{objective.key === "dragon" ? (
<div className="mt-1 grid grid-cols-2 gap-2 text-[9px] font-bold leading-tight">
<span className="text-right text-blue-400/70">
{objective.blueDetail}
</span>
<span className="text-red-400/70">{objective.redDetail}</span>
</div>
) : null}
</div>
))}
</div>
</div>
);
}
function GoldComparisonStrip({
selectedGame,
detail,
@@ -848,14 +1005,74 @@ function TimelineTooltip({
);
}
function timelineEventKey(event: NormalizedTimelineEvent, index: number) {
return [
event.timestamp,
event.side ?? "unknown",
event.type,
event.killerParticipantId ?? "none",
event.victimParticipantId ?? "none",
index,
].join(":");
}
function timelineParticipantLabel(
participant: MatchGameParticipant | undefined,
manifest: ReturnType<typeof useDdragonManifest>["data"],
) {
if (!participant) return null;
const championName =
championDisplayName(manifest, participant.championId) ??
String(participant.championId);
return `${participant.summonerName} (${championName})`;
}
function timelineEventActors(
event: NormalizedTimelineEvent,
participantById: ReadonlyMap<number, MatchGameParticipant>,
manifest: ReturnType<typeof useDdragonManifest>["data"],
) {
const killer = timelineParticipantLabel(
event.killerParticipantId === undefined
? undefined
: participantById.get(event.killerParticipantId),
manifest,
);
const victim = timelineParticipantLabel(
event.victimParticipantId === undefined
? undefined
: participantById.get(event.victimParticipantId),
manifest,
);
const assistants = (event.assistingParticipantIds ?? [])
.map((participantId) =>
timelineParticipantLabel(participantById.get(participantId), manifest),
)
.filter((label): label is string => Boolean(label));
const assistLabel =
assistants.length > 0 ? ` · 도움 ${assistants.join(", ")}` : "";
if (event.type === "championKill") {
if (killer && victim) return `${killer} → ${victim}${assistLabel}`;
if (killer) return `${killer} 처치${assistLabel}`;
if (victim) return `${victim} 사망`;
}
if (killer) return `${killer} 기여${assistLabel}`;
return null;
}
function TimelineGraph({
selectedGame,
detail,
manifest,
}: {
selectedGame: MatchGameDetail;
detail: ApiInternalMatchDetailResponse;
manifest: ReturnType<typeof useDdragonManifest>["data"];
}) {
const [metric, setMetric] = useState<TimelineMetric>("gold");
const [eventFilter, setEventFilter] = useState<TimelineEventFilter>("all");
const [selectedEventKey, setSelectedEventKey] = useState<string | null>(null);
const blueTeam = selectedGame.teams.find((team) => team.side === "blue");
const redTeam = selectedGame.teams.find((team) => team.side === "red");
const blueTeamName = blueTeam
@@ -883,6 +1100,41 @@ function TimelineGraph({
...chartData.map((point) => Math.abs(point.value)),
);
const finalPoint = chartData[chartData.length - 1];
const timelineEvents = normalizeTimelineEvents(
selectTimelineEventSource(
selectedGame.timelineEvents,
selectedGame.objectiveEvents ?? [],
),
);
const visibleEvents = filterTimelineEvents(timelineEvents, eventFilter);
const visibleEventEntries = visibleEvents.map((event) => {
const index = timelineEvents.indexOf(event);
return {
event,
key: timelineEventKey(event, index),
};
});
const selectedEvent = visibleEventEntries.find(
(entry) => entry.key === selectedEventKey,
);
const selectedTimestamp = selectedEvent?.event.timestamp ?? null;
const timelineMarkers = projectTimelineEventMarkers(
visibleEventEntries.map(({ event, key }) => ({ ...event, eventKey: key })),
chartData,
);
const participantById = new Map<number, MatchGameParticipant>();
for (const team of selectedGame.teams) {
for (const participant of team.participants) {
if (participant.participantId !== undefined) {
participantById.set(participant.participantId, participant);
}
}
}
const chartMaxTimestamp = Math.max(
selectedGame.gameDuration,
finalPoint?.timestamp ?? 0,
timelineEvents[timelineEvents.length - 1]?.timestamp ?? 0,
);
const finalLeader =
finalPoint?.leaderSide === "blue"
? blueTeamName
@@ -901,11 +1153,16 @@ function TimelineGraph({
: "타임라인 대기"}
</div>
</div>
<div className="flex w-full border border-base-content/10 bg-base-content/[0.02] sm:w-auto">
<div
className="flex w-full border border-base-content/10 bg-base-content/[0.02] sm:w-auto"
role="group"
aria-label="경기 흐름 지표"
>
{TIMELINE_METRICS.map((item) => (
<button
key={item.id}
type="button"
aria-pressed={metric === item.id}
onClick={() => setMetric(item.id)}
className={`min-w-24 flex-1 border-r border-base-content/8 px-4 py-2 text-xs font-black transition-colors last:border-r-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary sm:flex-none ${
metric === item.id
@@ -921,7 +1178,11 @@ function TimelineGraph({
{chartData.length > 0 ? (
<div className="px-2 py-4 sm:px-4">
<div className="h-[260px] min-w-0 w-full">
<ResponsiveContainer width="100%" height="100%">
<ResponsiveContainer
width="100%"
height="100%"
initialDimension={{ width: 800, height: 260 }}
>
<AreaChart
data={chartData}
margin={{ top: 12, right: 12, bottom: 0, left: 0 }}
@@ -933,6 +1194,8 @@ function TimelineGraph({
/>
<XAxis
dataKey="timestamp"
type="number"
domain={[0, chartMaxTimestamp]}
minTickGap={28}
tickFormatter={(value) =>
`${Math.round(Number(value) / 60)}분`
@@ -965,6 +1228,14 @@ function TimelineGraph({
stroke="currentColor"
strokeOpacity={0.25}
/>
{selectedTimestamp !== null ? (
<ReferenceLine
x={selectedTimestamp}
stroke="currentColor"
strokeDasharray="3 3"
strokeOpacity={0.35}
/>
) : null}
<Area
type="monotone"
dataKey="positive"
@@ -994,6 +1265,44 @@ function TimelineGraph({
}}
isAnimationActive={false}
/>
{timelineMarkers.map((event) => {
const selected = event.eventKey === selectedEventKey;
const markerRadius =
event.category === "objective"
? 4
: event.category === "structure"
? 3.5
: 2.5;
return (
<ReferenceDot
key={event.eventKey}
x={event.timestamp}
y={event.value}
r={selected ? 5.5 : markerRadius}
fill={
event.side === "blue"
? "#3b82f6"
: event.side === "red"
? "#ef4444"
: "currentColor"
}
stroke="currentColor"
strokeWidth={selected ? 2 : 1}
ifOverflow="extendDomain"
label={
selected
? {
value: event.markerLabel,
position: "top",
fontSize: 10,
fontWeight: 800,
fill: "currentColor",
}
: undefined
}
/>
);
})}
</AreaChart>
</ResponsiveContainer>
</div>
@@ -1008,6 +1317,106 @@ function TimelineGraph({
타임라인 데이터가 아직 없습니다
</div>
)}
{timelineEvents.length > 0 ? (
<div className="border-t border-base-content/8 px-4 py-3">
<div className="flex flex-wrap items-baseline justify-between gap-2">
<h3 className="text-xs font-black text-base-content">주요 사건</h3>
<p className="text-[11px] font-bold text-base-content/30">
항목을 선택하면 그래프의 해당 시점을 강조합니다
</p>
</div>
<div
className="mt-3 flex w-full overflow-x-auto border border-base-content/10 bg-base-content/[0.02] sm:w-fit"
role="group"
aria-label="사건 유형 필터"
>
{TIMELINE_EVENT_FILTERS.map((filter) => (
<button
key={filter.id}
type="button"
aria-pressed={eventFilter === filter.id}
onClick={() => setEventFilter(filter.id)}
className={`min-w-20 flex-1 border-r border-base-content/8 px-3 py-2 text-[11px] font-black transition-colors last:border-r-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary sm:flex-none ${
eventFilter === filter.id
? "bg-primary text-primary-content"
: "text-base-content/45 hover:bg-base-content/[0.03] hover:text-base-content"
}`}
>
{filter.label}
</button>
))}
</div>
<ul
className="m-0 mt-3 grid max-h-64 list-none gap-1.5 overflow-y-auto p-0 sm:grid-cols-2 lg:grid-cols-3"
aria-label="시간순 주요 사건"
>
{visibleEventEntries.map(({ event, key }) => {
const selected = key === selectedEventKey;
const teamName =
event.side === "blue"
? blueTeamName
: event.side === "red"
? redTeamName
: null;
const actorLabel = timelineEventActors(
event,
participantById,
manifest,
);
return (
<li key={key} className="min-w-0">
<button
type="button"
aria-pressed={selected}
onClick={() => setSelectedEventKey(selected ? null : key)}
className={`grid h-full w-full grid-cols-[3.25rem_3.25rem_minmax(0,1fr)] items-start gap-2 border px-2.5 py-2 text-left text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary ${
selected
? "border-primary bg-primary/8"
: "border-base-content/8 hover:bg-base-content/[0.03]"
}`}
>
<span className="font-mono font-black tabular-nums text-base-content/55">
{formatDuration(event.timestamp)}
</span>
<span
className={`text-[10px] font-black uppercase tracking-wider ${
event.side === "blue"
? "text-blue-400"
: event.side === "red"
? "text-red-400"
: "text-base-content/35"
}`}
>
{event.side ? sideLabel(event.side) : "-"}
</span>
<span className="min-w-0">
<span className="block truncate font-bold text-base-content/75">
{teamName ? (
<span className="sr-only">{teamName} </span>
) : null}
{event.label}
</span>
{actorLabel ? (
<span
className="mt-0.5 block truncate text-[10px] font-bold text-base-content/35"
title={actorLabel}
>
{actorLabel}
</span>
) : null}
</span>
</button>
</li>
);
})}
</ul>
{visibleEventEntries.length === 0 ? (
<p className="py-6 text-center text-xs font-bold text-base-content/35">
이 유형의 사건이 없습니다
</p>
) : null}
</div>
) : null}
</section>
);
}
@@ -1045,7 +1454,7 @@ function TeamTable({
<th className="w-[120px] px-3 py-2.5 text-center">가한 피해량</th>
<th className="w-[120px] px-3 py-2.5 text-center">받은 피해량</th>
<th className="w-[80px] px-3 py-2.5 text-center">시야</th>
<th className="w-[76px] px-3 py-2.5 text-center">CS</th>
<th className="w-[96px] px-3 py-2.5 text-center">CS · 경제</th>
<th className="w-[260px] px-3 py-2.5">아이템</th>
</tr>
</thead>
@@ -1306,6 +1715,13 @@ export default function MatchGameDetailPage() {
manifest={ddragon}
/>
<TimelineGraph
key={selectedGame.riotMatchId}
selectedGame={selectedGame}
detail={detail}
manifest={ddragon}
/>
<div className="mt-5 space-y-4">
<InternalGameDetailTabBar
activeTab={activeTab}
@@ -1325,8 +1741,6 @@ export default function MatchGameDetailPage() {
}
/>
</div>
<TimelineGraph selectedGame={selectedGame} detail={detail} />
</main>
);
}
@@ -0,0 +1,477 @@
import assert from "node:assert/strict";
import test from "node:test";
import type {
CompetitionGameView,
GameId,
GameSlotId,
SeriesId,
SeriesProjection,
TeamId,
} from "@lolympus/contracts";
import {
createCompetitionSeriesHistory,
formatSeriesGameDuration,
getSeriesHistoryStatusLabel,
} from "../src/components/competition/competition-series-history.ts";
test("aggregates Games under their Series and preserves Series slot scores", () => {
const teamA = teamId("team-a");
const teamB = teamId("team-b");
const series = completedSeries({
id: "series-score",
teamA,
teamB,
scoreA: 2,
scoreB: 1,
completedAt: "2026-07-12T13:00:00.000Z",
});
const laterGame = game({
id: "game-later",
seriesId: series.seriesId,
ordinal: 2,
displayNumber: 4,
blueTeamId: teamB,
redTeamId: teamA,
winnerTeamId: teamB,
startedAt: "2026-07-12T12:30:00.000Z",
});
const earlierGame = game({
id: "game-earlier",
seriesId: series.seriesId,
ordinal: 1,
displayNumber: 19,
blueTeamId: teamA,
redTeamId: teamB,
winnerTeamId: teamA,
startedAt: "2026-07-12T12:00:00.000Z",
});
const history = createCompetitionSeriesHistory({
series: [series],
games: [laterGame, earlierGame],
});
assert.equal(history.length, 1);
assert.equal(history[0].dateKey, "2026-07-12");
assert.equal(history[0].rows.length, 1);
assert.deepEqual(
history[0].rows[0].series.entries.map((entry) => entry.gameWins),
[2, 1],
);
assert.deepEqual(
history[0].rows[0].games.map(({ ordinal }) => ordinal),
[1, 2],
);
assert.equal(history[0].rows[0].occurredAt, earlierGame.startedAt);
assert.equal(history[0].rows[0].timestampSource, "game-start");
});
test("groups and orders Series by the Asia/Seoul calendar day", () => {
const firstDay = playedSeriesWithGame({
id: "first-day",
displayOrder: 3,
startedAt: "2026-07-12T14:55:00.000Z",
});
const secondDayLater = playedSeriesWithGame({
id: "second-day-later",
displayOrder: 2,
startedAt: "2026-07-12T16:05:00.000Z",
});
const secondDayEarlier = playedSeriesWithGame({
id: "second-day-earlier",
displayOrder: 1,
startedAt: "2026-07-12T15:05:00.000Z",
});
const history = createCompetitionSeriesHistory({
series: [secondDayLater.series, firstDay.series, secondDayEarlier.series],
games: [secondDayLater.game, secondDayEarlier.game, firstDay.game],
});
assert.deepEqual(
history.map(({ dateKey }) => dateKey),
["2026-07-12", "2026-07-13"],
);
assert.deepEqual(
history[1].rows.map(({ series }) => series.seriesId),
[secondDayEarlier.series.seriesId, secondDayLater.series.seriesId],
);
});
test("includes recorded in-progress Series and game-less completed decisions only", () => {
const teamA = teamId("team-a");
const teamB = teamId("team-b");
const running = inProgressSeries("running-recorded", teamA, teamB, 1, 0);
const runningGame = game({
id: "running-game",
seriesId: running.seriesId,
ordinal: 1,
displayNumber: 1,
blueTeamId: teamA,
redTeamId: teamB,
winnerTeamId: teamA,
startedAt: "2026-07-13T09:00:00.000Z",
});
const administrative = completedSeries({
id: "administrative",
teamA,
teamB,
scoreA: 0,
scoreB: 0,
completedAt: "2026-07-13T10:00:00.000Z",
outcome: "administrative",
});
const unrecordedRunning = inProgressSeries(
"running-unrecorded",
teamA,
teamB,
0,
0,
);
const history = createCompetitionSeriesHistory({
series: [
readySeries("ready", teamA, teamB),
waitingSeries("waiting"),
inactiveSeries("inactive"),
unrecordedRunning,
administrative,
running,
],
games: [runningGame],
});
const rows = history.flatMap(({ rows }) => rows);
assert.deepEqual(
rows.map(({ series }) => series.seriesId),
[running.seriesId, administrative.seriesId],
);
assert.equal(rows[0].timestampSource, "game-start");
assert.equal(rows[1].timestampSource, "decision");
assert.equal(rows[1].occurredAt, administrative.outcome.completedAt);
});
test("sorts tied timestamps deterministically and ignores orphan Games", () => {
const teamA = teamId("team-a");
const teamB = teamId("team-b");
const earlierDisplayOrder = completedSeries({
id: "series-z",
teamA,
teamB,
scoreA: 2,
scoreB: 0,
displayOrder: 1,
completedAt: "2026-07-13T12:00:00.000Z",
});
const laterDisplayOrder = completedSeries({
id: "series-a",
teamA,
teamB,
scoreA: 2,
scoreB: 1,
displayOrder: 2,
completedAt: "2026-07-13T12:00:00.000Z",
});
const orphanGame = game({
id: "orphan-game",
seriesId: seriesId("missing-series"),
ordinal: 1,
displayNumber: 99,
blueTeamId: teamA,
redTeamId: teamB,
winnerTeamId: teamA,
startedAt: "2026-07-13T08:00:00.000Z",
});
const rows = createCompetitionSeriesHistory({
series: [laterDisplayOrder, earlierDisplayOrder],
games: [orphanGame],
}).flatMap(({ rows }) => rows);
assert.deepEqual(
rows.map(({ series }) => series.seriesId),
[earlierDisplayOrder.seriesId, laterDisplayOrder.seriesId],
);
assert.equal(rows.every(({ games }) => games.length === 0), true);
});
test("returns explicit status labels for played and adjudicated outcomes", () => {
const teamA = teamId("team-a");
const teamB = teamId("team-b");
assert.equal(
getSeriesHistoryStatusLabel(
inProgressSeries("running", teamA, teamB, 1, 0),
),
"진행 중",
);
assert.equal(
getSeriesHistoryStatusLabel(
completedSeries({ id: "played", teamA, teamB, scoreA: 2, scoreB: 1 }),
),
"종료",
);
assert.equal(
getSeriesHistoryStatusLabel(
completedSeries({
id: "draw",
teamA,
teamB,
scoreA: 1,
scoreB: 1,
outcome: "draw",
}),
),
"무승부",
);
assert.equal(
getSeriesHistoryStatusLabel(
completedSeries({
id: "walkover",
teamA,
teamB,
scoreA: 0,
scoreB: 0,
outcome: "walkover",
}),
),
"부전승",
);
assert.equal(
getSeriesHistoryStatusLabel(
completedSeries({
id: "forfeit",
teamA,
teamB,
scoreA: 1,
scoreB: 1,
outcome: "forfeit",
}),
),
"기권승",
);
assert.equal(
getSeriesHistoryStatusLabel(
completedSeries({
id: "administrative",
teamA,
teamB,
scoreA: 0,
scoreB: 0,
outcome: "administrative",
}),
),
"판정",
);
});
test("formats recorded Game duration and omits unknown legacy zero values", () => {
assert.equal(formatSeriesGameDuration(1_875), "31:15");
assert.equal(formatSeriesGameDuration(3_661), "1:01:01");
assert.equal(formatSeriesGameDuration(0), null);
assert.equal(formatSeriesGameDuration(-1), null);
});
function playedSeriesWithGame({
id,
displayOrder,
startedAt,
}: {
id: string;
displayOrder: number;
startedAt: string;
}) {
const teamA = teamId(`${id}-a`);
const teamB = teamId(`${id}-b`);
const series = completedSeries({
id,
teamA,
teamB,
scoreA: 2,
scoreB: 0,
displayOrder,
completedAt: startedAt,
});
return {
series,
game: game({
id: `${id}-game`,
seriesId: series.seriesId,
ordinal: 1,
displayNumber: displayOrder,
blueTeamId: teamA,
redTeamId: teamB,
winnerTeamId: teamA,
startedAt,
}),
};
}
function completedSeries({
id,
teamA,
teamB,
scoreA,
scoreB,
displayOrder = 1,
completedAt = "2026-07-13T00:00:00.000Z",
outcome = "played",
}: {
id: string;
teamA: TeamId;
teamB: TeamId;
scoreA: number;
scoreB: number;
displayOrder?: number;
completedAt?: string;
outcome?: "played" | "draw" | "walkover" | "forfeit" | "administrative";
}): Extract<SeriesProjection, { status: "completed" }> {
const base = {
seriesId: seriesId(id),
stage: { type: "upper" as const, roundNumber: 1, displayOrder },
rule: { type: "first-to" as const, winsRequired: 2, maxGames: 3 },
status: "completed" as const,
entries: [
{ slot: "A" as const, teamId: teamA, gameWins: scoreA },
{ slot: "B" as const, teamId: teamB, gameWins: scoreB },
] as const,
};
if (outcome === "draw") {
return {
...base,
outcome: {
type: "draw",
basis: { type: "played", decidedByGameIds: [] },
completedAt,
},
};
}
if (outcome !== "played") {
return {
...base,
outcome: {
type: outcome,
winnerTeamId: teamA,
loserTeamId: teamB,
decisionFactId: `fact-${id}` as never,
completedAt,
},
};
}
return {
...base,
outcome: {
type: "played",
winnerTeamId: teamA,
loserTeamId: teamB,
decidedByGameIds: [],
completedAt,
},
};
}
function inProgressSeries(
id: string,
teamA: TeamId,
teamB: TeamId,
scoreA: number,
scoreB: number,
): Extract<SeriesProjection, { status: "in-progress" }> {
return {
seriesId: seriesId(id),
stage: { type: "upper", roundNumber: 1, displayOrder: 1 },
rule: { type: "first-to", winsRequired: 2, maxGames: 3 },
status: "in-progress",
entries: [
{ slot: "A", teamId: teamA, gameWins: scoreA },
{ slot: "B", teamId: teamB, gameWins: scoreB },
],
...(scoreA === scoreB
? {}
: { leaderTeamId: scoreA > scoreB ? teamA : teamB }),
};
}
function readySeries(
id: string,
teamA: TeamId,
teamB: TeamId,
): Extract<SeriesProjection, { status: "ready" }> {
return {
seriesId: seriesId(id),
stage: { type: "upper", roundNumber: 1, displayOrder: 1 },
rule: { type: "first-to", winsRequired: 2, maxGames: 3 },
status: "ready",
entries: [
{ slot: "A", teamId: teamA, gameWins: 0 },
{ slot: "B", teamId: teamB, gameWins: 0 },
],
};
}
function waitingSeries(
id: string,
): Extract<SeriesProjection, { status: "waiting" }> {
return {
seriesId: seriesId(id),
stage: { type: "upper", roundNumber: 1, displayOrder: 1 },
rule: { type: "first-to", winsRequired: 2, maxGames: 3 },
status: "waiting",
entries: [
{ slot: "A", teamId: null, gameWins: 0 },
{ slot: "B", teamId: null, gameWins: 0 },
],
};
}
function inactiveSeries(
id: string,
): Extract<SeriesProjection, { status: "inactive" }> {
return { ...waitingSeries(id), status: "inactive" };
}
function game({
id,
seriesId: parentSeriesId,
ordinal,
displayNumber,
blueTeamId,
redTeamId,
winnerTeamId,
startedAt,
}: {
id: string;
seriesId: SeriesId;
ordinal: number;
displayNumber: number;
blueTeamId: TeamId;
redTeamId: TeamId;
winnerTeamId: TeamId;
startedAt: string;
}): CompetitionGameView {
return {
id: id as GameId,
seriesId: parentSeriesId,
gameSlotId: `${id}-slot` as GameSlotId,
ordinal,
displayNumber,
evidence: { type: "legacy", legacyReference: id },
teams: {
blue: { side: "blue", teamId: blueTeamId },
red: { side: "red", teamId: redTeamId },
},
winnerTeamId,
startedAt,
durationSeconds: 1_875,
participants: [],
};
}
function seriesId(value: string): SeriesId {
return value as SeriesId;
}
function teamId(value: string): TeamId {
return value as TeamId;
}
@@ -0,0 +1,937 @@
import assert from "node:assert/strict";
import test from "node:test";
import type {
BracketRoundView,
CompetitionDetailResponse,
DoubleEliminationCompetitionProjection,
SeriesConnectorView,
SeriesId,
SeriesProjection,
TeamId,
} from "@lolympus/contracts";
import {
createCompetitionBracketLayout,
matchPageMaxWidthClass,
} from "../src/components/competition/competition-display-layout.ts";
import {
createDoubleEliminationBracketLayout,
DOUBLE_ELIMINATION_BRACKET_GEOMETRY,
} from "../src/components/competition/double-elimination-bracket-layout.ts";
import { isSeriesEntryWinner } from "../src/components/competition/series-score-card-model.ts";
type BracketStage = "upper" | "lower" | "grand-final" | "reset-final";
const FOUR_TEAM_IDS = {
WB_R1_M1: seriesId("four-upper-opening-1"),
WB_R1_M2: seriesId("four-upper-opening-2"),
WB_FINAL: seriesId("four-upper-final"),
LB_R1_M1: seriesId("four-lower-opening"),
LB_FINAL: seriesId("four-lower-final"),
GF: seriesId("four-grand-final"),
GF_RESET: seriesId("four-reset-final"),
};
const EIGHT_TEAM_IDS = {
WB_R1_M1: seriesId("eight-upper-opening-1"),
WB_R1_M2: seriesId("eight-upper-opening-2"),
WB_R1_M3: seriesId("eight-upper-opening-3"),
WB_R1_M4: seriesId("eight-upper-opening-4"),
WB_R2_M1: seriesId("eight-upper-semifinal-1"),
WB_R2_M2: seriesId("eight-upper-semifinal-2"),
WB_FINAL: seriesId("eight-upper-final"),
LB_R1_M1: seriesId("eight-lower-opening-1"),
LB_R1_M2: seriesId("eight-lower-opening-2"),
LB_R2_M1: seriesId("eight-lower-round-2-match-1"),
LB_R2_M2: seriesId("eight-lower-round-2-match-2"),
LB_R3_M1: seriesId("eight-lower-semifinal"),
LB_FINAL: seriesId("eight-lower-final"),
GF: seriesId("eight-grand-final"),
GF_RESET: seriesId("eight-reset-final"),
};
const FOUR_TEAM_LAYOUT = {
teamCount: 4,
resetFinalEnabled: false,
} as const;
const FOUR_TEAM_RESET_LAYOUT = {
teamCount: 4,
resetFinalEnabled: true,
} as const;
const EIGHT_TEAM_LAYOUT = {
teamCount: 8,
resetFinalEnabled: false,
} as const;
const EIGHT_TEAM_RESET_LAYOUT = {
teamCount: 8,
resetFinalEnabled: true,
} as const;
test("places the canonical four-team DAG in shared time columns", () => {
const { projection, ids } = fourTeamProjection();
const layout = requireLayout(projection, FOUR_TEAM_LAYOUT);
assert.deepEqual(columnsBySeriesId(layout), {
[ids.WB_R1_M1]: 0,
[ids.WB_R1_M2]: 0,
[ids.WB_FINAL]: 1,
[ids.LB_R1_M1]: 1,
[ids.LB_FINAL]: 2,
[ids.GF]: 3,
});
assert.equal(nodeFor(layout, ids.WB_FINAL).lane, "upper");
assert.equal(nodeFor(layout, ids.LB_FINAL).lane, "lower");
assert.equal(nodeFor(layout, ids.GF).lane, "final");
});
test("selects the wide page grid only for double-elimination matches", () => {
assert.equal(matchPageMaxWidthClass("double-elimination"), "max-w-[1600px]");
assert.equal(matchPageMaxWidthClass("pair"), "max-w-5xl");
assert.equal(matchPageMaxWidthClass("round-robin"), "max-w-5xl");
});
test("selects the bracket only for a coherent double-elimination snapshot", () => {
const { projection } = eightTeamProjection();
const competition = competitionDetail(projection);
assert.ok(createCompetitionBracketLayout(competition));
assert.equal(
createCompetitionBracketLayout({
...competition,
teams: competition.teams.slice(1),
}),
null,
);
assert.equal(
createCompetitionBracketLayout({
...competition,
format: { ...competition.format, resetFinalEnabled: true },
}),
null,
);
assert.equal(
createCompetitionBracketLayout({
...competition,
projection: { ...projection, formatType: "round-robin" },
} as CompetitionDetailResponse),
null,
);
});
test("marks a winner only for a completed non-draw Series outcome", () => {
const waiting = pendingSeries(
seriesId("winner-guard-waiting"),
"upper",
1,
1,
);
assert.equal(isSeriesEntryWinner(waiting, null), false);
const teamA = "winner-team-a" as TeamId;
const teamB = "winner-team-b" as TeamId;
const completed = {
...waiting,
status: "completed",
entries: [
{ slot: "A", teamId: teamA, gameWins: 2 },
{ slot: "B", teamId: teamB, gameWins: 1 },
],
outcome: {
type: "played",
winnerTeamId: teamA,
loserTeamId: teamB,
decidedByGameIds: [],
completedAt: "2026-07-13T00:00:00.000Z",
},
} as SeriesProjection;
assert.equal(isSeriesEntryWinner(completed, teamA), true);
assert.equal(isSeriesEntryWinner(completed, teamB), false);
const drawn = {
...completed,
outcome: {
type: "draw",
basis: { type: "played", decidedByGameIds: [] },
completedAt: "2026-07-13T00:00:00.000Z",
},
} as SeriesProjection;
assert.equal(isSeriesEntryWinner(drawn, teamA), false);
assert.equal(isSeriesEntryWinner(drawn, teamB), false);
});
test("places every code-less eight-team Series once regardless of input order", () => {
const ordered = eightTeamProjection();
const shuffled = eightTeamProjection({ shuffled: true });
assert.equal(
shuffled.projection.series.every((series) => series.code === undefined),
true,
);
const orderedLayout = requireLayout(ordered.projection, EIGHT_TEAM_LAYOUT);
const shuffledLayout = requireLayout(shuffled.projection, EIGHT_TEAM_LAYOUT);
const expectedColumns = {
[ordered.ids.WB_R1_M1]: 0,
[ordered.ids.WB_R1_M2]: 0,
[ordered.ids.WB_R1_M3]: 0,
[ordered.ids.WB_R1_M4]: 0,
[ordered.ids.WB_R2_M1]: 1,
[ordered.ids.WB_R2_M2]: 1,
[ordered.ids.WB_FINAL]: 2,
[ordered.ids.LB_R1_M1]: 1,
[ordered.ids.LB_R1_M2]: 1,
[ordered.ids.LB_R2_M1]: 2,
[ordered.ids.LB_R2_M2]: 2,
[ordered.ids.LB_R3_M1]: 3,
[ordered.ids.LB_FINAL]: 4,
[ordered.ids.GF]: 5,
};
assert.deepEqual(columnsBySeriesId(orderedLayout), expectedColumns);
assert.deepEqual(columnsBySeriesId(shuffledLayout), expectedColumns);
assert.deepEqual(shuffledLayout.connectors, orderedLayout.connectors);
assert.equal(shuffledLayout.nodes.length, shuffled.projection.series.length);
assert.equal(
new Set(shuffledLayout.nodes.map((node) => node.seriesId)).size,
shuffled.projection.series.length,
);
});
test("keeps the known WB_R2_M2 winner and loser routes keyed by opaque Series identity", () => {
const { projection, ids } = eightTeamProjection({ shuffled: true });
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
assert.deepEqual(routeFrom(layout, ids.WB_R2_M2, "winner"), {
fromSeriesId: ids.WB_R2_M2,
select: "winner",
toSeriesId: ids.WB_FINAL,
toSlot: "B",
kind: "winner",
});
assert.deepEqual(routeFrom(layout, ids.WB_R2_M2, "loser"), {
fromSeriesId: ids.WB_R2_M2,
select: "loser",
toSeriesId: ids.LB_R2_M1,
toSlot: "B",
kind: "loser",
});
});
test("maps grand-final slot carry-over to two distinct reset routes", () => {
const { projection, ids } = eightTeamProjection({ resetFinal: true });
const layout = requireLayout(projection, EIGHT_TEAM_RESET_LAYOUT);
assert.equal(nodeFor(layout, ids.GF_RESET).column, 6);
assert.deepEqual(
layout.connectors
.filter((connector) => connector.fromSeriesId === ids.GF)
.map(connectorIdentity)
.sort((left, right) => left.select.localeCompare(right.select)),
[
{
fromSeriesId: ids.GF,
select: "slot-a",
toSeriesId: ids.GF_RESET,
toSlot: "A",
kind: "reset",
},
{
fromSeriesId: ids.GF,
select: "slot-b",
toSeriesId: ids.GF_RESET,
toSlot: "B",
kind: "reset",
},
],
);
});
test("orders mobile groups as winners, losers, grand final, then reset final", () => {
const ordered = eightTeamProjection({ resetFinal: true });
const shuffled = eightTeamProjection({ resetFinal: true, shuffled: true });
const orderedLayout = requireLayout(
ordered.projection,
EIGHT_TEAM_RESET_LAYOUT,
);
const shuffledLayout = requireLayout(
shuffled.projection,
EIGHT_TEAM_RESET_LAYOUT,
);
assert.deepEqual(mobileGroupKeys(shuffledLayout), [
"upper:1",
"upper:2",
"upper:3",
"lower:1",
"lower:2",
"lower:3",
"lower:4",
"grand-final:1",
"reset-final:1",
]);
assert.deepEqual(
shuffledLayout.mobileGroups.map((group) => group.seriesIds),
orderedLayout.mobileGroups.map((group) => group.seriesIds),
);
assert.deepEqual(
shuffledLayout.mobileGroups.flatMap((group) => group.seriesIds).sort(),
shuffled.projection.series.map((series) => series.seriesId).sort(),
);
});
test("rejects a canonical projection that does not match the configured team count", () => {
const { projection } = eightTeamProjection();
assert.equal(
createDoubleEliminationBracketLayout(projection, FOUR_TEAM_LAYOUT),
null,
);
});
test("rejects a reset-final node when reset is disabled by the format", () => {
const { projection } = fourTeamProjection({ resetFinal: true });
assert.equal(
createDoubleEliminationBracketLayout(projection, FOUR_TEAM_LAYOUT),
null,
);
assert.ok(
createDoubleEliminationBracketLayout(projection, FOUR_TEAM_RESET_LAYOUT),
);
});
test("requires reset final to carry over the grand-final A and B slots", () => {
const { projection, ids } = eightTeamProjection({ resetFinal: true });
const malformed = cloneProjection(projection);
const slotA = malformed.connectors.find(
({ from }) => from.seriesId === ids.GF && from.select === "slot-a",
);
const slotB = malformed.connectors.find(
({ from }) => from.seriesId === ids.GF && from.select === "slot-b",
);
assert.ok(slotA);
assert.ok(slotB);
slotA.from.select = "slot-b";
slotB.from.select = "slot-a";
assert.equal(
createDoubleEliminationBracketLayout(
malformed,
EIGHT_TEAM_RESET_LAYOUT,
),
null,
);
});
test("rejects invalid stage transitions when source selections remain unique", () => {
const { projection, ids } = eightTeamProjection();
const malformed = cloneProjection(projection);
const winnerRoute = malformed.connectors.find(
({ from }) =>
from.seriesId === ids.WB_R1_M1 && from.select === "winner",
);
const loserRoute = malformed.connectors.find(
({ from }) =>
from.seriesId === ids.WB_R1_M1 && from.select === "loser",
);
assert.ok(winnerRoute);
assert.ok(loserRoute);
winnerRoute.from.select = "loser";
loserRoute.from.select = "winner";
assert.equal(
createDoubleEliminationBracketLayout(malformed, EIGHT_TEAM_LAYOUT),
null,
);
});
test("rejects duplicate source selections when every transition is valid", () => {
const { projection, ids } = eightTeamProjection();
const malformed = cloneProjection(projection);
const winnerRoute = malformed.connectors.find(
({ from }) =>
from.seriesId === ids.WB_R1_M2 && from.select === "winner",
);
assert.ok(winnerRoute);
winnerRoute.from.seriesId = ids.WB_R1_M1;
assert.equal(
createDoubleEliminationBracketLayout(malformed, EIGHT_TEAM_LAYOUT),
null,
);
});
test("returns null instead of throwing for an unknown connector discriminator", () => {
const { projection } = fourTeamProjection();
const malformed = cloneProjection(projection);
(
malformed.connectors[0].from as {
seriesId: SeriesId;
select: string;
}
).select = "unexpected";
assert.doesNotThrow(() =>
createDoubleEliminationBracketLayout(malformed, FOUR_TEAM_LAYOUT),
);
assert.equal(
createDoubleEliminationBracketLayout(malformed, FOUR_TEAM_LAYOUT),
null,
);
});
test("keeps connector rails distinct and outside intervening card rectangles", () => {
const { projection } = eightTeamProjection();
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
const nodes = new Map(layout.nodes.map((node) => [node.seriesId, node]));
const routesByTargetColumn = new Map<number, number[]>();
for (const route of layout.connectors) {
const source = nodes.get(route.fromSeriesId);
const target = nodes.get(route.toSeriesId);
assert.ok(source);
assert.ok(target);
assert.equal(Number.isFinite(route.verticalX), true);
assert.equal(Number.isFinite(route.sourceY), true);
assert.equal(Number.isFinite(route.targetY), true);
assert.equal(route.path.includes("NaN"), false);
assert.equal(route.path.includes("Infinity"), false);
assert.notEqual(route.label.trim(), "");
assert.ok(target.column > source.column);
assert.ok(route.verticalX > target.x - 32);
assert.ok(route.verticalX < target.x);
for (const intermediate of layout.nodes) {
if (
intermediate.column <= source.column ||
intermediate.column >= target.column
) {
continue;
}
assert.equal(
route.verticalX > intermediate.x &&
route.verticalX < intermediate.x + intermediate.width,
false,
);
}
const rails = routesByTargetColumn.get(target.column) ?? [];
rails.push(route.verticalX);
routesByTargetColumn.set(target.column, rails);
}
for (const rails of routesByTargetColumn.values()) {
assert.equal(new Set(rails).size, rails.length);
}
});
test("minimizes connector crossings without introducing segment overlaps", () => {
const { projection } = eightTeamProjection();
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
assert.equal(countStrictConnectorCrossings(layout.connectors), 12);
assert.equal(countCollinearConnectorOverlaps(layout.connectors), 0);
});
test("aligns connector endpoints with the A and B entry row centers", () => {
const { projection } = eightTeamProjection({ resetFinal: true });
const layout = requireLayout(projection, EIGHT_TEAM_RESET_LAYOUT);
const nodes = new Map(layout.nodes.map((node) => [node.seriesId, node]));
for (const route of layout.connectors) {
const source = nodes.get(route.fromSeriesId);
const target = nodes.get(route.toSeriesId);
assert.ok(source);
assert.ok(target);
assert.equal(route.targetY, entryRowCenterY(target.y, route.toSlot));
if (route.select === "slot-a" || route.select === "slot-b") {
assert.equal(
route.sourceY,
entryRowCenterY(source.y, route.select === "slot-a" ? "A" : "B"),
);
}
}
});
test("keeps every node in its lane and centers finals between both lanes", () => {
const { projection } = eightTeamProjection({ resetFinal: true });
const layout = requireLayout(projection, EIGHT_TEAM_RESET_LAYOUT);
for (const node of layout.nodes) {
if (node.lane === "upper") {
assert.ok(node.y >= layout.upperLane.top);
assert.ok(
node.y + node.height <=
layout.upperLane.top + layout.upperLane.height,
);
} else if (node.lane === "lower") {
assert.ok(node.y >= layout.lowerLane.top);
assert.ok(
node.y + node.height <=
layout.lowerLane.top + layout.lowerLane.height,
);
} else {
assert.equal(node.y + node.height / 2, layout.finalCenterY);
}
}
});
test("returns null when a connector references a missing Series", () => {
const { projection, ids } = fourTeamProjection();
const malformed = cloneProjection(projection);
malformed.connectors.push(
connector(ids.GF, "winner", seriesId("missing-series"), "A"),
);
assert.equal(
createDoubleEliminationBracketLayout(malformed, FOUR_TEAM_LAYOUT),
null,
);
});
test("returns null when multiple connectors target the same Series slot", () => {
const { projection, ids } = eightTeamProjection();
const malformed = cloneProjection(projection);
const rerouted = malformed.connectors.find(
(candidate) =>
candidate.from.seriesId === ids.WB_R1_M3 &&
candidate.from.select === "winner",
);
assert.ok(rerouted);
rerouted.to = { seriesId: ids.WB_R2_M1, slot: "A" };
assert.equal(
createDoubleEliminationBracketLayout(malformed, EIGHT_TEAM_LAYOUT),
null,
);
});
test("returns null when connectors introduce a cycle", () => {
const { projection, ids } = fourTeamProjection();
const malformed = cloneProjection(projection);
const openingLoser = malformed.connectors.find(
({ from, to }) =>
from.seriesId === ids.WB_R1_M1 &&
from.select === "loser" &&
to.seriesId === ids.LB_R1_M1 &&
to.slot === "A",
);
const lowerFinalWinner = malformed.connectors.find(
({ from, to }) =>
from.seriesId === ids.LB_FINAL &&
from.select === "winner" &&
to.seriesId === ids.GF &&
to.slot === "B",
);
assert.ok(openingLoser);
assert.ok(lowerFinalWinner);
openingLoser.from = { seriesId: ids.LB_FINAL, select: "winner" };
lowerFinalWinner.from = { seriesId: ids.WB_R1_M1, select: "loser" };
assert.equal(
createDoubleEliminationBracketLayout(malformed, FOUR_TEAM_LAYOUT),
null,
);
});
test("returns null when round membership disagrees with Series stage metadata", () => {
const { projection, ids } = eightTeamProjection();
const malformed = cloneProjection(projection);
const series = malformed.series.find(
(candidate) => candidate.seriesId === ids.WB_R1_M1,
);
assert.ok(series);
series.stage = { ...series.stage, roundNumber: 2 };
assert.equal(
createDoubleEliminationBracketLayout(malformed, EIGHT_TEAM_LAYOUT),
null,
);
});
function fourTeamProjection(options: { resetFinal?: boolean } = {}) {
const ids = FOUR_TEAM_IDS;
const series = [
pendingSeries(ids.WB_R1_M1, "upper", 1, 1),
pendingSeries(ids.WB_R1_M2, "upper", 1, 2),
pendingSeries(ids.WB_FINAL, "upper", 2, 3),
pendingSeries(ids.LB_R1_M1, "lower", 1, 4),
pendingSeries(ids.LB_FINAL, "lower", 2, 5),
pendingSeries(ids.GF, "grand-final", 1, 6),
];
const rounds = [
round("upper", 1, 1, [ids.WB_R1_M1, ids.WB_R1_M2]),
round("upper", 2, 3, [ids.WB_FINAL]),
round("lower", 1, 4, [ids.LB_R1_M1]),
round("lower", 2, 5, [ids.LB_FINAL]),
round("grand-final", 1, 6, [ids.GF]),
];
const connectors = [
connector(ids.WB_R1_M1, "winner", ids.WB_FINAL, "A"),
connector(ids.WB_R1_M2, "winner", ids.WB_FINAL, "B"),
connector(ids.WB_R1_M1, "loser", ids.LB_R1_M1, "A"),
connector(ids.WB_R1_M2, "loser", ids.LB_R1_M1, "B"),
connector(ids.LB_R1_M1, "winner", ids.LB_FINAL, "A"),
connector(ids.WB_FINAL, "loser", ids.LB_FINAL, "B"),
connector(ids.WB_FINAL, "winner", ids.GF, "A"),
connector(ids.LB_FINAL, "winner", ids.GF, "B"),
];
if (options.resetFinal) {
series.push(pendingSeries(ids.GF_RESET, "reset-final", 1, 7));
rounds.push(round("reset-final", 1, 7, [ids.GF_RESET]));
connectors.push(
connector(ids.GF, "slot-a", ids.GF_RESET, "A"),
connector(ids.GF, "slot-b", ids.GF_RESET, "B"),
);
}
return { ids, projection: projection(series, rounds, connectors) };
}
function eightTeamProjection(
options: { resetFinal?: boolean; shuffled?: boolean } = {},
) {
const ids = EIGHT_TEAM_IDS;
const series = [
pendingSeries(ids.WB_R1_M1, "upper", 1, 1),
pendingSeries(ids.WB_R1_M2, "upper", 1, 2),
pendingSeries(ids.WB_R1_M3, "upper", 1, 3),
pendingSeries(ids.WB_R1_M4, "upper", 1, 4),
pendingSeries(ids.WB_R2_M1, "upper", 2, 5),
pendingSeries(ids.WB_R2_M2, "upper", 2, 6),
pendingSeries(ids.WB_FINAL, "upper", 3, 7),
pendingSeries(ids.LB_R1_M1, "lower", 1, 8),
pendingSeries(ids.LB_R1_M2, "lower", 1, 9),
pendingSeries(ids.LB_R2_M1, "lower", 2, 10),
pendingSeries(ids.LB_R2_M2, "lower", 2, 11),
pendingSeries(ids.LB_R3_M1, "lower", 3, 12),
pendingSeries(ids.LB_FINAL, "lower", 4, 13),
pendingSeries(ids.GF, "grand-final", 1, 14),
];
const rounds = [
round("upper", 1, 1, [
ids.WB_R1_M1,
ids.WB_R1_M2,
ids.WB_R1_M3,
ids.WB_R1_M4,
]),
round("upper", 2, 5, [ids.WB_R2_M1, ids.WB_R2_M2]),
round("upper", 3, 7, [ids.WB_FINAL]),
round("lower", 1, 8, [ids.LB_R1_M1, ids.LB_R1_M2]),
round("lower", 2, 10, [ids.LB_R2_M1, ids.LB_R2_M2]),
round("lower", 3, 12, [ids.LB_R3_M1]),
round("lower", 4, 13, [ids.LB_FINAL]),
round("grand-final", 1, 14, [ids.GF]),
];
const connectors = [
connector(ids.WB_R1_M1, "winner", ids.WB_R2_M1, "A"),
connector(ids.WB_R1_M2, "winner", ids.WB_R2_M1, "B"),
connector(ids.WB_R1_M3, "winner", ids.WB_R2_M2, "A"),
connector(ids.WB_R1_M4, "winner", ids.WB_R2_M2, "B"),
connector(ids.WB_R2_M1, "winner", ids.WB_FINAL, "A"),
connector(ids.WB_R2_M2, "winner", ids.WB_FINAL, "B"),
connector(ids.WB_R1_M1, "loser", ids.LB_R1_M1, "A"),
connector(ids.WB_R1_M2, "loser", ids.LB_R1_M1, "B"),
connector(ids.WB_R1_M3, "loser", ids.LB_R1_M2, "A"),
connector(ids.WB_R1_M4, "loser", ids.LB_R1_M2, "B"),
connector(ids.LB_R1_M1, "winner", ids.LB_R2_M1, "A"),
connector(ids.WB_R2_M2, "loser", ids.LB_R2_M1, "B"),
connector(ids.LB_R1_M2, "winner", ids.LB_R2_M2, "A"),
connector(ids.WB_R2_M1, "loser", ids.LB_R2_M2, "B"),
connector(ids.LB_R2_M1, "winner", ids.LB_R3_M1, "A"),
connector(ids.LB_R2_M2, "winner", ids.LB_R3_M1, "B"),
connector(ids.LB_R3_M1, "winner", ids.LB_FINAL, "A"),
connector(ids.WB_FINAL, "loser", ids.LB_FINAL, "B"),
connector(ids.WB_FINAL, "winner", ids.GF, "A"),
connector(ids.LB_FINAL, "winner", ids.GF, "B"),
];
if (options.resetFinal) {
series.push(pendingSeries(ids.GF_RESET, "reset-final", 1, 15));
rounds.push(round("reset-final", 1, 15, [ids.GF_RESET]));
connectors.push(
connector(ids.GF, "slot-a", ids.GF_RESET, "A"),
connector(ids.GF, "slot-b", ids.GF_RESET, "B"),
);
}
const orderedProjection = projection(series, rounds, connectors);
if (!options.shuffled) return { ids, projection: orderedProjection };
return {
ids,
projection: {
...orderedProjection,
series: shuffledCopy(orderedProjection.series),
rounds: shuffledCopy(orderedProjection.rounds).map((value) => ({
...value,
seriesIds: shuffledCopy(value.seriesIds),
})),
connectors: shuffledCopy(orderedProjection.connectors),
},
};
}
function projection(
series: SeriesProjection[],
rounds: BracketRoundView[],
connectors: SeriesConnectorView[],
): DoubleEliminationCompetitionProjection {
return {
sourceRevision: 1,
projectorVersion: 1,
phase: "running",
formatType: "double-elimination",
series,
games: [],
gameSlots: [],
rounds,
connectors,
placements: [],
};
}
function competitionDetail(
projection: DoubleEliminationCompetitionProjection,
): CompetitionDetailResponse {
return {
projection,
format: {
type: "double-elimination",
teamCount: 8,
resetFinalEnabled: false,
},
teams: Array.from({ length: 8 }, (_, index) => ({
teamId: `team-${index + 1}`,
})),
} as CompetitionDetailResponse;
}
function pendingSeries(
id: SeriesId,
stage: BracketStage,
roundNumber: number,
displayOrder: number,
): SeriesProjection {
return {
seriesId: id,
stage: { type: stage, roundNumber, displayOrder },
rule: { type: "first-to", winsRequired: 1, maxGames: 1 },
entries: [
{ slot: "A", teamId: null, gameWins: 0 },
{ slot: "B", teamId: null, gameWins: 0 },
],
status: "waiting",
};
}
function round(
stage: BracketStage,
roundNumber: number,
displayOrder: number,
seriesIds: SeriesId[],
): BracketRoundView {
return {
stage,
roundNumber,
displayOrder,
label: `${stage}-${roundNumber}`,
seriesIds,
};
}
function connector(
fromSeriesId: SeriesId,
select: SeriesConnectorView["from"]["select"],
toSeriesId: SeriesId,
slot: SeriesConnectorView["to"]["slot"],
): SeriesConnectorView {
return {
from: { seriesId: fromSeriesId, select },
to: { seriesId: toSeriesId, slot },
};
}
function seriesId(value: string): SeriesId {
return value as SeriesId;
}
function cloneProjection(
value: DoubleEliminationCompetitionProjection,
): DoubleEliminationCompetitionProjection {
return structuredClone(value);
}
function shuffledCopy<T>(values: readonly T[]): T[] {
return values.filter((_, index) => index % 2 === 1).reverse().concat(
values.filter((_, index) => index % 2 === 0).reverse(),
);
}
function requireLayout(
projection: DoubleEliminationCompetitionProjection,
options:
| typeof FOUR_TEAM_LAYOUT
| typeof FOUR_TEAM_RESET_LAYOUT
| typeof EIGHT_TEAM_LAYOUT
| typeof EIGHT_TEAM_RESET_LAYOUT,
) {
const layout = createDoubleEliminationBracketLayout(projection, options);
assert.ok(layout);
return layout;
}
function entryRowCenterY(top: number, slot: "A" | "B"): number {
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
const rowIndex = slot === "A" ? 0 : 1;
return (
top +
geometry.cardBorderWidth +
geometry.cardHeaderHeight +
geometry.cardEntryHeight * (rowIndex + 0.5)
);
}
type ConnectorLayout = NonNullable<
ReturnType<typeof createDoubleEliminationBracketLayout>
>["connectors"][number];
type OrthogonalSegment =
| { orientation: "horizontal"; fixed: number; start: number; end: number }
| { orientation: "vertical"; fixed: number; start: number; end: number };
function connectorSegments(route: ConnectorLayout): OrthogonalSegment[] {
return [
segment("horizontal", route.sourceY, route.sourceX, route.verticalX),
segment("vertical", route.verticalX, route.sourceY, route.targetY),
segment("horizontal", route.targetY, route.verticalX, route.targetX),
];
}
function segment(
orientation: OrthogonalSegment["orientation"],
fixed: number,
first: number,
second: number,
): OrthogonalSegment {
return {
orientation,
fixed,
start: Math.min(first, second),
end: Math.max(first, second),
};
}
function countStrictConnectorCrossings(routes: readonly ConnectorLayout[]): number {
let crossings = 0;
for (let leftIndex = 0; leftIndex < routes.length; leftIndex += 1) {
const leftSegments = connectorSegments(routes[leftIndex]);
for (let rightIndex = leftIndex + 1; rightIndex < routes.length; rightIndex += 1) {
const rightSegments = connectorSegments(routes[rightIndex]);
for (const left of leftSegments) {
for (const right of rightSegments) {
const horizontal =
left.orientation === "horizontal"
? left
: right.orientation === "horizontal"
? right
: null;
const vertical =
left.orientation === "vertical"
? left
: right.orientation === "vertical"
? right
: null;
if (
horizontal &&
vertical &&
vertical.fixed > horizontal.start &&
vertical.fixed < horizontal.end &&
horizontal.fixed > vertical.start &&
horizontal.fixed < vertical.end
) {
crossings += 1;
}
}
}
}
}
return crossings;
}
function countCollinearConnectorOverlaps(routes: readonly ConnectorLayout[]): number {
let overlaps = 0;
for (let leftIndex = 0; leftIndex < routes.length; leftIndex += 1) {
const leftSegments = connectorSegments(routes[leftIndex]);
for (let rightIndex = leftIndex + 1; rightIndex < routes.length; rightIndex += 1) {
const rightSegments = connectorSegments(routes[rightIndex]);
for (const left of leftSegments) {
for (const right of rightSegments) {
if (
left.orientation === right.orientation &&
left.fixed === right.fixed &&
Math.min(left.end, right.end) > Math.max(left.start, right.start)
) {
overlaps += 1;
}
}
}
}
}
return overlaps;
}
function columnsBySeriesId(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
) {
return Object.fromEntries(
layout.nodes
.map((node) => [node.seriesId, node.column] as const)
.sort(([left], [right]) => left.localeCompare(right)),
);
}
function nodeFor(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
id: SeriesId,
) {
const node = layout.nodes.find((candidate) => candidate.seriesId === id);
assert.ok(node);
return node;
}
function routeFrom(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
id: SeriesId,
select: SeriesConnectorView["from"]["select"],
) {
const route = layout.connectors.find(
(candidate) =>
candidate.fromSeriesId === id && candidate.select === select,
);
assert.ok(route);
return connectorIdentity(route);
}
function connectorIdentity(
connector: NonNullable<
ReturnType<typeof createDoubleEliminationBracketLayout>
>["connectors"][number],
) {
return {
fromSeriesId: connector.fromSeriesId,
select: connector.select,
toSeriesId: connector.toSeriesId,
toSlot: connector.toSlot,
kind: connector.kind,
};
}
function mobileGroupKeys(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
) {
return layout.mobileGroups.map(
(group) => `${group.stage}:${group.roundNumber ?? 0}`,
);
}
@@ -0,0 +1,134 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
DEFAULT_LANE_CHECKPOINT,
pairLaneParticipants,
resolveCheckpointComparison,
} from "../src/lib/internal-game-matchups.ts";
function participant(
name: string,
side: "blue" | "red",
teamPosition: string,
gold: number,
cs: number,
xp: number,
) {
return {
name,
side,
teamPosition,
checkpoints: {
at15: {
timestamp: 900,
gold,
cs,
xp,
kills: side === "blue" ? 2 : 1,
deaths: side === "blue" ? 1 : 2,
assists: 3,
},
},
};
}
test("pairLaneParticipants matches shuffled players by normalized team position", () => {
const blue = [
participant("Blue ADC", "blue", "BOTTOM", 6_000, 120, 7_000),
participant("Blue Top", "blue", "TOP", 5_500, 110, 6_800),
participant("Blue Mid", "blue", "MID", 6_200, 115, 7_100),
];
const red = [
participant("Red Mid", "red", "MIDDLE", 5_900, 109, 6_900),
participant("Red Top", "red", "TOP", 5_300, 105, 6_600),
participant("Red ADC", "red", "ADC", 5_800, 116, 6_850),
];
const pairs = pairLaneParticipants(blue, red);
assert.deepEqual(
pairs.map((pair) => [pair.position, pair.blue?.name, pair.red?.name]),
[
["TOP", "Blue Top", "Red Top"],
["MIDDLE", "Blue Mid", "Red Mid"],
["BOTTOM", "Blue ADC", "Red ADC"],
],
);
});
test("pairLaneParticipants leaves a duplicated role ambiguous instead of pairing by index", () => {
const blue = [
participant("Blue Top A", "blue", "TOP", 5_500, 110, 6_800),
participant("Blue Top B", "blue", "TOP", 5_000, 100, 6_200),
];
const red = [
participant("Red Top", "red", "TOP", 5_300, 105, 6_600),
];
assert.deepEqual(pairLaneParticipants(blue, red), [
{
position: "TOP",
blue: null,
red: red[0],
ambiguousBlue: true,
ambiguousRed: false,
},
]);
});
test("resolveCheckpointComparison calculates blue-side GD, CSD, and XPD", () => {
const blue = participant("Blue Mid", "blue", "MIDDLE", 6_200, 115, 7_100);
const red = participant("Red Mid", "red", "MIDDLE", 5_900, 109, 6_900);
const comparison = resolveCheckpointComparison(blue, red, "at15");
assert.deepEqual(comparison, {
blue: blue.checkpoints.at15,
red: red.checkpoints.at15,
goldDiff: 300,
csDiff: 6,
xpDiff: 200,
});
});
test("resolveCheckpointComparison returns null when either checkpoint is unavailable", () => {
const blue = participant("Blue Mid", "blue", "MIDDLE", 6_200, 115, 7_100);
const red = participant("Red Mid", "red", "MIDDLE", 5_900, 109, 6_900);
assert.equal(resolveCheckpointComparison(blue, red, "at10"), null);
assert.equal(resolveCheckpointComparison(blue, null, "at15"), null);
});
test("the lane panel defaults to 15 minutes and supports an available 10-minute comparison", () => {
assert.equal(DEFAULT_LANE_CHECKPOINT, "at15");
const blue = participant("Blue Mid", "blue", "MIDDLE", 6_200, 115, 7_100);
const red = participant("Red Mid", "red", "MIDDLE", 5_900, 109, 6_900);
blue.checkpoints.at10 = {
timestamp: 590,
gold: 4_000,
cs: 75,
xp: 4_600,
kills: 1,
deaths: 0,
assists: 2,
};
red.checkpoints.at10 = {
timestamp: 590,
gold: 3_700,
cs: 69,
xp: 4_450,
kills: 0,
deaths: 1,
assists: 1,
};
assert.deepEqual(resolveCheckpointComparison(blue, red, "at10"), {
blue: blue.checkpoints.at10,
red: red.checkpoints.at10,
goldDiff: 300,
csDiff: 6,
xpDiff: 150,
});
});
@@ -0,0 +1,228 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
dragonTypeLabel,
filterTimelineEvents,
normalizeObjectiveEvents,
normalizeTimelineEvents,
projectObjectiveMarkers,
selectTimelineEventSource,
summarizeDragonTypes,
} from "../src/lib/internal-match-timeline.ts";
test("dragonTypeLabel maps Riot dragon subtypes to Korean labels", () => {
assert.deepEqual(
[
"AIR_DRAGON",
"EARTH_DRAGON",
"WATER_DRAGON",
"FIRE_DRAGON",
"HEXTECH_DRAGON",
"CHEMTECH_DRAGON",
"ELDER_DRAGON",
].map(dragonTypeLabel),
["바람", "대지", "바다", "화염", "마법공학", "화학공학", "장로"],
);
assert.equal(dragonTypeLabel("UNKNOWN_DRAGON"), null);
assert.equal(dragonTypeLabel(undefined), null);
});
test("normalizeObjectiveEvents sorts events and adds conservative Korean labels", () => {
const events = normalizeObjectiveEvents([
{ timestamp: 1_443, side: "blue", type: "baron" },
{
timestamp: 339,
side: "blue",
type: "dragon",
monsterSubType: "EARTH_DRAGON",
},
{ timestamp: 963, side: "red", type: "riftHerald" },
{
timestamp: 1_356,
side: "red",
type: "dragon",
monsterSubType: "UNKNOWN_DRAGON",
},
{ timestamp: 530, side: "blue", type: "voidGrub" },
{ timestamp: 1_600, side: "red", type: "elderDragon" },
]);
assert.deepEqual(
events.map(({ timestamp, label, markerLabel }) => ({
timestamp,
label,
markerLabel,
})),
[
{ timestamp: 339, label: "대지 드래곤", markerLabel: "대지" },
{ timestamp: 530, label: "공허 유충", markerLabel: "유충" },
{ timestamp: 963, label: "협곡의 전령", markerLabel: "전령" },
{ timestamp: 1_356, label: "드래곤", markerLabel: "용" },
{ timestamp: 1_443, label: "바론", markerLabel: "바론" },
{ timestamp: 1_600, label: "장로 드래곤", markerLabel: "장로" },
],
);
});
test("summarizeDragonTypes groups repeated dragon types per side in event order", () => {
const events = normalizeObjectiveEvents([
{
timestamp: 300,
side: "blue",
type: "dragon",
monsterSubType: "FIRE_DRAGON",
},
{
timestamp: 600,
side: "red",
type: "dragon",
monsterSubType: "WATER_DRAGON",
},
{
timestamp: 900,
side: "blue",
type: "dragon",
monsterSubType: "FIRE_DRAGON",
},
{
timestamp: 1_200,
side: "blue",
type: "dragon",
monsterSubType: "HEXTECH_DRAGON",
},
{
timestamp: 1_500,
side: "red",
type: "dragon",
monsterSubType: "UNKNOWN_DRAGON",
},
]);
assert.deepEqual(summarizeDragonTypes(events, "blue"), [
{ label: "화염", count: 2 },
{ label: "마법공학", count: 1 },
]);
assert.deepEqual(summarizeDragonTypes(events, "red"), [
{ label: "바다", count: 1 },
]);
});
test("projectObjectiveMarkers anchors events to the latest available chart value", () => {
const events = normalizeObjectiveEvents([
{ timestamp: 10, side: "blue", type: "voidGrub" },
{ timestamp: 90, side: "red", type: "riftHerald" },
{ timestamp: 180, side: "blue", type: "baron" },
]);
assert.deepEqual(
projectObjectiveMarkers(events, [
{ timestamp: 0, value: 0 },
{ timestamp: 60, value: 100 },
{ timestamp: 120, value: 80 },
]).map(({ timestamp, value }) => ({ timestamp, value })),
[
{ timestamp: 10, value: 0 },
{ timestamp: 90, value: 100 },
{ timestamp: 180, value: 80 },
],
);
});
test("normalizeTimelineEvents labels and sorts objectives, kills, and structures", () => {
const events = normalizeTimelineEvents([
{
timestamp: 700,
side: "blue",
type: "tower",
killerParticipantId: 1,
towerType: "OUTER_TURRET",
},
{
timestamp: 500,
side: "red",
type: "championKill",
killerParticipantId: 6,
victimParticipantId: 1,
assistingParticipantIds: [7, 8],
},
{
timestamp: 300,
side: "blue",
type: "dragon",
monsterSubType: "FIRE_DRAGON",
},
{ timestamp: 800, side: "red", type: "inhibitor" },
]);
assert.deepEqual(
events.map(({ timestamp, category, label, markerLabel }) => ({
timestamp,
category,
label,
markerLabel,
})),
[
{
timestamp: 300,
category: "objective",
label: "화염 드래곤",
markerLabel: "화염",
},
{
timestamp: 500,
category: "kill",
label: "챔피언 처치",
markerLabel: "킬",
},
{
timestamp: 700,
category: "structure",
label: "포탑 파괴",
markerLabel: "포탑",
},
{
timestamp: 800,
category: "structure",
label: "억제기 파괴",
markerLabel: "억제기",
},
],
);
assert.equal(events[1].killerParticipantId, 6);
assert.equal(events[1].victimParticipantId, 1);
});
test("selectTimelineEventSource falls back to objective events during rolling updates", () => {
const objectives = [
{ timestamp: 300, side: "blue" as const, type: "voidGrub" as const },
];
const timeline = [
{ timestamp: 400, side: "red" as const, type: "championKill" as const },
];
assert.equal(selectTimelineEventSource(timeline, objectives), timeline);
assert.equal(selectTimelineEventSource([], objectives), objectives);
assert.equal(selectTimelineEventSource(undefined, objectives), objectives);
});
test("filterTimelineEvents filters event categories without changing order", () => {
const events = normalizeTimelineEvents([
{ timestamp: 300, side: "blue", type: "dragon" },
{ timestamp: 500, side: "red", type: "championKill" },
{ timestamp: 700, side: "blue", type: "tower" },
]);
assert.deepEqual(
filterTimelineEvents(events, "all").map((event) => event.timestamp),
[300, 500, 700],
);
assert.deepEqual(
filterTimelineEvents(events, "kill").map((event) => event.timestamp),
[500],
);
assert.deepEqual(
filterTimelineEvents(events, "structure").map((event) => event.timestamp),
[700],
);
});
+122
View File
@@ -0,0 +1,122 @@
# Implementation Plan: Series Result History UI
## Overview
Replace the existing completed-Game mini-card grid with a tested chronological
Series result history. Keep data derivation pure, render responsive semantic rows,
and preserve all current Competition/API contracts.
## Architecture Decisions
- Derive a local view model from `projection.series` and `projection.games`; no API
or persistence change is required.
- Anchor a played Series to its earliest accepted Game start. Anchor a game-less
completed decision to its decision time only for grouping and sorting.
- Keep the original narrowed Series and Game objects in each row so the UI does not
duplicate domain state or collapse outcome semantics.
- Use a native `details/summary` disclosure for Game history and omit it when a
Series has no Games.
- Extract the new UI from `CompetitionResults.tsx` so the format selector remains
focused.
## Task List
### Phase 1: Result-History Contract
#### Task 1: Specify aggregation and chronology test-first
**Acceptance criteria:**
- [ ] Tests cover Series aggregation, ordinal Game order, KST date boundaries,
chronological order, outcome variants, and deterministic fallbacks.
- [ ] The focused test fails because the model module does not yet exist.
**Verification:**
- [ ] Run the focused Node test and record the expected RED failure.
**Files likely touched:**
- `apps/web/test/competition-series-history.test.ts`
#### Task 2: Implement the pure history model
**Acceptance criteria:**
- [ ] Only recorded in-progress and completed Series are returned.
- [ ] Date grouping and format helpers are explicitly KST-aware.
- [ ] Decision outcomes and missing legacy durations remain distinguishable.
**Verification:**
- [ ] Focused history tests pass.
- [ ] Existing web tests still pass.
**Files likely touched:**
- `apps/web/src/components/competition/competition-series-history.ts`
- `apps/web/test/competition-series-history.test.ts`
### Checkpoint: Model
- [ ] Pure tests pass without a React or browser dependency.
### Phase 2: Responsive Result UI
#### Task 3: Render date sections and Series rows
**Acceptance criteria:**
- [ ] Desktop uses a flat schedule-like row; mobile stacks metadata and matchup
without horizontal scrolling.
- [ ] Status and official winner are communicated with visible text and typography,
not color alone.
- [ ] Game-less decisions do not show fake start times or `0 : 0`.
**Verification:**
- [ ] Changed component files pass ESLint.
- [ ] Web build succeeds.
**Files likely touched:**
- `apps/web/src/components/competition/CompetitionSeriesHistory.tsx`
#### Task 4: Integrate accessible Game disclosures
**Acceptance criteria:**
- [ ] Each Series with Games exposes a native keyboard-operable disclosure.
- [ ] Games use Series-local ordinal, team-ID winner lookup, and omit unknown
zero-duration values.
- [ ] The old completed-Game mini-card block is removed.
**Verification:**
- [ ] Full web tests, lint, and build pass.
- [ ] Source review checks heading order, disclosure semantics, and 320px layout.
**Files likely touched:**
- `apps/web/src/components/competition/CompetitionSeriesHistory.tsx`
- `apps/web/src/components/competition/CompetitionResults.tsx`
### Checkpoint: Complete
- [ ] All specification success criteria are met.
- [ ] Git diff contains only the feature spec, plan, tests, model, and UI integration.
- [ ] Unrelated working-tree files are unchanged.
## Risks and Mitigations
| Risk | Impact | Mitigation |
|---|---|---|
| Game sides are mistaken for Series slots | High | Use Series A/B entries and outcome team IDs; test side swaps. |
| Completion time is shown as start time | Medium | Track timestamp source and render a blank time for decisions. |
| KST day changes by deploy environment | Medium | Use explicit `Intl.DateTimeFormat` timezone and boundary tests. |
| Long team names break mobile rows | Medium | Use balanced minmax columns and allow wrapping. |
| Existing dirty work is overwritten | High | Restrict patches and verification to named feature files. |
## Open Questions
None.
@@ -0,0 +1,78 @@
# Implementation Plan: Internal Match Game Analysis P0/P1
## Overview
Deliver three independently verifiable slices: P0 existing-data UI, P1-A timeline
checkpoints and lane comparison, and P1-B unified notable events. Preserve the
existing detail endpoint and use builder/cache versioning to refresh old projections.
## Task List
### Phase 1: P0 Existing Data
- [x] Add tested objective normalization, chart markers, an accessible event list,
and move game flow above the detail tabs.
- [x] Add a complete objective comparison strip with conservative dragon-type
fallback behavior.
- [x] Label KP and add participant gold/GPM to the combined CS/economy presentation.
### Checkpoint: P0
- [x] Web tests, lint, and production build pass.
- [x] Desktop and mobile layouts retain all existing scoreboard/build behavior.
### Phase 2: P1-A Lane Checkpoints
- [x] Parse the remaining participant event identifier fields and project tested
participant checkpoints at 10 and 15 minutes.
- [x] Persist and expose optional checkpoint fields, reject stale caches, and bump
the match-stats builder/detail-response versions.
- [x] Replace final-state lane comparisons with tested role-based 10/15-minute
GD/CSD/XPD and K/D/A comparisons.
### Checkpoint: P1-A
- [x] Focused API tests and builds pass.
- [x] Web tests and production build pass.
- [x] Short and missing-timeline games show unavailable states rather than zeros.
### Phase 3: P1-B Unified Events
- [x] Project objectives, champion kills, towers, and inhibitors into a deterministic
tested event stream.
- [x] Expose `timelineEvents` while retaining `objectiveEvents` compatibility and
bump persisted/cache versions as required.
- [x] Add accessible event filtering and chart selection with objective-only fallback.
- [x] Coalesce concurrent hydration and short-cache incomplete results so transient
failures retry without rebuilding on every sequential page request.
### Checkpoint: Complete
- [x] API and web focused suites pass without skipped tests.
- [x] API and web production builds pass.
- [x] Responsive runtime review passes at 320px, 390px, 768px, 1024px, and 1440px.
- [x] P0/P1 edits exclude unrelated Competition/bracket modifications already in
the shared worktree.
## Risks and Mitigations
| Risk | Impact | Mitigation |
|---|---|---|
| Missing or delayed Riot frames misrepresent @10/@15 | High | Use only a frame at/before the target within one frame interval and expose its actual timestamp. |
| Building events attribute the destroyed team's side as the scorer | High | Prefer killer participant side; otherwise invert the destroyed `teamId`; cover both paths in tests. |
| Old cached shapes hide new fields | High | Increment builder and response cache versions and strengthen completeness validation. |
| A kill-heavy game makes the page excessively long | Medium | Add event-category filters and a bounded scroll region. |
| Mobile chart remains hard to reach | Medium | Move flow directly below the summary before any participant cards. |
| Existing dirty work is accidentally included | High | Restrict edits and verification to the named game-analysis files and inspect the final diff by path. |
## Dependencies
```text
P0 event normalization -> P0 objective strip
P1 checkpoint projector -> response contract -> lane UI
P1 checkpoint identifiers -> event projector -> response contract -> event UI
```
## Open Questions
None.
+34 -4
View File
@@ -274,10 +274,19 @@ Migration builds new collections without dual canonical writes.
`null`, mapping it to `pair`; an explicitly stored unknown mode remains
quarantined instead of being guessed.
- A persisted legacy round-robin `gameSchedule` is authoritative. Migration
normalizes it into explicit seed-based pairings on the Competition format so the
normalizes it into explicit TeamId-based pairings on the Competition format so the
immutable Series graph reproduces the historical opponents and rounds instead of
generating a different canonical schedule. Matches without a persisted schedule
continue to use deterministic canonical round-robin generation.
generating a different canonical schedule. The persisted schedule must completely
cover every configured round and every Series in each round; incomplete schedules
are quarantined. If every round number is absent on an older schedule, migration
deterministically partitions its persisted opponent pairs into complete playable
rounds and emits a warning; mixed or unpartitionable schedules are quarantined.
Complete opponent sets use direct canonical factorization at any supported team
count. Partial opponent-only schedules use bounded reconstruction for at most 16
teams; larger or search-limit-exceeding inputs receive dedicated quarantine codes
instead of being mislabeled as invalid.
Matches without a persisted schedule continue to use deterministic canonical
round-robin generation.
- Legacy TournamentCode `gameNumber` is a global GameSlot number, not a Series
ordinal. Migration resolves it through accepted Riot evidence first, then the
persisted format topology (`gameSchedule` or double-elimination bracket layout),
@@ -286,7 +295,28 @@ Migration builds new collections without dual canonical writes.
Series/GameSlot must agree. A multi-slot Series is never assigned to its first
GameSlot as a fallback; missing, conflicting, duplicated, or out-of-range evidence
is quarantined without changing the legacy Match or TournamentCode.
- Dry-run is the default and emits machine-readable and human-readable reports.
- TournamentCode pool documents may retain timestamps from an earlier binding after
reuse. Migration preserves only the lifecycle reachable from the current state
(`reserved`, `used`, `released`, or `voided`) and validates that current lifecycle;
stale timestamps from a previous binding are not copied into the new assignment.
Riot match identity is likewise carried only for the current `used` or `voided`
binding, never from a restored `reserved` or `released` pool document.
- Historical result collection and repair paths stored Riot occurrence time (archive
game end/game creation, or game creation plus duration) in legacy `usedAt`, whereas
Competition assignments define `usedAt` as the persisted state-transition time.
Migration maps recognized legacy occurrence values to `TournamentCode.updatedAt`
for every `used` assignment only when an archive-backed accepted game has the same
Riot identity and
`max(reservedAt, original usedAt) <= updatedAt <= fact.recordedAt`. This also
safely covers post-game attachment where legacy `usedAt < reservedAt`. Source
values, evidence strategy, slot identity, and normalized time are emitted as an
audit warning. A recognized occurrence value without a valid persisted transition,
and any uncorroborated inverted lifecycle, remains quarantined. A chronological
`usedAt` that does not match a known occurrence encoding continues through the
ordinary lifecycle validation because it may already represent transition time.
- Dry-run is the default and emits machine-readable and human-readable reports. Every
ready/apply result includes a deterministic `planHash` over the graph, facts, and
TournamentCode targets so audits detect target changes even when counts stay equal.
- Apply is resumable, idempotent, transactionally scoped per Match, and verifies fact
replay equality after every write.
- Apply explicitly creates or verifies every Competition unique/partial index before
+170
View File
@@ -0,0 +1,170 @@
# Spec: Internal Match Game Analysis P0/P1
## Objective
Make an internal-match game result explain both the final numbers and how the game
reached them. P0 exposes data already present in the detail response: objective
events, complete team objectives, participant gold/GPM, and explicitly labelled
kill participation. P1 projects Riot Match-V5 timeline frames into real 10- and
15-minute lane checkpoints and a unified event stream for kills and structures.
The primary user is a tournament participant or organizer reviewing a completed
game on desktop or mobile. Success means the user can identify the major objective
sequence before reading ten player cards, compare lane state at 10/15 minutes, and
trace kills and building events without mistaking unavailable data for zero.
## Approved Product Decisions
- Place game flow immediately after the game summary and before detail tabs.
- Render chart events as both visual markers and a keyboard-readable text list.
- Keep the existing gold/XP toggle and runes/build experience.
- Show tower, dragon, inhibitor, Baron, Rift Herald, Void Grub, and Elder Dragon
totals; derive dragon type labels only when objective events are available.
- Combine participant CS and economy instead of adding another wide table column.
- Label kill participation explicitly as `KP`.
- Replace final-state values in the lane tab with 10/15-minute checkpoints; default
to 15 minutes and pair players by `teamPosition`, never array position.
- Keep `objectiveEvents` for compatibility and add `timelineEvents` for the unified
P1 stream.
- Treat missing checkpoints and events as unavailable, not zero.
- Do not add an opaque MVP/rating or new external data feed in this scope.
## Tech Stack
- React 19, TypeScript 6, Recharts 3, Tailwind CSS 4, and daisyUI under `apps/web`
- NestJS 11, TypeScript 5, Mongoose 9, and Jest under `apps/api`
- Riot Match-V5 match and timeline payloads already cached in `RiotMatchModel`
- Node's built-in test runner for pure web transformations
## Commands
- Focused web tests: `pnpm --filter web test`
- Web lint: `pnpm --filter web lint`
- Web production build: `pnpm --filter web build:prod`
- Focused API tests: `pnpm --filter api test -- --runInBand riot-match.service.spec.ts match-stats-fragment.builder.spec.ts community-stats.service.spec.ts`
- API build: `pnpm --filter api build`
- Development web server: `pnpm --filter web start:dev`
## Project Structure
- `apps/web/src/pages/MatchGameDetailPage.tsx` owns the result summary,
participant scoreboard, flow chart, and accessible event list.
- `apps/web/src/components/InternalGameAnalysisTabs.tsx` owns the lane and build
tabs.
- `apps/web/src/lib/internal-match-timeline.ts` owns pure event normalization,
labels, filtering, and chart projection.
- `apps/web/src/lib/internal-game-matchups.ts` owns pure role pairing and checkpoint
comparisons.
- `apps/web/test/` contains Node unit tests for the pure web transformations.
- `apps/api/src/modules/riot/` parses trusted fields from Riot match timelines.
- `apps/api/src/modules/community-stats/match-stats-fragment.builder.ts` projects
stored Riot payloads into cached internal-match records.
- `apps/api/src/modules/community-stats/community-stats.service.ts` maps persisted
records into the public detail response and versions response caches.
- `apps/api/src/modules/global/database/schema.ts` defines persisted TypeScript
shapes; nested `gameDetails` remains a Mongoose Mixed array.
## Data Contract
Participant checkpoint data is additive and optional for legacy/fallback games:
```ts
interface MatchStatsCheckpoint {
timestamp: number;
gold: number;
cs: number;
xp: number;
kills: number;
deaths: number;
assists: number;
}
interface MatchStatsParticipantCheckpoints {
at10?: MatchStatsCheckpoint;
at15?: MatchStatsCheckpoint;
}
```
Each detailed participant gains optional `participantId` and `checkpoints`. Each
game gains optional `timelineEvents`, whose `type` is an existing objective type or
`championKill`, `tower`, or `inhibitor`. Actor IDs, assists, monster subtype, and
tower subtype are optional fields appropriate to the event type.
For a 10/15-minute target, use the latest frame at or before the target only when it
is less than one `frameInterval` old. Persist the actual selected timestamp. CS is
`minionsKilled + jungleMinionsKilled`; checkpoint K/D/A includes champion-kill
events through the selected timestamp. A game ending before a target has no value
for that checkpoint.
## Code Style
Keep timeline calculations independent from React and use discriminated event
types with conservative fallbacks:
```ts
const events = game.timelineEvents?.length
? game.timelineEvents
: game.objectiveEvents;
const checkpoint = participant.checkpoints?.at15;
if (!checkpoint) return { kind: "unavailable" };
```
Use existing semantic color tokens and square bordered panels. Dynamic chart
coordinates may use numeric props; spacing, colors, and typography remain in the
existing Tailwind/daisyUI system.
## Testing Strategy
- Develop pure event normalization, checkpoint selection, role pairing, and metric
comparison test-first.
- Builder tests cover exact and missing checkpoints, jungle CS, cumulative K/D/A,
executes, objective fallback, building ownership, and deterministic event order.
- Service tests reject stale cached response shapes and verify additive mapping.
- Browser verification covers 320px, 390px, 768px, 1024px, and 1440px; the event
text list is the accessible equivalent of decorative chart markers.
- Verify the supplied production-like game as well as a short game and a game with
no timeline.
## Boundaries
### Always
- Preserve existing `objectiveEvents`, runes/builds, and match-detail routes.
- Derive participant checkpoint values from stored Riot timeline frames.
- Pair lanes by normalized `teamPosition` and show unavailable states explicitly.
- Communicate team/event meaning with text as well as color.
- Increment the match-stats builder and detail-response cache versions whenever a
persisted or cached response shape changes.
### Ask First
- Add a frontend or backend dependency.
- Change the public route or remove compatibility fields.
- Add a database migration or make a bulk external Riot API fetch.
- Deploy, push, or alter CI configuration.
### Never
- Infer absent checkpoint data as zero.
- Pair opponents by array order.
- Claim that a nearby objective caused a gold swing.
- Expose unparsed arbitrary Riot event fields.
- Modify unrelated Competition/bracket work already present in the worktree.
## Success Criteria
- Game flow appears before player details and includes objective markers plus an
equivalent textual sequence on desktop and mobile.
- Summary shows all currently projected objective totals and available dragon types.
- Every participant shows labelled KP, gold, GPM, CS, and CS/min without breaking
the responsive scoreboard.
- The lane tab defaults to 15 minutes, can switch to 10 minutes, and presents
GD/CSD/XPD and checkpoint K/D/A for correctly paired roles.
- The unified timeline can filter and display objectives, champion kills, towers,
and inhibitors, while falling back to objective-only data during rolling updates.
- Focused API/web tests, lint, and production builds pass.
## Open Questions
None. The user reviewed the P0/P1 task plan and requested implementation.
+131
View File
@@ -0,0 +1,131 @@
# Spec: Series Result History UI
## Objective
Replace the compact `Game N - winner` cards below Competition brackets with a
chronological, Series-centric result history. Users should be able to scan when a
Series was played, its round, participants, official result, and current score,
then expand the row to inspect the accepted Games that produced that record.
This first version is a truthful activity/result history, not a future schedule.
It uses only recorded Competition projection data and does not invent scheduled
times, venues, replay links, or team logos.
## Approved Product Decisions
- Keep the bracket first as the topology view and place the chronological history
below it.
- Render one primary row per Series, never one primary row per Game.
- Include a started `in-progress` Series when it has at least one accepted Game, so
completed Games do not disappear while a best-of Series is still running.
- Include every completed Series, including draw, walkover, forfeit, and
administrative outcomes with no accepted Game.
- Exclude inactive, waiting, ready, and game-less in-progress Series because they do
not have a truthful result timestamp.
- Use the earliest accepted Game `startedAt` as the Series activity time. For a
game-less decision, group by `outcome.completedAt` but display no fake start time.
- Group and format dates explicitly in `Asia/Seoul`.
- Keep individual Games in a native, keyboard-accessible disclosure below the Series
row.
## Tech Stack
- React 19 and TypeScript 6 under `apps/web`
- Tailwind CSS 4 and daisyUI semantic tokens
- Shared Competition contracts from `@lolympus/contracts`
- Node's built-in test runner with TypeScript type stripping for pure model tests
## Commands
- Focused RED/GREEN test:
`pnpm --filter web exec node --test --experimental-strip-types test/competition-series-history.test.ts`
- Full web tests: `pnpm --filter web test`
- Web lint: `pnpm --filter web lint`
- Web build: `pnpm --filter web build`
## Project Structure
- `apps/web/src/components/competition/competition-series-history.ts` derives the
stable, timezone-aware history view model without React.
- `apps/web/src/components/competition/CompetitionSeriesHistory.tsx` renders the
semantic date sections, responsive Series rows, and Game disclosures.
- `apps/web/src/components/competition/CompetitionResults.tsx` replaces the existing
completed-Game card grid with the new component.
- `apps/web/test/competition-series-history.test.ts` specifies aggregation, ordering,
outcome, and formatting behavior.
## Code Style
Use contract discriminators and team IDs as the source of truth:
```ts
const shouldInclude =
(series.status === "in-progress" && games.length > 0) ||
series.status === "completed";
const winnerTeamId =
series.status === "completed" && series.outcome.type !== "draw"
? series.outcome.winnerTeamId
: undefined;
```
The UI uses flat, full-width rows and existing semantic tokens. It does not reuse
the bordered bracket card layout or introduce new dependencies.
## Testing Strategy
Develop the pure model test-first. Cover:
- Games aggregated by `seriesId` and ordered by Series-local `ordinal`;
- Series score preserved from A/B entries even when blue/red sides change;
- chronological ordering independent of projection graph order;
- `Asia/Seoul` grouping across the UTC day boundary;
- started in-progress Series and game-less completed decisions;
- exclusion of unstarted and orphan data;
- played, draw, walkover, forfeit, and administrative status semantics;
- deterministic tie-breaking and legacy zero-duration formatting.
After unit tests, run full web tests, changed-file lint, and the TypeScript/Vite build.
Review the markup for native keyboard interaction, heading order, visible status text,
and mobile layouts down to 320px.
## Boundaries
### Always
- Use `series.entries` for A/B score and `outcome.winnerTeamId` for the official
winner; never infer identity from score, array position, or blue/red side.
- Keep game-less adjudications visible without presenting `0 : 0` as a played score.
- Omit `durationSeconds === 0` because it represents missing legacy data.
- Preserve all unrelated working-tree changes.
### Ask First
- Change the public Competition contract, database schema, or projector.
- Add Series scheduling or external replay/venue data.
- Add a frontend dependency or test framework.
### Never
- Present `completedAt` as a scheduled or actual start time.
- Reuse free-text `match.schedule` as official Series scheduling data.
- Parse `series.code` for identity, winner, or ordering.
- Make status or winner understandable only through color.
## Success Criteria
- A completed `2 : 1` Series appears as one chronological row with both teams, the
official score, round label, status, and an expandable three-Game history.
- In-progress Series retain already accepted Games and display `진행 중`.
- No-game decisions appear with the correct decision label and no misleading score
or start time.
- Date grouping and time display are stable in `Asia/Seoul` regardless of runtime
timezone.
- The layout is readable without horizontal scrolling at 320px and uses the wider
double-elimination page naturally on desktop.
- Focused/full tests, lint, and web build pass without modifying unrelated work.
## Open Questions
None. The user approved the Series-centric, result-history-first direction and
requested implementation.
+11 -13
View File
@@ -1,8 +1,5 @@
import type { TeamId } from "./ids.js";
import type {
FirstToSeriesRule,
FixedGamesSeriesRule,
} from "./series.js";
import type { FirstToSeriesRule, FixedGamesSeriesRule } from "./series.js";
export type CompetitionFormatType =
| "paired-series"
@@ -14,20 +11,21 @@ export interface PairedSeriesCompetitionFormat {
rule: FixedGamesSeriesRule;
}
export type RoundRobinTieBreaker =
| "series-wins"
| "game-diff"
| "head-to-head";
export type RoundRobinTieBreaker = "series-wins" | "game-diff" | "head-to-head";
export interface RoundRobinPairing {
roundNumber: number;
matchNumber: number;
teamAId: TeamId;
teamBId: TeamId;
}
export interface RoundRobinCompetitionFormat {
type: "round-robin";
rule: FixedGamesSeriesRule;
maxRounds?: number;
tieBreakers: [
"series-wins",
"game-diff",
"head-to-head",
];
pairings?: RoundRobinPairing[];
tieBreakers: ["series-wins", "game-diff", "head-to-head"];
}
export interface DoubleEliminationSeriesRules {
@@ -3,6 +3,7 @@ import type {
CompetitionId,
CompletedSeriesProjection,
InProgressSeriesProjection,
RoundRobinCompetitionFormat,
SeriesOutcome,
TeamId,
} from "../src/index.js";
@@ -26,3 +27,23 @@ export type InProgressSeriesCannotExposeOutcome = Expect<
export type LegacyBracketModeIsNotACompetitionFormat = Expect<
Not<IsAssignable<{ type: "bracket" }, CompetitionFormat>>
>;
type ExplicitRoundRobinPairing = NonNullable<
RoundRobinCompetitionFormat["pairings"]
>[number];
export type ExplicitRoundRobinPairingsAreOptional = Expect<
IsAssignable<{}, Pick<RoundRobinCompetitionFormat, "pairings">>
>;
export type ExplicitRoundRobinPairingsAreTeamIdBased = Expect<
IsAssignable<
ExplicitRoundRobinPairing,
{
roundNumber: number;
matchNumber: number;
teamAId: TeamId;
teamBId: TeamId;
}
>
>;