996 lines
28 KiB
TypeScript
996 lines
28 KiB
TypeScript
import { assertCompetitionInvariant } from './domain-error';
|
|
import type {
|
|
CompetitionGraphFormat,
|
|
CompetitionGraphTeam,
|
|
ParticipantSource,
|
|
SeriesDefinition,
|
|
} from './series-graph';
|
|
import {
|
|
projectSeries,
|
|
type SeriesDefinitionLike,
|
|
type SeriesProjection,
|
|
type SeriesProjectionOutcome,
|
|
} from './series-projector';
|
|
|
|
export interface ProjectCompetitionInput {
|
|
competitionId: string;
|
|
revision: number;
|
|
projectorVersion: number;
|
|
teams: readonly CompetitionGraphTeam[];
|
|
format: CompetitionGraphFormat;
|
|
seriesGraph: readonly SeriesDefinition[];
|
|
facts: readonly unknown[];
|
|
}
|
|
|
|
export interface RoundRobinStanding {
|
|
teamId: string;
|
|
rank: number;
|
|
seriesPlayed: number;
|
|
seriesWins: number;
|
|
seriesLosses: number;
|
|
seriesDraws: number;
|
|
gameWins: number;
|
|
gameLosses: number;
|
|
gameDiff: number;
|
|
}
|
|
|
|
export interface CompetitionPlacement {
|
|
teamId: string;
|
|
rank: number;
|
|
}
|
|
|
|
export interface CompetitionGameProjection {
|
|
id: string;
|
|
seriesId: string;
|
|
gameSlotId: string;
|
|
ordinal: number;
|
|
displayNumber: number;
|
|
evidence:
|
|
| { type: 'riot'; riotMatchId: string }
|
|
| { type: 'legacy'; legacyReference: string };
|
|
teams: {
|
|
blue: { side: 'blue'; teamId: string };
|
|
red: { side: 'red'; teamId: string };
|
|
};
|
|
winnerTeamId: string;
|
|
startedAt: string;
|
|
durationSeconds: number;
|
|
participants: unknown[];
|
|
}
|
|
|
|
export interface GameSlotProjection {
|
|
id: string;
|
|
seriesId: string;
|
|
ordinal: number;
|
|
displayNumber: number;
|
|
status: 'inactive' | 'waiting' | 'ready' | 'completed' | 'voided';
|
|
entries: [
|
|
{ slot: 'A'; teamId: string | null },
|
|
{ slot: 'B'; teamId: string | null },
|
|
];
|
|
gameId?: string;
|
|
}
|
|
|
|
export interface BracketRoundProjection {
|
|
stage: SeriesDefinition['stage']['type'];
|
|
roundNumber?: number;
|
|
displayOrder: number;
|
|
label: string;
|
|
seriesIds: string[];
|
|
}
|
|
|
|
export interface SeriesConnectorProjection {
|
|
from: {
|
|
seriesId: string;
|
|
select: 'winner' | 'loser' | 'slot-a' | 'slot-b';
|
|
};
|
|
to: { seriesId: string; slot: 'A' | 'B' };
|
|
}
|
|
|
|
export type CompetitionProjectionOutcome =
|
|
| {
|
|
type: 'paired-series';
|
|
completedSeriesIds: string[];
|
|
drawnSeriesIds: string[];
|
|
completedAt: string;
|
|
}
|
|
| {
|
|
type: 'round-robin';
|
|
leaderTeamIds: string[];
|
|
standings: RoundRobinStanding[];
|
|
completedAt: string;
|
|
}
|
|
| {
|
|
type: 'double-elimination';
|
|
championTeamId: string;
|
|
placements: CompetitionPlacement[];
|
|
completedAt: string;
|
|
};
|
|
|
|
export interface CompetitionProjection {
|
|
competitionId: string;
|
|
sourceRevision: number;
|
|
projectorVersion: number;
|
|
formatType: CompetitionGraphFormat['type'];
|
|
phase: 'ready' | 'running' | 'completed';
|
|
series: SeriesProjection[];
|
|
games: CompetitionGameProjection[];
|
|
gameSlots: GameSlotProjection[];
|
|
rounds: BracketRoundProjection[];
|
|
connectors: SeriesConnectorProjection[];
|
|
standings?: RoundRobinStanding[];
|
|
placements?: CompetitionPlacement[];
|
|
outcome?: CompetitionProjectionOutcome;
|
|
}
|
|
|
|
/**
|
|
* Rebuilds all official Competition state from the immutable graph and fact
|
|
* ledger. Participant identity is always resolved through explicit sources;
|
|
* display codes and slot/array order are never used as team identity.
|
|
*/
|
|
export function projectCompetition(
|
|
input: ProjectCompetitionInput,
|
|
): CompetitionProjection {
|
|
assertPrimaryFactTargetsGraph(input.seriesGraph, input.facts);
|
|
const teamBySeed = new Map<number, string>();
|
|
const knownTeams = new Set<string>();
|
|
for (const team of input.teams) {
|
|
knownTeams.add(team.teamId);
|
|
if (team.seedNumber !== undefined) {
|
|
teamBySeed.set(team.seedNumber, team.teamId);
|
|
}
|
|
}
|
|
|
|
const definitionsById = new Map(
|
|
input.seriesGraph.map((definition) => [definition.id, definition]),
|
|
);
|
|
const projectedById = new Map<string, SeriesProjection>();
|
|
const remaining = new Set(input.seriesGraph.map(({ id }) => id));
|
|
|
|
// A graph can be stored in any display order. Resolve it as a DAG rather
|
|
// than relying on that order or parsing diagnostic codes such as WB_R2_M2.
|
|
let madeProgress = true;
|
|
while (remaining.size > 0 && madeProgress) {
|
|
madeProgress = false;
|
|
|
|
for (const seriesId of [...remaining]) {
|
|
const definition = definitionsById.get(seriesId)!;
|
|
const activation = resolveActivation(definition, projectedById);
|
|
if (activation === 'pending') continue;
|
|
|
|
if (activation === 'inactive') {
|
|
projectedById.set(
|
|
definition.id,
|
|
projectSeries({
|
|
definition: asProjectorDefinition(definition),
|
|
participants: resolveAvailableParticipants(
|
|
definition,
|
|
knownTeams,
|
|
teamBySeed,
|
|
projectedById,
|
|
),
|
|
facts: input.facts,
|
|
active: false,
|
|
}),
|
|
);
|
|
remaining.delete(seriesId);
|
|
madeProgress = true;
|
|
continue;
|
|
}
|
|
|
|
const participants = definition.slots.map(({ source }) =>
|
|
resolveParticipant(source, knownTeams, teamBySeed, projectedById),
|
|
);
|
|
if (participants.some((teamId) => teamId === undefined)) continue;
|
|
|
|
projectedById.set(
|
|
definition.id,
|
|
projectSeries({
|
|
definition: asProjectorDefinition(definition),
|
|
participants,
|
|
facts: input.facts,
|
|
}),
|
|
);
|
|
remaining.delete(seriesId);
|
|
madeProgress = true;
|
|
}
|
|
}
|
|
|
|
// An unresolved outcome source is a normal waiting bracket node. Conditional
|
|
// reset nodes remain inactive until their grand-final condition is known.
|
|
for (const seriesId of remaining) {
|
|
const definition = definitionsById.get(seriesId)!;
|
|
const participants = resolveAvailableParticipants(
|
|
definition,
|
|
knownTeams,
|
|
teamBySeed,
|
|
projectedById,
|
|
);
|
|
projectedById.set(
|
|
definition.id,
|
|
projectSeries({
|
|
definition: asProjectorDefinition(definition),
|
|
participants,
|
|
facts: input.facts,
|
|
...(definition.activation ? { active: false } : {}),
|
|
}),
|
|
);
|
|
}
|
|
|
|
const series = input.seriesGraph.map(({ id }) => projectedById.get(id)!);
|
|
const gameProjection = projectGamesAndSlots(
|
|
input.seriesGraph,
|
|
series,
|
|
input.facts,
|
|
);
|
|
const common = {
|
|
competitionId: input.competitionId,
|
|
sourceRevision: input.revision,
|
|
projectorVersion: input.projectorVersion,
|
|
formatType: input.format.type,
|
|
series,
|
|
games: gameProjection.games,
|
|
gameSlots: gameProjection.gameSlots,
|
|
rounds: projectRounds(input.seriesGraph),
|
|
connectors: projectConnectors(input.seriesGraph),
|
|
};
|
|
|
|
switch (input.format.type) {
|
|
case 'paired-series': {
|
|
const outcome = pairedSeriesOutcome(series);
|
|
return {
|
|
...common,
|
|
phase: phaseFor(series, outcome),
|
|
...(outcome ? { outcome } : {}),
|
|
};
|
|
}
|
|
case 'round-robin': {
|
|
const standings = roundRobinStandings(input.teams, series);
|
|
const outcome =
|
|
series.length > 0 &&
|
|
series.every(({ status }) => status === 'completed')
|
|
? {
|
|
type: 'round-robin' as const,
|
|
leaderTeamIds: standings
|
|
.filter(({ rank }) => rank === 1)
|
|
.map(({ teamId }) => teamId),
|
|
standings,
|
|
completedAt: competitionCompletedAt(series),
|
|
}
|
|
: undefined;
|
|
return {
|
|
...common,
|
|
phase: phaseFor(series, outcome),
|
|
standings,
|
|
...(outcome ? { outcome } : {}),
|
|
};
|
|
}
|
|
case 'double-elimination': {
|
|
const outcome = doubleEliminationOutcome(
|
|
input.teams,
|
|
input.format.resetFinalEnabled,
|
|
series,
|
|
);
|
|
return {
|
|
...common,
|
|
phase: phaseFor(series, outcome),
|
|
placements: outcome?.placements ?? [],
|
|
...(outcome ? { outcome } : {}),
|
|
};
|
|
}
|
|
}
|
|
}
|
|
|
|
function assertPrimaryFactTargetsGraph(
|
|
graph: readonly SeriesDefinition[],
|
|
facts: readonly unknown[],
|
|
): void {
|
|
const definitionsById = new Map(
|
|
graph.map((definition) => [definition.id, definition]),
|
|
);
|
|
|
|
for (const fact of facts) {
|
|
if (!isRecord(fact)) continue;
|
|
|
|
if (fact.type === 'game-accepted') {
|
|
const seriesId =
|
|
typeof fact.seriesId === 'string' ? fact.seriesId : undefined;
|
|
const definition = seriesId ? definitionsById.get(seriesId) : undefined;
|
|
assertCompetitionInvariant(
|
|
definition !== undefined,
|
|
'GAME_SERIES_MISMATCH',
|
|
`Accepted game targets an unknown Series ${String(fact.seriesId)}`,
|
|
{ factId: fact.id, seriesId: fact.seriesId },
|
|
);
|
|
|
|
const gameSlot = definition.gameSlots.find(
|
|
({ id }) => id === fact.gameSlotId,
|
|
);
|
|
assertCompetitionInvariant(
|
|
gameSlot !== undefined,
|
|
'GAME_SLOT_INVALID',
|
|
`Accepted game targets an unknown GameSlot ${String(fact.gameSlotId)}`,
|
|
{
|
|
factId: fact.id,
|
|
seriesId: definition.id,
|
|
gameSlotId: fact.gameSlotId,
|
|
},
|
|
);
|
|
assertCompetitionInvariant(
|
|
gameSlot.ordinal === fact.ordinal,
|
|
'GAME_ORDINAL_INVALID',
|
|
`Accepted game ordinal does not match GameSlot ${gameSlot.id}`,
|
|
{
|
|
factId: fact.id,
|
|
gameSlotId: gameSlot.id,
|
|
expectedOrdinal: gameSlot.ordinal,
|
|
actualOrdinal: fact.ordinal,
|
|
},
|
|
);
|
|
continue;
|
|
}
|
|
|
|
if (fact.type === 'series-adjudicated') {
|
|
const seriesId =
|
|
typeof fact.seriesId === 'string' ? fact.seriesId : undefined;
|
|
assertCompetitionInvariant(
|
|
seriesId !== undefined && definitionsById.has(seriesId),
|
|
'ADJUDICATION_INVALID',
|
|
`Adjudication targets an unknown Series ${String(fact.seriesId)}`,
|
|
{ factId: fact.id, seriesId: fact.seriesId },
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
function asProjectorDefinition(
|
|
definition: SeriesDefinition,
|
|
): SeriesDefinitionLike {
|
|
return definition as unknown as SeriesDefinitionLike;
|
|
}
|
|
|
|
function resolveActivation(
|
|
definition: SeriesDefinition,
|
|
projections: ReadonlyMap<string, SeriesProjection>,
|
|
): 'active' | 'inactive' | 'pending' {
|
|
if (!definition.activation) return 'active';
|
|
|
|
const grandFinal = projections.get(definition.activation.grandFinalSeriesId);
|
|
if (!grandFinal || grandFinal.status !== 'completed') return 'pending';
|
|
if (grandFinal.outcome.type === 'draw') return 'inactive';
|
|
|
|
const lowerBracketFinalist = grandFinal.entries.find(
|
|
({ slot }) => slot === 'B',
|
|
)?.teamId;
|
|
return grandFinal.outcome.winnerTeamId === lowerBracketFinalist
|
|
? 'active'
|
|
: 'inactive';
|
|
}
|
|
|
|
function resolveAvailableParticipants(
|
|
definition: SeriesDefinition,
|
|
knownTeams: ReadonlySet<string>,
|
|
teamBySeed: ReadonlyMap<number, string>,
|
|
projections: ReadonlyMap<string, SeriesProjection>,
|
|
): Array<string | null> {
|
|
return definition.slots.map(
|
|
({ source }) =>
|
|
resolveParticipant(source, knownTeams, teamBySeed, projections) ?? null,
|
|
);
|
|
}
|
|
|
|
function resolveParticipant(
|
|
source: ParticipantSource,
|
|
knownTeams: ReadonlySet<string>,
|
|
teamBySeed: ReadonlyMap<number, string>,
|
|
projections: ReadonlyMap<string, SeriesProjection>,
|
|
): string | undefined {
|
|
switch (source.type) {
|
|
case 'team':
|
|
return knownTeams.has(source.teamId) ? source.teamId : undefined;
|
|
case 'seed':
|
|
return teamBySeed.get(source.seedNumber);
|
|
case 'series-outcome': {
|
|
const sourceSeries = projections.get(source.seriesId);
|
|
if (!sourceSeries || sourceSeries.status !== 'completed') {
|
|
return undefined;
|
|
}
|
|
if (sourceSeries.outcome.type === 'draw') return undefined;
|
|
return source.select === 'winner'
|
|
? sourceSeries.outcome.winnerTeamId
|
|
: sourceSeries.outcome.loserTeamId;
|
|
}
|
|
case 'series-slot': {
|
|
const sourceSeries = projections.get(source.seriesId);
|
|
return (
|
|
sourceSeries?.entries.find(({ slot }) => slot === source.slot)
|
|
?.teamId ?? undefined
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
function pairedSeriesOutcome(
|
|
series: readonly SeriesProjection[],
|
|
):
|
|
| Extract<CompetitionProjectionOutcome, { type: 'paired-series' }>
|
|
| undefined {
|
|
if (
|
|
series.length === 0 ||
|
|
!series.every(({ status }) => status === 'completed')
|
|
) {
|
|
return undefined;
|
|
}
|
|
return {
|
|
type: 'paired-series',
|
|
completedSeriesIds: series
|
|
.filter(
|
|
(candidate) =>
|
|
candidate.status === 'completed' && candidate.outcome.type !== 'draw',
|
|
)
|
|
.map(({ seriesId }) => seriesId),
|
|
completedAt: competitionCompletedAt(series),
|
|
drawnSeriesIds: series
|
|
.filter(
|
|
(candidate) =>
|
|
candidate.status === 'completed' && candidate.outcome.type === 'draw',
|
|
)
|
|
.map(({ seriesId }) => seriesId),
|
|
};
|
|
}
|
|
|
|
function roundRobinStandings(
|
|
teams: readonly CompetitionGraphTeam[],
|
|
series: readonly SeriesProjection[],
|
|
): RoundRobinStanding[] {
|
|
const standingByTeam = new Map(
|
|
teams.map((team) => [team.teamId, emptyStanding(team.teamId)]),
|
|
);
|
|
const completed = series.filter(
|
|
(candidate): candidate is SeriesProjection & { status: 'completed' } =>
|
|
candidate.status === 'completed',
|
|
);
|
|
|
|
for (const projected of completed) {
|
|
addSeriesToStandings(standingByTeam, projected);
|
|
}
|
|
|
|
const displayOrderByTeam = new Map(
|
|
teams.map(({ teamId, displayOrder }) => [teamId, displayOrder]),
|
|
);
|
|
const base = [...standingByTeam.values()].sort(
|
|
(left, right) =>
|
|
right.seriesWins - left.seriesWins ||
|
|
right.gameDiff - left.gameDiff ||
|
|
stableTeamOrder(left.teamId, right.teamId, displayOrderByTeam),
|
|
);
|
|
|
|
const ranked: RoundRobinStanding[] = [];
|
|
let start = 0;
|
|
while (start < base.length) {
|
|
let end = start + 1;
|
|
while (
|
|
end < base.length &&
|
|
base[end].seriesWins === base[start].seriesWins &&
|
|
base[end].gameDiff === base[start].gameDiff
|
|
) {
|
|
end += 1;
|
|
}
|
|
|
|
const tiedGroup = base.slice(start, end);
|
|
const teamIds = new Set(tiedGroup.map(({ teamId }) => teamId));
|
|
const miniTable = new Map(
|
|
tiedGroup.map(({ teamId }) => [teamId, emptyMiniTableRow()]),
|
|
);
|
|
for (const projected of completed) {
|
|
const participants = projected.entries.map(({ teamId }) => teamId);
|
|
if (
|
|
participants.length === 2 &&
|
|
participants.every(
|
|
(teamId): teamId is string => teamId !== null && teamIds.has(teamId),
|
|
)
|
|
) {
|
|
addSeriesToMiniTable(miniTable, projected);
|
|
}
|
|
}
|
|
|
|
tiedGroup.sort((left, right) => {
|
|
const leftMini = miniTable.get(left.teamId)!;
|
|
const rightMini = miniTable.get(right.teamId)!;
|
|
return (
|
|
rightMini.seriesWins - leftMini.seriesWins ||
|
|
rightMini.gameDiff - leftMini.gameDiff ||
|
|
stableTeamOrder(left.teamId, right.teamId, displayOrderByTeam)
|
|
);
|
|
});
|
|
|
|
let tiedStart = 0;
|
|
while (tiedStart < tiedGroup.length) {
|
|
const reference = miniTable.get(tiedGroup[tiedStart].teamId)!;
|
|
let tiedEnd = tiedStart + 1;
|
|
while (tiedEnd < tiedGroup.length) {
|
|
const candidate = miniTable.get(tiedGroup[tiedEnd].teamId)!;
|
|
if (
|
|
candidate.seriesWins !== reference.seriesWins ||
|
|
candidate.gameDiff !== reference.gameDiff
|
|
) {
|
|
break;
|
|
}
|
|
tiedEnd += 1;
|
|
}
|
|
|
|
const rank = start + tiedStart + 1;
|
|
for (const standing of tiedGroup.slice(tiedStart, tiedEnd)) {
|
|
ranked.push({ ...standing, rank });
|
|
}
|
|
tiedStart = tiedEnd;
|
|
}
|
|
start = end;
|
|
}
|
|
|
|
return ranked;
|
|
}
|
|
|
|
function emptyStanding(teamId: string): RoundRobinStanding {
|
|
return {
|
|
teamId,
|
|
rank: 0,
|
|
seriesWins: 0,
|
|
seriesLosses: 0,
|
|
seriesDraws: 0,
|
|
seriesPlayed: 0,
|
|
gameWins: 0,
|
|
gameLosses: 0,
|
|
gameDiff: 0,
|
|
};
|
|
}
|
|
|
|
function addSeriesToStandings(
|
|
rows: Map<string, RoundRobinStanding>,
|
|
projected: SeriesProjection & { status: 'completed' },
|
|
): void {
|
|
const [entryA, entryB] = projected.entries;
|
|
if (entryA.teamId === null || entryB.teamId === null) return;
|
|
const rowA = rows.get(entryA.teamId);
|
|
const rowB = rows.get(entryB.teamId);
|
|
if (!rowA || !rowB) return;
|
|
|
|
rowA.gameWins += entryA.gameWins;
|
|
rowA.gameLosses += entryB.gameWins;
|
|
rowB.gameWins += entryB.gameWins;
|
|
rowB.gameLosses += entryA.gameWins;
|
|
rowA.gameDiff = rowA.gameWins - rowA.gameLosses;
|
|
rowB.gameDiff = rowB.gameWins - rowB.gameLosses;
|
|
rowA.seriesPlayed += 1;
|
|
rowB.seriesPlayed += 1;
|
|
|
|
if (projected.outcome.type === 'draw') {
|
|
rowA.seriesDraws += 1;
|
|
rowB.seriesDraws += 1;
|
|
return;
|
|
}
|
|
rows.get(projected.outcome.winnerTeamId)!.seriesWins += 1;
|
|
rows.get(projected.outcome.loserTeamId)!.seriesLosses += 1;
|
|
}
|
|
|
|
interface MiniTableRow {
|
|
seriesWins: number;
|
|
gameWins: number;
|
|
gameLosses: number;
|
|
gameDiff: number;
|
|
}
|
|
|
|
function emptyMiniTableRow(): MiniTableRow {
|
|
return { seriesWins: 0, gameWins: 0, gameLosses: 0, gameDiff: 0 };
|
|
}
|
|
|
|
function addSeriesToMiniTable(
|
|
rows: Map<string, MiniTableRow>,
|
|
projected: SeriesProjection & { status: 'completed' },
|
|
): void {
|
|
const [entryA, entryB] = projected.entries;
|
|
if (entryA.teamId === null || entryB.teamId === null) return;
|
|
const rowA = rows.get(entryA.teamId)!;
|
|
const rowB = rows.get(entryB.teamId)!;
|
|
rowA.gameWins += entryA.gameWins;
|
|
rowA.gameLosses += entryB.gameWins;
|
|
rowB.gameWins += entryB.gameWins;
|
|
rowB.gameLosses += entryA.gameWins;
|
|
rowA.gameDiff = rowA.gameWins - rowA.gameLosses;
|
|
rowB.gameDiff = rowB.gameWins - rowB.gameLosses;
|
|
if (projected.outcome.type !== 'draw') {
|
|
rows.get(projected.outcome.winnerTeamId)!.seriesWins += 1;
|
|
}
|
|
}
|
|
|
|
function doubleEliminationOutcome(
|
|
teams: readonly CompetitionGraphTeam[],
|
|
resetFinalEnabled: boolean,
|
|
series: readonly SeriesProjection[],
|
|
):
|
|
| Extract<CompetitionProjectionOutcome, { type: 'double-elimination' }>
|
|
| undefined {
|
|
const grandFinal = series.find(({ stage }) => stage.type === 'grand-final');
|
|
if (!grandFinal || grandFinal.status !== 'completed') return undefined;
|
|
if (grandFinal.outcome.type === 'draw') return undefined;
|
|
|
|
let decisiveOutcome: Exclude<SeriesProjectionOutcome, { type: 'draw' }> =
|
|
grandFinal.outcome;
|
|
const lowerFinalist = grandFinal.entries.find(
|
|
({ slot }) => slot === 'B',
|
|
)?.teamId;
|
|
if (resetFinalEnabled && grandFinal.outcome.winnerTeamId === lowerFinalist) {
|
|
const resetFinal = series.find(({ stage }) => stage.type === 'reset-final');
|
|
if (!resetFinal || resetFinal.status !== 'completed') return undefined;
|
|
if (resetFinal.outcome.type === 'draw') return undefined;
|
|
decisiveOutcome = resetFinal.outcome;
|
|
}
|
|
|
|
const championTeamId = decisiveOutcome.winnerTeamId;
|
|
const runnerUpTeamId = decisiveOutcome.loserTeamId;
|
|
const placements: CompetitionPlacement[] = [
|
|
{ teamId: championTeamId, rank: 1 },
|
|
{ teamId: runnerUpTeamId, rank: 2 },
|
|
];
|
|
const alreadyPlaced = new Set([championTeamId, runnerUpTeamId]);
|
|
const eliminatedByRound = new Map<number, string[]>();
|
|
|
|
for (const projected of series) {
|
|
if (
|
|
projected.stage.type !== 'lower' ||
|
|
projected.status !== 'completed' ||
|
|
projected.outcome.type === 'draw'
|
|
) {
|
|
continue;
|
|
}
|
|
const key = projected.stage.roundNumber ?? projected.stage.displayOrder;
|
|
const eliminated = eliminatedByRound.get(key) ?? [];
|
|
if (!alreadyPlaced.has(projected.outcome.loserTeamId)) {
|
|
eliminated.push(projected.outcome.loserTeamId);
|
|
}
|
|
eliminatedByRound.set(key, eliminated);
|
|
}
|
|
|
|
let nextRank = 3;
|
|
for (const [, eliminated] of [...eliminatedByRound].sort(
|
|
([left], [right]) => right - left,
|
|
)) {
|
|
const unique = [...new Set(eliminated)].filter(
|
|
(teamId) => !alreadyPlaced.has(teamId),
|
|
);
|
|
unique.sort(
|
|
(left, right) =>
|
|
teamDisplayOrder(left, teams) - teamDisplayOrder(right, teams),
|
|
);
|
|
for (const teamId of unique) {
|
|
placements.push({ teamId, rank: nextRank });
|
|
alreadyPlaced.add(teamId);
|
|
}
|
|
nextRank += unique.length;
|
|
}
|
|
|
|
// With a valid 4/8-team graph every team is accounted for by the decisive
|
|
// final or a lower-bracket elimination. Keep replay deterministic if an old
|
|
// migrated graph omitted placement metadata.
|
|
const unplaced = teams
|
|
.filter(({ teamId }) => !alreadyPlaced.has(teamId))
|
|
.sort((left, right) => left.displayOrder - right.displayOrder);
|
|
for (const { teamId } of unplaced) {
|
|
placements.push({ teamId, rank: nextRank });
|
|
nextRank += 1;
|
|
}
|
|
|
|
return {
|
|
type: 'double-elimination',
|
|
championTeamId,
|
|
placements,
|
|
completedAt: decisiveOutcome.completedAt,
|
|
};
|
|
}
|
|
|
|
interface AcceptedGameProjectionFact {
|
|
id: string;
|
|
type: 'game-accepted';
|
|
revision: number;
|
|
ordinalWithinRevision: number;
|
|
gameId: string;
|
|
seriesId: string;
|
|
gameSlotId: string;
|
|
ordinal: number;
|
|
occurredAt: Date | string;
|
|
startedAt?: Date | string;
|
|
durationSeconds?: number;
|
|
participants?: unknown[];
|
|
evidence?: {
|
|
type?: string;
|
|
riotMatchId?: string;
|
|
legacyReference?: string;
|
|
};
|
|
mapping: {
|
|
blueTeamId: string;
|
|
redTeamId: string;
|
|
winnerTeamId: string;
|
|
};
|
|
}
|
|
|
|
interface VoidedGameProjectionFact {
|
|
type: 'game-voided';
|
|
revision: number;
|
|
ordinalWithinRevision: number;
|
|
gameAcceptedFactId: string;
|
|
}
|
|
|
|
function projectGamesAndSlots(
|
|
graph: readonly SeriesDefinition[],
|
|
series: readonly SeriesProjection[],
|
|
facts: readonly unknown[],
|
|
): {
|
|
games: CompetitionGameProjection[];
|
|
gameSlots: GameSlotProjection[];
|
|
} {
|
|
const acceptedByFactId = new Map<string, AcceptedGameProjectionFact>();
|
|
const activeBySlotId = new Map<string, AcceptedGameProjectionFact>();
|
|
|
|
for (const fact of projectionGameFacts(facts)) {
|
|
if (fact.type === 'game-accepted') {
|
|
acceptedByFactId.set(fact.id, fact);
|
|
activeBySlotId.set(fact.gameSlotId, fact);
|
|
continue;
|
|
}
|
|
const accepted = acceptedByFactId.get(fact.gameAcceptedFactId);
|
|
if (!accepted) continue;
|
|
if (activeBySlotId.get(accepted.gameSlotId)?.id === accepted.id) {
|
|
activeBySlotId.delete(accepted.gameSlotId);
|
|
}
|
|
}
|
|
|
|
const displayNumberBySlotId = new Map<string, number>();
|
|
let displayNumber = 0;
|
|
for (const definition of graph) {
|
|
for (const slot of [...definition.gameSlots].sort(
|
|
(left, right) => left.ordinal - right.ordinal,
|
|
)) {
|
|
displayNumber += 1;
|
|
displayNumberBySlotId.set(slot.id, displayNumber);
|
|
}
|
|
}
|
|
|
|
const games = [...activeBySlotId.values()]
|
|
.sort(
|
|
(left, right) =>
|
|
(displayNumberBySlotId.get(left.gameSlotId) ?? 0) -
|
|
(displayNumberBySlotId.get(right.gameSlotId) ?? 0),
|
|
)
|
|
.map((fact) => ({
|
|
id: fact.gameId,
|
|
seriesId: fact.seriesId,
|
|
gameSlotId: fact.gameSlotId,
|
|
ordinal: fact.ordinal,
|
|
displayNumber: displayNumberBySlotId.get(fact.gameSlotId) ?? 0,
|
|
evidence:
|
|
fact.evidence?.type === 'riot' && fact.evidence.riotMatchId
|
|
? {
|
|
type: 'riot' as const,
|
|
riotMatchId: fact.evidence.riotMatchId,
|
|
}
|
|
: {
|
|
type: 'legacy' as const,
|
|
legacyReference:
|
|
fact.evidence?.legacyReference ?? `fact:${fact.id}`,
|
|
},
|
|
teams: {
|
|
blue: {
|
|
side: 'blue' as const,
|
|
teamId: fact.mapping.blueTeamId,
|
|
},
|
|
red: { side: 'red' as const, teamId: fact.mapping.redTeamId },
|
|
},
|
|
winnerTeamId: fact.mapping.winnerTeamId,
|
|
startedAt: toIsoString(fact.startedAt ?? fact.occurredAt),
|
|
durationSeconds:
|
|
typeof fact.durationSeconds === 'number' ? fact.durationSeconds : 0,
|
|
participants: Array.isArray(fact.participants)
|
|
? [...fact.participants]
|
|
: [],
|
|
}));
|
|
|
|
const projectedBySeriesId = new Map(
|
|
series.map((projection) => [projection.seriesId, projection]),
|
|
);
|
|
const gameSlots = graph.flatMap((definition) => {
|
|
const projected = projectedBySeriesId.get(definition.id)!;
|
|
const entries: GameSlotProjection['entries'] = [
|
|
{
|
|
slot: 'A',
|
|
teamId:
|
|
projected.entries.find(({ slot }) => slot === 'A')?.teamId ?? null,
|
|
},
|
|
{
|
|
slot: 'B',
|
|
teamId:
|
|
projected.entries.find(({ slot }) => slot === 'B')?.teamId ?? null,
|
|
},
|
|
];
|
|
return [...definition.gameSlots]
|
|
.sort((left, right) => left.ordinal - right.ordinal)
|
|
.map((slot) => {
|
|
const game = activeBySlotId.get(slot.id);
|
|
const status = game
|
|
? ('completed' as const)
|
|
: gameSlotStatus(projected.status);
|
|
return {
|
|
id: slot.id,
|
|
seriesId: definition.id,
|
|
ordinal: slot.ordinal,
|
|
displayNumber: displayNumberBySlotId.get(slot.id) ?? 0,
|
|
status,
|
|
entries,
|
|
...(game ? { gameId: game.gameId } : {}),
|
|
};
|
|
});
|
|
});
|
|
|
|
return { games, gameSlots };
|
|
}
|
|
|
|
function projectionGameFacts(
|
|
facts: readonly unknown[],
|
|
): Array<AcceptedGameProjectionFact | VoidedGameProjectionFact> {
|
|
return facts
|
|
.filter(
|
|
(fact): fact is AcceptedGameProjectionFact | VoidedGameProjectionFact =>
|
|
isRecord(fact) &&
|
|
(fact.type === 'game-accepted' || fact.type === 'game-voided'),
|
|
)
|
|
.sort(
|
|
(left, right) =>
|
|
left.revision - right.revision ||
|
|
left.ordinalWithinRevision - right.ordinalWithinRevision,
|
|
);
|
|
}
|
|
|
|
function gameSlotStatus(
|
|
status: SeriesProjection['status'],
|
|
): GameSlotProjection['status'] {
|
|
switch (status) {
|
|
case 'inactive':
|
|
return 'inactive';
|
|
case 'waiting':
|
|
return 'waiting';
|
|
case 'ready':
|
|
case 'in-progress':
|
|
return 'ready';
|
|
case 'completed':
|
|
return 'inactive';
|
|
}
|
|
}
|
|
|
|
function projectRounds(
|
|
graph: readonly SeriesDefinition[],
|
|
): BracketRoundProjection[] {
|
|
const rounds = new Map<string, BracketRoundProjection>();
|
|
for (const definition of graph) {
|
|
const { type: stage, roundNumber, displayOrder } = definition.stage;
|
|
const key = `${stage}:${roundNumber ?? 'none'}`;
|
|
const existing = rounds.get(key);
|
|
if (existing) {
|
|
existing.seriesIds.push(definition.id);
|
|
existing.displayOrder = Math.min(existing.displayOrder, displayOrder);
|
|
continue;
|
|
}
|
|
rounds.set(key, {
|
|
stage,
|
|
...(roundNumber !== undefined ? { roundNumber } : {}),
|
|
displayOrder,
|
|
label: roundLabel(stage, roundNumber),
|
|
seriesIds: [definition.id],
|
|
});
|
|
}
|
|
return [...rounds.values()].sort(
|
|
(left, right) => left.displayOrder - right.displayOrder,
|
|
);
|
|
}
|
|
|
|
function roundLabel(
|
|
stage: SeriesDefinition['stage']['type'],
|
|
roundNumber?: number,
|
|
): string {
|
|
switch (stage) {
|
|
case 'pair':
|
|
return 'Pair';
|
|
case 'round-robin':
|
|
return `Round ${roundNumber ?? 1}`;
|
|
case 'upper':
|
|
return `Upper ${roundNumber ?? 1}`;
|
|
case 'lower':
|
|
return `Lower ${roundNumber ?? 1}`;
|
|
case 'grand-final':
|
|
return 'Grand Final';
|
|
case 'reset-final':
|
|
return 'Reset Final';
|
|
}
|
|
}
|
|
|
|
function projectConnectors(
|
|
graph: readonly SeriesDefinition[],
|
|
): SeriesConnectorProjection[] {
|
|
const connectors: SeriesConnectorProjection[] = [];
|
|
for (const definition of graph) {
|
|
for (const { position, source } of definition.slots) {
|
|
if (source.type === 'series-outcome') {
|
|
connectors.push({
|
|
from: {
|
|
seriesId: source.seriesId,
|
|
select: source.select,
|
|
},
|
|
to: { seriesId: definition.id, slot: position },
|
|
});
|
|
continue;
|
|
}
|
|
if (source.type === 'series-slot') {
|
|
connectors.push({
|
|
from: {
|
|
seriesId: source.seriesId,
|
|
select: source.slot === 'A' ? 'slot-a' : 'slot-b',
|
|
},
|
|
to: { seriesId: definition.id, slot: position },
|
|
});
|
|
}
|
|
}
|
|
}
|
|
return connectors;
|
|
}
|
|
|
|
function competitionCompletedAt(series: readonly SeriesProjection[]): string {
|
|
return series
|
|
.filter(
|
|
(projection): projection is SeriesProjection & { status: 'completed' } =>
|
|
projection.status === 'completed',
|
|
)
|
|
.map(({ outcome }) => outcome.completedAt)
|
|
.sort()
|
|
.at(-1)!;
|
|
}
|
|
|
|
function toIsoString(value: Date | string): string {
|
|
return value instanceof Date ? value.toISOString() : value;
|
|
}
|
|
|
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
return typeof value === 'object' && value !== null;
|
|
}
|
|
|
|
function phaseFor(
|
|
series: readonly SeriesProjection[],
|
|
outcome: CompetitionProjectionOutcome | undefined,
|
|
): CompetitionProjection['phase'] {
|
|
if (outcome) return 'completed';
|
|
return series.some(
|
|
({ status }) => status === 'in-progress' || status === 'completed',
|
|
)
|
|
? 'running'
|
|
: 'ready';
|
|
}
|
|
|
|
function stableTeamOrder(
|
|
left: string,
|
|
right: string,
|
|
displayOrderByTeam: ReadonlyMap<string, number>,
|
|
): number {
|
|
return (
|
|
(displayOrderByTeam.get(left) ?? Number.MAX_SAFE_INTEGER) -
|
|
(displayOrderByTeam.get(right) ?? Number.MAX_SAFE_INTEGER) ||
|
|
left.localeCompare(right)
|
|
);
|
|
}
|
|
|
|
function teamDisplayOrder(
|
|
teamId: string,
|
|
teams: readonly CompetitionGraphTeam[],
|
|
): number {
|
|
return (
|
|
teams.find((candidate) => candidate.teamId === teamId)?.displayOrder ??
|
|
Number.MAX_SAFE_INTEGER
|
|
);
|
|
}
|