import { assertCompetitionInvariant, CompetitionDomainError, } from './domain-error'; export type SeriesSlot = 'A' | 'B'; export type SeriesRule = | { type: 'first-to'; winsRequired: number; maxGames: number } | { type: 'fixed-games'; gameCount: number; drawPolicy: 'allow' | 'tiebreak-required'; }; export interface SeriesSchedule { date: string; time: string | null; timeZone: 'Asia/Seoul'; } export interface SeriesDefinitionLike { id: string; code?: string; stage: { type: string; roundNumber?: number; displayOrder: number; }; slots: ReadonlyArray<{ position: SeriesSlot; source: Readonly>; }>; rule: SeriesRule; schedule?: SeriesSchedule; gameSlots: ReadonlyArray<{ id: string; seriesId: string; ordinal: number; }>; } export interface ProjectSeriesInput { definition: SeriesDefinitionLike; participants: readonly (string | null | undefined)[]; facts: readonly unknown[]; /** A stable conditional node can exist before it is eligible for play. */ active?: boolean; } export interface SeriesProjectionEntry { slot: SeriesSlot; teamId: string | null; gameWins: number; } export type SeriesProjectionOutcome = | { type: 'played'; winnerTeamId: string; loserTeamId: string; decidedByGameIds: string[]; completedAt: string; } | { type: 'draw'; basis: | { type: 'played'; decidedByGameIds: string[] } | { type: 'administrative'; decisionFactId: string }; completedAt: string; } | { type: 'walkover' | 'forfeit' | 'administrative'; winnerTeamId: string; loserTeamId: string; decisionFactId: string; completedAt: string; }; interface SeriesProjectionBase { seriesId: string; code?: string; stage: SeriesDefinitionLike['stage']; rule: SeriesRule; schedule?: SeriesSchedule; entries: [SeriesProjectionEntry, SeriesProjectionEntry]; } export type SeriesProjection = SeriesProjectionBase & ( | { status: 'inactive' | 'waiting' | 'ready' } | { status: 'in-progress'; leaderTeamId?: string } | { status: 'completed'; outcome: SeriesProjectionOutcome } ); interface FactBase { id: string; type: string; revision: number; ordinalWithinRevision: number; occurredAt: Date | string; recordedAt?: Date | string; } interface GameAcceptedFact extends FactBase { type: 'game-accepted'; gameId: string; seriesId: string; gameSlotId: string; ordinal: number; evidence?: { type?: string; riotMatchId?: string; }; mapping: { blueTeamId: string; redTeamId: string; winnerTeamId: string; }; } interface GameVoidedFact extends FactBase { type: 'game-voided'; gameAcceptedFactId: string; reason?: string; } interface SeriesAdjudicatedFact extends FactBase { type: 'series-adjudicated'; seriesId: string; decision: | { type: 'walkover' | 'forfeit' | 'administrative'; winnerTeamId: string } | { type: 'administrative-draw' }; reason: string; } interface AdjudicationReversedFact extends FactBase { type: 'adjudication-reversed'; adjudicationFactId: string; reason?: string; } type CompetitionFact = | GameAcceptedFact | GameVoidedFact | SeriesAdjudicatedFact | AdjudicationReversedFact; interface PlayedState { activeGames: GameAcceptedFact[]; winsByTeam: Map; completed: boolean; } /** Project one Series exclusively from its definition, resolved participants and fact ledger. */ export function projectSeries(input: ProjectSeriesInput): SeriesProjection { validateDefinition(input.definition); const participants = normalizeParticipants(input.participants); const facts = normalizeFacts(input.facts); const base = projectionBase(input.definition, participants); if (input.active === false) { assertNoSeriesActivity(input.definition.id, facts); return { ...base, status: 'inactive' }; } if (participants.some((teamId) => teamId === null)) { assertNoSeriesActivity(input.definition.id, facts); return { ...base, status: 'waiting' }; } const resolvedParticipants = participants as [string, string]; const relevantFacts = selectRelevantFacts(input.definition.id, facts); const activeGames = new Map(); const voidedGameFacts = new Set(); const adjudications = new Map(); const reversedAdjudications = new Set(); let activeAdjudication: SeriesAdjudicatedFact | undefined; for (const fact of relevantFacts) { switch (fact.type) { case 'game-accepted': { assertCompetitionInvariant( activeAdjudication === undefined && !derivePlayedState( input.definition.rule, [...activeGames.values()], resolvedParticipants, ).completed, 'SERIES_ALREADY_COMPLETED', `Series ${input.definition.id} was already completed before game ${fact.gameId}`, { seriesId: input.definition.id, factId: fact.id }, ); validateAcceptedGame(input.definition, resolvedParticipants, fact); validateActiveGameUniqueness(activeGames.values(), fact); activeGames.set(fact.id, fact); break; } case 'game-voided': { const accepted = facts.find( (candidate): candidate is GameAcceptedFact => candidate.type === 'game-accepted' && candidate.id === fact.gameAcceptedFactId, ); assertCompetitionInvariant( accepted !== undefined, 'FACT_REFERENCE_NOT_FOUND', `Voided game fact ${fact.gameAcceptedFactId} does not exist`, { factId: fact.id, referencedFactId: fact.gameAcceptedFactId }, ); assertCompetitionInvariant( activeGames.has(accepted.id) && !voidedGameFacts.has(accepted.id), 'FACT_ALREADY_REVERSED', `Game fact ${accepted.id} is already voided`, { factId: fact.id, referencedFactId: accepted.id }, ); activeGames.delete(accepted.id); voidedGameFacts.add(accepted.id); break; } case 'series-adjudicated': { const played = derivePlayedState( input.definition.rule, [...activeGames.values()], resolvedParticipants, ); assertCompetitionInvariant( !played.completed && activeAdjudication === undefined, activeAdjudication ? 'DUPLICATE_ADJUDICATION' : 'SERIES_ALREADY_COMPLETED', `Series ${input.definition.id} already has an official outcome`, { seriesId: input.definition.id, factId: fact.id }, ); validateAdjudication( input.definition, resolvedParticipants, played.activeGames, fact, ); adjudications.set(fact.id, fact); activeAdjudication = fact; break; } case 'adjudication-reversed': { const adjudication = adjudications.get(fact.adjudicationFactId); assertCompetitionInvariant( adjudication !== undefined, 'FACT_REFERENCE_NOT_FOUND', `Adjudication fact ${fact.adjudicationFactId} does not exist or is not active in this Series`, { factId: fact.id, referencedFactId: fact.adjudicationFactId }, ); assertCompetitionInvariant( !reversedAdjudications.has(adjudication.id) && activeAdjudication?.id === adjudication.id, 'FACT_ALREADY_REVERSED', `Adjudication fact ${adjudication.id} is already reversed`, { factId: fact.id, referencedFactId: adjudication.id }, ); reversedAdjudications.add(adjudication.id); activeAdjudication = undefined; break; } } } const played = derivePlayedState( input.definition.rule, [...activeGames.values()], resolvedParticipants, ); const entries = entriesFor(resolvedParticipants, played.winsByTeam); const projectedBase = { ...base, entries }; if (activeAdjudication) { return { ...projectedBase, status: 'completed', outcome: adjudicatedOutcome(activeAdjudication, resolvedParticipants), }; } if (played.completed) { return { ...projectedBase, status: 'completed', outcome: playedOutcome( input.definition.rule, played.activeGames, resolvedParticipants, played.winsByTeam, ), }; } if (played.activeGames.length === 0) { return { ...projectedBase, status: 'ready' }; } const leaderTeamId = deriveLeader(resolvedParticipants, played.winsByTeam); return { ...projectedBase, status: 'in-progress', ...(leaderTeamId ? { leaderTeamId } : {}), }; } function validateDefinition(definition: SeriesDefinitionLike): void { assertCompetitionInvariant( typeof definition.id === 'string' && definition.id.length > 0, 'SERIES_DEFINITION_INVALID', 'A Series must have an opaque id', ); assertCompetitionInvariant( definition.slots.length === 2 && definition.slots[0]?.position === 'A' && definition.slots[1]?.position === 'B', 'SERIES_DEFINITION_INVALID', `Series ${definition.id} must define exactly the local A and B slots`, ); const schedule: unknown = definition.schedule; if (schedule !== undefined) { assertCompetitionInvariant( isSeriesSchedule(schedule), 'SERIES_DEFINITION_INVALID', `Series ${definition.id} has an invalid schedule`, ); } const requiredSlots = definition.rule.type === 'fixed-games' ? definition.rule.gameCount : definition.rule.maxGames; assertCompetitionInvariant( Number.isInteger(requiredSlots) && requiredSlots > 0, 'SERIES_DEFINITION_INVALID', `Series ${definition.id} has an invalid game count`, ); if (definition.rule.type === 'first-to') { assertCompetitionInvariant( Number.isInteger(definition.rule.winsRequired) && definition.rule.winsRequired > 0 && definition.rule.maxGames >= definition.rule.winsRequired * 2 - 1, 'SERIES_DEFINITION_INVALID', `Series ${definition.id} has an invalid first-to threshold`, ); } assertCompetitionInvariant( definition.gameSlots.length === requiredSlots, 'SERIES_DEFINITION_INVALID', `Series ${definition.id} must predefine every GameSlot`, ); const ids = new Set(); const ordinals = new Set(); for (const slot of definition.gameSlots) { assertCompetitionInvariant( slot.seriesId === definition.id && typeof slot.id === 'string' && slot.id.length > 0, 'SERIES_DEFINITION_INVALID', `GameSlot ${slot.id} does not belong to Series ${definition.id}`, ); assertCompetitionInvariant( Number.isInteger(slot.ordinal) && slot.ordinal >= 1 && slot.ordinal <= requiredSlots, 'SERIES_DEFINITION_INVALID', `GameSlot ${slot.id} has an invalid ordinal`, ); assertCompetitionInvariant( !ids.has(slot.id) && !ordinals.has(slot.ordinal), 'SERIES_DEFINITION_INVALID', `Series ${definition.id} has duplicate GameSlot identity or ordinal`, ); ids.add(slot.id); ordinals.add(slot.ordinal); } } function normalizeParticipants( participants: readonly (string | null | undefined)[], ): [string | null, string | null] { assertCompetitionInvariant( participants.length === 2, 'SERIES_PARTICIPANTS_INVALID', 'A Series projection requires exactly two participant slots', ); const normalized = participants.map((teamId) => teamId ?? null) as [ string | null, string | null, ]; for (const teamId of normalized) { assertCompetitionInvariant( teamId === null || (typeof teamId === 'string' && teamId.length > 0), 'SERIES_PARTICIPANTS_INVALID', 'Resolved participant ids must be opaque non-empty strings', ); } assertCompetitionInvariant( normalized[0] === null || normalized[1] === null || normalized[0] !== normalized[1], 'SERIES_PARTICIPANTS_INVALID', 'A team cannot occupy both Series slots', ); return normalized; } function normalizeFacts(facts: readonly unknown[]): CompetitionFact[] { const normalized = facts.map(normalizeFact).sort(compareFacts); const factIds = new Set(); const gameIds = new Set(); const riotMatchIds = new Set(); for (const fact of normalized) { assertCompetitionInvariant( !factIds.has(fact.id), 'DUPLICATE_FACT_ID', `Duplicate fact id ${fact.id}`, { factId: fact.id }, ); factIds.add(fact.id); if (fact.type === 'game-accepted') { assertCompetitionInvariant( !gameIds.has(fact.gameId), 'DUPLICATE_GAME_ID', `Duplicate game id ${fact.gameId}`, { gameId: fact.gameId }, ); gameIds.add(fact.gameId); const riotMatchId = fact.evidence?.riotMatchId; if (fact.evidence?.type === 'riot' && riotMatchId) { assertCompetitionInvariant( !riotMatchIds.has(riotMatchId), 'DUPLICATE_RIOT_MATCH_ID', `Riot match ${riotMatchId} was accepted more than once`, { riotMatchId }, ); riotMatchIds.add(riotMatchId); } } } return normalized; } function normalizeFact(value: unknown): CompetitionFact { assertCompetitionInvariant( isRecord(value) && typeof value.id === 'string' && typeof value.type === 'string' && Number.isFinite(value.revision) && Number.isFinite(value.ordinalWithinRevision), 'FACT_TYPE_INVALID', 'Competition facts require identity and ledger ordering fields', ); switch (value.type) { case 'game-accepted': case 'game-voided': case 'series-adjudicated': case 'adjudication-reversed': return value as unknown as CompetitionFact; default: throw new CompetitionDomainError( 'FACT_TYPE_INVALID', `Unsupported Competition fact type ${value.type}`, { factType: value.type }, ); } } function selectRelevantFacts( seriesId: string, facts: CompetitionFact[], ): CompetitionFact[] { const acceptedSeriesById = new Map( facts .filter((fact): fact is GameAcceptedFact => fact.type === 'game-accepted') .map((fact) => [fact.id, fact.seriesId]), ); const adjudicationSeriesById = new Map( facts .filter( (fact): fact is SeriesAdjudicatedFact => fact.type === 'series-adjudicated', ) .map((fact) => [fact.id, fact.seriesId]), ); return facts.filter((fact) => { switch (fact.type) { case 'game-accepted': case 'series-adjudicated': return fact.seriesId === seriesId; case 'game-voided': { const targetSeriesId = acceptedSeriesById.get(fact.gameAcceptedFactId); assertCompetitionInvariant( targetSeriesId !== undefined, 'FACT_REFERENCE_NOT_FOUND', `Voided game fact ${fact.gameAcceptedFactId} does not exist`, { factId: fact.id, referencedFactId: fact.gameAcceptedFactId }, ); return targetSeriesId === seriesId; } case 'adjudication-reversed': { const targetSeriesId = adjudicationSeriesById.get( fact.adjudicationFactId, ); assertCompetitionInvariant( targetSeriesId !== undefined, 'FACT_REFERENCE_NOT_FOUND', `Adjudication fact ${fact.adjudicationFactId} does not exist`, { factId: fact.id, referencedFactId: fact.adjudicationFactId }, ); return targetSeriesId === seriesId; } } }); } function assertNoSeriesActivity( seriesId: string, facts: CompetitionFact[], ): void { const acceptedSeriesById = new Map( facts .filter((fact): fact is GameAcceptedFact => fact.type === 'game-accepted') .map((fact) => [fact.id, fact.seriesId]), ); const adjudicationSeriesById = new Map( facts .filter( (fact): fact is SeriesAdjudicatedFact => fact.type === 'series-adjudicated', ) .map((fact) => [fact.id, fact.seriesId]), ); const activeGames = new Set(); const activeAdjudications = new Set(); for (const fact of facts) { switch (fact.type) { case 'game-accepted': if (fact.seriesId === seriesId) activeGames.add(fact.id); break; case 'game-voided': if (acceptedSeriesById.get(fact.gameAcceptedFactId) === seriesId) { assertCompetitionInvariant( activeGames.delete(fact.gameAcceptedFactId), 'FACT_ALREADY_REVERSED', `Game fact ${fact.gameAcceptedFactId} is already voided`, { factId: fact.id, referencedFactId: fact.gameAcceptedFactId }, ); } break; case 'series-adjudicated': if (fact.seriesId === seriesId) activeAdjudications.add(fact.id); break; case 'adjudication-reversed': if (adjudicationSeriesById.get(fact.adjudicationFactId) === seriesId) { assertCompetitionInvariant( activeAdjudications.delete(fact.adjudicationFactId), 'FACT_ALREADY_REVERSED', `Adjudication fact ${fact.adjudicationFactId} is already reversed`, { factId: fact.id, referencedFactId: fact.adjudicationFactId }, ); } break; } } assertCompetitionInvariant( activeGames.size === 0 && activeAdjudications.size === 0, 'SERIES_PARTICIPANTS_INVALID', `Series ${seriesId} cannot contain facts before both participants are active`, { seriesId }, ); } function validateAcceptedGame( definition: SeriesDefinitionLike, participants: [string, string], fact: GameAcceptedFact, ): void { assertCompetitionInvariant( fact.seriesId === definition.id, 'GAME_SERIES_MISMATCH', `Game ${fact.gameId} targets a different Series`, ); const slot = definition.gameSlots.find( (candidate) => candidate.id === fact.gameSlotId, ); assertCompetitionInvariant( slot !== undefined, 'GAME_SLOT_INVALID', `Game ${fact.gameId} targets an unknown GameSlot`, { gameId: fact.gameId, gameSlotId: fact.gameSlotId }, ); assertCompetitionInvariant( slot.ordinal === fact.ordinal, 'GAME_ORDINAL_INVALID', `Game ${fact.gameId} ordinal does not match its GameSlot`, { gameId: fact.gameId, ordinal: fact.ordinal }, ); const { blueTeamId, redTeamId, winnerTeamId } = fact.mapping; const expectedTeams = new Set(participants); const actualTeams = new Set([blueTeamId, redTeamId]); assertCompetitionInvariant( actualTeams.size === 2 && expectedTeams.size === actualTeams.size && [...expectedTeams].every((teamId) => actualTeams.has(teamId)), 'GAME_TEAM_MISMATCH', `Game ${fact.gameId} teams do not match Series ${definition.id}`, { gameId: fact.gameId, expectedTeamIds: participants, actualTeamIds: [blueTeamId, redTeamId], }, ); assertCompetitionInvariant( winnerTeamId === blueTeamId || winnerTeamId === redTeamId, 'GAME_WINNER_INVALID', `Game ${fact.gameId} winner is not a participant`, { gameId: fact.gameId, winnerTeamId }, ); } function validateActiveGameUniqueness( activeGames: Iterable, fact: GameAcceptedFact, ): void { for (const active of activeGames) { assertCompetitionInvariant( active.gameSlotId !== fact.gameSlotId, 'DUPLICATE_GAME_SLOT', `GameSlot ${fact.gameSlotId} already has an accepted game`, { gameSlotId: fact.gameSlotId }, ); assertCompetitionInvariant( active.ordinal !== fact.ordinal, 'DUPLICATE_GAME_ORDINAL', `Series ordinal ${fact.ordinal} already has an accepted game`, { ordinal: fact.ordinal }, ); } } function validateAdjudication( definition: SeriesDefinitionLike, participants: [string, string], activeGames: GameAcceptedFact[], fact: SeriesAdjudicatedFact, ): void { assertCompetitionInvariant( typeof fact.reason === 'string' && fact.reason.trim().length > 0, 'ADJUDICATION_INVALID', `Adjudication ${fact.id} requires a reason`, ); if (fact.decision.type === 'administrative-draw') { assertCompetitionInvariant( definition.rule.type === 'fixed-games' && definition.rule.drawPolicy === 'allow', 'ADJUDICATION_DRAW_NOT_ALLOWED', `Series ${definition.id} cannot be adjudicated as a draw`, ); return; } assertCompetitionInvariant( participants.includes(fact.decision.winnerTeamId), 'ADJUDICATION_INVALID', `Adjudication winner is not a Series participant`, ); if (fact.decision.type === 'walkover') { assertCompetitionInvariant( activeGames.length === 0, 'WALKOVER_HAS_ACTIVE_GAMES', `Walkover Series ${definition.id} cannot retain played games`, ); } } function derivePlayedState( rule: SeriesRule, games: GameAcceptedFact[], participants: [string, string], ): PlayedState { const activeGames = [...games].sort(compareGames); const winsByTeam = new Map(participants.map((teamId) => [teamId, 0])); for (const game of activeGames) { const winnerTeamId = game.mapping.winnerTeamId; winsByTeam.set(winnerTeamId, (winsByTeam.get(winnerTeamId) ?? 0) + 1); } const completed = rule.type === 'fixed-games' ? activeGames.length === rule.gameCount : participants.some( (teamId) => (winsByTeam.get(teamId) ?? 0) >= rule.winsRequired, ); return { activeGames, winsByTeam, completed }; } function playedOutcome( rule: SeriesRule, activeGames: GameAcceptedFact[], participants: [string, string], winsByTeam: Map, ): SeriesProjectionOutcome { const decidedByGameIds = activeGames.map((game) => game.gameId); const completedAt = toIsoString(activeGames.at(-1)!.occurredAt); const [teamAId, teamBId] = participants; const teamAWins = winsByTeam.get(teamAId) ?? 0; const teamBWins = winsByTeam.get(teamBId) ?? 0; if (teamAWins === teamBWins) { assertCompetitionInvariant( rule.type === 'fixed-games' && rule.drawPolicy === 'allow', 'SERIES_DEFINITION_INVALID', 'This Series completed tied but its rule requires a winner', ); return { type: 'draw', basis: { type: 'played', decidedByGameIds }, completedAt, }; } const winnerTeamId = teamAWins > teamBWins ? teamAId : teamBId; return { type: 'played', winnerTeamId, loserTeamId: winnerTeamId === teamAId ? teamBId : teamAId, decidedByGameIds, completedAt, }; } function adjudicatedOutcome( fact: SeriesAdjudicatedFact, participants: [string, string], ): SeriesProjectionOutcome { const completedAt = toIsoString(fact.occurredAt); if (fact.decision.type === 'administrative-draw') { return { type: 'draw', basis: { type: 'administrative', decisionFactId: fact.id }, completedAt, }; } const winnerTeamId = fact.decision.winnerTeamId; return { type: fact.decision.type, winnerTeamId, loserTeamId: participants[0] === winnerTeamId ? participants[1] : participants[0], decisionFactId: fact.id, completedAt, }; } function projectionBase( definition: SeriesDefinitionLike, participants: [string | null, string | null], ): SeriesProjectionBase { return { seriesId: definition.id, ...(definition.code ? { code: definition.code } : {}), stage: definition.stage, rule: definition.rule, ...(definition.schedule ? { schedule: { ...definition.schedule } } : {}), entries: [ { slot: 'A', teamId: participants[0], gameWins: 0 }, { slot: 'B', teamId: participants[1], gameWins: 0 }, ], }; } function isValidLocalDate(value: string): boolean { const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value); if (!match) return false; const year = Number(match[1]); const month = Number(match[2]); const day = Number(match[3]); const date = new Date(Date.UTC(year, month - 1, day)); return ( date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day ); } function isSeriesSchedule(value: unknown): value is SeriesSchedule { if (typeof value !== 'object' || value === null || Array.isArray(value)) { return false; } const schedule = value as Record; return ( typeof schedule.date === 'string' && isValidLocalDate(schedule.date) && (schedule.time === null || (typeof schedule.time === 'string' && /^(?:[01]\d|2[0-3]):[0-5]\d$/.test(schedule.time))) && schedule.timeZone === 'Asia/Seoul' ); } function entriesFor( participants: [string, string], winsByTeam: Map, ): [SeriesProjectionEntry, SeriesProjectionEntry] { return [ { slot: 'A', teamId: participants[0], gameWins: winsByTeam.get(participants[0]) ?? 0, }, { slot: 'B', teamId: participants[1], gameWins: winsByTeam.get(participants[1]) ?? 0, }, ]; } function deriveLeader( participants: [string, string], winsByTeam: Map, ): string | undefined { const firstWins = winsByTeam.get(participants[0]) ?? 0; const secondWins = winsByTeam.get(participants[1]) ?? 0; if (firstWins === secondWins) return undefined; return firstWins > secondWins ? participants[0] : participants[1]; } function compareFacts(left: CompetitionFact, right: CompetitionFact): number { return ( left.revision - right.revision || left.ordinalWithinRevision - right.ordinalWithinRevision || left.id.localeCompare(right.id) ); } function compareGames(left: GameAcceptedFact, right: GameAcceptedFact): number { return ( left.ordinal - right.ordinal || left.revision - right.revision || left.id.localeCompare(right.id) ); } function toIsoString(value: Date | string): string { const date = value instanceof Date ? value : new Date(value); assertCompetitionInvariant( !Number.isNaN(date.getTime()), 'FACT_TYPE_INVALID', 'Fact timestamps must be valid dates', ); return date.toISOString(); } function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null; }